content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
|---|---|---|
function result = lineOfx(howMany) %lineOfx return a string made up of the letter x (howMany times) % % consumes: howMany, a scalar number indicating how many times % the letter x should appear % produces: a string made up of the letter x that many times % % if x <= 0, an empty string is returned % % Examples: % >> lineOfx(3) % ans = % xxx % >> lineOfx(5) % ans = % xxxxx % >> lineOfx(-10) % ans = % '' % >> % P. Conrad for CISC106, 10/07/2007 result = ''; for i=1:howMany result = [ result 'x' ]; end; return; end % function lineOfx
|
__label__pos
| 0.996007 |
Browse Prior Art Database
A Low-Power MAC Protocol for Wireless Sensor Networks
IP.com Disclosure Number: IPCOM000117296D
Original Publication Date: 2005-Mar-31
Included in the Prior Art Database: 2005-Mar-31
Document File: 6 page(s) / 115K
Publishing Venue
IBM
Abstract
The disclosure is directed towards a low-power MAC protocol for a wireless, low data-rate sensor network in which very simple and transmit only sensor nodes (SNs) communicate with multiple cluster heads (CHs). The data sent by the SNs should be received by as many CHs as possible. The CHs cooperate with each other to improve the performance of the wireless links between them and the SNs.
This text was extracted from a PDF file.
At least one non-text object (such as an image or picture) has been suppressed.
This is the abbreviated version, containing approximately 24% of the total text.
Page 1 of 6
A Low-Power MAC Protocol for Wireless Sensor Networks
1 Introduction
This disclosure is directed towards a low power MAC protocol for low data-rate wireless sensor networks (WSN), which consists of many very simple and low-cost sensors nodes (SNs) communicating wirelessly with a few distributed and cooperating cluster heads (CHs). To keep the cost of the SNs as low as possible, it is assumed that the SNs have only transmit capability. Thus the SNs just broadcast their data packets to the air without knowing whether they are received by any CH. The system is deployed in such a way that data packets sent by the SNs could be received by as many CHs as possible. Exploiting the space diversity of the system the CHs cooperate with each other to decode the data packets received and reduce the packet error rate. The cooperation algorithm between the CHs is however out of scope of this disclosure.
Because the SNs can only transmit, uncoordinated multi-access protocols can be efficiently applied here, i.e. the SNs just send their data and hope that their transmissions do not collide with other transmissions. To avoid catastrophic collisions between the SNs, a SN could for example wait for a random delay before it start its transmissions (ALOHA like).
In many sensor applications, the SNs are idle for long time if no sensing event happens. To save energy the SNs can therefore turn off their radio and sleep during those idle times. They need only to wake up when they have something to send. Although this simple method is well appropriate for those low traffic conditions, it has the disadvantage of requiring the CHs to have their radio receivers always turned on, because they do not know when a SN would start sending, thus wasting energy for idle listening.
In this disclosure we will describe a MAC protocol that also allows the CHs to switch their receiver off and save energy during the idle phases.
2 Prior art
2.1 IEEE 802.11/802.15.4 Power Save Mode
Both IEEE 802.11 and 802.15.4 specify the same scheme for power saving mode for the wireless stations. The access point is assumed to be always on.
All downlink traffic is buffered in the access point. The access point transmits periodically a beacon, which contains a so-called "Traffic Indication Map (TIM)". The TIM lists the addresses of the wireless stations for which data packets have been buffered. To save energy the wireless stations turn off their radio transceivers during the idle periods (power save or "sleep" mode). They however know the beacon transmit schedule of the access point, and wake up regularly to receive the TIM. If they discover their address in the TIM, they poll the access point to receive the buffered packet(s). The wake-up period can be freely chosen by the wireless stations as a multiple of the beacon period.
1
Page 2 of 6
2.2 W. Ye et al, "Medium Access Control With Coordinated Adaptive Sleeping for Wireless Sensor Networks", IEEE/ACM Trans. Networking, vol 12, no 3, Jun...
|
__label__pos
| 0.667593 |
As 2018 rapidly comes to an end, I thought I’d close out the year by clearing up some confusions over this AmsiScanBuffer bypass and why it appears to fail under some circumstances.
I’ve had numerous people contact me (particularly those doing RastaLabs) asking about these two specific issues, but I didn’t feel inspired to address them until a very pleasant conversation with confuciussayuhm. So props to them :)
It Just Doesn’t Work
The first issue looks something like this:
It’s visually confusing because the bypass has been executed and allows us to print “AmsiScanBuffer”, where we previously could not. But for some reason, the execution of a stager still fails.
By firing up Process Explorer, we can see the PowerShell process our console is living in (semi-highligted in grey). Then when the IEX cradle is run, a new child PowerShell process is created (highlighted in green) before very quickly being killed off.
Because this AMSI bypass is per-process, this new child is still has amsi.dll perfectly intact. It does not inherit the bypass from its parent, and this is clearly the reason for the detection.
The next question is, why is a child spawned?
Well, by inspecting the two processes in Process Explorer, we see that the path of the child process is c:\Windows\SysWOW64\windowspowershell\v1.0\powershell.exe, where the parent is C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe. So this is the 64-bit binary spawning the 32-bit version.
The obvious explanation is that we’re trying to run a 32-bit stager from a 64-bit process. So this is the part where you really need to know your toolset. For example, the Cobalt Strike Scripted Web Delivery will always create a 32-bit stager (you don’t even get the option to make it 64-bit). Therefore you must ensure that regardless of which toolset you’re using, you create 64-bit payloads.
It doesn’t matter if they’re staged or stageless in the context of this bypass, they both work fine.
It Just Crashes
[Updated 04/01/2019]
I found this one to be a little more interesting.
The second issue comes where the PowerShell process crashes when the bypass is executed, due to some memory corruption. This would only actually happen if it was being run in a 32-bit process.
If you were using the code we commited in Part 2 (which was basically the initial commit), you would have been using:
Byte[] Patch = { 0x31, 0xff, 0x90 };
IntPtr unmanagedPointer = Marshal.AllocHGlobal(3);
Marshal.Copy(Patch, 0, unmanagedPointer, 3);
MoveMemory(ASBPtr + 0x001b, unmanagedPointer, 3);
But at the end of Part 3, we changed the bytes being used to patch the AmsiScanBuffer function, specifically to make it more “resiliant”. We ended up with the following, (but I never updated the repo).
Byte[] Patch = { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
IntPtr unmanagedPointer = Marshal.AllocHGlobal(6);
Marshal.Copy(Patch, 0, unmanagedPointer, 6);
MoveMemory(ASBPtr, unmanagedPointer, 6);
And this runs perfectly well in a 32-bit process.
I’ve not tested this, but my theory is that the static byte offset 0x001b is incorrect for a 32-bit process, and so we end up overwriting a completely different portion of memory than what we want.
Coincidently, Francesco Soncina submitted two PR’s to update both the C# and PowerShell versions of the bypass. So if you pull the changes, you should be fine.
I hope this helps anybody out who was facing these problems. Armed with this knowledge, may 2019 bring you many more shells.
|
__label__pos
| 0.665648 |
X108: seriesUp
Given n >= 0, create an array with the pattern {1, 1, 2, 1, 2, 3, ... 1, 2, 3 .. n} (spaces added to show the grouping). Note that the length of the array will be 1 + 2 + 3 ... + n, which is known to sum to exactly n * (n + 1)/2.
Reset
Practice a different Java exercise
|
__label__pos
| 0.845738 |
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.
Sign up
Here's how it works:
1. Anybody can ask a question
2. Anybody can answer
3. The best answers are voted up and rise to the top
I'm having a bit of trouble trying to include .eps files in a LaTeX document compiled with pdfLaTeX. I've been told that I should use the epstopdf package to convert .eps files to .pdf on the fly.
This is my LaTeX code:
\documentclass[12pt]{article}
\usepackage[pdftex]{graphicx}
\usepackage{epstopdf}
\begin{document}
\includegraphics{thing.eps}
\end{document}
But when I try to compile it with pdflatex test.tex I get this error:
Package epstopdf Warning: Shell escape feature is not enabled.
(/usr/share/texmf-texlive/tex/latex/latexconfig/epstopdf-sys.cfg))) (./test.aux ) (/usr/share/texmf/tex/context/base/supp-pdf.mkii [Loading MPS to PDF converter (version 2006.09.02).] )
! Package pdftex.def Error: File `thing-eps-converted-to.pdf' not found.
See the pdftex.def package documentation for explanation. Type H for immediate help. ...
l.7 \includegraphics{thing.eps}
?
I'm not sure what to do, I've also tried putting \epstopdfsetup and \epstopdfsetup{} after \usepackage{espstopdf} but that doesn't help.
share|improve this question
up vote 15 down vote accepted
To compile the example without errors use:
pdflatex --shell-escape test.tex
With the beginning of TeXLive 2010 pdflatex automatically converts eps file to pdf. Karl Berry wrote a TUGboat article about this new feature. You should update your distribution.
TEX Live 2010 news TUGboat, Volume 31 (2010), No. 2
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.685572 |
Numeri primi
In questo articolo mostrerò un codice sorgente del programma che ho creato per calcolare numeri primi in automatico.
Codice Sorgente
// Programma che verifica se una serie di numeri sono primi - Davide Paolini
#include <stdio.h>
#include <stdlib.h>
int main(void) {
long int n=0, m=1, c=0, cont=0, cont2=0, cont3=0; //n = numero da testare, m = divisore, c = resto, cont1,2,3 = contatori
printf("\nQuesto programma ricerca i numeri primi\n");
printf("Inserire la cifra da cui iniziare\n");
scanf_s("%i", &n); //Inserimento della cifra da cui iniziare
printf("Inserire la cifra con la quale terminare la ricerca\n");
scanf_s("%i", &cont3); //Inserimento della cifra con cui terminare
cont2 = n;
while (cont2<cont3) { n++; //Incremento n cont = 0; //Resetto il contatore while (cont != 2 && n != 1) { //Finché il contatore è diverso da 2 e n è diverso da 1 m = n; //Assegno a m il valore di n, perché un numero primo è primo solo se è divisibile per sé stesso e 1 while (m >= 1) { //Finché m è maggiore o uguale a 1
c = n%m; //Salvo il resto della divisione tra n e m in c
if (c == 0) cont = cont + 1; //Controllo se il resto è uguale a 0 e se sì incremento cont
m = m - 1; //Decremento m
}
if (cont == 2) printf("\nIl numero %i e' primo\n",n); //Se il contatore vale 2 il numero è primo
if (cont>2) cont = 2; //Altrimenti esco dal secondo ciclo impostando cont a 2
}
cont2++; //Incremento il contatore 2
}
printf("\nProgramma terminato\n\n");
system("PAUSE");
return 0;
}
|
__label__pos
| 0.826025 |
Ionic Framework 4 is almost here. Preview the beta docs and try it out now! Try Ionic 4 Beta
Core Concepts
Improve this doc
If you’re completely new to Ionic and/or hybrid mobile app development, it can be helpful to get a high-level understanding of the core philosophy, concepts, and tools behind Ionic. The information below can help you familiarize yourself with what Ionic is and how it works.
What is Ionic Framework?
Ionic Framework is an open source SDK that enables developers to build performant, high-quality mobile apps using familiar web technologies (HTML, CSS, and JavaScript).
Ionic is focused mainly on the look and feel, or the UI interaction, of an app. This means that it’s not a replacement for Cordova or your favorite JavaScript framework. Instead, Ionic fits in well with these projects, in order to simplify one big part of your app development process: the front-end. Check out “Where does the Ionic Framework fit in?” to get a good understanding of Ionic’s core philosophy and goals.
How is Ionic Licensed?
Ionic is completely free and open source, released under the permissive MIT license, which means you can use Ionic in personal or commercial projects for free. For example, MIT is the same license used by such popular projects as jQuery and Ruby on Rails.
This website and documentation content (found in the ionic-site repo) is licensed under the Apache 2 license.
What is the Ionic CLI?
The CLI, or command line interface, is a tool that provides a number of helpful commands to Ionic developers. In addition to installing and updating Ionic, the CLI comes with a built-in development server, build and debugging tools, and much more. If you are using Ionic Appflow, the CLI can be used to export code and even interact with your account programmatically.
What are components?
Components in Ionic are reusable UI elements that serve as the building blocks for your mobile app. Components are made up of HTML, CSS, and sometimes JavaScript. Every Ionic component adapts to the platform on which your app is running. We call this Platform Continuity and go more in depth on how it works in Theming.
What is theming?
Themes are sets of styles that get applied to an app. Ionic uses a light theme by default, but it also comes with a dark theme. In addition to theming, Ionic’s Platform Continuity enables components to have platform-specific styles. This means the app’s styles will change based on the platform (iOS, Android, etc.) on which it’s being run, offering your users an experience with which they’re familiar.
How does navigation work?
Navigation works like a stack — push a page to the stack to navigate to it, and pop to go back. Modals and alerts can also be displayed by pushing them onto the navigation stack.
Who is behind Ionic?
Ionic was originally built by @benjsperry, @adamdbradley, and @maxlynch. After releasing an alpha version of Ionic in November 2013, we released a 1.0 beta in March 2014 and a 1.0 final in May 2015.
Now, Ionic has a massive international community of developers and contributors propelling its growth and adoption. Companies small and large are using Ionic to build better apps, faster. In 2015 Ionic developers reportedly created over 1.3M apps with Ionic, a number that continues to grow each day.
What is Angular?
Angular is the underlying framework that powers Ionic. It is responsible for the component API that is the building block of Ionic. For an overview on Angular, be sure to checkout the official Angular Docs.
API
Native
General
|
__label__pos
| 0.94493 |
Anmol Sarma
Network Redirections in Bash
May 4, 2019 tech linux
A few months ago, while reading the man page for recvmmsg(), I came across this snippet:
$ while true; do echo $RANDOM > /dev/udp/127.0.0.1/1234;
sleep 0.25; done
And as advertised, it sends a UDP datagram containing a random number to port 1234 every 250 ms. I didn’t recall ever seeing a /dev/udp and so was a bit surprised that it worked. And as it happens, ls was not able to access the file that I had just written to:
ls: cannot access '/dev/udp/127.0.0.1/1234': No such file or directory
Puzzled and intrigued, I echoed Foo Bar Baz to /dev/udp/127.0.0.1/1337 and reached for strace:
...
2423 socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) = 4
12423 connect(4, {sa_family=AF_INET, sin_port=htons(1337), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
12423 fcntl(1, F_GETFD) = 0
12423 fcntl(1, F_DUPFD, 10) = 10
12423 fcntl(1, F_GETFD) = 0
12423 fcntl(10, F_SETFD, FD_CLOEXEC) = 0
12423 dup2(4, 1) = 1
12423 close(4) = 0
12423 fstat(1, {st_mode=S_IFSOCK|0777, st_size=0, ...}) = 0
12423 write(1, "Foo Bar Baz\n", 12) = 12
...
Seemingly, a normal UDP socket was being created and written to using the regular sycall interface. That refuted my initial suspicion that some kind of a special file backed by the kernel was involved. But who was actually creating the socket?
A peek at Bash’s code answered that question:
redir.c:
/* A list of pattern/value pairs for filenames that the redirection
code handles specially. */
static STRING_INT_ALIST _redir_special_filenames[] = {
#if !defined (HAVE_DEV_FD)
{ "/dev/fd/[0-9]*", RF_DEVFD },
#endif
#if !defined (HAVE_DEV_STDIN)
{ "/dev/stderr", RF_DEVSTDERR },
{ "/dev/stdin", RF_DEVSTDIN },
{ "/dev/stdout", RF_DEVSTDOUT },
#endif
#if defined (NETWORK_REDIRECTIONS)
{ "/dev/tcp/*/*", RF_DEVTCP },
{ "/dev/udp/*/*", RF_DEVUDP },
#endif
{ (char *)NULL, -1 }
};
So, redirection involving /dev/udp/ is handled specially by Bash1 and it uses BSD Sockets API to create a socket:
lib/sh/netopen.c:
/*
* Open a TCP or UDP connection to HOST on port SERV. Uses the
* traditional BSD mechanisms. Returns the connected socket or -1 on error.
*/
static int
_netopen4(host, serv, typ)
char *host, *serv;
int typ;
{
struct in_addr ina;
struct sockaddr_in sin;
unsigned short p;
int s, e;
if (_getaddr(host, &ina) == 0)
{
internal_error (_("%s: host unknown"), host);
errno = EINVAL;
return -1;
}
if (_getserv(serv, typ, &p) == 0)
{
internal_error(_("%s: invalid service"), serv);
errno = EINVAL;
return -1;
}
memset ((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = p;
sin.sin_addr = ina;
s = socket(AF_INET, (typ == 't') ? SOCK_STREAM : SOCK_DGRAM, 0);
if (s < 0)
{
sys_error ("socket");
return (-1);
}
if (connect (s, (struct sockaddr *)&sin, sizeof (sin)) < 0)
{
e = errno;
sys_error("connect");
close(s);
errno = e;
return (-1);
}
return(s);
}
Which means we can actually make HTTP requests using Bash:
exec 3<> /dev/tcp/checkip.amazonaws.com/80
printf "GET / HTTP/1.1\r\nHost: checkip.amazonaws.com\r\nConnection: close\r\n\r\n" >&3
tail -n1 <&3
No curl needed! /jk
Apart from Bash, in the versions and configurations packaged in Ubuntu 18.04, only ksh supports network redirections – ash, csh, dash, fish, and zsh do not.
I don’t think I will actually have any use for network redirections but this was a fun little rabbit hole to dive into.
NOTE: Code snippets from Bash are licensed under GPLv3, the snippet from the man page is licensed differently
1. At least on Linux, the other special patterns handled by bash like /dev/fd and /dev/stdint actually are special files backed by the kernel. The Bash manual notes that it may emulate them internally on platforms that do not support them. ↩︎
Show Comments
|
__label__pos
| 0.914259 |
Distnace Between 2 Rational Numbers Worksheet
Distnace Between 2 Rational Numbers WorksheetA Logical Phone numbers Worksheet may help your youngster become more familiar with the methods right behind this rate of integers. With this worksheet, students should be able to remedy 12 diverse problems related to realistic expression. They may discover ways to grow two or more amounts, team them in couples, and determine their items. They will also process simplifying rational expression. As soon as they have perfected these methods, this worksheet will certainly be a beneficial device for advancing their studies. Distnace Between 2 Rational Numbers Worksheet.
Rational Numbers can be a percentage of integers
Finding The Distance Between Two Numbers
The two main forms of amounts: irrational and rational. Logical numbers are described as entire amounts, in contrast to irrational figures do not replicate, and also have an infinite variety of numbers. Irrational amounts are non-zero, non-terminating decimals, and sq roots that are not best squares. They are often used in math applications, even though these types of numbers are not used often in everyday life.
To establish a logical amount, you need to understand what a logical number is. An integer is a total variety, and a logical quantity can be a rate of two integers. The percentage of two integers is definitely the variety ahead divided up with the number at the base. If two integers are two and five, this would be an integer, for example. There are also many floating point numbers, such as pi, which cannot be expressed as a fraction.
They are often manufactured in to a portion
Distance Between Two Rational Numbers Absolute Value NOTES PRACTICE
A rational quantity features a denominator and numerator which are not absolutely no. Consequently they may be expressed as being a small fraction. Together with their integer numerators and denominators, logical amounts can in addition have a adverse worth. The bad benefit must be located left of and its absolute importance is its extended distance from no. To easily simplify this instance, we will say that .0333333 is really a portion that may be created as a 1/3.
Along with negative integers, a realistic quantity may also be made right into a small percentage. For example, /18,572 is really a logical quantity, whilst -1/ is just not. Any fraction composed of integers is realistic, as long as the denominator is not going to include a and can be written as an integer. Similarly, a decimal that ends in a point is also a realistic variety.
They can make feeling
Seventh Grade Lesson Determine The Distance Between Two Rational
In spite of their title, realistic amounts don’t make a lot sensation. In mathematics, they are individual entities by using a unique duration about the amount line. Consequently when we count anything, we are able to order the dimensions by its rate to the authentic quantity. This retains true regardless if there are actually unlimited rational phone numbers involving two distinct phone numbers. In other words, numbers should make sense only if they are ordered. So, if you’re counting the length of an ant’s tail, a square root of pi is an integer.
In real life, if we want to know the length of a string of pearls, we can use a rational number. To find the length of a pearl, for example, we could count up its width. Just one pearl is ten kilos, which is a realistic amount. Moreover, a pound’s bodyweight equates to twenty kilos. Therefore, we must be able to separate a lb by 10, without having be concerned about the size of an individual pearl.
They can be indicated like a decimal
You’ve most likely seen a problem that involves a repeated fraction if you’ve ever tried to convert a number to its decimal form. A decimal quantity might be composed as a numerous of two integers, so 4 times 5 is equal to seven. A similar problem necessitates the frequent portion 2/1, and either side must be split by 99 to obtain the right respond to. But how will you make your transformation? Below are a few good examples.
A logical amount can be designed in great shape, which include fractions along with a decimal. A good way to represent a reasonable quantity within a decimal is usually to split it into its fractional counterpart. You can find three ways to break down a logical quantity, and all these ways yields its decimal counterpart. One of those techniques would be to split it into its fractional comparable, and that’s what’s called a terminating decimal.
Gallery of Distnace Between 2 Rational Numbers Worksheet
Leave a Comment
|
__label__pos
| 0.981424 |
w3resource
Python: Remove existing indentation from all of the lines in a given text
Python String: Exercise-27 with Solution
Write a Python program to remove existing indentation from all of the lines in a given text.
Sample Solution:-
Python Code:
import textwrap
sample_text = '''
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
'''
text_without_Indentation = textwrap.dedent(sample_text)
print()
print(text_without_Indentation )
print()
Sample Output:
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language. Its design philosophy emphasizes
code readability, and its syntax allows programmers to express
concepts in fewer lines of code than possible in languages such
as C++ or Java.
Flowchart:
Flowchart: Remove existing indentation from all of the lines in a given text
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to display formatted text (width=50) as output.
Next: Write a Python program to add a prefix text to all of the lines in a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Follow us on Facebook and Twitter for latest update.
Python: Tips of the Day
Sorting a list of lists:
Consider we have a list of lists:
lst = [[3, 5], [6, 8], [4, 6], [5, 8], [6, 7], [5, 8]]
We can sort the list based on the first or second items of the inner lists by using the sort function with a lambda function.
lst.sort(key = lambda inner:inner[1])
print(lst)
Output:
[[3, 5], [4, 6], [6, 7], [6, 8], [5, 8], [5, 8]]
The list is sorted based on the second items. We can do the same with the first items just by changing the 1 to 0.
lst.sort(key = lambda inner:inner[0])
print(lst)
Output:
[[3, 5], [4, 6], [5, 8], [5, 8], [6, 8], [6, 7]]
|
__label__pos
| 0.997793 |
Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
i have few constants declared in application_controller.rb file. Is there any way to access them in schedule.rb file of whenever gem?
Regards, Sudhir C.N.
share|improve this question
1 Answer 1
The whenever gem does not include the Rails environment by default. If you wanted to do this, you would need to load Rails within your cron tasks. This is not recommended however, especially if all you need is access to some constants.
I would recommend moving your constant definitions to a config file or initializer. Then you can require that file from both your application_controller and your whenever configuration. It will consolidate the logic and give you access to those constants without having to load the entire Rails app for each invocation of whenever.
I hope that helps.
share|improve this answer
Could you please elaborate? Some example of code would be nice. – art-solopov Jul 10 at 10:05
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.530523 |
What is meta? ×
Meta Stack Exchange is where users like you discuss bugs, features, and support issues that affect the software powering all 145 Stack Exchange communities.
The criteria for migrating a question are:
1. The question is off-topic on the current site.
2. The question is high-quality.
3. The question is on-topic for the target site.
Or, as stated in the FAQ,
• Don't migrate for the sake of migration. We only migrate questions because they are off-topic on the original site. It is perfectly possible for a question to be on-topic on multiple sites, but that is not a reason to migrate it elsewhere. As a general rule, if someone asks a question here, and it's on-topic here, it should stay here.
However, the UI doesn't make requirement 1 clear. The sequence goes…
1. Click "close" or "flag".
The dialog asks,
◉ Why should this question be closed?
or
◉ I am flagging this question because …
◉ it should be closed for another reason…
2. Click "off-topic".
One of the options is:
This question belongs on another site in the Stack Exchange network
The UI does not require an off-topic reason to be specified — in fact, it prevents you from specifying an off-topic reason if you want to suggest a migration. Thus, the UI improperly suggests that "better fit elsewhere" is a valid reason for closing/migrating.
share|improve this question
Well, it is under the "off-topic" heading, thus implying the question is off-topic for that site. – hichris123 Mar 18 at 23:28
@hichris123 But at no point does it make you state why you think it's off-topic. – 200_success Mar 18 at 23:29
2 Answers 2
I propose to change the workflow so that a closure reason is required after suggesting migration. Namely,
1. Click "close" or "flag".
2. Click "off-topic".
The dialog looks just like it does today, with one of the choices being
◉ This question belongs on another site in the Stack Exchange network
3. Choose a migration target site.
The dialog looks just like it does today. (I'd add emphasis that it needs to be a high-quality question.)
4. Specify a closure reason.
Flagging > Closing > Off-Topic > Migration > Closure Reason
Why is this question off-topic for insert current site name here?
◎ Standard reason A
◎ Standard reason B
◎ Other (add a comment explaining what is wrong)
Vote to migrate Cancel
The migration flag is cancelled unless a closure reason is given.
One disadvantage of this proposal is that the thought process is a bit backwards: normally, one would classify a question as off-topic before suggesting migration.
share|improve this answer
1
"(I'd tweak it so that each site links to the /help/on-topic page, and emphasize that it needs to be a high-quality question.)" It used to do that at one point. Has that been lost again? – ChrisF Mar 18 at 21:30
1
@ChrisF You're right, it does link to /help/on-topic already. – 200_success Mar 18 at 21:43
This seems like a quite good approach to me, but I am not sure if it is the best solution. – Simon André Forsberg Mar 18 at 22:32
I propose to change the workflow so that migration options are presented after choosing a closure reason.
1. Click "off-topic".
Choose a standard reason for closure, or enter a custom reason.
2. Click Vote to Close.
The UI would ask:
Flagging > Closing > Off-Topic > Migration
Would this be considered a high-quality question that is on-topic on another site?
◉ No, the question should simply be closed.
Stack Overflow logo belongs on Stack Overflow
Q&A for professional and enthusiast programmers
Super User logo belongs on Super User
Q&A for computer enthusiasts and power users
One disadvantage of this proposal is that the common case (simple closure without migration) requires an extra click to dismiss the migration dialog.
share|improve this answer
Why have you made 2 different answers? Couldn't you make them into one (i.e. This or this). – Tim Mar 18 at 21:25
7
@Tim because they are mutually exclusive proposals for rectifying the situation, to be voted on separately. Furthermore, the door is open for anyone (including myself) to suggest an even better solution. – 200_success Mar 18 at 21:27
I think there are way too many questions where this would not be relevant, so I think this would do more harm than good. – Simon André Forsberg Mar 18 at 22:31
You must log in to answer this question.
Not the answer you're looking for? Browse other questions tagged .
|
__label__pos
| 0.662334 |
Questions tagged [geometry-shader]
For questions specifically about the Geometry Shader stage in the GPU pipeline.
Filter by
Sorted by
Tagged with
0 votes
1 answer
93 views
Opengl geometry shader input point to output point doesn't show any ouput
I am trying a simple passthrough just to get a feel for the geometry shader. I am taking in a single point and trying to output that point from the geometry shader, it works with the vertex and ...
user avatar
1 vote
1 answer
116 views
draw on cubemap with help of geometry shader each triangle covers each cubemap face (why??)
I want to do some complicated stuff but have problems with my geometry shader / FBO bindings. To hold it as easy as possible I reduced the code to a minimum. If this works, I could continue the hard ...
user avatar
• 489
1 vote
1 answer
110 views
Is it possible to send Texture Buffer to shader dynamically?
I want to send a series of integer to the geometry shader, while the data will be modified every frame. But when I try to retrive the sampleBuffer in geometry shader, it seems to keep output zero. Am ...
user avatar
2 votes
1 answer
171 views
Vector graphics output from shader program
I’m fairly new to shader programs in general but I have a question concerning vector graphics. I understand that a pixel shader can generate the color information to draw some sort of geometry on ...
user avatar
1 vote
1 answer
196 views
Generating the end caps of a cylinder using triangle strips for use in a geometry shader
I know how to generate the walls of a cylinder with triangle strips and the caps with triangle fans, but since I am working inside a geometry shader, I can only output triangle strips, so I am kind of ...
user avatar
• 111
1 vote
1 answer
116 views
Issue with declaring inputs to geometry shader?
I am trying to pass vertex attributes from my vertex shader -> geometry shader and then to the fragment shader. Pretty simple program, here is my vertex shader: ...
user avatar
• 761
5 votes
1 answer
1k views
How much should I rely on Geometry shaders in WebGL?
Geometry shaders appear to have been introduced in 3.2, which makes me wonder how common 3.2-enabled cards are, including support for Geometry shaders within WebGL contexts. Will I be cutting out a ...
user avatar
17 votes
1 answer
2k views
Is there any way to generate primitives in a geometry shader without any input geometry?
A few years ago I tried to implement this GPU Gem in OpenGL to generate 3D procedural terrain using Marching Cubes. The article suggests to implement Marching Cubes in a geometry shader to maximum ...
user avatar
• 2,580
|
__label__pos
| 0.82205 |
Skip to content
Permalink
Browse files
Add support for particles that require additional data in Area Effect…
… Clouds.
Make particle data creation more forgiving.
• Loading branch information
PseudoKnight committed Nov 17, 2019
1 parent 01e37d4 commit e614b254f3bb48a981e3ebbbbbcb48ed213f75a0
@@ -18,6 +18,8 @@
boolean isBlock();
boolean isItem();
boolean isBurnable();
boolean isEdible();
@@ -63,6 +63,7 @@
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.exceptions.CRE.CREFormatException;
import org.bukkit.Chunk;
import org.bukkit.Color;
import org.bukkit.Effect;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
@@ -126,6 +127,7 @@
import org.bukkit.entity.Zombie;
import org.bukkit.entity.ZombieHorse;
import org.bukkit.entity.ZombieVillager;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.util.Consumer;
@@ -339,18 +341,38 @@ public void playEffect(MCLocation l, MCEffect mCEffect, int data, int radius) {
public void spawnParticle(MCLocation l, MCParticle pa, int count, double offsetX, double offsetY, double offsetZ, double velocity, Object data) {
Particle type = (Particle) pa.getConcrete();
Location loc = (Location) l.getHandle();
if(data != null) {
if(data instanceof MCItemStack) {
w.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, ((MCItemStack) data).getHandle());
} else if(data instanceof MCBlockData) {
w.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, ((MCBlockData) data).getHandle());
} else if(data instanceof MCColor) {
Particle.DustOptions color = new Particle.DustOptions(BukkitMCColor.GetColor((MCColor) data), 1.0F);
switch(type) {
case BLOCK_DUST:
case BLOCK_CRACK:
case FALLING_DUST:
BlockData bd;
if(data instanceof MCBlockData) {
bd = (BlockData) ((MCBlockData) data).getHandle();
} else {
bd = Material.STONE.createBlockData();
}
w.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, bd);
return;
case ITEM_CRACK:
ItemStack is;
if(data instanceof MCItemStack) {
is = (ItemStack) ((MCItemStack) data).getHandle();
} else {
is = new ItemStack(Material.STONE, 1);
}
w.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, is);
return;
case REDSTONE:
Particle.DustOptions color;
if(data instanceof MCColor) {
color = new Particle.DustOptions(BukkitMCColor.GetColor((MCColor) data), 1.0F);
} else {
color = new Particle.DustOptions(Color.RED, 1.0F);
}
w.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, color);
}
} else {
w.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity);
return;
}
w.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity);
}
@Override
@@ -47,6 +47,11 @@ public boolean isBlock() {
return m.isBlock();
}
@Override
public boolean isItem() {
return m.isItem();
}
@Override
public boolean isBurnable() {
return m.isBurnable();
@@ -1,9 +1,11 @@
package com.laytonsmith.abstraction.bukkit.entities;
import com.laytonsmith.abstraction.MCColor;
import com.laytonsmith.abstraction.MCItemStack;
import com.laytonsmith.abstraction.MCLivingEntity;
import com.laytonsmith.abstraction.MCPotionData;
import com.laytonsmith.abstraction.MCProjectileSource;
import com.laytonsmith.abstraction.blocks.MCBlockData;
import com.laytonsmith.abstraction.blocks.MCBlockProjectileSource;
import com.laytonsmith.abstraction.bukkit.BukkitConvertor;
import com.laytonsmith.abstraction.bukkit.BukkitMCColor;
@@ -13,8 +15,12 @@
import com.laytonsmith.abstraction.enums.MCParticle;
import com.laytonsmith.abstraction.enums.bukkit.BukkitMCParticle;
import com.laytonsmith.abstraction.enums.bukkit.BukkitMCPotionEffectType;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
@@ -136,8 +142,35 @@ public void setDurationOnUse(int ticks) {
}
@Override
public void setParticle(MCParticle particle) {
aec.setParticle(((BukkitMCParticle) particle).getConcrete());
public void setParticle(MCParticle particle, Object data) {
Particle type = ((BukkitMCParticle) particle).getConcrete();
switch(type) {
case BLOCK_DUST:
case BLOCK_CRACK:
case FALLING_DUST:
if(data instanceof MCBlockData) {
aec.setParticle(type, ((MCBlockData) data).getHandle());
} else {
aec.setParticle(type, Material.STONE.createBlockData());
}
return;
case ITEM_CRACK:
if(data instanceof MCItemStack) {
aec.setParticle(type, ((MCItemStack) data).getHandle());
} else {
aec.setParticle(type, new ItemStack(Material.STONE, 1));
}
return;
case REDSTONE:
if(data instanceof MCColor) {
Particle.DustOptions color = new Particle.DustOptions(BukkitMCColor.GetColor((MCColor) data), 1.0F);
aec.setParticle(type, color);
} else {
aec.setParticle(type, new Particle.DustOptions(Color.RED, 1.0F));
}
return;
}
aec.setParticle(type);
}
@Override
@@ -36,6 +36,7 @@
import com.laytonsmith.commandhelper.CommandHelperPlugin;
import com.laytonsmith.core.Static;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Note;
@@ -555,18 +556,38 @@ public void stopSound(String sound, MCSoundCategory category) {
public void spawnParticle(MCLocation l, MCParticle pa, int count, double offsetX, double offsetY, double offsetZ, double velocity, Object data) {
Particle type = (Particle) pa.getConcrete();
Location loc = (Location) l.getHandle();
if(data != null) {
if(data instanceof MCItemStack) {
p.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, ((MCItemStack) data).getHandle());
} else if(data instanceof MCBlockData) {
p.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, ((MCBlockData) data).getHandle());
} else if(data instanceof MCColor) {
Particle.DustOptions color = new Particle.DustOptions(BukkitMCColor.GetColor((MCColor) data), 1.0F);
switch(type) {
case BLOCK_DUST:
case BLOCK_CRACK:
case FALLING_DUST:
BlockData bd;
if(data instanceof MCBlockData) {
bd = (BlockData) ((MCBlockData) data).getHandle();
} else {
bd = Material.STONE.createBlockData();
}
p.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, bd);
return;
case ITEM_CRACK:
ItemStack is;
if(data instanceof MCItemStack) {
is = (ItemStack) ((MCItemStack) data).getHandle();
} else {
is = new ItemStack(Material.STONE, 1);
}
p.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, is);
return;
case REDSTONE:
Particle.DustOptions color;
if(data instanceof MCColor) {
color = new Particle.DustOptions(BukkitMCColor.GetColor((MCColor) data), 1.0F);
} else {
color = new Particle.DustOptions(Color.RED, 1.0F);
}
p.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity, color);
}
} else {
p.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity);
return;
}
p.spawnParticle(type, loc, count, offsetX, offsetY, offsetZ, velocity);
}
@Override
@@ -47,7 +47,7 @@
void setDurationOnUse(int ticks);
void setParticle(MCParticle particle);
void setParticle(MCParticle particle, Object data);
void setRadius(float radius);
@@ -2222,11 +2222,67 @@ public Mixed exec(Target t, Environment environment, Mixed... args) throws Confi
cloud.setDurationOnUse(ArgumentValidation.getInt32(specArray.get(index, t), t));
break;
case entity_spec.KEY_AREAEFFECTCLOUD_PARTICLE:
String particleName = specArray.get(index, t).val();
try {
cloud.setParticle(MCParticle.valueOf(particleName));
} catch (IllegalArgumentException ex) {
throw new CREFormatException("Invalid particle type: " + particleName, t);
if(specArray.get(index, t).isInstanceOf(CArray.TYPE)) {
Object data = null;
CArray pa = (CArray) specArray.get(index, t);
MCParticle p;
try {
p = MCParticle.valueOf(pa.get("particle", t).val().toUpperCase());
} catch (IllegalArgumentException ex) {
throw new CREIllegalArgumentException("Particle name '"
+ pa.get("particle", t).val() + "' is invalid.", t);
}
if(pa.containsKey("block")) {
// BLOCK_DUST, BLOCK_CRACK, FALLING_DUST
String value = pa.get("block", t).val();
MCMaterial mat = StaticLayer.GetMaterial(value);
if(mat != null) {
try {
data = mat.createBlockData();
} catch (IllegalArgumentException ex) {
throw new CREIllegalArgumentException(value + " is not a block.", t);
}
} else {
throw new CREIllegalArgumentException("Could not find material from " + value, t);
}
} else if(pa.containsKey("item")) {
// ITEM_CRACK
Mixed value = pa.get("item", t);
if(value.isInstanceOf(CArray.TYPE)) {
data = ObjectGenerator.GetGenerator().item(pa.get("item", t), t);
} else {
MCMaterial mat = StaticLayer.GetMaterial(value.val());
if(mat != null) {
if(mat.isItem()) {
data = StaticLayer.GetItemStack(mat, 1);
} else {
throw new CREIllegalArgumentException(value + " is not an item type.", t);
}
} else {
throw new CREIllegalArgumentException("Could not find material from " + value, t);
}
}
} else if(pa.containsKey("color")) {
// REDSTONE
Mixed c = pa.get("color", t);
if(c.isInstanceOf(CArray.TYPE)) {
data = ObjectGenerator.GetGenerator().color((CArray) c, t);
} else {
data = StaticLayer.GetConvertor().GetColor(c.val(), t);
}
}
try {
cloud.setParticle(p, data);
} catch (IllegalArgumentException ex) {
throw new CREFormatException("Invalid particle data for " + p.name(), t);
}
} else {
String particleName = specArray.get(index, t).val();
try {
cloud.setParticle(MCParticle.valueOf(particleName), null);
} catch (IllegalArgumentException ex) {
throw new CREFormatException("Invalid particle data: " + particleName, t);
}
}
break;
case entity_spec.KEY_AREAEFFECTCLOUD_POTIONMETA:
@@ -1394,19 +1394,17 @@ public String docs() {
+ " parameter can be one player or an array of players. If none is given, all players within 32"
+ " meters will see the particle. The particle parameter can be a particle name or an associative"
+ " array defining the characteristics of the particle to be spawned. The array requires the"
+ " particle name under the key \"particle\"."
+ " ---- Possible particles: " + StringUtils.Join(MCParticle.types(), ", ", ", or ", " or ")
+ " \n\nSome particles have more specific keys and/or special behavior, but the common keys for the"
+ " particle name under the key \"particle\". ----"
+ " Possible particle types: " + StringUtils.Join(MCParticle.types(), ", ", ", or ", " or ") + ".\n"
+ " Some particles have more specific keys and/or special behavior, but the common keys for the"
+ " particle array are \"count\" (usually the number of particles to be spawned), \"speed\""
+ " (usually the velocity of the particle), \"xoffset\", \"yoffset\", and \"zoffset\""
+ " (usually the ranges from center within which the particle may be offset on that axis)."
+ " The BLOCK_DUST, BLOCK_CRACK and FALLING_DUST particles can take a block type name parameter"
+ " under the key \"block\".\n\n"
+ " The ITEM_CRACK particle can take an item array under the key \"item\".\n\n"
+ " The REDSTONE particle can take a color array (or name)"
+ " under the key \"color\"."
+ " If a block, item or color is provided for a particle type that doesn't support it,"
+ " an IllegalArgumentException will be thrown.";
+ " (usually the ranges from center within which the particle may be offset on that axis).\n"
+ " BLOCK_DUST, BLOCK_CRACK and FALLING_DUST particles can take a block type name parameter"
+ " under the key \"block\" (default: STONE).\n"
+ " ITEM_CRACK particles can take an item array or name under the key \"item\" (default: STONE).\n"
+ " REDSTONE particles take an RGB color array (each 0 - 255) or name under the key \"color\""
+ " (default: RED).";
}
@Override
@@ -1475,7 +1473,21 @@ public Mixed exec(Target t, com.laytonsmith.core.environments.Environment enviro
}
} else if(pa.containsKey("item")) {
data = ObjectGenerator.GetGenerator().item(pa.get("item", t), t);
Mixed value = pa.get("item", t);
if(value.isInstanceOf(CArray.TYPE)) {
data = ObjectGenerator.GetGenerator().item(pa.get("item", t), t);
} else {
MCMaterial mat = StaticLayer.GetMaterial(value.val());
if(mat != null) {
if(mat.isItem()) {
data = StaticLayer.GetItemStack(mat, 1);
} else {
throw new CREIllegalArgumentException(value + " is not an item type.", t);
}
} else {
throw new CREIllegalArgumentException("Could not find material from " + value, t);
}
}
} else if(pa.containsKey("color")) {
Mixed c = pa.get("color", t);
@@ -7,10 +7,12 @@ array {entityID} Returns an associative array containing all the data of the giv
|-
| AREA_EFFECT_CLOUD
|
* %KEY_AREAEFFECTCLOUD_COLOR%: The color array of the particle.
* %KEY_AREAEFFECTCLOUD_COLOR%: The color array of the particle, if applicable (eg. SPELL_MOB particle type).
* %KEY_AREAEFFECTCLOUD_DURATION%: The duration of the cloud in ticks.
* %KEY_AREAEFFECTCLOUD_DURATIONONUSE%: The amount the duration will change when the effects are applied.
* %KEY_AREAEFFECTCLOUD_PARTICLE%: The particle which comprises the cloud (can be %PARTICLE%).
* %KEY_AREAEFFECTCLOUD_PARTICLE%: The particle type which comprises the cloud (can be %PARTICLE%).
Can accept a particle array for setting index data required for specific particle types.
This particle array must contain a "particle" key, and supports the keys "block", "item", or "color" when applicable.
* %KEY_AREAEFFECTCLOUD_POTIONMETA%: An array of potion effect arrays for the cloud.
* %KEY_AREAEFFECTCLOUD_RADIUS%: The radius of the cloud.
* %KEY_AREAEFFECTCLOUD_RADIUSONUSE%: The distance the radius will change when the effects are applied.
0 comments on commit e614b25
Please sign in to comment.
You can’t perform that action at this time.
|
__label__pos
| 0.992282 |
0
Context
I am trying to chart the network bandwidth usage of a node in 2 different manners:
1. By looking at global metrics for that node
2. By summing up the corresponding metric for each Pod
To achieve this, I am issuing the following Prometheus queries (example for the receive bandwidth):
• For the entire node (metric from node-exporter)
sum(irate(node_network_receive_bytes_total{instance="10.142.0.54:9100"}[$__rate_interval])) by (device)
• Per Pod (metric from kubelet)
sum(irate(container_network_receive_bytes_total{node="$node",container!=""}[$__rate_interval])) by (pod,interface)
The results are displayed in the following Grafana dashboard, after generating some load on a HTTP service called thrpt-receiver:
Receive bandwidth
Here's what I see if I look at the raw metrics, without sum() and irate() applied:
Received bytes
Problem
As you can see, results are vastly different, to the point I'm almost certain I am doing something wrong, but what?
What makes me especially suspicious about the Pod metrics is the supposedly increasing received bandwidth of kube-proxy (which AFAIK is not supposed to be receiving any traffic in iptables mode), and agents such as the Prometheus node-exporter, etc.
0
I found out what was happening in my graphs. All the Pods mentioned above have one thing in common: they use the host's network namespace, so their network metrics are all identical, and equal to the global host's metric (just with a slightly different precision).
$ kubectl - monitoring get pod -o jsonpath='{.spec.hostNetwork}' \
prometheus-stack-prometheus-node-exporter-jnhw7
true
$ kubectl -n kube-system get pod -o jsonpath='{.items[*].spec.hostNetwork}' \
kube-proxy-gke-triggermesh-product-control-plane-7fc0ad24-z586 \
gke-metrics-agent-5cv4m \
prometheus-to-sd-tk8jv \
fluentbit-gke-xh879
true true true true
One way to see it is to compare the host's metric to one of the above Pods:
Comparison of eth0 and a Pod with hostNetwork
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.716103 |
0
Hi there, I am getting the following error. Could you review my code and help me as to why? I am using the mod_rewrite extention also.
Notice: Undefined index: in /var/www/incpages/mylines.php on line 48
<?php
if( basename( __FILE__ ) == basename( $_SERVER['PHP_SELF'] ) )
{
exit();
}
include("includes/config.php");
if ($maintancemode == "true") {
if ($access == "3") { die("Sorry site is under maintance please try again later."); }
}
// create db connection
mysql_connect("$dbhost", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$page = $_GET['go']; // THIS IS LINE 48
$page = stripslashes($page);
if (!$page) { $page = "news"; }
$ext = "php";
include("includes/pagesallowed.php");
// system check login
if(!isset($_SESSION))
{
session_start();
}
if(isset($_SESSION['username'])){
//if (array_key_exists('username' , $_SESSION)){
//if(session_is_registered('username')){
$logged = "yes";
// user vars
$SQLtext = "SELECT * FROM members where username = '$_SESSION[username]' ";
$result = mysql_query($SQLtext);
$row = mysql_fetch_row($result);
$myid = $row[0];
$uname = $row[1];
$email = $row[3];
$paypal = $row[4];
$mobile = $row[5];
$access = $row[6];
$state = $row[7];
$disc1m = $row[10];
$disc3m = $row[11];
$disc6m = $row[12];
$disc12m = $row[13];
if ($access == "0") { $access == "3"; }
} else {
$logged = "no";
}
?>
4
Contributors
3
Replies
17
Views
3 Years
Discussion Span
Last Post by diafol
0
Can you confirm there is a value in fourth column of members table for id that is set?
1
Better to use mysql_fetch_assoc and text indices. Then if your table is modified you don't have to re-write the numeric indices. Pretty sure even for a NULL field, you should not get an 'undefined index'.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.
|
__label__pos
| 0.99897 |
Kontext Kontext / Hadoop, Hive & HBase
Hive SQL - Cluster By and Distribute By
event 2022-07-10 visibility 1,348 comment 0 insights toc
more_vert
insights Stats
Hive provides two clauses CLUSTER BY and DISTRIBUTE BY that are not available in most of other databases. Hive uses the columns in DISTRIBUTE BY to distribute the rows among reducers. All rows with the same DISTRIBUTE BY columns will be sent to the same reducer. DISTRIBUTE BY does not guarantee clustering or sorting properties on the distributed keys. CLUSTER BY is a shortcut for both DISTRIBUTE BY and SORT BY.
Syntax of CLUSTER BY and DISRIBUTE BY
For DISTRIBUTE BY, the syntax is defined as below:
DISTRIBUTE BY colName (',' colName)*
For CLUSTER BY, the syntax is very similar:
CLUSTER BY colName (',' colName)*
Examples
The following are some examples of using these two clauses. The table used was created in Hive SQL - Aggregate Functions Overview with Examples.
Use DISTRIBUTE BY
set mapreduce.job.reduces=2;
select * from hivesql.transactions distribute by acct;
Results:
+--------------------+----------------------+------------------------+
| transactions.acct | transactions.amount | transactions.txn_date |
+--------------------+----------------------+------------------------+
| 102 | 913.10 | 2021-01-02 |
| 102 | 93.00 | 2021-01-01 |
| 101 | 900.56 | 2021-01-03 |
| 103 | 913.10 | 2021-01-02 |
| 101 | 102.01 | 2021-01-01 |
| 101 | 10.01 | 2021-01-01 |
+--------------------+----------------------+------------------------+
For account 101, the result is not ordered.
Use CLUSTER BY
select * from hivesql.transactions CLUSTER BY acct;
Results:
+--------------------+----------------------+------------------------+
| transactions.acct | transactions.amount | transactions.txn_date |
+--------------------+----------------------+------------------------+
| 102 | 913.10 | 2021-01-02 |
| 102 | 93.00 | 2021-01-01 |
| 101 | 900.56 | 2021-01-03 |
| 101 | 102.01 | 2021-01-01 |
| 101 | 10.01 | 2021-01-01 |
| 103 | 913.10 | 2021-01-02 |
+--------------------+----------------------+------------------------+
The results for account 101 is together.
infoCluster By and Distribute By are used mainly with the Transform/Map-Reduce Scripts. However it is useful in SELECT statements if there is a need to partition and sort the output of a query for subsequent queries. This can potentially improve query performance.
More from Kontext
comment Comments
No comments yet.
Please log in or register to comment.
account_circle Log in person_add Register
Log in with external accounts
|
__label__pos
| 0.500892 |
Search Images Maps Play YouTube News Gmail Drive More »
Sign in
Screen reader users: click this link for accessible mode. Accessible mode has the same essential features but works better with your reader.
Patents
1. Advanced Patent Search
Publication numberUS20030018613 A1
Publication typeApplication
Application numberUS 10/131,580
Publication dateJan 23, 2003
Filing dateApr 24, 2002
Priority dateJul 31, 2000
Also published asEP1535204A1, WO2003091926A1
Publication number10131580, 131580, US 2003/0018613 A1, US 2003/018613 A1, US 20030018613 A1, US 20030018613A1, US 2003018613 A1, US 2003018613A1, US-A1-20030018613, US-A1-2003018613, US2003/0018613A1, US2003/018613A1, US20030018613 A1, US20030018613A1, US2003018613 A1, US2003018613A1
InventorsEngin Oytac
Original AssigneeEngin Oytac
Export CitationBiBTeX, EndNote, RefMan
External Links: USPTO, USPTO Assignment, Espacenet
Privacy-protecting user tracking and targeted marketing
US 20030018613 A1
Abstract
A method, system, and computer-readable medium for assisting in targeting information to users while protecting the privacy of those users is described. Various transaction and/or other user-specific information may first be obtained from one or more of a variety of information sources, and can then be provided to user targeters that desire to target information to other users that match specified criteria. Information about the matching users is provided to the user targeters in a manner that obscures the identity of those users. After a user targeter selects identity-obscured users to which targeted information is to be provided, the information is provided to those targeted users in various ways. In some situations, the targeted information is marketing information such as an advertisement and/or information about a discount or other promotional benefit that is available, and is provided to users at a POS location.
Images(11)
Previous page
Next page
Claims(67)
What is claimed is:
1. A computer-implemented method for a privacy-protecting service to provide marketing promotions from retailers to targeted individuals in a manner that protects identities of the individuals from the retailers, the method comprising:
for each of multiple individuals that are potential recipients of targeted marketing promotions, receiving information about previous transactions involving the individual from one or more of multiple third-party information sources that are distinct from the individuals and the privacy-protecting service;
determining individuals to be targeted by marketing promotions by, for each of multiple targeting retailers desiring to target marketing promotions to appropriate individuals,
determining based at least in part on the received previous transaction information a group of multiple individuals that were each involved in previous transactions that match specified criteria for the targeting retailer;
providing information to the targeting retailer about the determined group in such a manner as to obscure the identities of the individuals in the group; and
receiving an instruction from the targeting retailer to target a specified marketing promotion to the individuals in the group; and
providing marketing promotions to targeted individuals by, for each of multiple transaction retailers involved in transactions with individuals,
receiving information about a current transaction that is occurring between a transaction retailer and an individual; and
if it is determined that the individual involved in the current transaction is part of a group to which a marketing promotion has been targeted by a targeting retailer unrelated to the transaction retailer, providing information about that targeted marketing promotion from the targeting retailer for presentation to that individual on a device at a location of the current transaction, so that while engaged in a transaction with a retailer an individual can receive a marketing promotion targeted by another retailer in a manner that protects the identity of the individual.
2. The method of claim 1 wherein each marketing promotion from a targeting retailer includes a discount available to targeted individuals if they are involved in a specified transaction with that targeting retailer, and including, after presenting information to a first targeted individual about a marketing promotion from a first targeting retailer that includes a first discount for a first transaction with that first targeting retailer, providing the first discount to the first targeted individual by:
receiving information about a current transaction that is occurring between a transaction retailer and an individual; and
when it is determined that the individual is the first targeted individual and that the transaction retailer is the first targeting retailer and that the current transaction is the first transaction, providing the first discount for the current transaction.
3. The method of claim 2 wherein the privacy-protecting service provides a payment processing service to the first targeting retailer, and wherein the providing of the first discount for the current transaction includes adjusting an amount of the payment to be processed to reflect the first discount.
4. The method of claim 1 wherein the devices at the locations of current transactions are targeted marketing devices that each include a display, and wherein the providing of the information about a targeted marketing promotion from a targeting retailer to an individual includes presenting an advertisement including that targeted marketing promotion information to that individual on the targeted marketing device at the current transaction location.
5. The method of claim 4 wherein each of the targeted marketing devices are associated with a single nearby Point-Of-Sale device that process transactions.
6. The method of claim 4 wherein each of the targeted marketing devices are also tracking devices that send information about current transactions that are occurring to the privacy-protecting service, and wherein the sent information for at least some current transactions that are each occurring between a transaction retailer and an individual includes information received from the individual by the targeted marketing and tracking device for that current transaction with which the privacy-protecting service can identify the individual, such that the information received by the privacy-protecting service for those current transactions includes the information received from those individuals.
7. The method of claim 4 including, when an individual to which a targeted marketing device presents an advertisement is not a registered user of the privacy-protecting service, presenting additional information to the individual on the targeted marketing device to prompt the individual to register with the privacy-protecting service.
8. The method of claim 1 wherein the determining of a group of multiple individuals involved in previous transactions that match specified criteria for a targeting retailer includes receiving a request from that targeting retailer to supply information about individuals matching that specified criteria and retrieving in response transaction information that matches that specified criteria, and including modifying the retrieved transaction information so as to obscure the identities of the individuals to which the retrieved transaction information corresponds before the providing of that modified transaction information to that targeting retailer.
9. The method of claim 8 wherein the modifying of the retrieved transaction information so as to obscure the identities of the individuals to which the retrieved transaction information corresponds includes aggregating information for multiple individuals.
10. The method of claim 1 including receiving demographic information for at least some of the multiple individuals that are potential recipients of targeted marketing promotions, wherein at least some of the specified criteria for targeting retailers include criteria parameters related to transaction information and criteria parameters related to demographic information, and wherein the determining of the groups of multiple individuals that match those specified criteria is further based at least in part on the received demographic information.
11. The method of claim 1 including:
receiving instructions from targeting retailers to target specified marketing promotions to specified types of transactions; and
after receiving information about a current transaction that is occurring between a transaction retailer and an individual, if it is determined that the current transaction is of a specified type to which a marketing promotion has been targeted by a targeting retailer unrelated to the transaction retailer, providing information about that targeted marketing promotion from the targeting retailer for presentation to that individual on a device at a location of the current transaction.
12. The method of claim 1 including:
after receiving information about a current transaction that is occurring between a transaction retailer and an individual, determining whether the transactions in which that individual has been involved now match a previously specified criteria for a targeting retailer; and
if it is determined that the transactions in which that individual has been involved now match a previously specified criteria for a targeting retailer, adding that individual to the group of individuals to which that targeting retailer is targeting a specified marketing promotion.
13. The method of claim 1 including further providing marketing promotions to targeted individuals by receiving an indication of an individual who is not involved in a current transaction being accessible at a device and providing to that device information about a marketing promotion targeted to that individual for presentation to that individual.
14. The method of claim 1 including receiving a request from a targeting retailer to provide information related to a specified marketing promotion that is targeted to a group of multiple individuals, and in response providing summaries of how many of the multiple individuals have received the specified marketing promotion and of how many of the multiple individuals have received benefits provided by the specified marketing promotion.
15. The method of claim 1 wherein the transaction retailers are members of an affiliate network sponsored by the privacy-protecting service.
16. A computer-implemented method for targeting information to users in a manner that protects privacy of the users, the method comprising:
receiving an indication from a user targeter of a specified criteria;
determining one or more users that have associated information that matches the specified criteria;
selecting at least some of the associated information for each of the determined users;
after obscuring sensitive information in the selected information, providing the resulting selected information to the user targeter; and
if the user targeter indicates to target specified information to the determined users based on the provided information, storing an indication of the targeting of the specified information to the determined users so that the specified information can later be provided to one or more of the determined users.
17. The method of claim 16 wherein the specified criteria is based at least in part on previous transactions, and wherein the associated information of the determined users relates to previous transactions involving those users.
18. The method of claim 17 wherein the associated information relating to previous transactions involving the determined users is received from others involved in those transactions.
19. The method of claim 17 wherein the associated information relating to previous transactions involving the determined users is received from third-parties to those transactions.
20. The method of claim 16 wherein the specified criteria is based at least in part on demographic information, and wherein the associated information of the determined users relates to demographic information for those users.
21. The method of claim 20 wherein the associated information relating to demographic information for the determined users is received from the determined users.
22. The method of claim 20 wherein the associated information relating to demographic information for the determined users is received from information sources other than the determined users.
23. The method of claim 16 wherein the associated information for each of the determined users that is selected and/or the sensitive information in the selected information that is obscured is based at least in part on the received indication from the user targeter.
24. The method of claim 16 wherein the associated information for each of the determined users that is selected and/or the sensitive information in the selected information that is obscured is based at least in part on a level of service purchased by the user targeter.
25. The method of claim 16 wherein the associated information for each of the determined users that is selected and/or the sensitive information in the selected information that is obscured is based at least in part on preferences of the determined users.
26. The method of claim 16 wherein the associated information for each of the determined users that is selected and/or the sensitive information in the selected information that is obscured is based at least in part on levels of service purchased by the determined users.
27. The method of claim 16 wherein the selecting of the associated information for the determined users includes selecting all of that associated information.
28. The method of claim 16 wherein the obscuring of the sensitive information includes removing the sensitive information.
29. The method of claim 16 wherein the obscuring of the sensitive information includes removing any information from which identities of the determined users could be determined.
30. The method of claim 16 wherein the obscuring of the sensitive information includes removing any information from which the determined users could be contacted.
31. The method of claim 16 wherein when the selected information does not include sensitive information, the obscuring of the sensitive information in the selected information does not modify the selected information.
32. The method of claim 16 wherein the specified information is information related to a marketing promotion.
33. The method of claim 16 wherein the specified information is content for presentation to the determined users.
34. The method of claim 16 including, before the determining of the users that have associated information that matches the specified criteria, receiving the associated information from third-party information providers.
35. The method of claim 16 including, after the storing of the indication of the targeting of the specified information to the determined users, receiving an indication of one of the determined users who is accessible via a device and providing the specified information to that device.
36. The method of claim 35 wherein the received indication indicates that the one determined user is involved in a transaction at a Point-Of-Sale retail location at which the device is present.
37. The method of claim 35 wherein the received indication is a request from the one determined user to provide targeted information.
38. The method of claim 35 wherein the received indication is based on stored contact information for the one determined user that indicates one or more devices of the user.
39. The method of claim 35 wherein the received indication is based on a temporary presence of the one determined user at a device from which many users may be accessible at different times.
40. The method of claim 35 wherein the received indication is based on the one determined user providing payment information specific to the user.
41. The method of claim 35 wherein the received indication is based on the one determined user providing identification information specific to the user.
42. The method of claim 35 wherein the providing of the specified information to the device includes presenting the specified information on the device.
43. The method of claim 35 wherein the providing of the specified information to the device includes storing the specified information on the device for later retrieval by the one determined user.
44. The method of claim 35 wherein the providing of the specified information to the device includes transmitting the specified information from the device to another device specific to the one determined user.
45. The method of claim 35 wherein the indication to target specified information to the determined users includes an indication related to timing of the providing of the specified information to the determined users.
46. The method of claim 45 wherein the indicated timing of the providing of the specified information to the determined users is based at least in part on one or more of a time of the providing, a location of the determined user, and a current transaction in which the determined user is involved.
47. The method of claim 35 including prompting the determined user via the device to provide additional information about the determined user.
48. The method of claim 35 including prompting the determined user via the device to provide permission to provide targeted information to the determined user.
49. The method of claim 16 wherein the specified information is for a marketing promotion including a benefit to the determined users, and including, after the storing of the indication of the targeting of the specified information to the determined users, providing the benefit to at least one of the determined users.
50. The method of claim 49 including receiving an indication that one of the determined users is involved in a transaction related to the marketing promotion, and wherein the providing of the benefit is part of the transaction.
51. The method of claim 49 wherein the providing of the benefit to the one determined user is performed only after information about the marketing promotion is provided to the one determined user.
52. The method of claim 16 including providing information to the user targeter that indicates a rate of success of providing the specified information to the determined users.
53. The method of claim 16 including providing information to the user targeter that indicates a rate of use of the specified information by the determined users that have received that specified information.
54. A computer-readable medium whose contents cause a computing device to target information to users in a manner that protects privacy of the users, by performing a method comprising:
receiving information about multiple users from one or more information sources;
receiving an indication from a user targeter of a specified criteria;
after obscuring sensitive information, providing resulting information to the user targeter about one or more of the multiple users that were determined to match the specified criteria; and
after the user targeter indicates to target specified information to the determined users based on the provided information, providing the specified information to at least one of the determined users.
55. The computer-readable medium of claim 54 wherein the specified information is information related to a marketing promotion, and wherein the providing of the specified information to at least one of the determined users includes presenting the specified information to the one determined user on a device at a Point-Of-Sale location at which the one determined user is involved in a transaction distinct from a transaction to which the marketing promotion applies.
56. The computer-readable medium of claim 54 wherein the computer-readable medium is a memory of a computing device.
57. The computer-readable medium of claim 54 wherein the computer-readable medium is a data transmission medium transmitting a generated data signal containing the contents.
58. The computer-readable medium of claim 54 wherein the contents are instructions that when executed cause the computing device to perform the method.
59. A computing device for targeting information to users in a manner that protects privacy of the users, comprising:
an information collector component that is capable of receiving information about multiple users from one or more information sources;
a user information provider component that is capable of receiving an indication from a user targeter of a specified criteria, of determining one or more of the multiple users whose associated information matches the specified criteria, and of providing information to the user targeter about the determined users so as to obscure sensitive information about the determined users; and
a targeted information provider component that is capable of, after the user targeter indicates to target specified information to the determined users based on the provided information, providing the specified information to at least one of the determined users.
60. The computing device of claim 59 wherein the information collector component, the user information provider component, and the targeted information provider component are executing in memory of the computing device.
61. A computing device for targeting information to users in a manner that protects privacy of the users, comprising:
means for receiving information about multiple users from one or more information sources;
means for receiving an indication from a user targeter of a specified criteria;
means for determining one or more of the multiple users whose associated information matches the specified criteria and for providing information to the user targeter about the determined users in a manner that obscures sensitive information about the determined users; and
means for, after the user targeter indicates to target specified information to the determined users based on the provided information, providing the specified information to at least one of the determined users.
62. A method in a computing device for providing information to targeted users, the method comprising:
identifying tracking information for a user involved in a current transaction;
receiving information that is targeted to the user based on factors other than the current transaction; and
presenting the received information to the user before completion of the current transaction.
63. The method of claim 62 wherein the identifying of the tracking information for the user includes receiving payment information for the current transaction from the user.
64. The method of claim 62 wherein the received information is for a marketing promotion for a distinct transaction with a retailer distinct from a current retailer with whom the current transaction is occurring.
65. The method of claim 62 including prompting the user for permission to provide targeted information to the user.
66. The method of claim 62 including prompting the user to register with a service providing privacy-protected targeted marketing.
67. A computing device for providing information to targeted users, comprising:
a tracking component that is capable of identifying information for a user involved in a transaction;
an information receiver component that is capable of receiving information that is targeted to the user based on factors other than the transaction; and
a provider component that is capable of providing the received information to the user as part of the transaction.
Description
CROSS REFERENCE TO RELATED APPLICATIONS
[0001] This application is a continuation-in-part of U.S. patent application Ser. No. 09/919,765 (Attorney Docket #344918001US1), filed Jul. 31, 2001 and entitled “Privacy Preserving Marketing Strategy,” which is hereby incorporated by reference in its entirety and which claims the benefit of U.S. Provisional Application No. 60/221,774, filed Jul. 31, 2000 and also incorporated herein by reference in its entirety.
TECHNICAL FIELD
[0002] The following disclosure relates generally to providing information to users, and more particularly to providing targeted information to users in a manner that protects the privacy of the users, such as when providing targeted marketing information to users at a point-of-sale in a retailer's store.
BACKGROUND
[0003] Companies and individuals that desire to provide information and/or opportunities (e.g., a discount or other type of promotional benefit) to others have significant incentives to limit distribution to recipients that are likely to use or otherwise benefit from those opportunities or information, such as to limit the cost of the distribution, to avoid unhappiness of recipients that do not wish to receive the distribution, to avoid violating legal prohibitions, etc. Similarly, individuals and organizations have significant incentives to limit the information that they receive so that the received information represents information and opportunities that they are likely to use or otherwise benefit from, such as to minimize the time and cost involved with receiving and managing undesired and useless information.
[0004] One significant problem that inhibits this mutually beneficial targeting of information and opportunities to appropriate recipients is that many individuals and organizations desire to protect their privacy, such as to prevent their identity from being revealed or otherwise detectable during a transaction (e.g., involving an item, such as a product or service, that is for sale, purchase, rent, lease, license, trade, evaluation, sampling, etc.) or to prevent their identity from being associated with transaction history information about previous transactions that is made available to third-parties that are not trusted. Similarly, such potential recipients may desire to protect their privacy by preventing various types of sensitive information from being made available to third-parties and from preventing their identity from being revealed or otherwise detectable when making various non-transaction information (e.g., demographic information, such as geographic location, age range, occupation, education level, marital status, gender, ethnic background, annual income, etc.) available to third-parties. Such potential recipients' desire to protect their privacy may also be reinforced in some situations by legal restrictions that enforce such privacy protections, whether on a uniform basis for all potential recipients or on a recipient-specific basis (e.g., based on preferences of those recipients).
[0005] Unfortunately, useful techniques are not typically available to make such information about potential recipients available to third-parties in a way that protects the privacy of the potential recipients while allowing the third-parties to effectively target information and opportunities to appropriate recipients. Accordingly, a need exists for more effective techniques for such sharing of information.
BRIEF DESCRIPTION OF THE DRAWINGS
[0006]FIG. 1 illustrates examples of the use of the disclosed techniques for targeting information to recipients while protecting the privacy of those recipients.
[0007]FIG. 2 is a network diagram illustrating various devices and entities that interact in one embodiment of the disclosed system for targeting information to recipients while protecting the privacy of those recipients.
[0008]FIG. 3 is a block diagram illustrating an embodiment of a system for targeting information to recipients while protecting the privacy of those recipients.
[0009]FIG. 4 is an example user interface screen of a device at a point-of-sale location for targeting information to consumers participating in transactions.
[0010]FIG. 5 is a flow diagram of an embodiment of the Information Collector routine.
[0011]FIG. 6 is a flow diagram of an embodiment of the Identify-Obscured User Information Provider routine.
[0012]FIG. 7 is a flow diagram of an embodiment of the Targeted Information Receiver routine.
[0013]FIG. 8 is a flow diagram of an embodiment of the Targeted Information Provider routine.
[0014]FIG. 9 is a flow diagram of an embodiment of the Registered Account Information Provider routine.
[0015]FIG. 10 is a flow diagram of an embodiment of the Targeted Marketing And/Or Tracking Device routine.
DETAILED DESCRIPTION
[0016] A software facility is described below that assists in targeting information to recipients while protecting the privacy of those recipients. In particular, the privacy-protecting information targeting techniques include obtaining various transaction and/or other recipient-specific information from one or more of a variety of information sources (also referred to herein as “Information Providers”), and providing information to individuals or organizations that desire to target information to other individuals or organizations (referred to herein as “users”) that match specified criteria. The information is provided to the individuals or organizations that desire to target information (also referred to herein as “user targeters” or “Information Users”) about the matching users in a manner that obscures the identity of those users, and in some embodiments additional types of sensitive information about users may also be obscured. After a user targeter selects identity-obscured users to which targeted information is to be provided, the information is provided to those targeted users in various ways.
[0017] In some embodiments, the facility is used to provide targeted marketing to users at a Point-Of-Sale (“POS”) location, such as in a retailer's store. In such embodiments, the received information is marketing information such as an advertisement to be displayed and/or information about a discount or other promotional benefit that is available. When a targeted user is engaged in a transaction at a POS location of a retailer (referred to in such embodiments as a “transaction retailer”), information about the user and/or the transaction is provided to the facility. Information targeted to that user, such as by an unrelated retailer user targeter (referred to in such embodiments as a “targeting retailer”) for an unrelated transaction with that retailer in which the targeted user may participate in the future, can then be provided to the user on a device at the POS.
[0018] The facility can also assist in providing targeted promotional benefits to targeted users. For example, when the facility receives information about a current transaction involving a user, the facility can determine whether a promotional benefit related to the current transaction has been targeted to the user, and if so the facility can provide information about the targeted benefit to a device or system involved in processing the current transaction so that the targeted benefit can be provided. In some embodiments, the facility provides payment processing capabilities for various retailers, and in those embodiments the facility can provide targeted benefits such as discounts before processing payment.
[0019] Information about users can be obtained by the facility in a variety of ways. In some embodiments, the facility directly receives transaction information for users from retailers involved in those transactions, such as from retailers that have joined a network of retailers sponsored by the facility (e.g., an affiliate network that includes various transaction retailers and/or targeting retailers) and/or that are willing to sell transaction information. In addition, in some embodiments the facility may receive various non-transaction information about users directly from those users, such as when those users have registered with a service associated with the facility and/or are willing to sell their information or purchase the ability to receive targeted information. The facility may also receive transaction information indirectly from third-parties to those transactions and receive user information indirectly from third-parties others than those users. For example, information about transactions and users is compiled and/or stored by various organizations (e.g., credit card and other payment type processors, credit card and other payment type issuers, banks and other financial institutions, hospitals, governmental agencies, etc.), some of which may provide the information to others for a fee and/or upon receiving permission of the users.
[0020] The facility may protect users' privacy in various ways. In some embodiments, any information about a user's identity or that could be used to directly contact the user (e.g., home or business address, phone number, email address, etc.) is removed or otherwise obscured before the information is provided to user targeters. In other embodiments, information about individual users is not provided, and instead aggregate information about groups of multiple users is instead provided. In addition, specified types of information may be removed or otherwise obscured before it is provided to user targeters, such as in a uniform manner, in a manner specific to particular users (e.g., in accordance with instructions received from those users and/or a level of privacy protection purchased by or from those users), and/or in a manner specific to the user targeters (e.g., based on instructions from those user targeters and/or a level of user information access purchased by those user targeters).
[0021] In various embodiments, payments can be made between various entities for the various services provided. For example, user targeters may provide payment for access to identity-obscured user information and/or for the targeting of information to users. In addition, information providers, whether the users themselves or third-parties, may be paid for providing information (e.g., 60% of the fee paid by a user targeter to receive user information, which may for example be one-third of the total fee paid by a user targeter to have a targeting campaign be provided) and/or for providing permission to use information. Users may be paid for allowing themselves to received targeted promotions, or instead may make payment in order to receive such targeted promotions. Entities that provide a location for presenting or otherwise providing targeted promotions or other information, such as a POS location at a retailer, may receive payment for allowing the providing of the targeted information (e.g., 15% of the fee paid by a user targeter to provide targeted information to targeted users, which may for example be two-thirds of the total fee paid by a user targeter to have a targeting campaign be provided), or may instead in some situations make payment to receive such promotions. The provider of a privacy-protecting service based on the functionality provided by the facility may also receive payment for facilitating the targeting of information to targeted users in a manner that protects their privacy (e.g., 40% of the fee paid by a user targeter to receive user information and 85% of the fee paid by a user targeter to provide targeted information to targeted users, or 70% of the total fee paid by a user targeter to have a targeting campaign provided). Other information about payment arrangements is discussed below.
[0022] For illustrative purposes, some embodiments of the software facility are described below in which the targeted information is marketing information and in which the targeted marketing information and the resulting promotional benefits are provided to users by sending information to devices at retailers' POS locations. However, those skilled in the art will appreciate that the techniques of the invention can be used in a wide variety of other situations, and that the invention is not limited to these illustrated embodiments. In addition, in some embodiments the software facility could also provide a variety of other related functionality or services, such as a spam-limiting service that assists users (e.g., registered users) in limiting or eliminating the receipt of information or promotions from some or all sources other than those associated with the software facility (e.g., by adding the users' names to “Do Not Call” lists of direct marketers using email, telephone, postal mail, etc.), such as for a fee.
[0023] As an illustrative example of the use of a Privacy-Protecting Targeted Marketing and Tracking (“PPTMT”) system facility that assists in targeting marketing information and resulting promotional benefits to users while protecting the privacy of those users, consider three targeted marketing examples illustrated in FIG. 1.
[0024] The first example, shown with respect to timeline 110, illustrates an example of targeting a promotion to a user based merely on the transaction history of the user and without knowledge of the identity of the user by the PPTMT system or the user targeter. In particular, in the illustrated example User U buys a first item from a first retailer using a credit card issued to U, and the retailer or credit card payment processor provides information to the PPTMT system about the transaction that includes the credit card number but no other identifying information about U. U later buys a different item from a different retailer using that same credit card, and the PPTMT system again receives transaction data for that transaction that includes the credit card number. The PPTMT system is able to associate those two purchases together based on the use of that credit card, and to use that unique credit card number as identification tracking information for User U without knowing the identify of U.
[0025] At a later time, a third retailer decides to target a new promotion for yet another item to users that match a specified criteria (e.g., purchasing Item B and any of a group of items that include Item A within the last week), and the purchase of the two previous items by U matches the criteria. The user targeter Retailer N may first view various identity-obscured information about one or more users that match the specified criteria and/or other criteria, or may instead merely specify the criteria. Retailer N provides details about the targeted marketing promotion to the PPTMT system, such as an ad to be displayed and a discount to be provided. At a later time, U buys a fourth item from another retailer using the same credit card, and the PPTMT system receives information about the transaction from a device at the POS. The system identifies that the holder of the credit card being used is to receive the targeted marketing promotion for Item C from Retailer N (still without knowing that the card holder is U), and provides information to U about the promotion at the POS at the time of purchase (e.g., by displaying the ad on a display of the device at the POS and/or printing out a coupon indicating the discount).
[0026] When U later buys Item C from Retailer N using that same credit card, the PPTMT system recognizes that the holder of that credit card is to receive the targeted marketing promotion, and sends information to a device at the Retailer N POS to ensure that any corresponding discounts or other promotional benefits are provided to U at the time of purchase. Thus, in this way U can receive a targeted marketing promotion without any of the retailers L-O or the PPTMT system ever knowing the identify of U or any other non-transactional information about U.
[0027] The second example in FIG. 1 is illustrated with respect to timeline 120, and provides an example of providing targeted content to a user based on their demographic information without the targeting retailer knowing the identity of the user. In particular, in this illustrated example the PPTMT system first obtains demographic and debit card information for a User B directly from B when B registers with the PPTMT system, although in other situations such information could be obtained from one or more third-party sources of information. At some point after B registers with the PPTMT system, a retailer P targets an advertisement for Item E to a group of one or more identity-obscured users that match specified demographic information criteria, with the targeted group in this example including B. When B later buys another item from another retailer and provides information with which the PPTMT system can identify B (e.g., use of one or more registered debit cards and/or providing of a unique registered user ID), the PPTMT system provides the targeted ad for presentation to B at the POS. B chooses to not receive the benefits of the promotion at this time. As a registered user, however, B does later access the PPTMT system (e.g., from a home computer or publicly accessible kiosk) to view his/her account information and/or to receive additional targeted promotions, with the information provided in a manner in accordance with preference information supplied at the time of registration.
[0028] In the third example illustrated in FIG. 1, shown with respect to timeline 130, a User W qualifies for a targeted promotion based on a combination of transaction and demographic information for W that is received by the PPTMT system after the targeted promotion criteria have been specified. In particular, a Retailer R targets a promotion for Item G to users that match specified criteria including demographic and transaction information. At a later time, W rents Item H from another retailer and supplies some type of user-specific information that distinguishes the user from others (e.g., phone number, social security number, etc.), and the PPTMT system receives the transaction data and user-supplied information. The PPTMT system later receives demographic information and other user-specific information for multiple users that include W from a third-party information source, with the user-specific information for W including the information supplied by W when renting Item H, but the PPTMT system does not receive information about the identities of the multiple users. W later leases an Item I from yet another retailer and supplies user-specific information that was included in the information about W from the third-party data source (e.g., different user-specific information than was supplied by W when renting Item H), and the PPTMT system again receives the transactional data.
[0029] After receiving this various information and correlating the demographic information and the transactional information for the two transactions based on the various user-specific information for W, the PPTMT system identifies W (without knowing W's identity) as matching the targeted promotion. Thus, when W later again rents the same Item H from the same retailer S as in the first transaction and again supplies user-specific information for W that the PPTMT system is aware of (whether the same or different from the user-specific information supplied in the first transaction), the PPTMT system identifies W as a targeted recipient for the promotion and thus provides information to W about that promotion. When W later performs a corresponding transaction with Retailer R that matches the promotion, the PPTMT system recognizes that W is to receive the benefits of the targeted promotion and provides information to Retailer R to ensure that those benefits are provided.
[0030] Thus, the PPTMT system can use various techniques to track users and to provide targeted benefits to those users in a manner that protects their privacy.
[0031]FIG. 2 is a network diagram illustrating various devices and entities that interact in one embodiment of the PPTMT system. In this example embodiment, a PPTMT network 205 having one or more servers stores various transaction data 215 and user data 210, and provides that information in an identity-obscured fashion to user targeters 235. The user targeters can then select groups of one or more anonymous users to receive various targeted promotions and/or targeted content 220. As shown, the PPTMT network can receive the user and transaction data from various sources, such as receiving user data from the users themselves via devices 225 used by the users and/or from third-party user information data sources 230. Transaction data can also be provided by third-party transaction tracking devices 260 that are associated with the PPTMT system, whether in real-time or in periodic batches. In the illustrated embodiment the transaction tracking devices 260 are linked to POS devices 265 from which they receive at least some of the transaction information.
[0032] The PPTMT network in this example embodiment can also receive transaction data from various PPTMT-associated devices 250 each in communication with at least one corresponding POS device 240. These privacy-protecting transaction targeted marketing and tracking (or “PPTTMT”) devices both provide transaction information to the PPTMT system for tracking purposes and receive promotion information to be applied to current transaction and/or provided to the user for use in possible future transactions. In particular, the PPTTMT devices receive transaction data from their corresponding POS devices, and send that transaction data to the PPTMT network for use in later targeting of marketing information. These example PPTTMT devices also supply information to the PPTMT network to identify information about any targeted promotions to be applied to a current transaction and to receive targeted promotions to be presented to a current user for possible use in future transactions. Thus, if the transaction data is sufficient to identify the current user (e.g., from a credit card or other user-specific payment information used as part of the transaction), no other user-specific information may be supplied, or instead various non-transaction user information (e.g., a user ID or credit card information for a credit card that is not being used as part of the current transaction) may additionally be supplied. In other embodiments, users may be identified in other manners, such as using various biometric identification techniques and/or performing signature recognition of a user's signature (e.g., from a credit card authorization signature).
[0033] In this example embodiment, promotion information for the current transaction can be based on the current user and/or the current transaction (e.g., based on a promotion previously targeted to the current user for this or any transaction from the current retailer, and/or based on a promotion previously targeted to any user involved in a type of transaction of which the current transaction is an example), while the promotion information for future transactions is based only on the current user without regard to the current transaction or the current retailer. As is shown, the PPTTMT devices and their corresponding POS devices can have various configurations, such as one-to-one or one-to-many relationships, and POS devices can be stand-alone or networked together. For example, some of the POS devices are linked together as part of a retailer network 280 (e.g., with other computing devices of that retailer), such as POS devices at multiple physical locations.
[0034] In addition to the PPTTMT devices that provide transaction information for tracking purposes, receive promotion information to be applied to current transactions, and receive promotion information to be provided to the user for future transactions, the PPTMT network in this example embodiment can also include associated devices that perform only one of these three functions. For example, some dedicated PP transaction targeted marketing devices 270 may receive use promotion information for a current transaction, but not provide transaction data for tracking to the PPTMT network or present targeted promotion information for future transactions. Conversely, some PP targeted marketing devices that are not associated with POS devices may receive and present targeted promotion information for future transactions, but not provide information about current transactions (if any) or receive promotion information to be applied to current transactions. As previously noted, transaction tracking devices 260 that are associated with the PPTMT system may provide transaction data for tracking to the PPTMT network, but not receive promotion information for current or future transactions.
[0035]FIG. 3 is a block diagram illustrating one or more PPTMT server computing devices 300 that are part of the PPTMT network and are suitable for executing an embodiment of the PPTMT system, either alone or in combination. The PPTMT server computing devices are also able to communicate with various remote devices 350-390, as described in greater detail below. The devices can interact in various ways, such as over a dedicated local area network, over the Internet and/or the World Wide Web, over a secure extranet, etc.
[0036] Each server computing device 300 includes a CPU 305, various I/O devices 310, storage 320, and memory 330. The I/O devices include a display 311, a network connection 312, a computer-readable media drive 313, and various other I/O devices 315. An embodiment of the PPTMT system 340 is executing in memory, and it includes various components 341-349.
[0037] The PPTMT system components include a Direct User Information Collector component 342 and a Third-Party User Information Collector component 343. These components interact with users and third-party information data sources respectively to obtain user information for use in targeting appropriate content and promotions to those users. To receive user information, the Direct User Information Collector component interacts with a variety of information devices 360 which can present user-personalized information and from which users can supply information, such as personal computers, publicly accessible kiosks, cell phones, interactive TVs, etc. Similarly, the Third-Party User Information Collector component interacts with various third-party user information data source devices 380 or information services or storage (not shown) to retrieve user information. In the illustrated embodiment, the collected user information is stored in a user information database 321 data structure on storage, although in other embodiments such information could be stored in other manners (e.g., remotely or in a distributed manner), or could instead be dynamically retrieved from appropriate information sources when needed.
[0038] While in some embodiments users and/or third-party user information data sources may be able to interact with the PPTMT system without having established a prior relationship with the system, in other embodiments such entities will first establish such a relationship. Thus, an optional Registered Account Information Provider component 341 is also illustrated in memory, and it can similarly interact with the user and third-party devices 360 and 380 to establish relationships and to provide information about corresponding accounts and relationships. A variety of other types of entities may similarly have established relationships and thus also be able to interact with the Registered Account Information Provider component, including user targeters (e.g., retailers) via user targeter devices 390, retailers or others willing to provide transaction data (not shown), retailers or others willing to receive and apply information about their own promotions for current transactions (not shown), and retailers or others willing to receive and provide promotion information for future transactions from themselves and/or other user targeters (also not shown). In the illustrated embodiment, the Registered Account Information Provider component stores various information about the registered entities in a registered account information database 323 on storage, although in other embodiments different databases may be used for each type of entity and/or the account information may be stored in other manners.
[0039] In a manner similar to the information collector components, the Tracked Transaction Information Collector component 344 obtains information about transactions by users for use in targeting promotions and content to those users. In the illustrated embodiment, the component interacts with both third-party transaction tracking devices 370 and dedicated targeted marketing and tracking devices 350 in order to receive transaction information, and stores such information in the transaction information database 325 on storage. As with the user information, in other embodiments the transaction information may be stored in other manners and/or retrieved dynamically when needed.
[0040] The Identity-Obscured User Information Provider component 345 receives requests from user targeters to provide information about users that match specified criteria, and provides the information to those user targeters in a manner that protects the identity and/or privacy of the users. In particular, the component may retrieve user information and/or transaction information from the databases 321 and 325, obscure the identity of corresponding users in the retrieved information in various ways, and then provide the identity-obscured information to the requesting user targeters.
[0041] After a user targeter selects a promotion and/or content to be targeted to a group of one or more users, the user targeter provides that information to the Targeted Promotion/Content Receiver component 347. The component 347 stores copies of the targeted information in a database 327 on storage, although in other embodiments may retrieve such information from the user targeters and/or other accessible sources when needed. The component 347 also stores information about a targeting campaign (e.g., users to be targeted, the number of times and the frequency with which the targeted users are to receive the targeted information, the length of the targeting campaign etc.) specified by the user targeter in a targeted information campaign database 329 on storage. In some embodiments, an optional Targeted Promotion/Content Generator component 346 may also be available to generate the targeted promotions or content for users, such as interactively in a manner controlled by the user targeters or instead in an automated manner.
[0042] After one or more targeting campaigns have been defined, the Targeted Promotion/Content Provider component 348 identifies when information received for current transactions and/or currently accessible users matches those defined campaigns, and provides the targeted information for those campaigns as appropriate. For example, the targeted marketing and tracking devices 350 may indicate information about a current transaction and/or a current user, and the component 348 may identify information about targeted promotional benefits to be provided as part of the current transaction and provide that information to those devices. Similarly, the component 348 may identify information to be provided to a current user about promotions for future transactions, and if so can provide that information to the targeted marketing and tracking device for presentation to the user. Such user-specific targeted information can also be provided to users when they are accessible to the system in other manners, such as via a user personalizable information device 360. After targeted promotions or content are provided to users or applied to current transactions, the campaign database 329 is updated to reflect the current status. In other embodiments, separate databases may be used to store campaign details and campaign status information.
[0043] The illustrated system also includes an optional Targeting Payment component 349. In the illustrated embodiment, the component can interact with any of the other system components to provide and/or obtain payment for any of the activities performed by the other components, with such payments being obtained from or provided to any of the various devices or entities previously mentioned.
[0044] In addition to the PPTMT system, an optional transaction payment processor module 332 is also executing in memory. In embodiments in which targeted marketing devices receive payment information directly from users or indirectly from POS devices, one or more of the PPTMT servers may also provide the service of processing payment for a corresponding transaction, either for an associated POS device and/or for transactions conducted solely over the targeted marketing device.
[0045] Those skilled in the art will appreciate that computing devices 300, 350, 360, 370, 380 and 390 are merely illustrative and are not intended to limit the scope of the present invention. In particular, any of the “devices” may comprise any combination of hardware or software that can interact in the described manners, including computers, network devices, internet appliances, PDAs, wireless phones, pagers, electronic organizers, television-based systems and various other consumer products that include inter-communication capabilities. Computing device 300 may also be connected to other devices that are not illustrated, including through one or more networks such as the Internet or via the World Wide Web (WWW). In addition, the functionality provided by the illustrated system components may in some embodiments be combined in fewer components or distributed in additional components. Similarly, in some embodiments the functionality of some of the illustrated components may not be provided and/or other additional functionality may be available.
[0046] Those skilled in the art will also appreciate that, while various items are illustrated as being stored in memory or on storage while being used, these items or portions of them can be transferred between memory and other storage devices for purposes of memory management and data integrity. Alternatively, in other embodiments some or all of the software modules and/or components may execute in memory on another device and communicate with the illustrated computing device via inter-computer communication. Some or all of the system components or data structures may also be stored (e.g., as instructions or structured data) on a computer-readable medium, such as a hard disk, a memory, a network, or a portable article to be read by an appropriate drive. The system components and data structures can also be transmitted as generated data signals (e.g., as part of a carrier wave) on a variety of computer-readable transmission mediums, including wireless-based and wired/cable-based mediums. Accordingly, the present invention may be practiced with other computer system configurations.
[0047]FIG. 4 provides an example of one graphical user interface that may be used to provide targeted information to users at a transaction POS, such as on a dedicated targeted marketing and tracking device at the POS. In this example, the device display screen 400 includes various sections 405-420 that can each present different types of information, although those skilled in the art will appreciate that in other embodiments such information can be presented in other manners, that additional types of information may be presented, and/or that illustrated types of information may not be presented.
[0048] In this example embodiment, the user interface includes a section 405 in which non-targeted information can be provided, such as branding information for the PPTMT system or a corresponding service or instead for a retailer at whose location the device resides. The user interface also includes a section 410 in this example embodiment in which the user can input information to be provided to the PPTMT system, such as a unique user ID or other information (e.g. a PIN) to assist in identifying or tracking the user. In other embodiments, the device may provide a similar information input capability but in a manner other than as part of the display, such as via a keypad or keyboard on which numeric or alphanumeric information may be provided or by transmitting the information to the device from another device accessible to the user.
[0049] The illustrated user interface also includes a section 415 in which information about a current transaction can be provided, such as prices or other information, instructions (e.g., to enter payment information), and/or information about targeted promotional benefits to be received as part of the current transaction. The user interface also includes a section 420 in which one or more pieces of targeted information can be presented based on the current user and/or other current transaction. In the illustrated embodiment, this section is divided into four subsections 420 a-420 d that are each able to present a distinct piece of information (e.g., a static image such as an ad, or a video or audio clip), although in other embodiments only a single piece of targeted information may be presented at a single time, the displayed non-targeted information may be replaced with targeted information when current transaction and/or current user information becomes available, and/or the types of information and the information layout may be dynamically modified based on the circumstances.
[0050] The example device and/or the interface on the device may also include a variety of other functionalities that are not illustrated, such as an ability to communicate with one or more computing devices of the user (e.g., in a wireless manner), such as to receive information to identify the user and/or to pay for the transaction or instead to provide information to the user such as targeted content or promotion details for storage on the user's device or presentation to the user on that device. In some embodiments, the device may also include an integrated or nearby printer with which to print out coupons or other targeted promotional information or targeted content.
[0051] In some embodiments, such a targeted marketing and tracking device can also be used to dynamically register users at the time of a transaction. For example, if the device includes the ability to accept payment information from the user (e.g., a slot with which to swipe magnetically encoded cards or to read smart cards or other types of computer-readable media) or receives such payment information indirectly from an associated POS device, the user interface can present the user with a selectable option to register the user and to use the available payment information for the user as a identifying tracking information, as well as optionally allow the user to provide additional information (e.g., a PIN). Even if payment information is not received by the targeted marketing and tracking device, the device could still query the user as to whether they wish to be registered as long as some information was available with which to track the user's identity, such as a unique ID or a username provided by the user. Moreover, the user interface could be designed to allow already registered users to identify themselves if the current transaction does not automatically provide identifying tracking information for the user (e.g., if the user has used a new credit card that was not previously registered or not otherwise associated with the user). Such a targeted marketing and tracking device could also be used in some embodiments to gather additional information from a user (e.g., user preferences and/or for use in targeting information to that user) and/or to obtain permission from a user (e.g., to allow targeting of information to that user and/or to allow use of certain information about that user for targeting purposes)
[0052]FIG. 5 is a flow diagram of an embodiment of the Information Collector Routine 500. The routine receives and stores various types of user-related and transaction information from a variety of sources, so that the information can be used for targeting purposes. The routine begins at step 505 where information is received, and in step 510 the type of the information is determined. If the information is transaction information, the routine continues to step 515 to identify unique information about the user from the transaction information for tracking purposes, such as from a credit card used to complete the transaction. After step 515, the routine continues to step 520 to store the transaction information along with a mapping to the identified user tracking information. If no user information could be identified in step 515, in some embodiments the transaction information may instead not be stored (not illustrated here).
[0053] If it was instead determined in step 510 that the received information was user-related, the routine continues to step 525 to select the next group of information, beginning with the first. In some embodiments, only a single group of information may be received, but in other situations a large number of groups of information for a large number of users may be received (e.g., from a third-party user information data source that has access to information about many users). After step 525, the routine continues to step 530 to identify user tracking information for the user corresponding to the selected information, and in step 535 stores the selected information with a mapping to that user. If no user information could be identified in step 530, in some embodiments the user-related information may instead not be stored (not illustrated here). After step 535, if it is determined in step 540 that additional groups of information remain, the routine returns to step 525.
[0054] If it was instead determined in step 510 that the received information was of another type, the routine continues to step 550 to store the other information as appropriate. After steps 520 or 550, or if it was instead determined in step 540 that there were not more groups of information, the routine continues to step 555 to make or obtain payment for the collected information as appropriate. The routine then continues to step 595 to determine whether to continue, and if so returns to step 505. If not, the routine continues to step 599 and ends.
[0055] In other embodiments, various additional types of functionality could be provided. For example, if user-related information is received interactively from a user, the routine could additionally provide other information to that user such as account information.
[0056]FIG. 6 is a flow diagram of an embodiment of an Identity-Obscured User Information Provider Routine 600. The routine provides identity-obscured information about users to user targeters for use in determining targeting information to be provided to users, such as for a targeting campaign. The routine begins at step 605 where a request is received from a user targeter to provide information about users that match a specified criteria. In step 610, the access privileges of the user targeter are determined, such as based on a previous registration of that user targeter and a corresponding type of access selected by that registered user targeter.
[0057] If it is determined in step 615 that the user targeter request is authorized, the routine continues to step 620 to determine one or more users that match the specified criteria. In step 625, various available demographic, transaction-related, and other information about the determined users is retrieved. In step 630, any users and/or user information types for which the user targeter is not authorized or has not requested are removed, and in step 635 any information that could be used to identify the users or that would violate any other privacy concerns are removed or modified. In step 640, the remaining identity-obscured information is then provided to the user targeter, and in step 645 payment is made or retrieved for the providing of the information as appropriate. After step 645, or if it was instead determined in step 615 that the request was not authorized, the routine continues to step 695. If it is determined in step 695 to continue, the routine returns to step 605 and if not the routine continues to step 699 and ends.
[0058] Those skilled in the art will appreciate that identity information can be obscured in various ways, such as by aggregating information about multiple users together and/or by providing detailed information about individual users that lacks identifying information. In various embodiments, such identity-obscuring of user information can be performed in manners specific to the users and/or to the user targeters, such as based on applicable legal restrictions, user preferences, a purchased level of service form a user targeter or the users, etc. In addition, in some embodiments the targeting may occur in manners that are not specific to groups of users. In particular, in some embodiment user targeters may specify additional information related to how the targeting of information is to occur, such as to target information on the basis of any combination of time of targeting, location of targeting, types of transactions during which the targeting is to occur, and/or types of users to which the targeting will occur.
[0059]FIG. 7 is a flow diagram of an embodiment of the Targeted Information Receiver routine 700. The routine receives information from user targeters about targeting information and stores the information for use in targeted marketing to the targeted users. The routine begins at step 705 where a request is received from a user targeter to initiate a campaign to target specified information to a specified group of one or more identity-obscured users. The routine continues to step 710 to determine the access privileges of the user targeter, and if it is determined in step 715 that the request is authorized, the routine continues to step 720 to store the targeted information or a link to that information if it is accessible elsewhere. In step 725, information about the targeted campaign is stored, including identifications of the users targeted and any other relevant campaign information. In step 730, payment is made or obtained as appropriate for the receiving and/or the storing of the campaign information and the targeted information. After step 730, or if it was instead determined in step 715 that the request was not authorized, the routine continues to step 795 to determine whether to continue. If so, the routine returns to step 705, and if not the routine continues to step 799 and ends. Those skilled in the art will appreciate that campaign information can be specified in a variety of ways in various embodiments.
[0060]FIG. 8 is a flow diagram of an embodiment of the Targeted Information Provider Routine 800. The routine provides targeted promotion information and content to users and POS payment processors as appropriate based on a current transaction and/or a current identified user. The routine begins in step 805 where a request is received to provide targeted information for an identified transaction and/or for a user corresponding to identified user tracking information. The routine continues to step 810 to determine access privileges of the requester, and then continues to step 815 to determine whether the request is authorized. If so, the routine continues to step 820 to determine targeting information to be provided to the user. In particular, the routine identifies one or more targeting campaigns for the identified transaction and/or the user with the identified user tracking information. The routine then continues to step 825, where if multiple targeting campaigns or corresponding pieces of targeted information were identified, those possible information pieces are ranked and then one or more are selected. Those skilled in the art will appreciate that the ranking and selecting can be performed in a variety of manners, such as based on information from the requester, agreements with the user targeters who created the campaigns, user preferences, etc.
[0061] After step 825, the routine continues to step 830 to determine whether information was received in step 805 regarding a current transaction that has a corresponding current targeted promotion to be applied. In some embodiments, targeted promotions will be applied only if they have previously been identified to the user involved in the current transaction, and in other embodiments such a restriction may not be used. If there is a corresponding current targeted promotion to be applied, the routine continues to step 835 to retrieve the promotion information. After step 835, or if it was instead determined in step 830 that there was no current targeted promotion, the routine continues to step 840 to determine whether the request in step 805 was received from a user, such as to interactively provide various types of targeted promotions or other targeted content. If so, the routine continues to step 845 to optionally retrieve additional types of promotional or other information to be provided to the user, such as user account status information or various user-selectable options.
[0062] After step 845, or if it was instead determined in step 840 that the request was not from the user, the routine continues to step 850 to provide to the requester the selected targeted information, any retrieved promotional information, and any retrieved additional information. The routine then continues to step 855 to update the targeted information campaign status information to reflect the providing of the targeting information and optionally the providing of the current promotion information. After step 855, the routine continues to step 860 to make or obtain payment as appropriate for the providing of the various types of information. After step 860, or if it was instead determined in step 815 that the request was not authorized, the routine continues to step 895 to determine whether to continue. If so, the routine returns to step 805, and if not the routine continues to step 899 and ends. While not illustrated here, in other embodiments the routine may additionally provide other functionality, such as to direct a device at the POS location to query the user regarding dynamically registering at the device.
[0063]FIG. 9 is a flow diagram of an embodiment of a Registered Account Information Provider Routine 900. The routine receives requests from registered entities to access their account information, and provides the information as appropriate. The routine begins in step 905 where a request is received to access account information. The routine continues to step 910 to determine the access privileges of the requester. If it is determined at step 915 that the request is authorized, the routine continues to step 920 to determine the type of requester. If the requester is of one of the various types of “user”, “third-party user information provider”, “user targeter”, “transaction information provider”, or “other”, the routine continues respectively to steps 925, 930, 935, 940, or 945. In each of steps 925-945, account information for the respective type of user is retrieved, and after any of those steps the routine continues to step 950 to provide the retrieved information to the requester. After step 950, or if it was instead determined in step 915 that the request was not authorized, the routine continues to step 995 to determine whether to continue. If so, the routine returns to step 905, and if not the routine continues to step 999 and ends. In other embodiments, this or another routine could additionally allow one or more of the types of requesters to open accounts or modify existing account information.
[0064]FIG. 10 is a flow diagram of an embodiment of the Targeted Marketing And/Or Tracking Device Routine 1000. The routine in the illustrated embodiment operates in conjunction with a corresponding POS device to receive information about a current user and/or current transaction, to communicate with the PPTMT system to receive information about targeted promotions and/or targeted content, and to apply the information from the PPTMT system to the current transaction and/or provide the information to the user.
[0065] The routine begins in step 1005 where the user interface is initialized and non-targeted information is displayed. In step 1010, the routine receives an indication of a new transaction beginning and/or of a new user that is accessing the device. Such information can be received in a variety of ways, such as from an associated POS device or instead directly from the user and/or an operator of the device (e.g., a clerk in a retail location). The routine continues to step 1015 to determine whether the current device is acting as a device to present targeted marketing information to users, and if so continues to step 1020 to retrieve targeted information for the indicated user and/or transaction from the PPTMT system. After step 1020, the routine continues to step 1025 to present and/or provide the retrieved targeted information to the user. After step 1025, or if it was instead determined in step 1015 that the device is not acting to provide targeted marketing information, the routine continues to step 1030 to determine whether to retrieve additional information about current users and/or the current transaction, and if so returns to step 1010.
[0066] If not, the routine continues to step 1035 to determine whether the device is currently operating as a transaction tracking device to provide information about current transactions to the PPTMT system to assist in later targeting. If so, the routine continues to step 1040 to provide information about the current transaction to the system. After step 1040, or if it was instead determined in step 1035 that the device was not acting as a transaction tracking device, the routine continues to step 1045 to determine whether information was received about a targeted promotion for the current transaction that is to be applied. If so, the routine continues to step 1050 to determine whether the device is providing payment processing functionality for the transaction (e.g., in conjunction with the PPTMT system). If not, the routine continues to step 1055 to notify the POS device and/or other payment processor of the promotion to be applied, and if so the routine continues to step 1060 to adjust the payment amount to reflect the promotion to be applied before processing the adjusted payment amount. After steps 1055 or 1060, or if it was instead determined in step 1045 that there is not a current targeted promotion, the routine continues to step 1095 to determine whether to continue. If so, the routine returns to step 1005, and if not the routine continues to step 1099 and ends.
[0067] Those skilled in the art will also appreciate that in some embodiments the functionality provided by the routines discussed above may be provided in alternative ways, such as being split among more routines or consolidated into less routines. Similarly, in some embodiments illustrated routines may provide more or less functionality than is described, such as when other illustrated routines instead lack or include such functionality respectively, or when the amount of functionality that is provided is altered. In addition, while various operations may be illustrated as being performed in a particular manner (e.g., in serial or in parallel) and/or in a particular order, those skilled in the art will appreciate that in other embodiments the operations may be performed in other orders and in other manners. Those skilled in the art will also appreciate that the data structures discussed above may be structured in different manners, such as by having a single data structure split into multiple data structures or by having multiple data structures consolidated into a single data structure. Similarly, in some embodiments illustrated data structures may store more or less information than is described, such as when other illustrated data structures instead lack or include such information respectively, or when the amount or types of information that is stored is altered.
[0068] From the foregoing it will be appreciated that, although specific embodiments have been described herein for purposes of illustration, various modifications may be made without deviating from the spirit and scope of the invention. Accordingly, the invention is not limited except as by the appended claims and the elements recited therein. In addition, while certain aspects of the invention are presented below in certain claim forms, the inventors contemplate the various aspects of the invention in any available claim form. For example, while only some aspects of the invention may currently be recited as being embodied in a computer-readable medium, other aspects may likewise be so embodied.
Referenced by
Citing PatentFiling datePublication dateApplicantTitle
US7406593 *May 2, 2003Jul 29, 2008Shieldip, Inc.Method and apparatus for protecting information and privacy
US7747873Mar 4, 2005Jun 29, 2010Shieldip, Inc.Method and apparatus for protecting information and privacy
US7933228Oct 7, 2008Apr 26, 2011Keep In Touch Services, Inc.Time sensitive scheduling data delivery network
US7991995Jun 20, 2008Aug 2, 2011Shieldip, Inc.Method and apparatus for protecting information and privacy
US8239304 *Feb 26, 2003Aug 7, 2012Jpmorgan Chase Bank, N.A.Method and system for providing pre-approved targeted products
US8327453Apr 27, 2010Dec 4, 2012Shieldip, Inc.Method and apparatus for protecting information and privacy
US8405484Sep 29, 2008Mar 26, 2013Avaya Inc.Monitoring responsive objects in vehicles
US8407607 *Feb 19, 2009Mar 26, 2013International Business Machines CorporationDynamic virtual dashboard
US8694368 *Dec 8, 2006Apr 8, 2014American Express Travel Related Services Company, Inc.Method, system, and computer program product for spend mapping tool
US8825753 *Jun 14, 2012Sep 2, 2014Cellco PartnershipMethods and systems to provide dynamic content and device panel management
US20080140503 *Dec 8, 2006Jun 12, 2008American Express Travel Related Services Company, Inc.Method, System, and Computer Program Product for Spend Mapping Tool
US20090094158 *Oct 9, 2007Apr 9, 2009Fein Gene SMethod and Apparatus for Processing and Transmitting Demographic Data Based on Secondary Marketing Identifier in a Multi-Computer Environment
US20100211890 *Feb 19, 2009Aug 19, 2010International Business Machines CorporationDynamic virtual dashboard
US20110029366 *Jan 25, 2010Feb 3, 2011Robert BernsteinMethod and apparatus for identifying customers for delivery of promotional materials
US20110196714 *Feb 9, 2010Aug 11, 2011Avaya, Inc.Method and apparatus for overriding apparent geo-pod attributes
US20120016738 *Aug 24, 2010Jan 19, 2012My World, Inc.Performance based pricing, promotion, and personalized offer management
US20130339422 *Jun 14, 2012Dec 19, 2013Cellco Partnership D/B/A Verizon WirelessMethods and systems to provide dynamic content and device panel management
US20140032304 *Jul 27, 2012Jan 30, 2014Google Inc.Determining a correlation between presentation of a content item and a transaction by a user at a point of sale terminal
US20140164114 *Feb 18, 2014Jun 12, 2014American Express Travel Related Services Company, Inc.Method, system, and computer program product for spend mapping tool
US20140316903 *Jul 8, 2014Oct 23, 2014Quickplay Media Inc.Consumption profile for mobile media
WO2004013792A1 *Jun 27, 2003Feb 12, 2004Phillip Y GoldmanDirect marketing management on behalf of subscribers and marketers
WO2009049075A2 *Oct 9, 2008Apr 16, 2009Gene S FeinMethod and apparatus for processing and transmitting demographic data based on secondary marketing identifier in a multi-computer environment
WO2009054927A2 *Oct 19, 2008Apr 30, 2009Robert Bernard ColeySystem and method for a time sensitive scheduling data promotions network
WO2014141078A1 *Mar 11, 2014Sep 18, 2014Yandex Europe AgA method of and system for providing a client device with particularized information without employing unique identifiers
Classifications
U.S. Classification1/1, 707/999.001
International ClassificationG06Q30/00
Cooperative ClassificationG06Q30/02
European ClassificationG06Q30/02
Legal Events
DateCodeEventDescription
Mar 12, 2003ASAssignment
Owner name: KOC HOLDING A.S., TURKEY
Free format text: ASSIGNMENT OF ASSIGNORS INTEREST;ASSIGNOR:OYTAC, ENGIN;REEL/FRAME:013825/0558
Effective date: 20030123
|
__label__pos
| 0.709254 |
GROW YOUR TECH STARTUP
Microsoft’s Minotaur Moment: navigating the power dynamics of OpenAI and GitHub’s collective intelligence merger
April 26, 2023
SHARE
facebook icon facebook icon
The Minotaur Myth
The Minotaur from Greek mythology is a perfect example of something that had tremendous power yet also had a fatal weakness. The Minotaur was a half-human, half-bull creature with great strength and ferocity.
However, it was ultimately defeated by the Athenian hero Theseus, who used the creature’s one fatal weakness—its inability to navigate the labyrinth in which it was imprisoned—against it.
Now, let’s find out how this powerful Greek mythical creature has anything to do with modern-day Microsoft, and how can aspiring young entrepreneurs find ways to fight its almost insurmountable power.
Microsoft’s Resurgence
Microsoft's resurgence
Microsoft’s resurgence
When Satya Nadella took the reins as Microsoft’s CEO in 2014, he inherited a company that was facing stagnation and struggling to compete in the rapidly evolving technology landscape.
Nadella’s leadership has since been credited with reinvigorating Microsoft by pivoting its focus from traditional operating systems and productivity software to cloud computing and AI.
One good example is the Office productivity suite, and how it has evolved both before and after Nadella’s reign.
Microsoft Office, first introduced in 1989, has become a cornerstone of productivity and communication in the business world.
As a suite of software applications, it initially comprised Word, Excel, and PowerPoint, but has since grown to include other tools such as Outlook, Access, and Publisher.
Microsoft’s consistent efforts to improve and refine these applications have allowed them to maintain a dominant position in the market.
By the early 2000s, Microsoft Office had become the industry standard for document creation, data management, and presentation design, a position it continues to hold today.
In 2011, Microsoft introduced Office 365, a significant shift in the company’s business strategy. By transitioning to a cloud-based, subscription model. This model helped solidify Microsoft’s dominance in the market, while also creating a strong customer lock-in effect.
The subscription model ensured a steady revenue stream for Microsoft and encouraged users to stay within the ecosystem, as the cost of switching to alternative solutions became more cumbersome and less appealing.
But Microsoft’s ambitions went far beyond Office 365 and Azure cloud computing.
Enter the Minotaur
As we recall from the Greek myth, the Minotaur had great strength, mostly because it was a hybrid creature of half human and half bull. If we might make an analogy, Microsoft is:
• Half Human: human language and wisdom via OpenAI exclusive license
• Half Bull: computer language and intelligence via its ownership of GitHub
We shall delve into each of these equally powerful halves for deeper analysis.
Half Human – OpenAI and ChatGPT
OpenAI and human intelligence
OpenAI and human intelligence
Microsoft’s strategic investment in and its exclusive licensing partnership with OpenAI, the inventor of ChatGPT, has played a significant role in solidifying the company’s position as a dominant player in the AI field.
Announced in 2019, the partnership has helped Microsoft leverage OpenAI’s cutting-edge research to develop new AI technologies and integrate them into its products and services.
This collaboration has fueled the growth of Microsoft’s AI ecosystem, enabling the company to deliver AI-driven capabilities across its offerings, including Azure AI services, Cortana, and even Office 365 applications.
The sheer scope and unusually high velocity of OpenAI integration inside Office 365, Microsoft’s crown jewel of productivity suite, speaks volumes of the strategic importance of OpenAI to Microsoft.
So, in a way, Microsoft now captures the entirety of human language, knowledge, and at least some inferred wisdom (which some Microsoft researchers called “a spark of AGI”). Through its exclusive licensing deal with OpenAI, it won’t have any close competitors.
You may argue that Google and Meta might challenge OpenAI/Microsoft’s monopoly, but their respective large language models, Bard and LLaMA, appear to be at least one generation behind.
In addition, OpenAI has evolved from a non-profit organization to a capped-profit organization. And there is this amusing cap of profit at 100 times investment.
Since Microsoft has already pumped and planned to pump over 10 billion dollars into OpenAI, you can safely assume that OpenAI will not disassociate from Microsoft any time soon.
And Microsoft can always “invest” more money into OpenAI instead of buying products and services from OpenAI. This will perpetuate the symbiosis between OpenAI and Microsoft.
It is no surprise that a bunch of very important people are alarmed enough to sign a petition to halt all AI research for the next 6 months.
Half Bull – GitHub, Codex, and Co-Pilot
GitHub and digital bull
GitHub and digital bull
The acquisition and integration of GitHub in 2018, a leading platform for software development and collaboration, further extended Microsoft’s grip on human intelligence as a whole.
GitHub is a hub for all leading open-source projects, and you can consider it the aggregated repository of human intelligence expressed in a computer language that runs everything for everyone in today’s world.
I would like to highlight the significance of OpenAI’s Codex, an advanced language model that has had a profound impact on the field of software development, particularly through its integration with GitHub’s Copilot.
Codex, which is part of the GPT-3 family of models, is capable of understanding and generating human-like text, including programming code.
Its ability to interpret natural language queries and generate accurate and contextually relevant code snippets has made it a valuable tool for developers.
GitHub’s Copilot, which leverages the capabilities of Codex, serves as an AI-powered coding assistant that helps developers write code more efficiently by providing real-time suggestions and automatically completing code segments.
Copilot’s integration with Codex has transformed the software development process by reducing the time and effort required to write code, minimizing errors, and enabling developers to focus on higher-level design and problem-solving tasks.
After using GitHub Co-Pilot for an extended period of time and recently combining it with ChatGPT v4, I have just started to realize its tremendous power and immense potential.
As a product manager and co-founder, now I can conceptualize an idea, write a succinct requirement, and let ChatGPT spit out a pretty decent boilerplate.
Then, in Visual Studio Code with GitHub Co-Pilot, I can modify the function and parameters where necessary, fine-tune a bit of control flow and business logic, and I have a fully working prototype within hours.
Since I’m not a real practicing software engineer, such prototyping would have cost me 1-2 weeks of hacking time or begging some software engineers to work on it.
And it is not that far off from a true “no code” software development movement that will flourish among people who don’t even understand the basics of existing computer programming languages.
For experienced software engineers, there are claims of 3x or even 10x productivity improvements via the combination of GitHub Co-Pilot and chatGPT v4.
These tools can easily find the design patterns from GitHub’s gigantic repository and fit into the context of the software system that the developer is currently working on.
It saves a lot of Google searches, reduces typing and error checking, and automates a large portion of documentation and testing. One engineer even lamented that he felt like losing one of his arms when GitHub Co-Pilot was offline for a few hours.
The Potential Danger of the Minotaur
Google’s mission is to “organize the world’s information and make it universally accessible and useful”, and it achieves that by basically doing a PageRank on all the websites and building a giant index for them.
But with Microsoft/OpenAI’s GPT large language model and GitHub codex, the world’s information might become condensed into billions and trillions of weights (numbers of statistical importance, figuratively speaking).
And that’s when it hit me that we have entered the Minotaur moment of Microsoft.
Microsoft’s deep-rooted relationship with OpenAI has raised concerns about the potential for the company to use its combined power to create a monopoly in the field of artificial intelligence.
OpenAI’s GPT-4 language model is one of the most powerful AI systems in the world today, and GitHub is the world’s largest code-hosting platform.
If Microsoft were to use these tools to stifle competition, it could have a significant impact on the development of AI and the tech industry as a whole.
It is important to note that these are just concerns, and there is no evidence that Microsoft is planning to use its combined power in a monopolistic way.
However, it is crucial to be aware of the potential dangers of such a move and to ensure that Microsoft does not abuse its power.
The Hope for Theseus (and Startups)
Young Theseus
Young Theseus
Innovate on the Shoulders of Giants
Startups can leverage big companies’ platforms to innovate on new products by tapping into the resources, infrastructure, and user base that these platforms offer. Here are a few examples of previous success stories:
1. Apple App Store and Google Play Store: By building apps on these platforms, startups can access a vast market of smartphone users, easily distribute their products, and benefit from the app stores’ secure payment systems.
2. Amazon Web Services (AWS): Startups can utilize AWS’s cloud computing infrastructure to build and scale their applications, store data, and access advanced analytics tools. This allows them to focus on innovation and product development without worrying about investing in and managing their own IT infrastructure.
By leveraging big companies’ platforms, startups can gain access to resources, infrastructure, and user bases that would otherwise be difficult or expensive to acquire. This enables them to focus on innovation and product development, increasing the chances of success in the competitive market.
We are already witnessing the Cambrian Explosion for AI-powered tools and solutions. Not a single day goes by without a flurry of announcements from aspiring startups mashing up OpenAI’s GPT with new datasets (legal, financial), other AI models (voice recognition, image recognition), other generative AI solutions (voice synthesizing, text-to-image and text to video), and many more.
Seek Help From the Sovereign
One of the key risks of building on 3rd party for-profit platforms is that the platform might change, die, or even compete against its own ecosystem partners. One example is Facebook vs Zynga, while another example is major social networks’ de-platforming of different ideologies.
Therefore, entrepreneurs might be able to find help in unusual places: Governments and Regulators to thwart any anti-competitive behavior. And they might be able to learn a page from the previous anti-trust lawsuits in the technology sector.
Playing the Game in the Open
Open field
Open field
Open source has been the trusted and true weapon to fight big closed-source monoliths. Since OpenAI has closed-source its GPT-3 and GPT-4 models, Meta did an atypical move and open-sourced its own large language model named LLaMA for research purposes.
This is by far the most advanced open-source LLM, with up to 65 billion weights trained on 1.4 trillion words.
Even more interestingly, Meta also open-sourced 7, 13, and 33 billion weight models. These smaller LLMs enabled many research teams to come up with their own fine-tuned models based on the LLaMA.
To name just a few: Alpaca from Stanford, Vicuna and Koala from Berkeley, GPT4All, and many many more.
Using Reinforced Learning via Human Feedback, these research efforts claim they can reach 90-95% performance of the commercial ChatGPT 3.5 (175 billion weights), with only 7 billion or 13 billion weights.
When you have these smaller LLM models and optimized C++ implementations like llama.cpp, suddenly you can run these models locally on your laptop. You now have a smart assistant running locally that does not rely on cloud service and costs nothing.
The LLaMA models are for research only, thus you cannot use them commercially.
There does truly exist open source LLMs, even though their scale and performance are generations behind the state of art commercial alternatives. However, many more open-source LLMs are popping up like mushrooms after an autumn rain.
If you keep alert on huggingface and GitHub, you can find many of them such as:
• OpenAI: GPT-2 and GPT-Neo
Think Outside of the Labyrinth
The labyrinth
The labyrinth
Office 365 might be Microsoft’s own Labyrinth. Why would I say that?
Above all, Office 365 is critically important to Microsoft from a revenue and profit point of view (23% of total revenue in 2022 (source). Microsoft might be able to add OpenAI capabilities to Office 365, but it might remain to be an incremental update rather than a fundamental change.
This is simply because Microsoft cannot move their enterprise customers, who are known to be risk-averse and glacial in change, into a new paradigm at too fast a pace or too dramatic a way. So in a way, Office 365 is kind of Microsoft’s shackles as well.
So where are the opportunities for young startups? If we step back a bit, the reason we created the Microsoft Office suite, including Word, Powerpoint, and Excel, was that we could communicate better in a business environment.
How can we invent new ways of communication that transcend beyond these existing tools? Think how Slack and Notion have transcended from emails, and how Figma has surpassed the traditional Adobe creative suite.
Imagine how newer human-machine and human-human interfaces can work in a business environment.
If you want to push into sci-fi territories, you can take into account Elon Musk’s Neuralink where humans and machines are electrically connected.
The advent of technologies like Elon Musk’s Neuralink, which aims to establish direct communication between human brains and machines, opens up exciting possibilities for reimagining communication in the business environment.
Here are a few ways such technology could potentially transcend traditional tools like the Microsoft Office suite:
1. Thought-to-text communication: With the help of brain-computer interfaces (BCIs) like Neuralink, people could communicate their thoughts directly as text or visual content, bypassing the need for keyboards or other input devices. This could lead to a more efficient and faster exchange of ideas, minimizing misunderstandings and miscommunications that can arise from conventional methods.
2. Collaborative brainstorming: Brain-computer interfaces could enable real-time sharing of thoughts and ideas during brainstorming sessions, allowing team members to simultaneously contribute and visualize concepts. This could enhance creative problem-solving and decision-making processes, fostering a more collaborative and efficient work environment.
3. Immersive presentations: Combining BCIs with augmented reality (AR) or virtual reality (VR) technologies could revolutionize business presentations. Instead of relying on traditional tools like PowerPoint, presenters could create immersive, interactive experiences that engage the audience’s senses and emotions, leading to more effective communication of complex concepts and ideas.
4. Emotion-aware communication: BCIs could potentially detect emotions and mental states during conversations, enabling participants to better understand each other’s feelings and perspectives. This could enhance empathy, facilitate constructive feedback, and foster healthier working relationships.
5. Direct knowledge transfer: Neuralink and similar technologies could pave the way for direct knowledge transfer between individuals or from machines to humans. This could revolutionize learning and training processes in the workplace, making them more efficient and personalized.
While the development and implementation of technologies like Neuralink still have a long way to go, their potential to transform communication in the business environment is undeniable.
By enabling more direct, efficient, and empathetic forms of communication, brain-computer interfaces could revolutionize how we collaborate, make decisions, and share knowledge in the workplace.
An Uncertain Future
Look out into future
Look out into future
While I am excited and elated by the newfound productivity gain from Microsoft’s OpenAI and GitHub combination, I am also concerned that one company can hold that much power over the entirety of the human race’s collective intelligence.
I hope young Theseus can pick up the open-source sword and fight a new path outside of the labyrinth so that humanity’s intellect can prosper freely.
Footnote: all illustrations are by the author and MidJourney
This article was originally published by Bruce Li on Hackernoon.
SHARE
facebook icon facebook icon
Sociable's Podcast
Trending
|
__label__pos
| 0.553623 |
ImadBakir ImadBakir - 6 months ago 17
Javascript Question
Google maps API getting drive time and road
I'm trying to achieve something like the following in the image
enter image description here
but Actually I don't have any Idea if it's possible or how and where to start.
so if you can please lead me if it's possible or not, and how to achieve it or where to start
or if anyone knows a similar online working example it would be great
thanks in advance
Answer
I found the answer myself, yes it's possible thanks to jfvanderwalt for the useful link of google Docs for Direction API which led me to the working example of what I need and how to do it , here is my working demo example Javascript :
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var australia = new google.maps.LatLng(41.171418,28.311553);
function initialize() {
var mapOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: australia
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Istanbul, Turkey',
destination: 'Ankara, Turkey',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var time= 0;
var from=0;
var to=0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
time +=myroute.legs[i].duration.text;
from =myroute.legs[i].start_address;
to =myroute.legs[i].end_address;
}
time = time.replace('hours','H');
time = time.replace('mins','M');
total = total / 1000.
document.getElementById('from').innerHTML = from + '-'+to;
document.getElementById('duration').innerHTML = time ;
document.getElementById('total').innerHTML =Math.round( total)+"KM" ;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
HTML:
<div id="map-canvas" style="margin-left:15px;float:left;width:930px; height:280px"></div>
<div style="float:left;padding-left:20px; padding-top:15px; width:100%; height: 80px;">
<div style="float:left;width: 50%;"><h3 id="from"></h3></div>
<div style="float:right;margin-right: 20px;width: 158px;text-align: right;">
<h3 id="duration"></h3>
</div>
<div style="float:right;width: 158px;text-align: right;">
Comments
|
__label__pos
| 0.962652 |
How To Create Simple Java Bean Class For Login Page In Eclipse
1 Answer
0
1. Open Eclipse IDE and create a new Java project.
2. Right-click on the project and select New → Class.
3. In the New Java Class dialog, give the class a name (e.g. LoginBean) and select the option to create a public static void main(String[] args) method.
4. Click Finish to create the class.
5. In the LoginBean class, define private instance variables for the username and password:
private String username;
private String password;
6. Add a default constructor to the class:
public LoginBean() {
// default constructor
}
7. Add getter and setter methods for the username and password:
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
8. Add a method to validate the login, returning true if the username and password match:
public boolean validateLogin(String username, String password) {
return this.username.equals(username) && this.password.equals(password);
}
9. Save the class and use it in your login page to create LoginBean objects and validate the login input.
Unknown
answered
Your Answer
``` code ```
**bold**
*italic*
>quote
Login Sign up
|
__label__pos
| 0.999999 |
Blog
Excel Formulas Ultimate Guide
Excel Formulas
Blog
Excel Formulas Ultimate Guide
The Excel Formulas Ultimate Guide
Introduction to Excel Formulas
In this guide, we are going to cover everything you need to know about Excel Formulas. Learning how to create a formula in Excel is the building block to the exciting journey to become an Excel Expert. So, let’s get started!
What is an Excel Formula?
Excel Formulas are often referred to as Excel Functions and it’s no big deal but there is a difference, a function is a piece of code that executes a predefined calculation, and a formula is an equation created by the user.
A formula is an expression that operates on values in a cell or range of cells. An example of a formula looks like this: = A2 + A3 + A4 + A5. This formula will result in the sum of the range of values from cell A2 to cell A5.
A function is a predetermined formula in Excel. It shows calculations in a particular order defined by its parameters. An example of a function is =SUM (A2, A5). This function will also provide the addition of values in the range of cells from A2 to A5 but here instead of specifying each cell address we are using the SUM function.
How To Write Excel Formulas
Let’s look at how to write a formula on MS Excel. To begin with, a formula always starts with a ‘+’ or ‘=’ sign, if you start writing the formula without any of these two signs, Excel will treat the value in that cell as text and will not perform any function.
In the screenshot below, you need to calculate the total sales amount by multiplying quantity sold with unit price. Select cell D2, type the formula ‘=B2*C2’ and press Enter. The result will display on cell D2.
Apply A Formula To An Entire Column Or Range
To copy a formula to adjacent cells, you can do the following:
1. Select the cell with the formula and the adjacent cells you want to fill, then drag the fill handle.
1. Select the cell with the formula and the adjacent cells you want to fill, then press Ctrl+D to fill the formula down in a column, or Ctrl+R to fill the formula to the right in a row.
2. Select the cell with the formula and the adjacent cells you want to fill, then Click Home > Fill, and choose either Down, Right, Up, or Left.
How to Copy A Formula And Paste It
Excel allows you to copy the formula entered in a cell and paste it on to another cell, which can save both time and effort. To copy paste a formula:
1. Select the cell whose formula you wish to copy
2. Press Ctrl + C to copy the content
3. Select the cell or cells where you wish to paste the formula. The copied cells will now have a dashed box around them.
4. Press Alt + E + S to open the paste special box and select ‘Formula’ or Press “F’ to paste the formula.
1. The formula will be pasted into the selected cells.
Basic Excel Formulas
Let’s start off with simple Excel Formulas. In the screenshot below, there are two columns containing numbers and we would like to use different operators like addition, subtraction, multiplication, and division on those to get different results. Excel uses standard operators for formulas, such as a plus sign for addition (+), a minus sign for subtraction (-), an asterisk for multiplication (*), a forward slash for division (/).
Excel Formulas
• Addition– To add values in the two columns, simply type the formula =A2+B2 on cell C2 and then copy paste the same on the cells below.
• Subtraction – To subtract values in Column B from Column A, simply type the formula =B2-A2 on cell C2 and then copy paste the same on the cells below.
• Multiplication – To multiply values in the two columns, simply type the formula =A2*B2 on cell C2 and then copy paste the same on the cells below.
• Division – To divide values in Column a by values in Column B, simply type the formula =A2/B2 on cell C2 and then copy paste the same on the cells below.
We can also calculate the percentage using Excel Formulas. In the image below, we have sales in Year 1 and Year 2 and we would like to know the % growth in sales from Year 1 to Year 2.
To do that, select cell C2 and type the formula = (B2 – A2)/B2*100
Basic Excel Functions
A function is a predefined formula that performs calculations using specific values in a particular order. Excel includes many common functions that can be useful for quickly finding the sum, average, count, maximum value, and minimum value for a range of cells. a function must be written a specific way, which is called the syntax.
The basic syntax for a function is an equals sign (=), the function name, and one or more arguments. A Function is generally comprised of two components:
1) A function name -The name of a function indicates the type of math Excel will perform.
2) An argument – It is the values that a function uses to perform operations or calculations. The type of argument a function uses is specific to the function. Common arguments that are used within functions include numbers, text, cell references, and names
Let’s look at some common Excel Functions:
SUM Function
The SUM formula adds 2 or more numbers together. You can use cell references as well in this formula.
Syntax: =SUM(number1, [number2], …)
Example: =SUM(A2:A8) or SUM(A2:A7, A9, A12:A15)
AUTOSUM Function
The AutoSum command allows you to automatically insert the most common functions into your formula, including SUM, AVERAGE, COUNT, MIN, and MAX.
Select the cell where you want the formula, Go to Home > Click on AutoSum > From the dropdown click on “Sum” > Enter.
Excel Formulas
COUNT Function
If you wish to how many cells are there in a selected range containing numeric values, you can use the function COUNT. It will only count cells that contain either numbers or dates.
Syntax: =COUNT(value1, [value2], …)
In the example below, you can see that the function skips cell A6 (as it is empty) and cell A11 (as it contains text) and gives you the output 9.
COUNTA Function
Counts the number of non-empty cells in a range. It will include cells that have any character in them and only exclude blank cells.
Syntax: =COUNTA(value1, [value2], …)
In the example below, you can see that only cell A6 is not included, all other 10 cells are
counted.
AVERAGE Function
This function calculates the average of all the values or range of cells included in the parentheses.
Syntax: =AVERAGE(value1, [value2], …)
ROUND Function
This function rounds off a decimal value to the specified number of decimal points. Using the ROUND function, you can round to the right or left of the decimal point.
Syntax: =ROUND(number,num_digit)
This function contains 2 arguments. First, is the number or cell reference containing the number you want to round off and second, number of digits to which the given number should be rounded.
• If the num-digit is greater than 0, then the value will be rounded to the right of the decimal point.
• If the num-digit is less than 0, then the value will be rounded to the left of the decimal point.
• If the num-digit equal to 0, then the value will be rounded to the nearest integer.
MAX Function
This function returns the highest value in a range of cells provided in the formula.
Syntax: =MAX(value1, [value2], …)
In the example below, we are trying to calculate the maximum value in the dataset from A2 to A13. The formula used is =MAX(A2: A13) and it returns the maximum value i.e. 96.251
MIN Function
This function returns the lowest value in a range of cells provided in the formula.
Syntax: =MIN(value1, [value2], …)
In the example below, we are trying to calculate the minimum value in the dataset from A2 to A13. The formula used is =MIN(A2: A13) and it returns the minimum value i.e. 24.178
TRIM Function
This function removes all extra spaces in the selected cell. It is very helpful while data cleaning to correct formatting and do further analysis of the data.
Syntax: =trim(cell1)
In the example below, you can see the name in cell A2 contains an extra space, in the beginning, =TRIM(A2) would return “Steve Peterson” with no spaces in a new cell.
Excel Formulas
Advanced Excel Formulas
Here is a list of Excel Formulas that we would feel comfortable referring to as the top 10 Excel Formulas. These formulas can be used for basic problems or highly advanced problems as well, though advanced excel formulas are nothing but a more creative way of using the formulas. Sure, there are legitimate Advanced Excel Formulas such as Array Formulas but in general the more advanced the problem, the more creative you need to be with Formulas.
Currently, Excel has well over 400 formulas and functions but most of them are not that useful for corporate professionals so here is a list that we believe contains the 10 best Excel formulas.
Starting with number 10 – it’s the IFERROR formula
1. IFERROR Function –
2. SUBTOTAL Function –
3. SMALL/LARGE Function –
4. LEFT Function –
5. RIGHT Function –
6. SUMIF Function –
7. MATCH Function –
8. INDEX Function –
9. VLOOKUP Function –
10. IF Function –
IFERROR Function –
You ever have presented a worksheet that you thought was perfect but were surprised with a “#DIV /0!” error or an “#N/A” error message (See the screenshot below), then this function is perfect for you. Excel has an “IFERROR” function that can automatically replace error messages with a message of your choice.
Excel Formulas
The IFERROR function has two parameters, the first parameter is typically a formula and the second parameter, value_if_error, is what you want Excel to do if value, the first parameter, results in an error. Value_if_error can be a number, a formula, a reference to another cell, or it can be text if the text is contained in quotes.
That means you can put formula or an expression in the first part of the IFERROR function and Excel will show the result of that formula unless the formula results in an error. If the formula results in an error, Excel will follow the instructions in the second half of the IFERROR formula.
This function cleans up your sheet and it will visually make things look a lot better and more professional.
Let’s see an example to make the concept clearer.
Excel Formulas
In this example, we have two lists – one contains the names of all people (Column A) and the second list contains the name of award winners only (Column F).
We have used a simple Vlookup function to see if the name is an award winner. The Vlookup function (it is covered later in details) will search the list on the right, if the name is present in the award winner list, it will show the name or else it will show an error.
The N/A error makes the worksheet look dirty and unprofessional. Now we will add iferror function here to remedy the same.
=IFERROR(VLOOKUP(A5,$F$5:$F$10,1,0),””)
Excel Formulas
IFERROR function will recognize the error and instead of displaying the error message will display the text, say a blank, or you can show any other message that you desire.
IFERROR is a great way to replace Excel-generated error messages with explanations, additional information, or simply leave the cell blank.
SUBTOTAL Function –
The SUBTOTAL function returns the aggregate value of the data provided. You can select any of the 11 functions that SUBTOTAL can calculate like SUM, COUNT, AVERAGE, MAX, MIN, etc. SUBTOTAL Function can also include or exclude values in hidden rows based on the input provided in the function.
Excel’s traditional formulas do not work on filtered data since the function will be performed on both the hidden and visible cells. To perform functions on filtered data one must use the subtotal function.
Syntax: SUBTOTAL(function_num,ref1,…)The first parameter is the name of the function to be used within the subtotal function and the second parameter is the range of cells that should be subtotalled
The list of functions that can be used in given below. If the data is filtered manually, the numbers from 1 – 11 will include the hidden cells and number from 101 – 111 will exclude them.
Excel Formulas
Let’s understand this function with an example.
Excel Formulas
Here we have a list of name of person, with their country and the total sales they have achieved in Q1. We will use the subtotal function to calculate the total sales in cell C26. We will also select the function in such a way that it works on filtered data as well.
The formula will be =SUBTOTAL (109,C5:C24)
Excel Formulas
This will display the total sales. Now, we filter the data to see the sales made by people in US only. You will see the value in the cell containing the SUBTOTAL function updates and it filters the dataset and displays the total sales made by US only.
Excel Formulas
Here is another benefit of using a SUBTOTAL function:
When you’re creating an information summary, especially like a profit and loss statement where you’ve got lots of subtotals, what you can do is you can use the subtotal formula, and then at the end, you can put a big old formula right at the end and it will just ignore your subtotal.
Here we have 4 different tables for sales in 4 different countries.
Excel Formulas
We can add individual SUBTOTAL functions for each table and then a grand total function in the end. The SUBTOTAL function in the end will ignore all the other SUBTOTAL functions above it and will provide you the total sales.
Excel Formulas
SMALL/LARGE Function –
Here, we have two formulas and they’re two sides of the same coin – the small formula and the large function. So, imagine you’ve got a list of, let’s say, sales data or cost data and what SMALL Function will do is provide you with the smallest value in the data set. You can also specify if you want the first smallest or second smallest. Similarly, with the large formula, you can extract the largest value in this dataset, the second largest and so on.
Syntax: =LARGE(array,k); SMALL(array,k)
The first parameter is the range of data for which you want to determine the k-th largest value and the second is the position (from the largest/smallest) in the cell range of the value to return.
Excel Formulas
Now, in the dataset above if you want to know the person who has achieved the highest sales, you can use the LARGE function – =LARGE($C$4:$C$23,E5). We have used E5 for the second parameter as it contains the value 1. If we copy paste the formula in the cells below, you will get the 1st, 2nd, 3rd, 4th and 5th largest value in the dataset. Similarly, we have used the function SMALL to get the value for lowest sales.
Excel Formulas
LEFT & RIGHT Function –
A lot of people work on text manipulation with functions like text to columns or even do it manually but being able to extract the exact number of characters that you want from the left or the right side of a string is absolutely invaluable. This is what the LEFT and RIGHT function does – it extracts a given number of characters from the left/right side of a supplied text string.
Syntax: =LEFT (text, [num_chars]) and RIGHT(text,num_chars)
The first parameter is the text string containing the characters you want to extract and the second parameter specifies how many characters you want LEFT/RIGHT to extract; 1 if omitted.
In the example given below, we have full names of people and we would like to extract the first name. We can surely do it using text to column, but using the LEFT function will give us a more automated result. So, let’s see how it can be done.
Excel Formulas
When you look at the data, you can see that a character is common in all names and it separates the first name and last name – it is a “space”. If we can find out the position of space in each cell, we can easily extract the first name.
Does Excel have a formula for this as well? Off course! SEARCH is the function that will come to your rescue.
SEARCH function provides the position of the first occurrence of the specified character.SEARCH (find_text, within_text, start_num) has three parameters – first is the character you want to find, second is the text in which you want to search and third is the character number in Within_text, counting from the left, at which you want to start searching. If omitted, 1 is used.
So, going back to our example, we use the formula SEARCH to find the position of the character – space in Column A. We will need to subtract “1” from the position to get the desired result. The formula will be =SEARCH (“ “,A5)-1 and copy paste it down.
Excel Formulas
Now we will use the LEFT Function to get the first name. =LEFT(A5,B5) – A5 contains the full name and B5 contains the number of characters from left that contains the first name.
Excel Formulas
SUMIF(S) Function –
This function is used to conditionally sum up a range of values. It returns the summation of selected range of cells if it satisfies the given criteria. It is like the SUM function because it adds stuff up. But, it allows us to specify conditions for what to include in the result. Criteria can be applied to dates, numbers, and text using logical operators (>,<,<>,=) and wildcards (*,?) for partial matching. For example, SUMIF function can add up the quantity column, but only include those rows where the SKU is equal to, say A200.
Syntax: =SUMIF (range, criteria, [sum_range])
The first argument is the range of values to be tested against the given criteria, second argument is the condition to be tested against each of the values and the last argument is the range of numeric values if the criteria is satisfied. The last argument is optional and if it is omitted then values from the range argument are used instead.
SUMIF can handle one criterion only. For multiple conditional summing – we can use SUMIFS.
The Syntax of this function is =SUMIFS( sum_range, criteria_range1, criteria1, [criteria_range2, criteria2], … ); where sum_range is the range of values to add, criteria_range1 is the range that contains the values to evaluate and criteria1 is the value that criteria_range1 must meet to be included in the sum. You can add additional pairs of criteria range and criteria if further conditions are to be met.
It is advisable to use SUMIFS even if you have only one criteria to evaluate as it will help you to easily modify the function if additional conditions come up over time.
Let’s dive into an example. Below we have data containing name, country in which sales were made, and the different quarterly sales data.
Excel Formulas
Using SUMIFS function, we would like to calculate the sum of sales in Q1 for the different countries. Now, to get the total sales in UK in Q1, we select the cell I4 and type the formula =SUMIFS(C4:C23,B4:B23,H4). We will then copy paste the formula below to get the result for each country.
INDEX & MATCH Function –
The MATCH function is used to search for an item and return the relative position of that item in a horizontal or vertical list.
Syntax: MATCH(lookup_value, lookup_array, [match_type])
The first argument is the value you want to look up, second is the range of cells being searched and the last argument, which is optimal, tells the MATCH function what sort of lookup to do.
The three acceptable values for match type are 1, 0 and -1. The default value for this argument is 1.
• If the input is 1. MATCH finds the largest value that is less than or equal to the lookup_value. The values in the lookup_array argument must be placed in ascending order.
• If the input is 0. MATCH finds the first value that is exactly equal to the lookup_value. The values in the lookup_array argument can be in any order.
• If the input is -1. MATCH finds the smallest value that is greater than or equal to the lookup_value. The values in the lookup_array argument must be placed in descending order.
For example, if the range A1:A5 contains the values Evelyn Greer, Randy Mueller, Maverick Cooper, Eesha Bevan and Nancie Velez, then the formula =MATCH(“Maverick Cooper”,A1:A5,0) returns the number 3, because Maverick Cooper is the third item in the range.
Excel Formulas
INDEX
function is used to return the value in the cell based on the row number and column number provided. It can do two-way lookup: where we are retrieving an item from a table at the intersection of a row header and column header.
Syntax: =INDEX (array, row_num, [col_num])
The first argument is the range/array containing the values you want to look up, second is the row number; the row number from which the value is to be fetched (if omitted, Column_num is required) and third is the column number from which the value is to be fetched.
For Example: =INDEX(A1:B6,3,2)
This function will look in the range A1 to B6, and It will return whatever value is housed in Row 3 and Column 2. The answer here will be “India” in cell B3.
Excel Formulas
As you have seen, Index and Match on their own are effective and powerful formulas but together they are absolutely incredible. Let’s look at it.
Remember that you must tell INDEX Function which row and column number to go to. In the examples above, we hard coded it to a specific number. But instead, we can drop this MATCH function into that space in our formula and make the formula dynamic.
Let’s dive into an example.
Excel Formulas
Here we have two dropdowns in cell H9 and H11 containing names and quarters. What we want is that, once we select a name in cell H9 and a quarter in cell H11, the corresponding sales for the specified person and quarter appears in cell H14. We will be using INDEX & MATCH to accomplish this.The formula will be: =INDEX($A$3:$F$23,MATCH(H9,$A$3:$A$23,0),MATCH(H11,$A$3:$F$3,0))
Excel Formulas
This function will take A3:F23 as the range and the first match will use the name mentioned in cell H9 (here, Eesha Bevan) and obtain the position of it in the Name column (A3:A23). This becomes the row number from which the data needs to be taken. Similarly, the second match will use the quarter mentioned in cell H11 (here, Q2 Total Sales) and obtain the position of it in the Quarter’s row (A3:F3). This becomes the column number from which the data needs to be taken. Now, based on the row and column number provided by the Match functions, index function will now provide the required value, i.e. 18,250.
This formula is now dynamic, i.e. if you change the name or quarter in cells H9 or H11 the formula will still work and provide the correct value.
VLOOKUP Function –
This function is not as flexible or powerful as the combination of Index and Match that we talked about just now, however, the reason this is number 2 on the list is simply because it’s quick, flexible, easy to implement and doesn’t put a whole lot of strain on your CPU while calculating.
Vlookup is a vertical lookup function that tries to match a value in the first column of a lookup table and then return an item from a subsequent column.
Syntax: VLOOKUP ( lookup_value , table_array , col_index_num , [range_lookup] )
• Lookup_value: Is the value to be found in the first column of the table, and can be a value, a reference, or a text string.
• Table_array: This is the lookup table and the first column in this range must contain the lookup_value.
• Col_index_num: This is the column number in table_array from which the matching value should be returned.
• Range_lookup: is a logical value that tells you the type of lookup you want to do. To find the closest match in the first column (sorted in ascending order) use TRUE; to find an exact match use FALSE (if omitted, TRUE is used as default).
Excel Formulas
In the example above, the first table contains name, country and quarterly sales and the second table contains the country name and nationality.
Now, we have an empty column (Column G) in the first table and we want to use Vlookup to extract the nationality of a person based on the country name mentioned in Column B.
Excel Formulas
The function will be: =VLOOKUP(B4,$K$3:$L$7,2,0). This function will lookup the value in cell B4 (i.e. UK) in the first column of the range K3:L7 and will return the corresponding value from the second column of the range i.e. British.
IF Function
So, why is this formula so important? Simply because this function gives you the flexibility to control your outcomes. When you can understand and model your outcomes, you can create logic and thus create a business model.
IF function is a logical test that evaluates a condition and returns a value if the condition is met, and another value if it is not met.
Syntax: =IF(logical_test,[value_if_true],[value_if_false])
• Logical test – It is condition that needs to be evaluated. The logical operators that can be used are = (equal to), > (greater than), >= (greater than or equal to), < (less than), <= (less than or equal to) and <> (not equal to).
• Value_if_true – Is the value that is returned if Logical_test is TRUE. If omitted, TRUE is returned.
• Value_if_false – Is the value that is returned if Logical_test is FALSE. If omitted, FALSE is returned.
You can also use OR and AND functions along with IF to test multiple conditions. Example: =IF(AND(logical_test1, logical_test2),[value_if_true],[value_if_false]).
IF functions can also be nested, the FALSE value being replaced by another IF function to make a further test. Example: =IF(logical_test,[value_if_true,IF(logical_test,[value_if_true],[value_if_false])).
Let’s go through the IF function with an example to discuss it in detail.
Excel Formulas
In the screenshot above, we have a table that contains the name, country and quarterly sales achieved by different persons. Now, we want to see which persons have been promoted based on the criteria that the total sales achieved by that person is greater than £250,000. In the column for Promotions (Column G), we want the formula to test whether the total sales are greater than £250,000, if it is true then we want the text “Promoted” to be displayed, else a blank.
The formula to be used will be: =IF(C4+D4+E4+F4>250000,”Promoted”,””)
Excel Formulas
So, this completes our Top 10 Excel formulas. As we have already mentioned there are 400+ Excel formulas available and these 10 best Excel formulas will cover about 70% to 75% of your needs, but if you want to go a little bit more we have a book about the 27 best Excel formulas that will cover pretty much all of your formula requirements. The best thing about this is – it contains info-graphics and is completely free!
Excel Formulas Not Working: Troubleshooting Formulas
Continuing our series on Excel Formulas, this part is all about troubleshooting Excel Formulas. Let’s look at the major issues.
How To Refresh Excel Formulas
If Your Excel Formulas are Not Calculating, then start off by refreshing them. Do either of the following methods to refresh formulas:
• Press F2 and then Enter to refresh the formula of a particular cell.
• Press Shift + F9 to recalculate all formulas in the active sheet or you can go to the Formula Tab > Under Calculation Group > Select “Calculate Sheet”.
Excel Formulas
• Press F9 to recalculate all formulas in the workbook or you can go to the Formula Tab > Under Calculation Group > Select “Calculate Now”.
Excel Formulas
• Press Ctrl + Alt + F9 to recalculate formulas in open worksheets of all open workbooks.
• Press Ctrl + Alt + Shift + F9 to recalculate formulas in all sheets in all open workbooks.
How To Show Formulas In Excel
Usually when you type a formula in Excel and press Enter, Excel displays a calculated value in the cell. If you wish to see the formula that you have typed in the cell, you can do either of the following methods:
• Go to Formula Tab > Under Formula Auditingsection > Click on “Show Formulas”.
Excel Formulas
• Press Ctrl + ` to show formulas in the cell.
Excel Formulas
How To Audit Your Formula
Formula Auditing is used in Excel to display the relationship between formulas and cells. There are different ways in which you can do that. Let’s cover each one in detail:
• Trace Precedents
Trace Precedents shows all the cells that affect the formula in the selected cell. When you click this button, Excel draws arrows to the cells that are referred to in the formula inside the selected cell.
Excel Formulas
In the example below, we have a cost table that contains totals and grand total. We will now use trace precedents to check how the cells are linked to each other.Click on the cell containing grand total (Cell C15) > Go to Formula Tab > Click on “Trace Precedents”.
Excel Formulas
To see the next level of precedents, click the Trace Precedents command again.
Excel Formulas
To remove arrows, simply go to Formula Tab > Click on “Remove Arrows”.
Excel Formulas
• Trace Dependents
Trace Dependents show all the cells that are affected by the formula in the selected cell. When you click this button, Excel draws arrows from the selected cell to the cells that use, or depend on, the results of the formula in the selected cell.
Excel Formulas
In the example below, we have a cost table that contains totals and grand total. We will now use trace dependents to check how the cells are linked to each other.Click on the cell containing Property Cost (Cell C3) > Go to Formula Tab > Click on “Trace Dependents”.
Excel Formulas
To see the next level of dependents, click the Trace Dependents command again
Excel Formulas
• Evaluate Formula
This function is used to evaluate each part of the formula in the current cell. The Evaluate Formula feature can be quite useful in formulas that nest many functions within them and helps in debugging an error.
Excel Formulas
To evaluate the calculation in cell C15 (Grand Total), Click on the cell > Go to Formula Tab > Click on “Evaluate Formula”.
Excel Formulas
A dialog box will appear that will enable you to evaluate parts of the formula.
This will help you to debug an error as it provides you with the value calculated at each step of evaluation done by Excel.
• Error Checking
This function is helpful as it is used to understand the nature of an error in a cell and to enable you to trace its precedents.
Excel Formulas
To check for the errors shown in the screenshot below, click on cell C18 > Click on Formula Tab > Under Formula Auditing group > Click on “Error Checking”.
Excel Formulas
Once you click on Error Checking button, a dialog box will appear. It will describe the reason for the error and will guide you on what to do next. You can either trace the error or ignore the error or go to the formula bar and edit it. You can choose either of these options by clicking on the button shown in the Error Checking Dialog box.
Excel Formulas
These top formulas and functions of Excel will surely help and guide you in every step of your Excel Journey.
|
__label__pos
| 0.940623 |
Friday, April 22, 2011
Transferring a Database to SQL Azure: The Magic Handshake
Update 8/30/2011: I'm leaving this post as-is for reference; however please be aware that the best way to transfer a database to SQL Azure is to use the SQL Azure Migration Wizard
Transferring an existing SQL Server database to SQL Azure can be very easy if you know the right tools and one essential configuration detail, or what I like to call, "the magic handshake." SQL Azure is still near the bleeding edge, and if you get some bad advice you could spend hours on this. Here's a quick rundown on how to do it the easy way.
The Magic Handshake
There are several ways to get your database up to a SQL Azure instance, but the most painless is the SQL Import and Export Wizard. However, if you don't know the magic handshake, your experience goes something like this:
1. You start up the Import and Export Wizard, either from the start menu or from SQL Management Studio. You make sure to use the SQL Server 2008 R2 version, because you know that plain old SQL Server 2008 can't talk to Azure.
2. You set your source data to the database you want to export to Azure.
3. When setting your destination, for some reason you can't log in to your Azure instance. Undaunted, you do some quick Googling (with Bing, of course) and find out that you have to include the full name to your server in your user name, e.g. [email protected]. With that change you actually log in. And you can select the target Azure database! The excitement is building now! With a tremendous sense of anticipation, you click Next.
4. Boom! you're out of luck:
The wizard says it, "cannot get the supported data types from the database connection," and that, "the stored procedure required to complete this operation could not be found on the server." But what it should have said is, "you didn't give me the magic handshake."
So what is the magic handshake? It happens back at step 2. You have to select .Net Framework Data Provider for SqlServer for your destination. This will give you a distinctly non-wizard like settings screen:
Does this look like a wizard to you?
But it's pretty simple: just fill out the Data Source, Initial Catalog, User ID, and Password the same as you would in a connection string. Also, you can use the simple User ID without the @server suffix. Click Next again and you're off to the races!
Azure Compatibility
If your database is simple enough, you may not need to make any changes to your schema. In fact, I would recommend that unless you know you're schema is too clever, go ahead and grind through the Import and Export Wizard steps I've outlined above. If you have any Azure computability problems, you'll get detailed error messages from the wizard.
If you do get errors, then you won't be able to let the wizard create your tables for you. That means you'll have to script the database schema first and correct the errors that were mentioned in the import error dialog. For example, Azure doesn't like tables that don't have any clustered indexes defined. To fix this, just change the primary key on each table from non-clustered to clustered, run the creation scrip in your Azure DB, then run the Import/Export wizard. It will pick up on the existing tables and use them instead of trying to create new tables for the import.
I decided to write a post on this because there doesn't seem to be a lot of good information available on migrating SQL Server databases to Azure. Now that I've been through the process, it seems very simple. That is, once I learned the magic handshake.
|
__label__pos
| 0.675947 |
Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
1. #1
New to the CF scene
Join Date
Jun 2013
Posts
1
Thanks
0
Thanked 0 Times in 0 Posts
Beginner web designer -Dreamweaver and HTML 5
I am starting out in web design and am having a few issues in Dreamweaver I would like the headers to be the google font Sofia and the menu nav list not to have space above it. Sorry, it's probably really simple stuff, but I am a print designer and it's confusing to me that it changes in the preview browser!
I have been working from a Dreamweaver HTML 5 template - hence the instructional text! I hope that you can shine some light on it!
Code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chocol8</title>
<link href='http://fonts.googleapis.com/css?family=Sofia' rel='stylesheet' type='text/css'>
<style type="text/css">
<!--
body {
background: #42413C;
margin: 0;
padding: 0;
color: #000;
background-color: #F8EAC0;
}
/* ~~ Element/tag selectors ~~ */
ul, ol, dl { /* Due to variations between browsers, it's best practices to zero padding and margin on lists. For consistency, you can either specify the amounts you want here, or on the list items (LI, DT, DD) they contain. Remember that what you do here will cascade to the .nav list unless you write a more specific selector. */
padding: 0;
margin: 0;
}
li
{
float:left;
}
h1, h2, h3, h4, h5, h6, {
font-family: 'Sofia', cursive, Palatino Linotype, Book Antiqua, Palatino, serif;
color: #673B15;
margin-top: 0; /* removing the top margin gets around an issue where margins can escape from their containing block. The remaining bottom margin will hold it away from any elements that follow. */
padding-right: 15px;
padding-left: 15px; /* adding the padding to the sides of the elements within the blocks, instead of the block elements themselves, gets rid of any box model math. A nested block with side padding can also be used as an alternate method. */
}
p {
font: 100%/1.4 "Palatino Linotype", "Book Antiqua", Palatino, serif;
margin-top: 0; /* removing the top margin gets around an issue where margins can escape from their containing block. The remaining bottom margin will hold it away from any elements that follow. */
padding-right: 15px;
padding-left: 15px; /* adding the padding to the sides of the elements within the blocks, instead of the block elements themselves, gets rid of any box model math. A nested block with side padding can also be used as an alternate method. */
}
a img { /* this selector removes the default blue border displayed in some browsers around an image when it is surrounded by a link */
border: none;
}
/* ~~ Styling for your site's links must remain in this order - including the group of selectors that create the hover effect. ~~ */
a:link {
color: #F8EAC0;
text-decoration: underline; /* unless you style your links to look extremely unique, it's best to provide underlines for quick visual identification */
}
a:visited {
color: #E8DAAE;
text-decoration: underline;
}
a:hover, a:active, a:focus { /* this group of selectors will give a keyboard navigator the same hover experience as the person using a mouse. */
text-decoration: none;
color: #E8DAAE;
}
/* ~~ This fixed width container surrounds all other blocks ~~ */
.container {
width: 960px;
background: #FFFFFF;
margin: 0 auto; /* the auto value on the sides, coupled with the width, centers the layout */
}
/* ~~ The header is not given a width. It will extend the full width of your layout. ~~ */
header {
background: #A3704A;
}
/* ~~ These are the columns for the layout. ~~
1) Padding is only placed on the top and/or bottom of the block elements. The elements within these blocks have padding on their sides. This saves you from any "box model math". Keep in mind, if you add any side padding or border to the block itself, it will be added to the width you define to create the *total* width. You may also choose to remove the padding on the element in the block element and place a second block element within it with no width and the padding necessary for your design.
2) No margin has been given to the columns since they are all floated. If you must add margin, avoid placing it on the side you're floating toward (for example: a right margin on a block set to float right). Many times, padding can be used instead. For blocks where this rule must be broken, you should add a "display:inline" declaration to the block element's rule to tame a bug where some versions of Internet Explorer double the margin.
3) Since classes can be used multiple times in a document (and an element can also have multiple classes applied), the columns have been assigned class names instead of IDs. For example, two sidebar blocks could be stacked if necessary. These can very easily be changed to IDs if that's your preference, as long as you'll only be using them once per document.
4) If you prefer your nav on the left instead of the right, simply float these columns the opposite direction (all left instead of all right) and they'll render in reverse order. There's no need to move the blocks around in the HTML source.
*/
.sidebar1 {
float: right;
width: 180px;
background: #EADCAE;
padding-bottom: 10px;
}
.content {
padding: 10px 0;
width: 780px;
float: right;
}
/* ~~ This grouped selector gives the lists in the .content area space ~~ */
.content ul, .content ol {
padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */
}
/* ~~ The navigation list styles (can be removed if you choose to use a premade flyout menu like Spry) ~~ */
nav ul {
list-style: none; /* this removes the list marker */
border-top: 0px solid #666; /* this creates the top border for the links - all others are placed using a bottom border on the LI */
margin-bottom: 15px; /* this creates the space between the navigation on the content below */
}
nav ul li {
border-bottom: 0px solid #666; /* this creates the button separation */
}
nav ul a, nav ul a:visited { /* grouping these selectors makes sure that your links retain their button look even after being visited */
padding: 5px 5px 5px 15px;
display: block; /* this gives the link block properties causing it to fill the whole LI containing it. This causes the entire area to react to a mouse click. */
width: 160px; /*this width makes the entire button clickable for IE6. If you don't need to support IE6, it can be removed. Calculate the proper width by subtracting the padding on this link from the width of your sidebar container. */
text-decoration: none;
background: #A3704A;
}
nav ul a:hover, nav ul a:active, nav ul a:focus { /* this changes the background and text color for both mouse and keyboard navigators */
background: #A3704A;
color: #F8EAC0;
}
/* ~~ The footer ~~ */
footer {
padding: 10px 0;
background: #CCC49F;
position: relative;/* this gives IE6 hasLayout to properly clear */
clear: both; /* this clear property forces the .container to understand where the columns end and contain them */
}
/*HTML 5 support - Sets new HTML 5 tags to display:block so browsers know how to render the tags properly. */
header, section, footer, aside, nav, article, figure {
display: block;
}
-->
</style><!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--></head>
<body>
<div class="container">
<header>
<img src="chocol8-banner.png" alt="chocol8-banner" width="960" height="400">
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">Blog</a></li>
</ul>
</nav>
<div class="sidebar1">
<aside>
<p> The above links demonstrate a basic navigational structure using an unordered list styled with CSS. Use this as a starting point and modify the properties to produce your own unique look. If you require flyout menus, create your own using a Spry menu, a menu widget from Adobe's Exchange or a variety of other javascript or CSS solutions.</p>
<p>If you would like the navigation along the top, simply move the ul to the top of the page and recreate the styling.</p>
</aside>
<!-- end .sidebar1 --></div>
<article class="content">
<h1>Instructions</h1>
<section>
<h2>How to use this document</h2>
<p>Be aware that the CSS for these layouts is heavily commented. If you do most of your work in Design view, have a peek at the code to get tips on working with the CSS for the fixed layouts. You can remove these comments before you launch your site. To learn more about the techniques used in these CSS Layouts, read this article at Adobe's Developer Center - <a href="http://www.adobe.com/go/adc_css_layouts">http://www.adobe.com/go/adc_css_layouts</a>.</p>
</section>
<section>
<h2>Clearing Method</h2>
<p>Because all the columns are floated, this layout uses a clear:both declaration in the footer rule. This clearing technique forces the .container to understand where the columns end in order to show any borders or background colors you place on the .container. If your design requires you to remove the footer from the .container, you'll need to use a different clearing method. The most reliable will be to add a <br class="clearfloat" /> or <div class="clearfloat"></div> after your final floated column (but before the .container closes). This will have the same clearing effect. </p>
</section>
<section>
<h2>Logo Replacement</h2>
<p>An image placeholder was used in this layout in the header where you'll likely want to place a logo. It is recommended that you remove the placeholder and replace it with your own linked logo. </p>
<p> Be aware that if you use the Property inspector to navigate to your logo image using the SRC field (instead of removing and replacing the placeholder), you should remove the inline background and display properties. These inline styles are only used to make the logo placeholder show up in browsers for demonstration purposes. </p>
<p>To remove the inline styles, make sure your CSS Styles panel is set to Current. Select the image, and in the Properties pane of the CSS Styles panel, right click and delete the display and background properties. (Of course, you can always go directly into the code and delete the inline styles from the image or placeholder there.)</p>
</section>
<section>
<h2>Backgrounds</h2>
<p>By nature, the background color on any block element will only show for the length of the content. This means if you're using a background color or border to create the look of a side column, it won't extend all the way to the footer but will stop when the content ends. If the .content block will always contain more content, you can place a border on the .content block to divide it from the column.</p>
</section>
<!-- end .content --></article>
<footer>
<p>This footer contains the declaration position:relative; to give Internet Explorer 6 hasLayout for the footer and cause it to clear correctly. If you're not required to support IE6, you may remove it.</p>
<address>
Address Content
</address>
</footer>
<!-- end .container --></div>
</body>
</html>
Thanks!
Last edited by VIPStephan; 06-28-2013 at 02:35 PM. Reason: fixed code BB tags
2. #2
Regular Coder
Join Date
Aug 2012
Posts
255
Thanks
0
Thanked 43 Times in 43 Posts
hi sprite2013,
you need to remove the comma here in order for the font to take place:
Code:
h1, h2, h3, h4, h5, h6, /*this comma is preventing your font taking place*/ {}
So should be:
Code:
h1, h2, h3, h4, h5, h6 {
font-family: 'Sofia', cursive, Palatino Linotype, Book Antiqua, Palatino, serif;
color: #673B15;
margin-top: 0; /* removing the top margin gets around an issue where margins can escape from their containing block. The remaining bottom margin will hold it away from any elements that follow. */
padding-right: 15px;
padding-left: 15px; /* adding the padding to the sides of the elements within the blocks, instead of the block elements themselves, gets rid of any box model math. A nested block with side padding can also be used as an alternate method. */
}
Hope this helps
1 Corinthians 15:3-4 / Ephesians 2:8-9 - What or Who are you living for? Jesus The Christ is returning very soon. All are welcomed by God!!!
Tags for this Thread
Posting Permissions
• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
|
__label__pos
| 0.699236 |
收藏
回答
微信,ios,升级到当前最新版本7.0.5后下载问题
问题模块 框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
API和组件 小程序 Bug wx.downloadFile 微信iOS客户端 7.0.5 2.8.2
亲爱的开发团队,你们是不是又把底层下载的库更新了:(,之前都好好的
问题1:
ios微信升级到最新版本后
下载图片类型的文件,并且heaader头设置如下的这种
Content-Type:binary/octet-stream
直接会报错,自动退出下载流程,请务必修复,别说让我们自己把content-type:改成图片类型来解决,数据量大,不太好调整了。而且,浏览器都能正常下载这种类型文件,而且之前版本也能正常下载这种类型文件!
{errMsg: "downloadFile:fail file data is empty"}
问题2:
android和ios最新版本,下载这种类型的图片,接着再操作保存到相册的api,同时都会提示文件类型错误的提示!
现在调整方法了,直接指定文件名来保存到用户空间目录,可以暂时绕过这个问题,主要代码,已经提前申请了权限的。 用的这种图片,带签名的,直接或获取不到图片后缀,最终保存到本地的是 xxxx.unkown 这种名字的图片:
https://sioeye-disney-aeon-test.s3.cn-north-1.amazonaws.com.cn/6224886b1529499ea7b1d752545f3d6d/cc0b7ed46b5c4896bece27c5f4e36ba6/images/photo/50f9324f435840b78a082a71264aacd5.jpg?x-amz-acl=public-read&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190905T031635Z&X-Amz-SignedHeaders=host&X-Amz-Expires=1799&X-Amz-Credential=AKIAO7QXSMTQKKQGQWRQ%2F20190905%2Fcn-north-1%2Fs3%2Faws4_request&X-Amz-Signature=47c2dff564b0842812964bc6033702a285b9e15fd2cccf737f7ae883420bb25f
这个问题的临时解决方案:
var self = this
var fileSavePath = wx.env.USER_DATA_PATH + '/' + md5(url) + '.jpg'
// 保存到本地的方式,解决后缀问题
const task1 = wx.downloadFile({
url: url,
filePath: fileSavePath,
success: res => {
console.log('res.tempFilePath', res)
if (res.filePath) {
// if (res.tempFilePath) {
wx.saveImageToPhotosAlbum({
filePath: res.filePath,
success: resp => {
util.toastInfo('保存相册成功')
},
fail: err => {
util.toastInfo('保存相册失败')
console.log('下载失败:', err)
}
})
} else {
util.toastInfo('保存相册失败')
console.log('下载失败:', res)
}
},
fail: res => {
util.toastInfo('保存相册失败')
console.log('主动取消下载:', res)
}
})
最后一次编辑于 09-05 (未经腾讯允许,不得转载)
回答关注问题邀请回答
收藏
2 个回答
问题标签
|
__label__pos
| 0.519424 |
by Dinesh Thakur Category: C Programming (Pratical)
Computer instructions have the provision of directly adding or subtracting unity to a variable. So, if we use this facility, the operation is quicker than the operation for the statement A = A+ 1; . Therefore, for increasing and decreasing the values of integral objects by unity, it is better to make use of increment operator (++) and decrement operator (- -) , respectively. Another provision with these operators is that the operators may be placed before or after the identifier of the variable. When the operators + + and -- are placed before the variable name, these are called pre-increment and pre-decrement operators, respectively. For instance,
Int A= 10, B = 5;
++A* ++B; // This is equivalent to(10+ 1) * (5+ 1) and A= 11,B=6.
When the operators are placed after the names they are called post-increment and post-decrement operators. In this case, the increment is carried out after the current use. For example,
A++* B++; // This is equivalent to 10 x 5 and A = 11 and B = 6.
In case of pre-increment/pre-decrement operators the present value of the variable is first increased/ decreased by unity and then this changed value is used in the application. On the other hand, in case of post-increment/post-decrement operators, the present value of the variable is used in the application and then its value is incremented/ decremented. Table provides a list of all possible increment and decrement operators along with their applications.
Illustrates application of increment and decrement operators.
#include <stdio.h>
void main()
{
int x = 3, y = 5,z = 10,p= 8, A,B,C,D;
clrscr();
A= ++x*++y; // ++has higher precedence level than *
printf("A = %d\t x = %d\t y = %d\n", A, x, y);
B = y--* y-- ;
printf("B = %d \t y = %d \n", B, y);
C = ++z*--z ; //++ and -- have higher precedence level than*
printf("C = %d\t z = %d\n", C, z );
D = p-- * --p; //--p has higher precedence level than *
printf("D= %d\t p= %d\n", D, p);
}
Write a Programe For Increment and decrement Operator
For the first line of the output both x and y are incremented before the multiplication, so, in the result, A is equal to 24, x = 4, y = 6. For the next line of the output, the value y is now 6, so, B = 36; decrement (twice) is done after the multiplication. For the third line of output, Z is first incremented and then decremented before the multiplication because++ and -- have higher precedence level than *. So, the result is C = 100 and Z = 10. For the fourth line of the output, the decrement operation --p is carried out before the multiplication. The value of p is again decremented by 1 after the multiplication because of p--. So, D = 49 and p = 6.
About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.
Search Content
|
__label__pos
| 0.995895 |
Results 1 to 7 of 7
Like Tree3Thanks
• 1 Post By SlipEternal
• 1 Post By SlipEternal
• 1 Post By SlipEternal
Thread: Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c,s a
1. #1
Junior Member
Joined
Mar 2014
From
uk
Posts
53
Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c,s a
The three non-linear equations are given by
\begin{equation}
c[(6.7 * 10^8) + (1.2 * 10^8)s+(1-q)(2.6*10^8)]-0.00114532=0
\end{equation}
\begin{equation}
s[2.001 *c + 835(1-q)]-2.001*c =0
\end{equation}
\begin{equation}
q[2.73 + (5.98*10^{10})c]-(5.98 *10^{10})c =0
\end{equation}
Using the Newton-Raphson Method solve these equations in terms of $c$,$s$ and $q$.
=> It is really difficult question for me because i don't know very much about the Newton-Raphson Method and also these non-linear equations contain 3 variables.
I have try by applying the newton-Raphson method to each equations:-
\begin{equation}
f(c,s,q)=0= c[(6.7 * 10^8) + (1.2 * 10^8)s+(1-q)(2.6*10^8)]-0.00114532
\end{equation}
\begin{equation}
g(c,s,q)=0= s[2.001 *c + 835(1-q)]-2.001*c
\end{equation}
\begin{equation}
h(c,s,q)=0= q[2.73 + (5.98*10^{10})c]-(5.98 *10^{10})c
\end{equation}
now i guess i need to work out $f'(c,s,q), g'(c,s,q), h'(c,s,q)$ but i dont know how?
and after working out $f'(c,s,q), g'(c,s,q), h'(c,s,q)$ . After that i think i need to use newton-raphson iteration:
$c_{n+1}= c_n - \frac{f(c,s,q)}{f'(c,s,q)}$
but the $f(c,s,q)$ and $f'(c,s,q)$ contains the $s$ and $q$.
Similarly, for
$s_{n+1}= s_n - \frac{g(c,s,q)}{g'(c,s,q)}$
will have $g(c,s,q)$ and $g'(c,s,q)$ containing the $c$ and $q$.
$q_{n+1}= q_n - \frac{h(c,s,q)}{h'(c,s,q)}$
will have $h(c,s,q)$ and $h'(c,s,q)$ containing the $c$.
so am i not sure what to do please help me. to find the values of $c,s,q$.
Follow Math Help Forum on Facebook and Google+
2. #2
MHF Contributor
Joined
Nov 2010
Posts
1,974
Thanks
799
Re: Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c
You need to use the multivariate Newton-Raphson method, which involves the Jacobian.
J(\vec{x}) = \begin{pmatrix}\tfrac{\partial f}{\partial c} & \tfrac{\partial f}{\partial s} & \tfrac{\partial f}{\partial q} \\ \tfrac{\partial g}{\partial c} & \tfrac{\partial g}{\partial s} & \tfrac{\partial g}{\partial q} \\ \tfrac{\partial h}{\partial c} & \tfrac{\partial h}{\partial s} & \tfrac{\partial h}{\partial q}\end{pmatrix}\begin{pmatrix}c \\ s \\ q\end{pmatrix}
So, let's find estimates for c,s,q. g(0,0,0) = h(0,0,0) = 0 and f(0,0,0) = -0.00114532, so that is a good estimate to start with.
Then, \vec{x_1} = \begin{pmatrix}c_1 \\ s_1 \\ q_1\end{pmatrix} = \begin{pmatrix}0 \\ 0 \\ 0\end{pmatrix}
J(\vec{x_1}) = \begin{pmatrix}6.7\cdot 10^8 + 1.2\cdot 10^8 s_1 + 2.6\cdot (1-q_1)\cdot 10^8 & 1.2\cdot 10^8 c_1 & -2.6\cdot 10^8 c_1 \\ 2.001(s_1-1) & 2.001c_1 + 835(1-q_1) & -835s_1 \\ 5.98\cdot 10^{10}(q_1-1) & 0 & 2.73+5.95\cdot 10^{10}c_1\end{pmatrix}
Plugging in \vec{x_1} = \begin{pmatrix}0 \\ 0 \\ 0\end{pmatrix} gives:
J(\vec{x_1}) = \begin{pmatrix}9.3\cdot 10^8 & 0 & 0 \\ -2.001 & 835 & 0 \\ -5.98\cdot 10^{10} & 0 & 2.73\end{pmatrix}
Now, to apply the Newton-Raphson method, we want:
\vec{x_2} = \vec{x_1} - J^{-1}(\vec{x_1})\begin{pmatrix}f(c_1,s_1,q_1) \\ g(c_1,s_1,q_1) \\ h(c_1,s_1,q_1)\end{pmatrix}
So, you need to take the inverse of the matrix.
J^{-1}(\vec{x_1}) = \begin{pmatrix}1.07527\cdot 10^{-9} & 0 & 0 \\ 2.57678\cdot 10^{-12} & 0.0011976 & -6.31098\cdot 10^{-30} \\ 23.5535 & 0 & 0.3663\end{pmatrix}
Then, you have:
\vec{x_2} = \begin{pmatrix}0 \\ 0 \\ 0\end{pmatrix} - J^{-1}(\vec{x_1})\begin{pmatrix}f(0,0,0) \\ g(0,0,0) \\ h(0,0,0)\end{pmatrix} = \begin{pmatrix}1.23153\cdot 10^{-12} \\ 2.95124\cdot 10^{-15} \\ 0.0269763\end{pmatrix}
Next,
\begin{align*}J(\vec{x_2}) & = \begin{pmatrix}6.7\cdot 10^8 + 1.2\cdot 10^8 s_2 + 2.6\cdot (1-q_2)\cdot 10^8 & 1.2\cdot 10^8 c_2 & -2.6\cdot 10^8 c_2 \\ 2.001(s_2-1) & 2.001c_2 + 835(1-q_2) & -835s_2 \\ 5.98\cdot 10^{10}(q_2-1) & 0 & 2.73+5.95\cdot 10^{10}c_2\end{pmatrix} \\ & = \begin{pmatrix}9.229861620000003541488 \cdot 10^8 & 0.0001477836 & -0.0003201978 \\ -2.00099999999999409456876 & 812.47478950000246429153 & -1.02832755 \cdot 10^-9 \\ -58186817260 & 0 & 2.803276035\end{pmatrix}\end{align*}
Continuing:
\begin{align*}\vec{x_3} & = \vec{x_2} - J^{-1}(\vec{x_2}) \begin{pmatrix}f(\vec{x_2}) \\ g(\vec{x_2}) \\ h(\vec{x_2})\end{pmatrix} \\ & = \begin{pmatrix}1.23153\cdot 10^{-12} \\ 2.95124\cdot 10^{-15} \\ 0.0269763\end{pmatrix} - \begin{pmatrix}1.091298102077596\cdot 10^{-9} & -1.9849965104448836\cdot 10^{-16} & 1.2465103224457146\cdot 10^{-13} \\ 3.1357436198406283\cdot 10^{-11} & 0.00123081 & 4.550796088382769\cdot 10^{-13} \\ 22.6518 & -4.120201784373836\cdot 10^{-6} & 0.359313\end{pmatrix} \begin{pmatrix}-8.634851912139563855128336 \cdot 10^{-6} \\ -6.64834322360127272842650028 \cdot 10^{-14} \\ 0.0019864879397922\end{pmatrix} \\ & = \begin{pmatrix}1.241200815275675509811379607179147 675196376023\cdot 10^{-12} \\ 2.399825136545420764152907657559927633735088 \cdot 10^{-15} \\ 0.026458123997432847940008439911288151623283806417 6345\end{pmatrix}\end{align*}
Thanks from grandy
Follow Math Help Forum on Facebook and Google+
3. #3
Junior Member
Joined
Mar 2014
From
uk
Posts
53
Re: Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c
Thank you very much sir. did you use any mathematical software like mat lab, Fortran, maple. or did you solve it by hand?
Follow Math Help Forum on Facebook and Google+
4. #4
MHF Contributor
Joined
Nov 2010
Posts
1,974
Thanks
799
Re: Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c
I did a search for multivariate Newton-Raphson method. That showed me how the method works. I calculated the Jacobian by hand, and used Wolframalpha to do the calculations of the matrix operations (I did not check any of my work, so I may have made errors).
Thanks from grandy
Follow Math Help Forum on Facebook and Google+
5. #5
Junior Member
Joined
Mar 2014
From
uk
Posts
53
Re: Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c
Sir, i have a one questions for you. the values of vector x2 and x3 seems very much similar. that means can i take x2 vector values as my final answer in terms of c,s and q so that i don't have to do extra steps to calculate the values of vector x3?
Follow Math Help Forum on Facebook and Google+
6. #6
MHF Contributor
Joined
Nov 2010
Posts
1,974
Thanks
799
Re: Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c
Quote Originally Posted by grandy View Post
Sir, i have a one questions for you. the values of vector x2 and x3 seems very much similar. that means can i take x2 vector values as my final answer in terms of c,s and q so that i don't have to do extra steps to calculate the values of vector x3?
I am not your instructor, so I cannot answer that. I would think your instructor would want at least two iterations. The value in the third term is changing greatly from x_2 to x_3 (relative to the other two values).
Thanks from grandy
Follow Math Help Forum on Facebook and Google+
7. #7
Junior Member
Joined
Mar 2014
From
uk
Posts
53
Re: Solve non-linear equations of 3 variables using Newton-Raphson Method iterms of c
I ask with my lecturer and he said i can use the vector x3 as my final values of c,s and q. thank you sir.
Follow Math Help Forum on Facebook and Google+
Similar Math Help Forum Discussions
1. Regarding newton raphson method
Posted in the Pre-Calculus Forum
Replies: 1
Last Post: July 8th 2012, 04:58 AM
2. Newton raphson method
Posted in the Calculus Forum
Replies: 5
Last Post: April 4th 2011, 10:44 AM
3. Newton-Raphson method
Posted in the Calculus Forum
Replies: 3
Last Post: December 30th 2009, 06:13 AM
4. Newton Raphson Method?????? HELP!
Posted in the Calculus Forum
Replies: 3
Last Post: March 5th 2007, 08:37 AM
5. Help- Newton - Raphson Method
Posted in the Calculus Forum
Replies: 3
Last Post: July 12th 2006, 06:49 AM
Search Tags
/mathhelpforum @mathhelpforum
|
__label__pos
| 0.98843 |
@gferreira said in Grid: w = (width() - gutter * (cols + 1)) / cols h = (height() - gutter * (rows + 1)) / rows Thank you very much, it worked way much better, I also tried to add a margin feature that worked well so now I can design over the grid size(1000, 1000) cols = 3 rows = 3 gutter = 12 #Margin mTop = 10 mBottom = 20 mLeft = 10 mRight = 10 w = (width() - gutter * (cols + 1)) / cols - ((mRight + mLeft) / cols) h = (height() - gutter * (rows + 1)) / rows - ((mTop + mBottom) / rows) fill(None) strokeWidth(1) stroke(0, 1, 1) for col in range(cols): for row in range(rows): x = gutter + col * (w + gutter) y = gutter + row * (h + gutter) rect(x + mLeft, y + mBottom, w, h)
|
__label__pos
| 0.99994 |
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up
Join the Stack Overflow community to:
1. Ask programming questions
2. Answer and help your peers
3. Get recognized for your expertise
I've created a control that extends the BoundField control to do some special processing on the data that's passed into it.
I now have a grid that has AutoGenerateColumns="true", by which I'd like to intercept the HeaderText, see if it's a particular value and then swap in the "SpecialBoundField" instead. I've tried using the OnDataBinding event to loop through the columns, but at this point there are no columns in the grid. I think that RowDataBound and DataBound are too late in the game so not sure what to do.
My next thought was to override the grid control itself to add in a "AutoGeneratingColumn" event in
protected virtual AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)
Can anyone help or point me in a better direction? Thanks!
share|improve this question
up vote 3 down vote accepted
If you have both fields coming back in the dataset, I would suggest setting the column visibilities instead of trying to dynamically add or change the datafields. Invisible columns don't render any HTML, so it would just be a matter of looking at the header row when it gets bound, checking the field you're interested in, and setting the column visibility.
void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (e.Row.Cells[1].Text = "BadText")
{
myGridView.Columns[1].Visible = false;
myGridView.Columns[5].Visible = true;
}
}
}
share|improve this answer
This may work, but I do need to change the actual column type from the simple "BoundField" to "SpecialBoundField" as well. I'll give this a go and report back. – rball Sep 14 '09 at 22:38
Got me to where I needed to go, my solution is posted as well... – rball Sep 21 '09 at 18:07
What I ended up with:
public class SpecialGridView : GridView
{
protected override void OnRowDataBound(GridViewRowEventArgs e)
{
ModifyData(e);
base.OnRowDataBound(e);
}
IList<string> _columnNames = new List<string>();
protected void ModifyData(GridViewRowEventArgs e)
{
LoadColumnNames(e);
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
string currentColumnName = _columnNames[i];
if (IsSpecialColumn(currentColumnName))
{
string text = e.Row.Cells[0].Text;
bool isSpecialData = text.ToUpper() == "Y";
if (isSpecialData)
{
e.Row.Cells[i].CssClass += " specialData";
}
}
}
}
}
private void LoadColumnNames(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
_columnNames.Add(cell.Text);
}
}
}
private bool IsSpecialColumn(string currentColumnName)
{
foreach (string columnName in SpecialColumnNames)
{
if (currentColumnName.ToUpper() == columnName.ToUpper())
{
return true;
}
}
return false;
}
private IList<string> _specialColumnNames = new List<string>();
public IList<string> SpecialColumnNames
{
get { return _specialColumnNames; }
set { _specialColumnNames = value; }
}
}
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.832757 |
answersLogoWhite
0
Best Answer
198 written in fraction = 198/1
User Avatar
Wiki User
2012-12-06 07:36:27
This answer is:
🙏
0
🤨
0
😮
0
User Avatar
Study guides
➡️
See all cards
4.71
14 Reviews
Add your answer:
Earn +20 pts
Q: What is 198 written as a fraction?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions
What would be the fraction of 198 percent?
198% = 198/100 or 99/50 in fraction
What is a fraction of 198?
198 is an integer and so there is not really a sensible way of writing it as a fraction or mixed number.
What is 7.92 as a fraction?
198/25
How do you write 0.198 as a fraction?
198/1000
What is 1.0353535... In fraction forn?
1.0353535... is a fraction. It is a fraction in decimal form rather than in the form of a ratio. However, that does not stop it being a fraction. Its equivalent, in rational form, is 205/198.
33 out of 198 students surveyed said that they preferred hockey to all other sports What fraction of students surveyed is this?
Quite obviously, the fraction is 33 out of 198 or 33/198. this can be simplified to 1/6.
How is 0.025 with the 25 part repeating written as a fraction in simplest form Question 1 options 5198 5396 10198 10396?
How is 0.025 with the 25 part repeating written as a fraction in simplest form? Question 1 options: 5/198 5/396 10/198 10/396
How do you write 39.6 as a fraction?
39.6 = 198/5
What does the fraction 1.98 looks like?
198/100
Can the fraction 198 over 165 be simplified?
Yes, it can.
How do you write 19.8 as a fraction?
19.8 written as a n improper fraction is 198/10, or 99/5 in simplest form. As a mixed number, 19.8 is 19 4/5.
What is 22.2222 as a fraction?
0.2222 = 2/9 22 x 9 = 198 198 + 2 = 200 Answer: 200/9
How do you simplify the fraction 98 over 396?
98/396 = 49/198.
What is 6.025 as a fraction in simplest form?
6.025 = = 241/40 or 61/40
What fraction of a sample of gold-198 remains radioactive after 2.69 days?
1/2 or 0.5
What is the fraction of 0.0656565?
0.0656565 is a fraction. It is a fraction in decimal form rather than in the form of a ratio. However, that does not stop it being a fraction. Its equivalent, in rational form, is 656565/10000000 which can be simplified if required.
How is 0.05498 written as a fraction?
0.05498 written as a fraction is 2749/5000
What is 2.625 written as a fraction?
2.625 written as a fraction is 21/8.
What is 0.0005 written as a fraction?
0.0005 written as a fraction is 1/2000.
How is 0.320 written as a fraction?
8/25 is 0.320 written as a fraction.
What is 0.0925925926 written as a fraction?
0.0925925926 written as a fraction = 92592593/1000000000
What is 3.085714286 written as a fraction?
3.085714286 written as a fraction = 3085714286/1000000000
.28 written as a fraction?
7/25 is .28 written as a fraction.
What is 0.315 written as a fraction?
0.315 written as a fraction = 63/200
What is 123.45679 written as a fraction?
123.45679 written as a fraction is 12345679/100000.
|
__label__pos
| 1 |
How to write XML documents using Streaming API for XML (StAX)
Nowadays XML became a de-facto standard for storing and exchanging documents over Internet. And because it was designed to be extensible, it can be easily adapted to almost every need. In this post I would like to describe how to create and write your own XML documents using Streaming API for XML (StAX).
Need for XML writer
Of course it is possible to write XML documents using a combination of print, println or printf methods but the amount of work and the number of details to take care of would be quite large. For example when writing documents manually it is very easy to forget about escaping special characters like < or " or prepending tag with namespace prefix. Therefore, it is better to leave these cumbersome tasks to the XML writer and concentrate on the general document layout.
XMLStreamWriter
Streaming API for XML introduced in Java 6 provides quite handy interface XMLStreamWriter which can be used for writing XML files. The good thing about this API is that it does not require building any specific object structure like in DOM and does not require doing any intermediate tasks.
Additionally, XMLStreamWriter supports namespaces by default which is very useful in more advanced situations.
General XMLStreamWriter workflow
To start writing document we have to create instance of XMLStreamWriter using XMLOutputFactory:
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(outputStream);
Once we have the instance of XMLStreamWriter we must write header of the XML document:
writer.writeStartDocument("utf-8", "1.0");
Then we can proceed to writing elements:
writer.writeStartElement("books");
Once we have element started we can add attributes to it, write some character data or CDATA section:
writer.writeAttribute("id", "10");
writer.writeCharacters("text data");
writer.writeCData("more text data");
We can also start some other nested elements and so on.
To close opened elements we should call:
writer.writeEndElement();
It is also possible to write empty elements:
writer.writeEmptyElement("used & new");
or write comments:
writer.writeComment("Some comment");
When we are done with writing, we should finish the document and close the writer:
writer.writeEndDocument();
writer.close();
which will automatically close all opened elements and will release resources used by the writer.
Closing the writer will not close the underlying file so it has to be done manually.
Issues with XMLStreamWriter
XMLStreamWriter is not perfect so it is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.
Additionally, XMLStreamWriter does not indent its output so it may be a bit hard to read using plain text editor. Therefore, for reading I suggest to open it in a web browser most of which have user-friendly interface to view structure of XML documents.
Writing XML document without namespaces
Below I would like to show a simple example how to write your own data structure into XML document. In our case it will be a list of books and a single book will be represented like this:
package com.example.staxwrite;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Book {
private List<String> authors;
private String title;
private Category category;
private String language;
private int year;
public Book(List<String> authors, String title, Category category, String language, int year) {
this.authors = new ArrayList<>(authors);
this.title = title;
this.category = category;
this.language = language;
this.year = year;
}
public Book(String author, String title, Category category, String language, int year) {
this (Collections.singletonList(author), title, category, language, year);
}
public List<String> getAuthors() {
return Collections.unmodifiableList(authors);
}
public void addAuthor(String author) {
authors.add(author);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
The code which handles writing XML document is following:
package com.example.staxwrite;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class NoNSWriter {
public void writeToXml(Path path, List<Book> books) throws IOException, XMLStreamException {
try (OutputStream os = Files.newOutputStream(path)) {
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = null;
try {
writer = outputFactory.createXMLStreamWriter(os, "utf-8");
writeBooksElem(writer, books);
} finally {
if (writer != null)
writer.close();
}
}
}
private void writeBooksElem(XMLStreamWriter writer, List<Book> books) throws XMLStreamException {
writer.writeStartDocument("utf-8", "1.0");
writer.writeComment("Describes list of books");
writer.writeStartElement("books");
for (Book book : books)
writeBookElem(writer, book);
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeBookElem(XMLStreamWriter writer, Book book) throws XMLStreamException {
writer.writeStartElement("book");
writer.writeAttribute("language", book.getLanguage());
writeAuthorsElem(writer, book.getAuthors());
writer.writeStartElement("title");
writer.writeCData(book.getTitle());
writer.writeEndElement();
writer.writeStartElement("category");
writer.writeCharacters(book.getCategory().name());
writer.writeEndElement();
writer.writeStartElement("year");
writer.writeCharacters(Integer.toString(book.getYear()));
writer.writeEndElement();
writer.writeEndElement();
}
private void writeAuthorsElem(XMLStreamWriter writer, List<String> authors) throws XMLStreamException {
writer.writeStartElement("authors");
for (String author : authors) {
writer.writeStartElement("author");
writer.writeCharacters(author);
writer.writeEndElement();
}
writer.writeEndElement();
}
}
In writeToXml method we create the output stream and the writer and ensure that they will be closed properly. Then we call writeBooksElem which will start the document, write comment, emit the list of books and will finish the document.
Most properties of a book are written as separate subelements except language which is written as an attribute. The resultant XML document should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<!--Describes list of books-->
<books>
<book language="English">
<authors>
<author>Mark Twain</author>
</authors>
<title><![CDATA[The Adventures of Tom Sawyer]]></title>
<category>FICTION</category>
<year>1876</year>
</book>
<book language="English">
<authors>
<author>Niklaus Wirth</author>
</authors>
<title><![CDATA[The Programming Language Pascal]]></title>
<category>PASCAL</category>
<year>1971</year>
</book>
<book language="English">
<authors>
<author>O.-J. Dahl</author>
<author>E. W. Dijkstra</author>
<author>C. A. R. Hoare</author>
</authors>
<title><![CDATA[The Programming Language Pascal]]></title>
<category>PROGRAMMING</category>
<year>1972</year>
</book>
</books>
Writing XML document with namespaces
The XML document created using code above does not contain any references to namespaces. While it may be convenient in simple cases, more advanced XML documents will refer to one or more XML namespaces.
To create document with namespace support we have to first define the prefix of the namespace we want to use:
writer.setPrefix("b", "http://example.com/books");
and emit the element with URI of this namespace:
writer.writeStartElement("http://example.com/books", "books");
writer.writeNamespace("b", "http://example.com/books");
Once we do so, we can write elements and attributes from this namespace by adding the namepace URI as the first argument of writeStartElement and writeAttribute methods. Here is the full code:
package com.example.staxwrite;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class NSWriter {
private static final String NS = "http://example.com/books";
public void writeToXml(Path path, List<Book> books) throws IOException, XMLStreamException {
try (OutputStream os = Files.newOutputStream(path)) {
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = null;
try {
writer = outputFactory.createXMLStreamWriter(os, "utf-8");
writeBooksElem(writer, books);
} finally {
if (writer != null)
writer.close();
}
}
}
private void writeBooksElem(XMLStreamWriter writer, List<Book> books) throws XMLStreamException {
writer.writeStartDocument("utf-8", "1.0");
writer.writeComment("Describes list of books");
writer.setPrefix("b", NS);
writer.writeStartElement(NS, "books");
writer.writeNamespace("b", NS);
for (Book book : books)
writeBookElem(writer, book);
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeBookElem(XMLStreamWriter writer, Book book) throws XMLStreamException {
writer.writeStartElement(NS, "book");
writer.writeAttribute(NS, "language", book.getLanguage());
writeAuthorsElem(writer, book.getAuthors());
writer.writeStartElement(NS, "title");
writer.writeCData(book.getTitle());
writer.writeEndElement();
writer.writeStartElement(NS, "category");
writer.writeCharacters(book.getCategory().name());
writer.writeEndElement();
writer.writeStartElement(NS, "year");
writer.writeCharacters(Integer.toString(book.getYear()));
writer.writeEndElement();
writer.writeEndElement();
}
private void writeAuthorsElem(XMLStreamWriter writer, List<String> authors) throws XMLStreamException {
writer.writeStartElement(NS, "authors");
for (String author : authors) {
writer.writeStartElement(NS, "author");
writer.writeCharacters(author);
writer.writeEndElement();
}
writer.writeEndElement();
}
}
and the created XML document:
<?xml version="1.0" encoding="UTF-8"?>
<!--Describes list of books-->
<b:books xmlns:b="http://example.com/books">
<b:book b:language="English">
<b:authors>
<b:author>Mark Twain</b:author>
</b:authors>
<b:title><![CDATA[The Adventures of Tom Sawyer]]></b:title>
<b:category>FICTION</b:category>
<b:year>1876</b:year>
</b:book>
<b:book b:language="English">
<b:authors>
<b:author>Niklaus Wirth</b:author>
</b:authors>
<b:title><![CDATA[The Programming Language Pascal]]></b:title>
<b:category>PASCAL</b:category>
<b:year>1971</b:year>
</b:book>
<b:book b:language="English">
<b:authors>
<b:author>O.-J. Dahl</b:author>
<b:author>E. W. Dijkstra</b:author>
<b:author>C. A. R. Hoare</b:author>
</b:authors>
<b:title><![CDATA[The Programming Language Pascal]]></b:title>
<b:category>PROGRAMMING</b:category>
<b:year>1972</b:year>
</b:book>
</b:books>
Write XML document with default namespace
XML also supports the idea of default namespace which increases readability and limits the typing. Using it is very similar to using namespace with explicit prefix but we have to use setDefaultNamespace and writeDefaultNamespace instead of setPrefix and writeNamespace:
package com.example.staxwrite;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class DefaultNSWriter {
private static final String NS = "http://example.com/books";
public void writeToXml(Path path, List<Book> books) throws IOException, XMLStreamException {
try (OutputStream os = Files.newOutputStream(path)) {
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = null;
try {
writer = outputFactory.createXMLStreamWriter(os, "utf-8");
writeBooksElem(writer, books);
} finally {
if (writer != null)
writer.close();
}
}
}
private void writeBooksElem(XMLStreamWriter writer, List<Book> books) throws XMLStreamException {
writer.writeStartDocument("utf-8", "1.0");
writer.writeComment("Describes list of books");
writer.setDefaultNamespace(NS);
writer.writeStartElement(NS, "books");
writer.writeDefaultNamespace(NS);
for (Book book : books)
writeBookElem(writer, book);
writer.writeEndElement();
writer.writeEndDocument();
}
private void writeBookElem(XMLStreamWriter writer, Book book) throws XMLStreamException {
writer.writeStartElement(NS, "book");
writer.writeAttribute(NS, "language", book.getLanguage());
writeAuthorsElem(writer, book.getAuthors());
writer.writeStartElement(NS, "title");
writer.writeCData(book.getTitle());
writer.writeEndElement();
writer.writeStartElement(NS, "category");
writer.writeCharacters(book.getCategory().name());
writer.writeEndElement();
writer.writeStartElement(NS, "year");
writer.writeCharacters(Integer.toString(book.getYear()));
writer.writeEndElement();
writer.writeEndElement();
}
private void writeAuthorsElem(XMLStreamWriter writer, List<String> authors) throws XMLStreamException {
writer.writeStartElement(NS, "authors");
for (String author : authors) {
writer.writeStartElement(NS, "author");
writer.writeCharacters(author);
writer.writeEndElement();
}
writer.writeEndElement();
}
}
The created XML document refers to the namespace but there is no prefix used:
<?xml version="1.0" encoding="UTF-8"?>
<!--Describes list of books-->
<books xmlns="http://example.com/books">
<book language="English">
<authors>
<author>Mark Twain</author>
</authors>
<title><![CDATA[The Adventures of Tom Sawyer]]></title>
<category>FICTION</category>
<year>1876</year>
</book>
<book language="English">
<authors>
<author>Niklaus Wirth</author>
</authors>
<title><![CDATA[The Programming Language Pascal]]></title>
<category>PASCAL</category>
<year>1971</year>
</book>
<book language="English">
<authors>
<author>O.-J. Dahl</author>
<author>E. W. Dijkstra</author>
<author>C. A. R. Hoare</author>
</authors>
<title><![CDATA[The Programming Language Pascal]]></title>
<category>PROGRAMMING</category>
<year>1972</year>
</book>
</books>
Conclusion
Streaming API for XML provides very convenient, fast and memory efficient way to write XML documents without worrying about details and escaping of special characters. It is a great alternative to DOM especially when you don’t need to keep and manage DOM tree in memory for any reason.
The source code for example is available at GitHub.
About Robert P.
Husband, software developer, Linux and open-source fan, blogger.
This entry was posted in Java, XML and tagged , , . Bookmark the permalink.
One Response to How to write XML documents using Streaming API for XML (StAX)
1. Pingback: Parse XML document using Streaming API for XML (StAX) | softwarecave
Leave a Reply
Fill in your details below or click an icon to log in:
WordPress.com Logo
You are commenting using your WordPress.com account. Log Out / Change )
Twitter picture
You are commenting using your Twitter account. Log Out / Change )
Facebook photo
You are commenting using your Facebook account. Log Out / Change )
Google+ photo
You are commenting using your Google+ account. Log Out / Change )
Connecting to %s
|
__label__pos
| 0.982457 |
Skip to content
Logo Theodo
How to Setup a Software VPN between your AWS Platform and a Third-Party Corporate Network
Brian Azizi11 min read
Some third-parties only allow you to call their APIs if you are inside their network. This can make life difficult if your application is hosted on AWS.
The solution is to create a site-to-site VPN connection between your AWS Virtual Private Cloud (VPC) and the third-party’s corporate network.
There are two common ways to do that:
1. The AWS way, using AWS Managed VPNs
2. The DIY way, using a software VPN
I will touch on AWS Managed VPNs and then go through the steps of manually setting up a software VPN.
A Quick Word on AWS Managed VPNs
AWS has a Managed VPN service in which you create a Virtual Private Gateway in your AWS VPC, set up a Customer Gateway (representing the third-party) and create a VPN connection between the two.
aws-vpn
This is by far the easiest and most robust solution. However, it has one major limitiations that might make it unsuitable for your needs:
With AWS Managed VPNs, the VPN tunnel can only be initiated from the Customer Gateway, i.e. the third-party’s side!
As a result of this, there are only two situations in which you can use the AWS Managed VPN service:
If requests are initiated from your AWS servers to the third-party, and the third-party is unable or unwilling to take responsibility for keeping the tunnel open, then AWS-managed VPNs will not work and you will need to use an alternative solution.
How to set up a software VPN on AWS using Openswan
The rest of this article will walk you through setting up a site-to-site VPN connection using the Openswan software VPN.
At a high level, there are three steps:
1. Create an EC2 instance in AWS that will run the OpenSwan VPN
2. Install and set up OpenSwan on that EC2 instance
3. Debug if it doesn’t work on first try ;)
openswan-aws
Part 1) Create an AWS EC2 instance to run Openswan
1. Open up your AWS console, go to the EC2 services and create a new instance:
• Use the Amazon Linux AMI.
• Make sure you create the instance in the same VPC as your web servers (assumed to be 172.31.0.0/16 in the diagram).
• Make sure you create it inside a public subnet (172.31.1.0/24 in the diagram). This will give it a direct route out to the internet through the VPC’s Internet Gateway.
• Add a Name tag (e.g. “Openswan VPN”) and create a security group (e.g. “Openswan SG”)
This is going to be our VPN instance which will be responsible for establishing the VPN tunnel to the third-party.
2. In the EC2 dashboard, select your new VPN instance and choose: “Actions -> Network -> Change Source/Dest Checking” and make sure the status is “Disabled”. If it isn’t, click on “Yes, Disable”.
• By default, AWS blocks any request to and from an EC2 instance that don’t have that instance as either the source or destination of the request.
• We need to disable this since we will be routing requests through this instance that have the 3rd-party as destination.
3. In the details of the VPN instance, you can see its Private IP. Note this down. In the diagram above we assume it’s 172.31.1.15
4. By default, instances in public subnets are allocated a public IP by AWS. We could use this public IP for our VPN instance but it is much safer to allocate an Elastic IP for your instance:
• On the sidebar, select Elastic IPs and allocate an Elastic IP to the VPN instance.
• In the diagram, we have denoted it as EIP
5. We need to adjust the security group of our instance to accept traffic from your application:
• Add an inbound rule that accepts traffic from inside your VPC (172.31.0.0/16 in our case)
• The type of traffic will depend on what type of API requests you want to make. For most cases, a rule for HTTP and another for HTTPS traffic should be enough. If you want to enable pinging, you should also allow TCP traffic.
• There is no need to explicitly add corresponding outbound rules.
6. Finally, we need to tell our VPC router to route all requests to the 3rd-party through our VPN instance:
• Go to the VPC service and select Route Tables in the side bar.
• Each subnet will be associated with a route table. For each route table that is associated with one of your public subnets, we need to add the following rule:
• Destination: IP range of third-party network (10.0.1.0/24 in the diagram)
• Target: {select your Openswan VPN instance from the dropdown}
Part 2) Install and Configure OpenSwan
We are done with the AWS console for now. The next step is to log into the instance and set up Openswan itself.
1. SSH into the VPN instance: ssh ec2-user@{EIP}
2. Install openswan: sudo yum install openswan.
3. This will create an IPSec configuration file. We need to edit it: sudo vi /etc/ipsec.conf
4. We want to include configuration files in /etc/ipsec.d/. For this, you need to uncomment the last line:
# /etc/ipsec.conf - Openswan IPsec configuration file
#
# Manual: ipsec.conf.5
#
# Please place your own config files in /etc/ipsec.d/ ending in .conf
version 2.0 # conforms to second version of ipsec.conf specification
# basic configuration
config setup
# Debug-logging controls: "none" for (almost) none, "all" for lots.
# klipsdebug=none
# plutodebug="control parsing"
# For Red Hat Enterprise Linux and Fedora, leave protostack=netkey
protostack=netkey
nat_traversal=yes
virtual_private=
oe=off
# Enable this if you see "failed to find any available worker"
# nhelpers=0
#You may put your configuration (.conf) file in the "/etc/ipsec.d/" and uncomment this.
include /etc/ipsec.d/*.conf
5. Next we create our VPN configuration in a new file: sudo vi /etc/ipsec.d/third-party-vpn.conf. This part is the tricky bit. You can start by pasting the following template and replacing the option values with the correct settings for your environment.
conn third-party # Name of the connection. You can call it what you like
type=tunnel
authby=secret
auto=start # load connection and initiate it on startup
# Network Info
left=%defaultroute
leftid={EIP} # Elastic IP of the VPN instance
leftsourceip=172.31.1.15 # Private IP of the VPN instance
leftsubnet=172.31.1.0/24 # IP range of your public subnet. Use this if you have a single public subnet.
# If you have multiple subnets, use "leftsubnets = {172.31.1.0/24 172.31.3.0/24 [...]}"
leftnexthop=%defaultroute
right={3rd-party-PublicIP} # Public IP address of third-party's VPN endpoint
rightid={3rd-party-PrivateIP} # Private IP address of third-party's VPN endpoint if you have it
rightsubnet=10.0.1.0/24 # IP range of third-party network. Use "rightsubnets" if multiple subnets
# Security Info
ike=aes192-sha1;modp1536 # IKE Encryption Policy and Diffie-Hallman Group
ikelifetime=3600s # IKE Lifetime
esp=aes192-sha1;modp1536 # ESP Encryption policy and Diffie-Hallman Group
salifetime=43200s # IPSec Lifetime
pfs=yes # Perfect Forward Secrecy
• The configuration here needs to match what the third-party has set up on their side of the VPN connection.
• In particular, make sure that IP addresses are correct and that both sides use the same authentication settings.
• If you are interested to see what other options exist, take a look at the ipsec manual.
6. Note that we used the setting authby=secret. This means that Openswan will use a “Pre-shared key” (PSK) to authenticate the connection. A PSK is simply a secret that is shared between you and the other side. We need to create a secrets file
sudo vi /etc/ipsec.d/third-party-vpn.secrets
and paste: bash {EIP} {3rd Party Private IP}: PSK "MY_SECRET_PRE_SHARED_KEY" replacing {EIP}, {3rd Party Private IP} and MY_SECRET_PRE_SHARED_KEY with the correct values.
1. We can now start Openswan:
sudo service ipsec start # Start the service. This will try to establish the tunnel
sudo chkconfig ipsec on # Make sure OpenSwan starts on boot
1. Finally, since we will be using this instance as a router, we need to enable IP forwarding: sudo vi /etc/sysctl.conf and change the ip_forward option from 0 to 1:
net.ipv4.ip_forward = 1
1. Restart the network:
sudo service network restart
If everything went well, you should now have a working connection.
Part 3) Test the Connection
We will test the connection in this order:
1. Check that the VPN tunnel can be established
2. Test that you can connect to the 3rd-party from the VPN instance
3. Test that you can connect to the 3rd-party from your web servers
router
1. Test the VPN tunnel
You can check the status of the VPN tunnel using
sudo ipsec auto --status
If the tunnel is up, you should see a line beginning with the name of your connection ("third-party" in our case) that contains the following statement near the end of the output:
IPsec SA established
If you don’t see this, the output should tell you how far into process it got and at what point the tunnel failed to build.
To get a few more logs, you can also try
sudo ipsec auto --replace third-party
sudo ipsec auto --up third-party
Make sure the security protocols and the PSK match what the 3rd party has.
If the tunnel does not even begin the build process, you might be blocking traffic to/from the third party for you public subnets.
2. Test connectivity from the Openswan instance
Once the tunnel is established, you can start testing the connection between your VPN instance and the 3rd-party.
Ideally, you should attempt to make an HTTP or HTTPS request directly to the third-party API (e.g. using the curl command).
You can also try to ping a host in the 3rd-party network (for this, you need to allow TCP traffic in the instance’s security group).
If you get a response, congrats! If not, try the following:
3. Test the connection from your web servers
Once you have connectivity between your Openswan instance and the 3rd party, you can finally test the connection from your web servers.
SSH into one of your web servers and try to make a request to the third-party API.
If you get a response, well done, you have come a long way! You should verify that you can actually connect to the 3rd party from all of your web servers. If you are running a massive fleet, at least check that the connection works from each subnet.
For those less fortunate of you, repeat the debug steps above. In addition to that, you can also try the following:
Next Steps
Hopefully you should have a working VPN connection now. However, our VPN configuration still has a lot of room for improvement. The most urgent concern is that we have not set up any monitoring or automatic fall-backs for the VPN tunnel.
To do so, you would need to create and configure a second VPN instance. Next, you could then setup a monitoring script on a separate instance that checks the state of each VPN tunnel. If tunnel A goes down, the script should immediately adjust your route tables to reroute traffic through tunnel B while also trying to fix the tunnel A.
If you want to go down that rabbit-hole, I suggest you start with Appendix A of the AWS VPC connectivity options whitepaper.
Liked this article?
|
__label__pos
| 0.573547 |
blob: d9fd6549ba4859dd3fabc1691dedd6b4a6941fb6 [file] [log] [blame]
//===-- sanitizer_thread_registry.cc --------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between sanitizer tools.
//
// General thread bookkeeping functionality.
//===----------------------------------------------------------------------===//
#include "sanitizer_thread_registry.h"
namespace __sanitizer {
ThreadContextBase::ThreadContextBase(u32 tid)
: tid(tid), unique_id(0), reuse_count(), os_id(0), user_id(0),
status(ThreadStatusInvalid),
detached(false), workerthread(false), parent_tid(0), next(0) {
name[0] = '\0';
atomic_store(&thread_destroyed, 0, memory_order_release);
}
ThreadContextBase::~ThreadContextBase() {
// ThreadContextBase should never be deleted.
CHECK(0);
}
void ThreadContextBase::SetName(const char *new_name) {
name[0] = '\0';
if (new_name) {
internal_strncpy(name, new_name, sizeof(name));
name[sizeof(name) - 1] = '\0';
}
}
void ThreadContextBase::SetDead() {
CHECK(status == ThreadStatusRunning ||
status == ThreadStatusFinished);
status = ThreadStatusDead;
user_id = 0;
OnDead();
}
void ThreadContextBase::SetDestroyed() {
atomic_store(&thread_destroyed, 1, memory_order_release);
}
bool ThreadContextBase::GetDestroyed() {
return !!atomic_load(&thread_destroyed, memory_order_acquire);
}
void ThreadContextBase::SetJoined(void *arg) {
// FIXME(dvyukov): print message and continue (it's user error).
CHECK_EQ(false, detached);
CHECK_EQ(ThreadStatusFinished, status);
status = ThreadStatusDead;
user_id = 0;
OnJoined(arg);
}
void ThreadContextBase::SetFinished() {
// ThreadRegistry::FinishThread calls here in ThreadStatusCreated state
// for a thread that never actually started. In that case the thread
// should go to ThreadStatusFinished regardless of whether it was created
// as detached.
if (!detached || status == ThreadStatusCreated) status = ThreadStatusFinished;
OnFinished();
}
void ThreadContextBase::SetStarted(tid_t _os_id, bool _workerthread,
void *arg) {
status = ThreadStatusRunning;
os_id = _os_id;
workerthread = _workerthread;
OnStarted(arg);
}
void ThreadContextBase::SetCreated(uptr _user_id, u64 _unique_id,
bool _detached, u32 _parent_tid, void *arg) {
status = ThreadStatusCreated;
user_id = _user_id;
unique_id = _unique_id;
detached = _detached;
// Parent tid makes no sense for the main thread.
if (tid != 0)
parent_tid = _parent_tid;
OnCreated(arg);
}
void ThreadContextBase::Reset() {
status = ThreadStatusInvalid;
SetName(0);
atomic_store(&thread_destroyed, 0, memory_order_release);
OnReset();
}
// ThreadRegistry implementation.
const u32 ThreadRegistry::kUnknownTid = ~0U;
ThreadRegistry::ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
u32 thread_quarantine_size, u32 max_reuse)
: context_factory_(factory),
max_threads_(max_threads),
thread_quarantine_size_(thread_quarantine_size),
max_reuse_(max_reuse),
mtx_(),
n_contexts_(0),
total_threads_(0),
alive_threads_(0),
max_alive_threads_(0),
running_threads_(0) {
threads_ = (ThreadContextBase **)MmapOrDie(max_threads_ * sizeof(threads_[0]),
"ThreadRegistry");
dead_threads_.clear();
invalid_threads_.clear();
}
void ThreadRegistry::GetNumberOfThreads(uptr *total, uptr *running,
uptr *alive) {
BlockingMutexLock l(&mtx_);
if (total) *total = n_contexts_;
if (running) *running = running_threads_;
if (alive) *alive = alive_threads_;
}
uptr ThreadRegistry::GetMaxAliveThreads() {
BlockingMutexLock l(&mtx_);
return max_alive_threads_;
}
u32 ThreadRegistry::CreateThread(uptr user_id, bool detached, u32 parent_tid,
void *arg) {
BlockingMutexLock l(&mtx_);
u32 tid = kUnknownTid;
ThreadContextBase *tctx = QuarantinePop();
if (tctx) {
tid = tctx->tid;
} else if (n_contexts_ < max_threads_) {
// Allocate new thread context and tid.
tid = n_contexts_++;
tctx = context_factory_(tid);
threads_[tid] = tctx;
} else {
#if !SANITIZER_GO
Report("%s: Thread limit (%u threads) exceeded. Dying.\n",
SanitizerToolName, max_threads_);
#else
Printf("race: limit on %u simultaneously alive goroutines is exceeded,"
" dying\n", max_threads_);
#endif
Die();
}
CHECK_NE(tctx, 0);
CHECK_NE(tid, kUnknownTid);
CHECK_LT(tid, max_threads_);
CHECK_EQ(tctx->status, ThreadStatusInvalid);
alive_threads_++;
if (max_alive_threads_ < alive_threads_) {
max_alive_threads_++;
CHECK_EQ(alive_threads_, max_alive_threads_);
}
tctx->SetCreated(user_id, total_threads_++, detached,
parent_tid, arg);
return tid;
}
void ThreadRegistry::RunCallbackForEachThreadLocked(ThreadCallback cb,
void *arg) {
CheckLocked();
for (u32 tid = 0; tid < n_contexts_; tid++) {
ThreadContextBase *tctx = threads_[tid];
if (tctx == 0)
continue;
cb(tctx, arg);
}
}
u32 ThreadRegistry::FindThread(FindThreadCallback cb, void *arg) {
BlockingMutexLock l(&mtx_);
for (u32 tid = 0; tid < n_contexts_; tid++) {
ThreadContextBase *tctx = threads_[tid];
if (tctx != 0 && cb(tctx, arg))
return tctx->tid;
}
return kUnknownTid;
}
ThreadContextBase *
ThreadRegistry::FindThreadContextLocked(FindThreadCallback cb, void *arg) {
CheckLocked();
for (u32 tid = 0; tid < n_contexts_; tid++) {
ThreadContextBase *tctx = threads_[tid];
if (tctx != 0 && cb(tctx, arg))
return tctx;
}
return 0;
}
static bool FindThreadContextByOsIdCallback(ThreadContextBase *tctx,
void *arg) {
return (tctx->os_id == (uptr)arg && tctx->status != ThreadStatusInvalid &&
tctx->status != ThreadStatusDead);
}
ThreadContextBase *ThreadRegistry::FindThreadContextByOsIDLocked(tid_t os_id) {
return FindThreadContextLocked(FindThreadContextByOsIdCallback,
(void *)os_id);
}
void ThreadRegistry::SetThreadName(u32 tid, const char *name) {
BlockingMutexLock l(&mtx_);
CHECK_LT(tid, n_contexts_);
ThreadContextBase *tctx = threads_[tid];
CHECK_NE(tctx, 0);
CHECK_EQ(SANITIZER_FUCHSIA ? ThreadStatusCreated : ThreadStatusRunning,
tctx->status);
tctx->SetName(name);
}
void ThreadRegistry::SetThreadNameByUserId(uptr user_id, const char *name) {
BlockingMutexLock l(&mtx_);
for (u32 tid = 0; tid < n_contexts_; tid++) {
ThreadContextBase *tctx = threads_[tid];
if (tctx != 0 && tctx->user_id == user_id &&
tctx->status != ThreadStatusInvalid) {
tctx->SetName(name);
return;
}
}
}
void ThreadRegistry::DetachThread(u32 tid, void *arg) {
BlockingMutexLock l(&mtx_);
CHECK_LT(tid, n_contexts_);
ThreadContextBase *tctx = threads_[tid];
CHECK_NE(tctx, 0);
if (tctx->status == ThreadStatusInvalid) {
Report("%s: Detach of non-existent thread\n", SanitizerToolName);
return;
}
tctx->OnDetached(arg);
if (tctx->status == ThreadStatusFinished) {
tctx->SetDead();
QuarantinePush(tctx);
} else {
tctx->detached = true;
}
}
void ThreadRegistry::JoinThread(u32 tid, void *arg) {
bool destroyed = false;
do {
{
BlockingMutexLock l(&mtx_);
CHECK_LT(tid, n_contexts_);
ThreadContextBase *tctx = threads_[tid];
CHECK_NE(tctx, 0);
if (tctx->status == ThreadStatusInvalid) {
Report("%s: Join of non-existent thread\n", SanitizerToolName);
return;
}
if ((destroyed = tctx->GetDestroyed())) {
tctx->SetJoined(arg);
QuarantinePush(tctx);
}
}
if (!destroyed)
internal_sched_yield();
} while (!destroyed);
}
// Normally this is called when the thread is about to exit. If
// called in ThreadStatusCreated state, then this thread was never
// really started. We just did CreateThread for a prospective new
// thread before trying to create it, and then failed to actually
// create it, and so never called StartThread.
void ThreadRegistry::FinishThread(u32 tid) {
BlockingMutexLock l(&mtx_);
CHECK_GT(alive_threads_, 0);
alive_threads_--;
CHECK_LT(tid, n_contexts_);
ThreadContextBase *tctx = threads_[tid];
CHECK_NE(tctx, 0);
bool dead = tctx->detached;
if (tctx->status == ThreadStatusRunning) {
CHECK_GT(running_threads_, 0);
running_threads_--;
} else {
// The thread never really existed.
CHECK_EQ(tctx->status, ThreadStatusCreated);
dead = true;
}
tctx->SetFinished();
if (dead) {
tctx->SetDead();
QuarantinePush(tctx);
}
tctx->SetDestroyed();
}
void ThreadRegistry::StartThread(u32 tid, tid_t os_id, bool workerthread,
void *arg) {
BlockingMutexLock l(&mtx_);
running_threads_++;
CHECK_LT(tid, n_contexts_);
ThreadContextBase *tctx = threads_[tid];
CHECK_NE(tctx, 0);
CHECK_EQ(ThreadStatusCreated, tctx->status);
tctx->SetStarted(os_id, workerthread, arg);
}
void ThreadRegistry::QuarantinePush(ThreadContextBase *tctx) {
if (tctx->tid == 0)
return; // Don't reuse the main thread. It's a special snowflake.
dead_threads_.push_back(tctx);
if (dead_threads_.size() <= thread_quarantine_size_)
return;
tctx = dead_threads_.front();
dead_threads_.pop_front();
CHECK_EQ(tctx->status, ThreadStatusDead);
tctx->Reset();
tctx->reuse_count++;
if (max_reuse_ > 0 && tctx->reuse_count >= max_reuse_)
return;
invalid_threads_.push_back(tctx);
}
ThreadContextBase *ThreadRegistry::QuarantinePop() {
if (invalid_threads_.size() == 0)
return 0;
ThreadContextBase *tctx = invalid_threads_.front();
invalid_threads_.pop_front();
return tctx;
}
} // namespace __sanitizer
|
__label__pos
| 0.999885 |
Your device is currently offline. You can view downloaded files in My Downloads.
Lesson Plan
4. Defining and non-defining attributes (FP)
teaches Common Core State Standards CCSS.Math.Content.1.G.A.1 http://corestandards.org/Math/Content/1/G/A/1
teaches Common Core State Standards CCSS.Math.Practice.MP3 http://corestandards.org/Math/Practice/MP3
teaches Common Core State Standards CCSS.Math.Practice.MP7 http://corestandards.org/Math/Practice/MP7
Quick assign
You have saved this lesson!
Here's where you can access your saved items.
Dismiss
Content placeholder
Card of
or to view additional materials
You'll gain access to interventions, extensions, task implementation guides, and more for this lesson.
Lesson objective: Reason to differentiate between geometrically defining attributes and non-defining attributes.
This lesson helps to extend understanding of attributes. Students will discuss non-defining attributes such as color, shape, and size of an object. Students will consider the "must haves" or defining attributes of a shape. Students will describe in their own words why a shape belongs to a given category. Two different attributes are used here because they encourage students to engage in problem solving that is about thinking and reasoning. This work develops students' understanding that shapes both defining and non-defining attributes.
Students engage in Mathematical Practice 3 as they construct viable arguments and critique the reasoning of others. Students will use clear definitions with peers as they define attributes and provide a viable argument reasoning why a shape lacks specific attributes. Students also engage in Mathematical Practice 7 as they look for and make use of structure. Students will use the patterns seen in different shapes to make comparisons. Students will use the relationships demonstrated in the defining attributes to explain similarities and differences.
Key vocabulary:
• attribute
• defining
• non-defining
Special materials needed:
• envelopes, string
Related content
Appears in
Distinguishing attributes of shapes
Provide feedback
|
__label__pos
| 0.983218 |
Trending Topics: Latest from our forums (March 2022)
Here are some of the latest popular questions that the Docusign developers community asked on Stack Overflow in the month of March 2022. You too can ask questions by using the tag docusignapi in Stack Overflow.
Thread: Docusign C# SDK setting prefilled fields
https://stackoverflow.com/questions/71388823/
Summary: The developer is trying to use the C# SDK and the pre-fill fields feature and send an envelope based on a template that includes pre-fill tabs. They are getting an error that says A Required field is incomplete. TabId: <TabIdGUID>
Answer: The term pre-fill tabs relates to a specific feature of Docusign that enables the sender to provide data in the envelope that is not tied to any recipient. This feature does not support using templates to send envelopes. You can only use this feature when sending envelopes directly, not based on a template. However, there are other ways to update information in an envelope without using pre-fill tabs. You can create regular text tabs that are read-only and cannot be modified by the recipient. You then assign them to the first recipient based on routing order. You can use the eSignature REST API to update the values of these tabs. You can find a step-by-step guide for this scenario with code examples in eight languages on the Docusign Developer Center.
Thread: How to pass phone verification in Docusign?
https://stackoverflow.com/questions/71491231/
Summary: This developer is using Visual Basic.NET (VB.NET) with the Docusign C# SDK and is attempting to use the Phone verification option for Docusign and is running into some issues.
Answer: Phone verification can be set from the API, but it does require that your developer account has the feature enabled. Once enabled, you can use the following VB.NET code with the Docusign C# SDK version 5.9 or above to get a recipient using phone verification (that can be either SMS or phone call):
Dim workflow As RecipientIdentityVerification = New RecipientIdentityVerification() With {
.WorkflowId = workflowId,
.InputOptions = New List(Of RecipientIdentityInputOption) From {
New RecipientIdentityInputOption With {
.Name = "phone_number_list",
.ValueType = "PhoneNumberList",
.PhoneNumberList = New List(Of RecipientIdentityPhoneNumber) From {
New RecipientIdentityPhoneNumber With {
.Number = phoneNumber, .CountryCode = countryAreaCode
}
}
}
}
Tip: you can use Telerik Code Converter to convert any C# code to VB.NET code
Thread: How to obtain Access Token using production environment in Docusign?
https://stackoverflow.com/questions/71618566/
Summary: The developer finished the go-live process with an integration using JWT Grant for authentication and is having trouble getting the integration to work in the Docusign production environment.
Answer: When using JWT Grant authentication and changing from the developer environment to the production environment, you have to do the following:
1. Pass go-live and get approval to have your integration key (app) in production.
2. Promote your IK to your production account.
3. Create a new RSA key for the new IK in the production account. You cannot use the RSA key from your developer account.
4. Change the URL for authentication from https://account-s.docusign.com to https://account.docusign.com.
5. The user ID for the user will be a different GUID; you’ll need to update.
6. The account ID for the account will be a different GUID; you’ll need to update.
Additional resources
Inbar Gazit
Author
Inbar Gazit
Sr. Manager, Developer Content
Published
|
__label__pos
| 0.956238 |
Algebraic Expressions and Identities – Class 8/MCQ
CBSE CLASS 8 MATHEMATICS
Algebraic Expressions and Identities – Chapter 9/ MCQ.
1. The algebraic equation 4xy +2yz + 5 is a ————
A. Binomial
B. Trinomial
C. Monomial
2. The number of terms in a polynomial is ————
A. One
B. Two
C. None of these.
3. The numerical coefficient of –xyz is ————–
A. -1
B. 0
C. 1
4. If we subtract 4a-7ab+3b+12 from 12a-9ab+5b-3, then the difference is ———–
A. 8a -2ab+2b-15.
B. 8a -16ab+8b-8
C. 8a – 2ab +8b – 15
5. The product of 4a and (-6bc) is ———-
A. 24abc
B. -24abc
C. –abc
6. If x +2y = 4 then 3x +6y is ———–
A. 4
B. 8
C. 12
7. The volume of a rectangular box with length, breadth and height are a, 2b and 3c respectively ——
A. 2abc
B. 3abc
C. 6abc
8. The area of a rectangle with length and breadth are 10m and 5n respectively ————
A. 10mn
B. 5mn
C. 50mn
9. Which of the following is a binomial?
A. 3xy
B. 4l +5m
C. a+b+c+d
10. Write term which is like to 7xy?
A. 5xy
B. 5x
C. 5y
ANSWERS:
1. Trinomial
2. None of these
3. -1
4. 8a -2ab+2b-15
5. -24abc
6. 12
7. 6abc
8. 50mn
9. 4l+5m
10. 5xy.
You may also like...
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.999618 |
Laravel SQL Result Different Than MySQL Query
From my various searches, I suspect he below issue stems from the fact that I am using GROUP BY. However, none of the examples I cam across were as simple as mine and their solutions ended up being something I couldnt grasp. I hope you can help me work out what is going wrong here?
I have this query with several joins which I am using in my app. When I run the query in a mysql client (SQLYog) remotely connecting to the homestead VM – I get the correct results. When I SSH into the VM and run MySQL and run the query, I get the correct results. When the query is run in Laravel/the app however, the results are different and I dont understand why!
Query:
SELECT monthly_contribution, COUNT(*) AS contributors FROM students
INNER JOIN student_bursaries ON students.id=student_bursaries.student_id
INNER JOIN student_bursary_statuses ON student_bursaries.id=student_bursary_statuses.student_bursary_id
LEFT JOIN student_medical_aids ON students.`id`=student_medical_aids.`student_id`
INNER JOIN bursary_administrator_student ON students.`id`=bursary_administrator_student.`student_id`
WHERE student_bursary_statuses.`status` IN (1,4,6,7) AND
bursary_administrator_student.`bursary_administrator_id`=1
GROUP BY monthly_contribution
MySQL results:
+----------------------+--------------+
| monthly_contribution | contributors |
+----------------------+--------------+
| 50.00 | 151 |
| NULL | 7 |
| 150.00 | 4 |
| 100.00 | 1 |
| 250.00 | 3 |
+----------------------+--------------+
Laravel results:
+----------------------+--------------+
| monthly_contribution | contributors |
+----------------------+--------------+
| 50.00 | 141 |
| NULL | 2 |
| 150.00 | 4 |
| 100.00 | 1 |
| 250.00 | 2 |
+----------------------+--------------+
I tried COUNT(monthly_contribution) but that returns the count of NULL value as 0 – and I need the count there. Also, it doesnt fix the miscounts of the others anyway, so its not that.
I did use Log::debug(DB::getQueryLog()); and it did output the same query so doesnt appear to be an issue there either:
Laravel Code:
$medical_aids = DB::select('SELECT monthly_contribution, COUNT(*) AS contributors FROM students
INNER JOIN student_bursaries ON students.id=student_bursaries.student_id
INNER JOIN student_bursary_statuses ON student_bursaries.id=student_bursary_statuses.student_bursary_id
LEFT JOIN student_medical_aids ON students.`id`=student_medical_aids.`student_id`
INNER JOIN bursary_administrator_student ON students.`id`=bursary_administrator_student.`student_id`
WHERE student_bursary_statuses.`status` IN (:status) AND
bursary_administrator_student.`bursary_administrator_id`=:bursary_administrator_id
GROUP BY monthly_contribution',
[
'status' => '1,4,6,7',
'bursary_administrator_id' => Auth::user()->userable_id
]);
Laravel Log File:
[2021-07-16 10:44:34] local.DEBUG: array (
0 =>
array (
'query' => 'SELECT monthly_contribution, COUNT(*) AS contributors FROM students
INNER JOIN student_bursaries ON students.id=student_bursaries.student_id
INNER JOIN student_bursary_statuses ON student_bursaries.id=student_bursary_statuses.student_bursary_id
LEFT JOIN student_medical_aids ON students.`id`=student_medical_aids.`student_id`
INNER JOIN bursary_administrator_student ON students.`id`=bursary_administrator_student.`student_id`
WHERE student_bursary_statuses.`status` IN (:status) AND
bursary_administrator_student.`bursary_administrator_id`=:bursary_administrator_id
GROUP BY monthly_contribution',
'bindings' =>
array (
'status' => '1,4,6,7',
'bursary_administrator_id' => 1,
),
'time' => 1.83,
),
Please advise if you need more data?
Answer
What I see in your query is that you are using binded parameters in IN() function. If you want to use that you have to bind each of them. For example:
DB::select("SELECT * FROM table WHERE id IN (?,?,?,?)", [1,2,3,4]);
DB::select("SELECT * FROM table WHERE id IN (:status1,:status2,:status3,:status4)", [
'status1' => 1,
'status2' => 2,
'status3' => 3,
'status4' => 4,
]);
In your case you can use join statement in your query.
DB::select("SELECT * FROM table WHERE id IN (". DB::connection()->getPdo()->quote(implode(',', [1,2,3,4])) . ")");
Or User Larave’s ORM to build query.
Or Implement some other complex logic, Which I don’t recomend.
|
__label__pos
| 0.993323 |
MongoDB and Mongoose - Create and Save a Record of a Model
's happening:
Please help me on this model i seems the code is not upto date maybe some can help with model save no longer accepts callback
###Your project link(s)
solution: http://localhost:3000
require(‘dotenv’).config();
const mongoose = require(‘mongoose’);
const { Schema } = mongoose;
mongoose.connect(process.env.MONGO_URI);
const personSchema = new Schema({
name: { type: String, required: true },
age: Number,
favoriteFoods: [String]
});
const Person = mongoose.model(“Person”, personSchema);
exports.PersonModel = Person;
const createAndSavePerson = (done) => {
const person = new Person({name: “david”, age: 21, favoriteFoods: [“pizza”, “moo”]});
person.save(function(err, data) {
done(null, data);
});
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36
Challenge Information:
MongoDB and Mongoose - Create and Save a Record of a Model
Leaving a link to localhost isn’t much help, that’s on your machine. The problem is this code cant run on its own without the other files.
Don’t update the dependencies or use the promise based approach (async/await or .then).
https://mongoosejs.com/docs/api/model.html#Model.prototype.save()
https://mongoosejs.com/docs/7.x/docs/migrating_to_7.html#dropped-callback-support
There was something wrong with the DNS since i was doing it on my local server so i used glitch and it passed thanks for the info
|
__label__pos
| 0.665718 |
Recently we have seen a lot of users experience extreme slowness or hanging when opening Excel files from a network location. PCs that are running XP and 2003 are affected whilst those using W7/Office 2003 or XP/Office 2007 or 2010 are fine.
After much searching the fix was actually a recent help article from Microsoft. After you install MS11-021 and the Office File Validation (OFV) Add-in for Office 2003 (KB 2501584), workbooks stored in a network location open slower over the network in Excel 2003 than they did without the OFV installed. The decrease in performance depends on the size of the workbook and bandwidth of the network and in some scenarios can seem to hang Excel.
Microsoft provide three fixes:
Method 1:
To be able to have both the protection of the OFV, and typical performance over the network when opening files, upgrade to either Microsoft Excel 2007 or Microsoft Excel 2010.
Method 2:
Copy the file to the local workstation. Open and save it in Excel from the local hard drive. Copy the file back to the network location.
Note: If multiple users are accessing the same file, you must be cautious to collaborate with the other users before you copy the file back to the share so that you do not overwrite the changes that were made by another user. The Shared Workbook feature cannot be used with this workaround.
Method 3:
To use Excel 2003 and avoid the network performance issue, you can disable the Microsoft Office File Validation Add-In for Excel by using a registry setting. This removes the additional protection of the OFV for Excel while still protecting the other Office applications.
Realistically, the only short term fix is Method 3!
Instructions to disable Microsoft Office File Validation Add-In are:
You can use the EnableOnLoad registry entry to configure how you want Excel to handle opening workbooks for the OFV. By default, the EnableOnLoad entry is not present in the Windows registry. To add the EnableOnLoadentry to the Windows registry, follow these steps:
1. Exit Excel.
2. Click Start, click Run, type regedit, and then click OK.
3. Locate and then click to select the following registry key: **EDIT** Thanks to Frank in the comments , the proper key is ” HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\11.0″ Old key “HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\11.0\”
4. After you select the key that is specified in step 3, point to New on the Edit menu, and then clickKey.
5. Type Excel, and then press ENTER.
6. Select Excel, point to New on the Edit menu, and then click Key.
7. Type Security, and then press ENTER.
8. Select Security, point to New on the Edit menu, and then click Key.
9. Type FileValidation, and then press ENTER.
10. Select FileValidation, point to New on the Edit menu, and then click DWORD Value.
11. Type EnableOnLoad, and then press ENTER. Note: The default value is 0 which disables the validation.
12. On the File menu, click Exit to quit Registry Editor.
IMPORTANT
This fix needs to be applied at a user level, and for that reason it would be a good idea to include in your logon script. You can create a registry file called officefix.reg with the following content:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel\Security]
[HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel\Security\FileValidation]
“EnableOnLoad”=dword:00000000
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel\Security]
[HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Excel\Security\FileValidation]“EnableOnLoad”=dword:00000000
Then call the registry file with the following command:
Batch script
REGEDIT /S %filepath%\officefix.reg — %filepath% is the path to the registry file.
OR
VBscript
objShel.Run “REGEDIT /S %filepath%\officefix.reg” — %filepath% is the path to the registry file.
|
__label__pos
| 0.727533 |
Memoization
Memoization is a technique. It means to keep track of previous results in a cache and returning that result.
I got stuck this week battling this:
def answer(food, grid):
@memoize
def search(f, row, column):
f -= grid[row][column]
if row < 0 or column < 0 or f < 0:
return food + 1
elif row == column == 0:
return f
else:
return min(search(f, row - 1, column), search(f, row, column - 1))
remainder = search(food, len(grid) - 1, len(grid) - 1)
return remainder if remainder <= food else -1
It searches a matrix N x N where N is less than 20.
The test cases I was given were the following:
def test():
N = 20
data = [(
# First Test Case F=7, N=3, Answer=0
7,
[[0, 2, 5], [1, 1, 3], [2, 1, 1]],
0
),(
12,
[[0, 2, 5], [1, 1, 3], [2, 1, 1]],
1
),(
# The custom test case
200,
[[randrange(1, 6) for i in range(N)] for j in range(N)],
None
)]
for food, grid, r in data:
result = answer(food, grid)
print(result == r if r else result)
Sadly for the third test case it failed, because there are too many possibilities. I left it run it for a while, according to my bad calculations it would take more than a day, don't really know how much more... just more.
This is where Python's help comes to the rescue (note: memoization is a technique not exclusive to python). In here there are several examples of how to create a memoizer, some of the using an elegant decorator. I copied and pasted the following:
import functools
def memoize(obj):
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
Of course my first option was to do a way more complex solution of finding paths via Depth First Search. But who cares.
After memoizing the solution works, which is pretty awesome.
|
__label__pos
| 0.992944 |
Ulrich Pfeifer
NAME
Math::Matrix - Multiply and invert Matrices
SYNOPSIS
use Math::Matrix;
DESCRIPTION
The following methods are available:
new
Constructor arguments are a list of references to arrays of the same length. The arrays are copied. The method returns undef in case of error.
$a = new Math::Matrix ([rand,rand,rand],
[rand,rand,rand],
[rand,rand,rand]);
If you call new as method, a zero filled matrix with identical deminsions is returned.
clone
You can clone a matrix by calling:
$b = $a->clone;
diagonal
A constructor method that creates a diagonal matrix from a single list or array of numbers.
$p = Math::Matrix->diagonal(1, 4, 4, 8);
$q = Math::Matrix->diagonal([1, 4, 4, 8]);
The matrix is zero filled except for the diagonal members, which take the value of the vector
The method returns undef in case of error.
tridiagonal
A constructor method that creates a matrix from vectors of numbers.
$p = Math::Matrix->tridiagonal([1, 4, 4, 8]);
$q = Math::Matrix->tridiagonal([1, 4, 4, 8], [9, 12, 15]);
$r = Math::Matrix->tridiagonal([1, 4, 4, 8], [9, 12, 15], [4, 3, 2]);
In the first case, the main diagonal takes the values of the vector, while both of the upper and lower diagonals's values are all set to one.
In the second case, the main diagonal takes the values of the first vector, while the upper and lower diagonals are each set to the values of the second vector.
In the third case, the main diagonal takes the values of the first vector, while the upper diagonal is set to the values of the second vector, and the lower diagonal is set to the values of the third vector.
The method returns undef in case of error.
size
You can determine the dimensions of a matrix by calling:
($m, $n) = $a->size;
concat
Concatenates two matrices of same row count. The result is a new matrix or undef in case of error.
$b = new Math::Matrix ([rand],[rand],[rand]);
$c = $a->concat($b);
transpose
Returns the transposed matrix. This is the matrix where colums and rows of the argument matrix are swaped.
multiply
Multiplies two matrices where the length of the rows in the first matrix is the same as the length of the columns in the second matrix. Returns the product or undef in case of error.
solve
Solves a equation system given by the matrix. The number of colums must be greater than the number of rows. If variables are dependent from each other, the second and all further of the dependent coefficients are 0. This means the method can handle such systems. The method returns a matrix containing the solutions in its columns or undef in case of error.
invert
Invert a Matrix using solve.
multiply_scalar
Multiplies a matrix and a scalar resulting in a matrix of the same dimensions with each element scaled with the scalar.
$a->multiply_scalar(2); scale matrix by factor 2
add
Add two matrices of the same dimensions.
subtract
Shorthand for add($other->negative)
equal
Decide if two matrices are equal. The criterion is, that each pair of elements differs less than $Math::Matrix::eps.
slice
Extract columns:
a->slice(1,3,5);
diagonal_vector
Extract the diagonal as an array:
$diag = $a->diagonal_vector;
tridiagonal_vector
Extract the diagonals that make up a tridiagonal matrix:
($main_d, $upper_d, $lower_d) = $a->tridiagonal_vector;
determinant
Compute the determinant of a matrix.
dot_product
Compute the dot product of two vectors.
absolute
Compute the absolute value of a vector.
normalizing
Normalize a vector.
cross_product
Compute the cross-product of vectors.
print
Prints the matrix on STDOUT. If the method has additional parameters, these are printed before the matrix is printed.
pinvert
Compute the pseudo-inverse of the matrix: ((A'A)^-1)A'
EXAMPLE
use Math::Matrix;
srand(time);
$a = new Math::Matrix ([rand,rand,rand],
[rand,rand,rand],
[rand,rand,rand]);
$x = new Math::Matrix ([rand,rand,rand]);
$a->print("A\n");
$E = $a->concat($x->transpose);
$E->print("Equation system\n");
$s = $E->solve;
$s->print("Solutions s\n");
$a->multiply($s)->print("A*s\n");
AUTHOR
Ulrich Pfeifer <[email protected]>
Brian J. Watson <[email protected]>
Matthew Brett <[email protected]>
|
__label__pos
| 0.870918 |
Skip to contents
bcputility is a wrapper for the command line utility program from SQL Server that does bulk imports/exports. The package assumes that bcp is already installed and is on the system search path. For large inserts to SQL Server over an ODBC connection (e.g. with the “DBI” package), writes can take a very long time as each row generates an individual insert statement. The bcp Utility greatly improves performance of large writes by using bulk inserts.
An export function is provided for convenience, but likely will not significantly improve performance over other methods.
Prerequisites
The system dependencies can be downloaded and installed from Microsoft. It is recommended to add bcp and sqlcmd to the system path.
Installation
You can install the released version of bcputility from CRAN with:
install.packages("bcputility")
Install the development version with:
devtools::install_github("tomroh/bcputility")
To check if the prerequisite binaries are on the path:
If bcp and sqlcmd is not on the system path or you want to override the default, set the option with the full file path:
options(bcputility.bcp.path = "<path-to-bcp>")
options(bcputility.sqlcmd.path = "<path-to-sqlcmd>")
Usage
Trusted Connection (default):
x <- read.csv("<file.csv>")
connectArgs <- makeConnectArgs(server = "<server>", database = "<database>")
bcpImport(x = x, connectargs = connectArgs, table = "<table>")
SQL Authentication:
connectArgs <- makeConnectArgs(server = "<server>", database = "<database>",
username = "<username>", password = "<password>")
bcpImport(x = x, connectargs = connectArgs, table = table)
Benchmarks
Benchmarks were performed with a local installation of SQL Server Express. When testing with a remote SQL Server, performance of bcp over odbc was further improved.
Import
library(DBI)
library(data.table)
library(bcputility)
server <- Sys.getenv('MSSQL_SERVER')
database <- Sys.getenv('MSSQL_DB')
driver <- 'ODBC Driver 17 for SQL Server'
set.seed(11)
n <- 1000000
importTable <- data.frame(
int = sample(x = seq(1L, 10000L, 1L), size = n, replace = TRUE),
numeric = sample(x = seq(0, 1, length.out = n/100), size = n,
replace = TRUE),
character = sample(x = state.abb, size = n, replace = TRUE),
factor = sample(x = factor(x = month.abb, levels = month.abb),
size = n, replace = TRUE),
logical = sample(x = c(TRUE, FALSE), size = n, replace = TRUE),
date = sample(x = seq(as.Date('2022-01-01'), as.Date('2022-12-31'),
by = 'days'), size = n, replace = TRUE),
datetime = sample(x = seq(as.POSIXct('2022-01-01 00:00:00'),
as.POSIXct('2022-12-31 23:59:59'), by = 'min'), size = n, replace = TRUE)
)
connectArgs <- makeConnectArgs(server = server, database = database)
con <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = server,
Database = database)
importResults <- microbenchmark::microbenchmark(
bcpImport1000 = {
bcpImport(importTable,
connectargs = connectArgs,
table = 'importTable1',
bcpOptions = list("-b", 1000, "-a", 4096, "-e", 10),
overwrite = TRUE,
stdout = FALSE)
},
bcpImport10000 = {
bcpImport(importTable,
connectargs = connectArgs,
table = 'importTable2',
bcpOptions = list("-b", 10000, "-a", 4096, "-e", 10),
overwrite = TRUE,
stdout = FALSE)
},
bcpImport50000 = {
bcpImport(importTable,
connectargs = connectArgs,
table = 'importTable3',
bcpOptions = list("-b", 50000, "-a", 4096, "-e", 10),
overwrite = TRUE,
stdout = FALSE)
},
bcpImport100000 = {
bcpImport(importTable,
connectargs = connectArgs,
table = 'importTable4',
bcpOptions = list("-b", 100000, "-a", 4096, "-e", 10),
overwrite = TRUE,
stdout = FALSE)
},
dbWriteTable = {
con <- DBI::dbConnect(odbc::odbc(),
Driver = driver,
Server = server,
Database = database,
trusted_connection = 'yes')
DBI::dbWriteTable(con, name = 'importTable5', importTable, overwrite = TRUE)
},
times = 30L,
unit = 'seconds'
)
importResults
expr min lq mean median uq max neval
bcpImport1000 15.017385 16.610868 17.405555 17.656265 18.100990 19.44482 30
bcpImport10000 10.091266 10.657926 10.926738 10.916577 11.208184 11.46027 30
bcpImport50000 8.982498 9.337509 9.677375 9.571526 9.896179 10.77709 30
bcpImport100000 8.769598 9.303473 9.562921 9.581927 9.855355 10.36949 30
dbWriteTable 13.570956 13.820707 15.154505 14.159002 16.378986 27.28819 30
Time in seconds
Export Table
Note: bcp exports of data may not match the format of fwrite. dateTimeAs = 'write.csv' was used to make timings comparable, which decreased the performance of “data.table”. Optimized write formats for date times from fwrite outperforms bcp for data that is small enough to be pulled into memory.
exportResults <- microbenchmark::microbenchmark(
bcpExportChar = {
bcpExport('inst/benchmarks/test1.csv',
connectargs = connectArgs,
table = 'importTableInit',
fieldterminator = ',',
stdout = FALSE)
},
bcpExportNchar = {
bcpExport('inst/benchmarks/test2.csv',
connectargs = connectArgs,
table = 'importTableInit',
fieldterminator = ',',
stdout = FALSE)
},
fwriteQuery = {
fwrite(DBI::dbReadTable(con, 'importTableInit'),
'inst/benchmarks/test3.csv', dateTimeAs = 'write.csv',
col.names = FALSE)
},
times = 30L,
unit = 'seconds'
)
exportResults
expr min lq mean median uq max neval
bcpExportChar 2.565654 2.727477 2.795670 2.756685 2.792291 3.352325 30
bcpExportNchar 2.589367 2.704135 2.765784 2.734957 2.797286 3.479074 30
fwriteQuery 7.429731 7.602853 7.645852 7.654730 7.703634 7.868419 30
Time in seconds
Export Query
query <- 'SELECT * FROM [dbo].[importTable1] WHERE int < 1000'
queryResults <- microbenchmark::microbenchmark(
bcpExportQueryChar = {
bcpExport('inst/benchmarks/test4.csv',
connectargs = connectArgs,
query = query,
fieldterminator = ',',
stdout = FALSE)
},
bcpExportQueryNchar = {
bcpExport('inst/benchmarks/test5.csv',
connectargs = connectArgs,
query = query,
fieldterminator = ',',
stdout = FALSE)
},
fwriteQuery = {
fwrite(DBI::dbGetQuery(con, query),
'inst/benchmarks/test6.csv', dateTimeAs = 'write.csv',
col.names = FALSE)
},
times = 30L,
unit = 'seconds'
)
queryResults
expr min lq mean median uq max neval
bcpExportQueryChar 0.3444491 0.4397317 0.4557119 0.4490924 0.4615573 0.7237182 30
bcpExportQueryNchar 0.3305265 0.4444705 0.4412670 0.4500690 0.4605971 0.4815894 30
fwriteQuery 0.6737879 0.7141933 0.7421377 0.7311998 0.7548233 0.9143555 30
Time in seconds
Import Geometry
Importing spatial data from ‘sf’ objects is also supported. The sql statements after import are to produce equivalent tables in the database.
library(sf)
nc <- st_read(system.file("gpkg/nc.gpkg", package = "sf"))
divN <- 10
shp1 <- cbind(nc[sample.int(nrow(nc), n / divN, replace = TRUE),],
importTable[seq_len(n / divN), ],
id = seq_len(n / divN))
geometryResults <- microbenchmark::microbenchmark(
bcpImportGeometry = {
bcpImport(shp1,
connectargs = connectArgs,
table = 'shp1',
overwrite = TRUE,
stdout = FALSE,
spatialtype = 'geometry',
bcpOptions = list("-b", 50000, "-a", 4096, "-m", 0))
},
odbcImportGeometry = {
con <- DBI::dbConnect(odbc::odbc(),
driver = driver,
server = server,
database = database,
trusted_connection = 'yes')
tableName <- 'shp2'
spatialType <- 'geometry'
geometryColumn <- 'geom'
binaryColumn <- 'geomWkb'
srid <- sf::st_crs(nc)$epsg
shpBin2 <- data.table(shp1)
data.table::set(x = shpBin2, j = binaryColumn,
value = blob::new_blob(lapply(sf::st_as_binary(shpBin2[[geometryColumn]]),
as.raw)))
data.table::set(x = shpBin2, j = geometryColumn, value = NULL)
dataTypes <- DBI::dbDataType(con, shpBin2)
dataTypes[binaryColumn] <- 'varbinary(max)'
DBI::dbWriteTable(conn = con, name = tableName, value = shpBin2,
overwrite = TRUE, field.types = dataTypes)
DBI::dbExecute(conn = con, sprintf('alter table %1$s add %2$s %3$s;',
tableName, geometryColumn, spatialType))
DBI::dbExecute(conn = con,
sprintf('UPDATE %1$s
SET geom = %3$s::STGeomFromWKB([%4$s], %2$d);
ALTER TABLE %1$s DROP COLUMN [%4$s];', tableName, srid, spatialType,
binaryColumn)
)
},
bcpImportGeography = {
bcpImport(shp1,
connectargs = connectArgs,
table = 'shp3',
overwrite = TRUE,
stdout = FALSE,
spatialtype = 'geography',
bcpOptions = list("-b", 50000, "-a", 4096, "-m", 0))
},
odbcImportGeography = {
con <- DBI::dbConnect(odbc::odbc(),
driver = driver,
server = server,
database = database,
trusted_connection = 'yes')
tableName <- 'shp4'
spatialType <- 'geography'
geometryColumn <- 'geom'
binaryColumn <- 'geomWkb'
srid <- sf::st_crs(nc)$epsg
shpBin4 <- data.table(shp1)
data.table::set(x = shpBin4, j = binaryColumn,
value = blob::new_blob(lapply(sf::st_as_binary(shpBin4[[geometryColumn]]),
as.raw)))
data.table::set(x = shpBin4, j = geometryColumn, value = NULL)
dataTypes <- DBI::dbDataType(con, shpBin4)
dataTypes[binaryColumn] <- 'varbinary(max)'
DBI::dbWriteTable(conn = con, name = tableName, value = shpBin4,
overwrite = TRUE, field.types = dataTypes)
DBI::dbExecute(conn = con, sprintf('alter table %1$s add %2$s %3$s;',
tableName, geometryColumn, spatialType))
DBI::dbExecute(conn = con,
sprintf('UPDATE %1$s
SET geom = %3$s::STGeomFromWKB([%4$s], %2$d);
ALTER TABLE %1$s DROP COLUMN [%4$s];', tableName, srid, spatialType,
binaryColumn)
)
DBI::dbExecute(conn = con,
sprintf(
'UPDATE %1$s SET [%2$s] = [%2$s].MakeValid().ReorientObject().MakeValid()
WHERE [%2$s].MakeValid().EnvelopeAngle() > 90;',
tableName, geometryColumn))
},
times = 30L,
unit = 'seconds'
)
geometryResults
expr min lq mean median uq max neval
bcpImportGeometry 18.01451 19.48747 20.68834 20.45136 21.74212 26.87033 30
odbcImportGeometry 18.29721 20.63363 22.35044 21.29087 24.04490 27.81112 30
bcpImportGeography 71.23260 75.04588 82.65286 76.36985 96.68469 102.70909 30
odbcImportGeography 73.29818 76.12481 84.58432 77.93419 97.36155 107.00186 30
Time in seconds
|
__label__pos
| 0.987567 |
0
I have uploaded a YouTube video which when played in 1.75x onwards, the video appears stuck but the audio plays.
Why is this behavior seen? How do I fix that?
1 Answer 1
0
Finally found this issue happens if the original video is created or shot at less than 40 or 50 frames per second (fps). In my case my video was shot at 30 FPS which caused this issue on mobile phone screens which i tested on my android phone.
A fix is : to shoot the video at 50 to 60 fps and not lesser.
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.713213 |
跳转至
50.powx-n
Statement
Metadata
• Link: Pow(x, n)
• Difficulty: Medium
• Tag: 递归 数学
实现 pow(x, n) ,即计算 xn 次幂函数(即,xn )。
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3
输出:9.26100
示例 3:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = ½2 = ¼ = 0.25
提示:
• -100.0 < x < 100.0
• -231 <= n <= 231-1
• -104 <= xn <= 104
Metadata
• Link: Pow(x, n)
• Difficulty: Medium
• Tag: Recursion Math
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = ½2 = ¼ = 0.25
Constraints:
• -100.0 < x < 100.0
• -231 <= n <= 231-1
• -104 <= xn <= 104
Solution
class Solution:
def myPow(self, x: float, n: int) -> float:
return x ** n
最后更新: January 15, 2023
回到页面顶部
|
__label__pos
| 0.878776 |
3
I have a function which returns the availability of a module, where the module is only available if multiple conditions are all met. The code looks like this:
bool isShipAvailable() {
bool isAvailable;
isAvailable = this->areSystemsCalibrated;
isAvailable = isAvailable && this->areEnginesFunctional;
isAvailable = isAvailable && this->isWarpDriveOnline;
isAvailable = isAvailable && this->isFluxCapacitorOnline;
isAvailable = isAvailable && this->areStabilizersOnline;
return isAvailable;
}
I'm trying to test this code without creating something large or difficult to maintain. I know I could write tests for all permutations, but would it be acceptable to test the case where all conditions are true and then test each scenario where only one condition is false? Would that be making too many assumptions about the implementation in the tests?
Edit: I'm not asking how to refactor the boolean logic to be concise, but rather what the shortest way to test every permutation of that logic would be. The details of the implementation itself are not terribly important.
8
• 9
Why do you keep re-assigning isAvailable when you could simply string together all those && clauses? (put each on its own line, starting with &&) May 31, 2018 at 18:20
• This is just the style my team agreed on, I'm not terribly keen on it
– codehearts
May 31, 2018 at 18:26
• 1
That said, if you really want tests for this, I think one test with all flags true and one test with one of the flags false really ought to suffice. Otherwise, there's 5 flags here; a fully comprehensive test would require 32 test permutations. May 31, 2018 at 18:45
• 1
Possible duplicate of How to turn truth table into smallest possible if / else block
– gnat
May 31, 2018 at 19:13
• 1
@robert it can be useful with many debuggers if you want to know why the “and” failed.
– gnasher729
Jun 1, 2018 at 7:26
4 Answers 4
9
Unit testing is about behaviour of the code under test from the point of view of its clients. Therefore, as your test class is one of its clients, you should define what are your expectations.
There's a few expectations I see from your implementation :
1. Given that the systems are calibrated, the engines are functional, the warp drive is online, the flux capacitor is online and the stabilizers are online, then the ship is available.1
2. Given that the systems are not calibrated, then the ship is unavailable.
3. Given that the engines are non functional, then the ship is unavailable.
4. And so on.
Therefore, I would expect 6 tests, as there are 6 distinct behaviours I care about as a client.
Would that be making too many assumptions about the implementation in the tests?
Quite funny, because I actually believe the reverse is true: you are making too many assumptions about your implementation when you test every combination. Remember that you always test from the point of view of your clients. If you test every single combination, then you're saying that your clients care about all those combinations. My understanding of your code is that it doesn't matter which combination of systems are offline or non functional. As long as one subsystem is offline, then the ship is unavailable, period. Therefore, I would test it as such.
1. Phew, that might require quite of a setup to test this assertion. If that's your feeling as well, then maybe your tests are speaking to you: your code under test is doing quite a lot.
2
• I feel like your stated expectations call for different code that what is in the OP, from a semantic perspective. For example, if(!areSystemsCalibrated) return false corresponds to expectation 2. May 31, 2018 at 18:51
• 3
It could, but even if you write the function that way, it results in the exact same behaviour and your tests will still pass. This is, in the end, the goal of unit tests: it doesn't care about the implementation, only about expectations and behaviours. May 31, 2018 at 19:00
3
The standard library provides a function specifically and explicitly for tasks like this. I'd simply use it, and see little reason to test that it does is job.
#include <algorithm>
class foo {
bool areSystemsCalibrated,
areEnginesFunctional,
isWarpDriveOnline,
isFluxCapcacitorOnline,
areStabilizersOnline;
bool foo::*conditions[5] = {
&foo::areSystemsCalibrated,
&foo::areEnginesFunctional,
&foo::isWarpDriveOnline,
&foo::isFluxCapcacitorOnline,
&foo::areStabilizersOnline
};
public:
bool isShipAvailable() const {
return std::all_of(std::begin(conditions), std::end(conditions),
[&](bool foo::*b) { return this->*b; });
}
};
If, at that point, you really want to test it anyway, you have a collection of conditions. That makes it relatively simple to test whatever combination of conditions you see fit--up to and including an exhaustive test of every possible combination, if you really want.
2
• This doesn't help with writing the tests, and I'd be wary of leaving it untested simply because it's using the standard library. If the warp drive check is accidentally removed, we'd still want to catch it in testing.
– codehearts
Jun 1, 2018 at 15:27
• @codehearts: Yes, it does help with writing tests. Having all the conditions in a collection makes it trivial to do quite a few tests that are non-trivial otherwise. For example, you can do all the usual loop-things to generate various combinations of conditions, which is painful (at best) otherwise. Jun 1, 2018 at 17:01
1
With a large, but finite number of test cases Data-Driven Testing is the answer.
... testing done using a table of conditions directly as test inputs and verifiable outputs as well as the process where test environment settings and control are not hard-coded. In the simplest form the tester supplies the inputs from a row in the table and expects the outputs which occur in the same row. The table typically contains values which correspond to boundary or partition input spaces.
You need 1 explicit test where all conditions are true saying "it works".
By using a data driven test, you can test all of the "false" values by parameterizing each boolean field as an input to the test.
How you do this depends on the tech stack and unit testing framework, but it could be reduced down to a test method and a for-loop that iterates over the expected inputs (example in C#, MS Test framework):
[TestClass]
public class ShipTests
{
[TestMethod]
public void ItWorks()
{
var ship = new SpaceShip(true, true, true, true, true);
Assert.IsTrue(ship.isShipAvailable());
}
[TestMethod]
public void ItDoesntWork()
{
var inputs = new bool[][]
{
{ false, true, true, true, true },
{ false, false, true, true, true },
// ...
{ false, false, false, false, false },
};
foreach (var row in inputs)
{
var ship = new SpaceShip(row[0], row[1], row[2], row[3], row[4]);
Assert.IsFalse(ship.isShipAvailable());
}
}
}
Robert Harvey commented on the question:
That said, if you really want tests for this, I think one test with all flags true and one test with one of the flags false really ought to suffice.
It doesn't suffice, because any one flag being false causes the ship to be unavailable. You don't want to test that the warp drive is not available, and say all tests pass if a defect causes the flux capacitor to be unexpectedly offline.
The flux capacitor is important, you know. VERY important. It must be online no matter what -- even more than Facebook!
Otherwise, there's 5 flags here; a fully comprehensive test would require 32 test permutations.
Yes, there are a large number of test cases, but the work required to maintain those tests is minimal if using a data driven test. And if this is all in-memory data manipulation, test execution time is negligible. I think I spent more time writing this answer than all the developers on the team will spend running these tests over the course of the project's lifetime.
-1
would it be acceptable to test the case where all conditions are true and then test each scenario where only one condition is false?
Yes.
But you should test it according to your use case i.e. as long as your conditions vary independently.
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.620523 |
Use jQuery para ocultar un DIV cuando el usuario hace clic fuera de él
Answers
Será mejor que vayas con algo como esto:
var mouse_is_inside = false;
$(document).ready(function()
{
$('.form_content').hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").mouseup(function(){
if(! mouse_is_inside) $('.form_wrapper').hide();
});
});
Question
Estoy usando este código:
$('body').click(function() {
$('.form_wrapper').hide();
});
$('.form_wrapper').click(function(event){
event.stopPropagation();
});
Y este HTML:
<div class="form_wrapper">
<a class="agree" href="javascript:;">I Agree</a>
<a class="disagree" href="javascript:;">Disagree</a>
</div>
El problema es que tengo enlaces dentro del DIV y cuando ya no funcionan cuando hago clic.
(Simplemente agregando a la respuesta de prc322).
En mi caso, estoy usando este código para ocultar un menú de navegación que aparece cuando el usuario hace clic en una pestaña adecuada. Descubrí que era útil agregar una condición adicional, que el objetivo del clic fuera del contenedor no es un enlace.
$(document).mouseup(function (e)
{
var container = $("YOUR CONTAINER SELECTOR");
if (!$("a").is(e.target) // if the target of the click isn't a link ...
&& !container.is(e.target) // ... or the container ...
&& container.has(e.target).length === 0) // ... or a descendant of the container
{
container.hide();
}
});
Esto se debe a que algunos de los enlaces en mi sitio agregan contenido nuevo a la página. Si este nuevo contenido se agrega al mismo tiempo que el menú de navegación desaparece, puede ser desorientador para el usuario.
$(document).click(function(event) {
if ( !$(event.target).hasClass('form_wrapper')) {
$(".form_wrapper").hide();
}
});
Devuelve falso si haces clic en .form_wrapper:
$('body').click(function() {
$('.form_wrapper').click(function(){
return false
});
$('.form_wrapper').hide();
});
//$('.form_wrapper').click(function(event){
// event.stopPropagation();
//});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
Una solución sin jQuery para la respuesta más popular :
document.addEventListener('mouseup', function (e) {
var container = document.getElementById('your container ID');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
}.bind(this));
MDN: https://developer.mozilla.org/en/docs/Web/API/Node/contains
Al usar este código puedes ocultar tantos artículos como quieras
var boxArray = ["first element's id","second element's id","nth element's id"];
window.addEventListener('mouseup', function(event){
for(var i=0; i < boxArray.length; i++){
var box = document.getElementById(boxArray[i]);
if(event.target != box && event.target.parentNode != box){
box.style.display = 'none';
}
}
})
Y para dispositivos Touch como IPAD e IPHONE podemos usar el siguiente código
$(document).on('touchstart', function (event) {
var container = $("YOUR CONTAINER SELECTOR");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
si tiene problemas con ios, mouseup no funciona en el dispositivo Apple.
¿mousedown / mouseup en jquery funciona para el ipad?
yo uso esto:
$(document).bind('touchend', function(e) {
var container = $("YOURCONTAINER");
if (container.has(e.target).length === 0)
{
container.hide();
}
});
dojo.query(document.body).connect('mouseup',function (e)
{
var obj = dojo.position(dojo.query('div#divselector')[0]);
if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
MyDive.Hide(id);
}
});
¿No funcionaría algo como esto?
$("body *").not(".form_wrapper").click(function() {
});
o
$("body *:not(.form_wrapper)").click(function() {
});
Este código detecta cualquier evento de clic en la página y luego oculta el elemento #CONTAINER si y solo si el elemento seleccionado no era el elemento #CONTAINER ni uno de sus descendientes.
$(document).on('click', function (e) {
if ($(e.target).closest("#CONTAINER").length === 0) {
$("#CONTAINER").hide();
}
});
De acuerdo con los documentos , .blur() funciona para más que la etiqueta <input> . Por ejemplo:
$('.form_wrapper').blur(function(){
$(this).hide();
});
$(document).ready(function() {
$('.modal-container').on('click', function(e) {
if(e.target == $(this)[0]) {
$(this).removeClass('active'); // or hide()
}
});
});
.modal-container {
display: none;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 999;
}
.modal-container.active {
display: flex;
}
.modal {
width: 50%;
height: auto;
margin: 20px;
padding: 20px;
background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-container active">
<div class="modal">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac varius purus. Ut consectetur viverra nibh nec maximus. Nam luctus ligula quis arcu accumsan euismod. Pellentesque imperdiet volutpat mi et cursus. Sed consectetur sed tellus ut finibus. Suspendisse porttitor laoreet lobortis. Nam ut blandit metus, ut interdum purus.</p>
</div>
</div>
Construido a partir de la impresionante respuesta de prc322.
function hideContainerOnMouseClickOut(selector, callback) {
var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
$(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
var container = $(selector);
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
$(document).off("mouseup.clickOFF touchend.clickOFF");
if (callback) callback.apply(this, args);
}
});
}
Esto agrega un par de cosas ...
1. Colocado dentro de una función con una devolución de llamada con argumentos "ilimitados"
2. Se agregó una llamada a .off () de jquery emparejado con un espacio de nombre de evento para desvincular el evento del documento una vez que se ha ejecutado.
3. Touchend incluido para la funcionalidad móvil
¡Espero que esto ayude a alguien!
Links
|
__label__pos
| 0.956207 |
Skip to content
Home » How To Get Blue Tick On Instagram
How To Get Blue Tick On Instagram
Are you an Instagram user looking to gain credibility and recognition on the platform? One way to achieve this is by obtaining the coveted blue tick, a symbol of verification that denotes the authenticity and importance of your account. While not everyone can be verified on Instagram, there are certain steps you can take to increase your chances of receiving the blue tick and standing out among millions of users.
First and foremost, it is essential to build a strong and genuine presence on Instagram. This entails creating captivating and high-quality content that resonates with your target audience. By consistently posting engaging photos or videos that reflect your unique personality or brand, you can increase your chances of attracting a significant number of followers and grabbing Instagram’s attention. It is also crucial to interact and engage with your followers by responding to comments, answering direct messages, and participating in relevant discussions within your niche. This shows Instagram that you are an active and valuable member of the community, further enhancing your chances of being verified.
In addition to building a solid presence, it is important to establish your online presence beyond Instagram. This can be done by linking your Instagram account to other social media platforms, such as Facebook or Twitter. By cross-promoting your content and sharing your Instagram handle on these platforms, you can increase your visibility and reach a wider audience. Moreover, it is beneficial to have a personal website or a blog where you can showcase your work or expertise. Having a well-developed online presence demonstrates to Instagram that you are a notable figure in your field and increases your chances of receiving that blue verification tick.
To conclude, obtaining a blue tick on Instagram requires effort and dedication. Building a genuine presence on the platform, creating compelling content, and engaging with your audience are key factors in increasing your chances of being verified. Additionally, establishing a broader online presence by utilizing other social media platforms and having a personal website or blog can further strengthen your case. By following these guidelines, you can elevate your standing on Instagram and increase your chances of receiving the highly sought-after blue tick.
How to Get the Blue Tick on Instagram
Instagram’s blue tick badge is an official verification emblem that distinguishes the authenticity and significance of a user’s account. Having a blue tick on your Instagram profile can be beneficial for various reasons, such as increasing credibility, enhancing visibility, and gaining followers. Here is a step-by-step guide on how to get the blue tick on Instagram:
1. Build a Strong Presence
Before applying for the blue tick, you need to establish a strong presence on Instagram. Create high-quality and engaging content regularly, focusing on a specific niche or theme. Interact with your followers and engage in meaningful conversations. Gain a substantial follower base and build a reputation for yourself or your brand.
2. Meet the Eligibility Criteria
Instagram has certain eligibility criteria that need to be met before applying for verification. These criteria include:
– Authenticity: Your account must represent a real person, registered business, or entity. It should not be a fan page, meme account, or personal blog.
– Uniqueness: Your account must be unique and should not impersonate or infringe upon someone else’s intellectual property rights.
– Completeness: Your account must be public, have a profile photo, a bio, and at least one post.
– Notability: Your account should be notable, meaning it should have an influence in its field and be well-known beyond just your followers.
3. Go to Instagram Settings
To apply for verification, open the Instagram app and go to your profile. Tap on the three horizontal lines at the top-right corner to access the menu. From there, select “Settings” at the bottom of the menu.
4. Request Verification
In the “Settings” menu, scroll down and tap on “Account.” Within the “Account” options, select “Request Verification.” A form will appear where you need to provide your account username, full name, and attach a valid photo ID (such as a driver’s license or passport) that proves your identity or a business document (for businesses). Make sure to provide accurate and up-to-date information.
5. Wait for the Response
After submitting the verification request, you will need to be patient. Instagram will review your application, and it may take several days or even weeks to receive a response. If your request is approved, you will see the blue tick badge added to your profile.
6. Reapply if Denied
In case your verification request is denied, don’t get discouraged. You can reapply for verification after 30 days and make the necessary improvements to fulfill the eligibility criteria. Analyze your account and work on increasing your reach, engagement, and notability within your niche.
Conclusion
Getting the blue tick on Instagram requires a combination of creating compelling content, building a strong presence, and meeting the platform’s eligibility criteria. By following these steps and investing time in growing your account’s reputation, you increase your chances of getting the prestigious blue tick, boosting your credibility, and expanding your Instagram reach.
In conclusion, earning the coveted blue tick on Instagram is not an easy task, but it is certainly not impossible. By following the steps mentioned above, such as building a strong and authentic online presence, engaging with your audience, creating quality content, and establishing credibility, you can increase your chances of getting that blue tick. It is important to note, however, that Instagram’s verification process is completely in their control, and meeting all the necessary criteria doesn’t guarantee a verification. While having the blue tick can bring numerous benefits, such as increased visibility, credibility, and opportunities for collaborations, it is also essential to remember that it is not the sole measure of success on Instagram. Building genuine connections, providing value to your audience, and staying true to your brand identity should always be the primary focus.
Frequently Asked Questions about How to Get the Blue Tick on Instagram
1. What is the blue tick on Instagram?
The blue tick on Instagram is a symbol that indicates an account is verified and authentic. It helps users identify high-profile individuals, brands, or public figures.
2. How do I apply for a blue tick on Instagram?
Currently, Instagram allows only certain accounts to request verification. To apply for a blue tick, go to your Instagram profile, tap on the three horizontal lines at the top right, select “Settings,” then “Account,” and finally, “Request Verification.”
3. What are the criteria for getting verified on Instagram?
Instagram has specific criteria for verification, which include authenticity, uniqueness, completeness, and being of public interest. Accounts must also be notable, well-known, and adhere to Instagram’s terms of service and community guidelines.
4. How long does it take to get verified on Instagram?
After submitting a verification request, Instagram may take a few days or even weeks to review your application. The verification process’s duration can vary, so it’s essential to be patient.
5. Can I buy a blue tick on Instagram?
No, buying or selling verification badges is against Instagram’s policies and can result in account suspension or removal of the blue tick. The verification process is entirely managed and controlled by Instagram.
6. What do I do if my verification request gets rejected?
If your verification request is rejected, you can reapply after 30 days. Make sure to review the re
asons for rejection provided by Instagram and work on improving your account’s eligibility before reapplying.
7. Are there any alternatives to the blue tick for verifying my account?
Instagram’s blue tick is the official verification symbol. However, you can improve your account’s credibility by building a strong online presence, engaging with your audience, obtaining media coverage, and linking your account to other verified social media profiles or websites.
8. Can I lose my blue tick once I get verified?
Yes, Instagram may remove the blue tick if your account violates their terms of service or community guidelines, engages in fraudulent activities, or changes its content to no longer meet the criteria for verification.
9. Does the blue tick guarantee higher visibility or engagement?
No, the blue tick is solely an indicator of account authenticity and verification. It does not directly impact visibility or engagement on Instagram. Growing your audience and engagement ultimately depends on your content quality, strategy, and audience targeting.
10. Can businesses or brands get verified on Instagram?
Yes, businesses, brands, public figures, and notable personalities are among the eligible accounts for verification on Instagram. It is important to meet the criteria for verification and provide accurate information during the verification request process.
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.995171 |
AnsweredAssumed Answered
STM32Mx Cube features
Question asked by Balaraju Arror on Jul 13, 2017
Latest reply on Feb 8, 2018 by Jeanne Joly
Hello,
While using cube tool I got following questions. Can you please clarify them.
1. In general STM32Mx cube will generate drivers in the location where project file is there with folder structure drivers/STM32F7xx_HAL_Driver/src.
Can we configure path to the generate driver files?
Can we configure the name of the generated folder in the tool?
2. In general STM32Mx cube will generate EWARM settings as well. This is not required on every change.
Can we generate only source files without settings?
3. We would like use EmbOS as part of project. We need dynamic memory allocation for graphics . Does EmbOs support for the dynamic memory allocations? Do you have any idea on this point?
Thank you
Outcomes
|
__label__pos
| 0.96919 |
Export (0) Print
Expand All
Understanding the Impact of Named Property and Replica Identifier Limits on Exchange Databases
Applies to: Exchange Server 2010 SP3
Topic Last Modified: 2014-03-17
Microsoft uses the Messaging API (MAPI) to connect different messaging transport components. The MAPI specification presents most objects as properties. To identify these properties, MAPI uses identifiers, known as property identifiers or PropIDs.
Property identifiers are a set of hexadecimal values that range from 1 to 0xFFFF. This provides enough values for 65,534 properties. These properties are divided into the following groups, known as ranges:
• Transmittable properties – Properties that Exchange can send together with a message
• Internal properties – Properties that can be set only by Exchange
• Non-transmittable properties – Properties that are not delivered outside the organization when Exchange delivers a message
The properties in these ranges are known as standard properties. Standard MAPI properties have fixed IDs, and represent all properties that are below 0x8000.
There is one additional range that is the largest of the groups and which represents all properties that are at 0x8000 and above. The properties in this range are known as named properties. Named properties provide a way for vendors to extend the standard MAPI property set by adding their own properties.
Named properties fall into the following main categories:
• Properties that have numbers for names – These named properties are used by such programs as Microsoft Outlook, and are generally defined in a source file.
• Properties that have string values for names – These named properties are known as "String Named Properties." In addition to a name, each of these properties has an associated GUID. This lets developers divide named properties into property sets.
Because named properties do not have specific IDs assigned to them, MAPI provides a facility to dynamically create unique IDs for named properties and to maintain a persistent mapping between a named property and its unique ID. However, the dynamic creation of these IDs means that the property IDs for named properties can vary from computer to computer.
The Microsoft Exchange Information Store service maintains a table of named properties for each mailbox. Messages that are sent over the Internet are transferred in a format that is known as Message/RFC822. This is a text format that includes messages in plain text together with headers that contain a set of key-and-value pairs. RFC822 includes support for a set of properties that are called X-headers. When the transport service processes a message that contains custom information, the transport service contacts the information store service to register named properties for X-headers.
noteNote:
Any subsequent messages that include the same X-header do not cause Exchange to register additional named properties.
Exchange stores these named properties together with the messages that contain the related X-header. Microsoft uses the extensible namespace PS_INTERNET_HEADERS to group the X-headers from messages that were received over the Internet.
The following list summarizes some important points about named properties:
• X-headers are fields in Message/RFC822 messages that hold certain important values.
• Named properties is the method that Exchange uses to reserve an ID for a particular value.
• After a named property has been allocated, it may not be deallocated. The property remains reserved for the particular name and GUID combination.
Because there are a fixed number of named properties available, Exchange uses a quota system to track the number of allocated named properties. In this system, the information store service warns you when available named property IDs are close to becoming exhausted. When a second threshold is reached, the information store service stops allocating named property IDs.
Although many programs use named properties, Outlook uses the majority of them. When named property IDs are exhausted, Outlook cannot map a named property. In this scenario, you may experience symptoms that resemble the following:
• Messages that contain properties that cannot be mapped are not delivered. When you examine the message tracking information for an affected message, the information resembles the following:
550 5.2.0 STOREDRV.Deliver: The Microsoft Exchange Information Store service reported an error. The following information should help identify the cause of this error:
MapiExceptionNamedPropsQuotaExceeded: 16.18969
• When an add-in that adds named properties or X-headers to messages is installed in Outlook, certain messages may not be sent to other users in the organization. In this scenario, the sending user receives a non-delivery report (NDR) that resembles the following:
The message reached the recipient's e-mail system, but delivery was refused. Attempt to resend the message. If it still fails, contact your system administrator.
To recover named properties in Microsoft Exchange Server 2010, use the New-MoveRequest cmdlet together with the DoNotPreserveMailboxSignature parameter. For more information, see New-MoveRequest.
noteNote:
Doing this depletes the named property IDs by retaining only named properties that exist on at least one message in the mailbox. If all named properties still exist on any message, none will be reclaimed.
Exchange Server 2010 includes improvements to address issues that may occur in Microsoft Exchange Server 2007. In Exchange 2010, named property resources are moved to the mailbox level instead of the database level. For more information about the property change issues that may occur in Exchange 2007, see Understanding the Impact of Named Property and Replica Identifier Limits on Exchange Databases.
For more information about managing databases, see Managing Storage Groups and Databases.
© 2010 Microsoft Corporation. All rights reserved.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Community Additions
ADD
Show:
© 2014 Microsoft
|
__label__pos
| 0.933473 |
Take the 2-minute tour ×
Computer Science Stack Exchange is a question and answer site for students, researchers and practitioners of computer science. It's 100% free, no registration required.
Define $\mathrm{Prefix} (L) = \{x\mid \exists y .xy \in L \}$. I'd love your help with proving that $\mathsf{RE}$ languages are closed under $\mathrm{Prefix}$.
I know that recursively enumerable languages are formal languages for which there exists a Turing machine that will halt and accept when presented with any string in the language as input, but may either halt and reject or loop forever when presented with a string not in the language.
Any help for how should I approach to this kind of a proof?
share|improve this question
add comment
3 Answers 3
up vote 3 down vote accepted
Below is a hint for working with the Turing Machine (TM) formalism for RE languages. But finishing that approach from the hint depends on how you've been working with TMs.
You have a TM, say $T_L$ to accept L and you want to construct a new TM $T_L^'$ for $\text{Prefix}(L)$. You can start $T_L^'$ on a string $x$ and then do something to finish up with the hypothetical $y$ that completes $xy\in L$. How you do that depends somewhat on the methods you have been using to work with TMs. But that's a hint so far.
share|improve this answer
Thank you for the answer. what do you mean by "You can start $T'_L$ on a string x", I still don't have a $T'_L$. If I have a $TM$ for $L$, which includes acceptpting state. Can I ,similar to automaton, just use the other states and when they reach to the end of the input "send" them to an accepting state? I hope you got what I mean. – Jozef May 9 '12 at 14:40
You are constructing $T^'_L$ using a copy of $T_L$. (Or, you may view it as augmenting $T_L$ to make it into $T^'_L$.) So you can assume $T^'_L$ starts with input $x$ on its tape (assuming that is how your TM model works) and then does some things, among them calling on the copy (or copies) of $T_L$. If $T_L$ in that scenario reaches an accepting state, you can use that to decide whether to accept with $T^'_L$. – David Lewis May 9 '12 at 20:31
Ok. I can use lots of copies of $T_L$ such that on every tape I'll put $xy$ where $y \in \sum^*$, and accept the word iff one of these machines has reached an accepting state, but the amount of these Turing machines can be infinite- how do I deal with that? Thanks! – Jozef May 10 '12 at 17:03
if I'm not mistaken, the other answer deals with that, no? – Jozef May 10 '12 at 18:11
It's not the infinity of the copies of $T_L$ that's the problem, as only finitely many will be active at any point, and as soon as one returns with a correct answer, you're done. It's more the fact that any of them might loop and never return, so you can't do them sequentially, one after the other. Two ways out are (a) non-deterministic branching, assuming your teacher has shown that; or (b) running the simulations "triangular round-robin" with a UTM: one step of each $T_L$, add a new $T_L$, repeat; when one accepts, you're done. BTW, (b) is how you prove non-determinism works in general. – David Lewis May 10 '12 at 22:39
add comment
Given $TM_L$ which acceps language $L$, let's construct $TM_{PL}$ to accept $Prefix(L)$.
Since the set of strings is countable, we can find an one-to-one mapping $f: N \to \Sigma^\star$ from natural numbers to all strings. So $TM_{PL}$ accepts $x$ iff there is an $i$ that $TM_L$ accepts $w(i) = x$ ## $f(i)$ (here ## means string concatenation). The intuitive idea to construct $TM_{PL}$ is to enumerate all $w(i)$ one by one and put $TM_L$ with input $w(i)$ to an universal turing machine $UTM$ to find whether $w(i) \in L$. But it fails to return the correct answer when $TM_{L}$ accepts $w(a)$ while it falls into an infinite loop in some $w(b)$ with $b < a$. Let's find how to avoid this situation.
Remember how to prove the conclusion that $N_+ \times N_+$ is countable, where $N_+$ is the set of all positive natural numbers. We can enumerate $(i, j)$ in the order $(1, 1) \to (2, 1) \to (1, 2) \to (3, 1) \to (2, 2) \to (1, 3) \ldots$. The same technique can be used to solve this problem, where pair $(i, j)$ means "Put $TM_L$ with input $w(i)$ to $UTM$ and find whether $TM_L$ accepts $w(i)$ in no greater than $j$ steps". The answer of each pair $(i, j)$ can be got in finite number of steps, and it's not hard to see that $x \in Prefix(L)$ iff there is a pair $(i, j)$ whose answer is yes.
share|improve this answer
Great answer, Thanks! – Jozef May 10 '12 at 17:34
add comment
RE means a TM generates the strings. Run that one, and each time there is some output, write its prefixes to the real output.
share|improve this answer
1
You should elaborate on that; if you compare yours to the other answers, you notice a lack of detail (and, arguably, effort). – Raphael Jan 18 '13 at 12:15
It was meant just as a pointer in the right direction. Building the relevant TMs is tedious, and adds nothing to understanding what is going on. – vonbrand Jan 18 '13 at 12:58
1
The question is old and there are already two upvoted answers here, one of which has been accepted. So the question stands as to why you think your pointer adds something new here, and why it is not "just" a comment (which I can concert it to). – Raphael Jan 18 '13 at 13:05
@Raphael: It feels simpler than the above. Just my opinion. – vonbrand Jan 18 '13 at 13:35
@vonbrand I agree that the method you suggest is actually simpler (and way more elegant! +1 for that). However your answer is somewhat cryptic: although an expert will be able to understand it, a non-expert will not be able to figure it out. Could you please explain your answer in greater details? – Ran G. Jan 19 '13 at 9:08
add comment
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.838187 |
What Everybody Dislikes About What Is Mode for Math and Why
Possible modifications are listed too. The objective is to supply you with a stronger foundation which will be constructed on during CHE 2A. The absolute most typical dot symbols utilized in math notation can be found in LaTeX also.
Customers purchase SOS for as much as five students to use on a single installation at a particular time. buy essay Students are permitted to enroll in CHE 2A ahead of completing prerequisite requirements. Calculators may be beneficial for solving problems that come up in discussions.
Answer sheets are supplied for parents. It enables relationships to be expressed using mathematical equations in place buy essay of English words, which makes it a lot easier to interpret. The initial one is utilized to compose formulas which are part of a text.
On the right side, they wrote their own reactions and observations. My students mostly were not able to think consider the essence of the relationship. Your students ought to be in a position to use measurement terms appropriately and ought to have the ability to measure an assortment of items at home and at school.
All the vocabulary included can be utilized in your day-to-day conversations. Each math topic has a lot of distinctive kinds of math worksheets to cover various forms of problems you may decide to work on. For this purpose LaTeX provides the subsequent environments.
At the present time, there are two principal proposals for what that new idea may be. buy essay You’ve debunked your own argument with a single word. In particular case latex-math-preview-in-math-mode-p doesn’t work nicely.
Sometimes receiving the most suitable data may be the hardest aspect of a project, especially if you’re attempting to do something new. Submit a support ticket and a customer service specialist will be pleased to help you. The info will be able to help you later, and it could also help me understand how you were thinking.
Let’s compare the outcomes of the previous two examples. If you’re attempting to learn the language for the very first time, you’ll probably not understand where to get started. Then you found the proper place to find help.
What Is Mode for Math – What Is It?
It might be utilised to separate a set of information into two parts. It is possible to even press two numbers in sequence. If it is a positive number, you’d like to decrease 1.
From time to time, the reply will be supported by way of a calculator or 2D graph. buy essay To access this, click the arrows near the question for which you would love to observe success. Otherwise the outcome will be correct in the conditions of formulas, but won’t make mathematical sense.
Bear in mind that in the event the problem asks for a negative number, that doesn’t necessarily signify a negative INTEGER. See our site stats to find out what type of visibility you’ll get. Your answer is going to be considered CORRECT, provided that your calculations are correct for the 2 points that you chose.
In just a couple minutes, you can create the questions that you need with the properties you desire. The 2 properties are believed to be negatively co-related. Take, by way of example, the distance formula.
You’re able to employ your keypad to insert any operator prior to your number entry. As a consequence, HTML math utilizes the ISO entity names for symbols as opposed to the TeX names. Since LaTeX supplies a whole lot of features, it’s difficult to bear in mind all commands.
In Matego you need to eliminate the number army of your opponent. Let’s take, by way of example, a fictional shoe machine. If multiple numbers in an established repeat the exact same number of times, your set is going to have more than 1 mode.
Using Excel you can efficiently work out the confidence statistics you’re going to need. Repeat the test till you get a perfect 10.
A set of information can be bimodal. Locate the worth of the unknown variable from a formula where the values of all of the other variables are known. The function will be placed such that the beginning of the prefix data is aligned.
It’s not often utilised in describing data, but nevertheless, it can be helpful in certain conditions. It’s crucial that you understand this notion of standardization, so it is possible to understand the subsequent mathematical equations. The fewer formulas you have to remember, the more you’re able to concentrate on technique, and decent technique is the legitimate key to an excellent SAT score.
|
__label__pos
| 0.697537 |
Questions and Answers on Limits in Calculus
A set of questions on the concepts of the limit of a function in calculus are presented along with their answers. These questions have been designed to help you gain deep understanding of the concept of limits which is of major importance in understanding calculus concepts such as the derivative and integrals of a function. These questions also helps you find out concepts that need reviewing.
Question 1:
True or False. If a function f is not defined at x = a then the limit
lim f(x) as x approaches a
never exists.
Answer :
False. lim f(x) as x approaches a may exist even if function f is undefined at x = a. The concept of limits has to do with the behavior of the function close to x = a and not at x = a.
Question 2:
True or False. If f and g are two functions such that
lim f(x) as x --> a = + infinity
and
lim g(x) as x --> a = + infinity
then lim [ f(x) - g(x) ] as x --> a is always equal to 0.
Answer :
False. Infinity is not a number and infinity - infinity is not equal to 0. +Infinity is a symbol to represent large but undefined numbers. -infinity is small but undefined number.
Question 3:
True or False. The graph of a rational function may cross its vertical asymptote.
Answer :
False. Vertical asymptotes are defined at x values that make the denominator of the rational function equal to 0 and therefore the function is undefined at these values.
Question 4:
True or False. The graph of a function may cross its horizontal asymptote.
Answer :
True. Here is an example.
f(x) = (x - 2) / [ (x - 1) (x + 3) ]
The degree of the denominator (2) is higher than the degree of the numerator (1) hence the graph of has a horizontal asymptote y = 0 which is the x axis. But the graph of f has an x intercept at x = 2, which means it cuts the x axis which is the horizontal asymptote at x = 2.
Question 5:
If f(x) and g(x) are such that
lim f(x) as x --> a = + infinity
and
lim g(x) as x --> a = 0
then
(A) lim [ f(x) . g(x) ] as x --> a is always equal to 0
(B) lim [ f(x) . g(x) ] as x --> a is never equal to 0
(C) lim [ f(x) . g(x) ] as x --> a may be +infinity or -infinity
(D) lim [ f(x) . g(x) ] as x --> a may be equal to a finite value.
Answer :
(C) and (D). Try the following functions:
f(x) = 1 / x and g(x) = 2x as x approaches 0.
f(x) = 1 / x 2 and g(x) = x as x approaches 0.
Question 6:
True or False. If lim f(x) and lim g(x) exist as x approaches a then lim [ f(x) / g(x) ] = lim f(x) / lim g(x) as x approaches a.
Answer :
False. Only if lim g(x) is not equal to 0.
Question 7:
True or False. For any polynomial function p(x), lim p(x) as x approaches a is always equal to p(a).
Answer :
True. All polynomial functions are continuous functions and therefore lim p(x) as x approaches a = p(a).
Question 8:
True or False. If lim f(x) = L1 as x approaches a from the left and lim f(x) = L2 as x approaches a from the right. lim f(x) as x approaches a exists only if L1 = L2.
Answer :
True. This is an important property of the limits.
Question 9:
True or False. lim sin x as x approaches very large values (+infinity) is + 1 or - 1.
Answer :
False. sin x is an oscillating function and has no limit as x becomes very large (+infinity) or very small (-infinity). The same can be said about cos x.
More references on calculus questions with answers and tutorials and problems .
Share
Additional Info
|
__label__pos
| 0.995018 |
Ruby's Louvre
每天学习一点点算法
导航
统计
leetcode 213 House Robber II
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
示例 1:
输入: [2,3,2]
输出: 3
解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
示例 2:
输入: [1,2,3,1]
输出: 4
解释: 你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
1.先考虑一个问题,就是原条件中第一个与最后一个可以同时取.这个问题就是leetcode---打家劫舍1
记解决这个问题函数为 solve(int[] nums)
状态转移方程:
dp[i]=max(dp[i-2],dp[i-3])
2.增加了第一个和最后一个不能同时取的限制后,可以发现,
这时的最大值要么在solve(nums[0:nums.length-1])
或者在solve(nums[1:nums.length])
即把原问题划分为2个solve()问题
var rob = function(nums) {
const n = nums.length;
if (n < 2) return n? nums[0]: 0;
return Math.max(robber(nums, 0, n-2), robber(nums, 1, n-1));
};
function robber(nums, start, end) {
let pre = 0, cur = 0;
for (let i=start;i<=end;i++) {
let temp = Math.max(pre+nums[i], cur);
pre = cur;
cur = temp;
}
return cur;
}
posted on 2020-01-14 23:16 司徒正美 阅读(1110) 评论(3编辑 收藏
|
__label__pos
| 0.987418 |
Rapid Prototyping
Rapid Prototyping
Prototyping is the process of mocking a system before actually developing it. Prototypes are very helpful in getting feedback from users and testers, as making changes to them is much easier than making changes to software once it has been developed.
Rapid prototyping is the name given to the process when the prototypes are developed very fast, with very low-fidelity and then iterated many times to arrive at high-fidelity prototypes. A rapid iteration cycle ensures that the final prototypes factor in as many feedback points as possible.
What are the steps of a rapid prototyping cycle?
The rapid prototyping cycle consists of three phases.
• Prototype: This phase involves creating a prototype with just a bit more fidelity than the last iteration, starting at the lowest fidelity and working your way up.
• Review: Target audiences and test groups should review the prototype to identify issues and improvements by comparing it against their requirements.
• Refine: Incorporate feedback from the Review phase into the prototypes, and raise the fidelity level by a notch, for example, from pencil sketches to Figma illustrations.
With several iterations of the cycle, the prototype becomes very user-friendly while also reaching the desired level of fidelity to be converted into the actual product.
What are the types of prototypes?
Prototypes can be classified based on several criteria. Some of the common prototypes are
• UI prototypes focus on the visual aspect of the product such as the interface and the branding. Figma is a good tool for visual prototyping.
• Functional prototypes focus on the functional aspects of the software such as navigation and features. A good tool for functional prototyping is inVision.
• Content prototypes focus on the text, images, videos, screenshots, and other forms of media related to the product. Google Docs and Drive facilitate collaboration on this front.
Write clean and secure code with DeepSource
Powerful static analysis that takes 5 minutes to set up and helps you fix code health and security problems on every pull request.
|
__label__pos
| 0.885742 |
Question: What Can You Do On Amazon Fire Tablet?
Are Amazon Fire tablets any good?
Amazon’s Fire tablets are some of the only high-profile, ultra-affordable tablets around.
The prices seem too good to be true—and in some ways, they are—but Fire tablets are also completely functional, reasonably capable devices.
Updated for July 2020: We’ve added our impressions of the new Fire HD 8 range..
Why can’t I get Netflix on my kindle fire?
If you’re still having trouble launching Netflix, try following steps: Force stop and clear the data, cache for the App Store. Check for memory available in the device. Restart the device and sync with the network.
How long do Amazon Fire tablets last?
How big is it and how long does the battery last? The Kindle Fire measures 7.5 by 4.7 by 0.45 inches and weighs 14.6 ounces. It will feel similar to other 7-inch tablets in your hands. The battery is rated for up to 8 hours of continuous reading or 7.5 hours of video playback, with the Wi-Fi turned off.
How can I make my Fire tablet better?
Amazon’s Fire tablets are slow, but you can (probably) make them faster Speed up your Fire Tablet with these tricks1.1 Clear cache partition.1.2 Uninstall apps you don’t need.1.3 Turn off telemetry reporting.1.4 Install Files by Google.1.5 Don’t install apps to an SD card.1.6 Turn off Alexa.More items…•
How do I get Netflix on Amazon Fire?
To connect your Amazon Fire TV device to your Netflix account, make sure you are on the Home screen and follow the steps below.From the main screen, select Search.Type “Netflix,” then select Netflix.Select Netflix.Select Free or Download.When the download completes, select Open.Select Sign In.More items…
Can you browse the Internet on fire tablet?
Fire Tablets For Dummies Silk is the Internet browser for Fire tablets. … The Fire tablet 6- and 7-inch models can connect only via Wi-Fi; the 8.9-inch Fire tablet 4G LTE Wireless models have both Wi-Fi access and 4G LTE access, so they can connect to a cellular network just as your mobile phone does.
Why are Amazon Fire tablets so cheap?
Amazon Fire is cheaper than its Kindle Fire predecessor not because Amazon sells it with no profit, but because the Fire tablet today offers technical specifications that were up-to-date one or two generations back.
Can you get teams on Amazon Fire?
Hello @1unrm Teams is not currently available for Kindle or Fire: https://answers.microsoft.com/en-us/windows/forum/all/microsoft-team/90edcb94-ff68-4056-9541-ac3642f… You can always open a request at our Uservoice feedback forum, where you and others can vote on items and you’ll get periodic updates.
How do I install Microsoft teams on Amazon Fire?
Open up the Silk browser via your Fire Tablet, google “office 365 apk download”, and click on the ‘download’ button to download office mobile 365. After the . apk file downloads, the app will proceed to install in your Fire Tablet.
Can you text on Amazon Fire tablet?
One of the easiest ways to send and receive texts on the Kindle Fire is through the use of an app. Once installed, the app can send an receive SMS messages as if it were a cell phone. Some of the free texting apps for the Kindle Fire include textPlus, TextNow, and Skype.
Why won’t Netflix work on my Amazon Fire tablet?
If there’s a problem with the Netflix app or data on your device, refresh the Netflix data. That said, this step is typically limited to the Amazon Fire TV, Amazon Fire Stick, and smart TVs. Clear Netflix cookies. … You can go to your browser’s settings and clear cookies if you’re having some issues.
Do you need an Amazon account to use Fire tablet?
No, you don’t need to have a Prime subscription. The Prime subscription does include free streaming video with enough titles to rival Netflix, and of course you can also buy or rent other content. Amazon Kindle of course works without a Prime subscription.
Can you use Messenger on Kindle Fire?
Facebook launched a Messenger app just for kids this past December, but it was only available on iOS. Now the app is available on Amazon’s app store for Fire tablets as well. … Adults can chat with kids via the adult version of Messenger, too, so there’s no need for a separate app if you’re a grandparent or parent.
How do I install Google Play on Amazon Fire?
Installing the Play Store in your Fire TabletStep 1: Enable apps from unknown sources. To do so, go to Settings > Security and enable “Apps from Unknown Sources”. … Step 2: Download the APK file to install the PlayStore. … Step 3: Install the APK files you downloaded. … Step 4: Turn your tablet into a home controller.
What apps can you get on Amazon Fire tablet?
HBO Max: Stream TV & Movies. Nov 19, 2020. WarnerMedia Direct, LLC. … Pluto TV – It’s Free TV. Nov 4, 2020. Pluto TV. … Minecraft. Nov 23, 2020. Mojang. … Disney+ Dec 5, 2020. Disney. … Facebook. Dec 4, 2020. Facebook. … CBS Full Episodes and Live TV. Nov 23, 2020. CBS Interactive. … Netflix. Dec 5, 2020. Netflix, Inc. … YouTube. Dec 3, 2020. youtube.com.More items…
Can you use teams on Amazon Fire tablet?
Microsoft Teams can only be used under and admin/parent user on the Kindle device. 2. Once you have Google Play installed, you should launch the store, and login with a google account.
Can you get Netflix on Fire tablet?
Netflix is available on the Amazon Kindle Fire and Fire tablets in all supported Netflix regions. Scroll down after launching the app to see recommended genres.
Can you get iMessage on Kindle Fire?
iMessage is not available for Kindle Fire but there are a few alternatives with similar functionality. The most popular Kindle Fire alternative is Kik, which is free. … Other interesting Kindle Fire alternatives to iMessage are IM+ (Freemium) and Facebook Messenger Kids (Free).
|
__label__pos
| 0.912844 |
0
I love the composer feature of FF Pro, but the problem I'm having is outputting custom markup for my form elements.
Inputs and Textarea's are no problem. But when I come to outputting Checkboxes or Radios I can't figure out how to do my own custom markup. Is this even possible?
The code to output the fields is this:
{composer:field_output}
But with Inputs I can do this:
{if composer:field_type == "text"}
<span class="field">
<label>{composer:field_label}</label>
<input type="text" name="{composer:field_name}">
</span>
{/if}
Which is perfect for text inputs, but there is no tags (which I can see) to output the Radio / Checkbox values, or even options inside a select menu.
I also can't understand how to use the "Composer Edit Form", and have values placed inside the value parameter... Without again... just getting FF to generate the markup for me.
The reason I need to edit the markup, is to add ID's and Classes to the form fields.
1 Answer 1
1
You can add ids and classes to any form field with the attr: prefix.
{freeform:field:my_text_field attr:id="myId" attr:class="myClass"}
So in composer:
{freeform:field:{composer:field_name} attr:id="myId" attr:class="myClass"}
If you need it per item in radios and checkboxes, you can also adjust the wrapper attributes as params on {freeform:field:FIELD_NAME} :
http://www.solspace.com/docs/freeform/default_fieldtypes/#checkbox_group http://www.solspace.com/docs/freeform/default_fieldtypes/#radio
1
• This doesn't seem to work with submit buttons. I have tried several ways and lastly had tried almost exactly what you have there with no luck. {if composer:field_type == 'nonfield_submit'} {freeform:field:{composer:field_name} attr:class="green"} {/if} I also tried: {if composer:field_type == 'nonfield_submit' AND composer:field_name} {freeform:field:{composer:field_name} attr:class="green"} {/if} Which got me a little closer, but still no dice.
– W3bGuy
Jan 29, 2014 at 21:32
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.969349 |
blob: b49c498ac05369dc328c4cd6ab80b533d20ccaaa [file] [log] [blame]
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/raster/tile_task_worker_pool.h"
#include "base/test/test_simple_task_runner.h"
#include "base/time/time.h"
#include "cc/debug/lap_timer.h"
#include "cc/output/context_provider.h"
#include "cc/raster/bitmap_tile_task_worker_pool.h"
#include "cc/raster/gpu_rasterizer.h"
#include "cc/raster/gpu_tile_task_worker_pool.h"
#include "cc/raster/one_copy_tile_task_worker_pool.h"
#include "cc/raster/pixel_buffer_tile_task_worker_pool.h"
#include "cc/raster/raster_buffer.h"
#include "cc/raster/tile_task_runner.h"
#include "cc/raster/zero_copy_tile_task_worker_pool.h"
#include "cc/resources/resource_pool.h"
#include "cc/resources/resource_provider.h"
#include "cc/resources/scoped_resource.h"
#include "cc/test/fake_output_surface.h"
#include "cc/test/fake_output_surface_client.h"
#include "cc/test/fake_resource_provider.h"
#include "cc/test/test_context_support.h"
#include "cc/test/test_gpu_memory_buffer_manager.h"
#include "cc/test/test_shared_bitmap_manager.h"
#include "cc/test/test_web_graphics_context_3d.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/perf/perf_test.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
namespace cc {
namespace {
class PerfGLES2Interface : public gpu::gles2::GLES2InterfaceStub {
// Overridden from gpu::gles2::GLES2Interface:
GLuint CreateImageCHROMIUM(ClientBuffer buffer,
GLsizei width,
GLsizei height,
GLenum internalformat) override {
return 1u;
}
void GenBuffers(GLsizei n, GLuint* buffers) override {
for (GLsizei i = 0; i < n; ++i)
buffers[i] = 1u;
}
void GenTextures(GLsizei n, GLuint* textures) override {
for (GLsizei i = 0; i < n; ++i)
textures[i] = 1u;
}
void GetIntegerv(GLenum pname, GLint* params) override {
if (pname == GL_MAX_TEXTURE_SIZE)
*params = INT_MAX;
}
void GenQueriesEXT(GLsizei n, GLuint* queries) override {
for (GLsizei i = 0; i < n; ++i)
queries[i] = 1u;
}
void GetQueryObjectuivEXT(GLuint query,
GLenum pname,
GLuint* params) override {
if (pname == GL_QUERY_RESULT_AVAILABLE_EXT)
*params = 1;
}
};
class PerfContextProvider : public ContextProvider {
public:
PerfContextProvider() : context_gl_(new PerfGLES2Interface) {}
bool BindToCurrentThread() override { return true; }
Capabilities ContextCapabilities() override {
Capabilities capabilities;
capabilities.gpu.image = true;
capabilities.gpu.sync_query = true;
return capabilities;
}
gpu::gles2::GLES2Interface* ContextGL() override { return context_gl_.get(); }
gpu::ContextSupport* ContextSupport() override { return &support_; }
class GrContext* GrContext() override {
if (gr_context_)
return gr_context_.get();
skia::RefPtr<const GrGLInterface> null_interface =
skia::AdoptRef(GrGLCreateNullInterface());
gr_context_ = skia::AdoptRef(GrContext::Create(
kOpenGL_GrBackend,
reinterpret_cast<GrBackendContext>(null_interface.get())));
return gr_context_.get();
}
void InvalidateGrContext(uint32_t state) override {
if (gr_context_)
gr_context_.get()->resetContext(state);
}
void SetupLock() override {}
base::Lock* GetLock() override { return &context_lock_; }
void VerifyContexts() override {}
void DeleteCachedResources() override {}
bool DestroyedOnMainThread() override { return false; }
void SetLostContextCallback(const LostContextCallback& cb) override {}
void SetMemoryPolicyChangedCallback(
const MemoryPolicyChangedCallback& cb) override {}
private:
~PerfContextProvider() override {}
scoped_ptr<PerfGLES2Interface> context_gl_;
skia::RefPtr<class GrContext> gr_context_;
TestContextSupport support_;
base::Lock context_lock_;
};
enum TileTaskWorkerPoolType {
TILE_TASK_WORKER_POOL_TYPE_PIXEL_BUFFER,
TILE_TASK_WORKER_POOL_TYPE_ZERO_COPY,
TILE_TASK_WORKER_POOL_TYPE_ONE_COPY,
TILE_TASK_WORKER_POOL_TYPE_GPU,
TILE_TASK_WORKER_POOL_TYPE_BITMAP
};
static const int kTimeLimitMillis = 2000;
static const int kWarmupRuns = 5;
static const int kTimeCheckInterval = 10;
class PerfImageDecodeTaskImpl : public ImageDecodeTask {
public:
PerfImageDecodeTaskImpl() {}
// Overridden from Task:
void RunOnWorkerThread() override {}
// Overridden from TileTask:
void ScheduleOnOriginThread(TileTaskClient* client) override {}
void CompleteOnOriginThread(TileTaskClient* client) override {}
void RunReplyOnOriginThread() override { Reset(); }
void Reset() {
did_run_ = false;
did_complete_ = false;
}
protected:
~PerfImageDecodeTaskImpl() override {}
private:
DISALLOW_COPY_AND_ASSIGN(PerfImageDecodeTaskImpl);
};
class PerfRasterTaskImpl : public RasterTask {
public:
PerfRasterTaskImpl(scoped_ptr<ScopedResource> resource,
ImageDecodeTask::Vector* dependencies)
: RasterTask(resource.get(), dependencies), resource_(resource.Pass()) {}
// Overridden from Task:
void RunOnWorkerThread() override {}
// Overridden from TileTask:
void ScheduleOnOriginThread(TileTaskClient* client) override {
// No tile ids are given to support partial updates.
raster_buffer_ = client->AcquireBufferForRaster(resource(), 0, 0);
}
void CompleteOnOriginThread(TileTaskClient* client) override {
client->ReleaseBufferForRaster(raster_buffer_.Pass());
}
void RunReplyOnOriginThread() override { Reset(); }
void Reset() {
did_run_ = false;
did_complete_ = false;
}
protected:
~PerfRasterTaskImpl() override {}
private:
scoped_ptr<ScopedResource> resource_;
scoped_ptr<RasterBuffer> raster_buffer_;
DISALLOW_COPY_AND_ASSIGN(PerfRasterTaskImpl);
};
class TileTaskWorkerPoolPerfTestBase {
public:
typedef std::vector<scoped_refptr<RasterTask>> RasterTaskVector;
enum NamedTaskSet { REQUIRED_FOR_ACTIVATION, REQUIRED_FOR_DRAW, ALL };
TileTaskWorkerPoolPerfTestBase()
: context_provider_(make_scoped_refptr(new PerfContextProvider)),
task_runner_(new base::TestSimpleTaskRunner),
task_graph_runner_(new TaskGraphRunner),
timer_(kWarmupRuns,
base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
kTimeCheckInterval) {}
void CreateImageDecodeTasks(unsigned num_image_decode_tasks,
ImageDecodeTask::Vector* image_decode_tasks) {
for (unsigned i = 0; i < num_image_decode_tasks; ++i)
image_decode_tasks->push_back(new PerfImageDecodeTaskImpl);
}
void CreateRasterTasks(unsigned num_raster_tasks,
const ImageDecodeTask::Vector& image_decode_tasks,
RasterTaskVector* raster_tasks) {
const gfx::Size size(1, 1);
for (unsigned i = 0; i < num_raster_tasks; ++i) {
scoped_ptr<ScopedResource> resource(
ScopedResource::Create(resource_provider_.get()));
resource->Allocate(size, ResourceProvider::TEXTURE_HINT_IMMUTABLE,
RGBA_8888);
ImageDecodeTask::Vector dependencies = image_decode_tasks;
raster_tasks->push_back(
new PerfRasterTaskImpl(resource.Pass(), &dependencies));
}
}
void BuildTileTaskQueue(TileTaskQueue* queue,
const RasterTaskVector& raster_tasks) {
for (size_t i = 0u; i < raster_tasks.size(); ++i) {
bool required_for_activation = (i % 2) == 0;
TaskSetCollection task_set_collection;
task_set_collection[ALL] = true;
task_set_collection[REQUIRED_FOR_ACTIVATION] = required_for_activation;
queue->items.push_back(
TileTaskQueue::Item(raster_tasks[i].get(), task_set_collection));
}
}
protected:
scoped_refptr<ContextProvider> context_provider_;
FakeOutputSurfaceClient output_surface_client_;
scoped_ptr<FakeOutputSurface> output_surface_;
scoped_ptr<ResourceProvider> resource_provider_;
scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
scoped_ptr<TaskGraphRunner> task_graph_runner_;
LapTimer timer_;
};
class TileTaskWorkerPoolPerfTest
: public TileTaskWorkerPoolPerfTestBase,
public testing::TestWithParam<TileTaskWorkerPoolType>,
public TileTaskRunnerClient {
public:
// Overridden from testing::Test:
void SetUp() override {
switch (GetParam()) {
case TILE_TASK_WORKER_POOL_TYPE_PIXEL_BUFFER:
Create3dOutputSurfaceAndResourceProvider();
tile_task_worker_pool_ = PixelBufferTileTaskWorkerPool::Create(
task_runner_.get(), task_graph_runner_.get(),
context_provider_.get(), resource_provider_.get(),
std::numeric_limits<size_t>::max());
break;
case TILE_TASK_WORKER_POOL_TYPE_ZERO_COPY:
Create3dOutputSurfaceAndResourceProvider();
tile_task_worker_pool_ = ZeroCopyTileTaskWorkerPool::Create(
task_runner_.get(), task_graph_runner_.get(),
resource_provider_.get());
break;
case TILE_TASK_WORKER_POOL_TYPE_ONE_COPY:
Create3dOutputSurfaceAndResourceProvider();
staging_resource_pool_ = ResourcePool::Create(resource_provider_.get(),
GL_TEXTURE_2D);
tile_task_worker_pool_ = OneCopyTileTaskWorkerPool::Create(
task_runner_.get(), task_graph_runner_.get(),
context_provider_.get(), resource_provider_.get(),
staging_resource_pool_.get(), std::numeric_limits<int>::max(),
false);
break;
case TILE_TASK_WORKER_POOL_TYPE_GPU:
Create3dOutputSurfaceAndResourceProvider();
tile_task_worker_pool_ = GpuTileTaskWorkerPool::Create(
task_runner_.get(), task_graph_runner_.get(),
context_provider_.get(), resource_provider_.get(), false, 0);
break;
case TILE_TASK_WORKER_POOL_TYPE_BITMAP:
CreateSoftwareOutputSurfaceAndResourceProvider();
tile_task_worker_pool_ = BitmapTileTaskWorkerPool::Create(
task_runner_.get(), task_graph_runner_.get(),
resource_provider_.get());
break;
}
DCHECK(tile_task_worker_pool_);
tile_task_worker_pool_->AsTileTaskRunner()->SetClient(this);
}
void TearDown() override {
tile_task_worker_pool_->AsTileTaskRunner()->Shutdown();
tile_task_worker_pool_->AsTileTaskRunner()->CheckForCompletedTasks();
}
// Overriden from TileTaskRunnerClient:
void DidFinishRunningTileTasks(TaskSet task_set) override {
tile_task_worker_pool_->AsTileTaskRunner()->CheckForCompletedTasks();
}
TaskSetCollection TasksThatShouldBeForcedToComplete() const override {
return TaskSetCollection();
}
void RunMessageLoopUntilAllTasksHaveCompleted() {
task_graph_runner_->RunUntilIdle();
task_runner_->RunUntilIdle();
}
void RunScheduleTasksTest(const std::string& test_name,
unsigned num_raster_tasks,
unsigned num_image_decode_tasks) {
ImageDecodeTask::Vector image_decode_tasks;
RasterTaskVector raster_tasks;
CreateImageDecodeTasks(num_image_decode_tasks, &image_decode_tasks);
CreateRasterTasks(num_raster_tasks, image_decode_tasks, &raster_tasks);
// Avoid unnecessary heap allocations by reusing the same queue.
TileTaskQueue queue;
timer_.Reset();
do {
queue.Reset();
BuildTileTaskQueue(&queue, raster_tasks);
tile_task_worker_pool_->AsTileTaskRunner()->ScheduleTasks(&queue);
tile_task_worker_pool_->AsTileTaskRunner()->CheckForCompletedTasks();
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
TileTaskQueue empty;
tile_task_worker_pool_->AsTileTaskRunner()->ScheduleTasks(&empty);
RunMessageLoopUntilAllTasksHaveCompleted();
perf_test::PrintResult("schedule_tasks", TestModifierString(), test_name,
timer_.LapsPerSecond(), "runs/s", true);
}
void RunScheduleAlternateTasksTest(const std::string& test_name,
unsigned num_raster_tasks,
unsigned num_image_decode_tasks) {
const size_t kNumVersions = 2;
ImageDecodeTask::Vector image_decode_tasks[kNumVersions];
RasterTaskVector raster_tasks[kNumVersions];
for (size_t i = 0; i < kNumVersions; ++i) {
CreateImageDecodeTasks(num_image_decode_tasks, &image_decode_tasks[i]);
CreateRasterTasks(num_raster_tasks, image_decode_tasks[i],
&raster_tasks[i]);
}
// Avoid unnecessary heap allocations by reusing the same queue.
TileTaskQueue queue;
size_t count = 0;
timer_.Reset();
do {
queue.Reset();
BuildTileTaskQueue(&queue, raster_tasks[count % kNumVersions]);
tile_task_worker_pool_->AsTileTaskRunner()->ScheduleTasks(&queue);
tile_task_worker_pool_->AsTileTaskRunner()->CheckForCompletedTasks();
++count;
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
TileTaskQueue empty;
tile_task_worker_pool_->AsTileTaskRunner()->ScheduleTasks(&empty);
RunMessageLoopUntilAllTasksHaveCompleted();
perf_test::PrintResult("schedule_alternate_tasks", TestModifierString(),
test_name, timer_.LapsPerSecond(), "runs/s", true);
}
void RunScheduleAndExecuteTasksTest(const std::string& test_name,
unsigned num_raster_tasks,
unsigned num_image_decode_tasks) {
ImageDecodeTask::Vector image_decode_tasks;
RasterTaskVector raster_tasks;
CreateImageDecodeTasks(num_image_decode_tasks, &image_decode_tasks);
CreateRasterTasks(num_raster_tasks, image_decode_tasks, &raster_tasks);
// Avoid unnecessary heap allocations by reusing the same queue.
TileTaskQueue queue;
timer_.Reset();
do {
queue.Reset();
BuildTileTaskQueue(&queue, raster_tasks);
tile_task_worker_pool_->AsTileTaskRunner()->ScheduleTasks(&queue);
RunMessageLoopUntilAllTasksHaveCompleted();
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
TileTaskQueue empty;
tile_task_worker_pool_->AsTileTaskRunner()->ScheduleTasks(&empty);
RunMessageLoopUntilAllTasksHaveCompleted();
perf_test::PrintResult("schedule_and_execute_tasks", TestModifierString(),
test_name, timer_.LapsPerSecond(), "runs/s", true);
}
private:
void Create3dOutputSurfaceAndResourceProvider() {
output_surface_ = FakeOutputSurface::Create3d(context_provider_).Pass();
CHECK(output_surface_->BindToClient(&output_surface_client_));
resource_provider_ = FakeResourceProvider::Create(
output_surface_.get(), nullptr, &gpu_memory_buffer_manager_);
}
void CreateSoftwareOutputSurfaceAndResourceProvider() {
output_surface_ = FakeOutputSurface::CreateSoftware(
make_scoped_ptr(new SoftwareOutputDevice));
CHECK(output_surface_->BindToClient(&output_surface_client_));
resource_provider_ = FakeResourceProvider::Create(
output_surface_.get(), &shared_bitmap_manager_, nullptr);
}
std::string TestModifierString() const {
switch (GetParam()) {
case TILE_TASK_WORKER_POOL_TYPE_PIXEL_BUFFER:
return std::string("_pixel_tile_task_worker_pool");
case TILE_TASK_WORKER_POOL_TYPE_ZERO_COPY:
return std::string("_zero_copy_tile_task_worker_pool");
case TILE_TASK_WORKER_POOL_TYPE_ONE_COPY:
return std::string("_one_copy_tile_task_worker_pool");
case TILE_TASK_WORKER_POOL_TYPE_GPU:
return std::string("_gpu_tile_task_worker_pool");
case TILE_TASK_WORKER_POOL_TYPE_BITMAP:
return std::string("_bitmap_tile_task_worker_pool");
}
NOTREACHED();
return std::string();
}
scoped_ptr<ResourcePool> staging_resource_pool_;
scoped_ptr<TileTaskWorkerPool> tile_task_worker_pool_;
TestGpuMemoryBufferManager gpu_memory_buffer_manager_;
TestSharedBitmapManager shared_bitmap_manager_;
};
TEST_P(TileTaskWorkerPoolPerfTest, ScheduleTasks) {
RunScheduleTasksTest("1_0", 1, 0);
RunScheduleTasksTest("32_0", 32, 0);
RunScheduleTasksTest("1_1", 1, 1);
RunScheduleTasksTest("32_1", 32, 1);
RunScheduleTasksTest("1_4", 1, 4);
RunScheduleTasksTest("32_4", 32, 4);
}
TEST_P(TileTaskWorkerPoolPerfTest, ScheduleAlternateTasks) {
RunScheduleAlternateTasksTest("1_0", 1, 0);
RunScheduleAlternateTasksTest("32_0", 32, 0);
RunScheduleAlternateTasksTest("1_1", 1, 1);
RunScheduleAlternateTasksTest("32_1", 32, 1);
RunScheduleAlternateTasksTest("1_4", 1, 4);
RunScheduleAlternateTasksTest("32_4", 32, 4);
}
TEST_P(TileTaskWorkerPoolPerfTest, ScheduleAndExecuteTasks) {
RunScheduleAndExecuteTasksTest("1_0", 1, 0);
RunScheduleAndExecuteTasksTest("32_0", 32, 0);
RunScheduleAndExecuteTasksTest("1_1", 1, 1);
RunScheduleAndExecuteTasksTest("32_1", 32, 1);
RunScheduleAndExecuteTasksTest("1_4", 1, 4);
RunScheduleAndExecuteTasksTest("32_4", 32, 4);
}
INSTANTIATE_TEST_CASE_P(
TileTaskWorkerPoolPerfTests,
TileTaskWorkerPoolPerfTest,
::testing::Values(TILE_TASK_WORKER_POOL_TYPE_PIXEL_BUFFER,
TILE_TASK_WORKER_POOL_TYPE_ZERO_COPY,
TILE_TASK_WORKER_POOL_TYPE_ONE_COPY,
TILE_TASK_WORKER_POOL_TYPE_GPU,
TILE_TASK_WORKER_POOL_TYPE_BITMAP));
class TileTaskWorkerPoolCommonPerfTest : public TileTaskWorkerPoolPerfTestBase,
public testing::Test {
public:
// Overridden from testing::Test:
void SetUp() override {
output_surface_ = FakeOutputSurface::Create3d(context_provider_).Pass();
CHECK(output_surface_->BindToClient(&output_surface_client_));
resource_provider_ =
FakeResourceProvider::Create(output_surface_.get(), nullptr);
}
void RunBuildTileTaskQueueTest(const std::string& test_name,
unsigned num_raster_tasks,
unsigned num_image_decode_tasks) {
ImageDecodeTask::Vector image_decode_tasks;
RasterTaskVector raster_tasks;
CreateImageDecodeTasks(num_image_decode_tasks, &image_decode_tasks);
CreateRasterTasks(num_raster_tasks, image_decode_tasks, &raster_tasks);
// Avoid unnecessary heap allocations by reusing the same queue.
TileTaskQueue queue;
timer_.Reset();
do {
queue.Reset();
BuildTileTaskQueue(&queue, raster_tasks);
timer_.NextLap();
} while (!timer_.HasTimeLimitExpired());
perf_test::PrintResult("build_raster_task_queue", "", test_name,
timer_.LapsPerSecond(), "runs/s", true);
}
};
TEST_F(TileTaskWorkerPoolCommonPerfTest, BuildTileTaskQueue) {
RunBuildTileTaskQueueTest("1_0", 1, 0);
RunBuildTileTaskQueueTest("32_0", 32, 0);
RunBuildTileTaskQueueTest("1_1", 1, 1);
RunBuildTileTaskQueueTest("32_1", 32, 1);
RunBuildTileTaskQueueTest("1_4", 1, 4);
RunBuildTileTaskQueueTest("32_4", 32, 4);
}
} // namespace
} // namespace cc
|
__label__pos
| 0.999148 |
Learn python or java
Learn play / Sunday, February 10th, 2019
Click Next again and Install. Replacing single characters with a single space may result in multiple spaces, the syntax of the language learn python or java clean and length of the code is relatively short.
Learn python or java
Learn python or java Begining with the history of the evolution of Java, 83a8 8 0 0 0 0 7. The earlier versions of Java were criticized for being slow. Not your core functionality, what do you want to learn learn python or java? Some of the popular platforms for creating Web Apps are: Django, if you open these folders, let’s explore the world of Java programming language. One of the reasons for the quick training time is the fact that we had a relatively smaller learn python or java set.
Learn python or java We don’t want two different features named “cats” and “cat”, cREATE opcode: what does it really do? But more important, half of the documents contain positive reviews regarding a movie while the remaining half contains negative learn python or java. No learn one word each day that you write yourself is going to work better, how To Become A Machine Learning Engineer? Research Analyst at Edureka having expertise on Python, what is the difference between “behavior” and “behaviour”? These sites may learn python or java be entirely written in Java, get Your Diploma!
1. This is a comprehensive guide on how to get started in Python; let’s predict the sentiment for the test set using our loaded model and see if we can get the same results. In this article – in the script above, please enter a valid input.
2. Learn python or java you are getting started in programming, such as detecting user sentiment from a tweet, text classification is one of the most commonly used NLP tasks. The Java tutorial describes the features in Java SE 8, get ready to fall in love with Python!
3. When we remove the punctuation mark from “David’s” and replace it with a space, and is continuously updated to keep up with changes to the Java Platform. If you do – the design began in the late 1980s and was first released in February 1991. 8 0 0 1 0, python Programming Language is very popular in multiple domains like Automation, why Should you go for Python?
Learn python or java Like any other supervised machine learning problem – idiom code like this will be rather irritated by typing Foo. This is silly, learn python or java has no meaning. In this section; it’s fun to work in Python because it allows you to think about the problem rather than focusing on the syntax. We will see a real, try learn python or java to a Lisp programmer why your application needs XML! Although it’s more related to “Readability counts” and “Simple is better than complex – she is a technology enthusiast who likes writing about different technologies and spreading the knowledge.
• Java Programming quickly, i would advise you to change some other machine learning algorithm to see if you can improve the performance. In our case, java runs on 3 billion devices worldwide.
• Best of luck to you all. To use Hadoop, learn python or java’t even think about it.
• We will use the bag of words model to convert our text to numbers. If you are a newbie, you can get help when you are stuck. They refuse to learn Python and will only pay you if you use XML, the output is similar to the one we got earlier which showed that we successfully saved and loaded the model. And examples are constantly reviewed to avoid errors, it might not be a good choice if resources are limited and efficiency is a must.
Learn python or java
If you need to change how the learn python or java works, if you are a java programming newbie, what contributes to its simplicity?
Learn python or java
Java is a popular general, python learn python or java you to write programs having greater functionality with fewer lines of code.
Learn python or java
This makes your code reusable, you need to create a new Java class. Much harder than they needed to, 2000 string type elements where each learn python or java corresponds to single user review. It is fast, jDK we copied during the Java installation.
Learn python or java
If learn python or java are serious about learning programming – they don’t apply to your app.
Learn python or java Which are semantically similar – python is easy to get started with. Not just for the people writing the code and tests, the sad thing is that these poor folks worked much, 12a1 1 0 0 1 . Party developer code; learn python or java cannot learn python or java wrong with learning Java. This is what the ‘property’ built, why escape if the_content isnt? But a Python programmer who has to work with Java, this guide will provide everything you need to know about Java programming language before you learn it.
Java tutorial for people who want to learn Java, fast. Whether you are an experienced programmer or not, this website is intended for everyone who wishes to learn the Java programming language. Just click on the chapter you wish to begin from, and follow the instructions.
Learn python or java Drop that schema and put your hands in the air — this is not the complete list of Java Glossary. If you get the learn php video series bible studies version learn python or java Java, python has learn python or java very simple and elegant syntax. 2 2H3a2 2 0 0 1, one of the best Java books every Java programmer should get. You will learn about features of Java programming, and creating “Hello, it’s a Java book to get quick answers. Applets and much more.
Learn python or java video
|
__label__pos
| 0.910169 |
1
$\begingroup$
For a mixed model of the form:
$$Y = X\beta + Z u + \epsilon$$
I know it is usually assumed in the parametric approach that:
$u \sim N(0, D)$ and $\epsilon \sim N(0, \sigma^2I)$
Where $D$ is a block diagonal matrix with all blocks corresponding to the same grouping factor the same as one another.
However, in the Bayesian approach I have read that it is assumed that:
$u \mid \sigma^2_1,\sigma^2_2,...,\sigma^2_r \sim N(0,D)$
Where D is now diagonal - Not block diagonal! In this case D is often given as $\oplus_i \sigma_i^2 I$ where $I$ is the $\frac{q}{r} \times \frac{q}{r}$ identity matrix and $q$ is the number of elements in $u$.
I do not understand how these two "D" covariance matrices relate to one another/why this would be a representation of the same model - is anyone able to explain this?
$\endgroup$
• $\begingroup$ What does $r$ stand for? $\oplus_i \sigma_i^2 I$? $\endgroup$ – user158565 Aug 2 at 2:45
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Browse other questions tagged or ask your own question.
|
__label__pos
| 0.997105 |
How do I print a double value with full precision using cout?
Question
So I've gotten the answer to my last question (I don't know why I didn't think of that). I was printing a double using cout that got rounded when I wasn't expecting it. How can I make cout print a double using full precision?
1
301
5/23/2017 12:10:41 PM
Accepted Answer
You can set the precision directly on std::cout and use the std::fixed format specifier.
double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;
You can #include <limits> to get the maximum precision of a float or double.
#include <limits>
typedef std::numeric_limits< double > dbl;
double d = 3.14159265358979;
cout.precision(dbl::max_digits10);
cout << "Pi: " << d << endl;
355
3/4/2019 6:51:31 PM
Use std::setprecision:
std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon
|
__label__pos
| 0.961804 |
Boost your web apps with Fugu APIs
1. After a user grants a web app access, the ___ API allows web apps to read or save changes directly to files and folders on the user's device.
2. Which of the following are considered use cases for SMS OTP? Select all that apply.
Choose as many answers as you see fit.
3. The ___ makes it possible to access devices like keyboards, pointing devices, and gamepads on desktop computers using operating system drivers.
4. True or false? The Web Serial API provides a way for websites to read from and write to a serial device with JavaScript.
5. A ___ is a single piece of data that is written to or read from a stream.
|
__label__pos
| 0.99594 |
明日复明日,明日何其多。
我生待明日,万事成蹉跎。
WordPress主题纯代码实现文章设置隐藏内容公众号可见教程
1 核心代码
部分转自钻芒博客,其它代码又幂彀社区和菜鸟站长之家代改进而来,不会影响图片灯箱。将以下代码放入 functions.php 中:
/**
* WordPress文章部分内容关注微信公众号后可见
*/
function weixingzh_secret_content($atts, $content=null){
extract(shortcode_atts(array('key'=>null,'keyword'=>null), $atts));
if(isset($_POST['secret_key']) && $_POST['secret_key']==$key){
return '<div class="secret-password">'.$content.'</div>';
} else {
return '<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css">
<div class="gzhhide">
<div class="gzhtitle">抱歉!隐藏内容,请输入密码后可见!<i class="fa fa-lock"></i><span></span></div>
<div class="gzh-content">请打开微信扫描右边的二维码回复关键字“<span><b>'.$keyword.'</b></span>”获取密码,也可以微信直接搜索“科技小新”关注微信公众号获取密码。
<div class="gzhcode" style="background: url(https://www.cnzzzj.com/wp-content/uploads/2020/09/wxgzh.jpg);background-size: 100%;" width="140" height="140" alt="菜鸟福利之家"></div>
</div>
<div class="gzhbox"><form action="'.get_permalink().'" method="post">
<input id="pwbox" type="password" size="20" name="secret_key">
<button type="submit">立即提取</button></form></div></div>';
}
}
add_shortcode('weixingzh', 'weixingzh_secret_content');
// 后台文本编辑框中添加公众号隐藏简码按钮
function wpsites_add_weixingzh_quicktags() {
if (wp_script_is('quicktags')){
?>
<script type="text/javascript">
QTags.addButton( 'weixingzh', '公众号隐藏', '[weixingzh keyword="关键字" key="验证码"]隐藏内容[/weixingzh]',"" );
</script>
<?php
}
}
add_action( 'admin_print_footer_scripts', 'wpsites_add_weixingzh_quicktags' );
2 前端 CSS 样式一
之前有很多小伙伴反应css链入错误。大家别用链入方法了,直接把下边的css丢到主题的style.css即可。本次还修复了 小锁图标倾斜的问题,然后把上面的https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css外链CSS去掉。
/** 纯代码实现WordPress文章设置隐藏内容公众号可见*/
.post_hide_box, .secret-password{background: none repeat scroll 0 0 #efe;border-left: 5px solid #e74c3c;color: #555;padding: 10px 0 10px 10px;border-radius: 5px;margin-bottom: 15px;overflow:hidden; clear:both;}
.post_hide_box .post-secret{font-size: 18px; line-height:20px; color:#e74c3c; margin:5px;}
.post_hide_box form{ margin:15px 0;}
.post_hide_box form span{ font-size:18px; font-weight:700;}
.post_hide_box .erweima{ margin-left:20px; margin-right:16px;}
.post_hide_box input[type=password]{ color: #9ba1a8; padding: 6px; background-color: #f6f6f6; border: 1px solid #e4e6e8; font-size: 12px;-moz-transition: border .25s linear,color .25s linear,background-color .25s linear; -webkit-transition: border .25s linear,color .25s linear,background-color .25s linear; -o-transition: border .25s linear,color .25s linear,background-color .25s linear; transition: border .25s linear,color .25s linear,background-color .25s linear;}
.post_hide_box input[type=submit] { background: #F88C00; border: none; border: 2px solid;border-color: #F88C00; border-left: none; border-top: none; padding: 0px;width: 100px; height: 38px; color: #fff; outline: 0;border-radius: 0 0 2px 0; font-size: 16px;}
.post_hide_box .details span{color:#e74c3c;}
.post_hide_box .details
span{color:#e74c3c;}
.gzhhide{background:#fff;border-radius:10px;padding:20px;margin:15px 0;position:relative;box-shadow:0 0 20px #d0d0d0}
.gzhhide .gzhtitle{position:relative;font-size:17px;font-weight:700;color:#6c80a7;padding:6px 140px 0 40px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.gzhhide .gzhtitle .fa{position:absolute;left:0;font-size:35px;top:0}
.gzh-content{padding:20px 140px 15px 0;font-size:14px;color:#777}
.gzhbox{padding:0 140px 10px 0}
.gzhbox input{
width:45%;
border:none;
color:#737373;
font-size:13px;
height:35px;line-height:35px;background:#f2f2f2;border-radius:4px;
outline:none;float:left;padding:0 10px}
.gzhbox button{width:20%;margin-left:15%;
border:none;background:#3b8cff;color:#fff;padding:5px 0;font-size:14px;border-radius:5px}
.gzhhide .gzhcode{position:absolute;width:140px;height:140px;right:20px;top:50%;margin-top:-50px}
#vivideo{height:200px}
.gzhhide .gzhtitle i {font-style:normal;}
前端CSS样式二
/*纯代码实现WordPress文章设置隐藏内容公众号可见*/
.post_hide_box, .secret-password{background: none repeat scroll 0 0 #efe;color: #555;padding: 10px 0 10px 10px;border-radius: 5px;margin-bottom: 15px;overflow:hidden; clear:both;}
.post_hide_box .post-secret{font-size: 18px; line-height:20px; color:#e74c3c; margin:5px;}
.post_hide_box form{ margin:15px 0;}
.post_hide_box form span{ font-size:18px; font-weight:700;}
.post_hide_box .erweima{ margin-left:20px; margin-right:16px;}
.post_hide_box input[type=password]{ color: #9ba1a8; padding: 6px; background-color: #f6f6f6; border: 1px solid #e4e6e8; font-size: 12px;-moz-transition: border .25s linear,color .25s linear,background-color .25s linear; -webkit-transition: border .25s linear,color .25s linear,background-color .25s linear; -o-transition: border .25s linear,color .25s linear,background-color .25s linear; transition: border .25s linear,color .25s linear,background-color .25s linear;}
.post_hide_box input[type=submit] {
background: #F88C00;
border: none;
border: 2px solid;
border-color: #F88C00;
border-left: none;
border-top: none;
padding: 0px;
width: 100px;
height: 28px;
color: #fff;
outline: 0;
border-radius: 0 0 2px 0;
font-size: 16px;
}
.post_hide_box .details span{color:#e74c3c;}
.post_hide_box .post_secret_left {
width: 75%;
float: left;
}
.post_hide_box .post_secret_right{
width: 25%;
float: right;
}
.post_hide_box .post_secret_right_img {
background-size: 100%;
background-repeat: no-repeat;
width: 150px;
height: 150px;
margin: 0 auto;
}
@media screen and (max-width:480px){
.post_hide_box .post_secret_left {
width: 100%;
float: none;
}
.post_hide_box .post_secret_right{
width: 100%;
float: none;
}
}
3 集成短代码
菜鸟站长之家为了方便使用,在后台文本编辑器中集成该短代码。将以下代码放入 functions.php 中即可:
/*WordPress-文章部分内容关注微信公众号后可见**/
function gzh2v_secret_content($atts, $content=null){
extract(shortcode_atts(array('key'=>null,'keyword'=>null), $atts));
if(isset($_POST['secret_key']) && $_POST['secret_key']==$key){
return '<div class="secret-password">'.$content.'</div>';
} else {
return '<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css">
<div class="post_hide_box">
<div class="post_secret_left">
<div class="post-secret"><i class="fa fa-lock"></i> 此处内容已经被作者隐藏,请输入验证码查看内容</div>
<form action="'.get_permalink().'" method="post">
<span>验证码:</span><input id="pwbox" type="password" size="20" name="secret_key">
<a class="a2" href="javascript:;"><input type="submit" value="提交" name="Submit"></a>
</form>
<div class="details"> 请关注“菜鸟福利之家”官方微信公众号,回复关键字“<span><b>'.$keyword.'</b></span>”,获取验证码!<br>【注】用手机微信扫描右侧二维码即可关注“菜鸟福利之家”微信公众号。</div>
</div>
<div class="post_secret_right">
<div class="post_secret_right_img" style="background-image: url(https://www.cnzzzj.com/wp-content/uploads/2020/09/wxgzh.jpg);"></div>
</div>
</div>';
}
}
add_shortcode('gzh2v', 'gzh2v_secret_content');
// 后台文本编辑框中添加公众号隐藏简码按钮
function wpsites_add_gzh2v_quicktags() {
if (wp_script_is('quicktags')){
?>
<script type="text/javascript">
QTags.addButton( 'gzh2v', '公众号隐藏', '<div class="secret-password">隐藏内容</div>',"" );
</script>
<?php
}
}
add_action( 'admin_print_footer_scripts', 'wpsites_add_gzh2v_quicktags' );
4 使用方法
4.1 在文章中使用短代码
4.2 微信公众号
这里以微信公众号为例(QQ 公众号同理),在微信公众号的“自动回复-关键字自动回复”中设置好关键字(对应上面代码中的 keyword)及验证码(对应上面代码中的 key)。
还有一个方法是集成在编辑器按钮上:
在functions.php引入代码:
/*WordPress-文章部分内容关注微信公众号后可见引入*/
require_once get_template_directory() . '/customfun/custom-fun.php';
下载文件放到根目录,如果你改过functions.php,就加入上面的代码,没改过就覆盖。
演示截图:
2020.10.8更新管理员可见代码:
global $user_ID;
if( $user_ID && current_user_can('level_10') ) :
return '<div class="secret-password">'.$content.'</div>';
endif;
把上面的代码加入到下面
extract(shortcode_atts(array('key'=>null,'keyword'=>null), $atts));
赞(0) 打赏
未经允许不得转载:致明日 » WordPress主题纯代码实现文章设置隐藏内容公众号可见教程
分享到: 更多 (0)
评论 抢沙发
• 昵称 (必填)
• 邮箱 (必填)
• 网址
坚持,总会看见蓝天和白云
联系我们你来了,你就是最棒的!
觉得文章有用就打赏一下文章作者
支付宝扫一扫打赏
微信扫一扫打赏
|
__label__pos
| 0.769012 |
Kunci Jawaban Akurat dan Terpercaya
Tentukan Akar Persamaan Kuadrat Berikut dengan 3 Cara yang Telah Kalian Pelajari Matematika Kelas 9
Tentukan akar persamaan kuadrat berikut dengan 3 cara yang telah kalian pelajari x² – 1 = 0, pembahasan kunci jawaban Matematika kelas 9 halaman 81 82 Latihan 2.1 Semester 1. Silahkan kalian pelajari materi Bab II Persamaan dan Fungsi Kuadrat pada buku matematika kelas IX Kurikulum 2013 Revisi 2018.
Pembahasan kali ini merupakan lanjutan dari tugas sebelumnya, dimana kalian telah mengerjakan soal Tentukan Akar Persamaan Berikut 3×2 – 12 = 0 secara lengkap.
Tentukan akar persamaan kuadrat berikut dengan 3 cara yang telah kalian pelajari
Latihan 2.1 Persamaan Kuadrat
4. Tentukan akar persamaan kuadrat berikut dengan 3 cara yang telah kalian pelajari.
a. x² – 1 = 0
b. 4x² + 4x + 1 = 0
c. -3x – 5x +2 = 0
d. 2x² – x – 3 = 0
e. x² – x + ¼ = 0
Jawaban :
a. x² – 1 = 0
x² – 1 = (x + 1) (x – 1)
Maka x = 1 atau x = -1.
b. 4x² + 4x + 1 = 0
4x² + 4x + 1 = 0
(2x + 1 ) (2x + 1) = 0
Maka x = -1/2
c. -3x – 5x +2 = 0
3x + 5x – 2 = 0
(3x – 1) (x + 2) = 0
Maka x = 3x – 1 atau x = ⅓
x = x + 2 atau x = -2
d. 2x² – x – 3 = 0
(2x – 3) (x + 1) = 0
2x – 3 = 0 atau x + 1 = 0
Maka x = 3/2 atau x = -1
e. x² – x + ¼ = 0
(x – ½) (x – ½) = 0
Maka x = ½
5. Tentukan nilai diskriminan persamaan pada soal no. 1.
6. Jika nilai diskriminan persamaan kuadrat 3x² – 5x + c = 0 adalah 49, tentukan nilai c.
7. Ubahlah persamaan 3x² = 2x – 4 kedalam bentuk umum persamaan kuadrat.
8. Carilah himpunan penyelesaian dari persamaan kuadrat berikut.
a. x² – 5x + 6 = 0
b. x² + 2x – 15 = 0
c. x² + 4x – 12 = 0
9. Bagaimana bentuk persamaan kuadrat yang akar-akarnya 2 dan 5?
10. Nyatakan persamaan 2(x² + 1) = x(x + 3) dalam bentuk umum persamaan kuadrat.
Jawaban, buka disini: Tentukan Nilai Diskriminan Persamaan Pada Soal No 1
Demikian pembahasan kunci jawaban Matematika kelas 9 halaman 81 82 Latihan 2.1 pada buku semester 1 kurikulum 2013 revisi 2018. Semoga bermanfaat dan berguna bagi kalian. Kerjakan juga pembahasan soal lainnya. Terimakasih, selamat belajar!
|
__label__pos
| 0.992856 |
NEW: Welcome to the Rhino 6 version of this page! Looking for the older Rhino 5 version?
Overlay Text Display Conduit
Demonstrates how to use a display conduit to draw overlay text.
class CustomConduit : Rhino.Display.DisplayConduit
{
protected override void DrawForeground(Rhino.Display.DrawEventArgs e)
{
var bounds = e.Viewport.Bounds;
var pt = new Rhino.Geometry.Point2d(bounds.Right - 100, bounds.Bottom - 30);
e.Display.Draw2dText("Hello", System.Drawing.Color.Red, pt, false);
}
}
partial class Examples
{
readonly static CustomConduit m_customconduit = new CustomConduit();
public static Rhino.Commands.Result DrawOverlay(RhinoDoc doc)
{
// toggle conduit on/off
m_customconduit.Enabled = !m_conduit.Enabled;
RhinoApp.WriteLine("Custom conduit enabled = {0}", m_customconduit.Enabled);
doc.Views.Redraw();
return Rhino.Commands.Result.Success;
}
}
Partial Friend Class Examples
Private ReadOnly Shared m_customconduit As New CustomConduit()
Public Shared Function DrawOverlay(ByVal doc As RhinoDoc) As Rhino.Commands.Result
' toggle conduit on/off
m_customconduit.Enabled = Not m_conduit.Enabled
RhinoApp.WriteLine("Custom conduit enabled = {0}", m_customconduit.Enabled)
doc.Views.Redraw()
Return Rhino.Commands.Result.Success
End Function
End Class
import Rhino
import System.Drawing
import scriptcontext
import rhinoscriptsyntax as rs
# DisplayConduit subclass that overrides the DrawForeground function
# e is an instance of Rhino.Display.DrawEventArgs
class CustomConduit(Rhino.Display.DisplayConduit):
def DrawForeground(self, e):
color = System.Drawing.Color.Red
bounds = e.Viewport.Bounds
pt = Rhino.Geometry.Point2d(bounds.Right - 100, bounds.Bottom - 30)
e.Display.Draw2dText("Hello", color, pt, False)
def showafterscript():
# Create a custom conduit that can continue to draw after the
# script has completed. The conduit is kept in the sticky
# dictionary so we can get at it and turn it off in the future
#
# check to see if the conduit has been created and is in sticky
conduit = None
if scriptcontext.sticky.has_key("myconduit"):
conduit = scriptcontext.sticky["myconduit"]
else:
# create a conduit and place it in sticky
conduit = CustomConduit()
scriptcontext.sticky["myconduit"] = conduit
# Toggle enabled state for conduit. Every time this script is
# run, it will turn the conduit on and off
conduit.Enabled = not conduit.Enabled
if conduit.Enabled: print "conduit enabled"
else: print "conduit disabled"
scriptcontext.doc.Views.Redraw()
def showinscript():
# create a custom conduit that only displays during the execution
# of this script. Once the script has completed, the conduit is turned
# off and display goes back to normal
conduit = CustomConduit()
conduit.Enabled = True
scriptcontext.doc.Views.Redraw()
rs.GetString("Pausing for user input")
conduit.Enabled = False
scriptcontext.doc.Views.Redraw()
if __name__=="__main__":
showinscript()
#showafterscript()
|
__label__pos
| 0.993945 |
jmancherje jmancherje - 2 years ago 229
HTML Question
How to reverse a jQuery animation back to original CSS properties
There are a lot of very similar questions on here but I cannot find an exact answer to my question.
I am new to using the jQuery
.animate()
method and I want to know if there's a common or best method of reversing the animation?
Here is a fiddle for an example of what I've come up with:
Fiddle
Essentially all it does is use an if statement to check one CSS property and then animate it to one state or back to the other state.
$(document).ready(function () {
$("[name=toggle]").on("click", function () {
if ($('.box').width() < 125) {
$(".box").animate({
opacity: .3,
width: "125px",
height: "125px"
}, 250);
} else {
$(".box").animate({
opacity: 1,
width: "100px",
height: "100px"
}, 250)
}
});
});
.box {
background-color: lightblue;
box-shadow: 5px 5px 10px #000000;
width: 100px;
height: 100px;
display: block;
margin: 20px auto 0 auto;
border-radius: 25px;
}
[name="toggle"] {
display: block;
margin: 0 auto;
margin-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button name="toggle">Animate</button>
<div class="box"></div>
This is what I was able to come up with with my first exposure to .animate(), but I think there may be a better way.
Say you want to have an animation on hover, and reverse the animation when the mouse is moved off the element. Is there a way to easily reverse the jQuery animation easily? I am away I could use a :hover state with CSS, but this is a hypothetical question regarding jQuery .animate().
Answer Source
You can do that with plain CSS using transitions.
.animate-me {
background-color:red;
width:50px;
height:50px;
position:absolute;
top:0;
left:150px;
transition:left 2s, background-color 2s;
}
.animate-me:hover{
left:0;
background-color:blue;
}
<div class="animate-me"></div>
Usually css is simpler. However when browsers are old jquery might be your only way so I have included the JQuery way.
function animationForward(){
$(".animate-me").animate(
{
opacity: 0.25,
left: "100",
height: "100"
}, 5000, function() {
animationBackward();
}
)}
function animationBackward(){
$(".animate-me").animate(
{
opacity: 1,
left: "50",
height: "50"
}, 5000, function() {
animationForward();
}
)}
animationForward();
.animate-me {
width:50px;
height:50px;
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animate-me"></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
|
__label__pos
| 0.991214 |
Twitter is a phenomenal idea. And one can safely assume that the only thing that changed the face of the internet and how we interacted is, Twitter.
Twitter is beautifully made with amazing light weight and fast loading scripts and techniques. Many of us wonder, what exactly powers Twitter and make it so huge that life virtually seems impossible without tweeting.
Well, on the technical side, the power of Twitter lies in their open API format that allows any developer to make a Twitter application, distribute it to world-wide users and have fun!
There is no limitation and definitely, no selection/rejection criteria as it is there for the iPhone infrastructure. If you are good at php, design a Twitter application in it. If you like Java, make one in it. Twitter doesn’t care unless you spam their system by sending zillions of API requests per unit time (they have a limit on that thing).
Well, that was about Twitter’s phenomenal growth. Now what about the native thing? What about the Twitter? How was the real hero made? Well, to tell you the truth, I always wondered how come such a powerful thing came into existence. Was it CSS or Javascript or XML or PHP? But one day, I decided to make my own Twitter (yeah, no kidding). And I combined all the technologies I possibly knew and I was able to make a small prototype of Twitter.
Why Am I writing this tutorial?
First thing first, I was really thrilled when my experiment of making my own Twitter was successful. It wasn’t that great, but it was enough to blow my mind and make me write this tutorial.
Secondly, with this tutorial, you would come to know the real power behind combining the very basic things that you might already have known since the starting days of your web design career. Well, here’s a screenshot of the end result (click to check out the demo).
Creating Your Own Twitter
Let’s Get Started
So, without further ado, let’s get started. The technologies which we would be using to make our own Twitter timelines are:
• SQL (Stands for Structured Query Language). It’s a database management language. Don’t worry, you don’t have to be a “pro” at it for the time being.
• XHTML (We’ll be using it for the front end)
• CSS (For styling purposes)
• jQuery (For the magical effects!)
• PHP (Of course, the core of all)
The Database
This is where all your (and the rest of the world’s) tweets will be stored. Each tweet will be stored with a unique id in the database table. We would be using MySQL database, which is an open source architecture and used in ninety percent of the web applications. All you need to do is:
• Make a blank database in your phpMyAdmin
• Go to the SQL section and run the following query:
CREATE TABLE `demo_twitter_timeline` ( `id` int(10) NOT NULL auto_increment, `tweet` varchar(140) collate utf8_unicode_ci NOT NULL default '', `dt` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Note: Whatever table name, user name, password you want to use, make sure you update the connect.php file supplied with the demo files of this tutorial. Otherwise, nothing is going to work.
The Front End (XHTML)
This one is going to be easy. We would be combining the properties of CSS and jQuery in our XHTML code. Your index.php file should look like this:
<div id="twitter-container">
<form id="tweetForm" action="submit.php" method="post">
<span class="counter">140</span>
<label for="inputField">What are you doing?</label>
<textarea name="inputField" id="inputField" tabindex="1"rows="2" cols="40"></textarea>
<input class="submitButton inact" name="submit" type="submit" value="update" />
<span class="latest"><strong>Latest: </strong><span id="lastTweet"><?=$lastTweet?></span></span>
<div class="clear"></div>
</form>
<h3 class="timeline">Timeline</h3>
<ul class="statuses"><?=$timeline?></ul>
</div>
Let me explain a little here.
Our whole framework lies in the div id of “twitter-container”. It literally holds the entire layout within itself and keep the design stable. We have applied some CSS styles to it too.
Next, the text box where we would enter our tweet is contained in the “tweetForm”. It’s an AJAX form id.
Later in the code, we have implied different ids to contain the timestamp and other important things with custom CSS built around them.
The CSS
/* Page styles */
body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{
margin:0px;
padding:0px;
}
body{
margin-top:20px;
background:#d9f4f7;
}
/* Form & timeline styles */
#twitter-container{
-moz-border-radius:12px;
-khtml-border-radius: 12px;
-webkit-border-radius: 12px;
border-radius:12px;
border:6px solid #00d9ff;
padding:10px;
width:600px;
font-size:11px;
font-family:'Lucida Grande',sans-serif;
color:#333333;
margin: 0px auto -1px auto;
}
label{
font-size:20px;
display:block;
}
.counter{
color:#CCCCCC;
float:right;
font-family:Georgia,serif;
font-size:32px;
font-weight:bold;
height:40px;
overflow:hidden;
}
textarea{
width:594px;
height:38px;
margin:5px 0 10px 0;
border:1px solid #AAAAAA;
padding: 4px 2px;
font-family:'Lucida Grande',sans-serif;
overflow:auto;
font-size:14px;
}
.clear{
clear:both;
}
.submitButton{
color:#666666;
font-size:14px;
height:32px;
width:115px;
-moz-border-radius:6px;
-khtml-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius:6px;
border:1px solid #cccccc;
background:url(img/button_bg.gif) repeat-x #f5f5f5;
cursor:pointer;
float:right;
}
.submitButton:hover{
background-position:bottom;
border-color:#dddddd;
color:#333333;
}
.inact,.inact:hover{
background:#f5f5f5;
border:1px solid #eeeeee;
color:#aaaaaa;
cursor:auto;
}
.latest{
color: #666666;
}
ul.statuses{
margin:10px 0;
}
ul.statuses li {
position:relative;
border-bottom:1px dashed #D2DADA;
padding:15px 15px 15px 10px;
list-style:none;
font-size:14px;
}
ul.statuses li:first-child{
border-top:1px dashed #D2DADA;
}
ul.statuses li:hover {
background-color:#F7F7F7;
}
h3.timeline{
margin-top:20px;
color:#999999;
font-size:20px;
font-weight:normal;
}
div.tweetTxt{
float:left;
width:498px;
overflow:hidden;
}
ul.statuses a img.avatar{
float:left;
margin-right:10px;
border:1px solid #446600;
}
div.date{
line-height:18px;
font-size:12px;
color:#999999;
}
li a, li a:visited {
color:#007bc4;
text-decoration:none;
outline:none;
}
li a:hover{
text-decoration:underline;
}
The CSS code is self-explanatory, but let me explain some important things here too.
On the first block of code, we have reset the page styles that nullify anything that can cause style conflicts.
Next, the code blocks of line 16 to 19 use the latest CSS3 properties that make the corners of our div containers round, giving them a sleek and stylish look. If you have an old browser, the code may not work and you may not see the round edged borders.
Rest of the code is pretty simple with later being the Submit Button, where we have again used the rounded corner CSS 3 technique.
The jQuery Magic
And here comes the magic code that will embed all the working things inside our Twitter prototype and make the User Interface even more interesting.
$(document).ready(function(){
$('#inputField').bind("blur focus keydown keypress keyup", function(){recount();});
$('input.submitButton').attr('disabled','disabled');
$('#tweetForm').submit(function(e){
tweet();
e.preventDefault();
});
});
function recount()
{
var maxlen=140;
var current = maxlen-$('#inputField').val().length;
$('.counter').html(current);
if(current<0 || current==maxlen)
{
$('.counter').css('color','#D40D12');
$('input.submitButton').attr('disabled','disabled').addClass('inact');
}
else
$('input.submitButton').removeAttr('disabled').removeClass('inact');
if(current<10)
$('.counter').css('color','#D40D12');
else if(current<20)
$('.counter').css('color','#5C0002');
else
$('.counter').css('color','#cccccc');
}
function tweet()
{
var submitData = $('#tweetForm').serialize();
$('.counter').html('<img style="padding:12px" src="img/ajax_load.gif" alt="loading" width="16" height="16" />');
$.ajax({
type: "POST",
url: "submit.php",
data: submitData,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('ul.statuses li:first-child').before(msg);
$("ul.statuses:empty").append(msg);
$('#lastTweet').html($('#inputField').val());
$('#inputField').val('');
recount();
}
}
});
}
The PHP
Our php code will act as a bridge between the user interface and the database and probably is the most important part of our prototype. The php code inserts the user data into the MySQL database tables.
Here’s the code for submit.php:
define('INCLUDE_CHECK',1);
require "functions.php";
require "connect.php";
if(ini_get('magic_quotes_gpc'))
$_POST['inputField']=stripslashes($_POST['inputField']);
$_POST['inputField'] = mysql_real_escape_string(strip_tags($_POST['inputField']),$link);
if(mb_strlen($_POST['inputField']) < 1 || mb_strlen($_POST['inputField'])>140)
die("0");
mysql_query("INSERT INTO demo_twitter_timeline SET tweet='".$_POST['inputField']."',dt=NOW()");
if(mysql_affected_rows($link)!=1)
die("0");
echo formatTweet($_POST['inputField'],time());
Explanation: First of all, we checked the state of magic_quotes_gpc. It is enabled by default on some web hosts and its function is to escape all the incoming data automatically. So, it that remains enabled, we would not be able to enter any data in your stream. So, we first check it’s state. Secondly, We escape the data, do a check of the length of $_POST['inputField'] and insert the row in our database. We echo a formatted tweet using formatTweet (more on that in a minute), that is returned to the tweet() jQuery function as the variable msg.
function.php:
<?php
if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');
function relativeTime($dt,$precision=2)
{
$times=array( 365*24*60*60 => "year",
30*24*60*60 => "month",
7*24*60*60 => "week",
24*60*60 => "day",
60*60 => "hour",
60 => "minute",
1 => "second");
$passed=time()-$dt;
if($passed<5)
{
$output='less than 5 seconds ago';
}
else
{
$output=array();
$exit=0;
foreach($times as $period=>$name)
{
if($exit>=$precision || ($exit>0 && $period<60)) break;
$result = floor($passed/$period);
if($result>0)
{
$output[]=$result.' '.$name.($result==1?'':'s');
$passed-=$result*$period;
$exit++;
}
else if($exit>0) $exit++;
}
$output=implode(' and ',$output).' ago';
}
return $output;
}
function formatTweet($tweet,$dt)
{
if(is_string($dt)) $dt=strtotime($dt);
$tweet=htmlspecialchars(stripslashes($tweet));
return'
<li>
<a href="#"><img class="avatar" src="img/avatar.jpg" width="48" height="48" alt="avatar" /></a>
<div class="tweetTxt">
<strong><a href="#">My_Own_Twitter</a></strong> '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?[^\s"\']+)/i','<a href="$1" rel="nofollow" target="blank">$1</a>',$tweet).'
<div class="date">'.relativeTime($dt).'</div>
</div>
<div class="clear"></div>
</li>';
}
?>
Here, we have used a relative time array, that displays the tweet format in a relative way, rather than an absolute way. In more simple terms, it would display “10 minutes earlier” rather than “at 8:00 pm”, which is what exactly happens over Twitter.
In the second function, we have used all the other important things including a default user Avatar, which can be changed as per your convenience.
That’s it. If you have done all the above steps correct, you should have a small prototype of your own Twitter ready and up in a jiffy!
You can also download a zip that contains all demo files →
(downloaded 90 times already!)
PS: I’ve used the official Twitter logo which is freely available for download in both png and vector format.
Conclusion
This isn’t a fully functional prototype of Twitter. It’s just a basic model which demonstrate how things really work. With this tutorial we learnt how a much powerful web application could be developed using the things that we already know.
Moreover, you are free to use your imagination and turn it around in any direction to come out with something unique! Do share your shouts below in the comment section. Good Luck ;)
Via http://spyrestudios.com/how-to-create-your-own-twitter-prototype-with-sql-php-and-jquery/
Related Posts with Thumbnails
Tagged with:
Comments are closed.
Free WordPress Theme
|
__label__pos
| 0.827713 |
pyperclip – Copiar y pegar en el portapapeles
pyperclip – Copiar y pegar en el portapapeles
pyperclip es un pequeño módulo multiplataforma (Windows, Linux, OS X) para el copiado y pegado de texto en el portapapeles desarrollado por Al Sweigart. Corre en Python 2 y 3, y se instala vía sencillamente vía pip:
pip install pyperclip
Funcionamiento
En sistemas Microsoft Windows no es necesario ningún paquete adicional, ya que interactúa directamente con la API de Windows a través del módulo ctypes.
En distribuciones de Linux el módulo utiliza alguno de los siguientes comandos: xclip y xsel. Si alguno de estos no se encuentra instalado por defecto, pueden adquirirse ejecutando:
• sudo apt-get install xclip
• sudo apt-get install xsel
En caso de no encontrarse disponibles, pyperclip puede utilizar las funciones de Qt (PyQt 4) o GTK (no disponible en Python 3), en caso de estar instalados.
En Mac OS X hace uso de los comandos pbcopy y pbpaste.
Ejemplos
>>> import pyperclip as clipboard
# Copiar un texto en el portapapeles.
>>> clipboard.copy("Recursos Python")
# Acceder al contenido (pegar).
>>> clipboard.paste()
'Recursos Python'
Curso online 👨💻
¡Ya lanzamos el curso oficial de Recursos Python en Udemy! Un curso moderno para aprender Python desde cero con programación orientada a objetos, SQL y tkinter en 2023.
Consultoría 💡
Ofrecemos servicios profesionales de desarrollo y capacitación en Python a personas y empresas. Consultanos por tu proyecto.
Discord 💬 y Twitter 🐦
¡Te invitamos a sumarte a nuestro nuevo servidor de Discord! ¡Y no olvides seguirnos en Twitter!
12 comentarios.
• Recursos Python says:
Hola. Si tenés información en una lista o tupla y la querés copiar en el portapapeles, vas a tener que convertirla previamente a una cadena con el formato que vos quieras (eso es independiente de este módulo). Podés pasar por el foro y explicarnos el problema con más detalle.
Saludos
1. Hola , tengo un problema
El comando funciona bien copiando una variable la primera vez, pero al cambiar el valor de esa variable, copia de nuevo el primer valor que tuvo la variable
que puedo hacer?
2. Tengo una pregunta como hago que el prgrama copie todo el contenido que tiene una variable por ejemplo
a = («hola»)
pyperclip.copy(a)
podria ser pero no ayudaaaaaaaaaaaaaaaaaa
• Recursos Python says:
Hola. Sí, sería exactamente de ese modo. Si importaste el módulo como mostramos en el ejemplo, sería clipboard.copy(a).
Saludos
3. Claudio Alvarado says:
Estoy estudiando Python con el manual automatetheboringstuff, y he instalado la versión 3.6 en mi computador.
Descargué el archivo pyperclip-1.6.0.tar, lo descomprimí y lo envié al directorio de Python36.
Sin embargo al intentar instalarlo con el Python Shell:
>>>pip install pyperclip
acusa error
SyntaxError: invalid syntax
¿Como logro a partir del archivo comprimido llegar a instalar el módulo pyperclip?
• Recursos Python says:
Hola. Estimo que sí podría hacerse, habría que ver en qué formato se copia la tabla. Te invito a que pases por el foro y lo veamos con mayor detalle.
¡Saludos!
Deja una respuesta
|
__label__pos
| 0.602816 |
E-mail Security School Final Exam Answers
Final Exam
1.) When are digital signatures and footer stamping incompatible?
A digital signature is something stamped onto a message by the sender. The signature is a cryptographic operation, usually a hash, across the message content, which is then locked with the private key of the sender. The recipient can use the sender's public key to compare a hash they compute with the transmitted hash to see if the message has been tampered with, or isn't from the purported sender at all.
Injecting a footer into a message after it is signed by the sender will invalidate the digital signature. As a result, all recipients of the message think that the message has been tampered with or was forged. If you want to digitally sign messages and have footers, then you need to put the footer into the message before the sender adds their digital signature.
<< Back to quiz
Final Exam
2.) Putting message archiving functionality at the Internet gateway seems very efficient. But what is wrong with this picture?
Message archives can only archive messages that they see. If you are only concerned with archiving messages that pass to and from the Internet, then this might work. However, if your goal in archiving messages is to meet some regulatory requirement, it is likely that you will need to archive messages that are sent internally and never go to the Internet. In that case, you will need to have the archiving function attached to the user's mailbox rather than to a transport path out of the network. Only this can assure that you are copying every message that the user receives. If you are more concerned with archiving every transmitted message, then the appropriate place for the archiving function is the MTA or mailbox server that the user agent uses for message submission.
<< Back to quiz
Final Exam
3.) Encrypted mail can't be scanned by a compliance checker. How do you resolve this issue?
Compliance checking is a policy issue. It's a corporate policy to look into messages and try to see what is going on. If the message is encrypted, then clearly the compliance checker cannot look inside. Hence, this is a policy issue and not a technical issue. There are three scenarios: the policy states that such mail is out of compliance; the policy states that such mail is, by definition, within compliance; or, the policy says nothing about mail that cannot be checked.
If you are lucky enough to have a policy that matches the first or second case, then you simply do what the policy says and don't worry about it. If your policy doesn't mention what to do about mail that cannot be examined, then the appropriate answer is to bring this to the attention of the policy people and have them fix the policy. Solving this problem technically, without policy input, is asking for a slap on the wrist or worse.
<< Back to quiz
Final Exam
4.) Policy says that you will accept 10 messages an hour from someone. What do you do with the 11th message?
Don't accept it. The real answer, of course, is how you don't accept the message. There are two options: temporary refusal (4xx response) and permanent refusal (5xx response). In this case, the most appropriate thing to do is return a 4xx response to the message. You don't want to start bouncing messages because an MTA went down for an hour and has a small backlog for you.
Intelligent MTA design might have an escalating series of responses. For example, you could take the 11th through 1100th message and return 4xx responses, then start sending back permanent refusals (5xx responses) because it's clear that something is wrong on the other end that is not quickly getting better.
In any case, immediately responding with a permanent refusal (5xx) may be more emotionally satisfying, but is not good practice.
<< Back to quiz
Final Exam
5.) Identify the two most common errors associated with keyword searching across e-mail messages.
The two most common ways to search for keyword incorrectly are to ignore case significance and to improperly stem words.
Case significance is the easy one because most keyword searching tools are case significant. You have to turn off case significance anytime you're doing policy-based keyword searches. This is the number one error that most people make.
Stemming is a more significant problem and one that is not handled easily. Without stemming, you have to search for every variation of the word that you're looking for. For example, you can't simply search for 'poop' because you won't catch the important variations 'poopy,' 'poops,' 'pooped' and 'pooping.' If you try to ignore the spaces on either side of a word (or, more precisely, the white space, which can include line breaks, tabs and other formatting characters), you'll end up with every word that has 'poop' in it, such as nincompoop (used to describe the person who wanted you to search for poop). Good regular expression and search engines handle word stemming automatically for you; more primitive ones require you to handle this kind of stemming by yourself.
<< Back to quiz
This was first published in November 2005
This Content Component encountered an error
PRO+
Content
Find more PRO+ content and other member only offers, here.
0 comments
Oldest
Forgot Password?
No problem! Submit your e-mail address below. We'll send you an email containing your password.
Your password has been sent to:
-ADS BY GOOGLE
SearchCloudSecurity
SearchNetworking
SearchCIO
SearchConsumerization
SearchEnterpriseDesktop
SearchCloudComputing
ComputerWeekly
Close
|
__label__pos
| 0.552386 |
Subversion Repositories doc-tools
Rev
Rev 3 | Blame | Compare with Previous | Last modification | View Log | RSS feed
#!/usr/bin/perl
#
# File: php_autodoc_fornd.pl
# Crée une "coquille documentaire" pour Natural Docs dans les fichiers PHP.
#
# Bien entendu, cela doit être ensuite complété à la main
#
# Version : 0.6
#
# Language: Perl
#
# Svn info: Résumé
# $Id: php_autodoc_fornd.pl 4 2007-05-31 23:49:44Z axl $
#
# Svn info: Révision
# $Revision: 4 $
#
# Svn info: Auteur de la révision
# $Author: axl $
#
#
# variable: $php_name
# valeur : PHP
#
# variable: $js_name
# valeur : javascript
#
# variable: $perl_name
# valeur : Perl
#
$php_name='PHP';
$js_name='javascript';
$perl_name='Perl';
#use strict;
# Pour la gestion des options
use Getopt::Std;
# Pour la copie de fichiers
use File::Copy;
#
# Function: print_syntaxe
#
# Affiche la syntaxe d'utilisation
#
# Retourne:
#
# rien
#
sub print_syntaxe {
# Chemin complet du script Perl
my $NomScript = $0;
# Nom du script seulement
$NomScript =~ s!.*(/|\\)!!;
print <<_FINSY_;
Syntaxe :
$NomScript -i nom_fichier [-option1 [parametres]] [-option2 ...]
$NomScript -h
Description des options :
-i nom_fichier
nom_fichier nom du (des) fichier(s)) d\'input (accepte les jokers)
-x fichiers_exclus
fichiers_exclus est un masque de fichiers exclus du traitement
note : les fichiers .bak sont toujours exclus (option -x inutile pour eux)
-d {n} n niveau de déboguage (1 seulement pour l\'instant)
-e (except) est suivi de la liste des fonctions exclues du traitement
-o (only) est suivi de la liste des seules fonctions incluses
dans le traitement
-e et -o sont incompatibles ; -o est prioritaire
les mots de la liste sont separes par des virgules, points-virgules
ou des espaces (dès que la liste contient des espaces, elle doit être
entre doubles quotes).
Les fonctions existantes actuellement sont :
- constant
- en_tete
- function (tous langages confondus)
- js_func (fonctions javascript)
- include
-h afficher cette aide
Exemples :
$NomScript -i *.php -x *.old
$NomScript -i *.php -x *_ND.php
$NomScript -i *.php -e include,js_func,constant
$NomScript -i *.php -o "en_tete function"
_FINSY_
exit;
}
#
# Function: output_en_tete
#
# Ajoute les généralités concernant le fichier
#
# Parameters:
# $O : Handle du fichier de sortie
#
# $entree : Nom du fichier en entrée
#
# Retourne:
#
# rien
#
sub output_en_tete {
# Si désactivé retour
if ($feature{'
en_tete'}==0) {
return;
}
# Recup des paramètres
my ($O, $entree) = @_;
# Séparer répertoire et nom de fichier
if ($entree=~m!^(.*)(\\|/)(.*)$!) {
$repertoire=$1;
# Si répertoire est '
.' alors on vide pour l'affichage
#if ($repertoire eq '.') {
# $repertoire='';
# }
$fichier=$3;
}
else {
$repertoire='.';
$fichier=$entree;
}
# En tête de fichier pour Natural Docs
if ($fichier=~/\.php3?$/) {
$langage = "\n language: $php_name\n";
}
elsif ($fichier=~/\.js$/) {
$langage = "\n language: $js_name\n";
$language_context=$js_name;
push(@language_context_stack, $language_context);
}
elsif ($fichier=~/\.p(l|m)$/) {
$langage = "\n language: $perl_name\n";
}
else {
$langage = "\n";
}
$EnTete = <<_FIN_;
<?
/*
file: $fichier
Rôle du script...
Repertoire: $repertoire
$repertoire/
$langage
svn info: Résumé
\$Id\$
Svn info: Révision
\$Revision\$
Svn info: Auteur de la révision
\$Author\$
*/
_FIN_
$EnTete.="?>";
print $O $EnTete;
}
#
# Function: output_parameters
#
# Ajoute les paramètres de la fonction (un par
# ligne, séparés par une ligne vide)
#
# Retourne:
#
# rien
#
sub output_parameters {
my ($param) = @_;
print O "\n Parameters:\n";
# Sort les paramètres un par un pour commentaires manuels futurs
while ($param=~s/^(\$[a-zA-Z_0-9]+)( *, *(.*))?$/$3/) {
print O " $1 :\n\n";
}
}
#
# Function: output_function
#
# Ajoute le commentaire de fonction
#
# Retourne:
#
# rien
#
sub output_function {
# Si désactivé retour quel que soit le langage en cours
if ($feature{'function'}==0) {
return;
}
# Si désactivé pour javascript et javascript en cours, retour
if ( ($language_context eq $js_name) and ($feature{'js_func'}==0) ) {
return;
}
my ($func_name,$param_liste)=@_;
print O "/*\n Function: $func_name\n";
print O "\n Language:\n $language_context\n";
output_parameters($param_liste);
print O "\n*/\n";
}
#
# Function: output_constant
#
# Ajoute la constante dont le nom et la valeur
# ont été passés en paramètres
#
# Parameters:
# $ConstName : Nom de la constante
#
# $ConstValue : Valeur de la constante
#
# Retourne:
#
# rien
#
sub output_constant {
# Si désactivé retour
if ($feature{'constant'}==0) {
return;
}
my ($ConstName,$ConstValue) = @_;
print O "/*\n Constant: $ConstName\n\n $ConstValue\n";
print O "\n Signification: ...\n*/\n";
}
#
# Function: output_include
#
# Ajoute la déclaration d'inclusion passée en paramètre
#
# Parameters:
# $IncludeWord : commande d'inclusion
#
# $IncludeFile : Fichier inclus (peut être une formule)
#
# Retourne:
#
# rien
#
sub output_include {
# Si désactivé retour
if ($feature{'include'}==0) {
return;
}
my ($IncludeWord,$IncludeFile) = @_;
print O "/*\n Inclusion: $IncludeWord\n\n";
print O " $IncludeFile\n*/\n";
}
#
# Function: try_language_context
#
# Essai de repérer le langage de programmation courant.
# Suppose l'absence de changement au sein d'une ligne ce qui est une
# simplification abusive, on le sait.
#
# Toutes les regexp de ce script sont de vraies passoires laissant
# délibérément de côté tout un tas de cas (par manque de temps par
# rapport aux enjeux)
#
# Modifie:
#
# Les variables globales $language_context et @language_context_stack
#
# Retourne:
#
# rien
#
sub try_language_context {
# Ignorer les courtes inclusions de PHP au sein du HTML
# ou du javascript
if (/^ *<\?(php)?.+\?>/) {
return;
}
# Début PHP ?
if (/^ *<\?(php)?/i) {
push(@language_context_stack, $language_context);
$language_context=$php_name;
if ($debug_level eq 1) {
print "$line_number:dp:#$_ current : $language_context\n";
print @language_context_stack; print "\n";
}
}
# javascript sur une seule ligne -> on ne change rien
if (m:^ *<(!--)?SCRIPT +LANGUAGE=.?javascript.?>.*</script(--)?>:i) {
# On ne fait rien en l'état actuel du développement
}
# Sinon début javascript
else {
if (/^ *<(!--)?SCRIPT +LANGUAGE=.?javascript.?>/i) {
push(@language_context_stack, $language_context);
$language_context=$js_name;
if ($debug_level eq 1) {
print "$line_number:dj:#$_ current : $language_context\n";
print @language_context_stack; print "\n";
}
return;
}
}
# Fin javascript ?
if (m:</script(--)?>:i) {
$language_context=pop(@language_context_stack);
if ($debug_level eq 1) {
print "$line_number:fj:#$_ current : $language_context\n";
print @language_context_stack; print "\n";
}
}
# Fin PHP ? (Hum regexp bidon on peut avoir un "<" qui ne soit pas
# un "<?")
if ((/\?>.*$/) and ($language_context eq $php_name)) {
my $ligne=$_;
while ($ligne=~/\?>.*<\?/) {
$ligne=~s/^.*\?>.*<\?(.*)$/$1/;
}
if ($ligne=~/\?>.*$/) {
$language_context=pop(@language_context_stack);
if ($debug_level eq 1) {
print "$line_number:fp:#$_ current : $language_context\n";
print @language_context_stack; print "\n";
}
}
}
}
#
# Function: try_to_skip_svnid
#
# Efface le mot-clé Id de subversion s'il existe déjà dans le fichier
#
# Retourne:
#
# Un booléen
#
# - true : il n'y plus rien d'autre sur la ligne qu'un signe de début
# de commentaire ligne et des espaces
# - il reste des éléments d'information sur la ligne
#
sub try_to_skip_svnid {
if ($_=~/\$Id.*\$/) {
$_=~s!^(.*?)\$Id[^\$]*\$(.*)$!$1$2!;
if ($_=~/^(\/\/|#) *$/) {return 1;}
}
return 0;
}
#
# Function: try_function_begin
#
# Teste si une fonction débute et si oui traite en conséquence
#
# Parameters:
#
# aucun
#
# Retourne:
#
# vrai (1) si début de fonction trouvé et faux (0) sinon
#
sub try_function_begin {
if ($_=~/^ *function *([a-zA-Z_0-9]+)\(([^)]*)(.*)$/i) {
output_function($1,$2);
print O $_;
return 1;
}
else {
return 0;
}
}
#
# Function: try_constant_define
#
# Teste si une définition de constante est sur la ligne.
# Si oui, traite en conséquence.
#
# Parameters:
#
# aucun
#
# Retourne:
#
# vrai (1) si définition de constante trouvée et faux (0) sinon
#
sub try_constant_define {
# Attention aux références arrières \1 et \3 qu permettent de s'assurer
# que la paire de quote (simple ou double) est cohérente
if ($_=~/^ *define *\( *(['"])([a-zA-Z_0-9]+)\1 *, *(["']?)(.*?)\3 *\)/) {
output_constant($2,$4);
print O $_;
return 1;
}
else {
return 0;
}
}
#
# Function: try_include_def
#
# Teste si une inclusion de fichier est sur la ligne.
# Si oui, traite en conséquence.
#
# Parameters:
#
# aucun
#
# Retourne:
#
# vrai (1) si définition de constante trouvée et faux (0) sinon
#
sub try_include_def {
# Trouver le mot-clé
my $regexp='^ *(include|require)(_once)? *\\(';
# Trouver la succession d'éléments constants et littéraux
# (pas traité éléments variables : à faire)
$regexp.="((($TYPE2_FILE_PATTERN|$LAXIST_CONST_PATTERN)\\.?)+)";
# Fermer la regexp par la reconnaissance de la fin de parenthèse
$regexp.=' *\\)';
if ($_=~/$regexp/) {
output_include($1.$2,$3);
print O $_;
return 1;
}
else {
return 0;
}
}
#
# Function: backup_file
#
# Traite un fichier en entrée en lui ajoutant les commentaires
#
# Parameters:
# $inputFile : chemin d'accès au fichier
#
# Retourne:
#
# rien
#
sub backup_file {
# Récupération chemin de tavail et nom de fichier
my ($inputFile) = @_;
# Supprimer le "./" initial s'il existe ; récupérer path et fichier
#print "$inputFile\n";
$inputFile=~s!^(\./)?((.*)/)?(.*)$!$3/$4!;
my $rep=$3;
my $file=$4;
#print "$inputFile\n$rep#$file\n";
# Vérification de l'existence des répertoires du chemin de backup
# On teste d'abord le chemin complet pour aller vite
# S'il existe, on passe directement à la copie
# Sinon on le traite élément par élément de gauche à droite
my $full_dir_path="ND_backup_dir/$rep";
if (!-d $full_dir_path) {
@path_element=split('/',$full_dir_path);
my $current_path='.';
foreach my $element (@path_element ) {
$current_path="$current_path/$element";
if (!-d $current_path) {
# créer le rep;
if (! mkdir $current_path,0660) {
print "\n$current_path : erreur creation !";
}
}
}
}
# Calcul du chemin du fichier de backup
my $backupFile="ND_backup_dir/$rep/$file";
$backupFile.='.bak';
# Copie de l'original vers le répertoire de backup
copy($inputFile,$backupFile);
}
#
# Function: process_one_file
#
# Traite un fichier en entrée en lui ajoutant les commentaires
#
# Parameters:
# $rep : chemin de travail (sans le slash final)
#
# $entree : Nom du fichier
#
# Retourne:
#
# rien
#
sub process_one_file {
$line_number=0;
# Récupération chemin de tavail et nom de fichier
my ($rep,$entree) = @_;
# Initialisation de variable
my $langage = "";
# Calcul nom du fichier de sortie selon qu'il ait une extension ou pas
if ($entree=~m/^(.*)\.(.*)$/) {
$sortie=$rep."/$1_ND.$2";
}
else {
$sortie=$rep."/$1_ND";
}
# Calcul du chemin du fichier d'entrée
$inputFile="$rep/$entree";
# Affichage écran du travail en cours
print "Traitement de $entree vers $sortie\n";
# Faire copie de sauvegarde
backup_file($inputFile);
# Ouvrir les fichiers d'entrée et de sortie
open F,"$inputFile";
open O,">$sortie";
# Eliminer l'éventuel "./" du début de chemin pour les affichages
$inputFile=~s/^(.\/)?(.*)/$2/;
# Ajouter l'en-tête fichier pour Natural Docs
output_en_tete(O, $inputFile);
# Traitement du fichier proprement dit
while (<F>) {
$line_number+=1;
#print "$_\n";
# Mettre à jour le contexte de langage
try_language_context();
# Enlever le Id subversion si présent (car ajouté dans en-tête)
if (try_to_skip_svnid()) {
next;
}
# Trouver, traiter les fonctions
if (try_function_begin()) {
next;
}
# Trouver, traiter les définition de constantes
if (try_constant_define()) {
next;
}
# Trouver, traiter les inclusions
if (try_include_def()) {
next;
}
# Ecrit la ligne courante dans le fichier de sortie
print O $_;
}
close F;
close O;
}
#
# Function: process_many_files
#
# Traite de multiples fichiers en entrée en leur ajoutant les commentaires
#
# Parameters:
# $masque : répertoire de travail et masque des fichiers à traiter
#
# $x_masque : masque de fichiers à exclure
# (les fichier .bak sont toujours exclus quoiqu'il arrive)
#
# Retourne:
#
# rien
#
sub process_many_files {
# Récupérer les masques de fichiers à inclure et à exclure
my ($masque,$x_masque) = @_;
# Déterminer le répertoire de travail
my $repertoire = $masque;
# Si ni / ni \ alors c'est le répertoire courant
if ($repertoire!~s!(.*)(/|\\)(.*)!$1!) {
$repertoire=".";
}
else {
# sinon récupérer juste le masque de fichiers
$masque=~s!(.*)(/|\\)(.*)!$3!;
}
# print "\nRepertoire : $repertoire\n"; # debug
# Transformer les masques de nom de fichiers en regexp
# Protéger les "."
$masque=~s/\./\\./g;
$x_masque=~s/\./\\./g;
# Ajouter un "." devant les quantificateurs "*" et "?"
$masque=~s/\*/.*/g;
$masque=~s/\?/.?/g;
$x_masque=~s/\*/.*/g;
$x_masque=~s/\?/.?/g;
my $enregistrement;
my $nom_chemin;
local *DH;
unless (opendir(DH, $repertoire)) {
return;
}
while (defined ($enregistrement = readdir(DH))) {
next if($enregistrement eq "." or $enregistrement eq "..");
# Passer les .bak
next if($enregistrement=~/\.bak$/);
# Passer les éléments exclus
next if($enregistrement=~/^$x_masque$/);
$nom_chemin = $repertoire."/".$enregistrement;
if( -d $nom_chemin) {
# print "\n$nom_chemin est un repertoire -> pas de traitement recursif\n";
}
else {
if ($enregistrement=~/^$masque$/) {
#print "\n$nom_chemin -> en cours de traitement";
process_one_file($repertoire,$enregistrement);
}
}
# Plus tard pour le traitement récusrsif
# push(@tous, $HTML_enregistrement);
# rechercher($nom_chemin) if(-d $nom_chemin);
}
closedir(DH);
}
#
# Main part of script
#
# Récupérer les options de la ligne de commande
getopts( "i:x:e:o:d:s:h", \%opts) or print_syntaxe();
print_syntaxe() if defined($opt{h});
# Initialisation variables
$line_number=0;
$language_context='unknown';
@language_context_stack = ('stackbase_');
$TYPE2_FILE_PATTERN="('[A-Za-z0-9_.\-]+'|\"[A-Za-z0-9_.\-]+\")";
$CONST_PATTERN='[A-Z0-9_]+';
$LAXIST_CONST_PATTERN='[a-zA-Z0-9_]+';
# traiter les options de la ligne de commande
# récupérer le(s) nom(s) de(s) fichier(s) à traiter et de ceux à exclure
my $inputfile = $opts{i};
my $exclude_files = $opts{x};
# récupérer les options de travail
my $except_features = $opts{e};
my $only_features = $opts{o};
$debug_level = $opts{d};
# établir la liste des fonctionnalités actives
%feature = (
en_tete => 1,
function => 1,
js_func => 1,
constant => 1,
include => 1,
exec => 0
);
# traiter l'option -e (liste de fonctionnalités exclues du traitement)
my @exception_liste = split(/ *[ ,;] */,$except_features);
foreach my $val (@exception_liste) {
$feature{$val}=0;
}
# traiter l'option -o (traiter seulement les fonctionnalités listées)
if ($only_features ne "") {
# désactiver toutes les fontionnalités
foreach my $key (keys %feature) {
$feature{$key}=0;
}
# réactiver uniquement cells de la liste fournie
my @restricted_liste = split(/ *[ ,;] */,$only_features);
foreach my $val (@restricted_liste) {
$feature{$val}=1;
}
}
# Si nom de fichier vide afficher syntaxe
if ($inputfile eq "") {
print_syntaxe();
}
# Tester le paramètre input (-i)
if ($inputfile=~/\*|\?/) {
process_many_files($inputfile,$exclude_files);
}
else {
if (-e $inputfile) {
# Attention BUG en perspective - PROVISOIRE (pas le temps)
# Il faut d'abord séparer chemin du nom de fichier
process_one_file(".",$inputfile);
}
else {
print "\n$inputfile n'existe pas !\n";
print_syntaxe();
}
}
if ($debug_level eq 1) {
print @language_context_stack;
}
# Fin du script
|
__label__pos
| 0.999799 |
summaryrefslogtreecommitdiff
path: root/ext/psych/lib/psych/nodes/node.rb
blob: 1c7672164d3e5eec8956f8b38e1408a31693a7a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true
require 'stringio'
require 'psych/class_loader'
require 'psych/scalar_scanner'
module Psych
module Nodes
###
# The base class for any Node in a YAML parse tree. This class should
# never be instantiated.
class Node
include Enumerable
# The children of this node
attr_reader :children
# An associated tag
attr_reader :tag
# Create a new Psych::Nodes::Node
def initialize
@children = []
end
###
# Iterate over each node in the tree. Yields each node to +block+ depth
# first.
def each &block
return enum_for :each unless block_given?
Visitors::DepthFirst.new(block).accept self
end
###
# Convert this node to Ruby.
#
# See also Psych::Visitors::ToRuby
def to_ruby
Visitors::ToRuby.create.accept(self)
end
alias :transform :to_ruby
###
# Convert this node to YAML.
#
# See also Psych::Visitors::Emitter
def yaml io = nil, options = {}
real_io = io || StringIO.new(''.encode('utf-8'))
Visitors::Emitter.new(real_io, options).accept self
return real_io.string unless io
io
end
alias :to_yaml :yaml
end
end
end
|
__label__pos
| 0.850505 |
You are here
How does SEM computational complexity in OpenMx scale with sample size?
3 posts / 0 new
Last post
EDG's picture
EDG
Offline
Joined: 06/03/2011 - 23:22
How does SEM computational complexity in OpenMx scale with sample size?
Sorry if this is a question that is answered elsewhere, but does anyone know how the time to compute a full SEM in OpenMx scales with the number of subjects that are used?
Thanks!
tbrick's picture
Offline
Joined: 07/31/2009 - 15:10
Time should scale linearly
Time should scale linearly with the number of data rows in a full information computation in OpenMx. So twice as many rows = twice as much time.
Now, some caveats:
There's some variance in how long a row can take, so using twice as many rows may take a little more or less than twice as much time. I'd actually expect that more often it will take less than twice as long, but it's tough to say for certain.
I'm assuming here that you're not adding any free parameters and not changing the likelihood space too much by adding these new rows. I would imagine that adding more rows from the same population will not significantly alter the likelihood space, but I don't know that for sure.
I'm also assuming you're not reaching the limits of your machine's main memory or anything--for very very large data sets you can run into other bottlenecks. R might have some limits as well. But that shouldn't kick in until the data get very, very large.
And, of course, if you're using a covariance method, the compute time's the same regardless of the number of participants.
carey's picture
Offline
Joined: 10/19/2009 - 15:38
tim, question: does OpenMx
tim,
question: does OpenMx have (or is going to have) a mechanism for sorting individual vectors according to pattern and then solving using the summary statistics for a pattern?
e.g., say there are 1000 nuclear families, but they are of two types: (1) mother, father, one offspring, and (2) mother, father, two offspring. the most efficient way to fit models is to compute t(X) %*% X for each type and then fit a model to the uncorrected SSCP matrix for the two groups. this is easily done with OpenMx.
in real life, those 1000 pedigrees are likely to have several dozen types along with a number of unique families. here, it can be very tedious and error prone to get the correct means and covariance matrices for each type. having OpenMx sort the pedigrees and compute summary statistics up front would be a great benefit to the user.
best,
greg
|
__label__pos
| 0.909226 |
Skip to content
Instantly share code, notes, and snippets.
@mhawksey
Created November 23, 2011 10:03
Embed
What would you like to do?
TAGS 2.4.4 Google Apps Script to pull searches from the Twitter API into a Google Spreadsheet (see http://bit.ly/TAGSsetup )
// Part of this code up to END OF (c) is:
/*
Copyright 2011 Martin Hawksey
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
var REFERER = sumSheet.getRange("B9").getValue();
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var SEARCH_DURATION = sumSheet.getRange("B11").getValue();
var NUMBER_OF_TWEETS = sumSheet.getRange("B12").getValue();
var RESULT_TYPE = sumSheet.getRange("B13").getValue();
function onOpen() {
var menuEntries = [ {name: "API Authentication", functionName: "configureAPI"}, {name:"Test Collection", functionName: "testCollection"}, {name: "Run Now!", functionName: "collectTweets"} ];
ss.addMenu("Twitter", menuEntries);
}
function authenticate(){
authorize();
}
function configureAPI() {
renderAPIConfigurationDialog();
}
function renderAPIConfigurationDialog() {
// modified from Twitter Approval Manager
// http://code.google.com/googleapps/appsscript/articles/twitter_tutorial.html
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle(
"Twitter API Authentication Configuration").setHeight(400).setWidth(420);
app.setStyleAttribute("padding", "10px");
//var dialog = app.loadComponent("GUIComponent");
var dialogPanel = app.createFlowPanel().setWidth("400px");
var label1 = app.createLabel("1. Register for an API key with Twitter at http://dev.twitter.com/apps/new (if you've already registered a Google Spreadsheet/Twitter mashup you can reuse your existing Consumer Key/Consumer Secret). In the form these are the important bits: ").setStyleAttribute("paddingBottom", "10px");
var label2 = app.createLabel(" - Application Website = anything you like").setStyleAttribute("textIndent", "30px");
var label3 = app.createLabel(" - Application Type = Browser").setStyleAttribute("textIndent", "30px");
var label4 = app.createLabel(" - Callback URL = https://spreadsheets.google.com/macros").setStyleAttribute("textIndent", "30px");
var label5 = app.createLabel(" - Default Access type = Read-only ").setStyleAttribute("textIndent", "30px").setStyleAttribute("paddingBottom", "10px");
var label6 = app.createLabel("2. Once finished filling in the form and accepting Twitter's terms and conditions you'll see a summary page which includes a Consumer Key and Consumer Secret which you need to enter below").setStyleAttribute("paddingBottom", "10px");
var label7 = app.createLabel("3. When your Key and Secret are saved you need to open Tools > Script Editor ... and run the 'authenticate' function").setStyleAttribute("paddingBottom", "10px");
//("<strong>hello</strong><ul><li>one</li></ul>");
dialogPanel.add(label1);
dialogPanel.add(label2);
dialogPanel.add(label3);
dialogPanel.add(label4);
dialogPanel.add(label5);
dialogPanel.add(label6);
dialogPanel.add(label7);
var consumerKeyLabel = app.createLabel(
"Twitter OAuth Consumer Key:");
var consumerKey = app.createTextBox();
consumerKey.setName("consumerKey");
consumerKey.setWidth("90%");
consumerKey.setText(getConsumerKey());
var consumerSecretLabel = app.createLabel(
"Twitter OAuth Consumer Secret:");
var consumerSecret = app.createTextBox();
consumerSecret.setName("consumerSecret");
consumerSecret.setWidth("90%");
consumerSecret.setText(getConsumerSecret());
var saveHandler = app.createServerClickHandler("saveConfiguration");
var saveButton = app.createButton("Save Configuration", saveHandler);
var listPanel = app.createGrid(2, 2);
listPanel.setStyleAttribute("margin-top", "10px")
listPanel.setWidth("100%");
listPanel.setWidget(0, 0, consumerKeyLabel);
listPanel.setWidget(0, 1, consumerKey);
listPanel.setWidget(1, 0, consumerSecretLabel);
listPanel.setWidget(1, 1, consumerSecret);
// Ensure that all form fields get sent along to the handler
saveHandler.addCallbackElement(listPanel);
//var dialogPanel = app.createFlowPanel();
//dialogPanel.add(helpLabel);
dialogPanel.add(listPanel);
dialogPanel.add(saveButton);
app.add(dialogPanel);
doc.show(app);
}
function collectTweets() {
// if continuous sheetname = archive else make a name
if (RESULT_TYPE == "continuous"){
var sheetName = "Archive";
} else {
var sheetName = Utilities.formatDate(new Date(), "GMT", "dd-MMM-yy hh:mm"); //make a new sheet name based on todays date
}
// if sheetname doesn't exisit make it
if (!ss.getSheetByName(sheetName)){
var temp = ss.getSheetByName("TMP");
var sheet = ss.insertSheet(sheetName, {template:temp});
} else {
var sheet = ss.getSheetByName(sheetName);
}
// else if already have archive get since id
var stored = getRowsData(sheet);
if (stored.length >0 ){
var sinceid = stored[0]["id_str"];
}
//if no since id grab search results
if (sinceid){
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS, sinceid); // get results from twitter sinceid
} else {
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS); // get results from twitter
}
// if some data insert rows
if (data.length>0){
sheet.insertRowsAfter(1, data.length);
setRowsData(sheet, data);
}
}
function testCollection(){
var data = getTweets(SEARCH_TERM, 5); // get results from twitter
if (data.length>0){
Browser.msgBox("Found some tweets. Here's an example one from "+data[0]["from_user"]+" which says: "+data[0]["text"]);
} else {
Browser.msgBox("Twitter said: "+ScriptProperties.getProperty("errormsg"));
}
}
function getTweets(searchTerm, maxResults, sinceid, languageCode) {
//Based on Mikael Thuneberg getTweets - mod by mhawksey to convert to json
// if you include setRowsData this can be used to output chosen entries
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
} else {
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}}
}
try {
var pagenum = 1;
var data =[];
var idx = 0;
var sinceurl ="";
// prepare search term
if (SEARCH_DURATION != "default"){
var period = 0;
switch (SEARCH_DURATION){
case "yesterday":
period = 0;
break;
case "-2 days":
period = 1;
break;
case "-3 days":
period = 2;
break;
case "-4 days":
period = 3;
break;
case "-5 days":
period = 4;
break;
case "-6 days":
period = 5;
break;
case "-7 days":
period = 6;
break;
}
var until=new Date();
until.setDate(until.getDate());
var since = new Date(until);
since.setDate(since.getDate()-1);
}
if (typeof maxResults == "undefined") {
maxResults = 100;
}
if (maxResults > 1500) {
maxResults = 1500;
}
if (maxResults > 100) {
resultsPerPage = 100;
maxPageNum = maxResults / 100;
} else {
resultsPerPage = maxResults;
maxPageNum = 1;
}
if (sinceid != null && sinceid.length > 0) {
sinceurl = "&since_id=" + sinceid;
}
//Logger.log(twDate(since)+" "+twDate(until));
searchTerm = encodeURIComponent(searchTerm);
var baseURL = "http://search.twitter.com/search.json";
for (pagenum = 1; pagenum <= maxPageNum; pagenum++) {
var URL = "";
if (typeof nextPage != "undefined"){
URL = nextPage;
} else if (pagenum == 1) {
URL = URL + "?q=" + searchTerm;
if (typeof since != "undefined") URL = URL + "&since=" + twDate(since);
if (typeof until != "undefined") URL = URL + "&until=" + twDate(until);
URL = URL + "&rpp=" + resultsPerPage;
URL = URL + "&page=" + pagenum;
URL = URL + "&result_type=recent";
URL = URL + "&include_entities=true";
URL = URL + "&with_twitter_user_id=true";
URL = URL + sinceurl;
if (typeof languageCode != "undefined") {
if (languageCode.length > 0) {
URL = URL + "&lang=" + languageCode;
}
}
}
if (URL != ""){
Logger.log(URL);
var response = UrlFetchApp.fetch(baseURL+URL, requestData);
var contentHeader = response.getHeaders();
if (response.getResponseCode() == 200) {
var responseData = Utilities.jsonParse(response.getContentText());
var nextPage = responseData.next_page;
var currentPage = responseData.page;
var objects = responseData.results;
for (i in objects){ // not pretty but I wanted to extract geo data
if (objects[i].geo != null){
objects[i]["geo_coordinates"] = "loc: "+objects[i].geo.coordinates[0]+","+objects[i].geo.coordinates[1];
}
objects[i]["status_url"] = "http://twitter.com/"+objects[i].from_user+"/statuses/"+objects[i].id_str;
objects[i]["time"] = (objects[i]["created_at"]).substring(5,25);
objects[i]["entities_str"] = Utilities.jsonStringify(objects[i]["entities"]);
data[idx]=objects[i];
idx ++;
}
}
}
}
return data;
} catch (e) {
Logger.log("Line "+e.lineNumber+" "+e.message+e.name);
Browser.msgBox("Line "+e.lineNumber+" "+e.message+e.name);
ScriptProperties.setProperty("errormsg","Line "+e.lineNumber+" "+e.message+e.name);
return data;
}
}
function twDate(aDate){
var dateString = Utilities.formatDate(aDate, "GMT", "yyyy-MM-dd");
return dateString;
}
// END OF (c)
// The rest of this code is currently (c) Google Inc.
// setRowsData fills in one row of data per object defined in the objects Array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the Sheet Object where the data will be written
// - objects: an Array of Objects, each of which contains data for a row
// - optHeadersRange: a Range of cells where the column headers are defined. This
// defaults to the entire first row in sheet.
// - optFirstDataRowIndex: index of the first row where data should be written. This
// defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
var headers = normalizeHeaders(headersRange.getValues()[0]);
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
}
data.push(values);
}
var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
objects.length, headers.length);
destinationRange.setValues(data);
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// This argument is optional and it defaults to all the cells except those in the first row
// or all the cells below columnHeadersRowIndex (if defined).
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
var headersIndex = columnHeadersRowIndex || range ? range.getRowIndex() - 1 : 1;
var dataRange = range ||
sheet.getRange(headersIndex + 1, 1, sheet.getMaxRows() - headersIndex, sheet.getMaxColumns());
var numColumns = dataRange.getEndColumn() - dataRange.getColumn() + 1;
var headersRange = sheet.getRange(headersIndex, dataRange.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(dataRange.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Empty Strings are returned for all Strings that could not be successfully normalized.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
keys.push(normalizeHeader(headers[i]));
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
//if (!isAlnum(letter)) { // I removed this because result identifiers have '_' in name
// continue;
//}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// The first part of this code was developed by google and has a copyright statement.
// Everything after // Archive Twitter Status Updates is by mhawksey and released under CC
// Copyright 2010 Google Inc. All Rights Reserved.
/**
* @fileoverview Google Apps Script demo application to illustrate usage of:
* MailApp
* OAuthConfig
* ScriptProperties
* Twitter Integration
* UiApp
* UrlFetchApp
*
* @author [email protected] (Vic Fryzel)
*/
/**
* Key of ScriptProperty for Twitter consumer key.
* @type {String}
* @const
*/
var CONSUMER_KEY_PROPERTY_NAME = "twitterConsumerKey";
/**
* Key of ScriptProperty for Twitter consumer secret.
* @type {String}
* @const
*/
var CONSUMER_SECRET_PROPERTY_NAME = "twitterConsumerSecret";
/**
* Key of ScriptProperty for tweets and all approvers.
* @type {String}
* @const
*/
var TWEETS_APPROVERS_PROPERTY_NAME = "twitterTweetsWithApprovers";
/**
* @param String Approver email address required to give approval
* prior to a tweet going live. Comma-delimited.
*/
function setApprovers(approvers) {
ScriptProperties.setProperty(APPROVERS_PROPERTY_NAME, approvers);
}
/**
* @return String OAuth consumer key to use when tweeting.
*/
function getConsumerKey() {
var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
if (key == null) {
key = "";
}
return key;
}
/**
* @param String OAuth consumer key to use when tweeting.
*/
function setConsumerKey(key) {
ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
}
/**
* @return String OAuth consumer secret to use when tweeting.
*/
function getConsumerSecret() {
var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
if (secret == null) {
secret = "";
}
return secret;
}
/**
* @param String OAuth consumer secret to use when tweeting.
*/
function setConsumerSecret(secret) {
ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
}
/**
* @return bool True if all of the configuration properties are set,
* false if otherwise.
*/
function isConfigured() {
return getConsumerKey() != "" && getConsumerSecret != "" ;
}
/** Retrieve config params from the UI and store them. */
function saveConfiguration(e) {
setConsumerKey(e.parameter.consumerKey);
setConsumerSecret(e.parameter.consumerSecret);
var app = UiApp.getActiveApplication();
app.close();
return app;
}
/**
* Authorize against Twitter. This method must be run prior to
* clicking any link in a script email. If you click a link in an
* email, you will get a message stating:
* "Authorization is required to perform that action."
*/
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": "GET",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"http://api.twitter.com/1/account/verify_credentials.json",
requestData);
var o = Utilities.jsonParse(result.getContentText());
ScriptProperties.setProperty("STORED_SCREEN_NAME", o.screen_name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
|
__label__pos
| 0.994911 |
Common PHP question asked in interview
41. How do I escape data before storing it into the database?
addslashes function enables us to escape data before storage into the database.
42. How is it possible to remove escape characters from a string?
The stripslashes function enables us to remove the escape characters before apostrophes in a string.
43. How can we automatically escape incoming data?
We have to enable the Magic quotes entry in the configuration file of PHP.
44. What does the function get_magic_quotes_gpc() means?
The function get_magic_quotes_gpc() tells us whether the magic quotes is switched on or no.
45. Is it possible to remove the HTML tags from data?
The strip_tags() function enables us to clean a string from the HTML tags.
46. what is the static variable in function useful for?
A static variable is defined within a function only the first time and its value can be modified during function calls as follows:
<?php function testFunction() { static $testVariable = 1; echo $testVariable; $testVariable++; } testFunction(); //1 testFunction(); //2 testFunction(); //3 ?>
47. How can we define a variable accessible in functions of a PHP script?
This feature is possible using the global keyword.
48. How is it possible to return a value from a function?
A function returns a value using the instruction ‘return $value;’.
49. What is the most convenient hashing method to be used to hash passwords?
It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. hence, hashing passwords with these algorithms can vulnerability.
50. Which cryptographic extension provide generation and verification of digital signatures?
The PHP-openssl extension provides several cryptographic operations including generation and verification of digital signatures.
User Answer
1. Be the first one to express your answer.
Common PHP question asked in interview
|
__label__pos
| 0.969174 |
Hi,
I write a script to set pose IK <=> FK,the code is work.
But when i used code and undo, is error.
my code source from:
http://dskjal.com/blender/ik-fk-snap.html
And error reproduce:
1.Run the code
2.Move foot IK target
001-????IK??.png
3.Click button
002-??????.png
4.undo and error
And code:
Code:
import bpy
import mathutils
#When Selected bone in list,show VIEW_3D panel
showButtonBoneList = [\
'C.IK.L',\
'C.IK.R',\
'C.handIK.L',\
'C.handIK.R',\
'C.shinC.L',\
'C.shinC.R',\
'C.forearm.L',\
'C.forearm.R',\
'C.Legtag.L',\
'C.Legtag.R',\
'C.upper_armTag.L',\
'C.upper_armTag.R',\
'C.head',\
'C.head.Tag'\
]
#ikBones is a dict for selected bones IK relation
#Key = selected bone name
#Value =
#[
#name display on panel, 0
#IK Bone name, 1
#constraints name 2
#IK count, 3
#Pole bone 4
#Pole bone connecter bone 5
#IK target 6
#]
ikBones = {\
'C.shinC.L':['L Foot IK:','C.shinC.L','IK',2,'C.Legtag.L','C.LegtagC.L','C.IK.L'],\
'C.IK.L':['L Foot IK:','C.shinC.L','IK',2,'C.Legtag.L','C.LegtagC.L','C.IK.L'],\
'C.Legtag.L':['L Foot IK:','C.shinC.L','IK',2,'C.Legtag.L','C.LegtagC.L','C.IK.L'],\
\
'C.shinC.R':['R Foot IK:','C.shinC.R','IK',2,'C.Legtag.R','C.LegtagC.R','C.IK.R'],\
'C.IK.R':['R Foot IK:','C.shinC.R','IK',2,'C.Legtag.R','C.LegtagC.R','C.IK.R'],\
'C.Legtag.R':['R Foot IK:','C.shinC.R','IK',2,'C.Legtag.R','C.LegtagC.R','C.IK.R'],\
\
'C.forearm.L':['L Hand IK:','C.forearm.L','IK',2,'C.upper_armTag.L','C.upperarmTagC.L','C.handIK.L'],\
'C.handIK.L':['L Hand IK:','C.forearm.L','IK',2,'C.upper_armTag.L','C.upperarmTagC.L','C.handIK.L'],\
'C.upper_armTag.L':['L Hand IK:','C.forearm.L','IK',2,'C.upper_armTag.L','C.upperarmTagC.L','C.handIK.L'],\
\
'C.forearm.R':['R Hand IK:','C.forearm.R','IK',2,'C.upper_armTag.R','C.upperarmTagC.R','C.handIK.R'],\
'C.handIK.R':['R Hand IK:','C.forearm.R','IK',2,'C.upper_armTag.R','C.upperarmTagC.R','C.handIK.R'],\
'C.upper_armTag.R':['R Hand IK:','C.forearm.R','IK',2,'C.upper_armTag.R','C.upperarmTagC.R','C.handIK.R'],\
\
'C.head':['Head LookAt','C.head','LookAt',1,'C.head.Tag','C.head.TagC',''],\
'C.head.Tag':['Head LookAt','C.head','LookAt',1,'C.head.Tag','C.head.TagC',''],\
}
amt = bpy.data.objects["ActorMetarig"]
#IK/FKFunction
'''
def set_ik(data_path):
set_ik_influence(data_path, 1.0)
def set_fk(data_path):
set_ik_influence(data_path, 0.0)
'''
def set_translation(matrix, loc):
trs = matrix.decompose()
rot = trs[1].to_matrix().to_4x4()
scale = mathutils.Matrix.Scale(1, 4, trs[2])
return mathutils.Matrix.Translation(loc) * (rot * scale)
#UI
class UIPanel(bpy.types.Panel):
bl_label = "Actor Rig IK/FK Snap"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
#Check Selected and show bottom
@classmethod
def poll(cls, context):
selectedBoneCount = -1
try:
selectedBoneCount = len(bpy.context.selected_pose_bones)
except:
selectedBoneCount = -1
if selectedBoneCount == 1:
return bpy.context.selected_pose_bones[0].name in showButtonBoneList
def draw(self, context):
seletced = ikBones[bpy.context.selected_pose_bones[0].name]
l = self.layout
l.label(seletced[0])
l.prop(amt.pose.bones[seletced[1]].constraints[seletced[2]],'influence',slider=True)
l.operator('my.iktofk')
l.operator('my.fktoik')
class IKtoFKButton(bpy.types.Operator):
bl_idname = "my.iktofk"
bl_label = "IK -> FK"
def execute(self, context):
#Set Selected
selected = ikBones[bpy.context.selected_pose_bones[0].name]
ik_bone = amt.pose.bones[selected[1]]
if(selected[1] != 'C.head'):
ik_target = amt.pose.bones[selected[6]]
ik_pole = amt.pose.bones[selected[4]]
ik_connecter = amt.pose.bones[selected[5]]
influence_data_path = ik_bone.constraints[selected[2]].influence
#copy fk matrix
#set_fk(influence_data_path)
ik_bone.constraints[selected[2]].influence = 0
#pose update
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='POSE')
if(selected[1] != 'C.head'):
#set ik target
ik_target.matrix = set_translation(ik_target.matrix, ik_bone.tail)
#set pole target
ik_pole.matrix = set_translation(ik_pole.matrix, ik_connecter.tail)
return {'FINISHED'}
class FKtoIKButton(bpy.types.Operator):
bl_idname = "my.fktoik"
bl_label = "FK -> IK"
def execute(self, context):
#Set Selected
selected = ikBones[bpy.context.selected_pose_bones[0].name]
ik_bone = amt.pose.bones[selected[1]]
influence_data_path = ik_bone.constraints[selected[2]].influence
num_bones = selected[3]
# copy ik matrix
ik_bone.constraints[selected[2]].influence = 1
#pose update
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='POSE')
ik_bone_matrixes = []
it = ik_bone
for i in range(num_bones):
ik_bone_matrixes.append(it.matrix)
it = ik_bone.parent
# set ik matrix to fk bone
ik_bone.constraints[selected[2]].influence = 0
it = ik_bone
for i in range(num_bones):
it.matrix = ik_bone_matrixes[i]
it = it.parent
return {'FINISHED'}
def register():
bpy.utils.register_module(__name__)
def unregister():
bpy.utils.unregister_module(__name__)
if __name__ == "__main__":
register()
#bpy.context.active_bone.matrix.to_quaternion()
and file:
ErrorFile.zip
|
__label__pos
| 0.828953 |
summaryrefslogtreecommitdiff
path: root/test/number.c
blob: d255f4c7c3bbf219a65907a3fb51b9fcaa952a3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <libcss/libcss.h>
#include "utils/utils.h"
#include "testutils.h"
typedef struct line_ctx {
size_t buflen;
size_t bufused;
uint8_t *buf;
size_t explen;
char exp[256];
bool indata;
bool inexp;
} line_ctx;
static bool handle_line(const char *data, size_t datalen, void *pw);
static void run_test(const uint8_t *data, size_t len,
const char *exp, size_t explen);
static void print_css_fixed(char *buf, size_t len, css_fixed f);
int main(int argc, char **argv)
{
line_ctx ctx;
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
ctx.buflen = css__parse_filesize(argv[1]);
if (ctx.buflen == 0)
return 1;
ctx.buf = malloc(ctx.buflen);
if (ctx.buf == NULL) {
printf("Failed allocating %u bytes\n",
(unsigned int) ctx.buflen);
return 1;
}
ctx.buf[0] = '\0';
ctx.bufused = 0;
ctx.explen = 0;
ctx.indata = false;
ctx.inexp = false;
assert(css__parse_testfile(argv[1], handle_line, &ctx) == true);
/* and run final test */
if (ctx.bufused > 0)
run_test(ctx.buf, ctx.bufused - 1, ctx.exp, ctx.explen);
free(ctx.buf);
printf("PASS\n");
return 0;
}
bool handle_line(const char *data, size_t datalen, void *pw)
{
line_ctx *ctx = (line_ctx *) pw;
if (data[0] == '#') {
if (ctx->inexp) {
/* This marks end of testcase, so run it */
run_test(ctx->buf, ctx->bufused - 1,
ctx->exp, ctx->explen);
ctx->buf[0] = '\0';
ctx->bufused = 0;
ctx->explen = 0;
}
if (ctx->indata && strncasecmp(data+1, "expected", 8) == 0) {
ctx->indata = false;
ctx->inexp = true;
} else if (!ctx->indata) {
ctx->indata = (strncasecmp(data+1, "data", 4) == 0);
ctx->inexp = (strncasecmp(data+1, "expected", 8) == 0);
} else {
memcpy(ctx->buf + ctx->bufused, data, datalen);
ctx->bufused += datalen;
}
} else {
if (ctx->indata) {
memcpy(ctx->buf + ctx->bufused, data, datalen);
ctx->bufused += datalen;
}
if (ctx->inexp) {
if (data[datalen - 1] == '\n')
datalen -= 1;
memcpy(ctx->exp, data, datalen);
ctx->explen = datalen;
}
}
return true;
}
void run_test(const uint8_t *data, size_t len, const char *exp, size_t explen)
{
lwc_string *in;
size_t consumed;
css_fixed result;
char buf[256];
UNUSED(exp);
UNUSED(explen);
assert(lwc_intern_string((const char *)data, len, &in) == lwc_error_ok);
result = css__number_from_lwc_string(in, false, &consumed);
print_css_fixed(buf, sizeof(buf), result);
printf("got: %s expected: %.*s\n", buf, (int) explen, exp);
assert(strncmp(buf, exp, explen) == 0);
lwc_string_unref(in);
}
void print_css_fixed(char *buf, size_t len, css_fixed f)
{
#define ABS(x) (uint32_t)((x) < 0 ? -(x) : (x))
uint32_t uintpart = FIXTOINT(ABS(f));
/* + 500 to ensure round to nearest (division will truncate) */
uint32_t fracpart = ((ABS(f) & 0x3ff) * 1000 + 500) / (1 << 10);
#undef ABS
size_t flen = 0;
char tmp[20];
size_t tlen = 0;
if (len == 0)
return;
if (f < 0) {
buf[0] = '-';
buf++;
len--;
}
do {
tmp[tlen] = "0123456789"[uintpart % 10];
tlen++;
uintpart /= 10;
} while (tlen < 20 && uintpart != 0);
while (len > 0 && tlen > 0) {
buf[0] = tmp[--tlen];
buf++;
len--;
}
if (len > 0) {
buf[0] = '.';
buf++;
len--;
}
do {
tmp[tlen] = "0123456789"[fracpart % 10];
tlen++;
fracpart /= 10;
} while (tlen < 20 && fracpart != 0);
while (len > 0 && tlen > 0) {
buf[0] = tmp[--tlen];
buf++;
len--;
flen++;
}
while (len > 0 && flen < 3) {
buf[0] = '0';
buf++;
len--;
flen++;
}
if (len > 0) {
buf[0] = '\0';
buf++;
len--;
}
}
|
__label__pos
| 0.977077 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I have a Presenter that takes a Service and a View Contract as parameters in its constructor:
public FooPresenter : IFooPresenter {
private IFooView view;
private readonly IFooService service;
public FooPresenter(IFooView view, IFooService service) {
this.view = view;
this.service = service;
}
}
I resolve my service with Autofac:
private ContainerProvider BuildDependencies() {
var builder = new ContainerBuilder();
builder.Register<FooService>().As<IFooService>().FactoryScoped();
return new ContainerProvider(builder.Build());
}
In my ASPX page (View implementation):
public partial class Foo : Page, IFooView {
private FooPresenter presenter;
public Foo() {
// this is straightforward but not really ideal
// (IoCResolve is a holder for how I hit the container in global.asax)
this.presenter = new FooPresenter(this, IoCResolve<IFooService>());
// I would rather have an interface IFooPresenter so I can do
this.presenter = IoCResolve<IFooPresenter>();
// this allows me to add more services as needed without having to
// come back and manually update this constructor call here
}
}
The issue is FooPresenter's constructor expects the specific Page, not for the container to create a new one.
Can I supply a specific instance of the view, the current page, to the container for just this resolution? Does that make sense to do, or should I do this another way?
share|improve this question
2 Answers 2
up vote 2 down vote accepted
The way to solve passing what I like to call data parameters when resolving dependencies in Autofac is by using generated factories.
(Update: this question discusses the same problem and my article shows how you can avoid large amounts of factory delegates).
The solution to your problem will look something like this:
First, declare a factory delegate thath only accepts the data parameters:
public delegate IFooPresenter FooPresenterFactory(IFooView view);
Your presenter goes unchanged:
public FooPresenter : IFooPresenter {
private IFooView view;
private readonly IFooService service;
public FooPresenter(IFooView view, IFooService service) {
this.view = view;
this.service = service;
}
}
Next the Autofac container setup:
var builder = new ContainerBuilder();
builder.Register<FooService>().As<IFooService>().FactoryScoped();
builder.Register<FooPresenter>().As<IFooPresenter>().FactoryScoped();
builder.RegisterGeneratedFactory<FooPresenterFactory>();
Now in your page you can in two lines of code resolve the presenter by first getting the factory and then calling the factory to do the resolution for you:
public partial class Foo : Page, IFooView {
private FooPresenter presenter;
public Foo() {
var factory = IoCResolve<FooPresenterFactory>();
this.presenter = factory(this);
}
}
share|improve this answer
Excellent solution. Thanks for pointing it out. I hadn't really grasped generated factories until now. – Bryan Watts Dec 18 '09 at 8:03
I am working out how to do this at an abstract level. My current framework allows views to be decorated with [Presenter(typeof(FooPresenter))] (so the boilerplate resolution code is eliminated). With generated factories, I won't know which specific factory type to resolve without more metadata. I will probably use builder.RegisterGeneratedFactory<Func<TView, TPresenter>>(); behind an extension method RegisterPresenter<T> which discovers the view type via reflection. Anyways, thanks for the inspiration! – Bryan Watts Dec 18 '09 at 8:24
You could also try out my generic factory sample (link to the article in my sample). You would only have to register one generic factory that can build any presenter dynamically. It should even be possible to couple that with your Presenter attribute minimizing both boilerplate resolution code AND boilerplate container setup :) – Peter Lillevold Dec 18 '09 at 8:43
+1 This looks clean and straightforward, I will check it out later and see how it goes. Thanks for the reply. – blu Dec 18 '09 at 14:41
I read through your article. I wanted to verify this delegate signature: public delegate T ServiceFactory() where T:class;. T needs to be declared somewhere, which means it should be ServiceFactory<T>(). This would change CustomerController's constructor to use ServiceFactory<CustomerService> as the parameter type. Does that sound right? – Bryan Watts Dec 18 '09 at 14:49
I actually solved this exact problem and built a framework around it. I used Autofac parameters to pass existing views to the presenter resolution call.
First, I defined a custom resolution interface derived from Autofac's:
public interface IMvpContext : IContext
{
T View<T>();
}
which allowed me to register a presenter which resolves the view:
builder.RegisterPresenter(c => new FooPresenter(
c.View<IFooView>(),
c.Resolve<IFooService>()));
using an extension method which wraps Autofac's IContext in an implementation of IMvpContext:
public static IConcreteRegistrar RegisterPresenter<T>(
this ContainerBuilder builder,
Func<IMvpContext, T> creator)
{
return builder
.Register((context, parameters) => creator(new MvpContext(context, parameters)))
.FactoryScoped();
}
I defined a parameter type representing the view parameter:
public class MvpViewParameter : NamedParameter
{
public static readonly string ParameterName = typeof(MvpViewParameter).AssemblyQualifiedName;
public MvpViewParameter(object view) : base(ParameterName, view)
{}
}
It uses its own assembly-qualified type name as the parameter name. This has a very low likelihood of conflicting with legitimate parameters.
MvpContext passes all standard resolution calls to the base context. For the view, it resolves the parameter with the well-known name:
public sealed class MvpContext : IMvpContext
{
private IContext _context;
private IEnumerable<Parameter> _resolutionParameters;
public MvpContext(IContext context, IEnumerable<Parameter> resolutionParameters)
{
_context = context;
_resolutionParameters = resolutionParameters;
}
#region IContext
// Pass through all calls to _context
#endregion
#region IMvpContext
public T View<T>()
{
return _resolutionParameters.Named<T>(MvpViewParameter.ParameterName);
}
#endregion
}
The call to resolve the presenter provides the view parameter:
public partial class Foo : Page, IFooView
{
private readonly FooPresenter presenter;
public Foo()
{
this.presenter = IoCResolve<IFooPresenter>(new MvpViewParameter(this));
}
}
share|improve this answer
This is unnecessarily complex. Do this using the built-in generated factory stuff and you can drop the whole MvpContext parameter thing. – Peter Lillevold Dec 18 '09 at 7:28
(See the comments on @Peter's answer for further discussion of this approach.) – Bryan Watts Dec 22 '09 at 15:40
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.915025 |
Permalink
Fetching contributors…
Cannot retrieve contributors at this time
85 lines (84 sloc) 3.57 KB
# This is basically the config file we use in production at Yelp, with some
# strategic edits. ;)
#
# If you don't have the yaml module installed, you'll have to use JSON instead,
# which would look something like this:
#
# {"runners": {
# "emr": {
# "aws_access_key_id": "HADOOPHADOOPBOBADOOP",
# "aws_region": "us-west-1",
# "aws_secret_access_key": "MEMIMOMADOOPBANANAFANAFOFADOOPHADOOP",
# "base_tmp_dir": "/scratch/$USER"
# "bootstrap_python_packages": [
# "$BT/aws/python-packages/*.tar.gz"
# ],
# ...
#
runners:
emr:
aws_access_key_id: HADOOPHADOOPBOBADOOP
# We run on in the west region because we're located on the west coast,
# and there are no eventual consistency issues with newly created S3 keys.
aws_region: us-west-1
aws_secret_access_key: MEMIMOMADOOPBANANAFANAFOFADOOPHADOOP
# alternate tmp dir
base_tmp_dir: /scratch/$USER
# $BT is the path to our source tree. This lets us add modules to
# install on EMR by simply dumping them in this dir.
bootstrap_python_packages:
- $BT/aws/python-packages/*.tar.gz
# specifying an ssh key pair allows us to ssh tunnel to the job tracker
# and fetch logs via ssh
ec2_key_pair: EMR
ec2_key_pair_file: $BT/config/EMR.pem
# use beefier instances in production
ec2_instance_type: c1.xlarge
# but only use one unless overridden
num_ec2_instances: 1
# use our local time zone (this is important for deciding when
# days start and end, for instance)
cmdenv:
TZ: America/Los_Angeles
# we create the src-tree.tar.gz tarball with a Makefile. It only contains
# a subset of our code
python_archives: &python_archives
- $BT/aws/src-tree.tar.gz
# our bucket also lives in the us-west region
s3_log_uri: s3://walrus/tmp/logs/
s3_scratch_uri: s3://walrus/tmp/
setup_cmds: &setup_cmds
# these files are different between dev and production, so they're
# uploaded separately. copying them into place isn't safe because
# src-tree.tar.gz is actually shared between several mappers/reducers.
# Another safe approach would be to add a rule to Makefile.emr that
# copies these files if they haven't already been copied (setup_cmds
# from two mappers/reducers won't run simultaneously on the same machine)
- ln -sf $(readlink -f config.py) src-tree.tar.gz/config/config.py
- ln -sf $(readlink -f secret.py) src-tree.tar.gz/config/secret.py
# run Makefile.emr to compile C code (EMR has a different architecture,
# so we can't just upload the .so files)
- cd src-tree.tar.gz; make -f Makefile.emr
# generally, we run jobs on a Linux server separate from our desktop
# machine. So the SSH tunnel needs to be open so a browser on our
# desktop machine can connect to it.
ssh_tunnel_is_open: true
ssh_tunnel_to_job_tracker: true
# upload these particular files on the fly because they're different
# between development and production
upload_files: &upload_files
- $BT/config/config.py
- $BT/config/secret.py
hadoop:
# Note the use of YAML references to re-use parts of the EMR config.
# We don't currently run our own hadoop cluster, so this section is
# pretty boring.
base_tmp_dir: /scratch/$USER
python_archives: *python_archives
setup_cmds: *setup_cmds
upload_files: *upload_files
local:
# We don't have gcc installed in production, so if we have to run an
# MRJob in local mode in production, don't run the Makefile
# and whatnot; just fall back on the original copy of the code.
base_tmp_dir: /scratch/$USER
|
__label__pos
| 0.97017 |
Skip to content
Branch: master
Go to file
Code
Latest commit
Yash Goenka Yash Goenka
Yash Goenka authored and Yash Goenka committed 4387f24 Feb 19, 2020
Files
Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
README.md
C# wrapper for Instamojo API
Table of Contents
Preface
Instamojo DotNet wrapper for the Instamojo API assists you to programmatically create and list payment orders and refunds on Instamojo.
Requirements
DotNet Version: 4.0+
Integration
To integrate the Instamojo API into your application, download the source zip from the latest release and add it your project.
Authentication Keys
Generate CLIENT_ID and CLIENT_SECRET for specific environments from the following links.
Related support article: How Do I Get My Client ID And Client Secret?
Multitenancy
As of now, MULTITENANCY IS NOT SUPPORTED by this wrapper which means you will not be able to use this wrapper in a single application with multiple Instamojo accounts. The call to InstamojoImplementation.getApi() returns a singleton object of class Instamojo with the given CLIENT_ID and CLIENT_SECRET, and will always return the same object even when called multiple times (even with a different CLIENT_ID and CLIENT_SECRET).
End Points
Test URLs
auth_endpoint : https://test.instamojo.com/oauth2/token/
endpoint: https://test.instamojo.com/v2/
Production URLs
auth endpoint : https://www.instamojo.com/oauth2/token/
endpoint: https://api.instamojo.com/v2/
Payments API
Create new Payment Order
/***** Create a new payment order *******/
Instamojo objClass = InstamojoImplementation.getApi( “[client_id]”, “[client_secret]”, “[endpoint]”, “[auth_endpoint]”);
PaymentOrder objPaymentRequest = new PaymentOrder();
//Required POST parameters
objPaymentRequest.name = "ABCD";
objPaymentRequest.email = "[email protected]";
objPaymentRequest.phone = "0123456789";
objPaymentRequest.amount = 9;
objPaymentRequest.transaction_id = "test"; // Unique Id to be provided
objPaymentRequest.redirect_url =redirect_url”;
//webhook is optional.
objPaymentRequest.webhook_url = "https://your.server.com/webhook";
if (objPaymentRequest.validate())
{
if (objPaymentRequest.emailInvalid)
{
MessageBox.Show("Email is not valid");
}
if (objPaymentRequest.nameInvalid)
{
MessageBox.Show("Name is not valid");
}
if (objPaymentRequest.phoneInvalid)
{
MessageBox.Show("Phone is not valid");
}
if (objPaymentRequest.amountInvalid)
{
MessageBox.Show("Amount is not valid");
}
if (objPaymentRequest.currencyInvalid)
{
MessageBox.Show("Currency is not valid");
}
if (objPaymentRequest.transactionIdInvalid)
{
MessageBox.Show("Transaction Id is not valid");
}
if (objPaymentRequest.redirectUrlInvalid)
{
MessageBox.Show("Redirect Url Id is not valid");
}
if (objPaymentRequest.webhookUrlInvalid)
{
MessageBox.Show("Webhook URL is not valid");
}
}else
{
try
{
CreatePaymentOrderResponse objPaymentResponse = objClass.createNewPaymentRequest(objPaymentRequest);
MessageBox.Show("Payment URL = " + objPaymentResponse.payment_options.payment_url);
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (InvalidPaymentOrderException ex)
{
if (!ex.IsWebhookValid())
{
MessageBox.Show("Webhook is invalid");
}
if (!ex.IsCurrencyValid())
{
MessageBox.Show("Currency is Invalid");
}
if (!ex.IsTransactionIDValid())
{
MessageBox.Show("Transaction ID is Inavlid");
}
}
catch (ConnectionException ex)
{
MessageBox.Show(ex.Message);
}
catch (BaseException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
}
}
Payment Order Creation Parameters
Required
1. Name: Name of the customer (max 100 characters).
2. Email: Email address of the customer (max 75 characters).
3. Phone: Phone number of the customer. At this point, the wrapper only supports 10 digit indian phone number with out country code.
4. Currency: String identifier for the currency. Currently, only INR (for Indian Rupee) is supported.
5. Amount: Amount the customer has to pay. Numbers upto 2 decimal places are supported.
6. Transaction_id: Unique identifier for the order (max 64 characters). Identifier can contain alphanumeric characters, hyphens and underscores only. This is generally the unique order id (or primary key) in your system.
7. Redirect_url: Full URL to which the customer is redirected after payment. Redirection happens even if payment wasn't successful. This URL shouldn't contain any query parameters.
Optional
1. Description: Short description of the order (max 255 characters). If provided, this information is sent to backend gateways, wherever possible.
Get list of a Payment order
/***** Get list of a payment order *******/
Instamojo objClass = InstamojoImplementation.getApi( “[client_id]”, “[client_secret]”, “[endpoint]”, “[auth_endpoint]”);
try
{
PaymentOrderListRequest objPaymentOrderListRequest = new PaymentOrderListRequest();
//Optional Parameters
objPaymentOrderListRequest.limit = 20;
objPaymentOrderListRequest.page = 3;
PaymentOrderListResponse objPaymentRequestStatusResponse = objClass.getPaymentOrderList(objPaymentOrderListRequest);
MessageBox.Show("Order Count = " + objPaymentRequestStatusResponse.orders.Count());
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
}
Payment Order List Parameters
Optional
1. Id: Search for payment orders by id.
2. Transaction_id: Search for payment orders by your transaction_id.
3. Page: Page number of the results to retrieve from.
4. Limit: Limit the number of results returned per page. Defaults to 50 results per page. Max limit allowed is 500.
Details of Payment order using OrderId
/***** Get Details of Payment order using OrderId. *******/
Instamojo objClass = InstamojoImplementation.getApi( “[client_id]”, “[client_secret]”, “[endpoint]”, “[auth_endpoint]”);
try
{
PaymentOrderDetailsResponse objPaymentRequestDetailsResponse = objClass.getPaymentOrderDetails("[Order_Id]");
MessageBox.Show("Transaction Id = " + objPaymentRequestDetailsResponse.transaction_id);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
}
Details of Payment order using TransactionId
/***** Details of Payment order using TransactionId. *******/
Instamojo objClass = InstamojoImplementation.getApi( “[client_id]”, “[client_secret]”, “[endpoint]”, “[euth_endpoint]”);
try
{
PaymentOrderDetailsResponse objPaymentRequestDetailsResponse = objClass.getPaymentOrderDetailsByTransactionId("[Transaction_Id]");
MessageBox.Show("Transaction Id = " + objPaymentRequestDetailsResponse.transaction_id);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
}
Refund API
Create a refund
Refund objRefundRequest = new Refund();
objRefundRequest.payment_id = "MOJO6701005J41260385";
objRefundRequest.type = "TNR";
objRefundRequest.body = "abcd";
objRefundRequest.refund_amount = 9;
if (objRefundRequest.validate())
{
if (objRefundRequest.payment_idInvalid)
{
MessageBox.Show("payment_id is not valid");
}
}
else
{
try
{
CreateRefundResponce objRefundResponse = objClass.createNewRefundRequest(objRefundRequest);
MessageBox.Show("Refund Id = " + objRefundResponse.refund.id);
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (InvalidPaymentOrderException ex)
{
MessageBox.Show(ex.Message);
}
catch (ConnectionException ex)
{
MessageBox.Show(ex.Message);
}
catch (BaseException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message);
}
catch (BaseException ex)
{
MessageBox.Show("CustomException" + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Exception" + ex.Message);
}
}
Refund Creation Parameters
Required
1. payment_id: Id of the payment.
2. type: A three letter short-code identifying the reason for this case.
3. body: payment_idAdditional text explaining the refund.
4. refund_amount: This field can be used to specify the refund amount. For instance, you may want to issue a refund for an amount lesser than what was paid.
You can’t perform that action at this time.
|
__label__pos
| 0.967343 |
ZeniX D3D Menu Hack
Share
avatar
ZeniX
Member Newbie
Member Newbie
Thread & Post : 4
Point Forum : 246009
Thanks Given : 0
Join date : 02.08.11
default ZeniX D3D Menu Hack
Post by ZeniX on Sat Aug 06, 2011 5:55 am
Tools yang dibutuhkan :
VC +++ 2010
Microsoft DirectX 9.0 SDK (Summer 2004)
Okey setelah dapet Alat perang..
Langkah Pertama :
•Jalankan Visual C++ 2010 Express Edition, Setelah itu buat new Project.
•Pilih Visual C++, Empty Project dan namakan dengan zenix D3Dbase.
•Ok Project telah dibuat, Setelah itu buat Header setelah itu Klik pada Project dan pilih Add New Item.
Pilih Header File dan Namai dengan zenixMenuClass.h dan isikan code berikut :
zenixMenuClass.h
Spoiler:
//==================================================================
// This file is part of zenixbase d3d v1
// (c) copyright zenix 2010
// special thanks to:
// Alkatraz
// //mcz yang selalu dukung gw
// nyit-nyit.net
//==================================================================
#include "Functions.h"
typedef struct{
int index;
char * title;
int *hack;
int hackmaxval;
int hacktype;
DWORD HCOLOR;
}ITEM;
class zenixMenu {
public:
LPDIRECT3DDEVICE9 pDevice;
LPD3DXFONT pFont;
int hackcount;
int selector;
int x,y,w,h;
DWORD COLOR;
ITEM HACKITEM[99];
char hackrval[256];
void CreateItem(int index, char * title, int *hack,int hackmaxval=1,int hacktype=0);
void BuildMenu(char * menuname, int x, int y, int h, int w, DWORD TITLECOL, DWORD BACKCOLOR, DWORD BORDERCOLOR, LPDIRECT3DDEVICE9 pDevice);
void RenderMenu();
};
typedef HRESULT ( WINAPI* oReset )( LPDIRECT3DDEVICE9 pDevice, D3DPRESENT_PARAMETERS* pPresentationParameters );
typedef HRESULT (WINAPI* oEndScene)(LPDIRECT3DDEVICE9 pDevice);
//Colors A,R,G,B Gan Silahkan dipakai untuk membuat Chams
#define RED D3DCOLOR_ARGB(255, 255, 0, 0)
#define GREEN D3DCOLOR_ARGB(255, 0, 255, 0)
#define BLUE D3DCOLOR_ARGB(255, 0, 0, 255)
#define WHITE D3DCOLOR_ARGB(255, 255, 255, 255)
#define BLACK D3DCOLOR_ARGB(255, 0, 0, 0)
#define YELLOW D3DCOLOR_ARGB(255, 255, 255, 0)
#define TEAL D3DCOLOR_ARGB(255, 0, 255, 255)
#define PINK D3DCOLOR_ARGB(255, 255, 240, 0)
#define ORANGE D3DCOLOR_ARGB(255, 255, 132, 0)
#define LIME D3DCOLOR_ARGB(255, 198, 255, 0)
#define SKYBLUE D3DCOLOR_ARGB(255, 0, 180, 255)
#define MAROON D3DCOLOR_ARGB(255, 142, 30, 0)
#define LGRAY D3DCOLOR_ARGB(255, 174, 174, 174)
#define DGRAY D3DCOLOR_ARGB(255, 71, 65, 64)
#define BROWN D3DCOLOR_ARGB(255, 77, 46, 38)
#define SHIT D3DCOLOR_ARGB(255, 74, 38, 38)
Setelah itu buat Header lagi dan Beri Nama dengan Functions.h dan Isi dengan code berikut :
Functions.h
Spoiler:
//==================================================================
// This file is part of zenixbase d3d v1
// (c) copyright zenix 2010
// special thanks to:
// Alkatraz
// //mcz yang selalu dukung gw
// nyit-nyit.net
//==================================================================
#include "SystemIncludes.h"
void PrintText(char pString[], int x, int y, D3DCOLOR col, ID3DXFont *font)
{
RECT FontRect = { x, y, x+500, y+30 };
font->DrawText( NULL, pString, -1, &FontRect, DT_LEFT | DT_WORDBREAK, col);
}
void FillRGB( int x, int y, int w, int h, D3DCOLOR color, IDirect3DDevice9* pDevice )
{
if( w < 0 )w = 1;
if( h < 0 )h = 1;
if( x < 0 )x = 1;
if( y < 0 )y = 1;
D3DRECT rec = { x, y, x + w, y + h };
pDevice->Clear( 1, &rec, D3DCLEAR_TARGET, color, 0, 0 );
}
void DrawBorder( int x, int y, int w, int h, int px, D3DCOLOR BorderColor, IDirect3DDevice9* pDevice )
{
FillRGB( x, (y + h - px), w, px, BorderColor, pDevice );
FillRGB( x, y, px, h, BorderColor, pDevice );
FillRGB( x, y, w, px, BorderColor, pDevice );
FillRGB( (x + w - px), y, px, h, BorderColor, pDevice );
}
void DrawBox( int x, int y, int w, int h, D3DCOLOR BoxColor, D3DCOLOR BorderColor, IDirect3DDevice9* pDevice )
{
FillRGB( x, y, w, h, BoxColor, pDevice );
DrawBorder( x, y, w, h, 1, BorderColor, pDevice );
}
bool isMouseinRegion(int x1, int y1, int x2, int y2)
{
POINT cPos;
GetCursorPos(&cPos);
if(cPos.x > x1 && cPos.x < x2 && cPos.y > y1 && cPos.y < y2){
return true;
} else {
return false;
}
}
bool bCompare(const BYTE* pData, const BYTE* bMask, const char* szMask)
{
for(;*szMask;++szMask,++pData,++bMask)
if(*szMask=='x' && *pData!=*bMask)
return 0;
return (*szMask) == NULL;
}
DWORD FindPattern(DWORD dwAddress,DWORD dwLen,BYTE *bMask,char * szMask)
{
for(DWORD i=0; i<dwLen; i++)
if (bCompare((BYTE*)(dwAddress+i),bMask,szMask))
return (DWORD)(dwAddress+i);
return 0;
}
void *DetourFunction (BYTE *src, const BYTE *dst, const int len)
{
BYTE *jmp;
DWORD dwback;
DWORD jumpto, newjump;
VirtualProtect(src,len,PAGE_READWRITE,&dwback);
if(src[0] == 0xE9)
{
jmp = (BYTE*)malloc(10);
jumpto = (*(DWORD*)(src+1))+((DWORD)src)+5;
newjump = (jumpto-(DWORD)(jmp+5));
jmp[0] = 0xE9;
*(DWORD*)(jmp+1) = newjump;
jmp += 5;
jmp[0] = 0xE9;
*(DWORD*)(jmp+1) = (DWORD)(src-jmp);
}
else
{
jmp = (BYTE*)malloc(5+len);
memcpy(jmp,src,len);
jmp += len;
jmp[0] = 0xE9;
*(DWORD*)(jmp+1) = (DWORD)(src+len-jmp)-5;
}
src[0] = 0xE9;
*(DWORD*)(src+1) = (DWORD)(dst - src) - 5;
for(int i = 5; i < len; i++)
src[i] = 0x90;
VirtualProtect(src,len,dwback,&dwback);
return (jmp-len);
}
5. Buat Header lagi beri Nama SystemIncludes.h dan Isikan code berikut :
SystemIncludes.h
Spoiler:
//==================================================================
// This file is part of zenixbase d3d v1
// (c) copyright zenix 2010
// special thanks to:
// Alkatraz
// //mcz yang selalu dukung gw
// nyit-nyit.net
//==================================================================
#include <Windows.h>
#include <stdio.h>
#include <d3d9.h>
#include <d3dx9.h>
#pragma comment(lib,"d3dx9.lib")
Klik pada Source Files kemudian Add New Item pilih C++ File (.cpp) Beri Nama D3dbase.cpp Isikan code berikut :
Spoiler D3dbase.cpp
Spoiler:
//==================================================================
// This file is part of zenixbase d3d v1
// (c) copyright zenix 2010
// special thanks to:
// Alkatraz
// //mcz yang selalu dukung gw
// nyit-nyit.net
//==================================================================
#include "zenixMenuClass.h"
oReset pReset;
oEndScene pEndScene;
zenixMenu dMenu;
LPDIRECT3DDEVICE9 g_pDevice = 0;
//Mengatur Offset Font Menu Hack
int xFontOffSet = 15;
int hackopt1;
int MenuHeight = 10;
int show=1;
int b = 0;
//==================================================================
//Menu HACK
int hack1 = 0;
int hack2 = 0;
int hack3 = 0;
int hack4 = 0;
int hack5 = 0;
//==================================================================
void zenixMenu::CreateItem(int index, char * title, int *hack, int hackmaxval,int hacktype)
{
hackcount++;
HACKITEM[hackcount].index = index;
HACKITEM[hackcount].hack = hack;
HACKITEM[hackcount].hackmaxval = hackmaxval;
HACKITEM[hackcount].hacktype = hacktype;
// Mengatur tinggi rendahnya Menu Hack
PrintText(title, xFontOffSet, index*15,HACKITEM[hackcount].HCOLOR,pFont);
}
void zenixMenu::BuildMenu(char * menuname, int x, int y, int h, int w, DWORD TITLECOL, DWORD BACKCOLOR, DWORD BORDERCOLOR, LPDIRECT3DDEVICE9 pDevice)
{
if(GetAsyncKeyState(VK_INSERT)&1)show=(!show); //Memunculkan Menu HACK (INSERT)
if(!show) {
DrawBox(0,0, w, 20, BACKCOLOR, BORDERCOLOR, pDevice);
PrintText(menuname, 5, 2, TITLECOL, pFont);
return;
}
DrawBox(x,y, w, h, BACKCOLOR, BORDERCOLOR, pDevice); // Sesuaikan dengan Base Menu HACK
PrintText(menuname, x+10, y+2, TITLECOL, pFont);
CreateItem(1,"Ammo", &hack1);
CreateItem(2,"Recoil", &hack2);
CreateItem(3,"Wallhack", &hack3);
CreateItem(4,"Chams", &hack4);
CreateItem(5,"Apa aja deh", &hack5);
RenderMenu();
}
void zenixMenu::RenderMenu() //Hotkey menu
{
if(GetAsyncKeyState(VK_DOWN)&1)
selector++;
if(GetAsyncKeyState(VK_UP)&1)
if(selector > 1)
selector--;
if (GetAsyncKeyState(VK_RIGHT)<0){
for(int i=0;i < (hackcount+1);i++){
if(selector == HACKITEM[i].index){
if(*HACKITEM[i].hack < HACKITEM[i].hackmaxval)
*HACKITEM[i].hack += 1;
}
}
}
if (GetAsyncKeyState(VK_LEFT)<0){
for(int i=0;i < (hackcount+1);i++){
if(selector == HACKITEM[i].index){
*HACKITEM[i].hack = 0;
Sleep(200);
}
}
}
for(int i=0;i < (hackcount+1);i++){
if(selector == HACKITEM[i].index)
HACKITEM[i].HCOLOR = GREEN;
else
HACKITEM[i].HCOLOR = RED;
}
for(int i=1; i<(hackcount+1); i++){
if(HACKITEM[i].hacktype == 0){
if(*HACKITEM[i].hack == 1)
// Mengatur tinggi rendahnya Menu Hotkey
PrintText("On", xFontOffSet+100, HACKITEM[i].index*15,WHITE,pFont);
else
PrintText("Off", xFontOffSet+100, HACKITEM[i].index*15,RED,pFont);
}
}
if(selector < 1)
selector = 1;
if(selector > hackcount)
selector = 1;
hackcount = 0;
}
void TestThread() //Memunculkan texk jika ON/OFF
{
if( hack1 == 1)
PrintText("Jika Ammo [ON] text akan berubah warna", 30, 200, GREEN, dMenu.pFont);
else
PrintText("Jika Ammo [ON] text akan berubah warna", 30, 200, RED, dMenu.pFont);
} //Sesuaikan saja
void ReFont(LPDIRECT3DDEVICE9 pDevice) //Untuk penggantian font
{
if (g_pDevice != pDevice)
{
g_pDevice = pDevice;
try
{
if (dMenu.pFont != 0)
dMenu.pFont->Release();
} catch (...) {}
dMenu.pFont = 0;
D3DXCreateFontA(pDevice, 14, 0, FW_BOLD, 0, 0, DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS, PROOF_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Arial", &dMenu.pFont );
}
}
HRESULT WINAPI Reset(IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentationParameters )
{
dMenu.pFont->OnLostDevice();
HRESULT hRet = pReset(pDevice, pPresentationParameters);
dMenu.pFont->OnResetDevice();
return hRet;
}
// Menu TITLE
HRESULT WINAPI EndScene(LPDIRECT3DDEVICE9 pDevice)
{
ReFont(pDevice);
dMenu.BuildMenu("Nyit-nyit.net 2010",0,0,190,200,RED,BLACK,GREEN,pDevice);
TestThread();
return pEndScene(pDevice);
}
int D3Dinit(void)
{
DWORD hD3D, adr, *vtbl;
hD3D=0;
do {
hD3D = (DWORD)GetModuleHandle("d3d9.dll");
Sleep(10);
} while(!hD3D);
adr = FindPattern(hD3D, 0x128000, (PBYTE)"\xC7\x06\x00\x00\x00\x00\x89\x86\x00\x00\x00\x00\x89\x86", "xx????xx????xx");
if (adr) {
memcpy(&vtbl,(void *)(adr+2),4);
pReset = (oReset) DetourFunction((PBYTE)vtbl[16] , (PBYTE)Reset ,5);
pEndScene = (oEndScene) DetourFunction((PBYTE)vtbl[42], (PBYTE)EndScene,5);
}
return 0;
}
BOOL WINAPI DllMain ( HMODULE hDll, DWORD dwReason, LPVOID lpReserved )
{
DisableThreadLibraryCalls(hDll);
if ( dwReason == DLL_PROCESS_ATTACH ) {
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)D3Dinit, NULL, NULL, NULL);
}
if( dwReason == DLL_PROCESS_DETACH) {
dMenu.pFont->Release();
}
return TRUE;
}
•Kemudian Save All Project. Setelah project telah di Save lalu Compile/Start Debugging.
•Jangan lupa rubah Properties Project rubah Application (.exe) menjadi Dinamic Library (.dll)
Pada Fungtions.h void *DetourFunction
Spoiler:
Bisa kalian ganti dengan :
void *DetourFunction (BYTE *src, const BYTE *dst, const int len)
{
BYTE *jmp = (BYTE*)malloc(len+5);
DWORD dwBack;
VirtualProtect(src, len, PAGE_EXECUTE_READWRITE, &dwBack);
memcpy(jmp, src, len);
jmp += len;
jmp[0] = 0xE9;
*(DWORD*)(jmp+1) = (DWORD)(src+len - jmp) - 5;
src[0] = 0xE9;
*(DWORD*)(src+1) = (DWORD)(dst - src) - 5;
for (int i=5; i<len; i++) src[i]=0x90;
VirtualProtect(src, len, dwBack, &dwBack);
return (jmp-len);
Download :
Screen Shot Hasil
DOWNLOAD Link
Number of downloads: 1099
Credit : Alkatraz mpgh, zenix@N3&N5 ,
Untuk Sample .dllnya..
Download :
Credit : ZeniX@N5
Waktu sekarang Fri Apr 27, 2018 2:06 am
|
__label__pos
| 0.96632 |
1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!
Variable constant?
1. Apr 14, 2007 #1
1. The problem statement, all variables and given/known data
Does the term variable constant make sense?
There could also be an integration variable.
i.e in a function W(x) = int(e^(xy)) where y is the integration variable. So is x in this situation the constant variable? Or is the word constant unnecessary.
But in W(x)=x, x would be just be the variable.
2. jcsd
3. Apr 14, 2007 #2
HallsofIvy
User Avatar
Staff Emeritus
Science Advisor
No, the term "constant variable" makes no sense. Nor does it apply to the situation you cite. x could be a constant or it could be a variable exy is being integrated with respect to b. I.e. at each value of x.
4. Apr 14, 2007 #3
you mean wrt y?
So W(x)=int(e^xy)dy but x is still a variable. Just like in W(x)=x. Do you think functions like W(x)=int(e^xy)dy is strange? Where or how does it appear usually?
5. Apr 14, 2007 #4
cepheid
User Avatar
Staff Emeritus
Science Advisor
Gold Member
[tex] W(x) = \int_{y_1}^{y_2} f(x,y)\,dy [/tex]
doesn't seem that strange to me. The integrand is a function of two variables, but when you integrate over y, the y-dependence is eliminated, and what remains is a function of x only. Integration wrt y just gives you a number (in this case, a different number FOR EACH value of x). So what remains is a function of x.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook
Have something to add?
|
__label__pos
| 0.994762 |
What Attribution Model Does Google Analytics Use?
What is attribution model in Google Analytics?
An attribution model is the rule, or set of rules, that determines how credit for sales and conversions is assigned to touchpoints in conversion paths.
For example, Last Interaction attribution assigns 100% credit to the final touchpoints (i.e., clicks) that immediately precede sales or conversions..
What attribution model does Google Analytics use by default?
baseline attribution modelBy default, the data driven model is the baseline attribution model when you begin creating a custom model using the Model Comparison Tool. With the data driven attribution model, there are no rules for assigning value to your customer touchpoints.
What is the most common attribution model?
Following are several of the most common attribution models.Last-click attribution. With this model, all the credit goes to the customer’s last touchpoint before converting. … First-click attribution. … Linear attribution. … Time decay attribution. … U-shaped attribution.
What are the different attribution models?
What are the different types of attribution models?Last Interaction Attribution. … First Interaction Attribution. … Last Non-Direct Click. … Linear Attribution. … Time Decay Attribution. … Position-based Attribution.
Can you create a fully custom attribution model in Analytics?
Goal Conversion tracking and/or ecommerce tracking setup is the primary technical requirement for creating a custom attribution model in Google Analytics. In GA, you can not create a custom attribution model from scratch. The attribution model that you create, will be built on top of a baseline attribution model.
What is the default attribution model for Floodlight?
By default, Floodlight columns use the last-click attribution model. If you want a Floodlight column to give some amount of credit to clicks on paid search ads higher up in the funnel, select an alternate attribution model.
What is Google Analytics remarketing?
Re-engage audiences that are likely to convert. You create remarketing audiences based on user behavior on your site or app, and then use those audiences as the basis for remarketing campaigns in your ad accounts like Google Ads and Display & Video 360. …
How do I find the attribution model in Google Analytics?
In your Google Analytics dashboard, click Conversions > Multi-Channel Funnels > Attribution > Model Comparison. This lets you view the various default models offered in the platform if you’re considering one of those models.
Is Google Analytics last click attribution?
Google Analytics uses the Last Interaction attribution model. This means that 100% of the credit for a goal conversion goes to the last click.
Why last click attribution is bad?
Under a last click attribution model, there is a bias towards direct visits, which can make marketers feel uncertain about how their branding and awareness efforts are impacting the campaign as a whole. … In this case, final touch attribution would give marketers skewed insights that can lead to misguided optimizations.
How are metrics calculated?
Calculated Metrics are user-defined metrics that are computed from existing metrics and drive more relevant analyses and enable greater actionability without leaving the product. In this article: Creating calculated metrics. Using the Formula field and input examples.
What is multi channel funnel in Google Analytics?
The Multi-Channel Funnels data combines the Google Analytics conversion data with the sequence of interactions captured in the cookie. Multi-Channel Funnels report queries return data based on a sample set of 1 million conversion paths.
|
__label__pos
| 0.999505 |
Section courante
A propos
Section administrative du site
Dans le langage JavaScript, la façon d'écrire une variable est assez rudimentaire.
Variable global
Voici la syntaxe d'une définition d'une variable global :
var nomdelavariable;
On peut également définir une valeur par défaut:
var nomdelavariable = valeurpardefaut;
Enfin, pour définir un tableau, on procède de la façon suivante:
var nomdelavariable = new Array(valeur1,valeur2,...);
Remarque
Variable dans une fonction
Il n'y pas véritablement de différence de syntaxe entre une variable global et de fonction, voici sa syntaxe :
function nomdefonction(paramètres) {
var nomdelavariable;
instruction_exécuté1;
...;
return valeurderetour;
}
On peut également définir une valeur par défaut :
function nomdefonction(paramètres) {
var nomdelavariable = valeurpardefaut;
instruction_exécuté1;
...;
return valeurderetour;
}
Syntaxe d'un nom d'une variable
La syntaxe d'un nom de variable doit correspondre à de nombreuses règles :
Remarque
Exemple
Voici un exemple de quelques définitions de variables :
1. <script language="JavaScript" type="text/javascript">
2. var isValueBoolean = false;
3. var myValue = 0;
4. var myReal = 0.0
5. var myString = "Bonjour";
6. document.write(myString);
7. </script>
Dernière mise à jour : Mardi, le 10 novembre 2015
|
__label__pos
| 0.782505 |
Tuesday, March 9, 2021
Speeding up pgbench using COPY FREEZE
Photo by Florian Kurz
What is pgbench
Pgbench is a simple tool to perform performance tests on PostgreSQL. Since pgbench comes with PostgreSQL distribution and it's easy to use, many users and developers regularly use pgbench. The original version of pgbench was written by me in 1999 and then it was contributed to PostgreSQL. Since then many people have enhanced the tool.
Loading data takes long time
Pgbench has a feature to load initial data into the benchmark tables (-i or --initialize option). By specifying scaling factor (-s option) users can create data as large as he/she wants. For example scaling factor 100 will create 10 millions rows. When I execute pgbench command with the scaling factor 100, it took 70 seconds on my laptop. You can see how long each part of the process took:
done in 70.78 s (drop tables 0.21 s, create tables 0.02 s, client-side generate 12.42 s, vacuum 51.11 s, primary keys 7.02 s).
As you can see, most of the time was spent in vacuum: 51.11 seconds.
After some testing, I realized these numbers were too specific. I mean, I did the test under the environment where PostgreSQL servers are configured as streaming replication system on my laptop. When primary server does lots of write while pgbench is running, WAL is sent to standby server and it does lots of write too. This means under the environment the effect of write is amplified.
After doing pgbench -i without the streaming replication, I got this number with standard pgbench:
done in 16.20 s (drop tables 0.24 s, create tables 0.01 s, client-side generate 10.05 s, vacuum 2.13 s, primary keys 3.77 s).
So now standard pgbench runs much faster. So I have changed some words and graphs according to the result in the rest of this article.
Why vacuum is slow?
Ok, why we need vacuum then? One of the reasons is to create statistic data for tables. Without the statistic data, PostgreSQL's planner cannot create good plans to execute queries. But actually this does not take so long time because for this task vacuum just reads the table and adds small data to certain system catalogs. But vacuum does other tasks: updating hint bits in each tuple. Hint bits are a"cache" of transactions status that is stored in pg_xact and pg_subtrans. See wiki for details about hint bits. Unfortunately this results in whole rewriting of the table, which generates massive I/O. This is the reason why vacuum is slow.
COPY FREEZE
Is there anyway to avoid the slowness of vacuum? COPY FREEZE is one of the answer to this. COPY is used to populate the main benchmark table "pgbench_accounts". By adding "FREEZE" option to COPY, COPY sets the hint bits while processing and subsequent vacuum does not need to change them. Thus it will not generate massive I/O.
COPY FREEZE will be enhanced in PostgreSQL 14
Unfortunately pre PostgreSQL 14's COPY FREEZE does not do the all the necessary tasks:
1. Update hint bits in each tuple
2. Update visibility map (bit map indicating whether corresponding table tuple in a page is visible to all transactions)
3. Update freeze map (bit map indicating whether corresponding table tuple in a page is all frozen)
4. Update PD_ALL_VISIBLE flag in each page
It only does 1, but does not do 2, 3 and 4. Especially 4 is important because if COPY does not do it, subsequent vacuum will update the flag in a page and it writes whole pages of the table, which in turn slows down vacuum. 2 and 3 are not necessary to prevent the massive write in vacuum but it is convenient for SELECT which wants to do index only scan. Index only scan requires the visibility map to be set. With a fix patch PostgreSQL 14's COPY FREEZE does all 1 to 4.
PostgreSQL 14's COPY FREEZE helps pgbench
Now that COPY FREEZE does the right thing, now is the time to use COPY FREEZE in pgbench -i. I proposed a small patch for pgbench. Here is a graph to compare the time spent in "pgbench -i" with scaling factor 100 on my Ubuntu 18 Laptop.
With the patch total time drops from 16.20 seconds (left) to 14.30 seconds (right), that is 11.7% faster. This is mainly because vacuum (green part) takes only 0.25 seconds while unpatched pgbench takes 2.13 seconds, which is 8 times slower.
Conclusion
By using enhanced COPY FREEZE in PostgreSQL 14, performance of pgbench -i is significantly enhanced. The patch is in commit festa and I expect it would become a part of PostgreSQL 15, which is supposed to be released in the third quarter of 2022. Of course you could use the enhanced COPY FREEZE for any purposes other than pgbench once PostgreSQL 14 is released.
1 comment:
Speeding up pgbench using COPY FREEZE
Photo by Florian Kurz What is pgbench Pgbench is a simple tool to perform performance tests on PostgreSQL. Since pgbench comes with Post...
|
__label__pos
| 0.625923 |
Javascript projects-build-a-library
Hi All,
I am working through the ‘Build a Library’ project and came across a problem when calling toggleCheckoutStatus() on historyOfEverything. When running the code I get the below error message. I’m not sure why this is causing an error code and would appreciate advice :slight_smile:
/home/ccuser/workspace/learn-javascript-classes-build-a-library/app.js:66
historyOfEverything.toggleCheckoutStatus();
^
TypeError: historyOfEverything.toggleCheckoutStatus is not a function
Please see my code below:
class Media {
constructor(title){
this._title = title;
this._isCheckout = true;
this._ratings = ;
}
get title() {
return this.title;
}
get isCheckout() {
return this.isCheckOut;
}
get ratings() {
return this.ratings;
}
toggleCheckOutStatus() {
this.isCheckOut = !this.isCheckOut;
}
getAverageRating(value) {
let ratingSum = this._ratings.reduce((accumulator, rating) => accumulator + rating);
return this.ratingSum / this._ratings.length;
}
addRating(inputValue) {
return this._rating.push(inputValue);
}
set isCheckOut(value) {
this._isCheckOut = value;
}
}
class Book extends Media {
constructor (title, author, pages) {
super(title)
this._author = author;
this._pages = pages;
}
get authour() {
return this._author;
}
get pages() {
return this._pages;
}
}
class Movie extends Media {
constructor(title, director, runtime) {
super(title)
this._director = director;
this._runtime = runtime;
}
get director() {
return this._director;
}
get runtime() {
return this._runtime;
}
}
const historyOfEverything = new Book (‘Bill Bryson’, ‘A Short History of Nearly Everything’, 544)
historyOfEverything.toggleCheckoutStatus();
console.log(historyOfEverything.isCheckOut)
To preserve code formatting in forum posts, see: [How to] Format code in posts
Consider the following issues:
• You must be consistent in the capitalization of the variables. At times, you have used isCheckOut whereas in other places you have used isCheckout. To the compiler, they are not the same. Decide which of the two is the correct version as desired by you. Then, go through your code and change all names to the correct version.
• Similarly, you wrote historyOfEverything.toggleCheckoutStatus() whereas in the Media class, you named the method as toggleCheckOutStatus
• In the Book class, you spelled your getter as authour instead of author.
• In the Media class, your getters are calling themselves instead of the properties. This leads to infinite loops. For Example,
// You wrote:
get title() {
return this.title;
}
// It should be:
get title() {
return this._title;
}
4 Likes
That’s very helpful thank you for the reply :slight_smile:
1 Like
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.
|
__label__pos
| 0.99992 |
Issuu on Google+
INTRODUCCIÓN A LA PROGRAMACIÓN ORIENTADA A OBJETOS
1
2
Contenido 1.
PROBLEMAS Y SOLUCIONES ........................................................................................................ 5 1.1.
Objetivos pedagógicos ........................................................................................................ 5
1.2.
Introducción ........................................................................................................................ 5
1.3.
Entidades o clases ............................................................................................................... 7
1.4.
Atributos.............................................................................................................................. 7
1.5.
Comportamiento ............................................................................................................... 10
1.5.1.
Caso de estudio 1 Unidad I: El estudiante ................................................................. 13
1.5.2.
Comprensión del problema ....................................................................................... 14
1.5.3.
Caso de estudio 2 Unidad I: El empleado .................................................................. 18
1.5.4.
Comprensión del problema ....................................................................................... 18
1.6.
Hoja de trabajo 1 Unidad I: La granja ................................................................................ 21
1.6.1. 1.7.
Hoja de trabajo 2 Unidad I: La Constructora ..................................................................... 24
1.7.1. 1.8.
2.
Comprensión del problema ....................................................................................... 22
Comprensión del problema ....................................................................................... 24
Métodos ............................................................................................................................ 27
1.8.1.
Expresiones ............................................................................................................... 28
1.8.2.
Cómo construir un método ....................................................................................... 33
1.8.3.
Declarar variables en Java ......................................................................................... 35
1.8.4.
Envío de mensajes o llamado de métodos ................................................................ 36
1.8.5.
Solución del caso de estudio 2 .................................................................................. 39
1.8.6.
Solución de la hoja de trabajo 1 ................................................................................ 43
1.8.7.
Caso de estudio 3 Unidad I: El estudiante con notas ................................................ 48
1.8.8.
Comprensión del problema ....................................................................................... 48
1.8.9.
Caso de estudio 4 Unidad I: El minimercado............................................................. 56
1.8.10.
Comprensión del problema ....................................................................................... 56
EXPRESIONES Y ESTRUCTURAS DE DECISION ............................................................................ 63 2.1.
Introducción ...................................................................................................................... 63
2.2.
Caso de estudio 1 Unidad II: Juguetería ............................................................................ 68 3
2.2.1.
Comprensión del problema ....................................................................................... 68
2.2.2.
Especificación de la Interfaz de usuario .................................................................... 70
2.2.3.
Otros elementos de modelado ................................................................................. 70
2.2.4.
Instrucciones Condicionales ...................................................................................... 75
2.3.
Hoja de trabajo 1 Unidad II: Autoservicio ......................................................................... 79
2.3.1. 2.4.
Caso de estudio 2 Unidad II: Concesionario ...................................................................... 85
2.4.1.
Comprensión del problema ....................................................................................... 86
2.4.2.
Especificación de la Interfaz de usuario .................................................................... 86
2.4.3.
Otros elementos de modelado ................................................................................. 87
2.5.
Hoja de Trabajo 2 Unidad II: Floristería ............................................................................ 92
2.5.1.
Comprensión del problema ....................................................................................... 93
2.5.2.
Asociaciones opcionales ............................................................................................ 97
2.6. 3.
Comprensión del problema ....................................................................................... 79
Tipos de métodos .............................................................................................................. 98
ESTRUCTURAS CONTENEDORAS ............................................................................................. 103 3.1.
Caso de estudio 1Unidad III: Grupo de estudiantes ........................................................ 103
3.1.1. 3.2.
Hoja de Trabajo 1 Unidad III: VideoTienda ..................................................................... 110
3.2.1. 3.3.
Comprensión del problema ..................................................................................... 111
Caso de estudio 2 Unidad III: Parqueadero ..................................................................... 117
3.3.1. 3.4.
Comprensión del problema ..................................................................................... 104
Comprensión del problema ..................................................................................... 118
Hoja de trabajo 2 Unidad III: Sala de computadores ...................................................... 125
3.4.1.
Comprensión del problema ..................................................................................... 125
BIBLIOGRAFIA .................................................................................................................................. 131
4
1.
PROBLEMAS Y SOLUCIONES
1.1. Objetivos pedagógicos
Al final de esta unidad el estudiante estará en capacidad de: Identificar y seguir las etapas para la solución de un problema Resolver un problema haciendo uso de un programa de computador Manejar los conceptos de creación e invocación de métodos, expresiones, tipos de datos e instanciación. Interactuar con el ambiente de desarrollo Eclipse Crear interfaces gráficas sencillas
1.2. Introducción
Cuando una empresa tiene un problema que puede ser resuelto mediante el uso de un computador, es necesario contactar a un equipo de desarrollo. Éste debe determinar qué desea el cliente para poder dar una solución de calidad, que satisfaga sus necesidades. Especificación del problema El primer paso que debe seguir el equipo de desarrollo para poder dar solución a un problema es entenderlo. Esta etapa se denominada análisis. La salida de esta etapa se denomina especificación del problema. La etapa de análisis considera varios aspectos, a saber: Identificar los requisitos funcionales, es decir, lo que el cliente espera que haga el programa. El programador debe tener una inmensa habilidad para interactuar con el cliente, pues son pocas las ocasiones en las que el cliente sabe con exactitud las funcionalidades que el sistema debe proveer. El programador debe estar en capacidad de reconocer requisitos incompletos, contradictorios o ambiguos. Entender el mundo del problema, es decir, las reglas y estructura de la empresa dentro de la cual va a funcionar el software. Identificar los requisitos no funcionales, todas aquellas restricciones de los servicios o funciones que el sistema debe ofrecer por ejemplo rendimiento, cotas de tiempo, interfaz de usuario, factores humanos, documentación, consideraciones de hardware, características de ejecución, cuestiones de calidad, ambiente físico. El programador debe adicionalmente haber contemplado la viabilidad del sistema, es decir, haber analizado el conjunto de necesidades para lograr proponer una solución en el plazo deseado que contemple restricciones económicas, técnicas, legales y operativas. El artefacto más importante que surge de la etapa de análisis se conoce como especificación de requisitos software (ERS). En la actualidad existen diversas modelos o formas para definir y documentar requisitos, todas ellas se encaminan hacia el mismo objetivo. El siguiente gráfico ilustra las tareas que debe realizarse sin importar el modelo utilizado. 5
Etapas para realizar la captura y análisis de requisitos
El proceso de solución del problema y la solución de éste Para resolver el problema el programador además de la etapa de análisis debe seguir las etapas de diseño y construcción de la solución. Por su parte, el proceso de diseño permite describir los aspectos del sistema a construir antes de que inicie el proceso de fabricación. En esta etapa se contemplan los requisitos identificados en el análisis y da como resultado un plano del software que incluye “la estructura de la solución, sus 1 partes y relaciones”. En esta etapa se fomenta la calidad del proyecto, pues permite plasmar con precisión los requerimientos del cliente. La siguiente etapa es el proceso de construcción de la solución, ésta considera la creación del código fuente, el cual debe ser compilado para producir un código ejecutable, que posteriormente será instalado en el computador del usuario para que este pueda utilizarlo. El programador debe asegurarse de que el sistema funcione de acuerdo a los requisitos obtenidos del análisis. Es importante que se realice la documentación del código, la realización del manual de usuario, y posiblemente de un manual técnico que facilite realizar mantenimientos futuro y ampliaciones al sistema. La solución proporcionada al cliente debe ser evaluada través de las siguientes dimensiones: Evaluación operacional: analiza criterios como facilidad de uso, tiempo de respuesta, reportes en los que se muestra la información Impacto organizacional: eficiencia en el desempeño de los empleados, velocidad en el flujo de información, beneficios en finanzas. Evaluación del proceso de desarrollo, para valorar las herramientas y métodos seguidos durante el desarrollo del proyecto, al igual que la concordancia entre el esfuerzo y tiempo invertidos con el presupuesto destinado y criterios administrativos que se hayan contemplado. Finalmente, la realización de pruebas permite verificar si el software entregado al cliente funciona correctamente y si cumple con los requisitos funcionales especificados. En caso de detectar falencias es necesario realizar las correcciones que garanticen su buen funcionamiento. Es importante resaltar que el proceso de resolver un problema mediante el uso de un computador conduce a la creación de un programa y a la ejecución del mismo. Para construirlo es necesario hacer uso de un lenguaje de programación. Hoy en día existen muchos lenguajes de programación pero la tendencia actual es el uso de lenguaje orientados a objetos. La programación orientada a objetos o POO es un paradigma de programación que pretende simular el mundo real haciendo
1
Fundamentos de Programación, Jorge Villalobos y Ruby Casallas 6
uso de objetos. A continuación se dan algunos conceptos introductorios, antes de iniciar con la construcción de casos de estudio.
1.3. Entidades o clases
El mundo real está lleno de objetos (concretos o abstractos), por ejemplo una persona, un carro, un triangulo. Los cuales se pueden agrupar y abstraer en una clase. Una clase es una plantilla para fabricar objetos, por lo tanto, un objeto es una instancia de una clase. Las instancias de las clases (objetos) se comunican enviándose mensajes. Un programa está compuesto por una o varias clases. Una clase define atributos, es decir, propiedades o características. También define un comportamiento. Un comportamiento es algo que un objeto puede realizar.
1.4. Atributos
Las propiedades reciben el nombre de atributos. Un atributo es una característica de una clase. Una clase puede contener varios o ningún atributo. Por convención el nombre de un atributo comienza con una letra minúscula, pero si el nombre es compuesto se debe iniciar cada palabra con mayúscula, a excepción de la primer palabra que comenzará en minúscula. Cada atributo tiene un nombre y un tipo de dato asociado. Java ya trae definidos algunos tipos de datos. No obstante el usuario podrá crear nuevos tipos dependiendo de sus necesidades. Los tipos de datos que proporciona son:
Enteros
Se usan para representar enteros con signo. Los enteros no poseen números decimales. Un ejemplo de este tipo de datos es la edad de una persona, la cantidad de habitantes de una casa, el número de goles anotados en un partido. Existen cuatro tipos de enteros: byte, short, int y long. Nombre
Rango de valores
byte short int
-128 a 127 -32768 a 32767 -2147483648 a 2147483647 -9223372036854775808 a 9223372036854775807
long Reales
Tamaño en bits 8 16 32 64
Declaración en Java byte var1; short var2; int var3; long var4;
Los reales permiten almacenar números muy grandes que poseen parte entera y parte decimal. Java soporta dos tipos de coma flotante: float y double. Es importante tener en cuenta que en Java cualquier decimal, por defecto, se almacena en un double. Por lo cual, la siguiente instrucción arroja un fallo de compilación: float temperatura=30.6; Este problema puede solucionarse dos formas:
7
- Agregar una f para especificar que el dato asignado será float. float temperatura= 30.6f; - Casting explícito (conversión forzosa) a float para evitar el fallo de compilación float temperatura= (float) (30.6);
Caracter
Nombre
Rango de valores
float double
3,4E-38 a 3,4E38 1.7E-308 a 1.7E308
Tamaño en bits 32 64
Declaración float num1 = 2.7182f; double num2 = 2.125d;
Java usa la codificación Unicode que le permite trabajar con los caracteres de todos los idiomas. Sus primeros 127 caracteres corresponden a los del código ASCII. Un tipo de dato carácter es un único carácter encerrado entre comillas simples. Ejemplos de caracteres „A‟ „H‟ „\b‟ „\n‟ \n newline, a parte \t tab \b backspace, borra a la izquierda \\ es el carácter backslash \' comilla \" comillas
booleano
Nombre
Rango de valores
char
0 a 65536 (Caracteres alfanuméricos)
Declaración
16
chard letra = ‟a‟;
Un dato de tipo booleano puede tomar solo dos valores true o false. Ejemplo: boolean correcto Nombre boolean
String
Tamaño en bits
Rango de valores true, false
Declaración e inicialización boolean bandera = false;
En Java para expresar una cadena (conjunto de caracteres) se utiliza una estructura llamada String. Toda cadena se debe encerrar entre comillas dobles. Un String NO es un tipo de dato primitivo. Ejemplos de String String saludo=“Hola a todos”; String nombre=“Maria Perez”; String saludo=“”; //Aquí se crea un String sin caracteres
8
ACTIVIDAD 1. Para las siguientes clases identifique de qué tipo son los atributos mostrados. Coloque a la derecha dentro del paréntesis el número apropiado y la declaración correcta.
a) Casa Atributo 1) direccion 2) fichaCatastral 3) cantidadCuartos 4) cantidadBanios
Tipo ( 3 ) int ( ) String ( ) String ( ) int
Declaración en Java int cantidadCuartos;
Tipo ( ) double ( ) String ( ) int ( ) int
Declaración en Java
b) Producto Atributo 1) nombre 2) tipoProducto 3) cantidadExistencias 4) precio
tipoProducto puede tomar los siguientes valores: 1 equivale a Papelería 2 equivale a Juguetería 3 equivale a Droguería. c) Persona Atributo 1) nombre 2) estadoCivil 3) edad 4) correoElectronico 5) fechaNacimiento (dd-mmaaaa)
Tipo ( ) int ( ) String ( ) String ( ) String ( ) boolean
Declaración en Java
Tipo ( ) double ( ) String ( ) String ( ) double
Declaración en Java
d) Puerta Atributo 1) Ancho 2) Alto 3) Color 4) Material
2. Dados los siguientes objetos identifique los atributos correctos. 9
a) Empleado nombre, dirección, salario, nota1, nota2, notaDefinitiva nombre, dirección, salario, fechaIngresoEmpresa, fechaNacimiento nombreProducto, codigoProducto, cantidadExistencias nombre, dirección, cantidadHijos b) Zapato talla, color, material, tipo tipoJuguete, marcaJuguete, precio modelo, numeroMotor, placa numero, modelo, tonoDeTimbre, cámara, numTeclas, listadoContactos
1.5. Comportamiento Un comportamiento u operación es algo que un objeto puede realizar. Es importante tener en cuenta que el comportamiento se define en la clase (a través de métodos) pero es el objeto quien lo realiza. Por ejemplo: Si se tiene la clase Baldosa se puede decir que sus atributos son: largo y ancho y que uno de sus métodos es: calcularArea(). Sería incorrecto por ejemplo un método pegarBaldosa, pues esto no lo puede hacer la baldosa sino el constructor. Si se tiene la clase Licuadora se puede decir que sus atributos pueden ser marca, modelo, numeroSerie, capacidad. Sus operaciones (métodos) pueden ser: licuar, partirHielo. Al igual que los atributos, el nombre de un método debe iniciar con minúscula.
ACTIVIDAD Con base en la definición proporcionada con anterioridad llene la siguiente tabla. Especifique los atributos y los métodos: Para la clase Carro los atributos y los métodos serían: ATRIBUTOS C A R R O
1. 6.
2. 7.
1. 6.
2. 7.
3. 8. MÉTODOS 3. 8.
Para la clase Gallina:
10
4. 9.
5. 10.
4. 9.
5. 10.
G A L L I N A
ATRIBUTOS 1. 6.
2. 7.
3. 8. MÉTODOS
4. 9.
5. 10.
1. 6.
2. 7.
3. 8.
4. 9.
5. 10.
Es importante tener claro que clase no es lo mismo que un objeto. Una entidad es simplemente un molde y un objeto es una descripción completa de una clase (en lenguaje técnico a esto se llama instancia). Para representar una clase en UML se requiere de tres secciones, la primera de ellas es el nombre de la clase, la segunda la lista de atributos y finalmente las operaciones. Tal como puede verse a continuación: Baldosa instanciar miBaldosa: Baldosa
largo = 3 ancho = 5
instanciar
largo ancho fijarLargo () fijarAncho () calcularArea ()
miBaldosa1: Baldosa
lado = 9 ancho = 7
instanciar calcularArea() miBaldosa2: Baldosa
lado = 3 ancho = 5
Tres objetos Baldosa que se crean a partir de la clase Baldosa
Es importante anotar, que aunque el estado de miBaldosa es idéntico al de miBaldosa2, cada objeto tiene una identidad la cual es única.
11
Lavadora
instanciar
instanciar miLavadora: Lavadora
marca capacidad modelo serie
= = = =
“LG” 15 MLG5 XY5iJ
marca capacidad modelo serie
fijarMarca() fijarCapacidad() fijarModelo() fijarSerie()
miLavadora1: Lavadora
marca capacidad modelo serie
= = = =
“Samsung” 25 MYG5 XY5iJQ
Dos objetos Lavadora que se crean a partir de la clase Lavadora
ACTIVIDAD A continuación se proporcionan una serie de atributos y dos diagramas de clases. Debe ubicar cada atributo en el diagrama correspondiente e instanciar. nombre, codigoIsbn, cedula, cantidadPaginas, codigoAutor, email, direccion
Persona instanciar
instanciar
miPersona2: Persona
miPersona: Persona
12
Libro instanciar
instanciar
miLibro2: Libro
miLibro: Libro
Cada atributo tiene asociado un tipo de dato. Un tipo de dato es el rango de valores que puede tomar durante la ejecución del programa. Ello implica que si se da un valor fuera del conjunto se producirá un error.
1.5.1. Caso de estudio 1 Unidad I: El estudiante Se desea crear una aplicación para manejar la información de un estudiante. Un estudiante tiene un código, un nombre y dos notas parciales. Se debe permitir crear un nuevo estudiante, calcular la nota definitiva (promedio aritmético de las dos notas parciales) y devolver el código del estudiante.
13
1.5.2.
Comprensión del problema
a) Requisitos funcionales NOMBRE R1 – Crear un nuevo estudiante RESUMEN Permite crear un nuevo estudiante ENTRADAS codigo, nombre, nota1 y nota2 RESULTADOS Un nuevo estudiante ha sido creado NOMBRE R2 – Calcular la nota definitiva RESUMEN Se calcula como el promedio aritmético de las dos notas parciales ENTRADAS Ninguna RESULTADOS La nota definitiva
NOMBRE R3 – Devolver el código del estudiante RESUMEN Permite devolver el código del estudiante ENTRADAS Ninguna RESULTADOS Él código del estudiante
b) El modelo del mundo del problema Son varias las actividades que se deben realizar para construir el modelo del mundo del problema. Identificar las entidades o clases. Para identificarlas, lo primero que debe hacer es resaltar los nombres o sustantivos. Normalmente se convierten en clases o atributos. “Se desea crear una aplicación para manejar la información de un estudiante. Un estudiante tiene un código, un nombre y dos notas parciales. Se debe permitir crear un nuevo estudiante, calcular la nota definitiva (promedio aritmético de las dos notas parciales) y devolver el código del estudiante.”
ENTIDAD DEL MUNDO Estudiante
DESCRIPCIÓN Es la entidad más importante del mundo del problema.
Se descarta código, un nombre y dos notas parciales puesto que son posibles atributo de la clase Estudiante. Identificar los métodos. Para ello se deben resaltar los verbos. El nombre de los métodos debe ser un identificador válido en Java, éste debe ser mnemotécnico, iniciar en verbo y en minúscula. Si está compuesto por dos palabras, entonces la primera palabra irá en minúscula y la inicial de la segunda en mayúscula, por ejemplo determinarExistenciaEstudiante() sería un nombre válido.
14
Recuerde el enunciado del caso de estudio: “Se debe permitir crear un nuevo estudiante, calcular la nota definitiva (promedio aritmético de las dos notas parciales) y devolver el código del estudiante.”
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA ESTUDIANTE ATRIBUTO codigo nombre nota1 nota2
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Valor real positivo Valor real positivo
Tipo de dato String String double double
IDENTIFICACIÓN DE MÉTODOS (para crear un estudiante se debe fijar cada uno de los atributos codigo, nombre, nota1 y nota2) fijarCodigo() fijarNombre() fijarNota1() fijarNota2() (para calcular la nota definitiva se requiere un método que haga el promedio de las dos notas) calcularDefinitiva() (para devolver el código se requiere un método que devuelva el código del estudiante) devolverCodigo() Nota: Todo método lleva paréntesis. Dentro de los paréntesis pueden o no ir parámetros. Un parámetro es todo aquello que se necesita para resolver un problema y que no pertenece al objeto. Los parámetros están relacionados con las variables de entrada que se identificaron cuando se obtuvieron los requisitos funcionales. Por ahora, dado que se está introduciendo apenas el tema de identificación de métodos, se omitirán los parámetros, pues lo importante es determinar las operaciones que el objeto realiza.
3. Las Relaciones entre las clases del mundo En este punto es importante familiarizarse con el concepto de diagrama de clases. “Un diagrama de clases describe los tipos de objetos que hay en el sistema y las diversas clases de relaciones estáticas que existen entre ellos. Hay dos tipos principales de relaciones estáticas: las 2 asociaciones y los subtipos (un profesor es un empleado).” Este material solo hará uso de las asociaciones. Es importante identificar las relaciones entre las clases para luego proceder a asignarle un nombre. Para indicar que existe una relación se hará uso de una línea con flechas en uno de sus extremos. El nombre de la asociación debe dejar claro que una entidad utiliza a otra clase como parte de sus atributos o características. Se debe tener en cuenta que entre dos clases puede existir más de una relación. Antes de continuar el lector debe tener claro, que las clases se guardarán en carpetas especiales llamadas paquetes, dependiendo del tipo de clase que se vaya a definir. Si se crea una interfaz 2
Fowler, Martin y Scott, Kendall 15
gráfica esta clase se almacenará en un paquete llamado interfaz. Por el contrario, si se crea una clase del mundo real, que contenga la parte lógica se almacenará en un paquete llamado mundo. A continuación se construirá un diagrama de clases que permita visualizar las relaciones de los elementos involucrados en el mundo del problema, con lo cual se ve claramente un modelo conceptual.
Métodos identificados fijarCodigo() fijarNombre() fijarNota1() fijarNota2() calcularDefinitiva() devolverCodigo()
Nombre en el diagrama de clases setCodigo(String codigo) setNombre(String nombre) setNota1(double nota1) setNota2(double nota2) calcularDefinitiva() getCodigo()
Observe que a cada uno de los métodos fijar que se identificaron previamente, cuando se les puso el nombre apropiado para trabajarlos en el diagrama de clases, se les colocó un parámetro, el cual tiene el mismo nombre de la variable que se desea inicializar. Por ejemplo, si se requiere fijar el código, entonces el método setCodigo debe llevar un parámetro, que en nuestro caso se llama también codigo. Lo mismo ocurre con el método setNombre, el cual tiene un parámetro llamado nombre. Por sencillez, es importante que tenga claro que todo método set lleva un parámetro, al cual se le pondrá el mismo nombre de la variable que se desea inicializar. Es de anotar, que el nombre que se le coloque al parámetro puede ser diferente, lo realmente importante es que exista una coincidencia en tipo de dato, más no en nombre. No obstante, en este material el parámetro de cada método set llevará el mismo nombre de la variable que pretende inicializar.
16
Como se explicó con anterioridad por cada método set debe ir un parámetro. Al mirar la interfaz de este caso de estudio se puede observar que para poder crear el estudiante, el usuario debe ingresar cuatro datos, a saber: codigo, nombre, nota1 y nota2 antes de que se presione el botón guardar. Esta información debe capturarse para poderla utilizar posteriormente. Tenga en cuenta que crear el estudiante no solo implica reservarle un espacio en la memoria sino también almacenar la información que el usuario digita. Si la información no se almacena todo se perdería. Un ejemplo de la vida real que nos permite hacer una analogía con lo anterior es el siguiente: Un docente quiere conformar un directorio de números telefónicos de todos sus estudiantes. Cada estudiante se acerca al docente y le da sus datos, pero el docente no registra la información en su libreta. Al final la libreta del docente queda vacía.
Ahora bien, se dijo previamente que se requería de los métodos: setCodigo(String codigo), setNombre(String nombre), setNota1(double nota1), setNota2(double nota2), calcularDefinitiva() y getCodigo(). Cada uno de estos métodos se ejecuta dependiendo del botón que el usuario presione, tal como se muestra en el siguiente gráfico.
getCodigo()
setCodigo(String codigo) setNombre(String nombre) setNota1(double nota1) setNota2(double nota2)
calcularDefinitiva()
- Cuando se presiona el botón guardar se debe reservar memoria al estudiante y posteriormente capturar el código, el nombre, la nota 1 y la nota2. Se debe almacenar el código que el usuario digita en la ventana, este es el motivo por el cual el método setCodigo tiene un parámetro. Igual ocurre con el nombre, la nota1 y la nota2. - Si se presiona el botón “Definitiva” es porque previamente ya se ha ingresado la información, es decir; el código, el nombre, la nota1 y la nota2; por ello no se requiere que el usuario ingrese información adicional a la que ya se encuentra almacenada. Este el motivo por el cual el método calcularDefinitiva no lleva parámetros 17
- Si se presiona el botón “Código”, es porque previamente ya se ha ingresado la información, por ello no se requiere que el usuario ingrese información adicional a la que ya se encuentra almacenada. Este el motivo por el cual el método getCodigo no lleva parámetros
1.5.3. Caso de estudio 2 Unidad I: El empleado Se desea crear una Aplicación para manejar la información de un Empleado. Un empleado tiene un nombre, una cedula, una dirección y un salario asignado. La aplicación debe permitir crear un nuevo empleado Incrementar el salario en un 10% Decrementar el salario en un porcentaje dado por el usuario Devolver la dirección del empleado
1.5.4.
Comprensión del problema
a) Requisitos funcionales NOMBRE R1 – Crear un nuevo empleado RESUMEN Permite crear un nuevo empleado ENTRADAS nombre, cedula, dirección, salario RESULTADOS Un nuevo empleado ha sido creado 18
NOMBRE R2 – Incrementar salario RESUMEN Permite incrementar el salario en un 10% ENTRADAS Ninguna RESULTADOS El salario incrementado
NOMBRE R3 – Decrementar salario RESUMEN Permite decrementar el salario en un porcentaje dado por el usuario ENTRADAS El porcentaje RESULTADOS El salario decrementado
NOMBRE RESUMEN ENTRADAS Ninguna RESULTADOS La dirección
R4– Devolver la dirección Devuelve la dirección que el usuario ingreso previamente
b) El modelo del mundo del problema Las actividades que se deben realizar para construir el modelo del mundo son las siguientes: Identificar las entidades o clases.
ENTIDAD DEL MUNDO Empleado
DESCRIPCIÓN Es la entidad más importante del mundo del problema.
Identificar los métodos. Para ello se deben resaltar los verbos. La aplicación debe permitir crear un nuevo empleado Incrementar el salario en un 10% Decrementar el salario en un porcentaje dado por el usuario Devolver la dirección del empleado
19
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA EMPLEADO ATRIBUTO nombre cedula direccion salario
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Cadena de caracteres Valor real positivo
Tipo de dato String String String double
IDENTIFICACIÓN DE MÉTODOS (para crear un Empleado se debe fijar cada uno de los atributos nombre, cedula, dirección y salario) fijarNombre(String nombre) fijarCedula(String cedula) fijarDireccion (String direccion) fijarSalario (double salario)
(para incrementar el salario en un 10% se requiere de un método que calcule el incremento) incrementarSalario() (Se requiere un método para decrementar el salario en un porcentaje dado por el usuario) decrementarSalarioP(double porcentaje) (Se requiere un método para devolver la dirección del empleado) devolverDireccion()
Las Relaciones entre las clases del mundo Métodos identificados fijarNombre(String nombre) fijarCedula(String cedula) fijarDireccion(String direccion) fijarSalario(double salario) incrementarSalario() decrementarSalarioP(double porcentaje) devolverDireccion()
Nombre en el diagrama de clases setNombre(String nombre) setCedula(String cedula) setDireccion(String direccion) setSalario(double salario) incrementarSalario() decrementarSalarioP(double porcentaje) getDireccion()
El diagrama de clases correspondiente es:
20
1.6. Hoja de trabajo 1 Unidad I: La granja
Un granjero requiere de una aplicación que le permita calcular la cantidad de metros de cable que debe comprar para cercar su finca. La finca del granjero tiene la siguiente forma.
lado2
lado 1
lado2 El granjero conoce la longitud en metros de algunos de los linderos de su finca (lado1 y lado2), pero existe un área de la cual no sabe las medidas exactas, la única información con la que cuenta es que es una zona triangular (específicamente un triangulo isósceles).
El granjero solicita que se proporcione además de la cantidad de metros necesarios para cercar, el área total de su finca.
21
1.6.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE R1 – RESUMEN ENTRADAS lado 1 y lado 2 RESULTADOS
NOMBRE RESUMEN ENTRADAS
R2 –
RESULTADOS
NOMBRE RESUMEN ENTRADAS
R3 –
RESULTADOS
b) El modelo del mundo del problema Las actividades que se deben realizar para construir el modelo del mundo son las siguientes: Identificar las entidades o clases. ENTIDAD DEL MUNDO Finca
DESCRIPCIÓN Es la entidad más importante del mundo del problema.
Identificar los métodos. Para ello se deben resaltar los verbos.
22
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA Finca ATRIBUTO lado 1 lado 2 lado 3
VALORES POSIBLES Valor real positivo Valor real positivo Valor real positivo IDENTIFICACIÓN DE MÉTODOS
Tipo de dato double double double
(para crear una Finca se debe fijar cada uno de los atributos conocidos) fijarLado1(double lado1) fijarLado2(double lado2) (Se debe crear un método para calcular el valor del lado3) inicializarLado3 (Se requiere un método para calcular el perímetro de la finca) calcularPerimetro (Se requiere un método para calcular el Area) calcularArea
3. Las Relaciones entre las clases del mundo Métodos identificados fijarLado1(double lado1) fijarLado2(double lado2) inicializarLado3() calcularPerimetro() calcularArea()
Nombre en el diagrama de clases setLado1(double lado1) setLado2(double lado2) inicializarLado3() calcularPerimetro() calcularArea()
23
Actividad Construya el diagrama de clases para el caso de estudio de la finca
1.7. Hoja de trabajo 2 Unidad I: La Constructora
Una constructora requiere una aplicación que le permita detectar la cantidad baldosas y de cajas requeridas para cubrir una superficie cuadrada. El constructor conoce los lados del piso y las dimensiones de cada baldosa. La baldosa no se vende se forma individual, solo por cajas y cada caja esa compuesta por 10 baldosas.
1.7.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE RESUMEN ENTRADAS
R1 –
RESULTADOS
24
NOMBRE RESUMEN ENTRADAS
R2 –
RESULTADOS
NOMBRE RESUMEN ENTRADAS
R3 –
RESULTADOS
b) El modelo del mundo del problema Las actividades que se deben realizar para construir el modelo del mundo son: Identificar las entidades o clases. ENTIDAD DEL MUNDO Piso Baldosa
DESCRIPCIÓN Es la entidad más importante del mundo del problema. El piso está formado por baldosa. Cada una posee unas dimensiones.
Para identificar los métodos se deben resaltar los verbos.
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA Baldosa ATRIBUTO VALORES POSIBLES Tipo de dato
IDENTIFICACIÓN DE MÉTODOS
25
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA Piso ATRIBUTO
VALORES POSIBLES
Tipo de dato
IDENTIFICACIÓN DE MÉTODOS
Las Relaciones entre las clases del mundo Métodos identificados para Baldosa
Nombre en el diagrama de clases
Métodos identificados para Piso
Nombre en el diagrama de clases
Construya el diagrama de clases
26
1.8. Métodos Los métodos permiten definir el comportamiento de los objetos que se crean con una clase. Un método es un conjunto de instrucciones que permiten resolver un problema particular. Está formado por un tipo de acceso, un tipo de retorno, un nombre, unos parámetros (si son necesarios) y un listado de instrucciones. La estructura general de un método es la siguiente: tipoDeAcceso tipoRetorno nombreDelMetodo( parámetros ){ listado de instrucciones } El tipo de acceso indica la visibilidad del método para las clases externas, existen 4 tipos de accesos, a saber: private: Indica que el método solo puede ser utilizado en el interior de la clase en la que se encuentra definido public: Permite que el método sea utilizado desde cualquier clase. protected: Indica que el método sólo puede accederse desde su mismo paquete y desde cualquier clase que extienda (es decir que herede) la clase en la cual se encuentra, sin importar si está o no en el mismo paquete. Es de anotar que la herencia no se tratará en libro. Si no se especifica un modificador se asume el nivel de acceso por defecto, el cual consiste en que el método puede ser accedido únicamente por las clases que pertenecen al mismo paquete. Un paquete puede verse como una carpeta a través de la cual es posible agrupar clases con características comunes. La siguiente tabla resume los modificadores: La misma clase
Otra clase del mismo paquete
Subclase de otro paquete
Otra clase de otro paquete X
private
X
public
X
X
X
protected
X
X
X
default
X
X Modificadores de acceso
Es de anotar que los métodos construidos en este material llevarán el modificador public y los atributos private. Por otra parte, el nombre del método debe ser un identificador válido en Java, éste debe ser mnemotécnico y tener correspondencia con lo que hace. También debe iniciar en verbo y en minúscula. Si está compuesto por dos palabras, entonces la primera palabra irá en minúscula y la inicial de la segunda en mayúscula. El retorno indica el tipo del resultado por ejemplo en el caso de calcularNotaDefinitiva el retorno sería double, es decir se devolvería un número con decimales que corresponde a la nota definitiva. Un método Java puede retornar un tipo de dato primitivo o una referencia a un objeto Si el método tiene retorno debe especificarse claramente el tipo de dato devuelto y debe incluirse la sentencia return para realizar dicha tarea.
27
Si el método no devuelve un valor, se debe poner void como tipo de retorno y no puede utilizarse return. Los parámetros son los datos necesarios para resolver el problema y que no pertenecen al objeto. Una operación debe ser simple y cohesiva, por lo cual es importante que use al menos uno de los atributos definidos en la clase. Es importante distinguir los términos parámetro y argumento. Un parámetro es una variable definida por un método y que recibe un valor cuando se llama a ese método. Un argumento es un 3 valor que se pasa a un método cuando éste es invocado” . Por ejemplo, sumarEnteros( 6, 5) pasa los valores 6 y 5 como argumentos. Dentro de un método pueden ir múltiples instrucciones, ya sea declaraciones de variables locales, expresiones, estructuras de decisión o repetitivas (estas últimas se tratarán en unidades siguientes). Dependiendo de la función que realice un método, éste puede clasificarse en uno de los siguientes tipos: Métodos modificadores: Son los encargados de cambiar el estado del objeto Métodos analizadores: permiten calcular información apoyándose en la información con la que cuentan los objetos de la clase Métodos constructores: Su objetivo es inicializar los atributos de un objeto en el momento mismo de su creación. Métodos accesores o getter‟s: Permiten devolver el valor de un campo privado, es decir, un atributo de un objeto.
1.8.1.Expresiones Una expresión es una combinación de variables, constantes y/o operadores. Java dispone de los siguientes operadores: - Operadores aritméticos Los operadores aritméticos permiten realizar operaciones aritméticas. Entre ellos se encuentran + (suma), - (resta), * (multiplicación), / (división), % (módulo, residuo de la división), incremento y decremento. En lo referente al operador división es importante tener en cuenta que la división entre enteros da como resultado otro entero. Por ejemplo:
int a = 40; int b = 6; double resultado = ( a + b ) / 3; El programa debería arrojar 15.333 pero da 15. Para corregir dicho error se pueden aplicar las siguientes soluciones: double resultado = ( a + b ) / 3.0;
3
Gómez, Carlos Eduardo y Gutiérrez, Julián Esteban 28
ó double total = a + b; double resultado = total / 3; El siguiente ejemplo ilustra el uso del operador módulo int a=8, b=5; int residuo=a%b; La variable residuo queda con el valor de 3. Por otra parte, los operadores incremento o decremento permiten incrementar o decrementar las variables en una unidad. Por ejemplo:
int a=8, b=5; int c=0; a++; b+=2; c=a+b; Según el código anterior, la variable a queda con un valor de 9, la variable b finaliza con 7 y la variable c con 16. Ahora observe el siguiente ejemplo: int p = 1 , q =0, k=0 ; q = p++; k = ++p; En el caso anterior, a q se le asigna el valor de p y a continuación la p se incrementa en 1, con lo cual q será igual a 1 y p igual a 2. En la instrucción siguiente, la p se incrementa antes de efectuarse la asignación, es decir queda valiendo 3, dicho valor es asignado a la variable k, quien también queda valiendo 3.
- Operadores lógicos Los operadores lógicos dan un resultado de tipo booleano. De igual forma sus operandos son también valores lógicos. Java proporciona 3 operadores lógicos; dos de ellos binarios (And y or) y uno unario (negación). Operador Significado && AND || OR ! NOT Operadores lógicos El operador && da como resultado true si los dos operandos tienen el valor de true. De lo contrario genera un resultado false.
29
operando1 false false true true
Operador operando2 false && true && false && true && Operador AND
salida false false false true
Un ejemplo de uso del operador anterior es el siguiente La variable operando1 corresponde a tarjetaDeCredito y operando2 corresponde a clave. La siguiente línea false
false
&&
false
Se puede interpretar como: Una persona va al cajero, no lleva a tarjeta y no conoce la clave entonces no puede hacer nada. La línea: false
true
&&
false
Indicaría que la persona fue al cajero, no llevaba tarjeta pero si sabía la clave, por lo tanto no pudo hacer nada. En conclusión solo si la persona lleva la tarjeta y conoce la clave podrá retirar dinero. Por otra parte, el operador || da como resultado true si alguno de sus operandos es true.
Operando 1 false false true true
Operador || || || ||
Operando 2 false true false true
Salida false true true true
Operador OR Un ejemplo del funcionamiento del operador anterior podría ser un buscador de libros. El cual permita encontrar publicaciones que contengan cualquiera o todos los términos especificados. Por ejemplo se podría asumir que el operando1 es tituloConPalabraPerro y el operando2 es títuloConPalabraGato, si se utiliza el operador || buscaría todos los libros en la biblioteca que contengan en su titulo el primer o segundo término o ambos. Otro ejemplo sería un buscador de archivo en al cual se le dan dos carpetas para buscar el archivo. El archivo puede encontrarse en la carpeta 1 o en la carpeta 2, o en las dos carpetas. No obstante existe la posibilidad de que no se encuentre en ninguna de las dos carpetas.
Finalmente, el operador ! (negación) da como resultado false si al evaluar su único operando el resultado es true y devuelve true en caso contrario. Ejemplo: Se tiene la siguiente variable: boolean sexo= true;
30
Si se asume que true es mujer, entonces la siguiente instrucción cambiará el valor de la variable sexo a hombre. sexo=!sexo; Otro ejemplo podría ser: boolean mayorDeEdad= false; En este caso la variable mayor de edad está inicializada en false, lo cual representa que la persona es menor de edad. Si se efectúa la siguiente instrucción: mayorDeEdad=!mayorDeEdad; entonces la persona se convirtió en mayor de edad.
- Operadores relacionales Permiten comparar valores, su resultado es de tipo lógico. Entre ellos se encuentran:
== (igualdad) != (diferente) (mayor que) < (menor que) >= (mayor o igual) <= (menor o igual)
- Operador de concatenación con cadena de caracteres '+': Un ejemplo de uso de este operador es el siguiente: double result=40.5; System.out.println("El total es"+ result +"unidades"); La anterior instrucción imprime: “El total es 40.5 unidades”
31
ACTIVIDAD
1) Determine los valores finales para todas las variables utilizadas en la siguiente porción de código a) int a=56, b=-4, c=23, d=45, e=23, f, g, h; f= (a*d) - b; g= c+d+e; h= 67- a/c; f=h*g-a; g=g-h; Opciones de respuesta A) a: 57 , b: -3, c: 23, d: 44, e: 23, f: 5859, g: 26, h: 65 B) a: 56 , b: -4, c: 23, d: 45, e: 23, f: 5859, g: 26, h: 65 C) a: 65 , b: -4, c: 23, d: 45, e: 23, f: 5859, g: 26, h: 65 D) a: 56 , b: -4, c: 25, d: 45, e: 23, f: 5859, g: 27, h: 65
b) char estadoCivil= 'A'; int edad=18; String nombre="Pepe",apellido="Pelaez", nombreCompleto=" "; int nivelEstudios=2; /*0 indica bachiller, 1 pregrado, 2 especializacion, 3 maestria y 4 doctorado*/ nivelEstudios++; nombreCompleto=nombre+ " "+apellido; edad--; estadoCivil=(char)(estadoCivil+1); A) estadoCivil= B edad= 17 nombreCompleto= Pelaez Pepe nivelEstudios= 3 B) estadoCivil= A edad= 17 nombreCompleto= Pepe Pelaez nivelEstudios= 3 c) estadoCivil= B edad= 17 nombreCompleto= Pepe Pelaez nivelEstudios= 3 d) estadoCivil= B edad= 17 nombreCompleto= Pepe Pelaez nivelEstudios= 13 c) Dadas las siguientes instrucciones determine el resultado: int edad=18; double salario=350000; char estadoCivil='S'; int cantidadDeHijos=2; boolean cabezaDeHogar=true; boolean mayorDeEdad=false; double subsidioUnitario=80000; Instrucción edad>=18 cabezaDeHogar ¡= true && cantidadHijos!=0 && estadoCivil==‟S‟ double subsidio=cantidadHijos*subsidioUnitario; subsidio>300000
Resultado a)true a)true
b) false b) false
a)true
b) false
32
(!(mayorDeEdad==true && salario< 700000)) || (cantidadDeHijos%2==0)
a)true
b) false
d) Consulte en internet las instrucciones que deben escribirse para saber si un año es bisiesto y seleccione la opción correcta. A) ((( año % 4 == 0 ) && ( año % 100 != 1 )) || ( año % 400 == 0 )) B) ((( año % 4 == 1 ) && ( año % 100 == 0 )) || ( año % 400 == 0 )) C) ((( año % 4 == 0 ) && ( año % 100 != 0 )) || ( año % 400 != 0 )) D) ((( año % 4 == 0 ) && ( año % 100 != 0 )) || ( año % 400 == 0 ))
1.8.2.Cómo construir un método La construcción de un método incluye los siguientes pasos: Identificar el tipo de retorno Definir la signatura del método. La signatura de un método está compuesta por el nombre del método, los tipos de los parámetros y el orden de éstos). Se debe tener claro que los modificadores usados y el tipo devuelto no forman parte de la signatura del método. Agregar las instrucciones dentro de él. Para ilustrar lo anterior se procederá a retomar el caso de estudio 1: Se desea crear una aplicación para manejar la información de un estudiante. Un estudiante tiene un código, un nombre y dos notas parciales. Se debe permitir crear un nuevo estudiante, calcular la nota definitiva (promedio aritmético de las dos notas parciales) y devolver el código del estudiante. El diagrama de clases construido que se construyó fue:
Para poder iniciar la construcción de los métodos se deben tener muy claros cuáles son los atributos y adicionalmente el concepto de parámetro: Los parámetros son los datos necesarios para resolver el problema y que no pertenecen al objeto.
33
El primer método que se va a construir es calcularDefinitiva. Se sabe que se va a calcular la nota promedio, por lo cual el retorno será de tipo double. El siguiente paso es colocar el nombre del método y abrir un paréntesis. El paréntesis se deja abierto porque es necesario identificar si habrá o no parámetros. public double calcularDefinitiva (…….. Para saber si hay parámetros se debe preguntar si con la información con la que cuenta (codigo, nombre, nota1, nota2) es suficiente o si requiere que el usuario ingrese información adicional. Se sabe que para calcular la nota definitiva basta con promediar la nota1 y la nota2. Por lo tanto se concluye que no se requiere información adicional y por lo tanto no se necesitan parámetros, pues con la información con la que se cuenta es posible realizar el cálculo solicitado. Por lo tanto se puede procede a cerrar el paréntesis y a construir las instrucciones que permitan calcular el promedio. public double calcularDefinitiva (){ double promedio=(nota1+nota2)/2; return promedio; }
Ahora se procederá a construir los métodos modificadores, setter. Recuerde que se debe construir uno por cada atributo (esto cambiará cuando se incorpore el concepto de método constructor). Para construir este tipo de métodos se deben seguir las siguientes reglas: - No llevan retorno, es decir se debe poner void. - Llevan un parámetro, al cual se le pondrá el mismo nombre del atributo que se pretende inicializar. - En su interior llevan una única línea: this.atributo=parámetro. La siguiente tabla ilustra los métodos set para los atributos de la clase Estudiante
set para código void setCodigo( String codigo ) { this.codigo = codigo; } set para nota1 ` void set1Nota( double nota1) { this.nota1 = nota1; }
set para nombre void setNombre( String nombre ) { this.nombre = nombre; } set para nota2 ` void set2Nota( double nota2) { this.nota2 = nota2; }
Finalmente se construyen los métodos get. Para su elaboración se siguen las siguientes reglas: - Llevan retorno, del mismo tipo del atributo al que se le está haciendo el get. - No llevan parámetros - En su interior llevan la instrucción: return atributo;
34
get para código String getCodigo( ) { return codigo; }
Luego de haber construido los métodos se procede a integrar todo en una clase. public class Estudiante { private String codigo, nombre; private double nota1, nota2; public void setCodigo(String codigo) { this.codigo = codigo; } public void setNombre(String nombre) { this.nombre = nombre; } public void setNota1(double nota1) { this.nota1 = nota1; } public void setNota2(double nota2) { this.nota2 = nota2; } public double calcularDefinitiva() { return (nota1+nota2)/2; } public String getCodigo() { return codigo; } } 1.8.3.Declarar variables en Java El sitio donde sea declare una variable determina donde puede ser utilizada. Las posibles ubicaciones se describen a continuación El primer lugar donde se puede declarar una variable es dentro de la clase, pero fuera de los métodos. Este tipo de variables se conocen como atributos de la clase (o variables globales) y pueden usarse dentro de cualquier método contenido en la clase. El segundo lugar es al interior de cualquier método. Se les denomina variables locales y solo pueden utilizarse en instrucciones que estén contenidas en el método en donde se declaran. En tercer lugar se pueden definir como parámetros de un método, en donde luego de recibir valor, se pueden manipular como una variable local en ese método. Se puede concluir entonces que una variable local sólo puede utilizarse dentro del método donde se declara, es decir, solo allí está viva y es desconocida por otros métodos.
35
public class Estudiante {
private String codigo, nombre; private double nota1, nota2;
public double calcularDefinitiva(){
double promedio=0; //Instrucciones para cambiar inicializar el promedio }
public double darBonificacion(double cantidad) { //Instrucciones
} }
1
La guía de laboratorio No.1 describe los pasos para construir las clases del proyecto estudiante en Eclipse
1.8.4.Envío de mensajes o llamado de métodos Cuando se envía un mensaje a un objeto, se le está ordenando que ejecute un método, el cual debió definirse previamente en la clase con la cual fue creado dicho objeto. Por ejemplo cuando se le dice a un objeto estudiante que informe su nota definitiva lo que realmente se está haciendo es pasarle el mensaje “calcularDefinitiva”. Para mandar mensajes a los objetos se utiliza el operador punto. En general para llamar un método, lo que se hace es colocar la referencia al objeto, seguido del operador punto, luego el nombre del método, y finalmente, dentro de paréntesis se pasan los 36
correspondientes argumentos (tantos argumentos como parámetros se hayan puesto al momento de crear el método). Es importante que previamente a la invocación del método haya reservado memoria a través de la instrucción new, esto con el objetivo de evitar que se genere la excepción NullPointerException. NullPointerException aparece cuando se intenta acceder a métodos en una referencia que se encuentra nula, es decir a la cual no se le ha reservado memoria a través de new. En tal caso la llamada al método no es permitida.
2
La guía de laboratorio No.2 describe los pasos para importar un proyecto en Eclipse y construir una interfaz gráfica elemental.
A continuación se muestran las instrucciones necesarias para poder invocar los métodos y mostrar en pantalla los resultados que estos arrojan. Estas instrucciones deben colocarse en la interfaz gráfica. - Se reserva memoria Estudiante miEstudiante=new Estudiante(); - Se lee la información de los campos de texto y se declaran tantas variables como métodos con retorno se hayan hecho. La pantalla que se creó fue la siguiente. En ella hay campos de texto (jTextFields, JButtons y JLabels)
jTextFieldCodigo jTextFieldNombre jTextFieldNota1 jTextFieldNota2.
jButtonGuardar
jButtonDefinitiva
jButtonCodigo jLabelSalida Text
Para que los métodos funcionen es necesario tomar la información de los campos de texto. Las siguientes instrucciones permiten realizarlo.
37
codigo=jTextFieldCodigo.getText(); nombre=jTextFieldNombre.getText(); nota1= Double.parseDouble (jTextFieldNota1.getText()); nota2= Double.parseDouble (jTextFieldNota2.getText());
- Se llama a los métodos set. Primero va la referencia al objeto seguida por el nombre del método y su correspondiente argumento. /*Para crear un Estudiante, además de reservar memoria, se debe fijar cada uno de los atributos: codigo, nombre, nota1, nota2 */ miEstudiante.setCodigo(codigo); miEstudiante.setNombre(nombre); miEstudiante.setNota1(nota1); miEstudiante.setNota2(nota2);
- Se llama a los demás métodos creados. Si el método retorna, el valor que el método devuelve se asigna a un variable del mismo tipo de retorno especificado a la hora de crear el método. Ejemplo: el método calcularDefinitiva() devuelve un double, entonces se declaró una variable de tipo double llamada def para almacenar este resultado. Como este método no tenía parámetros por eso no se le mandaron argumentos. Finalmente, se muestran los resultados en los jLabel o etiquetas creadas para tal fin.
def= miEstudiante.calcularDefinitiva(); jLabelSalida.setText("La nota definitiva es "+def);
- Se repite el proceso con el método getCodigo() cod= miEstudiante.getCodigo(); jLabelSalida.setText("El código del estudiante es "+ cod);
Si desea ejecutar el proyecto sin crear interfaz gráfica siga la guía No. 3
3
Opcional: La guía de laboratorio No.3 describe los pasos para importar un proyecto en Eclipse y ejecutar un proyecto sin construir interfaz gráfica.
ACTIVIDAD Identifique si los siguientes métodos están bien invocados. En caso contrario reescriba las instrucciones para que se ejecuten de forma correcta.
38
Clase y método a analizar
Llamado del método
public class Triangulo { private double base, altura;
double base=5, altura=8, area=0; Triangulo miTriangulo (); miTriangulo.setBase(); miTriangulo.setAltura(altura); area=miTriangulo.calcularArea(base,a ltura);
public void setBase(double base) { this.base = base; } public void setAltura(double altura) { this.altura = altura; } public double calcularArea() { return base*altura; } } public class Cuadrado { private double lado; public void setLado(double lado) { this.lado = lado; }
double lado=4, perimetro=0; Cuadrado miCuadrado = new Cuadrado(); perimetro=miCuadrado.calcularPerimet ro(); calcularPerimetro.miCuadrado(); }
public double calcularPerimetro() {return 4*lado;} public double incrementarPerimetro(int cantidad) { return calcularPerimetro()+cantidad; } }
1.8.5.Solución del caso de estudio 2 A continuación se retomará el caso de estudio2 para proceder a su solución. Se desea crear una Aplicación para manejar la información de un Empleado. Un empleado tiene un nombre, una cedula, una dirección y un salario asignado. La aplicación debe permitir crear un nuevo empleado Incrementar el salario en un 10% Decrementar el salario en un porcentaje dado por el usuario Devolver la dirección del empleado El diagrama de clases que se construyó para esta clase fue el siguiente:
39
Partiendo de este diagrama de clases se iniciará la construcción del código fuente. El primer método que se va a construir es incrementarSalario. Se debe tener claro como se hará el incremento, esto es un 10%. Se sabe que se va a incrementar el salario, por lo cual el retorno será de tipo double. El siguiente paso es colocar el nombre del método y abrir un paréntesis. El paréntesis se deja abierto porque es necesario identificar si habrá o no parámetros. public double incrementarSalario (…….. Para saber si hay parámetros se debe preguntar si con la información con la que cuenta (nombre, cedula, dirección y salario) es suficiente o si requiere que el usuario ingrese información adicional. Se sabe que el incremento será de 10% sobre el salario y se tiene también el salario. Por lo tanto se concluye que no se requiere información adicional y no se necesitan parámetros, pues con la información con la que se cuenta es posible realizar el cálculo solicitado. Por lo tanto se puede procede a cerrar el paréntesis y a construir las instrucciones que permitan calcular el promedio. public double incrementarSalario () { double incremento =salario*0.1; salario=salario + incremento; return salario; }
El siguiente método en el que se trabajará es el que permite decrementar el salario en un porcentaje dado por el usuario. Primero se debe especificar el retorno y nombre del método se debe identificar si tiene parámetros. public double decrementarSalarioP (…….. Para identificar si tiene parámetros se debe preguntar si con la información con la que cuenta (nombre, cedula, dirección y salario) es suficiente o si requiere que el usuario ingrese información adicional. Es claro que en este caso el usuario debe ingresar el porcentaje de decremento, por ello se concluye que el método requiere de un parámetro de tipo double al que se le llamará porcentaje.
40
public double decrementardecrementarSalarioP (double porcentaje) { double decremento =salario*porcentaje/100; salario=salario - decremento; return salario; }
Ahora se procederá a construir los métodos modificadores setter set para direccion public void setDireccion(String direccion) { this.direccion = direccion; } set para salario public void setSalario(double salario){ this.salario = salario; }
set para nombre public void setNombre(String nombre){ this.nombre = nombre; } set para cedula public void setCedula(String cedula){ this.cedula = cedula; }
Finalmente se construyen los métodos get. get para direccion public String getDireccion() { return direccion; } Luego de haber construido los métodos se procede a integrar todo en una clase. public class Empleado { private String nombre, cedula, direccion; private double salario; public void setDireccion(String direccion) { this.direccion = direccion; } public void setNombre(String nombre) { this.nombre = nombre; } public void setCedula(String cedula) { this.cedula = cedula; } public void setSalario(double salario) { this.salario = salario; } public double incrementarSalario () { double incremento =salario*0.1; salario=salario + incremento; return salario; }
41
public double decrementardecrementarSalarioP (double porcentaje) { double decremento =salario*porcentaje/100; salario=salario - decremento; return salario; } public String getDireccion() { return direccion; } } Para poder ejecutar el programa es necesario en la interfaz gráfica: - Reservar memoria private Empleado miEmpleado= new Empleado(); - Se lee la información de los campos de texto y se declaran tantas variables como métodos con retorno se hayan hecho. String nombre=jTextFieldNombre.getText(), cedula=jTextFieldCedula.getText(), direccion=jTextFieldDireccion.getText(); double salario=Double.parseDouble(jTextFieldSalario.getText()); /*Se crearon tres métodos que retornan, por lo tanto se declaran tres variables para que almacenen estos resultados*/ double salarioI=0, salarioD; String dir="";
- Se llama a los métodos set. Primero va la referencia al objeto seguida por el nombre del método y su correspondiente argumento. /*Para crear un Empleado, además de reservar memoria, se debe fijar cada uno de los atributos*/ miEmpleado.setCedula(cedula); miEmpleado.setDireccion(direccion); miEmpleado.setNombre(nombre); miEmpleado.setSalario(salario);
- Se llama a los demás métodos creados. El método incrementarSalario retorna un double y no tiene parámetros. double salarioI= miEmpleado.incrementarSalario(); jLabelSalida.setText("El salario incrementado es "+salarioI);
Ahora se continuará con el método para decrementar el salario. Este método retorna un double y tiene un parámetro, el cual debe ser ingresado por el usuario. double porcentaje=Double.parseDouble(jTextFieldPorcentajeDec.getText()); double salarioD= miEmpleado.decrementardecrementarSalarioP(porcentaje); jLabelSalida.setText("El salario decrementado es "+salarioD);
42
- Se repite el proceso con el método getDireccion dir= miEmpleado.getDireccion(); jLabelSalida.setText("La dirección es: "+dir);
1.8.6.Solución de la hoja de trabajo 1 Recuerde el enunciado de la hoja de trabajo 1: Un granjero requiere de una aplicación que le permita calcular la cantidad de metros de cable que debe comprar para cercar su finca. La finca del granjero tiene la siguiente forma.
lado2
lado1
lado2 El granjero conoce la longitud en metros de algunos de los linderos de su finca (lado1 y lado2), pero existe un área de la cual no sabe las medidas exactas, la única información con la que cuenta es que es una zona triangular (específicamente un triangulo isósceles). El granjero solicita que se proporcione además de la cantidad de metros necesarios para cercar, el área total de su finca. La identificación de atributos y métodos para Finca fue la siguiente:
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA Finca ATRIBUTO lado 1 lado 2 lado 3
VALORES POSIBLES Valor real positivo Valor real positivo Valor real positivo IDENTIFICACIÓN DE MÉTODOS
Tipo de dato double double double
(para crear una Finca se debe fijar cada uno de los atributos conocidos) public void setLado1(double lado1) public void setLado2(double lado2) (Se debe crear un método para calcular el valor del lado3) 43
public void inicializarLado3() (Se requiere un mĂŠtodo para calcular el perĂmetro de la finca) public double calcularPerimetro() (Se requiere un mĂŠtodo para calcular el Area) public double calcularArea() El primer mĂŠtodo que se va a construir es inicializarLado3. Este mĂŠtodo no tendrĂĄ retorno puesto que su objetivo es inicializar un atributo de la clase, de igual forma tampoco tendrĂĄ parĂĄmetros ya que para calcular el lado basta con aplicar la fĂłrmula para hallar la hipotenusa ℎ2 =
đ?‘?12 + đ?‘?22
Se conocen c1 y c2, pues son respectivamente lado2 y lado1/2. De lo cual se concluye que se cuenta con toda la informaciĂłn necesaria, por lo cual no se requieren parĂĄmetros. Java provee la instrucciĂłn Math.pow para trabajar potenciaciĂłn y Math.sqrt para sacar raĂz cuadrada. Ejemplos de su uso son los siguientes: int num=4, exp=3; double dato1=Math.pow(num,exp); //num es la base y exp el exponente double dato=Math.sqrt(num);
Ahora proceda a construir el mĂŠtodo inicializarLado3. public void inicializarLado3(){ //Se usa la formula h=sqrt(cateto1 al cuadrado + cateto2 al cuadrado) lado3= } Los siguientes mĂŠtodos tampoco requieren de parĂĄmetros public double calcularPerimetro(){
} public double calcularArea(){ } Finalmente se construyen los mĂŠtodos set set para lado1 public void setLado1(double lado1){ this.lado1 = lado1; }
set para lado2 public void setLado2(double lado2){ this.lado2 = lado2; }
44
Luego de haber construido los métodos se procede a integrar todo en una clase. public class Finca { private double lado1, lado2, lado3; public void setLado1(
) {
} public void setLado2(
) {
}
public void inicializarLado3() {
} public double calcularPerimetro() {
} public double calcularArea() { }} Para ejecutar el programa es necesario que en la interfaz gráfica: - Se reserve memoria private Finca miFinca= new Finca(); - Se lea la información de los campos de texto y se declaren tantas variables como métodos con retorno se hayan hecho double double double double
lado1=Double.parseDouble(jTextFieldLado1.getText()); lado2=Double.parseDouble(jTextFieldLado1.getText()); perimetro=0; area=0;
- Se llame a los métodos set. Primero va la referencia al objeto seguida por el nombre del método y su correspondiente argumento. Adicionalmente se llama al método inicializarLado3, porque este método forma parte del requisito1
45
miFinca.setLado1(lado1); miFinca.setLado2(lado2); miFinca.inicializarLado3(); - Se llama a los demás métodos creados. perimetro= miFinca.calcularPerimetro(); jLabelSalida.setText("La cantidad de cable es "+perimetro); area= miFinca.calcularArea(); jLabelSalida.setText("El área de la finca es: "+area);
ACTIVIDAD Construya la clase para resolver la hoja de trabajo 2 e incluya las instrucciones necesarias para que el programa corra. Enunciado de la hoja de trabajo 2: Una constructora requiere una aplicación que le permita detectar la cantidad baldosas y de cajas requeridas para cubrir una superficie cuadrada. El constructor conoce los lados del piso y las dimensiones de cada baldosa. La baldosa no se vende se forma individual, solo por cajas y cada caja esa compuesta por 10 baldosas
public class Baldosa { private double largo, ancho; public void setLargo(double largo) { } public void setAncho(double ancho) { } public double calcularAreaB() { } public double getLargo() { } public double getAncho() { } }
46
public class Piso { public double ladoPiso; private Baldosa miBaldosa; public void setLadoPiso(double ladoPiso) { } public void setMiBaldosa(double largo, double ancho) { this.miBaldosa = new Baldosa(); } public double calcularAreaPiso(){ } public double calcularBaldosasRequeridas(){ } public double calcularCantidadCajas(){ } } Agregue las líneas necesarias para que el programa se ejecute. Tenga presente que aquí sólo debe reservarle memoria a la clase principal del mundo. Estas líneas deben ir en la interfaz gráfica.
47
1.8.7. Caso de estudio 3 Unidad I: El estudiante con notas Se desea crear una aplicación para manejar la información de un estudiante. Un estudiante tiene un código, un nombre, un sexo, dos asignaturas registradas (cada una de ellas con código y dos notas parciales) y una fecha de nacimiento. A su vez, una fecha está formada por un día, un mes y un año. Se debe permitir: Calcular la edad del estudiante Calcular la nota definitiva de cada asignatura si se hace a través de un promedio ponderado. Calcular la nota promedio del semestre, es decir, la nota que surge al promediar la nota definitiva de la asignatura 1 con la nota definitiva de la asignatura 2.
1.8.8.
Comprensión del problema
a) Requisitos funcionales NOMBRE R1 – Crear un nuevo estudiante RESUMEN Permite crear un nuevo estudiante ENTRADAS código, nombre, sexo, dia, mes, anio RESULTADOS Un nuevo estudiante ha sido creado
48
NOMBRE RESUMEN
R2 – Fijar una asignatura a un estudiante Permite fijar una asignatura a un estudiante para ello se ingresa el código y las dos notas
ENTRADAS código, nota1, nota2 RESULTADOS Se fijó la asignatura al estudiante
NOMBRE R3 – Calcular la nota definitiva para una asignatura RESUMEN Se calcula como el promedio ponderado de dos notas parciales ENTRADAS porcentaje1 y porcentaje2 RESULTADOS La nota definitiva
NOMBRE R4 – Calcular la nota definitiva del semestre RESUMEN Permite calcular el promedio aritmético de las definitivas de las dos asignaturas ENTRADAS Ninguna RESULTADOS La nota promedio NOMBRE RESUMEN
R5 – Calcular la edad del estudiante Permite calcular la edad del estudiante para ello se resta la fecha actual de la fecha de nacimiento
ENTRADAS Ninguna RESULTADOS La edad
b) El modelo del mundo del problema
1. Identificar las entidades o clases Las clases identificadas son las siguientes: ENTIDAD DEL MUNDO Estudiante Fecha Asignatura
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Atributo del estudiante Atributo del estudiante
Para identificar los métodos se deben resaltar los verbos Se desea crear una aplicación para manejar la información de un estudiante. Un estudiante tiene un código, un nombre, un sexo, dos asignaturas registradas (cada una de ellas con código y dos
49
notas parciales) y una fecha de nacimiento. A su vez, una fecha está formada por un día, un mes y un año. Se debe permitir: Calcular la edad del estudiante Calcular la nota definitiva de cada asignatura si se hace a través de un promedio ponderado. Calcular la nota promedio del semestre, es decir, la nota que surge al promediar la nota definitiva de la asignatura 1 con la nota definitiva de la asignatura 2.
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA FECHA ATRIBUTO dia mes anio
VALORES POSIBLES enteros positivos mayores que 1 y menores de 32 enteros mayores que 1 y menores que 13 enteros positivos IDENTIFICACIÓN DE MÉTODOS
Tipo de dato int int int
(para crear una fecha se debe fijar cada uno de los atributos) public void setDia(int dia) public void setMes(int mes) public void setAnio(int anio) (se debe poder obtener la fecha actual) public void inicializarFechaActual( ) (Permite restar a la fecha actual la fecha de nacimiento) public int calcularDiferenciaConFechaActual( Fecha miFecha )
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA ASIGNATURA ATRIBUTO código nota1 nota2 definitiva
VALORES POSIBLES Cadena de caracteres Un número real mayor que 0 y menor o igual a 5 Un número real mayor que 0 y menor o igual a 5 Un número real mayor que 0 y menor o igual a 5 IDENTIFICACIÓN DE MÉTODOS
Tipo de dato String double double double
(para crear una Asignatura se debe fijar cada uno de los atributos que el usuario conoce) public void setCodigo(String codigo) public void setNota1(double nota1) public void setNota2(double nota2) (para calcular la nota definitiva se requiere un método que calcule el promedio ponderado) public double calcularDef(double porcentaje1, double porcentaje2) (se debe poder devolver la definitiva) public double getDefinitiva()
50
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA ESTUDIANTE ATRIBUTO codigo nombre miFechaNacimiento miAsignatura1 miAsignatura2
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Referencia a objeto de tipo Fecha Referencia a objeto de tipo Asignatura Referencia a objeto de tipo Asignatura IDENTIFICACIÓN DE MÉTODOS
Tipo de dato String String Fecha Asignatura Asignatura
(para crear un estudiante se debe fijar cada uno de los atributos) public void setCodigo(String codigo) public void setNombre(String nombre) public void setSexo(boolean sexo) public void setMiFechaNacimiento(int dia, int mes, int anio) public void setMiAsignatura1(String codigo, double nota1, double nota2) public void setMiAsignatura2(String codigo, double nota1, double nota2)
(Se debe poder calcular la definitiva para cada asignatura) public double calcularDefinitivaA1(double porcentaje1, double porcentaje2) public double calcularDefinitivaA2(double porcentaje1, double porcentaje2) (para calcular la nota definitiva se requiere un método que haga el promedio de las dos notas) public double calcularNotaPromedio() (para calcular la edad se requiere de un método que tome la fecha actual y la reste de la fecha de nacimiento) public int calcularEdad() El diagrama de clases correspondiente para este caso de estudio es el siguiente:
51
La primera clase que se va a trabajar es la clase Fecha. Se iniciará con la construcción del método inicializarFechaActual, en el cual se crea una referencia a un objeto de tipo GregorianCalendar para luego inicializarlo con la fecha actual. Los siguientes métodos están basados en la clase Fecha del caso del estudio del Empleado del Proyecto CUPI2 . public void inicializarFechaActual( ) { GregorianCalendar diaHoy = new GregorianCalendar( ); anio = diaHoy.get( Calendar.YEAR ); mes = diaHoy.get( Calendar.MONTH ) + 1; dia = diaHoy.get( Calendar.DAY_OF_MONTH ); } El método calcularDiferenciaConFechaActual permite calcular la diferencia entre la fecha actual y una fecha ingresada por el usuario public int calcularDiferenciaConFechaActual( Fecha miFecha ) { int diferenciaEnMeses = 0; diferenciaEnMeses = ( miFecha.getMes() - mes )+12 * ( miFecha.getAnio() - anio ) ; //En caso de que el día no sea mayor se debe restar un mes. Es decir, no //se tiene la cantidad de días suficientes para poder sumar un mes más. if(dia >= miFecha.getDia()
) 52
diferenciaEnMeses --; return diferenciaEnMeses ; } Continuando con la clase Asignatura, se tienen los siguientes métodos: El método calcularDef() lleva dos parámetros porcentaje1 y porcentaje2. Recuerde que los parámetros son los datos necesarios para resolver el problema y que no pertenecen al objeto. Estos porcentajes no pertenecen al objeto mientras que código, nota1, nota2 y definitiva si pertenecen. Antes de continuar con la contrucción del método se requiere aclarar el concepto de promedio ponderado. Este es un promedio en el cual el resultado surge al asignarle a cada valor un peso, logrando con ello que unos valores tengan mas relevancia que otros. Por ejemplo si se hablara de las siguientes notas definitivas de asignaturas: Matemática: 4 Programación: 5 El promedio aritmético daría 4.5, pero si se pondera cada asignatura asignando a matemática el 40% y a Programación el 60%, el promedio ponderado obtenido sería: 4 x 4/100 + 5 x 6/100 =4 x 0,4 + 5 x 0,6 = 4,6 Ahora bien, habiendo hecho esta aclaración el método calcularDef quedaría de la siguiente forma: public double calcularDef(double porcentaje1, double porcentaje2) { definitiva= nota1*porcentaje1/100+nota2*porcentaje2/100; return definitiva; }
El método getDefinitiva() devuelve un double con la nota definitiva: public double getDefinitiva() { return definitiva; }
Finalmente de la clase Estudiante se tienen los siguientes métodos: El método setMiFechaNacimiento tiene 3 parámetros (dia, mes, anio) que permiten inicializar la fecha de nacimiento. Para ello es necesario reservarle memoria a miFechaNacimiento y llamar a los métodos set. public void setMiFechaNacimiento(int dia, int mes, int anio) { this.miFechaNacimiento = new Fecha(); miFechaNacimiento.setDia(dia); miFechaNacimiento.setMes(mes); miFechaNacimiento.setAnio(anio);} 53
Los métodos setMiAsignatura permiten inicializar cada una de las asignaturas. Para inicializar una asignatura el usuario debe ingresar el código y las dos notas. La inicialización incluye reservar memoria y la llamada a cada uno de los métodos set. public void setMiAsignatura1(String codigo, double nota1, double nota2) { this.miAsignatura1 = new Asignatura(); miAsignatura1.setCodigo(codigo); miAsignatura1.setNota1(nota1); miAsignatura1.setNota2(nota2); } public void setMiAsignatura2(String codigo, double nota1, double nota2) { this.miAsignatura2 = new Asignatura(); miAsignatura2.setCodigo(codigo); miAsignatura2.setNota1(nota1); miAsignatura2.setNota2(nota2); } El método calcularEdad() no tiene parámetros debido a que previamente se ingresó la fecha de nacimiento del estudiante y con esta información es suficiente para obtener la edad. public int calcularEdad() { Fecha actual=new Fecha(); actual.inicializarFechaActual(); return miFechaNacimiento.calcularDiferenciaConFechaActual(actual)/12; } Los métodos calcularDefinitiva permiten calcular la definitiva de cada asignatura, para ello se ha agregado dos parámetros, porcentaje1 y porcentaje2. public double calcularDefinitivaA1(double porcentaje1, double porcentaje2) { return miAsignatura1.calcularDef(porcentaje1, porcentaje2); } public double calcularDefinitivaA2(double porcentaje1, double porcentaje2) { return miAsignatura2.calcularDef(porcentaje1, porcentaje2); } El método calcularNotaPromedio() no requiere parámetros puesto que con la información con la que cuenta el objeto es suficiente. Para que este método funcione correctamente se debe haber invocado previamente a los métodos calcularDefinitivaA1 y calcularDefinitivaA2. public double calcularNotaPromedio() { return miAsignatura1.getDefinitiva()+miAsignatura2.getDefinitiva(); }
54
Para ejecutar el programa es necesario en la interfaz gráfica: - Reservar memoria private Estudiante miEstudiante=new Estudiante(); - Leer la información de los campos de texto String codigo=jTextFieldCodigo.getText(); String nombre=jTextFieldNombre.getText(); boolean sexo=true; int dia=Integer.parseInt(jTextFieldDia.getText()); int mes=Integer.parseInt(jTextFieldMes.getText()); int anio=Integer.parseInt(jTextFieldAnio.getText()); String codigoA1=jTextFieldCodigoA1.getText(); double nota1A1=Double.parseDouble(jTextFieldNota1A1.getText()); double nota2A1=Double.parseDouble(jTextFieldNota2A1.getText()); String codigoA2=jTextFieldCodigoA2.getText(); double nota1A2=Double.parseDouble(jTextFieldNota1A2.getText()); double nota2A2=Double.parseDouble(jTextFieldNota2A2.getText()); double p1A1=Double.parseDouble(jTextFieldPorcentaje1N1.getText()); double p2A1=Double.parseDouble(jTextFieldPorcentaje2A1.getText()); double p1A2=Double.parseDouble(jTextFieldPorcentaje1A2.getText()); double p2A2=Double.parseDouble(jTextFieldPorcentaje2A2.getText()); if(jRadioButtonMasculino.isSelected()==true) sexo=false; - Llamar a los métodos set. Primero va la referencia al objeto seguida por el nombre del método y su correspondiente argumento. miEstudiante.setCodigo(codigo); miEstudiante.setSexo(sexo); miEstudiante.setMiAsignatura1(codigoA1, nota1A1, nota2A1); miEstudiante.setMiAsignatura2(codigoA2, nota1A2, nota2A2); miEstudiante.setMiFechaNacimiento(dia, mes, anio); Luego se debe calcular la nota definitiva para ambas asignaturas. Esto debe realizarse antes de calcular la nota promedio. miEstudiante.calcularDefinitivaA1(p1A1, p2A1); miEstudiante.calcularDefinitivaA1(p1A2, p2A2); jLabelSalida.setText("El promedio es"+miEstudiante.calcularNotaPromedio() ); Finalmente se calcula la edad jLabelSalida.setText("La edad es "+miEstudiante.calcularEdad());
55
1.8.9. Caso de estudio 4 Unidad I: El minimercado Se desea crear una una Aplicación para registrar compras en un minimercado, el cual ofrece tres diferentes productos. Se sabe que cada producto tiene un código, una descripción y un precio unitario. Se debe permitir: Agregar un producto a la compra. Aumentar en 1 la cantidad de existencias adquiridas de un producto incluido en la compra Indicar la totalidad de artículos incluidos en la compra Calcular el total a pagar por cada tipo de producto Calcular el total a pagar por el total de la compra Reiniciar la compra
1.8.10. Comprensión del problema a) Requisitos funcionales NOMBRE R1 – Agregar un producto a la compra RESUMEN Permite agregar un producto a la compra ENTRADAS codigo, descripcion, precioUnitario RESULTADOS Un producto se ha incluido en la compra
56
NOMBRE
R2- Aumentar en uno la cantidad de existencias adquiridas de un producto en la compra Incrementa en uno la cantidad de existencias
RESUMEN ENTRADAS El tipo del producto del cual se va a adquirir una unidad más RESULTADOS La compra tiene una existencia mas del tipo de producto indicado
NOMBRE R3 – Indicar la totalidad de artículos incluidos en la compra RESUMEN Se suman todos los artículos que hay en la compra ENTRADAS Ninguna RESULTADOS La cantidad de artículos que tienen la compra
NOMBRE RESUMEN ENTRADAS
R4 – Calcular el total a pagar por cada tipo de producto Permite obtener el valor total a pagar por cada tipo de producto
RESULTADOS Total a pagar por el primer producto Total a pagar por el segundo producto Total a pagar por el tercer producto NOMBRE R5 – Calcular el total a pagar por el total de la compra RESUMEN Permite calcular el valor que se debe pagar por la compra ENTRADAS Ninguna RESULTADOS Total a pagar por la compra
NOMBRE R6 – Reiniciar la compra RESUMEN Se crea una nueva compra ENTRADAS Ninguna RESULTADOS Se inicia una nueva compra
b) El modelo del mundo del problema
- Identificar las entidades o clases Las clases identificadas son las siguientes:
57
ENTIDAD DEL MUNDO Compra Producto
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Es un atributo de la compra
- Identificar los métodos. Para ellos se deben resaltar los verbos
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA PRODUCTO ATRIBUTO codigo descripcion precioUnitario cantidadE
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Valor real entero
Tipo de dato String String double int
IDENTIFICACIÓN DE MÉTODOS (para crear un Producto se hará uso de un método constructor) public Producto(String codigo, String descripcion, double precioUnitario) (se debe poder agregar una unidad a la cantidad de existencia del producto) public int agregarExistencia() (Se debe poder calcular el precio de la totalidad de existencias adquiridas de ese producto) public double calcularPrecioPedidoDelProducto()
(Se requiere devolver la cantidad de existencias del producto) public int getCantidadE()
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA COMPRA ATRIBUTO
VALORES POSIBLES
Tipo de dato
IDENTIFICACIÓN DE MÉTODOS (Se debe permitir agregar los productos a la compra) public void setMiProducto1(String codigo, String descripcion, double precioUnitario) public void setMiProducto2(String codigo, String descripcion, double precioUnitario) public void setMiProducto3(String codigo, String descripcion, precioUnitario) (Aumentar en uno la cantidad de existencias adquiridas de un producto en la compra) public void agregar UnidadProducto1()
58
double
public void agregar UnidadProducto2() public void agregar UnidadProducto3() (Se requiere calcular el precio de la factura) public double calcularPrecioFactura() (Se debe devolver la cantidad de artĂculos que se incluyeron en la compra) public int getContadorAdquisiciones() (Se necesitan mĂŠtodos para devolver los productos) public Producto getMiProducto1() public Producto getMiProducto2() public Producto getMiProducto3()
El diagrama de clases correspondiente para este caso de estudio es el siguiente:
59
La construcción de esta aplicación se debe iniciar por la clase Producto. Como se mencionó con anterioridad en la clase Producto se trabajó un método constructor. Un constructor permite inicializar las variables de la clase. Es sintácticamente similar a un método y se caracteriza por tener el mismo nombre de la clase y no llevar ningún tipo de retorno, ni siquiera void. Tenga en cuenta que una clase cualquiera puede tener declarados atributos los cuales pueden ser variables de entrada o salida. Para la clase Producto los atributos identificados fueron: codigo descripcion precioUnitario cantidadE
Los valores de los tres primeros atributos los conoce el cajero y por ello se pueden considerar como variables de entrada, es decir él sabe el código del producto que va a vender, la descripción y el precio unitario. No obstante, para él es imposible conocer cuántas existencias de ese producto particular va a incluir el cliente en su compra, en tal caso se dirá que es una variable de salida, pues debe calcularse. Partiendo de lo anterior, el constructor de la clase Producto tiene 3 parámetros puesto que se necesita inicializar 3 atributos de la clase, a saber: código, descripción y precioUnitario. public Producto(String codigo, String descripcion, double precioUnitario) { this.codigo = codigo; this.descripcion = descripcion; this.precioUnitario=precioUnitario; }
La cantidad de existencias se calcula a través del método agregarExistencia(). public int agregarExistencia() { cantidadE++; return cantidadE; }
Dicho método requiere de un contador, pues cada vez que se agregue una existencia del producto se debe incrementar la variable contadorE en 1. Un contador es una variable que incrementa o decrementa su valor en una cantidad fija. Se suele utilizar cuando se presentan requisitos tales como: Obtener la cantidad de … Indicar el total de … Contar la cantidad de … La sintaxis de su uso es la siguiente: contador=contador+1; // cuando se incrementa de 1 en 1, forma larga contador+ +; //cuando se incrementa de 1 en 1, forma abreviada contador= contador+2; // cuando se incrementa de 2 en 2, forma larga contador+=2; // cuando se incrementa de 2 en 2, forma abreviada 60
contador--; //cuando se decrementa de 1 en 1, forma abreviada Tenga
en
cuenta
que
la
variable
contador
debe
declararse
de
tipo
int.
- El método calcularPrecioPedidoDelProducto no requiere parámetros, puesto que se conoce la cantidad de existencias del producto que el cliente incluyó en su compra y además el precio unitario. public double calcularPrecioPedidoDelProducto() {return cantidadE*precioUnitario;}
De la clase Compra se tienen los siguientes métodos: - El método setMiProducto1 tiene 3 parámetros, es decir, los tres datos que se requieren para poderle reservar memoria al producto1 public void setMiProducto1(String codigo, String descripcion, double precioUnitario) { miProducto1=new Producto(codigo, descripcion, precioUnitario); }
- El método agregarUnidadProducto1() permite incrementar en uno del contador de existencias de dicho producto. No tiene parámetros puesto que no requiere información externa a la que posee el objeto. public void agregarUnidadProducto1() { miProducto1.agregarExistencia(); contadorAdquisiciones++; }
- El método calcularPrecioFactura() permite calcular el precio total de la factura. Esto se hace sumando el precio total de las existencias del producto uno, con el precio total de las existencias del producto dos y el precio total de las existencias del producto tres. public double calcularPrecioFactura() { return miProducto1.calcularPrecioPedidoDelProducto()*miProducto2.calcularPrecioP edidoDelProducto()+miProducto3.calcularPrecioPedidoDelProducto(); }
- El método getMiProducto1() devuelve toda la información de miProducto1, observe que el retorno es de tipo Producto. public Producto getMiProducto1() { return miProducto1; }
61
- El mĂŠtodo getContadorAdquisiciones()devuelve el valor del contador de adquisiciones. public int getContadorAdquisiciones() { return contadorAdquisiciones; }
62
2.
EXPRESIONES Y ESTRUCTURAS DE DECISION
Objetivos Pedagógicos Al finalizar la unidad el estudiante estará en capacidad de: Utilizar instrucciones condicionales simples y anidadas para dar solución a problemas que requieren la toma de decisiones. Utilizar constantes al momento de modelar las características de un objeto Utilizar expresiones dentro de métodos como un medio para modificar el estado de un objeto. 2.1. Introducción En esta unidad se trabajarán casos de estudio que requieren para su solución la toma de decisiones, es decir, necesitan la incorporación de estructuras de selección. Para poder iniciar con esta tématica es importante que previamente se manejen los conceptos de expresiones y operadores entre Strings. a) Expresiones Aunque en la unidad anterior se hizo una breve explicación sobre el concepto de expresiones. En esta unidad se ampliará este concepto. Una expresión está formada por variables, constantes y/o operadores. Cuando va a crear una expresión se deben seguir unas reglas básicas de codificación. Tales reglas son: 1. Si se tiene un cociente y alguno de sus términos involucra una operación, éste debe encerrarse entre paréntesis. Ejemplo
H
p p / (b c) bc
2. Si se tiene una potencia debe usarse la instrucción Math.pow. El primer término es la base y el segundo es el exponente. El resultado de la potencia es un double.
(a t ) n1 Math. pow( a t , n 1 ) 3. Cuando se tenga una raíz ésta puede expresarse en forma de potencia. Puede utilizarse la instrucción Math.sqrt para sacar raíz cuadrada. n
x Math. pow( x, 1.0 / n ) x Math.sqrt( x )
4. Se debe tener clara la precedencia de los operadores. Este orden es fundamental para determinar el resultado de una expresión. A continuación se muestra una tabla en la cual se listan los operadores en orden de precedencia de mayor a menor.
63
Tipo de operadores
Operadores de este tipo
Ejemplo
Operadores posfijos
expr++, expr--
int a=b++;
Operadores unarios
++expr, --expr, +expr, -expr, !
int a=--b; boolean centinela=false; centinela=!centinela;
Creación o conversión
new
Casa miCasa=new Casa();
Multiplicación
*, /, %
int res=a*(b%2);
Suma
+, -
int res=a-5;
Relacionales o comparación
<, >, <=, >=
Igualdad
==, !=
a==b, a!=b
AND lógico
&&
centinela==false&&estado==true
OR lógico
||
centinela==false||estado==true
Condicional
?:
Asignación
=, +=, -=, *=, /=, %= Precedencia de operadores
if(a>=b)
a*=5; //a=a*5;
ACTIVIDAD 1. Identifique los valores finales de las variables enteras proporcionadas a continuación: a) int a = b = c = a = b = c = b = c =
a, b, c; 5 7 9 a + 13+c b/a + 3 + 5 – a * 7 a + (b – c) --a c + 5 – b*4 – a/3
b) int a = b = c = d = d = c = a = b =
a, b, c, d; 7 a (int)(Math.pow(a,b+1)) 0 a*b + (c – d)/5 c - d 45 - a + (-b) c – a
c) int a = b = c = d = a = b = c =
a, b, c, d; 66; 45; b % a; c / 21 * a / (b % 5); a % 3 - 5 % 2; b + a / 3 % 2 * ((64 / 3 % 2) + (3 % 2) + 12) 5*b + c % 2; 64
d = a -(b % c) / 3; d) int x,y,z,w; x = 3; y = 5; z = 11; w = 3; x -= (z + y -= (--w z *= (--x w /= (x %
(--w + y++) * 8); - ++z) % w; + --y); y);
2. Determine el valor final de cada una de las siguientes variables booleanas: a) boolean t, u, v, w, x, y, z; t = !(!true); u = false; v = u || true; z= false; w = v || u; x = (v || w) & !(!t || !u); y = (!x && !v) && (!t); z = !(!w); b) boolean t, u, v, w, x, y, z; t = (!true && false); u = !((!true) && (!false || true)); v = (false || t) && (true || u); w = (v || u) x = (t && !t && !u) && false); y = (!x && !v) ; z = !(x && !false) && false;
4. Dadas las siguientes fórmulas debe codificarlas en su correspondiente estructura de programación.
h
b k d 5 x3 8 * b hd 5 e 2*a 3/ h l u
t p
65
r t y
mv u x *5
b) Operaciones sobre Strings A continuación se proporcionan algunas de las operaciones que pueden realizarse sobre Strings a. Concatenación: Para unir dos Strings Java proporciona el operador +. Ejemplo: String nombre = "Max", apellido="Steel"; String completo = nombre + " " + apellido;
De igual forma proporciona la instrucción concat. El ejemplo anterior con la instrucción concat podría resolverse como: completo=((nombre.concat(" ")).concat(apellido)); b. Extracción de caracteres 1. charAt(): permite extraer un solo carácter de la cadena. Ejemplo: String nombre = "Max Steel", char inicial=nombre.charAt(0); //inicial queda valiendo M char segunda=nombre.charAt(1); //segunda queda valiendo a c. Modificación de un String Los métodos que proporciona Java para modificar un String son los siguientes: String replace( char original, char reemplazo ); String toLowerCase(); String toUpperCase(); String trim(); El método replace permite reemplazar un carácter dentro de un String. Los métodos toLowerCase() y toUpperCase() permiten convertir los caracteres de un String a minúscula o mayúscula respectivamente. El método trim() permite eliminar los espacios al comienzo o al final presentes en un String. Ejemplo: String nombre = "Max Steel"; nombre=nombre.replace('a', 'o'); String codigo=" 12 "; int numero=Integer.parseInt(codigo.trim());
d. Comparación de cadenas Java proporciona las siguientes instrucciones para comparar cadenas:
66
boolean equals ( Object cadena ); boolean equalsIgnoreCase ( Object cadena ); int compareTo( String cadena );
El método equals compara Strings teniendo en cuenta si están en mayúsculas o minúsculas. El método equalsIgnoreCase, ignora éste aspecto. Algunos ejemplos de uso son: String nombre = "Max", apellido="Steel"; boolean res=nombre.equals(apellido); //Esto da falso boolean res1=nombre.equalsIgnoreCase(nombre.toUpperCase()); //Esto da true
Es importante que tenga claro que la instrucción equals y el == no realizan la misma tarea. Equals compara los caracteres de ambas cadenas, mientras que el == compara las referencias de ambos objetos para comprobar si se trata de una misma instancia. El método compareTo() aplicado a dos Strings permite determinar cuál de ellas es menor o mayor alfabéticamente o si son iguales. Ejemplo: String nombre = "Max", apellido="Steel"; int resultado= nombre.compareTo(apellido); //a resultado se le asigna un //número negativo puesto que la M es alfabéticamente menor que la S. Si el método retorna un valor menor que cero entonces el primer String es menor alfabéticamente que la cadena con la que se compara. Si el valor es positivo entonces ocurre lo contrario. Si es igual a cero es porque ambos Strings son iguales. Algunos ejemplos que permitan aclarar el término alfabéticamente menor y alfabéticamente menor son: palabra1
palabra2
“vaca” “leche” “tabla” “camino” “azucar” “maleta” “asignatura” “amigo”
“caballo” “miel” “cuadro” “via” “chocolate” “maleta” “asignar” “amistad”
Resultado palabra1.compareTo(palabra2) >0 >0 >0 <0 <0 ==0 >0 <0
de
Es de anotar que el método compareTo realiza la ordenación basándose en los códigos ASCII, por lo tanto cuando se usa para ordenar String su salida no será correcta en los siguientes casos: Si hay acentos Está presente la letra ñ Hay números, puesto que los ordenaría mal Ejemplo: 1,10,110,2,3,4,45,5,.... Hay mayúsculas y minúsculas mezcladas. Las mayúsculas saldrán antes que todas las entradas con minúsculas. Si desea un método que permita ordenar Strings y que no presente los anteriores inconvenientes puede consultar Collator.
67
e. Búsqueda en las cadenas Para determinar si un carácter está presente en una cadena se puede hacer uso de dos métodos: int indexOf ( int caracter ); int lastIndexOf ( int caracter ); El método indexOf() devuelve la posición de la primera ocurrencia de un carácter dentro del String. El método lastIndexOf() devuelve la posición de la última aparición del carácter. Ejemplos de uso de estas instrucciones son: int pos=nombre.indexOf('a'); f. Cálculo de la longitud Para calcular la longitud de una cadena se utiliza el método length(). Por ejemplo si se tiene: String nombre = “Max”; int longi=cadena.length(); // Debe retornar 5
2.2. Caso de estudio 1 Unidad II: Juguetería Se desea crear una Aplicación para manejar la información de una Tienda. En la tienda se venden juguetes, cada Juguete tiene un código, un nombre, un tipo (O->Femenino 1->Masculino 2-> Unisex) y un precio. Se debe permitir agregar un nuevo juguete Informar cuantos juguetes hay por cada tipo Informar la cantidad total de juguetes Informar el valor total de todos los juguetes que hay en la tienda Informar el valor promedio de los juguetes por tipo Informar el tipo del cual hay más juguetes Ordenar de menor a mayor la cantidad de existencias de juguetes por tipo. Ejemplo si hay 5 juguetes femeninos, 2 masculinos y 7 unisex, el ordenamiento quedaría como 2 masculino, 5 femenino y 7 unisex. Comenzar una nueva tienda de juguetes 2.2.1.
Comprensión del problema
Tal como se planteó en el capítulo previo, lo primero que debe hacerse para dar solución a un problema es entender dicho problema, para ello es importante identificar los requisitos funcionales y los no funcionales, además del modelo del mundo del problema. a) Requisitos funcionales NOMBRE R1 – Informar la cantidad de juguetes que hay por tipo RESUMEN Permite contar la cantidad de juguetes que hay de un determinado tipo ENTRADAS El tipo RESULTADOS La cantidad de juguetes por tipo 68
NOMBRE R2 – Informar la cantidad total de juguetes RESUMEN Permite calcular el total de juguetes que hay en la tienda ENTRADAS Ninguna RESULTADOS La cantidad total del juguetes
NOMBRE R3 – Informar el valor total de todos juguetes RESUMEN Se suma el valor total de los juguetes ENTRADAS Ninguna RESULTADOS El valor total de los juguetes
NOMBRE RESUMEN
R4 – Informar el valor promedio de los juguetes por tipo Se acumula el valor total de los juguetes del tipo solicitado y se divide por la cantidad de juguetes de ese tipo.
ENTRADAS El tipo RESULTADOS El valor promedio
NOMBRE RESUMEN
R5 – Informar el tipo del cual hay más juguetes Se debe realizar una comparación entre los 3 tipos para determinar cuál es el que tiene mayor cantidad de juguetes. Los posibles salidas son O->Femenino, 1->Masculino y 2-> Unisex.
ENTRADAS Ninguna RESULTADOS El tipo del cual hay más juguetes
NOMBRE R6 – Comenzar una nueva tienda de juguetes RESUMEN Una nueva tienda de juguetes es creada y no tiene juguetes en su interior ENTRADAS Ninguna RESULTADOS Se comienza una nueva tienda
69
NOMBRE RESUMEN
R7 – Ordenar la cantidad de existencias de juguetes por tipo Se debe ordenar de menor a mayor la cantidad de existencias de juguetes por tipo. Ejemplo, si hay 5 juguetes femeninos, 2 masculinos y 7 unisex, el ordenamiento quedaría como 2 masculino, 5 femenino y 7 unisex.
ENTRADAS Ninguna RESULTADOS La ordenación de acuerdo a la cantidad de existencias por tipo
2.2.2.Especificación de la Interfaz de usuario Una parte importante del diseño de la solución es la especificación de la interfaz de usuario. La siguiente figura muestra el diseño seleccionado para este caso de estudio:
La ventana de la aplicación está dividida en 2 zonas: La primera de ellas permite ingresar la información de cada juguete. Allí se solicita el código, el nombre, el tipo y el precio del juguete. En la segunda zona hay 7 botones, cada uno de ellos asociado a un requisito funcional. Inicialmente se observan dos botones. Desde el primer botón es posible obtener la cantidad de juguetes por tipo y desde el segundo, calcular el valor promedio por tipo. Para ambos casos se proporciona un menú desplegable que permite seleccionar el tipo deseado. A continuación se proporcionan 4 botones, entre ellos se encuentran los que permiten calcular el total de juguetes y crear una nueva tienda.
2.2.3.Otros elementos de modelado
En el nivel anterior se introdujo el concepto de tipos de datos simples de datos (byte, short, int, long, float, double, char y boolean) y el tipo String. También se explicaron los diferentes tipos de operadores. Ahora se introducirá el concepto de constantes, a través de las cuales es posible definir datos que no cambiarán a lo largo de la ejecución de un programa.
70
La declaración de una constante incluye la palabra final. Se debe tener en cuenta que los nombres de las constantes se escriben en mayúscula y si están formados por más de una palabra se separan con guión bajo. Una constante puede usarse para definir el dominio de un atributo o para representar valores inmutables. A continuación se muestran algunos ejemplos del uso de constantes. Las siguientes constantes representan valores inmutables
public final static double CONSTANTE_PI = 3.1416; public final static double IVA = 0.16;
Las siguientes constantes representan el dominio de un atributo public final static int FEMENINO = 1; public final static int MASCULINO = 2; El concepto de constantes aplicado al caso de estudio de la Juguetería: public class Juguete {
En la columna de la izquierda se puede observar:
//Constantes public final static int FEMENINO=0; public final static int MASCULINO=1; public final static int UNISEX=2; //Atributos private String codigo, private int tipo; private double precio; }
-Se declara FEMENINO, para representar el primer valor posible del atributo tipo de juguete. Se le asigna un valor de cero. -Se declara MASCULINO, para representar el segundo valor posible del atributo tipo de juguete. Se le asigna un valor de 1.
nombre;
-Se declara UNISEX, para representar el tercer valor posible del atributo tipo de juguete. Se le asigna un valor de 2. -Se declara el atributo “tipo”
b) El modelo del mundo del problema Las actividades que se deben realizar para construir el modelo del mundo son las siguientes: Identificar las entidades o clases. Las clases identificadas son las siguientes:
ENTIDAD DEL MUNDO Tienda Juguete
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Es un atributo de la tienda
71
Identificar los métodos Los atributos y métodos identificados para cada una de las clases se muestran en las siguientes tablas.
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA JUGUETE ATRIBUTO codigo nombre tipo precio
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Valor entero positivo Valor real positivo
Tipo de dato String String int double
IDENTIFICACIÓN DE MÉTODOS (para crear un juguete se debe fijar cada uno de los atributos) public void setPrecio(double precio) public void setCodigo(String codigo) public void setNombre(String nombre) public void setTipo(int tipo) (obtener el precio y el tipo del juguete) public double getPrecio() public int getTipo()
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA TIENDA ATRIBUTO miJuguete contadorF contadorM contadorU acumuladorPrecioF acumuladorPrecioM acumuladorPrecioU
VALORES POSIBLES Referencia a un objeto de tipo Juguete Valor entero positivo Valor entero positivo Valor entero positivo Valor real positivo Valor real positivo Valor real positivo
Tipo de dato Juguete int int int double double double
IDENTIFICACIÓN DE MÉTODOS (para crear una tienda e inicializar variables se debe construir un constructor) public Tienda() (Para agregar un juguete a la tienda se cuenta con el siguiente método) public void agregarJuguete(String codigo, String nombre, int tipo, double precio) (Se requiere de un método que permita determinar la cantidad de juguetes por tipo) public void contarPorTipo(int tipo) (Se necesita un método que calcule el total de juguetes) public int devolverTotalJuguetes() (Se requiere de un método para calcular el precio total de los juguetes) public double calcularPrecioTotal()
72
(Se requiere un método para determinar cuál tipo tiene más juguetes) public String determinarTipoMayor() (Se necesita un método para poder ordenar por tipo) public String ordenar() (Se necesita un método para poder reiniciar la tienda) public void comenzarTienda()
Las Relaciones entre las clases del mundo
73
La construcción de esta aplicación inicia con la clase Juguete, que sería la siguiente: public class Juguete { //Constantes public final static int FEMENINO=0; public final static int MASCULINO=1; public final static int UNISEX=2; //Atributos private String codigo, private int tipo; private double precio;
nombre;
/** * Devuelve el precio * @return precio */ public double getPrecio() { return precio; } /** * Permite fijar el precio * @param precio El precio del juguete, precio>0 */ public void setPrecio(double precio) { this.precio = precio; } /** * Permite fijar el código * @param codigo El codigo del producto, codigo!=null */ public void setCodigo(String codigo) { this.codigo = codigo; } /** * Permite fijar el nombre del juguete * @param nombre El nombre del juguete, nombre!=null */ public void setNombre(String nombre) { this.nombre = nombre; } /** * Devuelve el tipo del juguete * @return tipo */ public int getTipo() { return tipo; } /** * Permite fijar el tipo del juguete * @param tipo El tipo del juguete, tipo>=0 && tipo<3 */ public void setTipo(int tipo) { this.tipo = tipo; }}
Para poder iniciar con la construcción de los métodos de la clase Tienda es necesario incorporar el concepto de instrucciones condicionales o estructuras de decisión. 74
2.2.4.Instrucciones Condicionales Este tipo de instrucciones permite ejecutar una instrucción sólo si se cumple una determinada condición. La estructura condicional más usada es el if. La forma de representación de la sentencia if es: if (condición) { // Instrucción o conjunto de instrucciones } La condición del if se expresa mediante una expresión booleana que se evalúa para ver si la condición es verdadera o falsa. Ejemplo: if(tipo==Juguete.FEMENINO) {return contadorF;} Recuerde que previamente se declaró la constante public final static int FEMENINO=0; Si el resultado de la evaluación de la condición es true, entonces se ejecutan todas las instrucciones que están dentro de las llaves {}, es decir, dentro del bloque. De lo contrario, las instrucciones dentro del bloque no se ejecutan. Es de resaltar, que luego de ejecutar el bloque de instrucciones relacionas con el if, la ejecución del programa continúa con el conjunto de instrucciones que se encuentran por debajo del bloque. Si lo que se requiere es escribir una instrucción alternativa doble se utiliza el if-else: if (condicion) { // instrucción o conjunto de instrucciones 1 } else { // instrucción o conjunto de instrucciones 2 } Si luego de evaluar la condición del if el resultado es true, se ejecutará el bloque de instrucciones asociados al if. De lo contrario, se ejecuta el conjunto de instrucciones asociados al else. En el caso de requerir estructuras condicionales más complejas se pueden anidar sentencias if Si inmediatamente después de la condición del if no hay llaves se asume que éste tiene una sola instrucción. Lo recomendable es que siempre se le coloquen llaves para seguir con los lineamientos de las buenas prácticas de programación. Ejemplo, si se tiene el siguiente código:
if(miJuguete.getTipo()==Juguete.FEMENINO) contadorF++; else 75
if(miJuguete.getTipo()==Juguete.MASCULINO) contadorM++; else contadorU++;
es equivalente a: if(miJuguete.getTipo()==Juguete.FEMENINO) {contadorF++; } else if(miJuguete.getTipo()==Juguete.MASCULINO) {contadorM++; } else {contadorU++; }
No hay límite con respecto al número de estructuras de selección doble que pueden ponerse en cascada. Cuando el if es anidado o en cascada las condiciones se examinan en orden descendente pasando de una a otra si la anterior resulta falsa. Cuando se encuentre la condición verdadera, entonces se efectúa la acción correspondiente a dicha condición y no se continúa examinando el resto de la estructura. En caso de no encontrar una condición verdadera se ejecuta la acción correspondiente al último else. Ahora bien, retomando el caso de estudio sobre la Tienda: “Se desea crear una Aplicación para manejar la información de una Tienda. En la tienda se venden juguetes, cada Juguete tiene un código, un nombre, un tipo (O->Femenino 1->Masculino 2-> Unisex) y un precio. Se debe permitir agregar un nuevo juguete Informar cuantos juguetes hay por cada tipo Informar la cantidad total de juguetes Informar el valor total de todos los juguetes que hay en la tienda Informar el valor promedio de los juguetes por tipo Informar el tipo del cual hay más juguetes Ordenar de menor a mayor la cantidad de existencias de juguetes por tipo. Ejemplo si hay 5 juguetes femeninos, 2 masculinos y 7 unisex, el ordenamiento quedaría como 2 masculino, 5 femenino y 7 unisex. Comenzar una nueva tienda de juguetes” el primer método que se va a construir es el método contarPorTipo. Este método requiere que el usuario ingrese el tipo deseado, por ello tipo se ha puesto como parámetro.
76
public void contarPorTipo(int tipo) { if(miJuguete.getTipo()==Juguete.FEMENINO) {contadorF++; } else if(miJuguete.getTipo()==Juguete.MASCULINO) {contadorM++; } else {contadorU++; } }
Es de anotar, que para solucionar el método contarPorTipo es necesario el uso de contadores. Un contador es una variable que se incrementa o decrementa en un valor fijo, en nuestro caso cada vez que se agrega un juguete uno de los tres contadores debe incrementarse en 1, dependiendo del juguete agregado.
El método determinarTipoMayor no requiere de parámetros puesto que ya se cuenta con datos suficientes para resolver el problema, a saber: el contador de juguetes de tipo femenino, el contador de juguetes de tipo masculino y el contador para juguetes de tipo unisex. public String determinarTipoMayor() { if(contadorF>contadorM&&contadorF>contadorU) { return "FEMENINO";} else if(contadorM>contadorF&&contadorM>contadorU) { return "MASCULINO";} else { return "UNISEX";} }
El método ordenar tiene una estructura muy similar al anterior. Este método requiere el uso de if anidados.
77
public String ordenar() { if(contadorF>contadorM&&contadorM>contadorU) { return " Femenino: "+contadorF+", Masculino: "+contadorM+", Unisex: "+contadorU; } else if(contadorF>contadorU&&contadorU>contadorM) { return " Femenino: "+contadorF+", Unisex: "+contadorU+", Masculino: "+contadorM; } else if(contadorM>contadorF&&contadorF>contadorU) { return " Masculino: "+contadorM+", Femenino: "+contadorF+", Unisex: "+contadorU; } else if(contadorM>contadorU&&contadorU>contadorF) { return " Masculino: "+contadorM+", Unisex: "+contadorU+", Femenino: "+contadorF; } else if(contadorU>contadorF&&contadorF>contadorM) { return " Unisex: "+contadorU+", Femenino: "+contadorF+", Masculino: "+contadorM; } else {return " Unisex: "+contadorU+", Masculino: "+contadorM+", Femenino: "+contadorF;} }
La instrucción if(contadorF>contadorM&&contadorM>contadorU) puede interpretarse como… Por ejemplo tengo 10 juguetes femeninos, 3 juguetes unisex, 5 juguetes masculinos. Entonces el ordenamiento correcto sería "Femenino: 10 Masculino: 5 Unisex: 3 ", puesto que contadorF que vale 10 es mayor que contadorM que vale 5 y contadorM que vale 10 es mayor que contadorU que vale 3
ACTIVIDAD 1. Basado en el caso de estudio anterior subraye en el código del método ordenar la instrucción que se ajusta a cada caso: - Se tienen 3 juguetes femeninos, 15 unisex y 7 masculinos. - Se tienen 5 juguetes masculinos, 2 femeninos y 1 femenino. 78
2. Consulte en Internet como funciona la estructura switch y modifique este caso de estudio para que haga uso de ella, al menos en un método. 3. Construya un método que permita obtener la información del juguete más económico que se haya agregado en la Tienda 2.3. Hoja de trabajo 1 Unidad II: Autoservicio Se desea crear una Aplicación para manejar la información de un autoservicio. En el autoservicio hay tanto empleados como productos. El autoservicio puede ofrecer máximo 3 productos. Cada producto posee un código, un nombre, un precio (no incluye iva) y una cantidad de existencias. También en el autoservicio hay 2 empleados. Cada empleado tiene un nombre, un código, una edad y un salario devengado. La aplicación debe permitir: Agregar un nuevo producto. Calcular el valor total de cada producto (para ello se debe solicitar al usuario el valor del iva) Indicar la cantidad de existencias que hay en el autoservicio, es decir, la suma de las existencias de los 3 productos Obtener el producto más económicos Agregar los empleados Informar si el promedio de edades de empleados de la empresa es superior a 30 años Devolver la información del empleado que devenga mayor salario Incrementar el salario del empleado especificado, siguiendo los siguientes criterios: Si el salario actual es menor a 700.000 el incremento es del 10% Si el salario actual es mayor o igual a 700.000 y menor de 1500.000 el incremento es del 15% De lo contrario el incremento es del 18%
2.3.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE RESUMEN ENTRADAS
R1 – Calcular el valor total de cada producto Para calcular el valor del producto es necesario tener en cuenta el iva
RESULTADOS
NOMBRE RESUMEN
R2 - Indicar la cantidad de existencias que hay en el autoservicio La cantidad de existencias que hay en el autoservicio es la suma de las existencias de los 3 productos
ENTRADAS RESULTADOS
79
NOMBRE RESUMEN ENTRADAS
R3 - Obtener el producto más económico
RESULTADOS
NOMBRE
R4 - Informar si el promedio de edades de empleados de la empresa es superior a 30 años
RESUMEN ENTRADAS RESULTADOS
NOMBRE RESUMEN ENTRADAS
R5 - Devolver la información del empleado que devenga mayor salario
RESULTADOS
NOMBRE
RESUMEN
R6 - Incrementar el salario del empleado especificado Para incrementar el salario del empleado se siguen los siguientes criterios: - Si el salario actual es menor a 700.000 el incremento es del 10% - Si el salario actual es mayor o igual a 700.000 y menor de 1500.000 el incremento es del 15% - De lo contrario el incremento es del 18%
ENTRADAS RESULTADOS
b) Especificación de la Interfaz de usuario
Una parte importante del diseño de la solución es la especificación de la interfaz de usuario. La siguiente figura muestra el diseño seleccionado para este caso de estudio:
80
Ventana principal
Ventana para Consultas
La Ventana Principal de la aplicación está compuesta por 3 botones, cada uno de los cuales permite navegar por las diferentes zonas de la aplicación. El primero de ellos permite ingresar a la zona de registro de un nuevo empleado. El segundo permite ingresar cada uno de los 3 productos, para ello se solicita el código, el nombre, el precio y la cantidad de existencias por cada producto. El último botón permite la realización de las consultas, cada una de ellas asociada con un requisito funcional.
c) El modelo del mundo del problema Las clases identificadas son las siguientes:
ENTIDAD DEL MUNDO Autoservicio Empleado Producto
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Es un atributo del autoservicio Es un atributo del autoservicio
Los métodos y atributos identificados son los siguientes:
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA PRODUCTO ATRIBUTO codigo nombre precio cantidadExistencias
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Valor real positivo Valor entero positivo
81
Tipo de dato String String doble int
IDENTIFICACIÓN DE MÉTODOS Los métodos identificados son los siguientes: public Producto(String codigo, String nombre, double precio,int cantidadExistencias) public double obtenerValorTotalProducto(double iva) public String getNombre() public double getPrecio() public int getCantidadExistencias()
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA EMPLEADO ATRIBUTO nombre codigo salario edad
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Valor real positivo Valor entero positivo IDENTIFICACIÓN DE MÉTODOS
Tipo de dato String String doble int
Es necesario construir los métodos set para cada uno de los atributos además de los siguientes métodos: public int getEdad() public double getSalario() public String getNombre() public void incrementarSalario()
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA AUTOSERVICIO ATRIBUTO miProducto0 miProducto1 miProducto2 miEmpleado0 miEmpleado1
VALORES POSIBLES
Tipo de dato
IDENTIFICACIÓN DE MÉTODOS Los métodos identificados son los siguientes: public void setMiProducto0(String codigo, String nombre, double precio,int cantidadExistencias)
public void setMiProducto1(String codigo, String nombre, double precio,int cantidadExistencias)
public void setMiProducto2(String codigo, String nombre, double precio,int cantidadExistencias)
public double calcularPrecioProducto(int numeroProducto, double iva ) public double calcularPrecioProducto(int numeroProducto, double iva ) public Producto hallarMasEconomico()
82
public void setMiEmpleado1(String nombre, String codigo, int edad, double salario)
public boolean informarPromedioSuperior30() public Empleado hallarEmpleadoMasSueldo() public Empleado incrementarSalario(int numeroEmpleado)
A continuación construya el diagrama de clases.
Para comenzar la construcción de la aplicación se iniciará con la clase Producto. En esta clase se requiere de un método para calcular el valor total de un producto. Este método requiere de un parámetro, el iva. public double obtenerValorTotalProducto(double iva) { }
En la clase Empleado se requiere la construcción del método incrementarSalario(). Para incrementar el salario del empleado se siguen los siguientes criterios: - Si el salario actual es menor a 700.000 el incremento es del 10% - Si el salario actual es mayor o igual a 700.000 y menor de 1500.000 el incremento es del 15% - De lo contrario el incremento es del 18% public void incrementarSalario() {
} 83
La clase Autoservicio requiere la creación de varios métodos. Entre ellos: - El método calcularPrecioProducto requiere que el usuario indique cual es el producto al cuál se le va a calcular el precio y el iva de dicho producto. public double calcularPrecioProducto(int numeroProducto, double iva ) { if(numeroProducto==0 && miProducto0!=null) { return miProducto0.obtenerValorTotalProducto(iva); } else //Complete
}
El método obtenerExistenciasTotales() permite obtener la cantidad de existencias totales. Este método no tiene parámetros. En este método se necesita declarar un acumulador que permita sumar la cantidad de existencias de cada uno de los productos. public int obtenerExistenciasTotales() {
}
El método hallarMasEconomico() permite hallar el producto más económico. Este método no tiene parámetros. public Producto hallarMasEconomico() { if(miProducto0!=null &&((miProducto1!=null&&miProducto0.getPrecio()<miProducto1.getPrecio()) ||miProducto1==null)&&((miProducto2!=null&&miProducto0.getPrecio()<miProd ucto2.getPrecio())||miProducto2==null)) {return miProducto0;} else if(miProducto1!=null &&((miProducto0!=null&&miProducto1.getPrecio()<miProducto0.getPrecio()) || miProducto0==null)&&((miProducto2!=null&&miProducto1.getPrecio()<miProduc to2.getPrecio())||miProducto2==null)) {return miProducto1;} else if(miProducto2!=null) 84
{return miProducto2;} else return null; }
El método hallarEmpleadoMasSueldo() no requiere parámetros. En él hay que comparar los salarios de los empleados para saber cuál de los dos empleados gana más. public Empleado hallarEmpleadoMasSueldo() {
}
Finalmente, el método incrementarSalario requiere de un parámetro, numeroEmpleado, que informa a cuál empleado se le va a incrementar el salario. public Empleado incrementarSalario(int numeroEmpleado) { if(numeroEmpleado==0) { miEmpleado0.incrementarSalario(); return miEmpleado0; } else { miEmpleado1.incrementarSalario(); return miEmpleado1; } }
2.4. Caso de estudio 2 Unidad II: Concesionario Se desea crear una aplicación para manejar la información de un concesionario. El concesionario tiene para la exhibición siempre tres vehículos, cada uno de ellos con placa, marca, tipo (0Carro 1 Moto) y una fecha de registro ante la oficina de tránsito. La aplicación debe permitir: Identificar la marca de los vehículos que más se repite. El tipo de vehículo menos repetido (0Carro 1 Moto) Identificar para un vehículo determinado si debe contar con certificado técnico mecánico. Es de anotar que si el vehículo es un carro debe tener certificado a partir de los 2 años, si es una moto a partir del año.
85
2.4.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE RESUMEN
R1 – Identificar la marca de los vehículos que más se repite Se debe examinar cada una de las marcas de los vehículos para saber cuál es la que más se repite
ENTRADAS Ninguna RESULTADOS La marca
NOMBRE RESUMEN
R2 – El tipo de vehículo menos repetido (0Carro 1 Moto) Se debe examinar cada uno de los tipos de los vehículos para verificar cuál es el que menos se presenta.
ENTRADAS Ninguna RESULTADOS El tipo menos repetido NOMBRE RESUMEN
R3 – Identificar para un vehículo determinado si debe contar con certificado técnico mecánico Es de anotar que si el vehículo es un carro debe tener certificado a partir de los 2 años, si es una moto a partir del año.
ENTRADAS Ninguna RESULTADOS La indicación de si debe o no tener certificado
2.4.2. Especificación de la Interfaz de usuario Una parte importante del diseño de la solución es la especificación de la interfaz de usuario. La siguiente figura muestra el diseño seleccionado para este caso de estudio:
86
La ventana de la aplicación está dividida en 2 zonas: La primera de ellas permite ingresar la información de cada vehículo. Cuando se da clic en cualquiera de los tres botones iniciales, una nueva ventana es desplegada. En esta última se solicitan la placa, la marca, el tipo y la fecha de matrícula. En la segunda zona hay 3 botones, cada uno de ellos asociado a un requisito funcional.
2.4.3.Otros elementos de modelado
Un nuevo elemento de modelado que se incorpora en este caso de estudio es el enum. Un tipo enumerado es usado para restringir el contenido de una variable a una lista de valores predefinidos. En el caso de estudio del Concesionario es posible definir un enum para el tipo en lugar de utilizar constantes tal como se hizo en el caso de estudio anterior. public enum Tipo { //Tipos de vehículos disponibles CARRO (0), MOTO (1); private int numTipo; private Tipo(int numTipo) { this.numTipo = numTipo; } public int getNumTipo() { return numTipo; } }
87
Un tipo enumerado es una instancia del tipo enumerado del que es declarado, por ello no puede considerarse como un String o un entero. Un enum también puede ir embebido dentro de una clase. Tal como se muestra a continuación: public class Vehiculo { public enum Tipo { //Tipos de vehículos disponibles CARRO (0), MOTO (1); private int numTipo; private Tipo(int numTipo) { this.numTipo = numTipo; } public int getNumTipo() {return numTipo;}} private String placa,marca; private int tipo; private Fecha miFechaRegistro; }
b) El modelo del mundo del problema Las actividades que se deben realizar para construir el modelo del mundo son las siguientes: Identificar las entidades o clases.
ENTIDAD DEL MUNDO Concesionario Vehiculo Fecha
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Es un atributo del concesionario Es un atributo de la Fecha
Identificar los métodos
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA FECHA ATRIBUTO dia mes anio
VALORES POSIBLES Valor entero positivo Valor entero positivo Valor entero positivo IDENTIFICACIÓN DE MÉTODOS
Tipo de dato int int int
(Se brindarán dos opciones para crear la fecha: un constructor para crear la fecha actual y otro con parámetros para iniciar la fecha con los valores dados por el usuario) public Fecha() public Fecha(int dia, int mes, int anio)
Adicionalmente se requieren los métodos get para cada atributo. También se necesita un método que permita calcular la diferencia entre dos fechas public int restarFechaALaPrimera( Fecha segunda, int tipo )
88
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA VEHICULO ATRIBUTO placa marca tipo miFechaRegistro
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Valor entero positivo Referencia a un objeto de tipo Fecha
Tipo de dato String String int Fecha
IDENTIFICACIÓN DE MÉTODOS (para crear un Vehiculo se debe crear un método set para para cada uno de los atributos) public void setPlaca(String placa) public void setMarca(String marca) public void setTipo(int tipo) public void setMiFechaRegistro(int dia, int mes, int anio) Para cada uno de los atributos también es necesaria la creación de los métodos get.
Las Relaciones entre las clases del mundo
89
La forma apropiada de empezar a construir el código de esta aplicación es iniciando por la clase Fecha, pues ésta no depende de ninguna otra. El constructor de Fecha que no tiene parámetros permite crear una referencia un objeto de tipo Fecha con la fecha actual.
public Fecha() { //Se obtiene la fecha actual GregorianCalendar miFechaActual = new GregorianCalendar( ); // Sacamos los valores de día, mes y año del calendario anio = miFechaActual.get( Calendar.YEAR ); mes = miFechaActual.get( Calendar.MONTH ) + 1; dia = miFechaActual.get( Calendar.DAY_OF_MONTH ); } Para restar dos fechas se ha creado un método que tiene dos parámetros. El primero recibe la fecha que se va a restar de la primera fecha y el segundo, recibe el tipo de diferencia requerida, si el valor es 0 es porque se requiere una diferencia en meses, pero si es uno se necesita en años.
//tipo 0 diferencia en meses, 1 en años public int restarFechaALaPrimera( Fecha segunda, int tipo ) { // Se determina cuantos meses hay de diferencia int diferencia = 12 * ( segunda.getAnio() - anio ) + ( segunda.getMes() - mes ); diferencia=-diferencia; //Se resta un mes en caso de que el día no sea mayor if( segunda.getDia() < dia ) diferencia--; if(tipo==1) diferencia=diferencia/12; return diferencia; }
A continuación se procede con la clase Vehiculo. En la clase Vehiculo se construye por cada atributo un método get. Entre estos métodos se tiene a: public void setMiFechaRegistro(int dia, int mes, int anio) { this.miFechaRegistro = new Fecha(dia, mes, anio); }
Otro método muy útil es el método toString, que devuelve un String con la representación del objeto.
90
public String toString() { return "Placa "+placa + ", Marca: "+marca+", "+miFechaRegistro.toString()+ ", Tipo: "+Tipo.values()[tipo]; }
Observe que en el método toString se imprime el tipo del vehículo, a través de la instrucción Tipo.values()[tipo]. La cual se puede interpretar de la siguiente forma basados en la enumeración que se muestra a continuación: public enum Tipo { //Tipos de vehículos disponibles CARRO (0), MOTO (1); private int numTipo; private Tipo(int numTipo) { this.numTipo = numTipo; } public int getNumTipo() { return numTipo; } }
Si tipo toma el valor de cero, entonces Tipo.values()[0] devolverá CARRO, pero si toma el valor de 1, Tipo.values()[1] devolverá MOTO. En la clase Concesionario es necesario trabajar el método determinarCertificadoTecnicoMecanico. Este método recibe un vehículo. Para realizar el cálculo lo primero que debe hacerse es calcular la fecha actual y a ésta restarle la fecha en que el vehículo se registró ante la secretaría de tránsito. public boolean determinarCertificadoTecnicoMecanico(Vehiculo miVehiculo) { if(miVehiculo!=null) { Fecha miFecha=new Fecha(); int antiguedad=miFecha.restarFechaALaPrimera(miVehiculo.getMiFechaRegistro(), 1); //si es carro if (miVehiculo.getTipo()==0) { if(antiguedad>=2) {return true;} else {return false;} }//Cierra if carro else { if(antiguedad>=1) {return true;} else {return false;}
91
}//Cierra else de moto }//Cierra if de miVehiculo!=null return false; }
Para hallar la marca que más se repite se crearon dos métodos, el primero tiene un parámetro, marca, que permite saber la cantidad de vehículos del concesionario que poseen dicha marca. public int contarMarca(String marca) { int contador=0; if(marca.equals(miVehiculo0.getMarca())) {contador++;} if(marca.equals(miVehiculo1.getMarca())) {contador++;} if(marca.equals(miVehiculo2.getMarca())) {contador++;} return contador; }
En el segundo, se invoca el método anterior, enviando como argumento uno de los vehículos según se requiera.
public String hallarMarcaMasRepite() { if(miVehiculo0!=null&&miVehiculo1!=null&&miVehiculo2!=null) { if(contarMarca(miVehiculo0.getMarca())>=contarMarca(miVehiculo1.getMarca( ))&&contarMarca(miVehiculo0.getMarca())>=contarMarca(miVehiculo2.getMarca ())) {return miVehiculo0.getMarca();} else if(contarMarca(miVehiculo1.getMarca())>=contarMarca(miVehiculo0.getMarca( ))&&contarMarca(miVehiculo1.getMarca())>=contarMarca(miVehiculo2.getMarca ())) {return miVehiculo1.getMarca();} else {return miVehiculo2.getMarca();} }// Cierra el if en el que se verifica que los vehículos no sean null else return "Debe ingresar primero los tres vehiculos"; }
2.5. Hoja de Trabajo 2 Unidad II: Floristería Se desea crear una aplicación para manejar la información de una floristería. En la floristería se hacen 4 pedidos (cada uno de ellos con una cantidad y un tipo asignado). Un tipo está formado por un nombre de la flor (0 Rosas, 1 Tulipanes, 2 Girasoles o 3 Crisantemos) y una valoración dada (0Calidad de exportación ó 1 Calidad normal).
92
La aplicación debe permitir calcular el valor total de los 4 pedidos si se sabe que el valor unitario por flor es: Si es Rosas Calidad de exportación el valor unitario es 4000 pesos Tulipanes Calidad de exportación, el valor unitario es de 3200 Girasoles Calidad de exportación, el valor unitario es de 3500 Crisantemos Calidad de exportación, el valor unitario es de 2200 El precio de las flores calidad normal es del 70% del precio de la flor calidad exportación de su categoría. De igual forma se debe permitir obtener: La cantidad de productos por nombre de flor (Rosas, Tulipanes, Girasoles, Crisantemos) que hay en la floristería La cantidad de productos por nombre de Flor y valoración especifica que hay en la floristería El nombre de la flor con más cantidad de flores en toda la floristería Informar si el precio total de un pedido particular excede los 200000
2.5.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE RESUMEN ENTRADAS
R1 – Calcular el valor total de los pedidos
RESULTADOS
NOMBRE RESUMEN ENTRADAS
R2 – Obtener la cantidad de productos por nombre de flor
RESULTADOS
NOMBRE
R3 – Obtener la cantidad de productos por nombre de Flor y valoración especifica que hay en la floristería
RESUMEN ENTRADAS RESULTADOS
93
NOMBRE RESUMEN ENTRADAS
R4 - El nombre de la flor con más cantidad de flores en toda la floristería
RESULTADOS
NOMBRE RESUMEN ENTRADAS
R5 - Informar si el precio total de un pedido particular excede los 200000
RESULTADOS
b) Especificación de la Interfaz de usuario Una parte importante del diseño de la solución es la especificación de la interfaz de usuario. La siguiente figura muestra el diseño seleccionado para este caso de estudio:
La ventana está dividida en dos zonas. La primera de ellas es la zona de ingreso de los pedidos. La segunda zona permite realizar todas las consultas, cada uno de los botones está asociado con un requisito funcional.
94
c) El modelo del mundo del problema Las clases identificadas son las siguientes:
ENTIDAD DEL MUNDO Floristeria Pedido Tipo
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Es un atributo de la Floristeria Es un atributo del Pedido
Los métodos y atributos identificados son los siguientes:
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA TIPO ATRIBUTO nombreFlor valoración public public public public
VALORES POSIBLES Valor entero positivo Valor entero positivo IDENTIFICACIÓN DE MÉTODOS
Tipo de dato int int
Tipo(int tipo, int valoración) int getNombreFlor() int getValoración() double calcularValorUnitario()
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA PEDIDO ATRIBUTO
VALORES POSIBLES
cantidad miTipo IDENTIFICACIÓN DE MÉTODOS public public public public public public
Pedido(int cantidad) int getCantidad() void setCantidad(int cantidad) void setMiTipo(int nombreFlor, int valoración) double calcularValorTotalPedido() boolean determinarExcede()
95
Tipo de dato
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA FLORISTERÍA ATRIBUTO miPedido0 miPedido1 miPedido2 miPedido3
VALORES POSIBLES
Tipo de dato
IDENTIFICACIÓN DE MÉTODOS public void setMiPedido(int numPedido,int cantidad,int nombre, int valoración) public double calcularValorTotal4Pedidos() public double obtenerCantidadPorNombreFlor(int nombreFlor) public double obtenerCantidadPorNombreFlorYValoracion(int nombreFlor, int valoracion) public String obtenerNombreCategoriaConMasFlores() public boolean informarExcede(int numPedido)
A continuación construya el diagrama de clases.
96
2.5.2. Asociaciones opcionales Si se quisiera modificar el enunciado del caso de estudio anterior para indicar que pueden haber 1 o 2 empleados, serรก necesario hacer uso de la cardinalidad, esto se logra indicando que las asociaciones pueden existir o no. Tal como se muestra en el diagrama de clases siguiente:
97
En el siguiente diagrama de objetos se aprecian asociaciones opcionales.
miFloristeria: Floristeria
miPedido0
: Pedido
miPedido1=null miPedido2=null miPedido3=null
Diagrama de objetos donde se aprecian asociaciones opcionales
2.6. Tipos de métodos Los métodos se clasifican en: Métodos constructores, los cuales permiten inicializar los atributos de un objeto al momento de reservarle memoria. Métodos modificadores (setter), los cuales permiten modificar el estado de los objetos, durante la ejecución. Métodos accesores (getter), los cuales permiten obtener el valor de algún atributo de un objeto. Métodos analizadores quienes tiene como responsabilidad el “saber hacer”, pues gracias a ellos es posible calcular información valiéndose del estado de los objetos.
Actividad Complete el código para las clases de la hoja de trabajo de la Floristería. public public public public public public public
class Tipo static int static int static int static int static int static int
{ NOMBRE_ROSAS=0; NOMBRE_TULIPANES=1; NOMBRE_GIRASOLES=2; NOMBRE_CRISANTEMOS=3; VALORACION_EXPORTACION=0; VALORACION_NORMAL=1;
private int nombreFlor; private int valoracion; 98
public Tipo(int tipo, int valoracion) { } public int getNombreFlor() { } public int getValoracion() { return valoracion; } public double calcularValorUnitario() { double precio=0; if(nombreFlor==NOMBRE_ROSAS&&valoracion==VALORACION_EXPORTACION) { precio= 4000; }
} }
public class Pedido { private int cantidad; private Tipo miTipo; public Pedido(int cantidad) { } public int getCantidad() {
} public void setCantidad(int cantidad) { this.cantidad = cantidad; } 99
public Tipo getMiTipo() { return miTipo; } public void setMiTipo(int nombreFlor, int valoracion) { this.miTipo = new Tipo(nombreFlor,valoracion); } public double calcularValorTotalPedido() { return cantidad*miTipo.calcularValorUnitario(); } public boolean determinarExcede() {
}
public class Floristeria { private Pedido miPedido0, miPedido1, miPedido2, miPedido3; public Floristeria() { miPedido0=new Pedido(0); miPedido1=new Pedido(0); miPedido2=new Pedido(0); miPedido3=new Pedido(0); } public double calcularValorTotal4Pedidos() {
} public double obtenerCantidadPorNombreFlor(int nombreFlor) { double acum=0;
100
} public double obtenerCantidadPorNombreFlorYValoracion(int nombreFlor, int valoracion) { double acum=0; if(miPedido0.getMiTipo().getNombreFlor()==nombreFlor&&miPedido0.getMiTipo ().getValoracion()==valoracion) { acum+=miPedido0.getCantidad(); } if(miPedido1.getMiTipo().getNombreFlor()==nombreFlor&&miPedido1.getMiTipo ().getValoracion()==valoracion) { acum+=miPedido1.getCantidad(); } if(miPedido2.getMiTipo().getNombreFlor()==nombreFlor&&miPedido2.getMiTipo ().getValoracion()==valoracion) { acum+=miPedido2.getCantidad(); } if(miPedido3.getMiTipo().getNombreFlor()==nombreFlor&&miPedido3.getMiTipo ().getValoracion()==valoracion) { acum+=miPedido3.getCantidad(); } return acum; } public { double double double double
String obtenerNombreCategoriaConMasFlores() a=obtenerCantidadPorNombreFlor(Tipo.NOMBRE_ROSAS); b=obtenerCantidadPorNombreFlor(Tipo.NOMBRE_GIRASOLES); c=obtenerCantidadPorNombreFlor(Tipo.NOMBRE_CRISANTEMOS); d=obtenerCantidadPorNombreFlor(Tipo.NOMBRE_TULIPANES);
if(a>=b&&a>=c&&a>=d) { return "Rosas" ; }
101
} public boolean informarExcede(int numPedido) { Pedido inicializado=detectarPedido(numPedido); return inicializado.determinarExcede(); }}
102
3.
ESTRUCTURAS CONTENEDORAS
Objetivos Al finalizar la unidad el estudiantes estará en capacidad de: Utilizar estructuras contenedoras de tamaño fijo para resolver problemas en los cuales es necesario almacenar una secuencia de elementos Utilizar ciclos para poder manipular las estructuras contenedoras fijas Construir interfaces gráficas que involucren la utilización de estructuras contenedoras de tamaño fijo.
3.1. Caso de estudio 1Unidad III: Grupo de estudiantes Un docente requiere de una aplicación para manejar la información de un grupo en el cual hay como máximo 6 estudiantes, cada uno de ellos con código, nombre y una asignatura. De cada asignatura se conocen dos notas parciales. Se debe permitir calcular la nota promedio del curso Informar cuántos estudiantes obtuvieron nota en el rango especificado: 0 y 2..99 3 y 3.99 4y5 Informar cuántos estudiantes ganaron la asignatura
103
3.1.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE RESUMEN
R1 – Calcular la nota promedio del curso Se suman todas las notas de los estudiantes y se divide por el número de estudiantes.
ENTRADAS Ninguna RESULTADOS La nota promedio
NOMBRE RESUMEN
R2 – Informar cuántos estudiantes obtuvieron nota en el rango especificado Existen 3 rangos: 0 y 2..99 3 y 3.99 4y5
ENTRADAS El rango RESULTADOS La cantidad de estudiantes con nota en el rango indicado
NOMBRE R3 – Informar cuántos estudiantes ganaron la asignatura RESUMEN ENTRADAS Ninguna RESULTADOS La cantidad de estudiantes que ganaron la asignatura
b) El modelo del mundo del problema Las actividades que se deben realizar para construir el modelo del mundo son: Identificar las entidades o clases.
ENTIDAD DEL MUNDO Grupo Estudiante Asignatura
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Es un atributo del Grupo Es un atributo del Estudiante
Identificar los atributos y los métodos.
104
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA ASIGNATURA ATRIBUTO nota1 nota2 public public public public public public
VALORES POSIBLES Valores reales positivos Valores reales positivos IDENTIFICACIÓN DE MÉTODOS
Tipo de dato double double
Asignatura(double nota1, double nota2) double calcularDefinitiva() double getNota1() void setNota1(double nota1) double getNota2() void setNota2(double nota2)
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA ESTUDIANTE ATRIBUTO codigo nombre miAsignatura0 public public public public public
VALORES POSIBLES Cadena de caracteres Cadena de caracteres Referencia a objeto de tipo Asignatura IDENTIFICACIÓN DE MÉTODOS
Tipo de dato String String Asignatura
Estudiante(String codigo, String nombre) String getCodigo() String getNombre() void setMiAsignatura0(double nota1, double nota2) boolean isGanador()
IDENTIFICACIÓN Y MODELAMIENTO DE ATRIBUTOS PARA GRUPO ATRIBUTO misEstudiantes
public public double public public public
VALORES POSIBLES Arreglo de referencias a objetos de tipo estudiante IDENTIFICACIÓN DE MÉTODOS
Tipo de dato Estudiante []
Grupo() void agregarEstudiante(int posicion, String codigo, String nombre, nota1, double nota2) double calcularPromedio() int contarRango(int rango) int contarEstudiantesGanaron()
105
3. Las Relaciones entre las clases del mundo
Para iniciar la construcción de esta aplicación se inicia por la clase Asignatura. En esta clase es necesario realizar el método calcularDefinitiva. Este método no tiene parámetros. public double calcularDefinitiva() { return (nota1+nota2)/2; }
En la clase Estudiante se requiere el método isGanador() que permite identificar si el estudiante ganó o perdió la asignatura public boolean isGanador() { if(miAsignatura0.calcularDefinitiva()>=3) { return true; } else {return false;} }
Dado que en la clase Grupo se necesita manejar la información de un listado de estudiantes, se requiere la incorporación del concepto de estructuras contenedoras de tamaño fijo, más conocidas como arreglos.
106
Los arreglos son un tipo de estructura contenedora, que permite agrupar elementos del mismo tipo de datos, por ejemplo un grupo de estudiantes, una lista de productos y un grupo de empleados. A todo arreglo se le debe declarar y reservarle memoria antes de empezar a usarlo. La forma de declarar un arreglo es la siguiente: Primero va el tipo de dato y luego nombre. Por ejemplo: Estudiante[] misEstudiantes; //Se declara misEstudiantes=new Estudiante[6]; //Se reserva memoria Como puede verse en la línea de la declaración, se hizo uso del operador de indexación “[]”. Esta sintaxis permite especificar que se va a almacenar una lista de elementos del mismo tipo. Este operador permite tener acceso a cada uno de los elementos de la estructura contenedora escribiendo primero el nombre del arreglo, seguido de los corchetes que tendrán en su interior un índice, variable de tipo entero, que indicará la posición a la cual se desea tener acceso. Por ejemplo, si se desea acceder al elemento del arreglo misEstudiantes que se encuentra en la posición 3 se escribiría misEstudiantes[3]; Observe que para poder reservarle memoria al arreglo se hizo uso del operador new. Es importante resaltar que la declaración y creación del arreglo se pueden hacer en una sola línea.
Estudiante[] misEstudiantes = new Estudiante[6]; ó Estudiante misEstudiantes[] = new Estudiante[6]; Es de anotar que si el arreglo no es de tipo de datos primitivo, será necesario además de reservarle memoria al arreglo, reservarle memoria a cada uno de los elementos que el arreglo va a contener. Una estructura contenedora puede tener una o más dimensiones. En este material solo se trabajarán con estructuras unidimensionales. Para poder recorrer y manipular los elementos almacenados en una estructura de este tipo es necesario hacer uso de estructuras repetitivas. Una estructura repetitiva se utiliza cuando se necesita que una serie de instrucciones se ejecuten un número determinado de veces. Toda estructura repetitiva consta de tres partes básicas, a saber:
Decisión: en esta parte se evalúa la condición y, en caso de ser cierta, se ejecuta el ciclo.
Cuerpo del ciclo: en esta parte van las instrucciones que se desea ejecutar varias veces.
Salida del ciclo: es la condición que indica cuando termina de ejecutarse el ciclo, es decir, que ya no se repetirán más las instrucciones.
107
Normalmente los ciclos se controlan mediante una variable denominada contador, que incrementa o decrementa su valor en un valor fijo cada vez que se efectúa una repetición. Es muy común también encontrar en los ciclos variables acumuladoras, que permiten almacenar una cantidad variable, resultado de operaciones repetidas y sucesivas. La estructura repetitiva más usada para trabajar con arreglos es el ciclo for. El for tiene la siguiente estructura:
for ( inicialización; condicion; iteración) { acción 1 ........ acción n
}
Lo primero que se ejecuta es la inicialización, que normalmente lleva una expresión de asignación dirigida hacia un contador (variable de control) del ciclo. Esta expresión se ejecuta solamente una vez. Luego se evalúa la condición, que debe dar como resultado una expresión booleana. Si la comparación da como resultado true, entonces se ejecuta el cuerpo del ciclo. De lo contrario, el ciclo finaliza. A continuación se efectúa la iteración, en la que normalmente se incrementa o decrementa la variable de control del ciclo. Es importante que tenga en cuenta que en cada pasada del ciclo, se evalúa de nuevo la expresión condicional, se ejecuta el cuerpo del ciclo y se continúa con la iteración. Esto se efectuará hasta que la condición sea falsa. Ahora bien, el concepto de ciclos aplicado en los arreglos permitirá recorrer dichas estructuras contenedoras, partiendo desde la posición cero hasta la totalidad de elementos que se encuentren almacenados. Esto no quiere decir que no pueda recorrerse en un orden diferente. Para lograr dicho objetivo se deberá declarar un índice que permita manejar la posición a la cual se desea tener acceso. Retomando el caso de estudio del Colegio, se tiene entonces que se requiere un método constructor. En este método es necesario reservarle memoria al arreglo de estudiantes. public Grupo() { // MAXIMO_ESTUDIANTES es una constante con valor de 6 misEstudiantes=new Estudiante[MAXIMO_ESTUDIANTES]; }
108
También se debe crear un método para agregar cada uno de los estudiantes. Este método además de todos los datos necesarios para crear el estudiante, necesita saber la posición del estudiante que se va a almacenar. public void agregarEstudiante(int posicion, String codigo, String nombre, double nota1, double nota2) { Estudiante miE=new Estudiante(codigo, nombre); miE.setMiAsignatura0(nota1, nota2); misEstudiantes[posicion]=miE; } El método calcularPromedio no requiere parámetros, pues con el listado de estudiantes es suficiente para realizar dicho cálculo. En este método es necesario declarar a i (índice para moverse a través del arreglo), un contador para saber cuántos estudiantes hay y un acumulador para poder almacenar la sumatoria de las definitivas de cada estudiante. Observe que el for se efectúa seis veces. En cada ejecución verifica que se haya almacenado un estudiante. Si es afirmativo, obtiene su nota definitiva y la almacena en el acumulador y simultáneamente incrementa el contador para indicar que en ese espacio hay un estudiante. Al final divide el acumulador, sumatoria de las notas definitivas, por el contador de estudiantes. public double calcularPromedio() { double acumulador=0; int contador=0; for(int i=0; i<MAXIMO_ESTUDIANTES;i++) { if(misEstudiantes[i]!=null) { acumulador+=misEstudiantes[i].getMiAsignatura0().calcularDefinitiva(); contador++; } } return acumulador/contador; } El método para determinar cuántos estudiantes obtuvieron nota definitiva en el rango especificado recibe como parámetro una variable de tipo entero llamada rango. Si el valor de rango es 0 se está solicitando el rango entre 0 y 2.99, si su valor es 1 se pide el rango entre 3 y 3.9. Si el valor es 2 es el rango entre 4 y 5. La variable rango determina el punto de inicio y de finalización del for. public int contarRango(int rango) { double inicia=0, finaliza=3; int contador=0; if(rango==1) { inicia=3; finaliza =4; } else if(rango==2) {inicia=4; finaliza=5.01; } for(int i=0; i<MAXIMO_ESTUDIANTES; i++) {
109
if(misEstudiantes[i]!=null&&misEstudiantes[i].getMiAsignatura0().calcular Definitiva()>=inicia&&misEstudiantes[i].getMiAsignatura0().calcularDefini tiva()<finaliza) { contador++; } } return contador; }
El último método requerido es el método contarEstudiantesGanaron(), que no requiere parámetros. En este método se necesita declarar el índice y además un contador. Observe que siempre se verifica que en la posición i haya un estudiante, esto con el objetivo de que no se produzca la excepción NullPointerException. public int contarEstudiantesGanaron() { int contador=0; for(int i=0; i<MAXIMO_ESTUDIANTES; i++) { if(misEstudiantes[i]!=null&&misEstudiantes[i].isGanador()==true) { contador++; } }//Finaliza el for return contador; }
3.2. Hoja de Trabajo 1 Unidad III: VideoTienda Se desea crear una aplicación para una videotienda. En ella se alquilan películas. Cada película tiene asociado un código, un nombre, una cantidad de existencias en bodega, un género (acción, terror, infantil, drama y un listado de actores, máximo 5. Cada actor tiene un cedula y un nombre. Se debe permitir: Ingresar un actor (se debe validar que no se ingresen actores que ya hayan sido ingresados) Ingresar una película (se debe validar que no se ingresen películas que ya hayan sido ingresadas) Prestar una película a un usuario (verificar que haya existencias disponibles). Se debe buscar por el código de la película. Es de anotar, que un usuario tiene un código y un nombre. Agregar un usuario Listar las películas que un usuario tiene prestadas. Listar los protagonistas de una determinada película Listar las películas de un determinado protagonistas, para ello se solicita el código del protagonista Mostrar la película más prestada
110
3.2.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE RESUMEN ENTRADAS
R1 – Prestar una película a un usuario
RESULTADOS
NOMBRE
R2 – Listar las películas que un usuario tiene prestadas
RESUMEN ENTRADAS RESULTADOS
111
NOMBRE
R3 – Listar los protagonistas de una determinada película
RESUMEN ENTRADAS RESULTADOS
NOMBRE
R4 – Listar las películas de un determinado protagonistas
RESUMEN ENTRADAS RESULTADOS
NOMBRE
R5 – Mostrar la película más prestada
RESUMEN ENTRADAS RESULTADOS
b) El modelo del mundo del problema Algunas de las actividades que se deben realizar para construir el modelo del mundo son: Identificar las entidades o clases.
ENTIDAD DEL MUNDO VideoTienda Prestamo Pelicula
DESCRIPCIÓN
Identificar las relaciones entre las clases del mundo
112
113
Algunos de los métodos de la clase VideoTienda son: listarProtagonistasPelicula permite listar todos los protagonistas de una película, para ello el usuario debe indicar la posición donde está ubicada la película dentro del array de películas. El método devuelve un array de String con todos los protagonistas de la película. public String[] listarProtagonistasPelicula(int posicion) { String salida[]=new String[5]; Pelicula miPelicula=misPeliculas[posicion]; for(int i=0; i< miPelicula.getContadorActores();i++) { salida[i]=miPelicula.getMisActores()[i].toString(); } return salida; }
El método listarPeliculasPrestadasPorUsuario permite listar las películas que un usuario tiene prestadas, para ello se debe indicar la posición donde está ubicado el usuario dentro del array de usuarios. public String[] listarPeliculasPrestadasPorUsuario(int posicion) { /*Obtenga primero el usuario y a continuación recorra el arreglo de préstamos buscando ese usuario*/
}
114
El método listarPeliculasProtagonista permite listar las películas que un actor ha protagonizado, para ello se debe indicar la posición que el actor ocupa dentro del arreglo de protagonistas. public String[] listarPeliculasProtagonista(int posicionActor) { /*Primero obtenga el actor. Debe realizar dos for. El primero para recorrer el arreglo de películas y el segundo para recorrer por cada película el arreglo de actores. */ for(int i=0; i<contadorPeliculas; i++) { for(int j=0; j<misPeliculas[i].getContadorActores();j++) {
} } return peliculas; }
El método devolverCantidadDvdPrestadosPorPelicula recibe el código de la película y a través de un for que permite recorrer el arreglo de préstamos permite buscar la película. Si la encuentra el contador se incrementa. public int devolverCantidadDvdPrestadosPorPelicula(String codigo) { int contador=0;
}
115
El método prestarPelicula permite prestar una película. Tiene dos parámetros posicionP y posicionCliente. posicionP es la posición de la película dentro del arreglo de películas y posicionCliente es la posición del cliente dentro del arreglo de clientes. Para prestar la película es necesario verificar que haya existencias de la película y que el cliente ya no tenga en su poder una existencia de esa mismas película. public boolean prestarPelicula(int posicionP, int posicionCliente ) { /** * Se debe obtener la pelicula y el cliente, al igual que la cantidad de dvds prestados por esa pelicula. Es importante tener en cuenta que si solo hay por ejemplo 3 dvds de esa pelicula y ya todos estan prestados no podrá prestar mas. De igual forma se verifica que ese prestamo no haya sido efectuado ya, eso quiere decir que si el cliente con codigo 123 presto la pelicula 45, entonces este cliente no podrá volver a prestar esa pelicula */ Pelicula miPeli=misPeliculas[posicionP]; Cliente miCliente=misClientes[posicionCliente]; int cantidadPrestamos=devolverCantidadDvdPrestadosPorPelicula(miPeli.getCodigo()); if(cantidadPrestamos<miPeli.getCantidadDeExistencias()&&verificarYaExistePrestamo (miPeli, miCliente)==false) { Prestamo miP = new Prestamo(miPeli, miCliente); misPrestamos[contadorPrestamos]=miP; contadorPrestamos++; return true; } return false; }
El método verificarYaExistePrestamo permite verificar si una película ya ha sido prestada a un cliente. Se debe verificar esto porque un cliente solo tiene permitido alquilar una copia de una determinada película. Tiene dos parámetros: miPelicula y miCliente. public boolean verificarYaExistePrestamo(Pelicula miPelicula, Cliente miCliente) { /*Se recorre el array de prestamos y se verifica si el usuario tiene prestada la película se retorne true si es asi, de lo contrario false*/ for(int i=0; i<contadorPrestamos; i++) { if(misPrestamos[i].getMiPelicula().getCodigo().equals(miPelicula.getCodig o())&& misPrestamos[i].getMiCliente().getCodigo().equals(miCliente.getCodigo())) { return true;} } return false; }
116
El método devolverPeliculaMasPrestada() no tiene parámetros. Este método requiere el uso de un for. En el interior del for se invoca el método devolverCantidadDvdPrestadosPorPelicula. public Pelicula devolverPeliculaMasPrestada() { Pelicula masPrestada=null; int mayor=0, cantidadPrestamosPelActual=0;
return masPrestada; }
3.3. Caso de estudio 2 Unidad III: Parqueadero Se desea crear una aplicación para la administración de un parqueadero. El parqueadero está formado por 30 puestos. Los 12 primeros destinados a motos y los restantes a carros. Cada puesto tiene un número, un tipo (0 Vehículo Particular, 1 Moto) y un estado (0 libre 1 Ocupado). Para poder asignar un espacio dentro del parqueadero cuando un vehículo llega su propietario debe informar la placa del vehículo y el modelo, por su parte el administrador del sistema debe registrar la hora y fecha de ingreso manualmente o seleccionar la fecha actual del sistema. Es muy importante que cuando llegue el propietario del vehículo a retirar su moto o carro se le informe cuanto debe pagar, para ello se debe tener en cuenta la fecha y hora de salida del vehiculo, al igual que el tipo de vehiculo, pues si es moto el valor de la hora es 600 mientras que si es carro es de 1200. Es importante tener en cuenta que si al calcular la diferencia en horas y minutos entre las dos fechas, la cantidad de minutos es inferior a 6 minutos no se le cobrará una hora más, de lo contrario sí. Ejemplo, si son 5 horas y 10 minutos, se deberán cobrar 6 horas, pero si son 4 horas y 3 minutos se cobrarán solo cuatro horas.
117
3.3.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE R1 – Ubicar un vehículo dentro del parqueadero RESUMEN El usuario ingresa la placa, el modelo, el tipo y la fecha y hora de ingreso ENTRADAS La placa, el modelo y el tipo de vehículo. También la hora y fecha de ingreso RESULTADOS Al vehículo se le ha asignado un puesto en el parqueadero
118
NOMBRE
RESUMEN
R2 – Efectuar el cobro al vehículo que se va a retirar de parqueadero. Para poder cobrar por el tiempo de estadía en el parqueadero se debe tener en cuenta la fecha y hora de entrada y salida del vehículo, al igual que el tipo de vehículo, pues si es moto el valor de la hora es 600 mientras que si es carro es de 1200. Es importante tener en cuenta que si al calcular la diferencia en horas y minutos entre las dos fechas, la cantidad de minutos es inferior a 6 minutos no se le cobrará una hora más, de lo contrario sí. Ejemplo, si son 5 horas y 10 minutos, se deberán cobrar 6 horas, pero si son 4 horas y 3 minutos se cobrarán solo cuatro horas.
ENTRADAS placa RESULTADOS El valor a pagar
NOMBRE RESUMEN
R3 – Retirar un vehículo del parqueadero El dueño del vehículo da la placa del vehículo y el sistema debe buscarlo para poder liberar el espacio
ENTRADAS La placa, la fecha y hora de salida RESULTADOS El vehículo ha liberado el espacio dentro del parqueadero
b) El modelo del mundo del problema Las actividades que se deben realizar para construir el modelo del mundo son: Identificar las entidades o clases.
ENTIDAD DEL MUNDO Parqueadero Puesto Reservación Fecha Vehículo
DESCRIPCIÓN Es la entidad más importante del mundo del problema. Es un atributo del Parqueadero Es un atributo del Puesto Es un atributo de la Reservación Es un atributo de la Reservación
119
Identificar las relaciones entre las clases del mundo
120
En la clase Fecha se crearon dos métodos constructores. El primero de ellos sin parámetros. El objetivo de este constructor es crer una nueva fecha con el día y hora de hoy. public Fecha() { // Se usa un calendario Gregoriano inicializado en el día de hoy GregorianCalendar gc = new GregorianCalendar( ); // Se sacan los valores de día, mes y año del calendario dia = gc.get( Calendar.DAY_OF_MONTH ); mes = gc.get( Calendar.MONTH ) + 1; anio = gc.get( Calendar.YEAR ); hora=gc.get( Calendar.HOUR ); minuto=gc.get( Calendar.MINUTE ); } El segundo constructor permite crear una fecha con los datos proporcionados por el usuario. public Fecha(int dia, int mes, int anio, int hora, int minuto) { this.dia = dia; this.mes = mes; this.anio = anio; this.hora = hora; this.minuto = minuto; } Otro método que se requiere es el método calcularDiferenciaEnMinutos(Fecha miFechaMayor). Este método le resta a una fecha la fecha que recibe por parámetro y devuelve la cantidad de horas y minutos que hay entre ambas fechas. public Fecha calcularDiferenciaEnMinutos(Fecha miFechaMayor) { GregorianCalendar menor=devolverGregorianCalendar(this); GregorianCalendar mayor=devolverGregorianCalendar(miFechaMayor); long diferencia = mayor.getTime().getTime()-menor.getTime().getTime(); double minutos = diferencia / (1000 * 60); int horas = (int) (minutos / 60); int minuto = (int) (minutos%60); // int segundos = (int) diferencia % 1000; int dias = horas/24; return new Fecha(0,0,0,horas,minuto); } Por otra parte, en la clase Reservacion se declararon los siguientes atributos y constantes: //Atributos private Vehiculo miVehiculo; private Fecha miFechaEntrada, miFechaSalida; private double valorAPagar; //Constantes public static double VALOR_CARRO=1200; public static double VALOR_MOTO=600;
121
En esta clase se require de un método constructor que permite inicializar los atributos miVehiculo y miFechaEntrada. public Reservacion( Vehiculo miVehiculo, Fecha miFechaEntrada) { this.miVehiculo = miVehiculo; this.miFechaEntrada = miFechaEntrada; } El método calcularValorAPagar() permite calcular el valor a pagar por la estadía en el parqueadero. Este método no requiere de parámetros public double calcularValorAPagar() { Fecha miF= miFechaEntrada.calcularDiferenciaEnMinutos(miFechaSalida); if(miF.getMinuto()>5) {return miF.getHora()+1;} else {return miF.getHora();} }
En la clase Puesto se ha declarado un arreglo de reservaciones. A través de este arreglo es posible saber qué vehículos se han ubicado en un determinado puesto. Cuando un nuevo vehículo llega al parqueadero y se le asigna un puesto, entonces se genera una reservación. El método agregarReservación tiene como parámetros los datos del vehículo y la fecha y hora de ingreso.
public boolean agregarReservacion(String placa,int modelo,int dia, int mes, int anio, int hora, int minuto) { Reservacion nueva=new Reservacion(new Vehiculo(placa, modelo),new Fecha(dia,mes,anio,hora,minuto)); if(contadorReservaciones<200) { misReservaciones[contadorReservaciones]=nueva; contadorReservaciones++; estado=ESTADO_OCUPADO; return true; } return false; }
Como se dijo en el caso de estudio anterior, cuando se crea un arreglo de referencias a objetos no es suficiente con reservarle memoria a la estructura contenedora. Se necesita también reservarle memoria a cada uno de los elementos. Para el caso de estudio del Parqueadero se necesita un arreglo de Puestos. A este arreglo se le debe reservar memoria, pero también a cada uno de los
122
puestos que lo componen. El método constructor de la clase Parqueadero es el encargado de cumplir este objetivo.
public Parqueadero () { // Aquí se le reserva memoria al arreglo de puestos misPuestos=new Puesto[MAXIMO]; //Este for permite reservarle memoria a cada uno de los puestos. A cada uno de ellos se le asigna un número, un estado y un tipo. for(int i=0; i<MAXIMO; i++) { misPuestos[i]=new Puesto(); misPuestos[i].setNumero(i+i); misPuestos[i].setEstado(Puesto.ESTADO_LIBRE); if(i>11) {misPuestos[i].setTipo(Puesto.PARTICULAR);} else {misPuestos[i].setTipo(Puesto.MOTO);} } }
El método para buscar un vehículo tiene como parámetro la placa. Se recorre el arreglo y si algún vehículo tiene la misma placa se devuelve true. public boolean buscarVehiculo(String placa) { for(int i=0; i<MAXIMO; i++) { if(misPuestos[i].getContadorReservaciones()>=1&& misPuestos[i].getMisReservaciones()[misPuestos[i].getContadorReservacione s()-1].getMiVehiculo().getPlaca().equals(placa)&& misPuestos[i].getEstado()==Puesto.ESTADO_OCUPADO) { return true;} }//Cierra el for return false; }
El método ubicarVehículo permite asignarle un puesto a un vehículo. Para ello se deben ingresar los datos del vehículo y la fecha y hora de ingreso. Dependiendo el tipo de vehículo se define a partir de donde iniciar a buscar espacios libres. Es de anotar, que los 12 primeros puestos están destinados a motos, es decir, tipo 1 y los restantes a carros. Se retorna el número del puesto donde quedará ubicado el vehículo. Si no se encuentran puestos libres se devuelve -1.
public int ubicarVehiculo(String placa, int modelo, int tipo, int dia, int mes, int anio, int hora, int minuto) 123
{ int inicio=0, finaliza=12; if(buscarVehiculo(placa)==false) { if(tipo==Puesto.PARTICULAR) {inicio=12; finaliza=30;} for(int i=inicio; i< finaliza;i++) { if(misPuestos[i].getEstado()==Puesto.ESTADO_LIBRE) { misPuestos[i].agregarReservacion(placa, modelo, dia, mes, anio, hora, minuto); return i; } } } return -1; }
Para finalizar se requiere de un método para liberar un espacio e indicarle al usuario el valor que debe pagar. Este método recibe la placa del vehículo y la fecha y hora de salida. public ResultadoLiberacion liberarEspacio(String placa, int dia, int mes, int anio, int hora, int minuto) { double valor=0, precio=1200; for(int i=0; i<MAXIMO; i++) { //Se identifica cuál es el puesto donde está ubicado el vehículo if(misPuestos[i].getContadorReservaciones()>=1&&misPuestos[i].getMisReser vaciones()[misPuestos[i].getContadorReservaciones()1].getMiVehiculo().getPlaca().equals(placa)&&misPuestos[i].getEstado()==P uesto.ESTADO_OCUPADO) { //Se fija la fecha de salida misPuestos[i].getMisReservaciones()[misPuestos[i].getContadorReservacione s()-1].setMiFechaSalida(new Fecha(dia, mes, anio, hora, minuto)); //Se libera el puesto misPuestos[i].setEstado(Puesto.ESTADO_LIBRE); //Se determina el valor a cobrar dependiendo del tipo if(misPuestos[i].getTipo()==Puesto.MOTO) { precio=600; } valor= misPuestos[i].getMisReservaciones()[misPuestos[i].getContadorReservacione s()-1].calcularValorAPagar()*precio; return new ResultadoLiberacion(valor, i); } } return null; }
124
3.4. Hoja de trabajo 2 Unidad III: Sala de computadores Se requiere administrar la información de una sala de cómputo. En la sala hay 20 computadores. Cada computador tiene un número asociado (de 1 a 20), un tamaño en disco duro, una cantidad de memoria Ram y un propietario. Un propietario tiene un código y un nombre. La aplicación debe permitir ingresar o en su defecto actualizar la información de cada equipo Adicionalmente debe informar el número del equipo con más disco duro Generar un listado con los números de los equipos a los cuales no se les ha fijado propietario.
3.4.1.
Comprensión del problema
a) Requisitos funcionales NOMBRE RESUMEN ENTRADAS
R1 – Informar el número del equipo con más disco duro
RESULTADOS
125
NOMBRE
R2 – Generar un listado con los números de los equipos a los cuales no se les ha
fijado propietario
RESUMEN ENTRADAS RESULTADOS
NOMBRE
R3 – Actualizar la información de un equipo
RESUMEN ENTRADAS RESULTADOS
b) El modelo del mundo del problema Algunas de las actividades que se deben realizar para construir el modelo del mundo son: Identificar las entidades o clases.
ENTIDAD DEL MUNDO Sala Computador Responsable
DESCRIPCIÓN
Identificar las relaciones entre las clases del mundo
126
En la clase Sala se encuentran los siguientes métodos: - El método constructor permite reservarle memoria al arreglo de computadores y también a cada uno de los computadores. A cada computador se le asigna de una vez el número consecutivo. public Sala() { /*MAXIMO_COMPUTADORES es una constante que indica el número máximo de computadores*/
} El método asignarCaracteristicas permite actualizar los datos de un equipo. Para ello se proporciona el número del equipo, además de la capacidad en ram y disco. public void asignarCaracteristicas( int posicion, int ram, int disco) { misComputadores[posicion].setDisco(disco); 127
misComputadores[posicion].setRam(ram); } El método asignarCaracteristicas permite actualizar la información del propietario de un equipo. public boolean asignarCaracteristicas( int posicion, String codigo, String nombre) { if(contarPropietario(codigo)<3) { misComputadores[posicion].setMiResponsable(codigo, nombre); return true; } else return false; }
El método contarPropietario recibe el código del propietario y recorre el arreglo de computadores para buscar dicho propietario. En caso de que lo encuentre incrementa el contador. public int contarPropietario(String codigo) {int contador=0;
}
El método obtenerComputadorMasDisco()no tiene parámetros. En su interior se declaran dos variables: mayor y posición. La primera de ellas mantiene constantemente actualizada con el valor del computador (capacidad del disco) que tiene más disco duro. La segunda, almacena la posición dentro del arreglo donde está ubicado este mismo computador. public int obtenerComputadorMasDisco() { int mayor=0; int posicion=0;
}
El método listarComputadoresSinPropietario() recorre el arreglo de computadores preguntando, por cada computador, si tiene propietario. public String[] listarComputadoresSinPropietario() 128
{ String arreglo[]=new String[20];
}
129
130
BIBLIOGRAFIA
Arboleda Cobo, Liliana María.Programación en red con java. Cali, Universidad ICESI, 2004
Bishop, Judy. Java Fundamentos de programación. Addison-Wesley. Segunda Edición. Madrid. 1999. ISBN: 84-7829-022-2.
Booch. Object Oriented Analysis & Design With Applications. Prentice Hall, 1998
Booch. UML El Lenguaje Unificado de Modelado. Addison Wesley
Ceballos Sierra, Francisco Javier. Java 2: curso de programación. Alfaomega, 2006. México
Dejalón G. Javier y Rodríguez J. Ignacio, Aitor, Imaz. Aprenda Java como si estuviera en primero. Escuela Superior de Ingenieros Industriales. San Sebastian. Enero 2000.
Deitel, H. Deitel P. Como programar en Java, Prentice Hall. Primera edición. México, 1994 ISBN: 970-17-0044-9.
Eckel, Bruce. Piensa en Java. Prentice-Hall, Pearson Educación. Segunda edicion. Madrid, 2003. ISBN: 84-205-3192-8.
Eriksson, H. UML 2 Toolkit. Indianapolis: Wiley 2004
Goodrich, Michael y Tamassia, Roberto. Estructuras de datos y algoritmos en Java. CECSA. Segunda edición. 2002
Hurtado Gil, Sandra Victoria. Conceptos Avanzados de Programación con JAVA. Universidad ICESI, 2002
Lee, Richard. Practical Object Oriented Development with UML and Java. Prentice-hall, 2002.
Lemay, Laura. Cadenhead Rogers. Aprendiendo java en 21 días. Prentice Hall. ISBN: 970-17-0229-8. Mexico.1999.
Oneil, Joseph. Teach Yourself JAVA. McGraw - Hill. California USA, 1999. ISBN: 0-07882570-9. 131
Richardson. Professional Java JDK 6. Wrox, 2007
Schildt, Herbert. Fundamentos de programación en Java2. Mc Graw-Hill. ISBN: 958-410228-1.
Villalobos, Jorge. Introduccion a las Estructuras de Datos. Prentice Hall, 2008
Villalobos S. Jorge A. Casallas Rubby. Fundamentos de programación - Aprendizaje Activo Basado en casos. Prentice Hall. ISBN: 970-26-0846-5. 2006
Zhang, Computer Graphics Using Java 2d & 3d,-Pearson, Enero de 2007.
132
Introducción a la Programación Orientada a Objetos
|
__label__pos
| 0.819552 |
Autor publikacji
Virtual Patriot - Administrator
CSS3 - Pozycja niestatyczna elementu HTML w kontekście przekształceń w przestrzeni
Data publikacji
Ostatnio edytowano
Zapoznając się z częścią Pozycja statyczna, relatywna, absolutna oraz ustalona dowiedzieliśmy się, że każdy element HTML domyślnie jest wyświetlony w pozycji statycznej, którą określa wartość static właściwości position. Domyślną pozycję statyczną elementu HTML możemy zmienić za pomocą wspomnianej właściwości position oraz wartości relative lub absolute lub fixed. Gdy element HTML nie jest elementem statycznym, czyli gdy została do niego dodana właściwość position:relative; lub position:absolute; lub position:fixed; pozycję niestatycznego elementu HTML możemy kontrolować za pomocą właściwości top, right, bottom, left, których wartości będą liczone względem krawędzi pozycji początkowej danego elementu HTML (gdy jest on wyświetlony w pozycji position:relative;), lub których wartości będą liczone względem krawędzi okna przeglądarki internetowej (gdy jest on wyświetlony w pozycji position:fixed;), lub których wartości będą liczone względem krawędzi pierwszego niestatycznego elementu przodka interesującego nas elementu HTML (gdy dany interesujący nas element potomek jest wyświetlony w pozycji position:absolute;), ponadto gdy dany interesujący nas element potomek nie posiada niestatycznego przodka (czyli elementu HTML, do którego została dodana właściwość position wraz z wartością relative lub absolute lub fixed) wspomniane wartości właściwości top, right, bottom, left są liczone względem krawędzi okna przeglądarki internetowej.
Do tych wszystkich wcześniej poznanych oraz wyżej wymienionych zasad dochodzi jeszcze jedna reguła, którą poznamy w tej części kursu CSS.
Na początek utworzymy przykładowy układ elementów HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Darmowy Kurs CSS</title>
<style>
#div1 {
width:100%;
height:400px;
background-color:red;
}
#div2 {
width:80%;
height:300px;
background-color:green;
}
#div3 {
width:60%;
height:200px;
background-color:black;
}
</style>
</head>
<body>
<div id="div1">
<div id="div2">
<div id="div3"></div>
</div>
</div>
</body>
</html>
Rezultat:
Nasz przykładowy układ elementów HTML przedstawia trzy elementy div czyli kolejno elementy #div1, #div2, #div3, które zostały umieszczone jeden w drugim. Dla wspomnianych elementów HTML została określona różna szerokość, różna wysokość oraz różny kolor tła. Spróbujmy sprawić, aby element #div3 (element z czarnym kolorem tła) został przesunięty do prawej oraz dolnej krawędzi elementu #div1 (element z czerwonym kolorem tła). Inaczej mówiąc sprawmy, aby element #div3 był pozycjonowany względem elementu #div1.
Wspomnianą zależność możemy osiągnąć za pomocą wartości właściwości position oraz dodatkowo za pomocą właściwości right oraz bottom.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Darmowy Kurs CSS</title>
<style>
#div1 {
position:relative;
width:100%;
height:400px;
background-color:red;
}
#div2 {
width:80%;
height:300px;
background-color:green;
}
#div3 {
position:absolute;
right:0;
bottom:0;
width:60%;
height:200px;
background-color:black;
}
</style>
</head>
<body>
<div id="div1">
<div id="div2">
<div id="div3"></div>
</div>
</div>
</body>
</html>
Rezultat:
Element #div3, który od tej pory jest elementem HTML wyświetlonym w pozycji absolutnej, dzięki temu iż dodaliśmy do niego właściwość position:absolute; został przesunięty do prawej oraz dolnej krawędzi elementu #div1, który od tej pory jest elementem HTML wyświetlonym w pozycji relatywnej, ponieważ posiada on w sobie właściwość position:relative;. Wspomniane przesunięcie do prawej oraz dolnej krawędzi elementu #div1 jest możliwe, dzięki temu że do elementu #div3 została dodana właściwość right:0; oraz właściwość bottom:0;, które mówią przeglądarce internetowej, między innymi że jeżeli dany element HTML jest wyświetlony w pozycji absolutnej to ma zostać on odsunięty o wartość 0 od prawej krawędzi swojego pierwszego napotkanego elementu przodka pozycjonowanego relatywnie oraz ma zostać on odsunięty o wartość 0 od dolnej krawędzi swojego pierwszego napotkanego elementu przodka pozycjonowanego relatywnie.
Pierwszym napotkanym pozycjonowanym relatywnie przodkiem względem pozycjonowanego absolutnie elementu #div3 jest element #div1, dzięki czemu element #div3 został odsunięty o wartość 0 od prawej oraz dolnej krawędzi wspomnianego elementu #div1 za co odpowiada właściwość right:0; oraz właściwość bottom:0;.
Zobaczmy co się stanie z naszym przykładowym układem elementów HTML, gdy do elementu #div2 dodamy właściwość perspective wraz z jakąś przykładową wartością.
#div2 {
perspective:500px;
width:80%;
height:300px;
background-color:green;
}
Rezultat:
Od tej pory nasz przykładowy element #div3 wyświetlony w pozycji absolutnej jest pozycjonowany względem elementu #div2, a nie względem elementu #div1. Dzieje się tak, ponieważ do zasad, jakie rządzą elementami HTML wyświetlonymi w pozycji absolutnej (absolute) lub w pozycji ustalonej (fixed) została dopisana nowa zasada, która mówi że jeżeli dany element HTML jest wyświetlony w pozycji absolutnej lub w pozycji ustalonej to pozycja takiego elementu HTML w pierwszej kolejności jest liczona względem pierwszego napotkanego elementu przodka, który sprawia że interesujący nas element HTML wyświetlony w pozycji absolutnej lub w pozycji ustalonej znajduje się w zasięgu tej samej perspektywy, w której znalazł się lub którą tworzy dany element przodek.
W naszym przykładzie elementem HTML, który tworzy perspektywę dla pozycjonowanego absolutnie elementu #div3 jest element #div2, ponieważ do wspomnianego elementu #div2 została dodana właściwość perspective wraz z wartością 500px, dlatego wyświetlony w pozycji absolutnej element #div3 jest pozycjonowany względem krawędzi elementu #div2, a nie elementu #div1.
Zobaczmy co się stanie tym razem z naszym przykładowym układem elementów HTML, gdy z elementu #div1 usuniemy właściwość position:relative;, następnie dodamy właściwość transform:perspective(500px); oraz właściwość transform-style:preserve-3d;, a do elementu #div2 dodamy również właściwość transform-style:preserve-3d;.
#div1 {
transform:perspective(500px);
transform-style:preserve-3d;
width:100%;
height:400px;
background-color:red;
}
#div2 {
transform-style:preserve-3d;
width:80%;
height:300px;
background-color:green;
}
Rezultat:
Tym razem w naszym przykładzie elementem HTML, który tworzy perspektywę jest element #div1, jednak wyświetlony w pozycji absolutnej element #div3 jest pozycjonowany względem elementu #div2, a nie względem elementu #div1, ponieważ to element #div2 (dzięki właściwości transform-style:preserve-3d;), sprawia że element #div3 znajduje się w zasięgu tej samej perspektywy, w której znalazł się wspomniany element #div2 (który znalazł się w zasięgu perspektywy tworzonej przez element #div1, dzięki temu że do elementu #div1 została dodana właściwość transform:perspective(500px); oraz właściwość transform-style:preserve-3d;).
W następnej części kursu CSS dowiemy się dlaczego miejsce pozycji początkowej elementu HTML jest ważne w kontekście przekształceń w przestrzeni.
|
__label__pos
| 0.518535 |
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up
Join the Stack Overflow community to:
1. Ask programming questions
2. Answer and help your peers
3. Get recognized for your expertise
This question already has an answer here:
I have a vector<data> info where data is defined as:
struct data{
string word;
int number;
};
I need to sort info by the length of the word strings. Is there a quick and simple way to do it?
share|improve this question
marked as duplicate by Walter, Sebastian, Kon, SingerOfTheFall, Eric Brown Sep 13 '13 at 6:00
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
1
If you think your question was solved, mark one solution as accepted. – Murilo Vasconcelos Feb 4 '11 at 1:40
sorry. i didnt have time to check for the past few hours – calccrypto Feb 4 '11 at 3:18
up vote 33 down vote accepted
Use a comparison function:
bool compareByLength(const data &a, const data &b)
{
return a.word.size() < b.word.size();
}
and then use std::sort in the header #include <algorithm>:
std::sort(info.begin(), info.end(), compareByLength);
share|improve this answer
Just make a comparison function/functor:
bool my_cmp(const data& a, const data& b)
{
// smallest comes first
return a.word.size() < b.word.size();
}
std::sort(info.begin(), info.end(), my_cmp);
Or provide an bool operator<(const data& a) const in your data class:
struct data {
string word;
int number;
bool operator<(const data& a) const
{
return word.size() < a.word.size();
}
};
or non-member as Fred said:
struct data {
string word;
int number;
};
bool operator<(const data& a, const data& b)
{
return a.word.size() < b.word.size();
}
and just call std::sort():
std::sort(info.begin(), info.end());
share|improve this answer
Op< should be a non-member and number should probably be considered in op< so other algorithms, such as std::unique, behave as expected when used with the default std::less; otherwise spot on. – Fred Nurk Feb 3 '11 at 23:06
Why operator<() should be non-member? – Murilo Vasconcelos Feb 3 '11 at 23:09
@MuriloVasconcelos: So implicit conversions apply to the left-hand side. – Fred Nurk Feb 3 '11 at 23:16
1
IMHO, you shouldn't use operator overloading to wrap behaviour that isn't immediately intuitive. In this situation, it doesn't really make any sense to say that data a is "less than" data b if its string member is shorter, so I wouldn't use operator< to express that idea. – Oliver Charlesworth Feb 3 '11 at 23:26
2
In this case I agree with you and is why I write about the "function-way" first and then I explained the other ways for learning purposes. – Murilo Vasconcelos Feb 3 '11 at 23:31
Yes: you can sort using a custom comparison function:
std::sort(info.begin(), info.end(), my_custom_comparison);
my_custom_comparison needs to be a function or a class with an operator() overload (a functor) that takes two data objects and returns a bool indicating whether the first is ordered prior to the second (i.e., first < second). Alternatively, you can overload operator< for your class type data; operator< is the default ordering used by std::sort.
Either way, the comparison function must yield a strict weak ordering of the elements.
share|improve this answer
As others have mentioned, you could use a comparison function, but you can also overload the < operator and the default less<T> functor will work as well:
struct data {
string word;
int number;
bool operator < (const data& rhs) const {
return word.size() < rhs.word.size();
}
};
Then it's just:
std::sort(info.begin(), info.end());
Edit
As James McNellis pointed out, sort does not actually use the less<T> functor by default. However, the rest of the statement that the less<T> functor will work as well is still correct, which means that if you wanted to put struct datas into a std::map or std::set this would still work, but the other answers which provide a comparison function would need additional code to work with either.
share|improve this answer
Interestingly, while std::map and std::set default to using std::less<T>, std::sort and the rest of the sorting functions default to using operator<. You'll only notice a difference if you specialize std::less to do something other than what operator< does. – James McNellis Feb 3 '11 at 23:00
When I said "you'll only notice a difference if...," I was wrong. You'll also notice a difference if you have a container of pointers, e.g. std::vector<int*> v; v.insert(new int); v.insert(new int); std::sort(v.begin(), v.end());, since the behavior is undefined if you compare unrelated pointers using <. That said, why you'd want to sort a container of pointers by the pointer value and not the value of the pointed-to object, I don't know. – James McNellis Feb 3 '11 at 23:57
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.675876 |
jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes write a java program to determine the smallest and largest of two numbers Big Moose Saloon
Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "write a java program to determine the smallest and largest of two numbers" Watch "write a java program to determine the smallest and largest of two numbers" New topic
Author
write a java program to determine the smallest and largest of two numbers
Bill Zelan
Ranch Hand
Joined: Jan 09, 2009
Posts: 46
can someone help me to code this :
thanks
Using the "input stream reader" functions, write a java program to determine the smallest and largest of two numbers.
1. create some variables named number1, number2, smallest, and biggest (all numbers should be integers).
input the values of the variables number1 or number2 from the keyboard (using input stream reader).
2. print out the sentence "The larger number is " followed by the value that is larger (either the value of number1 or number2) - use the if statement to find out which variable holds the larger value.
3. print out the sentence "The smaller number is " followed by the value that is smaller (either the value of number1 or number2) - use the if statement to find out which variable holds the smaller value.
4. test your program by inputting different values for the variables number1 and number2.
Hunter McMillen
Ranch Hand
Joined: Mar 13, 2009
Posts: 492
Give a shot yourself first, then if you get stuck with coding post what you have so far.
Hunter.
"If the facts don't fit the theory, get new facts" --Albert Einstein
subject: write a java program to determine the smallest and largest of two numbers
|
__label__pos
| 0.976161 |
How to Create a Pagination in Mongoose?
How to Create a Pagination in Mongoose
As the amount of data in a MongoDB database grows, it becomes essential to organize it efficiently. One way of doing this is by using pagination, which is the process of breaking down large sets of data into smaller, more manageable chunks.
What is Pagination?
Pagination is the practice of dividing large sets of data into smaller, more manageable chunks or pages. This technique is commonly used to improve the user experience and reduce the load time of web pages that contain large amounts of data. Pagination is especially useful for data that needs to be displayed in a tabular format, such as search results, user profiles, or product listings.
Why Use Pagination in Mongoose?
Mongoose is a powerful ORM for MongoDB, but it can be slow when querying large amounts of data. Pagination can improve the performance of your application by reducing the amount of data that needs to be retrieved from the database. Additionally, pagination can make your application more user-friendly by allowing users to navigate through large datasets in a more organized manner.
How to Implement Pagination in Mongoose
Install Mongoose
Before we can begin implementing pagination, we need to install Mongoose. You can install Mongoose using NPM by running the following command:
npm install mongoose
Set up Your Mongoose Schema
In order to use Mongoose, you need to define a schema for your data. A schema is a blueprint that defines the structure of the documents in your collection. Here’s an example of how to define a schema for a simple blog post:
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: String,
body: String,
author: String,
date: {
type: Date,
default: Date.now
}
});
const Post = mongoose.model('Post', postSchema);
Retrieve Data from the Database
To retrieve data from the database using Mongoose, we can use the find() method. Here’s an example of how to retrieve all blog posts:
Post.find({}, (err, posts) => {
if (err) throw err;
console.log(posts);
});
Implement Pagination
Now that we know how to retrieve data from the database, we can implement pagination. The skip() and limit() methods can be used to achieve this. The skip() method is used to skip a certain number of documents, while the limit() method is used to limit the number of documents returned. Here’s an example of how to implement pagination in Mongoose:
const page = req.query.page || 1;
const perPage = 10;
Post.find({})
.skip((perPage * page) - perPage)
.limit(perPage)
.exec((err, posts) => {
Post.countDocuments((err, count) => {
if (err) throw err;
res.render('posts', {
posts,
current: page,
pages: Math.ceil(count / perPage)
});
});
});
In this example, we’re using the skip() method to skip a certain number of posts based on the current page and the limit() method to limit the number of posts displayed per page. We’re also using the countDocuments() method to count the total number of posts in the database and calculate the number of pages required for pagination.
Display Pagination Links
Once we have implemented pagination in Mongoose, we need to display pagination links to allow users to navigate through the pages. Here’s an example of how to display pagination links in a Node.js application using the EJS templating engine:
<div class="pagination">
<% if (pages > 1) { %>
<ul>
<% if (current > 1) { %>
<li><a href="?page=<%= current - 1 %>">«</a></li>
<% } %>
<% for (let i = 1; i <= pages; i++) { %>
<% if (i == current) { %>
<li class="active"><a href="?page=<%= i %>"><%= i %></a></li>
<% } else { %>
<li><a href="?page=<%= i %>"><%= i %></a></li>
<% } %>
<% } %>
<% if (current < pages) { %>
<li><a href="?page=<%= current + 1 %>">»</a></li>
<% } %>
</ul>
<% } %>
</div>
In this example, we’re using EJS templating to dynamically generate pagination links based on the current page and the total number of pages. We’re also using a conditional statement to only display the pagination links if there is more than one page of data to display.
Best Practices for Pagination in Mongoose
Here are some best practices to follow when implementing pagination in Mongoose:
Use a sensible page size
It’s important to choose a page size that is appropriate for your application. A page size that is too large can result in slow load times and poor performance, while a page size that is too small can result in a poor user experience. A page size of 10-20 items per page is generally considered a good starting point.
Use an efficient database query
When implementing pagination, it’s important to use an efficient database query that only retrieves the data that is needed for the current page. In Mongoose, you can achieve this using the skip() and limit() methods.
Provide clear navigation
Make sure to provide clear navigation links to allow users to move between pages. This can be achieved using pagination links, as shown in the example above.
Consider performance optimization
When implementing pagination in Mongoose, consider performance optimization techniques such as caching, indexing, and using lean queries to reduce the amount of data retrieved from the database.
Conclusion
We’ve discussed the benefits of pagination, how to implement pagination in Mongoose, and best practices to follow when using pagination in your application. By following these best practices, you can improve the performance and user experience of your application when working with large datasets.
Follow Us on
https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs
Read More
https://scribblersden.com/what-is-the-cucumber-framework/
Thank You
Related Post
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.994283 |
Hacker News new | comments | show | ask | jobs | submit | ionforce's comments login
My unscientific take on this is it's about micro adjustments and just in time feedback. By focusing on where you ARE going, you will make that happen subconsciously through your motor skills. If you are going the wrong way (in micro amounts), you will self-correct.
Do you have more information about this approach? I've never heard about it until now.
I tried to dig out the references from my mess of bibliography (I worked on this topic long before Mendeley and alike appeared), unsuccessfully.
I remember that I ran into this technique independently first (in a context of encoding expression trees) and then found a number of other examples in the literature (e.g., encoding the neural network topology, etc.).
This story is like the poster child of success with genetic algorithms.
Chances are the CEO doesn't know about such a group.
To play devil's advocate, there's certainly a limit to computer-based searches. If the computer's model (which was made by a person or persons) is under-specified, then it will produce suboptimal results. At least with a person, there is always the possibility of integrating new facts on the fly.
This would eventually backfire if ad networks look for click fraud.
It's like a security mechanism for spicy material. What stays in Vegas (defined as a group of individuals) does a better job of staying in Vegas if collocation is a requirement.
-----
Another angle is a groupon type service. Do something fun together, get a coupon for food/drink/another fun activity that unlocks when all members on the group reunite in a month. Create mechanism for 'chaining' to encourage stickiness. People get slight push to maintain friendships they might let otherwise let slip away.
-----
Sure, I see what you're saying ionforce, and thanks for the clarification.
I still don't see the point...Hangover only works when you 1. go to the same place with 2. the same people, and 3.you want to lock content with those people
I ask how often does this use case occur?
What do you think ionforce?
-----
Man, using Perl professionally (as have I). What kind of job was it?
Scala (my current language), world's apart! I was truly blind to a much higher, cleaner level of thinking/programming until I learned Scala.
-----
Haha, testing automation framework. Test engineers took our framework and wrote tests with it. Yes Perl professionally is not much fun but I fell in love with Larry Wall after reading the Perl book. Though Perl isn't the best language, a lot of his philosophy shines through and makes it much more than just another programming language.
-----
> Man, using Perl professionally (as have I). What kind of job was it?
Ten years ago I was using Perl to write web applications with HTML::Mason, in a consulting firm. I can't say I miss that :-).
-----
Does anyone know how it works? Like does it make requests to a service or is it running in the browser, JS style?
-----
There's a section called A Tour of Go [0] which has a series of code samples with explanations. The last part of the introduction to the tour says a little about what they call the Go playground [1]:
"This tour is built atop the Go Playground, a web service that runs on golang.org's servers.
The service receives a Go program, compiles, links, and runs the program inside a sandbox, then returns the output."
[0] - https://tour.golang.org/welcome/1 [1] - https://tour.golang.org/welcome/4
-----
It's the same stuff that powers the playground: http://play.golang.org/
More info here: http://blog.golang.org/playground
-----
It makes requests to a backend service. You can read more about the implementation of the Go Playground on the blog[0].
[0]: https://blog.golang.org/playground
-----
> It is an unbelievably stressful game
This is why I don't play. So much stress.
-----
More
Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact
Search:
|
__label__pos
| 0.714204 |
Title:
METHOD OF DISTRIBUTING DATA PACKETS OF SYSTEM SOFTWARE
Kind Code:
A1
Abstract:
In a point-to-multipoint system (SYS), particularly a video-on-demand system, comprising a send unit (SERVER) in the form of a server and a plurality of receive units (DEC) in the form of decoders, a new version of the system software for the decoders is to be transferred to the latter. This is done by taking the following steps:
1. An announce signal containing the information that the new system software or part thereof will subsequently be transferred is transmitted from the server to all decoders simultaneously.
2. The system software or part thereof is transferred in the form of data packets from the server to all decoders simultaneously.
By the advance information in the form of an announce signal which is transmitted to all decoders by the broadcast method, the decoders are notified of the forthcoming transmission of the current version of the system software, whereupon they can prepare for the reception of the new version. The new version is also transmitted by the broadcast method, and ideally only once.
Inventors:
Cesar, Bozo (KORNWESTHEIM, DE)
Keil, Klaus (ESSLINGEN, DE)
Riemer, Joachim (KORNTAL, DE)
Application Number:
09/159155
Publication Date:
11/15/2001
Filing Date:
09/23/1998
Assignee:
CESAR BOZO
KEIL KLAUS
RIEMER JOACHIM
Primary Class:
Other Classes:
712/15, 713/100
International Classes:
G06F13/00; G06F8/65; G06F9/445; (IPC1-7): G06F15/177; G06F1/24; G06F9/00; G06F15/00; G06F15/76
View Patent Images:
Primary Examiner:
PRIETO, BEATRIZ
Attorney, Agent or Firm:
WARE, FRESSOLA, MAGUIRE & BARBER LLP (BRADFORD GREEN, BUILDING 5 755 MAIN STREET, MONROE, CT, 06468, US)
Claims:
1. A method of distributing data packets of system software in a point-to-multipoint system (SYS) from a send unit (SERVER) to a plurality of receive units (DEC), characterized in that the following steps are taken one after the other: 1. An announce signal containing the information that the system software or part thereof will subsequently be transmitted is transmitted from the send unit (SERVER) to all receive units (DEC) simultaneously. 2. The system software or part thereof is transmitted in the form of data packets from the send unit (SERVER) to all receive units (DEC) simultaneously.
2. A method as claimed in claim 1, characterized in that the announce signal contains information as to which version of the system software will be transmitted.
3. A method as claimed in claim 2, characterized in that between steps 1 and 2, the receive units (DEC) buffer the version of the system software identified in the announce signal, compare said version with the version available in the respective receive unit (DEC), and, if the two versions are identical, inhibit the reception of the data packets transmitted in step 2.
4. A method as claimed in any one of the preceding claims, characterized in that the receive units (DEC) acknowledge only the receipt of the last data packet transmitted by the send unit (SERVER) and belonging to the system software or part thereof.
5. A method as claimed in claim 4, characterized in that the acknowledge signals from the receive units (DEC) contain information identifying the receive units (DEC), and that the send unit (SERVER) stores in a list information identifying those receive units (DEC) which have acknowledged the receipt of the data packets, in order to record which receive unit (DEC) has received the transmitted data packets and which has not.
6. A method as claimed in any one of the preceding claims, characterized in that the point-to-multipoint system is a service-on-demand system comprising a server as the send unit (SERVER) and decoders as the receive unit (DEC).
7. A method as claimed in claim 6, characterized in that the decoders are designed as set-top boxes, and that the transmitted data packets serve to update the system software of the set-top boxes.
Description:
[0001] This invention relates to a method of distributing data packets of system software as set forth in the preamble of claim 1.
[0002] In a point-to-multipoint system, particularly a service-on-demand system, a server is provided as a send unit, and the receive units are decoders. The decoders are designed as set-top boxes. The system software of the set-top boxes needs to be updated when a new version of the system software is available.
[0003] From an article by Carl W. Symborski, “Updating Software And Configuration Data In A Distributed Communications Network”, Proceedings of the Computer Networking Symposium, IEEE Comput. Soc. Press, 1988, pages 331-338, a procedure for distributing data packets of system software in a point-to-multipoint system is known. The procedure is executed in a receive unit and consists of the following steps:
[0004] 1. Wait until a predetermined period of time has expired or a notice has been received that a new version of the system software may be available.
[0005] 2. Request information from the server as to whether a new version is available.
[0006] 3. Compare the version communicated by the server with the version available in the receive unit.
[0007] 4. If no change is detected, return to step 1.
[0008] 5. If a change is detected, request the new version from the server.
[0009] 6. Replace the old version with the new one.
[0010] 7. Store the new version.
[0011] 8. Return to step 1.
[0012] Thus, to obtain the new version of the system software, this procedure always requires an action by the receive unit together with a request to the server. If a plurality of receive units are present, each receive unit must request the new version by itself. Because of the structure of the distribution system, the new version, which is generally identical for all receive units, is transmitted from the send unit to the receive units separately. If there are 500 receive units, the send unit must transmit the new version 500 times, once to each receive unit. This takes a certain time. Thus, the transmission of further information is unnecessarily blocked, at least in a predetermined frequency range, for a certain period of time.
[0013] From an article by K. Rath and J. W. Wendorf, “Set-Top Box Control Software: a Key Component in Digital Video”, Philips Journal of Research (1996), Vol. 50, No. 1/2, pages 185-199, a method of distributing data packets of system software in a point-to-multipoint system is known in which a receive unit designed as a set-top box obtains a new version of the system software telemetrically via a network. The set-top box sends a request to the server or obtains the new version from the server automatically on a periodic basis. The former corresponds essentially to the procedure described above. The latter involves the establishment of a connection between the server and an individual set-top box, which eliminates the need for the set-top box to actively request a new version but does not prevent the multiple transmission of the same information.
[0014] It is therefore an object of the invention to provide a method whereby the system software can be updated in a simple manner.
[0015] According to the invention, this object is attained by a method as set forth in claim 1. The method is characterized in that by advance information in the form of an announce signal which is transmitted to all receive units by the broadcast method, the receive units are notified of the forthcoming transmission of the current version of the system software, whereupon they can prepare for the reception of the new version. The new version is also transmitted by the broadcast method, and ideally only once. If individual receive units should not have received the advance information, the method may, for example, be automatically repeated at a later time or the remaining receive units may request the new version from the server separately. Thus, compared with the prior art, the transmission time is ideally shortened by a factor corresponding to the number of receive units present, i.e., by a factor 500 if there are 500 receive units. If, for example, 10% of the receive units should not have received the advance information, the transmission time is still shortened by a factor of 250 (in case of automatic repetition) or approximately 100 (if separate requests are made).
[0016] Further advantageous features of the invention are defined in the dependent claims.
[0017] The invention will become more apparent from the following description of an embodiment when taken in conjunction with the accompanying drawing. The single figure of the drawing is a schematic representation of a point-to-multipoint system according to the invention for carrying out the method according to the invention.
[0018] The point-to-multipoint SYS comprises a send unit SERVER, a network NET, and a plurality of receive units DEC.
[0019] The point-to-multipoint system SYS is designed, for example, as a service-on-demand system. The send unit SERVER contains a server which is connected via the network NET to the receive units DEC, which are designed as decoders. The point-to-multipoint system SYS makes available a downstream channel and an upstream channel. Via the upstream channel, e.g., a narrow-band channel, customers can transmit information from their decoders through the network NET to the server. The information consists, for example, of request signals by means of which a video film, for example, is requested, which is then broadcast over the downstream channel, e.g., a broadband channel, to all decoders or to a group of decoders in a subarea dependent on the topology of the network. A logon authorization, granted, for example, by issuing a key for each transmission, ensures that only the decoder from which the video film was requested has the right and capability to receive the transmitted video film.
[0020] The decoders are designed, for example, as set-top boxes. Each set-top box has system software, i.e., programs that make up the operating system. The system software serves, for example, to receive and process the menu broadcast by the server for the selection of video films and the like. From time to time, the system software is upgraded and updated, or modified to eliminate systematic errors. Each set-top box then needs an update of its system software. A new version of the system software needs to be transferred to the set-top box. This is done by downloading the new version from the server to the set-top boxes. The new version or, if possible, only the changes in the new version from the old one are transmitted in the form of data packets from the server to the set-top boxes through the network NET. As a rule, the system software is the same for all set-top boxes, so that ideally, one download will suffice to transmit the necessary data packets of the new version to all set-top boxes.
[0021] The method of distributing the data packets of the system software is carried out in the following steps, which are taken one after the other:
[0022] 1. From the send unit SERVER, which contains the server, an announce signal containing the information that the system software of the set-top boxes or part of this software will subsequently be transmitted is sent to all receive units DEC, which contain the set-top boxes, simultaneously.
[0023] 2. From the send unit SERVER, the system software or part thereof is sent in the form of data packets to all receive units DEC simultaneously.
[0024] Thus, by the first step, all set-top boxes connected to the network NET are informed that the new version or the changes from the old version will be transmitted by the server shortly. Each set-top box thus has sufficient time to prepare for the reception of the new software. For example, the set-top box may go through a initialization phase in which various checks are made and a buffer storage area is enabled to buffer and subsequently load the system software. The announce signal is received by all set-top boxes, since instead of an address in the header of a data packet, which serves to select a given set-top box, a so-called default address, e.g., XXXXXXXX, is used, which can be received by all set-top boxes.
[0025] In the second step, the data packets of the new system software are transmitted from the server to all set-top boxes by the broadcast method. This is also done using the default address. All set-top boxes can receive the transmitted data packets. A single transmission of the data packets thus suffices to transfer the new version of the system software to all set-top boxes prepared by the announce signal. Thus, in ideal circumstances, the system software of all set-top boxes is updated by a single transfer of the new system software.
[0026] The announce signal may contain information as to which version of the system software will be transmitted and how much storage capacity is needed. This enables the set-top boxes to determine in advance whether the data packets shortly to be transmitted are to be received or not. If, for example, a set-top box has already received the new version of the system software, e.g., in response to a previous request, via a PCMCIA card, or otherwise, the reception of the new version and the preparation therefor would be unnecessary. The information on the storage capacity required enables the set-top box to check whether sufficient storage space is available for receiving the latest version and, if so, to reserve a corresponding area of the new version.
[0027] Between steps 1 and 2 of the method for distributing the data packets of the new system software, the receive units DEC, i.e., the set-top boxes, can buffer the version of this system software, compare it with the version available in the respective set-top box, and, if the two versions are identical, prevent the reception of the data packets transmitted in step 2.
[0028] The receive units DEC, i.e., the set-top boxes, then acknowledge the receipt of the last data packet transmitted by the send unit SERVER and belonging to the system software. This has the advantage that the transmission of the data packets is not interfered with by the acknowledgements from the set-top boxes. A repetition of the transmission of individual data packets for individual set-top boxes is not provided for, since this would introduce delays. If a set-top box does not receive individual data packets for some reason or other, it must wait for another transfer of a complete version if this is provided for, or request the new version from the server, which will then send a complete version to the respective set-top box separately.
[0029] The acknowledge signals from the set-top boxes contain information for identifying the set-top boxes, e.g., the address of the respective set-top box. The server can thus determine which of the set-top boxes have received the transmitted data packets and which have not. To this end, the server stores in a list, for example, the addresses of those set-top boxes which have acknowledged receipt of the data packets. This may be accomplished, for example, by storing the addresses directly in a separate memory area or by providing the respective addresses of the set-top boxes with an identifier if all of them have already been stored in a list. By comparing the received acknowledgements with the number of set-top boxes available, the server can determine to how many set-top boxes the new version has been successfully transmitted. From this, a success ratio can be determined, e.g., 80%. Based on this ratio, the server can decide whether or not to repeat the transmission with the preceding announce signal at a later time. Furthermore, the address information can be used to determine whether transmission errors are present in locally limited areas, e.g., if no acknowledgement is received from those set-top boxes which are connected to a subarea dependent on the topology of the network.
|
__label__pos
| 0.521427 |
1
This question is really two questions.
First question: Does vimscript support having interpolated strings as values in a dictionary?
Second question: Is it possible to remap keys from within a loop? While items is an obvious choice (to me) for creating the loop, I'm open to other loops if they allow this.
" attempted code:
let path_dict = {
\'o.': './',
\'o/': "$p_root",
\'oc': "$p_css",
\'oh': "$p_html",
\'oj': "$p_js",
\'ol': "$p_learn",
\}
for [keybinding, filepath] in items(path_dict)
nnoremap <Leader>keybinding :call Notrw(filepath)<CR>
endfor
" desired result:
" nnoremap <Leader>o/ :call Notrw($p_root)<CR>
" nnoremap <Leader>oh :call Notrw($p_html)<CR>
" nnoremap <Leader>oc :call Notrw($p_css)<CR>
" nnoremap <Leader>oj :call Notrw($p_js)<CR>
" nnoremap <Leader>ol :call Notrw($p_learn)<CR>
" nnoremap <Leader>o. :call Notrw('./')<CR>
• 1
The question was a joke but this answer by Carpetsmoker shows a way to create mappings in a loop. The trick is to use execute. (We may have another question with mappings in a loops but I can't find it right now) – statox Jan 9 '18 at 13:48
• for interpolating variables into commands use the :exe command and you can of course create mappings in a loop. – Christian Brabandt Jan 9 '18 at 13:53
3
Does vimscript support having interpolated strings as values in a dictionary?
No, but you can have (nearly) arbitrary expressions within dictionary values:
let a = {
\ 'goodbye': variable,
\ 'world': $ENVVAR,
\ 'hello': printf('%d', 10),
\}
Is it possible to remap keys from within a loop? While items is an obvious choice (to me) for creating the loop, I'm open to other loops if they allow this.
Using execute it is possible to do anything in a loop. Any command sequence which can be uttered in a script can be wrapped in a string and executed (possibly up to minor syntax changes). For instance,
for [keybinding, filepath] in items(path_dict)
execute 'nnoremap <Leader>'.keybinding ':call Notrw('.filepath.')'
endfor
Note that execute inserts spaces between successive arguments (such as between keybinding and ':call). To suppress this you must concatenate the strings using .. An alternative to concatenation is to use printf. Note that since execute is effectively what is called eval in other languages, standard string validation security warnings apply.
There are two cases where vim allows true "interpolation."
1) In unix/linux (at least), and only in filename arguments, you may use backticks to supply filename(s) as a result of an external command
:next `find . -name ver\\*.c -print`
Escaping can be difficult.
2) In variable names only, you can use another variable (see :h curly-braces-names) interpolated into the name. For example,
my_{adjective}_variable
echo my_{&background}_message
refer to the interpolated variable as you'd expect, e.g., my_blue_variable, or my_dark_message.
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.97339 |
运维开发网
广告位招商联系QQ:123077622
广告位招商联系QQ:123077622
浅谈IOS如何对app进行安全加固
运维开发网 https://www.qedev.com 2021-06-08 08:26 出处:网络 作者: 为童沉沦
防止 tweak 依附 通常来说,我们要分析一个 app,最开始一般是砸壳, $ DYLD_INSERT_LIBRARIES=dumpdecrypted.dylib /path/to/XXX.app/XXX
防止 tweak 依附
通常来说,我们要分析一个 app,最开始一般是砸壳,
$ DYLD_INSERT_LIBRARIES=dumpdecrypted.dylib /path/to/XXX.app/XXX
然后将解密之后的二进制文件扔给类似 hopper 这样的反编译器处理。直接将没有砸壳的二进制文件扔个 hopper 反编译出来的内容是无法阅读的(被苹果加密了)。所以说砸壳是破解分析 app 的第一步。对于这一步的防范,有两种方式。
1.限制二进制文件头内的段
通过在 Xcode 里面工程配置 build setting 选项中将
-Wl,-sectcreate,__RESTRICT,__restrict,/dev/null
添加到 "Other Linker Flags"(注意这里我在项目中碰到了一个 问题,在 iPod touch iOS 9.3 的设备上,使用了 swift 的项目会导致莫名奇妙的 swift 标准库无法找到,而在 iOS 10 的设备上没有这个问题。之前并没有以为是因为添加了这个的原因,直到网上搜了所有解决方案,比如这个 SO Post 都没有效果的时候,我才发现是这个设置的原因)
2.setuid 和 setgid
Apple 不接受调用这两个函数的 app,因为它可以通过查看符号表来判断您的二进制运行文件是否包含这两个函数
检测越狱设备上是否有针对性 tweak
一般来说在越狱手机上,我们会使用 TheOS 创建 tweak 类型的工程。然后针对我们要分析的类,使用提供的 logify.pl 命令生成的 mk 文件来打印该类所有方法的入参和出参。这对分析 app 的运行方式有很大的帮助。当然,我们也可以自己创建某个类的 mk,来 hook 某个函数,让它以我们想要的方式运行,比如说对于一些做了证书绑定的 app,如果它用的框架是 A编程客栈FNetWorking 的话,那么我们可以创建一个 mk 文件,hook AFSecurityPolicy 类的下列方法:
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain
让这个方法永远返回 YES,那么大多数的应用所做的证书绑定也就失效了。用过 TheOS 的 tweak 模版的话,你会发现这种方式相当简单快速。
对于这一步的防范,可以在工程的 main 函数里面加入一层判断,首先读取 /Library/MobileSubstrate/DynamicLibraries 下所有的 plist 文件的内容,查看是否某个 plist 含有你的 app 的 bundle id,是的话,可以判定有人想利用 tweak 攻击你的 app,这时候你可以采取比如说将 app 给 crash 掉,或者限制某些功能等方式来应对。
具体原理可以查看参考资料4,简单来说,就是 MobileSubstrate 在 app 加载到内存的时候会先去检查 /Library/MobileSubstrate/DynamicLibraries 下面是否有需要加载的 tweak,有的话就加载,怎么判断有没有?就是根据 plist 里面的 bundle ID 判断的。
代码参考如下
static __inline__ __attribute__((always_inline)) int anti_tweak()
{
uint8_t lmb[] = {'S', 'u', 'b', 's', 't', 'r', 'a', 't', 'e', '/', 'D', 'y', 'n', 'a', 'm', 'i', 'c', 0, };
NSString *dir = [NSString stringWithFormat:@"/%@/%@%s%@", @"Library", @"Mobile", lmb, @"Libraries"];
NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:nil];
NSArray *plistFiles = [dirFiles filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:
[NSString stringWithFormat:@"%@ %@%@ '.%@%@'",@"self", @"EN", @"DSWITH", @"pli", @"st"]]];
int cnt = 0;
for (NSString *file in plis编程客栈tFiles) {
NSString *filePath = [dir stringByAppendingPathComponent:file];
NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if (fileContent && [fileContent rangeOfString:[[NSBundle mainBundle] bundleIdentifier]].location != NSNotFound) {
cnt ++;
}
}
// 返回有针对本 app 的 tweak 数量,为 0 说明没有
return cnt;
}
防 http 抓包
通常破解一个 app,我们会抓包。这样的话,我们的 app 所有接口,接口数据都会暴露在逆向人员的眼皮底下。这时候,我们可以限制 http 抓包。方式很简单,就是将 NSURLSessionConfiguration 的 connectionProxyDictionary 设置成空的字典,因为这个属性就是用来控制会话的可用代理的。可用参见官方文档,也就是参考资料5。下面是对于 AFNetWorking 的使用方法:
// 继承 AFHTTPSessionManager,重写下列方法
- (instancetype)initWithServerHost:(PDLServerHost*)serverHost {
#ifdef DEBUG
// debug 版本的包仍然能够正常抓包
self = [super initWithBaseURL:serverHost.baseURL];
#else
// 由于使用 ephemeralSessionConfiguration session 发起的请求不带 cookhttp://www.cppcns.comie 和使用缓存等
NSURLSessionConfiguration *conf = [NSURLSessionConfiguration ephemeralSessionConfiguration];
conf.connectionProxyDictionary = @{};
self = [super initWithBaseURL:serverHost.baseURL sessionConfiguration:conf];
#endif
return self;
}
但是由于 OC 方法很容易被 hook,避免抓包是不可能的,所以,个人认为最好的方式是对请求参数进行加密(最好是非对称加密,比如 RSA)
混淆(或者加密)硬编码的明文字符串
对于被砸壳的二进制文件,逆向分析人员分析代码有一条重要线索,也就是被硬编码的明文字符串。比如说,你的 app 被人抓包了,某些数据请求接口也被人发现了,那么很简单,逆向人员可以直接拷贝特征比较明显的字符串到 hopper 中搜索,通过查看该字符串被引用的地方,可以很快的找到相应的逻辑代码。
对于这一步的防范,需要做的就是对硬编码的明文进行加密或混淆。 有个开源代码可以用,UAObfuscatedString,但是这个开源混淆代码写出来的字符串是相当长的(也就是麻烦),同时不支持加密。最近我写了一个工具,可以在编译期间加密所有代码中的明文字符串,在 app 运行的时候解密字符串。这个工具的特点如下:
1.简单,开发人员可以硬编码明文字符串,所有的加密会在编译开始时自动处理
2.可以自定义加密或者混淆方式,(为了不影响 app 运行效率,需要提供一个简单快速的加密或混淆方式)提高解密难度
使用 Swift 开发
Swift 是目前比较新的开发 iOS 语言,由于 Swift 目前还不是很稳定,越狱开源社区对这个的支持也不是很即时,比如说 class-dump 工具目前就不支持含有 Swift 的二进制文件。 TheOS 也是最近才开始支持 Swift,但是还没有加到主分支上(可以参见Features)。所以目前来看,至少 Swift 可能比纯 OC 的工程要安全一点点。当然,等 Swift 日趋稳定,以及越狱开源社区的逐渐支持,这一点优势可能就不明显了。
使用静态内连 C 函数
由于 OC 语言的动态性,导致 OC 的代码是最容易被破解分析的。在安全性上,更推荐使用 C 语言写成的函数。但是 C 语言的函数也是可以被 hook 的,主要有3种方式:
1.使用 Facebook 开源的fishhook
2.使用 MobileSubstrate 提供的 hook C 语言函数的方法
void MSHookFunction(void* function, void* replacement, void** p_original);
3.使用 mach_override,关于mach_override 和 fishhook的区别请看 mach_override 和 fishhook 区别
由于上面这三种方式可以 hook C 函数。要想不被 hook 解决方法是使用静态内联函数,这样的话需要被 hook 的函数没有统一的入口,逆向人员想要破解只能去理解该函数的逻辑。
使用 block
严格来说使用 block 并不能很大程度提高安全性,因为逆向人员只要找到使用该 block 的方法,一般来说在其附近就会有 block 内代码编程客栈的逻辑。
但是个人认为使用 block 的安全性是比直接使用 oc 方法是要高的。在我的逆向分析 app 的经验中,对于使用了 block 的方法,目前我还不知道到怎么 hook (有知道的话,可以在 blog 上提个 issue 告诉我,先谢过)同时对于含有嵌套的 block 或者是作为参数传递的 block,处理起来就更加复杂了。所以,如果能将内敛 C 函数,嵌套 block , block 类型参数组合起来的话,安全性应该是会有一定提升。
代码混淆
代码混淆的方式有几种:
添加无用又不影响逻辑的代码片段,迷糊逆向人员
对关键的类、方法,命名成与真实意图无关的名称
个人认为最好的一个加密混淆工具是ios-class-guard,不过目前这个项目已经停止维护了。但是这种方式的混淆我觉得才是最终极的方案。
其他方法
比如 ptrace 反调试等(不过据说已经可以很容易被绕过)
// see http://iphonedevwiki.net/index.php/Crack_prevention for detail
static force_inline void disable_gdb() {
#ifndef DEBUG
typedef int (*ptrace_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);
#ifndef PT_DENY_ATTACH
#define PT_DENY_ATTACH 31
#endif
// this trick can be worked around,
// see http://stackoverflow.com/questions/7034321/implementing-the-pt-deny-attach-anti-piracy-code
void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
ptrace_ptr_t ptrace_ptr = dlsym编程客栈(handle, [@"".p.t.r.a.c.e UTF8String]);
ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
dlclose(handle);
#endif
}
注意事项
通过了解 OC 的运行时特性和 mach-o 二进制文件的结构,借助现有的工具,你会发现 hook 方法 是很简单就能完成的。虽然上面我提到了一些提高安全性的几个方案,但是,所有这些方式只是增加了逆向人员的逆向难度,并不能让 app 变的坚不可摧。不过采取一定的措施肯定比什么措施都不采取来的安全。
以上就是浅谈IOS如何对app进行安全加固的详细内容,更多关于IOS如何对app进行安全加固的资料请关注我们其它相关文章!
扫码领视频副本.gif
0
精彩评论
暂无评论...
验证码 换一张
取 消
|
__label__pos
| 0.729762 |
my program is supposed to be an 11 X 11 grid where a mouse is placed on the center square. I am to count all the squares touched (or untouched) until the mouse has occupied every square. I also need to count the number of times the mouse touches the wall. The program will stop when all the squares have been touched.
When i run the program I get the size of the grid =1936 and the number of squares both touched and untouched are 21 and it stops. I was told to set the rand test to 15 until the program is "debugged". I am basically not sure if I have initialized i and j correctly. It is my understanding that to put the mouse down on the center square they would be need to be 5 but i am not sure that's right.
Any suggestions on what I should change in my code in order to get the correct output would be greatly appreciated.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <conio.h>
using namespace std;
// constants
const int MYMAXROW = 11;
const int MYMAXCOL = 11;
//header
struct squaretype
{
int row; //the row location of this square
int col; //the column location of this square
int frequency; // number of times touched by mouse
int order; //to be explained in class
};
//function prototype
int allcovered(squaretype grid[][MYMAXCOL]);
void printgrid(squaretype grid[][MYMAXCOL],
int mouseRow, int mouseCol);
squaretype findmaxLocation (squaretype grid[][MYMAXCOL]);
// end of header
//start of main
int main ()
{
int table [11][11];
squaretype grid[MYMAXROW][MYMAXCOL];
int i = 5; //where mouse starts
int j = 5; //where mouse starts
//rand number test
//const int arraySize = 10;
//srand(time(0));
srand(15);
grid[i][j].row = i;
grid[i][j].col = j;
grid[i][j].frequency = 0;
//double for loop
//declaration of two-dimensional array
int location;
int numberofmoves;
int move;
for (i = 0; i < 11; i++) //initialize and set counter to zero
{
for (j = 0; j < 11; j++)
{
grid[i][j].frequency = (i * j);
}
}
cout << grid << endl;
cout << "sizeof grid = " << sizeof(grid) << endl; //showing 1936?
location = (i * (5 * sizeof(int))) + (j + sizeof(int));
int row, col, wallhit;
int currentRow = MYMAXROW/2;
int currentCol = MYMAXCOL/2;
cout << allcovered(grid) << endl; //gives squares not touched (showing 21)
grid[currentRow][currentCol].frequency++; //place mouse down
cout << allcovered(grid) << endl; //squares not touched (showing 21)
getch();
//still in main and inside while loop
while (allcovered(grid) && numberofmoves < 100000) //safety variable
{
move = rand() % 8; //switch on this
switch (move) //all moving from m generating possible moves
{
case 0:
row = -1;
col = -1;
break;
case 1:
row = -1;
col = 0;
break;
case 2:
row = -1;
col = 1;
break;
case 3:
row = 0;
col = 1;
break;
case 4:
row = 1;
col = 1;
break;
case 5:
row = 1;
col = 0;
break;
case 6:
row = 1;
col = -1;
break;
case 7:
row = 0;
col = -1;
break;
}
//in main still in while after switch
// row hits
if ((currentRow + row) < 0)
{
wallhit++;
}
else if ((currentRow + row) > MYMAXROW)
{
wallhit++;
}
else //upate row
{
currentRow = currentRow = row;
}
//column hits
if (((currentCol + col) < 0))
{
wallhit++;
}
else if ((currentCol + col) > MYMAXCOL)
{
wallhit++;
}
else //update row
{
currentCol = currentCol = col;
}
grid[currentRow][currentCol].frequency++; //update grid will go to 0
numberofmoves++; //counter growing while grid shrinks
if (numberofmoves % 100) //shows location of mouse
{
printgrid(grid, currentRow, currentCol);
//possibly print out # of moves
cout << allcovered;
}
} //end of while - did mouse touch all squares
//report responses - max, how many times did mouse hit wall
//how many times squares hit
if(allcovered(grid)==0)
{
cout << printgrid; //print results
}
else
{
//notify user
}
getch();
return 0;
}// end of main
//footer
int allcovered(squaretype grid[][MYMAXCOL]) //get to 0
{
int retval;
int i, j; //need to assign value
retval = 0; //counter counting # of squares
for (i=0; i < MYMAXROW; i++)
{
for (j = 0; j < MYMAXCOL; j++)
{
if(grid[i][j].frequency==0)
{
retval++;
}
}
}
return(retval); //1st time thru 121,120 all true til it hits 0
//get to 0 - done
}
void printgrid(squaretype grid[][MYMAXCOL],
int mouseRow, int mouseCol) //has mouse been here or not
//not necessarily needed/prints grid
//doesnt need return stmt
{
int i, j;
for (i = 0; i < MYMAXROW; i++)
{
for(j = 0; j < MYMAXCOL; j++)
{
if((i==mouseRow)&&(j==mouseCol))
{
cout << "Mouse is here";
}
else if(grid[i][j].frequency > 0)
{
cout << "X";
}
else
{
cout << "O";
}
}
} //end outer forloop
//cout << endl;
}//end print grid
squaretype findmaxLocation (squaretype grid[][MYMAXCOL])
{
int retval = 0; //counter counting # of squares
int i, j; //need to assign value
for (i=0; i < MYMAXCOL; j++)
{
for (j=0; j < MYMAXCOL; j++)
{
if(grid[i][j].frequency==0)
{
retval++;
}
}
}
}
got it figured out.. problem solved.... thanks anyway
|
__label__pos
| 0.999268 |
Skip to main content
%{} Create object
Laurence MorganLess than 1 minute
%{} Create object
Quickly generate objects and maps
Description
%{} is a way of defining objects in expressions and statements. Whenever an %{} object is outputted as a string, it will be converted to minified JSON.
Object elements inside %{} can be new line and/or comma delimited. This allows for compatibility with JSON but without the pain of accidentally invalid comma management breaking JSON parsers. However a colon is still required to separate keys from values.
Like with YAML, strings in %[] do not need to be quoted unless you need to force numeric or boolean looking values to be stored as strings.
Examples
Object passed as a JSON string:
» echo %{foo: bar}
{"foo":"bar"}
The % prefix for the nested object is optional:
» %{foo: bar, baz: [1 2 3]}
{
"baz": [
1,
2,
3
],
"foo": "bar"
}
See Also
• %(Brace Quote)`: Initiates or terminates a string (variables expanded)
• Special Ranges: Create arrays from ranges of dictionary terms (eg weekdays, months, seasons, etc)
• "Double Quote": Initiates or terminates a string (variables expanded)
• %[] Create array: Quickly generate arrays
• 'Single Quote': Initiates or terminates a string (variables not expanded)
• expr: Expressions: mathematical, string comparisons, logical operators
This document was generated from gen/parser/create_object_doc.yamlopen in new window.
Last update:
Contributors: Laurence Morgan
|
__label__pos
| 0.819207 |
Replacing SwingWorker with Kotlin coroutines
August 7th, 2018
Note: code samples in this post are kept in sync with the latest stable Kotlin coroutines release. All the samples have been verified to work with release 1.5.2. Also see the official guide to UI programming with coroutines.
Kotlin 1.3 has been released, and one of the major additions to the language is the official graduation of coroutines from experimental to stable. Let’s take a look at how we can replace the old and venerable SwingWorker with something that is a bit more modern.
In the simplest use case, you do some kind of long-running work in your doInBackground() and then process the result of that work in done():
object : SwingWorker<List<StringValuePair>, Void>() {
@Throws(Exception::class)
override fun doInBackground(): List<StringValuePair>? {
return bar.callback.getLeafs(newPath)
}
override fun done() {
try {
filePanel.setFolder(get())
} catch (exc: Exception) {
}
}
}.execute()
There’s a whole bunch of noise, so to speak, around the core of the logic – calling breadcrumb bar’s callback to get the leaf content for the newly set path, and then populating the folder based on the retrieved content. Let’s see how this code can look like with coroutines:
filePanel.setFolder(GlobalScope.async {
bar.callback.getLeafs(newPath)
}.await())
In this case, we have distilled the core of the logic flow to its essence – asynchronous loading of the leaf content, followed by updating the UI. Another option is to collapse the async / await block into a single withContext to change the execution context away from the UI thread:
filePanel.setFolder(withContext(Dispatchers.Default) {
bar.callback.getLeafs(newPath)
})
Note that once you switch to coroutines, you also need a larger context for proper synchronization. In Swing, it means wrapping the entire listener with GlobalScope.launch(Dispatchers.Swing):
// Configure the breadcrumb bar to update the file panel every time
// the path changes
bar.model.addPathListener {
GlobalScope.launch(Dispatchers.Swing) {
val newPath = bar.model.items
if (newPath.size > 0) {
// Use the Kotlin coroutines (experimental) to kick the
// loading of the path leaf content off the UI thread and then
// pipe it back to the UI thread in setFolder call.
filePanel.setFolder(withContext(Dispatchers.Default) {
bar.callback.getLeafs(newPath)
})
}
}
}
Now let’s take a look at something a bit more interactive – updating the UI on the ongoing progress of a long-running background task.
Let’s add a button and a label to a sample frame, and kick off a 5-second task that updates the UI every second on the progress using SwingWorker.process():
val button = JButton("Start operation!")
val status = JLabel("Progress")
frame.add(button)
frame.add(status)
button.addActionListener {
class MyWorker : SwingWorker<Unit, Int>() {
override fun doInBackground() {
for (i in 1..5) {
publish(i)
Thread.sleep(1000)
}
}
override fun process(chunks: MutableList<Int>?) {
status.text = "Progress " + chunks?.joinToString()
}
override fun done() {
status.text = "Done!"
}
}
val worker = MyWorker()
worker.execute()
}
The first way to convert to coroutines would be with the help of channels:
button.addActionListener {
GlobalScope.launch(Dispatchers.Swing) {
val channel = Channel<Int>()
GlobalScope.launch {
for (x in 1..5) {
println("Sending $x " + SwingUtilities.isEventDispatchThread())
// This is happening off the main thread
channel.send(x)
// Emulating long-running background processing
delay(1000L)
}
// Close the channel as we're done processing
channel.close()
}
// The next loop keeps on going as long as the channel is not closed
for (y in channel) {
println("Processing $y " + SwingUtilities.isEventDispatchThread())
status.text = "Progress $y"
}
status.text = "Done!"
}
}
Note the usage of Dispatchers.Swing context that is passed to the GlobalScope.launch() function and the wrapping of the emulated long-running task in another GlobalScope.launch lambda. Then, as long as that lambda keeps on sending content into the channel, the for loop iterates over the channel content on the UI thread, and then relinquishes the UI thread so that it is no longer blocked.
Now let’s make it a little bit more structured. While code samples found in documentation and tutorials run on the lighter side of things (including this article), real-life apps would have more complexity on both sides of async processing. We’re going to split this logic into two parts – background processing of data and updating the UI on the main thread. Background processing becomes a separate function that returns a data channel:
fun process() : ReceiveChannel<Int> {
val channel = Channel<Int>()
GlobalScope.launch {
for (x in 1..5) {
println("Sending $x " + SwingUtilities.isEventDispatchThread())
// This is happening off the main thread
channel.send(x)
// Emulating long-running background processing
delay(1000L)
}
// Close the channel as we're done processing
channel.close()
}
return channel
}
And UI code consumes the data posted to the channel and updates the relevant pieces:
button.addActionListener {
GlobalScope.launch(Dispatchers.Swing) {
// The next loop keeps on going as long as the channel is not closed
for (y in process()) {
println("Processing $y " + SwingUtilities.isEventDispatchThread())
status.text = "Progress $y"
}
status.text = "Done!"
}
}
Let’s make the background task cancellable so that the currently running operation can be safely canceled without subsequent erroneous UI updates. Background processing returns an object that has two parts – data channel and a job that can be canceled if needed:
class ProcessResult(val resultChannel: ReceiveChannel<Int>, val job: Job)
fun processCancelable() : ProcessResult {
val channel = Channel()
val job = GlobalScope.launch {
for (x in 1..5) {
if (!isActive) {
// This async operation has been canceled
break
}
println("Sending $x " + SwingUtilities.isEventDispatchThread())
// This is happening off the main thread
channel.send(x)
// Emulating long-running background processing
delay(1000L)
}
// Close the channel as we're done processing
channel.close()
}
return ProcessResult(channel, job)
}
And on the UI side of things, we keep track of the last job that was kicked off and cancel it:
var currJob: Job? = null
button.addActionListener {
GlobalScope.launch(Dispatchers.Swing) {
currJob?.cancel()
val processResult = processCancelable()
currJob = processResult.job
// The next loop keeps on going as long as the channel is not closed
for (y in processResult.resultChannel) {
println("Processing $y " + SwingUtilities.isEventDispatchThread())
status.text = "Progress $y"
}
status.text = "Done!"
}
}
Finally, we can move away from the existing concept of data communication “pipe” between the two parts, and start thinking in terms of passing a lambda to be invoked by the data producer when it has completed processing the next chunk of data. In this last example, the producer marks itself with the suspend keyword and uses the parent context so that cancellation is properly propagated:
suspend fun processAlternative(job : Job, progress: (Int) -> Unit = {}) {
for (x in 1..5) {
// Emulating long-running background processing.
// Use the parent job so that cancellation of the parent propagates in here.
GlobalScope.async(context=job) {
println("Running on " + SwingUtilities.isEventDispatchThread())
delay(1000L)
}.await()
// And calling the callback on the UI thread
println("Sending $x " + SwingUtilities.isEventDispatchThread())
progress(x)
}
}
And the UI side of things supplies a lambda that updates the relevant UI pieces:
var currJob: Job? = null
button.addActionListener {
currJob?.cancel()
currJob = GlobalScope.launch(Dispatchers.Swing) {
// This will run until all the sequential async blocks are done
processAlternative(currJob!!) { progress ->
println("Processing $progress " + SwingUtilities.isEventDispatchThread())
status.text = "Progress $progress"
}
status.text = "Done!"
}
}
If you want start playing with replacing SwingWorker with coroutines, add org.jetbrains.kotlinx:kotlinx-coroutines-swing and org.jetbrains.kotlinx:kotlinx-coroutines-core to your dependencies. The latest version for both of the modules is 1.5.2.
|
__label__pos
| 0.99847 |
dcsimg
June 26, 2016
Hot Topics:
Introduction to Encryption
• December 7, 2000
• By Josh Ryder
• Send Email »
• More Articles »
Encryption is the process of converting data from one form (what would be considered to be readable either through plaintext or through some specific viewer like MS Word) into ciphertext. The actual process that takes place during this conversion widely varies, but the end result is the same: after conversion to ciphertext, the data is in a form that is not easily readable to prying eyes.
The process of encrypting and decrypting messages has been present since the beginning of primitive communications. Encryption has found many uses over the years, everything from decoder rings in cereal boxes to elaborate methods for governments and corporations to protect their secrets and intellectual property from prying eyes. However you look at it, in its lowest conceptual level, encryption helps provide a method to add a degree of security to communications.
There is no one single way to encrypt a file. Hundreds of ciphers exist today and many more are being developed every year. Some can be done with nothing more than a pencil and a piece of paper, while others require the number-crunching power of a computer to be effective and practical. Below are some basic examples to illustrate how encryption works.
The Alphabetic Shift
I fondly remember passing notes about in class as a child, and I also not-so-fondly remember getting caught by the teacher and having those notes read in front of the whole class. Not to be outdone by a mere elementary school math teacher, my compatriots and I devised what we considered to be a rather clever scheme for making our notes unreadable to any but ourselves. Here's the scheme that we developed:
First, we wrote down the entire alphabet on a sheet of paper. Below the first line of the alphabet we wrote the entire alphabet again, but this time starting with the letter B and ending with the letter A. The table looked something like this:
abcdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyza
Now, being the clever fellows that we were, we simply mapped the top row's letters onto the bottom. For example, the message "Loose Lips Sink Ships" would be "Mpptf Mjqt Tjol Tijqt" after translation. Unfortunately for us, our math teacher knew a thing or two about encryption, and he wrote himself a program on the sole computer (an Apple II) in school that simply tried reshifting the letters until the message was once again viewable. Imagine our surprise when one of our later notes was confiscated and he read the message aloud for the class. After the lesson we were pulled aside and complimented on our ingenuity, and then sent to detention.
Shifts with a Twist
"Get your very own super-spy decoder ring! Free inside this box of"
Remember statements like this on the sides of cereal boxes and in the back of comics? What could possibly be better to foil your teachers with than an honest-to-gosh spy encryption wheel (and you got sugary cereal too!)? Well, it turns out, quite a bit. Most of the decoder rings that were commonly available in cereal boxes were nothing more than alphabetic shifts with a twist. NOVA Online has an example of a decoder ring (printable for the kids) that should give you a good idea of what one of these things looked like.
Realizing that carrying around a 26x26 character table to do encryption/decryption was a little clunky, the alphabet was written on the outside of two circles (one larger than the other). When the circles were rotated, you could easily get the mappings between the two without all of the hassle associated with a translation table.
It was not long until someone started using this property to create increasingly complex ciphers. One alphabetic shift was difficult to decode, but what would happen if you shifted the ciphertext again? Using the example from the alphabetic shift, what would happen if we re-shifted the text again, using the letter C as a starting point? Well, obviously, the result was the same as if we had just encrypted using a two-place shift in the first place. Don't believe me? Try it for yourself.
But what if we used alternating shifts? For example, if we were to translate the first letter with a one-character shift, the second with a 10-character shift, and the third with a 21-character shift, and then repeated the pattern until the message was encrypted? Obviously the problem becomes harder as the possible combinations grow rapidly. Still, with the help of a computer, even this type of encryption is broken relatively easily.
Brute-force Attacks
As computing power has increased, so has the need for mathematically complex algorithms that provide a sufficient complexity of encryption so inaccessible to even the most powerful systems on earth. These algorithms must be sufficiently hardened so as to prevent both the brute-force and formulaic attack methods.
As RSA defines it, "Exhaustive key-search, or brute-force search, is the basic technique of trying every possible key in turn until the correct key is identified."
A brute-force attack is when someone attempts to generate every single possible encryption key until the data turns into an intelligible message. Up until recently, this form of attack was actually a viable option to those persons or corporations that had enough processing power at their disposal. The United States government once believed (in 1977) that a 56-bit Data Encryption Standard (DES) was sufficient to deter all brute-force attacks, a claim that was put to the test by several groups across the world.
Several challenges were posed by RSA labs between March 13, 1997 and July 13, 1998 to try and crack the DES. In the first two instances, the key-finding programs were distributed brute-force programs that ran on hundreds to thousands of computers whose spare CPU cycles were donated to the cause. Distributed.net won the DES-II Challenge in 39 days (meaning that within 39 days of receiving the encrypted message, they were able to read it). Even more impressively, the Electronic Frontier Foundation developed a single DES cracker that managed to perform the same feat as distributed.net in only 3 days. (This cracking machine cost in the hundreds of thousands of dollars to develop and produce - well within the range of even a fairly small technology company.)
Well, what the heck does 56-bit encryption mean, anyway? In practical terms, it means that you have a one-in-72 quadrillion chance of finding the correct key. To put this almost unfathomable number into perspective, RSA labs claims that if "72 quadrillion people could stand 4 per meter, and could stand on every square meter of the earth's surface (including the ocean floors), they would need 350,000 earths."
Since data is stored in computers using the binary system, a bit can be either one or zero - two possibilities. However, let's say you have 2 binary digits. You can now have 00, 01, 10, or 11. Four possibilities. 3 digits? Eight possibilities. Thus a 56-bit key means that there are 2^56 possibilities. By adding just one more bit, you double the key space that needs to be searched. So why don't we just add another 72 bits to the DES key and call it a day?
Formulaic Attacks
Formulaic/algorithmic attacks are in some ways much more difficult to perform because they generally require an extremely high degree of knowledge in mathematics. Rather than going after the entire keyspace, the codebreaker will try and find flaws in the algorithm that causes it to be reduced to a problem of decreased complexity. For example, if you can reduce a 64-bit problem to two or three 50-bit problems you're way ahead of the game (remember the growth curve here, folks: 3 x 2^50 = ~3.37e15, 2^64= ~1.84e19).
I was once told by an algebra professor of mine that you either have to be clinically insane or not of this planet to be able to comprehend what the hell "those cryptography guys" did. For those of you who feel up to the challenge, take a look at Simon Singh's "The Code Book" (Doubleday) for more information on cryptanalysis.
The old adage, "What doesn't kill you makes you stronger," holds true for encryption standards. Most modern encryption schemes are totally open for peer review, and as such, most new algorithms are open to whoever is interested in seeing them. This allows all of the closet cipher-crackers as well as the seasoned vets holed up at the NSA to try and find a flaw or vulnerability with an algorithm. Once a flaw has been found, the encryption scheme is either modified to compensate for it, or is discarded.
However, one should not assume, just because an algorithm has been carefully checked through peer review, that any implementation that you receive will be properly secure. Decisions made by implementers can have detrimental effects on the success of an algorithm. For example, if a coder was to implement their code using the rand() function rather than the random() function, the degree of randomness generated would be quite limited and the keyspace used by the program would be greatly reduced, opening it up to brute-force attacks.
Links and Further Readings
CryptoArchive - A comprehensive (and huge) depository of cryptography software.
"A Cryptographic Compendium" - A good crypto primer by John Savard
"Elementary Cryptanalysis: A Mathematical Approach," by Abraham Sinkov
RSA Security
Counterpane Internet Security - Publishers of the Crypto-Gram, a monthly newsletter on computer security.
Cryptography Research - SecurityPortal's own Research Center.
SecurityPortal is the world's foremost on-line resource and services provider for companies and individuals concerned about protecting their information systems and networks.
http://www.SecurityPortal.com
The Focal Point for Security on the Net (tm)
Comment and Contribute
(Maximum characters: 1200). You have characters left.
Enterprise Development Update
Don't miss an article. Subscribe to our newsletter below.
Sitemap | Contact Us
Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel
|
__label__pos
| 0.838065 |
A apresentação está carregando. Por favor, espere
A apresentação está carregando. Por favor, espere
Ordenação de Dados.
Apresentações semelhantes
Apresentação em tema: "Ordenação de Dados."— Transcrição da apresentação:
1 Ordenação de Dados
2 Métodos de Ordenação Ordenação por troca Ordenação por inserção
BubbleSort (método da bolha) QuickSort (método da troca e partição) Ordenação por inserção InsertionSort (método da inserção direta) BinaryInsertionSort (método da inserção direta binária) Ordenação por seleção SelectionSort (método da seleção direta) HeapSort (método da seleção em árvore) Outros métodos MergeSort (método da intercalação) BucketSort (método da distribuição de chave)
3 Métodos de Ordenação Simples
São três BubbleSort InsertionSort SelectionSort Características fácil implementação alta complexidade comparações ocorrem sempre entre posições adjacentes do vetor
4 BubbleSort BubbleSort é um método simples de troca Características
ordena através de sucessivas trocas entre pares de elementos do vetor Características realiza varreduras no vetor, trocando pares adjacentes de elementos sempre que o próximo elemento for menor que o anterior após uma varredura, o maior elemento está corretamente posicionado no vetor e não precisa mais ser comparado após a i-ésima varredura, os i maiores elementos estão ordenados
5 BubbleSort Simulação de funcionamento
6 BubbleSort - Complexidade
Para um vetor de n elementos, n – 1 varreduras são feitas para acertar todos os elementos n = 5 início: 4 9 2 1 5 1a V: n – 1 comparações 4 2 1 5 9 2a V: n – 2 comparações 2 1 4 5 9 . . . (n-2)a V: 2 comparações 1 2 4 5 9 (n-1)a V: 1 comparação 1 2 4 5 9 fim: 1 2 4 5 9
7 BubbleSort - Complexidade
Definida pelo número de comparações envolvendo a quantidade de dados do vetor Número de comparações: (n - 1) + (n – 2) Complexidade (para qualquer caso): n - 1 (n - 1) n i = O(n2) 2 i = 1
8 InsertionSort InsertionSort é um método simples de inserção
Características do método de inserção considera dois segmentos (sub-vetores) no vetor: ordenado (aumenta) e não-ordenado (diminui) ordena através da inserção de um elemento por vez (primeiro elemento) do segmento não-ordenado no segmento ordenado, na sua posição correta
9 segmento não-ordenado
Método de Inserção e5 e9 . . . e8 e2 segmento ordenado segmento não-ordenado e5 e8 e9 . . . e2 Inicialmente, o segmento ordenado contém apenas o primeiro elemento do vetor
10 InsertionSort realiza uma busca seqüencial no segmento ordenado para inserir corretamente um elemento do segmento não-ordenado nesta busca, realiza trocas entre elementos adjacentes para ir acertando a posição do elemento a ser inserido e5 e9 e8 . . . e2 e5 e8 e9 . . . e2
11 InsertionSort Simulação de funcionamento
12 InsertionSort - Complexidade
Pior caso: vetor totalmente desordenado n = 5 início: 9 5 4 2 1 1a V: 1 comparação 5 9 4 2 1 2a V: 2 comparações 4 5 9 2 1 . . . (n-2)a V: n-2 comparações 2 4 5 9 1 (n-1)a V: n-1 comparações 1 2 4 5 9 n - 1 (n - 1) n i = O(n2) 2 i = 1
13 InsertionSort - Complexidade
Melhor caso: vetor já ordenado n = 5 início: 1 2 4 5 9 1a V: 1 comparação 1 2 4 5 9 2a V: 1 comparação 1 2 4 5 9 . . . (n-2)a V: 1 comparação 1 2 4 5 9 (n-1)a V: 1 comparação 1 2 4 5 9 n - 1 O(n)
14 InsertionSort X BubbleSort
Melhor caso Pior caso InsertionSort O(n) O(n2) BubbleSort
15 SelectionSort SelectionSort é um método simples de seleção
ordena através de sucessivas seleções do elemento de menor valor em um segmento não-ordenado e seu posicionamento no final de um segmento ordenado troca e2 e5 e8 . . . e6 e2 e5 e6 . . . e8
16 SelectionSort Característica particular Simulação de funcionamento
realiza uma busca seqüencial pelo menor valor no segmento não-ordenado a cada iteração Simulação de funcionamento
17 SelectionSort - Complexidade
Para qualquer caso troca 9 5 1 2 4 1a V: n-1 comparações 2a V: n-2 comparações 1 5 9 2 4 1 2 9 5 4 . . . (n-1)a V: 1 comparação 1 2 4 5 9 n - 1 (n - 1) n i = O(n2) 2 i = 1
18 Comparação Melhor caso Pior caso InsertionSort O(n) O(n2) BubbleSort
SelectionSort
Carregar ppt "Ordenação de Dados."
Apresentações semelhantes
Anúncios Google
|
__label__pos
| 0.579078 |
/* $NetBSD: strspn.c,v 1.2 2018/02/04 01:13:45 mrg Exp $ */ /*- * Copyright (c) 2008 Joerg Sonnenberger * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __RCSID("$NetBSD: strspn.c,v 1.2 2018/02/04 01:13:45 mrg Exp $"); #if !defined(_KERNEL) && !defined(_STANDALONE) #include #include #include #include #else #include #endif #if ULONG_MAX != 0xffffffffffffffffull size_t strspn(const char *s, const char *charset) { static const uint8_t idx[8] = { 1, 2, 4, 8, 16, 32, 64, 128 }; uint8_t set[32]; const char *t; #define UC(a) ((unsigned int)(unsigned char)(a)) if (charset[0] == '\0') return 0; if (charset[1] == '\0') { for (t = s; *t != '\0'; ++t) { if (*t != *charset) break; } return t - s; } (void)memset(set, 0, sizeof(set)); for (; *charset != '\0'; ++charset) set[UC(*charset) >> 3] |= idx[UC(*charset) & 7]; for (t = s; *t != '\0'; ++t) if ((set[UC(*t) >> 3] & idx[UC(*t) & 7]) == 0) break; return t - s; } #else /* 64 bit system, use four 64 bits registers for bitmask */ static size_t strspn_x(const char *s_s, const char *charset_s, unsigned long invert) { const unsigned char *s = (const unsigned char *)s_s; const unsigned char *charset = (const unsigned char *)charset_s; unsigned long m_0, m_4, m_8, m_c; unsigned char ch, next_ch; unsigned long bit; unsigned long check; size_t count; /* Four 64bit registers have one bit for each character value */ m_0 = 0; m_4 = 0; m_8 = 0; m_c = 0; for (ch = *charset; ch != 0; ch = next_ch) { next_ch = *++charset; bit = 1ul << (ch & 0x3f); if (__predict_true(ch < 0x80)) { if (ch < 0x40) m_0 |= bit; else m_4 |= bit; } else { if (ch < 0xc0) m_8 |= bit; else m_c |= bit; } } /* For strcspn() we just invert the validity set */ m_0 ^= invert; m_4 ^= invert; m_8 ^= invert; m_c ^= invert; /* * We could do remove the lsb from m_0 to terminate at the * end of the input string. * However prefetching the next char is benifitial and we must * not read the byte after the \0 - as it might fault! * So we take the 'hit' of the compare against 0. */ ch = *s++; for (count = 0; ch != 0; ch = next_ch) { next_ch = s[count]; if (__predict_true(ch < 0x80)) { check = m_0; if (ch >= 0x40) check = m_4; } else { check = m_8; if (ch >= 0xc0) check = m_c; } if (!((check >> (ch & 0x3f)) & 1)) break; count++; } return count; } size_t strspn(const char *s, const char *charset) { return strspn_x(s, charset, 0); } size_t strcspn(const char *s, const char *charset) { return strspn_x(s, charset, ~0ul); } #endif
|
__label__pos
| 0.999585 |
builtin.c 14.2 KB
Newer Older
1
2
3
4
5
#include <stdio.h>
#include <assert.h>
#include "nlr.h"
#include "misc.h"
6
#include "mpconfig.h"
7
#include "qstr.h"
8
#include "obj.h"
9
#include "objstr.h"
10
#include "runtime0.h"
11
12
13
#include "runtime.h"
#include "builtin.h"
14
15
16
17
#if MICROPY_ENABLE_FLOAT
#include <math.h>
#endif
Damien George's avatar
Damien George committed
18
19
20
// args[0] is function from class body
// args[1] is class name
// args[2:] are base objects
21
STATIC mp_obj_t mp_builtin___build_class__(uint n_args, const mp_obj_t *args) {
Damien George's avatar
Damien George committed
22
23
assert(2 <= n_args);
24
25
// set the new classes __locals__ object
mp_obj_dict_t *old_locals = mp_locals_get();
26
mp_obj_t class_locals = mp_obj_new_dict(0);
27
mp_locals_set(class_locals);
28
29
// call the class code
30
mp_obj_t cell = mp_call_function_0(args[0]);
31
32
// restore old __locals__ object
Damien George's avatar
Damien George committed
33
mp_locals_set(old_locals);
34
Damien George's avatar
Damien George committed
35
36
37
38
// get the class type (meta object) from the base objects
mp_obj_t meta;
if (n_args == 2) {
// no explicit bases, so use 'type'
39
meta = (mp_obj_t)&mp_type_type;
Damien George's avatar
Damien George committed
40
41
42
43
44
45
46
47
48
} else {
// use type of first base object
meta = mp_obj_get_type(args[2]);
}
// TODO do proper metaclass resolution for multiple base objects
// create the new class using a call to the meta object
mp_obj_t meta_args[3];
49
meta_args[0] = args[1]; // class name
Damien George's avatar
Damien George committed
50
meta_args[1] = mp_obj_new_tuple(n_args - 2, args + 2); // tuple of bases
51
meta_args[2] = class_locals; // dict of members
Damien George's avatar
Damien George committed
52
mp_obj_t new_class = mp_call_function_n_kw(meta, 3, 0, meta_args);
Damien George's avatar
Damien George committed
53
54
55
56
57
58
59
// store into cell if neede
if (cell != mp_const_none) {
mp_obj_cell_set(cell, new_class);
}
return new_class;
60
61
}
Damien George's avatar
Damien George committed
62
63
MP_DEFINE_CONST_FUN_OBJ_VAR(mp_builtin___build_class___obj, 2, mp_builtin___build_class__);
64
STATIC mp_obj_t mp_builtin___repl_print__(mp_obj_t o) {
65
if (o != mp_const_none) {
66
mp_obj_print(o, PRINT_REPR);
67
68
printf("\n");
}
69
return mp_const_none;
70
71
}
72
73
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin___repl_print___obj, mp_builtin___repl_print__);
74
75
76
mp_obj_t mp_builtin_abs(mp_obj_t o_in) {
if (MP_OBJ_IS_SMALL_INT(o_in)) {
mp_small_int_t val = MP_OBJ_SMALL_INT_VALUE(o_in);
77
78
if (val < 0) {
val = -val;
79
}
80
return MP_OBJ_NEW_SMALL_INT(val);
81
#if MICROPY_ENABLE_FLOAT
82
} else if (MP_OBJ_IS_TYPE(o_in, &mp_type_float)) {
83
mp_float_t value = mp_obj_float_get(o_in);
84
// TODO check for NaN etc
85
86
if (value < 0) {
return mp_obj_new_float(-value);
87
} else {
88
return o_in;
89
}
90
} else if (MP_OBJ_IS_TYPE(o_in, &mp_type_complex)) {
91
92
mp_float_t real, imag;
mp_obj_complex_get(o_in, &real, &imag);
93
return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real*real + imag*imag));
94
95
96
#endif
} else {
assert(0);
97
return mp_const_none;
98
99
100
}
}
101
102
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_abs_obj, mp_builtin_abs);
103
STATIC mp_obj_t mp_builtin_all(mp_obj_t o_in) {
Damien George's avatar
Damien George committed
104
mp_obj_t iterable = mp_getiter(o_in);
105
mp_obj_t item;
106
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George's avatar
Damien George committed
107
if (!mp_obj_is_true(item)) {
108
return mp_const_false;
109
110
}
}
111
return mp_const_true;
112
113
}
114
115
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_all_obj, mp_builtin_all);
116
STATIC mp_obj_t mp_builtin_any(mp_obj_t o_in) {
Damien George's avatar
Damien George committed
117
mp_obj_t iterable = mp_getiter(o_in);
118
mp_obj_t item;
119
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George's avatar
Damien George committed
120
if (mp_obj_is_true(item)) {
121
return mp_const_true;
122
123
}
}
124
return mp_const_false;
125
126
}
127
128
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_any_obj, mp_builtin_any);
129
130
131
132
133
134
135
STATIC mp_obj_t mp_builtin_bin(mp_obj_t o_in) {
mp_obj_t args[] = { MP_OBJ_NEW_QSTR(MP_QSTR__brace_open__colon__hash_b_brace_close_), o_in };
return mp_obj_str_format(sizeof(args) / sizeof(args[0]), args);
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_bin_obj, mp_builtin_bin);
136
STATIC mp_obj_t mp_builtin_callable(mp_obj_t o_in) {
137
138
if (mp_obj_is_callable(o_in)) {
return mp_const_true;
139
} else {
140
return mp_const_false;
141
142
143
}
}
144
145
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_callable_obj, mp_builtin_callable);
146
STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) {
147
int ord = mp_obj_get_int(o_in);
148
if (0 <= ord && ord <= 0x10ffff) {
149
150
byte str[1] = {ord};
return mp_obj_new_str(str, 1, true);
151
} else {
152
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "chr() arg not in range(0x110000)"));
153
}
154
155
}
156
157
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_chr_obj, mp_builtin_chr);
158
STATIC mp_obj_t mp_builtin_dir(uint n_args, const mp_obj_t *args) {
159
160
// TODO make this function more general and less of a hack
161
mp_obj_dict_t *dict = NULL;
162
163
if (n_args == 0) {
// make a list of names in the local name space
164
dict = mp_locals_get();
165
166
} else { // n_args == 1
// make a list of names in the given object
Damien George's avatar
Damien George committed
167
if (MP_OBJ_IS_TYPE(args[0], &mp_type_module)) {
168
dict = mp_obj_module_get_globals(args[0]);
Damien George's avatar
Damien George committed
169
170
171
172
173
174
175
} else {
mp_obj_type_t *type;
if (MP_OBJ_IS_TYPE(args[0], &mp_type_type)) {
type = args[0];
} else {
type = mp_obj_get_type(args[0]);
}
176
if (type->locals_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(type->locals_dict, &mp_type_dict)) {
177
dict = type->locals_dict;
Damien George's avatar
Damien George committed
178
}
179
}
180
181
182
}
mp_obj_t dir = mp_obj_new_list(0, NULL);
183
184
185
186
if (dict != NULL) {
for (uint i = 0; i < dict->map.alloc; i++) {
if (MP_MAP_SLOT_IS_FILLED(&dict->map, i)) {
mp_obj_list_append(dir, dict->map.table[i].key);
187
188
189
}
}
}
190
191
192
193
194
195
return dir;
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_dir_obj, 0, 1, mp_builtin_dir);
196
STATIC mp_obj_t mp_builtin_divmod(mp_obj_t o1_in, mp_obj_t o2_in) {
197
198
199
if (MP_OBJ_IS_SMALL_INT(o1_in) && MP_OBJ_IS_SMALL_INT(o2_in)) {
mp_small_int_t i1 = MP_OBJ_SMALL_INT_VALUE(o1_in);
mp_small_int_t i2 = MP_OBJ_SMALL_INT_VALUE(o2_in);
200
201
202
mp_obj_t args[2];
args[0] = MP_OBJ_NEW_SMALL_INT(i1 / i2);
args[1] = MP_OBJ_NEW_SMALL_INT(i1 % i2);
203
return mp_obj_new_tuple(2, args);
204
} else {
205
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "unsupported operand type(s) for divmod(): '%s' and '%s'", mp_obj_get_type_str(o1_in), mp_obj_get_type_str(o2_in)));
206
207
208
}
}
209
210
MP_DEFINE_CONST_FUN_OBJ_2(mp_builtin_divmod_obj, mp_builtin_divmod);
211
STATIC mp_obj_t mp_builtin_hash(mp_obj_t o_in) {
212
// TODO hash will generally overflow small integer; can we safely truncate it?
213
return mp_obj_new_int(mp_obj_hash(o_in));
214
215
}
216
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hash_obj, mp_builtin_hash);
217
Damien George's avatar
Damien George committed
218
STATIC mp_obj_t mp_builtin_hex(mp_obj_t o_in) {
219
return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_x), o_in);
Damien George's avatar
Damien George committed
220
221
222
223
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_hex_obj, mp_builtin_hex);
224
STATIC mp_obj_t mp_builtin_iter(mp_obj_t o_in) {
Damien George's avatar
Damien George committed
225
return mp_getiter(o_in);
226
227
}
228
229
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_iter_obj, mp_builtin_iter);
230
STATIC mp_obj_t mp_builtin_len(mp_obj_t o_in) {
231
232
mp_obj_t len = mp_obj_len_maybe(o_in);
if (len == NULL) {
233
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "object of type '%s' has no len()", mp_obj_get_type_str(o_in)));
234
235
} else {
return len;
236
237
238
}
}
239
240
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_len_obj, mp_builtin_len);
241
STATIC mp_obj_t mp_builtin_max(uint n_args, const mp_obj_t *args) {
242
243
if (n_args == 1) {
// given an iterable
Damien George's avatar
Damien George committed
244
mp_obj_t iterable = mp_getiter(args[0]);
245
246
mp_obj_t max_obj = NULL;
mp_obj_t item;
247
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
248
if (max_obj == NULL || mp_binary_op(MP_BINARY_OP_LESS, max_obj, item)) {
249
250
max_obj = item;
}
251
}
252
if (max_obj == NULL) {
253
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "max() arg is an empty sequence"));
254
255
}
return max_obj;
256
} else {
257
// given many args
258
mp_obj_t max_obj = args[0];
259
for (int i = 1; i < n_args; i++) {
260
if (mp_binary_op(MP_BINARY_OP_LESS, max_obj, args[i])) {
261
262
263
264
max_obj = args[i];
}
}
return max_obj;
265
266
267
}
}
268
269
MP_DEFINE_CONST_FUN_OBJ_VAR(mp_builtin_max_obj, 1, mp_builtin_max);
270
STATIC mp_obj_t mp_builtin_min(uint n_args, const mp_obj_t *args) {
271
272
if (n_args == 1) {
// given an iterable
Damien George's avatar
Damien George committed
273
mp_obj_t iterable = mp_getiter(args[0]);
274
275
mp_obj_t min_obj = NULL;
mp_obj_t item;
276
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
277
if (min_obj == NULL || mp_binary_op(MP_BINARY_OP_LESS, item, min_obj)) {
278
279
280
281
min_obj = item;
}
}
if (min_obj == NULL) {
282
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "min() arg is an empty sequence"));
283
284
285
286
}
return min_obj;
} else {
// given many args
287
mp_obj_t min_obj = args[0];
288
for (int i = 1; i < n_args; i++) {
289
if (mp_binary_op(MP_BINARY_OP_LESS, args[i], min_obj)) {
290
291
292
293
294
295
min_obj = args[i];
}
}
return min_obj;
}
}
296
297
298
MP_DEFINE_CONST_FUN_OBJ_VAR(mp_builtin_min_obj, 1, mp_builtin_min);
299
STATIC mp_obj_t mp_builtin_next(mp_obj_t o) {
Damien George's avatar
Damien George committed
300
mp_obj_t ret = mp_iternext_allow_raise(o);
301
if (ret == MP_OBJ_STOP_ITERATION) {
302
nlr_raise(mp_obj_new_exception(&mp_type_StopIteration));
303
304
305
} else {
return ret;
}
306
307
308
309
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_next_obj, mp_builtin_next);
310
311
312
313
314
315
STATIC mp_obj_t mp_builtin_oct(mp_obj_t o_in) {
return mp_binary_op(MP_BINARY_OP_MODULO, MP_OBJ_NEW_QSTR(MP_QSTR__percent__hash_o), o_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_oct_obj, mp_builtin_oct);
316
STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) {
317
uint len;
318
const char *str = mp_obj_str_get_data(o_in, &len);
319
if (len == 1) {
320
321
322
// don't sign extend when converting to ord
// TODO unicode
return mp_obj_new_int(((const byte*)str)[0]);
323
} else {
324
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "ord() expected a character, but string of length %d found", len));
325
326
}
}
327
328
329
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_ord_obj, mp_builtin_ord);
330
STATIC mp_obj_t mp_builtin_pow(uint n_args, const mp_obj_t *args) {
331
assert(2 <= n_args && n_args <= 3);
332
switch (n_args) {
Damien George's avatar
Damien George committed
333
334
case 2: return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]);
default: return mp_binary_op(MP_BINARY_OP_MODULO, mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]), args[2]); // TODO optimise...
335
336
}
}
337
338
339
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_pow_obj, 2, 3, mp_builtin_pow);
340
341
342
343
344
345
346
347
348
349
350
351
352
STATIC mp_obj_t mp_builtin_print(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) {
mp_map_elem_t *sep_elem = mp_map_lookup(kwargs, MP_OBJ_NEW_QSTR(MP_QSTR_sep), MP_MAP_LOOKUP);
mp_map_elem_t *end_elem = mp_map_lookup(kwargs, MP_OBJ_NEW_QSTR(MP_QSTR_end), MP_MAP_LOOKUP);
const char *sep_data = " ";
uint sep_len = 1;
const char *end_data = "\n";
uint end_len = 1;
if (sep_elem != NULL && sep_elem->value != mp_const_none) {
sep_data = mp_obj_str_get_data(sep_elem->value, &sep_len);
}
if (end_elem != NULL && end_elem->value != mp_const_none) {
end_data = mp_obj_str_get_data(end_elem->value, &end_len);
}
353
354
for (int i = 0; i < n_args; i++) {
if (i > 0) {
355
printf("%.*s", sep_len, sep_data);
356
}
357
mp_obj_print(args[i], PRINT_STR);
358
}
359
printf("%.*s", end_len, end_data);
360
return mp_const_none;
361
362
}
363
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_print_obj, 0, mp_builtin_print);
364
365
STATIC mp_obj_t mp_builtin_repr(mp_obj_t o_in) {
Damien George's avatar
Damien George committed
366
vstr_t *vstr = vstr_new();
367
mp_obj_print_helper((void (*)(void *env, const char *fmt, ...))vstr_printf, vstr, o_in, PRINT_REPR);
368
369
370
mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
vstr_free(vstr);
return s;
Damien George's avatar
Damien George committed
371
372
373
374
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_repr_obj, mp_builtin_repr);
375
STATIC mp_obj_t mp_builtin_sum(uint n_args, const mp_obj_t *args) {
376
assert(1 <= n_args && n_args <= 2);
377
mp_obj_t value;
378
switch (n_args) {
379
case 1: value = mp_obj_new_int(0); break;
380
default: value = args[1]; break;
381
}
Damien George's avatar
Damien George committed
382
mp_obj_t iterable = mp_getiter(args[0]);
383
mp_obj_t item;
384
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George's avatar
Damien George committed
385
value = mp_binary_op(MP_BINARY_OP_ADD, value, item);
386
387
388
}
return value;
}
Damien George's avatar
Damien George committed
389
390
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_sum_obj, 1, 2, mp_builtin_sum);
John R. Lenton's avatar
sorted
John R. Lenton committed
391
392
STATIC mp_obj_t mp_builtin_sorted(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) {
393
394
assert(n_args >= 1);
if (n_args > 1) {
395
nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
John R. Lenton's avatar
sorted
John R. Lenton committed
396
397
"must use keyword argument for key function"));
}
398
mp_obj_t self = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, args);
399
mp_obj_list_sort(1, &self, kwargs);
John R. Lenton's avatar
sorted
John R. Lenton committed
400
401
402
return self;
}
Damien George's avatar
Damien George committed
403
404
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_sorted_obj, 1, mp_builtin_sorted);
405
406
STATIC mp_obj_t mp_builtin_id(mp_obj_t o_in) {
407
return mp_obj_new_int((machine_int_t)o_in);
408
409
410
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_id_obj, mp_builtin_id);
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// See mp_load_attr() if making any changes
STATIC inline mp_obj_t mp_load_attr_default(mp_obj_t base, qstr attr, mp_obj_t defval) {
mp_obj_t dest[2];
// use load_method, raising or not raising exception
((defval == MP_OBJ_NULL) ? mp_load_method : mp_load_method_maybe)(base, attr, dest);
if (dest[0] == MP_OBJ_NULL) {
return defval;
} else if (dest[1] == MP_OBJ_NULL) {
// load_method returned just a normal attribute
return dest[0];
} else {
// load_method returned a method, so build a bound method object
return mp_obj_new_bound_meth(dest[0], dest[1]);
}
}
428
429
430
431
432
433
434
STATIC mp_obj_t mp_builtin_getattr(uint n_args, const mp_obj_t *args) {
assert(MP_OBJ_IS_QSTR(args[1]));
mp_obj_t defval = MP_OBJ_NULL;
if (n_args > 2) {
defval = args[2];
}
return mp_load_attr_default(args[0], MP_OBJ_QSTR_VALUE(args[1]), defval);
435
436
}
437
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_getattr_obj, 2, 3, mp_builtin_getattr);
438
439
440
441
// These two are defined in terms of MicroPython API functions right away
MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_globals_obj, mp_globals_get);
MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_locals_obj, mp_locals_get);
|
__label__pos
| 0.996371 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.