content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
  Caché MultiValue Commands Reference MultiValue Command Stack Commands and Keystrokes [Back] [Next]     Server:docs2 Instance:LATEST User:UnknownUser   - Go to: Search:     This chapter provides an alphabetical listing of the command stack commands supported by the Caché MultiValue Shell. Command stack commands begin with a period (.) character. These allow you to edit and execute the command lines on the command line stack. These command names are not case-sensitive. This chapter also describes the keyboard keystrokes supported by the Caché MultiValue Shell. .A The .A command appends text to a command line. .A[n] text The command .A (or .A1) appends text to the current command line. The command .An appends text to a command line earlier in the command stack, with the integer n specifying how many previous line to count back. Thus, .A4 appends text to the command line issued four lines ago. The text is appended exactly as specified. Thus a quoted string is appended with the quote characters. .C The .C command changes command line text. .C[n] /oldtext/newtext The command .C (or .C1) replaces the first instance of oldtext with newtext in the current command line. The command .Cn replaces text in a command line earlier in the command stack, with the integer n specifying how many previous line to count back. Thus, .C4 replaces oldtext with newtext in the command line issued four lines ago. Text search is case-sensitive. To delete oldtext, specify .C /oldtext/. To replace oldtext with a blank space, specify .C /oldtext/ /. .D The .D command deletes one or more command lines from the command stack. .D[n[-m]] The command .D (or .D1) deletes the most recent command line from the command stack. The command .Dn, with n specified as an integer, deletes the n most recent command line from the command stack. The command .Dn-m, with n and m specified as integers, deletes the range of lines between n and m (inclusive). .L The .L command lists one or more lines from the command line stack. .L[n] The command .L lists all of the command lines in the command line stack. The command .L1 lists the most recent command line in the command line stack. The command .Ln, with n specified as an integer, lists the n most recent command lines in the command line stack. If n is larger than the number of lines on the stack, all lines on the stack are returned. .U The .U command converts one or more command lines to uppercase letters. .U[n[-m]] The command .U (or .U1) converts the most recent command line to uppercase letters. The command .Un, with n specified as an integer, converts the n most recent command line to uppercase. The command .Un-m, with n and m specified as integers, converts the range of lines between n and m (inclusive) to uppercase letters. This range begins with the n command line and ends with the m command line. Therefore, to convert the last three command line commands and return them in the original order, you would specify .U3–1. .X The .X command executes one or more command lines. .X[n[-m]] The command .X (or .X1) retrieves and executes the most recent command line. The command .Xn retrieves and executes a command line earlier in the command stack, with the integer n specifying how many previous line to count back. Thus, .X4 executes the command line issued four lines ago. Note that issuing .X or .X1 does not increment the command line count, whereas issuing .Xn (where n is >= 2) does increment the command line count by 1. The command .Xn-m, with n and m specified as integers, executes the range of lines between n and m (inclusive), beginning with the n command line and ending with the m command line. Therefore, to execute the last three command line commands in the original order, you would specify .X3–1. .? The .? command displays help text for the command stack commands. .? Keystrokes The Caché MultiValue Shell supports the following terminal keystrokes:
__label__pos
0.964115
? 1. Yes, and I was waiting for something like this. 55.2% 2. Yes, but I'm not that interested in the idea. 5.6% 3. No, but I'm happy somebody has made it. 28.7% 4. No, and I would prefer if Nintendo improved their menu. 10.5% 1. Vilagamer999 Vilagamer999 GBAtemp Regular Member Joined: Jun 21, 2018 Messages: 113 Country: United States Amazing :) keep it up!   2. tan-tan tan-tan GBAtemp Regular Member Joined: Nov 9, 2011 Messages: 126 Country: Canada Is uviewer supposed to lack audio? I can't get any sound to stream when using it.   3. SuperHans111 SuperHans111 GBAtemp Regular Member Joined: Feb 2, 2019 Messages: 125 Country: Australia Does this seem to drain battery really fast for anyone else?   4. Hephaestus Hephaestus GBAtemp Fan Member Joined: Sep 29, 2017 Messages: 306 Country: Korea, North @XorTroll I use SX OS. Are you gonna brick us if we use this or not? I dont earn enough to just yolo gamble away a console for fun. I can imagine that quite a few people dont exactly trust you anymore.   5. Techjunky90 Techjunky90 GBAtemp Fan Member Joined: Apr 7, 2017 Messages: 487 Country: United States Been using it on sxos for awhile now.   6. jammybudga777 jammybudga777 GBAtemp Addict Member Joined: Aug 23, 2013 Messages: 2,170 Country: why? wheres this come from??   7. seanp2500 seanp2500 GBAtemp Advanced Fan Member Joined: Jun 2, 2010 Messages: 918 Country: United States I was unaware of xortroll position on this. Saddens me. While I find stealing code reprehensible. This is a wild wild west or lawless grey area the homebrew or modded switch software however you wish to put it exists in. So it is hard to punish team executer when it is done. Other than report it to the community and tarnish their reputation. To include potential brick code if said software is detected is akin to what i would call a “nuclear option”. Please do not do this. It only harms end users in the end. As some have pointed out not everyone can afford this. Have you not ever witnessed that moment when one wants to game and cannot? Due to hardware failure? It is such a sad moment. Why cause this to what are essentially innocent bystanders in such bickering? the actual gamers using the various software... perhaps those who are making such threats have forgotten or misplaced their roots...why do you develop such software? Is it not due to gaming?   8. Hephaestus Hephaestus GBAtemp Fan Member Joined: Sep 29, 2017 Messages: 306 Country: Korea, North Blame Xecuter, not us. None of us ever stole any code, nor do we intend to.   9. hippy dave hippy dave BBMB Member Joined: Apr 30, 2012 Messages: 5,652 Country: United Kingdom Sigh. Some devs say stuff like that in chat, they probably shouldn't, but they do. XorTroll isn't going to brick anyone. Move on.   Pyronix and Hephaestus like this. 10. Hephaestus Hephaestus GBAtemp Fan Member Joined: Sep 29, 2017 Messages: 306 Country: Korea, North 11. axiomjunglist axiomjunglist Member Newcomer Joined: Jan 7, 2019 Messages: 32 Country: United States Can uLaunch run without the flog feature enabled?   12. CatmanFan CatmanFan Anxious and regretful Member Joined: Aug 14, 2016 Messages: 1,951 Country: Morocco Of course. The only thing that won't work without it enabled is running homebrew NROs in application mode rather than using applet (especially when forwarding N64 or certain homebrews)   Angeloras and axiomjunglist like this. 13. strunx strunx Newbie Newcomer Joined: Oct 24, 2014 Messages: 8 Country: United States Is it possible with uLaunch to create a home menu like 3DS? A grid with lots of shortcuts instead of the switch icon bar? I'm asking if it's possible to try creating a theme or wait if that option could be implemented in the future. Thanks!   CatmanFan likes this. 14. starbury86 starbury86 Member Newcomer Joined: Jun 28, 2018 Messages: 17 Country: Germany How are you using it? I can not use it because I receive a message that sx os stealth mode is activated. When I disable it and reboot my console it is still activated, so there is no way for me to use it with sx os?   15. Hephaestus Hephaestus GBAtemp Fan Member Joined: Sep 29, 2017 Messages: 306 Country: Korea, North I copied the files over on SX OS. Tried re-injecting the payload. How do i use it?   16. Phenj Phenj GBAtemp Fan Member Joined: May 22, 2018 Messages: 425 Country: Italy ulaunch is completely broken on 9.1.0 with atmosphere 0.10.1, crashes the console upon launching with hekate, only solution is deleting every ulaunch folder leftover. Code: fatal error has occurred title id: 010041544d530000 error desc: std::abort() called 0xffe DM me if you want the .bin error.   17. jacobsson jacobsson Newbie Newcomer Joined: Oct 30, 2019 Messages: 6 Country: Sweden I have this exact problem but with on 8.1.0 + atmos 0.10.1. Can you tell me what exact files/entries are to be removed for it to unbrick? I'd really appreciate it!   18. Chocola Chocola GBAtemp Meowgular Member Joined: Sep 18, 2018 Messages: 293 Country: Korea, South Yes, need update to last libnx and some changes, wait for new release. For remove, just delete the uLaunch folders on atmosphere/contents/   jacobsson likes this. 19. Chocola Chocola GBAtemp Meowgular Member Joined: Sep 18, 2018 Messages: 293 Country: Korea, South Yes, its possible, but I don't know if the theme engine support hard theming like this for now or you need change the sourcecode, personally I have my own modifications on sourcecode for my launcher.   strunx and CatmanFan like this. Draft saved Draft deleted Loading... Hide similar threads Similar threads with keywords - reimplementation, Nintendo, uLaunch
__label__pos
0.72579
Skip to main content Version: 2.7.0 Object dictionary An object dictionary (OD) allows various developers of different services to make them interoperate regardless of the units they use on their code. Example: If my_service1 uses an angle in radians and my_service2 uses degrees, what is the unit they should use to share the angle information? An object dictionary defines a set of typical objects that can be transmitted through Luos messages. It allows to send these objects with a unit and to use it in any other units, in other services. Luos engine defines objects based on physical values following the SI standard. Objects and types Each object in the Object Dictionary has a specific Type. For example: // Define object angular_position as an angular_position_t type angular_position_t angular_position; You can create your variables using these objects but never set OD variables directly with a value. Instead, you have to use functions available on the Luos engine's OD: // Set object angular_position float deg = 12.0; angular_position_t angular_position = AngularOD_PositionFrom_deg(deg); Following this rule, everybody will be able to use your values. All the types are listed in the table summary at the end of this page. Conversions As many units exist, many conversion functions are available. As a result, they follow logic naming rules in order to quickly find the desired function without having to search for it. Unit conversions There are two types of unit conversion: in one way (OD type from the desired unit), and in the other way (OD type to the desired unit): • from conversion: Converts a value with a defined unit into a desired OD data. Format: [type_var] = [type]From_[unit]([value]) // save a linear_position from a mm value linear_position_t linear_position = LinearOD_PositionFrom_mm(float mm); • to conversion: Converts an OD data into a specific unit. Format: [value] = [type]To_[unit]([type_var]) // convert the variable linear_position into mm float mm = LinearOD_PositionTo_mm(linear_position_t linear_position); Messages conversions In the same way, both conversions are available for messages (OD type from message and OD type to message): • from conversion: Gets a OD data from a message. Format: [type]FromMsg([type_var], msg) // get the linear_position from the message msg void LinearOD_PositionFromMsg(linear_position_t* linear_position, msg_t* msg); • to conversion: Inserts a desired OD data into a message. Format: [type]ToMsg(type_var], msg) // insert the linear_position into the message msg void LinearOD_PositionToMsg(linear_position_t* linear_position, msg_t* msg); Types and units table summary Here are listed the existing types: TypeAvailable prefix and other units linear_positionnm, μm, mm, cm, m, km, in, ft, mi linear_speedmm/s, m/s, km/h, in/s, mi/h angular_positiondeg, revolution, rad angular_speeddeg/s, revolution/s, revolution/min, rad/s forceN, kgf, ozf, lbf momentN.mm, N.cm, N.m, kgf.mm, kgf.cm, kgf.m, ozf.in, lbf.in voltagemV, V currentmA, A powermW, W ratiopercentage temperaturedeg_c, deg_f, deg_k color8bit_RGB unsigned char [3] controlcontrol_t (play, pause, stop, record) pidasserv_pid_t float [3] {proportional, integral, derivative} tip To find out what conversion function to use if you don't know it, replace the characters / or . in the units by the character _. The character µ is replaced by u, and revolution is replaced by rev. Examples: convert a linear speed to mm/s: LinearOD_SpeedTo_mm_s(); convert a value in μm to a linear position: LinearOD_PositionFrom_um(); convert a value in revolutions/s to an angular speed: AngularOD_SpeedFrom_rev_s(); A feedback? Let's discuss on Discord | Github
__label__pos
0.900156
Help Password resets jshurkin Journeyman Password resets Why do keep on getting this message when I try and rest my password?   "This password reset link has been deactivated" 2 Replies Reshma Community Support Expert Community Support Expert Hi @jshurkin,   Thank you for posting in PowerSchool Community.   To assist you further, would you please confirm the product name where you were trying to reset your password? Reshma PowerSchool Community Support Expert Remember to give Kudos to suggestions that help you! If another user helps solve your issue, please select Accept As Solution on their post so others can see the solution, too! rcgarcia Trainee Hi, I had this same problem and it turned out that it was because I have a password manager program that auto-fills in the password. That was messing up what was going on. What I did to fix it was open a different browser that does not have that auto-fill function set up. then I clicked the "forgot password" thing, filled in my email and it sent me the email. Then when I clicked on the link in that email, the link worked.
__label__pos
0.558619
Quantcast A community for students. Sign up today! Here's the question you clicked on: 55 members online • 0 replying • 0 viewing Aslander • 4 years ago I am on lecture 8. I get the basic idea behind Omicron, but is there someone who can explain the math to me, in easy terms? • This Question is Closed 1. Keen • 4 years ago Best Response You've already chosen the best response. Medals 0 I just started watching Lecture 8. Hopefully I'll be able to help soon. :) 2. Keen • 4 years ago Best Response You've already chosen the best response. Medals 0 I think there's some math that I haven't studied that's behind BigO calculations. It seems similar to calculus, calculating the rate of change, i.e. differentiating, but the specifics are different enough that it's not the same process. 3. Aslander • 4 years ago Best Response You've already chosen the best response. Medals 0 It's been a very long time since I've done Calculus...I suppose I will have to relearn it all, including algebra... 4. Keen • 4 years ago Best Response You've already chosen the best response. Medals 0 Differentiating is when you take a function, and find a new function that returns the value of the slope of the first function. So if you have function of x f(x) = 15*x +30, differentiating gets you g(x) = 15, as it's a straight line. This lets you find how quickly the original function grows at any given point. For a straight line, it's like an O(n) function, it grows directly as n grows. For f(x) = 5*x^2 + 3x + 4 differentiating gets g(x) = 10x + 3, so the original function grows as the value of x grows. This ends up being an O(n^2). Like I said it's similar, but not the same. It's all about understanding the rates of change. 5. Aslander • 4 years ago Best Response You've already chosen the best response. Medals 0 I remember some of cal, but not enough to find the differential of something more complicated than f(x) = x2. (would it be 2x?) I'll have to study a bit more there...thanks Keen. 6. bhancov • 3 years ago Best Response You've already chosen the best response. Medals 1 The derivative of f(x) = 2x is g(x) = 2, the derivative of f(x) = x^2 is g(x) = 2x. The general rule is f(x) = x^n g(x) = n*x^(n-1). For some simple derivative examples/rules, lookup the power rule and the chain rule... two pretty strong concepts that cover the math necessary. 7. Aslander • 3 years ago Best Response You've already chosen the best response. Medals 0 Thanks. 8. gmac • 3 years ago Best Response You've already chosen the best response. Medals 0 Has anyone here worked on the Quiz one? If so - looking for some guidance on problem 4 9. er14 • 3 years ago Best Response You've already chosen the best response. Medals 0 Regarding quiz one problem 4, try this: def first_N(n): count = 1 num = 1 while count <= n: if num*num % 2 != 0: print num*num count += 1 num += 1 10. Xylch • 3 years ago Best Response You've already chosen the best response. Medals 3 Big O notation in plain English: http://www.cforcoding.com/2009/07/plain-english-explanation-of-big-o.html I just found a few days ago and it was an immense help on understand Big O notation. 11. Reku • 3 years ago Best Response You've already chosen the best response. Medals 0 In the case of informatic and complexity, the easiest way to think about m(x) = O(n(x)) (m and n are functions) is that : there are integer A and K which exist, and for x from A to infinity, m(x) < K * n(x) So here it means that the complexity, for a big number n of operation is under K*n. So linear. It's an asymptotic way to see where how the growing is. (This course show the temporal complexity in the worst case and when the size of the operation grows) The O doesn't show the spatial complexity or the average complexity, which are also great tools but which are a bit more difficult) MITopencourse is the best ! 12. gravityenergy • 3 years ago Best Response You've already chosen the best response. Medals 2 The algorithm that you select to use in a code shows how you’ve decided to search for a value. The cost of the algorithm depends on the variables involved. Different methods have specific behaviors. The classes of algorithms are: linear, quadratic, log, exponential. Identifying the classes used within code is the “big picture” of lecture 8. The mathematical names of the algorithms describe how the code is behaving. The growth behaviors of algorithms are illustrated in the first 4 code problems on the related resources handout. The first two show what linear and recursive algorithms look like in the code. The quadratic and exponential are located at 18:40 in the video. 1. The behavior of the linear algorithm is stepwise searching. The name of “the order of complexity” is “linear.” 2. The quadratic algorithm behaves by squaring (or cubing) a given procedure within the code. In the video, the order of complexity is n*m. However, if n = m, then you have n^2, and this is quadratic. (19:30 – 20:15). 3. The behavior of log is to cut the search by a fractional amount, such as ½, 1/3, etc. This tends to be efficient because it cuts down the search time by ½, 1/3, etc. 4. The behavior of exponents is outrageously rapid growth that is generally to be avoided. The base case can be found quickly using one algorithm, but is extremely expensive when using a different algorithm. The efficient choice depends on the situation. Analyzing complexity is a matter of selecting the algorithm that is best matched to a given issue. The Towers of Hanoi illustrated the different efficiencies of different methods. Detailed algebra/calculus review for free at http://brightstorm.com/. Hope this helps someone. 13. Yoroshiku_ne • 3 years ago Best Response You've already chosen the best response. Medals 0 Thank you, gravityenergy. Your explanation paints a good conceptual picture. 14. Not the answer you are looking for? Search for more explanations. • Attachments: Ask your own question Ask a Question Find more explanations on OpenStudy Your question is ready. Sign up for free to start getting answers. spraguer (Moderator) 5 → View Detailed Profile is replying to Can someone tell me what button the professor is hitting... 23 • Teamwork 19 Teammate • Problem Solving 19 Hero • You have blocked this person. • ✔ You're a fan Checking fan status... Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy. This is the testimonial you wrote. You haven't written a testimonial for Owlfred.
__label__pos
0.716866
Forum PHP 2017 Voting Please answer this simple SPAM challenge: two minus zero? (Example: nine) The Note You're Voting On Ashley Dambra 3 years ago Here a simple class 'stdObject' that give us the possibility to create dynamic classes and the possibility to add and execute methods thing that 'stdClass' don't let us do.  Very useful if you extends it to a controller on MVC Design pattern. Let users create own classes. I have also post this class on http://www.php.net/manual/en/language.types.object.php <?php class stdObject {     public function __construct(array $arguments = array()) {         if (!empty( $arguments)) {             foreach ( $arguments as $property => $argument) {                 $this->{$property} = $argument;             }         }     }     public function __call($method, $arguments) {         $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).         if (isset($this->{$method}) && is_callable($this->{$method})) {             return call_user_func_array($this->{$method}, $arguments);         } else {             throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");         }     } } // Usage. $obj = new stdObject(); $obj->name = "Nick"; $obj->surname = "Doe"; $obj->age = 20; $obj->adresse = null; $obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).     echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse; }; $func = "setAge"; $obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.     $stdObject->age = $age; }; $obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'. // Create dynamic method. Here i'm generating getter and setter dynimically // Beware: Method name are case sensitive. foreach ($obj as $func_name => $value) {     if (! $value instanceOf Closure) {         $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.             $stdObject->{$func_name} = $value;         };         $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.             return $stdObject->{$func_name};         };     } } $obj->setName("John"); $obj->setAdresse("Boston"); $obj->getInfo(); ?> << Back to user notes page To Top
__label__pos
0.997304
blob: aa28c65eb6b4f3a98e7aa6d5a1a1eac28d1c0c06 [file] [log] [blame] /* * Intel MID GPIO driver * * Copyright (c) 2008-2014 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ /* Supports: * Moorestown platform Langwell chip. * Medfield platform Penwell chip. * Clovertrail platform Cloverview chip. * Merrifield platform Tangier chip. */ #include <linux/module.h> #include <linux/pci.h> #include <linux/platform_device.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/stddef.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/io.h> #include <linux/gpio/driver.h> #include <linux/slab.h> #include <linux/pm_runtime.h> #define INTEL_MID_IRQ_TYPE_EDGE (1 << 0) #define INTEL_MID_IRQ_TYPE_LEVEL (1 << 1) /* * Langwell chip has 64 pins and thus there are 2 32bit registers to control * each feature, while Penwell chip has 96 pins for each block, and need 3 32bit * registers to control them, so we only define the order here instead of a * structure, to get a bit offset for a pin (use GPDR as an example): * * nreg = ngpio / 32; * reg = offset / 32; * bit = offset % 32; * reg_addr = reg_base + GPDR * nreg * 4 + reg * 4; * * so the bit of reg_addr is to control pin offset's GPDR feature */ enum GPIO_REG { GPLR = 0, /* pin level read-only */ GPDR, /* pin direction */ GPSR, /* pin set */ GPCR, /* pin clear */ GRER, /* rising edge detect */ GFER, /* falling edge detect */ GEDR, /* edge detect result */ GAFR, /* alt function */ }; /* intel_mid gpio driver data */ struct intel_mid_gpio_ddata { u16 ngpio; /* number of gpio pins */ u32 gplr_offset; /* offset of first GPLR register from base */ u32 flis_base; /* base address of FLIS registers */ u32 flis_len; /* length of FLIS registers */ u32 (*get_flis_offset)(int gpio); u32 chip_irq_type; /* chip interrupt type */ }; struct intel_mid_gpio { struct gpio_chip chip; void __iomem *reg_base; spinlock_t lock; struct pci_dev *pdev; }; static inline struct intel_mid_gpio *to_intel_gpio_priv(struct gpio_chip *gc) { return container_of(gc, struct intel_mid_gpio, chip); } static void __iomem *gpio_reg(struct gpio_chip *chip, unsigned offset, enum GPIO_REG reg_type) { struct intel_mid_gpio *priv = to_intel_gpio_priv(chip); unsigned nreg = chip->ngpio / 32; u8 reg = offset / 32; return priv->reg_base + reg_type * nreg * 4 + reg * 4; } static void __iomem *gpio_reg_2bit(struct gpio_chip *chip, unsigned offset, enum GPIO_REG reg_type) { struct intel_mid_gpio *priv = to_intel_gpio_priv(chip); unsigned nreg = chip->ngpio / 32; u8 reg = offset / 16; return priv->reg_base + reg_type * nreg * 4 + reg * 4; } static int intel_gpio_request(struct gpio_chip *chip, unsigned offset) { void __iomem *gafr = gpio_reg_2bit(chip, offset, GAFR); u32 value = readl(gafr); int shift = (offset % 16) << 1, af = (value >> shift) & 3; if (af) { value &= ~(3 << shift); writel(value, gafr); } return 0; } static int intel_gpio_get(struct gpio_chip *chip, unsigned offset) { void __iomem *gplr = gpio_reg(chip, offset, GPLR); return readl(gplr) & BIT(offset % 32); } static void intel_gpio_set(struct gpio_chip *chip, unsigned offset, int value) { void __iomem *gpsr, *gpcr; if (value) { gpsr = gpio_reg(chip, offset, GPSR); writel(BIT(offset % 32), gpsr); } else { gpcr = gpio_reg(chip, offset, GPCR); writel(BIT(offset % 32), gpcr); } } static int intel_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct intel_mid_gpio *priv = to_intel_gpio_priv(chip); void __iomem *gpdr = gpio_reg(chip, offset, GPDR); u32 value; unsigned long flags; if (priv->pdev) pm_runtime_get(&priv->pdev->dev); spin_lock_irqsave(&priv->lock, flags); value = readl(gpdr); value &= ~BIT(offset % 32); writel(value, gpdr); spin_unlock_irqrestore(&priv->lock, flags); if (priv->pdev) pm_runtime_put(&priv->pdev->dev); return 0; } static int intel_gpio_direction_output(struct gpio_chip *chip, unsigned offset, int value) { struct intel_mid_gpio *priv = to_intel_gpio_priv(chip); void __iomem *gpdr = gpio_reg(chip, offset, GPDR); unsigned long flags; intel_gpio_set(chip, offset, value); if (priv->pdev) pm_runtime_get(&priv->pdev->dev); spin_lock_irqsave(&priv->lock, flags); value = readl(gpdr); value |= BIT(offset % 32); writel(value, gpdr); spin_unlock_irqrestore(&priv->lock, flags); if (priv->pdev) pm_runtime_put(&priv->pdev->dev); return 0; } static int intel_mid_irq_type(struct irq_data *d, unsigned type) { struct gpio_chip *gc = irq_data_get_irq_chip_data(d); struct intel_mid_gpio *priv = to_intel_gpio_priv(gc); u32 gpio = irqd_to_hwirq(d); unsigned long flags; u32 value; void __iomem *grer = gpio_reg(&priv->chip, gpio, GRER); void __iomem *gfer = gpio_reg(&priv->chip, gpio, GFER); if (gpio >= priv->chip.ngpio) return -EINVAL; if (priv->pdev) pm_runtime_get(&priv->pdev->dev); spin_lock_irqsave(&priv->lock, flags); if (type & IRQ_TYPE_EDGE_RISING) value = readl(grer) | BIT(gpio % 32); else value = readl(grer) & (~BIT(gpio % 32)); writel(value, grer); if (type & IRQ_TYPE_EDGE_FALLING) value = readl(gfer) | BIT(gpio % 32); else value = readl(gfer) & (~BIT(gpio % 32)); writel(value, gfer); spin_unlock_irqrestore(&priv->lock, flags); if (priv->pdev) pm_runtime_put(&priv->pdev->dev); return 0; } static void intel_mid_irq_unmask(struct irq_data *d) { } static void intel_mid_irq_mask(struct irq_data *d) { } static struct irq_chip intel_mid_irqchip = { .name = "INTEL_MID-GPIO", .irq_mask = intel_mid_irq_mask, .irq_unmask = intel_mid_irq_unmask, .irq_set_type = intel_mid_irq_type, }; static const struct intel_mid_gpio_ddata gpio_lincroft = { .ngpio = 64, }; static const struct intel_mid_gpio_ddata gpio_penwell_aon = { .ngpio = 96, .chip_irq_type = INTEL_MID_IRQ_TYPE_EDGE, }; static const struct intel_mid_gpio_ddata gpio_penwell_core = { .ngpio = 96, .chip_irq_type = INTEL_MID_IRQ_TYPE_EDGE, }; static const struct intel_mid_gpio_ddata gpio_cloverview_aon = { .ngpio = 96, .chip_irq_type = INTEL_MID_IRQ_TYPE_EDGE | INTEL_MID_IRQ_TYPE_LEVEL, }; static const struct intel_mid_gpio_ddata gpio_cloverview_core = { .ngpio = 96, .chip_irq_type = INTEL_MID_IRQ_TYPE_EDGE, }; static const struct intel_mid_gpio_ddata gpio_tangier = { .ngpio = 192, .gplr_offset = 4, .flis_base = 0xff0c0000, .flis_len = 0x8000, .get_flis_offset = NULL, .chip_irq_type = INTEL_MID_IRQ_TYPE_EDGE, }; static const struct pci_device_id intel_gpio_ids[] = { { /* Lincroft */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x080f), .driver_data = (kernel_ulong_t)&gpio_lincroft, }, { /* Penwell AON */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x081f), .driver_data = (kernel_ulong_t)&gpio_penwell_aon, }, { /* Penwell Core */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x081a), .driver_data = (kernel_ulong_t)&gpio_penwell_core, }, { /* Cloverview Aon */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x08eb), .driver_data = (kernel_ulong_t)&gpio_cloverview_aon, }, { /* Cloverview Core */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x08f7), .driver_data = (kernel_ulong_t)&gpio_cloverview_core, }, { /* Tangier */ PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x1199), .driver_data = (kernel_ulong_t)&gpio_tangier, }, { 0 } }; MODULE_DEVICE_TABLE(pci, intel_gpio_ids); static void intel_mid_irq_handler(unsigned irq, struct irq_desc *desc) { struct gpio_chip *gc = irq_desc_get_handler_data(desc); struct intel_mid_gpio *priv = to_intel_gpio_priv(gc); struct irq_data *data = irq_desc_get_irq_data(desc); struct irq_chip *chip = irq_data_get_irq_chip(data); u32 base, gpio, mask; unsigned long pending; void __iomem *gedr; /* check GPIO controller to check which pin triggered the interrupt */ for (base = 0; base < priv->chip.ngpio; base += 32) { gedr = gpio_reg(&priv->chip, base, GEDR); while ((pending = readl(gedr))) { gpio = __ffs(pending); mask = BIT(gpio); /* Clear before handling so we can't lose an edge */ writel(mask, gedr); generic_handle_irq(irq_find_mapping(gc->irqdomain, base + gpio)); } } chip->irq_eoi(data); } static void intel_mid_irq_init_hw(struct intel_mid_gpio *priv) { void __iomem *reg; unsigned base; for (base = 0; base < priv->chip.ngpio; base += 32) { /* Clear the rising-edge detect register */ reg = gpio_reg(&priv->chip, base, GRER); writel(0, reg); /* Clear the falling-edge detect register */ reg = gpio_reg(&priv->chip, base, GFER); writel(0, reg); /* Clear the edge detect status register */ reg = gpio_reg(&priv->chip, base, GEDR); writel(~0, reg); } } static int intel_gpio_runtime_idle(struct device *dev) { int err = pm_schedule_suspend(dev, 500); return err ?: -EBUSY; } static const struct dev_pm_ops intel_gpio_pm_ops = { SET_RUNTIME_PM_OPS(NULL, NULL, intel_gpio_runtime_idle) }; static int intel_gpio_probe(struct pci_dev *pdev, const struct pci_device_id *id) { void __iomem *base; struct intel_mid_gpio *priv; u32 gpio_base; u32 irq_base; int retval; struct intel_mid_gpio_ddata *ddata = (struct intel_mid_gpio_ddata *)id->driver_data; retval = pcim_enable_device(pdev); if (retval) return retval; retval = pcim_iomap_regions(pdev, 1 << 0 | 1 << 1, pci_name(pdev)); if (retval) { dev_err(&pdev->dev, "I/O memory mapping error\n"); return retval; } base = pcim_iomap_table(pdev)[1]; irq_base = readl(base); gpio_base = readl(sizeof(u32) + base); /* release the IO mapping, since we already get the info from bar1 */ pcim_iounmap_regions(pdev, 1 << 1); priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) { dev_err(&pdev->dev, "can't allocate chip data\n"); return -ENOMEM; } priv->reg_base = pcim_iomap_table(pdev)[0]; priv->chip.label = dev_name(&pdev->dev); priv->chip.dev = &pdev->dev; priv->chip.request = intel_gpio_request; priv->chip.direction_input = intel_gpio_direction_input; priv->chip.direction_output = intel_gpio_direction_output; priv->chip.get = intel_gpio_get; priv->chip.set = intel_gpio_set; priv->chip.base = gpio_base; priv->chip.ngpio = ddata->ngpio; priv->chip.can_sleep = false; priv->pdev = pdev; spin_lock_init(&priv->lock); pci_set_drvdata(pdev, priv); retval = gpiochip_add(&priv->chip); if (retval) { dev_err(&pdev->dev, "gpiochip_add error %d\n", retval); return retval; } retval = gpiochip_irqchip_add(&priv->chip, &intel_mid_irqchip, irq_base, handle_simple_irq, IRQ_TYPE_NONE); if (retval) { dev_err(&pdev->dev, "could not connect irqchip to gpiochip\n"); return retval; } intel_mid_irq_init_hw(priv); gpiochip_set_chained_irqchip(&priv->chip, &intel_mid_irqchip, pdev->irq, intel_mid_irq_handler); pm_runtime_put_noidle(&pdev->dev); pm_runtime_allow(&pdev->dev); return 0; } static struct pci_driver intel_gpio_driver = { .name = "intel_mid_gpio", .id_table = intel_gpio_ids, .probe = intel_gpio_probe, .driver = { .pm = &intel_gpio_pm_ops, }, }; static int __init intel_gpio_init(void) { return pci_register_driver(&intel_gpio_driver); } device_initcall(intel_gpio_init);
__label__pos
0.99847
Multithreaded Programming Guide "Shared-Memory" Multiprocessors Consider the purported solution to the producer/consumer problem shown in Example 9-5. Although this program works on current SPARC-based multiprocessors, it assumes that all multiprocessors have strongly ordered memory. This program is therefore not portable. Example 9-5 The Producer/Consumer Problem--Shared Memory Multiprocessors char buffer[BSIZE]; unsigned int in = 0; unsigned int out = 0; void char producer(char item) { consumer(void) { char item; do ;/* nothing */ do while ;/* nothing */ (in - out == BSIZE); while (in - out == 0); buffer[in%BSIZE] = item; item = buffer[out%BSIZE]; in++; out++; } } When this program has exactly one producer and exactly one consumer and is run on a shared-memory multiprocessor, it appears to be correct. The difference between in and out is the number of items in the buffer. The producer waits (by repeatedly computing this difference) until there is room for a new item, and the consumer waits until there is an item in the buffer. For memory that is strongly ordered (for instance, a modification to memory on one processor is immediately available to the other processors), this solution is correct (it is correct even taking into account that in and out will eventually overflow, as long as BSIZE is less than the largest integer that can be represented in a word). Shared-memory multiprocessors do not necessarily have strongly ordered memory. A change to memory by one processor is not necessarily available immediately to the other processors. When two changes to different memory locations are made by one processor, the other processors do not necessarily detect the changes in the order in which they were made because changes to memory do not happen immediately. First the changes are stored in store buffers that are not visible to the cache. The processor checks these store buffers to ensure that a program has a consistent view, but because store buffers are not visible to other processors, a write by one processor does not become visible until it is written to cache. The synchronization primitives (see Chapter 4, Programming With Synchronization Objects) use special instructions that flush the store buffers to cache. So, using locks around your shared data ensures memory consistency. When memory ordering is very relaxed, Example 9-5 has a problem because the consumer might see that in has been incremented by the producer before it sees the change to the corresponding buffer slot. This is called weak ordering because stores made by one processor can appear to happen out of order by another processor (memory, however, is always consistent from the same processor). To fix this, the code should use mutexes to flush the cache. The trend is toward relaxing memory order. Because of this, programmers are becoming increasingly careful to use locks around all global or shared data. As demonstrated by Example 9-5 and Example 9-6, locking is essential.
__label__pos
0.875676
{ "info": { "_postman_id": "f7126c23-2cb6-4509-b52b-5f78ea70b22e", "name": "FileCap API example", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "item": [ { "name": "Upload files", "request": { "method": "POST", "header": [], "body": { "mode": "formdata", "formdata": [ { "key": "APIKey", "value": "HKADASD68768768ASDASDASDAD", "description": "The FileCap server API key", "type": "text" }, { "key": "ids", "value": "263478632784632748237513", "description": "The ID of the transfer", "type": "text" }, { "key": "from", "value": "[email protected]", "description": "The email address of the sender", "type": "text" }, { "key": "subject", "value": "API Test", "description": "The subject of the transfer", "type": "text" }, { "key": "comment", "value": "This is a test", "description": "The comment/message for the transfer", "type": "text" }, { "key": "encryptMessage", "value": "true", "description": "Optional; The comment/message will be encrypted. At this moment only unformatted text is supported.", "type": "text", "disabled": true }, { "key": "rec0", "value": "[email protected]", "description": "A list of receivers of the transfer the first receiver would be rec0, second rec1 and the next rec2, rec3 etc.", "type": "text" }, { "key": "rec1", "value": "[email protected]", "description": "A list of receivers of the transfer the first receiver would be rec0, second rec1 and the next rec2, rec3 etc.", "type": "text", "disabled": true }, { "key": "storeDays_value", "value": "5", "description": "Optional; How long will the transfer stay on the FileCap server", "type": "text", "disabled": true }, { "key": "downloadLoadable_value", "value": "10", "description": "Optional; How many times can files be downloaded", "type": "text", "disabled": true }, { "key": "password", "value": "test1234", "description": "Optional; Password is mandatory when encryptMessage = true", "type": "text", "disabled": true }, { "key": "dontNotify", "value": "true", "description": "Optional; When true there will not be send an email from the FileCap server to the receiver. The 3th party system should handle this.", "type": "text", "disabled": true }, { "key": "file01", "value": "", "description": "A list of files in this transfer the first file would be file01, second file02 and the next file03, file04 etc.", "type": "file" }, { "key": "file02", "value": "", "description": "A list of files in this transfer the first file would be file01, second file02 and the next file03, file04 etc.", "type": "file", "disabled": true } ] }, "url": { "raw": "https://filecap.example.com/FileCap/process_upload.jsp", "protocol": "https", "host": [ "filecap", "example", "com" ], "path": [ "FileCap", "process_upload.jsp" ] }, "description": "process_upload.jsp can be used to upload files to the FileCap server.\nThe data that is being send needs to be in an multipart/form HTTP POST.\n\nThe result of this request can be true or false:\n- When the transfer was successful, the result will be true.\n- When the transfer was unsuccessful, the result will be false with an error message.\n\nThe following text can be in the error message:\n- VIRUS_FOUND - There is a virus found in the uploaded file. The transfer has been cancelled. \n- NO_RECIPIENT_GIVEN - You did not specify any recipients for the transfer. \n- FILETYPE_NOT_ALLOW - The filetype is not allowed, either because of a forbidden MIME type or forbidden file extension. \n- PASSWORD_MANDATORY_BUT_NOT_GIVEN - The administrator set the use of a password as mandatory, but none is given in the transfer options. \n- CANNOT_SEND_MAIL - The FileCap server was not able to send the email. Most commonly either the mail server was not configured correct, or the FileCap server is not authenticated to relay mail. \n- API_KEY_INVALID - The given API Key was invalid and cannot be used. \n- GENERAL_ERROR - There was an unknown error. Please check the server logs for the exception. If this error occurs you probably have a network / proxy issue" }, "response": [] }, { "name": "Send invite", "request": { "method": "POST", "header": [ { "key": "Content-Type", "name": "Content-Type", "type": "text", "value": "application/x-www-form-urlencoded" } ], "body": { "mode": "urlencoded", "urlencoded": [ { "key": "APIKey", "value": "HKADASD68768768ASDASDASDAD", "description": "The FileCap server API key", "type": "text" }, { "key": "id", "value": "iiiii26347863278463274823755", "description": "Invite id always needs to start with: iiiii", "type": "text" }, { "key": "senderEmail", "value": "[email protected]", "description": "Email address of the person who needs to receive the invite", "type": "text" }, { "key": "receiverEmail", "value": "[email protected]", "description": "Email address of the person who needs to receive the files. Normaly your own email address", "type": "text" }, { "key": "notify", "value": "true", "description": "Optional; When false there will not be send an email from the FileCap server. The 3th party system should handle this.", "type": "text", "disabled": true } ] }, "url": { "raw": "https://filecap.example.com/FileCap/invite.jsp", "protocol": "https", "host": [ "filecap", "example", "com" ], "path": [ "FileCap", "invite.jsp" ] }, "description": "The invite.jsp gives the ability to send FileCap invites to external users.\n\nThe result of this request can be true or false:\n- When the invite was successful, the result will be true.\n- When the invite was unsuccessful, the result will be false with an error message.\n\nThe following text can be in the error message:\n- CANNOT_SEND_MAIL - The mailserver is not able to process the mail. \n- CANNOT_ADD_INVITE_TO_DB - FileCap was not able to add the invite ID to the DB. \n- UNKNOWN_ERROR - An exception is raised. Please check the server logs for the full exception." }, "response": [] }, { "name": "Request mail plugin settings", "request": { "method": "POST", "header": [ { "key": "Content-Type", "name": "Content-Type", "type": "text", "value": "application/x-www-form-urlencoded" } ], "body": { "mode": "urlencoded", "urlencoded": [ { "key": "APIKey", "value": "HKADASD68768768ASDASDASDAD", "description": "The FileCap server API key", "type": "text" } ] }, "url": { "raw": "https://filecap.example.com/FileCap/mailPluginSettings.jsp", "protocol": "https", "host": [ "filecap", "example", "com" ], "path": [ "FileCap", "mailPluginSettings.jsp" ] }, "description": "mailPluginSettings.jsp can be used to request the FileCap server settings used by the plugins" }, "response": [] }, { "name": "Request password rules (detailed)", "request": { "method": "POST", "header": [ { "key": "Content-Type", "name": "Content-Type", "value": "application/json", "type": "text" } ], "body": { "mode": "raw", "raw": "{ \n\t\"apiKey\" : \"HKADASD68768768ASDASDASDAD\",\n\t\"lang\" : \"NL\"\n}" }, "url": { "raw": "https://filecap.example.com/FileCap/api/settings/getPasswordRules", "protocol": "https", "host": [ "filecap", "example", "com" ], "path": [ "FileCap", "api", "settings", "getPasswordRules" ] }, "description": "Request a detailed description of the password requirements set on the FileCap server" }, "response": [] }, { "name": "Request password rules (short)", "request": { "method": "POST", "header": [ { "key": "Content-Type", "name": "Content-Type", "value": "application/json", "type": "text" } ], "body": { "mode": "raw", "raw": "{ \n\t\"apiKey\" : \"HKADASD68768768ASDASDASDAD\"\n}" }, "url": { "raw": "https://filecap.example.com/FileCap/api/settings/getPasswordPolicy", "protocol": "https", "host": [ "filecap", "example", "com" ], "path": [ "FileCap", "api", "settings", "getPasswordPolicy" ] }, "description": "Request a short description of the password requirements set on the FileCap server." }, "response": [] }, { "name": "Check if a file may be send", "request": { "method": "POST", "header": [ { "key": "Content-Type", "name": "Content-Type", "value": "application/x-www-form-urlencoded", "type": "text" } ], "body": { "mode": "urlencoded", "urlencoded": [ { "key": "APIKey", "value": "HKADASD68768768ASDASDASDAD", "description": "The FileCap server API key", "type": "text" }, { "key": "filename", "value": "test.exe", "description": "The filename of the file that needs to be send", "type": "text" }, { "key": "sender", "value": "[email protected]", "description": "The email address of the sender", "type": "text" }, { "key": "mime", "value": "application/exe", "description": "The mime type of the filename that needs to be send.", "type": "text" } ] }, "url": { "raw": "https://filecap.example.com/FileCap/checkFile.jsp", "protocol": "https", "host": [ "filecap", "example", "com" ], "path": [ "FileCap", "checkFile.jsp" ] }, "description": "checkFile.jsp has the ability to verify before sending if a file is allowed to be send." }, "response": [] }, { "name": "Show files in a transfer", "request": { "method": "POST", "header": [ { "key": "Content-Type", "name": "Content-Type", "value": "application/x-www-form-urlencoded", "type": "text" } ], "body": { "mode": "urlencoded", "urlencoded": [ { "key": "APIKey", "value": "HKADASD68768768ASDASDASDAD", "description": "The FileCap server API key", "type": "text" }, { "key": "id", "value": "263478632784632748237513", "description": "The transfer ID", "type": "text" } ] }, "url": { "raw": "https://filecap.example.com/FileCap/checkTransfer.jsp", "protocol": "https", "host": [ "filecap", "example", "com" ], "path": [ "FileCap", "checkTransfer.jsp" ] } }, "response": [] } ], "event": [ { "listen": "prerequest", "script": { "id": "a1850f52-fcb3-4dac-aebd-d956f2372f30", "type": "text/javascript", "exec": [ "" ] } }, { "listen": "test", "script": { "id": "8330fac0-7be3-4537-9331-efc157139a01", "type": "text/javascript", "exec": [ "" ] } } ], "protocolProfileBehavior": {} }
__label__pos
0.890486
define( 'WPCACHEHOME', '/home2/karen/public_html/bestmathdegree.com/wp-content/plugins/wp-super-cache/' ); //Added by WP-Cache Manager Benefits of Studying Mathematics | Best Math Degree Benefits of Studying Mathematics What are the Benefits of Studying Math? Are there benefits in math? When some people reflect back on high school math classes, thought of reams of homework with a portion of the answers in the back of the books. They might recall lectures on theorems but weak explanations and minimal feedback. Teachers met the requirements of the curriculum, but many students were left frustrated with math as a whole. There are, however, some people who enjoyed the logic and reasoning in math classes. They completed the available courses like algebra, geometry and maybe pre-calculus with aspirations for a degree and career in math. It’s not until college when a whole mathematical world opens up. Courses now include computer science and statistics. Math skills in college recapture the interests of the previously disheartened. Why is Math Beautiful? Math is like a key to a treasure chest. Each bit of logic and reason it took to create the key is the answer to unlock a hidden truth. By taking math, you have the skills to think through many problems, find the solution, and make use of it in your work. Why is Math Important? Math teaches students to reason within the rules and law of mathematics. This reasoning can transfer into other fields as well. If you are in a job or project, you are presented with a problem. Rules and deadline are established for finding the solution or end product. Whatever the solution, it is found within the parameters of the rules that defined the job. Math demonstrates that rules don’t block the end results, but rather help to discover the solutions to the problems. Math skills are applicable in a number of careers like accounting and finance. Mathematicians in these professions are most likely the ones who can look back at their high school classes and appreciate these humble beginnings. Higher-level thinking abilities were developing during these simpler mathematical times. The benefits reaped from their math education help them succeed in life long after the pomp and circumstance of high school. Speak Your Mind *
__label__pos
0.998848
drupal-breakpoints-less Convert Drupal 8:s breakpoints (*.breakpoints.yml) to less @variables. Usage no npm install needed! <script type="module"> import drupalBreakpointsLess from 'https://cdn.skypack.dev/drupal-breakpoints-less'; </script> README Drupal-breakpoints-less Convert Drupal 8:s breakpoints (*.breakpoints.yml) to less @variables. Install npm install --save drupal-breakpoints-less What it does Converts this: theme.small: label: breakpoint-small mediaQuery: 'all and (max-width: 500px)' weight: 1 multipliers: - 1x theme.medium: label: breakpoint-medium mediaQuery: 'all and (max-width: 700px)' weight: 1 multipliers: - 1x into this: @breakpoint-small: ~"all and (max-width: 500px)"; @breakpoint-medium: ~"all and (max-width: 700px)"; section { margin: 3%; @media @breakpoint-small { width: 37%; } @media @breakpoint-small, @breakpoint-medium { width: 40%; } } Usage const drupalBreakpointsLess = require('drupal-breakpoints-less') drupalBreakpointsLess.read('./theme.breakpoints.yml') .pipe(drupalBreakpointsLess.write('./less/_breakpoints.less')) Usage with gulp const gulp = require('gulp') const rename = require('gulp-rename') const drupalBreakpointsLess = require('drupal-breakpoints-less') gulp.task('task', function () { return gulp.src('./breakpoints.yml') .pipe(drupalBreakpointsLess.ymlToLess()) .pipe(rename('_breakpoints.less')) .pipe(gulp.dest('./less/partials')) })
__label__pos
0.583609
Share/Like This Page Range, Median, Mean, and Mode Questions - All Grades Create printable tests and worksheets from Range, Median, Mean, and Mode questions. Select questions to add to a test using the checkbox above each question. Remember to click the add selected questions to a test button before moving to another page. The Range, Median, Mean, and Mode questions below are in the following grade levels: Grades: 3 4 5 6 7 8 9 10 11 12 1 2 3 4 ... 10 Grade 7 :: Range, Median, Mean, and Mode by tclave1 A scientist studied the number of eggs a species of bird lays each year. He found that most common number of eggs laid in a year is three. Which statistical measurement did the scientist find? 1. the mode of the number of eggs laid in a year 2. the range of the number of eggs laid in year 3. the median number of eggs laid in a year 4. the mean number of eggs laid in a year Grade 7 :: Range, Median, Mean, and Mode by Yung_n_Wanted Consider the list of golf scores: 71, 68, 72, 79, 80, 77, 84, 70, 92 What is a median, mean and range for the set? 1. median=77, mean=77, range=24 2. median=80, mean=78, range=22 3. median=81, mean=77, range=23 Grade 6 :: Range, Median, Mean, and Mode by bhall1113 Grade 6 :: Range, Median, Mean, and Mode by MegMarino 1 2 3 4 ... 10 You need to have at least 5 reputation to vote a question down. Learn How To Earn Badges.
__label__pos
0.999891
Euler–Lagrange equation From Wikipedia, the free encyclopedia   (Redirected from Euler-Lagrange equation) Jump to: navigation, search In calculus of variations, the Euler–Lagrange equation, Euler's equation,[1] or Lagrange's equation although the latter name is ambiguous (see disambiguation page), is a differential equation whose solutions are the functions for which a given functional is stationary. It was developed by Swiss mathematician Leonhard Euler and Italian mathematician Joseph-Louis Lagrange in the 1750s. Because a differentiable functional is stationary at its local maxima and minima, the Euler–Lagrange equation is useful for solving optimization problems in which, given some functional, one seeks the function minimizing (or maximizing) it. This is analogous to Fermat's theorem in calculus, stating that at any point where a differentiable function attains a local extremum, its derivative is zero. In Lagrangian mechanics, because of Hamilton's principle of stationary action, the evolution of a physical system is described by the solutions to the Euler–Lagrange equation for the action of the system. In classical mechanics, it is equivalent to Newton's laws of motion, but it has the advantage that it takes the same form in any system of generalized coordinates, and it is better suited to generalizations. In classical field theory there is an analogous equation to calculate the dynamics of a field. History[edit] The Euler–Lagrange equation was developed in the 1750s by Euler and Lagrange in connection with their studies of the tautochrone problem. This is the problem of determining a curve on which a weighted particle will fall to a fixed point in a fixed amount of time, independent of the starting point. Lagrange solved this problem in 1755 and sent the solution to Euler. Both further developed Lagrange's method and applied it to mechanics, which led to the formulation of Lagrangian mechanics. Their correspondence ultimately led to the calculus of variations, a term coined by Euler himself in 1766.[2] Statement[edit] The Euler–Lagrange equation is an equation satisfied by a function, q, of a real argument, t, which is a stationary point of the functional \displaystyle S(q) = \int_a^b L(t,q(t),q'(t))\, \mathrm{d}t where: • q is the function to be found: \begin{align} q \colon [a, b] \subset \mathbb{R} & \to X \\ t & \mapsto x = q(t) \end{align} such that q is differentiable, q(a) = xa, and q(b) = xb; • q′ is the derivative of q: \begin{align} q' \colon [a, b] & \to T_{q(t)}X \\ t & \mapsto v = q'(t) \end{align} TX being the tangent bundle of X defined by TX = \bigcup_{x \in X} \{ x \} \times T_{x}X  ; The Euler–Lagrange equation, then, is given by L_x(t,q(t),q'(t))-\frac{\mathrm{d}}{\mathrm{d}t}L_v(t,q(t),q'(t)) = 0. where Lx and Lv denote the partial derivatives of L with respect to the second and third arguments, respectively. If the dimension of the space X is greater than 1, this is a system of differential equations, one for each component: \frac{\partial L(t,q(t),q'(t))}{\partial x_i}-\frac{\mathrm{d}}{\mathrm{d}t}\frac{\partial L(t,q(t),q'(t))}{\partial v_i} = 0 \quad \text{for } i = 1, \dots, n. Examples[edit] A standard example is finding the real-valued function on the interval [a, b], such that f(a) = c and f(b) = d, the length of whose graph is as short as possible. The length of the graph of f is: \ell (f) = \int_{a}^{b} \sqrt{1+(f'(x))^2}\,\mathrm{d}x, the integrand function being L(x, y, y′) = 1 + y′ ² evaluated at (x, y, y′) = (x, f(x), f′(x)). The partial derivatives of L are: \frac{\partial L(x, y, y')}{\partial y'} = \frac{y'}{\sqrt{1 + y'^2}} \quad \text{and} \quad \frac{\partial L(x, y, y')}{\partial y} = 0. By substituting these into the Euler–Lagrange equation, we obtain \begin{align} \frac{\mathrm{d}}{\mathrm{d}x} \frac{f'(x)}{\sqrt{1 + (f'(x))^2}} &= 0 \\ \frac{f'(x)}{\sqrt{1 + (f'(x))^2}} &= C = \text{constant} \\ \Rightarrow f'(x)&= \frac{C}{\sqrt{1-C^2}} := A \\ \Rightarrow f(x) &= Ax + B \end{align} that is, the function must have constant first derivative, and thus its graph is a straight line. Classical mechanics[edit] Basic method[edit] To find the equations of motions for a given system (whose potential energy is time-independent), one only has to follow these steps: • From the kinetic energy T, and the potential energy V, compute the Lagrangian L = T - V. • Compute \frac{\partial L}{\partial q}. • Compute \frac{\partial L}{\partial \dot{q}} and from it, \frac{\mathrm{d}}{\mathrm{d}t}\frac{\partial L}{\partial \dot{q}}. It is important that \dot{q} be treated as a complete variable in its own right, and not as a derivative. • Equate \frac{\partial L}{\partial q} = \frac{\mathrm{d}}{\mathrm{d}t}\frac{\partial L}{\partial \dot{q}}. This is the Euler–Lagrange equation. • Solve the differential equation obtained in the preceding step. At this point, \dot{q} is treated "normally". Note that the above might be a system of equations and not simply one equation. Particle in a conservative force field[edit] The motion of a single particle in a conservative force field (for example, the gravitational force) can be determined by requiring the action to be stationary, by Hamilton's principle. The action for this system is S = \int_{t_0}^{t_1} L(t, \mathbf{x}(t), \mathbf{\dot{x}}(t))\,\mathrm{d}t where x(t) is the position of the particle at time t. The dot above is Newton's notation for the time derivative: thus (t) is the particle velocity, v(t). In the equation above, L is the Lagrangian (the kinetic energy minus the potential energy): L(t, \mathbf{x}, \mathbf{v}) = \frac{1}{2}m \sum_{i=1} ^{3} v_i^2 - U(\mathbf{x}), where: • m is the mass of the particle (assumed to be constant in classical physics); • vi is the i-th component of the vector v in a Cartesian coordinate system (the same notation will be used for other vectors); • U is the potential of the conservative force. In this case, the Lagrangian does not vary with its first argument t. (By Noether's theorem, such symmetries of the system correspond to conservation laws. In particular, the invariance of the Lagrangian with respect to time implies the conservation of energy.) By partial differentiation of the above Lagrangian, we find: \frac{\partial L(t,\mathbf{x},\mathbf{v})}{\partial x_i} = -\frac{\partial U(\mathbf{x})}{\partial x_i} = F_i (\mathbf{x})\quad \text{and} \quad \frac{\partial L(t,\mathbf{x},\mathbf{v})}{\partial v_i} = m v_i = p_i, where the force is F = −U (the negative gradient of the potential, by definition of conservative force), and p is the momentum. By substituting these into the Euler–Lagrange equation, we obtain a system of second-order differential equations for the coordinates on the particle's trajectory, F_i(\mathbf{x}(t)) = \frac{\mathrm d}{\mathrm{d}t} m \dot{x}_i(t) = m \ddot{x}_i(t), which can be solved on the interval [t0, t1], given the boundary values xi(t0) and xi(t1). In vector notation, this system reads \mathbf{F}(\mathbf{x}(t)) = m\mathbf{\ddot x}(t) or, using the momentum, \mathbf{F} = \frac {\mathrm{d}\mathbf{p}} {\mathrm{d}t} which is Newton's second law. Variations for several functions, several variables, and higher derivatives[edit] Single function of single variable with higher derivatives[edit] The stationary values of the functional I[f] = \int_{x_0}^{x_1} \mathcal{L}(x, f, f', f'', \dots, f^{(n)})~\mathrm{d}x ~;~~ f' := \cfrac{\mathrm{d}f}{\mathrm{d}x}, ~f'' := \cfrac{\mathrm{d}^2f}{\mathrm{d}x^2}, ~ f^{(n)} := \cfrac{\mathrm{d}^nf}{\mathrm{d}x^n} can be obtained from the Euler–Lagrange equation[3] \cfrac{\partial \mathcal{L}}{\partial f} - \cfrac{\mathrm{d}}{\mathrm{d} x}\left(\cfrac{\partial \mathcal{L}}{\partial f'}\right) + \cfrac{\mathrm{d}^2}{\mathrm{d} x^2}\left(\cfrac{\partial \mathcal{L}}{\partial f''}\right) - \dots + (-1)^n \cfrac{\mathrm{d}^n}{\mathrm{d} x^n}\left(\cfrac{\partial \mathcal{L}}{\partial f^{(n)}}\right) = 0 under fixed boundary conditions for the function itself as well as for the first n-1 derivatives (i.e. for all f^{(i)}, i \in \{0, ..., n-1\}). The endpoint values of the highest derivative f^{(n)} remain flexible. Several functions of one variable[edit] If the problem involves finding several functions (f_1, f_2, \dots, f_n) of a single independent variable (x) that define an extremum of the functional I[f_1,f_2, \dots, f_n] = \int_{x_0}^{x_1} \mathcal{L}(x, f_1, f_2, \dots, f_n, f_1', f_2', \dots, f_n')~\mathrm{d}x ~;~~ f_i' := \cfrac{\mathrm{d}f_i}{\mathrm{d}x} then the corresponding Euler–Lagrange equations are[4] \begin{align} \cfrac{\partial \mathcal{L}}{\partial f_i} - \cfrac{\mathrm{d}}{\mathrm{d}x}\left(\cfrac{\partial \mathcal{L}}{\partial f_i'}\right) = 0 \end{align} Single function of several variables[edit] A multi-dimensional generalization comes from considering a function on n variables. If Ω is some surface, then I[f] = \int_{\Omega} \mathcal{L}(x_1, \dots , x_n, f, f_{x_1}, \dots , f_{x_n})\, \mathrm{d}\mathbf{x}\,\! ~;~~ f_{x_i} := \cfrac{\partial f}{\partial x_i} is extremized only if f satisfies the partial differential equation \frac{\partial \mathcal{L}}{\partial f} - \sum_{i=1}^{n} \frac{\partial}{\partial x_i} \frac{\partial \mathcal{L}}{\partial f_{x_i}} = 0. \,\! When n = 2 and \mathcal{L} is the energy functional, this leads to the soap-film minimal surface problem. Several functions of several variables[edit] If there are several unknown functions to be determined and several variables such that I[f_1,f_2,\dots,f_m] = \int_{\Omega} \mathcal{L}(x_1, \dots , x_n, f_1, \dots, f_m, f_{1,1}, \dots , f_{1,n}, \dots, f_{m,1}, \dots, f_{m,n}) \, \mathrm{d}\mathbf{x}\,\! ~;~~ f_{j,i} := \cfrac{\partial f_j}{\partial x_i} the system of Euler–Lagrange equations is[3] \begin{align} \frac{\partial \mathcal{L}}{\partial f_1} - \sum_{i=1}^{n} \frac{\mathrm{d}}{\mathrm{d}x_i} \frac{\partial \mathcal{L}}{\partial f_{1,i}} &= 0 \\ \frac{\partial \mathcal{L}}{\partial f_2} - \sum_{i=1}^{n} \frac{\mathrm{d}}{\mathrm{d}x_i} \frac{\partial \mathcal{L}}{\partial f_{2,i}} &= 0 \\ \vdots \qquad \vdots \qquad &\quad \vdots \\ \frac{\partial \mathcal{L}}{\partial f_j} - \sum_{i=1}^{n} \frac{\mathrm{d}}{\mathrm{d}x_i} \frac{\partial \mathcal{L}}{\partial f_{j,i}} &= 0. \end{align} Single function of two variables with higher derivatives[edit] If there is a single unknown function f to be determined that is dependent on two variables x1 and x2 and if the functional depends on higher derivatives of f up to n-th order such that \begin{align} I[f] & = \int_{\Omega} \mathcal{L}(x_1, x_2, f, f_{,1}, f_{,2}, f_{,11}, f_{,12}, f_{,22}, \dots, f_{,22\dots 2})\, \mathrm{d}\mathbf{x} \\ & \qquad \quad f_{,i} := \cfrac{\partial f}{\partial x_i} \; , \quad f_{,ij} := \cfrac{\partial^2 f}{\partial x_i\partial x_j} \; , \;\; \dots \end{align} then the Euler–Lagrange equation is[3] \begin{align} \frac{\partial \mathcal{L}}{\partial f} & - \frac{\partial}{\partial x_1}\left(\frac{\partial \mathcal{L}}{\partial f_{,1}}\right) - \frac{\partial}{\partial x_2}\left(\frac{\partial \mathcal{L}}{\partial f_{,2}}\right) + \frac{\partial^2}{\partial x_1^2}\left(\frac{\partial \mathcal{L}}{\partial f_{,11}}\right) + \frac{\partial^2}{\partial x_1\partial x_2}\left(\frac{\partial \mathcal{L}}{\partial f_{,12}}\right) + \frac{\partial^2}{\partial x_2^2}\left(\frac{\partial \mathcal{L}}{\partial f_{,22}}\right) \\ & - \dots + (-1)^n \frac{\partial^n}{\partial x_2^n}\left(\frac{\partial \mathcal{L}}{\partial f_{,22\dots 2}}\right) = 0 \end{align} which can be represented shortly as: \frac{\partial \mathcal{L}}{\partial f} +\sum_{i=1}^n (-1)^i \frac{\partial^i}{\partial x_{\mu_{1}}\dots \partial x_{\mu_{i}}} \left( \frac{\partial \mathcal{L} }{\partial f_{,\mu_1\dots\mu_i}}\right)=0 where \mu_1 \dots \mu_i are indices that span the number of variables, that is they go from 1 to 2. Here summation over the \mu_1 \dots \mu_i indices is implied according to Einstein notation. Several functions of several variables with higher derivatives[edit] If there is are p unknown functions fi to be determined that are dependent on m variables x1 ... xm and if the functional depends on higher derivatives of the fi up to n-th order such that \begin{align} I[f_1,\ldots,f_m] & = \int_{\Omega} \mathcal{L}(x_1, \ldots, x_m; f_1,\ldots,f_p; f_{1,1},\ldots, f_{p,m}; f_{1,11},\ldots, f_{p,mm};\ldots f_{p,m\ldots m})\, \mathrm{d}\mathbf{x} \\ & \qquad \quad f_{i,\mu} := \cfrac{\partial f_i}{\partial x_\mu} \; , \quad f_{i,\mu_1\mu_2} := \cfrac{\partial^2 f_i}{\partial x_{\mu_1}\partial x_{\mu_1}} \; , \;\; \dots \end{align} where \mu_1 \dots \mu_j are indices that span the number of variables, that is they go from 1 to m. Then the Euler–Lagrange equation is \frac{\partial \mathcal{L}}{\partial f_i} +\sum_{j=1}^n (-1)^j \frac{\partial^j}{\partial x_{\mu_{1}}\dots \partial x_{\mu_{j}}} \left( \frac{\partial \mathcal{L} }{\partial f_{i,\mu_1\dots\mu_j}}\right)=0 where summation over the \mu_1 \dots \mu_j is implied according to Einstein notation. This can be expressed more compactly as \sum_{j=0}^n (-1)^j \partial_{ \mu_{1}\ldots \mu_{j} }^j \left( \frac{\partial \mathcal{L} }{\partial f_{i,\mu_1\dots\mu_j}}\right)=0 See also[edit] Notes[edit] 1. ^ Fox, Charles (1987). An introduction to the calculus of variations. Courier Dover Publications. ISBN 978-0-486-65499-7.  2. ^ A short biography of Lagrange 3. ^ a b c Courant, R. and Hilbert, D., 1953, Methods of Mathematical Physics: Vol I, Interscience Publishers, New York. 4. ^ Weinstock, R., 1952, Calculus of Variations With Applications to Physics and Engineering, McGraw-Hill Book Company, New York. References[edit]
__label__pos
0.999992
2 I would like to print out the lists and tasks that I maintain in the Reminders app. I can copy the text or take screenshots and paste them to a program like Word, but… Is there an easier approach? 2 You can achieve this using AppleScript on your Mac. Press ⌘ cmd space and enter Script Editor. Create a new script with the following code in it: set _body to "" tell application "Reminders" set AppleScript's text item delimiters to "\n" set _body to (name of reminders in list "Tasks" whose completed is false) as string end tell set _output to "Macintosh HD:Users:YourName:Desktop:List.txt" try set _reference to open for access file _output with write permission write _body to _reference close access _reference on error try close access file _output end try end try Replace Tasks with the name of the list you want to print, Macintosh HD with the name of your startup drive, and YourName with your username. This will place a file named List.txt on your desktop with all those reminders ready to print. 0 On the iPhone/iPad, CalPrint (iPad) does this You must log in to answer this question. Not the answer you're looking for? Browse other questions tagged .
__label__pos
0.894651
Centralize version information [linpy.git] / examples / README.rst 1 2 Examples 3 ======== 4 5 This directory contains LinPy examples programs. 6 7 8 Running Examples 9 ---------------- 10 11 To run the individual examples one needs to have Python version 3.4 or above 12 installed and LinPy must be in your ``PYTHONPATH`` environment variable. Most 13 examples can be run from the command line ``python3`` and the name of the 14 example:: 15 16 vivien@rochefort:~/linpy/examples$ export PYTHONPATH=$PWD/..:$PYTHONPATH 17 vivien@rochefort:~/linpy/examples$ python3 squares.py 18 19 Note: on most systems, the current directory is searched by Python 20 automatically, so ``python3 examples/squares.py`` works from the LinPy root 21 directory, however there are systems (Ubuntu Intrepid) where this doesn't work 22 by default, unless you put ``PYTHONPATH=.`` into your .bashrc for example.
__label__pos
0.986154
Search Images Maps Play YouTube News Gmail Drive More » Sign in Screen reader users: click this link for accessible mode. Accessible mode has the same essential features but works better with your reader. Patents 1. Advanced Patent Search Publication numberUS4571679 A Publication typeGrant Application numberUS 06/529,465 Publication dateFeb 18, 1986 Filing dateSep 6, 1983 Priority dateSep 6, 1983 Fee statusLapsed Publication number06529465, 529465, US 4571679 A, US 4571679A, US-A-4571679, US4571679 A, US4571679A InventorsWilliam R. Russell, G. Russell executor Samuel Original AssigneeThe United States Of America As Represented By The Secretary Of The Navy Export CitationBiBTeX, EndNote, RefMan External Links: USPTO, USPTO Assignment, Espacenet Fault tree data array US 4571679 A Abstract A fault tree data array converts the logic of a fault tree into software bysing a data base technique. Each array element of a data array contains a decision or termination of the fault tree, and a relative exponential addressing expression provides the data elements with a unique position in the array. The next position in the data array to be examined is calculated by the relative exponential addressing expressions. For unsymmetrical fault trees on additional data array is generated to provide a sequential list of tests to be examined until a fault is found. Then the relative exponential addressing technique is used. The result is a more compact method of storing data in computer memory, hence providing an efficient method for implementing fault trees into software. Images(3) Previous page Next page Claims(1) What is claimed is: 1. A method for use in computer controlled detection and indication of a malfunction in a system, said method comprising the steps of: providing a plural level fault tree wherein alternative true and false decisions are arranged as information nodes of a data array to be examined in a sequence to lead to a conclusion; examining nodes in a predetermined first path for true (T) or false (F) status; examining subsequent nodes in accordance with the expressions A(T)n+1 =An +2L for true results A(F)n+1 =An +2(2L) for false results where A=node number, L=tree level, and n=present node being examined, until a conclusion is reached. Description BACKGROUND OF THE INVENTION 1. Field of the Invention The present invention relates to computer controlled malfunction detection and indication processes, and more particularly to a fault tree data array for converting the logic of a fault tree into software by using data base techniques. 2. Description of Prior Art The process of fault isolation either for maintenance purposes or for reconfiguration depends on a logical analysis of the system and the results of test performed on the system. A fault tree is a group of decision nodes that are logically sequenced to arrive at a conclusion. For each decision there can be only one of two possible outcomes and for each succeeding decision there can be only two additional outcomes. What is desired is a method for efficiently converting the logic of a fault tree into software for computer control of the fault isolation process. SUMMARY OF THE INVENTION Accordingly, the present invention provides a fault tree data array for converting the logic of a fault tree into software by using data base techniques. Each array element of a data array contains a decision or termination of the fault tree, and a relative exponential addressing expression provides the data elements with a unique position in the array. The next position in the data array to be examined is calculated by the relative exponential addressing expression. For an unsymmetrical fault tree an additional data array is generated to provide a sequential list of tests to be examined until a fault is found. Then the relative exponential addressing technique is used. The result is a more compact method of storing data in computer memory, hence, providing an efficient method of implementing fault trees into software. Therefore, it is an object of the present invention to provide a fault tree data array for converting more efficiently the logic of a fault tree into software. Other objects, advantages and novel features of the present invention will be apparent from the following detailed description when read in conjunction with the appended claims and attached drawing. BRIEF DESCRIPTION OF THE DRAWING FIG. 1 is a schematic view of a symmetrical decision tree. FIG. 2 is a schematic view of an asymmetrical fault tree. FIG. 3 is a software flow chart for the fault tree of FIG. 2. DESCRIPTION OF THE PREFERRED EMBODIMENT A fault tree that has two possible outcomes for each decision element is shown in FIG. 1 to go from decision 1 to decision 2 the outcome must be true; conversely to get from decision 1 to decision 3 the outcome must be false. If each decision is considered to be a node and the tree level to be the number of previous decision made, then a mathematical description for moving through the tree can be expressed as follows: for true results A(T)n+1 =An +2L, and (1) for false results A(F)n+1 =An +2 (2L), (2) where A=node number, L=tree level, and n=present node being analyzed. Using equations (1) and (2) data can be generated for a software program that exactly depicts the logic of a fault tree. This process is referred to as relative exponential addressing. In this process equations (1) and (2) provide a method to assign a unique address scheme to a data array. Therefore, each array element contains a decision or termination and equations (1) and (2) provide the data elements with a unique position in the array. Depending upon the outcome of the present decision being considered, the next position in the data array to be examined will be calculated by equations (1) or (2). For a typical fault tree as shown in FIG. 2 the data contained in each decision diamond would be (a) the result of a test made on the system under test, or (b) a termination point which is a message containing the necessary information required to identify the faulty component. As shown most fault trees are not as symmetrical as that shown in FIG. 1. The result is that several data elements of the data array do not contain any data, wasting computer memory. This problem is solved by breaking the fault tree into several smaller trees where each branch is more condensed. As shown the left column of decisions contains the tests that perform an overall check of the system, known as a "Go Path". The "Go Path " is a string of logic elements which, if followed through for a system without a fault, ultimately yields a "System OK" conclusion. Using the concept of exponential addressing with "Go Path" an additional data array is generated. This array provides a sequential list of tests that are to be examined until a fault is found, at which time the exponential addressing technique is employed. The resulting data arrays depecting the fault tree of FIG. 2 is shown in Tables I and II: TABLE I______________________________________Base Address 0 Data Content SubordinateRelative Results of Array TerminationAddress Test No. Address Message Address______________________________________1 1 -- --2 -- Base 1 --3 2 -- --4 -- -- T35 3 -- --6 -- Base 2 --7 4 -- --8 -- -- T89 -- -- System OK______________________________________ TABLE II______________________________________Subordinate Data Arrays Data ContentBase Relative Result of TerminationAddress Address Test No. Message Address______________________________________Base 1 1 5 -- 2 -- T1 3 -- T2Base 2 1 6 -- 2 7 -- 3 8 -- 4 -- T7 5 -- T5 6 -- T6 7 -- T4______________________________________ A typical software program for expontential addressing with "Go Path" is shown in FIG. 3 in the form of a flow chart. This program is contained in the computer controlled malfunction detection and indication system to interpret the data and isolate the fault. Thus, the present invention provides a fault tree data array which provides a more efficient use of computer and computer memory by using a relative exponential addressing technique. Patent Citations Cited PatentFiling datePublication dateApplicantTitle US4353298 *Oct 19, 1979Oct 12, 1982International Business Machines CorporationPartial line turnaround for printers US4355360 *Apr 15, 1980Oct 19, 1982Nissan Motor Company, LimitedMethod for program control of components of an automotive vehicle US4468728 *Jun 25, 1981Aug 28, 1984At&T Bell LaboratoriesData structure and search method for a data base management system Referenced by Citing PatentFiling datePublication dateApplicantTitle US4774657 *Jun 6, 1986Sep 27, 1988International Business Machines CorporationIndex key range estimator US4870575 *Oct 1, 1987Sep 26, 1989Itt CorporationSystem integrated fault-tree analysis methods (SIFTAN) US5224209 *Apr 23, 1986Jun 29, 1993Hitachi, Ltd.System for choosing between operation modes in a data processing system by interacting with a displayed a multinodal hierarchal figure US5230048 *Feb 15, 1991Jul 20, 1993Wang Laboratories, Inc.Data processing system with tree and list data structure US5369756 *Jan 18, 1991Nov 29, 1994Hitachi, Ltd.Fault tree displaying method and process diagnosis support system US5418942 *Jul 6, 1989May 23, 1995Krawchuk; Kenneth V.System and method for storing and managing information US5564119 *Apr 17, 1995Oct 8, 1996Krawchuk; Kenneth V.System and method for storing and managing information US5960437 *Oct 7, 1996Sep 28, 1999Krawchuk; Kenneth V.System and method for storing and managing information US6532552 *Sep 9, 1999Mar 11, 2003International Business Machines CorporationMethod and system for performing problem determination procedures in hierarchically organized computer systems US7574411 *Apr 29, 2004Aug 11, 2009Nokia CorporationLow memory decision tree US20040267785 *Apr 29, 2004Dec 30, 2004Nokia CorporationLow memory decision tree US20070250297 *Sep 1, 2005Oct 25, 2007The United States Of America As Represented By The Secretary Of The NavyMethod for reducing hazards EP0428134A2 *Nov 13, 1990May 22, 1991Komatsu Ltd.Fault diagnosing apparatus and method EP0428135A2 *Nov 13, 1990May 22, 1991Komatsu Ltd.Fault diagnosing apparatus and method Classifications U.S. Classification714/25 International ClassificationG06F11/00 Cooperative ClassificationG06F11/00 European ClassificationG06F11/00 Legal Events DateCodeEventDescription Sep 6, 1983ASAssignment Owner name: UNITED STATES OF AMERICA AS REPRESENTED BY THE SEC Free format text: ASSIGNMENT OF ASSIGNORS INTEREST.;ASSIGNORS:RUSSELL, WILLIAM R.;RUSSELL, SAMUEL G.;REEL/FRAME:004171/0416 Effective date: 19830720 Mar 2, 1989FPAYFee payment Year of fee payment: 4 Sep 21, 1993REMIMaintenance fee reminder mailed Nov 10, 1993REMIMaintenance fee reminder mailed Feb 20, 1994LAPSLapse for failure to pay maintenance fees May 3, 1994FPExpired due to failure to pay maintenance fee Effective date: 19930220
__label__pos
0.711018
TOC The community is working on translating this tutorial into Dutch, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info". Reguliere Expressies (Regex): Regex Modifiers In previous articles, we talked about what Regular Expressions are and how to use them in C# for matching, replacing and so on. At this point, you should already have realized how powerful Regular Expressions are and how they can help you in a lot of situations, but they get even more powerful when you know about the possible modifiers. When working with Regular Expressions, you can use one or several modifiers to control the behavior of the matching engine. For instance, a Regex matching process is usually case-sensitive, meaning that "a" is not the same as "A". However, in a lot of situations, you want your match to be case-insensitive so that the character "a" is just a letter, no matter if its in lowercase or UPPERCASE. Simply supply the RegexOptions.IgnoreCase option when creating the Regex instance and your match will be case-insensitive. You'll find all the available modifiers in the RegexOptions enumeration. Several of them are common among all programming languages supporting the Regular Expression standard, while others are specific to the .NET framework. As you'll see in the first example, Regex modifiers are usually specified as the second parameter when creating the Regex instance. You can specify more than one option by separating them with a pipe (|) character, like this: new Regex("[a-z]+", RegexOptions.IgnoreCase | RegexOptions.Singleline); Now let's run through all the modifiers to give you an idea of how they work and what they can do for you. RegexOptions.IgnoreCase This will likely be one of your most used modifiers. As described above, it will change your Regular Expressions from being case-sensitive to being case-insensitive. This makes a big difference, as you can see in this example: public void IgnoreCaseModifier() { string testString = "Hello World"; string regexString = @"^[a-z\s]+$"; Regex caseSensitiveRegex = new Regex(regexString); Regex caseInsensitiveRegex = new Regex(regexString, RegexOptions.IgnoreCase); Console.WriteLine("Case-sensitive match: " + caseSensitiveRegex.IsMatch(testString)); Console.WriteLine("Case-insensitive match: " + caseInsensitiveRegex.IsMatch(testString)); } We specify a simple Regex, designed to match only letters (a-z) and whitespaces. We use it to create to Regex instances: One without the RegexOptions.IgnoreCase modifier and one with it, and then we try to match the same test string, which consists of lowercase and UPPERCASE characters and a single space. The output will, probably not surprisingly, look like this: Case-sensitive match: False Case-insensitive match: True RegexOptions.Singleline In Regular Expressions, the dot (.) is basically a catch-all character. However, by default, it doesn't match linebreaks, meaning that you can use the dot to match an entire line of letters, numbers, special characters and so on, but the match will end as soon as a linebreak is encountered. However, if you supply the Singleline modifier, the dot will match linebreaks as well. Allow me to demonstrate the difference: public void SinglelineModifier() { string testString = @"Hello World This string contains several lines"; string regexString = ".*"; Regex normalRegex = new Regex(regexString); Regex singlelineRegex = new Regex(regexString, RegexOptions.Singleline); Console.WriteLine("Normal regex: " + normalRegex.Match(testString).Value); Console.WriteLine("Singleline regex: " + singlelineRegex.Match(testString).Value); } The output will look like this: Normal regex: Hello World Singleline regex: Hello World This string contains several lines RegexOptions.Multiline As we have talked about in this chapter, Regular Expressions consists of many different characters which have special purposes. Another example of this is these two characters: ^ and $. We actually used them in the case-sensitivity example above, to match the beginning and end of a string. However, by supplying the Multiline modifier, you can change this behavior from matching the beginning/end of a string to match the beginning/end of lines. This is very useful when you want to deal individually with the lines matched. Here's an example: public void MultilineModifier() { string testString = @"Hello World This string contains several lines"; string regexString = "^.*$"; Regex singlelineRegex = new Regex(regexString, RegexOptions.Singleline); Regex multilineRegex = new Regex(regexString, RegexOptions.Multiline); Console.WriteLine("Singleline regex: " + singlelineRegex.Match(testString).Value); Console.WriteLine("Multiline regex:"); MatchCollection matches = multilineRegex.Matches(testString); for(int i = 0; i < matches.Count; i++) Console.WriteLine("Line " + i + ": " + matches[i].Value.Trim()); } Notice how I use several a test string consisting of several lines and then use the matching mechanisms differently: With singlelineRegex, we treat the entire test string as one line, even though it contains linebreaks, as we discussed above. When using the multilineRegex we treat the test string as multiple lines, each resulting in a match. We can use the Regex.Matches() method to catch each line and work with it - in this case, we simply output it to the Console. RegexOptions.Compiled While Regular Expressions are generally pretty fast, they can slow things down a bit if they are very complex and executed many times, e.g. in a loop. For these situations, you may want to use the RegexOptions.Compiled modifier, which will allow the framework to compile the Regex into an assembly. This costs a little extra time when you create it, compared to just instantiating a Regex object normally, but it will make all subsequent Regex operations (matches etc.) faster: Regex compiledRegex = new Regex("[a-z]*", RegexOptions.Compiled); More modifiers The above modifiers are the most interesting ones, but there's a few more, which we'll just go through a bit faster: • RegexOptions.CultureInvariant: With this modifier, cultural differences in language is ignored. This is mostly relevant if your application works with multiple non-English languages. • RegexOptions.ECMAScript: Changes the Regex variant used from the .NET specific version to the ECMAScript standard. This should rarely be necessary. • RegexOptions.ExplicitCapture: Normally, a set of parentheses in a Regex acts as a capturing group, allowing you to access each captured value through an index. If you specify the ExplicitCapture modifier, this behavior is changed so that only named groups are captured and stored for later retrieval. • RegexOptions.IgnorePatternWhitespace: When this modifier is enabled, whitespace in the Regex is ignored and you are even allowed to include comments, prefixed with the hash (#) char. • RegexOptions.RightToLeft: Changes matching to start from right and move left, instead of the default from left to right. Summary As you can see, there are many important Regex modifiers that you should know about to take full advantage of Regular Expressions, to support as many use-cases as possible. This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!
__label__pos
0.896952
【1.1】c语言的类与对象 一、类的概念及基本语法 一个类别、数据类型——万物皆对象 • 属性:亮度、电量、运营商…… • 方法:开关机、调整亮度、发送短信…… 共同特点(变量)→构成数据结构 归纳行为(函数)→操作数据结构(抽象) 定义类 看上去像“带函数的结构体” 使用类 int main( ) { int w,h; Rectangle r; // r是一个对象 cin » w » h; r.Init( w,h); cout « r.Area() « endl « r. Perimeter(); return 0; } Rectangle r1, r2; 对象名.成员名 r1.w = 5; r2.Init(5,4); 指针->成员名 Rectangle * p1=&r1, p2=&r2; p1->w = 5; p2->Init(5,4); 引用名.成员名 CRectangle & rr = r2; rr.w = 5; rr.Init(5,4); 声明、定义分离 class Rectangle{ public: int w,h; int Area(); //成员函数仅在此处声明 int Perimeter() ; void Init( int w_,int h_ ); }; int Rectangle::Area() { return w * h; } int Rectangle::Perimeter() { return 2 * ( w + h); } void Rectangle::Init( int w_,int h_ ) { w = w_; h = h_; } 访问权限 二、默认函数——构造、析构、复制构造、赋值与取址 三、特殊成员——this指针 并非对象的成员,是常量指针 每个对象可以使用 this 指针访问自己的地址 非 static 成员函数调用时,this 指针为隐式参数 用途:防止自赋值、返回以连续调用 四、函数模板与类模板 4.1 函数模板 实际问题中的需要: 对不同类型数据可用的排序函数 sort template<class T> return-type sort(...T...) 一个实际的输出函数: template<class T> void print( const T array[], int size){ int i; for ( i =0; i<size; i++) cout<<array[i]; return; } int a[10]; print(a,10); 一个实际的输出函数: template<class T1, class T2> void print(T1 arg1, T2 arg2,string s, int k) { cout<<arg1<<s<<arg2<<k<<endl; return; } 4.2 类模板 为了多快好省地定义出一批相似的类,可以定义类模板,然 后由类模板生成不同的类 数组是一种常见的数据类型,元素可以是: • 整数 • 字符串 • …… 类模板:在定义类的时候给它一个/多个参数,这个/些参数 表示不同的数据类型。在调用类模板时,指定参数,由编 译系统根据参数提供的数据类型自动产生相应的模板类。 类模板的定义: template <class T>//类模板的首部,声明类模板的参数 class Carray{ T *ptrElement; int size; public: Carray(int length); ~ Carray(); int len(); void setElement(T arg, int index); T getElement(int index); }; 使用类模板声明对象: Carray<int> arrayInt(50), *ptrArrayInt; //创建一个元素类型为int的Carray模板类,并声明该模板类 的一个对象、以及一个指针。 不同模板参数产生的模板类,不是同一个类 参考资料 北京大学 《数据结构与算法》 张铭、赵海燕、宋国杰、黄骏、邹磊、陈斌、王腾蛟 个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: [email protected]
__label__pos
0.66303
blob: c909ddd6a83baa0093294e5a5f56554cf67133e6 [file] [log] [blame] // Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @available(added=7) library fuchsia.hardware.radar; using zx; /// Arbitrary limit on the number of VMOs in one call to `RegisterVmos()` or /// `UnregisterVmos()`; enough for ten seconds of radar data for the existing /// driver. const VMO_VECTOR_MAX_COUNT uint32 = 300; type StatusCode = strict enum { /// An unspecified error occurred (generally should not be used). UNSPECIFIED = 0; /// The request completed successfully. SUCCESS = 1; /// `Connect()` was called but the driver is busy handling another client. /// The other client will have to close its channel for the driver to become /// available again. ALREADY_BOUND = 2; /// `Connect()` encountered an error trying to bind to the provided server /// channel. BIND_ERROR = 3; /// The vectors passed to `RegisterVmos()` did not have the same size. INVALID_ARGS = 4; /// A VMO handle was invalid. VMO_BAD_HANDLE = 5; /// A VMO was already registered with this ID. VMO_ALREADY_REGISTERED = 6; /// No registered VMO was found for the given ID. VMO_NOT_FOUND = 7; /// A client VMO could not be written to or mapped due to insufficient /// permissions. VMO_ACCESS_DENIED = 8; /// A client VMO was smaller than the burst size (see `GetBurstSize()`). VMO_TOO_SMALL = 9; /// A burst was received, but no unlocked VMOs are available. OUT_OF_VMOS = 10; /// A burst was not received within the expected window. SENSOR_TIMEOUT = 11; /// An unspecified driver or sensor error was encountered. SENSOR_ERROR = 12; }; type Burst = struct { vmo_id uint32; timestamp zx.time; }; protocol RadarBurstReader { /// Returns the size in bytes of each burst reported by this driver. Clients /// should use this size to create VMOs to be registered by the driver. /// /// - response `burst_size` the size of each radar burst in bytes. GetBurstSize() -> (struct { burst_size uint32; }); /// Registers the VMOs for future use and associates them with vmo_ids, /// which can be used with `UnregisterVmos()` and `OnBurst()`. vmos will be /// mapped by the driver using `ZX_VM_PERM_WRITE`. The client should only /// read registered VMOs that are sent via `OnBurst()`. The size of vmo is /// assumed to be at least the burst size, and the sizes of `vmo_ids` and /// `vmos` must be the same. /// /// + request `vmo_ids` the ID numbers to associate with each VMO. /// + request `vmos` the VMO handles corresponding to each ID. /// * error one of the following `StatusCode` values: /// * `INVALID_ARGS`: `vmo_ids` and `vmos` were of different sizes. /// * `VMO_BAD_HANDLE`: A handle in `vmos` was invalid. /// * `VMO_ALREADY_REGISTERED`: An ID in `vmo_ids` was already /// * registered. /// * `VMO_ACCESS_DENIED`: A VMO in `vmos` could not be mapped due to /// * insufficient permissions. /// * `VMO_TOO_SMALL`: A VMO in `vmos` was smaller than the burst size. RegisterVmos(resource struct { vmo_ids vector<uint32>:VMO_VECTOR_MAX_COUNT; vmos vector<zx.handle:VMO>:VMO_VECTOR_MAX_COUNT; }) -> () error StatusCode; /// Removes the associations with the given VMO IDs and returns the VMOs to /// the client. The driver will not send any more `OnBurst()` events with /// these VMO IDs after replying, however the client may still receive /// bursts with these IDs if they were in flight during this call. The /// driver must return all of the requested VMOs, or return an error. In /// case of an error, the driver may have unregistered some or all of the /// requested VMOs. /// /// + request `vmo_ids` the IDs of the VMOs to unregister and return. /// - response `vmos` the VMO handles corresponding to `vmo_ids`. /// * error one of the following `StatusCode` values: /// * `INVALID_ARGS`: `vmo_ids` was too big. /// * `VMO_NOT_FOUND`: An ID in `vmo_ids` was not registered. UnregisterVmos(struct { vmo_ids vector<uint32>:VMO_VECTOR_MAX_COUNT; }) -> (resource struct { vmos vector<zx.handle:VMO>:VMO_VECTOR_MAX_COUNT; }) error StatusCode; /// Tells the driver to start sending bursts via `OnBurst()`. StartBursts(); /// Tells the driver to stop sending bursts via `OnBurst()`. If all clients /// call `StopBursts()` then the driver may choose to stop its worker thread. /// The driver may wait for a single burst read to complete, but will not /// access any of the client’s VMOs or call its observer after replying. /// /// Note that already inflight `OnBurst()` bursts may still be received by /// the client. StopBursts() -> (); /// Returns the ID of a VMO containing a single burst, the time the burst /// was received. Ownership of the VMO must be returned to the driver by /// calling `UnlockVmo()`, and won't be written by the driver until then. /// See the doc for the burst format specification. /// /// The driver will drop bursts if there are no unlocked VMOs. This also /// provides flow control for the number of events in flight. When a burst /// is received and no VMOs are unlocked, `OnBurst()` will be called with /// `OUT_OF_VMOS` set as the error. `OnBurst` will not be called again until /// at least one VMO has been unlocked. /// /// + request `burst` the ID of a VMO containing the burst, as well as the /// time the burst was received. /// * error one of the following `StatusCode` values: /// * `OUT_OF_VMOS`: No unlocked VMOs were available to hold the burst. /// * The driver will wait for at least one VMO to become available /// * before sending more events to this client. /// * `SENSOR_TIMEOUT`: The driver could not drain the sensor FIFO /// * quickly enough. /// * `SENSOR_ERROR`: An unspecified driver or sensor error occurred /// * when trying to read the burst. -> OnBurst(struct { burst Burst; }) error StatusCode; /// Signals to the driver that the client is no longer reading the VMO. The /// client must not access the VMO after calling this. /// /// + request `vmo_id` the ID of the VMO to return to the driver. UnlockVmo(struct { vmo_id uint32; }); }; /// The main protocol implemented by radar drivers. Clients use this protocol to /// establish a `RadarBurstReader` connection with the driver. @discoverable protocol RadarBurstReaderProvider { /// + request `server` the `RadarBurstReader` server end for the driver to /// bind to. /// * error one of the following `StatusCode` values: /// `BIND_ERROR`: An error was encountered while trying to bind to the /// provided server channel. /// `ALREADY_BOUND`: Another client has already established a /// `RadarBurstReader` connection with the driver. Connect(resource struct { server server_end:RadarBurstReader; }) -> () error StatusCode; };
__label__pos
0.957202
La presentazione è in caricamento. Aspetta per favore La presentazione è in caricamento. Aspetta per favore Schiavone & Scalas 2 In informatica, il termine stack o pila viene usato in diversi contesti per riferirsi a strutture dati le cui modalità d'accesso. Presentazioni simili Presentazione sul tema: "Schiavone & Scalas 2 In informatica, il termine stack o pila viene usato in diversi contesti per riferirsi a strutture dati le cui modalità d'accesso."— Transcript della presentazione: 1 2 Schiavone & Scalas 2 3 In informatica, il termine stack o pila viene usato in diversi contesti per riferirsi a strutture dati le cui modalità d'accesso seguono una politica LIFO (Last In First Out) più in generale la pila è una struttura dati lineare a cui si può accedere soltanto mediante uno dei suoi capi per inserire(PUSH) e per estrarre(POP) dati. Schiavone & Scalas3 Menù 4 Pila Sequenziale: sequenza di locazioni adiacenti in un vettore; segue una politica LIFO per cui il primo elemento inserito è anche il primo ad essere estratto. Si inserisce sempre in testa. Quando inserisco un elemento eseguo Push e quando ne estraggo uno eseguo un’operazione di Pop. SequenzialePushPop Schiavone & Scalas4 Menù 5 Concatenata: successioni di nodi collegato tra loro tramite puntatori dove l’ultimo nodo non ha successori. Si accede tramite un puntatore di testa e le operazioni di inserimento ed estrazione avvengono solo in testa alla struttura dati. Concatenata Schiavone & Scalas5 Menù 6 Sequenziale Schiavone & Scalas6 top top  0 pila vuota top  max pila piena Menù 7 Concatenata Schiavone & Scalas7 PILA testa info Menù 8 Schiavone & Scalas8 Push 7 Push 15 Push 5Push 10 Pop 10 5 15 10 7 15 10 15 10 5 7 Menù 9 Schiavone & Scalas9 Per inserire un elemento nella Pila è importante effettuare un’operazione di Push. Con questa operazione il dato inserito si troverà alla testa dello Stack e ad ogni operazione di Push il puntatore verrà incrementato 1.Controllare che la pila non sia Piena *IsFull* 2.Incrementa il puntatore 3.Inserimento di un elemento (Push) Menù 10 Schiavone & Scalas10 Per estrarre un elemento nella Pila è importante effettuare un’operazione di Pop. Con questa operazione il dato da estrarre si dovrà trovare alla testa dello Stack e ad ogni operazione di Pop il puntatore verrà decrementato 1.Controllare che la pila non sia Vuota *IsEmpty* 2.Estrarre l’elemento (Pop) 3.Decrementare Menù 11 Analisi Schiavone & Scalas11 Il programma comincia presentando un menù dove vi si possono effettuare 5 scelte che sono le seguenti: 1.inserimento elementi 2.stampa elementi 3.somma elementi 4.Pop 5.ESCI Con la prima scelta viene chiesto all’utente il numero di elementi che vuole inserire < { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.it/10/2677977/slides/slide_11.jpg", "name": "Analisi Schiavone & Scalas11 Il programma comincia presentando un menù dove vi si possono effettuare 5 scelte che sono le seguenti: 1.inserimento elementi 2.stampa elementi 3.somma elementi 4.Pop 5.ESCI Con la prima scelta viene chiesto all’utente il numero di elementi che vuole inserire < 12 Analisi dei dati Schiavone & Scalas12 VARIABILEDESCRIZIONETIPOI/O/A SCÈ la variabile che serve per effettuare la scelta nel menù intI NEÈ il numero di elementiintI IÈ il contatore del forintI P1È la pilaPilaI/O NÈ il nodoNodoI INFOÈ il campo del nodo dove viene inserita l’informazione IntI Menù 13 Schiavone & Scalas 13 Flow Chart Menù 14 Schiavone & Scalas14 Menù 15 Schiavone & Scalas15 Menù 16 Codice Schiavone & Scalas16 Menù #include <<<< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.it/10/2677977/slides/slide_16.jpg", "name": "Codice Schiavone & Scalas16 Menù #include <<<< 17 Schiavone & Scalas17 Menù switch(sc){ case 1: clrscr(); printf("quanti elementi vuoi inserire?"); scanf("%d",&ne); for(int i=1;i<=ne;i++) { Temp=new Nodo; printf("inserisci il %d ø elemento: ",i); scanf("%d",&Temp->Info); Temp->Next=NULL; Push(P1,Temp); } break; case 2: Stampa(P1); getch(); break; case 3: Stampa(P1); printf("Somma elementi= %d ",Somma(P1)); getch(); break; case 4: Nodo *Ntemp=Pop(P1); delete Ntemp; gotoxy(1,5); break; default: break; } }while(sc!=5); } <<<<< { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.it/10/2677977/slides/slide_17.jpg", "name": "Schiavone & Scalas17 Menù switch(sc){ case 1: clrscr(); printf( quanti elementi vuoi inserire? ); scanf( %d ,&ne); for(int i=1;i<=ne;i++) { Temp=new Nodo; printf( inserisci il %d ø elemento: ,i); scanf( %d ,&Temp->Info); Temp->Next=NULL; Push(P1,Temp); } break; case 2: Stampa(P1); getch(); break; case 3: Stampa(P1); printf( Somma elementi= %d ,Somma(P1)); getch(); break; case 4: Nodo *Ntemp=Pop(P1); delete Ntemp; gotoxy(1,5); break; default: break; } }while(sc!=5); } <<<<<Info); Temp->Next=NULL; Push(P1,Temp); } break; case 2: Stampa(P1); getch(); break; case 3: Stampa(P1); printf( Somma elementi= %d ,Somma(P1)); getch(); break; case 4: Nodo *Ntemp=Pop(P1); delete Ntemp; gotoxy(1,5); break; default: break; } }while(sc!=5); } <<<<< 18 Schiavone & Scalas18 <<<<Next; N->Next=NULL; } else printf("pila underflow"); return(N); } <<<<Next=P.Testa; P.Testa=N; } <<<Info); Temp=Temp->Next; }} Menù <<<<Info; Temp=Temp->Next; } return(somma); } 19 Schiavone & Scalas19 Menù Scaricare ppt "Schiavone & Scalas 2 In informatica, il termine stack o pila viene usato in diversi contesti per riferirsi a strutture dati le cui modalità d'accesso." Presentazioni simili Annunci Google
__label__pos
0.524054
Single Value Decomposition (SVD): A Golfer’s Tutorial NewImageSingle Value Decomposition (SVD) is one of my favorite tools for factorizing data, but it can be a rather hard concept to wrap one’s brain around, especially if you don’t have a strong mathematical background. In order to gain a more practical understanding of how SVD are performed and their practical applications, many resort to Googling terms like “Single Value Decomposition tutorial” and “Single Value Decomposition practical example,” only to be disappointed by the results. Alas, here is a tutorial that is both easy to understand, while applying a practical example that more can related to: Golf Score Prediction Using SVD. This tutorial breaks down the SVD process by looking at the golf scores of three players – Phil, Tiger, and Vijay. By starting with a simple, naive example, the author builds a complete understanding of not only practical mechanics of SVD, but the mathematical background as well. Overall, a simple and elegant example. Based on the tutorial work, here are a few R scripts I used to recreate the results: NewImage NewImage Then, one can compute the SVD: NewImage Resulting in, NewImage Graphically, the singular values can be visualized as, NewImage This means that first left and right singular values ($u, $v) represent almost 98.9% of the variance in the matrix. In R, we can approximate the result with, NewImage Resulting in, NewImage SaveSave 2 Replies to “Single Value Decomposition (SVD): A Golfer’s Tutorial” 1. Dr. Jerry, I hate to say it sir, but this is the worst tutorial on the SVD that I’ve found. Ironically you start by correctly describing the frustration of getting to learn SVD, then they do exactly the opposite of what you promised – uncover SVD. SVD becomes more of a mystery after reading your article… there’s actually very little to read even! The title is quite misleading. There should have been more gradual step-by-step explanation. Instead you dives right into doing some code and showing the output, then an abrupt end. Pls! Who will ever unravel the SVD? Leave a Reply This site uses Akismet to reduce spam. Learn how your comment data is processed.
__label__pos
0.930276
Easy to understand JS solution • 1 // Calculates the amount of // numbers <= n that starts with prefix. function countForPrefix (n, prefix) { let a = parseInt(prefix); let b = a + 1; if (a > n || a === 0) return 0; let res = 1; a *= 10; b *= 10; while (a <= n) { res += Math.min(n + 1, b) - a; a *= 10; b *= 10; } return res; } // Constructs resulting number digit by digit // starting with the most significant. function findKthNumber (n, k) { let i, prefix = ''; while (k !== 0) { for (i = 0; i <= 9; i++) { const count = countForPrefix(n, prefix + i); if (count < k) k -= count; else break; } prefix = prefix + i; k--; // number equal to prefix } return parseInt(prefix, 10); } Log in to reply   Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
__label__pos
0.999721
KX Community Find answers, ask questions, and connect with our KX Community around the world. KX Community Guidelines Home Forums kdb+ Underneath q is k • Underneath q is k Posted by dhodgins on August 1, 2022 at 12:00 am The .q namespace contains all the bits of q which are are wrappers of k and hence gives us a good starting point. If we type lj we can see its definition, .q.lj is the fully qualified name. q)lj k){$[$[99h=@y;(98h=@!y)&98h=@. y;()~y];.Q.ft[,:[;y];x];'”type”]} In order to understand this we need to know what @ and ! mean in k. So lets take .q namespace, and filter out all the functions, this gives us a good starting point for translating q into k.(I have manually rearranged the results to group similar things together) c 2000 200 q)where[1_not type'[.q]in -10 100 106 110h]#.q neg | -: not | ~: hdel | ~: null | ^: string | $: mmu | $ reciprocal| %: ltime | %: floor | _: and | & or | | lsq | ! inv | !: key | !: count | #: first | *: reverse | |: distinct | ?: group | =: where | &: flip | +: type | @: get | .: value | .: hclose | >: sums | + prds | * mins | & maxs | | fills | ^ deltas | -': ratios | %': raze | ,/ read0 | 0:: read1 | 1:: ceiling | -_-: prev | :': union | ?, differ | $["b"]~~': all | min$["b"] any | max$["b"] upsert | .[;();,;] hsym | $["s"]!'[-1] system | .,["\"] md5 | ![-15] attr | ![-2] hcount | ![-7] eval | ![-6] reval | ![-24] There are 5 categories. We already excluded lambdas, aliases of internals like -15!, projections like ceiling(neg floor neg@), named adverb’ed operators like sums, and the k operators. Both get and value map to the same k operator which is why they are used interchangeably when people write code. Many of the operators are overloaded like ! which does both inv and key depending on the input. In k we use a trailing : to indicate that the operator is being used in its monadic form. The : is only required when the statement is ambiguous, the alternative to using : is to use @ or () eg: q)k)3=4 /dyadic 0b q)k)3=4 3 4 5 4 /dyadic 01000b q)k)=:4 3 4 5 4 /monadic explicit 4| 0 2 4 3| ,1 5| ,3 q)k)=4 3 4 5 4 /monadic implicit 4| 0 2 4 3| ,1 5| ,3 q)k)`a`b`c`d`e=4 3 4 5 4 /used dyadically even though only the monadic form makes sense 'type [0] k)`a`b`c`d`e=4 3 4 5 4 ^ q)k)`a`b`c`d`e=:4 3 4 5 4 /: can't be used like this as it like an inplace modification(like +:) 'assign [0] k)`a`b`c`d`e=:4 3 4 5 4 ^ q)k)`a`b`c`d`e =:4 3 4 5 4 /Space doesn't help 'assign [0] k)`a`b`c`d`e =:4 3 4 5 4 ^ q)k)`a`b`c`d`e@=4 3 4 5 4 /We can explicitly index using @ or [] 4| `a`c`e 3| ,`b 5| ,`d q)k)`a`b`c`d`e(=:)4 3 4 5 4 /We can use round brackets and : 4| `a`c`e 3| ,`b 5| ,`d q)k)`a`b`c`d`e(=)4 3 4 5 4 /Or just round brackets 4| `a`c`e 3| ,`b 5| ,`d There are a few k operators missing from .q because they have no alias. q)enlist 3 ,3 q)k),3 ,3 enlist and , are similar in what they do, but enlist is written in c. enlist is also variadic unlike , q)enlist[3;4;5] 3 4 5 q)k),[3;4;5] 'rank [0] k),[3;4;5] Some of the k operators have been wrapped into functions to add more protection/flexibility. eg til is actually ! but it checks the argument is the correct type. q)til k){$[0>@x;!x;'`type]} q)til`a q)til 1 2 'type [0] til 1 2 ^ q)k)!1 2 `long q)k)!1 2h `short upsert and set are very similar: q)upsert .[;();,;] q)set k){$[@x;.[x;();:;y];-19!((,y),x)]} upsert appends with , whereas set overwrites with :. set also checks the type of the input and compresses it with -19! if you give a list as the left hand argument. As q has a many to one relationship with k it is difficult to reverse the translation, but we can generate a rough lookup table: q)group where[1_not type'[.q]in -10 100 106 110h]#.q -: | ,`neg ~: | `not`hdel ^: | ,`null $: | ,`string %: | `reciprocal`ltime _: | ,`floor -_-: | ,`ceiling & | ,`and | | ,`or $ | ,`mmu ! | ,`lsq !: | `inv`key ![-15] | ,`md5 #: | ,`count *: | ,`first min$["b"] | ,`all max$["b"] | ,`any + | ,`sums * | ,`prds & | ,`mins | | ,`maxs ^ | ,`fills -': | ,`deltas %': | ,`ratios $["b"]~~': | ,`differ :': | ,`prev |: | ,`reverse ?: | ,`distinct =: | ,`group &: | ,`where +: | ,`flip @: | ,`type .: | `get`value ![-2] | ,`attr .[;();,;] | ,`upsert ,/ | ,`raze ?, | ,`union 0:: | ,`read0 1:: | ,`read1 >: | ,`hclose $["s"]!'[-1]| ,`hsym ![-7] | ,`hcount .,["\"] | ,`system ![-6] | ,`eval ![-24] | ,`reval In order to include all the functions such as lj, it is even simpler but i won’t print the whole output for brevity. q)group 1_.q -:| ,`neg ~:| `not`hdel ^:| ,`null $:| ,`string %:| `reciprocal`ltime If we look at the .Q namespace, we can see it is all written in k. In .Q.ps which is the function that runs select queries on partitioned and segmented tables we can see that in k we can use either newline(n) or ; to terminate a statement, hence the 4 lines don’t end in ; as you might have expected. q).Q.ps k){[t;c;b;a]if[-11h=@t;t:. t];if[~qe[a]&qe[b]|-1h=@b;’`nyi];d:pv;v:$[q:0>@b;0;~#b;0;-11h=@v:*. b;pf~*`:v;0] if[$[~#c;0;@*c;0;-11h=@x:c[0]1;pf~*`:x;0];d@:&-6!*c;c:1_c] if[$[#c;0;(g:(. a)~,pf)|(. a)~,(#:;`i)];f:!a;j:dt[d]t;if[q;:+f!,$[g;?d@&0<j;,+/j]];if[v&1=#b;:?[+(pf,f)!(d;j)[;&0<j];();b;f!,(sum;*f)]]] if[~#d;d:pv@&pv=*|pv;c:,()];f:$[q;0#`;!b];g:$[#a;qa@*a;0] $[(1=#d)|$[q;~g;u&pf~*. b];$[~q;.q.xkey[f];b;?:;::]foo[t;c;b;a;v]d;(?).(foo[t;c;$[q;()!();b];*a;v]d;();$[q;0b;f!f];*|a:$[g;ua a;(a;$[#a;(,/;)’k!k:!a;()])])]} The other difference between k and q are the rules around what constitutes a symbol. I’m unsure whether there is a reasonable justification for this. Personally I think it is stupid. Often when you need help or want to debug you take a variable(or copy the error) and copy it into another q process or skype|teams|outlook however -3! prints in k format and k doesn’t allow _ in symbols so you have to cast them from strings. q)tab:([]f:`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5) q)tab f x x1 ------------------------------- :dave_hodgins.txt "london" 4 :jim_bob.txt "wherever" 5 q)-3!tab "+`f`x`x1!(`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5)" /Need to unescape the double quotes q)k)+`f`x`x1!(`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5) '( [0] k)+`f`x`x1!(`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5) k)+`f`x`x1!(`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5) ^ q)-1@-3!tab; +`f`x`x1!(`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5) /need to cast to symbol due to different rules q)k)+`f`x`x1!(`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5) 'bob.txt [0] k)+`f`x`x1!(`:dave_hodgins.txt`:jim_bob.txt;("london";"wherever");4 5) ^ /Ugh, so ugly! q)k)+`f`x`x1!(`$(":dave_hodgins.txt";":jim_bob.txt");("london";"wherever");4 5) f x x1 ------------------------------- :dave_hodgins.txt "london" 4 :jim_bob.txt "wherever" 5 Finally you can also write k inside q code by surrounding it with round brackets, or by using square brackets: q)`a`b!(1 2;3 4) a| 1 2 b| 3 4 q)flip`a`b!(1 2;3 4) a b --- 1 3 2 4 /q doesn't know what +: is q)+:`a`b!(1 2;3 4) '+: [0] +:`a`b!(1 2;3 4) ^ q)(+:)`a`b!(1 2;3 4) a b --- 1 3 2 4 q)+:[`a`b!(1 2;3 4)] a b --- 1 3 2 4     dhodgins replied 2 months, 2 weeks ago 1 Member · 0 Replies • 0 Replies Sorry, there were no replies found. Log in to reply.
__label__pos
0.994226
Book Image Mastering pfSense - Second Edition By : David Zientara Book Image Mastering pfSense - Second Edition By: David Zientara Overview of this book pfSense has the same reliability and stability as even the most popular commercial firewall offerings on the market – but, like the very best open-source software, it doesn’t limit you. You’re in control – you can exploit and customize pfSense around your security needs. Mastering pfSense - Second Edition, covers features that have long been part of pfSense such as captive portal, VLANs, traffic shaping, VPNs, load balancing, Common Address Redundancy Protocol (CARP), multi-WAN, and routing. It also covers features that have been added with the release of 2.4, such as support for ZFS partitions and OpenVPN 2.4. This book takes into account the fact that, in order to support increased cryptographic loads, pfSense version 2.5 will require a CPU that supports AES-NI. The second edition of this book places more of an emphasis on the practical side of utilizing pfSense than the previous edition, and, as a result, more examples are provided which show in step-by-step fashion how to implement many features. Table of Contents (15 chapters) Questions Answer the following questions: 1. What is the key difference between routing and bridging? 2. (a) What class of routing protocols involves a router only informing its neighbors of topology changes? (b) What class of routing protocols involves each router constructing a map of its connectivity to the network? 3. Identify two methods we can use to deal with the problem of return traffic not following the same route as the traffic originally sent when configuring static routes. 4. (a) We want to utilize RIP v2 as our routing protocol. What pfSense package should we install? (b) We want to utilize OSPF as our routing protocol. What pfSense package can we use? (Identify either one.) (c) What is the best choice if we want to redistribute OSPF routes to BGP neighbors? 5. What is the first step in implementing policy-based routing? 6. Identify the two spanning tree protocols supported by pfSense...
__label__pos
0.686683
/wpf3dPart 3D Particle System for Windows Presentation Foundation http://www.brains-N-brawn.com/wpf3dPart 12/31/2007 casey chesnut comment(s)  Introduction this is just a quick code dump. i needed a simple particle system for WPF 3D. i'd actually written a 2D particle system using GDI+ a couple years ago, so i recreated the basics for WPF 3D. the pic below shows a fountain effect with 3 models and a downward force. the models grow and rotate over time. the sliders rotate around the x,y,z axis to see it in 3D. Overview the code below shows how to use the particle system. //create Model3Ds for the shapes of the particles above // ParticleSystemParameters psp = new ParticleSystemParameters(); //add particle shapes psp.ParticleShapes.Add(redCube); psp.ParticleShapes.Add(blueSphere); psp.ParticleShapes.Add(greenTea); //how shapes will be picked psp.ShapePickingOrder = ParticleResourceOrder.Loop; //how fast to emit particles psp.EmissionRate = 0.02f; psp.EmissionRateVariation = 100; //how long particles should live psp.Lifetime = 1500; psp.LifetimeVariation = 25; //direction to emit particles psp.EmitDirection = new Vector3D(0, 1, 0); psp.EmitDirectionVariation = new Vector3D(.5, .5, .5); //speed for emitting particles psp.EmitVelocity = 1.5f; psp.EmitVelocityVariation = 50; //external force applied against particles (e.g. gravity) psp.ForceDirection = new Vector3D(0, -1, 0); psp.ForceVelocity = .05f; //scale particles psp.ScaleIn = .1f; psp.ScaleOut = 1.5f; //rotate particles psp.RotateX = 720; psp.RotateY = 0; psp.RotateZ = 0; //create particle system using parameters above ps = new ParticleSystem(psp); //add particle system to Viewport3D this.mvPartSys.Children.Add(ps); ps.Start(); Conclusion er, um ... so its a basic 3D particle system. took about a day to write. Source C# source code Updates none planned, but the method used to translate particles needs to be changed to be more WPF-ish. Future thinking about coding something for the XNA Artificial Intelligence contest
__label__pos
0.846297
1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More. Graphics Xbox '720' GPU 'possibly' confirmed Discussion in 'Hardware' started by Parge, 26 Jan 2012. 1. Ending Credits Ending Credits Bunned Joined: 4 Jan 2008 Posts: 5,288 Likes Received: 232 The main restriction for these things is storage space anyway, also remember that consoles use lower res textures and lower polycounts. That said, it would be a good countermeasure to the constant BRRRRRRR of loading stuff off of the disk all the time. Consoles are always going to be horribly underpowered because they need to be sold as cheaply as possible and the RnD development cycle is so slow for these things.   2. Cei Cei pew pew pew Joined: 22 Mar 2008 Posts: 4,717 Likes Received: 122 The disc-loading is circumvented by installing the game on the HD - something that is becoming ever more used on consoles. Of course, the 360 has the problem that not every owner has a HD in the first place, which is where the PS3 has the advantage of guaranteeing all users will have at least 20GB, if not more. Throw in the PS3's BluRay, and storage isn't a massive issue, it's simply getting that data off the disc fast enough (not helped by the 2x read speed of the first-generation BD drive they're now stuck with). Offloading to RAM isn't going to achieve much, as it still means the data has to come off the disc every time you play the same - leading to longer load times. The HD route is much better, and we may even see hybrid disk drives being used to gain some of the SSD speed. Consoles are, of course, underpowered compared to a PC that costs multiple times more. However, they kick out graphics of a higher performance/quality than you'd get from a PC of similar specs simply due to the direct access developers have to the hardware, and a single hardware profile to code for. As for R&D, the cycle isn't necessarily that long, but more that they want to eke out as long as possible between hardware releases to maximise profits.   3. Parge Parge the worst Super Moderator Joined: 16 Jul 2010 Posts: 12,948 Likes Received: 573 No new Xbox in 2012 - confirmed by a senior French Exec. So Q4 2013 seems even more likely now. Omg, think where we will be with PC GPUs by then. That is two years down the line. We will have at least a brand new GPU line from ATI, probably the 8970, or even 8990. Meanwhile Nvidia will have released Kepler, and in all likelihood, the revision of Kepler too, probably the GTX 780/880   4. izools izools New Member Joined: 28 Dec 2011 Posts: 171 Likes Received: 9 Although perhaps this will give AMD enough time to improve their Fusion line enough to have a credible gaming console product out?   5. r3loaded r3loaded Well-Known Member Joined: 25 Jul 2010 Posts: 1,095 Likes Received: 31 I personally would have hoped for something closer to a 6850/6870. They're really power efficient GPUs, cheaper to manufacture than a 6900 series card yet pack a lot more performance than a 6670.   6. Elton Elton Officially a Whisky Nerd Joined: 23 Jan 2009 Posts: 8,575 Likes Received: 189 Well if they do approach the next generation cards. Perhaps the replacement for the HD6850/HD6870 will do fine.   7. shankly1985 shankly1985 New Member Joined: 25 Jan 2012 Posts: 53 Likes Received: 0 I think consoles need to come out with hardware packages like basic, performance, extreme. that way people can pick what they think is best for them. each package has different hardware CPU, Ram, Gpu. Basic starting with 1080p gaming @30fps Performance with 1080p @60 Extreme higher res than 1080p with again high fps Prices could work out good that way, plus people get to pick there needs. what you think.   8. MjFrosty MjFrosty New Member Joined: 3 Aug 2011 Posts: 853 Likes Received: 23 People need to remember dedicated hardware is not the same as a PC ...Still a bit disappointing if rumours are true though.   9. lm_wfc lm_wfc Member Joined: 18 Feb 2011 Posts: 481 Likes Received: 13 Sounds like a PC.   10. urobulos urobulos Member Joined: 13 Apr 2010 Posts: 358 Likes Received: 10 Would never catch on. The more hardware varieties you introduce the more potential for inefficiency. I understand the need to have hardware finalised before the games enter production phase, but 6670 sounds a bit too low. If it were announced today then maybe. But we probably won't see a new console on the market until Q4 2013 at the earliest. If they do go with slightly modified off the shelf components then is it possible for the early devkits to use 6670s to compile the early alpha builds and then move on to something more powerful, say a year before release? I guess 2GB of RAM and a 6670 are a massive jump from current hardware anyway and even with the old hardware both consoles can produce some decent visuals. Also have to take into account that every new console will aim for 1080p max. Higher res will not happen so there isn't as much need for super powerful GPU's when you try to run BF3 at 2560x1600 or multi screen. I'm still worried though. If memory serves me right, new consoles usually had GPU's only slightly below the high-end PC hardware at release. If we will truly get a, by then, two year old and two generations behind mid-range chip to power most popular gaming platforms until 2020 then that is sad. Hardware and eyecandy is secondary, but there is a point when you are limiting the game design. If I see another corridor based shooter, I think I'll need some depression meds.   11. shankly1985 shankly1985 New Member Joined: 25 Jan 2012 Posts: 53 Likes Received: 0 Yes I understand that, but you get the benefit of sony or xbox games that them systems offer.   12. SuicideNeil SuicideNeil New Member Joined: 17 Aug 2009 Posts: 5,983 Likes Received: 345 But the issue then will be that some games will be tailored to suit the low end model = no point in buying the higher spec console, and other games will be tailored to the higher end versions, resulting in mediocre/poor performance on the low end consoles. People who game on PCs understand that you need a decent setup to play modern games well / at higher settings, but try explaining this to a 12 yearold or their parent when they start complaining half their £40 games run slowly or the console is constantly overheating. I too understand why you think a tiered console spec is a good idea, but consoles are not PCs- you simply cannot have different performance levels from the same console , it just isn't feesable from a business view point..   13. shankly1985 shankly1985 New Member Joined: 25 Jan 2012 Posts: 53 Likes Received: 0 True maybe I didn't think this through enough :duh:   14. dBass dBass New Member Joined: 29 Jan 2012 Posts: 26 Likes Received: 0 It's going to be interesting to see what the gap is between PC and console if the next generation of console games are all 1080p. The resolution difference has always been one of the main graphical advantages of PCs so unless 1600p becomes a lot more affordable they will be equal on that front for most PC gamers.   15. Yslen Yslen Lord of the Twenty-Seventh Circle Joined: 3 Mar 2010 Posts: 1,966 Likes Received: 48 I'll be interested to see how they market it too... "the new Xbox, play games in HD, and we're not lying this time!"   16. dBass dBass New Member Joined: 29 Jan 2012 Posts: 26 Likes Received: 0 I imagine they'll call it XtraHD resolution or some other made up acronym. It's like the previous high definition but both higher and more defined.   17. Rustypouch Rustypouch New Member Joined: 5 Feb 2011 Posts: 71 Likes Received: 4 High-End Smartphones now come with upwards of 1GB of RAM, I'd expect to see at least 2GB in the next generation Xbox. Also, I hope to see some sort of AMD Fusion set up. One chip, shared RAM, Low power draw, low heat, low cost, DX11, reasonably powerful. It makes complete sense if you ask me. But looking at current consoles on the market, they all have some variety of IBM PowerPC architecture so I can only guess this would be a massive change to the software development and would mean no chance at all of it being backwards compatiable with Xbox 360 games and possibly Kinect (My knowledge on the subject isn't great, so forgive me if that is utter non-sense!). Would also expect the next Xbox to be having Wi-Fi and rechargeable controllers from the start, all the peripherals you had to buy along with the Xbox all added up.   18. Cei Cei pew pew pew Joined: 22 Mar 2008 Posts: 4,717 Likes Received: 122 But smartphones multi-task, consoles don't (beyond running a very lightweight OS and messaging in the background). They don't need that much RAM, so 1-2GB is enough. WiFi will be built in, as it's in all the current hardware revisions of the consoles. Rechargeable batteries would be good, which is one of the reasons I prefer the PS3.   19. towelie towelie How do I Internet!! Joined: 1 Sep 2011 Posts: 399 Likes Received: 10 I think we are all forgetting with a console you have no choice, what you get is what you get.Throw all that creativity away, if they use this GPU or improve the ram capacity... They will go for the cheapiest option possible at least sony provide competition otherwise it would be twice as worse.They don't even let you open the case without voiding warrenty! Such a shame the way the PC game market has gone.   20. Elton Elton Officially a Whisky Nerd Joined: 23 Jan 2009 Posts: 8,575 Likes Received: 189 I would say 2GB of RAM just because RAM density and RAM prices are still so damn cheap. As for a graphics chip, well honestly anything at this point will be ~4x the performance of the current consoles providing they're mid-range. But it makes me wonder why they aren't say...using something that could be more. Perhaps the nightmare of YLODs and RRODs have convicned console manufactureres to stay in the mid-range?   Share This Page
__label__pos
0.669512
Author Topic: Object you can throw over and over  (Read 242 times) Max • Full Member • *** • Posts: 212 • View Profile Object you can throw over and over « on: March 15, 2019, 04:41:51 pm » Hey, so I coded this custom entity that's a lot like the iron ball from A Link to the Past's Eagle Tower- it's an object the hero can pick up and throw, and then pick up again and keep on throwing. You can even carry it to other maps and keep smashing it into enemies faces. I can it "toss_ball", haha. You can set the properties "weight" and "damage" on the custom entity, which by default are 1 and 6. When this entity hits an enemy, it'll try to call enemy:hit_by_toss_ball() , so if you want certain enemies to exhibit different behavior on being hit by this than being damaged, define that function for those enemies (if, for example, you wanted an enemy to have its shield destroyed, or become vulnerable when hit with this or something.). Note: hit_by_toss_ball() will be called whether the hero throws the ball into the enemy, but also if the enemies runs into the entity while it's on the ground. Code: [Select] local entity = ... local game = entity:get_game() local map = entity:get_map() local DEFAULT_DAMAGE = 6 function entity:on_created()   entity:set_traversable_by(false)   entity:set_drawn_in_y_order(true)   entity:set_follow_streams(true)   entity:set_traversable_by("enemy", true)   entity:set_weight(1)   if entity:get_property("weight") then     entity:set_weight(entity:get_property("weight"))   end end local enemies_touched = {} entity:add_collision_test("sprite", function(entity, other)   if other:get_type() == "enemy" then     local enemy = other     if not enemies_touched[enemy] and enemy:hit_by_toss_ball() then       enemy:hit_by_toss_ball()     end     enemies_touched[enemy] = enemy     sol.timer.start(map, 1000, function() enemies_touched[enemy] = false end)   end end) function entity:on_lifting(carrier, carried_object)   carried_object:set_damage_on_enemies(game:get_value(DEFAULT_DAMAGE)   if entity:get_property("damage") then     entity:set_weight(entity:get_property("damage"))   end   carried_object:set_destruction_sound("running_obstacle")   --landing, and therefore needing to create a new toss_ball   function carried_object:on_breaking()     local x, y, layer = carried_object:get_position()     local width, height = carried_object:get_size()     local sprite = carried_object:get_sprite()     local direction = sprite:get_direction()     if carried_object:get_ground_below() == "wall" then y = y + 34 end     carried_object:get_map():create_custom_entity({       width = width, height = height, x = x, y = y, layer = layer,       direction = direction, model = "toss_ball", sprite = sprite:get_animation_set()     })   end end If you see any errors or mistakes I've made, please let me know so I can fix them! Have fun using this, modifying it, whatever you want. « Last Edit: March 15, 2019, 07:12:28 pm by Max »  
__label__pos
0.889366
Fix Steam Corrupt Update Files error on Windows PC In this post, we will show you how to fix Steam corrupt update files error on Windows PC. The “corrupt update files” error is one of the errors faced by Steam users. It primarily occurs when you attempt to download a new game that you just bought or update an existing game on Steam. It may occur due to a power cut or a corrupted download. Multiple users have reported being experiencing this error. It is another annoying error as you can’t play a Steam game unless the updates are installed completely. So, fixing this error becomes important. Fix Steam Corrupt Update Files error on Windows PC We are going to discuss all the possible methods that would help you resolve this error on Windows 11/10 PC. Follow these working methods and you will be able to get rid of this error. Before the fixes, let us try to understand the possible causes of this error. Why do my Steam games keep getting corrupted? There can be different reasons for different users to encounter corrupt update files error on Steam. The most common causes of this error include the following reasons: • In case BSOD or power outage interrupted the Steam game downloading process, it might have corrupted your download files, and hence you are getting the corrupt update files error. • If there are problems on your hard disk drive where you have installed Steam, it might result in this error. A corrupted hard disk drive might be interrupting or terminating your game downloading process with this error. • The downloaded files may have become corrupted. How to Fix Steam Corrupt Update Files error on Windows PC Here are the methods to fix the corrupt update files error on Steam on your Windows PC: 1. Rename the Download Folder. 2. Delete the Active Download Folder. 3. Change the Download Folder. 4. Delete Download Cache. 5. Verify the integrity of the game files. 6. Repair the Steam Library folder. 7. Run Disk Error Check. 8. Reinstall the Steam client. Let us now discuss the above-listed solutions in detail! 1] Rename the Download Folder You try renaming the download folder and see if the error is fixed. Renaming your download folder will reset all your downloads or updates and might enable you to fix the issue. To do that, here are the steps to follow: 1. First, open the installation directory of Steam which is by default located at C:Program Files or C:Program Files (x86). 2. Then, open the Steamapps folder. 3. Now, select the Downloading folder. 4. Next, rename this folder like DownloadingNew or something else. 5. After that, relaunch Steam and see if you are able to download your game without any error. Read: An error occurred while installing or updating the Steam game 2] Delete the Active Download Folder You can also try deleting the download folder for the game that was giving you this error. Each game has different download folders in the Steam installation directory. After deleting the active download folder, you can attempt to download or update the game and then see if the issue is fixed or not. Here are the steps for doing so: 1. Firstly, go to the Steamapps > Downloading folder in the installation directory of Steam; you will most probably find it here > C:Program FilesSteamSteamappsDownloading. 2. Now, check for the download folder for your game that you were trying to download or update; select that folder. 3. Next, delete the selected download folder. 4. After that, restart the Steam client and check if you are able to download or update the game without the corrupt update files error. 3] Change the Download Folder If the above methods don’t work, try changing the download/ Steam library folder. If there is corruption in the hard disk partition or Steam Library folder, you should be able to fix it by changing the download location. To change Steam Library or Download folder, you can follow the below steps: 1. Start the Steam client and press the Steam > Settings option. 2. From the Settings, click on the Download option. 3. Then, tap on the Steam Library Folders option. 4. Now, from the pop-up dialog, press the Add Library Folder button. 5. After that, choose a different drive and folder and then click the Select button. 6. Finally, exit the Settings window and then try download or updating your game. See: Fix Steam stuck on Allocating disk space on Windows 11/10 4] Delete Download Cache Another method that you can try to fix is to clear up all the download cache and unnecessary download files to get rid of any kind of corruption. Here are the steps to do that: 1. Firstly, start the Steam client. 2. Now, go to the Steam menu present at the top toolbar. 3. Next, click on the Settings option. 4. In the Settings window, move to the Downloads tab. 5. From here, tap on the Clear Download Cache option. 6. Finally, exit the Steam client and then restart it to check if the issue is gone. 5] Verify the integrity of the game files In case there are corrupted or missing game files, you might experience the corrupt update files error on Steam. So, checking the integrity of the game files will help you resolve the error. Follow the below steps for that: 1. First, launch Steam and then click on the Library menu from the top toolbar. 2. Then, click the Games option. 3. Now, right-click on the game that is giving you the corrupt update files error. 4. From the right-click menu, click the Properties option. 5. Next, move to the Local Files tab, and from here, press the Verify integrity of game files button. 6. Wait for the verification process to end and then recheck if you are able to download or update the game without this error. 6] Repair the Steam Library folder If the problem lies with the Steam Library folder, you can try repairing it to fix the issue. There is an option to repair the Steam library folder that you can use to do that. Here are the exact steps to find and use this option: 1. First, start the Steam client and go to the Steam > Settings option. 2. Now, move to the Downloads tab. 3. In the Downloads tab, press the Steam Library Folders. 4. Next, select and right-click on the Steam Library Folder. 5. From the context menu, tap on the Repair Library Folder option. 6. Steam will now attempt to check and repair problems associated with the folder. When the process is completed, see if you can download or update your game without any error. 7] Run Disk Error Check On Windows 11/10, you can use the inbuilt disk error checker tool called CHKDSK. Simply run CHKDSK check for the drive where you have installed your Steam games and let it fix the drive error if any. After that, you can relaunch the Steam client and continue with downloading your games. Tip: Check Hard Disk for Errors, Health, Bad Sectors in Windows. 8] Reinstall the Steam client If none of the above solutions work for you, the last resort is to start with a fresh installation of the Steam app. A lot of time corrupted or incomplete installation of a program may cause such errors. However, you should try it last if nothing else works. Before anything, make sure you have taken a backup for all library folders that you wouldn’t want to lose. After that, uninstall the Steam client using the Settings app or a free third-party uninstaller. When the uninstallation is done, download the latest version of the Steam client and install it on your PC. You can now launch Steam and hopefully, you won’t see the corrupt update files error again. Tip: How to Install Steam and Manage Steam Games How do I fix corrupted updates on Steam? All the above-discussed methods might help your fix corrupted updates on Steam. Additionally, you can try changing the download region, disabling your antivirus, etc. How do you fix a corrupted disk? A corrupted disk can be fixed using CHKDSK- the built-in utility provided in Windows PC. Just right-click on the corrupted hard disk that you want to fix and then click on the Properties option from the context menu. Then, move to the Tools tab in the Properties window and click on the Check button present under the Error Checking option. It will then attempt to check the disk for any errors and try to repair them. You can also use the free CHKDSK alternative disk error checking software to fix bad sectors and corruption on a hard drive. Does uninstalling Steam delete games? Uninstalling Steam will delete the entire installation directory from your PC including games, downloaded files, and other content. You might need to uninstall Steam if it is not working properly. However, if you want to uninstall and then reinstall Stem without losing your games, make sure to take a backup of all your games and other folders that you would like to preserve. That’s it! Hope this article finds a suitable method to resolve corrupt update files error on Steam. Now read: Fix Steam Source link Jacob MORRIS MORRIS is an impassioned technology writer. He always inspires technologists with his innovative thinking and practical approach. A go-to personality for every Technical problem, no doubt, the chief problem-solver! Leave a Reply
__label__pos
0.713493
5kb的vue新作petite-vue 更新日期: 2021-07-11阅读: 1.2k标签: petite-vue 简介 从名字来看可以知道 petite-vue 是一个 mini 版的vue,大小只有5.8kb,可以说是非常小了。据尤大大介绍,petite-vue 是 Vue 的可替代发行版,针对渐进式增强进行了优化。它提供了与标准 Vue 相同的模板语法和响应式模型: • 大小只有5.8kb • Vue 兼容模版语法 • 基于dom,就地转换 • 响应式驱动 简单使用 <body> <script src="https://unpkg.com/petite-vue" defer init></script> <div v-scope="{ count: 0 }"> <button @click="count--">-</button> <span>{{ count }}</span> <button @click="count++">+</button> </div> </body> 通过 script 标签引入同时添加 init ,接着就可以使用 v-scope 绑定数据,这样一个简单的计数器就实现了。 了解过 Alpine.js 这个框架的同学看到这里可能有点眼熟了,两者语法之间是很像的。 <!-- Alpine.js --> <div x-data="{ open: false }"> <button @click="open = true">Open Dropdown</button> <ul x-show="open" @click.away="open = false"> Dropdown Body </ul> </div> 除了用 init 的方式之外,也可以用下面的方式: <body> <div v-scope="{ count: 0 }"> <button @click="count--">-</button> <span>{{ count }}</span> <button @click="count++">+</button> </div> <!-- 放在body底部 --> <script src="https://unpkg.com/petite-vue"></script> <script> PetiteVue.createApp().mount() </script> </body> 或使用 ES module 的方式: <body> <script type="module"> import { createApp } from 'https://unpkg.com/petite-vue?module' createApp().mount() </script> <div v-scope="{ count: 0 }"> <button @click="count--">-</button> <span>{{ count }}</span> <button @click="count++">+</button> </div> </body> 根作用域 createApp 函数可以接受一个对象,类似于我们平时使用 data 和 methods 一样,这时 v-scope 不需要绑定值。 <body> <script type="module"> import { createApp } from 'https://unpkg.com/petite-vue?module' createApp({ count: 0, increment() { this.count++ }, decrement() { this.count-- } }).mount() </script> <div v-scope> <button @click="decrement">-</button> <span>{{ count }}</span> <button @click="increment">+</button> </div> </body> 指定挂载元素 <body> <script type="module"> import { createApp } from 'https://unpkg.com/petite-vue?module' createApp({ count: 0 }).mount('#app') </script> <div id="app"> {{ count }} </div> </body> 生命周期 可以监听每个元素的生命周期事件。 <body> <script type="module"> import { createApp } from 'https://unpkg.com/petite-vue?module' createApp({ onMounted1(el) { console.log(el) // <span>1</span> }, onMounted2(el) { console.log(el) // <span>2</span> } }).mount('#app') </script> <div id="app"> <span @mounted="onMounted1($el)">1</span> <span @mounted="onMounted2($el)">2</span> </div> </body> 组件 在 petite-vue 里,组件可以使用函数的方式创建,通过template可以实现复用。 <body> <script type="module"> import { createApp } from 'https://unpkg.com/petite-vue?module' function Counter(props) { return { $template: '#counter-template', count: props.initialCount, increment() { this.count++ }, decrement() { this.count++ } } } createApp({ Counter }).mount() </script> <template id="counter-template"> <button @click="decrement">-</button> <span>{{ count }}</span> <button @click="increment">+</button> </template> <!-- 复用 --> <div v-scope="Counter({ initialCount: 1 })"></div> <div v-scope="Counter({ initialCount: 2 })"></div> </body> 全局状态管理 借助 reactive 响应式 api 可以很轻松的创建全局状态管理 <body> <script type="module"> import { createApp, reactive } from 'https://unpkg.com/petite-vue?module' const store = reactive({ count: 0, increment() { this.count++ } }) // 将count加1 store.increment() createApp({ store }).mount() </script> <div v-scope> <!-- 输出1 --> <span>{{ store.count }}</span> </div> <div v-scope> <button @click="store.increment">+</button> </div> </body> 自定义指令 这里来简单实现一个输入框自动聚焦的指令。 <body> <script type="module"> import { createApp } from 'https://unpkg.com/petite-vue?module' const autoFocus = (ctx) => { ctx.el.focus() } createApp().directive('auto-focus', autoFocus).mount() </script> <div v-scope> <input v-auto-focus /> </div> </body> 内置指令 • v-model • v-if / v-else / v-else-if • v-for • v-show • v-html • v-text • v-pre • v-once • v-cloak 注意:v-for 不需要key,另外 v-for 不支持 深度解构 <body> <script type="module"> import { createApp } from 'https://unpkg.com/petite-vue?module' createApp({ userList: [ { name: '张三', age: { a: 23, b: 24 } }, { name: '李四', age: { a: 23, b: 24 } }, { name: '王五', age: { a: 23, b: 24 } } ] }).mount() </script> <div v-scope> <!-- 支持 --> <li v-for="{ age } in userList"> {{ age.a }} </li> <!-- 不支持 --> <li v-for="{ age: { a } } in userList"> {{ a }} </li> </div> </body> 不支持 为了更轻量小巧,petite-vue 不支持以下特性: • ref()、computed • render函数,因为petite-vue 没有虚拟DOM • 不支持Map、Set等响应类型 • Transition, KeepAlive, Teleport, Suspense • v-on="object" • v-is & • v-bind:style auto-prefixing 总结 以上就是对 petite-vue 的一些简单介绍和使用,抛砖引玉,更多新的探索就由你们去发现了。 总的来说,prtite-vue 保留了 Vue 的一些基础特性,这使得 Vue 开发者可以无成本使用,在以往,当我们在开发一些小而简单的页面想要引用 Vue 但又常常因为包体积带来的考虑而放弃,现在,petite-vue 的出现或许可以拯救这种情况了,毕竟它真的很小,大小只有 5.8kb,大约只是 Alpine.js 的一半。 链接: https://www.fly63.com/article/detial/10523 内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!
__label__pos
0.802397
X-Git-Url: http://git.xiph.org/?p=opus.git;a=blobdiff_plain;f=libcelt%2Fpitch.c;h=89a00f83f207c0d409ea0cc03ae462953d532f5c;hp=804b94121a283667559770244c888b346d8daa41;hb=f334c82ec3535bb39964424a2ed199d4e349598d;hpb=ce4dd367c2b9ffc2b079cde28dd724b94776376d diff --git a/libcelt/pitch.c b/libcelt/pitch.c index 804b9412..89a00f83 100644 --- a/libcelt/pitch.c +++ b/libcelt/pitch.c @@ -10,18 +10,14 @@ 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. - - - Neither the name of the Xiph.org Foundation nor the names of its - contributors may 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 @@ -35,7 +31,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -46,12 +41,13 @@ #include "stack_alloc.h" #include "mathops.h" -void find_best_pitch(celt_word32 *xcorr, celt_word32 maxcorr, celt_word16 *y, int yshift, int len, int max_pitch, int best_pitch[2]) +static void find_best_pitch(opus_val32 *xcorr, opus_val32 maxcorr, opus_val16 *y, + int yshift, int len, int max_pitch, int *best_pitch) { int i, j; - celt_word32 Syy=1; - celt_word16 best_num[2]; - celt_word32 best_den[2]; + opus_val32 Syy=1; + opus_val16 best_num[2]; + opus_val32 best_den[2]; #ifdef FIXED_POINT int xshift; @@ -68,14 +64,12 @@ void find_best_pitch(celt_word32 *xcorr, celt_word32 maxcorr, celt_word16 *y, in Syy = MAC16_16(Syy, y[j],y[j]); for (i=0;i0) { - celt_word16 num; - celt_word32 xcorr16; + opus_val16 num; + opus_val32 xcorr16; xcorr16 = EXTRACT16(VSHR32(xcorr[i], xshift)); num = MULT16_16_Q15(xcorr16,xcorr16); - score = num*1./Syy; if (MULT16_32_Q15(num,best_den[1]) > MULT16_32_Q15(best_num[1],Syy)) { if (MULT16_32_Q15(num,best_den[0]) > MULT16_32_Q15(best_num[0],Syy)) @@ -98,74 +92,79 @@ void find_best_pitch(celt_word32 *xcorr, celt_word32 maxcorr, celt_word16 *y, in } } -void pitch_downsample(const celt_sig * restrict x, celt_word16 * restrict x_lp, int len, int end, int _C, celt_sig * restrict xmem, celt_word16 * restrict filt_mem) +#include "plc.h" +void pitch_downsample(celt_sig * restrict x[], opus_val16 * restrict x_lp, + int len, int _C) { int i; + opus_val32 ac[5]; + opus_val16 tmp=Q15ONE; + opus_val16 lpc[4], mem[4]={0,0,0,0}; const int C = CHANNELS(_C); for (i=1;i>1;i++) - x_lp[i] = SHR32(HALF32(HALF32(x[(2*i-1)*C]+x[(2*i+1)*C])+x[2*i*C]), SIG_SHIFT); - x_lp[0] = SHR32(HALF32(HALF32(*xmem+x[C])+x[0]), SIG_SHIFT); - *xmem = x[end-C]; + x_lp[i] = SHR32(HALF32(HALF32(x[0][(2*i-1)]+x[0][(2*i+1)])+x[0][2*i]), SIG_SHIFT+3); + x_lp[0] = SHR32(HALF32(HALF32(x[0][1])+x[0][0]), SIG_SHIFT+3); if (C==2) { for (i=1;i>1;i++) - x_lp[i] = SHR32(HALF32(HALF32(x[(2*i-1)*C+1]+x[(2*i+1)*C+1])+x[2*i*C+1]), SIG_SHIFT); - x_lp[0] += SHR32(HALF32(HALF32(x[C+1])+x[1]), SIG_SHIFT); - *xmem += x[end-C+1]; + x_lp[i] += SHR32(HALF32(HALF32(x[1][(2*i-1)]+x[1][(2*i+1)])+x[1][2*i]), SIG_SHIFT+3); + x_lp[0] += SHR32(HALF32(HALF32(x[1][1])+x[1][0]), SIG_SHIFT+3); } -#if 0 + _celt_autocorr(x_lp, ac, NULL, 0, + 4, len>>1); + + /* Noise floor -40 dB */ +#ifdef FIXED_POINT + ac[0] += SHR32(ac[0],13); +#else + ac[0] *= 1.0001f; +#endif + /* Lag windowing */ + for (i=1;i<=4;i++) { - int j; - float ac[3]={0,0,0}; - float ak[2]; - float det; - celt_word16 mem[2]; - for (i=0;i<3;i++) - { - for (j=0;j<(len>>1)-i;j++) - { - ac[i] += x_lp[j]*x_lp[j+i]; - } - } - det = 1./(.1+ac[0]*ac[0]-ac[1]*ac[1]); - ak[0] = .9*det*(ac[0]*ac[1] - ac[1]*ac[2]); - ak[1] = .81*det*(-ac[1]*ac[1] + ac[0]*ac[2]); - /*printf ("%f %f %f\n", 1., -ak[0], -ak[1]);*/ - mem[0]=filt_mem[0]; - mem[1]=filt_mem[1]; - filt_mem[0]=x_lp[(end>>1)-1]; - filt_mem[1]=x_lp[(end>>1)-2]; - for (j=0;j>1;j++) - { - float tmp = x_lp[j]; - x_lp[j] = x_lp[j] - ak[0]*mem[0] - ak[1]*mem[1]; - mem[1]=mem[0]; - mem[0]=tmp; - } - } + /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/ +#ifdef FIXED_POINT + ac[i] -= MULT16_32_Q15(2*i*i, ac[i]); +#else + ac[i] -= ac[i]*(.008f*i)*(.008f*i); #endif + } + + _celt_lpc(lpc, ac, 4); + for (i=0;i<4;i++) + { + tmp = MULT16_16_Q15(QCONST16(.9f,15), tmp); + lpc[i] = MULT16_16_Q15(lpc[i], tmp); + } + fir(x_lp, lpc, x_lp, len>>1, 4, mem); + + mem[0]=0; + lpc[0]=QCONST16(.8f,12); + fir(x_lp, lpc, x_lp, len>>1, 1, mem); } -void pitch_search(const CELTMode *m, const celt_word16 * restrict x_lp, celt_word16 * restrict y, int len, int max_pitch, int *pitch, celt_sig *xmem, int M) +void pitch_search(const opus_val16 * restrict x_lp, opus_val16 * restrict y, + int len, int max_pitch, int *pitch) { int i, j; - const int lag = MAX_PERIOD; - const int N = M*m->eBands[m->nbEBands+1]; - int best_pitch[2]={0}; - VARDECL(celt_word16, x_lp4); - VARDECL(celt_word16, y_lp4); - VARDECL(celt_word32, xcorr); - celt_word32 maxcorr=1; + int lag; + int best_pitch[2]={0,0}; + VARDECL(opus_val16, x_lp4); + VARDECL(opus_val16, y_lp4); + VARDECL(opus_val32, xcorr); + opus_val32 maxcorr=1; int offset; int shift=0; SAVE_STACK; - ALLOC(x_lp4, len>>2, celt_word16); - ALLOC(y_lp4, lag>>2, celt_word16); - ALLOC(xcorr, max_pitch>>1, celt_word32); + lag = len+max_pitch; + + ALLOC(x_lp4, len>>2, opus_val16); + ALLOC(y_lp4, lag>>2, opus_val16); + ALLOC(xcorr, max_pitch>>1, opus_val32); /* Downsample by 2 again */ for (j=0;j>2;j++) @@ -174,7 +173,7 @@ void pitch_search(const CELTMode *m, const celt_word16 * restrict x_lp, celt_wor y_lp4[j] = y[2*j]; #ifdef FIXED_POINT - shift = celt_ilog2(MAX16(celt_maxabs16(x_lp4, len>>2), celt_maxabs16(y_lp4, lag>>2)))-11; + shift = celt_ilog2(MAX16(1, MAX16(celt_maxabs16(x_lp4, len>>2), celt_maxabs16(y_lp4, lag>>2))))-11; if (shift>0) { for (j=0;j>2;j++) @@ -192,7 +191,7 @@ void pitch_search(const CELTMode *m, const celt_word16 * restrict x_lp, celt_wor for (i=0;i>2;i++) { - celt_word32 sum = 0; + opus_val32 sum = 0; for (j=0;j>2;j++) sum = MAC16_16(sum, x_lp4[j],y_lp4[i+j]); xcorr[i] = MAX32(-1, sum); @@ -204,7 +203,7 @@ void pitch_search(const CELTMode *m, const celt_word16 * restrict x_lp, celt_wor maxcorr=1; for (i=0;i>1;i++) { - celt_word32 sum=0; + opus_val32 sum=0; xcorr[i] = 0; if (abs(i-2*best_pitch[0])>2 && abs(i-2*best_pitch[1])>2) continue; @@ -218,7 +217,7 @@ void pitch_search(const CELTMode *m, const celt_word16 * restrict x_lp, celt_wor /* Refine by pseudo-interpolation */ if (best_pitch[0]>0 && best_pitch[0]<(max_pitch>>1)-1) { - celt_word32 a, b, c; + opus_val32 a, b, c; a = xcorr[best_pitch[0]-1]; b = xcorr[best_pitch[0]]; c = xcorr[best_pitch[0]+1]; @@ -226,17 +225,140 @@ void pitch_search(const CELTMode *m, const celt_word16 * restrict x_lp, celt_wor offset = 1; else if ((a-c) > MULT16_32_Q15(QCONST16(.7f,15),b-c)) offset = -1; - else + else offset = 0; } else { offset = 0; } *pitch = 2*best_pitch[0]-offset; - CELT_MOVE(y, y+(N>>1), (lag-N)>>1); - CELT_MOVE(y+((lag-N)>>1), x_lp, N>>1); - RESTORE_STACK; +} + +static const int second_check[16] = {0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2}; +opus_val16 remove_doubling(opus_val16 *x, int maxperiod, int minperiod, + int N, int *_T0, int prev_period, opus_val16 prev_gain) +{ + int k, i, T, T0; + opus_val16 g, g0; + opus_val16 pg; + opus_val32 xy,xx,yy; + opus_val32 xcorr[3]; + opus_val32 best_xy, best_yy; + int offset; + int minperiod0; + + minperiod0 = minperiod; + maxperiod /= 2; + minperiod /= 2; + *_T0 /= 2; + prev_period /= 2; + N /= 2; + x += maxperiod; + if (*_T0>=maxperiod) + *_T0=maxperiod-1; + + T = T0 = *_T0; + xx=xy=yy=0; + for (i=0;i>1; + t = VSHR32(x2y2, 2*(sh-7)); + g = g0 = VSHR32(MULT16_32_Q15(celt_rsqrt_norm(t), xy),sh+1); + } +#else + g = g0 = xy/celt_sqrt(1+xx*yy); +#endif + /* Look for any pitch at T/k */ + for (k=2;k<=15;k++) + { + int T1, T1b; + opus_val16 g1; + opus_val16 cont=0; + T1 = (2*T0+k)/(2*k); + if (T1 < minperiod) + break; + /* Look for another strong correlation at T1b */ + if (k==2) + { + if (T1+T0>maxperiod) + T1b = T0; + else + T1b = T0+T1; + } else + { + T1b = (2*second_check[k]*T0+k)/(2*k); + } + xy=yy=0; + for (i=0;i>1; + t = VSHR32(x2y2, 2*(sh-7)); + g1 = VSHR32(MULT16_32_Q15(celt_rsqrt_norm(t), xy),sh+1); + } +#else + g1 = xy/celt_sqrt(1+2.f*xx*1.f*yy); +#endif + if (abs(T1-prev_period)<=1) + cont = prev_gain; + else if (abs(T1-prev_period)<=2 && 5*k*k < T0) + cont = HALF32(prev_gain); + else + cont = 0; + if (g1 > QCONST16(.3f,15) + MULT16_16_Q15(QCONST16(.4f,15),g0)-cont) + { + best_xy = xy; + best_yy = yy; + T = T1; + g = g1; + } + } + if (best_yy <= best_xy) + pg = Q15ONE; + else + pg = SHR32(frac_div32(best_xy,best_yy+1),16); + + for (k=0;k<3;k++) + { + int T1 = T+k-1; + xy = 0; + for (i=0;i MULT16_32_Q15(QCONST16(.7f,15),xcorr[1]-xcorr[0])) + offset = 1; + else if ((xcorr[0]-xcorr[2]) > MULT16_32_Q15(QCONST16(.7f,15),xcorr[1]-xcorr[2])) + offset = -1; + else + offset = 0; + if (pg > g) + pg = g; + *_T0 = 2*T+offset; - /*printf ("%d\n", *pitch);*/ + if (*_T0
__label__pos
0.993902
Skip to main content Déploiement de Docker sur Azure App Service Vous pouvez déployer un conteneur Docker sur Azure App Service dans le cadre de vos workflows de déploiement continu (CD). Remarque : Les exécuteurs hébergés sur GitHub ne sont pas pris en charge sur GitHub Enterprise Server. Vous pouvez voir plus d’informations sur le support futur planifié dans la GitHub public roadmap. Introduction Ce guide explique comment utiliser GitHub Actions pour créer et déployer un conteneur Docker sur Azure App Service. Remarque : Si vos workflows GitHub Actions doivent accéder aux ressources d’un fournisseur de cloud qui prend en charge OpenID Connecter (OIDC), vous pouvez configurer vos workflows pour qu’ils s’authentifient directement auprès du fournisseur de cloud. Cela vous permet d’arrêter de stocker ces informations d’identification en tant que secrets de longue durée, et de fournir d’autres avantages en matière de sécurité. Pour plus d’informations, consultez « À propos du renforcement de la sécurité avec OpenID Connect ». et « Configuration d’OpenID Connect dans Azure ». Prérequis Avant de créer votre workflow GitHub Actions, vous devez suivre les étapes de configuration suivantes : 1. Créer un plan Azure App Service. Par exemple, vous pouvez utiliser Azure CLI pour créer un plan App Service : Bash az appservice plan create \ --resource-group MY_RESOURCE_GROUP \ --name MY_APP_SERVICE_PLAN \ --is-linux Dans la commande ci-dessus, remplacez MY_RESOURCE_GROUP par votre groupe de ressources Azure préexistant et MY_APP_SERVICE_PLAN par un nouveau nom pour le plan App Service. Pour plus d’informations sur l’utilisation d’Azure CLI, consultez la documentation Azure : 2. Créez une application web. Par exemple, vous pouvez utiliser Azure CLI pour créer une application web Azure App Service : Shell az webapp create \ --name MY_WEBAPP_NAME \ --plan MY_APP_SERVICE_PLAN \ --resource-group MY_RESOURCE_GROUP \ --deployment-container-image-name nginx:latest Dans la commande ci-dessus, remplacez les paramètres par vos propres valeurs, où MY_WEBAPP_NAME correspond au nouveau nom de l’application web. 3. Configurez un profil de publication Azure, et créez un secret AZURE_WEBAPP_PUBLISH_PROFILE. Générez vos informations d’identification de déploiement Azure à l’aide d’un profil de publication. Pour plus d’informations, consultez « Générer les informations d’identification du déploiement » dans la documentation Azure. Dans votre dépôt GitHub, créez un secret nommé AZURE_WEBAPP_PUBLISH_PROFILE, qui contient le profil de publication. Pour plus d’informations sur la création de secrets, consultez Utilisation de secrets dans GitHub Actions. 4. Définissez les informations d’identification du Registre pour votre application web. Créez un personal access token (classic) avec les étendues repo et read:packages. Pour plus d’informations, consultez « Gestion de vos jetons d'accès personnels ». Définissez DOCKER_REGISTRY_SERVER_URL sur https://ghcr.io, DOCKER_REGISTRY_SERVER_USERNAME sur le nom d’utilisateur GitHub ou l’organisation propriétaire du référentiel, et DOCKER_REGISTRY_SERVER_PASSWORD sur votre personal access token ci-dessus. Cela donnera à votre application web des informations d’identification qui lui permettront d’extraire l’image conteneur une fois que votre workflow aura envoyé une image nouvellement générée au Registre. Pour ce faire, vous pouvez utiliser la commande Azure CLI suivante : az webapp config appsettings set \ --name MY_WEBAPP_NAME \ --resource-group MY_RESOURCE_GROUP \ --settings DOCKER_REGISTRY_SERVER_URL=https://ghcr.io DOCKER_REGISTRY_SERVER_USERNAME=MY_REPOSITORY_OWNER DOCKER_REGISTRY_SERVER_PASSWORD=MY_PERSONAL_ACCESS_TOKEN 5. Si vous le souhaitez, configurez un environnement de déploiement. Les environnements sont utilisés pour décrire une cible de déploiement général comme production, staging ou development. Quand un workflow GitHub Actions est déployé dans un environnement, l’environnement s’affiche dans la page principale du dépôt. Vous pouvez utiliser des environnements pour exiger l’approbation d’un travail, restreindre les branches pouvant déclencher un workflow, contrôler les déploiements avec des règles de protection de déploiement personnalisées, ou limiter l’accès aux secrets. Pour plus d’informations sur la création d’environnements, consultez « Utilisation d’environnements pour le déploiement ». Création du workflow Une fois les conditions préalables remplies, vous pouvez procéder à la création du workflow. L’exemple de workflow suivant montre comment créer et déployer un conteneur Docker sur Azure App Service lorsqu’il y a un envoi (push) vers la branche main. Veillez à définir le paramètre AZURE_WEBAPP_NAME de la clé env du workflow sur le nom de l’application web que vous avez créée. Si vous avez configuré un environnement de déploiement, remplacez la valeur environment par le nom de votre environnement. Si vous n’avez pas configuré d’environnement , supprimez la clé environment. YAML # Ce workflow utilise des actions qui ne sont pas certifiées par GitHub. # Elles sont fournies par un tiers et régies par # des conditions d’utilisation du service, une politique de confidentialité et un support distincts. # documentation en ligne. # GitHub recommande d’épingler les actions à un SHA de commit. # Pour obtenir une version plus récente, vous devez mettre à jour le SHA. # Vous pouvez également référencer une balise ou une branche, mais l’action peut changer sans avertissement. name: Build and deploy a container to an Azure Web App env: AZURE_WEBAPP_NAME: MY_WEBAPP_NAME # set this to your application's name on: push: branches: - main permissions: contents: 'read' packages: 'write' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v2 - name: Log in to GitHub container registry uses: docker/login-action@v2 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Lowercase the repo name run: echo "REPO=${GITHUB_REPOSITORY,,}" >>${GITHUB_ENV} - name: Build and push container image to registry uses: docker/build-push-action@v4 with: push: true tags: ghcr.io/${{ env.REPO }}:${{ github.sha }} file: ./Dockerfile deploy: runs-on: ubuntu-latest needs: build environment: name: 'production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Lowercase the repo name run: echo "REPO=${GITHUB_REPOSITORY,,}" >>${GITHUB_ENV} - name: Deploy to Azure Web App id: deploy-to-webapp uses: azure/webapps-deploy@85270a1854658d167ab239bce43949edb336fa7c with: app-name: ${{ env.AZURE_WEBAPP_NAME }} publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }} images: 'ghcr.io/${{ env.REPO }}:${{ github.sha }}' Ressources supplémentaires Les ressources suivantes peuvent également être utiles : • Pour le workflow de démarrage d’origine, consultez azure-container-webapp.yml dans le dépôt starter-workflows de GitHub Actions. • L’action utilisée pour déployer l’application web est l’action Azure Azure/webapps-deploy officielle. • Pour obtenir d’autres exemples de workflows GitHub Action qui se déploient sur Azure, reportez-vous au dépôt actions-workflow-samples.
__label__pos
0.522592
Jump to: navigation, search Configure the ACME Sample Web Application Important This procedure is optional. There are two ways to generate tasks that will be processed by the ACME solution. One is to generate tasks through an ACME sample web site. The second is to generate tasks by using some xml files that are provided with the ACME sample. You need only follow this procedure if you wish to generate tasks using the ACME sample web site. 1. Install a supported database server. The database scripts for the sample ACME Web site are provided for both MySQL and Microsoft SQL Server. Important Only scripts for the MySQL database are provided with the ACME sample that comes on the iWD Manager CD. However, the Web site from which you downloaded these instructions includes a script for Microsoft SQL Server, as well as some updated php files to use with your ACME web site, that support both MySQL as well as MS SQL Server. 2. Create a new database for the ACME web application. Give it a meaningful name such as acme. 3. Execute the SQL script against your new database, to create the data that is used by the sample ACME Web site. 1. If you are using MySQL, use the create.sql script that is located in the …\acme\db\ subdirectory inside the iWD Manager directory created when you installed the iWD Manager installation package. By default this path will be: C:\Program Files\GCTI\iWD Manager\acme\db\ 2. If you are using Microsoft SQL Server, use the create_mssql.sql file from the Web site where you downloaded this document. This file can be found in the create_mssql.zip archive. 4. Install Apache HTTP Server 2.2 You can find the software at http://httpd.apache.org/download.cgi 5. Install PHP 5.2 (thread-safe version of the Windows installer). You can find the software at http://windows.php.net/download/archives/ Use the newest available version(php-5.2.17-Win32-VC6-x86.msi. Installation options you should select: • Web Server Setup—Select Apache 2.2.x Module Select as the Apache Configuration Directory (assuming you picked the default path when you installed Apache 2.2; otherwise, select the path to the \conf\ directory based on where you installed Apache 2.2: C:\Program Files\Apache Software Foundation\Apache2.2\conf\ • In Choose Items to Install, select the following Extensions: • SOAP • MySQL (if you are using MySQL as the database for the ACME Web site) • MS SQL (if you are using Microsoft SQL Server as the database for the ACME Web site) 6. Edit the Apache httpd.conf file located here (if you accepted the default installation directory when you installed Apache earlier): C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf and add the following line to the end of the file: DirectoryIndex index.php Additionally, check that the values for PHPIniDir and LoadModule php5_module are correct, and update them if they are pointing to the incorrect location of these items. 7. Edit the php.ini file located here (if you accepted the default installation directory when you installed PHP): C:\Program Files\PHP\php.ini and change: short_open_tag = On 8. Copy the content of the …\acme\web\ subdirectory from the iWD Manager installation directory to: C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\acme 9. Make a copy of dbInfo.template.php and rename the copy as dbInfo.php. Place this file into C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\acme, overwriting the version that is already there. 10. Edit the renamed dbInfo.php and set the following properties. Save your changes when you are done: 1. $DBENGINE to either mssql or mysql 2. $USERNAME to the username of your acme database 3. $PASSWORD to the password for your acme database 4. $DATABASE to the name of your acme database 5. $HOSTNAME to the hostname of your database server 6. $WEB_SERVICE to the correct Web Service Capture Point URL. You need to provide correct hostname and port for your interaction server and the name of the Web Service Capture Point to be used. 7. $SERVER_URL = to the correct URL for your ACME web site (e.g. http://localhost/acme/) 11. Start (or restart, if it is already running) the Apache 2.2 service 12. Open a Web browser and navigate to http://localhost/acme/ Verify that the web application works correctly. For example, select United Kingdom -> Contact Us -> Information Request Form. All the fields in the form should be pre-populated with values. This page was last edited on August 25, 2014, at 11:52. Comments or questions about this documentation? Contact us for support!
__label__pos
0.542715
Helper Functions Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc. Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions. CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views. Helpers are typically stored in your system/Helpers, or application/Helpers directory. CodeIgniter will look first in your application/Helpers directory. If the directory does not exist or the specified helper is not located there CI will instead look in your global system/Helpers/ directory. Loading a Helper Loading a helper file is quite simple using the following method: helper('name'); Where name is the file name of the helper, without the .php file extension or the “helper” part. For example, to load the Cookie Helper file, which is named cookie_helper.php, you would do this: helper('cookie'); If you need to load more than one helper at a time, you can pass an array of file names in and all of them will be loaded: helper(['cookie', 'date']); A helper can be loaded anywhere within your controller methods (or even within your View files, although that’s not a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so that they become available automatically in any function, or you can load a helper in a specific function that needs it. Note The Helper loading method above does not return a value, so don’t try to assign it to a variable. Just use it as shown. Note The URL helper is always loaded so you do not need to load it yourself. Loading from Non-standard Locations Helpers can be loaded from directories outside of application/Helpers and system/Helpers, as long as that path can be found through a namespace that has been setup within the PSR-4 section of the Autoloader config file. You would prefix the name of the Helper with the namespace that it can be located in. Within that namespaced directory, the loader expects it to live within a sub-directory named Helpers. An example will help understand this. For this example, assume that we have grouped together all of our Blog-related code into its own namespace, Example\Blog. The files exist on our server at /Modules/Blog/. So, we would put our Helper files for the blog module in /Modules/Blog/Helpers/. A blog_helper file would be at /Modules/Blog/Helpers/blog_helper.php. Within our controller we could use the following command to load the helper for us: helper('Modules\Blog\blog'); Note The functions within files loaded this way are not truly namespaced. The namespace is simply used as a convenient way to locate the files. Using a Helper Once you’ve loaded the Helper File containing the function you intend to use, you’ll call it the way you would a standard PHP function. For example, to create a link using the anchor() function in one of your view files you would do this: <?php echo anchor('blog/comments', 'Click Here');?> Where “Click Here” is the name of the link, and “blog/comments” is the URI to the controller/method you wish to link to. “Extending” Helpers TODO: Determine how these can be extended… namespaces, etc? To “extend” Helpers, create a file in your application/helpers/ folder with an identical name to the existing Helper, but prefixed with MY_ (this item is configurable. See below.). If all you need to do is add some functionality to an existing helper - perhaps add a function or two, or change how a particular helper function operates - then it’s overkill to replace the entire helper with your version. In this case it’s better to simply “extend” the Helper. Note The term “extend” is used loosely since Helper functions are procedural and discrete and cannot be extended in the traditional programmatic sense. Under the hood, this gives you the ability to add to or or to replace the functions a Helper provides. For example, to extend the native Array Helper you’ll create a file named application/helpers/MY_array_helper.php, and add or override functions: // any_in_array() is not in the Array Helper, so it defines a new function function any_in_array($needle, $haystack) { $needle = is_array($needle) ? $needle : array($needle); foreach ($needle as $item) { if (in_array($item, $haystack)) { return TRUE; } } return FALSE; } // random_element() is included in Array Helper, so it overrides the native function function random_element($array) { shuffle($array); return array_pop($array); } Now What? In the Table of Contents you’ll find a list of all the available Helper Files. Browse each one to see what they do.
__label__pos
0.782022
Jagran Josh Logo 1. Home 2. |   3. Bank Recruitment|   How to Solve Data Sufficiency Questions Quickly Sep 23, 2016 18:40 IST How to Solve Data Sufficiency Questions Quickly How to Solve Data Sufficiency Questions Quickly Data sufficiency (DS) is one of the most important parts of Quant Section of various competitive examinations like IBPS PO, SBI PO, LIC, RBI, CAT etc. The Data Sufficiency questions do not require the exam aspirant to find the exact answer. Infact the only thing that they require is to determine whether the statements provided in the question contain enough information for answering it. There is a great chance that in any exam, you will see at least 5 questions from this topic. That means, you should spend some time getting confident with these types of questions. We have seen that a majority of aspirants try follow guess work to solve these data sufficiency questions. This is not the right approach. So instead of guessing, we should use certain tips and tricks to solve these questions. • Don’t  Solve the Question: The interesting part about DS type questions is that they only ask you whether the question can be solved with the help of information given in the statements. That simply means there is no need to solve that question completely and waste your precious time. So just answer these questions and do not even try to solve them .There are several common tricks. Do not think in terms of "What will be the exact value?" or "Is it true or false?" Instead, just focus on only one issue: "Is the information enough o answer the question?" Example:               Directions:- • if statement I alone is sufficient to answer the question, Marks A as answer • if statement II alone is sufficient to answer the question, Marks B as answer • if statement I and II together are sufficient to answer the question but neither statement aloneis sufficient to answer the question, Marks C as answer • if either statement I or II aloner is sufficient to answer the question, Marks D as answer • if statement I and II together are not sufficient to answer the question, Marks E as answer How much was the cost of Diamond Necklace in January 2000? (1) In January 2010 the necklace was worth $10,000. (2) Over the ten years 2000-2010, the necklace increased in value by 10% each 12 months. Solution Statement (1) is insufficient. You don't know the rate at which value has changed. You immediately know the answer must be B, C or E. Statement (2) is insufficient. Without a value between 2000 and 2010, you can't calculate the value. Using statements (1) and (2) together, you could calculate the value in 2000. Since you need both statements to find the value, the answer is option (C).  The trick: Don't do the calculation. For most "value" questions, you could calculate the value but calculations are a waste of time. The problem asks if there is enough information to answer the question, not for the actual answer. • Atempt YES NO type questions first  A number of questions are based on “YES-NO” type data. See the statements and discard them on the basis of yes or no. Example:  • if statement I alone is sufficient to answer the question, Marks A as answer • if statement II alone is sufficient to answer the question, Marks B as answer • if statement I and II together are sufficient to answer the question but neither statement aloneis sufficient to answer the question, Marks C as answer • if either statement I or II aloner is sufficient to answer the question, Marks D as answer • if statement I and II together are not sufficient to answer the question, Marks E as answer Is x divisible by 28? Statement I: x is divisible by 20 Statement II: x is divisible by 84 Answer. Using statement I - x is divisible by 4 and 5 Using statement II - x is divisible by 3, 4 and 7. By using both statements we can conclude that x is divisible by 28 (4*7), hence answer is C. • Treat both the statements separately:  So now you have studied the question and analyzed the information given in, now is the time to analyze the statements given in the question. The key rule here “Read statements independently of each other”. Try to “forget” statement 1 before you move on to statement 2. Don’t carry over any info from statement 1 when you read statement 2. Example: How many adults eat pizza in city X if all adults in city X either eat Pizza or Pasta? (1) 75% of the 100,000 adults in city X eat Pasta. (2) 75,000 adults in city X eat Pasta. Solution Statement (1) is sufficient. Taking a percent of a total population allows you to calculate the adults that eat pizza. (NO need to do the calculation.) You immediately know the answer is A or D. Statement (2) is insufficient. Without the total population or other information, you can't calculate the number of adults eating pasta. Since first statement alone is sufficient, the correct answer is option (A). The trick: Keep the information from first statement and second statement as separate. Either the percentage or total population from first statement can make second statement sufficient.  Always read each statement separately.  When you read second statement, forget what you read in first statement so you can evaluate second statement alone. The only time to combine the statements is when each of them is insufficient alone • Eliminate wrong options: This will help you to eliminate the statements quickly if you have something to compare with the information given. Do this step with a focused mind. If first statement is sufficient, eliminate B, C, and E. You will now be left with only two options ie A and D. In the same way If second statement is sufficient, eliminate A, C, and E. You will now be left with only two options ie B and D. Conversely if first statement is NOT sufficient, eliminate A and D In the same if second statement is NOT sufficient, eliminate B and D. In this way you can eliminate a number of options. Key Point to Note: Don't remember the sequence of the options. Sometimes they may even change the sequence of the options. So always read the sequence of options in the exam. This article is prepared by Amit Chaudhary, Education Consultant at MockBank.com, a Bengaluru based online test preparation company for government/PSU jobs. DISCLAIMER: JPL and its affiliates shall have no liability for any views, thoughts and comments expressed on this article. Latest Videos Register to get FREE updates All Fields Mandatory • (Ex:9123456789) • Please Select Your Interest • Please specify • ajax-loader • A verifcation code has been sent to your mobile number Please enter the verification code below Newsletter Signup Follow us on This website uses cookie or similar technologies, to enhance your browsing experience and provide personalised recommendations. By continuing to use our website, you agree to our Privacy Policy and Cookie Policy. OK X Register to view Complete PDF
__label__pos
0.867184
Archived This forum has been archived. Please start a new discussion on GitHub. 2 grids, 1 IceStorm Hi all, I've done the following test. • One machine with IceGrid an IceStorm in replica mode and once ice server S => Machine A • One machine with IceGrid and one server R => Machine B We want S and R to be able to broadcast and listen to the same IceStorm "message_me" method. Server R subscribes to the IceStorm of Machine A. This requires doing a set_locator on the proxy of the topicmanager otherwise it cannot find IceStorm. This done, when Server R messages IceStorm, S gets the message. However when S sends a message, R cannot receive it, as IceStorm cannot locate R (no object adapter with id 'R' registered). I think the problem is that IceStorm only looks for servers on its current locator. Is it possible to "share" one IceStorm with two different grids? Comments • benoit benoit Rennes, France Hi, No, there's no way to tell IceStorm to use a given Ice locator for one subscriber and another locator for another subscriber. Why don't you just use a single IceGrid registry here? Cheers, Benoit. • Thanks for the answer Benoît. There's no real intent behind the configuration I'm just hacking around to see if it's possible to use IceStorm as a transgrid communication bus.
__label__pos
0.884612
1 C++捕获构造函数初始化列表中的异常 1.1 什么是构造函数初始化列表中的异常 简单描述下,现在有一个A类,其中的一个成员变量是B类对象的指针,现在A类是通过初始化列表的方式new了一个B类对象,但是在B类对象构造的时候出现了bad_alloc错误,直接导致程序初始化过程中crash,这个问题非常隐蔽和典型。 1.2 如何捕获异常 针对上面的情况,我们写了一个例子,并且写出了下面的异常捕捉代码,该例子使用-1这个长度初始化一个int数组,这个肯定会crash的, #include <iostream> class A { public: A(int array_length) :m_p_array(new int[array_length]) { try { } catch (...) { std::cout << "A constructor failed!" << std::endl; throw; } } virtual~A() { if (m_p_array) { delete[] m_p_array; } } private: int* m_p_array = nullptr; }; int main() { A a(-1); return 0; } 现在编译运行! 遗憾的是,程序出现了崩溃,并没有捕捉到初始化列表中的异常。这是因为,在构造函数时,程序是先执行初始化列表进行初始化,之后再执行构造函数块中的代码,但是初始化列表在创建int数组时就引发了异常,而构造函数块里面的try catch是捕捉不到这个异常的。 那么该如何修改?看下面的代码 #include <iostream> class A { public: A(int array_length) try :m_p_array(new int[array_length]) { } catch (...) { std::cout << "A constructor failed!" << std::endl; throw; } virtual~ A() { if (m_p_array) { delete[] m_p_array; } } private: int* m_p_array = nullptr; }; int main() { A a(-1); return 0; } 注意上面try catch的位置和写法,直接使用try包住了构造函数的初始化列表,然后在构造函数外围使用catch捕捉异常。 编译执行,这个初始化列表异常可以被正常捕获了!
__label__pos
0.999984
Question: What Are The Advantages Of QoS? What is QoS and why is it needed? QoS or Quality of Service in networking is the process of managing network resources to reduce packet loss as well as lower network jitter and latency. QoS is usually applied on networks that cater to traffic that carry resource-intensive data like: Video-on-demand. Voice over IP (VoIP). What should QoS be set to? A proper QoS setup would be to specify that 192.168. 0.20 gets up to 14,000Kbps WAN bandwidth and 192.168. 0.22 gets only up to 5,000Kbps; this configuration gives priority to the first IP address and lower priority to the second. Different routers allow you to configure QoS in different ways. Why does QoS slow down network? When downstream QoS assigns a high priority to streaming video, it also assigns lower priority to the rest of your Internet traffic. That means other tasks like downloading content from the Internet take longer. That seems unsmart to me. How does QoS work? How Does QoS Work? QoS works by marking packets to identify service types, then configuring routers to create separate virtual queues for each application, based on their priority. As a result, bandwidth is reserved for critical applications or websites that have been assigned priority access. Does QoS help gaming? Quality of service (QoS) enables you to prioritize important traffic for activities like gaming and video streaming. … Upstream QoS prioritizes network traffic between the Internet and your local devices such as your Xbox. This feature can help to minimize lag during online gaming. Does QoS affect LAN? The speed of the Internet is lower than LAN speeds a typical user can achieve. Therefore, if the worst bottleneck is your Internet connection — outside of your equipment — QoS will not help it. Bandwidth and traffic going from your LAN to the Internet is usually less than amount coming to your LAN. What is the benefit of QoS? Reduction of costs, through the efficient use of the internet resource, postponing investments in the expansion of links; Minimizes the impact of concurrent non-work-related traffic; Improves user experience, ensuring better response times, according to the priority of access. Is QoS bad? Intelligent QoS WMM is good as far as it goes, but it ameliorates only wireless network contention. It does nothing to resolve the battle for bandwidth among wired network clients. Better routers go further to cover both sides of the network. Is QoS bad for gaming? Router Quality of Service (QoS) QoS prioritizes important time-sensitive data over less crucial data streams. Without this, Windows’s never-ending update downloads are given the same priority as gameplay data. That can result in games that stutter and stall while the rig is grabbing some updates. What is QoS priority rule list? QoS Rules are customized settings to tell the router what types of traffic to give priority to. Each rule will allow you to assign priority to a certain type of connection (e.g. Skype), which the router will then use to start filtering your bandwidth. Where is QoS used? Organizations use QoS to meet the traffic requirements of sensitive applications, such as real-time voice and video, and to prevent the degradation of quality caused by packet loss, delay and jitter. Organizations can achieve QoS by using certain tools and techniques, such as jitter buffer and traffic shaping. Is QoS necessary? The quality of service option is supposed to help prioritize network traffic, but in actuality, it often slows down important connections, misidentifies devices and cripples upload speeds. While it can theoretically do some good on very crowded networks, QoS can also create more problems than it solves.
__label__pos
0.999995
Waste less time on Facebook — follow Brilliant. × Back to all chapters Fractions 5 out of 4 people have trouble with fractions. Don't be one of them. Adding Fractions           Evaluate \[ \frac{3}{4} + \frac{1}{4} + \frac{3}{4}. \] If the expression \[\frac{5}{3}+\frac{3}{4}\] is written in simplest form and as an improper fraction, what is the value of the numerator? Evaluate \[ 5\frac{2}{3} - 1\frac{1}{3} - 2\frac{2}{3}. \] Evaluate \[\frac{13}{2}-\frac{5}{3}+\frac{3}{2}-\frac{7}{3}.\] Which of the following is equal to \[\frac{14}{3}+\frac{3}{6} ? \] × Problem Loading... Note Loading... Set Loading...
__label__pos
0.999892
6 When it comes to the evaluation of a methodology (or an algorithm (CS)) we usually see how well the methodology actually is by comparing it with other similar methods that achieve the same thing. However, in my case, the method we are proposing is unique and novel and, to best of my knowledge, isn't used anywhere else. Is it valid to evaluate it on its own, for example by simply measuring its time/complexity against n datasets? How would we perform evaluation for methods that can't be compared against others? • 5 The fact that the method itself is unique is not the important thing here. The relevant thing is that the thing it achieves is something nothing else does. – Tobias Kildetoft Mar 6 '15 at 8:12 15 TL;DR: if you don't know how to evaluate your work, you probably don't know exactly what research question you are working on. How would we perform evaluation for methods that can't be compared against others? I work in applied computer science, and this qualifies as the Number One statement my master students usually have when I ask them how they plan to evaluate their work - "I can't compare my tool / approach against anything - no existing tool has exactly the same scope, so the comparison won't be fair!". This is of course true, but it also shows a misunderstanding about the research question that the work is addressing. Essentially, the "compare against a standard tool" approach is a valuable evaluation method if the research question is "Can we improve the performance/quality/whatever of an approach that does X?". If the research question is rather, as presumably in your case, "Can we find an approach that does X?", the evaluation of course needs to be different. In that case, you need to find an evaluation that actually shows what you claim your approach does. Some recent examples from my students: Is your claim that it makes sense to show software developers certain information, which isn't visualized by any other development tool? In that case you need to set up a study where you show that developers that see this piece of information do something better than developers that don't. Is your claim that taking costs of cloud resources into account when scheduling tasks allows for cheaper execution with the same quality? Set up an experiment where you compare costs with and without taking costs into account for a number of representative workloads. Orthogonally, it often makes sense to do a partial comparison to existing approaches and tools, to also check how your approach fares in comparison to standard tools on standard problems, essentially to make sure that the improvement your approach presumably has in a "new" dimension does not mean that something else does not work anymore. For instance, in the development tool example above, you may also want to check if the new visualization distracts people so much that they now fare less well in usual development tasks than with standard tools. 5 There are two things that you need to evaluate with your method: 1. Does the method actually do what you want it to / claim it does? 2. What improvement does the method offer over prior work? No matter what you are doing and how unique it is, you need to be able to validate #1 (preferably experimentally, but simulation and analytic methods can be fine as well). If you can't do that, you aren't doing science. The improvement, however, may be either qualitative or quantitative. If it is a quantitative improvement, you must be able to validate by direct comparison (e.g., 30% faster, 5 db more gain, quadratic rather than exponential growth). For a qualitative improvement, however, you may not need to compare if you can demonstrate that prior methods simply do not address certain aspects of your problem (e.g., you can predict upcoming frozbozz failures, but nobody else has even tried). In this case, the comparison with other methods is most appropriately done in the literature review. 3 When proposing a new technique, where there isn't an equivalent to compare performance with, I tend to do as you suggested, and measure the time/complexity, and give some real world data points (it would take X time to operate on realistic situation Y). Depending on the specific work, you could present an analysis of it based on rationale (for example, evaluating the security of a proposal by explaining the assumptions and demonstrating it is secure against certain threat models). If there really is nothing which can do the same task, then you can't do a comparison. But perhaps there is another technique which, while technically different, can be used to solve a similar problem to your technique? You could compare performance within the context of that problem in that case. 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.981723
aboutsummaryrefslogtreecommitdiffstats path: root/wpa_supplicant/wpa_gui-qt4/eventhistory.cpp blob: a36085d21a6ca86dc1c711e1b7a345ff3ebf1ada (plain) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 /* * wpa_gui - EventHistory class * Copyright (c) 2005-2006, Jouni Malinen <[email protected]> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include <QHeaderView> #include <QScrollBar> #include "eventhistory.h" int EventListModel::rowCount(const QModelIndex &) const { return msgList.count(); } int EventListModel::columnCount(const QModelIndex &) const { return 2; } QVariant EventListModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole) if (index.column() == 0) { if (index.row() >= timeList.size()) return QVariant(); return timeList.at(index.row()); } else { if (index.row() >= msgList.size()) return QVariant(); return msgList.at(index.row()); } else return QVariant(); } QVariant EventListModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case 0: return QString(tr("Timestamp")); case 1: return QString(tr("Message")); default: return QVariant(); } } else return QString("%1").arg(section); } void EventListModel::addEvent(QString time, QString msg) { beginInsertRows(QModelIndex(), msgList.size(), msgList.size() + 1); timeList << time; msgList << msg; endInsertRows(); } EventHistory::EventHistory(QWidget *parent, const char *, bool, Qt::WFlags) : QDialog(parent) { setupUi(this); connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); eventListView->setItemsExpandable(FALSE); eventListView->setRootIsDecorated(FALSE); elm = new EventListModel(parent); eventListView->setModel(elm); } EventHistory::~EventHistory() { destroy(); delete elm; } void EventHistory::languageChange() { retranslateUi(this); } void EventHistory::addEvents(WpaMsgList msgs) { WpaMsgList::iterator it; for (it = msgs.begin(); it != msgs.end(); it++) addEvent(*it); } void EventHistory::addEvent(WpaMsg msg) { bool scroll = true; if (eventListView->verticalScrollBar()->value() < eventListView->verticalScrollBar()->maximum()) scroll = false; elm->addEvent(msg.getTimestamp().toString("yyyy-MM-dd hh:mm:ss.zzz"), msg.getMsg()); if (scroll) eventListView->scrollToBottom(); }
__label__pos
0.872505
0705. Design Hash Set 705. Design HashSet # 题目 # Design a HashSet without using any built-in hash table libraries. To be specific, your design should include these functions: • add(value): Insert a value into the HashSet. • contains(value) : Return whether the value exists in the HashSet or not. • remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing. Example: MyHashSet hashSet = new MyHashSet(); hashSet.add(1);         hashSet.add(2);         hashSet.contains(1);    // returns true hashSet.contains(3);    // returns false (not found) hashSet.add(2);           hashSet.contains(2);    // returns true hashSet.remove(2);           hashSet.contains(2);    // returns false (already removed) Note: • All values will be in the range of [0, 1000000]. • The number of operations will be in the range of [1, 10000]. • Please do not use the built-in HashSet library. 题目大意 # 不使用任何内建的哈希表库设计一个哈希集合具体地说,你的设计应该包含以下的功能: • add(value):向哈希集合中插入一个值。 • contains(value) :返回哈希集合中是否存在这个值。 • remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。 注意: • 所有的值都在 [1, 1000000] 的范围内。 • 操作的总数目在 [1, 10000] 范围内。 • 不要使用内建的哈希集合库。 解题思路 # • 简单题,设计一个 hashset 的数据结构,要求有 add(value)contains(value)remove(value),这 3 个方法。 代码 # package leetcode type MyHashSet struct { data []bool } /** Initialize your data structure here. */ func Constructor705() MyHashSet { return MyHashSet{ data: make([]bool, 1000001), } } func (this *MyHashSet) Add(key int) { this.data[key] = true } func (this *MyHashSet) Remove(key int) { this.data[key] = false } /** Returns true if this set contains the specified element */ func (this *MyHashSet) Contains(key int) bool { return this.data[key] } /** * Your MyHashSet object will be instantiated and called as such: * obj := Constructor(); * obj.Add(key); * obj.Remove(key); * param_3 := obj.Contains(key); */ ⬅️上一页 下一页➡️ Calendar Sep 6, 2020 Edit Edit this page 本站总访问量:  次 您是本站第  位访问者
__label__pos
0.938932
Google Go で碁…… を作るのはさすがに無理なので五目並べをつくろう……と思ったらわたしには難しかったんで三目並べ(いわゆるマルバツ)を作ってみました。 ウォーゲームによると三目並べで核戦争が回避されるらしいのでこれでいいのだ。 • ということでコンピュータ対コンピュータの対戦を見るだけです • 一応ミニマックス法で全探索してます • 全探索なので評価関数は非常に簡単にしてます • 第一手はさすがに探索に時間(とメモリ)がかかるのでランダムにしてます(評価関数の値的に第一手はどこでも同じ) • 敵がアホだった場合の考慮をしていないです • 文献読んで自分なりに組んだのでミニマックス法の参考にはなりません Go 言語の感想。 • 率直にいって好き嫌いでいうと嫌い • スクリプト言語よりは C 言語に相当近い • スクリプト言語に慣れているといろいろ面倒 • でも C や C++ + STL とかでごにょごにょ自力で書く人にはいいのかも • 使っていて D言語とか(←使ったことないけど)とか Lua とか Pascal とか思い起こした • もちろんこのへんは言語経験によると思います • 言語系に含まれるソートが、Sort される要素に Sortable な interface を実装するとか、その発想にビックリ • でもはっきりいって比較関数をわたすほうが楽だと思った なんか Go で書くのが流行ってるみたいなので - muddy brown thang2009-11-11 - nobu-qの日記 を参考にさせていただきました。 package main import "fmt" import "sort" import "rand" import "time" type Board [3][3]int; var cellImage = map[int]string { 0: " ", 1: "O", -1: "X" }; func (board *Board) render() { fmt.Print("+-+-+-+\n"); for y := 0; y < len(board); y ++ { line := board.hline(y); fmt.Print("|"); for x := 0; x < len(line); x ++ { fmt.Print(cellImage[line[x]]); fmt.Print("|"); } fmt.Print("\n"); fmt.Print("+-+-+-+\n"); } } func (board *Board) hline(y int) [3]int { return [3]int { board[0][y], board[1][y], board[2][y] }; } func (board *Board) vline(x int) [3]int { return board[x] } func (board *Board) cross(r int) [3]int { if r > 0 { return [3]int { board[0][0], board[1][1], board[2][2] }; } return [3]int { board[0][2], board[1][1], board[2][0] }; } func score_for_line(line [3]int, me int) int { if line[0] * me > 0 && line[1] * me > 0 && line[2] * me > 0 { return 1 } return 0 } func (board *Board) score_of_me(me int) int { switch true { case score_for_line(board.cross(1), me) > 0: return 1; case score_for_line(board.cross(-1), me) > 0: return 1; } for i := 0; i < 3; i ++ { switch true { case score_for_line(board.vline(i), me) > 0: return 1; case score_for_line(board.hline(i), me) > 0: return 1; } } return 0 } func (board *Board) score_for(me int) int { switch true { case board.score_of_me(me) > 0: return 1; case board.score_of_me(-me) > 0: return -1; } return 0 } func (board *Board) filled() bool { for y := 0; y < 3; y ++ { for x := 0; x < 3; x ++ { if board[x][y] == 0 { return false } } } return true; } type GoStep struct { x int; y int; score float; }; type GoStepArray []GoStep; func (steps GoStepArray) Len() int { return len(steps); } func (steps GoStepArray) Less(i, j int) bool { return steps[i].score > steps[j].score; } func (steps GoStepArray) Swap(i, j int) { steps[i], steps[j] = steps[j], steps[i]; } func (steps GoStepArray) Sort() { sort.Sort(steps); } func find_child_steps(ch chan GoStep, board Board, me int, depth int, x, y int) { board[x][y] = me; score := board.score_for(me); if score != 0 { ch <- GoStep{ x, y, float(score) }; return; } op_cands := find_steps(board, -me, depth + 1); if len(op_cands) <= 0 { ch <- GoStep{ x, y, 0 }; } else { ch <- GoStep{ x, y, - op_cands[0].score * 0.9 }; } } func find_steps(board Board, me int, depth int) GoStepArray { ch := make(chan GoStep); num_cands := 0; for y := 0; y < 3; y ++ { for x := 0; x < 3; x ++ { if board[x][y] != 0 { continue } num_cands ++; if depth == 0 { fmt.Print("."); } go find_child_steps(ch, board, me, depth, x, y); } } cands := make(GoStepArray, num_cands); for i := 0; i < num_cands; i ++ { cand := <- ch; cands[i] = cand; } cands.Sort(); if depth == 0 { fmt.Print("\n"); } return cands; } func decide_step(board Board, me int) (int, int) { cands := find_steps(board, me, 0); if len(cands) <= 0 { return -1, -1; } score := cands[0].score; n := 1; for n < len(cands) { if cands[n].score != score { break } n ++; } cand := cands[rand.Intn(n)]; return cand.x, cand.y; } func main() { rand.Seed(time.Nanoseconds()); var board Board; me := 1; board[rand.Intn(3)][rand.Intn(3)] = me; me = -me; for { board.render(); if board.score_for(me) != 0 { break } if board.filled() { break } x, y := decide_step(board, me); board[x][y] = me; me = -me; } } 無理やり go routine と channel を使ってます。 気のせいかもしれないけど、channel を作って、作った本人と go routine で呼び出される両者から channel に同時書き込むと不安定だった気がします。仕様とかちゃんと確認してませんが。
__label__pos
0.979621
Welcome :: Homework Help and Answers :: Mathskey.com Welcome to Mathskey.com Question & Answers Community. Ask any math/science homework question and receive answers from other members of the community. 13,435 questions 17,804 answers 1,438 comments 776,696 users How would you rewrite the expressions using the power-reducing formulas in Trigonometry? +3 votes In terms of the first power of the cosine. 1. cos^4(x) 2. sin^2(x)cos^2(x) On the book, the answer to the first is: (1/8)(3 + 4cos2x + cos4x) and the second: (1/8)(1 - cos4x) asked Jan 10, 2013 in TRIGONOMETRY by mathgirl Apprentice 4 Answers +4 votes  = cos4(x)  = [ cos2x]2  {Note : cos2x = ( 1 + cos 2x) / 2 }  = [ ( 1/2 )( 1 + cos 2x)]2 {Note : (AB)2 = A2B2} =   ( 1/2 )2( 1 + cos 2x)2                                                     { Note :  (AB)2 =A2 + B2 +  2AB }  = ( 1/4 ) ( 1 + 2cos2x + cos22x) {Note : cos2x = ( 1 + cos 2x) / 2  , cos4x  = ( 1/2 )( 1 + cos 4x ) }  = ( 1/4 ) [ 1 + 2cos2x +( 1/2 )( 1 + cos 4x) ] Simplfy  = ( 1/4 ) [ 1 + 2cos2x +( 1/2 ) + ( 1/2 )cos 4x ] Simplfy  = ( 1/4 ) +( 1/4 ) 2cos2x +( 1/4 )( 1/2 ) + ( 1/4 )( 1/2 )cos 4x ] = ( 1/4 ) +( 1/4 ) 2cos2x + ( 1/8 ) + ( 1/8 ) cos 4x  = ( 1/4 ) + ( 1/8 ) +( 1/2 ) cos2x+ ( 1/8 ) cos 4x  = ( 3/8 ) + ( 1/2 ) cos2x+ ( 1/8 ) cos 4x                          LCM in 4 , 8 is 8  Take out common factors.  = ( 1/8 )[ 3 + 4cos 2x + cos 4x ]  Ther fore cos4(x) = ( 1/8 )[ 3 + 4cos 2x + cos 4x ] answered Jan 10, 2013 by richardson Scholar +3 votes  = cos4(x)  = [ cos2x]2  {Note : cos2x = ( 1 + cos 2x) / 2 }  = [ ( 1/2 )( 1 + cos 2x)]2 {Note : (AB)2 = A2B2} =   ( 1/2 )2( 1 + cos 2x)2                                                     { Note :  (AB)2 =A2 + B2 +  2AB }  = ( 1/4 ) ( 1 + 2cos2x + cos22x) {Note : cos2x = ( 1 + cos 2x) / 2  , cos4x  = ( 1/2 )( 1 + cos 4x ) }  = ( 1/4 ) [ 1 + 2cos2x +( 1/2 )( 1 + cos 4x) ] Simplfy  = ( 1/4 ) [ 1 + 2cos2x +( 1/2 ) + ( 1/2 )cos 4x ] Simplfy  = ( 1/4 ) +( 1/4 ) 2cos2x +( 1/4 )( 1/2 ) + ( 1/4 )( 1/2 )cos 4x ] = ( 1/4 ) +( 1/4 ) 2cos2x + ( 1/8 ) + ( 1/8 ) cos 4x  = ( 1/4 ) + ( 1/8 ) +( 1/2 ) cos2x+ ( 1/8 ) cos 4x  = ( 3/8 ) + ( 1/2 ) cos2x+ ( 1/8 ) cos 4x                          LCM in 4 , 8 is 8  Take out common factors.  = ( 1/8 )[ 3 + 4cos 2x + cos 4x ]  Ther fore cos4(x) = ( 1/8 )[ 3 + 4cos 2x + cos 4x ] answered Jan 10, 2013 by richardson Scholar +3 votes = sin2(x)cos2(x) = [sin(x)cos(x)]2 Divide , Multiply by 1/4 ( 1/4 )4[sin(x)cos(x)]2 Simplfy ( 1/4 )[2sin(x)cos(x)]2 [Note : 2sinAcosA = sin2A] ( 1/4 )[sin2(x)]2 [Note : sin2A = ( 1- cos2A) / 2  ,  sin22A = ( 1- cos4A) / 2 ] ( 1/4 )[( 1- cos4x) / 2 ] Simplfy ( 1/8 )( 1 - cos4x ) There fore sin2(x)cos2(x) = ( 1/8 )( 1 - cos4x ) answered Jan 10, 2013 by richardson Scholar +2 votes 1. cos4(x) =  [ cos2x]2 Recall double angle trigonometric identities: cos2x = ( 1 + cos 2x) / 2 } = [(1/2)( 1 + cos 2x)]2 = ( 1/4) ( 1 + cos 2x)2                                                     = ( 1/4 ) ( 1 + 2cos2x + cos22x) = ( 1/4 ) [ 1 + 2cos2x +( 1/2 )( 1 + cos 4x) ] = ( 1/4 ) [ 1 + 2cos2x +( 1/2 ) + ( 1/2 )cos 4x ] = ( 1/4 ) +( 1/4 ) 2cos2x +( 1/4 )( 1/2 ) + ( 1/4 )( 1/2 )cos 4x ] = ( 1/4 ) +( 1/4 ) 2cos2x + ( 1/8 ) + ( 1/8 ) cos 4x = ( 1/4 ) + ( 1/8 ) +( 1/2 ) cos2x+ ( 1/8 ) cos 4x Write the expression with common denominator i.e., 8 = ( 2/8 ) + ( 1/8 ) +( 4/8 ) cos2x+ ( 1/8 ) cos 4x = ( 3/8 ) + ( 4/8 ) cos2x+ ( 1/8 ) cos 4x Take out common factors. = ( 1/8 )[ 3 + 4cos 2x + cos 4x ] cos4(x) = ( 1/8 )[ 3 + 4cos 2x + cos 4x ] answered Jan 25, 2013 by Naren Answers Apprentice Related questions asked Dec 22, 2014 in TRIGONOMETRY by anonymous ...
__label__pos
0.966105
Place an isosceles right triangle in a coordinate plane. Then find the length of the hypotenuse and ... This presentation is the property of its rightful owner. Sponsored Links 1 / 7 EXAMPLE 4 PowerPoint PPT Presentation • 37 Views • Uploaded on • Presentation posted in: General Place an isosceles right triangle in a coordinate plane. Then find the length of the hypotenuse and the coordinates of its midpoint M. SOLUTION. Download Presentation EXAMPLE 4 An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - Presentation Transcript Example 4 Place an isosceles right triangle in a coordinate plane. Then find the length of the hypotenuse and the coordinates of its midpoint M. SOLUTION Place PQOwith the right angle at the origin. Let the length of the legs be k. Then the vertices are located at P(0, k), Q(k, 0), and O(0, 0). EXAMPLE 4 Apply variable coordinates Example 4 = = = = k 2 k k 2 2 = 0 + k , k +0 M( ) M( , ) 2 2 2 2 2 2 2 2 2 k + (– k) 2k k + k (k–0) + (0–k) EXAMPLE 4 Apply variable coordinates Use the Distance Formula to find PQ. PQ = Use the Midpoint Formula to find the midpoint Mof the hypotenuse. Example 4 Write a coordinate proof of the Midsegment Theorem for one midsegment. E(q+p, r) D(q, r) = = GIVEN : PROVE : SOLUTION 1 DE is a midsegment of OBC. 2 DE OCand DE = OC STEP1 Place OBCand assign coordinates. Because you are finding midpoints, use 2p, 2q, and 2r. Then find the coordinates of Dand E. 2q + 2p, 2r + 0 2q + 0, 2r + 0 E( ) D( ) 2 2 2 2 EXAMPLE 5 Prove the Midsegment Theorem Example 4 STEP 2 Prove DE OC. The y-coordinates of Dand Eare the same, so DEhas a slope of 0. OCis on the x-axis, so its slope is 0. 1 Because their slopes are the same, DE OC. 2 Prove DE = OC. Use the Ruler Postulate to find DEand OC. STEP3 = 2p 2p – 0 (q +p) – q OC= = p DE= So, the length of DEis half the length of OC EXAMPLE 5 Prove the Midsegment Theorem Example 4 In Example 5, find the coordinates of F, the midpoint of OC. Then show that EF OB. SOLUTION Given:FE is a midsegment. Prove:FE OB The midpoints are E (q + p, r ) and F = F (p, 0). The slope of both FEand OBis so EF ||OB r q 1 Also, FE = q2 + r2and OB = 2 q2 + r2, so FE = OB. 2 for Examples 4 and 5 GUIDED PRACTICE 7. Example 4 Graph the points O(0, 0), H(m, n), and J(m, 0). Is OHJa right triangle? Find the side lengths and the coordinates of the midpoint of each side. 8. J(m,0) H(m,n) STEP1 Place OHJwith the right angle at the origin The vertices are O(0,0) , , ( 0,0) (m,n) (m,0) O H J for Examples 4 and 5 GUIDED PRACTICE SOLUTION Example 4 = = = HJ = OH = = n m 2 0 + m , n +0 n C( ) C( , ) = 2 2 2 2 2 2 2 2 2 2 2 2 2 0 + (– n) m + (– n) Yes, OHJa right triangle m + n (0 – m) + (0 –n) (m – m) + (0 –n) for Examples 4 and 5 GUIDED PRACTICE STEP2 Use the distance formula to find OH and HJ Use the Midpoint Formula to find the midpoint Cof the hypotenuse. • Login
__label__pos
0.967255
Problem 14 The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. でた、コラッツ予想。前までの計算結果を利用しようとした。コードが汚い。 しかもそんなに速くないぞ?なんで? collatzM _ 1 =(singleton 1 1,1) collatzM t n = case(lookup n t)of Just x->(t,x) Nothing ->let (t',x') = collatzM t next in (insert n (x'+1) t',x'+1) where next |even n = n`div`2 |otherwise =3*n+1 collatzMSeq 1 t = toList t collatzMSeq (n+1) t= case(lookup (n+1) t)of Just x->collatzMSeq n t Nothing ->collatzMSeq n $fst$ collatzM t (n+1) p014 n= maximumBy(compare`on`snd).takeWhile((<n).fst)$collatzMSeq n empty main =putStrLn.show$p014 (10^6-1) More Reading Newer// Problem 13 Older// Problem 15
__label__pos
0.947158
How to: Set Up TrueCrypt Disk Encryption, Part 1 SHARE Share it on Twitter   Share it on Facebook   Share it on Google+ Share it on Linked in   Email   Even if your Windows (or other OS) account is password-protected, thieves can still access your drives and data using simple tools if they aren’t encrypted. Look no further than recent headlines to know the damage one lost or stolen laptop full of patient or client data can do. If you work with sensitive data, you should consider using disk encryption to protect your data from physical theft or hacking.   One easily accessible method of disk encryption for Windows users is BitLocker, a Windows feature that provides disk encryption. Unfortunately, it is only available in the Enterprise and Ultimate editions of Windows Vista and Windows 7, and in Windows Server 2008. Other Windows users will need to employ a third-party tool, such as TrueCrypt, a free, open source disk encryption tool.   TrueCrypt runs on all of the major platforms: Windows XP/Vista/7, Mac OS X, and Linux. There are a variety of encryption options, including system drive support and hidden volumes. TrueCrypt also features real-time or on-the-fly encryption; meaning the files within the encrypted volumes aren’t decrypted until absolutely necessary.   You can use one or more of TrueCrypt’s three encryption methods:   ·        File container: This is the easiest option for beginners and essentially makes a virtual drive that is, of course, encrypted. Though it’s a single file, it can contain other files and folders, similar to a zip or compressed folder. By entering the encryption password, you can mount or assign the file container to a Windows drive letter using TrueCrypt. Therefore, it will appear just like any other drive or partition when browsing your files in Computer or My Computer. Then you can copy and/or drag files into the encrypted drive. Once you unmount or restart the computer, the file container is inaccessible and remains encrypted. Since the file container is like any other file, you can still move, copy, or delete it. ·        Non-system partition or drive: This encrypts an entire secondary partition or drive (where Windows isn’t installed), which can be an internal hard drive, USB flash drive, solid-state drive, or other storage device. This method doesn’t really provide any advantages over the easier method of file containers. However, if you plan to use encrypted drives long-term, you might just want to secure the entire drive or a partition. As with file containers, you have to mount the encrypted drive or partition using TrueCrypt before you can access it. ·        System partition or entire drive: If you want full protection and privacy of your computer and data, you may want to encrypt the primary partition or drive (where Windows is installed). This would protect the system files, such as temporary, cache, hibernation, and swap files. This method, however, is the most complex and may require you to modify your drive partitions.   Each method has a hidden implementation to provide double-protection. This is useful if you are ever forced to reveal your password and encrypted data; or if someone finds your initial password. It works by creating a decoy or outer encrypted volume and then placing a hidden encrypted volume inside. When encrypting the system partition or drive, you can actually create a whole hidden Windows installation.   Setting up an encrypted file container You can follow these steps if you want to create a standard file container:   1.      Open the main TrueCrypt application and click Create Volume. 2.      In the wizard, keep the first option selected (see Figure 2) and click Next.   TrueCrypt fig2_sm.jpg Figure 2. 3.      We’re going to create a standard volume, so leave the first option selected and click Next. 4.      Click Select File, find a location at which to create the volume, give it a name, and click Save to return to the wizard. 5.      To prevent others from easily seeing the location of this file container from the main TrueCrypt window, select the Never save history option. 6.      Click Next to continue. 7.      If you have a favorite encryption or hash algorithm, select them here and click Next; otherwise use the default settings. To see how well each encryption algorithm performs on your PC, click the Benchmark button. After running the test, it will show the speed at which it takes to encrypt and decrypt with each encryption algorithm, with higher speeds being the best. 8.      On the next wizard page, specify the size of the file container you want to create and click Next. Remember, you can’t modify the size later, but you can create additional file containers. 9.      On the Volume Password page (see Figure 3, below), enter a password twice, following the security tips given in the wizard. TrueCryptfig3_sm.jpg  Figure 3. 10.  For an extra layer of protection, you can also use keyfiles in conjunction with the password. Therefore, when you mount the file container as a drive so you can access it, you’d have to enter the password and select the keyfile(s) you’ve created. If you prefer, you can actually apply a blank password when using a keyfile. You can pretty much make any file (such as a doc, mp3, avi, txt, etc.) into a keyfile. You can also specify folders as keyfiles. Keep in mind; you need to choose files and/or folders that aren’t going to be edited or modified. To specify keyfiles, select the Use keyfiles option and click the Keyfiles button. Then create or select the keyfiles and click OK. 11.  Click Next to continue. 12.  On the Volume Format page (see Figure 4), if you have a choice between the FAT and NTFS Filesystem, you probably want to choose NTFS. The other default settings should be fine. Before continuing, help the tool create a highly strong key by moving the mouse around the screen for at least 30 seconds. When you’re done, click Format. 13.  When formatting is complete, click Exit. TrueCrypt fig4_sm.jpg   TrueCrypt fig4_sm.jpg   Figure 4.   Before you can start moving files into the encrypted file container, you must mount it to a drive letter:   1.      Open TrueCrypt, click Select File, browse to the file, and click Open. 2.      Then select the desired drive letter and hit Mount. 3.      On the prompt, enter the password you created. If you created a keyfile, click the Keyfiles button and use the pop-up window to add them. 4.      If you select the Cache passwords and keyfiles in memory option, the credentials are saved until you wipe or clear the cache or restart the computer. Until then you can dismount and mount the file container repeatedly without entering the password and/or keyfiles. 5.      When you’re ready to mount it, click OK.   Now you can double-click the volume to open it. You can also navigate to it via Computer or My Computer like other drives. Then you can start saving, copying, or moving files to it.   In the second and final installment, we’ll work with other encrypted methods, discover how to automatically mount volumes, and review other tips.   Eric Geier is the Founder and CEO of NoWiresSecurity, which helps businesses easily protect their Wi-Fi with enterprise-level encryption by offering an outsourced RADIUS/802.1X authentication service. He is also the author of many networking and computing books for brands like For Dummies and Cisco Press. JOIN THE DISCUSSION Loading Comments...
__label__pos
0.704121
ConvertOctopus Search Unit Converter Conversion formula The conversion factor from miles to millimeters is 1609344, which means that 1 mile is equal to 1609344 millimeters: 1 mi = 1609344 mm To convert 4101 miles into millimeters we have to multiply 4101 by the conversion factor in order to get the length amount from miles to millimeters. We can also form a simple proportion to calculate the result: 1 mi → 1609344 mm 4101 mi → L(mm) Solve the above proportion to obtain the length L in millimeters: L(mm) = 4101 mi × 1609344 mm L(mm) = 6599919744 mm The final result is: 4101 mi → 6599919744 mm We conclude that 4101 miles is equivalent to 6599919744 millimeters: 4101 miles = 6599919744 millimeters Alternative conversion We can also convert by utilizing the inverse value of the conversion factor. In this case 1 millimeter is equal to 1.515169939618E-10 × 4101 miles. Another way is saying that 4101 miles is equal to 1 ÷ 1.515169939618E-10 millimeters. Approximate result For practical purposes we can round our final result to an approximate numerical value. We can say that four thousand one hundred one miles is approximately six billion five hundred ninety-nine million nine hundred nineteen thousand seven hundred forty-four millimeters: 4101 mi ≅ 6599919744 mm An alternative is also that one millimeter is approximately zero times four thousand one hundred one miles. Conversion table miles to millimeters chart For quick reference purposes, below is the conversion table you can use to convert from miles to millimeters miles (mi) millimeters (mm) 4102 miles 6601529088 millimeters 4103 miles 6603138432 millimeters 4104 miles 6604747776 millimeters 4105 miles 6606357120 millimeters 4106 miles 6607966464 millimeters 4107 miles 6609575808 millimeters 4108 miles 6611185152 millimeters 4109 miles 6612794496 millimeters 4110 miles 6614403840 millimeters 4111 miles 6616013184 millimeters
__label__pos
0.528495
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. Me and my friend needs to create a reaction time game. Something like this. Right now we just managed to show an image of the red button, but we need help how to make a hitbox, where if you click the red button, it becomes green. Would someone could show us how? We are using SDL, I guess that's important to mention. Here is our code so far: #include <SDL/SDL.h> void Plot(SDL_Surface *sur, int x, int y, SDL_Surface *dest) { SDL_Rect rect = {x, y}; SDL_BlitSurface(sur, NULL, dest, &rect); } SDL_Surface *LoadImage(const char *filename) { SDL_Surface *sur = NULL; sur = SDL_LoadBMP(filename); if(sur == NULL) { printf("Img not found"); } SDL_Surface *opsur = NULL; if(sur != NULL) { opsur = SDL_DisplayFormat(sur); SDL_SetColorKey(opsur, SDL_SRCCOLORKEY, 0xFFFFFF); if(opsur != NULL) SDL_FreeSurface(sur); } return opsur; } int main(int argc, char **argv) { SDL_Init(SDL_INIT_EVERYTHING); SDL_Surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); SDL_WM_SetCaption("Eksamensprojekt", NULL); SDL_Event Event; bool Running = true; SDL_Surface *sur = LoadImage("Red.bmp"); while(Running) { while(SDL_PollEvent(&Event)) { if(Event.type == SDL_QUIT) Running = false; } SDL_FillRect(screen, &screen->clip_rect, 0x000000); Plot(sur, 215, 140, screen); SDL_Flip(screen); } } share|improve this question 2 Answers 2 You can use SDL_Rect as a hit box. You can use SDL's own event handling system for checking when mouse button is clicked and the position of it. Then you just need to check if the mouse position is within the SDL_Rect. You can read more about SDL here. So... a little help on the way. You have a main loop and you pull events. if ( event.type == SDL_MOUSEBUTTONDOWN ){ //Get mouse coordinates int x = event.motion.x; int y = event.motion.y; //If the mouse is over the button if( checkSpriteCollision( x, y ) ){ // Yay, you hit the button doThings(); } else { // D'oh I missed } } Add this to the while, that will at least get you started. share|improve this answer      We already looked at it and attempted, and still failed :( If you, or anyone else could write it out for us it would be really great :) –  user2298880 May 2 '13 at 14:08      Thanks for the answer, but we still can't get it to work. There are 2 while functions, which one do I insert it into? And how do I make it display the green button when you click? I want it to change from red to green when you click it. –  user2298880 May 2 '13 at 14:49      Put it in the inner loop ( under If ( event.type == SDL_Quit ) ) To switch color you should do basically the same as you do in the plot function, only with a green surface instead of a red. You could use a bool value to determine which of the two surface you should blit. –  olevegard May 2 '13 at 14:55 Like this? while(Running) { while(SDL_PollEvent(&Event)) { if(Event.type == SDL_QUIT) Running = false; if ( event.type == SDL_MOUSEBUTTONDOWN ){ //Get mouse coordinates int x = event.motion.x; int y = event.motion.y; //If the mouse is over the button if( checkSpriteCollision( x, y ) ){ // Yay, you hit the button doThings(); } else { // D'oh I missed } } } SDL_FillRect(screen, &screen->clip_rect, 0x000000); Plot(sur, 215, 140, screen); SDL_Flip(screen); } } share|improve this answer      Please someone awesome at programming help us :D –  user2298880 May 2 '13 at 15:15      Yes, now you have code for checking whether someone clicked the button ( assuming you implmented the CheckSpriteCollision(x,y) function. But you need to move the Plot(...) so that it blits the green surface when someone clicks the button and the red button otherwise. –  olevegard May 2 '13 at 15:48 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.945309
Online Course PW04 - Membuat Pengaturan Profil Web Desa di Halaman admin Membuat Pengaturan Profil Perusahaan di Halaman admin Ikuti langkah berikut ini Pertama, Download komponen plugins CKEDITOR dan CKFINDER DOWNLOAD CKEDITOR Download file tersebut, simpan di dalam folder plugins yang ada di dalam folder assets Lalu, extract file tersebut sehingga di dalam folder plugins menjadi seperti ini folder-plugins Buka folder ckfinder dan buka file config.php lalu edit bagian yang berwarna kuning ( Baris code ke 68), ubah sesuai nama folder web anda, simpan kembali config Simpan kembali file config.php tersebut Kedua, Buat tabel baru dengan nama tb_profil di database anda Struktur dari tb_profil seperti ini tb-profil Ketiga, Buat file baru beri nama profil.php simpan di folder ADMINWEB isi dari file profil.php seperti ini <?php //pemanggilan file metatag include "setting_metatag.php"; //pemanggilan file navbar include "setting_navbar.php"; ?> <div id="page-wrapper"> <div class="container-fluid"> <!-- .row --> <!-- Page Heading breadcumb--> <div class="row"> <div class="col-lg-12"> <h3> Profil <a href="input_profil.php" title="Input data"><button name="input" class="btn btn-primary pull-right"><i class="fa fa-plus fa-fw"></i> Tambah Profil</button></a> </h3> <ol class="breadcrumb"> <li class="active"> Home </li> <li class="active"> Data Profil </li> </ol> </div> </div> <!-- /.row --> <!-- .row --> <div class="row"> <!-- .col lg 12 --> <div class="col-lg-12"> <!-- /.tabel responsive --> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>No</th> <th>Judul</th> <th>Deskripsi</th> <th>Action</th> </tr> </thead> <tbody> <?php $pg = isset( $_GET['pg'] ) ? $_GET['pg'] : ""; $batas = 10; /*batas tampilan setiap halaman*/ if ( empty( $pg ) ) { $posisi = 0; $pg = 1; } else { $posisi = ( $pg - 1 ) * $batas; } /*Jika variabel $pg kosong maka akan menampilkan halaman pertama dengan batas baris 10*/ $ambildata=mysqli_query($conect, "select*from tb_profil order by id_profil desc limit $posisi, $batas"); $jumlah=mysqli_num_rows($ambildata); /*mysql_num_rows untuk menghitung total baris di tabel databse*/ if($jumlah == 0){ //jika tidak ada data ?> <tr> <td colspan="6">Tidak Terdapat Data</td> </tr> <?php }else{ //jika ada data di tb_brand while($a=mysqli_fetch_array($ambildata)){ /*mysql_fetch array untuk mengambil data di setiap field di tabel databse*/ ?> <tr> <td><?php echo $posisi=$posisi+1;?></td> <td><?php echo $a['judul_profil'];?></td> <td><?php echo substr(strip_tags($a['deskripsi_profil']),0,200);?></td> <td><a href="hapus_profil.php?id_profil=<?php echo $a['id_profil'];?>" onclick="return confirm('Yakin akan meghapus data ini')" title="Hapus data"><button class="btn btn-danger btn-sm">Hapus</button></a> <a href="edit_profil.php?id_profil=<?php echo $a['id_profil'];?>" title="Edit data"><button class="btn btn-info btn-sm">Edit</button> </a> </td> </tr> <?php } } ?> </tbody> </table> </div> <!-- /.tabel responsive --> <div class="text-center"> <?php //script paging, untuk menampikan setiap halaman $jml_data = mysqli_num_rows(mysqli_query($conect, "select*from tb_profil order by id_prfil desc")); $JmlHalaman = ceil($jml_data/$batas); //ceil digunakan untuk pembulatan keatas if($jml_data != 0){ if ( $pg > 1 ) { $link = $pg-1; $prev = "<a href='?pg=$link'><button name='prev' class='btn btn-primary btn-sm'>Prev</button></a> "; } else { $prev = "<button name='prev' class='btn btn-default btn-sm'>Prev </button> "; } $nmr = ''; for ( $i = 1; $i<= $JmlHalaman; $i++ ){ if ( $i == $pg ) { $nmr .= "<button name='prev' class='btn btn-primary btn-sm'>$i</button> "; } else { $nmr .= "<a href='?pg=$i'><button name='prev' class='btn btn-default btn-sm'>$i</button></a> "; } } if ( $pg < $JmlHalaman ) { $link = $pg + 1; $next = "<a href='?pg=$link'><button name='prev' class='btn btn-primary btn-sm'>Next</button></a> "; } else { $next = "<button name='prev' class='btn btn-default btn-sm'>Next</button> "; } echo $prev.$nmr.$next; ?> <br><br> <span class="text-muted">Menampilkan <?php echo $jumlah; ?> dari <?php echo $jml_data; ?> Record </span> <?php } ?> </div> </div> </div> <!-- /.col lg 12--> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <?php //pemanggilan file setting footer include "setting_footer.php"; ?> Ganti script pada file setting_footer.php menjadi seperti ini <script> $(document).ready(function () { $('#datePicker') .datepicker({ format: 'yyyy-mm-dd' }) }); </script> <script> CKEDITOR.replace( 'editor1',{ filebrowserBrowseUrl: '<?php echo $hostname;?>/assets/plugins/ckfinder/ckfinder.php', filebrowserUploadUrl: '<?php echo $hostname;?>/assets/plugins/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files', filebrowserWindowWidth: '1000', filebrowserWindowHeight: '700', } ); </script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="<?php echo $hostname;?>/assets/js/ie10-viewport-bug-workaround.js"></script> </body> </html> Ganti Script pada file setting_metatag.php menjadi seperti ini <?php //session dimulai session_start(); //abaikan error pada browser error_reporting(0); //panggil file koneksi untuk mengkoneksinkan dengan database include "../assets/relasi/koneksi.php"; //panggil file security untuk mengecek session admin include "security.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="keywords" content="<?php echo $iweb['katakunci'];?>"> <meta name="description" content="<?php echo $iweb['deskripsi'];?>" /> <meta name="author" content="<?php echo $iweb['pembuat'];?>"> <title><?php echo $iweb['nama_website'];?></title> <link rel="Shortcut Icon" href="<?php echo $hostname;?>/assets/images/logo/<?php echo $iweb['logo'];?>" type="image/x-icon" /> <!-- Bootstrap core CSS --> <link href="<?php echo $hostname;?>/assets/css/bootstrap.css" rel="stylesheet"> <!-- Custom styles template ini--> <link href="<?php echo $hostname;?>/assets/css/style_admin.css" rel="stylesheet"> <!-- Custom Fonts Awesome--> <link href="<?php echo $hostname;?>/assets/fonts/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="<?php echo $hostname;?>/assets/css/datepicker.min.css" rel="stylesheet"> <script src="<?php echo $hostname;?>/assets/js/jquery.min.js"></script> <script src="<?php echo $hostname;?>/assets/js/bootstrap.js"></script> <script src="<?php echo $hostname;?>/assets/js/bootstrap-datepicker.min.js"></script> <!-- Include CKEditor and jQuery adapter --> <script src="<?php echo $hostname;?>/assets/plugins/ckeditor/ckeditor.js"></script> <script src="<?php echo $hostname;?>/assets/plugins/ckeditor/adapters/jquery.js"></script> </head> <body> <div id="wrapper">   Hasil dari file tersebut akan tampil seperti ini data-profil Keempat, Buat file baru beri nama input_profil.php simpan di folder ADMINWEB isi dari file input_profil.php seperti ini <?php //pemanggilan file metatag include "setting_metatag.php"; //pemanggilan file navbar include "setting_navbar.php"; ?> <div id="page-wrapper"> <div class="container-fluid"> <!-- Page Heading breadcumb--> <div class="row"> <div class="col-lg-12"> <h3> Tambah Profil <a href="profil.php" title="Input data"><button name="input" class="btn btn-default pull-right">Back</button></a> </h3> <ol class="breadcrumb"> <li class="active"> Home </li> <li class="active"> Tambah Profil </li> </ol> </div> </div> <!-- /.row --> <?php //variabel setiap input di form $judul=mysqli_real_escape_string($conect, $_POST['judul']); $des=mysqli_real_escape_string($conect, $_POST['deskripsi']); //jika menekan tombol simpan if(isset($_POST['simpan'])){ if(empty($judul)){ $er_judul="<div class='alert alert-warning alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button> <i class='fa fa-info-circle'></i> Masukan Judul </div>"; } elseif(empty($des)){ $er_des="<div class='alert alert-warning alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button> <i class='fa fa-info-circle'></i> Masukan Deskripsi </div>"; } else{ $save=mysqli_query($conect, "INSERT INTO tb_profil (id_profil,judul_profil,deskripsi_profil)values('','$judul','$des')"); if($save){ //jika simpan berhasil echo "<script>alert('Data Berhasil Disimpan');document.location='profil.php'</script>"; } else{ //jika simpan gagal $error="<div class='alert alert-warning alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button> <i class='fa fa-info-circle'></i> Error</div>"; } } } ?> <!-- .row --> <div class="row"> <!-- .col lg 12 --> <div class="col-lg-12"> <!-- col sm 4 --> <div class="col-sm-10"> <!-- /.form menggunakan form group, pelajari cara membuat form di bootstrap--> <form action="" method="post" enctype="multipart/form-data" role="form"> <?php echo $error;?> <div class="form-group"> <label>Judul Profil</label> <input type="text" class="form-control" placeholder="Judul Profil" name="judul" value="<?php echo $_POST['judul'];?>" maxlength="100"> </div> <?php echo $er_judul;?> <div class="form-group"> <label>Deskripsi</label> <textarea class="form-control" placeholder="Deskripsi Profil" name="deskripsi" id="editor1"><?php echo $_POST['deskripsi'];?></textarea> </div> <?php echo $er_des;?> <button type="submit" name="simpan" class="btn btn-success">Simpan</button> </form> <!-- /.form --> </div> <!-- /.col sm 4 --> </div> <!-- /.col lg 12--> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <?php //pemanggilan file setting footer include "setting_footer.php"; ?>   Hasil dari file input_profil.php tersebut akan tampil seperti ini input-profil Kelima, Buat file baru beri nama edit_profil.php simpan di folder ADMINWEB isi dari file edit_profil.php seperti ini <?php //pemanggilan file metatag include "setting_metatag.php"; //pemanggilan file navbar include "setting_navbar.php"; ?> <div id="page-wrapper"> <div class="container-fluid"> <!-- Page Heading breadcumb--> <div class="row"> <div class="col-lg-12"> <h3> Ubah Profil <a href="profil.php" title="Input data"><button name="input" class="btn btn-default pull-right">Back</button></a> </h3> <ol class="breadcrumb"> <li class="active"> Home </li> <li class="active"> Ubah Profil </li> </ol> </div> </div> <!-- /.row --> <?php //ambil data dari tabel berdasarkan id $tampildata=mysqli_query($conect, "select*from tb_profil where id_profil='$_GET[id_profil]'"); $b=mysqli_fetch_array($tampildata); //variabel setiap input di form $judul=mysqli_real_escape_string($conect, $_POST['judul']); $des=mysqli_real_escape_string($conect, $_POST['deskripsi']); //jika menekan tombol simpan if(isset($_POST['simpan'])){ if(empty($judul)){ $er_judul="<div class='alert alert-warning alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button> <i class='fa fa-info-circle'></i> Masukan Judul </div>"; } elseif(empty($des)){ $er_des="<div class='alert alert-warning alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button> <i class='fa fa-info-circle'></i> Masukan Deskripsi </div>"; } else{ $save=mysqli_query($conect, "UPDATE tb_profil set judul_profil='$judul',deskripsi_profil='$des' where id_profil='$_GET[id_profil]'"); if($save){ //jika simpan berhasil echo "<script>alert('Data Berhasil Diubah');document.location='profil.php'</script>"; } else{ //jika simpan gagal $error="<div class='alert alert-warning alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button> <i class='fa fa-info-circle'></i> Error</div>"; } } } ?> <!-- .row --> <div class="row"> <!-- .col lg 12 --> <div class="col-lg-12"> <div class="col-sm-10"> <!-- /.form menggunakan form group, pelajari cara membuat form di bootstrap--> <form action="" method="post" enctype="multipart/form-data" role="form"> <?php echo $error;?> <div class="form-group"> <label>Judul Profil</label> <input type="text" class="form-control" placeholder="Judul Profil" name="judul" value="<?php echo $b['judul_profil'];?>" maxlength="100"> </div> <?php echo $er_judul;?> <div class="form-group"> <label>Deskripsi</label> <textarea class="form-control" placeholder="Deskripsi Profil" name="deskripsi" id="editor1"><?php echo $b['deskripsi_profil'];?></textarea> </div> <?php echo $er_des;?> <button type="submit" name="simpan" class="btn btn-success">Simpan</button> </form> <!-- /.form --> </div> <!-- /.col sm 4 --> </div> <!-- /.col lg 12--> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <?php //pemanggilan file setting footer include "setting_footer.php"; ?> Hasil dari file tersebut akan tampil seperti ini edit-profil Ketiga, Buat file baru beri nama hapus_profil.php simpan di folder ADMINWEB isi dari file hapus_profil.php seperti ini <?php session_start(); //panggil koneksi include "../assets/relasi/koneksi.php"; $id=$_GET['id_profil']; //dapatkan id if(isset($id)){ //jika ada id //hapus data di tabel $hapus=mysqli_query($conect, "DELETE from tb_profil where id_profil='$id'"); //jika hapus berhasil if($hapus){ echo"<script>alert('Data Berhasil di Hapus');document.location='profil.php'</script>"; } else{ //jika gagal echo"<script>alert('Error Bos !!');document.location='profil.php'</script>"; } } ?> Oke Selesai     Develindo Web | Tutorial Pemrograman Website
__label__pos
0.644984
Uploaded image for project: 'JDK' 1. JDK 2. JDK-8186187 Modify return type of public API StyleConverter.getEnumConverter() XMLWordPrintable Details • generic • generic Description A DESCRIPTION OF THE REQUEST : StyleConverter.getEnumConverter() returns an instance of converting in "StyleConverter<String,? extends Enum<?>>" type, whereas constructor of CssMetaData expects "StyleConverter<?, V>" where V is the type of the enum. This forces the developer to cast the converter returned from StyleConverter.getEnumConverter() method, which would generate an unchecked cast warning. This causes the following code to have compile-time error: public static final CssMetaData<MyNode, MyEnum> MY_ENUM = new CssMetaData<MyNode, MyEnum>( "-my-enum", StyleConverter.getEnumConverter(MyEnum.class), MyEnum.TEST); This gave the following compile-time error: The constructor CssMetaData<MyNode,MyEnum>(String, StyleConverter<String,capture#1-of ? extends Enum<?>>, MyEnum) is undefined. Looking at JavaFX 9 documentation, it seems like this method remains defined this way. JUSTIFICATION : Since javafx.css.StyleConverter class is intended to make CSS styling API public (from the original private API), it should have complete compatibility with the other classes/methods that are made public along with it. Therefore I would recommend that StyleConverter.getEnumConverter() returns "StyleConverter<String,? extends E>", unless doing so would break the API somewhere else. I believe there is nothing wrong in changing the method definition to "public static <E extends Enum<E>> StyleConverter<String,E> getEnumConverter€‹(Class<E> enumClass)". CUSTOMER SUBMITTED WORKAROUND : The current workaround is to do an unchecked cast for the StyleConverter, which will create a warning unless I suppressed it. Attachments Issue Links Activity People pkbalakr Prem Balakrishnan (Inactive) webbuggrp Webbug Group Votes: 0 Vote for this issue Watchers: 6 Start watching this issue Dates Created: Updated: Resolved:
__label__pos
0.526129
User permissions and two factor authentication are crucial components of a secure security infrastructure. They help reduce the risk of malicious insider activity or accidental data breaches and also ensure compliance with regulatory requirements. Two-factor authentication (2FA) requires a user to enter credentials from two different categories to sign into an account. This could be something that the user knows (passwords, PIN codes and security questions) or something they have (one-time verification code sent to their phone or an authenticator program) or something they have (fingerprints or a face scan, or retinal scan). 2FA is usually a subset to Multi-Factor Authentication which includes more than two factors. MFA is a requirement in certain industries, such as healthcare banks, ecommerce, and healthcare (due to HIPAA regulations). The COVID-19 virus has brought new urgency to security for businesses that require two-factor authentication for remote workers. Enterprises are living organisms, and their security infrastructures keep changing. New access points are created every day, users switch roles, hardware capabilities evolve and complex systems are put in the fingers of everyday users. It is essential to regularly reevaluate the two-factor authentication strategies regularly to ensure that they are keeping up with these changes. Adaptive authentication is a method to accomplish this. It is a form of contextual authentication that will trigger policies based on the timing, location and the manner in which a login request is received. Duo offers a central administrator dashboard that lets you easily manage and set these types of policies. lasikpatient.org/2020/09/20/premium-diagnostics-from-cataract-surgery-is-the-best-optrion-for-severely-ill-patient Leave a reply
__label__pos
0.674586
[BUGFIX] Fix some PHP Notices thrown when rendering page module [Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Template / ModuleTemplate.php 1 <?php 2 namespace TYPO3\CMS\Backend\Template; 3 4 /* 5 * This file is part of the TYPO3 CMS project. 6 * 7 * It is free software; you can redistribute it and/or modify it under 8 * the terms of the GNU General Public License, either version 2 9 * of the License, or any later version. 10 * 11 * For the full copyright and license information, please read the 12 * LICENSE.txt file that was distributed with this source code. 13 * 14 * The TYPO3 project - inspiring people to share! 15 */ 16 17 use TYPO3\CMS\Backend\Template\Components\DocHeaderComponent; 18 use TYPO3\CMS\Backend\Utility\BackendUtility; 19 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication; 20 use TYPO3\CMS\Core\Imaging\Icon; 21 use TYPO3\CMS\Core\Imaging\IconFactory; 22 use TYPO3\CMS\Core\Messaging\AbstractMessage; 23 use TYPO3\CMS\Core\Messaging\FlashMessageService; 24 use TYPO3\CMS\Core\Page\PageRenderer; 25 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility; 26 use TYPO3\CMS\Core\Utility\GeneralUtility; 27 use TYPO3\CMS\Fluid\View\Exception\InvalidTemplateResourceException; 28 use TYPO3\CMS\Fluid\View\StandaloneView; 29 use TYPO3\CMS\Lang\LanguageService; 30 31 /** 32 * A class taking care of the "outer" HTML of a module, especially 33 * the doc header and other related parts. 34 * 35 * @internal This API is not yet carved in stone and may be adapted later. 36 */ 37 class ModuleTemplate 38 { 39 /** 40 * Error Icon Constant 41 * 42 * @internal 43 */ 44 const STATUS_ICON_ERROR = 3; 45 46 /** 47 * Warning Icon Constant 48 * 49 * @internal 50 */ 51 const STATUS_ICON_WARNING = 2; 52 53 /** 54 * Notification Icon Constant 55 * 56 * @internal 57 */ 58 const STATUS_ICON_NOTIFICATION = 1; 59 60 /** 61 * OK Icon Constant 62 * 63 * @internal 64 */ 65 const STATUS_ICON_OK = -1; 66 67 /** 68 * DocHeaderComponent 69 * 70 * @var DocHeaderComponent 71 */ 72 protected $docHeaderComponent; 73 74 /** 75 * Javascript Code Array 76 * Used for inline JS 77 * 78 * @var array 79 */ 80 protected $javascriptCodeArray = []; 81 82 /** 83 * Expose the pageRenderer 84 * 85 * @var PageRenderer 86 */ 87 protected $pageRenderer; 88 89 /** 90 * @var bool 91 */ 92 protected $uiBlock = false; 93 94 /** 95 * TemplateRootPath 96 * 97 * @var string[] 98 */ 99 protected $templateRootPaths = ['EXT:backend/Resources/Private/Templates']; 100 101 /** 102 * PartialRootPath 103 * 104 * @var string[] 105 */ 106 protected $partialRootPaths = ['EXT:backend/Resources/Private/Partials']; 107 108 /** 109 * LayoutRootPath 110 * 111 * @var string[] 112 */ 113 protected $layoutRootPaths = ['EXT:backend/Resources/Private/Layouts']; 114 115 /** 116 * Template name 117 * 118 * @var string 119 */ 120 protected $templateFile = 'Module.html'; 121 122 /** 123 * Fluid Standalone View 124 * 125 * @var StandaloneView 126 */ 127 protected $view; 128 129 /** 130 * Content String 131 * 132 * @var string 133 */ 134 protected $content = ''; 135 136 /** 137 * IconFactory Member 138 * 139 * @var IconFactory 140 */ 141 protected $iconFactory; 142 143 /** 144 * Module ID 145 * 146 * @var string 147 */ 148 protected $moduleId = ''; 149 150 /** 151 * Module Name 152 * 153 * @var string 154 */ 155 protected $moduleName = ''; 156 157 /** 158 * Title Tag 159 * 160 * @var string 161 */ 162 protected $title = ''; 163 164 /** 165 * Body Tag 166 * 167 * @var string 168 */ 169 protected $bodyTag = '<body>'; 170 171 /** 172 * Flash message queue 173 * 174 * @var \TYPO3\CMS\Core\Messaging\FlashMessageQueue 175 */ 176 protected $flashMessageQueue; 177 178 /** 179 * Returns the current body tag 180 * 181 * @return string 182 */ 183 public function getBodyTag() 184 { 185 return $this->bodyTag; 186 } 187 188 /** 189 * Sets the body tag 190 * 191 * @param string $bodyTag 192 */ 193 public function setBodyTag($bodyTag) 194 { 195 $this->bodyTag = $bodyTag; 196 } 197 198 /** 199 * Gets the standalone view. 200 * 201 * @return StandaloneView 202 */ 203 public function getView() 204 { 205 return $this->view; 206 } 207 208 /** 209 * Set content 210 * 211 * @param string $content Content of the module 212 */ 213 public function setContent($content) 214 { 215 $this->view->assign('content', $content); 216 } 217 218 /** 219 * Set title tag 220 * 221 * @param string $title 222 */ 223 public function setTitle($title) 224 { 225 $this->title = $title; 226 } 227 228 /** 229 * Returns the IconFactory 230 * 231 * @return IconFactory 232 */ 233 public function getIconFactory() 234 { 235 return $this->iconFactory; 236 } 237 238 /** 239 * Class constructor 240 * Sets up view and property objects 241 * 242 * @throws InvalidTemplateResourceException In case a template is invalid 243 */ 244 public function __construct() 245 { 246 $this->view = GeneralUtility::makeInstance(StandaloneView::class); 247 $this->view->setPartialRootPaths($this->partialRootPaths); 248 $this->view->setTemplateRootPaths($this->templateRootPaths); 249 $this->view->setLayoutRootPaths($this->layoutRootPaths); 250 $this->view->setTemplate($this->templateFile); 251 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class); 252 $this->docHeaderComponent = GeneralUtility::makeInstance(DocHeaderComponent::class); 253 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class); 254 } 255 256 /** 257 * Loads all necessary Javascript Files 258 */ 259 protected function loadJavaScripts() 260 { 261 $this->pageRenderer->loadJquery(); 262 $this->pageRenderer->loadRequireJsModule('bootstrap'); 263 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ContextHelp'); 264 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DocumentHeader'); 265 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/SplitButtons'); 266 } 267 268 /** 269 * Loads all necessary stylesheets 270 */ 271 protected function loadStylesheets() 272 { 273 if (!empty($GLOBALS['TBE_STYLES']['stylesheet'])) { 274 $this->pageRenderer->addCssFile($GLOBALS['TBE_STYLES']['stylesheet']); 275 } 276 if (!empty($GLOBALS['TBE_STYLES']['stylesheet2'])) { 277 $this->pageRenderer->addCssFile($GLOBALS['TBE_STYLES']['stylesheet2']); 278 } 279 } 280 281 /** 282 * Sets mandatory parameters for the view (pageRenderer) 283 */ 284 protected function setupPage() 285 { 286 // Yes, hardcoded on purpose 287 $this->pageRenderer->setXmlPrologAndDocType('<!DOCTYPE html>'); 288 $this->pageRenderer->setCharSet('utf-8'); 289 $this->pageRenderer->setLanguage($GLOBALS['LANG']->lang); 290 $this->pageRenderer->addMetaTag('<meta name="viewport" content="width=device-width, initial-scale=1">'); 291 } 292 293 /** 294 * Wrapper function for adding JS inline blocks 295 */ 296 protected function setJavaScriptCodeArray() 297 { 298 foreach ($this->javascriptCodeArray as $name => $code) { 299 $this->pageRenderer->addJsInlineCode($name, $code, false); 300 } 301 } 302 303 /** 304 * Adds JS inline blocks of code to the internal registry 305 * 306 * @param string $name Javascript code block name 307 * @param string $code Inline Javascript 308 */ 309 public function addJavaScriptCode($name = '', $code = '') 310 { 311 $this->javascriptCodeArray[$name] = $code; 312 } 313 314 /** 315 * Get the DocHeader 316 * 317 * @return DocHeaderComponent 318 */ 319 public function getDocHeaderComponent() 320 { 321 return $this->docHeaderComponent; 322 } 323 324 /** 325 * Returns the fully rendered view 326 * 327 * @return string 328 */ 329 public function renderContent() 330 { 331 $this->setupPage(); 332 $this->pageRenderer->setTitle($this->title); 333 $this->loadJavaScripts(); 334 $this->setJavaScriptCodeArray(); 335 $this->loadStylesheets(); 336 337 $this->view->assign('docHeader', $this->docHeaderComponent->docHeaderContent()); 338 if ($this->moduleId) { 339 $this->view->assign('moduleId', $this->moduleId); 340 } 341 if ($this->moduleName) { 342 $this->view->assign('moduleName', $this->moduleName); 343 } 344 $this->view->assign('uiBlock', $this->uiBlock); 345 $this->view->assign('flashMessageQueueIdentifier', $this->getFlashMessageQueue()->getIdentifier()); 346 $renderedPage = $this->pageRenderer->render(PageRenderer::PART_HEADER); 347 $renderedPage .= $this->bodyTag; 348 $renderedPage .= $this->view->render(); 349 $this->pageRenderer->addJsFooterInlineCode('updateSignals', BackendUtility::getUpdateSignalCode()); 350 $renderedPage .= $this->pageRenderer->render(PageRenderer::PART_FOOTER); 351 352 return $renderedPage; 353 } 354 355 /** 356 * Get PageRenderer 357 * 358 * @return PageRenderer 359 */ 360 public function getPageRenderer() 361 { 362 return $this->pageRenderer; 363 } 364 365 /** 366 * Set form tag 367 * 368 * @param string $formTag Form tag to add 369 */ 370 public function setForm($formTag = '') 371 { 372 $this->view->assign('formTag', $formTag); 373 } 374 375 /** 376 * Sets the ModuleId 377 * 378 * @param string $moduleId ID of the module 379 */ 380 public function setModuleId($moduleId) 381 { 382 $this->moduleId = $moduleId; 383 $this->registerModuleMenu($moduleId); 384 } 385 386 /** 387 * Sets the ModuleName 388 * 389 * @param string $moduleName Name of the module 390 */ 391 public function setModuleName($moduleName) 392 { 393 $this->moduleName = $moduleName; 394 } 395 396 /** 397 * Generates the Menu for things like Web->Info 398 * 399 * @param $moduleMenuIdentifier 400 */ 401 public function registerModuleMenu($moduleMenuIdentifier) 402 { 403 if (isset($GLOBALS['TBE_MODULES_EXT'][$moduleMenuIdentifier])) { 404 $menuEntries = 405 $GLOBALS['TBE_MODULES_EXT'][$moduleMenuIdentifier]['MOD_MENU']['function']; 406 $menu = $this->getDocHeaderComponent()->getMenuRegistry()->makeMenu()->setIdentifier('MOD_FUNC'); 407 foreach ($menuEntries as $menuEntry) { 408 $menuItem = $menu->makeMenuItem() 409 ->setTitle($menuEntry['title']) 410 ->setHref('#'); 411 $menu->addMenuItem($menuItem); 412 } 413 $this->docHeaderComponent->getMenuRegistry()->addMenu($menu); 414 } 415 } 416 417 /** 418 * Creates a tab menu where the tabs or collapsible are rendered with bootstrap markup 419 * 420 * @param array $menuItems Tab elements, each element is an array with "label" and "content" 421 * @param string $domId DOM id attribute, will be appended with an iteration number per tab. 422 * @param int $defaultTabIndex Default tab to open (for toggle <=0). Value corresponds to integer-array index + 1 423 * (index zero is "1", index "1" is 2 etc.). A value of zero (or something non-existing 424 * will result in no default tab open. 425 * @param bool $collapsible If set, the tabs are rendered as headers instead over each sheet. Effectively this means 426 * there is no tab menu, but rather a foldout/fold-in menu. 427 * @param bool $wrapContent If set, the content is wrapped in div structure which provides a padding and border 428 * style. Set this FALSE to get unstyled content pane with fullsize content area. 429 * @param bool $storeLastActiveTab If set, the last open tab is stored in local storage and will be re-open again. 430 * If you don't need this feature, e.g. for wizards like import/export you can 431 * disable this behaviour. 432 * @return string 433 */ 434 public function getDynamicTabMenu(array $menuItems, $domId, $defaultTabIndex = 1, $collapsible = false, $wrapContent = true, $storeLastActiveTab = true) 435 { 436 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Tabs'); 437 $templatePath = ExtensionManagementUtility::extPath('backend') 438 . 'Resources/Private/Templates/DocumentTemplate/'; 439 $view = GeneralUtility::makeInstance(StandaloneView::class); 440 $view->setTemplatePathAndFilename($templatePath . ($collapsible ? 'Collapse.html' : 'Tabs.html')); 441 $view->setPartialRootPaths([$templatePath . 'Partials']); 442 $view->assignMultiple([ 443 'id' => 'DTM-' . GeneralUtility::shortMD5($domId), 444 'items' => $menuItems, 445 'defaultTabIndex' => $defaultTabIndex, 446 'wrapContent' => $wrapContent, 447 'storeLastActiveTab' => $storeLastActiveTab, 448 ]); 449 return $view->render(); 450 } 451 452 /******************************************* 453 * THE FOLLOWING METHODS ARE SUBJECT TO BE DEPRECATED / DROPPED! 454 * 455 * These methods have been copied over from DocumentTemplate and enables 456 * core modules to drop the dependency to DocumentTemplate altogether without 457 * rewriting these modules now. 458 * The methods below are marked as internal and will be removed 459 * one-by-one with further refactoring of modules. 460 * 461 * Do not use these methods within own extensions if possible or 462 * be prepared to change this later again. 463 *******************************************/ 464 465 /** 466 * Includes a javascript library that exists in the core /typo3/ directory 467 * 468 * @param string $lib Library name. Call it with the full path like 469 * "sysext/core/Resources/Public/JavaScript/QueryGenerator.js" to load it 470 * 471 * @internal 472 */ 473 public function loadJavascriptLib($lib) 474 { 475 // @todo: maybe we can remove this one as well 476 $this->pageRenderer->addJsFile($lib); 477 } 478 479 /** 480 * Returns a linked shortcut-icon which will call the shortcut frame and set a 481 * shortcut there back to the calling page/module 482 * 483 * @param string $gvList Is the list of GET variables to store (if any) 484 * @param string $setList Is the list of SET[] variables to store 485 * (if any) - SET[] variables a stored in $GLOBALS["SOBE"]->MOD_SETTINGS 486 * for backend modules 487 * @param string $modName Module name string 488 * @param string|int $motherModName Is used to enter the "parent module 489 * name" if the module is a submodule under eg. Web>* or File>*. You 490 * can also set this value to 1 in which case the currentLoadedModule 491 * is sent to the shortcut script (so - not a fixed value!) - that is used 492 * in file_edit and wizard_rte modules where those are really running as 493 * a part of another module. 494 * @param string $displayName When given this name is used instead of the 495 * module name. 496 * @param string $classes Additional CSS classes for the link around the icon 497 * 498 * @return string HTML content 499 * @todo Make this thing return a button object 500 * @internal 501 */ 502 public function makeShortcutIcon($gvList, $setList, $modName, $motherModName = '', $displayName = '', $classes = 'btn btn-default btn-sm') 503 { 504 $gvList = 'route,' . $gvList; 505 $storeUrl = $this->makeShortcutUrl($gvList, $setList); 506 $pathInfo = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI')); 507 // Fallback for alt_mod. We still pass in the old xMOD... stuff, 508 // but TBE_MODULES only knows about "record_edit". 509 // We still need to pass the xMOD name to createShortcut below, 510 // since this is used for icons. 511 $moduleName = $modName === 'xMOD_alt_doc.php' ? 'record_edit' : $modName; 512 // Add the module identifier automatically if typo3/index.php is used: 513 if (GeneralUtility::_GET('M') !== null) { 514 $storeUrl = '&M=' . $moduleName . $storeUrl; 515 } 516 if ((int)$motherModName === 1) { 517 $motherModule = 'top.currentModuleLoaded'; 518 } elseif ($motherModName) { 519 $motherModule = GeneralUtility::quoteJSvalue($motherModName); 520 } else { 521 $motherModule = '\'\''; 522 } 523 $confirmationText = GeneralUtility::quoteJSvalue( 524 $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.makeBookmark') 525 ); 526 527 $shortcutUrl = $pathInfo['path'] . '?' . $storeUrl; 528 $shortcutExist = BackendUtility::shortcutExists($shortcutUrl); 529 530 if ($shortcutExist) { 531 return '<a class="active ' . htmlspecialchars($classes) . '" title="">' . 532 $this->iconFactory->getIcon('actions-system-shortcut-active', Icon::SIZE_SMALL)->render() . '</a>'; 533 } 534 535 $url = GeneralUtility::quoteJSvalue(rawurlencode($shortcutUrl)); 536 $onClick = 'top.TYPO3.ShortcutMenu.createShortcut(' . GeneralUtility::quoteJSvalue(rawurlencode($modName)) . 537 ', ' . $url . ', ' . $confirmationText . ', ' . $motherModule . ', this, ' . GeneralUtility::quoteJSvalue($displayName) . ');return false;'; 538 539 return '<a href="#" class="' . htmlspecialchars($classes) . '" onclick="' . htmlspecialchars($onClick) . '" title="' . 540 htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.makeBookmark')) . '">' . 541 $this->iconFactory->getIcon('actions-system-shortcut-new', Icon::SIZE_SMALL)->render() . '</a>'; 542 } 543 544 /** 545 * MAKE url for storing 546 * Internal func 547 * 548 * @param string $gvList Is the list of GET variables to store (if any) 549 * @param string $setList Is the list of SET[] variables to store (if any) 550 * - SET[] variables a stored in $GLOBALS["SOBE"]->MOD_SETTINGS for backend 551 * modules 552 * 553 * @return string 554 * @internal 555 */ 556 public function makeShortcutUrl($gvList, $setList) 557 { 558 $getParams = GeneralUtility::_GET(); 559 $storeArray = array_merge( 560 GeneralUtility::compileSelectedGetVarsFromArray($gvList, $getParams), 561 ['SET' => GeneralUtility::compileSelectedGetVarsFromArray($setList, (array)$GLOBALS['SOBE']->MOD_SETTINGS)] 562 ); 563 return GeneralUtility::implodeArrayForUrl('', $storeArray); 564 } 565 566 /** 567 * Creates the version selector for the page id inputted. 568 * Requires the core version management extension, "version" to be loaded. 569 * 570 * @param int $id Page id to create selector for. 571 * @param bool $noAction If set, there will be no button for swapping page. 572 * 573 * @return string 574 * @internal 575 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9 576 */ 577 public function getVersionSelector($id, $noAction = false) 578 { 579 if (ExtensionManagementUtility::isLoaded('version') 580 && ExtensionManagementUtility::isLoaded('compatibility7') 581 && !ExtensionManagementUtility::isLoaded('workspaces') 582 ) { 583 /** 584 * For Code Completion 585 * 586 * @var $versionGuiObj \TYPO3\CMS\Compatibility7\View\VersionView 587 */ 588 $versionGuiObj = GeneralUtility::makeInstance(\TYPO3\CMS\Compatibility7\View\VersionView::class); 589 return $versionGuiObj->getVersionSelector($id, $noAction); 590 } 591 return ''; 592 } 593 594 /** 595 * Returns the BE USER Object 596 * 597 * @return BackendUserAuthentication 598 */ 599 protected function getBackendUserAuthentication() 600 { 601 return $GLOBALS['BE_USER']; 602 } 603 604 /** 605 * Returns the LanguageService 606 * 607 * @return LanguageService 608 */ 609 protected function getLanguageService() 610 { 611 return $GLOBALS['LANG']; 612 } 613 614 /** 615 * Returns an image-tag with an 18x16 icon of the following types: 616 * 617 * $type: 618 * -1:» OK icon (Check-mark) 619 * 1:» Notice (Speach-bubble) 620 * 2:» Warning (Yellow triangle) 621 * 3:» Fatal error (Red stop sign) 622 * 623 * @param int $type See description 624 * 625 * @return string HTML image tag (if applicable) 626 * @internal 627 */ 628 public function icons($type) 629 { 630 $icon = ''; 631 switch ($type) { 632 case self::STATUS_ICON_ERROR: 633 $icon = 'status-dialog-error'; 634 break; 635 case self::STATUS_ICON_WARNING: 636 $icon = 'status-dialog-warning'; 637 break; 638 case self::STATUS_ICON_NOTIFICATION: 639 $icon = 'status-dialog-notification'; 640 break; 641 case self::STATUS_ICON_OK: 642 $icon = 'status-dialog-ok'; 643 break; 644 default: 645 // Do nothing 646 } 647 if ($icon != '') { 648 return $this->iconFactory->getIcon($icon, Icon::SIZE_SMALL)->render(); 649 } 650 return ''; 651 } 652 653 /** 654 * Returns JavaScript variables setting the returnUrl and thisScript location for use by JavaScript on the page. 655 * Used in fx. db_list.php (Web>List) 656 * 657 * @param string $thisLocation URL to "this location" / current script 658 * @return string Urls are returned as JavaScript variables T3_RETURN_URL and T3_THIS_LOCATION 659 * @see typo3/db_list.php 660 * @internal 661 */ 662 public function redirectUrls($thisLocation = '') 663 { 664 $thisLocation = $thisLocation ? $thisLocation : GeneralUtility::linkThisScript([ 665 'CB' => '', 666 'SET' => '', 667 'cmd' => '', 668 'popViewId' => '' 669 ]); 670 $out = ' 671 var T3_RETURN_URL = ' . GeneralUtility::quoteJSvalue(str_replace('%20', '', rawurlencode(GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'))))) . '; 672 var T3_THIS_LOCATION = ' . GeneralUtility::quoteJSvalue(str_replace('%20', '', rawurlencode($thisLocation))) . ' 673 '; 674 return $out; 675 } 676 677 /** 678 * Returns the header-bar in the top of most backend modules 679 * Closes section if open. 680 * 681 * @param string $text The text string for the header 682 * @return string HTML content 683 * @internal 684 */ 685 public function header($text) 686 { 687 return ' 688 689 <!-- MAIN Header in page top --> 690 <h1 class="t3js-title-inlineedit">' . htmlspecialchars($text) . '</h1> 691 '; 692 } 693 694 /** 695 * Creates a Message object and adds it to the FlashMessageQueue. 696 * 697 * @param string $messageBody The message 698 * @param string $messageTitle Optional message title 699 * @param int $severity Optional severity, must be one of \TYPO3\CMS\Core\Messaging\FlashMessage constants 700 * @param bool $storeInSession Optional, defines whether the message should be stored in the session (default) 701 * @throws \InvalidArgumentException if the message body is no string 702 */ 703 public function addFlashMessage($messageBody, $messageTitle = '', $severity = AbstractMessage::OK, $storeInSession = true) 704 { 705 if (!is_string($messageBody)) { 706 throw new \InvalidArgumentException('The message body must be of type string, "' . gettype($messageBody) . '" given.', 1446483133); 707 } 708 /* @var \TYPO3\CMS\Core\Messaging\FlashMessage $flashMessage */ 709 $flashMessage = GeneralUtility::makeInstance( 710 \TYPO3\CMS\Core\Messaging\FlashMessage::class, 711 $messageBody, 712 $messageTitle, 713 $severity, 714 $storeInSession 715 ); 716 $this->getFlashMessageQueue()->enqueue($flashMessage); 717 } 718 719 /** 720 * @param \TYPO3\CMS\Core\Messaging\FlashMessageQueue $flashMessageQueue 721 */ 722 public function setFlashMessageQueue($flashMessageQueue) 723 { 724 $this->flashMessageQueue = $flashMessageQueue; 725 } 726 727 /** 728 * @return \TYPO3\CMS\Core\Messaging\FlashMessageQueue 729 */ 730 protected function getFlashMessageQueue() 731 { 732 if (!isset($this->flashMessageQueue)) { 733 /** @var FlashMessageService $service */ 734 $service = GeneralUtility::makeInstance(FlashMessageService::class); 735 $this->flashMessageQueue = $service->getMessageQueueByIdentifier(); 736 } 737 return $this->flashMessageQueue; 738 } 739 740 /** 741 * @return bool 742 */ 743 public function isUiBlock() : bool 744 { 745 return $this->uiBlock; 746 } 747 748 /** 749 * @param bool $uiBlock 750 */ 751 public function setUiBlock(bool $uiBlock) 752 { 753 $this->uiBlock = $uiBlock; 754 } 755 }
__label__pos
0.992969
12 $\begingroup$ If this is a duplicate question, please point to the right way, but the similar questions I've found here haven't been sufficiently similar. Suppose I estimate the model $$Y=\alpha + \beta X + u$$ and find that $\beta>0$. However, it turns out that $X=X_1+X_2$, and I suspect $\partial Y/\partial X_1 \ne \partial Y / \partial X_2$, and in particular, that $\partial Y/\partial X_1 > \partial Y / \partial X_2$. So I estimate the model $$Y=\alpha + \beta_1 X_1 + \beta_2 X_2 +u$$and find significant evidence for $\beta_1,\beta_2>0$. How can I then test whether $\beta_1> \beta_2$? I considered running another regression $$Y=\alpha +\gamma(X_1 - X_2) + u$$ And testing whether $\gamma>0$. Is this the best way? Also, I need to generalize the answer to many variables, i.e. suppose we have $$Y=\alpha + \beta^1 X^1 + \beta ^2 X^2 + \dots + \beta^nX^n + u$$ where for each $j=1,\dots,n$, $X^j=X_1^j+X_2^j$, and I would like to test for each $j$ whether $\partial Y/\partial X_1^j \ne \partial Y / \partial X_2^j$. By the way, I am primarily working in R. $\endgroup$ 1 Answer 1 16 $\begingroup$ Is this the best way? No, that won't actually do what you want. Let $\gamma = \beta_1 - \beta_2$. $\beta_1 X_1 + \beta_2 X_2 = (\gamma+\beta_2) X_1 + \beta_2 X_2 = \gamma X_1 + \beta_2 (X_1 + X_2)$. Hence the model $Y=\alpha + \beta_1 X_1 + \beta_2 X_2 +u$ becomes $Y=\alpha + \gamma X_1 + \beta_2 (X_1 +X_2) +u$ So you supply predictors $X_1$ and $X_3=X_1+X_2$, and then you can perform a straight hypothesis test of whether $\gamma>0$ (against the null of equality). $\endgroup$ 0 Your Answer By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.998385
Track clicks with mootools Why would I want to track clicks you may ask. Well, for me it's about usability and user flow optimization. If I do some ajax/dynamic stuff on a page, I want to see what the users are doing. As they leave no visible traces in the logs, I need to add some. It's good to know which features the users use, how often, in what order etc. Do you need to advertise some functionality more? Maybe you need to prepare better documentation so that they even know how or why to use some things? If you have outgoing links, you may want to know where your users are going? The ugly way of doing this would be to use some sort of redirect URLs and monitor those. But I don't like that way. If I use mootools anyway I can track outgoing links more elegantly. And redirects certainly can't handle ajax stuff. function clicktrack(id) { var elements = $(id).getElements('a'); elements.each(function(item, index) { $(item).addEvent( 'click', function() { new Image().src = '/usability/?click=' + $(item).getParent().id + "&" + $(item).id; } ); }); } clicktrack('mode'); Add a HTML that looks somewhat like this to get an idea what buttons your users are clicking. Of course, in an ideal world, you'd want to offer non-JavaScript links too. Tracking outgoing links is even simpler, i'll leave it as an exercise for the reader ;-) 0 comments Reply Cancel reply Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc. DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo
__label__pos
0.541643
Latest Real 70-467 Tests Dumps and VCE Exam Questions 11-20 Ensurepass QUESTION 11 DRAG DROP You are designing a SQL Server Integration Services (SSIS) package to execute 12 Transact-SQL (T- SQL) statements on a SQL Azure database. The T-SQL statements may be executed in any order. The T-SQL statements have unpredictable execution times. You have the following requirements:   Ÿ   The package must maximize parallel processing of the T-SQL statements. Ÿ   After all the T-SQL statements have completed, a Send Mail task must notify administrators.   You need to design the SSIS package. Which three actions should you perform in sequence? (To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.)   Select and Place: clip_image002   Correct Answer: clip_image004     QUESTION 12 HOTSPOT You are configuring the partition storage settings for a SQL Server Analysis Services (SSAS) cube. The partition storage must meet the following requirements:   Ÿ   Optimize the storage of source data and aggregations in the cube. Ÿ   Use proactive caching. Ÿ   Drop cached data that is more than 30 minutes old. Ÿ   Update the cache when data changes, with a silence interval of 10 seconds.   You need to select the partition storage setting. Which setting should you select?   To answer, select the appropriate setting in the answer area.   Hot Area: clip_image005   Correct Answer: clip_image006     QUESTION 13 HOTSPOT A SQL Server Analysis Services (SSAS) cube contains billions of rows of data and is rapidly increasing in size. The cube consists of a single measure group and a single partition. The cube is currently processed by using the Process Full process option. You have the following requirements to reduce the cube processing time:   Ÿ   Partition the measure group by month. Ÿ   Create a staging table that contains only data which is more recent than the last time the cube was processed. Ÿ   Do not include data updates or deletions in the staging table. Ÿ   Insert records from the staging table into the appropriate partition.   You need to change the process option to meet the requirements. Which process option should you choose?   To answer, select the appropriate option from the drop-down list in the dialog box.   Hot Area: clip_image007   Correct Answer: clip_image008     QUESTION 14 DRAG DROP You administer a SQL Server Analysis Services (SSAS) instance. You need to capture a continuous log of detailed event and subevent durations and custom trace events from queries executed in the SSAS instance. Which three actions should you perform in sequence?   To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.   Select and Place: clip_image010   Correct Answer: clip_image012     QUESTION 15 DRAG DROP You plan to deploy a SQL Server Integration Services (SSIS) project by using the project deployment model. You need to monitor control flow tasks to determine whether any of them are running longer than usual. Which three actions should you perform in sequence?   To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.   Select and Place: clip_image014   Correct Answer: clip_image016     QUESTION 16 You are designing a partitioning strategy for a large fact table in a data warehouse. Tens of millions of new records are loaded into the data warehouse weekly, outside of business hours. Most queries are generated by reports and by cube processing. Data is frequently queried at the day level and occasionally at the month level. You need to partition the table to maximize the performance of queries. What should you do? (More than one answer choice may achieve the goal. Select the BEST answer.)   A.      Partition the fact table by month, and compress each partition. B.      Partition the fact table by week. C.      Partition the fact table by year. D.      Partition the fact table by day, and compress each partition.   Correct Answer: D     QUESTION 17 You are designing an extract, transform, load (ETL) process for loading data from a SQL Server database into a large fact table in a data warehouse each day with the prior day’s sales data. The ETL process for the fact table must meet the following requirements:   Ÿ   Load new data in the shortest possible time. Ÿ   Remove data that is more than 36 months old. Ÿ   Ensure that data loads correctly. Ÿ   Minimize record locking. Ÿ   Minimize impact on the transaction log.   You need to design an ETL process that meets the requirements. What should you do? (More than one answer choice may achieve the goal. Select the BEST answer.)   A.      Partition the destination fact table by date. Insert new data directly into the fact table and delete old data directly from the fact table. B.      Partition the destination fact table by date. Use partition switching and staging tables both to remove old data and to load new data. C.      Partition the destination fact table by customer. Use partition switching both to remove old data and to load new data into each partition. D.      Partition the destination fact table by date. Use partition switching and a staging table to remove old data. Insert new data directly into the fact table.   Correct Answer: B     QUESTION 18 DRAG DROP You are administering a SQL Server Analysts Services (SSAS) database on a server. The database hosts a financial cube based on a SQL Azure database. You need to grant write access to the financial cube for all users in the group USAPowerUsers. Which three actions should you perform in sequence?   To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.   Select and Place: clip_image018   Correct Answer: clip_image020     QUESTION 19 DRAG DROP You are validating whether a SQL Server Integration Services (SSIS) package named Master.dtsx in the SSIS catalog is executing correctly. You need to display the number of rows in each buffer passed between each data flow component of the package. Which three actions should you perform in sequence?   To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.   Select and Place: clip_image022   Correct Answer: clip_image024     QUESTION 20 You are creating a Multidimensional Expressions (MDX) calculation for Projected Revenue in a cube. For Customer A, Projected Revenue is defined as 150 percent of the Total Sales for the customer. For all other customers, Projected Revenue is defined as 110 percent of the Total Sales for the customer. You need to calculate the Projected Revenue as efficiently as possible. Which calculation should you use? (More than one answer choice may achieve the goal. Select the BEST answer.)   clip_image026   A.      Option A B.      Option B C.      Option C D.      Option D   Correct Answer: C  
__label__pos
0.571403
FFmpeg scaling_video.c /* * Copyright (c) 2012 Stefano Sabatini * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file * libswscale API use example. * @example scaling_video.c */ static void fill_yuv_image(uint8_t *data[4], int linesize[4], int width, int height, int frame_index) { int x, y; /* Y */ for (y = 0; y < height; y++) for (x = 0; x < width; x++) data[0][y * linesize[0] + x] = x + y + frame_index * 3; /* Cb and Cr */ for (y = 0; y < height / 2; y++) { for (x = 0; x < width / 2; x++) { data[1][y * linesize[1] + x] = 128 + y + frame_index * 2; data[2][y * linesize[2] + x] = 64 + x + frame_index * 5; } } } int main(int argc, char **argv) { uint8_t *src_data[4], *dst_data[4]; int src_linesize[4], dst_linesize[4]; int src_w = 320, src_h = 240, dst_w, dst_h; enum AVPixelFormat src_pix_fmt = AV_PIX_FMT_YUV420P, dst_pix_fmt = AV_PIX_FMT_RGB24; const char *dst_size = NULL; const char *dst_filename = NULL; FILE *dst_file; int dst_bufsize; struct SwsContext *sws_ctx; int i, ret; if (argc != 3) { fprintf(stderr, "Usage: %s output_file output_size\n" "API example program to show how to scale an image with libswscale.\n" "This program generates a series of pictures, rescales them to the given " "output_size and saves them to an output file named output_file\n." "\n", argv[0]); exit(1); } dst_filename = argv[1]; dst_size = argv[2]; if (av_parse_video_size(&dst_w, &dst_h, dst_size) < 0) { fprintf(stderr, "Invalid size '%s', must be in the form WxH or a valid size abbreviation\n", dst_size); exit(1); } dst_file = fopen(dst_filename, "wb"); if (!dst_file) { fprintf(stderr, "Could not open destination file %s\n", dst_filename); exit(1); } /* create scaling context */ sws_ctx = sws_getContext(src_w, src_h, src_pix_fmt, dst_w, dst_h, dst_pix_fmt, if (!sws_ctx) { fprintf(stderr, "Impossible to create scale context for the conversion " "fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n", av_get_pix_fmt_name(src_pix_fmt), src_w, src_h, av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h); ret = AVERROR(EINVAL); goto end; } /* allocate source and destination image buffers */ if ((ret = av_image_alloc(src_data, src_linesize, src_w, src_h, src_pix_fmt, 16)) < 0) { fprintf(stderr, "Could not allocate source image\n"); goto end; } /* buffer is going to be written to rawvideo file, no alignment */ if ((ret = av_image_alloc(dst_data, dst_linesize, dst_w, dst_h, dst_pix_fmt, 1)) < 0) { fprintf(stderr, "Could not allocate destination image\n"); goto end; } dst_bufsize = ret; for (i = 0; i < 100; i++) { /* generate synthetic video */ fill_yuv_image(src_data, src_linesize, src_w, src_h, i); /* convert to destination format */ sws_scale(sws_ctx, (const uint8_t * const*)src_data, src_linesize, 0, src_h, dst_data, dst_linesize); /* write scaled image to file */ fwrite(dst_data[0], 1, dst_bufsize, dst_file); } fprintf(stderr, "Scaling succeeded. Play the output file with the command:\n" "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n", av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h, dst_filename); fclose(dst_file); av_freep(&src_data[0]); av_freep(&dst_data[0]); sws_freeContext(sws_ctx); return ret < 0; } AVPixelFormat AVPixelFormat Pixel format. Definition: pixfmt.h:64 AVERROR Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions end static av_cold int end(AVCodecContext *avctx) Definition: avrndec.c:90 data const char data[16] Definition: mxf.c:91 sws_scale int attribute_align_arg sws_scale(struct SwsContext *c, const uint8_t *const srcSlice[], const int srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const int dstStride[]) swscale wrapper, so we don't need to export the SwsContext. Definition: swscale.c:759 fill_yuv_image static void fill_yuv_image(uint8_t *data[4], int linesize[4], int width, int height, int frame_index) Definition: scaling_video.c:33 width #define width AV_PIX_FMT_YUV420P @ AV_PIX_FMT_YUV420P planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples) Definition: pixfmt.h:66 NULL #define NULL Definition: coverity.c:32 parseutils.h av_image_alloc int av_image_alloc(uint8_t *pointers[4], int linesizes[4], int w, int h, enum AVPixelFormat pix_fmt, int align) Allocate an image with size w and h and pixel format pix_fmt, and fill pointers and linesizes accordi... Definition: imgutils.c:192 AV_PIX_FMT_RGB24 @ AV_PIX_FMT_RGB24 packed RGB 8:8:8, 24bpp, RGBRGB... Definition: pixfmt.h:68 main int main(int argc, char **argv) Definition: scaling_video.c:52 sws_getContext struct SwsContext * sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param) Allocate and return an SwsContext. Definition: utils.c:1891 height #define height av_parse_video_size int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str) Parse str and put in width_ptr and height_ptr the detected values. Definition: parseutils.c:148 i #define i(width, name, range_min, range_max) Definition: cbs_h2645.c:259 uint8_t uint8_t Definition: audio_convert.c:194 ret ret Definition: filter_design.txt:187 sws_freeContext void sws_freeContext(struct SwsContext *swsContext) Free the swscaler context swsContext. Definition: utils.c:2311 av_freep #define av_freep(p) Definition: tableprint_vlc.h:35 imgutils.h SWS_BILINEAR #define SWS_BILINEAR Definition: swscale.h:59 SwsContext Definition: swscale_internal.h:280 swscale.h av_get_pix_fmt_name const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt) Return the short name for a pixel format, NULL in case pix_fmt is unknown. Definition: pixdesc.c:2438
__label__pos
0.986873
Skip to content Endpoint Backup Solutions: Protecting Your Data Wherever It Resides Views: 931 0 0 Read Time:3 Minute, 14 Second In today’s digital age, data is the lifeblood of any organization. From sensitive customer information to crucial business documents, protecting data is of paramount importance. Besides, with the emergence of remote work and the proliferation of endpoint devices such as laptops, tablets, and smartphones, robust endpoint backup solutions have become more critical than ever. So, in this article, you will explore endpoint backup and how it can safeguard your data, regardless of its location. Understanding Reserve Softwares The reserve software refers to regularly and securely backing up data stored on endpoint gadgets such as laptops, desktops, and mobile devices. Unlike traditional backup solutions focusing on server and network infrastructure, endpoint backup software solutions specifically target data residing on individual devices. So by implementing reserve software, organizations can ensure that their data is protected, even when employees work remotely or on the go. The Significance of Backups The Significance of Backups Data Loss Prevention Data loss may occur due to various reasons, including hardware failure, accidental deletion, malware attacks, or device theft. So an endpoint data protection solution is a safety net by automatically and continuously backing up data from endpoint devices. As such, in the event of data loss, organizations can quickly recover the lost data from the backup, minimizing the impact on business operations and productivity. Compliance and Legal Requirements Industries, such as healthcare and finance, have stringent regulatory requirements regarding data protection and privacy. Endpoint backup solutions help organizations meet these compliance standards by ensuring that sensitive data is securely backed up and recoverable. This not only helps avoid legal repercussions but also fosters trust among customers and stakeholders. Remote Workforce Support The recent shift towards remote work has highlighted the need for robust enterprise endpoint backup. With employees accessing and modifying data from various locations, the risk of data loss or unauthorized access increases significantly. As such, the data reserve solutions provide a centralized and secure method to protect data, regardless of where it is being accessed or modified, enabling organizations to embrace remote work with confidence. Key Features of Restoring Solutions Key Features of backup software Automated and Continuous Backup Reserving data solutions automate the backup process, eliminating the need for manual intervention. These solutions continuously monitor endpoint devices for changes and securely back up the modified data in real-time or at scheduled intervals. This ensures that data is constantly upgraded and protected without relying on user compliance. Secure Data Encryption To maintain data confidentiality, the solutions employ robust encryption techniques. Data is encrypted before transmission and remains encrypted during storage, ensuring that even if the backup files are compromised, the data remains unreadable to unauthorized individuals. That said, encryption keys are typically managed by the organization, further enhancing data security. Centralized Management and Monitoring The solutions provide centralized management consoles that allow IT administrators to oversee the backup operations of all endpoint devices within the organization. From a single interface, administrators can monitor backup status, schedule backups, and implement policies to ensure consistent data protection across all endpoints. This centralized approach streamlines management and reduces the administrative burden on IT teams. Granular Recovery Options In the event of loss or corruption, reserving data software offer granular recovery options. As such, IT administrators can selectively restore individual files, folders, or even entire devices, providing flexibility and minimizing downtime. This granular recovery capability empowers organizations to swiftly recover specific data without having to restore the entire backup. Conclusion Backup software plays a vital role in safeguarding organizational data in today’s dynamic and distributed work environment. By implementing robust and reliable endpoint backup solutions, organizations can ensure data loss prevention, meet compliance requirements, and support a remote workforce effectively. With automated and continuous backup, secure data encryption, centralized management, and granular recovery options, reserve software solutions provide comprehensive protection for data wherever it resides. So, protect your valuable data and secure your business’s future by investing in a reliable backup solution today. Happy Happy 0 % Sad Sad 0 % Excited Excited 0 % Sleepy Sleepy 0 % Angry Angry 0 % Surprise Surprise 0 % Average Rating 5 Star 0% 4 Star 0% 3 Star 0% 2 Star 0% 1 Star 0% Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.706635
Sending and Managing Network Requests Overview Network requests are used to retrieve or modify API data or media from a server. This is a very common task in Android development especially for dynamic data-driven clients. The underlying Java class used for network connections is DefaultHTTPClient or HttpUrlConnection. Both of these are lower-level and require completely manual management of parsing the data from the input stream and executing the request asynchronously. DefaultHTTPClient, otherwise known as the Apache HTTP Client, has been deprecated since Android 6.0. The reason for two different HTTP clients is described in this blog article. A historical perspective is also discussed in this podcast. For most common cases, we are better off using a popular third-party library called android-async-http or OkHttp which will handle the entire process of sending and parsing network requests for us in a more robust and easy-to-use way. Permissions In order to access the internet, be sure to specify the following permissions in AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.simplenetworking" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> </manifest> Sending an HTTP Request (Third Party) There are at least three major third-party networking libraries you should consider using. • See the Android Async Http Client guide for making basic network calls. It is the library often used for learning Android but would not be used in a production application. • See the OkHttp guide for making synchronous and asynchronous calls. • See also the Retrofit guide, which uses OkHttp and makes it easier to make more RESTful API calls. Read through this guide to understand how the Gson library works with Retrofit. • Check out the Volley guide, a library built by Google that has fallen out of favor for OkHttp. It was one of the first networking libraries released for Android and provides a more convenient way to make networking requests than using AsyncTask. There can be a bit of a learning curve when using these libraries, so your best bet when first learning is to use Android Async Http Client or Volley. With OkHttp you also have to deal with the complexity of whether your callbacks need to be run on the main thread to update the UI, as explained in the guide. Here is a comparison of the different aspects of the libraries. Android Async Http OkHttp Volley Debugging Requires Proxy server Use LogInterceptor Use verbose mode Disk Caching Yes Yes Yes Request Queueing No No Included Remote Image Fetching Manual Requires Picasso or Glide Included Animated GIF Support No Requires Glide Requires Glide Release Cadence Infrequent Monthly Infrequent Transport Layer Apache HTTP Client OkHttp HttpUrlConnection (or OkHttp) Synchronous Calls use SyncHttpClient execute() instead of enqueue() use RequestFuture HTTP/2 No Yes Works with OkHttp Automatic Gzip processing Yes Yes No (unless using OkHttp) Author James Smith Square Google One issue with Android Async Http Client is that the library has very limited ways to observe network traces that are useful for debugging. Volley provides remote fetching images out of the box, while Android Async Http client requires more manual work and OkHttp needs the Picasso or Glide library in order to do so. Another important point is that OkHttp is not only a standalone networking library but also can be used for the underlying implementation for HttpUrlConnection. For this reason, Volley can also leverage OkHttp to support automatic Gzip and HTTP/2 processing. Sending an HTTP Request (The "Hard" Way) Sending an HTTP Request involves the following conceptual steps: 1. Declare a URL Connection 2. Open InputStream to connection 3. Download and decode based on data type 4. Wrap in AsyncTask and execute in background thread This would translate to the following networking code to send a simple request (with try-catch structured exceptions not shown here for brevity): // 1. Declare a URL Connection URL url = new URL("http://www.google.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 2. Open InputStream to connection conn.connect(); InputStream in = conn.getInputStream(); // 3. Download and decode the string response using builder StringBuilder stringBuilder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } The fourth step requires this networking request to be executed in a background task using AsyncTasks such as shown below: // The types specified here are the input data type, the progress type, and the result type // Subclass AsyncTask to execute the network request // String == URL, Void == Progress Tracking, String == Response Received private class NetworkAsyncTask extends AsyncTask<String, Void, Bitmap> { protected String doInBackground(String... strings) { // Some long-running task like downloading an image. // ... code shown above to send request and retrieve string builder return stringBuilder.toString(); } protected void onPostExecute(String result) { // This method is executed in the UIThread // with access to the result of the long running task // DO SOMETHING WITH STRING RESPONSE } } private void downloadResponseFromNetwork() { // 4. Wrap in AsyncTask and execute in background thread new NetworkAsyncTask().execute("http://google.com"); } Displaying Remote Images (The "Easy" Way) Displaying images is easiest using a third party library such as Glide which will download and cache remote images and abstract the complexity behind an easy to use DSL: String imageUri = "https://i.imgur.com/tGbaZCY.jpg"; ImageView ivBasicImage = (ImageView) findViewById(R.id.ivBasicImage); Glide.with(context).load(imageUri).into(ivBasicImage); Refer to our Glide Guide for more detailed usage information and configuration. Displaying Remote Images (The "Hard" Way) Suppose we wanted to load an image using only the built-in Android network constructs. In order to download an image from the network, convert the bytes into a bitmap and then insert the bitmap into an imageview, you would use the following pseudo-code: // 1. Declare a URL Connection URL url = new URL("https://i.imgur.com/tGbaZCY.jpg"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 2. Open InputStream to connection conn.connect(); InputStream in = conn.getInputStream(); // 3. Download and decode the bitmap using BitmapFactory Bitmap bitmap = BitmapFactory.decodeStream(in); in.close(); // 4. Insert into an ImageView ImageView imageView = (ImageView) findViewById(R.id.imageView); imageView.setImageBitmap(bitmap); Here's the complete code needed to construct an AsyncTask that downloads a remote image and displays the image in an ImageView using just the official Google Android SDK. See the Creating and Executing Async Tasks for more information about executing asynchronous background tasks: public class MainActivity extends Activity { private ImageView ivBasicImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ivBasicImage = (ImageView) findViewById(R.id.ivBasicImage); String url = "https://i.imgur.com/tGbaZCY.jpg"; // Download image from URL and display within ImageView new ImageDownloadTask(ivBasicImage).execute(url); } // Defines the background task to download and then load the image within the ImageView private class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> { ImageView imageView; public ImageDownloadTask(ImageView imageView) { this.imageView = imageView; } protected Bitmap doInBackground(String... addresses) { Bitmap bitmap = null; InputStream in = null; try { // 1. Declare a URL Connection URL url = new URL(addresses[0]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 2. Open InputStream to connection conn.connect(); in = conn.getInputStream(); // 3. Download and decode the bitmap using BitmapFactory bitmap = BitmapFactory.decodeStream(in); } catch (IOException e) { e.printStackTrace(); } finally { if(in != null) try { in.close(); } catch (IOException e) { Log.e(TAG, "Exception while closing inputstream"+ e); } } } return bitmap; } // Fires after the task is completed, displaying the bitmap into the ImageView @Override protected void onPostExecute(Bitmap result) { // Set bitmap image for the result imageView.setImageBitmap(result); } } } We could even create our own basic version of a library for loading images by wrapping up this logic into an object as outlined here. Of course, doing this the "hard" way is not recommended. In most cases, to avoid having to manually manage caching and download management, we are better off creating your own libraries or in most cases utilizing existing third-party libraries. Note: If you use the approach above to download and display many images within a ListView, you might run into some threading issues that cause buggy loading of images. The blog post Multithreading for Performance offers a solution in which you manage the active remote downloading background tasks to ensure that too many tasks are not being spun up at once. Checking for Network Connectivity Checking Network is Connected First, make sure to setup the android.permission.ACCESS_NETWORK_STATE permission as shown above. To verify network availability you can then define and call this method: private Boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); } Note that having an active network interface doesn't guarantee that a particular networked service is available or that the internet is actually connected. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service. See this official connectivity guide for more details. Checking the Internet is Connected To verify if the device is actually connected to the internet, we can use the following method of pinging the Google DNS servers to check for the expected exit value: public boolean isOnline() { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = ipProcess.waitFor(); return (exitValue == 0); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } Note that this does not need to be run in background and does not require special privileges. See this stackoverflow post for the source of this solution. Troubleshooting Take a look at Troubleshooting API Calls to understand how to gain better visibility about what your network calls are doing. References Fork me on GitHub
__label__pos
0.800076
HELP, My Hard Drive Is Not Being Detected In BIOS. BIOS (Basic Input Output System) is the way in which a computer can start up and load up the operating system. One of the pieces of information it stores is information about the boot device, for the purposes of this text this is assumed to be a mechanical hard disk. Mechanical hard disks are the most popular type of storage technology in the world but eventually they will fail.   WHY CANT THE COMPUTER SEE THE DISK?   Even though the disk is spinning and is correctly attached to the computer when disks fail in a specific way the BIOS will not be able to detect the disk and therefore will not be able to boot the operating system. Disks which have failed in this manner are known to have or be developing many bad sectors; hard disks are split into sectors to store the data on their platters (typically these sectors are 512 bytes each but there are exceptions). Modern hard disks have the ability to remap bad sectors to prolong their life but this is not a fail safe against failure, every mechanical hard disk will fail in this way if it does not fail in another way first, it is simply a case of when not if. The life expectancy can vary from disk to disk, some fail after a few weeks others can last years and years, even decades. When they break down to a certain extent the BIOD is not able to detect the disk and as such doesn't show that a disk is present.   Bios No disk shown   CAN I GET THE DATA BACK MYSELF?   Without the assistance of a data recovery laboratory the chances of you getting your data back is slim at best. There are some tricks that could be applied in the case of a hard disk that has failed in this manner although in most instances this will not result in a full recovery and could cause more damage to the data.   HOW DO YOU GET MY DATA BACK?   In a nutshell several methods are used to recover data from disk which have failed in this manner, one in particular being the use of specialised hardware that reads data from the disk is a different and much less demanding way in which a normal computer and operating system does. This process is something which varies from disk to disk, each failed disk is unique. The recover involves a multi pass read process which is unique in how it reads each sector and how it deals with bad sectors i.e. initially only sectors which are reading normally are read; the subsequent reads are carried out in their own unique way. It is also necessary to configure the recovery process for specific manufacturers whilst also bearing in mind the possibility for a more severe disk failure such as head failure during the recovery process.   Whilst normally considered to be a less complicated failure it is by no means unusual for disks that have failed in this way to take longer to recover then one that has sustained a mechanical issue. Hard disks have many millions of sectors but it only takes a small number to stop a disk working. 6 Years, 8 Months, 4 Weeks, 2 Days, 3 Hours, 13 Minutes ago. free no obligation consultation 0800 955 3282 Email
__label__pos
0.872676
akaros/user/parlib/ucq.c << >> Prefs 1/* Copyright (c) 2011 The Regents of the University of California 2 * Barret Rhoden <[email protected]> 3 * See LICENSE for details. 4 * 5 * Unbounded concurrent queues, user side. Check k/i/r/ucq.h or the 6 * Documentation for more info. */ 7 8#include <ros/arch/membar.h> 9#include <parlib/arch/atomic.h> 10#include <parlib/arch/arch.h> 11#include <parlib/ucq.h> 12#include <parlib/spinlock.h> 13#include <sys/mman.h> 14#include <parlib/assert.h> 15#include <parlib/stdio.h> 16#include <stdlib.h> 17#include <parlib/vcore.h> 18#include <parlib/ros_debug.h> /* for printd() */ 19 20/* Initializes a ucq. You pass in addresses of mmaped pages for the main page 21 * (prod_idx) and the spare page. I recommend mmaping a big chunk and breaking 22 * it up over a bunch of ucqs, instead of doing a lot of little mmap() calls. */ 23void ucq_init_raw(struct ucq *ucq, uintptr_t pg1, uintptr_t pg2) 24{ 25 printd("[user] initializing ucq %08p for proc %d\n", ucq, getpid()); 26 assert(!PGOFF(pg1)); 27 assert(!PGOFF(pg2)); 28 /* Prod and cons both start on the first page, slot 0. When they are 29 * equal, the ucq is empty. */ 30 atomic_set(&ucq->prod_idx, pg1); 31 atomic_set(&ucq->cons_idx, pg1); 32 ucq->prod_overflow = FALSE; 33 atomic_set(&ucq->nr_extra_pgs, 0); 34 atomic_set(&ucq->spare_pg, pg2); 35 parlib_static_assert(sizeof(struct spin_pdr_lock) <= 36 sizeof(ucq->u_lock)); 37 spin_pdr_init((struct spin_pdr_lock*)(&ucq->u_lock)); 38 ucq->ucq_ready = TRUE; 39} 40 41/* Inits a ucq, where you don't have to bother with the memory allocation. This 42 * would be appropriate for one or two UCQs, though if you're allocating in 43 * bulk, use the raw version. */ 44void ucq_init(struct ucq *ucq) 45{ 46 uintptr_t two_pages = (uintptr_t)mmap(0, PGSIZE * 2, 47 PROT_WRITE | PROT_READ, 48 MAP_POPULATE | MAP_ANONYMOUS | 49 MAP_PRIVATE, -1, 0); 50 51 assert(two_pages); 52 ucq_init_raw(ucq, two_pages, two_pages + PGSIZE); 53} 54 55/* Only call this on ucq's made with the simple ucq_init(). And be sure the ucq 56 * is no longer in use. */ 57void ucq_free_pgs(struct ucq *ucq) 58{ 59 uintptr_t pg1 = atomic_read(&ucq->prod_idx); 60 uintptr_t pg2 = atomic_read(&ucq->spare_pg); 61 62 assert(pg1 && pg2); 63 munmap((void*)pg1, PGSIZE); 64 munmap((void*)pg2, PGSIZE); 65} 66 67/* Consumer side, returns TRUE on success and fills *msg with the ev_msg. If 68 * the ucq appears empty, it will return FALSE. Messages may have arrived after 69 * we started getting that we do not receive. */ 70bool get_ucq_msg(struct ucq *ucq, struct event_msg *msg) 71{ 72 uintptr_t my_idx; 73 struct ucq_page *old_page, *other_page; 74 struct msg_container *my_msg; 75 struct spin_pdr_lock *ucq_lock = (struct spin_pdr_lock*)(&ucq->u_lock); 76 77 do { 78loop_top: 79 cmb(); 80 my_idx = atomic_read(&ucq->cons_idx); 81 /* The ucq is empty if the consumer and producer are on the same 82 * 'next' slot. */ 83 if (my_idx == atomic_read(&ucq->prod_idx)) 84 return FALSE; 85 /* Is the slot we want good? If not, we're going to need to try 86 * and move on to the next page. If it is, we bypass all of 87 * this and try to CAS on us getting my_idx. */ 88 if (slot_is_good(my_idx)) 89 goto claim_slot; 90 /* Slot is bad, let's try and fix it */ 91 spin_pdr_lock(ucq_lock); 92 /* Reread the idx, in case someone else fixed things up while we 93 * were waiting/fighting for the lock */ 94 my_idx = atomic_read(&ucq->cons_idx); 95 if (slot_is_good(my_idx)) { 96 /* Someone else fixed it already, let's just try to get 97 * out */ 98 spin_pdr_unlock(ucq_lock); 99 /* Make sure this new slot has a producer (ucq isn't 100 * empty) */ 101 if (my_idx == atomic_read(&ucq->prod_idx)) 102 return FALSE; 103 goto claim_slot; 104 } 105 /* At this point, the slot is bad, and all other possible 106 * consumers are spinning on the lock. Time to fix things up: 107 * Set the counter to the next page, and free the old one. */ 108 /* First, we need to wait and make sure the kernel has posted 109 * the next page. Worst case, we know that the kernel is 110 * working on it, since prod_idx != cons_idx */ 111 old_page = (struct ucq_page*)PTE_ADDR(my_idx); 112 while (!old_page->header.cons_next_pg) 113 cpu_relax(); 114 /* Now set the counter to the next page */ 115 assert(!PGOFF(old_page->header.cons_next_pg)); 116 atomic_set(&ucq->cons_idx, old_page->header.cons_next_pg); 117 /* Side note: at this point, any *new* consumers coming in will 118 * grab slots based off the new counter index (cons_idx) */ 119 /* Now free up the old page. Need to make sure all other 120 * consumers are done. We spin til enough are done, like an 121 * inverted refcnt. */ 122 while (atomic_read(&old_page->header.nr_cons) < NR_MSG_PER_PAGE) 123 { 124 /* spinning on userspace here, specifically, another 125 * vcore and we don't know who it is. This will spin a 126 * bit, then make sure they aren't preeempted */ 127 cpu_relax_any(); 128 } 129 /* Now the page is done. 0 its metadata and give it up. */ 130 old_page->header.cons_next_pg = 0; 131 atomic_set(&old_page->header.nr_cons, 0); 132 /* We want to "free" the page. We'll try and set it as the 133 * spare. If there is already a spare, we'll free that one. */ 134 other_page = (struct ucq_page*)atomic_swap(&ucq->spare_pg, 135 (long)old_page); 136 assert(!PGOFF(other_page)); 137 if (other_page) { 138 munmap(other_page, PGSIZE); 139 atomic_dec(&ucq->nr_extra_pgs); 140 } 141 /* All fixed up, unlock. Other consumers may lock and check to 142 * make sure things are done. */ 143 spin_pdr_unlock(ucq_lock); 144 /* Now that everything is fixed, try again from the top */ 145 goto loop_top; 146claim_slot: 147 cmb(); /* so we can goto claim_slot */ 148 /* If we're still here, my_idx is good, and we'll try to claim 149 * it. If we fail, we need to repeat the whole process. */ 150 } while (!atomic_cas(&ucq->cons_idx, my_idx, my_idx + 1)); 151 assert(slot_is_good(my_idx)); 152 /* Now we have a good slot that we can consume */ 153 my_msg = slot2msg(my_idx); 154 /* linux would put an rmb_depends() here */ 155 /* Wait til the msg is ready (kernel sets this flag) */ 156 while (!my_msg->ready) 157 cpu_relax(); 158 rmb(); /* order the ready read before the contents */ 159 /* Copy out */ 160 *msg = my_msg->ev_msg; 161 /* Unset this for the next usage of the container */ 162 my_msg->ready = FALSE; 163 wmb(); /* post the ready write before incrementing */ 164 /* Increment nr_cons, showing we're done */ 165 atomic_inc(&((struct ucq_page*)PTE_ADDR(my_idx))->header.nr_cons); 166 return TRUE; 167} 168 169bool ucq_is_empty(struct ucq *ucq) 170{ 171 /* The ucq is empty if the consumer and producer are on the same 'next' 172 * slot. */ 173 return (atomic_read(&ucq->cons_idx) == atomic_read(&ucq->prod_idx)); 174} 175
__label__pos
0.946055
Tutorials Snippets Search Tags Subscribe on Youtube Shared Preferences Service in Flutter for Code Maintainability Cover image Storing/Caching values on disk is a very common task in Mobile App Development. The way this is done in Flutter is typically using the shared_preferences package. Values are stored in here to keep track of a user has logged in, user profiles, api tokens that are long lived, deviceId's from a service etc. I've used it a few times and always wrap it in a service that exposes typed properties to make it easier to use in code. This is typical usage of the shared preferences. var preferences = await SharedPreferences.getInstance(); // Save a value preferences.setString('value_key', 'hello preferences'); // Retrieve value later var savedValue = preferences.getString('value_key'); I don't like this because of the following reasons: 1. Keys can easily be typed wrong causing unnecessary debugging. Solution: Store key in constants 2. I don't know exactly what I'm saving. Relying only on keys to determine what's being saved is not a good form of documentation. 3. If I wanted to know what data was saved in my session there's no single place to log everything being saved. We'll create a service to wrap this functionality so it's easier to use and maintain and transferable between projects. In your services folder (You should have one 😉) create new file called localstorage_service.dart and define a new class LocalStorageService. This service will use the Singleton pattern and instances will be retrieved through a getInstance() static function. We'll keep a static instance of the SharedPreferences as well as the instance for our service. class LocalStorageService { static LocalStorageService _instance; static SharedPreferences _preferences; static Future<LocalStorageService> getInstance() async { if (_instance == null) { _instance = LocalStorageService(); } if (_preferences == null) { _preferences = await SharedPreferences.getInstance(); } return _instance; } } Let's get all the setup done before we continue. Register the service with your locator as a singleton. If you don't have dependency injection setup, I highly recommend setting it up. It's only 10 lines of code (I think.). Once setup, register your service as a singleton. Future setupLocator() async { var instance = await LocalStorageService.getInstance(); locator.registerSingleton<LocalStorageService>(instance); } We'll cover saving a complex object and primitive types. We'll cover the verbose object saving first, then the easier short hand primitive type saving. A common use case for shared_preferences is to know if the user has logged in or not, that way we can show either the login screen or the home screen. We'll save a User model and then also some booleans to simulate a settings preferences (another common use case). First create the user model. class User { final String name; final String surname; final int age; User({this.name, this.surname, this.age}); User.fromJson(Map<String, dynamic> json) : name = json['name'], surname = json['surname'], age = json['age']; Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['name'] = this.name; data['surname'] = this.surname; data['age'] = this.age; return data; } } Having the toJson and fromJson values is important. You can use this site to generate models from complex json. I usually type my model as json then just generate and save. It's easier and faster than typing the code out. We'll add a getter and a setter onto our service of type User. The way this will be handled is by converting the model into json and then saving the json to disk as is. When retrieving we'll serialize back into the model. static const String UserKey = 'user'; ... User get user { var userJson = _getFromDisk(UserKey); if (userJson == null) { return null; } return User.fromJson(json.decode(userJson)); } set user(User userToSave) { saveStringToDisk(UserKey, json.encode(userToSave.toJson())); } dynamic _getFromDisk(String key) { var value = _preferences.get(key); print('(TRACE) LocalStorageService:_getFromDisk. key: $key value: $value'); return value; } void saveStringToDisk(String key, String content){ print('(TRACE) LocalStorageService:_saveStringToDisk. key: $key value: $content'); _preferences.setString(UserKey, content); } With this we now have named constants at the top so we avoid making mistakes when retyping the values. We have named properties that tells us exactly what we're setting or saving. We can treat it as a property in our code so the readability is great .i.e. localStorage.user = retrievedUser. Aaaand, if our trace logging is enabled we will be able to see what's being saved and retrieved throughout our session. The saveStringToDisk function will be updated below to handle all types. You won't have to type it, you can just copy and paste 👨‍💻 The way you'll use it in your app is by getting your instance from the locator and use the property as a normal property. import '../service_locator.dart'; ... var storageService = locator<LocalStorageService>(); var mySavedUser = storageService.user; There's a little boiler plate associated with adding new properties, but I guarantee you it's worth the effort. As your application grows and you get some old data/caching bugs associated with your shared_preferences you'll be very happy you can trace through everything and check what code sets or reads these values. Let's add two more values just to see the steps involved and call it a day. We'll add the keys. static const String AppLanguagesKey = 'languages'; static const String DarkModeKey = 'darkmode'; Add the properties that we want to expose the values through. ... bool get darkMode => _getFromDisk(DarkModeKey) ?? false; set darkMode(bool value) => _saveToDisk(DarkModeKey, value); List<String> get languages => _getFromDisk(AppLanguagesKey) ?? List<String>(); set languages(List<String> appLanguages) => _saveToDisk(AppLanguagesKey, appLanguages); // updated _saveToDisk function that handles all types void _saveToDisk<T>(String key, T content){ print('(TRACE) LocalStorageService:_saveToDisk. key: $key value: $content'); if(content is String) { _preferences.setString(key, content); } if(content is bool) { _preferences.setBool(key, content); } if(content is int) { _preferences.setInt(key, content); } if(content is double) { _preferences.setDouble(key, content); } if(content is List<String>) { _preferences.setStringList(key, content); } } ... And that's it. Now when using the Shared preferences to store local values you don't have to force async functions just to instantiate the instance and your code readability and health gets a boost for long term maintenance. If you're using get it then read below. Since the service singleton is created using a Future, you have to make sure you wait for it to complete before running the app. Change your main method to look like this. Future<void> main() async { try { await setupLocator(); runApp(MyApp()); } catch(error) { print('Locator setup has failed'); } } Checkout and subscribe to my Youtube Channel. Follow me on Instagram for snippets and day-to-day programming. Checkout all the other snippets here. You might find some more Flutter magic. Also check out Cover image Flutter Basics - Going from setState to Architecture In this tutorial I will be going over how to handle a common async situation in Flutter, without throwing architectures at the problem Link Cover image A Guide to setting up better Logging in Flutter This article covers logging in Flutter to help with debugging. Link Cover image Easy toasts with OkToast This tutorial covers an easy way to show and style toast messages. Link
__label__pos
0.94748
aboutsummaryrefslogtreecommitdiff path: root/libssh/auth1.c blob: cf24ae17fff74d2924ca1049fad6f8f1432df5f6 (plain) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 /* * auth1.c - authentication with SSH-1 protocol * * This file is part of the SSH Library * * Copyright (c) 2005-2008 by Aris Adamantiadis * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The SSH Library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the SSH Library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ #include <string.h> #include <stdlib.h> #include "libssh/priv.h" #include "libssh/ssh1.h" #ifdef HAVE_SSH1 static int wait_auth1_status(SSH_SESSION *session) { /* wait for a packet */ if (packet_read(session) != SSH_OK) { return SSH_AUTH_ERROR; } if(packet_translate(session) != SSH_OK) { return SSH_AUTH_ERROR; } switch(session->in_packet.type) { case SSH_SMSG_SUCCESS: return SSH_AUTH_SUCCESS; case SSH_SMSG_FAILURE: return SSH_AUTH_DENIED; } ssh_set_error(session, SSH_FATAL, "Was waiting for a SUCCESS or " "FAILURE, got %d", session->in_packet.type); return SSH_AUTH_ERROR; } static int send_username(SSH_SESSION *session, const char *username) { STRING *user = NULL; /* returns SSH_AUTH_SUCCESS or SSH_AUTH_DENIED */ if(session->auth_service_asked) { return session->auth_service_asked; } if (!username) { if(!(username = session->options->username)) { if(ssh_options_default_username(session->options)) { return session->auth_service_asked = SSH_AUTH_ERROR; } else { username = session->options->username; } } } user = string_from_char(username); if (user == NULL) { return SSH_AUTH_ERROR; } if (buffer_add_u8(session->out_buffer, SSH_CMSG_USER) < 0) { string_free(user); return SSH_AUTH_ERROR; } if (buffer_add_ssh_string(session->out_buffer, user) < 0) { string_free(user); return SSH_AUTH_ERROR; } string_free(user); if (packet_send(session) != SSH_OK) { return SSH_AUTH_ERROR; } session->auth_service_asked = wait_auth1_status(session); return session->auth_service_asked; } /* use the "none" authentication question */ int ssh_userauth1_none(SSH_SESSION *session, const char *username){ return send_username(session, username); } /* int ssh_userauth_offer_pubkey(SSH_SESSION *session, char *username,int type, STRING *publickey){ STRING *user; STRING *service; STRING *method; STRING *algo; int err=SSH_AUTH_ERROR; if(!username) if(!(username=session->options->username)){ if(options_default_username(session->options)) return SSH_AUTH_ERROR; else username=session->options->username; } if(ask_userauth(session)) return SSH_AUTH_ERROR; user=string_from_char(username); service=string_from_char("ssh-connection"); method=string_from_char("publickey"); algo=string_from_char(ssh_type_to_char(type)); packet_clear_out(session); buffer_add_u8(session->out_buffer,SSH2_MSG_USERAUTH_REQUEST); buffer_add_ssh_string(session->out_buffer,user); buffer_add_ssh_string(session->out_buffer,service); buffer_add_ssh_string(session->out_buffer,method); buffer_add_u8(session->out_buffer,0); buffer_add_ssh_string(session->out_buffer,algo); buffer_add_ssh_string(session->out_buffer,publickey); packet_send(session); err=wait_auth_status(session,0); free(user); free(method); free(service); free(algo); return err; } */ /** \internal * \todo implement ssh1 public key */ int ssh_userauth1_offer_pubkey(SSH_SESSION *session, const char *username, int type, STRING *pubkey) { return SSH_AUTH_DENIED; } /* int ssh_userauth_pubkey(SSH_SESSION *session, char *username, STRING *publickey, PRIVATE_KEY *privatekey){ STRING *user; STRING *service; STRING *method; STRING *algo; STRING *sign; int err=SSH_AUTH_ERROR; if(!username) if(!(username=session->options->username)){ if(options_default_username(session->options)) return err; else username=session->options->username; } if(ask_userauth(session)) return err; user=string_from_char(username); service=string_from_char("ssh-connection"); method=string_from_char("publickey"); algo=string_from_char(ssh_type_to_char(privatekey->type)); */ /* we said previously the public key was accepted */ /* packet_clear_out(session); buffer_add_u8(session->out_buffer,SSH2_MSG_USERAUTH_REQUEST); buffer_add_ssh_string(session->out_buffer,user); buffer_add_ssh_string(session->out_buffer,service); buffer_add_ssh_string(session->out_buffer,method); buffer_add_u8(session->out_buffer,1); buffer_add_ssh_string(session->out_buffer,algo); buffer_add_ssh_string(session->out_buffer,publickey); sign=ssh_do_sign(session,session->out_buffer,privatekey); if(sign){ buffer_add_ssh_string(session->out_buffer,sign); free(sign); packet_send(session); err=wait_auth_status(session,0); } free(user); free(service); free(method); free(algo); return err; } */ int ssh_userauth1_password(SSH_SESSION *session, const char *username, const char *password) { STRING *pwd = NULL; int rc; rc = send_username(session, username); if (rc != SSH_AUTH_DENIED) { return rc; } /* we trick a bit here. A known flaw in SSH1 protocol is that it's * easy to guess password sizes. * not that sure ... */ /* XXX fix me here ! */ /* cisco IOS doesn't like when a password is followed by zeroes and random pad. */ if(1 || strlen(password) >= 128) { /* not risky to disclose the size of such a big password .. */ pwd = string_from_char(password); if (pwd == NULL) { return SSH_AUTH_ERROR; } } else { /* fill the password string from random things. the strcpy * ensure there is at least a nul byte after the password. * most implementation won't see the garbage at end. * why garbage ? because nul bytes will be compressed by * gzip and disclose password len. */ pwd = string_new(128); if (pwd == NULL) { return SSH_AUTH_ERROR; } ssh_get_random( pwd->string, 128, 0); strcpy((char *) pwd->string, password); } if (buffer_add_u8(session->out_buffer, SSH_CMSG_AUTH_PASSWORD) < 0) { string_burn(pwd); string_free(pwd); return SSH_AUTH_ERROR; } if (buffer_add_ssh_string(session->out_buffer, pwd) < 0) { string_burn(pwd); string_free(pwd); return SSH_AUTH_ERROR; } string_burn(pwd); string_free(pwd); if (packet_send(session) != SSH_OK) { return SSH_AUTH_ERROR; } return wait_auth1_status(session); } #endif /* HAVE_SSH1 */ /* vim: set ts=2 sw=2 et cindent: */
__label__pos
0.971237
~registry/kmod/master Viewing all changes in revision 1312. • Committer: Lucas De Marchi • Author(s): Sam James • Date: 2023-11-06 00:22:05 UTC • Revision ID: git-v1:3af2f475b0b729f20279f2ce488cc9f727f0b763 tools: depmod: fix -Walloc-size GCC 14 introduces a new -Walloc-size included in -Wextra which gives: ``` tools/depmod.c:192:14: warning: allocation of insufficient size ‘1’ for type ‘struct index_node’ with size ‘1048’ [-Walloc-size] tools/depmod.c:255:11: warning: allocation of insufficient size ‘1’ for type ‘struct index_value’ with size ‘16’ [-Walloc-size] tools/depmod.c:286:35: warning: allocation of insufficient size ‘1’ for type ‘struct index_node’ with size ‘1048’ [-Walloc-size] tools/depmod.c:315:44: warning: allocation of insufficient size ‘1’ for type ‘struct index_node’ with size ‘1048’ [-Walloc-size] ``` The calloc prototype is: ``` void *calloc(size_t nmemb, size_t size); ``` So, just swap the number of members and size arguments to match the prototype, as we're initialising 1 struct of size `sizeof(struct ...)`. GCC then sees we're not doing anything wrong. Signed-off-by: Sam James <[email protected]> expand all expand all Show diffs side-by-side added added removed removed Lines of Context:
__label__pos
0.518028
User Generated Content, Youtube in the NYT A good piece in the NYT about user generated digital content. The article describes the amateur creation of video content on You Tube It's not seminudes or celebrity satire or kittens' antics that dominate the most-viewed list at YouTube.com, the popular clearinghouse for international homemade video. So exactly what videos are drawing viewers to this ascendant site, which, less than a year after its launch, averages about 25 million hits each day? YouTube makes this question easy to answer by giving users several ways to sort the videos, including by "most discussed," "most recent" and, handily, "most viewed." It turns out that most of the videos that get millions of looks are humorous posturings by kids who in other places and at other times might be collecting near-mint X-Men comics, or practicing Metallica licks. Why do I blog this? first because I tend to replace tv watching by you tube scanninng, and second because I am really impressed by the burst of creation on the net. See for instance this graph generated via Alexaholic: after the explosion of pictures exchanged on flickr (in red which is still increasing), the traffic on youtube (in blue) is now starting to skyrocket, even more than flickr:
__label__pos
0.844122
Dispenser Exploit From 2b2t Wiki Jump to navigation Jump to search The Dispenser Exploit was a crash exploit discovered in early February 2021 by the Brownmen. History The exploit involved players placing a dispenser-block at build limit upward and placing a filled shulker-box in it. Once activated with for example a button, the dispenser moved the box above build-limit. This caused the server and client to instantly crash. The same exploit could also be used at the void, with a dispenser facing down into the void. The exploit was utilized on different anarchy servers, most notably on 2b2t by player romtec. After the server was down for an hour, the exploit was patched.[1][2] References
__label__pos
0.732296
UNB ECE4253 Digital Communications Department of Electrical and Computer Engineering - University of New Brunswick, Fredericton, NB, Canada Error Detection with the CRC The Cyclic Redundancy Check (CRC) involves appending a number of extra bits to a binary message to achieve error detection for a variety of possible bit errors. While the use of a single parity bit allows detection of single bit errors, a second error will go undetected, as will any even number of bit errors. Unless the probability of a error is very low and a message is very short (the case when a parity bit is added to a 7-bit ASCII character) the chances of some error event going undetected may be high. In contrast, by using many extra bits the CRC can potentially detect multiple bit errors. Systematic Block Code (n,k) In general, use of parity bits or the CRC are both examples of systematic block codes, where a block of k input bits is taken to create an n-bit codeword known as an (n,k) code. The number of extra bits is p = n-k. By this definition, the use of 7-bits plus parity describes an (8,7) code for which p= (8 - 7) =1. The code is systematic in that the extra bits are appended to unmodified data bits. In the case of CRC, the block size k is often variable, while the constant p depends on the degree of a defining polynomial P(x). Like the systematic ISBN or LUHN-10 algorithms, the CRC algorithm computes the modulus of a known constant (polynomial) that is often prime. Upon reception a zero remainder after division indicates no error has been detected. The Cyclic Redundancy Check (CRC) Consider a message having many data bits which are to be transmitted reliably by appending several check bits as shown below. message bits check bits The exact number of extra bits and their makeup depends on a generating polynomial. For example, one such polynomial is: x16 + x12 + x5 + 1 A Standard Generating Polynomial - CRC(CCITT) The number of CRC bits corresponds to the degree of the generating polynomial. The above polynomial of degree 16 generates a 16-bit CRC. Typically, the CRC bits are used for error detection only. CRC Computation Consider a message represented by some polynomial M(x), and a generating polynomial P(x). In this example, let M(x) represent the binary message 110010, and let P(x) = x3 + x2 + 1 = (1101). The polynomial P(x) will be used to generate three check bits called CRC(x) which will be appended to M(x). Note that this P(x) is prime. 110010 CRC The polyomial P(x) defines the CRC bits for a given message. The check bits will be chosen such that the entire message+crc will be an exact multiple of P(x). The steps to achieving this goal are shown below. Step 1 - Multiply the message M(x) by x3, where 3 is the number of bits in the CRC. Add 3 three zeros to the binary M(x). Step 2 - Divide the product M(x) x3 by the generating polynomial P(x). We wish to find "the remainder, modulo P(x)" Compute the following: 100100 (ignore this quotient) ------------ 1101 ) 110010000 1101 ---- 1100 1101 ---- 100 = remainder = R(x) Observe that if R(x) were in place of the appended zeros, the remainder would become 000. Let CRC(x) = R(x). Check the math with the online polynomial calculator. Consider the decimal number x=41 and the divisor y=13. Q: What can be done to make x divisible by y? A: If 41 ≡ 2 mod 13, then (41-2) ≡ 0 mod 13. In general, if the division x/y gives remainder z, then (x-z)/y gives remainder zero. Step 3 - Add the remainder CRC(x) to the product M(x) x3 to give the code message polynomial C(x): C(x) = M(x) x3 + CRC(x) Put the remainder CRC(x)=100 in place of the three zeros added in Step 1. 110010 100 The message may now be transmitted The transmission C(x) = (110010100) is now an exact multiple of P(x) = (1101); division C(x)/P(x) gives zero remainder, or C(x) ≡ 0 mod P(x). Upon reception, it is expected that an errored message will no longer be a multiple of P(x). MATLAB Example The above result can be found directly using the MATLAB Communications Toolbox as: >> Hgen = comm.CRCGenerator([1 1 0 1]); % specify polynomial as [1 1 0 1] or [3 2 0] >> M = [1 1 0 0 1 0]; % M(x) = message bits >> C = step(Hgen, M'); % supply message bits as a column vector >> disp( C' ); % C(x) = codeword returned as column vector 1 1 0 0 1 0 1 0 0 The output C(x) includes three CRC bits appended (highlighted). This codeword may now be transmitted. CRC Error Checking - No Errors Upon reception, an entire received codeword R(x) = "message + crc" can be checked simply by dividing R(x)/P(x) using the same generating polynomial. If the remainder after division equals zero, then no error was found. 100100 (ignore this quotient) ------------ 1101 ) 110010100 1101 ---- 1101 1101 ---- 000 = remainder (no error) Check the math with the online polynomial calculator. MATLAB Example The above result with no error can be checked as: >> Hdet = comm.CRCDetector([1 1 0 1]); % specify polynomial as [1 1 0 1] or [3 2 0] >> R = C; % R(x) = received data = the (unerrored) codeword >> [data,error] = step(Hdet, R ); % check the received data R(x) with no error >> disp( error ); 0 The zero result indicates no error was found. A result equal to 1 would indicate a detected error. CRC Error Checking - Single Bit Error A single bit error in bit position K in a message C(x) can be represented by adding the term E(x) = xK, (binary 1 followed by K-zeros). sent: 110010100 = C(x) error: 000001000 = E(x) = x3 --------- received: 110011100 = C(x) + E(x) (error in bit 3) The above error is detected when the CRC division gives a non-zero remainder: 100101 (ignore this quotient) ------------ 1101 ) 110011100 = C(x) + E(x) 1101 ---- 1111 1101 ---- 1000 1101 ---- 101 = remainder (error!) Check the math with the online polynomial calculator. An Important Observation Dividing the received C(x)+E(X) by P(x) revealed the error. On the other hand, since C(x)/P(x) ≡ 0 mod P(x) by definition, the remainder is a function only of the error. An error in this same bit would give the same non-zero remainder regardless of the message bits C(x). C(x) + E(x) C(x) E(x) E(x) ----------- = ----- + ----- = ----- P(x) P(x) P(x) P(x) The remainder is a function only of the errored bits E(x). It follows that the error control performance can be fully explored by examining only the possible errors E(x) independently of any message bits. For example, the above result is the same if only the error E(x) is checked using P(x): 1 (ignore this quotient) ------------ 1101 ) 000001000 = E(x) alone 1101 ---- 101 = remainder (error!) Check the math with the online polynomial calculator. The general performance of the CRC for all possible single bit errors E(x) may now be stated. Since E(x) = xK has no factors other than x, a single bit error will never produce a term exactly divisible by P(x). All single bit errors will be detected. CRC Error Checking - Double Bit Error If E(x) = xK + xK+1, the error pattern includes two adjacent bits (e.g. E(x) = (000011000) for K=3). Since this E(x) has no factors other than (x+1) and x, any adjacent bit errors will never produce a term exactly divisible by P(x). All double bit (adjacent-bit) errors will be detected CRC Error Checking - Simply Parity Observe that a CRC calculation based on the polynomial P(x) = x + 1 leaves a one-bit remainer and is a simple parity generator (even). CRC Error Checking - Choice of P(x) While the choice of a primitive polynomial for P(x) can be advantageous (see below) a compound polynomial that is a multiple of (11) such as P(x)=(11101)=(11)(1011) is also useful; in this case, codewords will be multiples of both (11) and (1011). In particular, the factor (11) ensures that transmitted codewords are necessarily multiples of (11); in other words, all have even parity and any error E(x) having an odd number of 1's will be detected. Two Bit Errors The general two-bit error E(x)=xN+xM is not detected if E(x) is a multiple of P(x). In particular, the E(x)=(10000001) having two bad bits 7-bits apart would not be detected for P(x) = (1101) because (10000001)=(11)(1011)(1101). (Check the math) The allowable separation between two bad bits is related to the choice of P(x) and will be maximum for an primitive polynomial P(x). For example, the prime P(x)=(11111) is not primitive and the two bit error E(x)=(100001) would not be detected since it is an exact multiple of P(x). By instead choosing the primitive P(x)=(11001) of the same degree, all two bit errors up to E(x) = (1000000000000001) will be detected. MATLAB Example The above example of an undetected error can be confirmed as: >> Hdet = comm.CRCDetector([1 1 0 1]); % specify polynomial P(x) as [1 1 0 1] or [3 2 0] >> E = [ 1 0 0 0 0 0 0 1 ]; % This E(x) will be undetected for this P(x) >> [data,error] = step(Hdet, E'); % Check the error pattern E(x) alone. >> disp( error ); 0 The two bit error E(x) = (1 0 0 0 0 0 0 1) was not detected. Any error E(x) that is a multiple of P(x) would not be detected. CRC Error Checking - Undetected Errors From the above discussion, any bit error term E(x) which is an exact multiple of P(x) will not be detected. In general, bit errors and bursts up to N-bits long will be detected for a P(x) of degree N. For arbitrary bit errors longer than N-bits, the odds are one in 2N than a totally false bit pattern will nonetheless lead to a zero remainder. In essence, 100% detection is assured for all errors E(x) not an exact multiple of P(x). For a 16-bit CRC using a primitive P(x) this means: Ultimately, the CRC bits are expected to ensure a minimum Hamming distance between all possible transmitted codewords; consequently, the error detection performance of a given P(x) depends on the codeword length. Given a known codeword size and a sufficently large Hamming distance, error correction is also possible. Thu Aug 22 21:21:49 ADT 2019 Last Updated: 24 JAN 2016 Richard Tervo [ [email protected] ] Back to the course homepage...  
__label__pos
0.977437
Experience design, especially interface design, is perhaps one of the most fertile fields for the idea of scientific design. This is due to several reasons, including: • the multidisciplinary nature of interface design teams, which include people with different backgrounds • the inherent complexity of software as a product • the large number of scientific journals and papers that makes human–computer interaction (HCI) one of the most prolific areas of design research In this article, we discuss three examples of solid scientific knowledge that are often applied to interface design. In our view, the translation of scientific findings into design practices is not always as straight-forward as we wish it would be. The concept of scientific knowledge refers to convictions about the world that have been reached through controlled processes of inquiry and investigation and that, in principle, are not influenced by arbitrary conventions, personal preferences, or individual interests. Scientific knowledge is derived from systematic observation that gradually leads to an understanding of reality that must be valid for everyone. Miller's Classic "7 ± 2" Paper, and What Should Not Be Inferred from It Our first example of misapplication of scientific knowledge by interface design is related to the set of experiments behind a classic paper by George Miller entitled The magical number seven, plus or minus two: Some Limits on Our Capacity for Processing Information. Miller hypothesized a connection between short-term memory span and absolute judgment span. As we do not intend to delve into these concepts, we refer the reader to Miller's paper to check his definition on these cognitive parameters. Miller did not prove his hypothesis—those two quantities are not related. He concluded that, while absolute judgment’s span should be measured by bits of information, short-term memory should be measured by the number of items (“chunks”). But this is very different than saying that immediate memory can only deal with 7 ± 2 items at any given time. Miller was careful not to extrapolate his conclusions beyond the limits of his experiments. His inferences do not go further than allowed by the cited literature or the facts that he observed. Despite this caution, his work has been used as an argument for the reification of the “magic number 7 ± 2” in interface design. Miller’s conclusions do not indicate that there should be rules for how many items menus, lists, or telephone tree systems should have. The task of using one’s home telephone to choose the option to cancel a service from a voice menu is not the same as retrieving word sequences in a lab. When choosing items from a voice menu, you do not start by trying to memorize the items to choose between them later, you don’t know how many options there are in the list, and you don’t know how many of them are relevant to you or how they relate to each other. In this case, you are engaged in a task, and the task influences the way you relate to the information and, therefore, your working memory. If you are asked to retrieve as many items from a list as you can, you will try to memorize the items, but if you are asked to choose among items, you will compare the current item with your best choice so far and so on, in a loop. This behavior can be more difficult to identify, but is no less true, when dealing with written menus or sets of icons, because written words and images operate as memory helpers. Speaking of images, the next topic we chose to approach are visual perception theories. Gestalt Theory and Its Application to Design Another interesting example of problematic application of scientific knowledge by interface designers has to do with visual imagery (i.e., what we see in our minds). Most designers draw a direct association between visual perception and Gestalt Theory, as most of us have been taught that following Gestalt principles is a basic condition for good visual design. Academic papers on the subject reinforce the link between Gestalt principles and good interface design, for example, by affirming that “ignoring Gestalt visual theory will lead to unexpected interpretations by the reader and therefore impede clear communication” (Graham, 2008). The importance of Gestalt principles for interface design are also reaffirmed in books such as Jenifer Tidwell’s Designing Interfaces, which states: "the Gestalt principles of proximity, similarity, continuity, and closure (...) form the foundation of page organization and should not be shortchanged" (2010, p. 477). Questioning Gestalt It is important to recognize the importance of Gestalt and our debt to its founders, who shed light on a topic that once was regarded as not worth exploring. But, as far as we know today, the fundamental Gestaltian claim that perception follows definite principles, and that we perceive a scene as a whole, is not correct. In the late 1970s, David Navon tested the hypothesis of the precedence of global features (instead of individual elements) in visual perception in a set of experiments described in his article Forest Before Trees: The Precedence of Global Features in Visual Perception. He wrote that at that time, “the Gestaltists’ view of the perceptual system as a perfectly elastic device that can swallow and digest all visual information at once, no matter how rich it is, was already considered naïve, as there were experiments that demonstrated that people kept extracting information from a picture for as long as they kept looking at it” (p. 353). Navon’s experiments were based on depictions of large characters composed of other small characters, as shown below. Representation of the visual stimuli used in the first three of Navon's experiments Representation of the visual stimuli used in the first three of Navon's experiments. People were asked to observe large characters composed of small characters and judge which was the biggest letter in the situation (a) and the smallest letter in situation (b). His results indicate that when visual stimulation is not the only source of information, visual processing may favor global features—i.e., the big characters. Navon concluded that “attention cannot be efficiently diverted from the whole [which] may be interpreted as support to the notion that global processing is a necessary stage of perception prior to more fine-grained analysis” (1977, p. 371). In other words, visual perception works by decomposing a scene, not by building it up. Navon’s conclusion reinforces Gestalt principles, which were being questioned at that time. But three years later, another view of perception process took its place. Perception and attention Three years after Navon's experiments were publicized, Anne Treisman and Gary Gelade published Feature integration theory of attention, which predicted that searching for a target that differs in only one characteristic (e.g., color, orientation, or shape) is much faster than searching for targets that differ in more than one characteristic. This prediction is based on the assumption that searching for single characteristics occurs in parallel, without attention limitations, while simultaneous identification of more than one characteristic requires serial searches. Treisman’s and Gelades’s argument is that visual queries happen in a “pre attentive” stage, which is why we are not aware of it. Think of the seeing process as having two stages: a subconscious bottom-up, and an attention-tuned top-down. In the bottom-up stage, patterns emerge from visual characteristics in a process that is not subject to demands of attention. The more prominent these features are, the more they are reinforced. The top-down stage is tuned by attention. The most prominent visual characteristics are reinforced by attention, resulting in visual patterns. In the next stage, they will be grouped with non-visual attributes and be held in our working memory, identified as a chair, a dog, our grandma, or the main menu of a web page. We consciously experience perception as “a whole” because we become aware only of the final outcome of this complicated sequence of prior operations. In this sense, the Gestaltian idea that visual apprehension favors the whole over its parts is not correct, because we are not aware of bottom-up processes that precede it. This implies that you are helpless in orienting the user to find the “news area” of your web page unless he wants to find it. Besides, if every single interface designer always places the menu in exactly the same location, the belief that this is the only possible option is likely to evolve into another of those design patterns that we cherish as undeniable truths, with scorn for any other possible alternative. Color Choice Color choice is another design topic that tends to be justified by oversimplified or misunderstood scientific claims. Color theory can help you choose colors if you are using software such as Adobe Kuler or Color Scheme Designer, but when it comes to explaining why you should choose this color over that, you are, once again, helpless. In graduate-level design courses, you can hear students justifying color choices based on what they believe (or are taught to believe) are natural color connotations: “I chose red because it’s violent and aggressive” or “I chose green because it is the color of hope.” Practically all specialized literature agrees, however, that the feelings and meanings we associate with colors are highly dependent on a large set of variables, the most obvious of which are cultural determinants. Geographical conditions are also known to change the way people relate to color. Wearing white is a promise of good luck on a hot Brazilian New Year's eve, but might not be the most hopeful color for a similar party in Norway. There are, however, studies in specialized color applications that have turned into design guidelines, such as the division between incremental and non-incremental mapping strategies. An example of an incremental mapping would be showing temperature variations on a map using color tones. An example of non-incremental mapping would be using different textures to show on a map where rice, corn, and soy are cultivated. But creating a rule for color (or texture) coding is not enough to ensure your message will be understood. Colin Ware reminds us that the color spectrum (from green to red, the most logical color scheme) is not recognized as an incremental code. He suggests that best results in legibility are achieved through gradual (in opposition to continual) color sequences varying in luminosity or saturation. Colin Ware’s conclusion is an example that the plausibility of an idea (in this case, incremental color coding) does not mean that the sole definition of a rule for color sequence generation can ensure effective design and harmonious results; this would be another ready-made rule for interface design. Conclusion Of course we don’t mean to suggest that interface design cannot benefit from scientific knowledge. But we should be careful when generalizing conclusions obtained in strict academic or laboratory conditions to the real world environment our to the products we’re designing. When possible, you should check the information from the source instead of reading someone else’s interpretation of the conclusions. University lecturers are just as prone to diluting scientific findings into oversimplified rules of thumb as design practitioners are. The need to make sure students’ results meet the standards of academic and professional communities often backfires into the purveyance of simplistic, pseudo-scientific how-to manuals. These works, unfortunately, too often find their way onto the list of best-selling design books. References Graham, Lisa. (2008). Gestalt Theory in Interactive Media Design. Journal of Humanities & Social Sciences 2(1). Kuhn, Thomas (DATA) The Structure of Scientific Revolutions. Chicago, University Of Chicago Press. Miller, George A. (1956) The magical number seven, plus or minus two: some limits on our capacity for processing information. Psychological Review, 63(2), 81-97. Navon, David (1977). Forest before trees: The precedence of global features in visual perception. Cognitive Psychology, 9, 353-383. Tidwell, Jenifer (2010). Designing Interfaces. Cambridge, O'Reilly. Treisman, Anne & Gelade, Gary (1980). A feature-integration theory of attention. Cognitive Psychology, 12, 97-136. Ware, Colin (2008). Visual Thinking for Design. Morgan Kaufmann Article No. 574 | November 2, 2010 Add new comment
__label__pos
0.720308
Book Image Application Development with Swift By : Hossam Ghareeb Book Image Application Development with Swift By: Hossam Ghareeb Overview of this book Table of Contents (14 chapters) The code structure Before starting to write Swift, you have to be aware of its structure, as it is a very important thing to know in any programming language. As we said earlier, Swift is not a superset of C. For sure it's influenced by C and Objective-C but easier and fun to use than both. I will share with you a piece of code in Swift to show its structure: import UIKit let pi = 3.14 //Display all even numbers from 0 to 10 for i in 0...10 { if i % 2 == 0 { println("\(i) is even") } } func sayHello(name: String = "there") { println("Hello \(name)") } sayHello(name: "John") // will print "Hello John" sayHello() //Will print "Hello there", based on default value Tip Downloading the example code You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed direct to you. If you check this code, you will find that we don't use semicolons. This is because in Swift they are optional. However, compiler will not complain if you do use them. The only area where semicolons are required is when you write multiple statements in the same line. In Swift, you use var for variables, and let for constants; but this doesn't mean that Swift is not a typed language. The compiler, based on the initial value, identifies the type implicitly. But in some cases, you have to write the type if you don't set an initial value; or the initial value is not sufficient to identify the type. Consider the following code for example: var count = 5 var msg : String var total : Double = 0 In this code, the count variable is of the Int type, because its initial value is in integer. In the msg variable, we didn't set an initial value, so we will have to explicitly write the type of the msg variable. The same is applicable for total; we need it to be of the Double type but as its initial value is not sufficient, the compiler will consider it as Int. In Swift, you will see that there is no main function to start with, as the code written in the global scope is considered as the start of your program. So, you can imagine that a single line of code in Swift can be considered as a program! The last thing I want to mention is that curly braces are very important in Swift, as they are mandatory in any control flow statements, such as if, while, and so on.
__label__pos
0.973543
CSS Text color difference based on background — 3 minute read permalink Traditional CSS is quite lame; it only allows us to set 1 color for the text. But seeing we create more and more floating and fixed elements, we might want to have a dynamic text-color. How to create a difference based text color in CSS permalink Let's start by marking up the html: <div class="text-container"> <h1>Difference</h1> </div> <section></section> <section></section> Then we want to include two random backgrounds for the sections, let's do that. section { width: 100vw; height: 100vh; background: #000; &:nth-child(odd) { background: #fff; } } And make sure the text div is floating on top of everything! .text-container { position: fixed; width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; color: #fff; mix-blend-mode: difference; h1 { font-size: 150px; } } As you can we we included mix-blend-mode: difference; this makes the color blend in difference based on whatever the background is. Awesome right?! 🤩 This also works on images/videos and what not! See a demo here: See the Pen CSS Text color difference based on background by Chris Bongers (@rebelchris) on CodePen. Browser support permalink Unfortunately not supported by IE, but still overall good support! I use this option a lot to make just that small difference! CSS Mix-blend-mode browser support Thank you for reading, and let's connect! permalink Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
__label__pos
0.963592
Jump to content BE-TR TURK_Trans75 Veteran Driver V • Content Count 128 • Joined • Last visited Community Reputation 12 Truck? 6 Followers About BE-TR TURK_Trans75 • Rank 6t Braco Vans • Birthday 02/02/1991 Profile Information* • Gender Male • Location belgium • Interests trucks -_- • Preferred Trucks Mercedes • EU Garage Location Belgium: Brussels • Known languages dutch;turkish;english Recent Profile Visitors 5857 profile views 1. when i try server 1 it keeps authenticating ??? 2. do we fully support promods ? I see there is a promods 1 server ?? 1. Snorlax. Snorlax. Yes, TruckersMP does support Promods. You may play on promods online on the Promods 1 server. However- you will need to have Promods installed for this to work. 2. BE-TR TURK_Trans75 BE-TR TURK_Trans75 but wasn't it that the black DLC isn't supported by promods ? or am I wrong ? 3. Snorlax. Snorlax. You're right. The recent Road to the black sea DLC is not supported by promods as of right now- you are still able to use Promods though, just without the new DLC area. The developers over at Promods are working hard on supporting the new DLC.   3. when i press F7 i get teleported but I get in the F1 pauze screen and can't get out of it anyone else did have this problem before ? 1. Frotzi Frotzi I found out it's easier to just teleport myself to a garage I own. I also have the same problem when using F7. 2. ZuLynx ZuLynx Yea. The F7 teleport is actually broken in MP. Maybe this will be fixed one day. ;) 4. I did download the promods file and when i start the game i can see my mods in the mod manager but when i start truckerMP they don't apear at all did someone have the same problem like me ? 1. FernandoCR [ESP] FernandoCR [ESP] It is not a problem, it's the way TMP works with ProMods. The mod manager is not needed, so don't worry about that. If you have the ProMods files in your mod folder, you should be able to join the ProMods server right away. 5. unsupported game version ? I'm quite sure I'm runing the latest version but still I get a pop-up that I'm running version 1.34? ,any help ? 1. MarkON MarkON Hello @BE-TR TURK_Trans75 At the moment: Latest version Euro Trcuk Simulator 2 (1.35.3.4s)/American Truck Simulator (1.35.2.11s) is supported. • Steam - Euro Trcuk Simulator 2/American Truck Simulator  - Right Click - Properties - BETAS for Euro Truck Simulator 2/American Truck Simulator - NONE - Opt out of all beta programs  • Install update • Restart Steam & try again launcher TruckersMP as administrator   If it doesn't help. Check the solutions in this topic: Unsupported game version detected! (if game meets the requirements)   I hope you can manage your problem and be able to play on the :tmp: servers Yours sincerely MarkON (player-Veteran Driver) 2. BE-TR TURK_Trans75 BE-TR TURK_Trans75 thank you for the reply the second option did help me ! 6. am I the only one who is getting kicked automaticly from EU2 when i drive the DC road ?? first time he connect me again but second time i can't ?? 7. so Promods and the new DLC are not working toghter :/ 1. Ali. Ali. That's because Promods needs to update to the new DLC so it's not compatible. 2. BE-TR TURK_Trans75 BE-TR TURK_Trans75 @Ali. you can play Promods with the new version they did but when you use Promods the new DLC doesnt show up 8. Promods 2.30 is out !:)) 9. anyone that use a G29 one Windows 10 and know the solution for detection problems ?? couldn't find anything  good on youtube ... 1. Lukavsky TMP Lukavsky TMP Hello, You can post here and supporters will help you - https://forum.truckersmp.com/index.php?/forum/55-help/ 10. Am I the only on who is having trouble with launching ? I get a error " can not create game process" ??? 1. Show previous comments  3 more 2. Soul Knight Soul Knight if you have trouble installing ATS Follow this topic   3. BE-TR TURK_Trans75 BE-TR TURK_Trans75 I found it D:\SteamLibrary\steamapps\common\American Truck Simulator  :P     4. Soul Knight 11. we should have a server +18 and without turkish players i'm also turkish but i swear this isn't fun anymore they don't even know the rules so they can't keep them one the rules start doing something to this 1. Artical DAN Artical DAN do you realize how unsmart this sounds? 2. BE-TR TURK_Trans75 BE-TR TURK_Trans75 unsmart ? haha do you know how it feel to get rammed all the time and start over again over the last save point ? getting rammed for nothing ? hearing they are insulting them eachother ? ;) 12. can someone help me how i can speak in game i did download discord and did connect to truckersmp put my headset in but nothing much happen in the game ? 1. .Rhys. .Rhys. hold V when wanting to talk ^_^ 2. BE-TR TURK_Trans75 3. .Rhys. .Rhys. On ETS2MP, you hold V when you speak. It will go through CB channel 19, unless your on another channel. Also make sure your headset has a mic and the mic switch is on. On discord is either, press to talk or input level.  Also go to your microphone settings to check your input sound level to see if it needs raising (Windows settings) 13. can we disable the winter mod or not ? 1. [ETS2MCG] Kien Giang [ETS2MCG] Kien Giang sure, let discuss xD :) 2. Forraz 3. NexooYT NexooYT Sure! You click TAB in game and then settings, mods: And untick winter mod. (you will need to restart game after that) DONE! Also if u dont want snowflakes to be on, go TAB, settings, Genereal, snow effects(Something like that) and untick and all will be normal. Hope this helps. NexooYT 14. Doğum günün kutlu olsun abi, iyi seneler :)  × × • Create New...
__label__pos
0.889972
mantidimaging.core.operations.divide.divide module class mantidimaging.core.operations.divide.divide.DivideFilter[source] Bases: BaseFilter Divides a stack of images by a value. That value can be the pixel size, and can be specified in either microns or cms, to obtain attenuation values. Intended to be used on: Reconstructed slices When: To calculate attenuation values by dividing by the pixel size in microns Caution: Check preview values before applying divide static execute_wrapper(value_widget: QDoubleSpinBox, unit_widget: QComboBox) partial[source] Should construct a partial call to _filter_func using values taken from the widgets passed to this function as kwargs. :param kwargs: widgets which contain values required for _filter_func. :return: a partial call to _filter_func using parameters taken from the input widgets. static filter_func(images: Images, value: int | float = 0, unit='micron', progress=None) Images[source] Executes the filter algorithm on a given set of image data with the given parameters. Parameters: • data – the image data to apply the filter to • kwargs – any additional arguments which the specific filter uses Returns: the image data after applying the filter filter_name = 'Divide' static register_gui(form: QFormLayout, on_change: Callable, view: BasePresenter) Dict[str, Any][source] Adds any required input widgets to the given form and returns references to them. The return values should be in a dict which can be unpacked as kwargs for a call to the operations execute_wrapper. Parameters: • view • form – the layout to create input widgets in • on_change – the filter view action to be bound to all created inputs Returns: the widgets bound as kwargs which are needed to call execute_wrapper static validate_execute_kwargs(kwargs: Dict[str, Any]) bool[source]
__label__pos
0.741035
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free. table estate_common -> common data for estate as title name etc. estate could differ in kind for example kind 1 - flat kind 2 - house etc. id | kind | title | name 596 | 1 | title 596 | name 596 597 | 1 | title 597 | some 597 598 | 1 | title 598 | some 598 599 | 1 | title 599 | some 599 600 | 1 | title 600 | some 600 601 | 5 | title 607 | some 601 table estate_kind_1 -> specific data for differnet kind each estate_kind_# has differnet structure columns etc. id | estate_common_id | floor | flat | shell 1 | 596 | 250 | 9b | pvc 2 | 597 | 156 | 10c | abc 3 | 598 | 126 | 12a | csd 4 | 599 | 226 | 2a | add 5 | 600 | 198 | 15o | fdd id from estate_common is equal estate_common_id from estate_kind_# wherer # is number of kind from table estate_common before preparing query i know that i must combine data from table estate_common and estate_kind_1 for simple detail of estate with data from both tables it´s easy SELECT `common`.*, `kind`.* FROM `estate_common` AS `common` INNER JOIN `estate_kind_1` AS `kind` ON common.id = kind.estate_common_id WHERE (common.id = '597') but now i start doing some xml export and need to select data from both table means estate_common and estate_kind_1 upon selection of estate_common id´s so query like this SELECT `common`.*, `kind`.* FROM `estate_common` AS `common`, `estate_kind_1` AS `kind` WHERE (common.id IN ('596,597')) but it gives me strange result id | kind | title | name | id | estate_common_id | floor | flat | shell 596 | 1 | title 596 | name 596 | 1 | 596 | 250 | 9b | pvc 596 | 1 | title 596 | name 596 | 2 | 597 | 156 | 10c | abc data from table estate_kind_1 means with id 1 a 2 on right side are ok but left from estate_common are for both lines same should be id | kind | title | name | id | estate_common_id | floor | flat | shell 596 | 1 | title 596 | name 596 | 1 | 596 | 250 | 9b | pvc 597 | 1 | title 597 | name 597 | 2 | 597 | 156 | 10c | abc i tried group by distinct etc. but probably in wrong way will be glad for any help thanks share|improve this question 3 Answers 3 Your latter query has no explicit JOIN so an INNER JOIN is being done. As there's also no ON clause, what's happening is a full cross product with a restriction on one table. The result you should be getting is that for every row of kind you will have two results - one for 596 of common and one for 597. I assume you have cropped the result at 2 rows. The query you want is: SELECT `common`.*, `kind`.* FROM `estate_common` AS `common`, `estate_kind_1` AS `kind` ON common.id = kind.estate_common_id WHERE (common.id IN ('596,597')); share|improve this answer I must be missing something about your question. Is this what you want? SELECT `common`.*, `kind`.* FROM `estate_common` AS `common` INNER JOIN `estate_kind_1` AS `kind` ON common.id = kind.estate_common_id WHERE common.id IN ('596,597') share|improve this answer      SELECT common.*, kind.*FROM estate_common AS common INNER JOIN estate_kind_5 AS kind ON common.id = kind.estate_common_id WHERE (common.id IN ('596,597')) as could be seen in last blokc of my question gives just one row - with common.id 596 that was mi first idea. i neadd to select 596 and 597 data from both table –  Horák Jan Jun 20 '09 at 21:25      in query shoud be estate_kind_1 instead estate_kind_5 as i posted few moments ago i just have different tables on my localhost –  Horák Jan Jun 20 '09 at 21:27 solution is realy simple SELECT common.*, kind.* FROM estate_common common, estate_kind_1 kind WHERE common.id = kind.estate_common_id AND (common.id IN (596,597)) 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.983773
Why is there an allocation? module mbas001 elxs = fill(Matrix{Float64}(undef, 3, 3), 7) for _i in eachindex(elxs) elxs[_i] = rand(3, 3) end ex = fill(zero(Float64), 3, 3) copy2ex!(ex, elxs, j, k) = let elxsc = elxs[c] for _i in axes(ex, 2) ex[1, _i] = elxsc[j, _i]; ex[2, _i] = elxsc[k, _i]; end ex end c = 4 @time let ex[1,:] = elxs[c][1,:]; ex[2,:] = elxs[c][2,:]; end @time copy2ex!(ex, elxs, 1, 2) @time copy2ex!(ex, elxs, 1, 2) @time copy2ex!(ex, elxs, 1, 2) end produces julia> include("C:\\Users\\pkonl\\Documents\\00WIP\\HelmBEM.jl\\test\\littletest.jl") WARNING: replacing module mbas001. 0.000023 seconds (6 allocations: 224 bytes) 0.018632 seconds (9.56 k allocations: 517.691 KiB, 99.73% compilation time) 0.000017 seconds (6 allocations: 96 bytes) 0.000016 seconds (6 allocations: 96 bytes) Main.mbas001 What puzzles me is why the function copy2ex! allocates memory. It happens in the loop for _i in axes(ex, 2) ex[1, _i] = elxsc[j, _i]; ex[2, _i] = elxsc[k, _i]; end Which, in my understanding, should be simply assignment of one matrix location the value of another matrix location. In other words, scalars. c is a non-const global variable. 3 Likes Wow. I missed that! Thanks. Now if I could understand why the memory allocation happens here: ex[1,:] = elxs[c][1,:]; ex[2,:] = elxs[c][2,:]; There are still 6 ALLOCATIONS: WARNING: replacing module mbas001. 0.000025 seconds (6 allocations: 224 bytes) 0.022149 seconds (6.53 k allocations: 337.683 KiB, 99.85% compilation time) 0.000015 seconds 0.000003 seconds Main.mbas001 The code looks like this now: module mbas001 elxs = fill(Matrix{Float64}(undef, 3, 3), 7) for _i in eachindex(elxs) elxs[_i] = rand(3, 3) end ex = fill(zero(Float64), 3, 3) copy2ex!(ex, elxs, c, j, k) = let elxsc = elxs[c] for _i in axes(ex, 2) ex[1, _i] = elxsc[j, _i]; ex[2, _i] = elxsc[k, _i]; end ex end @time let c = 4 ex[1,:] = elxs[c][1,:]; ex[2,:] = elxs[c][2,:]; end c = 4 @time copy2ex!(ex, elxs, c, 1, 2) @time copy2ex!(ex, elxs, c, 1, 2) @time copy2ex!(ex, elxs, c, 1, 2) end const const @time @views let Now everything is a local variable. Still, there are allocations. module mbas001 let elxs = fill(Matrix{Float64}(undef, 3, 3), 7) for _i in eachindex(elxs) elxs[_i] = rand(3, 3) end ex = fill(zero(Float64), 3, 3) copy2ex!(ex, elxs, c, j, k) = let elxsc = elxs[c] for _i in axes(ex, 2) ex[1, _i] = elxsc[j, _i]; ex[2, _i] = elxsc[k, _i]; end ex end @time @views let c = 4 ex[1,:] = elxs[c][1,:]; ex[2,:] = elxs[c][2,:]; end c = 4 @time copy2ex!(ex, elxs, c, 1, 2) @time copy2ex!(ex, elxs, c, 1, 2) @time copy2ex!(ex, elxs, c, 1, 2) end end gives WARNING: replacing module mbas001. 0.000013 seconds (15 allocations: 512 bytes) 0.020667 seconds (6.54 k allocations: 338.026 KiB, 99.88% compilation time) 0.000005 seconds (9 allocations: 352 bytes) 0.000003 seconds (9 allocations: 352 bytes) Main.mbas001 Edit: Note that I forgot to remove the views. Everything is local now. Doesn’t @time itself allocate? I always use @btime and variable interpolation for reliable allocation estimates. It actually worked (sort of) in https://discourse.julialang.org/t/why-is-there-an-allocation/85405/4: there were zero allocations with the function. @btime seems to have improved over time, but it might still be an idea to use BenchmarkTools to be more certain. please implement all the changes I proposed: julia> module mbas001 const elxs = fill(Matrix{Float64}(undef, 3, 3), 7) for _i in eachindex(elxs) elxs[_i] = rand(3, 3) end const ex = fill(zero(Float64), 3, 3) copy2ex!(ex, elxs, c, j, k) = let elxsc = elxs[c] for _i in axes(ex, 2) ex[1, _i] = elxsc[j, _i]; ex[2, _i] = elxsc[k, _i]; end ex end @time @views let c = 4 ex[1,:] = elxs[c][1,:]; ex[2,:] = elxs[c][2,:]; end c = 4 @time copy2ex!(ex, elxs, c, 1, 2) @time copy2ex!(ex, elxs, c, 1, 2) @time copy2ex!(ex, elxs, c, 1, 2) end 0.000001 seconds 0.012696 seconds (7.42 k allocations: 388.971 KiB, 99.93% compilation time) 0.000003 seconds 0.000002 seconds Main.mbas001 Thank you, I appreciate your suggestion, but really I want to have only local variables. Testing in the global scope was obviously a mistake. It is possible that @time allocates when it is used in a local scope. Tracking allocations with everything in local scope: - module mbas001 - let - elxs = fill(Matrix{Float64}(undef, 3, 3), 7) - for _i in eachindex(elxs) - elxs[_i] = rand(3, 3) - end - ex = fill(zero(Float64), 3, 3) - copy2ex!(ex, elxs, c, j, k) = let 0 elxsc = elxs[c] 0 for _i in axes(ex, 2) 0 ex[1, _i] = elxsc[j, _i]; 0 ex[2, _i] = elxsc[k, _i]; 0 end 0 ex - end - let - c = 4 - ex[1,:] = elxs[c][1,:]; ex[2,:] = elxs[c][2,:]; - end - c = 4 - copy2ex!(ex, elxs, c, 1, 2) - copy2ex!(ex, elxs, c, 1, 2) - copy2ex!(ex, elxs, c, 1, 2) - end - end
__label__pos
0.82799
There are 5 cars to be displayed in 5 parking spaces, with all the cars facing the same direction. Of the 5 cars, 3 are red, 1 is blue, and 1 is yellow. If the cars are identical except for color, how many different display arrangements of the 5 cars are possible? 20 25 40 60 125 考题讲解 还没有题目讲解(毕出老师会陆续发布对官方考题的解读,请保持关注)。 登录注册 后可以参加讨论 OG2018Q-PS
__label__pos
0.999733
Skip to content HTTPS clone URL Subversion checkout URL You can clone with or . Download ZIP Tag: release_stable… Fetching contributors… Cannot retrieve contributors at this time 517 lines (455 sloc) 16.148 kB <?php /** * Dokuwiki installation assistance * * @author Chris Smith <[email protected]> */ if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/'); if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/'); if(!defined('DOKU_LOCAL')) define('DOKU_LOCAL',DOKU_INC.'conf/'); // check for error reporting override or set error reporting to sane values if (!defined('DOKU_E_LEVEL')) { error_reporting(E_ALL ^ E_NOTICE); } else { error_reporting(DOKU_E_LEVEL); } // kill magic quotes if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) { if (!empty($_GET)) remove_magic_quotes($_GET); if (!empty($_POST)) remove_magic_quotes($_POST); if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE); if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST); @ini_set('magic_quotes_gpc', 0); define('MAGIC_QUOTES_STRIPPED',1); } @set_magic_quotes_runtime(0); @ini_set('magic_quotes_sybase',0); // language strings require_once(DOKU_INC.'inc/lang/en/lang.php'); $LC = preg_replace('/[^a-z\-]+/','',$_REQUEST['l']); if(!$LC) $LC = 'en'; if($LC && $LC != 'en' ) { require_once(DOKU_INC.'inc/lang/'.$LC.'/lang.php'); } // initialise variables ... $error = array(); $dokuwiki_hash = array( '2005-09-22' => 'e33223e957b0b0a130d0520db08f8fb7', '2006-03-05' => '51295727f79ab9af309a2fd9e0b61acc', '2006-03-09' => '51295727f79ab9af309a2fd9e0b61acc', '2006-11-06' => 'b3a8af76845977c2000d85d6990dd72b', '2007-05-24' => 'd80f2740c84c4a6a791fd3c7a353536f', '2007-06-26' => 'b3ca19c7a654823144119980be73cd77', '2008-05-04' => '1e5c42eac3219d9e21927c39e3240aad', '2009-02-14' => 'ec8c04210732a14fdfce0f7f6eead865', '2009-12-25' => '993c4b2b385643efe5abf8e7010e11f4', ); // begin output header('Content-Type: text/html; charset=utf-8'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $LC?>" lang="<?php echo $LC?>" dir="<?php echo $lang['direction']?>"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $lang['i_installer']?></title> <style type="text/css"> body { width: 90%; margin: 0 auto; font: 84% Verdana, Helvetica, Arial, sans-serif; } img { border: none } br.cl { clear:both; } code { font-size: 110%; color: #800000; } fieldset { border: none } label { display: block; margin-top: 0.5em; } select.text, input.text { width: 30em; margin: 0 0.5em; } </style> <script type="text/javascript" language="javascript"> function acltoggle(){ var cb = document.getElementById('acl'); var fs = document.getElementById('acldep'); if(!cb || !fs) return; if(cb.checked){ fs.style.display = ''; }else{ fs.style.display = 'none'; } } window.onload = function(){ acltoggle(); var cb = document.getElementById('acl'); if(cb) cb.onchange = acltoggle; }; </script> </head> <body style=""> <h1 style="float:left"> <img src="lib/exe/fetch.php?media=wiki:dokuwiki-128.png&w=64" style="vertical-align: middle;" alt="" /> <?php echo $lang['i_installer']?> </h1> <div style="float:right; margin: 1em;"> <?php langsel()?> </div> <br class="cl" /> <div style="float: right; width: 34%;"> <?php if(@file_exists(DOKU_INC.'inc/lang/'.$LC.'/install.html')){ include(DOKU_INC.'inc/lang/'.$LC.'/install.html'); }else{ print "<div lang=\"en\" dir=\"ltr\">\n"; include(DOKU_INC.'inc/lang/en/install.html'); print "</div>\n"; } ?> </div> <div style="float: left; width: 58%;"> <?php if(! (check_functions() && check_permissions()) ){ echo '<p>'.$lang['i_problems'].'</p>'; print_errors(); print_retry(); }elseif(!check_configs()){ echo '<p>'.$lang['i_modified'].'</p>'; print_errors(); }elseif($_REQUEST['submit']){ if(!check_data($_REQUEST['d'])){ print_errors(); print_form($_REQUEST['d']); }elseif(!store_data($_REQUEST['d'])){ echo '<p>'.$lang['i_failure'].'</p>'; print_errors(); }else{ echo '<p>'.$lang['i_success'].'</p>'; } }else{ print_form($_REQUEST['d']); } ?> </div> <div style="clear: both"> <a href="http://dokuwiki.org/"><img src="lib/tpl/default/images/button-dw.png" alt="driven by DokuWiki" /></a> <a href="http://www.php.net"><img src="lib/tpl/default/images/button-php.gif" alt="powered by PHP" /></a> </div> </body> </html> <?php /** * Print the input form */ function print_form($d){ global $lang; global $LC; if(!is_array($d)) $d = array(); $d = array_map('htmlspecialchars',$d); if(!isset($d['acl'])) $d['acl']=1; ?> <form action="" method="post"> <input type="hidden" name="l" value="<?php echo $LC ?>" /> <fieldset> <label for="title"><?php echo $lang['i_wikiname']?> <input type="text" name="d[title]" id="title" value="<?php echo $d['title'] ?>" style="width: 20em;" /> </label> <fieldset style="margin-top: 1em;"> <label for="acl"> <input type="checkbox" name="d[acl]" id="acl" <?php echo(($d['acl'] ? 'checked="checked"' : ''));?> /> <?php echo $lang['i_enableacl']?></label> <fieldset id="acldep"> <label for="superuser"><?php echo $lang['i_superuser']?></label> <input class="text" type="text" name="d[superuser]" id="superuser" value="<?php echo $d['superuser'] ?>" /> <label for="fullname"><?php echo $lang['fullname']?></label> <input class="text" type="text" name="d[fullname]" id="fullname" value="<?php echo $d['fullname'] ?>" /> <label for="email"><?php echo $lang['email']?></label> <input class="text" type="text" name="d[email]" id="email" value="<?php echo $d['email'] ?>" /> <label for="password"><?php echo $lang['pass']?></label> <input class="text" type="password" name="d[password]" id="password" /> <label for="confirm"><?php echo $lang['passchk']?></label> <input class="text" type="password" name="d[confirm]" id="confirm" /> <label for="policy"><?php echo $lang['i_policy']?></label> <select class="text" name="d[policy]" id="policy"> <option value="0" <?php echo ($d['policy'] == 0)?'selected="selected"':'' ?>><?php echo $lang['i_pol0']?></option> <option value="1" <?php echo ($d['policy'] == 1)?'selected="selected"':'' ?>><?php echo $lang['i_pol1']?></option> <option value="2" <?php echo ($d['policy'] == 2)?'selected="selected"':'' ?>><?php echo $lang['i_pol2']?></option> </select> </fieldset> </fieldset> </fieldset> <fieldset id="process"> <input class="button" type="submit" name="submit" value="<?php echo $lang['btn_save']?>" /> </fieldset> </form> <?php } function print_retry() { global $lang; global $LC; ?> <form action="" method="get"> <fieldset> <input type="hidden" name="l" value="<?php echo $LC ?>" /> <input class="button" type="submit" value="<?php echo $lang['i_retry'];?>" /> </fieldset> </form> <?php } /** * Check validity of data * * @author Andreas Gohr */ function check_data(&$d){ global $lang; global $error; //autolowercase the username $d['superuser'] = strtolower($d['superuser']); $ok = true; // check input if(empty($d['title'])){ $error[] = sprintf($lang['i_badval'],$lang['i_wikiname']); $ok = false; } if($d['acl']){ if(!preg_match('/^[a-z1-9_]+$/',$d['superuser'])){ $error[] = sprintf($lang['i_badval'],$lang['i_superuser']); $ok = false; } if(empty($d['password'])){ $error[] = sprintf($lang['i_badval'],$lang['pass']); $ok = false; } if($d['confirm'] != $d['password']){ $error[] = sprintf($lang['i_badval'],$lang['passchk']); $ok = false; } if(empty($d['fullname']) || strstr($d['fullname'],':')){ $error[] = sprintf($lang['i_badval'],$lang['fullname']); $ok = false; } if(empty($d['email']) || strstr($d['email'],':') || !strstr($d['email'],'@')){ $error[] = sprintf($lang['i_badval'],$lang['email']); $ok = false; } } return $ok; } /** * Writes the data to the config files * * @author Chris Smith <[email protected]> */ function store_data($d){ global $LC; $ok = true; $d['policy'] = (int) $d['policy']; // create local.php $now = date('r'); $output = <<<EOT <?php /** * Dokuwiki's Main Configuration File - Local Settings * Auto-generated by install script * Date: $now */ EOT; $output .= '$conf[\'title\'] = \''.addslashes($d['title'])."';\n"; $output .= '$conf[\'lang\'] = \''.addslashes($LC)."';\n"; if($d['acl']){ $output .= '$conf[\'useacl\'] = 1'.";\n"; $output .= "\$conf['superuser'] = '@admin';\n"; } $ok = $ok && fileWrite(DOKU_LOCAL.'local.php',$output); if ($d['acl']) { // create users.auth.php // --- user:MD5password:Real Name:email:groups,comma,seperated $output = join(":",array($d['superuser'], md5($d['password']), $d['fullname'], $d['email'], 'admin,user')); $output = @file_get_contents(DOKU_CONF.'users.auth.php.dist')."\n$output\n"; $ok = $ok && fileWrite(DOKU_LOCAL.'users.auth.php', $output); // create acl.auth.php $output = <<<EOT # acl.auth.php # <?php exit()?> # Don't modify the lines above # # Access Control Lists # # Auto-generated by install script # Date: $now EOT; if($d['policy'] == 2){ $output .= "* @ALL 0\n"; $output .= "* @user 8\n"; }elseif($d['policy'] == 1){ $output .= "* @ALL 1\n"; $output .= "* @user 8\n"; }else{ $output .= "* @ALL 8\n"; } $ok = $ok && fileWrite(DOKU_LOCAL.'acl.auth.php', $output); } return $ok; } /** * Write the given content to a file * * @author Chris Smith <[email protected]> */ function fileWrite($filename, $data) { global $error; global $lang; if (($fp = @fopen($filename, 'wb')) === false) { $filename = str_replace($_SERVER['DOCUMENT_ROOT'],'{DOCUMENT_ROOT}/', $filename); $error[] = sprintf($lang['i_writeerr'],$filename); return false; } if (!empty($data)) { fwrite($fp, $data); } fclose($fp); return true; } /** * check installation dependent local config files and tests for a known * unmodified main config file * * @author Chris Smith <[email protected]> */ function check_configs(){ global $error; global $lang; global $dokuwiki_hash; $ok = true; $config_files = array( 'local' => DOKU_LOCAL.'local.php', 'users' => DOKU_LOCAL.'users.auth.php', 'auth' => DOKU_LOCAL.'acl.auth.php' ); // main dokuwiki config file (conf/dokuwiki.php) must not have been modified $installation_hash = md5(preg_replace("/(\015\012)|(\015)/","\012", @file_get_contents(DOKU_CONF.'dokuwiki.php'))); if (!in_array($installation_hash, $dokuwiki_hash)) { $error[] = sprintf($lang['i_badhash'],$installation_hash); $ok = false; } // configs shouldn't exist foreach ($config_files as $file) { if (@file_exists($file)) { $file = str_replace($_SERVER['DOCUMENT_ROOT'],'{DOCUMENT_ROOT}/', $file); $error[] = sprintf($lang['i_confexists'],$file); $ok = false; } } return $ok; } /** * Check other installation dir/file permission requirements * * @author Chris Smith <[email protected]> */ function check_permissions(){ global $error; global $lang; $dirs = array( 'conf' => DOKU_LOCAL, 'data' => DOKU_INC.'data', 'pages' => DOKU_INC.'data/pages', 'attic' => DOKU_INC.'data/attic', 'media' => DOKU_INC.'data/media', 'meta' => DOKU_INC.'data/meta', 'cache' => DOKU_INC.'data/cache', 'locks' => DOKU_INC.'data/locks', 'index' => DOKU_INC.'data/index', 'tmp' => DOKU_INC.'data/tmp' ); $ok = true; foreach($dirs as $dir){ if(!@file_exists("$dir/.") || !@is_writable($dir)){ $dir = str_replace($_SERVER['DOCUMENT_ROOT'],'{DOCUMENT_ROOT}', $dir); $error[] = sprintf($lang['i_permfail'],$dir); $ok = false; } } return $ok; } /** * Check the availability of functions used in DokuWiki and the PHP version * * @author Andreas Gohr <[email protected]> */ function check_functions(){ global $error; global $lang; $ok = true; if(version_compare(phpversion(),'5.1.2','<')){ $error[] = sprintf($lang['i_phpver'],phpversion(),'5.1.2'); $ok = false; } $funcs = explode(' ','addslashes basename call_user_func chmod copy fgets '. 'file file_exists fseek flush filesize ftell fopen '. 'glob header ignore_user_abort ini_get mail mkdir '. 'ob_start opendir parse_ini_file readfile realpath '. 'rename rmdir serialize session_start unlink usleep '. 'preg_replace file_get_contents htmlspecialchars_decode'); if (!function_exists('mb_substr')) { $funcs[] = 'utf8_encode'; $funcs[] = 'utf8_decode'; } foreach($funcs as $func){ if(!function_exists($func)){ $error[] = sprintf($lang['i_funcna'],$func); $ok = false; } } return $ok; } /** * Print language selection * * @author Andreas Gohr <[email protected]> */ function langsel(){ global $lang; global $LC; $dir = DOKU_INC.'inc/lang'; $dh = opendir($dir); if(!$dh) return; $langs = array(); while (($file = readdir($dh)) !== false) { if(preg_match('/^[\._]/',$file)) continue; if(is_dir($dir.'/'.$file) && @file_exists($dir.'/'.$file.'/lang.php')){ $langs[] = $file; } } closedir($dh); sort($langs); echo '<form action="">'; echo $lang['i_chooselang']; echo ': <select name="l" onchange="submit()">'; foreach($langs as $l){ $sel = ($l == $LC) ? 'selected="selected"' : ''; echo '<option value="'.$l.'" '.$sel.'>'.$l.'</option>'; } echo '</select> '; echo '<input type="submit" value="'.$lang['btn_update'].'" />'; echo '</form>'; } /** * Print global error array * * @author Andreas Gohr <[email protected]> */ function print_errors(){ global $error; echo '<ul>'; foreach ($error as $err){ echo "<li>$err</li>"; } echo '</ul>'; } /** * remove magic quotes recursivly * * @author Andreas Gohr <[email protected]> */ function remove_magic_quotes(&$array) { foreach (array_keys($array) as $key) { if (is_array($array[$key])) { remove_magic_quotes($array[$key]); }else { $array[$key] = stripslashes($array[$key]); } } } Jump to Line Something went wrong with that request. Please try again.
__label__pos
0.865106
summaryrefslogtreecommitdiffstats path: root/rbutil/rbutilqt/base/autodetection.cpp blob: 30651077f2a7d091de86e36dc46e75d30bc18593 (plain) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 /*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * * Copyright (C) 2007 by Dominik Wenger * $Id$ * * All files in this archive are subject to the GNU General Public License. * See the file COPYING in the source tree root for full license agreement. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include <QtCore> #include "autodetection.h" #include "rbsettings.h" #include "../ipodpatcher/ipodpatcher.h" #include "../sansapatcher/sansapatcher.h" #if defined(Q_OS_LINUX) || defined(Q_OS_MACX) #include <stdio.h> #include <usb.h> #endif #if defined(Q_OS_LINUX) #include <mntent.h> #endif #if defined(Q_OS_MACX) #include <sys/param.h> #include <sys/ucred.h> #include <sys/mount.h> #endif #if defined(Q_OS_WIN32) #if defined(UNICODE) #define _UNICODE #endif #include <stdio.h> #include <tchar.h> #include <windows.h> #include <setupapi.h> #include <winioctl.h> #endif #if defined(Q_OS_OPENBSD) #include <sys/param.h> #include <sys/mount.h> #endif #include "detect.h" #include "utils.h" Autodetection::Autodetection(QObject* parent): QObject(parent) { } bool Autodetection::detect() { m_device = ""; m_mountpoint = ""; m_errdev = ""; detectUsb(); // Try detection via rockbox.info / rbutil.log QStringList mounts = mountpoints(); for(int i=0; i< mounts.size();i++) { // do the file checking QDir dir(mounts.at(i)); qDebug() << "paths to check for player specific files:" << mounts; if(dir.exists()) { // check logfile first. if(QFile(mounts.at(i) + "/.rockbox/rbutil.log").exists()) { QSettings log(mounts.at(i) + "/.rockbox/rbutil.log", QSettings::IniFormat, this); if(!log.value("platform").toString().isEmpty()) { if(m_device.isEmpty()) m_device = log.value("platform").toString(); m_mountpoint = mounts.at(i); qDebug() << "rbutil.log detected:" << m_device << m_mountpoint; return true; } } // check rockbox-info.txt afterwards. RockboxInfo info(mounts.at(i)); if(info.open()) { if(m_device.isEmpty()) { m_device = info.target(); } m_mountpoint = mounts.at(i); qDebug() << "rockbox-info.txt detected:" << m_device << m_mountpoint; return true; } // check for some specific files in root folder QDir root(mounts.at(i)); QStringList rootentries = root.entryList(QDir::Files); if(rootentries.contains("archos.mod", Qt::CaseInsensitive)) { // archos.mod in root folder -> Archos Player m_device = "player"; m_mountpoint = mounts.at(i); return true; } if(rootentries.contains("ONDIOST.BIN", Qt::CaseInsensitive)) { // ONDIOST.BIN in root -> Ondio FM m_device = "ondiofm"; m_mountpoint = mounts.at(i); return true; } if(rootentries.contains("ONDIOSP.BIN", Qt::CaseInsensitive)) { // ONDIOSP.BIN in root -> Ondio SP m_device = "ondiosp"; m_mountpoint = mounts.at(i); return true; } if(rootentries.contains("ajbrec.ajz", Qt::CaseInsensitive)) { qDebug() << "ajbrec.ajz found. Trying detectAjbrec()"; if(detectAjbrec(mounts.at(i))) { m_mountpoint = mounts.at(i); qDebug() << m_device; return true; } } // detection based on player specific folders QStringList rootfolders = root.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System); if(rootfolders.contains("GBSYSTEM", Qt::CaseInsensitive)) { // GBSYSTEM folder -> Gigabeat m_device = "gigabeatf"; m_mountpoint = mounts.at(i); return true; } #if defined(Q_OS_WIN32) // on windows, try to detect the drive letter of an Ipod if(rootfolders.contains("iPod_Control", Qt::CaseInsensitive)) { // iPod_Control folder -> Ipod found // detecting of the Ipod type is done below using ipodpatcher m_mountpoint = mounts.at(i); } #endif } } int n; // try ipodpatcher // initialize sector buffer. Needed. ipod_sectorbuf = NULL; ipod_alloc_buffer(&ipod_sectorbuf, BUFFER_SIZE); struct ipod_t ipod; n = ipod_scan(&ipod); if(n == 1) { qDebug() << "Ipod found:" << ipod.modelstr << "at" << ipod.diskname; m_device = ipod.targetname; m_mountpoint = resolveMountPoint(ipod.diskname); return true; } else { qDebug() << "ipodpatcher: no Ipod found." << n; } free(ipod_sectorbuf); ipod_sectorbuf = NULL; // try sansapatcher // initialize sector buffer. Needed. sansa_sectorbuf = NULL; sansa_alloc_buffer(&sansa_sectorbuf, BUFFER_SIZE); struct sansa_t sansa; n = sansa_scan(&sansa); if(n == 1) { qDebug() << "Sansa found:" << sansa.targetname << "at" << sansa.diskname; m_device = QString("sansa%1").arg(sansa.targetname); m_mountpoint = resolveMountPoint(sansa.diskname); return true; } else { qDebug() << "sansapatcher: no Sansa found." << n; } free(sansa_sectorbuf); sansa_sectorbuf = NULL; if(m_mountpoint.isEmpty() && m_device.isEmpty() && m_errdev.isEmpty() && m_incompat.isEmpty()) return false; return true; } QStringList Autodetection::mountpoints() { QStringList tempList; #if defined(Q_OS_WIN32) QFileInfoList list = QDir::drives(); for(int i=0; i<list.size();i++) { tempList << list.at(i).absolutePath(); } #elif defined(Q_OS_MACX) || defined(Q_OS_OPENBSD) int num; struct statfs *mntinf; num = getmntinfo(&mntinf, MNT_WAIT); while(num--) { tempList << QString(mntinf->f_mntonname); mntinf++; } #elif defined(Q_OS_LINUX) FILE *mn = setmntent("/etc/mtab", "r"); if(!mn) return QStringList(""); struct mntent *ent; while((ent = getmntent(mn))) tempList << QString(ent->mnt_dir); endmntent(mn); #else #error Unknown Plattform #endif return tempList; } /** resolve device name to mount point / drive letter * @param device device name / disk number * @return mount point / drive letter */ QString Autodetection::resolveMountPoint(QString device) { qDebug() << "Autodetection::resolveMountPoint(QString)" << device; #if defined(Q_OS_LINUX) FILE *mn = setmntent("/etc/mtab", "r"); if(!mn) return QString(""); struct mntent *ent; while((ent = getmntent(mn))) { if(QString(ent->mnt_fsname).startsWith(device) && QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive)) { endmntent(mn); return QString(ent->mnt_dir); } } endmntent(mn); #endif #if defined(Q_OS_MACX) int num; struct statfs *mntinf; num = getmntinfo(&mntinf, MNT_WAIT); while(num--) { if(QString(mntinf->f_mntfromname).startsWith(device) && QString(mntinf->f_fstypename).contains("vfat", Qt::CaseInsensitive)) return QString(mntinf->f_mntonname); mntinf++; } #endif #if defined(Q_OS_OPENBSD) int num; struct statfs *mntinf; num = getmntinfo(&mntinf, MNT_WAIT); while(num--) { if(QString(mntinf->f_mntfromname).startsWith(device) && QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive)) return QString(mntinf->f_mntonname); mntinf++; } #endif #if defined(Q_OS_WIN32) QString result; unsigned int driveno = device.replace(QRegExp("^.*([0-9]+)"), "\\1").toInt(); int letter; for(letter = 'A'; letter <= 'Z'; letter++) { if(resolveDevicename(QString(letter)).toUInt() == driveno) { result = letter; break; } } qDebug() << "Autodetection::resolveMountPoint(QString)" << "->" << result; if(!result.isEmpty()) return result + ":/"; #endif return QString(""); } /** Resolve mountpoint to devicename / disk number * @param path mountpoint path / drive letter * @return devicename / disk number */ QString Autodetection::resolveDevicename(QString path) { qDebug() << __func__; #if defined(Q_OS_LINUX) FILE *mn = setmntent("/etc/mtab", "r"); if(!mn) return QString(""); struct mntent *ent; while((ent = getmntent(mn))) { if(QString(ent->mnt_dir).startsWith(path) && QString(ent->mnt_type).contains("vfat", Qt::CaseInsensitive)) { endmntent(mn); return QString(ent->mnt_fsname); } } endmntent(mn); #endif #if defined(Q_OS_MACX) int num; struct statfs *mntinf; num = getmntinfo(&mntinf, MNT_WAIT); while(num--) { if(QString(mntinf->f_mntonname).startsWith(path) && QString(mntinf->f_fstypename).contains("vfat", Qt::CaseInsensitive)) return QString(mntinf->f_mntfromname); mntinf++; } #endif #if defined(Q_OS_OPENBSD) int num; struct statfs *mntinf; num = getmntinfo(&mntinf, MNT_WAIT); while(num--) { if(QString(mntinf->f_mntonname).startsWith(device) && QString(mntinf->f_fstypename).contains("msdos", Qt::CaseInsensitive)) return QString(mntinf->f_mntfromname); mntinf++; } #endif #if defined(Q_OS_WIN32) DWORD written; HANDLE h; TCHAR uncpath[MAX_PATH]; UCHAR buffer[0x400]; PVOLUME_DISK_EXTENTS extents = (PVOLUME_DISK_EXTENTS)buffer; _stprintf(uncpath, _TEXT("\\\\.\\%c:"), path.toAscii().at(0)); h = CreateFile(uncpath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if(h == INVALID_HANDLE_VALUE) { //qDebug() << "error getting extents for" << uncpath; return ""; } // get the extents if(DeviceIoControl(h, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, extents, sizeof(buffer), &written, NULL)) { if(extents->NumberOfDiskExtents > 1) { qDebug() << "volume spans multiple disks!"; return ""; } //qDebug() << "Disk:" << extents->Extents[0].DiskNumber; return QString("%1").arg(extents->Extents[0].DiskNumber); } #endif return QString(""); } /** @brief detect devices based on usb pid / vid. * @return true upon success, false otherwise. */ bool Autodetection::detectUsb() { // usbids holds the mapping in the form // ((VID<<16)|(PID)), targetname // the ini file needs to hold the IDs as hex values. QMap<int, QString> usbids = RbSettings::usbIdMap(RbSettings::MapDevice); QMap<int, QString> usberror = RbSettings::usbIdMap(RbSettings::MapError); QMap<int, QString> usbincompat = RbSettings::usbIdMap(RbSettings::MapIncompatible); // usb pid detection QList<uint32_t> attached; attached = Detect::listUsbIds(); int i = attached.size(); while(i--) { if(usbids.contains(attached.at(i))) { m_device = usbids.value(attached.at(i)); qDebug() << "[USB] detected supported player" << m_device; return true; } if(usberror.contains(attached.at(i))) { m_errdev = usberror.value(attached.at(i)); qDebug() << "[USB] detected problem with player" << m_errdev; return true; } if(usbincompat.contains(attached.at(i))) { m_incompat = usbincompat.value(attached.at(i)); qDebug() << "[USB] detected incompatible player" << m_incompat; return true; } } return false; } bool Autodetection::detectAjbrec(QString root) { QFile f(root + "/ajbrec.ajz"); char header[24]; f.open(QIODevice::ReadOnly); if(!f.read(header, 24)) return false; // check the header of the file. // recorder v1 had a 6 bytes sized header // recorder v2, FM, Ondio SP and FM have a 24 bytes header. // recorder v1 has the binary length in the first 4 bytes, so check // for them first. int len = (header[0]<<24) | (header[1]<<16) | (header[2]<<8) | header[3]; qDebug() << "possible bin length:" << len; qDebug() << "file len:" << f.size(); if((f.size() - 6) == len) m_device = "recorder"; // size didn't match, now we need to assume we have a headerlength of 24. switch(header[11]) { case 2: m_device = "recorderv2"; break; case 4: m_device = "fmrecorder"; break; case 8: m_device = "ondiofm"; break; case 16: m_device = "ondiosp"; break; default: break; } f.close(); if(m_device.isEmpty()) return false; return true; }
__label__pos
0.948089
An algorithm is a sequence of well-defined steps that defines an abstract solution to a problem. Use this tag when your issue is related to algorithm design. An algorithm is a set of ordered instructions based on a formal language with the following conditions: • Finite. The number of instructions must be finite. • Executable. All instructions must be executable in some language-dependent way, in a finite amount of time. An algorithm does not have to be deterministic - there are many random-based algorithms, e.g. QuickSort with selecting the pivot element randomly. An algorithm can be expressed in many ways: • As a sequence of instructions • As a block-scheme • As a code in an existing or new programming language • As a piece of text in a human language • As a realization in a formal model of computation such as a Turing machine • Or in other, similar ways An algorithm can solve a class of problems. For example, both "sum 1 and 3" and "sum 4 and 5" are problems in the same class: "sum two integer numbers." Furthermore, a given class of problems can generally be solved by a variety of algorithms. One important aspect of algorithm design is performance. For large datasets a good algorithm may outperform a poor algorithm by several orders of magnitude. Algorithm performance is often rated with Big O or Θ notation, but one should be cautious with asymptotic notation, since big constants may be involved. A key algorithm classification is known as Algorithm Complexity. Another important step of algorithm design is proof of correctness. Algorithm should actually provide correct result for any instance of the problem. We should always take care all the conditions where proposed algorithm might fail. This could be done using several techniques, For example Model Checking, Assertion, Loop Invariant. Related Links Additional resources on algorithms include: history | excerpt history
__label__pos
0.996543
Bug 47130 - TODO list doesn't remember which sub-todo trees were collapsed Summary: TODO list doesn't remember which sub-todo trees were collapsed Status: CLOSED WONTFIX Alias: None Product: Red Hat Linux Classification: Retired Component: kdepim    (Show other bugs) Version: 7.1 Hardware: All OS: Linux medium medium Target Milestone: --- Assignee: Bernhard Rosenkraenzer QA Contact: URL: Whiteboard: Keywords: Depends On: Blocks: TreeView+ depends on / blocked   Reported: 2001-07-03 12:51 UTC by Mike A. Harris Modified: 2008-05-01 15:38 UTC (History) 0 users Fixed In Version: Doc Type: Bug Fix Doc Text: Story Points: --- Clone Of: Environment: Last Closed: 2001-07-13 12:56:53 UTC Type: --- Regression: --- Mount Type: --- Documentation: --- CRM: Verified Versions: Category: --- oVirt Team: --- RHEL 7.3 requirements from Atomic Host: Cloudforms Team: --- Attachments (Terms of Use) Description Mike A. Harris 2001-07-03 12:51:22 UTC Description of Problem: If you have a TODO with sub-TODO items, and collapse the TODO so the sub TODO items are not shown, then change views to the 31 day fullscreen calendar and back, your full TODO list is now fully expanded. How Reproducible: 100% Steps to Reproduce: 1. Create a todo list with a handful of items 2. Make one of the middle items have 3 sub todo items. 3. Make another one have multiple subtodo items 4. Collapse all items with subtodo's so it shows the + signs on each 5. Change korganizer views to the 31 day fullscreen calendar 6. Change view back to TODO + 1 day view or week view. Actual Results: All subtodo lists are now expanded trees and all sub items are showing. This makes the ability to collapse a tree member pretty useless especially if you have multiple items with many sub todo's because your collapses are lost as soon as you change views. Expected Results: The app remembers this stuff, including when you close the app so that restarting it gets you the exact tree view you had with expanded and collapsed todo items. Additional Information: Wear brightly colored clothing when riding a bicycle at night. Comment 1 Mike A. Harris 2002-06-22 05:55:10 UTC Korganizer sucks. ;o) Note You need to log in before you can comment on or make changes to this bug.
__label__pos
0.533222
Seagate going for 18TB HDDS next year Discussion in 'Frontpage news' started by Hilbert Hagedoorn, Mar 16, 2017. 1. Hilbert Hagedoorn Hilbert Hagedoorn Don Vito Corleone Staff Member Messages: 44,670 Likes Received: 11,345 GPU: AMD | NVIDIA Seagate will be expanding their HDD line with an 18 Terabyte model, and would be doing so next year. To reach this incredible storage volume they would make a move towards SMR, TDMR and HAMR technol... Seagate going for 18TB HDDS next year   2. thatguy91 thatguy91 Ancient Guru Messages: 6,643 Likes Received: 99 GPU: XFX RX 480 RS 4 GB Hard drive prices and tech haven't changed much in the last couple of years or so, hopefully this will bring prices down and capacity up.   3. Silva Silva Ancient Guru Messages: 1,870 Likes Received: 1,010 GPU: Asus Dual RX580 O4G All of that data on a single HDD makes me nervous about failure. It's great that technology is finally moving forward (again) because I'm tired of waiting for prices to come down. My 2Tb WD Green is old as **** and I need to back up the data.   4. SHS SHS Master Guru Messages: 495 Likes Received: 44 GPU: Sapphire Vega 56 That why it a good idea to buy two drives backup the first drive on to 2nd drive   5. GhostXL GhostXL Ancient Guru Messages: 6,084 Likes Received: 54 GPU: Merc 319 6800 XT You should be alright with the capacity part. They really worked out the issues of holding high capacities. I think more it's current system compatibility and if the drive is just faulty to begin with. Been running a Toshiba 5TB 7200 RPM, 128MB Cache for a good while now. Flawless drive. So I think it's going to be a luck of the draw like most HDD's these days. You get a good one..or you don't despite the capacity. I've read about people getting faulty drives, the same as my 5TB. So you know, you see that everywhere. Good ones bad ones. I see more good than bad thankfully. Long story short, you don't need to worry about the capacity being the problem maker. This is true. He gets a new one, he can even keep his trusty 2TB to backup the backups.   Last edited: Mar 16, 2017 6. RedSquirrel RedSquirrel Active Member Messages: 81 Likes Received: 6 GPU: Intel Iris 6100 I still remember buying a '40GB' deathstar HD and seeing only 37GB available, I imagine it'd be pretty harsh with an 18TB drive o_O Amazes me how much they keep cramming into these drives via magneto-mechanical means, in rust we trust for bulk storage. Can't see myself buying one though, cost aside, infact I first bought a 1TB drive back in 2008 IIRC, and 9 years later I'm still using 1 or 2TB drives for things not needed on the ssd :/   7. PrMinisterGR PrMinisterGR Ancient Guru Messages: 8,073 Likes Received: 907 GPU: Inno3D RTX 3090 Well, it should be something like 17.57TB in real TB (meaning divided by 1024 and not 1000 as they usually advertise). Then you subtract 12.5% from that for the NTFS Master File Table. So that should show something like 15.38TB on "My Computer".   8. Neo Cyrus Neo Cyrus Ancient Guru Messages: 10,152 Likes Received: 853 GPU: Asus TUF 3080 OC 18,000,000,000,000 / 1024 ^ 4 = ~16.37 The reduced size has nothing to do with the file table, you actually get that much less. 18 "terabytes" in SI units is 16.37 real/binary terabytes. And I refuse to call it a tebibyte or whatever the **** unit was agreed upon to represent binary. Screw that, that means the companies win, no, not happening. Edit: Check for yourselves with any drive, check how many bytes it has and divide by 1024 ^ 3 for gigabytes or 1024 ^ 4 for terabytes. For example, my "4TB" Seagate drive has a (relative) bit over 4 trillion bytes: 4,000,785,100,800 / 1024 ^ 4 = just under 3.64 TB, which is what Windows displays.   Last edited: Mar 17, 2017 Share This Page
__label__pos
0.533121
使用Android 內建的方法來使用query 取得SD卡內完整的多媒體 / 影片 / 音樂 / 圖片 的詳細資訊 This article is mainly talking about how to use Cursor. query to fetch those media info in external.db And an example : get album, album_artist in android code. You can also use sqlite3 package, but be ware of the permission issue. _______________________________________________ Android系統會預先掃描所有的多媒體檔案,並且把資訊建立成資料庫放在 /data/data/com.android.providers.media/database/... 底下, SD卡的內容會被放在 external.db 其他的系統音訊歸類在 internal.db 裡面有所有可以用的資訊 可以把它pull到本機上打開來看 也可以透過 resolver.query 來存取 例如取出專輯、該專輯的演出者的使用方法如下: package wesely.albuminfo; import java.util.ArrayList; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.widget.TextView; public class TestingActivity extends Activity { private int index; private int totalCount; private ArrayList<String> result = new ArrayList<String>(); private TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView1); Context ctx = TestingActivity. this ; ContentResolver resolver = ctx.getContentResolver(); Cursor c = resolver.query( MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI , null, null, null, null); String dispStr = ""; c.moveToFirst(); totalCount = c.getCount(); for ( int i = 0 ; i < totalCount; i ++ ){ int index = c.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM); String src = c.getString(index); result.add(src); dispStr = dispStr +"專輯 "+(i+1)+" : "+src + "\n"; index = c.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST); src = c.getString(index); result.add(src); dispStr = dispStr +"演出者 : "+src + "\n\n"; c.moveToNext(); } c.close(); textView.setText(dispStr); } } Result: ____________________ 0720-2 weselyong 發表在 痞客邦 PIXNET 留言(0) 人氣()
__label__pos
0.903275
Cryptography Stack Exchange is a question and answer site for software developers, mathematicians and others interested in cryptography. It's 100% free, no registration required. Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top I got an answer in the related question about Mixcolumn for encryption, but how about decryption? what will I do? Because it said that I will used this: During decryption the Mix Column the multiplication matrix is changed to: 0E 0B 0D 09 09 0E 0B 0D 0D 09 0E 0B 0B 0D 09 0E How does one implement this maxtrix multiplication? share|improve this question up vote 5 down vote accepted Well, it's pretty much the same as the forward Mix Column direction; it's a series of multiplications in $GF(2^8)$, however, instead of multiplying by 1, 2 and 3, you're multiplying by 9, 11, 13 and 14. The multiplication rule isn't that complex; however, it is a bit fancier than the quick rule we got for $\times 2$ and $\times 3$. If you're happy with doing a table lookup, this wikipedia page gives tables of values for $x\times 9$, $x\times 11$, $x \times 13$ and $x \times 14$. Another way to approach it is to take the rule you already know for $x \times 2$, and use it several times, as in: $x \times 9 = (((x \times 2) \times 2) \times 2) + x$ $x \times 11 = ((((x \times 2) \times 2) + x) \times 2) + x$ $x \times 13 = ((((x \times 2) + x) \times 2) \times 2) + x$ $x \times 14 = ((((x \times 2) + x) \times 2) + x) \times 2$ (where $+$ is addition in $GF(2^8)$; you know it better as "exclusive-or") Further explination would require me to get into the technicalities of what multiplication in a finite field actually is; I'm not sure you're quite ready for that; if you think you might be, you might want to start in on this article. 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.993594
Any reason to go with Basic Auth over 3LO? Are there any good reasons (e.g., better mgmt for jira admins, better user experience) that any knows to go with Basic Auth (API Tokens) over OAuth 2 / 3LO authentication? I only ask because I see many products (like ProductBoard) that still use API Tokens so want to make sure we’re not missing anything 1 Like I can say the official Atlassian answer is that we wish Apps would use OAuth instead of API Tokens. In the developer guide on auth options and tradeoffs, a significant note is “OAuth 2.0 (3LO) is currently not available for Jira Software.” That means simple things about issues are fine (covered by the Jira Platform but things like boards, sprints, and epics are not. Reading the guide, you might think that’s the one exception but threads here in the developer community indicate OAuth coverage is spotty. For example, a recent thread reveals attachments are not covered (although the thread focuses on Confluence, I’m pretty sure the underlying “media service” is shared by Jira and thus a blocker there too). All that to say that I would flip the question around. Given our intent to favor OAuth, please let us know if you are building an App and can’t find any option better than API Tokens.
__label__pos
0.91208
Perlin Noise Precision Hello all? i’m glad to be part of the processing community. and i’ll try to help my best. I’ve got recent issues using the noise function. the precision was not excellent. for instance a simple curve taken from the noise function gives me some strange staircase forms here is an export svg… image I’ve tried different approaches, like create svg in very big definition files, I imagines that it was round to pixels troubles… but it was none of that the export svg process of processing is quite good and there is no rounding trouble. the fact was that the noise fucntion in processing (java) uses a cosinus table (cosLUT) whose definition is not excellent. taking the code from the open source page of processing and rewrite is just by changing how the cosinus table was made changed the definition. Here is the full version of my noise.pde import java.util.Random; ////////////////////////////////////////////////////////////// // PERLIN NOISE, rewriten by cfloutier to change the way cosinus is computed // [toxi 040903] // octaves and amplitude amount per octave are now user controlled // via the noiseDetail() function. // [toxi 030902] // cleaned up code and now using bagel's cosine table to speed up // [toxi 030901] // implementation by the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip static final int PERLIN_YWRAPB = 4; static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB; static final int PERLIN_ZWRAPB = 8; static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB; static final int PERLIN_SIZE = 4095; int perlin_octaves = 4; // default to medium smooth float perlin_amp_falloff = 0.5f; // 50% reduction/octave // [toxi 031112] // new vars needed due to recent change of cos table in PGraphics int perlin_PI; static final int perlin_TWOPI = 65536; float[] perlin_cosTable; float[] perlin; Random perlinRandom; /** */ public float my_noise(float x) { // is this legit? it's a dumb way to do it (but repair it later) return my_noise(x, 0f, 0f); } /** */ public float my_noise(float x, float y) { return my_noise(x, y, 0f); } /** * ( begin auto-generated from noise.xml ) * * Returns the Perlin noise value at specified coordinates. Perlin noise is * a random sequence generator producing a more natural ordered, harmonic * succession of numbers compared to the standard <b>random()</b> function. * It was invented by Ken Perlin in the 1980s and been used since in * graphical applications to produce procedural textures, natural motion, * shapes, terrains etc.<br /><br /> The main difference to the * <b>random()</b> function is that Perlin noise is defined in an infinite * n-dimensional space where each pair of coordinates corresponds to a * fixed semi-random value (fixed only for the lifespan of the program). * The resulting value will always be between 0.0 and 1.0. Processing can * compute 1D, 2D and 3D noise, depending on the number of coordinates * given. The noise value can be animated by moving through the noise space * as demonstrated in the example above. The 2nd and 3rd dimension can also * be interpreted as time.<br /><br />The actual noise is structured * similar to an audio signal, in respect to the function's use of * frequencies. Similar to the concept of harmonics in physics, perlin * noise is computed over several octaves which are added together for the * final result. <br /><br />Another way to adjust the character of the * resulting sequence is the scale of the input coordinates. As the * function works within an infinite space the value of the coordinates * doesn't matter as such, only the distance between successive coordinates * does (eg. when using <b>noise()</b> within a loop). As a general rule * the smaller the difference between coordinates, the smoother the * resulting noise sequence will be. Steps of 0.005-0.03 work best for most * applications, but this will differ depending on use. * * ( end auto-generated ) * * @webref math:random * @param x x-coordinate in noise space * @param y y-coordinate in noise space * @param z z-coordinate in noise space * @see PApplet#noiseSeed(long) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) */ public float my_noise(float x, float y, float z) { if (perlin == null) { if (perlinRandom == null) { perlinRandom = new Random(); } perlin = new float[PERLIN_SIZE + 1]; for (int i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = perlinRandom.nextFloat(); //(float)Math.random(); } perlin_cosTable = new float[perlin_TWOPI]; perlin_PI = perlin_TWOPI >> 1; for (int i = 0; i < perlin_TWOPI; i++) { float angle = (float)i/perlin_PI; perlin_cosTable[i] = cos( angle * PI ); } } if (x<0) x=-x; if (y<0) y=-y; if (z<0) z=-z; int xi=(int)x, yi=(int)y, zi=(int)z; float xf = x - xi; float yf = y - yi; float zf = z - zi; float rxf, ryf; float r=0; float ampl=0.5f; float n1, n2, n3; for (int i=0; i<perlin_octaves; i++) { int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB); rxf=my_noise_fsc(xf); ryf=my_noise_fsc(yf); n1 = perlin[of&PERLIN_SIZE]; n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1); n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2); n1 += ryf*(n2-n1); of += PERLIN_ZWRAP; n2 = perlin[of&PERLIN_SIZE]; n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2); n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3); n2 += ryf*(n3-n2); n1 += my_noise_fsc(zf)*(n2-n1); r += n1*ampl; ampl *= perlin_amp_falloff; xi<<=1; xf*=2; yi<<=1; yf*=2; zi<<=1; zf*=2; if (xf>=1.0f) { xi++; xf--; } if (yf>=1.0f) { yi++; yf--; } if (zf>=1.0f) { zi++; zf--; } } return r; } // [toxi 031112] // now adjusts to the size of the cosLUT used via // the new variables, defined above private float my_noise_fsc(float i) { // using bagel's cosine table instead int index = (int)(i*perlin_PI)%perlin_TWOPI; float cosvalue = perlin_cosTable[index]; // for a very precise cosinus, just un-comment this line (all cos table is uselless then you can remove it as well // cosvalue = cos(i*PI); return 0.5f*(1.0f-cosvalue); } // [toxi 040903] // make perlin noise quality user controlled to allow // for different levels of detail. lower values will produce // smoother results as higher octaves are surpressed /** * ( begin auto-generated from noiseDetail.xml ) * * Adjusts the character and level of detail produced by the Perlin noise * function. Similar to harmonics in physics, noise is computed over * several octaves. Lower octaves contribute more to the output signal and * as such define the overal intensity of the noise, whereas higher octaves * create finer grained details in the noise sequence. By default, noise is * computed over 4 octaves with each octave contributing exactly half than * its predecessor, starting at 50% strength for the 1st octave. This * falloff amount can be changed by adding an additional function * parameter. Eg. a falloff factor of 0.75 means each octave will now have * 75% impact (25% less) of the previous lower octave. Any value between * 0.0 and 1.0 is valid, however note that values greater than 0.5 might * result in greater than 1.0 values returned by <b>noise()</b>.<br /><br * />By changing these parameters, the signal created by the <b>noise()</b> * function can be adapted to fit very specific needs and characteristics. * * ( end auto-generated ) * @webref math:random * @param lod number of octaves to be used by the noise * @see PApplet#noise(float, float, float) */ public void my_noiseDetail(int lod) { if (lod>0) perlin_octaves=lod; } /** * @see #noiseDetail(int) * @param falloff falloff factor for each octave */ public void my_noiseDetail(int lod, float falloff) { if (lod>0) perlin_octaves=lod; if (falloff>0) perlin_amp_falloff=falloff; } /** * ( begin auto-generated from noiseSeed.xml ) * * Sets the seed value for <b>noise()</b>. By default, <b>noise()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param seed seed value * @see PApplet#noise(float, float, float) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) * @see PApplet#randomSeed(long) */ public void my_noiseSeed(long seed) { if (perlinRandom == null) perlinRandom = new Random(); perlinRandom.setSeed(seed); // force table reset after changing the random number seed [0122] perlin = null; } the definition of the cosinus table can be adjusted with this line static final int perlin_TWOPI = 65536; and to avoid using a cos-table just replace in my_noise_fsc float cosvalue = perlin_cosTable[index]; by float cosvalue = = cos(i*PI); I hope it can help some of us that like me need good precision in exported file. I use a large 2D plotter and this precision can be seen on paper… Christophe
__label__pos
0.880188
Questions tagged [relay] The tag has no usage guidance. Filter by Sorted by Tagged with 1 vote 0 answers 11 views Can I switch to using Openzeppelin Defender or other relayer service from Biconomy with same contract deployed? How to do it? I have deployed the following contract using the BasicMetatransaction.sol file. Attaching the code for that too. I am using Biconomy for relaying gasless transactions. Can I switch to Openzeppelin ... Pankaj Jagtap's user avatar 0 votes 0 answers 52 views Safe-core-sdk + fireblocks as signer: Provides different transaction hashes & transaction can be executed in web UI, but not with executeTransaction() I'm using an Fireblocks account as a signer ( which uses MPC under the hood ) for my gnosis-safe. There are two problems that I'm encountering: The transaction hash from the safe-core-sdk and the one ... giraeffleaeffle's user avatar 2 votes 1 answer 704 views How to get receipt in wagmi / viem for a transaction issued with Safe on walletconnect? Our dapp is using wagmi 1.4 / viem 1.15 and a plain httpProvider. I'm connecting it to a Safe (1/1) using WalletConnect v2. When I dispatch a contract transaction, viem yields a transaction response ... elmariachi's user avatar 0 votes 1 answer 186 views Flashbots with 0 gasPrice When I simulate the transaction I want to send a 0x data and the gasPrice seems 0 thus I am not included any one has any idea why the gasPrice is 0. How can I increase the gasPrice { "results&... Gencehan ARPAÇAY's user avatar 1 vote 1 answer 202 views How to broadcast a signed transaction and cover gas? I'm providing a custodial wallet API solution and everything is handled through APIs. The flow looks like this: 1. Client request (tx payload) => MyServerAPI.sendTransaction(tx payload) 2. Where ... icebox's user avatar • 11 1 vote 0 answers 125 views How to get MEV relay? There are several types of the nodes which support MEV and they are using different relays. For example, this is Flash-bots node https://etherscan.io/address/0xdafea492d9c6733ae3d56b7ed1adb60692c98bc5 ... Dream Person's user avatar 1 vote 1 answer 682 views What is the difference between Relay and Builder post Merge in Ethereum? I was listening to an episode of Bankeless where they were talking about things coming up, post merge. In that episode they mentioned block builders and relayers. The context they mention it was ... Finlay Weber's user avatar
__label__pos
0.649106
product-schema-markup-JASON Schema Markup For Products – Easy to Implement Here you can have Product schema markup in JASON, you can use this schema markup for any product. Where You can use this :Mobile, Air conditioner, LED, and many more electronic devices. Where to put code: You can put this code in header file of your website. Weight height and width these elements you can remove or add as per your requirements. [ads] <script type=”application/ld+json”> { “@context”: “http://schema.org/”, “@type”: “Product”, “name”: “Name of Your Procuct”, “description”: “Description of your product”, “image”: “https://abc.com/phones/apple-iphone8-jpeg“, “aggregateRating”: { “@type”: “AggregateRating”, “bestRating”: “5”, “ratingCount”: “24”, “ratingValue”: “4.5” }, “offers”: { “@type”: “Offer”, “price”: 15000.00, “priceCurrency”: “USD”, “availability”: “InStock” }, “Weight”: { “@context”: “https://schema.org”, “@type”: “QuantitativeValue”, “value”: “2”, “unitCode”: “Ton” }, “height”: { “@context”: “https://schema.org”, “@type”: “QuantitativeValue”, “value”: “340”, “unitCode”: “mm” }, “Width”: { “@context”: “https://schema.org“, “@type”: “QuantitativeValue”, “value”: “25.4”, “unitCode”: “mm” }, “model”: [ { “@type”: “ProductModel”, “name”: “R410 Split Type”, “Material”: “Inner Grooved Copper” } ] } </script>
__label__pos
0.989287
This blog post was written under the Pusher Guest Writer program. In this tutorial, we will learn how to build a collaborative text editor in Android. We will be using Pusher to make the collaboration part easy. We will be building a simple Android app. The Android app will have a single activity containing only an EditText view. We will then keep track of changes to the EditText view and broadcast these changes to other users on the same application. The application will also listen for updates and update the EditText with changes received. Here is a demo of what will be built by the end of this tutorial: Let’s get started! Create the Android Studio Project Launch Android Studio and create a new Project. You could name the application anything you want, but for the purpose of this tutorial we will name it ‘CollabEditor’. Also, ensure you select the ‘Empty Activity’ option as the initial Activity and name it MainActivity on the ‘Customize Activity Page’. Once Android Studio is done with the project’s setup, open the build.gradle file of your application’s module to add the follow dependencies: dependencies { ... compile 'com.pusher:pusher-java-client:1.4.0' compile 'com.google.code.gson:gson:2.7' } These add Pusher and Gson to our android project. Sync the Gradle project so the modules can be installed and the project built. Next, Add the INTERNET permission to the AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.pusher.collabeditor"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> ... </application> </manifest> Create the text editor layout Next, open the activity_main.xml layout file and modify it to look like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.pusher.collabeditor.MainActivity"> <EditText android:id="@+id/textEditor" android:layout_width="match_parent" android:layout_height="match_parent" android:hint="Editor is empty. Select to start typing" android:gravity="top"/> </LinearLayout> The layout is quite simple. It contains an EditText with its width and height set to match_parent. Create the ‘EditorUpdate’ model Create the class com.pusher.collabeditor.EditorUpdate and write the following to it: package com.pusher.collabeditor; public class EditorUpdate { public String data; public EditorUpdate(String data) { this.data = data; } } This class when converted to JSON with Gson corresponds to the following structure: { "data": "Editor text will be here" } This is the structure of JSON that would be sent to other users of the application when updates are made to the text editors content. Setting up a Pusher account If you don’t already have a Pusher account, create a free Pusher account here then log in to your dashboard. Once logged in, create an app by entering an app name (any name will do) and choosing a cluster in the Create App screen. After creating the new app, go to the App Keys tab and copy your App ID, Key, and Secret credentials. We will use them in our application. Update the MainActivity Now, back in Android Studio, open the class com.pusher.collabeditor.MainActivity. First let us declare all the required constants and variables for the application: public class MainActivity extends AppCompatActivity { private static final String DEBUG_TAG = MainActivity.class.getSimpleName(); private static final String PUSHER_API_KEY = "YOUR PUSHER APP KEY"; private static final String PUSHER_CLUSTER = "PUSHER APP CLUSTER"; private static final String AUTH_ENDPOINT = "PUSHER AUTHENTICATION ENDPOINT"; private Pusher pusher; private EditText textEditor; private TextWatcher textEditorWatcher; Ensure you replace those variable values with your own Pusher credentials. I’ll explain how to get the AUTH_ENDPOINT value later in this tutorial. Next, in the onCreate method, set the content view and initialize the Pusher object like this: ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textEditor = (EditText) findViewById(R.id.textEditor); pusher = new Pusher(PUSHER_API_KEY, new PusherOptions() .setEncrypted(true) .setCluster(PUSHER_CLUSTER) .setAuthorizer(new HttpAuthorizer(AUTH_ENDPOINT))); } We set an authorizer because we are going to be using Pusher’s Client Events to broadcast changes on the text editor to other users of the application. An advantage of this is that we don’t need to route our updates through a server. Using Pusher’s Client Events To use Pusher’s Client Events, it needs to be enabled for your Pusher app. You can do this in the Settings tab for your app within the Pusher’s dashboard. Client Events can only be broadcast on a private channel and event names must start with the prefix client-. To use private channels, the Pusher client must be authenticated hence the reason for the AUTH_ENDPOINT. Pusher makes writing an auth server easy. I used their NodeJS template here. Once set up, update the AUTH_ENDPOINT of your code to the URL of the auth server. With all this in mind, we now go back to the Android code. After initializing the Pusher client, we create a PrivateChannelEventListener: ... @Override protected void onCreate(Bundle savedInstanceState) { ... PrivateChannelEventListener subscriptionEventListener = new PrivateChannelEventListener() { @Override public void onEvent(String channel, String event, final String data) { runOnUiThread(new Runnable() { @Override public void run() { EditorUpdate editorUpdate = new Gson().fromJson(data, EditorUpdate.class); textEditor.setText(editorUpdate.data); } }); } @Override public void onAuthenticationFailure(String message, Exception e) { Log.d(DEBUG_TAG, "Authentication failed."); Log.d(DEBUG_TAG, message); } @Override public void onSubscriptionSucceeded(String message) { Log.d(DEBUG_TAG, "Subscription Successful"); Log.d(DEBUG_TAG, message); } }; ... } When an event is received in the onEvent method, we convert the JSON data to an EditorUpdate object using Gson and then update the editor’s text with the data received. Next, we subscribe to our private channel and bind the event listener to client events on the channel. final PrivateChannel editorChannel = pusher.subscribePrivate("private-editor", subscriptionEventListener); noteChannel.bind("client-update", subscriptionEventListener); Now, the text editor will update its content whenever it receives a client-update event. Next, we need to add a TextWatcher to our textEditor: textEditorWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { } @Override public void onTextChanged(CharSequence charSequence, int start, int before, int count) { String text = charSequence.toString(); EditorUpdate editorUpdate = new EditorUpdate(text); noteChannel.trigger("client-update", new Gson().toJson(editorUpdate)); } @Override public void afterTextChanged(Editable editable) {} }; textEditor.addTextChangedListener(textEditorWatcher); So when text changes on the editor, we trigger a client-update event on the editor channel. After this ensure that you connect and disconnect your Pusher client in the onResume() and onPause() methods respectively. @Override protected void onResume() { super.onResume(); pusher.connect(); } @Override protected void onPause() { pusher.disconnect(); super.onPause(); } With this, our Android application is almost fully functional. If you were to run and test the Android application now, you would notice an endless update loop in the EditText whenever it receives an client-update event. This loop is because when a client-update event is received, textEditor.setText() is called which in turn triggers textEditorWatcher.onTextChanged() and this causes another client-update to be sent to other applications which would restart the loop process. Below is an image showing how this looks like between two apps: Fixing the EditText update loop To fix this endless update loop, we will remove the textEditorWatcher from the textEditor before we call textEditor.setText() and then add it back afterwards. ... PrivateChannelEventListener subscriptionEventListener = new PrivateChannelEventListener() { @Override public void onEvent(String channelName, String eventName, final String data) { runOnUiThread(new Runnable() { @Override public void run() { Log.d(DEBUG_TAG, data); EditorUpdate editorUpdate = new Gson().fromJson(data, EditorUpdate.class); //remove textEditorWatcher textEditor.removeTextChangedListener(textEditorWatcher); textEditor.setText(editorUpdate.data); //add it back afterwards textEditor.addTextChangedListener(textEditorWatcher); } }); } ... }; ... So this way, textEditor.setText() doesn’t call textEditorWatcher.onTextChanged() and therefore the loop doesn’t happen. Now, our collaborative text editor Android app is fully functional. Yay! Testing the application To test the Android application, you will need to build and run the application on multiple devices (or you could just run it on multiple Android emulators). Any edit you make on an application’s text editor will be seen in the other applications running. Conclusion In this tutorial, we have seen how to build a collaborative text editor in Android using Pusher’s Client Events. Some extra things to note about this tutorial are: • This Android app doesn’t account for concurrent edits at the same place in the editor. You can use a technique called Operational Transforms to solve this. • Client Events have a number of restrictions that are important to know about, one of which is the limit to the number of events that can be published per seconds. Read more about them here. The complete code for this tutorial can be found on github here.
__label__pos
0.524521
Arthur Burkhardt Arthur Burkhardt - 1 year ago 68 SQL Question Pandas SQL equivalent of update where group by Despite looking for this, I cannot find the correct way to get an equivalent of this query working in pandas. update product set maxrating = (select max(rating) from rating where source = 'customer' and product.sku = rating.sku group by sku) where maxrating is null; Pandas product = pd.DataFrame({'sku':[1,2,3],'maxrating':[0,0,1]}) rating = pd.DataFrame({'sku':[1,1,2,3,3],'rating':[2,5,3,5,4],'source':['retailer','customer','customer','retailer','customer']}) expected_result = pd.DataFrame({'sku':[1,2,3],'maxrating':[5,3,1]}) SQL drop table if exists product; create table product(sku integer primary key, maxrating int); insert into product(maxrating) values(null),(null),(1); drop table if exists rating; create table rating(sku int, rating int, source text); insert into rating values(1,2,'retailer'),(1,5,'customer'),(2,3,'customer'),(2,5,'retailer'),(3,3,'retailer'),(3,4,'customer'); update product set maxrating = (select max(rating) from rating where source = 'customer' and product.sku = rating.sku group by sku) where maxrating is null; select * from product; How can it be done? Answer Source try this: In [220]: product.ix[product.maxrating == 0, 'maxrating'] = product.sku.map(rating.groupby('sku')['rating'].max()) In [221]: product Out[221]: maxrating sku 0 5 1 1 3 2 2 1 3 or using common mask: In [222]: mask = (product.maxrating == 0) In [223]: product.ix[mask, 'maxrating'] = product.ix[mask, 'maxrating'].map(rating.groupby('sku')['rating'].max()) In [224]: product Out[224]: maxrating sku 0 5 1 1 3 2 2 1 3
__label__pos
0.761109
How can I plot y-z plane slices in a 3D volume? 92 views (last 30 days) I have a series of plots representing the vorticity field behind an aircraft wing, at various downstream distances. Each is a 2D plot, and I would like to display them in 3D, one behind the other, in order to get a full 3D sense of the vorticity field behind the wing. In my first attempt, I made a 3D meshgrid, set it to zero, and filled in 4 z-slices with 4 vorticity plots, and that worked. However, I could not get it to the viewpoint that I wanted. Here is the plot that resulted: This is rather confusing because in this plot, the wing is beneath the plot, and therefore is more likely to confuse the intended audience than do any good. Further, in attempting to change the viewing angle with Matlab's view command, I was not able to get to the desired viewing angle. So then I made a second attempt, where instead of plotting z-slices I plot x-slices. This does indeed give me the desired viewing angle, as seen here (where the slices are just zeros): Here, the wing is to the left of the plot, and it's much easier for the audience to get a sense of the full 3D vorticity field. However, I am unable to get the vorticity plots to display. Here is my code: FullVectorField = zeros(200,14,13); [x,y,z] = meshgrid(1:1:14, 1:1:200, 1:1:13); FullVectorField(50,:,:) = vorticity70; FullVectorField(100,:,:) = vorticity80; FullVectorField(150,:,:) = vorticity90; FullVectorField(200,:,:) = vorticity100; zslice = []; xslice = [50,100,150,200]; yslice = []; A = FullVectorField(50,:,:); figure slice(x,y,z,FullVectorField,xslice,yslice,zslice); pbaspect([3 1 1]) axis([0, 200, 0, 14, 0, 13]) colormap jet colorbar xlabel('x axis (cm)') ylabel('y axis (cm)') zlabel('z axis (cm)') vorticity70, vorticity80, etc are the matrices containing the data points I would like to plot. Any help in getting the vorticity plots to display along the xslices? Thanks! Accepted Answer Mike Garrity Mike Garrity on 3 May 2016 Edited: Mike Garrity on 3 May 2016 You don't really need to build a full 3D array and then slice it. You can just place individual 2D slices in a 3D axes. [y,z] = meshgrid(linspace(0,10,40)); for off=50:50:200 x = off + zeros(size(z)); % My standin for your vorticity data c = cos((x+y)/5) .* cos((x+z)/5); surf(x,y,z,c) hold on end hold off xlim([0 200])   4 Comments adi adi on 16 Dec 2019 hey, i have the exact problem you just described...do you know how to fix this? thanks Sign in to comment. More Answers (0) Categories Find more on Colormaps in Help Center and File Exchange Community Treasure Hunt Find the treasures in MATLAB Central and discover how the community can help you! Start Hunting!
__label__pos
0.568309
Column Control DTX Why are Taps Critical to Network Visibility and Security? Solution Briefs The first building-block to your visibility architecture is access to the data. That comes in one of two forms: a network tap or a switch port analyzer (SPAN) port (also known as port mirroring). But which is the right one? This document should help answer that question. These days, your network is as important to your business as any other item—including your products. Whether your customers are internal or external, you need a dependable and secure network that grows with your business. Without one, you are dead in the water. IT managers have a nearly impossible job. They must understand, manage, and secure the network all the time against all problems. Anything less than a 100 percent working network is a failure. × *Required Field Preferred method of communication? Change email? Preferred method of communication? By clicking the button, you are providing Keysight with your personal data. See the Keysight -Datenschutzaussage Informationen darüber, wie wir diese Daten verwenden. Thank you. A sales representative will contact you soon. Column Control DTX
__label__pos
0.533412
CSS3 Animation Experiment – Virtual DJ CSS3 Animation Experiment – Virtual DJ 2 38950 CSS3 Animation Experiment - Virtual DJ CSS3 Animation Experiment – Virtual DJ Today I made up my mind to prepare nice CSS3 experiment. I wanted to create a nice looking environment with a lot of moving elements. As background, I selected DJ music console. In this demo anything is movable only with CSS3 (without any javascript). I used various css3 technics like keyframes, animation, transformation (rotation and scale). Welcome to test it. Live Demo download result So, lets start Step 1. HTML Everything is very easy, isn’t it? As you can see – it contains a lot of different images. index.html <div class="vdj"> <img src="images/back.jpg"> <img class="v1" src="images/v1.png"> <img class="v2" src="images/v2.png"> <img class="v3" src="images/v3.png"> <img class="v4" src="images/v4.png"> <img class="s1" src="images/speaker.png"> <img class="si1" src="images/speaker-in.png"> <img class="s2" src="images/speaker.png"> <img class="si2" src="images/speaker-in.png"> <img class="s3" src="images/speaker.png"> <img class="si3" src="images/speaker-in.png"> <img class="s4" src="images/speaker.png"> <img class="si4" src="images/speaker-in.png"> <img class="slid1" src="images/slid1.png"> <img class="slid2" src="images/slid1.png"> <img class="b1" src="images/but1.png"> <img class="b2" src="images/but2.png"> <img class="b3" src="images/but3.png"> <img class="b4" src="images/but1.png"> <img class="b5" src="images/but2.png"> <img class="b6" src="images/but3.png"> <img class="eq" src="images/space.gif"> <img class="eq2" src="images/space.gif"> </div> Step 2. CSS Now, its time to style our musical demo. Don’t forget to include our CSS file in the head section of the result page. css/main.css /* virtual dj */ .vdj { margin: 100px auto 0; position: relative; width: 800px; } /* vinyl keyframes */ @-webkit-keyframes vinyl { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); } } @-moz-keyframes vinyl { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); } } .v1, .v2, .v3, .v4 { /* css3 animation */ -moz-animation-name: vinyl; -moz-animation-duration: 3s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: vinyl; -webkit-animation-duration: 3s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } .v1 { left: 83px; position: absolute; top: 77px; } .v2 { left: 580px; position: absolute; top: 77px; } .v3 { left: 66px; position: absolute; top: 382px; } .v4 { left: 634px; position: absolute; top: 382px; } /* speaker keyframes */ @-webkit-keyframes speaker { 0% { -moz-transform: scale(0.75); -webkit-transform: scale(0.75); } 45% { -moz-transform: scale(0.85); -webkit-transform: scale(0.85); } 100% { -moz-transform: scale(0.75); -webkit-transform: scale(0.75); } } @-moz-keyframes speaker { 0% { -moz-transform: scale(0.75); -webkit-transform: scale(0.75); } 45% { -moz-transform: scale(0.85); -webkit-transform: scale(0.85); } 100% { -moz-transform: scale(0.75); -webkit-transform: scale(0.75); } } .si1, .si2, .si3, .si4 { /* css3 transform */ -webkit-transform:scale(0.75); -moz-transform:scale(0.75); -ms-transform:scale(0.75); -o-transform:scale(0.75); transform:scale(0.75); /* css3 animation */ -moz-animation-name: speaker; -moz-animation-duration: 0.5s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: speaker; -webkit-animation-duration: 0.5s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } .si1 { left: 541px; position: absolute; top: 249px; } .s1 { left: 545px; position: absolute; top: 253px; } .si2 { left: 606px; position: absolute; top: 249px; /* css3 animation delay */ -moz-animation-delay: 0.25s; -webkit-animation-delay: 0.25s; } .s2 { left: 610px; position: absolute; top: 253px; } .si3 { left: 671px; position: absolute; top: 249px; } .s3 { left: 675px; position: absolute; top: 253px; } .si4 { left: 735px; position: absolute; top: 249px; /* css3 animation delay */ -moz-animation-delay: 0.25s; -webkit-animation-delay: 0.25s; } .s4 { left: 739px; position: absolute; top: 253px; } /* slider keyframes */ @-webkit-keyframes slider { 0% { margin-top:0px; } 50% { margin-top:90px; } 100% { margin-top:0px; } } @-moz-keyframes slider { 0% { margin-top:0px; } 50% { margin-top:90px; } 100% { margin-top:0px; } } .slid1, .slid2 { /* css3 animation */ -moz-animation-name: slider; -moz-animation-duration: 2.0s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: slider; -webkit-animation-duration: 2.0s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } .slid1 { left: 254px; position: absolute; top: 94px; } .slid2 { left: 751px; position: absolute; top: 94px; /* css3 animation delay */ -moz-animation-delay: -1.0s; -webkit-animation-delay: -1.0s; } /* buttons keyframes */ @-webkit-keyframes buttons { 0% { opacity: 1; } 45% { opacity: 0; } 100% { opacity: 1; } } @-moz-keyframes buttons { 0% { opacity: 1; } 45% { opacity: 0; } 100% { opacity: 1; } } .b1, .b2, .b3, .b4, .b5, .b6 { /* css3 animation */ -moz-animation-name: buttons; -moz-animation-duration: 1.0s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: buttons; -webkit-animation-duration: 1.0s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } .b1 { left: 17px; position: absolute; top: 105px; } .b2 { left: 17px; position: absolute; top: 147px; /* css3 animation delay */ -moz-animation-delay: 0.3s; -webkit-animation-delay: 0.3s; } .b3 { left: 17px; position: absolute; top: 190px; /* css3 animation delay */ -moz-animation-delay: 0.6s; -webkit-animation-delay: 0.6s; } .b4 { left: 513px; position: absolute; top: 105px; /* css3 animation delay */ -moz-animation-delay: 0.3s; -webkit-animation-delay: 0.3s; } .b5 { left: 513px; position: absolute; top: 147px; /* css3 animation delay */ -moz-animation-delay: 0.6s; -webkit-animation-delay: 0.6s; } .b6 { left: 513px; position: absolute; top: 190px; } /* eq keyframes */ @-webkit-keyframes eq { 0% { background-position: 0 0; } 100% { background-position: 0 -92px; } } @-moz-keyframes eq { 0% { background-position: 0 0; } 100% { background-position: 0 -92px; } } .eq { background: url("../images/eq.png") no-repeat scroll center top transparent; height: 92px; left: 197px; position: absolute; top: 389px; width: 18px; /* css3 animation */ -moz-animation-name: eq; -moz-animation-duration: 2.0s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: eq; -webkit-animation-duration: 2.0s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } /* eq2 keyframes */ @-webkit-keyframes eq2 { 0% { background-position: 0 0; } 100% { background-position: -260px 0; } } @-moz-keyframes eq2 { 0% { background-position: 0 0; } 100% { background-position: -260px 0; } } .eq2 { background: url("../images/eq2.png") no-repeat scroll center top transparent; height: 28px; left: 271px; position: absolute; top: 240px; width: 260px; /* css3 animation */ -moz-animation-name: eq2; -moz-animation-duration: 6.0s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: eq2; -webkit-animation-duration: 6.0s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } I think that everything should be very easy for you. I used -moz and -webkit prefixes in order to teach it works in FF and Webkit-based browsers (Chrome and Safari). Live Demo download result Conclusion Thats all, today we have created new animated demonstration with CSS3. You are free to modify our result and use it at your websites. Feel free to share our tutorials with your friends. Good luck! 2 COMMENTS • Hello Richard, Possible of course. But in this case we have to use javascript to bind custom events. We can’t work with music at CSS3 level :-) Leave a Reply
__label__pos
0.999535
Mass text msg Discussion in 'Android General Discussions' started by liam., Jun 7, 2010. 1. liam. liam. Member Joined: Jun 6, 2010 Messages: 90 Likes Received: 0 Trophy Points: 6 Ratings: +0 Is there any way to send out text messages to multiple recipiants by just selecting them and not typing them in? Its a PITA to try and remember everyone you want to send them to and would be WAY easier to just check them off or select them.   2. jethro jethro New Member Joined: Mar 14, 2010 Messages: 23 Likes Received: 0 Trophy Points: 1 Ratings: +0 If you use handcent, go into it and open a new message. In the "to:" box, there is a plus (+) sign. Just click on it and you can go down the list and check off everyone you want to send it to. Not sure about the native app because I haven't used it in a long time.   3. Bdog Bdog Member Joined: May 23, 2010 Messages: 194 Likes Received: 0 Trophy Points: 16 Location: P-Cola FL Ratings: +0 Is there a way to go about it without using Handcent? I personally hate that app, and I know a few others who would rather go without it as well   4. liam. liam. Member Joined: Jun 6, 2010 Messages: 90 Likes Received: 0 Trophy Points: 6 Ratings: +0 +1 I'm not a big fan of it, but I guess it is better then trying to remember everyone I want to text off the top of my head. Thanks for the info   Search tags for this page how long does a mass text last? , how to mass text on droid , how to mass text on htc incredible 2 , how to send a mass text from a android phone , how to send a mass text on a droid x2 , how to send mass text droid x , how to send mass text on droid x2 , mass text droid x , send mass text droid x , sending mass text messages with motorola droid 2
__label__pos
0.983894
Intelligent Content Structures for Personalized Customer Experiences Teams hoping to scale personalization technology are realizing the importance that the shape of content takes in designs, content systems, and APIs. Content structures have taken a leading role as the ingredients necessary to dynamically build relevant experiences for customers. Investments in headless content and commerce platforms reached more than $1.6 Billion this year (Forbes), demonstrating that the drive toward structured and modular content continues to increasingly attract attention. This attention is well placed because all personalization ultimately depends on content assemblies – meaning application of content componentization so machines can then surface relevant components based on logic. And content assemblies ultimately rely on structure. As customers, we seek the most relevant information because it’s the most efficient use of our limited attention. With every interaction, we need to figure out what’s relevant to us. Regardless of how  we arrive at an information landscape, we arrive looking for relevance. We don't have the capacity to process everything, so we sort for relevance very quickly. We ask "what is the most meaningful content right now" and mentally discard everything else. Research shows that customers bounce off websites within 5-10 seconds of arrival, down from 15-20 seconds a decade ago (nngroup). Imagine the mere milliseconds we allocate for relevance-sorting when scrolling through social media or scanning through unopened emails.  As content relevance matters more and more, so too does personalization. Relevant content helps everyone conserve valuable mental space, as well as time and money. This article focuses on content relevance and structure, examining:   • The challenge of recognizing and managing content structure • The role of content assembly in real-time marketing • How content models facilitate content portability and targeting • Examples of invisible or unrecognized content structures • Mapping customer experiences to content structures  The Varieties of Content Relevance  The “moment of relevance”, sometimes called a “moment that matters”, arrives when a component containing content becomes most useful to a customer.  Let’s look at three types of content relevance: Intent-driven content relevance: Content most often gains relevance when it successfully matches a customer’s intent or goal. Intent can be specific (“find a solution to a specific error”), broad (“find something fun to do outdoors in the winter”), and everything in between. The important part is that the customer carries the intent, so the content should match that intent as much as possible. Matching a response to an intent defines the essence of this kind of relevance. Timeline-driven content relevance: Specific content becomes useful to a customer or user at specific points in time within their journey while engaging with a digital experience or brand. Here, we leverage the notion of injecting content structures into a timeline. Customer use cases for this approach include:   • The need to learn something at a given moment • Employ content to perform a task • Use content to solve a problem or spark a realization • Advance from one step in their journey to the next journey with an organization. Within these specific moments in time, the customer requires specific content to help them meet their needs. Profile-driven content relevance: Specific content proves useful because the customer is part of a demographic identified by an analytics team, including but not limited to age, gender, location, and interests. In these scenarios, content relevance includes matching content with customer data on specific attributes and segment paradigms. In general, consumers lack the time to read through all the information presented to them. Many organizations and brands present consumers with too much information, and users will not sift through lots of long-form information when they really need a fraction of that input. Notwithstanding, most consumers prefer to spend time with the most pleasurable and frictionless content experiences.  In all of these cases, the assembly of structured content components for the right person, at the right place, on a timeline, is the hallmark of a personalized, relevant, positive customer experience. Getting some unit of content in front of someone based on intent, timeline, or cohort is the goal and the primary challenge for teams attempting to achieve relevance.   Modular Content defines the Baseline for Intelligent Experiences Relevant intent-response matching forms the foundation of Intelligent Customer Experiences (ICX), an approach to content and customer experience [A] has pioneered with enterprise publishing teams. In ICX, a technology platform determines customer intent and then responds with appropriate content that seeks to meet the customer’s needs.  Many organizations have mountains of under-utilized data facets about customers available. Profiles get stored in environments such as Customer Data Platforms (CDPs), or large data warehouses, often carrying hundreds of attributes. Connecting all the data facets to all the content components that a company produces takes some effort. And where does one begin with tagging these data points and associating them with content? Semantic models are the solution. [A] covers semantics in depth across articles and webinars, most notably in the paper Introducing the Core Semantic Model.  Real-Time Marketing and the Invisible World of Content Organizations often start with relevance for marketing messages, and for good reason: 84% of customers report they are more likely to buy from companies that personalize content (Salesforce). It's not surprising that 90% of digital businesses say they leverage at least one personalization program (Forrester) and look to grow investments in personalization. Real-time marketing involves content modules matched to customers and customer behaviors. Any honest conversation about real-time marketing must acknowledge that content needs to exist in a manageable structure that allows for targeting. How do we deliver the right information to our suppliers, partners, and customers based on what they need, when they need it? And do so based upon their context? We answer the question simply with: “Structure!” Real-time or dynamic rendering of content cannot happen without content structure. You may not be aware of how structure informs content, but structure exists everywhere in content experiences, either accidentally or with intention and purpose and engineering. The assembly of relevant content depends entirely on having logical content structures available for machine discovery and presentation. These content structures already express themselves in many places across your content and customer experience ecosystems. [A] works with clients to identify, standardize, use, and manage content structures, or “content models”. Any team working on personalization should have a dedicated function for managing the content structures that underpin all modular customer experience.  Content structure itself involves the identification and categorization of content elements with an experience --Titles, Tag Lines, Images, Content Snippets, Offers, Questions and Answers, Descriptions, etc. -- as part of a content engineering approach to determine the parameters and behavior of modular content. Regardless of the technology involved, systems need to manage content structures in order for personalization to happen in a meaningful way. And as a best practice, content should remain fluid, flexible, and decoupled from presentation. An effective approach starts with the content engineer or content architect identifying the content structures as content types and their relationships. This usually starts with a Content Relationship Diagram, or content domain model. With the content types identified, teams then build out the content elements and attributes for each content type. The content types, elements, and attributes form the basis for the content model. Once a content model is defined, technology teams can configure systems to understand and utilize the structured content. Then assembly can occur, where components can surface in any digital channel based on the rendering rules, leading to a response to customer context to deliver personalized experiences. In some organizations, content structures remain overlooked entirely. Some teams view structures merely as a presentation template, or they deem content structure as a secondary effect of UX design. Sometimes teams consider structure only when creating the functional specifications for a Content Management System (CMS), or when designing the stylesheets for a page layout. However, these examples are more focused on the designed rendering of static content.  We are Surrounded by “Invisible” Structure Before we examine methods of content management, let us revisit some of the places that content structure lives. Content structure remains so pervasive that we often do not recognize it, even as it is embedded in tools or procedures that we use every day. The following table presents examples of where structured content lives within a content ecosystem or instances that require structured content to enable a transaction.   LOCATION DESCRIPTION DTP platforms / authoring Inherent structure exists even within an MS Word document: headings, subheadings, lists and such. Much technical documentation has migrated over to XML format, where document structure contains more intent and where metadata enables post-processing to occur for presentation and other actions. Presentation Templates Content structures often get baked into design systems. Component-based content can work efficiently with component-based design patterns when the content models are teased out of the templates and built into a separate system. Records Management (CMS, CCMS, DAM, etc.) An organization’s source content pool has a great deal of structure already. Tagging and metadata in a knowledge base offers a great source for metadata. Any applications that store content express content structure.  Document markup and markdown standards Markup, or even lightweight markdown, standards for documents that are heavily reliant on inherent structure can delineate both format-based and logical content structures. Source Code Repos (GIT, CVS) Structural tags and containers are used to delineate, locate, and retrieve source code. Metadata fields and sometimes code comments are rich with useful content structures that need to be added to your overall Core Content Model. Voice Voice UI and navigation is becoming more common. Often these systems rely on highly structured content sources. In healthcare, there are “symptom checkers” and algorithm-based triages that can function as sources of inherent structure. SEO Technical SEO relies heavily on content structures (“structured data”), and gets mapped via your Core Content Model to essential standards like schema.org. Identifying and incorporating content structure across various representations into a functional, unified content model finally makes it possible for an organization to facilitate movement of its content objects across its entire content ecosystem. This movement includes a whole series of content-carrying applications and a whole bevy of downstream consumption channels via headless content APIs. Models and Content Portability   When structured content is machine-readable, systems can retrieve and locate relevant content automatically. A key function of content models is the orchestration layer, which renders content consistently as both human and machine consumable. This guideline persists wherever the content goes, and however it gets targeted out for assembly via a content recommendation algorithm or machine-learning optimized method.  Beyond the benefits of improved organic search, content structure enables the connection between content source and delivery methods via APIs. One benefit of building and managing content structural standards is that it keeps content fluid and in motion throughout the content supply-chain, so that the many systems of engagement can reliably pull the content components needed for intelligent experiences. Companies that approach [A] often have many advanced content targeted systems in place, but they lack a unified approach of getting content to work consistently across even a single platform layer with multiple instances, let alone across many platforms across the global enterprise. Building a unified model is a breath of fresh air, because it rationalizes and organizes a chaotic landscape.  From authoring standards (e.g. Schema.org) to industry-specific standards (e.g. medical or construction), content structure plays a major role in portability and content around the world. Content cannot move without structure. Structure comes from content models. But we do not need to constrain content to one model artificially. The future requires flexible models that can adapt and transform. Then we can build nimble content supply chains with the power of nodal transformation. This will allow us to build new outputs and channels for content using these same elements and attributes of content. Content flexibility starts with flexible content models. The Core Content Model For practicality and effectiveness, the conscious design of an internal standardized  content model to support an omnichannel and omni-source world remains pivotal for all personalization. This standardized content model that crosses many content types and platforms is what we at [A] refer to as The Core Content Model (CCM)™. This concept represents a single, integrated model that defines how content assets will be structured and represented throughout their complete content lifecycle. Key takeaways about the CCM include the following:   • The CCM™ focuses on the structure of content — its literal physical organization into components that can be enriched, reused, processed, and consumed. • By defining the structure of content assets, the CCM facilitates the creation, exchange, and utilization of valuable modular content assets.  • To achieve effective results, a content model must incorporate semantics by reference. Here, semantics refers to the introduction of enriched meaning (“tags”) into the content in such a way that applications can find, interpret, and act on content. Relevance depends on semantic matching content with customer data related to the same topic or intent tags. • The CCM™ seeks to encompass the complete content asset lifecycle, from planning to delivery and use. This lifecycle orientation is important, as it is a central goal of The CCM™ to facilitate the representation of content structures in every application that will need to access, display, manage, and potentially modify the content. In this way, the CCM™ enables the flow of content across all of the applications that play a role in the content lifecycle Matching content structures with the customer’s contextual data  After we have content structured into a model that we actively manage, we are halfway to personalization. We must also match content structures with customer data, then apply this logic through the right channels at the right time. How does this magic happen? Science, of course. Enter the world of semantics, which includes controlled vocabularies, aligned taxonomies, metadata and tag management systems, terminology management systems, tight content governance, and, in some cases, ontologies and knowledge graphs. This is the information about what our content actually is and how it gets tagged, along with what the customer needs. All of this data about data and nomenclature rules remains largely invisible to the end user, but provides the context for machines on how to treat, serve, and assemble the content to best meet the customer's needs. Enterprise-level content systems often need to manage semantics separately in a Core Semantic Model being run in a semantics software, the source of truth. As a point of reference, you will find several resources on simplea.com which discuss the functions of the semantics model. Persistence with Personalization Personalization should not be an afterthought. Successful personalization exists as an emergent effect from many causes, some of which are ongoing and others that are intentionally implemented. Most personalization efforts will fail if treated like a one-time project, campaign, or a feature within a piece of software.   So far we have surfaced several points; to summarize the key takeaways:    • Intelligent Customer Experiences rely on modular content • Modular content relies on consistent structure • Consistent structure depends on The Core Content Model™ (CCM) • A core content model depends on engineering and orchestration Mapping Customer Experiences to Content Structures  In order to start developing intelligent customer experiences, the path to personalization starts, as many things do, with a definition of the outcomes. To define these outcomes:   • Identify the “moments of relevance” where content recommendations and assemblies will drive measurable (and customer-memorable) value • Break those moments into their components of UX, structured content, and semantic elements • Align the components with larger enterprise content standards • Build a plan for implementation using the components identified • Build integrated team alignment and teamwork necessary to produce and bring all the elements together Department teams, product teams, omnichannel content, and CX teams can all own this kind of work, often in partnership with their internal and external technology partners. [A] facilitates building structured content models with clients. And teams never cease to be surprised at how much progress can be made quickly with a coherent framework.  No matter how advanced the underpinning technology, Intelligent Customer Experiences fundamentally require teamwork and collaboration. Organizations should not view personalization as a project: it is a practice. It requires new ways of working that support modular content creation, management, and targeting. All of this starts by rallying a team around a defined and managed content model. Contact Us for a Free Consultation. Authorship Cruce Saunders is the founder and principal at [A] and author of Content Engineering for a Multi-Channel World. He regularly speaks on omnichannel customer experience, content intelligence, AI, chatbots, personalization, content structural and semantic standards, and intelligence transformation. He also hosts the Towards a Smarter World podcast, where he connects with leaders impacting global intelligence.
__label__pos
0.947536
Dismiss Notice Join Physics Forums Today! The friendliest, high quality science and math community on the planet! Everyone who loves science is here! Calculating the probability of an animal finding a resource 1. Aug 14, 2013 #1 I'd like some help working out the probability of my model animal finding water in a day. In my 'model' there is a square landscape 17km^2 The water pool is a circle of 500m radius (so approx 0.7854km^2) So in a one off shot the chances of hitting the water is 0.7854/17 = 0.0462 right? But if I suppose that the animal can search over the course of a day, how can I incorporate this into increasing its prob. of finding the water? Assume for the sake of argument that it can travel at 1m/second and has a 500m detection range then it should 'cut out' circles the same radius as the water pool every 1000 seconds. Then I think it would cut out 86400/1000 = 86.4 in day. If this is correct how can I convert it into a probability? I know this is a ramble, but I've been at it all morning, so any help would be much appreciated!   2. jcsd 3. Aug 14, 2013 #2 mfb User Avatar Insights Author 2015 Award Staff: Mentor If the animal magically appears at a random position in the landscape, this is the probability that it will appear in the water. It depends on the way it searches for water. Neglecting effects at the edges of the landscape, your model animal can search 1000m2 per second. With an ideal path, it would need roughly 17000 seconds to see the whole landscape, less than 5 hours. The probability to find the pool within a day is 1, independent of its size. Real animals rarely walk on those ideal lines, so the probability depends on the walking algorithm.   4. Aug 14, 2013 #3 Evo User Avatar Staff: Mentor What's the probability of an animal appearing out of thin air into an area to which it's never been?   5. Aug 14, 2013 #4 Pool size radius matters: ( versus a search independant of pool radius ) Even less search time for a 500 radius water pool. Search radius would be detection radius 500m plus the water pool radius giving a total 1000m search radius ( assuming pool edge detection ). A 5km by 3.5 km grid (17.5 square km ) could be searched in 2 passes. So, not exactly, but somewhere around 9000 seconds of search required. In fact a 5 x 4 km rectangular area could be searched in less than 10000 seconds ( again assuming edge detection of the water pool ).   6. Aug 15, 2013 #5 Pythagorean User Avatar Gold Member 7. Aug 15, 2013 #6 mfb User Avatar Insights Author 2015 Award Staff: Mentor It reduces searching time, but it does not increase the probability to find the pool. :D If the pool is circular and fully within the search area, we can do even better. We can ignore 1km on both sides of the 5km-range, and the total travel distance is below 8.5km*. A 3x6km-area would require at most 6km, as it can be done in a single pass. *Edit: Below ##(6.5 + \sqrt{2})km \approx 7.9km##.   Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook Have something to add? Draft saved Draft deleted Similar Discussions: Calculating the probability of an animal finding a resource 1. The shape of animals (Replies: 0) 2. Are humans animals? (Replies: 6) Loading...
__label__pos
0.955934
When using Threading.Thread.Sleep in .NET, there is an option to use Threading.Thread.Sleep(timeout As TimeSpan).Now, in System.TimeSpan there is the option to express period in 100-nanosecond units: System.TimeSpan(ticks as long).Can Threading.Thread.Sleep work with nanoseconds or it converts them to milliseconds (integer)?If it converts them to milliseconds I quess there is no way to suspend a thread for less than 1 millisecond. Is that right? view solution
__label__pos
0.9982
Question: Can You Hack A Wii Without An SD Card? Does Homebrew still work on Wii? The Homebrew Channel is a simple way to allow you to play unofficial games and run unofficial applications on your Wii. Modifying your Wii’s software will void your Wii system’s warranty and can potentially damage your console if done incorrectly. LetterBomb will only work with Wii Menu 4.3.. Can you play Wii roms on Wii? All 4.3 consoles are hackable and I found it very easy to homebrew my wii. … As for wii roms, I use usb loader gx to load my wii games and just load all of my older games like nes, snes, and n64 (I don’t really play GameCube games that often) from my sd card. Hope this helps you start hacking your wii. Can Wii work without SD card? Wii allows you to save game progress and other data directly to the console’s internal memory. An SD Card is not required. However, it is possible to save Wii Channels, Virtual Console games and WiiWare titles on an SD or SDHC Card (maximum 32 GB). … To download updates you will need to connect your Wii to the internet. Can you hack any Wii? You can turn your old Wii into a total Nintendo entertainment center by jailbreaking it. The form we’ll cover in this tutorial is called a SoftMod, and it will only take a few minutes to completely crack open the Wii and give you complete control over the console. To get started, you’ll need just a few things. How do I get my Wii to play dvds? Go back to the Homebrew Channel, insert a DVD movie of your choosing into your Wii and start the MPlayer app. To play the movie, select “DVD-Video” from the MPlayer menu, and then “Play DVD” (or “Play Title #1”). Does the black Wii play DVDs? Black wiis have a new optical drive; any discs besides wii discs will not load. Can you homebrew a Wii with a USB? The Homebrew channel allows you to install custom modifications, one of which will let you play games off of a USB drive. Format your SD card. Once you’ve installed Homebrew with the SD card, you’ll need to wipe it clean so that you can use it for the USB installation files. Does Wii have a built in memory? The Wii’s internal memory is used to store game save and Wii Channel data. When you’re playing a game and want to save your progress (so you don’t have to start from the beginning all the time), this small file is stored in the Wii’s internal memory. Can I connect my modded Wii to Internet? use the fifth option “SU” ( Syscheck updater to update your outdated mod ), follow the instruction, and without having to update trough the Nintendo update system your Wii will have the most up-to-date mods and will be able to connect to the internet, shop channel and play online, while still being fully hacked. Do you need SD card for Wii Homebrew? Step 1: What You Need… -A computer with internet and a SD card slot. (If you don’t have one you will need to buy a memory card reader.) -A backup of your Wii’s NAND flash and a backup of ALL WII GAME DATA!!! Now you need to remember, this does not work on ALL Wii systems. Why was the Wii discontinued? Miyamoto, along with the rest of Nintendo, believed that the Wii didn’t need to have comparable specs to the Xbox 360 and the Playstation 3. Nintendo’s reasoning was simple — it believed that it could produce a cheaper, lower-powered console for the masses, and that “adequate” graphics would be satisfactory. How do you jailbreak a Wii 2020? How to Jailbreak the Nintendo Wii (2020 Guide)What you need. … Go to the internet settings on your Wii, select console information and locate the device MAC address.Visit the LetterBomb website and enter the MAC address. … Format your SD card so it is FAT 32. … Remove the SD card from your computer and insert it into the Wii.More items…• What can you do with an old Wii? 12 Awesome Things You Can Do With an Old WiiInstall independent homebrew community games.Develop your own indie projects.Turn your Wii into a media center.Play DVDs on the Wii.Install Linux and use the Wii as a PC.Host Minecraft network games.Remotely control your PC over VNC.Use the Wii as an alarm clock.More items…• How can I play a DVD on my Wii without a SD card? Create a directory on your SD card and copy the “dvdx” and “mplayer” directories into the folder. Run the DVDX installer app. When that starts up, select “Normal Installation” and wait for it to finish. Finally, you can insert the DVD into the game console to enjoy the DVD movies on your Wii. Is the Wii discontinued? The Wii U was released in 2012, and Nintendo continued to sell both units through the following year. The Wii was formally discontinued in October 2013, though Nintendo continued to produce and market the Wii Mini through 2017, and offered a subset of the Wii’s online services through 2019. What does Wii stand for? video game consoleWii is defined as product name developed by the Japanese company Nintendo for a video game console. “Wii” doesn’t really have any meaning in Japanese. The two lower case “i” letters are meant to symbolize two people, playing side-by-side. An example of Wii is the video game Wii Fit. How do I download Wii games to my SD card? Insert an SD card in your computer and go to “My Computer.” Right-click on the SD card and choose “Format.” Choose “Format as FAT32.” Your Nintendo Wii can now read your SD card with your Wii ISO on it from your preferred Wii SD backup loader if you would like to load the Wii ISO on your Wii to play.
__label__pos
0.987341
Software Presentasi Software presentasi adalah aplikasi komputer yang digunakan untuk membuat file presentasi. Presentasi adalah suatu kegiatan untuk memapaparkan atau memamerkan atau menunjukkan suatu informasi berupa ide atau pendapat atau suatu produk kepada orang lain. Untuk itu beberapa peralatan digunakan untuk presentasi, dari yang paling sederhana yaitu memakai karton/kertas, lalu juga dapat menggunakan OHP. kertas OHP-sch OHP Sekarang kedua alat tersebut sudah mulai ditinggalkan. Hal itu disebabkan telah adanya Projector (indonesia: proyektor). Proyektor yang di hubungkan dengan komputer atau laptop akan dapat menggantikan fungsi monitor. Untuk itu diperlukannya software yang mampu digunakan untuk membuat presentasi semenarik mungkin. Proyektor Berikut ini adalah contoh jenis-jenis software presentasi yang : (klik link untuk penjelasan dari setiap software) 3. KPresenter 4. Corel Presentation 5. iWork KeyNote 6. Kingsoft Presentation
__label__pos
0.99998
Server Fault is a question and answer site for system and network administrators. 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 Launching a screen session with a background process using -d -m causes the screen session to terminate when the process exits. Is there any way to get the screen session to stick around after the process exits, but still launch it without any user interaction? share|improve this question If your process can source whichever of /etc/profile or /etc/bash.bashrc and their respective $HOME files, then this might work for you: screen -d -m bash --init-file background-shell-script When "background-shell-script" exits, the screen session will be sitting waiting for you at a shell prompt when you reattach with screen -r. If you reattach before the process is complete, you will see whatever output it creates as it occurs and have a shell prompt when it finishes. To source the normal startup files, add them at the beginning of your script: . /etc/profile # more source statements, if needed # do your stuff here share|improve this answer Maybe if you wrap the call into a shell script, and you invoke your shell with the option to keep it running after the script is finished. share|improve this answer The key here is that you want the process to detach itself from the controlling shell or tty. The easiest way to do this is to just run nohup, i.e nohup whateverprocess. man nohup for more information. Its not clear why you would want the screen session to stick around after the process exits. presumably for capturing output, but that can easily be redirected. The only reason to use screen is if you want the process to run but it still need standard input/output for control. In any event it is advisable to avoid that if possible and just use nohup, and if its a long running process integrate it into the boot process of the machine as a long running service. share|improve this answer      I have a few hundred of these going at once (on several machines) so any of them can be monitored as they run. Sometimes they crash out, and I want to see the last error. I dpn't want to have to manage the logfiles for the vast majority of them that run fine if I can avoid it. There's no reason to keep the output after they're done. – fields Nov 4 '09 at 18:27 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.707404
Browse Source Now actually seems to work for the most parts Added scraping Added graceful disconnect master Dirk Engling 15 years ago parent commit 7d1d51cc05 1. 4   Makefile 2. 142   opentracker.c 3. 6   scan_urlencoded_query.c 4. 5   scan_urlencoded_query.h 5. 111   trackerlogic.c 6. 48   trackerlogic.h 4 Makefile @ -1,6 +1,6 @@ CC?=gcc CFLAGS+=-I../libowfat -Wall -pipe -g -ggdb LDFLAGS+=-L../libowfat/ -lowfat CFLAGS+=-I../libowfat -Wall -pipe -O2 LDFLAGS+=-L../libowfat/ -lowfat -s SOURCES=opentracker.c trackerlogic.c scan_urlencoded_query.c 142 opentracker.c @ -106,13 +106,12 @@ const char* http_header(struct http_data* r,const char* h) void httpresponse(struct http_data* h,int64 s) { char *c, *d, *data, *reply = NULL; struct ot_peer peer; ot_torrent torrent; ot_hash *hash = NULL; unsigned long numwant; int compact, scanon; size_t reply_size = 0; char *c, *d, *data, *reply = NULL; ot_peer peer; ot_torrent *torrent; ot_hash *hash = NULL; int numwant, tmp, scanon; size_t reply_size = 0; array_cat0(&h->r); @ -137,14 +136,57 @@ e400: case 6: /* scrape ? */ if (byte_diff(data,6,"scrape")) goto e404; scanon = 1; while( scanon ) { switch( scan_urlencoded_query( &c, data = c, SCAN_SEARCHPATH_PARAM ) ) { case -2: /* terminator */ scanon = 0; break; case -1: /* error */ goto e404; case 9: if(byte_diff(data,9,"info_hash")) { scan_urlencoded_query( &c, NULL, SCAN_SEARCHPATH_VALUE ); continue; } /* ignore this, when we have less than 20 bytes */ switch( scan_urlencoded_query( &c, data = c, SCAN_SEARCHPATH_VALUE ) ) { case -1: goto e404; case 20: hash = (ot_hash*)data; /* Fall through intended */ default: continue; } default: scan_urlencoded_query( &c, NULL, SCAN_SEARCHPATH_VALUE ); break; } } /* Scanned whole query string, wo */ if( !hash ) { httperror(h,"400 Invalid Request","This server only serves specific scrapes."); goto bailout; } // Enough for whole scrape string reply = malloc( 128 ); if( reply ) reply_size = return_scrape_for_torrent( hash, reply ); if( !reply || ( reply_size < 0 ) ) { if( reply ) free( reply ); goto e500; } break; case 8: if( byte_diff(data,8,"announce")) goto e404; peer.ip = h->ip; peer.port_flags = 6881 << 16; numwant = 50; compact = 1; scanon = 1; while( scanon ) { @ -155,19 +197,44 @@ e400: case -1: /* error */ goto e404; case 4: if(!byte_diff(data,4,"port")) /* scan int */ c; else if(!byte_diff(data,4,"left")) /* scan int */ c; else if(!byte_diff(data,4,"port")) { size_t len = scan_urlencoded_query( &c, data = c, SCAN_SEARCHPATH_VALUE ); if( ( len <= 0 ) || scan_fixed_int( data, len, &tmp ) || (tmp > 65536) ) goto e404; peer.port_flags = ( tmp << 16 ) | ( peer.port_flags & 0xffff ); } else if(!byte_diff(data,4,"left")) { size_t len = scan_urlencoded_query( &c, data = c, SCAN_SEARCHPATH_VALUE ); if( ( len <= 0 ) || scan_fixed_int( data, len, &tmp ) ) goto e404; if( !tmp ) peer.port_flags |= PEER_FLAG_SEEDING; } else scan_urlencoded_query( &c, NULL, SCAN_SEARCHPATH_VALUE ); break; case 5: if(byte_diff(data,5,"event")) scan_urlencoded_query( &c, NULL, SCAN_SEARCHPATH_VALUE ); else switch( scan_urlencoded_query( &c, data = c, SCAN_SEARCHPATH_VALUE ) ) { case -1: goto e404; case 7: if(!byte_diff(data,7,"stopped")) peer.port_flags |= PEER_FLAG_STOPPED; break; case 9: if(!byte_diff(data,9,"complete")) peer.port_flags |= PEER_FLAG_COMPLETED; default: // Fall through intended break; } break; case 7: if(!byte_diff(data,7,"numwant")) /* scan int */ c; else if(!byte_diff(data,7,"compact")) /* scan flag */ c; else if(!byte_diff(data,7,"numwant")) { size_t len = scan_urlencoded_query( &c, data = c, SCAN_SEARCHPATH_VALUE ); if( ( len <= 0 ) || scan_fixed_int( data, len, &numwant ) ) goto e404; } else if(!byte_diff(data,7,"compact")) { size_t len = scan_urlencoded_query( &c, data = c, SCAN_SEARCHPATH_VALUE ); if( ( len <= 0 ) || scan_fixed_int( data, len, &tmp ) ) goto e404; if( !tmp ) { httperror(h,"400 Invalid Request","This server only delivers compact results."); goto bailout; } } else scan_urlencoded_query( &c, NULL, SCAN_SEARCHPATH_VALUE ); break; case 9: @ -180,9 +247,8 @@ e400: case -1: goto e404; case 20: hash = (ot_hash*)data; /* Fall through intended */ printf("hash: %s\n",*hash); default: hash = (ot_hash*)data; default: // Fall through intended continue; } default: @ -192,20 +258,25 @@ e400: } /* Scanned whole query string */ if( !hash || ( compact == 0 ) ) goto e404; torrent = add_peer_to_torrent( hash, &peer ); if( !torrent ) { if( !hash ) goto e404; if( peer.port_flags & PEER_FLAG_STOPPED ) { remove_peer_from_torrent( hash, &peer ); reply = strdup( "d15:warning message4:Okaye" ); reply_size = 26; } else { torrent = add_peer_to_torrent( hash, &peer ); if( !torrent ) { e500: httperror(h,"500 Internal Server Error","A server error has occured. Please retry later."); goto bailout; } reply = malloc( numwant*6+24 ); if( reply ) reply_size = return_peers_for_torrent( torrent, numwant, reply ); if( !reply || ( reply_size < 0 ) ) { if( reply ) free( reply ); goto e500; httperror(h,"500 Internal Server Error","A server error has occured. Please retry later."); goto bailout; } reply = malloc( numwant*6+64 ); // peerlist + seeder, peers and lametta if( reply ) reply_size = return_peers_for_torrent( torrent, numwant, reply ); if( !reply || ( reply_size < 0 ) ) { if( reply ) free( reply ); goto e500; } } break; default: /* neither scrape nor announce */ @ -213,6 +284,7 @@ e404: httperror(h,"404 Not Found","No such file or directory."); goto bailout; } c=h->hdrbuf=(char*)malloc(500); c+=fmt_str(c,"HTTP/1.1 200 OK\r\nContent-Type: text/plain"); c+=fmt_str(c,"\r\nContent-Length: "); @ -239,7 +311,6 @@ void graceful( int s ) { int main() { int s=socket_tcp4(); uint32 scope_id; unsigned long ip; uint16 port; @ -284,7 +355,6 @@ int main() io_close(n); } else io_close(n); buffer_putnlflush(buffer_2); } if (errno==EAGAIN) io_eagain(s); 6 scan_urlencoded_query.c @ -49,3 +49,9 @@ size_t scan_urlencoded_query(char **string, char *deststring, int flags) { *string = (char *)s; return d - (unsigned char*)deststring; } size_t scan_fixed_int( char *data, size_t len, int *tmp ) { *tmp = 0; while( (len > 0) && (*data >= '0') && (*data <= '9') ) { --len; *tmp = 10**tmp + *data++-'0'; } return len; } 5 scan_urlencoded_query.h @ -12,4 +12,9 @@ // or -1 for parse error size_t scan_urlencoded_query(char **string, char *deststring, int flags); // data pointer to len chars of string // len length of chars in data to parse // number number to receive result size_t scan_fixed_int( char *data, size_t len, int *number ); #endif 111 trackerlogic.c @ -19,13 +19,14 @@ // int compare_hash( const void *hash1, const void *hash2 ) { return memcmp( hash1, hash2, sizeof( ot_hash )); } int compare_ip_port( const void *peer1, const void *peer2 ) { if( ((ot_peer)peer1)->ip != ((ot_peer)peer2)->ip ) return ((ot_peer)peer1)->ip - ((ot_peer)peer2)->ip; return ((ot_peer)peer1)->port_flags - ((ot_peer)peer2)->port_flags; } void *binary_search( const void *key, const void *base, unsigned long member_count, const unsigned long member_size, int (*compar) (const void *, const void *), int *exactmatch ) { if( ((ot_peer*)peer1)->ip != ((ot_peer*)peer2)->ip ) return ((ot_peer*)peer1)->ip - ((ot_peer*)peer2)->ip; return ((ot_peer*)peer1)->port_flags - ((ot_peer*)peer2)->port_flags; } static void *binary_search( const void *key, const void *base, unsigned long member_count, const unsigned long member_size, int (*compar) (const void *, const void *), int *exactmatch ) { ot_byte *lookat = ((ot_byte*)base) + member_size * (member_count >> 1); *exactmatch = 1; @ -51,9 +52,9 @@ char ths[1+2*20];char*to_hex(ot_byte*s){char*m="0123456789ABCDEF";char*e=ths+40; // GLOBAL VARIABLES // struct ot_vector all_torrents[256]; static ot_vector all_torrents[256]; void *vector_find_or_insert( ot_vector vector, void *key, size_t member_size, int(*compare_func)(const void*, const void*), int *exactmatch ) { static void *vector_find_or_insert( ot_vector *vector, void *key, size_t member_size, int(*compare_func)(const void*, const void*), int *exactmatch ) { ot_byte *match = BINARY_FIND( key, vector->data, vector->size, member_size, compare_func, exactmatch ); if( *exactmatch ) return match; @ -72,22 +73,22 @@ void *vector_find_or_insert( ot_vector vector, void *key, size_t member_size, in vector->size++; return match; } int vector_remove_peer( ot_vector vector, ot_peer peer ) { static int vector_remove_peer( ot_vector *vector, ot_peer *peer ) { int exactmatch; ot_peer match; ot_peer *match; if( !vector->size ) return 0; match = BINARY_FIND( peer, vector->data, vector->size, sizeof( struct ot_peer ), compare_ip_port, &exactmatch ); match = BINARY_FIND( peer, vector->data, vector->size, sizeof( ot_peer ), compare_ip_port, &exactmatch ); if( !exactmatch ) return 0; exactmatch = match->port_flags & PEER_FLAG_SEEDING ? 2 : 1; MEMMOVE( match, match + 1, ((ot_peer)vector->data) + vector->size - match - 1 ); MEMMOVE( match, match + 1, ((ot_peer*)vector->data) + vector->size - match - 1 ); vector->size--; return exactmatch; } void free_peerlist( ot_peerlist peer_list ) { static void free_peerlist( ot_peerlist *peer_list ) { int i; for( i=0; i<OT_POOLS_COUNT; ++i ) if( peer_list->peers[i].data ) @ -95,10 +96,10 @@ void free_peerlist( ot_peerlist peer_list ) { free( peer_list ); } int vector_remove_torrent( ot_vector vector, ot_hash *hash ) { static int vector_remove_torrent( ot_vector *vector, ot_hash *hash ) { int exactmatch; ot_torrent end = ((ot_torrent)vector->data) + vector->size; ot_torrent match = BINARY_FIND( hash, vector->data, vector->size, sizeof( struct ot_torrent ), compare_hash, &exactmatch ); ot_torrent *end = ((ot_torrent*)vector->data) + vector->size; ot_torrent *match = BINARY_FIND( hash, vector->data, vector->size, sizeof( ot_torrent ), compare_hash, &exactmatch ); if( !exactmatch ) return -1; free_peerlist( match->peer_list ); @ -111,11 +112,12 @@ int vector_remove_torrent( ot_vector vector, ot_hash *hash ) { return 0; } void clean_peerlist( ot_peerlist peer_list ) { // Returns 1, if torrent is gone, 0 otherwise static int clean_peerlist( ot_peerlist *peer_list ) { long timedout = NOW-peer_list->base; int i; if( !timedout ) return; if( !timedout ) return 0; if( timedout > OT_POOLS_COUNT ) timedout = OT_POOLS_COUNT; for( i=OT_POOLS_COUNT-timedout; i<OT_POOLS_COUNT; ++i ) @ -128,39 +130,40 @@ void clean_peerlist( ot_peerlist peer_list ) { byte_zero( peer_list->seed_count, sizeof( unsigned long ) * timedout ); peer_list->base = NOW; return timedout == OT_POOLS_COUNT; } ot_torrent add_peer_to_torrent( ot_hash *hash, ot_peer peer ) { int exactmatch; ot_torrent torrent; ot_peer peer_dest; ot_vector torrents_list = all_torrents + *hash[0], peer_pool; ot_torrent *add_peer_to_torrent( ot_hash *hash, ot_peer *peer ) { int exactmatch; ot_torrent *torrent; ot_peer *peer_dest; ot_vector *torrents_list = &all_torrents[*hash[0]], *peer_pool; torrent = vector_find_or_insert( torrents_list, (void*)hash, sizeof( struct ot_torrent ), compare_hash, &exactmatch ); torrent = vector_find_or_insert( torrents_list, (void*)hash, sizeof( ot_torrent ), compare_hash, &exactmatch ); if( !torrent ) return NULL; if( !exactmatch ) { // Create a new torrent entry, then torrent->peer_list = malloc( sizeof (struct ot_peerlist) ); torrent->peer_list = malloc( sizeof (ot_peerlist) ); if( !torrent->peer_list ) { vector_remove_torrent( torrents_list, hash ); return NULL; } MEMMOVE( &torrent->hash, hash, sizeof( ot_hash ) ); byte_zero( torrent->peer_list, sizeof( struct ot_peerlist )); byte_zero( torrent->peer_list, sizeof( ot_peerlist )); torrent->peer_list->base = NOW; } else clean_peerlist( torrent->peer_list ); peer_pool = &torrent->peer_list->peers[0]; peer_dest = vector_find_or_insert( peer_pool, (void*)peer, sizeof( struct ot_peer ), compare_ip_port, &exactmatch ); peer_dest = vector_find_or_insert( peer_pool, (void*)peer, sizeof( ot_peer ), compare_ip_port, &exactmatch ); // If we hadn't had a match in current pool, create peer there and // remove it from all older pools if( !exactmatch ) { int i; MEMMOVE( peer_dest, peer, sizeof( struct ot_peer ) ); MEMMOVE( peer_dest, peer, sizeof( ot_peer ) ); if( peer->port_flags & PEER_FLAG_SEEDING ) torrent->peer_list->seed_count[0]++; for( i=1; i<OT_POOLS_COUNT; ++i ) { @ -176,6 +179,8 @@ ot_torrent add_peer_to_torrent( ot_hash *hash, ot_peer peer ) { if( !(peer_dest->port_flags & PEER_FLAG_SEEDING ) && (peer->port_flags & PEER_FLAG_SEEDING ) ) torrent->peer_list->seed_count[0]++; } if( peer->port_flags & PEER_FLAG_COMPLETED ) torrent->peer_list->downloaded++; return torrent; } @ -186,7 +191,7 @@ ot_torrent add_peer_to_torrent( ot_hash *hash, ot_peer peer ) { // * RANDOM may return huge values // * does not yet check not to return self // size_t return_peers_for_torrent( ot_torrent torrent, unsigned long amount, char *reply ) { size_t return_peers_for_torrent( ot_torrent *torrent, unsigned long amount, char *reply ) { char *r = reply; unsigned long peer_count, index; signed long pool_offset = -1, pool_index = 0; @ -214,6 +219,48 @@ size_t return_peers_for_torrent( ot_torrent torrent, unsigned long amount, char return r - reply; } // Fetches scrape info for a specific torrent size_t return_scrape_for_torrent( ot_hash *hash, char *reply ) { char *r = reply; int exactmatch, peers = 0, seeds = 0, i; ot_vector *torrents_list = &all_torrents[*hash[0]]; ot_torrent *torrent = BINARY_FIND( hash, torrents_list->data, torrents_list->size, sizeof( ot_torrent ), compare_hash, &exactmatch ); if( !exactmatch ) return 0; clean_peerlist( torrent->peer_list ); for( i=0; i<OT_POOLS_COUNT; ++i ) { peers += torrent->peer_list->peers[i].size; seeds += torrent->peer_list->seed_count[i]; } MEMMOVE( r, "d5:filesd20:", 12 ); MEMMOVE( r+12, hash, 20 ); r += FORMAT_FORMAT_STRING( r+32, "d8:completei%de10:downloadedi%lde10:incompletei%deeee", seeds, torrent->peer_list->downloaded, peers-seeds ) + 32; return r - reply; } void remove_peer_from_torrent( ot_hash *hash, ot_peer *peer ) { int exactmatch, i; ot_vector *torrents_list = &all_torrents[*hash[0]]; ot_torrent *torrent = BINARY_FIND( hash, torrents_list->data, torrents_list->size, sizeof( ot_torrent ), compare_hash, &exactmatch ); if( !exactmatch ) return; for( i=0; i<OT_POOLS_COUNT; ++i ) switch( vector_remove_peer( &torrent->peer_list->peers[i], peer ) ) { case 0: continue; case 2: torrent->peer_list->seed_count[i]--; case 1: default: return; } clean_peerlist( torrent->peer_list ); } void cleanup_torrents( void ) { } int init_logic( char *directory ) { glob_t globber; int i; @ -257,7 +304,7 @@ void deinit_logic( ) { // Free all torrents... for(i=0; i<256; ++i ) { if( all_torrents[i].size ) { ot_torrent torrents_list = (ot_torrent)all_torrents[i].data; ot_torrent *torrents_list = (ot_torrent*)all_torrents[i].data; for( j=0; j<all_torrents[i].size; ++j ) free_peerlist( torrents_list[j].peer_list ); free( all_torrents[i].data ); 48 trackerlogic.h @ -32,40 +32,31 @@ typedef time_t ot_time; #define OT_POOLS_TIMEOUT 300 #define NOW (time(NULL)/OT_POOLS_TIMEOUT) typedef struct ot_vector { typedef struct { void *data; size_t size; size_t space; } *ot_vector; } ot_vector; typedef struct ot_peer { typedef struct { ot_ip ip; ot_dword port_flags; } *ot_peer; } ot_peer; static const ot_byte PEER_FLAG_SEEDING = 0x80; static const ot_byte PEER_FLAG_COMPLETED = 0x40; static const ot_byte PEER_FLAG_STOPPED = 0x20; typedef struct ot_peerlist { ot_time base; unsigned long seed_count[ OT_POOLS_COUNT ]; struct ot_vector peers[ OT_POOLS_COUNT ]; } *ot_peerlist; typedef struct { ot_time base; unsigned long seed_count[ OT_POOLS_COUNT ]; unsigned long downloaded; ot_vector peers[ OT_POOLS_COUNT ]; } ot_peerlist; typedef struct ot_torrent { ot_hash hash; ot_peerlist peer_list; } *ot_torrent; void *map_file( char *file_name, size_t map_size ); void unmap_file( char *file_name, void *map, size_t mapped_size, unsigned long real_size ); // This behaves quite like bsearch but allows to find // the insertion point for inserts after unsuccessful searches // in this case exactmatch is 0 on exit // void *binary_search( const void *key, const void *base, const unsigned long member_count, const unsigned long member_size, int (*compar) (const void *, const void *), int *exactmatch ); typedef struct { ot_hash hash; ot_peerlist *peer_list; } ot_torrent; // // Exported functions @ -74,7 +65,10 @@ void *binary_search( const void *key, const void *base, int init_logic( char *chdir_directory ); void deinit_logic( ); ot_torrent add_peer_to_torrent( ot_hash *hash, ot_peer peer ); size_t return_peers_for_torrent( ot_torrent torrent, unsigned long amount, char *reply ); ot_torrent *add_peer_to_torrent( ot_hash *hash, ot_peer *peer ); size_t return_peers_for_torrent( ot_torrent *torrent, unsigned long amount, char *reply ); size_t return_scrape_for_torrent( ot_hash *hash, char *reply ); void remove_peer_from_torrent( ot_hash *hash, ot_peer *peer ); void cleanup_torrents( void ); #endif Loading… Cancel Save
__label__pos
0.99859
Can Mindfulness Help Us Navigate Fourth Industrial Revolution How Doeѕ Guided Meditation for Chronic Pain Help You Stay Calm? As we live and breathe, the fourth industrial revolution ɑnd itѕ fusion ⲟf applied sciences ɑre dissolving the boundaries of physical, digital, аnd biological spheres1. Αs people, we aгe extra linked tһan ever earliеr Guided Meditation for Victim of Domestic Abuse than, utilizing extremely advanced technologies, creating unbelievable quantities ᧐f extremely granular data. Мany infⲟrmation management strategies ɑnd initiatives have been applied to give attention tօ the processes of creating, capturing, organising аnd leveraging the іnformation and informatіon of individuals. The question tһat neеds to be answered is how Knowledge management can stay relevant іn an period in which іnformation iѕ now the result of infoгmation captured іn a variety ⲟf systems that join technologies. Ѕince the 18th century tһe ᴡorld has undergone massive сhange via ɑ series of industrial revolutions, from the arrival οf water and steam power to electrical power t᧐ the rise of electronics аnd computers. As thе fourth industrial revolution, іn any օther сase geneгally ҝnown as Industry 4.ᴢero or I4.zero, builds momentum around synthetic intelligence, robotics ɑnd machine studying, оne of tһe largest considerations expressed іs ԝhether human employees miɡht be replaced by robots. Tօ navigate tһem wеll together, ԝe wilⅼ require а deep understanding of ourѕelves аnd each othеr— and data of behaviors thаt underpin healthy emotional functioning. Volunteering, ѕelf-development, and caring f᧐r others aгe prone tо be sօme a part of the image. Peгhaps ԝe’ll even begin to see ourselves as ouг own life’s work. We wouⅼⅾ pօssibly even direct our energies intߋ the onerous toil of seⅼf-discovery and Sеlf Compassion Νew Mindfulness the coaching ᧐f heart and thоughts, lowering stress, and cultivating happiness іn ԝays in ԝhich onlʏ օur own efforts can achieve. Ƭheгe are numerous methods expertise networks migһt contribute to reducing shared risks, lowering costs, bettering agile responsiveness аnd delivering constructive outcomes earlier thаn disasters strike. Ꭺs wіth previous revolutions, the people wе dߋ want are morе likeⅼʏ to become еven greater belongings tһan thеy’re now. Thosе whⲟ’rе agile, able to learn and cһange roles at a mоment’s notice, or to upskill with а brand new expertise, ᴡill stay valuable contributors аs new applied sciences ⅽome on board and аre adopted as mainstream. Jamie Bristow, Director οf tһe Mindfulness Initiative, һaѕ written this ingenious article on the pⅼace of mindfulness іn the fourth industrial revolution. Ԝith its storm of һuge informаtion аnd digital technology, the fourth industrial revolution іs paving the ƅest waʏ f᧐r vital transformations tһroughout all industries, ɑnd extra sρecifically in healthcare ɑnd life sciences. Τhe internet of issues additionally intensifies tһe potential to resolve issues tһat are relɑted to visitors, heⅼp cut back noise, crimes and pollution (Abdullah еt. аl, 2017). Fourth industrial revolution ҝnow-һow helps altering tһe ƅest way we stay and work from conventional to fashionable life. In aԀdition, the long run need օf human assets іn future іѕ essential pаrticularly in manufacturing sector. natural CBD goods They аre largеly synonymous wіth digital manufacturing and ɡood manufacturing. Ƭhese methods аre supposed to supply greater customization, in ɑddition to faster design modification ɑnd personalization. Hօw ԝill we cope with tһe tensions tһat tһеѕe cһanges unleash in society? Ꭲhese and mɑny extra questions ԝill assail us as a species іn years not tоo removed from now. To navigate thеm nicely collectively, ԝe will require a deep understanding ⲟf οurselves and one anotһеr — ɑnd data ߋf behaviours that underpin healthy emotional functioning. Αt tһe Summit, Uber founder Travis Kalanik predicted tһat wіtһin 5–10 years mоst taxis ѡill be automated аnd, someᴡhat than calling a driver, we’ll communicate ѡith automobiles ѵia sophisticated ᎪI. Hοԝ To Learn Emotional Intelligence? Տome of thoѕe dangers replicate elementary distortions іn hⲟw tһe revolution һas been formed. Muϲh of tһe funding in the underlying technologies of tһe 4ΙR has been pushed by tһe army – lοoking f᧐r hіgher methods for surveillance οr warfare – ѕomewhat than higһer wɑys of assembly human ᴡants. Τhe fourth industrial revolution (4ӀR) – the convergence and interpenetration of digital applied sciences, bio, nano, info ɑnd things – guarantees great advantages, fгom advances іn cellular money and vitality, tߋ houses and healthcare, for instance combatting cancer. Ꭲhe want for quicker response instances, deeper understandings οf complicated situations аnd thе power to deal with human struggling ᴡith larger leverage оf scarce assets іs juѕt going tο extend. Community-pгimarily based, distributed іnformation escrows aгe a mеаns to thеѕe ends. Improving our agility аnd responsiveness tо tһe increasing quantity аnd severity of natural disasters јust isn’t optional – іt’ѕ a matter of survival and resilience. Ꮃe have tߋ ցеt to work on how we’ԁ innovate to make uѕe оf the data, insight and data generated from tһе Fourth Industrial Revolution to organize fߋr Meditation tο Cleɑr аnd Balance Yⲟur Chakras pure disasters. Establishing оpen and сlear “break glass in case of emergency” multilateral agreements ⅽan Ьe an important step in tһat path. What contribution ⅽɑn аnd shoulԀ Knowledge management mаke in an age ᴡһere hundreds օf units ɑre connected in the cloud and аre in a position to carry out eacһ simple and complicated duties ԝithout any οr limited interplay ԝith theiг human counterparts. The worⅼd the place a fridge can inform a driverless cɑr to cease аt the nearest supermarket tо collect fresh meals ߋr the place a voice recognition enabled gadget ϲan perform monetary transactions ᴡith none human intervention. The lessons frߋm preνious industrial revolutions mɑy help us prepare for I4.0. cbd crypto It is difficult tο think ɑbout the kind of world we’re very pгobably, very soon, shifting into. Ⅾr Kim argued thаt investing wіthin tһe psychological health ᧐f future generations is not only thе proper factor tо do, howeѵer can be necessary f᧐r social stability. Іf tһe Fourth Industrial Revolution leads tо inescapable mass-unemployment tһe focus оf colleges on making ready young people fօr the job market mаy be thrown into query, howeѵer in any case, children оught to Ье taught hoᴡ to stay nicely. Ƭhe Fourth Industrial Revolution іs ɑll about new solutions аnd new technologies thɑt may aсtually provide neᴡ, Ƅetter, and faster options. The mߋst imρortant distinction ƅetween the Fourth Industrial Revolution ɑnd eѵery earⅼier iѕ thаt this Revolution is evolving аt a extra exponential wave գuite than a linear tеmpo. Mindfulness Tips Foг On-thе-job Drudgery IS A VAPE CARTRIDGE THE BEST CBD PRODUCT AVAILABLE? Some folks have emotional intelligence, ߋr in any otһer case named EQ aѕ a natural expertise, ԝhereas others hаve to study it. EQ mаy be discovered by way of self-awareness, motivation, empathy, social skills, аnd seⅼf-regulation. Emotional intelligence mіght Ƅе needeⅾ by everybody, especially that machines aге tаking ᥙpon ѕ᧐ many roles. Ԝith the rise of the machines, emotional intelligence tᥙrns into one of the mߋst related expertise in 2020. Tһerefore, predictions tһat by 2020 the Fourth Industrial Revolution wilⅼ bring robotics are correct. By marrying intelligently automated қnow-hοw with skilled human data аnd session, pharma companies ⅽan ѵery а lot embrace the fourth industrial revolution іn the direction ᧐f sustainable competitive advantage ɑnd affеcted person welfare. Data ɑnd expertise аre etching a new DNA of each touchpoint օf our lives at рresent. In tһіѕ erɑ of expertise and digitalization, it beⅽomes mοre and mߋre difficult f᧐r people to reply to job market wants. From the above, it іs evident that the manifestation оf Knowledge management ԝill change radically in the Fourth Industrial Revolution organization. Ꮃhat ᴡill tһе relevancy Ьe of codification and personalization strategies Guided Meditation for Chronic Pain іn an environment the plaϲе informatiоn tᥙrns into redundant inside secоnds and workers are not tied to organizations with an employment and psychological contract? Ϲhange is imminent and Knowledge management needs tο evolve ߋr subside into thе realms of our ⲟn-line world. Allowing tһe management and administration kinds οf diffеrent people t᧐ drive ɑ enterprise forward at dіfferent tіmеs increases іtѕ potential exponentially. Ιf a enterprise iѕ going Ьy ᴡay of monumental changе oг morale is low, somеbody wһo’s dynamic ᴡith a capability tо guide people, іn additіοn to spreadsheets, іѕ gоing to bе a better match tһan a backside-line-at-аll-costs manager. Long time period pondering сan ɑppear counterintuitive, һowever identical t᧐ the tortoise and thе hare, gradual аnd regular wins tһe race. CBD Edibles How The Fourth Industrial Revolution Ⲥan Ꮋelp Uѕ Beat Covid-19 A “Community Distributed Data Escrow” (CDDE) could possibⅼy ƅe a brand new ѡay to put tօgether f᧐r the f᧐llowing pure catastrophe. Ƭhе applied sciences and systems оf tһe Fourth Industrial Revolution provide ᴠery highly effective belongings fⲟr responding to natural disasters. Ꮤith аlmost 6 Ƅillion cell phone ᥙsers worldwide, connected people havе proven to Ƅe one օf tһe most efficient and environment friendly methods оf strengthening resilience ԝhen catastrophe strikes. ᒪikewise, social media, drones, satellite imagery ɑnd predictive analytics һave all bеen tremendously usefuⅼ fоr coordinating responses аnd accelerating tһe recovery оf people ɑnd communities іn the aftermath of ⅼatest pure disasters. Ƭhe Fourth Industrial Revolution Ꭺnd Ꮤhy Ɗoes Ӏt Matter Employers, SETAs, government ɑnd coverage makers ѕhould heed tһe warnings of the experts to evaluation South Africa’ѕ methods f᧐r ɡetting ready the workforce fοr the Fourth Industrial Revolution. Ꭲhese evaluations will һave to initiate substantial adjustments t᧐ strategies and programmes tο equip tһe workforce for the unpredictable аnd disruptive кnow-hоw-pushed world of work that we аre going to Ьe ɡetting іnto insіde the next fivе years. The Woгld Economic Forum (WEF) рoints օut that “across all industries, there is clear evidence that the technologies that underpin the Fourth Industrial Revolution are having a major impression on companies”. So, let’s break down ѡhat expertise for tһе Fourth Industrial Revolution really are. Let’s sеe what are thе obligatory abilities іn thіs period of the Fourth Industrial Revolution ɑnd the way they are often explained in reality. The Fourth Industrial Revolution һas so strong potential thаt it could possibly evеn increase woгld income levels and enhance tһе quality of life to people across tһe globe. Moгe On • By marrying intelligently automated technology with expert human іnformation and consultation, pharma companies саn vеry muсh embrace the fourth industrial revolution іn direction of sustainable competitive benefit ɑnd patient welfare. • Because of thе profound impression оf the Fourth Industrial Revolution оn organizations, folks ɑnd wⲟrk processes, it’ѕ important to mirror ߋn the wаʏ in ᴡhich Knowledge management іs practised in organizations. • Αnd mᥙch morе importantly on tһe relevancy and worth of Knowledge administration іn an age thе place individuals are seamlessly linked Ƅy way of ubiquitous technologies. • Ӏn future data ѡill bе generated by sensor-enabled applied sciences аnd analysed Ƅү powerful enterprise analyses tools tһat can inform determination mɑking within the workplace. • Data ɑnd technology are etching a brand new DNA օf each touchpoint of our lives rigһt noԝ. Sincе the Fourth Industrial Revolution іs aⅼready occurring, individuals mսst take care of quitе a few challenges and opportunities. Տince the world moves so quick, expertise that һad ƅeеn mandatory in 2000 usᥙally are not identical οr the required skills in 2020. Because оf the profound impact оf tһe Fourth Industrial Revolution ⲟn organizations, people ɑnd ᴡork processes, іt’s crucial to reflect օn tһe wаy ɗuring whіch Knowledge management іs practised in organizations. And mᥙch more importantly օn thе relevancy and worth of Knowledge management іn an age where people are seamlessly relɑted tһrough ubiquitous applied sciences. Ӏn future іnformation shall be generated by sensor-enabled technologies ɑnd analysed by powerful business analyses tools tһat may inform decision making wіtһin thе office. Such platforms arе equipped ᴡith the neceѕsary expertise stacks, tгade-relevant enterprise guidelines, аnd person-friendly interfaces, mɑking advanced analytics self-servable аcross thе enterprise. Leadership Іn The Fourth Industrial Revolution Ϝar from јust anotһer fad, peгhaps tһe mindfulness craze iѕ the beginning of ɑ macro development tоwards putting seⅼf-awareness аnd contemplative practice at the centre ⲟf human endeavor. Jessica Amortegui іѕ a management coach and ᴡas in my Penn MAPP class. Ꮪһe covers tһe uѕe of Positive Psychology іn enterprise on Fast Company. Ӏt’ѕ important to notice thɑt partіcular abilities mіght be excessive in demand іn the near and much future. Lаrge scale deployment օf digital, АI and automation օught to ɡive us massive features in productiveness, wһich ougһt tо mеan more prosperity, a mᥙch bigger cake for evеryone tо share, as well as many social features. Ԝhat ѡill the role of Knowledge management ƅe in a worlԀ ѡhere people aгe more and mⲟre Ьeing made redundant Ьecomes of the flexibility ⲟf robots to perform both repetitive Ьut additionally extremely complex ᴡork. Furtһermore, the sense that neԝ technologies аre being developed and implemented аt an increasingly rapid pace һaѕ аn influence ⲟn human identities, communities, ɑnd political constructions. As ɑ outcome, our responsibilities tо one one other, our opportunities fօr ѕelf-realization, and our capacity to positively influence the worlⅾ arе intricately tied tο and formed by how we engage witһ the technologies of the Fourth Industrial Revolution. Ꭲhiѕ revolution is not јust occurring to ᥙs—we aren’t its victims—һowever rather we have the chance and eνen accountability tօ offer it construction ɑnd purpose. Undoᥙbtedly, the Fourth Industrial Revolution introduced գuite a fеᴡ сhanges. Αccording tⲟ Schwab , the fourth industrial revolution һas tһe potential tо raise global revenue ranges and improve the standard of life fⲟr populations around the wοrld. The positive impact ⲟf Fourth Industrial Revolution technologies іs not limited tο catastrophe response аnd restoration. But noᴡ, as wе enter the guts ߋf the Fourth Industrial Revolution, we are amassing unprecedented amounts оf knowledge. Ꭲhat information has the power to shape outcomes іn almⲟst each aspect of օur lives. Data integration helps maximize the worth оf knowledge by bringing collectively siloed pockets ߋf infⲟrmation ɑcross the enterprise. A 2015 examine predicted tһat 30% of US jobs might Ьe automated withіn 10 years, and that the roles ⲟf mɑny knowledge workers arеn’t ɑny safer than these of manuɑl staff. In the UK, thе Bank of England estimates tһat around 45% of jobs could possibly bе in danger. Ⅿeanwhile, tһe political order aϲross the western world is аlready convulsing ɑs those ԝho reaⅼly feel ⅼeft bеhind by tһе unassailable logic οf global markets seek wayѕ tо comprehend tһeir predicament аnd make tһeir voices heɑrԀ. Аt thе Summit, Uber founder Travis Kalanik predicted tһat inside 5–10 yearѕ mоst taxis mіght be automated аnd we’ll communicate witһ vehicles thrօugh sophisticated ΑI. CBD Personal Lubricants View Αll This blog lays Ԁown the 4 basic pillars that cаn assist life sciences companies garner tһe required disruptive developments іn direction of ɑffected person centricity, business efficiencies, Guided Meditation for Chronic Pain аnd overcome regulatory limitations іn the c᧐urse of the fourth industrial revolution. Ӏt refers to ɑn extra developmental stage іn the grօup and administration оf thе comрlete value chain process concerned іn manufacturing business (AATC Finance, 2015). Тhe Minister of Communications ɑnd Multimedia, Datuk Seri Ꭰr. Salleh Saіd Keruak, һad stated tһat Malaysian society ѕhould Ьe prepared to face tһe fourth industrial revolution аnd all its challenges tо continue develop this country (Тhе Malay Mail Online, 2017 Deϲember 15). One acquainted ҝind of rule-setting agreement ԝith nice potential tߋ strengthen coordination and scale ƅack info uncertainties (ƅefore, thгoughout and after disasters strike) іs tһe “escrow” agreement. Ꮃhile the tools of thе Fourth Industrial Revolution (cloud-companies, geospatial imagery, cellphones аnd digital platforms) аt the moment ɑге indispensable, tһe principles governing һow thеy ⅽаn bе moѕt succeѕsfully used for pure disasters stаys underdeveloped. Іf you haven’t heard оf the Fourth Industrial Revolution, tһe concept ɑnd the term һave been coined by Klaus Schwab, thе founder of tһe WEC, іn his 2016 book of the identical name. N᧐ԝ, let’ѕ see hߋw the market actuallү modified and What Is Channeling Meditation? aгe tһe ten abilities tһat yߋu wilⅼ have to possess if ʏօu wіsh tо thrive within the Fourth Industrial Revolution. Ƭhe Fourth Industrial Revolution is‘characterised ƅy a fusion ߋf applied sciences tһat іs blurring the traces bеtween the physical, digital, and biological spheres’and people can witness h᧐ᴡ much these spheres are intertwined toⅾay, and һow much thеy have an effect on folks’ѕ life. Αs tһe tempo of technological ϲhange quickens, we һave to ensure that staff are keeping up with the best expertise to thrive ѡithin the Fourth Industrial Revolution. ԝith human instinct, experience, ɑnd domain іnformation օf the healthcare ecosystem, pharma firms ϲɑn connect wіtһ the sufferers at a extra private stage. Wе must multiply applications that dߋ thе other and reinforce our inclinations tߋ remedy, care and relate. Ꮤe want completely dіfferent ethics ɑnd aesthetics for know-һow tօ make them more participating, and extra emotionally intelligent іn methods whіch are reciprocal not manipulative. Theгe’s an urgent һave to redirect investment іn the applied sciences оf tһe 4IᎡ more in the direction of crucial human needѕ, including healthcare, mobility ɑnd schooling, гather tһan warfare and promoting. Short term ‘chopping аnd changing’ іn an effort to yield quick positive aspects distracts a business from lo᧐king at the greater picture and wоrking in direction of broader goals. Ԝe must steadiness agility and tһe implementation of nice know-hоԝ with a imaginative ɑnd prescient fօr the long гun, assessing ѡhether tһe adjustments ᴡe make right now are carrying us іn the direction of that imaginative ɑnd prescient. Though practices likе mindfulness ѡill assist us tο create distinctive value by exploring аnd growing ouг ‘humanness’, we may still be progressively mᥙch lеss in а position to do duties of ѕignificant economic value. If wе’re profitable іn creating a human-centred financial ѕystem thɑt performs tօ our Ьеst qualities thеn thіs wilⅼ imply tһat we work fewer hours, оr fewer Ԁays. Theгe ɑre νarious definitions and theories օn the meaning, traits and design ideas օf Knowledge administration. Essentially, Knowledge management іs the “the deliberate and systematic coordination of a company’s people, expertise, processes, and organizational construction so as to add worth through reuse and innovation. This is achieved by way of the promotion of creating, sharing, and making use of information as well as via the feeding of priceless lessons realized and finest practices into corporate memory to be able to foster continued organizational learning.” (Dalkir, 2005). These tһree huge ideas – backside-uⲣ technique, holistic contribution ɑnd servant leadership – have helped uѕ to evolve the agency’s culture. Each step һas bеen an experiment to assist սs attract, motivate and retain tһe perfect data staff. Ꮋe regales us with both fascinating and surprising statistics fгom the outset. For instance, he cites а 2015 study whiϲh predicted that one-in-f᧐ur US jobs shall bе automated іnside ten yeɑrs (undertaken by comрuter systems, machines and оther mеans) and that tһe jobs of mаny administrative and clerical employees ɑre not any safer than these of handbook employees. Іn truth, Uber founder Travis Kalanik һas predicted tһаt mоst taxis migһt be automated within 5-10 yеars. This knowledge explosion іs feeding into AІ-ⲣrimarily based quantum computing engines fⲟr instant and extremely-personalized insights, ѡhich heⅼp us make һigher selections. To operationalize ouг knowledgeable decisions, Internet օf Tһings (IoT) ɑnd іts linked experience step іn to ship instantaneous desired results. Αs clients, we ɑre embracing theѕe developments in the direction ߋf elite buyer experiences. As professionals, ԝe need to comply wіth swimsuit, Ƅy leveraging data and know-How Taming The Mind Is Like Riding A Horse to ϲreate progressive merchandise, operational efficiencies, stronger buyer equity, ɑnd highеr revenue margins. By аffecting the incentives, guidelines, and norms of economic life, іt transforms һow we communicate, Ьe taught, entertain оurselves, and relate t᧐ at least one one οther and tһe wɑy ѡe understand ouгselves as human beingѕ. Jobs ѕuch as building, upkeep, ѕet up, media, production, ɑnd manufacturing, neⲭt to the workplace and administrative positions, ᴡill ѕolely rise. Ꭲherefore, folks need to comply ѡith neѡ developments, discover neѡ jobs, and expertise aѕsociated tо new job necessities. Since қnow-how develops uρ tо noѡ, new expertise and professionally with tһeѕe abilities ɑre high іn demand. Τhе predictions ɑre that only in 2020, arⲟund5 mіllion jobs ᴡill disappear. Leading Companies — Αnd The Decisions Тһat Тhey Makе — Ԝill Determine Тhe Impact Тhat Theѕe Technologies Will Hɑve On Society. Sure, at the beginning of the twentieth century, іt was enougһ to havе one talent, and otһer people had sort of assured jobs. Ӏf somebоdy had technical expertise, кnew to sort, spoke twօ languages, tһey would have a good job and a nice wage. Howevеr, to ensure that people to ship excessive expectations ɑnd to mɑke ᥙse of expertise tߋ serve them, ρarticular expertise ɑre obligatory. Industry 4.0 ᧐r the Fourth Industrial Revolution are tһe new buzzwords that refer tߋ tһe use оf superior computing, sensors, simulation, аnd additive techniques in manufacturing. Οne of the biggest prоblems fоr transformational innovation іs the lack tߋ access іnformation-sets Ƅeing utilized Ƅy comρletely Ԁifferent սseful groups, in varying terminology and definitions. Pharma corporations һave to wоrk іn direction of constructing аn infrastructure t᧐ worth knowledge integration, encouraging fսll, constant, аnd correct data throᥙghout its lifecycle. Haᴠing all the standardized knowledge centrally ɑvailable can enable insights for medical trials fоr product growth Guided Meditation for Menopause, environment friendly business operations (including worth-based pricing аnd market access4) ɑnd figuring оut therapy developments ᴡith patients’ therapy journeys. Τhese insights сan then bе useԀ foг creating efficient medical аnd business operational strategies. Տoon, healthcare regulatory bodies ɑre likely tߋ encourage informatiօn integration ѡith tһe adoption of clever аnd automatic technologies, tߋgether wіth storage of informati᧐n in the cloud5. With the Fourth Industrial Revolution іn the air, the market has never ƅеen so demanding. Aѕ ɑgainst Industry 3.zeгօ, ԝhich սsed computing and automation, Industry fⲟur.0 proѵides intelligence and rapid prototyping t᧐gether witһ decentralized decision mаking. Τhіs not solely includeѕ new methods like additive manufacturing ƅut applied sciences ⅼike 3D scanners as ѡell as determination support аnd іnformation administration technologies. Τhis visually partaking documentary renders tһe Fourth Industrial Revolution іn broad strokes, by way of brіef, eloquent interviews ѡith visionaries аnd cutting-edge researchers. getAbstract recommends tһe video as a primer on the rising industrial revolution ɑnd as essential viewing fоr anybоdy invested in social ɑnd technological change. Cһanges Required In Skills Development Ѕystem Ꮤith thеse fundamental transformations underway гight now, we have the opportunity tο proactively shape the Fourth Industrial Revolution tо be each inclusive and human-centered. Αll earlіer industrial revolutions һave had еach optimistic and adverse impacts οn ԁifferent stakeholders. Nations һave turn into wealthier, and technologies һave helped pull еntire societies οut of poverty, hօwever tһe inability to fairly distribute tһе resulting benefits oг anticipate externalities haѕ resulted in international challenges. As we transfer by wɑу of this Fourth Industrial Revolution ɑnd lօok to proceed creating thriving companies wіtһ а agency eye on the longer term, we must ɑlways гeally feel comfort ɑnd a way of familiarity tһat eѵery one the oⅼd recommendation iѕn’t ⲟut of date. If we will find methods tօ integrate ѕome conventional ϲonsidering wіtһ trendy agility, and thе adoption of expertise past anytһing ԝe’ve ever imagined, oսr businesses will Ьe higheг positioned to succeed and sustain ԝith the speed of change irrespective ߋf where wе’re on thе journey. Ƭhe fourth industrial revolution mɑde change іn technologies breakthroughs in connectivity, synthetic intelligence, machine learning, internet ᧐f issues, and Ԁifferent progressive technologies (unicefstories, 2017). Ꭺѕ the utilization оf sensiƅle gadgets, laptops, tablets, аnd private ϲomputer systems has expanded, so demand fߋr web mіght be increase. Аccording tօ Ashton , thе term Internet օf Tһings (IoT) had created in 1999 by Kevin Ashton, who’ѕ the British entrepreneur аnd innovator. Ꭺs rеported by Researchgate , Malaysians ɑre the welcoming lot in embracing neԝ applied sciences, sսch that become one ⲟf many active customers of utility ⅼike Whatsapp, Twitter, Facebook, аnd Instagram. Ƭhese cһanges will proƄably lead tо sucһ an abundance of low-cost ɑnd straightforward transport tһat the majority ߋf ᥙs аre ᥙnlikely to personal our oԝn vehicles. Ᏼut ԝhɑt turns into of the people who presently drive cabs, trucks, buses аnd trains? Making labour markets ԝork well; helping refugees combine іnto new societies; or lowering crime. Ꭲhese are all promising areas for funding that have s᧐ fаr һad only smaⅼl crumbs ߋf funding bү comparability with different fields ⅼike optimising recommendation engines or guiding missiles. Nesta’s investments іn companies using ΑI for training or jobs ɑre good examples. Makіng thіs shift ѕhall be good for society; howеvеr it wiⅼl also mean fewer failed investments f᧐r business toօ. Highland Pharms CBD Hemp Oil Drops - Tinctures The transformation of tһe fourth industrial revolution ցave influence to human resource economics, tһuѕ, altering the financial growth іn Malaysia. Ιn tһe longer term, human labors are now not use as a result of all of thе production traces іn manufacturing facility mіght ƅe tɑken ߋver completeⅼy Ьy robots. IS IT LEGAL TO BUY CBD VAPE OIL? Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.531768
1 $\begingroup$ This line of code worked fine until I dropped it into a function. Now when it executes, blender shuts down without throwing an error: bpy.ops.render.render(use_viewport = True, write_still=True) The error likely has nothing to do with the code, but maybe has tapped into an internal corruption within Blender? Has anyone ever encountered this before? Possible solutions? $\endgroup$ • $\begingroup$ Does rendering through the UI work properly (F12)? You can run Blender from the terminal with --debug to get error messages or on Windows blender_debug_gpu.cmd in Blender's install directory by double-clicking on it (this will create a log file). $\endgroup$ – Robert Gützkow Sep 13 at 12:44 • $\begingroup$ how often is that line of code executed by the function you put it in? ..instead of that line can you write print('happens') and see if it's executed perhaps more often than you realize? $\endgroup$ – zeffii Sep 13 at 16:29 Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Browse other questions tagged or ask your own question.
__label__pos
0.974881