content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
How to: Reinitialize a Subscription (SQL Server Management Studio)
Reinitializing a subscription is a two-part process:
1. A single subscription or all subscriptions to a publication are marked for reinitialization. Mark subscriptions for reinitialization in the Reinitialize Subscription(s) dialog box, which is available from the Local Publications folder and the Local Subscriptions folder in Microsoft SQL Server Management Studio. You can also mark subscriptions from the All Subscriptions tab and the publications node in Replication Monitor. For information about starting Replication Monitor, see How to: Start Replication Monitor (Replication Monitor). When you mark a subscription for reinitialization, you have the following options:
• Use the current snapshot
Select to apply the current snapshot to the Subscriber the next time the Distribution Agent or Merge Agent runs. If there is no valid snapshot available, this option cannot be selected.
• Use a new snapshot
Select to reinitialize the subscription with a new snapshot. The snapshot can be applied to the Subscriber only after it has been generated by the Snapshot Agent. If the Snapshot Agent is set to run on a schedule, the subscription is not reinitialized until after the next scheduled Snapshot Agent run. Select Generate the new snapshot now to start the Snapshot Agent immediately.
• Upload unsynchronized changes before reinitialization
Merge replication only. Select to upload any pending changes from the subscription database before the data at the Subscriber is overwritten with a snapshot.
If you add, drop, or change a parameterized filter, pending changes at the Subscriber cannot be uploaded to the Publisher during reinitialization. If you want to upload pending changes, synchronize all subscriptions before changing the filter.
2. A subscription is reinitialized the next time it is synchronized: the Distribution Agent (for transactional replication) or Merge Agent (for merge replication) applies the most recent snapshot to each Subscriber that has a subscription marked for reinitialization. For more information about synchronizing subscriptions, see How to: Synchronize a Push Subscription (SQL Server Management Studio) and How to: Synchronize a Pull Subscription (SQL Server Management Studio).
1. Connect to the Publisher in Management Studio, and then expand the server node.
2. Expand the Replication folder, and then expand the Local Publications folder.
3. Expand the publication that has the subscription you want to reinitialize.
4. Right-click the subscription, and then click Reinitialize.
5. In the Reinitialize Subscription(s) dialog box, select options, and then click Mark for Reinitialization.
1. Connect to the Subscriber in Management Studio, and then expand the server node.
2. Expand the Replication folder, and then expand the Local Subscriptions folder.
3. Right-click the subscription, and then click Reinitialize.
4. In the Reinitialize Subscription(s) dialog box, select options, and then click Mark for Reinitialization.
1. Connect to the Publisher in Management Studio, and then expand the server node.
2. Expand the Replication folder, and then expand the Local Publications folder.
3. Right-click the publication with subscriptions you want to reinitialize, and then click Reinitialize All Subscriptions.
4. In the Reinitialize Subscription(s) dialog box, select options, and then click Mark for Reinitialization.
1. In Replication Monitor, expand a Publisher group in the left pane, expand a Publisher, and then click a publication.
2. Click the All Subscriptions tab.
3. Right-click the subscription you want to reinitialize, and then click Reinitialize Subscription.
4. In the Reinitialize Subscription(s) dialog box, select options, and then click Mark for Reinitialization.
1. In Replication Monitor, expand a Publisher group in the left pane, and then expand a Publisher.
2. Right-click the publication with subscriptions you want to reinitialize, and then click Reinitialize All Subscriptions.
3. In the Reinitialize Subscription(s) dialog box, select options, and then click Mark for Reinitialization.
Community Additions
ADD
Show:
© 2015 Microsoft
|
__label__pos
| 0.994594 |
Get-Acl
Get-Acl
Gets the security descriptor for a resource, such as a file or registry key.
Syntax
Parameter Set: ByPath
Get-Acl [[-Path] <String[]> ] [-AllCentralAccessPolicies] [-Audit] [-Exclude <String[]> ] [-Filter <String> ] [-Include <String[]> ] [-UseTransaction] [ <CommonParameters>]
Parameter Set: ByInputObject
Get-Acl -InputObject <PSObject> [-AllCentralAccessPolicies] [-Audit] [-Exclude <String[]> ] [-Filter <String> ] [-Include <String[]> ] [-UseTransaction] [ <CommonParameters>]
Parameter Set: ByLiteralPath
Get-Acl [-AllCentralAccessPolicies] [-Audit] [-Exclude <String[]> ] [-Filter <String> ] [-Include <String[]> ] [-LiteralPath <String[]> ] [-UseTransaction] [ <CommonParameters>]
Detailed Description
The Get-Acl cmdlet gets objects that represent the security descriptor of a file or resource. The security descriptor contains the access control lists (ACLs) of the resource. The ACL specifies the permissions that users and user groups have to access the resource.
Beginning with Windows PowerShell 3.0, you can use the InputObject parameter of Get-Acl to get the security descriptor of objects that do not have a path.
Parameters
-Audit
Gets the audit data for the security descriptor from the system access control list (SACL).
Aliases
none
Required?
false
Position?
named
Default Value
none
Accept Pipeline Input?
false
Accept Wildcard Characters?
false
-Exclude<String[]>
Omits the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.
Aliases
none
Required?
false
Position?
named
Default Value
none
Accept Pipeline Input?
false
Accept Wildcard Characters?
true
-Filter<String>
Specifies a filter in the provider's format or language. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when getting the objects, rather than having Windows PowerShell filter the objects after they are retrieved.
Aliases
none
Required?
false
Position?
named
Default Value
none
Accept Pipeline Input?
false
Accept Wildcard Characters?
true
-Include<String[]>
Gets only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.
Aliases
none
Required?
false
Position?
named
Default Value
none
Accept Pipeline Input?
false
Accept Wildcard Characters?
true
-Path<String[]>
Specifies the path to a resource. Get-Acl gets the security descriptor of the resource indicated by the path. Wildcards are permitted. If you omit the Path parameter, Get-Acl gets the security descriptor of the current directory.
It is not necessary to type Path when you specify a value for this parameter.
Aliases
none
Required?
false
Position?
1
Default Value
none
Accept Pipeline Input?
true (ByValue, ByPropertyName)
Accept Wildcard Characters?
true
-AllCentralAccessPolicies
Gets information about all central access policies that are enabled on the computer.
Beginning in Windows Server® 2012, administrators can use Active Directory and Group Policy to set central access policies for users and groups. For more information, see "Central Access Policies" at http://go.microsoft.com/fwlink/?LinkId=238408.
This parameter was introduced in Windows PowerShell 3.0.
Aliases
none
Required?
false
Position?
named
Default Value
False
Accept Pipeline Input?
false
Accept Wildcard Characters?
false
-InputObject<PSObject>
Gets the security descriptor for the specified object. Enter a variable that contains the object or a command that gets the object.
You cannot pipe an object, other than a path, to Get-Acl. Instead, use the InputObject parameter explicitly in the command.
This parameter was introduced in Windows PowerShell 3.0.
Aliases
none
Required?
true
Position?
named
Default Value
none
Accept Pipeline Input?
false
Accept Wildcard Characters?
false
-LiteralPath<String[]>
Specifies the path to a resource. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.
This parameter was introduced in Windows PowerShell 3.0.
Aliases
none
Required?
false
Position?
named
Default Value
none
Accept Pipeline Input?
true (ByValue, ByPropertyName)
Accept Wildcard Characters?
false
-UseTransaction
Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see about_Transactions
Required?
false
Position?
named
Default Value
false
Accept Pipeline Input?
false
Accept Wildcard Characters?
false
<CommonParameters>
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
Inputs
The input type is the type of the objects that you can pipe to the cmdlet.
• System.String
You can pipe a string that contains a path to Get-Acl.
Outputs
The output type is the type of the objects that the cmdlet emits.
• System.Security.AccessControl
Get-Acl returns an object that represents the ACLs that it gets. The object type depends upon the ACL type.
Notes
• By default, Get-Acl displays the Windows PowerShell path to the resource (<provider>::<resource-path>), the owner of the resource, and Access, a list (array) of the access control entries in the discretionary access control list (DACL) for the resource. The DACL list is controlled by the resource owner.
When you format the result as a list, ("Get-Acl | Format-List"), in addition to the path, owner, and access list, Windows PowerShell displays the following properties and property values:
-- Group. The security group of the owner.
-- Audit. A list (array) of entries in the system access control list (SACL). The SACL specifies the types of access attempts for which Windows generates audit records.
-- Sddl. The security descriptor of the resource displayed in a single text string in Security Descriptor Definition Language (SDDL) format. Windows PowerShell uses the GetSddlForm method of security descriptors to get this data.
• Because Get-Acl is supported by the file system and registry providers, you can use Get-Acl to view the ACL of file system objects, such as files and directories, and registry objects, such as registry keys and entries.
Examples
Example 1: Get the security descriptor for a folder
This command gets the security descriptor of the C:\Windows directory. The folder C:\Windows is understood as the value for the Path parameter, so it is not necessary to type Path at the command line.
PS C:\> Get-Acl C:\Windows
Example 2: Get security descriptors for a filtered list of files
This command gets the Windows PowerShell path and SDDL for all of the .log files in the C:\Windows directory whose names begin with k.
The command uses the Get-Acl cmdlet to get objects representing the security descriptors of each log file. It uses a pipeline operator (|) to send the results to the Format-List cmdlet. The command uses the Property parameter of Format-List to display only the PsPath and SDDL properties of each security descriptor object.
Lists are often used in Windows PowerShell, because long values appear truncated in tables.
The SDDL values are valuable to system administrators, because they are simple text strings that contain all of the information in the security descriptor. As such, they are easy to pass and store, and they can be parsed when needed.
PS C:\> Get-Acl -Path "C:\Windows\k*.log" | Format-List -Property PSPath, Sddl
Example 3: Get security descriptors and audit data for a filtered list of files
This command gets the security descriptors of the .log files in the C:\Windows directory whose names begin with k. It uses the Audit parameter to get the audit records from the SACL in the security descriptor. Then it uses the ForEach-Object cmdlet to count the number of audit records associated with each file. The result is a list of numbers representing the number of audit records for each log file.
PS C:\> Get-Acl -Path "C:/Windows/k*.log" -Audit | ForEach-Object { $_.Audit.Count }
Example 4: Get the security descriptor for a registry subkey
This command uses the Get-Acl cmdlet to get the security descriptor of the Control subkey (HKLM\SYSTEM\CurrentControlSet\Control) of the registry.
The Path parameter specifies the Control subkey. The pipeline operator (|) passes the security descriptor that Get-Acl gets to the Format-List command, which formats the properties of the security descriptor into a list.
PS C:\> Get-Acl -Path "HKLM:\System\CurrentControlSet\Control" | Format-List
Example 5: Get the security descriptor for a storage subsystem object
This command uses the InputObject parameter of Get-Acl to get the security descriptor of a storage subsystem object.
PS C:\> Get-Acl -InputObject (Get-StorageSubsystem -Name S087)
Related topics
Community Additions
ADD
Show:
|
__label__pos
| 0.99987 |
Connect Insights
Does your business need a VPN?
CyberHive
A VPN – Virtual Private Network – is a way to ensure safety when connecting to another network over the internet. A VPN for business can be essential because it will encrypt the connection from whatever device is being used, making it much more secure and also offer a greater degree of online privacy. A VPN has become vital for all types of organisations where there are remote connections being accessed, whether the focus is on protecting data or keeping a location private. So, does your business need a VPN?
Why would you use VPN?
For most organisations today, the purpose of a VPN is to securely connect branch offices – or those who are working remotely – to the networks, data, tools and resources that are required to carry out specific work. A VPN for business is essentially a way to enhance perimeter security so that corporate networks can be accessed from anywhere in the world without security worries.
The types of VPN for businesses
• A remote access VPN. This simply gives remote users access to an employer’s network infrastructure in a secure way. All traffic that is being sent and received is securely encrypted in a ‘secure tunnel’ between the user and the employer network.
• Site-to-site VPN. This is a connection between two, or more, networks – as opposed to a connection between a user and a network. These are often used by companies with multiple sites or offices.
What do you need to consider with a VPN for business?
Not all VPNs are the same so it’s important to make sure that you’re aware of the limitations some may have before you invest in VPN for your business.
• VPN speed. This will not be any faster than the speed of the internet connection between the device being used and the network it is connecting to. However, the VPN technology that you use can also have an impact on speed, for example where encryption and authentication technologies that are being used increase data size or send data through multiple checkpoints, for example. The amount of data that is travelling over a VPN connection can also have an impact on speed, for example if someone using the connection is making a video call.
• VPN security. The type of VPN for business that you use will have an impact on security. For example, those organisations that are looking to implement effective VPN security for employees who are working remotely should consider remote access VPNs with site-to-site VPNs for their branch offices.
VPN for business vs a personal VPN
The main difference between a VPN for business and personal VPNs is whether the user is connecting devices to a corporate network or a personal network. Where someone is accessing employer resources then this should be done via a VPN that is controlled and maintained by the employer. VPNs are most often used in a personal context to keep internet browser history private.
Tailored cyber security solutions
It’s advisable for any organisation with any kind of remote workforce element – or multiple offices – to consider VPN for their business today. The beauty of CyberHive Connect is that it is built differently to traditional a VPN, utilising a mesh network. CyberHive Connect implements a secure software-defined mesh network that transforms how devices communicate. Built using a secure-by-design methodology and a zero trust architecture, it provides instant security that can be easily retrofitted into existing infrastructure.
If you would like to learn more, connecting with a member of our team allows us to guide you through our products and their uses. For general queries and to discuss our products, get in touch today.
Get in touch
If you have a question or would like some more information, contact us today.
|
__label__pos
| 0.722181 |
1. We will be upgrading to the latest version of XenForo today beginning at 4:30 PM ET. We expect about 1 hour of downtime during this process. We'll remove this notice when the work is complete - sorry for any inconvenience!
Dismiss Notice
Overheating
Discussion in 'Acer (Gateway)' started by SineFato, Mar 27, 2007.
1. ParisAsta
ParisAsta Dell XT2
Messages:
27
Likes Received:
0
Trophy Points:
5
For the past week my PC has been overheating. I have it sat up on a table, and with the battery in to lift it off the table, but its still running at 150+F. I have called up Gateway tech, and they told me to take compressed air and blow out the fans, and that would fix the problem. I have read online that sometimes doing that can damage the fans. But I have done a visual inspection and their is no real dust on my fans.
Is their any reason for this.. I use to be able to have this PC on my lap and watch TV shows and what not, but no now, cause it might burn me.
2. JDragon
JDragon Pen Pal - Newbie
Messages:
89
Likes Received:
0
Trophy Points:
16
What kind of system?
Also, do you hear the fans coiming on? IF so how often and for how long?
I would get the compressed air and call GW TS back and have them walk you through what they want you to do. Make them aware of your concerns and have them note what you are doing and that its at their request. Have them read the notes they left back exactly as they are noted. If you are paranoid call them back and ask a different rep to read you what notes are on your account for that call. Make sure you get the Tech's name & ID. Also be nice, it really does work better.
If it causes any problems that may help with dealing with them, and then again it may not. :p
Just my 0.02
3. ParisAsta
ParisAsta Dell XT2
Messages:
27
Likes Received:
0
Trophy Points:
5
I have a CX262 and the fans are always on, they never shut off.. as soon as it boots, the fans start, when I leave my PC alone, and get up to get a drink or somethings, they slow down and the PC somewhat cools off.
4. SimsHsia
SimsHsia "I will do science to it" Senior Member
Messages:
3,293
Likes Received:
0
Trophy Points:
66
Hi ParisAsta,
Have you checked if there is any spyware on your computer, by using either Lavasoft's Ad-Aware or Safer Networking's SpyBot S&D? Some rouge applications running in the background may contribute to high processor usage, thus the fan must run.
I'm also looking at your signature, with the specifications of your Tablet PC. A Intel C2D T7400 2.16 GHz tends to run hot at that high frequency; and a 7200 RPM hard drive also runs hotter than a 5400 RPM. The combined temperature of both the processor and the hard drive will cause the system temperature to rise, thus the fans must initiate to expel the heat from these two peripherals. You could try NHC (Notebook Hardware Control), here, download it and set the CPU speed to "Dynamic Switching" to bring the speed of the processor down when it is idle, but dynamically switches the processor. to the 2.16 GHz frequency if possible, when a program requires processing time with the processor. :)
5. ParisAsta
ParisAsta Dell XT2
Messages:
27
Likes Received:
0
Trophy Points:
5
Thanks for the link..
But I do not have a tablet with a Duo, its a Centrino M at 1.7, with a 100GB HDD, 1GB of RAM, and its running Windows Tablet PC.
I have ran the spyware scans and only found a few, but nothing that was running in the background.
6. SimsHsia
SimsHsia "I will do science to it" Senior Member
Messages:
3,293
Likes Received:
0
Trophy Points:
66
Whoops! Wrong signature then! :D
I have a laptop that also didn't seem to have any dust, until I blew some compressed air and it flew straight out. Just try not to go Rambo with the compressed air and blast at full strength. Small, short bursts should be sufficient to blow out the dust.
7. herb2k
herb2k Pen Pal - Newbie
Messages:
30
Likes Received:
0
Trophy Points:
15
The trick for compressed air is to keep the can upright and use short bursts.
Holding the can upside down causes the chemical to be thrown out which frosts anything it touches, and that's what can damage your machine.
8. JDragon
JDragon Pen Pal - Newbie
Messages:
89
Likes Received:
0
Trophy Points:
16
Good to know, thanks.
9. ParisAsta
ParisAsta Dell XT2
Messages:
27
Likes Received:
0
Trophy Points:
5
Thanks for the tips, I know about compressed air, cause I use it to clean out my mums PC.. and about the frost problem.. at least the frost does not effect Keys on a keyboard.. well at least not a dell keyboard... yea. compressed air should never be given to PC techs at Job Corps either.
I'll give it a go... and see what happens... if all else fails, I'll take the back off and clean the fan and blow out any dust with an anti-static vac.
This is the first time that this thing has overheated.. and done it more than once. I just hope that nothing melted.. cause I know the burns on my legs hurt (like a sunburn).
Any other tips to keeping one of these beast cool, keep them coming.
Thanks for the help ^_^
10. SineFato
SineFato Pen Pal - Newbie
Messages:
33
Likes Received:
0
Trophy Points:
16
You can check out osme of those laptop coolers, you put them under the laptop and they act like a giant heatsink and have a few extra fans. They would also act as a buffer between the heat and your lap.
Loading...
Share This Page
|
__label__pos
| 0.585353 |
2
votes
0answers
152 views
A fractal object at origin but nowhere else: derived from Brownain motion
Hi, Please consider this object: Start with a realization of Brownian motion in 2D, which I'll denote by rho(t) where -infinity < t < +infinity. Next, lets smooth rho. There are various ...
1
vote
2answers
304 views
Fractional Gaussian noise in higher dimensions
I'm having difficulty imagining (or explaining to myself) how the partial sums a two dimensional Gaussian noise can produce a surface. According to equation (20) of the paper, "On two-dimensional ...
1
vote
1answer
643 views
Need help understanding Mandelbrot and Van Ness Fractional Brownian Motion
I need help understanding the Mandelbot and Van Ness' definition of Fractional Brownian motion $ B_H( t , \omega ) - B_H( 0 , \omega ) = \frac{1}{\Gamma(H + \frac{1}{2})} \left\( \int_{-\infty}^0 ...
|
__label__pos
| 0.969566 |
", "learningResourceType": "Expert Answer", "datePublished": "2019-11-03" }" } } ] }
Describe five components of code, indicating their role in programming. Identify the specific code to be changed, modify it, and describe the changes, supported by screenshots. Group 1: Choose an initial upgrade date that is at least 30 days in the future. Group 2: This date should be 2 days after the initial upgrade date. Group 3: This date should be 5 days after the initial upgrade date. Group 4: This date should be 8 days after the initial upgrade date. Group 5: This date should be 10 days after the initial upgrade date. <!DOCTYPE html><html><head> <h1>Welcome Team Pakistan</h1> <h2>Warning Operating System (OS) Updgrade</h2><script type="text/javascript"> var today = new Date (); var UpgradeDay = new Date("December 4, 2019"); var msPerDay = 24 * 60 * 60 * 1000; var TimeLeft = (UpgradeDay.getTime() - today.getTime()); var Days = TimeLeft / msPerDay; var DaysLeft = Math.floor(Days); document.write("There are only<BR><H4>" + DaysLeft + " Days </H4> Until Your Computer Upgrade </P>");</script></body></html>
Question
Describe five components of code, indicating their role in programming. Identify the specific code to be changed, modify it, and describe the changes, supported by screenshots.
Group 1: Choose an initial upgrade date that is at least 30 days in the future. Group 2: This date should be 2 days after the initial upgrade date. Group 3: This date should be 5 days after the initial upgrade date. Group 4: This date should be 8 days after the initial upgrade date. Group 5: This date should be 10 days after the initial upgrade date.
<!DOCTYPE html>
<html>
<head>
<h1>Welcome Team Pakistan</h1>
<h2>Warning Operating System (OS) Updgrade</h2>
<script type="text/javascript">
var today = new Date ();
var UpgradeDay = new Date("December 4, 2019");
var msPerDay = 24 * 60 * 60 * 1000;
var TimeLeft = (UpgradeDay.getTime() - today.getTime());
var Days = TimeLeft / msPerDay;
var DaysLeft = Math.floor(Days);
document.write("There are only<BR><H4>" + DaysLeft + " Days </H4> Until Your Computer Upgrade </P>");
</script>
</body>
</html>
Expert Answer
1 Rating
Want to see the step-by-step answer?
See Answer
Check out a sample Q&A here.
Want to see this answer and more?
Experts are waiting 24/7 to provide step-by-step solutions in as fast as 30 minutes!*
See Answer
*Response times vary by subject and question complexity. Median response time is 34 minutes and may be longer for new subjects.
Related Computer Science Q&A
Find answers to questions asked by student like you
Show more Q&A
Q: The logic will allow the user to: Load a single dimensional array of size 50 with a random number T...
A: Header file #include<stdlib.h> included for srand function.Char ch declared to hold ‘Y’ or ‘N’...
Q: Python 3.7.4: The current calendar, called the Gregorian calendar, was introduced in 1582. Every yea...
A: In order to correct given program, make the following changes:Put def main() code above the def leap...
Q: I am working on a code for loops where I need to list all the prime numbers between value A(number p...
A: Validate all validations with 2 first and last numbers i.e. nbr1 and nbr2.Update nbr1 again and agai...
Q: Assignment First, launch NetBeans and close any previous projects that may be open (at the top menu ...
A: A Java program that satisfies the given criteria is given below,Program://Import necessary packagesi...
Q: Python 1. Write a for loop (using the range() function) that will print the integers 10,15,20,25,3...
A: Program:#display the statementprint("The integers are: ") #iterate "i" in the range of 10 to 51 with...
Q: Hi, I have to display the first 20 Fibonacci numbers to the console. The first two numbers are given...
A: Program: class PrSpecial { public static final int N = 20; public static void main(String[] args){ i...
Q: Problem 2: Using HTML/JavaScript, find and display the number of multiples of a certain number enter...
A: Program:<!--open the html tag--><html> <!--head tag defines the head portion of a doc...
Q: Identify, list, and define the six components of an information system.
A: Information System (IS):Information system is the system that deals with the organisation, storage, ...
Q: What role does database technology play in managing data as a business resource within an organizati...
A: Data resource management is applying software tools and information systems technologies such as dat...
|
__label__pos
| 0.626497 |
program test_lstsq use f95_lapack, only: la_gelsy, la_gelsd implicit none double precision, parameter :: PI = 4*tan(1.0), C1=-4.87e2, C2=5.3411e3, C3=1.61153 double precision, allocatable, dimension(:,:) :: a, b double precision, allocatable, dimension(:) :: t integer :: i, j, N, rank, info write(*,*) C1, C2, C3 write(*,*) N = 100 do i = 1, 8 allocate(a(N,3)) allocate(b(N,1)) allocate(t(N)) do j = 1, N t(j) = j*2*PI/N end do b(:,1) = C1*sin(t) + C2*cos(t) + C3 a(:,1) = sin(t) a(:,2) = cos(t) a(:,3) = 1 rank = 0 info = 0 call la_gelsd(a, b, rank=rank, info=info) write(*,'(A, I6, A5, 3E15.3)') 'N=', N, 'X=', b(:3,1) deallocate(a) deallocate(b) deallocate(t) N = N*2 end do end program
|
__label__pos
| 0.999563 |
Ads (728x90)
Dalam proses instalasi OS laptop atau komputer yang tidak memiliki CD/DVD Room biasanya kita menggunakan flashdisk sebagai media untuk melakukan proses instalasi OS pada komputer tersebut. Hanya saja flashdisk tidak dapat langsung dijadikan sebagai bootable untuk melakukan proses instalasi. Perlu beberapa langkah atau software khusus yang dapat membuat flashdisk tersebut bootable. Banyak sekali freeware yang bisa Anda gunakan, namun tidak semuanya memiliki kemampuan yang baik. Untuk kali ini ieuwelah.com akan mencoba untuk memberikan tutorial membuat flashdisk bootable tanpa software yaitu dengan menggunakan perintah-perintah di command prompt. Untuk lebih jelasnya silahkan untuk mencobanya berikut ini :
Langkah 1
Pastikan flashdisk sudah terpasang pada komputer. Tekan Win+R lalu ketikka cmd.
Langkah 2
Ketikkan diskpart lalu tekan Enter. Maka akan muncul jendela baru.
Langkah 3
Pada jendela diskpart tadi, ketikkan list disk lalu Enter, untuk melihat list disk yang ada pada komputer Anda.
membuat flashdisk bootable dengan cmd
Langkah 4
Cari flashdisk Anda. Pada gambar di atas, flashdisk yang saya gunakan memiliki kapasitas 8GB atau 7719MB yang berarti flashdisk saya adalah Disk 2. Ketikkan select disk 2 lalu Enter, untuk memilih disk yang akan digunakan.
harap perhatikan jangan sampai salah memilih disk.
Langkah 5
Ketik clean lalu Enter,
membuat flashdisk bootable dengan cmd
Ketik create partition primary lalu Enter,
membuat flashdisk bootable dengan cmd
Ketik select partition lalu Enter,
membuat flashdisk bootable dengan cmd
Ketik active lalu Enter,
membuat flashdisk bootable dengan cmd
Lakukan format flashdisk, dengan cara ketikkan format fs=fat32 lalu tekan Enter. Tunggu sampai proses selesai.
membuat flashdisk bootable dengan cmd
Jika sudah selesai, ketikkan assign lalu Enter. Ketikkan exit untuk keluar dari CMD.
Langkah 6
Flashdisk kini sudah dapat digunakan sebagai bootable. Langkah selanjutnya adalah tinggal Anda Copy isi dari OS Windows yang akan Anda install ke flashdisk tersebut.
Langkah 7
Setelah dicopy, Anda dapat langsung melakukan proses instalasi dengan flashdisk tersebut. Jangan lupa untuk mensetting boot di BIOS ke USB terlebih dahulu. Sumber
Posting Komentar
Blogger
|
__label__pos
| 0.996261 |
habitat
Type safe configuration for your classes and modules
0.4.1 released
Habitat
Easily configure settings for Crystal projects
Installation
Add this to your application's shard.yml:
dependencies:
habitat:
github: luckyframework/habitat
Usage
require "habitat"
class MyServer
Habitat.create do
setting port : Int32
setting debug_errors : Bool = true
setting host : String, example: "127.0.0.1"
end
# Access them like this
def start
start_server_on port: settings.port
end
end
MyServer.configure do |settings|
settings.port = 8080
end
# At the very end of your program use this
# It will raise if you forgot to set any settings
Habitat.raise_if_missing_settings!
Settings can also be accessed from outside the class:
port = MyServer.settings.port
puts "The server is starting on port #{port}"
Contributing
1. Fork it ( https://github.com/luckyframework/habitat/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request
Contributors
habitat:
github: luckyframework/habitat
version: ~> 0.4.1
License MIT
Crystal 0.27.2
Authors
Dependencies 0
Development Dependencies 0
Dependents 16
Show all 16 dependents
Last synced .
search fire star recently
|
__label__pos
| 0.728356 |
SSAT Upper Level Math : How to find the length of the hypotenuse of a right triangle : Pythagorean Theorem
Study concepts, example questions & explanations for SSAT Upper Level Math
varsity tutors app store varsity tutors android store
Example Questions
Example Question #1 : How To Find The Length Of The Hypotenuse Of A Right Triangle : Pythagorean Theorem
The base and height of a right triangle are each 1 inch. What is the hypotenuse?
Possible Answers:
Correct answer:
Explanation:
You need to use the Pythagorean Theorem, which is .
Add the first two values and you get . Take the square root of both sides and you get .
Example Question #1 : Apply The Pythagorean Theorem To Find The Distance Between Two Points In A Coordinate System: Ccss.Math.Content.8.G.B.8
Parallelogram2
Give the perimeter of the above parallelogram if .
Possible Answers:
Correct answer:
Explanation:
By the Theorem:
, and
The perimeter of the parallelogram is
Example Question #2 : How To Find The Length Of The Hypotenuse Of A Right Triangle : Pythagorean Theorem
A right triangle has legs with lengths of units and units. What is the length of the hypotenuse?
Possible Answers:
units
units
units
units
Correct answer:
units
Explanation:
Using the numbers given to us by the question,
units
Example Question #3 : How To Find The Length Of The Hypotenuse Of A Right Triangle : Pythagorean Theorem
A right triangle has legs with the lengths and . Find the length of the hypotenuse.
Possible Answers:
Correct answer:
Explanation:
Use the Pythagorean Theorem to find the length of the hypotenuse.
Example Question #4 : How To Find The Length Of The Hypotenuse Of A Right Triangle : Pythagorean Theorem
Find the length of the hypotenuse in the right triangle below.
12
Possible Answers:
Correct answer:
Explanation:
Use the Pythagorean Theorem to find the hypotenuse.
Example Question #5 : How To Find The Length Of The Hypotenuse Of A Right Triangle : Pythagorean Theorem
If James traveled north and John traveled west from the same town, how many miles away will they be from each other when they reach their destinations?
Possible Answers:
Correct answer:
Explanation:
The distances when put together create a right triangle.
The distance between them will be the hypotenuse or the diagonal side.
You use Pythagorean Theorem or to find the length.
So you plug and for and which gives you,
or .
Then you find the square root of each side and that gives you your answer of .
Learning Tools by Varsity Tutors
|
__label__pos
| 0.999828 |
13
$\begingroup$
Assume there is a public-key encryption scheme $(KeyGen, Enc, Dec)$ with perfect correctness (i.e., for all messages M and valid key-pairs (PK,SK), we have $Dec_{SK}(Enc_{PK}(M))=M$).
Will there always be a function $A$ such that for all messages M and valid public-keys PK, $A_{PK}(Enc_{PK}(M))=M$?
In other words, can a computationally unbounded adversary decrypt the message, having only the public key?
$\endgroup$
4
• $\begingroup$ I edited your question to look more like a question and less like a homework task. Feel free to edit it again to make it more clear. $\endgroup$ Sep 25, 2011 at 14:29
• $\begingroup$ Well, in light of the rewording of the question, I'd say yes it is possible for a computationally unbounded adversary to decrypt a message. Not sure why I was negative voted, as I have clearly demonstrated how this would be done using a simplified example. Nevertheless, if somebody were to answer the initial question, only to have it down-voted when the question changes, I prefer to retract my answer. $\endgroup$
– user476
Sep 26, 2011 at 2:04
• $\begingroup$ @Bill Sorry, I did not intend to change the meaning of the question with my edit, I only intended to make it less "home-work-y" and more "question-y". Do you really feel the original question (or the question after huyichen's first edit) was in core other than it is now? $\endgroup$ Sep 26, 2011 at 10:31
• $\begingroup$ @PaŭloEbermann - No problem Paulo. I agree with your reasoning since we do not want to be providing solutions to assignment questions. That is why I have always been careful (in the past) of not providing too much detail in my answers. In this case, however, I may have gone a bit overboard. $\endgroup$
– user476
Sep 26, 2011 at 10:38
2 Answers 2
27
$\begingroup$
Yes, a computationally unbounded attacker can break any public key system.
One easy way to see this is to consider the KeyGen algorithm, which takes takes as input a value R (which in normal use is the output of some random number generator), and outputs a public key PK and a private key SK.
Now, what a computationally unbounded adversary can do is consider all possible inputs R, and see which one produces the public key that he has been given. We know that there is at least one such input R (the one that was used when the public key was created); we can then use the corresponding private key to decrypt the message.
The obvious objection to this is "what if there are multiple such R's which generate the same public key, but different private keys?". Actually, it turns out that this is not a problem; because each such private key SK was generated correctly by the key generation function and corresponds to the public key under attack, it must still satisfy the formula:
$Dec_{SK}(Enc_{PK}(M)) = M$
Hence, it must correctly decrypt the message, even if it was not the exact private key that the legitimate user had.
$\endgroup$
1
$\begingroup$
I believe that the whole point of developing secure encryption schemes is to prevent such scenarios from occurring. With respect to the ElGamal encryption scheme, though, the above scenario is possible if the same random number (called the commitment) is used to encrypt two or more messages. The cryptanalyst can use this information to recover the private key.
To answer this question thoroughly, though, one needs to explain how set up and encrypt messages using the ElGamal coding scheme. Choosing the keys requires selecting a large prime number $p$. For security reasons, $p$ needs to be a number of at least 2000 bits, or 600 decimal digits.
First, select a primitive root $a \pmod{p}$. Note that finding a primitive root will be similar to finding a primitive element for cyclic groups. Also, select a number $b$ with $1 \leq b < p - 1$. This will be our private key. Calculate $c \equiv a^{b} \pmod{p}$ as a least residue modulo $p$. Note that $c \not\equiv 0, 1 \pmod{p}$. Publish $p$, $a$ and $c$ as the public key, and keep $b$ secret as the private key.
To encode a message, we must first translate the text into a numerical string using the ASCII collating sequence, or another agreed method (e.g. EBCDIC). Break this numerical string into blocks, each a number $x$ with $0 \leq x < p$. For each block $x$, choose a random number $r$ (called the commitment) with $1 \leq r < p - 1$. This number should be different for each block, for reasons that are explained below. Compute $y_{1}$ and $y_{2}$, with $0 < y_{1}$, $y_{2} < p$ by assigning $y_{1} \equiv a^{r} \pmod{p}$ and $y_{2} \equiv x \cdotp c^{r} \pmod{p}$. Finally, transmit $y_{1}$ and $y_{2}$, in that order.
To decode a message, we must first calculate $x$ with $0 \leq x < p$ by assigning $x \equiv y_{2}(y_{1}^{b})^{-1} \pmod{p}$, and then collect the decoded blocks into a numerical string which is translated to text by the agreed method.
As an example, to encode the message HELLO, we first translate the text into a numerical string using the ASCII collating sequence. This becomes the numerical string 72 69 76 76 79. For simplicity, we choose $p = 97$, $a = 10$ and $b = 2$, and calculate $c \equiv a^{b} \equiv 10^{2} \equiv 100 \equiv 3 \pmod{97}$. We then publish $p = 97$, $a = 10$ and $c = 3$, and keep $b = 2$ private.
Next, we split the numeric strings into blocks of two digits; that is, one letter in each block. For block $x = 72$, we choose $r = 2$, which results in $(y_{1}, y_{2}) = (3,66)$. Similarly, for block $x = 69$, we choose $r = 3$, which results in $(y_{1}, y_{2}) = (30,20)$. For blocks $x = 76$, we choose $r = 4$ and $r = 5$, respectively, and for block $x = 79$, we choose $r = 6$. Collectively, this results in the following message being transmitted:
(3,66), (30,20), (9,45), (90,38), (27,70)
If one were to use the same random number (or commitment), say $r = 2$, to encode different blocks, this would result in the following message being transmitted:
(3,66), (3,39), (3,5), (3,5), (3,32)
Notice that $y_{1}$ is repeated for each block, and that there is no entropy or dispersion of characters in the message that is encoded, meaning that if an intruder or cryptanalyst were to know (or guess) the message of the first (or any consecutive) block, he/she would be able to use it to find the multiplicative inverse of $(y_{1}^{b})^{-1}$, without the knowledge of the private key, and therefore use it to decode the rest of the message in the remaining blocks.
Remember, to decode a message, we use $x \equiv y_{2}(y_{1}^{b})^{-1} \pmod{p}$. So, if we were to know that $(3, 66)$ decodes to $72$, we can use this information to determine that $(y_{1}^{b})^{-1} = 54$, using the Euclidean algorithm for solving linear congruences. We can then use this to decode the message in the remaining blocks. Hence, $(3,39)$ translates to $69$, $(3,5)$ translates to $76$, and $(3,32)$ translates to $79$.
Note that this is a very simplistic example, and typically measures will be taken to prevent such a cryptanalysis of the message. Other methods of cryptanalysis typically involve dictionary attacks on the passphrase, or brute force attacks on the private key.
$\endgroup$
6
• $\begingroup$ Well, in light of the rewording of the question, I'd say yes it is possible for a computationally unbounded adversary to decrypt a message. Not sure why I was negative voted, as I have clearly demonstrated how this would be done using a simplified example. Nevertheless, if somebody were to answer the initial question, only to have it down-voted when the question changes, I prefer to retract my answer. $\endgroup$
– user476
Sep 26, 2011 at 2:03
• $\begingroup$ I don't think this answered the original or revised question.The question is not asking about re-use of randomness. It's not asking whether there exists a public-key scheme that can be broken by an unbounded attacker; it's asking whether all public-key schemes can be broken by such an attacker (\forall vs \exists). In addition, your answer contains some inaccurate statements: e.g., "the whole point of developing secure encryption schemes is to prevent such scenarios from occurring" - this is not correct. I wonder if you might have misunderstood the question. $\endgroup$
– D.W.
Sep 26, 2011 at 2:44
• $\begingroup$ @D.W. - Sorry to have to break it to you but, unless I misunderstood, the initial question posted was an existential one. Whether or not you agree with my opinion is your problem. And, in light of our recent exchange to this and other posts, it appears that you do have a problem with me specifically. Not that I want to insult your intelligence but, if you think you are so knowledgeable on the topic, why don't you post a solution to this question rather than criticizing and/or down-voting mine. $\endgroup$
– user476
Sep 26, 2011 at 3:44
• 1
$\begingroup$ I read the original question, and your characterization is not accurate. It says: "Show the following: [...] If there is a public-key encryption scheme [...] then there is a function A [that breaks the encryption scheme]". Moreover, as I already mentioned, reuse of randomness attacks are not in scope, so your attack does not actually solve the question as originally asked. This is not a matter of opinion; it is a matter of mathematics. I'm sorry that you are taking it personally, but I assure you that I do not have a problem with you -- my interest is in ensuring accuracy. $\endgroup$
– D.W.
Sep 26, 2011 at 4:06
• 9
$\begingroup$ Good morning everyone. So in the interests of not letting this get out of hand - here's what I think. I think it's hard to criticise constructively and not hurt feelings. That said, @D.W. I think the best course of action when you disagree with something is to use your vote (you're entitled to do that) - for minor issues (did you mean XYZ?) comments work, but otherwise propose an alternative solution. That way the better answer should be voted up more - comments have much less visibility in terms of being read. $\endgroup$
– user46
Sep 26, 2011 at 8:15
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.926887 |
CHAPTER 01.03: INTRODUCTION: What is a column vector?
Let’s define what a column vector is in this segment. A matrix is called a column vector if it has one column. So let’s look at what a typical column matrix would look like. So it would have elements such as C 1, C2 all the way up to CN. So what that means is that is has N elements in it; so the dimension of this column vector is N. The dimension of the column vector is N.
Let’s look at an example. Somebody says “Hey my C matrix is 50, -20.5, 30, -60,” let’s suppose. So in this case it is a column vector because it only has one column in it but it has 4 elements. 1, 2, 3, 4. So the dimension for the column vector is 4. And that’s the end of this segment.
|
__label__pos
| 0.999515 |
General XMetaL Discussion
XMetaL Community Forum General XMetaL Discussion Can XMetal be used to create HTML/Webhelp
• jas
Can XMetal be used to create HTML/Webhelp
Participants 0
Replies 1
Last Activity 9 years, 8 months ago
My firm currently uses RoboHelp 9 to create online, HTML webhelp. We are open to moving to a new product, such as MadCap Flare or XMetal, and are currently in the research stage. Can anyone answer the following questions for me:
1. Do you use XMetal to create online help, and if so, what does it look like graphically? Do you have many options? (very plain/functional versus numerous design features/graphics, etc.)
2. How is XMetal for creating context-sensitive help? Does it provide that functionality, and if it does, how well does it work? Any details would be appreciated.
3. What are the downsides you have found, if any, for using XMetal to create online webhelp? What are the upsides?
Thanks for reading this!
Reply
Derek Read
Reply to: Can XMetal be used to create HTML/Webhelp
It sounds like you are probably looking for real world / client answers (can't give you that myself). However, the quick answer is yes, you can produce webhelp out of the box provided your source files are DITA and you choose to run XMetaL Author Enterprise (which includes DITA authoring and output capabilities).
One example of the webhelp output (unmodified) produced from DITA source files is here:
http://na.justsystems.com/webhelp/en/xmetalauthor/enterprise/7.0/XMEE.html#Welcome%20to%20XMetaL%20Author
Reply
• You must be logged in to reply to this topic.
Lost Your Password?
Products
Downloads
Support
|
__label__pos
| 0.991283 |
1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!
Line integral around an ellipse
1. Jan 9, 2010 #1
1. The problem statement, all variables and given/known data
What is [tex]\int_{\gamma} xy dx + x^2 dy[/tex] in each of the following cases?
1. [tex]\gamma[/tex] is the lower half of the curve [tex]2x^2 + 3y^2 = 8[/tex], traveled from [tex](2,0)[/tex] to [tex](-2,0)[/tex].
2. [tex]\gamma[/tex] is the full curve [tex]2x^2 + 3y^2 = 8[/tex], traveled counterclockwise.
2. Relevant equations
The line integral formula, I suppose. The fact that the integral can be expressed as the dot product of the vector field [tex](xy, x^2)[/tex] with the unit tangent vector to the curve can also be helpful.
3. The attempt at a solution
I parametrized the curves for (1) and (2) in different ways, viz.
1. [tex]x = t, y = -2\sqrt{\frac{2}{3}\left(1 - \frac{t^2}{4}\right)}[/tex].
2. [tex]x = 2\cos{\theta}, y = 2\sqrt{2/3}\sin{\theta}[/tex].
Then standard integration rules, but I came up with 0 for both the answers. Am I correct?
2. jcsd
3. Jan 9, 2010 #2
For no.1, the xy dx part is equal to 0, by symmetry: for every point (x,y) [which contributes xy dx] on the curve, there is another point (-x,y) [which contributes -xy dx] on the opposite side of the y axis. dx is always positive on this curve, so they cancel each other out.
We can also see that the x^2 dy part is equal to 0: because for the first half of the curve, dy is negative, for the second half, dy is positive, while x^2 is positive and mirrored. so the first half cancels out the second half again.
So 0 seems right.
2nd question follows easily from the first by splitting it up into 2 integrals: first around the bottom half and then around the top half of the ellipse. We already know from the first question that the bottom half = 0, and by symmetry the top half must be 0 too. 0+0=0.
Symmetry arguments are good for checking your work.
4. Jan 9, 2010 #3
I checked your answers and they are correct. Here is a graphical analysis of the problem in both cases:
http://img30.imageshack.us/img30/8343/intego.jpg [Broken]
AB
Last edited by a moderator: May 4, 2017
5. Jan 9, 2010 #4
A brilliant technical argument, but less mathematical. :wink:
6. Jan 9, 2010 #5
vela
User Avatar
Staff Emeritus
Science Advisor
Homework Helper
Education Advisor
[STRIKE]Note that [tex]d\Phi(x,y)=xydx+x^2dy[/tex] is an exact differential, so the integrals depend only on the endpoints. (I'll leave it to you to find [tex]\Phi(x,y)[/tex].) The second integral is then trivially zero because the start and end points are the same. The first integral is equal to [tex]\Phi(-2,0)-\Phi(2,0)=0[/tex].[/STRIKE]
Last edited: Jan 9, 2010
7. Jan 9, 2010 #6
many thanks, guys! i can't find [tex]\Phi(x)[/tex] though, i keep just missing it by a scalar factor. it would seem that [tex]\Phi = x^2y[/tex] would work, but it just misses it. poincare's lemma doesn't seem to help either. am i missing something obvious? :(
8. Jan 9, 2010 #7
vela
User Avatar
Staff Emeritus
Science Advisor
Homework Helper
Education Advisor
Why does [tex]\Phi(x,y)=x^2y[/tex] not work? You could add on a constant, obviously, but that wouldn't make a difference in evaluating the integral.
9. Jan 9, 2010 #8
oh, i thought because [tex]d(x^2y) = 2xy dx + x^2 dy[/tex]. how do we get rid of the scalar multiple of 2? it isn't an additive constant, right?
10. Jan 9, 2010 #9
vela
User Avatar
Staff Emeritus
Science Advisor
Homework Helper
Education Advisor
Oh, I'm sorry. I misled you. For some reason I thought there was a two there in the original problem. You're right. It's not exact, so you have to do the integral by hand. (And they were both zero when I did them earlier.)
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook
Loading...
Similar Threads - Line integral around Date
Line integral of a curve Dec 27, 2017
Line integral of a vector field Nov 29, 2017
|
__label__pos
| 0.961239 |
++ed by:
PAVELSR HMBRAND STEFANS MARIOROY ASB
8 PAUSE users
11 non-PAUSE users.
Slaven Rezić
and 1 contributors
NAME
Tk::place - Geometry manager for fixed or rubber-sheet placement
SYNOPSIS
$widget->place?(-option=>value?, -option=>value, ...)?
$widget->placeForget
$widget->placeInfo
$master->placeSlaves
DESCRIPTION
The placer is a geometry manager for Tk. It provides simple fixed placement of windows, where you specify the exact size and location of one window, called the slave, within another window, called the master. The placer also provides rubber-sheet placement, where you specify the size and location of the slave in terms of the dimensions of the master, so that the slave changes size and location in response to changes in the size of the master. Lastly, the placer allows you to mix these styles of placement so that, for example, the slave has a fixed width and height but is centered inside the master.
$slave->place?(-option=>value?, -option=>value, ...?)?
The place method arranges for the placer to manage the geometry of $slave. The remaining arguments consist of one or more -option=>value pairs that specify the way in which $slave's geometry is managed. -option may have any of the values accepted by the placeConfigure method.
The place method returns $slave.
$slave->placeConfigure?(-option=>value?, -option=>value, ...?)?
Query or modify the geometry options of the $slave. If no option is specified, this method returns a list describing the available options (see Tk_ConfigureInfo for information on the format of this list). If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the method modifies the given option(s) to have the given value(s); in this case the command returns undef.
The following -option=>value pairs are supported:
-anchor => where
Where specifies which point of $slave is to be positioned at the (x,y) location selected by the -x, -y, -relx, and -rely options. The anchor point is in terms of the outer area of $slave including its border, if any. Thus if where is se then the lower-right corner of $slave's border will appear at the given (x,y) location in the master. The anchor position defaults to nw.
-bordermode => mode
Mode determines the degree to which borders within the master are used in determining the placement of the slave. The default and most common value is inside. In this case the placer considers the area of the master to be the innermost area of the master, inside any border: an option of -x=>0 corresponds to an x-coordinate just inside the border and an option of -relwidth=>1.0 means $slave will fill the area inside the master's border. If mode is outside then the placer considers the area of the master to include its border; this mode is typically used when placing $slave outside its master, as with the options -x=>0, -y=>0, -anchor=>ne. Lastly, mode may be specified as ignore, in which case borders are ignored: the area of the master is considered to be its official X area, which includes any internal border but no external border. A bordermode of ignore is probably not very useful.
-height => size
Size specifies the height for $slave in screen units (i.e. any of the forms accepted by Tk_GetPixels). The height will be the outer dimension of $slave including its border, if any. If size is an empty string, or if no -height or -relheight option is specified, then the height requested internally by the window will be used.
-in => $master
$master is the reference to the window relative to which $slave is to be placed. $master must either be $slave's parent or a descendant of $slave's parent. In addition, $master and $slave must both be descendants of the same top-level window. These restrictions are necessary to guarantee that $slave is visible whenever $master is visible. If this option isn't specified then the master defaults to $slave's parent.
-relheight => size
Size specifies the height for $slave. In this case the height is specified as a floating-point number relative to the height of the master: 0.5 means $slave will be half as high as the master, 1.0 means $slave will have the same height as the master, and so on. If both -height and -relheight are specified for a slave, their values are summed. For example, -relheight=>1.0, -height=>-2 makes the slave 2 pixels shorter than the master.
-relwidth => size
Size specifies the width for $slave. In this case the width is specified as a floating-point number relative to the width of the master: 0.5 means $slave will be half as wide as the master, 1.0 means $slave will have the same width as the master, and so on. If both -width and -relwidth are specified for a slave, their values are summed. For example, -relwidth=>1.0, -width=>5 makes the slave 5 pixels wider than the master.
-relx => location
Location specifies the x-coordinate within the master window of the anchor point for $slave widget. In this case the location is specified in a relative fashion as a floating-point number: 0.0 corresponds to the left edge of the master and 1.0 corresponds to the right edge of the master. Location need not be in the range 0.0-1.0. If both -x and -relx are specified for a slave then their values are summed. For example, "-relx=>0.5, -x=-2" positions the left edge of the slave 2 pixels to the left of the center of its master.
-rely => location
Location specifies the y-coordinate within the master window of the anchor point for $slave widget. In this case the value is specified in a relative fashion as a floating-point number: 0.0 corresponds to the top edge of the master and 1.0 corresponds to the bottom edge of the master. Location need not be in the range 0.0-1.0. If both -y and -rely are specified for a slave then their values are summed. For example, -rely=>0.5, -x=>3 positions the top edge of the slave 3 pixels below the center of its master.
-width => size
Size specifies the width for $slave in screen units (i.e. any of the forms accepted by Tk_GetPixels). The width will be the outer width of $slave including its border, if any. If size is an empty string, or if no -width or -relwidth option is specified, then the width requested internally by the window will be used.
-x => location
Location specifies the x-coordinate within the master window of the anchor point for $slave widget. The location is specified in screen units (i.e. any of the forms accepted by Tk_GetPixels) and need not lie within the bounds of the master window.
-y => location
Location specifies the y-coordinate within the master window of the anchor point for $slave widget. The location is specified in screen units (i.e. any of the forms accepted by Tk_GetPixels) and need not lie within the bounds of the master window.
If the same value is specified separately with two different options, such as -x and -relx, then the most recent option is used and the older one is ignored.
$slave->placeForget
The placeForget method causes the placer to stop managing the geometry of $slave. As a side effect of this method call $slave will be unmapped so that it doesn't appear on the screen. If $slave isn't currently managed by the placer then the method call has no effect. placeForget returns an empty string as result.
$slave->placeInfo
The placeInfo method returns a list giving the current configuration of $slave. The list consists of -option=>value pairs in exactly the same form as might be specified to the place method.
$slave->placeSlaves
The placeSlaves method returns a list of all the slave windows for which $master is the master. If there are no slaves for $master then an empty list is returned.
If the configuration of a window has been retrieved with placeInfo, that configuration can be restored later by first using placeForget to erase any existing information for the window and then invoking place with the saved information.
FINE POINTS
It is not necessary for the master window to be the parent of the slave window. This feature is useful in at least two situations. First, for complex window layouts it means you can create a hierarchy of subwindows whose only purpose is to assist in the layout of the parent. The ``real children'' of the parent (i.e. the windows that are significant for the application's user interface) can be children of the parent yet be placed inside the windows of the geometry-management hierarchy. This means that the path names of the ``real children'' don't reflect the geometry-management hierarchy and users can specify options for the real children without being aware of the structure of the geometry-management hierarchy.
A second reason for having a master different than the slave's parent is to tie two siblings together. For example, the placer can be used to force a window always to be positioned centered just below one of its siblings by specifying the configuration
-in=>$sibling, -relx=>0.5, -rely=>1.0, -anchor=>'n', -bordermode=>'outside'
Whenever the $sibling widget is repositioned in the future, the slave will be repositioned as well.
Unlike many other geometry managers (such as the packer) the placer does not make any attempt to manipulate the geometry of the master windows or the parents of slave windows (i.e. it doesn't set their requested sizes). To control the sizes of these windows, make them windows like frames and canvases that provide configuration options for this purpose.
SEE ALSO
Tk::form, Tk::grid, Tk::pack
KEYWORDS
geometry manager, height, location, master, place, rubber sheet, slave, width
|
__label__pos
| 0.559061 |
[TASK] Optimize usage of debug_backtrace()
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / DebugUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
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 use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
17
18 /**
19 * Class to handle debug
20 */
21 class DebugUtility
22 {
23 /**
24 * Debug
25 *
26 * @param string $var
27 * @param string $header
28 * @param string $group
29 * @return void
30 */
31 public static function debug($var = '', $header = '', $group = 'Debug')
32 {
33 // buffer the output of debug if no buffering started before
34 if (ob_get_level() == 0) {
35 ob_start();
36 }
37 $debug = self::convertVariableToString($var);
38 if (TYPO3_MODE === 'BE' && !(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) {
39 $tabHeader = $header ?: 'Debug';
40 $script = '
41 (function debug() {
42 var message = ' . GeneralUtility::quoteJSvalue($debug) . ',
43 header = ' . GeneralUtility::quoteJSvalue($header) . ',
44 group = ' . GeneralUtility::quoteJSvalue($group) . ';
45 if (top.TYPO3.DebugConsole) {
46 top.TYPO3.DebugConsole.add(message, header, group);
47 } else {
48 var consoleMessage = [group, header, message].join(" | ");
49 if (typeof console === "object" && typeof console.log === "function") {
50 console.log(consoleMessage);
51 }
52 };
53 })();
54 ';
55 echo GeneralUtility::wrapJS($script);
56 } else {
57 echo $debug;
58 }
59 }
60
61 /**
62 * Converts a variable to a string
63 *
64 * @param mixed $variable
65 * @return string
66 */
67 public static function convertVariableToString($variable)
68 {
69 if (is_array($variable)) {
70 $string = self::viewArray($variable);
71 } elseif (is_object($variable)) {
72 $string = json_encode($variable, true);
73 } elseif ((string)$variable !== '') {
74 $string = htmlspecialchars((string)$variable);
75 } else {
76 $string = '| debug |';
77 }
78 return $string;
79 }
80
81 /**
82 * Opens a debug message inside a popup window
83 *
84 * @param mixed $debugVariable
85 * @param string $header
86 * @param string $group
87 */
88 public static function debugInPopUpWindow($debugVariable, $header = 'Debug', $group = 'Debug')
89 {
90 $debugString = self::convertVariableToString($debugVariable);
91 $script = '
92 (function debug() {
93 var debugMessage = ' . GeneralUtility::quoteJSvalue($debugString) . ',
94 header = ' . GeneralUtility::quoteJSvalue($header) . ',
95 group = ' . GeneralUtility::quoteJSvalue($group) . ',
96
97 browserWindow = function(debug, header, group) {
98 var newWindow = window.open("", "TYPO3DebugWindow_" + group,
99 "width=600,height=400,menubar=0,toolbar=1,status=0,scrollbars=1,resizable=1"
100 );
101 if (newWindow.document.body.innerHTML) {
102 newWindow.document.body.innerHTML = newWindow.document.body.innerHTML +
103 "<hr />" + debugMessage;
104 } else {
105 newWindow.document.writeln(
106 "<html><head><title>Debug: " + header + "(" + group + ")</title></head>"
107 + "<body onload=\\"self.focus()\\">"
108 + debugMessage
109 + "</body></html>"
110 );
111 }
112 };
113
114 if (top && typeof top.TYPO3 !== "undefined" && typeof top.TYPO3.Modal !== "undefined") {
115 top.TYPO3.Modal.show(
116 "Debug: " + header + " (" + group + ")",
117 debugMessage,
118 top.TYPO3.Severity.notice
119 );
120 } else {
121 browserWindow(debugMessage, header, group);
122 }
123 })();
124 ';
125 echo GeneralUtility::wrapJS($script);
126 }
127
128 /**
129 * Displays the "path" of the function call stack in a string, using debug_backtrace
130 *
131 * @return string
132 */
133 public static function debugTrail()
134 {
135 $trail = debug_backtrace(0);
136 $trail = array_reverse($trail);
137 array_pop($trail);
138 $path = array();
139 foreach ($trail as $dat) {
140 $pathFragment = $dat['class'] . $dat['type'] . $dat['function'];
141 // add the path of the included file
142 if (in_array($dat['function'], array('require', 'include', 'require_once', 'include_once'))) {
143 $pathFragment .= '(' . PathUtility::stripPathSitePrefix($dat['args'][0]) . '),' . PathUtility::stripPathSitePrefix($dat['file']);
144 }
145 $path[] = $pathFragment . '#' . $dat['line'];
146 }
147 return implode(' // ', $path);
148 }
149
150 /**
151 * Displays an array as rows in a table. Useful to debug output like an array of database records.
152 *
153 * @param mixed $rows Array of arrays with similar keys
154 * @param string $header Table header
155 * @param bool $returnHTML If TRUE, will return content instead of echo'ing out. Deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
156 * @return void Outputs to browser.
157 */
158 public static function debugRows($rows, $header = '', $returnHTML = false)
159 {
160 if ($returnHTML !== false) {
161 GeneralUtility::deprecationLog('Setting the parameter $returnHTML is deprecated since TYPO3 CMS 7 and will be removed in TYPO3 CMS 8.');
162 }
163 self::debug('<pre>' . DebuggerUtility::var_dump($rows, $header, 8, true, false, true), $header . '</pre>');
164 }
165
166 /**
167 * Returns a string with a list of ascii-values for the first $characters characters in $string
168 *
169 * @param string $string String to show ASCII value for
170 * @param int $characters Number of characters to show
171 * @return string The string with ASCII values in separated by a space char.
172 */
173 public static function ordinalValue($string, $characters = 100)
174 {
175 if (strlen($string) < $characters) {
176 $characters = strlen($string);
177 }
178 $valuestring = '';
179 for ($i = 0; $i < $characters; $i++) {
180 $valuestring .= ' ' . ord(substr($string, $i, 1));
181 }
182 return trim($valuestring);
183 }
184
185 /**
186 * Returns HTML-code, which is a visual representation of a multidimensional array
187 * use \TYPO3\CMS\Core\Utility\GeneralUtility::print_array() in order to print an array
188 * Returns FALSE if $array_in is not an array
189 *
190 * @param mixed $array_in Array to view
191 * @return string HTML output
192 */
193 public static function viewArray($array_in)
194 {
195 return '<pre>' . DebuggerUtility::var_dump($array_in, '', 8, true, false, true) . '</pre>';
196 }
197
198 /**
199 * Prints an array
200 *
201 * @param mixed $array_in Array to print visually (in a table).
202 * @return void
203 * @see viewArray()
204 */
205 public static function printArray($array_in)
206 {
207 echo self::viewArray($array_in);
208 }
209 }
|
__label__pos
| 0.997789 |
The forum will be down for maintenance at some point from Friday, November 16 at 19:00 EDT until Sunday, November 18 at 23:59 EDT. Downtime will be minimized but the exact timing is unknown.
I'm currently developing web app (PHP 7, Lumen framework 5) that communicates with SQL Anywhere database. I have succesfully created an SQL Anywhere database (version 17), and now I'm trying to insert data into database tables, but no luck. I have the following solution which works correctly (no errors during execution), but stores data into tables row by row:
$query = "INSERT INTO $table_name ($cols) " .
"VALUES (" . implode(",", array_fill(0, $cols_count, "?")) . ")";
foreach ($rows as $row) {
$stmt = sasql_prepare($conn, $query);
foreach (array_values($row) as $index => &$value) {
sasql_stmt_bind_param_ex(
$stmt, $index, $value,
$value ? gettype($value)[0] : 's',
$value === null
);
}
sasql_stmt_execute($stmt);
sasql_stmt_close($stmt);
}
However, when I try the next solution I receive the following error "sasql_stmt_execute(): SQLAnywhere: [-638] Right truncation of string data" (logic stays the same, but rows are stored all at once):
$row_placeholder = implode(",", array_fill(0, $cols_count, "?"));
$placeholders = implode(",", array_fill(0, count($rows), "($row_placeholder)"));
$query = "INSERT INTO $table_name ($cols) VALUES $placeholders";
$stmt = sasql_prepare($conn, $query);
$param_number = 0;
foreach ($rows as $row) {
foreach ($row as &$value) {
sasql_stmt_bind_param_ex(
$stmt, $param_number++, $value,
$value ? gettype($value)[0] : 's',
$value === null
);
}
}
sasql_stmt_execute($stmt);
sasql_stmt_close($stmt);
I don't know what can cause this error, as well as was not able to find a proper solution...Need help here.
asked 02 Jul, 06:23
ilyas_khametov's gravatar image
ilyas_khametov
31117
accept rate: 100%
edited 02 Jul, 14:23
SQLCODE -638 usually means exactly that:
Probable cause
Non-space characters were truncated upon the assignment of string data.
I'd guess the according data type of your column is too small to hold the full string data.
(02 Jul, 10:38) Volker Barth
Replies hidden
Ok, but why exactly the same rows (strings, integers, etc.) are normally stored (without errors) in database tables when inserting it one by one instead of inserting all at once?
(02 Jul, 12:37) ilyas_khametov
Can't tell that without knowing more details (commit behaviour, table schema, data) - however, you can temporarily ignore that error via setting the string_rtruncation option to Off, and then check what values might have been silently truncated - and additionally check whether the behaviour is different between the two code samples.
(02 Jul, 16:25) Volker Barth
I’d like to know the table Schema, but I remember that one smart guy said once that all (or maybe some) fixed length strings have a varying length. I couldn’t find the evidence in the documentation, but only this one:
CHAR is semantically equivalent to VARCHAR, although they are different types. In SQL Anywhere, CHAR is a variable-length type. In other relational database management systems, CHAR is a fixed-length type, and data is padded with blanks to max-length bytes of storage. SQL Anywhere does not blank-pad stored character data.
I agree with the database server. If you pass a string that is longer than a column, the further assumptions what the server does must be avoided. It is the application, that must truncate / validate the input. The DB server just warns you, and you have to fix it.
(04 Jul, 07:40) Vlad
Ok, but why exactly the same rows (strings, integers, etc.) are normally stored (without errors) in database tables when inserting it one by one instead of inserting all at once?
Vlad is correct that the message probably means what it says.
Can you display exactly what $query looks like in the second example? ...I don't know how PHP works so I can't figure it out for myself :)
(04 Jul, 08:50) Breck Carter
Another (possibly better) suggestion: Run dbsrv17.exe with the -zr ALL option to see exactly WHAT statements are being sent to the server... something is awry with the second example :)
(04 Jul, 08:54) Breck Carter
showing 1 of 6 show all flat view
Be the first one to answer this question!
toggle preview
Follow this question
By Email:
Once you sign in you will be able to subscribe for any updates here
By RSS:
Answers
Answers and Comments
Markdown Basics
• *italic* or _italic_
• **bold** or __bold__
• link:[text](http://url.com/ "title")
• image?
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
Question tags:
×111
×53
×31
×14
question asked: 02 Jul, 06:23
question was seen: 988 times
last updated: 04 Jul, 08:54
|
__label__pos
| 0.775844 |
I need to convert this code to web.config file. Plz Help..
#Fix Rewrite
Options -Multiviews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Rewriterule ^(.*)$ $1.php [L,QSA]
Does your web.config allow rewrite rules then? What are you trying to convert this to, IIS? Are you using IIS URL Rewrite?
I am trying to convert this piece of code to IIS.
@pritaeas .. thanks.. it solved my problem.
|
__label__pos
| 0.717666 |
Delete the resources - Amazon SDK for JavaScript
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China.
The Amazon SDK for JavaScript V3 API Reference Guide describes in detail all the API operations for the Amazon SDK for JavaScript version 3 (V3).
Starting October 1, 2022, Amazon SDK for JavaScript (v3) will end support for Internet Explorer 11 (IE 11). For details, see Announcing the end of support for Internet Explorer 11 in the Amazon SDK for JavaScript (v3).
Delete the resources
As stated at the beginning of this tutorial, be sure to terminate all of the resources you create while going through this tutorial to ensure that you’re not charged. You can do this by deleting the Amazon CloudFormation stack you created in the Create the Amazon resources topic of this tutorial,as follows:
1. Open the Amazon CloudFormation in the Amazon management console.
2. Open the Stacks page, and select the stack.
3. Choose Delete.
For more Amazon cross-service examples, see Amazon SDK for JavaScript cross-service examples.
|
__label__pos
| 0.778109 |
Mastering iOS auto layout anchors programmatically from Swift
Looking for best practices of using layout anchors? Let's learn how to use the iOS autolayout system in the proper way using Swift.
iOS
Creating views and constraints programmatically
First of all I'd like to recap the UIViewController life cycle methods, you are might familiar with some of them. They are being called in the following order:
• loadView
• viewDidLoad
• viewWillAppear
• viewWillLayoutSubviews
• viewDidLayoutSubviews
• viewDidAppear
In the pre-auto layout era, you had to do your layout calcuations inside the viewDidLayoutSubviews method, but since this is a pro auto layout tutorial we are only going to focus on the loadView & viewDidLoad methods. 🤓
These are the basic rules of creating view hierarchies using auto layout:
• Never calculate frames manually by yourself!
• Initialize your views with .zero rect frame
• Set translatesAutoresizingMaskIntoConstraints to false
• Add your view to the view hierarchy using addSubview
• Create and activate your layout constraints NSLayoutConstraint.activate
• Use loadView instead of viewDidLoad for creating views with constraints
• Take care of memory management by using weak properties
• Set every other property like background color, etc. in viewDidLoad
Enough theory, here is a short example:
class ViewController: UIViewController {
weak var testView: UIView!
override func loadView() {
super.loadView()
let testView = UIView(frame: .zero)
testView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(testView)
NSLayoutConstraint.activate([
testView.widthAnchor.constraint(equalToConstant: 64),
testView.widthAnchor.constraint(equalTo: testView.heightAnchor),
testView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
testView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
])
self.testView = testView
}
override func viewDidLoad() {
super.viewDidLoad()
self.testView.backgroundColor = .red
}
}
Pretty simple, huh? Just a few lines of code and you have a fixed size center aligned view with a dedicated class property reference. If you create the exact same through interface builder, the system will "make" you the loadView method for free, but you'll have to setup an IBOutlet reference to the view.
The eternal dilemma: code vs Interface Builder.
It really doesn't matters, feel free to chose your path. Sometimes I love playing around with IB, but in most of the cases I prefer the programmatic way of doing things. 😛
Common UIKit auto layout constraint use cases
So I promised that I'll show you how to make constraints programmatically, right? Let's do that now. First of all, I use nothing but layout anchors. You could waste your time with the visual format language, but that's definitely a dead end. So mark my words: use only anchors or stack views, but nothing else! 😇
Here are the most common patterns that I use to create nice layouts. 😉
Set fixed with or height
First one is the most simple one: set a view's height or a width to a fixed point.
testView.widthAnchor.constraint(equalToConstant: 320),
testView.heightAnchor.constraint(equalToConstant: 240),
Set aspect ratio
Settings a view's aspect ratio is just constrainting the width to the height or vica versa, you can simply define the rate by the multiplier.
testView.widthAnchor.constraint(equalToConstant: 64),
testView.widthAnchor.constraint(equalTo: testView.heightAnchor, multiplier: 16/9),
Center horizontally & vertically
Centering views inside another one is a trivial task, there are specific anchors for that.
testView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
testView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
Stretch | fill inside view with padding
The only tricky part here is that trailing and bottom constraints behave a little bit different, than top & leading if it comes to the constants. Usually you have to work with negative values, but after a few tries you'll understand the logic here. 😅
testView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 32),
testView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 32),
testView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -32),
testView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -32),
Proportional width or height
If you don't want to work with constant values, you can use the multiplier.
testView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1/3),
testView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 2/3),
Using safe area layout guides
With the latest iPhone you'll need some guides in order to keep you safe from the notch. This is the reason why views have the safeAreaLayoutGuide property. You can get all the usual anchors after calling out to the safe area guide. 💪
testView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
testView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
testView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
testView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
Animating layout constraints
Animation with constraints is easy, you shouldn't believe what others might say. I made some rules and an example that'll help you understanding the basic principles of animating constant values of a constraint, plus toggling various constraints. 👍
Rules:
• Use standard UIView animation with layoutIfNeeded
• Always deactivate constraints first
• Hold to your deactivated constraints strongly
• Have fun! 😛
Constraint animation example:
class ViewController: UIViewController {
weak var testView: UIView!
weak var topConstraint: NSLayoutConstraint!
var bottomConstraint: NSLayoutConstraint!
var heightConstraint: NSLayoutConstraint!
override func loadView() {
super.loadView()
let testView = UIView(frame: .zero)
testView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(testView)
let topConstraint = testView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
let bottomConstraint = testView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
NSLayoutConstraint.activate([
topConstraint,
testView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
testView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
bottomConstraint,
])
let heightConstraint = testView.heightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.5)
self.testView = testView
self.topConstraint = topConstraint
self.bottomConstraint = bottomConstraint
self.heightConstraint = heightConstraint
}
override func viewDidLoad() {
super.viewDidLoad()
self.testView.backgroundColor = .red
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapped))
self.view.addGestureRecognizer(tap)
}
@objc func tapped() {
if self.topConstraint.constant != 0 {
self.topConstraint.constant = 0
}
else {
self.topConstraint.constant = 64
}
if self.bottomConstraint.isActive {
NSLayoutConstraint.deactivate([self.bottomConstraint])
NSLayoutConstraint.activate([self.heightConstraint])
}
else {
NSLayoutConstraint.deactivate([self.heightConstraint])
NSLayoutConstraint.activate([self.bottomConstraint])
}
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
}
}
It's not that bad, next: adaptivity and supporting multiple device screen sizes. 🤔
How to create adaptive layouts for iOS?
Even Apple is struggling with adaptive layouts in the built-in iOS applications. If you look at apps that are made with collection views - like photos - layouts are pretty ok on every device. However there are a few other ones, that - in my opinion - are horrible experiences on a bigger screen. #justusecollectionviewforeverything. 🤐
Rotation support
Your first step to adaptive layout is supporting multiple device orientations. You can check my previous article about iOS auto layout there are lots of great stuff inside that article about rotation support, working with layers inside auto layout land, etc. 🌈
Trait collections
Second step is to adapt trait collections. UITraitCollection is there for you to group all the environmental specific traits such as size classes, display scale, user interface idom and many more. Most of the times you will have to check the vertical & horizontal size classes. There is a reference of device size classes and all the possible variations made by Apple, see the external sources section below. 😉
This little Swift code example below is demonstrating how to check size classes for setting different layouts for compact and regular screens.
class ViewController: UIViewController {
weak var testView: UIView!
var regularConstraints: [NSLayoutConstraint] = []
var compactConstraints: [NSLayoutConstraint] = []
override func loadView() {
super.loadView()
let testView = UIView(frame: .zero)
testView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(testView)
self.regularConstraints = [
testView.widthAnchor.constraint(equalToConstant: 64),
testView.widthAnchor.constraint(equalTo: testView.heightAnchor),
testView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
testView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
]
self.compactConstraints = [
testView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
testView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
testView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
testView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
]
self.activateCurrentConstraints()
self.testView = testView
}
private func activateCurrentConstraints() {
NSLayoutConstraint.deactivate(self.compactConstraints + self.regularConstraints)
if self.traitCollection.verticalSizeClass == .regular {
NSLayoutConstraint.activate(self.regularConstraints)
}
else {
NSLayoutConstraint.activate(self.compactConstraints)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.testView.backgroundColor = .red
}
// MARK: - rotation support
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .portrait
}
// MARK: - trait collections
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.activateCurrentConstraints()
}
}
Device detection
You can also check the user interface idom through the UIDevice class (aka. is this freakin' device an iPhone or an iPad?) to set for example font sizes based on it. 📱
UIDevice.current.userInterfaceIdiom == .pad
Screen size
Another option to figure out your environment is checking the size of the screen. You can check the native pixel count or a relative size based in points.
//iPhone X
UIScreen.main.nativeBounds // 1125x2436
UIScreen.main.bounds // 375x812
Usually I'm trying to keep myself to these rules. I don't really remember a scenario where I needed more than all the things I've listed above, but if you have a specific case or questions, please don't hesitate to contact me. 😉
Share this article on Twitter.
Thank you. 🙏
Picture of Tibor Bödecs
Tibor Bödecs
Creator of https://theswiftdev.com (weekly Swift articles), server side Swift enthusiast, full-time dad. -- Follow me & feel free to say hi. 🤘🏻 -- #iOSDev #SwiftLang
Twitter · GitHub
📬
100% Swift news, delivered right into your mailbox
Subscribe to my monthly newsletter. On the first Monday of every month, you'll get an update about the most important Swift community news, including my articles.
|
__label__pos
| 0.544592 |
0
$\begingroup$
I am learning about computational models, I wonder why Turing chose his model of Turing machines (the strip with the head and Read / Move left or right / Change state). I am suspecting his physical machine Enigma was having a stripe and behaved similarly. Is this correct?
The circuit gates model seems close to what an electronic circuit can do (and seems more natural?), why aren't we using it?
If the two models are equivalent (are they?), then we can just use the simplest ? Why then is the Turing machine model more simple than the other models?
$\endgroup$
1
• $\begingroup$ Did you read Turing's original paper? It is very readable and it explains carefully what the significance of the model is. $\endgroup$ Jul 21 at 8:29
2 Answers 2
2
$\begingroup$
It's important to understand that the field of "computability", together with its vocabulary and formalisms, wasn't a thing in Turing's time.
Also, when introducing his machines, he was not trying to come up with a "computer architecture" in the sense understood today, planning a machine that you can build for problem-solving purposes.
Turing was intersted in a meta-mathematical problem that can be roughly stated as: what can a mathematician "solve" in a way that doesn't involve any insight or leap of creativity?$^1$
In his original 1936 paper describing these machines, he dedicates a third of section 9. ("The extent of the computable numbers - (a)") to justifying his "design choices":
He imagines a human trying to solve some mathematical problem, on a typical "child's arithmetic book", with the page divided into squares:$^2$
• the "pages" are irrelevant, simply glue them all side by side to have just one long page
• the "lines" are irrelevant, cut the page and glue the lines side by side to have a really long line
• if you reach the end, buy another notebook, glue it to the end of your current one then keep going; similarly for if you reach the beginning$^3$
• the symbols that can be written in a square must be distinguishable, so their difference can't be arbitrarily small; hence, a finite number of symbols
• the number of observable symbols must be bounded - you can't notice everything at once; you can then straightforwardly argue that if there's a finite bound $B$, you could just as well reduce it to 1; thus a RW head placed over one symbol
• when you're working on the problem, you operate in steps; at any step you can make a decision based on only two factors: what you're observing and what you're thinking, some "mental state";
• you can choose to write something new; you can choose whether to read on, but you can't just jump with your eyes to some arbitrary point, you wouldn't know where to land; you can only go in a near place to the left or to the right (again, you can straightforwardly argue that you can reduce this to just 1 position L/R); finally you can choose to change your mental state. Hence, you get the transition function of a Turing Machine
• like the symbols used, he argues that mental states must be finite.
From these principles, the Turing Machines follows naturally. Other computational models (e.g. Gödel's recursive functions, Church's lambda calculus) also aimed at answering this question, of what can be resolved "algorithmically"; they were trying to synthesize a vague, intuitive and imprecise philosophical concept as a rigorous mathematical formalism.
Turing's machines were the most compelling; it was the most successful at convincing people that the set of things computable by a Turing machine is indeed the sought-for set of "effectively calculable" things. The fact that other models with the same aim could be formally proven to "compute" exactly the Turing-computable things, served to further cement this idea; that "effectively calculable" is "Turing computable".
$^1$ The term used for such tasks was "effectively-calculable"; I recommend reading the first section of the SEP entry on the Church-Turing thesis for more background.
$^2$ You also need to adopt the convention that you write one symbol per square; so no large "m" taking two squares.
$^3$ It's very important, IMO, to understand that a Turing Machine doesn't require "infinite" amounts of tape; in fact, at any point $i$ of computation, at most $i$ squares can be non-blank, always a finite number; you just need "an arbitrarily large number"
$\endgroup$
1
$\begingroup$
The Turing machine is a very simple concept, based on two components: the program (a finite state machine) and an infinite memory (the strip). The FMSs were well-known at the time of Turing, as were the pushdown automata (a refinement of the former). Replacing the stack (of the SA) by a strip increases the power of the machine to an extent considered as sufficient to represent any imaginable computation. (Technically, a Turing machine can handle non-context-free grammars.)
Enigma does not have the power of a Turing Machine and AFAIK, has little in common. It is quite ad-hoc to break the encryption method used by the Germans.
The Turing Machine is a theoretical tool with a sound mathematical representation, which is much more compact and convenient to handle than logical circuits can be. In particular, it is not tied to the binary basis and does not need any diagrammatic routing.
$\endgroup$
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.894643 |
How Many Topics can be Packed into a Short OTN Thread?
21 01 2010
January 21, 2010
This thread from 2008 has 31 replies:
http://forums.oracle.com/forums/thread.jspa?messageID=2502493&tstart=0
The thread starts off with a simple statement, without a lot of technical detail (kind of like this example):
“We are runing in 10g (10.2.0.3), when using full table scan, the perfromance is very slow. Is a bug in ASM or SQL program problem? How can I vertify the problem come from? I have runing health check in oracle but found nothing.”
So, where does the thread head? Topics?
• “By definition the Full Table Scan access is the most feared enemy, you should avoid that monster when your tables are huge (many rows &/or long rows).”
• “Not all full table scans are bad, not all indexes are good”
• Enabling a 10046 trace file for a session might help.
• “Usually you don’t want your applications to access a very large part of a large table. This will be very slow and could deteriorate the performance of your application severely.”
• “We had the same issues with full table scans in 10.2.0.3 where we had gathered system stats”
• “If I’m not mistaken, Oracle says that if you query 7.5% of the table rows and above you are usually better off with an FTS” A link was provided by someone else to a site that made a similar claim.
• “I can very easily give you an example where an index would be the best option to query 99% of data. I can very easily give you an example where a FTS is the best option to query 1% of data.”
• What is noise in a thread?
• A full tablescan reads all of the blocks up to the high watermark – but does it always?
• “The only way to improve the end-to-end performance of a full-table scan is Oracle parallel query (OPQ).” – or is it?
• “That’s improved the tablescan by a factor of nearly 30 simply by changing the array fetch size”
• Properly setting the DB_FILE_MULTIBLOCK_READ_COUNT will have an impact on the performance of a full table scan.
• The value of a 10046 trace, a test case.
In this OTN thread I provided a nice litte test case that showed a 10046 trace where a full table scan operation did not read all of the table blocks up to the high watermark for the table. That test case appears below:
CREATE TABLE T1(
C1 NUMBER(10),
C2 VARCHAR2(255),
C3 VARCHAR2(255),
C4 VARCHAR2(255));
INSERT INTO
T1
SELECT
ROWNUM RN,
LPAD('A',255,'A'),
LPAD('B',255,'B'),
LPAD('C',255,'C')
FROM
DUAL
CONNECT BY
LEVEL<=500000;
COMMIT;
We have a table with 500,000 rows with possibly 10 rows per 8KB block (AVG_ROW_LEN is 772). Now, flush the buffer cache to force physical reads:
ALTER SYSTEM FLUSH BUFFER_CACHE;
ALTER SYSTEM FLUSH BUFFER_CACHE;
Now, let’s force a full table scan (a 10046 trace is enabled at level 8, and a DBMS_XPLAN is generated):
SELECT
*
FROM
T1
WHERE
ROWNUM<=1000;
DBMS_XPLAN (partial output):
----------------------------------------------------------------------------------------------
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers | Reads |
----------------------------------------------------------------------------------------------
|* 1 | COUNT STOPKEY | | 1 | | 1000 |00:00:00.10 | 123 | 176 |
| 2 | TABLE ACCESS FULL| T1 | 1 | 500K| 1000 |00:00:00.08 | 123 | 176 |
----------------------------------------------------------------------------------------------
Did the TABLE ACCESS FULL (full table scan) operation in the plan indicate that Oracle read all blocks up to the high water mark (I intentially excluded the Access/Filter Predicates)? Oracle did NOT read all blocks up to the high water mark, regardless of what the plan shows. The proof is in the 10046 trace file:
=====================
PARSING IN CURSOR #11 len=54 dep=0 uid=63 oct=3 lid=63 tim=1044938463796 hv=4195490999 ad='1c501fdc' sqlid='g386bagx1475r'
SELECT
*
FROM
T1
WHERE
ROWNUM<=1000
END OF STMT
PARSE #11:c=0,e=2282,p=0,cr=0,cu=0,mis=1,r=0,dep=0,og=4,tim=1044938463790
EXEC #11:c=0,e=50,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=4,tim=1044938464457
WAIT #11: nam='SQL*Net message to client' ela= 7 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938464504
WAIT #11: nam='db file sequential read' ela= 40853 file#=1 block#=84361 blocks=1 obj#=72319 tim=1044938505437
WAIT #11: nam='reliable message' ela= 232 channel context=563314104 channel handle=563285032 broadcast message=564250208 obj#=72319 tim=1044938506251
WAIT #11: nam='enq: KO - fast object checkpoint' ela= 163 name|mode=1263468550 2=65558 0=1 obj#=72319 tim=1044938506489
WAIT #11: nam='direct path read' ela= 41814 file number=1 first dba=84362 block cnt=7 obj#=72319 tim=1044938586589
WAIT #11: nam='direct path read' ela= 19323 file number=1 first dba=87305 block cnt=48 obj#=72319 tim=1044938606571
FETCH #11:c=0,e=142335,p=86,cr=15,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938606885
WAIT #11: nam='SQL*Net message from client' ela= 1258 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938608214
WAIT #11: nam='SQL*Net message to client' ela= 3 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938608305
FETCH #11:c=0,e=690,p=0,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938608971
WAIT #11: nam='SQL*Net message from client' ela= 656 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938609666
WAIT #11: nam='SQL*Net message to client' ela= 2 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938609725
FETCH #11:c=0,e=687,p=0,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938610396
WAIT #11: nam='SQL*Net message from client' ela= 579 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938611012
WAIT #11: nam='SQL*Net message to client' ela= 3 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938611072
FETCH #11:c=0,e=681,p=0,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938611734
WAIT #11: nam='SQL*Net message from client' ela= 742 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938612512
WAIT #11: nam='SQL*Net message to client' ela= 3 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938612575
WAIT #11: nam='direct path read' ela= 4898 file number=1 first dba=87361 block cnt=30 obj#=72319 tim=1044938618207
FETCH #11:c=0,e=5901,p=42,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938618458
WAIT #11: nam='SQL*Net message from client' ela= 631 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938619135
WAIT #11: nam='SQL*Net message to client' ela= 3 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938619197
FETCH #11:c=0,e=681,p=0,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938619860
WAIT #11: nam='SQL*Net message from client' ela= 581 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938620476
WAIT #11: nam='SQL*Net message to client' ela= 3 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938620532
FETCH #11:c=0,e=683,p=0,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938621199
WAIT #11: nam='SQL*Net message from client' ela= 920 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938622154
WAIT #11: nam='SQL*Net message to client' ela= 3 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938622219
WAIT #11: nam='direct path read' ela= 8072 file number=1 first dba=87391 block cnt=42 obj#=72319 tim=1044938630900
FETCH #11:c=0,e=8966,p=48,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938631167
WAIT #11: nam='SQL*Net message from client' ela= 613 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938631822
WAIT #11: nam='SQL*Net message to client' ela= 2 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938631880
FETCH #11:c=0,e=686,p=0,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938632550
WAIT #11: nam='SQL*Net message from client' ela= 583 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938633168
WAIT #11: nam='SQL*Net message to client' ela= 2 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938633271
FETCH #11:c=0,e=675,p=0,cr=12,cu=0,mis=0,r=100,dep=0,og=4,tim=1044938633928
WAIT #11: nam='SQL*Net message from client' ela= 602 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938634565
WAIT #11: nam='direct path read' ela= 22151 file number=1 first dba=86793 block cnt=48 obj#=72319 tim=1044938656764
FETCH #11:c=0,e=22249,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=4,tim=1044938656854
STAT #11 id=1 cnt=1000 pid=0 pos=1 obj=0 op='COUNT STOPKEY (cr=123 pr=176 pw=176 time=37561 us)'
STAT #11 id=2 cnt=1000 pid=1 pos=1 obj=72319 op='TABLE ACCESS FULL T1 (cr=123 pr=176 pw=176 time=34756 us cost=8433 size=386000000 card=500000)'
WAIT #11: nam='SQL*Net message to client' ela= 4 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938656998
WAIT #11: nam='SQL*Net message from client' ela= 132538 driver id=1413697536 #bytes=1 p3=0 obj#=72319 tim=1044938789567
=====================
From the trace file we see many interesting details, including the absence of the typical db file scattered reads commonly associated with full table scans. From the trace it is also possible to see that 100 rows were read at a time, with a fairly consistent delay between requests for each set of the 100 rows. What else might we see in the trace file that would help us identify the source of a performance problem?
Actions
Information
2 responses
21 01 2010
Taral Desai
Hi Charles,
It’s very interesting one. Also, can you please elaborate if possible from Jonathan post saying
” through the index, you will hit the root block of the index one, and the table block once for a total of 2 LIOs. If you do a tablescan you will access the segment header block twice (9i onwards) and the table block once for a total of 3 LIO”
1. Table scan will access segment block twice . How can we arrive at this number any proof
2. So, does this means that ever block access has 3 LIO for table.
3. If i am understanding right then for Index range scan it will hit root + branch + blevel (total 3 LIO) for ever scan.(every value scan) any example
22 01 2010
Charles Hooper
I was hoping that Jonathan would see your question and provide you with a very carefully constructed answer to your questions. The results could be different depending on whether you are using dictionary managed tablespaces, locally managed tablespaces with manual freelist management, or locally managed tablespaces with ASSM AUTO ALLOCATEd management.
How to demonstrate what is happening? Setting event 10200 causes all logical IOs to be written to a trace file. See:
http://www.freelists.org/post/oracle-l/Logical-IO,3
http://www.juliandyke.com/Diagnostics/Events/EventReference.html#10200
Keep in mind that Jonathan is referring to a very specific case in the response that you quoted, a case where there is a table with a single row in a table with a single column that also has an index on that single column. In such a case, the index structure will contain a single block – the root block, so an index access to the one block would require reading the index root block, and then the table block pointed to by the index entry. I believe that Richard Foote’s blog contains several examples of how this would work for very small index structures.
So, how to set up a test case (note that I modified this to have a table with two columns)?
CREATE TABLE T1 (
C1 NUMBER,
C2 NUMBER,
PRIMARY KEY (C1));
INSERT INTO T1 VALUES(1,1);
COMMIT;
EXEC DBMS_STATS.GATHER_TABLE_STATS(OWNNAME=>USER,TABNAME=>'T1',CASCADE=>TRUE)
OK, we now have a table defined with two columns, with a primary key index, and a single row. Now the test case:
SELECT /*+ GATHER_PLAN_STATISTICS FULL(T1) */
*
FROM
T1;
SELECT
*
FROM
TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL,NULL,'ALLSTATS LAST'));
SELECT /*+ GATHER_PLAN_STATISTICS INDEX(T1) */
*
FROM
T1;
SELECT
*
FROM
TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL,NULL,'ALLSTATS LAST'));
ALTER SESSION SET EVENTS '10200 TRACE NAME CONTEXT FOREVER, LEVEL 1';
ALTER SESSION SET TRACEFILE_IDENTIFIER = 'Event10200Test1';
SELECT /*+ GATHER_PLAN_STATISTICS FULL(T1) */
*
FROM
T1;
ALTER SESSION SET TRACEFILE_IDENTIFIER = 'Event10200Test2';
SELECT /*+ GATHER_PLAN_STATISTICS INDEX(T1) */
*
FROM
T1;
ALTER SESSION SET EVENTS '10200 TRACE NAME CONTEXT OFF';
The output from the above for Oracle 10.2.0.x with an ASSM AUTO ALLOCATEd tablespace follows:
SQL_ID 0yp492wfxqf3q, child number 0
-------------------------------------
SELECT /*+ GATHER_PLAN_STATISTICS FULL(T1) */ * FROM T1
Plan hash value: 3617692013
------------------------------------------------------------------------------------
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers |
------------------------------------------------------------------------------------
| 1 | TABLE ACCESS FULL| T1 | 1 | 1 | 1 |00:00:00.01 | 7 |
------------------------------------------------------------------------------------
SQL_ID 2v0wvvx7sjxj8, child number 0
-------------------------------------
SELECT /*+ GATHER_PLAN_STATISTICS INDEX(T1) */ * FROM T1
Plan hash value: 3727918903
------------------------------------------------------------------------------------------------------
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers |
------------------------------------------------------------------------------------------------------
| 1 | TABLE ACCESS BY INDEX ROWID| T1 | 1 | 1 | 1 |00:00:00.01 | 2 |
| 2 | INDEX FULL SCAN | SYS_C0020540 | 1 | 1 | 1 |00:00:00.01 | 1 |
------------------------------------------------------------------------------------------------------
As you can see from the above, the full table scan required 7 logical IOs, and the index access required 2 logical IOs (1 for the index root block, and a second for the parent operation’s table access). Let’s take a look in the trace files:
From event10200test1 (full table scan – slightly trimmed for space):
Consistent read started for block 4 : 0110ae0c
Consistent read finished for block 4 : 110ae0c
Consistent read finished for block 4 : 110ae0c
Consistent read started for block 4 : 0110ae0d
Consistent read finished for block 4 : 110ae0d
Consistent read finished for block 4 : 110ae0d
Consistent read started for block 4 : 0110ae0e
Consistent read finished for block 4 : 110ae0e
Consistent read finished for block 4 : 110ae0e
Consistent read started for block 4 : 0110ae0f
Consistent read finished for block 4 : 110ae0f
Consistent read finished for block 4 : 110ae0f
Consistent read started for block 4 : 0110ae10
Consistent read finished for block 4 : 110ae10
Consistent read finished for block 4 : 110ae10
From event10200test1 (index full scan – slightly trimmed for space):
Consistent read started for block 4 : 0110ae1c
Consistent read finished for block 4 : 110ae1c
Consistent read started for block 4 : 0110ae0e
Consistent read finished for block 4 : 110ae0e
Consistent read finished for block 4 : 110ae0e
So, what are those blocks? Well, you could execute something like this to look at the table’s blocks (note that this could be very slow):
SELECT /*+ ORDERED */
DE.BLOCK_ID+C.COUNTER BLOCK_ID,
TO_CHAR(DE.BLOCK_ID+C.COUNTER,'XXXXXXXX') HEX_BLOCK_ID,
DE.BLOCKS,
C.COUNTER+1 COUNTER
FROM
(SELECT
BLOCK_ID,
BLOCKS
FROM
DBA_EXTENTS
WHERE
OWNER=USER
AND SEGMENT_NAME IN ('T1')) DE,
(SELECT
ROWNUM-1 COUNTER
FROM
DUAL
CONNECT BY
LEVEL<=64) C
WHERE
DE.BLOCKS>C.COUNTER
ORDER BY
C.COUNTER;
BLOCK_ID HEX_BLOCK BLOCKS COUNTER
---------- --------- ---------- ----------
1093129 10AE09 8 1
1093130 10AE0A 8 2
1093131 10AE0B 8 3
1093132 10AE0C 8 4
1093133 10AE0D 8 5
1093134 10AE0E 8 6
1093135 10AE0F 8 7
1093136 10AE10 8 8
So, during the full table scan, Oracle read blocks 4, 5, 6, 7, and 8 – for a total of 5 logical IO blocks reads. But, the DBMS_XPLAN output clearly showed that were 7 logical IO blocks read, so what about the other two logical IOs. I suppose that there is another event that needs to be set to see those logical IOs.
Leave a Reply
Fill in your details below or click an icon to log in:
WordPress.com Logo
You are commenting using your WordPress.com account. Log Out / Change )
Twitter picture
You are commenting using your Twitter account. Log Out / Change )
Facebook photo
You are commenting using your Facebook account. Log Out / Change )
Google+ photo
You are commenting using your Google+ account. Log Out / Change )
Connecting to %s
Follow
Get every new post delivered to your Inbox.
Join 128 other followers
%d bloggers like this:
|
__label__pos
| 0.913108 |
public marks
PUBLIC MARKS from bhartzer with tags i & weinberg
February 2008
Zicam and the Reputation Management Fiasco
Awhile ago, I used Twitter to talk about one of my favorite cold remedy vitamins, Airborne. It was then that two friends suggested Zicam to me. When stocking up on medication for the winter months, the high recommendations of Zicam had me buying the oral mist.
December 2007
Why Nobody Should Buy Digg
It hasn’t even been a week and my once positive outlook of Digg has come to a sour end. Yesterday, Brian Clark over at Copyblogger wrote that Digg is dead. You know, for awhile, I was giving Digg the benefit of the doubt.
How I Network on Friendster, Facebook, MySpace, and LinkedIn » techipedia | tamar weinberg
I am fascinated by the amount of social networks that I’m part of, but better yet, I’m intrigued to find that I assume different “personas,” at least in terms of choosing friends (and using the networks), on each social site. Are you the same?
bhartzer's TAGS related to tag i
10 + 2007 + 2008 + 5 + about + amp + an + best + blog + blog spotlight + blogging + blogs + Britney Spears + broden + business + by + care + celebrity + cookies + dallas + do + domain + domain name + domain names + Domains + earth day 2008 + electricity + engine + entertainment + facebook + famous + get + gift basket + google + google search results + home + how + How I Met Your Mother + internet + is + its + lawyers + link + links + make + management + marketing + media + microsoft + money + music + new + news + newsroom + â + now + of + online + other + our + over + pricegrabber + s + search + search engine + search engine optimization + seo + services + Should + site + social + social media + social networking + stories + strategy + tamar + tech + techipedia + technology + texas + that + tips + top + us + way + web + websites + weinberg + what + why + will + with + work + yahoo + yahoo shopping + year + you + your + | + +
|
__label__pos
| 0.704319 |
Logo: Relish
1. Sign in
Project: RSpec Rails 3.9
Cookies
Controller specs wrap Rails controller tests, which expose a few different ways
to access cookies:
@request.cookies['key']
@response.cookies['key']
cookies['key']
rails-3.0.x and 3.1 handle these slightly differently, so to avoid confusion, we recommend
the following guidelines:
Recommended guidelines for rails-3.0.0 to 3.1.0
• Access cookies through the request and response objects in the spec.
• Use request.cookies before the action to set up state.
• Use response.cookies after the action to specify outcomes.
• Use the cookies object in the controller action.
• Use String keys.
# spec
request.cookies['foo'] = 'bar'
get :some_action
expect(response.cookies['foo']).to eq('modified bar')
# controller
def some_action
cookies['foo'] = "modified #{cookies['foo']}"
end
Why use Strings instead of Symbols?
The cookies objects in the spec come from Rack, and do not support
indifferent access (i.e. :foo and "foo" are different keys). The cookies
object in the controller does support indifferent access, which is a bit
confusing.
This changed in rails-3.1, so you can use symbol keys, but we recommend
sticking with string keys for consistency.
Why not use the cookies method?
The cookies method combines the request and response cookies. This can
lead to confusion when setting cookies in the example in order to set up state
for the controller action.
# does not work in rails 3.0.0 > 3.1.0
cookies['foo'] = 'bar' # this is not visible in the controller
get :some_action
Future versions of Rails
There is code in the master branch in rails that makes cookie access more
consistent so you can use the same cookies object before and after the action,
and you can use String or Symbol keys. We'll update these docs accordingly when
that is released.
Last published 8 months ago by Jon Rowe.
|
__label__pos
| 0.984728 |
Crystal Reports – How to display boolean true/false as checkbox
The steps below show how to display boolean true/false values as a checkbox with either a tick and/or cross.
By default these values are displayed as either ‘True’ or ‘False’.
crystalreports-booleantick1
1. In the Field Explorer right-click on ‘Formula Fields’ and choose ‘New’
2. crystalreports-booleantick2
3. Enter a name for the formula, e.g. tick_user_likes_fruit
4. Add in the following formula (replace {Sheet1_.user_likes_fruit} for your field)
5. if NOT ISNULL({Sheet1_.user_likes_fruit}) AND {Sheet1_.user_likes_fruit} then
Chr(254)
else
Chr(253)
6. Save and close the window
7. Add the formula field to the report.
8. Change the font for the field to Wingdings
9. The field will now display ticks and crosses that correspond to the boolean value.
Similar characters
The following values may also be used
Symbol Name Value
Ballot X 251
Check mark 252
Ballot box with X 253
Ballot box with check mark 254
|
__label__pos
| 0.816352 |
Q&A from the article:
Spy On Your Boyfriend, Girlfriend or Children's Text Messages and Emails from a Cellphone
Edited by pinkpower, Calob Horton, sadmanahmed, Eng and 13 others
Contents
Questions and Answers
How can I check her phone messages such as Viber?
My girlfriend is overseas. My girlfriend uses an iPhone. I have an Android phone. How do I check her messages? Please, solve my problem. Thank you so much.
Ad
Since your girlfriend is overseas and you have no physical access to her iPhone, you will need to use a remote-install spy application. While remote-install spy applications are generally not as reliable as spy applications that require a physical installation, they may still work for spying on your girlfriend's messages.
Was this helpful? Yes | No | I need help
These applications may or may not work for you, and they also may or may not be illegal in your area. Before you try any of the remote-install spy applications listed above, be sure to contact local law enforcement to learn about your area's laws regarding cellphone spying.
Was this helpful? Yes | No | I need help
See more questions like this: I want to check the deleted Viber messages from my girlfriend's phone.
Can I check my fiance's Viber messages without accessing to her phone?
I think my fiance is cheating on me and I want to know but don't want to jeopardize our relation by asking her, so I need something to access her Viber messages but I can't get hold of her phone. Can you help?
Was this helpful? Yes | No | I need help
Advertisement
With an app like Auto Forward you can spy on her phone without physically installing any apps. Your viewpoint of not asking her though is not a good start to a marriage. If you ask her about the possibility of cheating you do not have to do so in an accusatory manner but could approach the subject by asking her if she is truly sure that she wants to spend the rest of her life with only you. Spying on her with a spy app will harm your relationship if she finds out, especially if you never tried to have a conversation about your insecurities with her.
Was this helpful? Yes | No | I need help
I want to check on my girlfriend SMS and WhatsApp calls without her phone?
I want to spy on my girlfriend phone
Advertisement
Any of the spy apps listed here like mSpy can monitor WhatsApp data and SMS. Make sure that what you are about to do is not illegal in your area.
See more questions like this: Sir, How can I check messages of my girlfriend cell?
I have the phone number of my friend, he is using Viber, I need to know all his history?
Please make it free of charge
Why do you need to spy on your friend? That is such an invasion of privacy and unless your friend is in immediate danger you should not violate that privacy. Instead you should ask him about the questions that you have and give him the chance to decide whether to tell you about that.
Was this helpful? Yes | No | I need help
The above questions are from the following wiki...
Spy On Your Boyfriend, Girlfriend or Children's Text Messages and Emails from a Cellphone
More questions and answers
How can I find out who is contacting on Skype on husband phone?
if my husband has Skype app on his cell phone, how do I find out who he is contacting?
If you install once of the reputable apps mentioned in the VisiHow article on this page you will be able to see who is contacting through Skype. First you can try to get access to his phone while he is sleeping or otherwise occupied and if you load up the Skype app there will be a contact history and you can see if he is talking to anyone as well as messages within Skype.
Was this helpful? Yes | No | I need help
Want to spy on phone and social network?
Want to spy on every activity of phone as well as laptop. I have tried: No. I think it was caused by: No
Spy software like mSpy can monitor both their phone and laptop. You will have to purchase the phone and PC plans separately but the PC plan is under $10 a month.
Is it possible to spy on a phone without it being around me, just with the IP?
My boyfriend is ruining my life, and I need to know what he is up to, I don't even want to risk my family's life!. I have tried: I can't even unlock it because he has a code on it , I've tried hacking the code but I couldn't.
Was this helpful? Yes | No | I need help
If you use an app like FlexiSpy Extreme or Auto Forward you can remotely monitor his phone without having to unlock the phone. You are fearful for your family's safety and it is time to contact authorities and even if they can not help they will assist you with local programs that can keep your family and you safe. Using a spy app will not exactly ensure your safety.
Was this helpful? Yes | No | I need help
I'm wondering if there is anything out there that can use someone else phone as a listening device as well as read messages and listen to phone calls - I do not have access to the iPhone in question, in fact she is in another country?
I'm wondering if there is anything out there that can use someone else phone as a listening device as well as read messages and listen to phone calls - I do not have access to the iPhone in question, in fact she is in another country?
Was this helpful? Yes | No | I need help
There are no spy apps that can be installed remotely like Auto Forward yet turn on the mic and record calls. The Auto Forward app will give you call logs and how long she was on the phone with that person as well as all other SMS and social media data.
Was this helpful? Yes | No | I need help
See more questions like this: How can I access Viber messages on iPhone without him knowing so I can see all activities with my cheating boyfriend?
I need to access a Viber account in full, how can I go about it without accessing the phone being its abroad and I cannot get hold of it?
I need to access a Viber account, how do I go about it, I cannot get hold of the phone being its a broad. I have tried: Tried looking at spyware but I need access to the phone which I cannot get hold at all being its abroad all the way. I think it was caused by: None so far
Was this helpful? Yes | No | I need help
You will need an app that can monitor remotely like Auto Forward.
See more questions like this: I need to hack my fiancee Viber account asap can you show me how?
I want to log in to someone's Viber without touching their cell phone?
I want to download Viber to my desktop and see if I can log in as my girlfriend and see her messages. I have tried: All others required me to install some form of data on her phone
VisiHow QnA. This section is not written yet. Want to join in? Click EDIT to write this answer.
Want to know if I can read my daughter Viber message without touching it because she is in Africa?
Want to know if I can read my daughter Viber message without touching it because she is in Africa
VisiHow QnA. This section is not written yet. Want to join in? Click EDIT to write this answer.
My wife lives overseas and I heard she is having an affair. I want to see all her messages to see if it is true?
How do I see if she is really cheating? I have tried: Nothing. I think it was caused by: Not really sure
VisiHow QnA. This section is not written yet. Want to join in? Click EDIT to write this answer.
How can I monitor my husband cellphone without touching his cellphone?
My husband is not always around. I have tried: Cellphone checking
VisiHow QnA. This section is not written yet. Want to join in? Click EDIT to write this answer.
I want to spy on my girlfriend live talk and messages to a male friend. I live in Canada and she lives in Fiji?
She talks to this guy almost daily via Viber, she is cheating on me. We were supposed to get married in December 2017 so please let me know how you would help me. Well I am not sure whether she wants to marry me any more but I want to be 100 percent sure if she is having an affair. I have tried: I tried to find out who she is talking with but always an excuses. I think it was caused by: Only things I would think is she found someone to screw me!
Was this helpful? Yes | No | I need help
VisiHow QnA. This section is not written yet. Want to join in? Click EDIT to write this answer.
I want to check my wife's Viber and WhatsApp message. She has an Apple iPhone 6S. I do not have physical access to it. I believe she is cheating. Help required?
I want to check my wife's Viber and WhatsApp message. She has an Apple iPhone 6S. I do not have physical access to it. I believe she is cheating. Help required? My wife is in a foreign location for work. I believe she is cheating. I want to check her WhatsApp and Viber messages. I do not have access to her phone.She said it was by mistake written as she was half asleep. But her recent behavior sends a strong signal of infidelity. Help is requested. I do not have physical access to her phone, Also I want to do it without any trouble of touching her phone. I just want to use her number!
Was this helpful? Yes | No | I need help
VisiHow QnA. This section is not written yet. Want to join in? Click EDIT to write this answer.
Same person Viber account shows two different status in two different phones.How can it happen?
I see my boy friend's Viber account as last seen time almost no of hours ago.. But when I see My Boy friends Viber status from my friend's phone I see it as "online".I knot this means cheating. But how he does this. Two phone two accounts? Because both accounts shows the same phone no.. . Secondly if I recognize a person's Viber account , but still showing up as old country phone no., is it possible to find out where this person is currently located? I mean from where this person is logging in to Viber now?. . This will be a great relief if you can provide me a proper answer.. Thank you. First of all my question is to prove that same person is using two accounts using two different applications ,but mobile no visible is same.
Was this helpful? Yes | No | I need help
Secondly I am trying to figure our a person's physical location via Viber account, since it still shows old country mobile no. I have tried and tried to get the true information from person , but never worked. then I used screen shots to prove two different status of the same account appearing in my account and from another account.But person doesn't' accept. This is an attempt to reveal the truth/cheating. I think it was caused by two mobile devices. Person is showing up as using one account. But there is a separate mobile devise/separate mobile phone or WiFi devise which supports this confusion.
Was this helpful? Yes | No | I need help
How ever number visible is same.
VisiHow QnA. This section is not written yet. Want to join in? Click EDIT to write this answer.
Referencing this Article
If you need to reference this article in your work, you can copy-paste the following depending on your required format:
APA (American Psychological Association)
How can I check her phone messages such as Viber. (2017). In VisiHow. Retrieved Apr 26, 2017, from http://visihow.com/How_can_I_check_her_phone_message_such_as_Viber
Was this helpful? Yes | No | I need help
MLA (Modern Language Association) "How can I check her phone messages such as Viber." VisiHow, visihow.com/How_can_I_check_her_phone_message_such_as_Viber Accessed 26 Apr 2017.
Chicago / Turabian VisiHow.com. "How can I check her phone messages such as Viber." Accessed Apr 26, 2017. http://visihow.com/How_can_I_check_her_phone_message_such_as_Viber.
If you have problems with any of the steps in this article, please ask a question for more help, or post in the comments section below.
Comments
VisiHow welcomes all comments. If you do not want to be anonymous, register or log in. It is free.
Ask the author
Pizzamike
Premier Author
4 Articles Started
18 Article Edits
2,500 Points
Pizzamike is a premier author with VisiHow. Pizzamike has achieved the level of "Corporal" with 2,500 points. Pizzamike has started 4 articles (including this one) and has also made 18 article edits. 7,000 people have read Pizzamike's article contributions.
Pizzamike's Message Board
Pizzamike: Hi, my name is Pizzamike.
Pizzamike: Can I help you with your problem about "How can I check her phone messages such as Viber"?
Article Info
Categories : Suspicions
Recent edits by: steve mohammed, BenNelson, heartmackenzie
Share this Article:
Thanks to all authors for creating a page that has been read 13,973 times.
Do you have a question not answered in this article?
Click here to ask one of the writers of this article
x
Thank Our Volunteer Authors.
Would you like to give back to the community by fixing a spelling mistake? Yes | No
|
__label__pos
| 0.669087 |
Login Not happening Correctly in Codeignitor php 7.4
When I click on Login button, 1) then login successfully message appears. 2) I also checked session is created successfully as I put response line $resp = array('status'=>'1','msg'=>$this->lang->line('ltr_logged_msg'),'url'=>$url); inside condition if ($this->session->has_userdata('email')), it shows session is also created. 3) I also checked overall code and debug the code in browser also. I cannot find out any reason why it comes back to the login page. That’s why I am here for your assistance. I attached relevent View file code, Controller code as well as js file code so that anyone can test it. Looking forward to your guideance
In view Login.php
<form class="form" method="post" action="<?php echo base_url().'front_ajax/login'; ?>" data-redirect="yes">
<div class="edu_field_holder">
<input type="text" class="edu_form_field require" name="email" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_p_email'));?>" autocomplete="off" value="<?php echo(isset($_COOKIE['UML'])) ? base64_decode(urldecode(base64_decode($_COOKIE['UML']))) : ''; ?>">
</div>
<div class="edu_field_holder">
<input type="password" name="password" class="require edu_form_field" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_password'));?>" value="<?php echo(isset($_COOKIE['SSD'])) ? base64_decode(urldecode(base64_decode($_COOKIE['SSD']))) : ''; ?>">
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-12 text-md-right">
<button class="edu_btn edu_btn_black" id="auth_login" type="button" data-action="submitThisForm"><?php echo html_escape($this->common->languageTranslator('ltr_login'));?></button>
</div>
</form>
In Controller Front_ajax.php
function login(){
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')){
if(!empty($this->input->post('email',false)) && !empty($this->input->post('password',false))){
$email = trim($this->input->post('email',TRUE));
$pass = md5(trim($this->input->post('password',TRUE)));
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$stud_cond = array('enrollment_id'=>$email,'password'=>$pass);
}else{
$stud_cond = array('email'=>$email,'password'=>$pass);
}
$userDetails = $this->db_model->select_data('id,name,role,status,parent_id,teach_image,email,teach_batch,teach_subject,super_admin','users use index (id)',array('email'=>$email,'password'=>$pass),1);
$studentDetails = $this->db_model->select_data('id,name,contact_no,batch_id,admin_id,enrollment_id,image,email,status,login_status','students use index (id)',$stud_cond,1);
$this->session->sess_destroy();
if(!empty($userDetails)){
if($userDetails[0]['status']=='1'){
$brewers_strings = $this->random_strings(10);
$sess_arr = array(
'uid'=> $userDetails[0]['id'],
'name'=> $userDetails[0]['name'],
'role'=> $userDetails[0]['role'],
'status'=> $userDetails[0]['status'],
'admin_id' => $userDetails[0]['parent_id'],
'profile_img' => $userDetails[0]['teach_image'],
'email' => $userDetails[0]['email'],
'mobile' => $userDetails[0]['contact_no'],
'brewers_check' => $brewers_strings,
'super_admin' => $userDetails[0]['super_admin'],
);
$url = '';
$url = base_url().'admin/dashboard';
$this->session->set_userdata($sess_arr);
$resp = array('status'=>'1','msg'=>$this->lang->line('ltr_logged_msg'),'url'=>$url);//
$this->db_model->update_data_limit('users use index (id)',$this->security->xss_clean(array('token'=>1,'brewers_check'=>$brewers_strings)),array('id'=>$userDetails[0]['id']),1);
}else{
$resp = array('status' => '0','msg' =>$this->lang->line('ltr_contact_to_admin_msg'));//
}
}
else{
$resp = array('status' => '0','msg' =>$this->lang->line('ltr_wrong_credentials_msg'));
}
}
else{
$resp = array('status' => '0','msg' =>$this->lang->line('ltr_wrong_credentials_msg'));
}
echo json_encode($resp,JSON_UNESCAPED_SLASHES);
}
else{
echo $this->lang->line('ltr_not_allowed_msg');
}
}
In login.js
$(document).ready(function(){
$('[data-action="submitThisForm"]').on('click' , function(){
var targetForm = $(this).closest('form');
if(!myCustom.checkFormFields(targetForm)){
myCustom.callFormAjax(targetForm).done(function(res){
var resp = $.parseJSON(res);
if(resp.status == 1){
if(typeof targetForm.attr('data-reset') != 'undefined' && targetForm.attr('data-reset') == 1){ //check reset form data
targetForm[0].reset();
}
if(typeof targetForm.attr('data-redirect') != 'undefined'){ //check reset form data
if(resp.msg != '')
toastr.success(resp.msg)
setTimeout(function(){
location.href = resp.url;
},1500)
}else if(resp.msg){
toastr.success(resp.msg);
}
}else if(resp.status == 2){
$.magnificPopup.open({
items: {
src: '#studentLogin',
},
type: 'inline'
});
$('#studentLogin .changeStudentLogin').attr('data-id',resp.student_id);
}
else if(resp.status == 0){
toastr.error((resp.msg)?resp.msg:resp.error);
}
});
}
});
|
__label__pos
| 0.95106 |
sapdev logo background
sapdev logo sapdev logo
Comments
F4IF_INT_TABLE_VALUE_REQUEST sap function module
The below code shows how function module F4IF_INT_TABLE_VALUE_REQUEST is used to display a basic ABAP internal table as an SAP search help. The users selection is then passed into a selection screen parameter.
*&-------------------------------------------------------------*
*& Report ZTAB_SHELP *
*&-------------------------------------------------------------*
*& Created by sapdev.co.uk *
*& *
*& Display itab as search help *
*& ................................... *
*& The basic requirement for this demo is to display a number *
*& of fields from the EKKO table as a search help using *
*& SAP function module F4IF_INT_TABLE_VALUE_REQUEST. *
*&-------------------------------------------------------------*
REPORT ZTAB_SHELP.
parameters: p_ebeln type ekko-ebeln.
TYPES: BEGIN OF t_ekko,
ebeln TYPE ekpo-ebeln,
ebelp TYPE ekpo-ebelp,
statu TYPE ekpo-statu,
aedat TYPE ekpo-aedat,
matnr TYPE ekpo-matnr,
menge TYPE ekpo-menge,
meins TYPE ekpo-meins,
netpr TYPE ekpo-netpr,
peinh TYPE ekpo-peinh,
END OF t_ekko.
DATA: it_ekko TYPE STANDARD TABLE OF t_ekko INITIAL SIZE 0,
wa_ekko TYPE t_ekko,
it_return type STANDARD TABLE OF DDSHRETVAL,
wa_return like line of it_return.
**************************************************************
*at selection-screen
at selection-screen on value-request for p_ebeln.
select *
up to 10 rows
from ekko
into CORRESPONDING FIELDS OF TABLE it_ekko.
CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
EXPORTING
* DDIC_STRUCTURE = 'EKKO'
RETFIELD = 'EBELN'
* PVALKEY = ' '
* DYNPPROG = sy-repid
* DYNPNR = sy-dynnr
* DYNPROFIELD = 'EBELN'
* STEPL = 0
WINDOW_TITLE = 'Ekko Records'
* VALUE = ' '
VALUE_ORG = 'S'
* MULTIPLE_CHOICE = 'X' "allows you select multiple entries from the popup
* DISPLAY = ' '
* CALLBACK_PROGRAM = ' '
* CALLBACK_FORM = ' '
* MARK_TAB =
* IMPORTING
* USER_RESET = ld_ret
TABLES
VALUE_TAB = it_ekko
* FIELD_TAB = lt_field
RETURN_TAB = it_return
* DYNPFLD_MAPPING =
EXCEPTIONS
PARAMETER_ERROR = 1
NO_VALUES_FOUND = 2
OTHERS = 3.
READ TABLE it_return into wa_return index 1.
p_ebeln = wa_return-fieldval.
Check out sap documentation and pattern details for f4if_int_table_value_request sap function module on website se80.co.uk
comments powered by Disqus
|
__label__pos
| 0.948224 |
Differentiation Rules
There are many different rules that can be used when differentiating, and each rule can be used for a specific reason. There are three different rules that you will need to know:
Differentiation Rules Differentiation Rules
Create learning materials about Differentiation Rules with our free learning app!
• Instand access to millions of learning materials
• Flashcards, notes, mock-exams and more
• Everything you need to ace your exams
Create a free account
Contents
Table of contents
It is important to note that not all of the below formulae are written in the provided formula booklet and you will have to memorise them for your exam.
Chain rule
The chain rule can be used when you are differentiating a composite function, which is also known as a function of a function. The formula for this rule is below. This is when y is a function of u and u is a function of x:
\[\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}\]
Using the chain rule, differentiate \(y = (2x^3 + x)^6\)
First, you can start by rewriting it in terms of y and u:
\[\begin{align}y = (u)^6 \\ u = 2x^3 + x \end{align}\]
Now you can find the first part of your chain rule formula \(\frac{dy}{du}\), by differentiating your y:
\(\frac{dy}{du} = 6 u^5\)
Next, you can find the second part of your chain rule formula \(\frac{du}{dx}\), by differentiating your u:
\[\frac{du}{dx} = 6x^2 + 1\]
Now that you have found both parts of your sum you can multiply them together to find \(\frac{dy}{dx}\):
\[\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}\]
\[\frac{dy}{dx} = 6u^5 \cdot 6x^2 + 1\]
\[\frac{dy}{dx} = 6u^5 (6x^2 + 1)\]
Finally, it is important to express your answer in terms of x, and to do this you can use \(u = 2x^3 + x\):
\[\frac{dy}{dx} = 6(2x^3 + x)^5(6x^2 +1)\]
The function that you are given may involve a trigonometric function. Let's work through an example to see how this would be solved.
If \(y = (\sin x)^3\) find \(\frac{dy}{dx}\)
Let’s start by identifying your u and y:
\(y = (u)^3\) \(u = \sin x\)
Now you can look at the chain rule formula, break it down, and find each part:
\(\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}\)
\(\frac{dy}{du} = 3u^2\) \(\frac{du}{dx} = \cos x\)
Next, you can put your \(\frac{dy}{du}\) and \(\frac{du}{dx}\) into the formula to find \(\frac{dy}{dx}\):
\[\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}\]
\[\frac{dy}{dx} = 3u^2 \cdot \cos x\]
Finally, you need to make sure your answer is written in terms of x, and you can do this by substituting in \(u = \sin x\):
\[\frac{dy}{dx} = 3u^2 \cdot \cos x\]
\[\frac{dy}{dx} = 3(\sin x)^2 \cos x\]
The chain rule can also be written in notation form, which allows you to differentiate a function of a function:
If \(y = f(g(x))\) then \(\frac{dy}{dx} = f'(g(x)) g'(x)\)
Product rule
The product rule is used when you are differentiating the product of two functions. A product of a function can be defined as two functions being multiplied together. When using this rule you need to make sure you have the product of two functions and not a function of a function, as they can be confused. The formula for this rule is below – this is if y=uv when u and v are functions of x:
\(\frac{dy}{dx} = u \frac{dv}{dx} + v \frac{du}{dx}\)
This function can also be written in function notation:
If \(f(x) = g(x)h(x)\) then \(f'(x) = g(x)h'(x) + h(x)g'(x)\)
Given that \(y = 2xe^2\) find \(\frac{dy}{dx}\)
Looking at the formula, first, you need to identify each part of the formula:
\[\frac{dy}{dx} = u \frac{dv}{dx} + v\frac{du}{dx}\]
\(u = 2x\) \(v = e^2\)
To find \(\frac{dv}{dx}\) and \(\frac{du}{dx}\) you need to differentiate your u and v:
\(\frac{du}{dx} = 2\) \(\frac{dv}{dx} = 0\)
Now you have found each part of the formula you can solve for \(\frac{dy}{dx}\):
\begin{align} \frac{dy}{dx} = (2x)(0) + (e^2)(2) \\ \frac{dy}{dx} = 2e^2 \end{align}
Given that \(y = x^2 \sin x\) find \(\frac{dy}{dx}\)
To do this you can start by looking at the formula and identifying what you need:
\[\frac{dy}{dx} = u \frac{dv}{dx} + v\frac{du}{dx}\]
\(u = x^2\) \(v = \sin x\)
Now you can differentiate your u and v to find the next part of the formula:
\(\frac{du}{dx} = 2x\) \(\frac{dv}{dx} = \cos{x}\)
Input all of the information into the formula to find \(\frac{dy}{dx}\):
\[\frac{dy}{dx} = u \frac{dv}{dx} + v \frac{du}{dx}\]dydx=udvdx+vdudx
\[\frac{dy}{dx} = (x^2)(\cos x) + (\sin x)(2x)\]
\[\frac{dy}{dx} = \cos x(x^2) + 2x\sin x\]
\[\frac{dy}{dx} = x^2\cos x + 2x \sin x\]
Quotient rule
The quotient rule is used when you are differentiating the quotient of two functions, this is when one function is being divided by another. The formula used for this rule is below, this is when \(y = \frac{u}{v}\):
\(\frac{dy}{dx} = \frac{v\frac{du}{dx} - u \frac{dv}{dx}}{v^2}\)
This can also be written in function notation:
If \(f(x) = \frac{g(x)}{h(x)}\) then \(f'(x) = \frac {h(x)g'(x) - g(x)h'(x)}{(h(x))^2}\)
If \(y = \frac{2x}{3x +4}\) find \(\frac{dy}{dx}\) :
First, you can start by looking at your formula and find each part of it:
\(\frac{dy}{dx} = \frac{v\frac{du}{dx} - u \frac{dv}{dx}}{v^2}\)
\(u = 2x\) \(v = 3x + 4\) \(\frac{du}{dx} = 2\) \(\frac{dv}{dx} = 3\)
Now you can solve the formula with all of the above information:
\(\frac{dy}{dx} = \frac{(3x +4) \cdot 2 - (2x) \cdot 3}{(3x + 4)^2}\)
\(\frac{dy}{dx} = \frac{8}{(3x + 4)^2}\)
Let’s look at a second example involving a trigonometric function.
If \(y = \frac{\cos x}{2x^2}\) find \(\frac{dy}{dx}\).
Just like in the previous example, you can start by looking at your formula and finding each part of it to find your \(\frac{dy}{dx}\):
\(\frac{dy}{dx} = \frac{v\frac{du}{dx} - u \frac{dv}{dx}}{v^2}\)
\(u = \cos x\) \(v = 2x^2\) \(\frac{du}{dx} = -\sin x\) \(\frac{dy}{dx} = 4x\)
Now that you have each part of the formula you can substitute them into the formula and find \(\frac{dy}{dx}\):
\[\frac{dy}{dx} = \frac{v\frac{du}{dx} - u \frac{dv}{dx}}{v^2}\]
\[\frac{dy}{dx} = \frac{(2x^2)(-\sin x) - (\cos x)(4x)}{(2x^2)^2}\]
\[\frac{dy}{dx} = \frac{-2x^2 \sin x - 4x \cos x}{(2x^2)^2}\]
Differentiation Rules - Key takeaways
• There are three main differentiation rules, chain rule, product rule, and quotient rule.
• Each rule is used for a different reason and has a different formula for you to use.
• The chain rule is used when you are differentiating a composite function.
• The product rule is used when you are differentiating the products of two functions.
• The quotient rule is used when you are differentiating the quotient of two functions.
Frequently Asked Questions about Differentiation Rules
When do you use the chain rule in differentiation?
The chain rule can be used when you are differentiating a composite function, also known as a function of a function.
How do you differentiate using the chain rule?
To differentiate using the chain rule you use the following formula: dy/dx = dy/du X du/dx
How do you differentiate using the quotient rule?
To differentiate using the quotient rule you use the following formula when y = u/v, dy/dx = (v du/dx - u dv/dx)/v^2
Discover learning materials with the free StudySmarter app
Sign up for free
1
About StudySmarter
StudySmarter is a globally recognized educational technology company, offering a holistic learning platform designed for students of all ages and educational levels. Our platform provides learning support for a wide range of subjects, including STEM, Social Sciences, and Languages and also helps students to successfully master various tests and exams worldwide, such as GCSE, A Level, SAT, ACT, Abitur, and more. We offer an extensive library of learning materials, including interactive flashcards, comprehensive textbook solutions, and detailed explanations. The cutting-edge technology and tools we provide help students create their own learning materials. StudySmarter’s content is not only expert-verified but also regularly updated to ensure accuracy and relevance.
Learn more
StudySmarter Editorial Team
Team Math Teachers
• 7 minutes reading time
• Checked by StudySmarter Editorial Team
Save Explanation
Study anywhere. Anytime.Across all devices.
Sign-up for free
Sign up to highlight and take notes. It’s 100% free.
Join over 22 million students in learning with our StudySmarter App
The first learning app that truly has everything you need to ace your exams in one place
• Flashcards & Quizzes
• AI Study Assistant
• Study Planner
• Mock-Exams
• Smart Note-Taking
Join over 22 million students in learning with our StudySmarter App
Get unlimited access with a free StudySmarter account.
• Instant access to millions of learning materials.
• Flashcards, notes, mock-exams, AI tools and more.
• Everything you need to ace your exams.
Second Popup Banner
|
__label__pos
| 1 |
cancel
Showing results for
Search instead for
Did you mean:
why does my iPhone work better without the Internet
New Member
why does my iPhone work better without the Internet
My iPhone works better without the Internet if I turn the Wi-Fi off it works better and if I try to use the Wi-Fi my phone cuts in and out and my Facebook will not play any of the videos
4 REPLIES 4
Alum
Re: why does my iPhone work better without the Internet
Hello Willie,
Thanks for posting and welcome to the community! There are many factors that could cause this. Do you see the same performance when connecting with a computer through WiFi? Your router and configuration are the biggest determining factor for your experience with a wireless connection.
- Chris
Highlighted
New Member
Re: why does my iPhone work better without the Internet
Chris I have turn off everything and started it all back up and hard wire my laptop to the modem but it my phone that I use the most I'm am constantly turning the wifi on and off to make it work
New Member
Re: why does my iPhone work better without the Internet
Chris I have turn off everything and started it all back up and hard wire my laptop to the modem but it my phone that I use the most I'm am constantly turning the wifi on and off to make it work
Alum
Re: why does my iPhone work better without the Internet
Hi Willie,
I don't think I really understand what your saying. How is your performance using the laptop in comparison to your phone when on the Hughesnet service?
- Chris
|
__label__pos
| 0.644453 |
%% @author Bob Ippolito %% @copyright 2007 Mochi Media, Inc. %% @doc Simple and stupid echo server to demo mochiweb_socket_server. -module(mochiweb_echo). -author('[email protected]'). -export([start/0, stop/0, loop/1]). stop() -> mochiweb_socket_server:stop(?MODULE). start() -> mochiweb_socket_server:start([{name, ?MODULE}, {port, 6789}, {ip, "127.0.0.1"}, {max, 1}, {loop, {?MODULE, loop}}]). loop(Socket) -> case gen_tcp:recv(Socket, 0, 30000) of {ok, Data} -> case gen_tcp:send(Socket, Data) of ok -> loop(Socket); _ -> exit(normal) end; _Other -> exit(normal) end.
|
__label__pos
| 0.988579 |
Hack Like a Pro: How to Conduct OS Fingerprinting with Xprobe2
How to Conduct OS Fingerprinting with Xprobe2
Welcome back, my novice hackers!
I've written a couple of articles on reconnaissance and its importance, and as I've said before, a good hacker will spend 3 to 4 more times doing reconnaissance than actually exploiting the system. If your recon isn't good, you'll likely fail, or worse—end up serving time and becoming Bubba's wife for a couple years. I can't say it enough—recon is critical.
Among the information we need to gather are the open ports, running services, and the operating system. Although such tools as nmap and hping2 can do operating system fingerprinting, they are not as accurate and reliable as the tools that are built specifically for this purpose.
In this tutorial, we'll use one of the best active tools for doing OS fingerprinting, xprobe2, which is an active OS fingerprinter, meaning that it actually sends probes to the target system, then gauges the OS from the system's response. In total, xprobe2 has 16 different modules it runs to help determine the OS.
It probably goes without saying that any fingerprinter that's probing with special packets is going to be noisy and likely detected by NIDS and other security systems.
Step 1: Find xprobe2
Like so many other great hacker tools, xprobe2 is included in our BackTrack distribution. To find it, type:
• whereis xprobe2
As you can see from the screenshot above, it's in the /usr/local/bin, so if that directory is in our PATH variable, we can use xprobe2 from any directory.
Step 2: Find Help
Now, let's get some basic help to run xprobe2 for OS fingerprinting.
• xprobe2
The syntax for running an xprobe2 fingerprint is really straightforward. We simply need the command and the target.
• xprobe2 <target domain or IP>
Step 3: Fingerprint with xprobe2
Now, let's point xprobe2 at some systems and see what it's able to tell us. I'll first point it at my Windows 2003 Server VM.
As you can see, xprobe2 identified it as Windows XP (100%) and Windows 2003 Standard Edition (100%). As these are the same Windows build, this is not surprising.
When I run nmap with OS fingerprinting (nmap -O), I get similar results.
Step 4: Fingerprint an Unknown System
Now, let's try fingerprinting an unknown system. For example, google.com.
• xprobe2 google.com
Xprobe2 tells us with 100% probability that the system is Foundry Networks Ironware. This is the gigabit switch on the google.com domain.
Xprobe2 then identifies, with lower probability of being correct, the Linux kernel version of the server. This is good example of how imperfect even very good products are and require some knowledge and skill to interpret the results.
Step 5: List xprobe2 Modules
As I mentioned earlier, xprobe2 has 16 modules that it uses to try to determine the operating system of the target. It uses each of them to try to determine the probability of its guess. Let's look at those modules.
• xprobe2 -L
By default, xprobe2 uses all of its modules, but we can remove modules by using the -D switch. For instance, on many networks the icmp modules will hang and you may need to remove these modules to get xprobe2 to work. To run xprobe2 without the icmp port unreachable module (#11), we could run xprobe2 like this:
• xprobe2 -D 11 google.com
Step 6: Test Another Public Domain
Let's try xprobe2 on another public domain, such as espn.com.
• xprobe2 espn.com
As we can see, xprobe2 tells us that it has determined with a 92% probability that espn.com is running OpenBSD 3.4. It also shows us that espn.com might be running a different version (3.5-3.7) of OpenBSD, but it's pretty certain it's OpenBSD.
Xprobe2, like nmap and hping, is an essential reconnaissance tool that should be in every hacker's toolbox. If you have questions on this or any hacking recon, ask below in the comments.
Fingerprint photo via Shutterstock
Never Miss a Hacking or Security Guide
New Null Byte in your inbox, every week.
14 Comments
again which IP of target is required??
hello sir OTW,
do you think hping3 and xprobe2 are obsolete ? Because both have not been updated since 2005 ?
It depends upon what you mean by obsolete. They both still work great!!
In the case of xprobe2, you can simply update the signatures for newer OS's and everything works.
thanks sir, but can you explain how to update the signatures for newer OS's in xprobe2 ? Because i think mine is really outdated lol
When you use xprobe2, does your IP get logged into the computer you are sending packets to? If so is there a built in feature to spoof or hide your IP without the use of proxychain?
im using xprobe2 for fingerprinting
it found the OS behind the host,but it give a 100% guess probability on
about 4 0r 5 versions it guessed..
should i assume the first one it listed is the version of the OS?
Ive tried xprobe2 <my IP > And it just gives me a error.
Host <IP> is down ( quess probalility 0%)
Try it again on an external IP.
I can't get the OS running on any website
Host 199.181.132.250 Running OS: (Guess probability: 91%)
Mmm I'm running Kali rolling. There were some bugs. Output showed unreadable UNI of ascii signs (or just a space)where the name of the OS should be, but it did give a probability. Later some good results with the same command; (Weird)
xprobe2 -L responds with the help page, not the list of modules.
Does anybody know what I'm doing wrong?
Hi,
How were you able to resolve the bug of unreadable text for the guessed OS names? Can you please share? I am not able to find a solution for it anywhere.
Share Your Thoughts
• Hot
• Latest
|
__label__pos
| 0.622292 |
8
It seems it allows you to edit the content of an element, but what is actually happening? What's the use of this property?
EDIT: see here
9
This is usually used for rich text input. While regular form elements like <input type="text"/> don't provide real rich text editing options, elements with contentEditable set to true can. Most rich text editors (e.g. FCK Editor) available for the web are built using an <iframe/> with contentEditable set to true.
1
contentEditable=true for elements make them editable. You can write/edit text in those elements as if they are a textarea or a text field.
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.998808 |
In this blog, we embark on a journey to explore the top 12 uses of blockchain development in healthcare, shedding light on its potential to reshape the industry. The healthcare sector is at a crossroads, grappling with the challenges of data privacy, interoperability, and the security of sensitive patient information.
|
__label__pos
| 0.954986 |
Start learning with our library of video tutorials taught by experts. Get started
Blender 2.6 Essential Training
Watching:
Creating reflections
From:
Blender 2.6 Essential Training
with George Maestri
Expand all | Collapse all
1. 3m 42s
1. Welcome
1m 22s
2. Using the exercise files
28s
3. Downloading Blender
34s
4. Using Blender on a Mac
42s
5. Using Blender on a laptop
36s
2. 30m 32s
1. Overview of the Blender interface
6m 6s
2. Understanding 3D view windows
5m 23s
3. Navigating in 3D space
6m 35s
4. Configuring user preferences
6m 24s
5. Creating custom layouts
6m 4s
3. 32m 29s
1. Selecting objects
6m 12s
2. Moving objects
4m 35s
3. Rotating objects
2m 48s
4. Scaling objects
2m 16s
5. Understanding transform orientation
3m 53s
6. Changing an object's origin
5m 27s
7. Selecting pivot points
3m 22s
8. Using Snap to move objects precisely
3m 56s
4. 44m 15s
1. Creating mesh primitives
6m 36s
2. Selecting vertices, edges, and faces
4m 48s
3. Editing mesh objects
7m 39s
4. Proportional editing
3m 52s
5. Sculpt mode
4m 45s
6. Working with edges and edge loops
3m 42s
7. Extrusions
5m 18s
8. Smooth shading objects
2m 23s
9. Subdividing meshes
5m 12s
5. 50m 31s
1. Working with modifiers
5m 52s
2. Working with subdivision surfaces
3m 48s
3. Creating a simple creature
7m 54s
4. Symmetrical modeling with the Mirror modifier
8m 21s
5. Joining mesh objects
3m 37s
6. Stitching vertices
4m 52s
7. Finalizing a simple creature
4m 48s
8. Creating text
3m 29s
9. Boolean tools
2m 59s
10. Vertex groups
4m 51s
6. 22m 36s
1. Using the Outliner
8m 22s
2. Using layers
4m 30s
3. Creating groups
2m 48s
4. Working with scenes
4m 2s
5. Creating hierarchies
2m 54s
7. 54m 26s
1. Assigning materials to objects
8m 4s
2. Diffuse shaders
6m 47s
3. Working with specularity
5m 56s
4. Using the Ramp Shader options
9m 45s
5. Additional shading options
2m 37s
6. Creating reflections
8m 29s
7. Adding transparency and refractions
6m 49s
8. Subsurface scattering
5m 59s
8. 51m 48s
1. Adding a simple texture
6m 11s
2. Using bitmaps
6m 53s
3. Mapping textures in the UV Editor
8m 28s
4. Using UV projections
5m 56s
5. UV mapping a character
6m 11s
6. Fine-tuning UV mapping
6m 7s
7. Creating Bump and Normal maps
3m 15s
8. Displacement mapping
3m 48s
9. Using the Node Editor
4m 59s
9. 53m 9s
1. Adding lamps to a scene
8m 44s
2. Fine-tuning ray-trace shadows
4m 32s
3. Using spot lamps
4m 20s
4. Fine-tuning buffer shadows
6m 19s
5. Using Hemi lamps
2m 32s
6. Working with Area lamps
5m 17s
7. Creating sky and ambient light
4m 49s
8. Adding background images
3m 19s
9. Creating sunlight
6m 6s
10. Ambient occlusion
7m 11s
10. 30m 8s
1. Working with cameras
4m 47s
2. Creating camera targets with constraints
3m 43s
3. Render properties
5m 7s
4. Rendering animation
5m 13s
5. Adding motion blur
4m 10s
6. Creating depth of field
7m 8s
11. 32m 30s
1. Understanding the Timeline
4m 3s
2. Animating objects
6m 26s
3. Animating properties
4m 0s
4. Editing animation in the Graph Editor
8m 36s
5. Using the Dope Sheet
4m 53s
6. Path animation
4m 32s
12. 39m 59s
1. Facial animation using shape keys
4m 40s
2. Understanding armatures
6m 2s
3. Fitting an armature to a creature
7m 23s
4. Deforming a character with an armature
3m 49s
5. Setting up inverse kinematics
3m 53s
6. Controlling the hips and body
2m 1s
7. Animating in Pose mode
2m 47s
8. Creating a test animation
9m 24s
13. 15s
1. Goodbye
15s
Video: Creating reflections
Now let's take a look at how to do reflections in Blender. I have a simple scene here, and it's got a couple of spheres, a cylinder, and a camera. And let's go ahead and just do a quick render. I am going to hit F12. And what you can see here is that, well, there are no reflections. We have a couple of solid spheres and the checkerboard on our floor plane. So I am going to go ahead and add reflections to the sphere, and we will go through so many options for reflections on that object.
Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.
Become a member
Please wait...
Blender 2.6 Essential Training
7h 26m Beginner Dec 21, 2011
Viewed by members. in countries. members currently watching.
This course provides an overview of modeling, animating, and rendering 3D graphics in the open-source software Blender 2.6. Beginning with a tour of the Blender interface, author George Maestri shows how to create and edit basic objects, work with modifiers and subdivision surfaces, and apply materials and textures. The course also demonstrates lighting 3D scenes, setting up and using cameras, animating objects, and assembling basic character rigs.
Topics include:
• Navigating in 3D space
• Selecting, rotating, and scaling objects
• Using Snap to move objects precisely
• Creating mesh primitives and extrusions
• Subdividing meshes
• Creating a simple creature
• Joining mesh objects and stitching vertices
• Organizing a scene with layers, groups, and hierarchies
• Assigning glossy and reflective materials to objects
• Creating bump maps
• Creating sky and ambient light
• Understanding ambient occlusion
• Adding motion blur and depth of field
• Editing animation in the Graph Editor
• Building and animating a simple character
Subject:
3D + Animation
Software:
Blender
Author:
George Maestri
Creating reflections
Now let's take a look at how to do reflections in Blender. I have a simple scene here, and it's got a couple of spheres, a cylinder, and a camera. And let's go ahead and just do a quick render. I am going to hit F12. And what you can see here is that, well, there are no reflections. We have a couple of solid spheres and the checkerboard on our floor plane. So I am going to go ahead and add reflections to the sphere, and we will go through so many options for reflections on that object.
So I am going to go ahead and expand this up a little bit here so we could see it. So I have my sphere and it has a texture on it called Sphere. Let's go ahead and change that to Reflective so that way we have a more descriptive name, and let's scroll down to the Mirror rollout here. And this is where we can add reflections. But before I do that I'm actually going to go ahead and collapse some of these rollouts, so that way we can see it along with the preview.
So when I turn on Mirror, it gives me a bunch of controls. The most important control is called Reflectivity, and this is how much it reflects. And you can actually see how this works in the preview. So if I turn it up, you can see how that checkerboard is reflected in that viewport. So let's just put this right in the middle. Let's just put it a .5 and just hit F12 to render. So you can see how this adds some additional reflectivity. So this makes us ball from a white ball into kind of a shiny metal ball, or a mirrored ball.
And so if we want we can bring up Reflective a whole lot. If we bring it up all the way, it becomes perfectly reflective, which is not so natural, so let's go ahead and roll that back a little bit. I am going to keep it at .75, just so that we have a pretty good reflection for this example. Below this we have a color picker. So right now it's set to white, which means it will reflect whatever color is given to it, but we can tint the reflection with this color picker.
So if I click on it and I give it kind of a purple hint here, you can see how that affects my preview, and it also affects my scene. So the saturation of this color determines how much it's tinted. So if I go over to my HSV here, I can turn down the Saturation and you can see how it becomes less of an effect. So you can really still see the tint here in the whites of that checkerboard, but as the Saturation goes down, that tinting goes down as well. And I am going to go ahead and turn that to 0.
Now over here to the right we have Fresnel effect, and that's pretty much the same as the Fresnel effect we saw before when using ramps, but let's go ahead and take a look at it. I am going to turn this up to 3, and you can see how it affects the reflections. Basically what it does is it pushes the reflections off to the side. So when I have the Fresnel up above 1, that actually tends to make the center less reflective and the edges are the ones that receive all the reflections.
Now this Blend control basically just controls how that Fresnel effect blends into the object here, and you can see how that works in the preview. So I am going to go ahead and turn Fresnel off. We are going to turn it back to 0 here. And now let's take a look at Depth. Now Depth controls how many times an object or material reflects. So in this case I have it set to 2, so when I render, I can have up to two reflections.
This doesn't work as well with just one object in the scene, because what we need to do is have something reflecting a reflection in order to see how this works. So let's go ahead and make the floor reflective. I am going to go ahead right-click on the object called Floor; in fact, you can see it here in the outliner. And if I scroll up here, you will see I have a checker pattern applied, or a checker material applied. So if I hit my material selector here, I can scroll down and find the Reflective material that we created.
And when I do that, both the floor and the sphere have that reflective material. So I am going to go ahead and scroll back up so we can see our options here. So let's take a look at Depth. I am going to go ahead turn Depth down to 0 and do a quick render. And this shows it very, very well, because really we are not reflecting any reflections. So the sphere sees the plane without reflections, so it sees it in kind of a neutral color.
Same for the floor. The floor sees the sphere. It's not reflecting the reflections. If I turn that up to 1, you can see that little bit more clearly. So what we've got here is now I'm reflecting the reflection one time. It still creates a little bit of a spot there. So if we want, we can turn it up to say 3 or 4 and then render again. Once you get enough iterations, you get a realistic effect. So it depends on how many reflective objects you have in the scene.
Now more Depth will affect render performance because you're bouncing more light waves around. So I am going to go ahead and select the plane again, and I'm going to change it back to that checker pattern, and then let's go ahead and right-click back on the sphere. And I want to take a look at Max Distance. So if I do a quick render here, you'll see that it's basically reflecting everything, and this controls how far an object reflects.
So when Max Distance is at 0, it reflects everything. As soon as we bring it up above 0--let's bring in up to 6. So if I render this with a Max Distance of 6, you will see that, well, it's kind of seeing the spheres, but it doesn't have enough distance to see the cylinder, and it certainly doesn't see the sky. So what we can do is we can actually limit how far things reflect, and that can actually be very useful.
So if I want, I can turn this up to a larger number, let's say about 20, and if I render, there you can see how now it's starting to get a little bit of the sky, but it's not perfect. So if I set it back to 0, you can see how it does a perfect reflection. Now the last parameter is called Gloss, and that's over here. By default it's at 1 and makes the object perfectly glossy. How you use this is you turn down the Gloss. And by default it can be kind of sensitive, so let's go ahead and just turn it to .9 and do a quick render, and you'll instantly see a little bit of a difference. You will see how the reflections are a little bit blurry.
They're not perfect, and this can be great. What it says is that surface is not perfectly reflective. As we turn it down--let's go ahead turn it down to say .7--and do another render, you see how it starts to fizzle out actually pretty quickly. So something even as high as .8 will give you some effect, but again, it will blur it out fairly quickly. Now also notice how this might be a little bit modeled. This is because we have a number of samples. And the higher the number of samples the more accurate this will be, but again, at the expense of rendering time.
So those are some of the basics of how to add reflectivity to some of your materials in Blender. Now reflections can add a lot of realism, but if they're too perfect, they start to lose realism. So try to find ways either using Max Distance or Gloss or even the Fresnel effect to give it a little bit of variation in its reflectivity, which will add a lot more life to your objects.
There are currently no FAQs about Blender 2.6 Essential Training.
Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.
Exercise files video
How to use exercise files.
Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now
Exercise files
Exercise files video
How to use exercise files.
For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.
This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.
Upgrade now
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.
Mark all as unwatched Cancel
Congratulations
You have completed Blender 2.6 Essential Training.
Return to your organization's learning portal to continue training, or close this page.
OK
Become a member to add this course to a playlist
Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.
Get started
Already a member?
Become a member to like this course.
Join today and get unlimited access to the entire library of video courses.
Get started
Already a member?
Exercise files
Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more
Get started
Already a Premium member?
Exercise files video
How to use exercise files.
Ask a question
Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.
Please enter the text shown below:
The classic layout automatically defaults to the latest Flash Player.
To choose a different player, go to the site preferences section of the my account menu.
Continue to classic layout Stay on new layout
Welcome to the redesigned course page.
We’ve moved some things around, and now you can
Exercise files
Access exercise files from a button right under the course name.
Mark videos as unwatched
Remove icons showing you already watched videos if you want to start over.
Control your viewing experience
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Interactive transcripts
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Thanks for signing up.
We’ll send you a confirmation email shortly.
Sign up and receive emails about lynda.com and our online training library:
Here’s our privacy policy with more details about how we handle your information.
Keep up with news, tips, and latest courses with emails from lynda.com.
Sign up and receive emails about lynda.com and our online training library:
Here’s our privacy policy with more details about how we handle your information.
submit Lightbox submit clicked
|
__label__pos
| 0.885793 |
||
Skip to end of metadata
Go to start of metadata
The API Manager comes with two Web interfaces as API Publisher and API Store. The following steps show an example of how to localize the API Publisher UI. Same instructions apply to localize the API Store.
Changing the browser settings
1. Follow the instructions in your Web browser's user guide and set the browser's language to a preferred one. For example, in Google Chrome, you set the language using the Settings -> Show advanced settings -> Languages menu.
2. Set the browser's encoding type to UTF-8.
Introduction to resource files
3. Go to <APIM_HOME>/repository/deployment/server/jaggeryapps/publisher directory where <AM_HOME> is the API Manager distribution's home.
4. There are two types of resource files used to define localization strings in the API Manager.
• The resource file used to store the strings defined in .jag files according to browser locale (For example, locale_en.json) is located in .../publisher/site/conf/locales/jaggery folder.
• The resource file i18nResources.json, which is used to store strings defined in client-side javascript files such as pop-up messages when a UI event is triggered, is located in .../publisher/site/conf/locales/js folder.
For example,
To implement localization support for jaggery, we use its in-built script module 'i18n'. For more information, refer to http://jaggeryjs.org/documentation.jag?api=i18n.
Localizing strings in Jaggery files
5. To localize the API publisher to Spanish, first localize the strings defined in jaggery files. Create a new file by the name locale_{lolcaleCode}.json inside ...publisher/site/conf/locales/jaggery folder. For example, if the language set in the browser is Spanish, the locale code is es and the file name should be locale_es.json.
The file name which includes the locale code will differ according to the language selected in your browser. Create a new file for the language you select, if the selected language is not available. The file Name should be locale_{localeCode}.json where the localeCode refers to the sub tag of the particular language. Please refer the IANA Language Subtag Registry page for a list of sub tags.
By matching the accept Language header, the particular file will be selected from the resource file directory of each web application for the localization by the server. If there is no locale file found with the matching sub tag, locale_default.json file will be served for the localization.
6. Add the key-value pairs to locale_es.json file. For an example on adding key value pairs, refer to locale_en.json file in ...publisher/site/conf/locales/jaggery folder. It is the default resource file for jaggery.
In addition, a section of a sample locale_es.json file is shown below for your reference.
Localizing strings in client-side Javascript files
7. To localize the javascript UI messages, navigate to publisher/site/conf/locales/js folder and update i18nResources.json file with relevant values for the key strings.
8. Once done, open the API Publisher web application in your browser (https: //<YourHostName>:9443/publisher).
9. Note that the UI is now changed to Spanish.
• No labels
|
__label__pos
| 0.505912 |
class Api::UsersController
Allows for adding, modifying and showing Markus users. Uses Rails’ RESTful routes (check ‘rake routes’ for the configured routes)
Public Instance Methods
create() click to toggle source
Creates a new user Requires: user_name, type, first_name, last_name Optional: section_name, grace_credits
# File app/controllers/api/users_controller.rb, line 27
def create
if has_missing_params?([:user_name, :type, :first_name, :last_name])
# incomplete/invalid HTTP params
render 'shared/http_status', :locals => {:code => '422', :message =>
HttpStatusHelper::ERROR_CODE['message']['422']}, :status => 422
return
end
# Check if that user_name is taken
user = User.find_by_user_name(params[:user_name])
unless user.nil?
render 'shared/http_status', :locals => {:code => '409', :message =>
'User already exists'}, :status => 409
return
end
# No conflict found, so create new user
param_user_type = params[:type].downcase
if param_user_type == 'student'
user_type = Student
elsif param_user_type == 'ta' || param_user_type == 'grader'
user_type = Ta
elsif param_user_type == 'admin'
user_type = Admin
else # Unknown user_type, Invalid HTTP params.
render 'shared/http_status', :locals => { :code => '422', :message =>
'Unknown user type' }, :status => 422
return
end
attributes = { :user_name => params[:user_name] }
attributes = process_attributes(params, attributes)
new_user = user_type.new(attributes)
unless new_user.save
# Some error occurred
render 'shared/http_status', :locals => {:code => '500', :message =>
HttpStatusHelper::ERROR_CODE['message']['500']}, :status => 500
return
end
# Otherwise everything went alright.
render 'shared/http_status', :locals => {:code => '201', :message =>
HttpStatusHelper::ERROR_CODE['message']['201']}, :status => 201
end
destroy() click to toggle source
Requires nothing, does nothing
# File app/controllers/api/users_controller.rb, line 94
def destroy
# Admins should not be deleting users, so pretend this URL doesn't exist
render 'shared/http_status', :locals => {:code => '404', :message =>
HttpStatusHelper::ERROR_CODE['message']['404'] }, :status => 404
end
index() click to toggle source
Returns users and their attributes Optional: filter, fields
# File app/controllers/api/users_controller.rb, line 12
def index
users = get_collection(User)
fields = fields_to_render(@@default_fields)
respond_to do |format|
format.xml{render :xml => users.to_xml(:only => fields, :root => 'users',
:skip_types => 'true')}
format.json{render :json => users.to_json(:only => fields)}
end
end
process_attributes(params, attributes) click to toggle source
Process the parameters passed for user creation and update
# File app/controllers/api/users_controller.rb, line 141
def process_attributes(params, attributes)
# Get the id of the section corresponding to :section_name
unless params[:section_name].blank?
section = Section.find_by_name(params[:section_name])
unless section.blank?
attributes[:section_id] = section.id
end
end
parameters = [:last_name, :first_name, :type, :grace_credits]
parameters.each do |key|
unless params[key].blank?
attributes[key] = params[key]
end
end
attributes
end
show() click to toggle source
Returns a user and its attributes Requires: id Optional: filter, fields
# File app/controllers/api/users_controller.rb, line 76
def show
user = User.find_by_id(params[:id])
if user.nil?
# No user with that id
render 'shared/http_status', :locals => {:code => '404', :message =>
'No user exists with that id'}, :status => 404
else
fields = fields_to_render(@@default_fields)
respond_to do |format|
format.xml{render :xml => user.to_xml(:only => fields, :root => 'user',
:skip_types => 'true')}
format.json{render :json => user.to_json(:only => fields)}
end
end
end
update() click to toggle source
Requires: id Optional: first_name, last_name, user_name, section_name, grace_credits
# File app/controllers/api/users_controller.rb, line 102
def update
# If no user is found, render an error.
user = User.find_by_id(params[:id])
if user.nil?
render 'shared/http_status', :locals => {:code => '404', :message =>
'User was not found'}, :status => 404
return
end
# Create a hash to hold fields/values to be updated for the user
attributes = {}
unless params[:user_name].blank?
# Make sure the user_name isn't taken
other_user = User.find_by_user_name(params[:user_name])
if !other_user.nil? && other_user != user
render 'shared/http_status', :locals => {:code => '409', :message =>
'Username already in use'}, :status => 409
return
end
attributes[:user_name] = params[:user_name]
end
attributes = process_attributes(params, attributes)
user.attributes = attributes
unless user.save
# Some error occurred
render 'shared/http_status', :locals => { :code => '500', :message =>
HttpStatusHelper::ERROR_CODE['message']['500'] }, :status => 500
return
end
# Otherwise everything went alright.
render 'shared/http_status', :locals => {:code => '200', :message =>
HttpStatusHelper::ERROR_CODE['message']['200']}, :status => 200
end
|
__label__pos
| 0.587841 |
Uninstall ETP Client
If necessary, an IT administrator can uninstall the client with a networked devices management solution, such as KACE.
Uninstall ETP Client on Windows
You can uninstall ETP Client on Windows with the user interface or with a command line.
If your organization does not allow end users to uninstall ETP Client, you are prompted to enter the entitlement code in the user interface. If you use the command line to uninstall ETP Client with a management solution, you include the entitlement code in the uninstall command.
Uninstall ETP Client with Windows 7 user interface
To uninstall ETP Client on the Windows 7 interface:
1. Click Start.
2. In the search field, enter Add or remove programs.
3. Click Add or remove programs.
4. Select Enterprise Client Connector and click Uninstall.
5. When the confirmation message appears, click Yes to confirm the deletion.
6. If the configuration setting to uninstall ETP Client on Windows machines is disabled, you are prompted to enter the entitlement code. Enter the entitlement code and click Next.
Uninstall ETP Client with Windows 10 user interface
To uninstall ETP Client on the Windows 10 interface:
1. Click Start and select Settings.
2. Click Apps.
3. In the list of apps, locate Enterprise Client Connector.
4. Select Enterprise Client Connector and click Uninstall.
5. Click Uninstall.
6. If the configuration setting to uninstall ETP Client on Windows machines is disabled, you are prompted to enter the entitlement code. Enter the entitlement code and click Next.
Uninstall ETP Client with Windows command prompt
To uninstall ETP with Windows command prompt:
1. Open a command prompt as an administrator.
2. If the setting to uninstall ETP Client on Windows machines is enabled in ETP, enter this command:
msiexec /x etpclient_<versionNumber>.msi
where <versionNumber> is the version number of ETP Client.
3. If the setting to uninstall ETP Client on Windows machines is disabled in ETP, enter this command:
msiexec /x etpclient_<versionNumber>.msi CODE="<entitlement_code>" /q
where:
• <versionNumber> is the version number of ETP Client.
• <entitlement_code> is the entitlement code.
4. In the prompt confirming the uninstall, click Yes.
Uninstall ETP Client on Mac
You can complete these steps to uninstall ETP Client on a Mac.
To uninstall ETP Client on Mac:
1. Open a terminal.
2. Enter this command and press Enter:
sudo /Library/Application\ Support/Akamai\ ETP\ Client/uninstall_etpclient
Did this page help you?
|
__label__pos
| 0.919641 |
Would you mind participating in a short survey? We don't need your details - it's anonymous.
We'd like to find out more about your opinion of purchasing software online.
hilitext.exe
Process name: Hilitext
Application using this process: Fanix Software Hilitext
hilitext.exe
Process name: Hilitext
Application using this process: Fanix Software Hilitext
hilitext.exe
Click here to run a scan if you are experiencing issues with this process.
Process name: Hilitext
Application using this process: Fanix Software Hilitext
Recommended: Scan your system for invalid registry entries.
What is hilitext.exe doing on my computer?
hilitext.exe is a Hilitext belonging to Fanix Software Hilitext from Fanix Software (www.fanix.com) Non-system processes like hilitext.exe originate from software you installed on your system. Since most applications store data in your system's registry, it is likely that your registry has suffered fragmentation and accumulated invalid entries which can affect your PC's performance. It is recommended that you check your registry to identify slowdown issues.
hilitext.exe
Is hilitext.exe harmful?
hilitext.exe has not been assigned a security rating yet. Check your computer for viruses or other malware infected files.
hilitext.exe is unrated
Can I stop or remove hilitext.exe?
Most non-system processes that are running can be stopped because they are not involved in running your operating system. Scan your system now to identify unused processes that are using up valuable resources. hilitext.exe is used by 'Fanix Software Hilitext'.This is an application created by 'Fanix Software (www.fanix.com)'. To stop hilitext.exe permanently uninstall 'Fanix Software Hilitext' from your system. Uninstalling applications can leave invalid registry entries, accumulating over time. Run a free scan to find out how to optimize software and system performance.
Is hilitext.exe CPU intensive?
This process is not considered CPU intensive. However, running too many processes on your system may affect your PC’s performance. To reduce system overload, you can use the Microsoft System Configuration Utility to manually find and disable processes that launch upon start-up. Alternatively, download SpeedUpMyPC to automatically scan and identify any unused processes.
Why is hilitext.exe giving me errors?
Process related issues are usually related to problems encountered by the application that runs it. The safest way to stop these errors is to uninstall the application and run a system scan to automatically identify any unused processes and services that are using up valuable resources.
The safest way to stop these errors is to uninstall the application and run a scan to identify any system issues including invalid registry entries that have accumulated over time.
Process Library is the unique and indispensable process listing database since 2004 Now counting 140,000 processes and 55,000 DLLs. Join and subscribe now!
System Tools
SpeedUpMyPC
Toolbox
ProcessQuicklink
|
__label__pos
| 0.850261 |
We're sorry Aspose doesn't work properply without JavaScript enabled.
Free Support Forum - aspose.com
Update on Printing and IF fields
Hi,
Please could you give me an update on two pieces of functionality?
1. IF fields. I am working to convert a Word Automation application to Aspose.Words. One of the things the current application does, is to conditionally display a “voucher”. This is just a block of formatted text within the document that is displayed only if a speciifc flag is set within the mailmerge data. The conditional part uses an IF field. Please can you tell me when this functionality is scheduled to be available in Aspose.Words. Could you also suggest a workaround, bearing in mind that my current application has been designed to allow business staff to manage the Word templates themselves, and so I do not really want to have to recode the application, or work with embedded sub-documents (as that will be complex for the business users to understand)
2. Printing. I believe the printing capability is still in Alpha test, and has quite a few issues. Please can you tell me when this is scheduled to be released as a core part of the Aspose.Words system
Many thanks
Hi
Thanks for your inquiry.
1. At the moment Aspose.Words does not evaluate IF fields. Calculation of all fields (including TOC and IF) - current estimate is sometime in 2008. But it is not very reliable. As workaround you can move your conditional logic into your SQL query or into MargeField event handler.
2. Rendering/Printing feature is still in beta. Unfortunately I cant provide you any reliable estimate date.
Best regards.
Hi Alexey,
Thanks for your quick updates. Could I ask another final question re the IF fields? I have been playing around with GetChildNodes(Aspose.Words.NodeType.FieldStart,True) method, and believe I might be able to use this to “read” the IF statement into my application, and then conduct the condition logic within the code. This means that within the code, if the application is configured to use Microsoft Word (with Word Automation, as has historically been used), Word can handle the IF clause. If, however, the application has been configured to use Aspose.Words, the application can detect the IF fields, perform the conditional logic in the code, and do what is necessary.
The templates currently display additional text if the IF condition is met, and display nothing at all if the IF condition is not met. So, I’m hoping that I can simply lift the formatted text out of the true condition of the IF clause, and replace the entire IF statement with that text. If the IF condition returns FALSE, then I can delete the entire IF statement.
Do you think this would be possible, and would you be able to provide some example code that I can tailor to meet my needs? Fields within Word seem very easy to manipulate, but within Aspose.Words I am quite confused about the number of Run elements within each field.
Many Thanks
Hi
Thanks for your inquiry. Here is code that you can use to get field codes of IF field:
Document doc = new Document(@"Test008\in.doc");
// Get collection of field starts
NodeCollection starts = doc.GetChildNodes(NodeType.FieldStart, true);
// Loop through all field starts
foreach (FieldStart start in starts)
{
// Check whether current FieldStart is start of IF field
if (start.FieldType == FieldType.FieldIf)
{
// Field code is represented by content between Field Start and FieldSeparator
string fieldCode = string.Empty;
Node currentNode = start.NextSibling;
while (currentNode.NodeType != NodeType.FieldSeparator)
{
Run fieldPart = currentNode as Run;
if (fieldPart != null)
fieldCode += fieldPart.Text;
// Move to next node
currentNode = currentNode.NextSibling;
// Break loop if current node is null
if (currentNode == null)
break;
}
// Here you should evaluate conditional expression.
// ..............................
// And execute your logic.
}
}
But any way you should evaluate conditional expression. Maybe the following article could be useful for you:
https://www.codeproject.com/Articles/13335/C-Eval-Function
Hope this helps.
Best regards.
|
__label__pos
| 0.783057 |
短信营销帮助您扩大产品知名度,提高企业经营业绩,提升管理水平
137-0898-9179
您的位置: 首页>>短信接口
短信接口
destoon7.0网站管理系统短信官方短信接口替换方法
发布时间:2018-05-08 人气:56115
DESTOON是一款B2B网站管理系统他是基于PHP+MYSQL,二次开发及后期维护方便。
今天就以替换官方destoon7.0短信接口为例为大家讲解一下如何进行二次开发,我们今天讲解的是7.0版本,使用的短信接口是我们企信通destoon7.0短信接口,我们企信通群发平台非常稳定,发送速度快,注册就送测试短信,推荐大家使用。
开启方法
网站设置》云服务》手机短信》开启 (V7.0版本)
网站短信模板修改
网站项目/lang/zh-cn/sms.inc.php 网站中用到的及时提醒短信的模板,大家可以在这儿修改
$L['sms_code'] = '您的短信验证码为:{V0},有效期{V1}分钟,切勿透露给他人';
$L['sms_inquiry'] = '您的产品[{V0}](ID:{V1}),收到询价.联系人:{V2},电话:{V3}';
$L['sms_price'] = '您的求购[{V0}](ID:{V1}),收到报价.联系人:{V2},电话:{V3}';
$L['sms_message'] = '您发布的[{V0}](ID:{V1}),收到留言.联系人:{V2},电话:{V3}';
$L['ord_confirm'] = '卖家更新了您的订单(T{V0}),请及时付款';
$L['ord_pay'] = '买家已经支付订单(T{V0})款项{V1}元,请及时发货';
$L['ord_send'] = '订单(T{V0})卖家已经发货.物流:{V1},单号:{V2},时间:{V3}';
$L['ord_receive'] = '订单(T{V0})买家已确认收货.款项{V1}元已支付,请注意查收';
$L['ord_income'] = '站内收入提醒,您收到{V0}一笔付款,金额:{V1}元';
$L['ord_new'] = '您的产品[{V0}]收到新订单,请及时处理.金额:{V1}元,编号:{V2},联系人:{V3},电话:{V4}';
$L['ord_group'] = '您已成功团购{V0},订单ID:{V1},密码:{V2}';
$L['wel_reg'] = '您好{V0},欢迎您注册{V1},您的户名:{V2},密码:{V3},请妥善保存';
方法一:适用于原版安装
快捷安装直接解压之后把include和admin覆盖网站根目录文件夹包含里面的文件
destoon7.0短信接口
方法二:适用于二次开发
详细方法请找客服索取
网站设置》云服务》手机短信》开启 (V7.0版本)
后台设置 输入 注册的企信通帐号 密码 企业ID 和网站签名即可看到剩余短信条数
destoon7.0网站管理系统短信
发送记录
destoon7.0网站管理系统短信
欢迎来电咨询:131 5636 6963
http://www.186117.cn/smsplug/Destoon7.html
标签:网站验证码 短信接口 Destoon 手机短信息
短信系统
帐号登录
帐号注册
在线客服 客服软件
|
__label__pos
| 0.712818 |
Difference between revisions of "Random points"
From JSXGraph Wiki
Jump to navigationJump to search
Line 1: Line 1:
+
===Draw 100 random points===
<html>
<html>
<link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css" />
<link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css" />
Line 24: Line 25:
<source lang="javascript">
<source lang="javascript">
+
board = JXG.JSXGraph.initBoard('box', {originX: 10, originY:390 , unitX:380 , unitY: 380});
+
+
function reload() {
+
JXG.JSXGraph.freeBoard(board);
+
board = JXG.JSXGraph.initBoard('box', {originX: 10, originY: 390, unitX: 380, unitY: 380});
+
+
board.suspendUpdate();
+
for (var i=0;i<100;i++) {
+
var p = board.createElement('point',
+
[Math.random(),Math.random()],{style:5,name:' '});
+
}
+
board.unsuspendUpdate();
+
}
+
reload();
</source>
</source>
+
===Draw 100 random points===
+
These 100 points are updated on the onmouseover event and get
+
new random coordinates.
+
<html>
+
<link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css" />
+
<script type="text/javascript" src="http://jsxgraph.uni-bayreuth.de/distrib/prototype.js"></script>
+
<script type="text/javascript" src="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraphcore.js"></script>
+
<form><input type='button' value="Reload" onClick="reload();"></form>
+
<div id="box2" class="jxgbox" style="width:400px; height:400px;"></div>
+
<script language="JavaScript">
+
board2 = JXG.JSXGraph.initBoard('box2', {originX: 10, originY:390 , unitX:380 , unitY: 380});
+
board2.suspendUpdate();
+
for (var i=0;i<100;i++) {
+
var p = board2.createElement('point',
+
[function(){return Math.random();},function(){ return Math.random()}],
+
{style:5,name:' '});
+
}
+
board.unsuspendUpdate();
+
</script>
+
</html>
+
+
<source lang="javascript">
+
</source>
[[Category:Examples]]
[[Category:Examples]]
Revision as of 15:25, 7 December 2008
Draw 100 random points
board = JXG.JSXGraph.initBoard('box', {originX: 10, originY:390 , unitX:380 , unitY: 380});
function reload() {
JXG.JSXGraph.freeBoard(board);
board = JXG.JSXGraph.initBoard('box', {originX: 10, originY: 390, unitX: 380, unitY: 380});
board.suspendUpdate();
for (var i=0;i<100;i++) {
var p = board.createElement('point',
[Math.random(),Math.random()],{style:5,name:' '});
}
board.unsuspendUpdate();
}
reload();
Draw 100 random points
These 100 points are updated on the onmouseover event and get new random coordinates.
|
__label__pos
| 0.869978 |
Creating an Oracle user for the repository database instance
Contributors akseldavis Download PDF of this page
An Oracle user is required to log in to and access the repository database instance. You must create this user with connect and resource privileges.
1. Log in to SQL *Plus: 'sqlplus / as sysdba'
2. Create a new user and assign an administrator password to that user: 'create useruser_name identified by admin_password default tablespace tablespace_name quota unlimited on tablespace_name;'
• user_name is the name of the user you are creating for the repository database.
• admin_password is the password you want to assign to the user.
• tablespace_name is the name of the tablespace created for the repository database.
3. Assign connect and resource privileges to the new Oracle user: 'grant connect, resource to user_name;'
|
__label__pos
| 0.894413 |
Announcing the AWS Amplify CLI toolchain. Click here to read more.
Storage
S3
Overview
Enable your app to store and retrieve user files from cloud storage with the permissions model that suits your purpose. The CLI deploys and configures cloud storage buckets using Amazon Simple Storage Service.
Storage Access
The CLI configures three different access levels on the storage bucket: public, protected and private. When you run amplify add storage, the CLI will configure appropriate IAM policies on the bucket using a Cognito Identity Pool Role. If you had previously enabled user sign-in by running amplify add auth in your project, the policies will be connected to an Authenticated Role of the Identity Pool which has scoped permission to the objects in the bucket for each user identity. If you haven’t configured user sign-in, then an Unauthenticated Role will be assigned for each unique user/device combination, which still has scoped permissions to just their objects.
• Public: Accessible by all users of your app. Files are stored under the public/ path in your S3 bucket.
• Protected: Readable by all users, but writable only by the creating user. Files are stored under protected/{user_identity_id}/ where the user_identity_id corresponds to the unique Amazon Cognito Identity ID for that user.
• Private: Only accessible for the individual user. Files are stored under private/{user_identity_id}/ where the user_identity_id corresponds to the unique Amazon Cognito Identity ID for that user.
See Authentication for more information on how to get the user_identity_id for a signed in user.
Set Up Your Backend
1. Complete the Get Started steps before you proceed.
2. Use the CLI to add storage to your cloud-enabled backend and app.
In a terminal window, navigate to your project folder (the folder that contains your app .xcodeproj file), and add the SDK to your app.
$ cd ./YOUR_PROJECT_FOLDER
$ amplify add storage
3. Choose Content as your storage service.
❯ Content (Images, audio, video, etc.)
4. The CLI walks you through the options to enable Auth (if not enabled previously), to name your S3 bucket, and to decide who should have access (select Auth and guest users and read/write for both auth and guest users).
5. Confirm that you have storage and auth set up.
$ amplify status
| Category | Resource name | Operation | Provider plugin |
| --------- | --------------- | --------- | ----------------- |
| Auth | cognito2e202b09 | Create | awscloudformation |
| Storage | sabc0123de | Create | awscloudformation |
6. To create your backend run:
$ amplify push
The CLI will create the awsconfiguration.json file in your project directory. Add it to your project using XCode.
Connect to Your Backend
Use the following steps to add file storage backend services to your app.
1. Add the AWSS3 dependency to the Podfile to install the AWS Mobile SDK:
platform :ios, '9.0'
target :'YOUR-APP-NAME' do
use_frameworks!
pod 'AWSS3', '~> 2.9.0' # For file transfers
# other pods . . .
pod 'AWSMobileClient', '~> 2.9.0'
end
Run pod install --repo-update before you continue.
1. Add the following import to the classes that perform user file storage operations:
import AWSS3
Using TransferUtility
To make it easy to upload and download objects from Amazon S3, we provide a TransferUtility component with built-in support for background transfers, progress tracking, and MultiPart uploads. This section explains how to implement upload and download functionality and a number of additional storage use cases.
Note: If you use the transfer utility MultiPart upload feature, take advantage of automatic cleanup features by setting up the AbortIncompleteMultipartUpload action in your Amazon S3 bucket life cycle configuration.
Transfer Utility Options
You can use the AWSS3TransferUtilityConfiguration object to configure the operations of the TransferUtility.
isAccelerateModeEnabled
The isAccelerateModeEnabled option lets you to upload and download content from a bucket that has Transfer Acceleration enabled on it. This option is set to false by default. See Transfer Acceleration for information on how to enable transfer acceleration for your bucket.
The code sample below manually sets up credentials for the TransferUtility. The best practice is to use the AWSMobileClient. See Authentication for more details
//Setup credentials, see your awsconfiguration.json for the "YOUR-IDENTITY-POOL-ID"
let credentialProvider = AWSCognitoCredentialsProvider(regionType: YOUR-IDENTITY-POOL-REGION, identityPoolId: "YOUR-IDENTITY-POOL-ID")
//Setup the service configuration
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialProvider)
//Setup the transfer utility configuration
let tuConf = AWSS3TransferUtilityConfiguration()
tuConf.isAccelerateModeEnabled = true
//Register a transfer utility object asynchronously
AWSS3TransferUtility.register(
with: configuration!,
transferUtilityConfiguration: tuConf,
forKey: "transfer-utility-with-advanced-options"
) { (error) in
if let error = error {
//Handle registration error.
}
}
//Look up the transfer utility object from the registry to use for your transfers.
let transferUtility:(AWSS3TransferUtility?) = AWSS3TransferUtility.s3TransferUtility(forKey: "transfer-utility-with-advanced-options")
retryLimit
The retryLimit option allows you to specify the number of times the TransferUtility will retry a transfer when it encounters an error during the transfer. By default, it is set to 0, which means that there will be no retries.
tuConf.retryLimit = 5
multiPartConcurrencyLimit
The multiPartConcurrencyLimit option allows you to specify the number of parts that will be uploaded in parallel for a MultiPart upload request. By default, this is set to 5.
tuConf.multiPartConcurrencyLimit = 3
timeoutIntervalForResource
The timeoutIntervalForResource parameter allows you to specify the maximum duration the transfer can run. The default value for this parameter is 50 minutes. This value is important if you use Amazon Cognito temporary credential because it aligns with the maximum span of time that those credentials are valid.
tuConf.timeoutIntervalForResource = 15*60 //15 minutes
Upload a File
The transfer utility provides methods for both single-part and multipart uploads. When a transfer uses multipart upload, the data is chunked into a number of 5 MB parts which are transferred in parallel for increased speed.
The following example shows how to upload a file to an Amazon S3 bucket.
func uploadData() {
let data: Data = Data() // Data to be uploaded
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = {(task, progress) in
DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
})
}
var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async(execute: {
// Do something e.g. Alert a user for transfer completion.
// On failed uploads, `error` contains the error object.
})
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadData(data,
bucket: "YourBucket",
key: "YourFileName",
contentType: "text/plain",
expression: expression,
completionHandler: completionHandler).continueWith {
(task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
// Do something with uploadTask.
}
return nil;
}
}
The following example shows how to upload a file to an Amazon S3 bucket using multipart uploads.
func uploadData() {
let data: Data = Data() // Data to be uploaded
let expression = AWSS3TransferUtilityMultiPartUploadExpression()
expression.progressBlock = {(task, progress) in
DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
})
}
var completionHandler: AWSS3TransferUtilityMultiPartUploadCompletionHandlerBlock
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async(execute: {
// Do something e.g. Alert a user for transfer completion.
// On failed uploads, `error` contains the error object.
})
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadUsingMultiPart(data:data,
bucket: "YourBucket",
key: "YourFileName",
contentType: "text/plain",
expression: expression,
completionHandler: completionHandler).continueWith {
(task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
// Do something with uploadTask.
}
return nil;
}
}
Download a File
The following example shows how to download a file from an Amazon S3 bucket.
func downloadData() {
let expression = AWSS3TransferUtilityDownloadExpression()
expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
})
}
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
completionHandler = { (task, URL, data, error) -> Void in
DispatchQueue.main.async(execute: {
// Do something e.g. Alert a user for transfer completion.
// On failed downloads, `error` contains the error object.
})
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.downloadData(
fromBucket: "YourBucket",
key: "YourFileName",
expression: expression,
completionHandler: completionHandler
).continueWith {
(task) -> AnyObject! in if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
// Do something with downloadTask.
}
return nil;
}
}
Track Transfer Progress
Implement progress and completion actions for transfers by passing a progressBlock and completionHandler blocks to the call to AWSS3TransferUtility that initiates the transfer.
The following example of initiating a data upload, shows how progress and completion handling is typically done for all transfers. The AWSS3TransferUtilityUploadExpression, AWSS3TransferUtilityMultiPartUploadExpression and AWSS3TransferUtilityDownloadExpression contains the progressBlock that gives you the progress of the transfer which you can use to update the progress bar.
// For example, create a progress bar
let progressView: UIProgressView! = UIProgressView()
progressView.progress = 0.0;
let data = Data() // The data to upload
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: {
// Update a progress bar.
progressView.progress = Float(progress.fractionCompleted)
})
}
let completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock = { (task, error) -> Void in DispatchQueue.main.async(execute: {
if let error = error {
NSLog("Failed with error: \(error)")
}
else if(self.progressView.progress != 1.0) {
NSLog("Error: Failed.")
} else {
NSLog("Success.")
}
})
}
var refUploadTask: AWSS3TransferUtilityTask?
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadData(data,
bucket: "S3BucketName",
key: "S3UploadKeyName",
contentType: "text/plain",
expression: expression,
completionHandler: completionHandler).continueWith { (task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let uploadTask = task.result {
// Do something with uploadTask.
// The uploadTask can be used to pause/resume/cancel the operation, retrieve task specific information
refUploadTask = uploadTask
}
return nil;
}
Pause a Transfer
To pause a transfer, retain references to AWSS3TransferUtilityUploadTask, AWSS3TransferUtilityMultiPartUploadTask or AWSS3TransferUtilityDownloadTask .
As described in the previous section :ref:native-track-progress-and-completion-of-a-transfer, the variable refUploadTask is a reference to the UploadTask object that is retrieved from the continueWith block of an upload operation that is invoked through transferUtility.uploadData.
To pause a transfer, use the suspend method:
refUploadTask.suspend()
Resume a Transfer
To resume a transfer, use the resume method:
refUploadTask.resume()
Cancel a Transfer
To cancel a transfer, use the cancel method:
refUploadTask.cancel()
Background Transfers
All transfers performed by TransferUtility for iOS happen in the background using NSURLSession background sessions. Once a transfer is initiated, it will continue regardless of whether the initiating app moves to the foreground, moves to the background, is suspended, or is terminated by the system. Note that this doesn’t apply when the app is force-closed. Transfers initiated by apps that are force-closed are terminated by the operating system at the NSURLSession level. For regular uploads and downloads, you will have to re-initiate the transfer. For multi-part uploads, the TransferUtility will resume automatically and will continue the transfer.
To wake an app that is suspended or in the background when a transfer it has initiated is completed, implement the handleEventsForBackgroundURLSession method in the AppDelegate and have it call the interceptApplication method of AWSS3TransferUtility as follows.
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
// Store the completion handler.
AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)
}
Managing Transfers When an App Restarts
When an app that has initiated a transfer restarts (if it has been terminated by the system and not force-closed), the transfer may still be in progress or have completed. To make the restarting app aware of the status of transfers, instantiate the transfer utility using the AWSS3TransferUtility.s3TransferUtility(forKey: "YOUR_KEY") method. AWSS3TransferUtility uses the key to uniquely identify the NSURLSession of the transfers initiated by the app, so it is important to always use the same identifier. AWSS3TransferUtility will automatically reconnect to the transfers that were in progress the last time the app was running.
Though it can be called anywhere in the app, we recommend that you instantiate the AWSS3TransferUtility in the appDidFinishLaunching lifecycle method.
Manage a Transfer when a Suspended App Returns to the Foreground
When an app that has initiated a transfer becomes suspended and then returns to the foreground, the transfer may still be in progress or may have completed. In both cases, use the following code to re-establish the progress and completion handler blocks of the app.
let uploadTasks = transferUtility.getUploadTasks().result
for task in uploadTasks! {
task.setCompletionHandler(completionHandler!)
task.setProgressBlock(progressBlock!)
}
let downloadTasks = transferUtility.getDownloadTasks().result
for task in downloadTasks! {
task.setCompletionHandler(completionHandler!)
task.setProgressBlock(progressBlock!)
}
}
let multiPartUploadTasks = transferUtility.getMultiPartUploadTasks().result
for task in multiPartUploadTasks! {
task.setCompletionHandler(completionHandler!)
task.setProgressBlock(progressBlock!)
}
Transfer with Object Metadata
The AWSS3TransferUtilityUploadExpression and AWSS3TransferUtilityMultiPartUploadExpression classes contain the method setValue:forRequestHeader where you can pass in metadata to Amazon S3. This example demonstrates passing in the Server-side Encryption Algorithm as a request header in uploading data to S3 using MultiPart. See Object Key and Metadata for more information.
let data: Data = Data() // The data to upload
let uploadExpression = AWSS3TransferUtilityMultiPartUploadExpression()
uploadExpression.setValue("AES256", forRequestHeader: "x-amz-server-side-encryption-customer-algorithm")
uploadExpression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
})
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.uploadUsingMultiPart(data:data,
bucket: "S3BucketName",
key: "S3UploadKeyName",
contentType: "text/plain",
expression: uploadExpression,
completionHandler: nil).continueWith { (task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
}
return nil;
}
Usage with GraphQL APIs (Complex Objects)
Note: Please review the documentation for API before you proceed with the rest of this section.
You can also upload and download Amazon S3 Objects using AWS AppSync, a GraphQL based solution to build data-driven apps with real-time and offline capabilities. Sometimes you might want to create logical objects that have more complex data, such as images or videos, as part of their structure. For example, you might create a Person type with a profile picture or a Post type that has an associated image. You can use AWS AppSync to model these as GraphQL types. If any of your mutations have a variable with bucket, key, region, mimeType, and localUri fields, the SDK uploads the file to Amazon S3 for you.
Attach the following policy to your IAM role to grant it programmatic read-write access to your bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::myBucket"]
},
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject"
],
"Resource": ["arn:aws:s3:::myBucket/*"]
}
]
}
Update your schema as follows to add the S3Object and S3ObjectInput types for the file, and a new mutation named CreatePostWithFileInputMutation:
input CreatePostInput {
author: String!
title: String
content: String
url: String
ups: Int
downs: Int
version: Int!
}
input CreatePostWithFileInput {
author: String!
title: String
content: String
url: String
ups: Int
downs: Int
file: S3ObjectInput!
version: Int!
}
input DeletePostInput {
id: ID!
}
type Mutation {
createPost(input: CreatePostInput!): Post
createPostWithFile(input: CreatePostWithFileInput!): Post
updatePost(input: UpdatePostInput!): Post
deletePost(input: DeletePostInput!): Post
}
type Post {
id: ID!
author: String!
title: String
content: String
url: String
ups: Int
downs: Int
file: S3Object
version: Int!
}
type PostConnection {
items: [Post]
nextToken: String
}
type Query {
singlePost(id: ID!): Post
getPost(id: ID!): Post
listPosts(filter: TablePostFilterInput, limit: Int, nextToken: String): PostConnection
}
type S3Object {
bucket: String!
key: String!
region: String!
}
input S3ObjectInput {
bucket: String!
key: String!
region: String!
localUri: String!
mimeType: String!
}
type Subscription {
onCreatePost(
id: ID,
author: String,
title: String,
content: String,
url: String
): Post
@aws_subscribe(mutations: ["createPost"])
onUpdatePost(
id: ID,
author: String,
title: String,
content: String,
url: String
): Post
@aws_subscribe(mutations: ["updatePost"])
onDeletePost(
id: ID,
author: String,
title: String,
content: String,
url: String
): Post
@aws_subscribe(mutations: ["deletePost"])
}
input TableBooleanFilterInput {
ne: Boolean
eq: Boolean
}
input TableFloatFilterInput {
ne: Float
eq: Float
le: Float
lt: Float
ge: Float
gt: Float
contains: Float
notContains: Float
between: [Float]
}
input TableIDFilterInput {
ne: ID
eq: ID
le: ID
lt: ID
ge: ID
gt: ID
contains: ID
notContains: ID
between: [ID]
beginsWith: ID
}
input TableIntFilterInput {
ne: Int
eq: Int
le: Int
lt: Int
ge: Int
gt: Int
contains: Int
notContains: Int
between: [Int]
}
input TablePostFilterInput {
id: TableIDFilterInput
author: TableStringFilterInput
title: TableStringFilterInput
content: TableStringFilterInput
url: TableStringFilterInput
ups: TableIntFilterInput
downs: TableIntFilterInput
version: TableIntFilterInput
}
input TableStringFilterInput {
ne: String
eq: String
le: String
lt: String
ge: String
gt: String
contains: String
notContains: String
between: [String]
beginsWith: String
}
input UpdatePostInput {
id: ID!
author: String
title: String
content: String
url: String
ups: Int
downs: Int
version: Int
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
Note: If you’re using the sample schema specified at the start of this documentation, you can replace your schema with the previous schema. Next, you need to add a resolver for createPostWithFile mutation. You can do that from the AWS AppSync console by selecting PostsTable as the data source and the following mapping templates. Request Mapping Template
{
"version": "2017-02-28",
"operation": "PutItem",
"key": {
"id": $util.dynamodb.toDynamoDBJson($util.autoId()),
},
#set( $attribs = $util.dynamodb.toMapValues($ctx.args.input) )
#if($util.isNull($ctx.args.input.file.version))
#set( $attribs.file = $util.dynamodb.toS3Object($ctx.args.input.file.key, $ctx.args.input.file.bucket, $ctx.args.input.file.region))
#else
#set( $attribs.file = $util.dynamodb.toS3Object($ctx.args.input.file.key, $ctx.args.input.file.bucket, $ctx.args.input.file.region, $ctx.args.input.file.version))
#end
"attributeValues": $util.toJson($attribs),
"condition": {
"expression": "attribute_not_exists(#id)",
"expressionNames": {
"#id": "id",
},
},
}
Response Mapping Template
$util.toJson($context.result)
After you have a resolver for the mutation, to ensure that our S3 Complex Object details are fetched correctly during any query operation, add a resolver for the file field of Post. You can do that from the AWS AppSync console by using the following mapping templates. Request Mapping Template
{
"version" : "2017-02-28",
"operation" : "Query",
"query" : {
## Provide a query expression. **
"expression": "id = :id",
"expressionValues" : {
":id" : {
"S" : "${ctx.args.id}"
}
}
}
}
Response Mapping Template
$util.toJson($util.dynamodb.fromS3ObjectJson($context.source.file))
The AWS AppSync SDK doesn’t take a direct dependency on the AWS SDK for iOS for Amazon S3, but takes in :code:AWSS3TransferUtility and :code:AWSS3PresignedURLClient clients as part of AWSAppSyncClientConfiguration. The code generator used above for generating the API generates the Amazon S3 wrappers required to use the previous clients in the client code. To generate the wrappers, pass the :code:--add-s3-wrapper flag while running the code generator tool. You also need to take a dependency on the AWSS3 SDK. You can do that by updating your Podfile to the following:
target: 'PostsApp' do
use_frameworks!
pod 'AWSAppSync', ~> '2.9.0'
pod 'AWSS3', ~> '2.9.0'
end
Then run pod install to fetch the new dependency. Download the updated schema.json from the and put it in the GraphQLOperations folder in the root of the app. Next, you have to add the new mutation, which is used to perform S3 uploads as part of mutation. Add the following mutation operation in your posts.graphql file:
mutation AddPostWithFile($input: CreatePostWithFileInput!) {
createPostWithFile(input: $input) {
id
title
author
url
content
ups
downs
version
file {
...S3Object
}
}
}
fragment S3Object on S3Object {
bucket
key
region
}
}
After adding the new mutation in our operations file, we run the code generator again with the new schema to generate mutations that support file uploads. This time, we also pass the -add-s3-wrapper flag, as follows:
aws-appsync-codegen generate GraphQLOperations/posts.graphql --schema GraphQLOperations/schema.json --output API.swift --add-s3-wrapper
Update the :code:AWSAppSyncClientConfiguration object to provide the :code:AWSS3TransferUtility client for managing the uploads and downloads:
let appSyncConfig = try AWSAppSyncClientConfiguration(url: AppSyncEndpointURL,
serviceRegion: AppSyncRegion,
credentialsProvider: credentialsProvider,
databaseURL:databaseURL,
s3ObjectManager: AWSS3TransferUtility.default())
The mutation operation doesn’t require any specific changes in method signature. It requires only an S3ObjectInput with bucket, key, region, localUri, and mimeType. Now when you do a mutation, it automatically uploads the specified file to Amazon S3 using the AWSS3TransferUtility client internally.
Working with Pre-Signed URLS
By default, all Amazon S3 resources are private. If you want your users to have access to Amazon S3 buckets or objects, you can assign appropriate permissions with an IAM policy.
However, what if you wanted to provide permissions temporarily, for example: you want to share a link to file temporarily and have the link expire after a set time. To do this using an IAM policy would require you to first setup the policy to grant access and then at a later time remember to delete the IAM policy to revoke access.
Alternatively, you can use pre-signed URLs to give your users temporary access to Amazon S3 objects. When you create a pre-signed URL, you must provide your security credentials, specify a bucket name, an object key, an HTTP method, and an expiration date and time. The pre-signed URL is valid only for the specified duration.
Building a Pre-Signed URL
The following example shows how to build a pre-signed URL to get an Amazon S3 object.
let getPreSignedURLRequest = AWSS3GetPreSignedURLRequest()
getPreSignedURLRequest.bucket = "myBucket"
getPreSignedURLRequest.key = "myFile.txt"
getPreSignedURLRequest.httpMethod = .GET
getPreSignedURLRequest.expires = Date(timeIntervalSinceNow: 3600) // Change the value of the expires time interval as required
AWSS3PreSignedURLBuilder.default().getPreSignedURL(getPreSignedURLRequest).continueWith { (task:AWSTask<NSURL>) -> Any? in
if let error = task.error as? NSError {
print("Error: \(error)")
return nil
}
let presignedURL = task.result
// Use the Pre-Signed URL here as required
....
....
return nil
}
The preceding example uses GET as the HTTP method: AWSHTTPMethodGET. For an upload request to Amazon S3, we would need to use a PUT method.
let getPreSignedURLRequest = AWSS3GetPreSignedURLRequest()
getPreSignedURLRequest.bucket = "myBucket"
getPreSignedURLRequest.key = "myFile.txt"
getPreSignedURLRequest.httpMethod = .PUT
getPreSignedURLRequest.expires = Date(timeIntervalSinceNow: 3600) // Change the value of the expires time interval as required
getPreSignedURLRequest.contentType = "text/plain"
AWSS3PreSignedURLBuilder.default().getPreSignedURL(getPreSignedURLRequest).continueWith { (task:AWSTask<NSURL>) -> Any? in
if let error = task.error as? NSError {
print("Error: \(error)")
return nil
}
let presignedURL = task.result
// Use the Pre-Signed URL here as required
....
....
return nil
}
Note on Transfer Utility and Pre-Signed URLS
The TransferUtility generates Amazon S3 pre-signed URLs to use for background data transfer. The best practice is to use Amazon Cognito for credentials with Transfer Utility. With Amazon Cognito Identity, you receive AWS temporary credentials that are valid for up to 60 minutes. The pre-signed URLs built using these credentials are bound by the same time limit, after which the URLs will expire.
Because of this limitation, when you use TransferUtility with AWS Cognito, the expiry on the Pre-Signed URLs generated internally is set to 50 minutes. Transfers that run longer than the 50 minutes will fail. If you are transferring a large enough file where this becomes a constraint, you should create static credentials using AWSStaticCredentialsProvider ( see Authentication for more details on how to do this) and increase the expiry time on the Pre-Signed URLs by increasing the value for the timeoutIntervalForResource in the Transfer Utility Options. Note that the max allowed expiry value for a Pre-Signed URL is 7 days.
Additional Resources
Next Steps
For a sample app that demonstrate the capabilities of the TransferUtility, see S3 TransferUtility Sample.
|
__label__pos
| 0.995023 |
/* GKrellM | Copyright (C) 1999-2019 Bill Wilson | | Author: Bill Wilson [email protected] | Latest versions might be found at: http://gkrellm.net | | | GKrellM is free software: you can redistribute it and/or modify it | under the terms of the GNU General Public License as published by | the Free Software Foundation, either version 3 of the License, or | (at your option) any later version. | | GKrellM 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. | | You should have received a copy of the GNU General Public License | along with this program. If not, see http://www.gnu.org/licenses/ | | | Additional permission under GNU GPL version 3 section 7 | | If you modify this program, or any covered work, by linking or | combining it with the OpenSSL project's OpenSSL library (or a | modified version of that library), containing parts covered by | the terms of the OpenSSL or SSLeay licenses, you are granted | additional permission to convey the resulting work. | Corresponding Source for a non-source form of such a combination | shall include the source code for the parts of OpenSSL used as well | as that of the covered work. */ #include "gkrellmd.h" #include "gkrellmd-private.h" #include GList *gkrellmd_monitor_list; static GList *serveflag_done_list; static struct tm gkrellmd_current_tm; gint gkrellm_get_timer_ticks(void) { return GK.timer_ticks; } gboolean gkrellmd_check_client_version(GkrellmdMonitor *mon, gint major, gint minor, gint rev) { GkrellmdClient *client = mon->privat->client; if ( client->major_version > major || (client->major_version == major && client->minor_version > minor) || ( client->major_version == major && client->minor_version == minor && client->rev_version >= rev ) ) return TRUE; return FALSE; } void gkrellmd_add_serveflag_done(gboolean *flag) { serveflag_done_list = g_list_append(serveflag_done_list, flag); } void gkrellmd_set_serve_name(GkrellmdMonitor *mon, const gchar *tag) { GkrellmdMonitorPrivate *mp = mon->privat; mp->serve_name = tag; mp->serve_name_sent = FALSE; } void gkrellmd_serve_data(GkrellmdMonitor *mon, gchar *line) { GkrellmdMonitorPrivate *mp = mon->privat; gchar buf[128]; if (!line || !*line) return; if (!mp->serve_name_sent) { if (mp->serve_name) { snprintf(buf, sizeof(buf), "<%s>\n", mp->serve_name); gkrellm_debug(DEBUG_SERVER, "%s", buf); mp->serve_gstring = g_string_append(mp->serve_gstring, buf); mp->serve_name_sent = TRUE; } else { g_warning("gkrellmd: %s forgot to gkrellmd_set_serve_name()\n", mon->name); return; } } gkrellm_debug(DEBUG_SERVER,"%s", line); mp->serve_gstring = g_string_append(mp->serve_gstring, line); } /* ======================================================= */ typedef struct { gint instance; gulong user, nice, sys, idle; } CpuData; static gchar *n_cpus_setup; static gboolean nice_time_unsupported; static GList *cpu_list; static GList *instance_list; void gkrellm_cpu_set_number_of_cpus(gint n) { CpuData *cpu; GList *list; gint i; n_cpus_setup = g_strdup_printf("n_cpus %d\n", n); for (i = 0; i < n; ++i) { cpu = g_new0(CpuData, 1); cpu_list = g_list_append(cpu_list, cpu); if (instance_list && (list = g_list_nth(instance_list, i)) != NULL) cpu->instance = GPOINTER_TO_INT(list->data); else cpu->instance = i; } } void gkrellm_cpu_add_instance(gint instance) { instance_list = g_list_append(instance_list, GINT_TO_POINTER(instance)); } void gkrellm_cpu_nice_time_unsupported(void) { nice_time_unsupported = TRUE; } void gkrellm_cpu_assign_composite_data(gulong user, gulong nice, gulong sys, gulong idle) { return; /* let client gkrellm compute it */ } void gkrellm_cpu_assign_data(gint n, gulong user, gulong nice, gulong sys, gulong idle) { CpuData *cpu = NULL; GList *list; for (list = cpu_list; list; list = list->next) { cpu = (CpuData *) list->data; if (cpu->instance == n) break; } if (list) { cpu->user = user; cpu->nice = nice; cpu->sys = sys; cpu->idle = idle; } } static void update_cpu(GkrellmdMonitor *mon, gboolean first_update) { gkrellm_sys_cpu_read_data(); gkrellmd_need_serve(mon); } static void serve_cpu_data(GkrellmdMonitor *mon, gboolean first_serve) { CpuData *cpu; GList *list; gchar buf[128]; gkrellmd_set_serve_name(mon, "cpu"); for (list = cpu_list; list; list = list->next) { cpu = (CpuData *) list->data; snprintf(buf, sizeof(buf), "%d %lu %lu %lu %lu\n", cpu->instance, cpu->user, cpu->nice, cpu->sys, cpu->idle); gkrellmd_serve_data(mon, buf); } } static void serve_cpu_setup(GkrellmdMonitor *mon) { GkrellmdClient *client = mon->privat->client; GList *list; gchar buf[64]; gkrellmd_send_to_client(client, "\n"); for (list = instance_list; list; list = list->next) { snprintf(buf, sizeof(buf), "cpu_instance %d\n", GPOINTER_TO_INT(list->data)); gkrellmd_send_to_client(client, buf); } gkrellmd_send_to_client(client, n_cpus_setup); if (nice_time_unsupported) gkrellmd_send_to_client(client, "nice_time_unsupported\n"); } static GkrellmdMonitor cpu_monitor = { "cpu", update_cpu, serve_cpu_data, serve_cpu_setup }; static GkrellmdMonitor * init_cpu_monitor(void) { if (gkrellm_sys_cpu_init()) return &cpu_monitor; return NULL; } /* ======================================================= */ struct { gboolean changed; gint n_processes, n_running, n_users; gulong n_forks; gfloat fload; } proc; void gkrellm_proc_assign_data(gint n_processes, gint n_running, gulong n_forks, gfloat load) { if ( proc.n_processes != n_processes || proc.n_running != n_running || proc.n_forks != n_forks || proc.fload != load ) { proc.n_processes = n_processes; proc.n_running = n_running; proc.n_forks = n_forks; proc.fload = load; proc.changed = TRUE; } } void gkrellm_proc_assign_users(gint n_users) { if (proc.n_users != n_users) { proc.n_users = n_users; proc.changed = TRUE; } } static void update_proc(GkrellmdMonitor *mon, gboolean first_update) { proc.changed = FALSE; gkrellm_sys_proc_read_data(); if (first_update || GK.five_second_tick) gkrellm_sys_proc_read_users(); if (proc.changed) gkrellmd_need_serve(mon); } static void serve_proc_data(GkrellmdMonitor *mon, gboolean first_serve) { gchar buf[128]; gkrellmd_set_serve_name(mon, "proc"); snprintf(buf, sizeof(buf), "%d %d %lu %.2f %d\n", proc.n_processes, proc.n_running, proc.n_forks, proc.fload, proc.n_users); gkrellmd_serve_data(mon, buf); } static GkrellmdMonitor proc_monitor = { "proc", update_proc, serve_proc_data, NULL }; static GkrellmdMonitor * init_proc_monitor(void) { if (!gkrellm_sys_proc_init()) return NULL; serveflag_done_list = g_list_append(serveflag_done_list, &proc.changed); return &proc_monitor; } /* ======================================================= */ typedef struct { gchar *name; gchar *subdisk_parent; gint order, subdisk, changed; gint device_number, unit_number; gboolean virtual; guint64 rb, wb; } DiskData; static GList *disk_list; static gint n_disks; static gboolean units_are_blocks; static DiskData * add_disk(const gchar *name, gint order, gint device_number, gint unit_number) { DiskData *disk; GList *list; gint i; disk = g_new0(DiskData, 1); disk->name = g_strdup(name); disk->order = order; disk->subdisk = -1; disk->device_number = device_number; disk->unit_number = unit_number; if (order >= 0) { for (i = 0, list = disk_list; list; list = list->next, ++i) if (disk->order < ((DiskData *) list->data)->order) break; disk_list = g_list_insert(disk_list, disk, i); } else disk_list = g_list_append(disk_list, disk); ++n_disks; return disk; } static DiskData * add_subdisk(gchar *subdisk_name, gchar *disk_name, gint subdisk) { DiskData *sdisk = NULL; DiskData *disk; GList *list = NULL; for (list = disk_list; list; list = list->next) { disk = (DiskData * ) list->data; if (!strcmp(disk_name, disk->name)) break; } if (!list) return NULL; sdisk = g_new0(DiskData, 1); sdisk->name = g_strdup(subdisk_name); sdisk->subdisk_parent = g_strdup(disk_name); sdisk->order = disk->order; sdisk->subdisk = subdisk; for (list = list->next; list; list = list->next) { disk = (DiskData * ) list->data; if (disk->subdisk == -1 || disk->subdisk > subdisk) break; } disk_list = g_list_insert_before(disk_list, list, sdisk); ++n_disks; return sdisk; } static void disk_assign_data(DiskData *disk, guint64 rb, guint64 wb, gboolean virtual) { if (disk) { if (disk->rb != rb || disk->wb != wb) disk->changed = TRUE; else disk->changed = FALSE; disk->rb = rb; disk->wb = wb; disk->virtual = virtual; } } void gkrellm_disk_reset_composite(void) { /* Don't handle this. */ } void gkrellm_disk_units_are_blocks(void) { units_are_blocks = TRUE; } void gkrellm_disk_add_by_name(const gchar *name, const gchar *label) { gint order = -1; if (NULL == name) // Cannot add disk without a name return; order = gkrellm_sys_disk_order_from_name(name); /* FIXME: gkrellmd currently has no support for disk labels. Extend network-protocol and server to support disks with both name and label. */ add_disk(name, order, 0, 0); } void gkrellm_disk_assign_data_by_device(gint device_number, gint unit_number, guint64 rb, guint64 wb, gboolean virtual) { GList *list; DiskData *disk = NULL; gchar *name; gint order = -1; for (list = disk_list; list; list = list->next) { disk = (DiskData * ) list->data; if ( disk->device_number == device_number && disk->unit_number == unit_number ) break; disk = NULL; } if (!disk) { name = gkrellm_sys_disk_name_from_device(device_number, unit_number, &order); if (name) disk = add_disk(name, order, device_number, unit_number); } disk_assign_data(disk, rb, wb, virtual); } void gkrellm_disk_assign_data_nth(gint n, guint64 rb, guint64 wb, gboolean virtual) { DiskData *disk; gchar name[32]; if (n < n_disks) disk = (DiskData *) g_list_nth_data(disk_list, n); else { snprintf(name, sizeof(name), "%s%c", _("Disk"), 'A' + n); disk = add_disk(name, n, 0, 0); } disk_assign_data(disk, rb, wb, virtual); } void gkrellm_disk_assign_data_by_name(gchar *name, guint64 rb, guint64 wb, gboolean virtual) { GList *list; DiskData *disk = NULL; gint order = -1; for (list = disk_list; list; list = list->next) { disk = (DiskData * ) list->data; if (!strcmp(name, disk->name)) break; disk = NULL; } if (!disk) { order = gkrellm_sys_disk_order_from_name(name); disk = add_disk(name, order, 0, 0); } disk_assign_data(disk, rb, wb, virtual); } void gkrellm_disk_subdisk_assign_data_by_name(gchar *subdisk_name, gchar *disk_name, guint64 rb, guint64 wb) { GList *list; DiskData *disk = NULL; gchar *s, *endptr; gint subdisk; if (!subdisk_name || !disk_name) return; for (list = disk_list; list; list = list->next) { disk = (DiskData * ) list->data; if (!strcmp(subdisk_name, disk->name)) break; disk = NULL; } if (!disk) { /* A subdisk name is expected to be the disk_name with a number string | appended. Eg. "hda1" is a subdisk_name of disk_name "hda" */ s = subdisk_name + strlen(disk_name); if (*s == 'p') /* except mmcblkN SD disks have "pN" partition numbers */ ++s; subdisk = strtol(s, &endptr, 0); if (!*s || *endptr) return; disk = add_subdisk(subdisk_name, disk_name, subdisk); } disk_assign_data(disk, rb, wb, FALSE); } static void update_disk(GkrellmdMonitor *mon, gboolean first_update) { GList *list; DiskData *disk = NULL; gkrellm_sys_disk_read_data(); for (list = disk_list; list; list = list->next) { disk = (DiskData * ) list->data; if (disk->changed) { gkrellmd_need_serve(mon); break; } } } static void serve_disk_data(GkrellmdMonitor *mon, gboolean first_serve) { DiskData *disk; GList *list; gchar *buf = NULL; gkrellmd_set_serve_name(mon, "disk"); for (list = disk_list; list; list = list->next) { disk = (DiskData *) list->data; if (!disk->changed && !first_serve) continue; if (!disk->subdisk_parent) { if (gkrellmd_check_client_version(mon, 2, 2, 7) && disk->virtual) buf = g_strdup_printf("%s virtual %" PRIu64 " %" PRIu64 "\n", disk->name, disk->rb, disk->wb); else buf = g_strdup_printf("%s %" PRIu64 " %" PRIu64 "\n", disk->name, disk->rb, disk->wb); } else if (mon->privat->client->feature_subdisk) buf = g_strdup_printf("%s %s %" PRIu64 " %" PRIu64 "\n", disk->name, disk->subdisk_parent, disk->rb, disk->wb); else continue; gkrellmd_serve_data(mon, buf); g_free(buf); buf = NULL; } } static void serve_disk_setup(GkrellmdMonitor *mon) { GkrellmdClient *client = mon->privat->client; if (units_are_blocks) gkrellmd_send_to_client(client, "\nunits_are_blocks\n"); if (gkrellmd_check_client_version(mon, 2,1,3)) client->feature_subdisk = TRUE; } static GkrellmdMonitor disk_monitor = { "disk", update_disk, serve_disk_data, serve_disk_setup }; static GkrellmdMonitor * init_disk_monitor(void) { if (gkrellm_sys_disk_init()) return &disk_monitor; return NULL; } /* ======================================================= */ #include "../src/inet.h" typedef struct { ActiveTCP tcp; gboolean alive, new_connection; } InetData; static GList *inet_list, *inet_dead_list; static gboolean inet_unsupported, inet_new; void gkrellm_inet_log_tcp_port_data(gpointer data) { GList *list; InetData *in; ActiveTCP *tcp, *active_tcp = NULL; gchar *ap, *aap; gint slen; tcp = (ActiveTCP *) data; for (list = inet_list; list; list = list->next) { in = (InetData *) list->data; active_tcp = &in->tcp; if (tcp->family == AF_INET) { ap = (char *)&tcp->remote_addr; aap = (char *)&active_tcp->remote_addr; slen = sizeof(struct in_addr); } #if defined(INET6) else if (tcp->family == AF_INET6) { ap = (char *)&tcp->remote_addr6; aap = (char *)&active_tcp->remote_addr6; slen = sizeof(struct in6_addr); } #endif else return; if ( memcmp(aap, ap, slen) == 0 && active_tcp->remote_port == tcp->remote_port && active_tcp->local_port == tcp->local_port ) { in->alive = TRUE; /* Old alive connection still alive */ return; } } inet_new = TRUE; in = g_new0(InetData, 1); in->tcp = *tcp; in->alive = TRUE; in->new_connection = TRUE; inet_list = g_list_append(inet_list, in); } static void update_inet(GkrellmdMonitor *mon, gboolean first_update) { GList *list; InetData *in; static gint check_tcp; if (!first_update && !GK.second_tick) return; if (first_update || check_tcp == 0) { gkrellm_free_glist_and_data(&inet_dead_list); inet_new = FALSE; for (list = inet_list; list; list = list->next) { in = (InetData *) list->data; in->alive = FALSE; in->new_connection = FALSE; } gkrellm_sys_inet_read_tcp_data(); for (list = inet_list; list; ) { in = (InetData *) list->data; if (!in->alive) { if (list == inet_list) inet_list = inet_list->next; list = g_list_remove(list, in); inet_dead_list = g_list_append(inet_dead_list, in); } else list = list->next; } if (inet_new || inet_dead_list) gkrellmd_need_serve(mon); } check_tcp = (check_tcp + 1) % _GK.inet_interval; } static void serve_inet_data(GkrellmdMonitor *mon, gboolean first_serve) { InetData *in; ActiveTCP *tcp; GList *list; gchar buf[NI_MAXHOST + 128], *cp; #if defined(INET6) && defined(HAVE_GETADDRINFO) struct sockaddr_in6 sin6; char addrbuf[NI_MAXHOST]; #endif if (inet_new || first_serve) { gkrellmd_set_serve_name(mon, "inet"); for (list = inet_list; list; list = list->next) { in = (InetData *) list->data; tcp = &in->tcp; if ( tcp->family == AF_INET && (in->new_connection || first_serve) ) { cp = inet_ntoa(tcp->remote_addr); snprintf(buf, sizeof(buf), "+0 %x %s:%x\n", tcp->local_port, cp, tcp->remote_port); } #if defined(INET6) && defined(HAVE_GETADDRINFO) else if (tcp->family == AF_INET6 && (in->new_connection || first_serve)) { memset(&sin6, 0, sizeof(sin6)); memcpy(&sin6.sin6_addr, &tcp->remote_addr6, sizeof(struct in6_addr)); sin6.sin6_family = AF_INET6; #ifdef SIN6_LEN sin6.sin6_len = sizeof(struct sockaddr_in6); #endif if (getnameinfo((struct sockaddr *)&sin6, sizeof(struct sockaddr_in6), addrbuf, sizeof(addrbuf), NULL, 0, NI_NUMERICHOST|NI_WITHSCOPEID) != 0) continue; snprintf(buf, sizeof(buf), "+6 %x [%s]:%x\n", tcp->local_port, addrbuf, tcp->remote_port); } #endif else continue; gkrellmd_serve_data(mon, buf); } } if (!first_serve) { gkrellmd_set_serve_name(mon, "inet"); for (list = inet_dead_list; list; list = list->next) { in = (InetData *) list->data; tcp = &in->tcp; if (tcp->family == AF_INET) { cp = inet_ntoa(tcp->remote_addr); snprintf(buf, sizeof(buf), "-0 %x %s:%x\n", tcp->local_port, cp, tcp->remote_port); } #if defined(INET6) && defined(HAVE_GETADDRINFO) else if (tcp->family == AF_INET6) { memset(&sin6, 0, sizeof(sin6)); memcpy(&sin6.sin6_addr, &tcp->remote_addr6, sizeof(struct in6_addr)); sin6.sin6_family = AF_INET6; #ifdef SIN6_LEN sin6.sin6_len = sizeof(struct sockaddr_in6); #endif if (getnameinfo((struct sockaddr *)&sin6, sizeof(struct sockaddr_in6), addrbuf, sizeof(addrbuf), NULL, 0, NI_NUMERICHOST|NI_WITHSCOPEID) != 0) continue; snprintf(buf, sizeof(buf), "-6 %x [%s]:%x\n", tcp->local_port, addrbuf, tcp->remote_port); } #endif else continue; gkrellmd_serve_data(mon, buf); } } } static void serve_inet_setup(GkrellmdMonitor *mon) { GkrellmdClient *client = mon->privat->client; if (inet_unsupported) gkrellmd_send_to_client(client, "\ninet_unsupported\n"); } static GkrellmdMonitor inet_monitor = { "inet", update_inet, serve_inet_data, serve_inet_setup }; static GkrellmdMonitor * init_inet_monitor(void) { if (_GK.inet_interval > 0 && gkrellm_sys_inet_init()) return &inet_monitor; inet_unsupported = TRUE; return NULL; } /* ======================================================= */ #define TIMER_TYPE_NONE 0 #define TIMER_TYPE_PPP 1 #define TIMER_TYPE_IPPP 2 typedef struct { gchar *name; gboolean changed, up, up_prev, up_event, down_event; gboolean timed_changed; time_t up_time; gulong rx, tx; } NetData; static NetData *net_timer; static GList *net_list, *net_sys_list; static time_t net_timer0; static gint net_timer_type; static gboolean net_use_routed; gchar * gkrellm_net_mon_first(void) { gchar *name = NULL; net_sys_list = net_list; if (net_sys_list) { name = ((NetData *) (net_sys_list->data))->name; net_sys_list = net_sys_list->next; } return name; } gchar * gkrellm_net_mon_next(void) { gchar *name = NULL; if (net_sys_list) { name = ((NetData *) (net_sys_list->data))->name; net_sys_list = net_sys_list->next; } return name; } void gkrellm_net_use_routed(gboolean real_routed /* not applicable in server */) { net_use_routed = TRUE; } static NetData * net_new(gchar *name) { NetData *net; net = g_new0(NetData, 1); net->name = g_strdup(name); net_list = g_list_append(net_list, net); if (net_timer_type != TIMER_TYPE_NONE && !strcmp(_GK.net_timer, net->name)) net_timer = net; return net; } void gkrellm_net_assign_data(gchar *name, gulong rx, gulong tx) { GList *list; NetData *net; for (list = net_list; list; list = list->next) { net = (NetData *) list->data; if (!strcmp(net->name, name)) { if (net->rx != rx || net->tx != tx) net->changed = TRUE; else net->changed = FALSE; break; } } if (!list) net = net_new(name); if (GK.second_tick && !net_use_routed) net->up = TRUE; net->rx = rx; net->tx = tx; } void gkrellm_net_routed_event(gchar *name, gboolean routed) { GList *list; NetData *net; for (list = net_list; list; list = list->next) { net = (NetData *) list->data; if (!strcmp(net->name, name)) break; } if (!list) net = net_new(name); if (routed) net->up_event = TRUE; else net->down_event = TRUE; net->up = routed; } void gkrellm_net_add_timer_type_ppp(gchar *name) { if (!_GK.net_timer || !name) return; if (name && !strncmp(_GK.net_timer, name, strlen(name) - 1)) net_timer_type = TIMER_TYPE_PPP; } void gkrellm_net_add_timer_type_ippp(gchar *name) { if (!_GK.net_timer || !name) return; if (name && !strncmp(_GK.net_timer, name, strlen(name) - 1)) net_timer_type = TIMER_TYPE_IPPP; } void gkrellm_net_set_lock_directory(gchar *dir) { /* Not supported remotely */ } static void update_net(GkrellmdMonitor *mon, gboolean first_update) { GList *list; NetData *net; gint up_time = 0; if (GK.second_tick) { if (!net_use_routed) { for (list = net_list; list; list = list->next) { net = (NetData *) list->data; net->up_prev = net->up; net->up = FALSE; } } else gkrellm_sys_net_check_routes(); } gkrellm_sys_net_read_data(); if (GK.second_tick && !net_use_routed) { for (list = net_list; list; list = list->next) { net = (NetData *) list->data; if (net->up && !net->up_prev) net->up_event = TRUE; else if (!net->up && net->up_prev) net->down_event = TRUE; } } if (net_timer && GK.second_tick) { if (net_timer_type == TIMER_TYPE_PPP) { struct stat st; gchar buf[256]; if (net_timer->up_event) { snprintf(buf, sizeof(buf), "/var/run/%s.pid", net_timer->name); if (g_stat(buf, &st) == 0) net_timer0 = st.st_mtime; else time(&net_timer0); } if (net_timer->up) up_time = (int) (time(0) - net_timer0); } else if (net_timer_type == TIMER_TYPE_IPPP) { /* get all isdn status from its connect state because the | net_timer->up can be UP even with isdn line not connected. | Can't get time history if gkrellmd started after connects. */ static gboolean old_connected; gboolean connected; connected = gkrellm_sys_net_isdn_online(); if (connected && !old_connected) time(&net_timer0); /* New session just started */ old_connected = connected; up_time = (int) (time(0) - net_timer0); } if (up_time != net_timer->up_time) net_timer->timed_changed = TRUE; net_timer->up_time = up_time; } gkrellmd_need_serve(mon); /* serve func checks for changed */ } static void serve_net_data(GkrellmdMonitor *mon, gboolean first_serve) { NetData *net; GList *list; gchar buf[128]; gboolean fake_up_event; gkrellmd_set_serve_name(mon, "net"); for (list = net_list; list; list = list->next) { net = (NetData *) list->data; if (net->changed || first_serve) { snprintf(buf, sizeof(buf), "%s %lu %lu\n", net->name, net->rx, net->tx); gkrellmd_serve_data(mon, buf); } } /* Since the server transmits changes only, use the routed interface | to the client regardless if the sysdep code uses routed. */ if (GK.second_tick || first_serve) { gkrellmd_set_serve_name(mon, "net_routed"); for (list = net_list; list; list = list->next) { net = (NetData *) list->data; fake_up_event = (first_serve && net->up); if (net->up_event || net->down_event || fake_up_event) { snprintf(buf, sizeof(buf), "%s %d\n", net->name, fake_up_event ? TRUE : net->up_event); gkrellmd_serve_data(mon, buf); } if (mon->privat->client->last_client) net->up_event = net->down_event = FALSE; } } if (net_timer && GK.second_tick) { if (net_timer->timed_changed || first_serve) { gkrellmd_set_serve_name(mon, "net_timer"); snprintf(buf, sizeof(buf), "%s %d\n", net_timer->name, (gint)net_timer->up_time); gkrellmd_serve_data(mon, buf); } } } static void serve_net_setup(GkrellmdMonitor *mon) { GkrellmdClient *client = mon->privat->client; gchar buf[128]; /* The client <-> server link always uses routed mode, but the client | needs to know if server sysdep uses routed for config purposes. */ if (net_use_routed) gkrellmd_send_to_client(client, "\nnet_use_routed\n"); if (net_timer_type != TIMER_TYPE_NONE) { snprintf(buf, sizeof(buf), "\nnet_timer %s\n", _GK.net_timer); gkrellmd_send_to_client(client, buf); } } static GkrellmdMonitor net_monitor = { "net", update_net, serve_net_data, serve_net_setup }; static GkrellmdMonitor * init_net_monitor(void) { net_timer_type = TIMER_TYPE_NONE; if (gkrellm_sys_net_init()) return &net_monitor; return NULL; } /* ======================================================= */ struct { gboolean mem_changed; guint64 total, used, free, shared, buffers, cached; gboolean swap_changed; guint64 swap_total, swap_used; gulong swap_in, swap_out; } mem; void gkrellm_mem_assign_data(guint64 total, guint64 used, guint64 free, guint64 shared, guint64 buffers, guint64 cached) { if ( mem.total != total || mem.used != used || mem.free != free || mem.shared != shared || mem.buffers != buffers || mem.cached != cached ) { mem.total = total; mem.used = used; mem.free = free; mem.shared = shared; mem.buffers = buffers; mem.cached = cached; mem.mem_changed = TRUE; } } void gkrellm_swap_assign_data(guint64 total, guint64 used, gulong swap_in, gulong swap_out) { if ( mem.swap_total != total || mem.swap_used != used || mem.swap_in != swap_in || mem.swap_out != swap_out ) { mem.swap_total = total; mem.swap_used = used; mem.swap_in = swap_in; mem.swap_out = swap_out; mem.swap_changed = TRUE; } } static void update_mem(GkrellmdMonitor *mon, gboolean first_update) { mem.mem_changed = mem.swap_changed = FALSE; gkrellm_sys_swap_read_data(); if (first_update || GK.five_second_tick) gkrellm_sys_mem_read_data(); if (mem.mem_changed || mem.swap_changed) gkrellmd_need_serve(mon); } static void serve_mem_data(GkrellmdMonitor *mon, gboolean first_serve) { gchar buf[128]; if (mem.mem_changed || first_serve) { gkrellmd_set_serve_name(mon, "mem"); snprintf(buf, sizeof(buf), "%" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n", mem.total, mem.used, mem.free, mem.shared, mem.buffers, mem.cached); gkrellmd_serve_data(mon, buf); } if (mem.swap_changed || first_serve) { gkrellmd_set_serve_name(mon, "swap"); snprintf(buf, sizeof(buf), "%" PRIu64 " %" PRIu64 " %lu %lu\n", mem.swap_total, mem.swap_used, mem.swap_in, mem.swap_out); gkrellmd_serve_data(mon, buf); } } static GkrellmdMonitor mem_monitor = { "mem", update_mem, serve_mem_data, NULL }; static GkrellmdMonitor * init_mem_monitor(void) { if (!gkrellm_sys_mem_init()) return NULL; serveflag_done_list = g_list_append(serveflag_done_list, &mem.mem_changed); serveflag_done_list = g_list_append(serveflag_done_list,&mem.swap_changed); return &mem_monitor; } /* ======================================================= */ typedef struct { gboolean busy, deleted, is_mounted, is_nfs, changed; gchar *directory, *device, *type, *options; gint64 blocks, bavail, bfree, bsize; } Mount; static GList *mounts_list, *fstab_list; static gboolean nfs_check, fs_check, fs_need_serve, fstab_list_modified, mounts_list_modified, mounting_unsupported; static gchar *remote_fs_types[] = { "cifs", "nfs", "smbfs" }; void gkrellm_fs_setup_eject(gchar *eject_tray, gchar *close_tray, void (*eject_func)(), void (*close_func)()) { /* Not supported remotely */ } void gkrellm_fs_add_to_mounts_list(gchar *dir, gchar *dev, gchar *type) { GList *list; Mount *m; gint i; for (list = mounts_list; list; list = list->next) { m = (Mount *) list->data; if ( !strcmp(m->directory, dir) && !strcmp(m->device, dev) && !strcmp(m->type, type) ) break; } if (!list) { m = g_new0(Mount, 1); m->directory = g_strdup(dir); m->device = g_strdup(dev); m->type = g_strdup(type); mounts_list = g_list_append(mounts_list, m); mounts_list_modified = TRUE; serveflag_done_list = g_list_append(serveflag_done_list, &m->changed); for (i = 0; i < (sizeof(remote_fs_types) / sizeof(gchar *)); ++i) { if (!strcmp(m->type, remote_fs_types[i])) { m->is_nfs = TRUE; break; } } } m->is_mounted = TRUE; } void gkrellm_fs_add_to_fstab_list(gchar *dir, gchar *dev, gchar *type, gchar *opt) { Mount *m; m = g_new0(Mount, 1); m->directory = g_strdup(dir); m->device = g_strdup(dev); m->type = g_strdup(type); fstab_list = g_list_append(fstab_list, m); } void gkrellm_fs_assign_fsusage_data(gpointer pointer, gint64 blocks, gint64 bavail, gint64 bfree, gint64 bsize) { Mount *m = (Mount *) pointer; if ( m->blocks != blocks || m->bavail != bavail || m->bfree != bfree || m->bsize != bsize ) { m->blocks = blocks; m->bavail = bavail; m->bfree = bfree; m->bsize = bsize; m->changed = TRUE; } } void gkrellm_fs_mounting_unsupported(void) { mounting_unsupported = TRUE; } static void refresh_mounts_list(void) { GList *list; Mount *m; for (list = mounts_list; list; list = list->next) ((Mount *) list->data)->is_mounted = FALSE; gkrellm_sys_fs_get_mounts_list(); for (list = mounts_list; list; ) { m = (Mount *) list->data; if (!m->is_mounted) { if (list == mounts_list) mounts_list = mounts_list->next; list = g_list_remove_link(list, list); g_free(m->directory); g_free(m->device); g_free(m->type); serveflag_done_list = g_list_remove(serveflag_done_list, &m->changed); if (m->busy) m->deleted = TRUE; else g_free(m); mounts_list_modified = TRUE; } else list = list->next; } } static void refresh_fstab_list(void) { Mount *m; while (fstab_list) { m = (Mount *) fstab_list->data; g_free(m->directory); g_free(m->device); g_free(m->type); g_free(m); fstab_list = g_list_remove(fstab_list, fstab_list->data); } gkrellm_sys_fs_get_fstab_list(); fstab_list_modified = TRUE; } static gpointer get_fsusage_thread(void *data) { Mount *m = (Mount *) data; gkrellm_sys_fs_get_fsusage(m, m->directory); if (m->deleted) g_free(m); else { if (m->changed) fs_need_serve = TRUE; m->busy = FALSE; } return NULL; } static void update_fs(GkrellmdMonitor *mon, gboolean first_update) { GThread *gth; GList *list; Mount *m; static gint check_tick; if (fs_need_serve) /* Asynchronous change in fsusage thread? */ gkrellmd_need_serve(mon); fs_need_serve = FALSE; if (GK.second_tick) ++check_tick; fs_check = !(check_tick % _GK.fs_interval); if (_GK.nfs_interval > 0) nfs_check = !(check_tick % _GK.nfs_interval); else nfs_check = 0; if (!first_update && (!GK.second_tick || (!fs_check && !nfs_check))) return; refresh_mounts_list(); for (list = mounts_list; list; list = list->next) { m = (Mount *) list->data; if (fs_check && !m->is_nfs) gkrellm_sys_fs_get_fsusage(m, m->directory); else if (nfs_check && m->is_nfs && !m->busy) { m->busy = TRUE; gth = g_thread_new("get_fsusage", get_fsusage_thread, m); g_thread_unref(gth); } } if (first_update || gkrellm_sys_fs_fstab_modified()) refresh_fstab_list(); gkrellmd_need_serve(mon); } static void serve_fs_data(GkrellmdMonitor *mon, gboolean first_serve) { Mount *m; GList *list; gchar buf[128]; if (mounts_list_modified || first_serve) { gkrellmd_set_serve_name(mon, "fs_mounts"); gkrellmd_serve_data(mon, ".clear\n"); for (list = mounts_list; list; list = list->next) { m = (Mount *) list->data; snprintf(buf, sizeof(buf), "%s %s %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n", m->directory, m->device, m->type, m->blocks, m->bavail, m->bfree, m->bsize); /*gkrellm_debug(DEBUG_SERVER, "Adding mount-line for %s to serve-data\n", m->directory);*/ gkrellmd_serve_data(mon, buf); } } else { gkrellmd_set_serve_name(mon, "fs"); for (list = mounts_list; list; list = list->next) { m = (Mount *) list->data; if (!m->changed) continue; snprintf(buf, sizeof(buf), "%s %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n", m->directory, m->device, m->blocks, m->bavail, m->bfree, m->bsize); /*gkrellm_debug(DEBUG_SERVER, "Updating fs %s in serve-data\n", m->directory);*/ gkrellmd_serve_data(mon, buf); } } if (fstab_list_modified || first_serve) { gkrellmd_set_serve_name(mon, "fs_fstab"); gkrellmd_serve_data(mon, ".clear\n"); for (list = fstab_list; list; list = list->next) { m = (Mount *) list->data; snprintf(buf, sizeof(buf), "%s %s %s\n", m->directory, m->device, m->type); /*gkrellm_debug(DEBUG_SERVER, "Adding fstab-line for %s to serve-data\n", m->directory);*/ gkrellmd_serve_data(mon, buf); } } } static void serve_fs_setup(GkrellmdMonitor *mon) { GkrellmdClient *client = mon->privat->client; if (mounting_unsupported) gkrellmd_send_to_client(client, "\nmounting_unsupported\n"); } static GkrellmdMonitor fs_monitor = { "fs", update_fs, serve_fs_data, serve_fs_setup }; static GkrellmdMonitor * init_fs_monitor(void) { if (!gkrellm_sys_fs_init()) return NULL; serveflag_done_list = g_list_append(serveflag_done_list, &fstab_list_modified); serveflag_done_list = g_list_append(serveflag_done_list, &mounts_list_modified); return &fs_monitor; } /* ======================================================= */ typedef struct { gboolean changed, have_data; gint id; gboolean present, on_line, charging; gint percent; gint time_left; } Battery; static GList *battery_list; static Battery *composite_battery; static Battery * battery_nth(gint n) { Battery *bat; static gint n_batteries; if (n > 10) return NULL; if (n < 0) { if (!composite_battery) { bat = g_new0(Battery, 1); battery_list = g_list_prepend(battery_list, bat); bat->id = GKRELLM_BATTERY_COMPOSITE_ID; composite_battery = bat; serveflag_done_list = g_list_append(serveflag_done_list, &composite_battery->changed); } return composite_battery; } if (composite_battery) ++n; while ((bat = (Battery *)g_list_nth_data(battery_list, n)) == NULL) { bat = g_new0(Battery, 1); battery_list = g_list_append(battery_list, bat); bat->id = n_batteries++; serveflag_done_list = g_list_append(serveflag_done_list, &bat->changed); } return bat; } void gkrellm_battery_assign_data(gint id, gboolean present, gboolean on_line, gboolean charging, gint percent, gint time_left) { Battery *bat; bat = battery_nth(id); if (!bat) return; if ( present != bat->present || on_line != bat->on_line || charging != bat->charging || percent != bat->percent || time_left != bat->time_left ) { bat->present = present; bat->on_line = on_line; bat->charging = charging; bat->percent = percent; bat->time_left = time_left; bat->changed = TRUE; } bat->have_data = TRUE; } gint gkrellm_battery_full_cap_fallback() { return 5000; /* XXX Linux ACPI bug not handled by server */ } static void update_battery(GkrellmdMonitor *mon, gboolean first_update) { GList *list; Battery *bat; if (!first_update && !GK.five_second_tick) return; for (list = battery_list; list; list = list->next) { bat = (Battery *) list->data; bat->have_data = FALSE; bat->changed = FALSE; } gkrellm_sys_battery_read_data(); for (list = battery_list; list; list = list->next) { bat = (Battery *) list->data; if (!bat->have_data && bat->present) { bat->present = FALSE; bat->changed = TRUE; } if (bat->changed) gkrellmd_need_serve(mon); } } static void serve_battery_data(GkrellmdMonitor *mon, gboolean first_serve) { Battery *bat; GList *list; gchar buf[128]; gkrellmd_set_serve_name(mon, "battery"); for (list = battery_list; list; list = list->next) { bat = (Battery *) list->data; if ( (!bat->changed && !first_serve) || ( !gkrellmd_check_client_version(mon, 2,1,9) && bat->id > 0 ) ) continue; snprintf(buf, sizeof(buf), "%d %d %d %d %d %d\n", bat->present, bat->on_line, bat->charging, bat->percent, bat->time_left, bat->id); gkrellmd_serve_data(mon, buf); } } static void serve_battery_setup(GkrellmdMonitor *mon) { GkrellmdClient *client = mon->privat->client; gkrellm_sys_battery_read_data(); if (battery_list) gkrellmd_send_to_client(client, "\nbattery_available\n"); } static GkrellmdMonitor battery_monitor = { "battery", update_battery, serve_battery_data, serve_battery_setup }; static GkrellmdMonitor * init_battery_monitor(void) { if (!gkrellm_sys_battery_init()) return NULL; return &battery_monitor; } /* ======================================================= */ typedef struct { gboolean changed; gint type; gchar *path; /* Pathname to sensor data or device file */ gchar *id_name; /* These 4 are unique sensor identification */ gint id; /* of a particular sensor type */ gint iodev; /* One or any combination may be used. */ gint inter; gchar *vref; gchar *default_label; gint group; gfloat factor; gfloat offset; gfloat raw_value; } Sensor; static GList *sensors_list; static gboolean thread_busy, sensors_need_serve; static gpointer read_sensors(void *data) { GList *list; Sensor *sensor; gfloat tmp; gboolean need_serve = FALSE; for (list = sensors_list; list; list = list->next) { sensor = (Sensor *) list->data; tmp = sensor->raw_value; if (sensor->type == SENSOR_TEMPERATURE) gkrellm_sys_sensors_get_temperature(sensor->path, sensor->id, sensor->iodev, sensor->inter, &sensor->raw_value); else if (sensor->type == SENSOR_FAN) gkrellm_sys_sensors_get_fan(sensor->path, sensor->id, sensor->iodev, sensor->inter, &sensor->raw_value); else if (sensor->type == SENSOR_VOLTAGE) gkrellm_sys_sensors_get_voltage(sensor->path, sensor->id, sensor->iodev, sensor->inter, &sensor->raw_value); if (sensor->raw_value != tmp) { sensor->changed = TRUE; need_serve = TRUE; } else sensor->changed = FALSE; } thread_busy = FALSE; sensors_need_serve = need_serve; /* Thread, so set after data collected */ return NULL; } static void run_sensors_thread(void) { GThread *gth; if (thread_busy) return; thread_busy = TRUE; gth = g_thread_new("read_sensors", read_sensors, NULL); g_thread_unref(gth); } void gkrellm_sensors_config_migrate_connect(gboolean (*func)(), gint sysdep_version) { } void gkrellm_sensors_update_volt_order_base(void) { } void gkrellm_sensors_set_group(gpointer sr, gint group) { Sensor *sensor = (Sensor *) sr; if (sensor) sensor->group = group; } void gkrellm_sensors_sysdep_option(gchar *keyword, gchar *label, void (*func)()) { } /* A sensor within a type is uniquely identified by its id_name. | A sysdep interface may additionally use any of the triple integer | set (id, iodev, inter) for internal identification. | Monitor code here uses path to read the sensor values, but id_name is only | passed to the client since that is all that is needed for identification | (the client is no longer interfacing to sysdep code). */ gpointer gkrellm_sensors_add_sensor(gint type, gchar *sensor_path, gchar *id_name, gint id, gint iodev, gint inter, gfloat factor, gfloat offset, gchar *vref, gchar *default_label) { Sensor *sensor; if (!id_name || !*id_name || type < 0 || type > 2) return NULL; sensor = g_new0(Sensor, 1); sensor->id_name = g_strdup(id_name); if (sensor_path) sensor->path = g_strdup(sensor_path); else sensor->path = g_strdup(id_name); sensor->vref = g_strdup(vref ? vref : "NONE"); sensor->default_label = g_strdup(default_label ? default_label : "NONE"); sensor->factor = factor; sensor->offset = offset; sensor->type = type; sensor->id = id; sensor->iodev = iodev; sensor->inter = inter; sensors_list = g_list_append(sensors_list, sensor); return sensor; } static void update_sensors(GkrellmdMonitor *mon, gboolean first_update) { if (sensors_need_serve) /* Asynchronously set in thread */ gkrellmd_need_serve(mon); sensors_need_serve = FALSE; if (!GK.five_second_tick && !first_update) return; if (first_update) read_sensors(NULL); /* No thread on first read */ else run_sensors_thread(); } static void serve_sensors_data(GkrellmdMonitor *mon, gboolean first_serve) { Sensor *sr; GList *list; gchar buf[128]; gboolean sensor_disk_ok; gkrellmd_set_serve_name(mon, "sensors"); sensor_disk_ok = gkrellmd_check_client_version(mon, 2,2,0); for (list = sensors_list; list; list = list->next) { sr = (Sensor *) list->data; if (sr->group == SENSOR_GROUP_DISK && !sensor_disk_ok) continue; if (sr->changed || first_serve) { snprintf(buf, sizeof(buf), "%d \"%s\" %d %d %d %.2f\n", sr->type, sr->id_name, sr->id, sr->iodev, sr->inter, sr->raw_value); gkrellmd_serve_data(mon, buf); } } } static void serve_sensors_setup(GkrellmdMonitor *mon) { GkrellmdClient *client = mon->privat->client; GList *list; Sensor *s; gchar buf[256]; gboolean sensor_disk_ok; gkrellmd_send_to_client(client, "\n"); sensor_disk_ok = gkrellmd_check_client_version(mon, 2,2,0); for (list = sensors_list; list; list = list->next) { s = (Sensor *) list->data; if (s->group == SENSOR_GROUP_DISK && !sensor_disk_ok) continue; if (sensor_disk_ok) snprintf(buf, sizeof(buf), "%d \"%s\" %d %d %d %.4f %.4f \"%s\" \"%s\" %d\n", s->type, s->id_name, s->id, s->iodev, s->inter, s->factor, s->offset, s->vref, s->default_label, s->group); else snprintf(buf, sizeof(buf), "%d \"%s\" %d %d %d %.4f %.4f \"%s\" \"%s\"\n", s->type, s->id_name, s->id, s->iodev, s->inter, s->factor, s->offset, s->vref, s->default_label); gkrellmd_send_to_client(client, buf); } } static GkrellmdMonitor sensors_monitor = { "sensors", update_sensors, serve_sensors_data, serve_sensors_setup }; static GkrellmdMonitor * init_sensors_monitor(void) { if (!gkrellm_sys_sensors_init()) return NULL; return &sensors_monitor; } /* ======================================================= */ static time_t base_uptime, up_seconds; static glong up_minutes = -1; void gkrellm_uptime_set_base_uptime(time_t base) { base_uptime = base; } static void update_uptime(GkrellmdMonitor *mon, gboolean first_update) { glong prev_up; if (GK.ten_second_tick || up_minutes < 0 || first_update) { prev_up = up_minutes; up_seconds = gkrellm_sys_uptime_read_uptime(); if (up_seconds > 0) up_minutes = (glong) (up_seconds / 60); else up_minutes = (glong)(time(0) - _GK.start_time + base_uptime) / 60; if (up_minutes != prev_up) gkrellmd_need_serve(mon); } } static void serve_uptime_data(GkrellmdMonitor *mon, gboolean first_serve) { gchar buf[128]; gkrellmd_set_serve_name(mon, "uptime"); snprintf(buf, sizeof(buf), "%ld\n", (glong) (up_minutes >= 0 ? up_minutes : 0)); gkrellmd_serve_data(mon, buf); } static GkrellmdMonitor uptime_monitor = { "uptime", update_uptime, serve_uptime_data, NULL }; static GkrellmdMonitor * init_uptime_monitor(void) { if (!gkrellm_sys_uptime_init()) return NULL; return &uptime_monitor; } /* ======================================================= */ static void send_time(GkrellmdClient *client) { struct tm *t; gchar buf[128]; t = &gkrellmd_current_tm; snprintf(buf, sizeof(buf), "
|
__label__pos
| 0.998268 |
-module(binary_test). -compile(export_all). -define(NL_PAT, binary:compile_pattern(<<"\n">>)). -define(CM_PAT, binary:compile_pattern(<<",">>)). read_csv() -> {ok, Data} = file:read_file("med.csv"), Data. tester(F, Data, Result) -> receive {From,data,NewData} -> From ! ok, tester(F, NewData, Result); {From,gc} -> garbage_collect(), From ! ok, tester(F, Data, Result); {From,run} -> NewResult = ?MODULE:F(Data), From ! ok, tester(F, Data, NewResult); {From,shutdown} -> From ! ok end. show_memory(Msg) -> [{total,Total}, _, {processes_used,PU}, _, _, _, {binary,Bin}, _, _] = erlang:memory(), MB = 1024 * 1024, TotalMB = Total / MB, PUMB = PU / MB, BinMB = Bin / MB, io:format("*** ~s~n",[Msg]), io:format(" ~20s | ~20s | ~20s ~n",["total", "processes used", "binary"]), io:format(" ~18.2fMB | ~18.2fMB | ~18.2fMB~n~n",[TotalMB, PUMB, BinMB]). do_run(Data, TestFun) -> S = self(), io:format("==========RUNNING ~-40..=s~n",[TestFun]), show_memory("Start"), Pid = spawn_opt(?MODULE, tester, [TestFun, undefined, undefined], [{fullsweep_after, 0}]), Pid ! {S,data,Data}, wait(), show_memory("After send data"), Pid ! {S,run}, wait(), show_memory("After run"), Pid ! {S,gc}, wait(), show_memory("After GC"), Pid ! {S,shutdown}, wait(), show_memory("After shutdown"), io:format("==========DONE ~-43..=s~n~n",[TestFun]). wait() -> receive ok -> ok; _ -> uh_oh end. %% break CSV out into individual columns %% e.g. %% %% [[<<"col1">>,<<"col2">>,<<"col3">>], %% [<<"val1">>,<<"val2">>,<<"val3">>]] list_of_cols(Data) -> NL = ?NL_PAT, CM = ?CM_PAT, list_of_cols(Data, [], {NL, CM}). list_of_cols(<<>>, Acc, _) -> lists:reverse(Acc); list_of_cols(Data, Acc, {NL, CM}) -> [Line,Rest] = binary:split(Data, NL), Cols = binary:split(Line, CM, [global]), list_of_cols(Rest, [Cols|Acc], {NL, CM}). list_of_lines(Data) -> NL = ?NL_PAT, list_of_lines(Data, [], NL). list_of_lines(<<>>, Acc, _) -> lists:reverse(Acc); list_of_lines(Data, Acc, NL) -> [Line,Rest] = binary:split(Data, NL), list_of_lines(Rest, [Line|Acc], NL). list_of_byte_size(Data, Size) -> list_of_byte_size(Data, Size, []). list_of_byte_size(<<>>, _, Acc) -> lists:reverse(Acc); list_of_byte_size(Data, Size, Acc) when size(Data) >= Size -> <> = Data, list_of_byte_size(Rest, Size, [Bytes|Acc]); list_of_byte_size(<>, _, Acc) -> lists:reverse([LastChunk|Acc]). list_of_32byte(Data) -> list_of_byte_size(Data, 32). list_of_64byte(Data) -> list_of_byte_size(Data, 64). list_of_128byte(Data) -> list_of_byte_size(Data, 128). list_of_256byte(Data) -> list_of_byte_size(Data, 256). list_of_512byte(Data) -> list_of_byte_size(Data, 512). run_tests() -> Data = read_csv(), show_memory("After read"), do_run(Data, list_of_cols), do_run(Data, list_of_lines), do_run(Data, list_of_32byte), do_run(Data, list_of_64byte), do_run(Data, list_of_128byte), do_run(Data, list_of_256byte), do_run(Data, list_of_512byte).
|
__label__pos
| 0.991 |
Respostas
2013-11-27T12:08:35-02:00
1/2 - 1/3 + 5/6 - 3/4 =
mmc de (2, 3, 6 e 4)
2, 3, 6, 4|2
1, 3, 3, 2|2
1, 3, 3, 1|3
1, 1, 1 ,1 / mmc = 2x2x3 --> mmc = 12
(12:2.1)/12 - (12:3.1)/12 + (12:6.5)/12 - (12:4.3)/12 =
6/12 - 4/12 + 10/12 - 9/12 = (6-4+10-9)/12 = 3/12 = 3:3/12:3 = 1/4
3 4 3
2013-11-27T12:21:47-02:00
1 - 1 + 5 - 3 =
2 3 6 4
mmc
2, 3, 4, 6 | 2
2, 3, 2, 3 | 2
1, 3, 1, 3 | 3
1, 1, 1, 1 / 2² x 3 = 12
6 - 4 + 10 - 9 =
12
3 ---> simplificada: 1
12 4
Resposta:
1
4
4 4 4
|
__label__pos
| 0.936118 |
MDL-32895: Improvements to assignment upgrade tool for large numbers of assignments.
[moodle.git] / admin / tool / assignmentupgrade / locallib.php
CommitLineData
bbd0e548
DW
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Assignment upgrade tool library functions
19 *
20 * @package tool_assignmentupgrade
21 * @copyright 2012 NetSpot
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25defined('MOODLE_INTERNAL') || die();
26
27/**
28 * Get the URL of a script within this plugin.
29 * @param string $script the script name, without .php. E.g. 'index'
30 * @param array $params URL parameters (optional)
31 * @return moodle_url
32 */
33function tool_assignmentupgrade_url($script, $params = array()) {
34 return new moodle_url('/admin/tool/assignmentupgrade/' . $script . '.php', $params);
35}
36
37/**
38 * Class to encapsulate the continue / cancel for batch operations
39 *
40 * @package tool_assignmentupgrade
41 * @copyright 2012 NetSpot
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 */
44class tool_assignmentupgrade_batchoperationconfirm implements renderable {
45 /** @var string $continuemessage The message to show above the continue cancel buttons */
46 public $continuemessage = '';
47 /** @var string $continueurl The url to load if the user clicks continue */
48 public $continueurl;
49
50 /**
51 * Constructor for this class
52 * @param stdClass $data - The data from the previous batch form
53 */
54 function __construct($data) {
55 if (isset($data->upgradeselected)) {
56 $this->continuemessage = get_string('upgradeselectedcount', 'tool_assignmentupgrade', count(explode(',', $data->selectedassignments)));
57 $this->continueurl = new moodle_url('/admin/tool/assignmentupgrade/batchupgrade.php', array('upgradeselected'=>'1', 'confirm'=>'1', 'sesskey'=>sesskey(), 'selected'=>$data->selectedassignments));
58 } else if (isset($data->upgradeall)) {
59 if (!tool_assignmentupgrade_any_upgradable_assignments()) {
60 $this->continuemessage = get_string('noassignmentstoupgrade', 'tool_assignmentupgrade');
61 $this->continueurl = '';
62 } else {
63 $this->continuemessage = get_string('upgradeallconfirm', 'tool_assignmentupgrade');
64 $this->continueurl = new moodle_url('/admin/tool/assignmentupgrade/batchupgrade.php', array('upgradeall'=>'1', 'confirm'=>'1', 'sesskey'=>sesskey()));
65 }
66 }
67 }
68}
69
70
71/**
72 * Class to encapsulate one of the functionalities that this plugin offers.
73 *
74 * @package tool_assignmentupgrade
75 * @copyright 2012 NetSpot
76 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
77 */
78class tool_assignmentupgrade_action {
79 /** @var string the name of this action. */
80 public $name;
81 /** @var moodle_url the URL to launch this action. */
82 public $url;
83 /** @var string a description of this aciton. */
84 public $description;
85
86 /**
87 * Constructor to set the fields.
88 *
89 * In order to create a new tool_assignmentupgrade_action instance you must use the tool_assignmentupgrade_action::make
90 * method.
91 *
92 * @param string $name the name of this action.
93 * @param moodle_url $url the URL to launch this action.
94 * @param string $description a description of this aciton.
95 */
96 protected function __construct($name, moodle_url $url, $description) {
97 $this->name = $name;
98 $this->url = $url;
99 $this->description = $description;
100 }
101
102 /**
103 * Make an action with standard values.
104 * @param string $shortname internal name of the action. Used to get strings and build a URL.
105 * @param array $params any URL params required.
106 * @return tool_assignmentupgrade_action
107 */
108 public static function make($shortname, $params = array()) {
109 return new self(
110 get_string($shortname, 'tool_assignmentupgrade'),
111 tool_assignmentupgrade_url($shortname, $params),
112 get_string($shortname . '_desc', 'tool_assignmentupgrade'));
113 }
114}
115
116/**
117 * Determine if there are any assignments that can be upgraded
118 * @return boolean - Are there any assignments that can be upgraded
119 */
120function tool_assignmentupgrade_any_upgradable_assignments() {
121 global $DB, $CFG;
122 require_once($CFG->dirroot . '/mod/assign/locallib.php');
123 // first find all the unique assignment types
124 $types = $DB->get_records_sql('SELECT plugin AS assignmenttype, value AS version FROM {config_plugins} WHERE name = ? AND plugin LIKE ?', array('version', 'assignment_%'));
125
126 $upgradabletypes = array();
127
128 foreach ($types as $assignment) {
129 $shorttype = substr($assignment->assignmenttype, strlen('assignment_'));
130 if (assign::can_upgrade_assignment($shorttype, $assignment->version)) {
131 $upgradabletypes[] = $shorttype;
132 }
133 }
5d81b754 134 list($sql, $params) = $DB->get_in_or_equal($upgradabletypes);
bbd0e548 135
5d81b754 136 $count = $DB->count_records_sql('SELECT COUNT(id) from {assignment} where assignmenttype ' . $sql, $params);
bbd0e548 137
5d81b754 138 return $count > 0;
bbd0e548
DW
139}
140
141/**
142 * Load a list of all the assignmentids that can be upgraded
143 * @return array of assignment ids
144 */
145function tool_assignmentupgrade_load_all_upgradable_assignmentids() {
146 global $DB, $CFG;
147 require_once($CFG->dirroot . '/mod/assign/locallib.php');
148 // first find all the unique assignment types
149 $types = $DB->get_records_sql('SELECT plugin AS assignmenttype, value AS version FROM {config_plugins} WHERE name = ? AND plugin LIKE ?', array('version', 'assignment_%'));
150
151 $upgradabletypes = array();
152
153 foreach ($types as $assignment) {
154 $shorttype = substr($assignment->assignmenttype, strlen('assignment_'));
155 if (assign::can_upgrade_assignment($shorttype, $assignment->version)) {
156 $upgradabletypes[] = $shorttype;
157 }
158 }
bbd0e548 159
5d81b754
DW
160 list($sql, $params) = $DB->get_in_or_equal($upgradabletypes);
161
162 $records = $DB->get_records_sql('SELECT id from {assignment} where assignmenttype ' . $sql, $params);
bbd0e548
DW
163 $ids = array();
164 foreach ($records as $record) {
165 $ids[] = $record->id;
166 }
167
168 return $ids;
169}
170
171
172/**
5b121144
DW
173 * Upgrade a single assignment. This is used by both upgrade single and upgrade batch
174 *
175 * @param int $assignmentid - The assignment id to upgrade
176 * @return array(string, boolean, string) -
177 * The array contains
178 * - the assignment summary (returned by tool_assignmentupgrade_get_assignment)
179 * - success
180 * - the upgrade log
bbd0e548 181 */
5b121144 182function tool_assignmentupgrade_upgrade_assignment($assignmentid) {
bbd0e548 183 global $CFG;
bbd0e548 184 require_once($CFG->dirroot . '/mod/assign/upgradelib.php');
bbd0e548
DW
185
186 $assignment_upgrader = new assign_upgrade_manager();
5b121144
DW
187 $info = tool_assignmentupgrade_get_assignment($assignmentid);
188 if ($info) {
189 $log = '';
190 $success = $assignment_upgrader->upgrade_assignment($assignmentid, $log);
191 } else {
192 $success = false;
193 $log = get_string('assignmentnotfound', 'tool_assignmentupgrade', $assignmentid);
194 $info = new stdClass();
195 $info->name = get_string('unknown', 'tool_assignmentupgrade');
196 $info->shortname = get_string('unknown', 'tool_assignmentupgrade');
bbd0e548 197 }
bbd0e548 198
5b121144 199 return array($info, $success, $log);
bbd0e548
DW
200}
201
202/**
203 * Get the information about a assignment to be upgraded.
204 * @param int $assignmentid the assignment id.
205 * @return stdClass the information about that assignment.
206 */
207function tool_assignmentupgrade_get_assignment($assignmentid) {
208 global $DB;
209 return $DB->get_record_sql("
210 SELECT a.id, a.name, c.shortname, c.id AS courseid
211 FROM {assignment} a
212 JOIN {course} c ON c.id = a.course
213 WHERE a.id = ?", array($assignmentid));
214}
215
|
__label__pos
| 0.981507 |
mongoose 与 koa 如何比较好的结合
发布于 8 年前 作者 demohi 18303 次浏览 最后一次编辑是 5 年前
###没发现类似co-mongoose的项目,为每一个操作进行thunkify,感觉很麻烦
请问有没有mongoose与koa 结合的示范代码
13 回复
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Promise = mongoose.Promise;
var UserSchema = new Schema({
name: {
type: String,
required: true
}
});
UserSchema.methods.add = function() {
var self = this,
p = new Promise();
self.save(function(error, data) {
if (error) {
p.reject(error);
} else {
p.resolve(null, data);
}
});
return p;
};
mongoose.model('User', UserSchema);
/*
* POST
* create user
*/
var parse = require('co-body'),
mongoose = require('mongoose'),
User = mongoose.model('User');
app.post('/users', function * () {
var body = yield parse(this),
user = new User(body);
yield user.add();
this.body = {
message: 'success',
id: user.id
};
});
就是弄成promise,如果查询,直接exec()就行。
var user = yield User.findById(id).exec();
感谢@coderhaoxin 的回复
同时也找到另外一种方法
undoZen/yieldwiki
因为koa支持yield一个promise,所以可以考虑用mongoose-q
我试试
mongoose-q 是比较好的选择
如今发布问题已经八个月过去了,现在有没有新的解决方法?
原先用express或者其他框架的代码不需要改动,只要多封装一层处理逻辑就好。例: <code> //model.js var Post = require(’…/…/db/models/post’);
module.exports = {
fetch: function * () {
var fetch = thunkify(Post.fetch, Post);
var postList = yield fetch();
return postList;
}
} </code>
大部分的功能在后面加个.exec()即可,mongoose是支持promise的 例如:
var user=yield userModel.findByIdAndUpdate(userBody._id, userBody).exec();
那天看到一个支持yield的mongoose库,忘了记下来,现在找不到了。
回到顶部
|
__label__pos
| 0.998021 |
Sunday, May 23, 2010
Writing a Perl 6 URI module
I wanted to write a parser of some sort using Perl 6's spiffy parser language otherwise known as "rules". This is the super-extended regular expression syntax that Perl 6's own parser is written in, and it's not just powerful, it's easy to use. In fact, it's so easy to use that almost all of my time writing a URI parser module was spent on other aspects of the code than the parser itself.
First off, some background. Perl 6 has a URI module already. However, it relies on a number of Perl built-in character classes to match things like digits and alphanumerics. In reality, the RFCs that define URIs are very precise, and there are different specifications depending on what you need. So, I decided to re-write the module with a pluggable parser so that you could give a regular, modern URI and have it parse correctly, but you could also ask for special "IRI" parsing on an internationalized URI and the right thing would happen there. I even went so far as to bring in an older version of the specification as a legacy mode.
The current state of the Perl 6 parser and runtime called Rakudo is actually fairly solid for a pre-release implementation of such a complex language spec. There are some gaping holes, but they were all relatively easy to work around. Some of these included overly aggressive list-flattening, some operators that were broken at the time I wrote this code and the big one: named rules only work as a stand-alone grammer with a specific entry-point called TOP.
I worked around all of these issues and have, so far, been able to parse basic URIs according to RFC 3986. Here's a sample of what a Perl grammar for URIs looks like:
token URI {
':' [ '?' ]? [ '#' ]?
}
Here you can see most of the basics: "token" introduces a single expression within the grammar. It calls out to other tokens by enclosing their names in angle-brackets. Literal sequences are enclosed in single-quotes and sub-expressions can be enclosed in square-brackets with regular expression-like repetition counts such as ? for 0 or 1 matches.
In order to have a pluggable interface, I needed a class capable of providing me with two things for each grammar: the grammar itself and a set of routines which would tell me how to find the resulting URI elements in the match data. For this I defined an interface using Perl 6's roles:
role URI::Specification {
method parser() { ... }
method scheme_path() { ... }
# ... other _path methods here...
}
Those ellipses are literal. They cause the methods to be required for any class composed with this role, but do not define any functionality themselves.
Each parser is then defined as:
class URI::rfc3896 does URI::Specification {
grammar URI::rfc3896::spec {
token TOP { }
# RFC definition of URI goes here.
}
method parser() { return ::URI::rfc3896::spec }
method scheme_path() {
gather do { take }
}
# And so on ...
}
That's it. The only really funky bit here is the gather/take code in the scheme_path. That's the way Perl 6 defines a coroutine-like interface. The paths define how we traverse the match object to find match results. So, for example, the "scheme" (the "http" in "http:/www.example.com/") can only be matched in the URI rule's scheme sub-rule. Some URI elements, however, such as authority (the host name and port - possibly username as well) can be matched multiple ways, so these routines might return multiple lists of subrule names to traverse. I would have simply returned a list of lists, but Perl 6's parameter passing is very complex and currently some of the specification is not yet implemented. Right now, this manifests as overly aggressive list flattening when returning them from a subroutine or method.
This is why I used coroutines to return each of the sub-lists, one call at a time.
I'll continue to post new updates as my URI module nears readiness. For now, it's just awaiting some love on the other parsers, and I think it'll be ready to go.
|
__label__pos
| 0.842418 |
Module: ChefSpec::API::RubyBlockMatchers
Defined in:
lib/chefspec/api/ruby_block.rb
Overview
Since:
• 0.5.0
Instance Method Summary collapse
Instance Method Details
#run_ruby_block(resource_name) ⇒ ChefSpec::Matchers::ResourceMatcher
Assert that a ruby_block resource exists in the Chef run with the action :run. Given a Chef Recipe that runs “do_something” as a ruby_block:
ruby_block 'do_something' do
block do
# ...
end
action :run
end
The Examples section demonstrates the different ways to test a ruby_block resource with ChefSpec.
Examples:
Assert that a ruby_block was run
expect(chef_run).to run_ruby_block('do_something')
Assert that a ruby_block was not run
expect(chef_run).to_not run_ruby_block('do_something')
Parameters:
• resource_name (String, Regex)
the name of the resource to match
Returns:
Since:
• 0.5.0
33
34
35
# File 'lib/chefspec/api/ruby_block.rb', line 33
def run_ruby_block(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:ruby_block, :run, resource_name)
end
|
__label__pos
| 0.974996 |
Conditional Boolean property
Hello folks,
Is there a way to work with Conditional properties for layers using Boolean?
For example:
If Layer A is True, Layer B can’t be True; if Layer B is True, that means that Layer A is False;
*Imagine any component containing many Boolean options, but they can’t all be true simultaneously; How to achieve this?
Right now, I have a component like this, but the user can make it all True when creating an instance, and I don’t want that.
If not, this is my idea - Conditional Boolean Properties
Thanks
Joao
2 Likes
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
|
__label__pos
| 0.999894 |
Yeelight login loop
Hi there,
I recently bought a Yeelight Smart RGB Led, and it says I need the Yeelight App to configure it.
I installed the app on my phone, did the registration, it gets to the “Select Server” screen, and no matter what I do, it asks me to login again.
This always ends up in a loop - Login -> Select Server -> Login -> Select Server.
Can anybody tell me how to login this app to configure this Led? Or should I return it and stay away from Yeelight products?
1 Like
Is there anything prompt of toast? Or can you go into page of login?
Not sure what you mean by “Prompt of toast”.
As I said, gets to login -> select server -> login -> select server…on and on and on
Same problem here…
Hi, what’s your xiaomi account?
I managed to solve it by stopping the app and cleaning the cache. When I started it again it was already logged in.
I have the exact same problem. I suspect it has something to do with the MI Home app installed. Have you managed to solve it?
|
__label__pos
| 0.992906 |
Riccardo "Jack" Lucchetti 1.0 2017-04-02 Basic statistics about gaps in panel datasets C23 C33 MAINWIN/Sample The paneldesc function was inspired by Stata's xtdescribe command, but it's slightly different. It is used to check for gaps in a panel datasets. Unlike Stata's xtdescribe, however, its action can be restricted to a list of variables, which can be useful if you want to check for data availability only for a subset of your variables. The syntax is: pat_series = paneldesc(X, limit) both arguments are optional. X: a list (possibly null, which is the default). Check for gaps in any of the variables contained in the list. If null, instead, the logic is reversed and an observation is deemed "gappy" if at least one variable in the dataset is missing for that observation. limit, a positive scalar. Controls how many patterns to print out (see below; default = 10). The function returns a series in which pattern of missing/valid observations is uniquely coded with a binary technique: for each unit in the sample, the returned series has one non-missing observation, at the first non-missing entry, coded as (in LaTeX notation) y_i = \sum_{t=1}^T 2^{t-1} I_{it} where I_{it} is 0 if the corresponding observation is missing, and 1 otherwise. For example, take a dataset with T=5; a unit that has observations at t=2 3 and 5 and a missing observation at t=3 and t=3 would have y_i = 0 + 2 + 4 + 0 + 16 = 22, so that paneldesc(x) would return a series y as in: t x y ----------- 1 2 5 22 3 3 4 5 -1 scalar nolist = nelem(X) == 0 if nolist series o = 0 smpl --no-missing o = 1 smpl full else series o = ok(X) endif series tt = time-1 series ot = o ? tt : NA series z = ot == pmin(ot) # z==1 -> first valid obs series x = z ? psum(2^tt * o) : NA # binary code # print o tt z x -o discrete x matrix a = aggregate(null, x) a = -msortby(-a, 2) scalar m = ceil(log2(maxc(a[,1]))) u = umat(a, m) if rows(u) == 1 printf "Panel is balanced\n" else printf "\nDistribution of T_i:" s = quantiles(z ? psum(o) : NA) limit = xmin(limit+1, rows(u)) printumat(u, sumc(a[,2]), limit) endif descstr = "Panel gap pattern" setinfo x --description="@descstr" --discrete return x # this function turns each pattern into its binary # representation matrix id = a[, 1] matrix wrk = id matrix ret = zeros(rows(a), m) loop i=1..m --quiet matrix uno = wrk % 2 matrix wrk = (wrk - uno) / 2 matrix ret[,i] = uno endloop return a[,2] ~ ret # take the binary pattern matrix and turn it into a ".1" string r = rows(a) c = cols(a) string filler = "" loop i=1..c --quiet filler ~= "-" endloop b = strsub(sprintf("%1.0f", a[1:limit,2:]), "0", ".") string l = "" scalar c = 0 printf " Freq. Percent Cum. | Pattern\n" printf " ---------------------------+-%s\n", filler loop i=1..limit-1 --quiet getline(b, l) scalar n = a[i,1] f = 100 * n/N c += f printf "%8d%11.2f%8.2f | %s\n", n, f, c, l endloop if r == limit n = a[r,1] getline(b, l) l = " " ~ l else n = sumc(a[limit:,1]) l = "(other patterns)" endif f = 100 * n/N c += f printf "%8d%11.2f%8.2f | %s\n", n, f, c, l printf " ---------------------------+-%s\n", filler matrix a = {o} scalar N = rows(a) a = msortby(a, 1) matrix q = 1 ~ ceil(N*{0.05, 0.25, 0.5, 0.75, 0.95, 1}) a = a[q] l1 = " min 5% 25% 50% 75% 95% max" l2 = sprintf("%18s%8d\n", "", a') ret = sprintf("%s\n%s", l1, l2) print ret return ret include paneldesc.gfn open abdata.gdt list X = n w series pt = paneldesc(X, 10) discrete pt freq pt
|
__label__pos
| 0.983709 |
Skip to main content
Version: Next
Interacting with a HOPR node
Once you have your HOPR cluster up and running, you are ready to connect to a single HOPR node and listen to messages sent to it by other HOPR nodes. The following guide will show you how to connect to a running HOPR node, and verify some basic functionality using both the REST and WebSocket endpoints.
Requirements
1. Get the node security credentials
To avoid unsecured access to your HOPR node, all HOPR node's WebSocket and REST calls require an apiToken. Your API token needs to be appended as a query parameter for WebSocket connections and as an encoded token via the Authorization header for you to be able to connect to it. You will not be able to connect to your HOPR node without its apiToken.
Tip
The flag used to set this value in a HOPR node via hoprd is --apiToken. The default apiToken used across our documentation is the following one, so make sure to change it when running your own node in a public network.
^^LOCAL-testing-123^^
Make sure to export your apiToken to be used in the incoming commands, and every time you open a new terminal.
export apiToken="^^LOCAL-testing-123^^"
2. Export your HOPR node REST/WebSocket endpoints
If you followed the guide in the "HOPR Cluster Development Setup" section, these will be already exported in your current terminal. Otherwise, you can run the following commands to ensure at least your first node's endpoints are exported.
As an alternative, you an also run a single HOPR node following our monorepo instructions.
Export REST and WebSocket endpoints (from local HOPR cluster)
Node 1
export HOPR_NODE_1_HTTP_URL=http://127.0.0.1:13301 HOPR_NODE_1_WS_URL=ws://127.0.0.1:19501
API token & Node 1
export apiToken=^^LOCAL-testing-123^^ HOPR_NODE_1_HTTP_URL=http://127.0.0.1:13301 HOPR_NODE_1_WS_URL=ws://127.0.0.1:19501
Export REST and WebSocket endpoints (from a single localhost HOPR node)
Node 1
export HOPR_NODE_1_HTTP_URL=http://127.0.0.1:3001 HOPR_NODE_1_WS_URL=ws://127.0.0.1:3000
API token & Node 1
export apiToken=^^LOCAL-testing-123^^ HOPR_NODE_1_HTTP_URL=http://127.0.0.1:3001 HOPR_NODE_1_WS_URL=ws://127.0.0.1:3000
We use 127.0.0.1 instead of localhost as some tools like websocat (described below) struggle to resolve localhost properly.
3. Install a WebSocket and REST client
To properly1 interact with a HOPR node, you'll need both REST and WebSocket client software. A REST client is used to give instructions to your HOPR node via its REST API, and the WebSocket client is to listen to these interactions, usually given by other nodes.
We recommend using curl and websocat to interact with both endpoints. These tools are terminal only and supported by any Unix-based OS. If you would like to use a UI-based alternative, please check the Additional REST/WebSocket clients section. For the purposes of this guide, curl and websocat will be assumed.
Installing curl
Most Unix-based systems already have curl installed, but if you don't have it you can always use the default package manager to do so. For instance, here’s how you install `curl` in Ubuntu:
sudo apt-get install curl
You can see if curl is installed in your system by running which curl or simply running curl, which will output a message like the following:
curl: try 'curl --help' or 'curl --manual' for more information
Installing websocat
Our suggested client is websocat, which you can install by running our./install-websocat.sh script from our monorepo. To install, make sure to run it from the scripts folder, as by default it will install it in the parent folder under a .bin folder, and will not export it to your $PATH.
Go to the scripts folder within the monorepo
cd scripts
Install script
./install-websocat.sh
You can see if websocat has been installed by running .bin/websocat.
Connect to a HOPR node
1. Test REST API connectivity
Accessing our HOPR node REST API documentation
Your HOPR node comes with Swagger UI documentation showcasing all the exposed API methods available to your node, and the expected parameters and format to use them.
You can access the UI by visiting HOPR_NODE_1_HTTP_URL/api/v2/_swagger/# in your browser.
You can also click here to open 127.0.0.1:3001 for an individual node or 127.0.0.1:13301 for the first node in a HOPR cluster.
If your node is running properly, you should see an image similar to this one:
HOPR network
Testing the REST API with curl
Using your node's apiToken and your HOPR_NODE_1_HTTP_URL from the "Running a local HOPR Cluster" section (likely 127.0.0.1:3001 or 127.0.0.1:13301), try to send a REST command to query its address with the following curl command. If you don’t have jq installed, just remove it from the end of the command.
echo -n $apiToken | base64 | xargs -I {} curl -s -H "Authorization: Basic {}" $HOPR_NODE_1_HTTP_URL/api/v2/account/address | jq
If successful, you should get a response similar to this one:
{
"nativeAddress": "0x3a54dDE3ee5ACfd43C902cbecC8ED0CBA10Ff326",
"hoprAddress": "16Uiu2HAmE9b3TSHeF25uJS1Ecf2Js3TutnaSnipdV9otEpxbRN8Q"
}
If you've made a mistake, for example forgotting to use -n in your echo or using the wrong apiToken, you’ll see the following instead:
{
"status": 403,
"challenge": "Basic realm=hoprd",
"message": "You must authenticate to access hoprd."
}
2. Test WebSocket connectivity
Unlike our REST API endpoint, seeing interactions with your HOPR node WebSocket server requires a WebSocket client that will remain open to listen to all messages sent to our HOPR node.
Connecting to your HOPR node WebSocket server
With websocat installed, please go up one directory: cd .. and run the following command to connect to your HOPR node WebSocket server.
.bin/websocat "$(echo "$HOPR_NODE_1_WS_URL" | sed "s/http/ws/")/?apiToken=$apiToken"
Note
Please note that you need to use your HOPR_NODE_1_WS_URL (likely 127.0.0.1:3000 or 127.0.0.1:19501) instead of the HOPR_NODE_1_HTTP_URL from the previous step. Your HOPR_NODE_1_WS_URL is also referred as Admin URL in our tools.
If everything worked correctly, you should see a dump of messages, the last one being:
{ "type": "log", "msg": "ws client connected [ authentication ENABLED ]", "ts": "2022-02-01T19:42:34.152Z" }
Now that you are connected, try typing balance in the same terminal, which should output as follows:
{"type":"log","msg":"admin > balance\n","ts":"2022-02-01T19:42:35.417Z"}
{"type":"log","msg":"HOPR Balance: 9.6 txHOPR\nETH Balance: 0.99871794476851171 xDAI","ts":"2022-02-01T19:42:35.421Z"}
With the connection verified to both our REST and WebSocket endpoints, we can now go ahead and go through the basic functions of the API to send messages across nodes.
Additional REST/WebSocket clients
In addition to curl and websocat, the following clients can also help you connect to your HOPR node fully. Be aware that you will still need to know your apiToken.
WebSocket clients
• Piesocket WebSocket Tester: This is a great tool to debug both listening to and sending messages from/to your HOPR node. Make sure to paste your HOPR_NODE_1_WS_URL and append your apiToken as a query parameter. Also, you'll need to change the http protocol to ws. For instance, here's how this would look in a Gitpod.io instance. After it's connected, you can type balance to see your node response.
ws://127.0.0.1:19501/?apiToken=^^LOCAL-testing-123^^
If you are using a Gitpod public URL, you can simply use the output of gp url for that particular port (19501) and paste it in the website.
gp url 19501
The output should look something like this: wss://19501-hoprnet-mynechat-7x6h2ghc17f.ws-us30.gitpod.io/?apiToken=^^LOCAL-testing-123^^.
REST client
• ReqBin: Using their Custom header option, you can send the proper Authorization request so you can test your HOPR node endpoint. For testing, we suggest using HOPR_NODE_1_HTTP_URL and the api/v2/account/address endpoint. Make sure to use the base64 encoded version of your apiToken and add the prefix Basic .
Tip
For the standard apiToken ^^LOCAL-testing-123^^, the base64 encoded value is Xl5MT0NBTC10ZXN0aW5nLTEyM15e. To use ReqBin with a Gitpod exposed URL (e.g. https://13302-hoprnet-mynechat-7x6h2ghc17f.ws-us30.gitpod.io/api/v2/account/addresses), you can use gp url. For a different apiToken value, you can use the btoa function of your browser developer tools to figure it out.
Gitpod command (paste output in the URL section of reqbin)
gp url 13302
Custom Header
Basic Xl5MT0NBTC10ZXN0aW5nLTEyM15e
1. Although you can successfully interact with a HOPR node only using a WebSocket client, it is recommended to always use the REST API to send commands to the HOPR node. This is because the API is optimized for applications, whereas the WebSocket commands are mostly used within the hopr-admin UI, an operator-targeted tooling used to verify the functionality of the node. In other words, only use the WebSocket server when you need to process information sent to a node, and use the REST API when you need to write actions to a node.
|
__label__pos
| 0.50672 |
Back to home page
Project CMSSW displayed by LXR
File indexing completed on 2023-10-25 09:45:40
0001 #include "EventFilter/L1TRawToDigi/interface/OmtfDtUnpacker.h"
0002
0003 #include "FWCore/MessageLogger/interface/MessageLogger.h"
0004
0005 #include "EventFilter/L1TRawToDigi/interface/OmtfDtDataWord64.h"
0006
0007 namespace omtf {
0008
0009 void DtUnpacker::unpack(unsigned int fed,
0010 unsigned int amc,
0011 const DtDataWord64 &data,
0012 std::vector<L1MuDTChambPhDigi> &phi_Container,
0013 std::vector<L1MuDTChambThDigi> &the_Container) {
0014 LogTrace("") << "HERE OMTF->DT " << std::endl;
0015 LogTrace("") << data << std::endl;
0016 if (data.sector() == 0) {
0017 LogTrace("") << "...data skipped, since from oberlaping chambers." << std::endl;
0018 return; // skip signal from chamber fiber exchange
0019 }
0020 int bx = data.bxNum() - 3;
0021 int whNum = (fed == 1380) ? -2 : 2;
0022 int sector = (amc - 1) * 2 + data.sector();
0023 if (sector == 12)
0024 sector = 0;
0025 int station = data.station() + 1;
0026 LogTrace("") << "DT_AMC# " << amc << " RAW_SECTOR: " << data.sector() << " DT_SECTOR: " << sector << std::endl;
0027 phi_Container.push_back(L1MuDTChambPhDigi(bx,
0028 whNum,
0029 sector,
0030 station,
0031 data.phi(),
0032 data.phiB(),
0033 data.quality(),
0034 data.fiber(), // utag/Ts2Tag
0035 data.bcnt_st())); //ucnt/BxCnt
0036 int pos[7];
0037 int posQual[7];
0038 for (unsigned int i = 0; i < 7; i++) {
0039 pos[i] = (data.eta() >> i & 1);
0040 posQual[i] = (data.etaQuality() >> i & 1);
0041 }
0042 if (data.eta())
0043 LogTrace("") << "HERE DATA DT ETA";
0044 if (data.eta())
0045 the_Container.push_back(L1MuDTChambThDigi(bx, whNum, sector, station, pos, posQual));
0046 }
0047
0048 } // namespace omtf
|
__label__pos
| 0.798124 |
Shopstory
Search
K
Comment on page
Overview
Learn about Shopstory core concepts, features and architecture.
What is Shopstory?
Shopstory is a visual (or no-code) page builder. It allows non-technical folks (designers, marketers, etc) to build new pages or sections in websites without involvement of developers. So it's kind of like Squarespace or Wix, but:
1. 1.
It's for websites with custom front-end, using modern framework like next.js, Gatsby, Remix, etc.
2. 2.
It works inside of modern CMSes, like Sanity or Contentful, where you probably already manage content. We extend CMSes with a new field type (a visual content field) that can be added anywhere within your content model. You can think of Shopstory as super-advanced rich text field. Shopstory uses CMS native media pickers and localisation strategy.
3. 3.
It's focused only on "content blocks" (hero banners, product grids, blog articles, popups etc) - the stuff that marketing team wants to modify most often. You can't build menu or checkout with Shopstory - we believe that these complex components should be built and maintained by developers.
4. 4.
It's built around simplicity and constraints to make sure that editors don't accidentally break the website or use wrong design tokens (fonts, colors, buttons, etc).
Shopstory is ultra-compatible with custom-code
With Shopstory developers are still in a driver's seat. Our goal is to add visual building capabilities without compromising any advantages of custom front-end architecture:
1. 1.
It's developers who decide where content built visually can be rendered (for example in landing page). The rest is handled as usual with code (checkout, menu, collection filtering, account etc).
2. 2.
It's fast and low-footprint. We know how important Web Vitals are.
3. 3.
It can be easily constrained with your design system. Fonts, colors, spacings, icons or even page containers and image aspect ratios are defined in code. Editors can only pick from a predefined set of values so they can never go "off-brand".
4. 4.
You can use your custom components in Shopstory (think of custom buttons, product cards or already coded sections). It is an extremely powerful feature because sometimes components are too complex for marketers and should be built by developers. But marketing team should still be able to access them in a visual builder.
5. 5.
It allows to connect 3rd party data very easily. You can connect any 3rd party source (like a products from e-commerce platform) in literally a couple of minutes. Developers have full control over how this data is displayed and searched in Shopstory UI and then how it is fetched in a build phase of your framework (like in getStaticProps from next.js). All the configuration stays in your project's code.
6. 6.
Other CMS data (entries / assets) can be very easily linked in Shopstory content. How they're fetched is customizable.
7. 7.
You can use code to build custom actions (like "open newsletter modal") and then make them available in Shopstory.
8. 8.
You can customise link behaviour. Connecting custom router (like next/link) is very easy.
9. 9.
It's possible to use custom image component (like next/image).
Below in How it works? section we explain each of these points in more detail.
Why?
In a traditional content architecture when marketer or designer comes up with a new idea then it usually must go through the following process:
1. 1.
Developer builds new content blocks with code.
2. 2.
Developer adds new content types in a headless CMS.
3. 3.
Developer writes a code that fetches the data from the CMS and renders the components in the front-end.
It simply takes too long. For many businesses that don't have their own resources and rely on agencies it is a painful process requiring scoping, invoicing etc. And let's be honest, how many developers like to be bothered all the time with these small marketing requests?
With Shopstory this process can be completely avoided. Marketer or designer can build new blocks without code and push to production with no developer involvement.
How it works?
CMS
Shopstory provides the app (or plugin / extension depending on the naming convention) for the CMS of your choice. We currently support Contentful and Sanity. The purpose of the app is to extend your CMS with a new field type - Shopstory field. This field can be added anywhere within your content model. It displays a button that opens Shostory editor where you can build the content visually. Let's see how a simple hero section can be built with Shopstory in Sanity:
When you close the editor all the content is saved back to the CMS field.
As you can see in the video, Shopstory uses native media picker from the CMS. The media source is overrideable.
Shopstory is fully compatible with native CMS localisation strategy.
The architecture where visual content is represented by a CMS field is very powerful. It allows to add visual building capabilities without losing any features of your CMS and its ecosystem:
1. 1.
Publishing, scheduling, previewing or reviewing CMS workflows are preserved.
2. 2.
You can keep using apps from the marketplace. For example, personalisation apps from Contentful marketplace can be used easily alongside Shopstory visual content.
3. 3.
Flexibility in content modeling is the same. Shopstory doesn't enforce any specific content types structure.
Displaying content in your front-end
Currently Shopstory supports any React framework like next, Gatsby or Remix. To render Shopstory visual content all you need to do is fetch the data from CMS and pass it through Shopstory SDK:
// in the server (for example getStaticProps):
const entry = await fetchDataFromCMS(...)
const shopstoryClient = new ShosptoryClient(
shopstoryConfig /* shopstory configuration object */
)
const renderableContent = shopstoryClient.add(entry.shopstoryField)
const meta = await shopstoryClient.build()
// somewhere in page component
<ShopstoryMetadataProvider meta={meta}>
<Shopstory content={renderableContent} />
</ShopstoryMetadataProvider>
Each Shopstory field in the CMS represents a piece of visual content and it's up to the developers where the content is rendered.
Is it compatible with SSR and static sites?
Yes. Shopstory is built with the static sites in mind. All the data fetching and heavy lifting happens in the server (like in next.js getStaticProps) exactly as in the traditional architecture. ShopstoryClient is not supposed to work in the browser. There is no layout shift that is so common in many visual building solutions.
Design system
In Shopstory editors can use only a predefined set of design tokens: fonts, colors, icons, spacings, page containers, etc. The tokens are set in the code in the Shopstory configuration object (that is later passed to the ShopstoryClient). Example color configuration:
export const shopstoryConfig = {
//...
colors: [
{
id: "green",
label: "Green",
value: "#83d1c4",
},
{
id: "purple",
label: "Purple",
value: "#78517c",
}
]
}
To learn more, read Design Tokens guide.
Custom components
You can easily extend Shopstory with your custom components. Imagine a very simple React component with border and background color that can be set via props:
import React from "react";
export type CustomComponentProps = {
color: "white" | "purple" | "green",
noBorder: boolean
}
export const CustomComponent : React.FC<CustomComponentProps> = (props) => {
return <div style={{
border: props.noBorder ? "none" : "2px solid black",
background: props.color === "white" ? "white" : props.color === "green" ? "#83d1c4" : "#78517c",
padding: 24,
display: "flex",
justifyContent: "center",
alignItems: "center",
textAlign: "center"
}}>
My custom component
</div>
}
To make it available in Shopstory all you need to do is register this component with its schema in Shopstory configuration object and add the instance of the component to Shopstory Provider:
// shopstory/config.ts
export const shopstoryConfig: Config = {
// ...
components: [
{
id: "CustomComponent",
label: "Custom component",
schema: [
{
prop: "color",
label: "Color",
type: "select",
options: [
"white", "purple", "green"
]
},
{
prop: "noBorder",
label: "Disable border",
type: "boolean"
},
]
}
]
}
// shopstory/provider.tsx
export const DemoShopstoryProvider : React.FC = ({ children }) => {
return <ShopstoryProvider
components={{
// ...
CustomComponent
}}
>
{ children }
</ShopstoryProvider>
}
The result looks like this:
You can add your custom cards, sections, buttons, literally anything you can imagine. Most commonly added components are custom buttons or, in e-commerce, product cards.
How does Shopstory render custom components?
When setting up Shopstory in your front-end (described in Getting Started) we ask you to create an empty page called "Shopstory Canvas". The URL for this page is usually yourdomain.com/shopstory-canvas (it can be any URL you want though). While using Shopstory editor the actual content rendering takes place in an iframe that uses the Canvas Page. Thanks to this all your custom components are rendered in the context of your own website. It means that even if the component uses React Context, window, etc., it will still work perfectly without any nasty hacks. It also means that whatever you see in Shopstory preview, it's gonna look exactly the same for your visitors.
A bit of philosophy - hybrid no-code / code
Shopstory makes it easy to build things without code but at the same time makes it easy to interleave content build visually with the content built traditionally with code. It's by design.
The idea behind Shopstory is to provide the easiest possible page building experience for end-users. This assumption implies that not every block can be built with Shopstory. If Shopstory allowed for building every possible block it would mean that the tool would have to become complex and intimidating for editors (like Webflow where you need a Webflow expert or know HTML/CSS). It would also greatly increase the risk of site getting broken by a non-professional and big mature brands can't afford it.
Shopstory follows Pareto principle. We noticed that most of the content blocks in websites are simple (80% from Pareto). We want to make these 80% doable in a super simple and unbreakable way by non-technical people. Simplicity and foolproofness are the most important features for us. For the remaining 20% you should stick to the custom code. When things are complex and custom then no visual tool can take away inherent complexity from the task. We believe that complex tasks are handled best by people who are trained for years to deal with such complexity - developers.
One of our e-commerce customers recently had a challenge of building a component for checking a gift card balance. It's a small component with input, button, validation, call to the API and displaying a result in a custom modal. We think this kind of component is too complex to be built by marketers. Developer built this component with code, made it available in Shopstory as a custom component and from that point he didn't have to worry about where and how this component is displayed in the website. Marketing team could add this component in different parts of the pages, sections and layouts, without limitations.
When editor adds a button in Shopstory it must be possible to decide what happens when user clicks it. It can be done with the mechanism called actions and links. Actions are simply JS functions (like openNewsletterSignupModal) that are run on button click (button HTML element is used). Links are responsible for page transitions (a element). Similar to components, each action or link can have its own fields (schema).
In the example below we assign link and action respectively to left and right buttons:
Actions and links can be also applied to text selection. Editors can fine-tune text styling easily:
Custom routing behaviour
The powerful feature of Shopstory is that it's fully customisable in terms of routing behaviour. Whether you use next/link, react-router or any other router, it can be easily applied to link actions. All you need to do is define the Link Wrapper component:
import Link from "next/link"
const NextLink : ShopstoryLink = ({ Component, componentProps, values }) => {
return (
<Link href={values.pagePath} passHref={true}>
<Component {...componentProps} />
</Link>
)
}
// shopstory/provider.tsx
export const DemoShopstoryProvider : React.FC = ({ children }) => {
return <ShopstoryProvider
// ...
links={{
NextLink
}}
>
{ children }
</ShopstoryProvider>
Read actions and links guides to learn more.
It's a common pattern to represent website URLs by a separate CMS content type. With Shopstory it's very easy to connect your custom links or actions to CMS entries of specific type (described below).
Loading data from external sources
Imagine custom ProductCard component with one of the props being product. product is an object with data coming from e-commerce platform. Shopstory allows developers to connect any 3rd party data source and customise every aspect of it. It can be achieved by using the concept called "resources".
Adding a resource field to a custom component, link or action schema is very simple:
export const shopstoryConfig: Config = {
// ...
components: [
{
id: "ProductCard",
label: "Product Card",
type: "card",
schema: [
// ...
{
prop: "product",
label: "Product",
type: "resource", // resource field
resourceType: "product" // resource type
}
]
}
],
}
At that point Shopstory doesn't know anything about product. It's a custom name for which additional behaviour must be defined. The next step is to define how editors can browse and pick products. In this example we'll use built-in item-picker widget. It displays a list of items with a search input at the top:
To connect the widget to your data source you must define widget property for your newly created resource type product:
export const shopstoryConfig: Config = {
// ...
resourceTypes: {
product: {
widget: {
type: "item-picker",
getItems: async (query) => {
const products = await fetchProductsByQuery(query);
return products.map(product => ({
id: product.id,
title: product.title,
thumbnail: product.image
}))
},
getItemById: async (id) => {
const product = await fetchProductById(id);
if (!product) {
throw new Error("can't find product");
}
return {
id: product.id,
title: product.title,
thumbnail: product.image
}
}
}
}
},
}
Voilà! From now on editors can browse and select products from your e-commerce platform and assign them to custom ProductCard components.
Now the important thing: the only data stored in Shopstory data is product id! Shopstory doesn't store any resource data internally. Thanks to this there are no problems with data synchronisation and privacy. But this brings up another question - how and when the product data is fetched? The answer is that you need to define another function called fetch where you can define the custom fetching behaviour:
export const shopstoryConfig: Config = {
// ...
resourceTypes: {
product: {
fetch: async (resources) => {
const ids = resources.map(resource => resource.id);
const products = await getFullProductDataByIds(ids);
return resources.map(resource => ({
...resource,
value: products.find(product => product.id === resource.id)
}))
},
widget: {
// ...widget definition
}
}
},
}
It's an extremely powerful mechanism, because developers are in full control over how data is fetched to their front-end. We know that there are bazzilion of different ways how you might want to fetch your data (from e-commerce platform, from cache, from CMS, from PIM, from a mix of any, with different optimisations, etc), so we don't enforce anything. You just pick your own way.
Another great thing is that Shopstory batches the fetch calls. If marketer built a page with 10 sections and each section has 2 product cards with different products, then only one fetch call with 20 products will be invoked. It allows you to fetch all these resources in one API call without overloading the server and unnecessarily increasing build time.
The fetching is done when you call await shopstoryClient.build() and it should obviously run on the server.
Connecting CMS data
Shopstory allows for linking other CMS data (entries, images, files) to your custom components, actions or links. Each Shopstory CMS plugin provides special built-in resource types for this purpose:
1. 1.
Entries / Documents (contentful.entry, sanity.document)
2. 2.
Assets / Media (contentful.asset, sanity.image)
3. 3.
Files (sanity.file)
Below we're showing the example with custom coded section connected to CMS entry (Sanity document):
How the data from CMS is fetched for these built-in resource types? Out of the box Shopstory provides a default fetch function. For example the contentful.entry is fetched with Contentful JS client with include: 5 parameter. For sanity.document, because of how GROQ is designed, we fetch all field values of the requested document without any deeper references. Obviously in many cases you might need to override this behaviour. It's very easy to do with Shopstory, either by providing custom fetch function or by using transform property (both described in-depth in Resources guide).
Can I use my existing sections with Shopstory?
Yes, totally. There are multiple ways of doing this, all described in Content modeling with Shopstory.
Custom Image component
By default Shopstory renders images with <img /> tag, but we know displaying images is often more sophisticated than that. Shopstory allows to override built-in image component with the one of your own choosing. Example for next/image:
import { ShopstoryProvider, ImageProps } from "@shopstory/react";
import NextImage from "next/image";
const Image : React.FC<ImageProps> = (props) => {
return <NextImage src={props.src} alt={props.alt} layout={"fill"} />
}
export const DemoShopstoryProvider : React.FC = ({ children }) => {
return <ShopstoryProvider
Image={Image}
>
{ children }
</ShopstoryProvider>
}
Summary
The purpose of this chapter was to show you how Shopstory works in a nutshell. Obviously we just scratched the surface here, so if you want to dive deeper, continue with Getting Started guide.
Last modified 6mo ago
|
__label__pos
| 0.81485 |
Coverage Report
Created: 2019-07-24 05:18
/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/External/isl/isl_union_single.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
* Copyright 2010 INRIA Saclay
3
* Copyright 2013 Ecole Normale Superieure
4
*
5
* Use of this software is governed by the MIT license
6
*
7
* Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
8
* Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
9
* 91893 Orsay, France
10
* and Ecole Normale Superieure, 45 rue d'Ulm, 75230 Paris, France
11
*/
12
13
#include <isl_hash_private.h>
14
#include <isl_union_macro.h>
15
16
/* A union of expressions defined over different domain spaces.
17
* "space" describes the parameters.
18
* The entries of "table" are keyed on the domain space of the entry.
19
*/
20
struct UNION {
21
int ref;
22
#ifdef HAS_TYPE
23
enum isl_fold type;
24
#endif
25
isl_space *space;
26
27
struct isl_hash_table table;
28
};
29
30
/* Return the number of base expressions in "u".
31
*/
32
int FN(FN(UNION,n),BASE)(__isl_keep UNION *u)
33
160
{
34
160
return u ? u->table.n :
00
;
35
160
}
isl_union_pw_aff_n_pw_aff
Line
Count
Source
33
158
{
34
158
return u ? u->table.n :
00
;
35
158
}
Unexecuted instantiation: isl_union_pw_qpolynomial_fold_n_pw_qpolynomial_fold
isl_union_pw_qpolynomial_n_pw_qpolynomial
Line
Count
Source
33
2
{
34
2
return u ? u->table.n :
00
;
35
2
}
36
37
S(UNION,foreach_data)
38
{
39
isl_stat (*fn)(__isl_take PART *part, void *user);
40
void *user;
41
};
42
43
static isl_stat FN(UNION,call_on_copy)(void **entry, void *user)
44
42.2k
{
45
42.2k
PART *part = *entry;
46
42.2k
S(UNION,foreach_data) *data = (S(UNION,foreach_data) *)user;
47
42.2k
48
42.2k
part = FN(PART,copy)(part);
49
42.2k
if (!part)
50
0
return isl_stat_error;
51
42.2k
return data->fn(part, data->user);
52
42.2k
}
isl_aff.c:isl_union_pw_aff_call_on_copy
Line
Count
Source
44
42.2k
{
45
42.2k
PART *part = *entry;
46
42.2k
S(UNION,foreach_data) *data = (S(UNION,foreach_data) *)user;
47
42.2k
48
42.2k
part = FN(PART,copy)(part);
49
42.2k
if (!part)
50
0
return isl_stat_error;
51
42.2k
return data->fn(part, data->user);
52
42.2k
}
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_call_on_copy
isl_polynomial.c:isl_union_pw_qpolynomial_call_on_copy
Line
Count
Source
44
3
{
45
3
PART *part = *entry;
46
3
S(UNION,foreach_data) *data = (S(UNION,foreach_data) *)user;
47
3
48
3
part = FN(PART,copy)(part);
49
3
if (!part)
50
0
return isl_stat_error;
51
3
return data->fn(part, data->user);
52
3
}
53
54
isl_stat FN(FN(UNION,foreach),BASE)(__isl_keep UNION *u,
55
isl_stat (*fn)(__isl_take PART *part, void *user), void *user)
56
21.6k
{
57
21.6k
S(UNION,foreach_data) data = { fn, user };
58
21.6k
59
21.6k
if (!u)
60
0
return isl_stat_error;
61
21.6k
62
21.6k
return isl_hash_table_foreach(u->space->ctx, &u->table,
63
21.6k
&FN(UNION,call_on_copy), &data);
64
21.6k
}
isl_union_pw_aff_foreach_pw_aff
Line
Count
Source
56
21.6k
{
57
21.6k
S(UNION,foreach_data) data = { fn, user };
58
21.6k
59
21.6k
if (!u)
60
0
return isl_stat_error;
61
21.6k
62
21.6k
return isl_hash_table_foreach(u->space->ctx, &u->table,
63
21.6k
&FN(UNION,call_on_copy), &data);
64
21.6k
}
Unexecuted instantiation: isl_union_pw_qpolynomial_fold_foreach_pw_qpolynomial_fold
isl_union_pw_qpolynomial_foreach_pw_qpolynomial
Line
Count
Source
56
3
{
57
3
S(UNION,foreach_data) data = { fn, user };
58
3
59
3
if (!u)
60
0
return isl_stat_error;
61
3
62
3
return isl_hash_table_foreach(u->space->ctx, &u->table,
63
3
&FN(UNION,call_on_copy), &data);
64
3
}
65
66
/* Is the domain space of "entry" equal to the domain of "space"?
67
*/
68
static int FN(UNION,has_same_domain_space)(const void *entry, const void *val)
69
794
{
70
794
PART *part = (PART *)entry;
71
794
isl_space *space = (isl_space *) val;
72
794
73
794
if (isl_space_is_set(space))
74
13
return isl_space_is_set(part->dim);
75
781
76
781
return isl_space_tuple_is_equal(part->dim, isl_dim_in,
77
781
space, isl_dim_in);
78
781
}
isl_aff.c:isl_union_pw_aff_has_same_domain_space
Line
Count
Source
69
793
{
70
793
PART *part = (PART *)entry;
71
793
isl_space *space = (isl_space *) val;
72
793
73
793
if (isl_space_is_set(space))
74
13
return isl_space_is_set(part->dim);
75
780
76
780
return isl_space_tuple_is_equal(part->dim, isl_dim_in,
77
780
space, isl_dim_in);
78
780
}
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_has_same_domain_space
isl_polynomial.c:isl_union_pw_qpolynomial_has_same_domain_space
Line
Count
Source
69
1
{
70
1
PART *part = (PART *)entry;
71
1
isl_space *space = (isl_space *) val;
72
1
73
1
if (isl_space_is_set(space))
74
0
return isl_space_is_set(part->dim);
75
1
76
1
return isl_space_tuple_is_equal(part->dim, isl_dim_in,
77
1
space, isl_dim_in);
78
1
}
79
80
/* Return the entry, if any, in "u" that lives in "space".
81
* If "reserve" is set, then an entry is created if it does not exist yet.
82
* Return NULL on error and isl_hash_table_entry_none if no entry was found.
83
* Note that when "reserve" is set, the function will never return
84
* isl_hash_table_entry_none.
85
*
86
* First look for the entry (if any) with the same domain space.
87
* If it exists, then check if the range space also matches.
88
*/
89
static struct isl_hash_table_entry *FN(UNION,find_part_entry)(
90
__isl_keep UNION *u, __isl_keep isl_space *space, int reserve)
91
18.1k
{
92
18.1k
isl_ctx *ctx;
93
18.1k
uint32_t hash;
94
18.1k
struct isl_hash_table_entry *entry;
95
18.1k
isl_bool equal;
96
18.1k
PART *part;
97
18.1k
98
18.1k
if (!u || !space)
99
0
return NULL;
100
18.1k
101
18.1k
ctx = FN(UNION,get_ctx)(u);
102
18.1k
hash = isl_space_get_domain_hash(space);
103
18.1k
entry = isl_hash_table_find(ctx, &u->table, hash,
104
18.1k
&FN(UNION,has_same_domain_space), space, reserve);
105
18.1k
if (!entry)
106
2
return reserve ? NULL : isl_hash_table_entry_none;
107
18.1k
if (reserve &&
!entry->data17.3k
)
108
17.3k
return entry;
109
794
part = entry->data;
110
794
equal = isl_space_tuple_is_equal(part->dim, isl_dim_out,
111
794
space, isl_dim_out);
112
794
if (equal < 0)
113
0
return NULL;
114
794
if (equal)
115
794
return entry;
116
0
if (!reserve)
117
0
return isl_hash_table_entry_none;
118
0
isl_die(FN(UNION,get_ctx)(u), isl_error_invalid,
119
0
"union expression can only contain a single "
120
0
"expression over a given domain", return NULL);
121
0
}
isl_aff.c:isl_union_pw_aff_find_part_entry
Line
Count
Source
91
18.0k
{
92
18.0k
isl_ctx *ctx;
93
18.0k
uint32_t hash;
94
18.0k
struct isl_hash_table_entry *entry;
95
18.0k
isl_bool equal;
96
18.0k
PART *part;
97
18.0k
98
18.0k
if (!u || !space)
99
0
return NULL;
100
18.0k
101
18.0k
ctx = FN(UNION,get_ctx)(u);
102
18.0k
hash = isl_space_get_domain_hash(space);
103
18.0k
entry = isl_hash_table_find(ctx, &u->table, hash,
104
18.0k
&FN(UNION,has_same_domain_space), space, reserve);
105
18.0k
if (!entry)
106
2
return reserve ? NULL : isl_hash_table_entry_none;
107
18.0k
if (reserve &&
!entry->data17.3k
)
108
17.3k
return entry;
109
793
part = entry->data;
110
793
equal = isl_space_tuple_is_equal(part->dim, isl_dim_out,
111
793
space, isl_dim_out);
112
793
if (equal < 0)
113
0
return NULL;
114
793
if (equal)
115
793
return entry;
116
0
if (!reserve)
117
0
return isl_hash_table_entry_none;
118
0
isl_die(FN(UNION,get_ctx)(u), isl_error_invalid,
119
0
"union expression can only contain a single "
120
0
"expression over a given domain", return NULL);
121
0
}
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_find_part_entry
isl_polynomial.c:isl_union_pw_qpolynomial_find_part_entry
Line
Count
Source
91
6
{
92
6
isl_ctx *ctx;
93
6
uint32_t hash;
94
6
struct isl_hash_table_entry *entry;
95
6
isl_bool equal;
96
6
PART *part;
97
6
98
6
if (!u || !space)
99
0
return NULL;
100
6
101
6
ctx = FN(UNION,get_ctx)(u);
102
6
hash = isl_space_get_domain_hash(space);
103
6
entry = isl_hash_table_find(ctx, &u->table, hash,
104
6
&FN(UNION,has_same_domain_space), space, reserve);
105
6
if (!entry)
106
0
return reserve ? NULL : isl_hash_table_entry_none;
107
6
if (reserve &&
!entry->data5
)
108
5
return entry;
109
1
part = entry->data;
110
1
equal = isl_space_tuple_is_equal(part->dim, isl_dim_out,
111
1
space, isl_dim_out);
112
1
if (equal < 0)
113
0
return NULL;
114
1
if (equal)
115
1
return entry;
116
0
if (!reserve)
117
0
return isl_hash_table_entry_none;
118
0
isl_die(FN(UNION,get_ctx)(u), isl_error_invalid,
119
0
"union expression can only contain a single "
120
0
"expression over a given domain", return NULL);
121
0
}
122
123
/* Remove "part_entry" from the hash table of "u".
124
*/
125
static __isl_give UNION *FN(UNION,remove_part_entry)(__isl_take UNION *u,
126
struct isl_hash_table_entry *part_entry)
127
0
{
128
0
isl_ctx *ctx;
129
0
130
0
if (!u || !part_entry)
131
0
return FN(UNION,free)(u);
132
0
133
0
ctx = FN(UNION,get_ctx)(u);
134
0
isl_hash_table_remove(ctx, &u->table, part_entry);
135
0
FN(PART,free)(part_entry->data);
136
0
137
0
return u;
138
0
}
Unexecuted instantiation: isl_aff.c:isl_union_pw_aff_remove_part_entry
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_remove_part_entry
Unexecuted instantiation: isl_polynomial.c:isl_union_pw_qpolynomial_remove_part_entry
139
140
/* Check that the domain of "part" is disjoint from the domain of the entries
141
* in "u" that are defined on the same domain space, but have a different
142
* target space.
143
* Since a UNION with a single entry per domain space is not allowed
144
* to contain two entries with the same domain space, there cannot be
145
* any such other entry.
146
*/
147
static isl_stat FN(UNION,check_disjoint_domain_other)(__isl_keep UNION *u,
148
__isl_keep PART *part)
149
17.3k
{
150
17.3k
return isl_stat_ok;
151
17.3k
}
isl_aff.c:isl_union_pw_aff_check_disjoint_domain_other
Line
Count
Source
149
17.3k
{
150
17.3k
return isl_stat_ok;
151
17.3k
}
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_check_disjoint_domain_other
isl_polynomial.c:isl_union_pw_qpolynomial_check_disjoint_domain_other
Line
Count
Source
149
5
{
150
5
return isl_stat_ok;
151
5
}
152
153
/* Check that the domain of "part1" is disjoint from the domain of "part2".
154
* This check is performed before "part2" is added to a UNION to ensure
155
* that the UNION expression remains a function.
156
* Since a UNION with a single entry per domain space is not allowed
157
* to contain two entries with the same domain space, fail unconditionally.
158
*/
159
static isl_stat FN(UNION,check_disjoint_domain)(__isl_keep PART *part1,
160
__isl_keep PART *part2)
161
0
{
162
0
isl_die(FN(PART,get_ctx)(part1), isl_error_invalid,
163
0
"additional part should live on separate space",
164
0
return isl_stat_error);
165
0
}
Unexecuted instantiation: isl_aff.c:isl_union_pw_aff_check_disjoint_domain
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_check_disjoint_domain
Unexecuted instantiation: isl_polynomial.c:isl_union_pw_qpolynomial_check_disjoint_domain
166
167
/* Call "fn" on each part entry of "u".
168
*/
169
static isl_stat FN(UNION,foreach_inplace)(__isl_keep UNION *u,
170
isl_stat (*fn)(void **part, void *user), void *user)
171
770
{
172
770
isl_ctx *ctx;
173
770
174
770
if (!u)
175
0
return isl_stat_error;
176
770
ctx = FN(UNION,get_ctx)(u);
177
770
return isl_hash_table_foreach(ctx, &u->table, fn, user);
178
770
}
isl_aff.c:isl_union_pw_aff_foreach_inplace
Line
Count
Source
171
769
{
172
769
isl_ctx *ctx;
173
769
174
769
if (!u)
175
0
return isl_stat_error;
176
769
ctx = FN(UNION,get_ctx)(u);
177
769
return isl_hash_table_foreach(ctx, &u->table, fn, user);
178
769
}
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_foreach_inplace
isl_polynomial.c:isl_union_pw_qpolynomial_foreach_inplace
Line
Count
Source
171
1
{
172
1
isl_ctx *ctx;
173
1
174
1
if (!u)
175
0
return isl_stat_error;
176
1
ctx = FN(UNION,get_ctx)(u);
177
1
return isl_hash_table_foreach(ctx, &u->table, fn, user);
178
1
}
179
180
/* Does "u" have a single reference?
181
* That is, can we change "u" inplace?
182
*/
183
static isl_bool FN(UNION,has_single_reference)(__isl_keep UNION *u)
184
3.05k
{
185
3.05k
if (!u)
186
0
return isl_bool_error;
187
3.05k
return u->ref == 1;
188
3.05k
}
isl_aff.c:isl_union_pw_aff_has_single_reference
Line
Count
Source
184
3.05k
{
185
3.05k
if (!u)
186
0
return isl_bool_error;
187
3.05k
return u->ref == 1;
188
3.05k
}
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_has_single_reference
Unexecuted instantiation: isl_polynomial.c:isl_union_pw_qpolynomial_has_single_reference
189
190
static isl_stat FN(UNION,free_u_entry)(void **entry, void *user)
191
17.2k
{
192
17.2k
PART *part = *entry;
193
17.2k
FN(PART,free)(part);
194
17.2k
return isl_stat_ok;
195
17.2k
}
isl_aff.c:isl_union_pw_aff_free_u_entry
Line
Count
Source
191
17.2k
{
192
17.2k
PART *part = *entry;
193
17.2k
FN(PART,free)(part);
194
17.2k
return isl_stat_ok;
195
17.2k
}
Unexecuted instantiation: isl_fold.c:isl_union_pw_qpolynomial_fold_free_u_entry
isl_polynomial.c:isl_union_pw_qpolynomial_free_u_entry
Line
Count
Source
191
5
{
192
5
PART *part = *entry;
193
5
FN(PART,free)(part);
194
5
return isl_stat_ok;
195
5
}
196
197
#include <isl_union_templ.c>
|
__label__pos
| 0.973396 |
/* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*- theme.c for the Openbox window manager Copyright (c) 2006 Mikael Magnusson Copyright (c) 2003-2007 Dana Jansens This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. See the COPYING file for a copy of the GNU General Public License. */ #include "render.h" #include "color.h" #include "font.h" #include "mask.h" #include "theme.h" #include "icon.h" #include "parser/parse.h" #include #include #include #include #include static XrmDatabase loaddb(const gchar *name, gchar **path); static gboolean read_int(XrmDatabase db, const gchar *rname, gint *value); static gboolean read_string(XrmDatabase db, const gchar *rname, gchar **value); static gboolean read_color(XrmDatabase db, const RrInstance *inst, const gchar *rname, RrColor **value); static gboolean read_mask(const RrInstance *inst, const gchar *path, RrTheme *theme, const gchar *maskname, RrPixmapMask **value); static gboolean read_appearance(XrmDatabase db, const RrInstance *inst, const gchar *rname, RrAppearance *value, gboolean allow_trans); static int parse_inline_number(const char *p); static RrPixel32* read_c_image(gint width, gint height, const guint8 *data); static void set_default_appearance(RrAppearance *a); #define READ_INT(x_resstr, x_var, x_min, x_max, x_def) \ if (!read_int(db, x_resstr, & x_var) || \ x_var < x_min || x_var > x_max) \ x_var = x_def; #define READ_COLOR(x_resstr, x_var, x_def) \ if (!read_color(db, inst, x_resstr, & x_var)) \ x_var = x_def; #define READ_COLOR_(x_res1, x_res2, x_var, x_def) \ if (!read_color(db, inst, x_res1, & x_var) && \ !read_color(db, inst, x_res2, & x_var)) \ x_var = x_def; #define READ_MASK_COPY(x_file, x_var, x_copysrc) \ if (!read_mask(inst, path, theme, x_file, & x_var)) \ x_var = RrPixmapMaskCopy(x_copysrc); #define READ_APPEARANCE(x_resstr, x_var, x_parrel) \ if (!read_appearance(db, inst, x_resstr, x_var, x_parrel)) \ set_default_appearance(x_var); #define READ_APPEARANCE_COPY(x_resstr, x_var, x_parrel, x_defval) \ if (!read_appearance(db, inst, x_resstr, x_var, x_parrel)) {\ RrAppearanceFree(x_var); \ x_var = RrAppearanceCopy(x_defval); } #define READ_APPEARANCE_(x_res1, x_res2, x_var, x_parrel, x_defval) \ if (!read_appearance(db, inst, x_res1, x_var, x_parrel) && \ !read_appearance(db, inst, x_res2, x_var, x_parrel)) {\ RrAppearanceFree(x_var); \ x_var = RrAppearanceCopy(x_defval); } RrTheme* RrThemeNew(const RrInstance *inst, const gchar *name, gboolean allow_fallback, RrFont *active_window_font, RrFont *inactive_window_font, RrFont *menu_title_font, RrFont *menu_item_font, RrFont *osd_font) { XrmDatabase db = NULL; RrJustify winjust, mtitlejust; gchar *str; RrTheme *theme; gchar *path; gboolean userdef; RrAppearance *a_disabled_focused_tmp; RrAppearance *a_disabled_unfocused_tmp; RrAppearance *a_hover_focused_tmp; RrAppearance *a_hover_unfocused_tmp; RrAppearance *a_focused_unpressed_tmp; RrAppearance *a_focused_pressed_tmp; RrAppearance *a_unfocused_unpressed_tmp; RrAppearance *a_unfocused_pressed_tmp; RrAppearance *a_toggled_hover_focused_tmp; RrAppearance *a_toggled_hover_unfocused_tmp; RrAppearance *a_toggled_focused_unpressed_tmp; RrAppearance *a_toggled_focused_pressed_tmp; RrAppearance *a_toggled_unfocused_unpressed_tmp; RrAppearance *a_toggled_unfocused_pressed_tmp; if (name) { db = loaddb(name, &path); if (db == NULL) { g_message("Unable to load the theme '%s'", name); if (allow_fallback) g_message("Falling back to the default theme '%s'", DEFAULT_THEME); /* fallback to the default theme */ name = NULL; } } if (name == NULL) { if (allow_fallback) { db = loaddb(DEFAULT_THEME, &path); if (db == NULL) { g_message("Unable to load the theme '%s'", DEFAULT_THEME); return NULL; } } else return NULL; } /* initialize temp reading textures */ a_disabled_focused_tmp = RrAppearanceNew(inst, 1); a_disabled_unfocused_tmp = RrAppearanceNew(inst, 1); a_hover_focused_tmp = RrAppearanceNew(inst, 1); a_hover_unfocused_tmp = RrAppearanceNew(inst, 1); a_toggled_focused_unpressed_tmp = RrAppearanceNew(inst, 1); a_toggled_unfocused_unpressed_tmp = RrAppearanceNew(inst, 1); a_toggled_hover_focused_tmp = RrAppearanceNew(inst, 1); a_toggled_hover_unfocused_tmp = RrAppearanceNew(inst, 1); a_toggled_focused_pressed_tmp = RrAppearanceNew(inst, 1); a_toggled_unfocused_pressed_tmp = RrAppearanceNew(inst, 1); a_focused_unpressed_tmp = RrAppearanceNew(inst, 1); a_focused_pressed_tmp = RrAppearanceNew(inst, 1); a_unfocused_unpressed_tmp = RrAppearanceNew(inst, 1); a_unfocused_pressed_tmp = RrAppearanceNew(inst, 1); /* initialize theme */ theme = g_new0(RrTheme, 1); theme->inst = inst; theme->name = g_strdup(name ? name : DEFAULT_THEME); /* init buttons */ theme->btn_max = RrButtonNew(inst); theme->btn_close = RrButtonNew(inst); theme->btn_desk = RrButtonNew(inst); theme->btn_shade = RrButtonNew(inst); theme->btn_iconify = RrButtonNew(inst); /* init appearances */ theme->a_focused_grip = RrAppearanceNew(inst, 0); theme->a_unfocused_grip = RrAppearanceNew(inst, 0); theme->a_focused_title = RrAppearanceNew(inst, 0); theme->a_unfocused_title = RrAppearanceNew(inst, 0); theme->a_focused_label = RrAppearanceNew(inst, 1); theme->a_unfocused_label = RrAppearanceNew(inst, 1); theme->a_icon = RrAppearanceNew(inst, 1); theme->a_focused_handle = RrAppearanceNew(inst, 0); theme->a_unfocused_handle = RrAppearanceNew(inst, 0); theme->a_menu = RrAppearanceNew(inst, 0); theme->a_menu_title = RrAppearanceNew(inst, 0); theme->a_menu_text_title = RrAppearanceNew(inst, 1); theme->a_menu_normal = RrAppearanceNew(inst, 0); theme->a_menu_selected = RrAppearanceNew(inst, 0); theme->a_menu_disabled = RrAppearanceNew(inst, 0); theme->a_menu_disabled_selected = RrAppearanceNew(inst, 0); theme->a_menu_text_normal = RrAppearanceNew(inst, 1); theme->a_menu_text_selected = RrAppearanceNew(inst, 1); theme->a_menu_text_disabled = RrAppearanceNew(inst, 1); theme->a_menu_text_disabled_selected = RrAppearanceNew(inst, 1); theme->a_menu_bullet_normal = RrAppearanceNew(inst, 1); theme->a_menu_bullet_selected = RrAppearanceNew(inst, 1); theme->a_clear = RrAppearanceNew(inst, 0); theme->a_clear_tex = RrAppearanceNew(inst, 1); theme->osd_hilite_bg = RrAppearanceNew(inst, 0); theme->osd_hilite_label = RrAppearanceNew(inst, 1); theme->osd_hilite_fg = RrAppearanceNew(inst, 0); theme->osd_unhilite_fg = RrAppearanceNew(inst, 0); /* load the font stuff */ if (active_window_font) { theme->win_font_focused = active_window_font; RrFontRef(active_window_font); } else theme->win_font_focused = RrFontOpenDefault(inst); if (inactive_window_font) { theme->win_font_unfocused = inactive_window_font; RrFontRef(inactive_window_font); } else theme->win_font_unfocused = RrFontOpenDefault(inst); winjust = RR_JUSTIFY_LEFT; if (read_string(db, "window.label.text.justify", &str)) { if (!g_ascii_strcasecmp(str, "right")) winjust = RR_JUSTIFY_RIGHT; else if (!g_ascii_strcasecmp(str, "center")) winjust = RR_JUSTIFY_CENTER; } if (menu_title_font) { theme->menu_title_font = menu_title_font; RrFontRef(menu_title_font); } else theme->menu_title_font = RrFontOpenDefault(inst); mtitlejust = RR_JUSTIFY_LEFT; if (read_string(db, "menu.title.text.justify", &str)) { if (!g_ascii_strcasecmp(str, "right")) mtitlejust = RR_JUSTIFY_RIGHT; else if (!g_ascii_strcasecmp(str, "center")) mtitlejust = RR_JUSTIFY_CENTER; } if (menu_item_font) { theme->menu_font = menu_item_font; RrFontRef(menu_item_font); } else theme->menu_font = RrFontOpenDefault(inst); if (osd_font) { theme->osd_font = osd_font; RrFontRef(osd_font); } else theme->osd_font = RrFontOpenDefault(inst); /* load direct dimensions */ READ_INT("menu.overlap", theme->menu_overlap, -100, 100, 0); READ_INT("window.handle.width", theme->handle_height, 0, 100, 6); READ_INT("padding.width", theme->paddingx, 0, 100, 3); READ_INT("padding.height", theme->paddingy, 0, 100, theme->paddingx); READ_INT("border.width", theme->fbwidth, 0, 100, 1); READ_INT("menu.border.width", theme->mbwidth, 0, 100, theme->fbwidth); READ_INT("osd.border.width", theme->obwidth, 0, 100, theme->fbwidth); READ_INT("window.client.padding.width", theme->cbwidthx, 0, 100, theme->paddingx); READ_INT("window.client.padding.height", theme->cbwidthy, 0, 100, theme->cbwidthx); /* load colors */ READ_COLOR_("window.active.border.color", "border.color", theme->frame_focused_border_color, RrColorNew(inst, 0, 0, 0)); /* title separator focused color inherits from focused boder color */ READ_COLOR("window.active.title.separator.color", theme->title_separator_focused_color, RrColorCopy(theme->frame_focused_border_color)); /* unfocused border color inherits from frame focused border color */ READ_COLOR("window.inactive.border.color", theme->frame_unfocused_border_color, RrColorCopy(theme->frame_focused_border_color)); /* title separator unfocused color inherits from unfocused boder color */ READ_COLOR("window.inactive.title.separator.color", theme->title_separator_unfocused_color, RrColorCopy(theme->frame_unfocused_border_color)); /* menu border color inherits from frame focused border color */ READ_COLOR("menu.border.color", theme->menu_border_color, RrColorCopy(theme->frame_focused_border_color)); /* osd border color inherits from frame focused border color */ READ_COLOR("osd.border.color", theme->osd_border_color, RrColorCopy(theme->frame_focused_border_color)); READ_COLOR("window.active.client.color", theme->cb_focused_color, RrColorNew(inst, 0xff, 0xff, 0xff)); READ_COLOR("window.inactive.client.color", theme->cb_unfocused_color, RrColorNew(inst, 0xff, 0xff, 0xff)); READ_COLOR("window.active.label.text.color", theme->title_focused_color, RrColorNew(inst, 0x0, 0x0, 0x0)); READ_COLOR("osd.label.text.color", theme->osd_color, RrColorCopy(theme->title_focused_color)); READ_COLOR("window.inactive.label.text.color", theme->title_unfocused_color, RrColorNew(inst, 0xff, 0xff, 0xff)); READ_COLOR("window.active.button.unpressed.image.color", theme->titlebut_focused_unpressed_color, RrColorNew(inst, 0, 0, 0)); READ_COLOR("window.inactive.button.unpressed.image.color", theme->titlebut_unfocused_unpressed_color, RrColorNew(inst, 0xff, 0xff, 0xff)); READ_COLOR("window.active.button.pressed.image.color", theme->titlebut_focused_pressed_color, RrColorCopy(theme->titlebut_focused_unpressed_color)); READ_COLOR("window.inactive.button.pressed.image.color", theme->titlebut_unfocused_pressed_color, RrColorCopy(theme->titlebut_unfocused_unpressed_color)); READ_COLOR("window.active.button.disabled.image.color", theme->titlebut_disabled_focused_color, RrColorNew(inst, 0xff, 0xff, 0xff)); READ_COLOR("window.inactive.button.disabled.image.color", theme->titlebut_disabled_unfocused_color, RrColorNew(inst, 0, 0, 0)); READ_COLOR("window.active.button.hover.image.color", theme->titlebut_hover_focused_color, RrColorCopy(theme->titlebut_focused_unpressed_color)); READ_COLOR("window.inactive.button.hover.image.color", theme->titlebut_hover_unfocused_color, RrColorCopy(theme->titlebut_unfocused_unpressed_color)); READ_COLOR_("window.active.button.toggled.unpressed.image.color", "window.active.button.toggled.image.color", theme->titlebut_toggled_focused_unpressed_color, RrColorCopy(theme->titlebut_focused_pressed_color)); READ_COLOR_("window.inactive.button.toggled.unpressed.image.color", "window.inactive.button.toggled.image.color", theme->titlebut_toggled_unfocused_unpressed_color, RrColorCopy(theme->titlebut_unfocused_pressed_color)); READ_COLOR("window.active.button.toggled.hover.image.color", theme->titlebut_toggled_hover_focused_color, RrColorCopy(theme->titlebut_toggled_focused_unpressed_color)); READ_COLOR("window.inactive.button.toggled.hover.image.color", theme->titlebut_toggled_hover_unfocused_color, RrColorCopy(theme->titlebut_toggled_unfocused_unpressed_color)); READ_COLOR("window.active.button.toggled.pressed.image.color", theme->titlebut_toggled_focused_pressed_color, RrColorCopy(theme->titlebut_focused_pressed_color)); READ_COLOR("window.inactive.button.toggled.pressed.image.color", theme->titlebut_toggled_unfocused_pressed_color, RrColorCopy(theme->titlebut_unfocused_pressed_color)); READ_COLOR("menu.title.text.color", theme->menu_title_color, RrColorNew(inst, 0, 0, 0)); READ_COLOR("menu.items.text.color", theme->menu_color, RrColorNew(inst, 0xff, 0xff, 0xff)); READ_COLOR("menu.items.disabled.text.color", theme->menu_disabled_color, RrColorNew(inst, 0, 0, 0)); READ_COLOR("menu.items.active.disabled.text.color", theme->menu_disabled_selected_color, RrColorCopy(theme->menu_disabled_color)); READ_COLOR("menu.items.active.text.color", theme->menu_selected_color, RrColorNew(inst, 0, 0, 0)); /* load the image masks */ /* maximize button masks */ userdef = TRUE; if (!read_mask(inst, path, theme, "max.xbm", &theme->btn_max->mask)) { guchar data[] = { 0x3f, 0x3f, 0x21, 0x21, 0x21, 0x3f }; theme->btn_max->mask = RrPixmapMaskNew(inst, 6, 6, (gchar*)data); userdef = FALSE; } if (!read_mask(inst, path, theme, "max_toggled.xbm", &theme->btn_max->toggled_mask)) { if (userdef) theme->btn_max->toggled_mask = RrPixmapMaskCopy(theme->btn_max->mask); else { guchar data[] = { 0x3e, 0x22, 0x2f, 0x29, 0x39, 0x0f }; theme->btn_max->toggled_mask = RrPixmapMaskNew(inst, 6, 6,(gchar*)data); } } READ_MASK_COPY("max_pressed.xbm", theme->btn_max->pressed_mask, theme->btn_max->mask); READ_MASK_COPY("max_disabled.xbm", theme->btn_max->disabled_mask, theme->btn_max->mask); READ_MASK_COPY("max_hover.xbm", theme->btn_max->hover_mask, theme->btn_max->mask); READ_MASK_COPY("max_toggled_pressed.xbm", theme->btn_max->toggled_pressed_mask, theme->btn_max->toggled_mask); READ_MASK_COPY("max_toggled_hover.xbm", theme->btn_max->toggled_hover_mask, theme->btn_max->toggled_mask); /* iconify button masks */ if (!read_mask(inst, path, theme, "iconify.xbm", &theme->btn_iconify->mask)) { guchar data[] = { 0x00, 0x00, 0x00, 0x00, 0x3f, 0x3f }; theme->btn_iconify->mask = RrPixmapMaskNew(inst, 6, 6, (gchar*)data); } READ_MASK_COPY("iconify_pressed.xbm", theme->btn_iconify->pressed_mask, theme->btn_iconify->mask); READ_MASK_COPY("iconify_disabled.xbm", theme->btn_iconify->disabled_mask, theme->btn_iconify->mask); READ_MASK_COPY("iconify_hover.xbm", theme->btn_iconify->hover_mask, theme->btn_iconify->mask); /* all desktops button masks */ userdef = TRUE; if (!read_mask(inst, path, theme, "desk.xbm", &theme->btn_desk->mask)) { guchar data[] = { 0x33, 0x33, 0x00, 0x00, 0x33, 0x33 }; theme->btn_desk->mask = RrPixmapMaskNew(inst, 6, 6, (gchar*)data); userdef = FALSE; } if (!read_mask(inst, path, theme, "desk_toggled.xbm", &theme->btn_desk->toggled_mask)) { if (userdef) theme->btn_desk->toggled_mask = RrPixmapMaskCopy(theme->btn_desk->mask); else { guchar data[] = { 0x00, 0x1e, 0x1a, 0x16, 0x1e, 0x00 }; theme->btn_desk->toggled_mask = RrPixmapMaskNew(inst, 6, 6, (gchar*)data); } } READ_MASK_COPY("desk_pressed.xbm", theme->btn_desk->pressed_mask, theme->btn_desk->mask); READ_MASK_COPY("desk_disabled.xbm", theme->btn_desk->disabled_mask, theme->btn_desk->mask); READ_MASK_COPY("desk_hover.xbm", theme->btn_desk->hover_mask, theme->btn_desk->mask); READ_MASK_COPY("desk_toggled_pressed.xbm", theme->btn_desk->toggled_pressed_mask, theme->btn_desk->toggled_mask); READ_MASK_COPY("desk_toggled_hover.xbm", theme->btn_desk->toggled_hover_mask, theme->btn_desk->toggled_mask); /* shade button masks */ if (!read_mask(inst, path, theme, "shade.xbm", &theme->btn_shade->mask)) { guchar data[] = { 0x3f, 0x3f, 0x00, 0x00, 0x00, 0x00 }; theme->btn_shade->mask = RrPixmapMaskNew(inst, 6, 6, (gchar*)data); } READ_MASK_COPY("shade_toggled.xbm", theme->btn_shade->toggled_mask, theme->btn_shade->mask); READ_MASK_COPY("shade_pressed.xbm", theme->btn_shade->pressed_mask, theme->btn_shade->mask); READ_MASK_COPY("shade_disabled.xbm", theme->btn_shade->disabled_mask, theme->btn_shade->mask); READ_MASK_COPY("shade_hover.xbm", theme->btn_shade->hover_mask, theme->btn_shade->mask); READ_MASK_COPY("shade_toggled_pressed.xbm", theme->btn_shade->toggled_pressed_mask, theme->btn_shade->toggled_mask); READ_MASK_COPY("shade_toggled_hover.xbm", theme->btn_shade->toggled_hover_mask, theme->btn_shade->toggled_mask); /* close button masks */ if (!read_mask(inst, path, theme, "close.xbm", &theme->btn_close->mask)) { guchar data[] = { 0x33, 0x3f, 0x1e, 0x1e, 0x3f, 0x33 }; theme->btn_close->mask = RrPixmapMaskNew(inst, 6, 6, (gchar*)data); } READ_MASK_COPY("close_pressed.xbm", theme->btn_close->pressed_mask, theme->btn_close->mask); READ_MASK_COPY("close_disabled.xbm", theme->btn_close->disabled_mask, theme->btn_close->mask); READ_MASK_COPY("close_hover.xbm", theme->btn_close->hover_mask, theme->btn_close->mask); /* submenu bullet mask */ if (!read_mask(inst, path, theme, "bullet.xbm", &theme->menu_bullet_mask)) { guchar data[] = { 0x01, 0x03, 0x07, 0x0f, 0x07, 0x03, 0x01 }; theme->menu_bullet_mask = RrPixmapMaskNew(inst, 4, 7, (gchar*)data); } /* setup the default window icon */ theme->def_win_icon = read_c_image(OB_DEFAULT_ICON_WIDTH, OB_DEFAULT_ICON_HEIGHT, OB_DEFAULT_ICON_pixel_data); /* the toggled hover mask = the toggled unpressed mask (i.e. no change) */ theme->btn_max->toggled_hover_mask = RrPixmapMaskCopy(theme->btn_max->toggled_mask); theme->btn_desk->toggled_hover_mask = RrPixmapMaskCopy(theme->btn_desk->toggled_mask); theme->btn_shade->toggled_hover_mask = RrPixmapMaskCopy(theme->btn_shade->toggled_mask); /* the toggled pressed mask = the toggled unpressed mask (i.e. no change)*/ theme->btn_max->toggled_pressed_mask = RrPixmapMaskCopy(theme->btn_max->toggled_mask); theme->btn_desk->toggled_pressed_mask = RrPixmapMaskCopy(theme->btn_desk->toggled_mask); theme->btn_shade->toggled_pressed_mask = RrPixmapMaskCopy(theme->btn_shade->toggled_mask); /* read the decoration textures */ READ_APPEARANCE("window.active.title.bg", theme->a_focused_title, FALSE); READ_APPEARANCE("window.inactive.title.bg", theme->a_unfocused_title, FALSE); READ_APPEARANCE("window.active.label.bg", theme->a_focused_label, TRUE); READ_APPEARANCE("window.inactive.label.bg", theme->a_unfocused_label, TRUE); READ_APPEARANCE("window.active.handle.bg", theme->a_focused_handle, FALSE); READ_APPEARANCE("window.inactive.handle.bg",theme->a_unfocused_handle, FALSE); READ_APPEARANCE("window.active.grip.bg", theme->a_focused_grip, TRUE); READ_APPEARANCE("window.inactive.grip.bg", theme->a_unfocused_grip, TRUE); READ_APPEARANCE("menu.items.bg", theme->a_menu, FALSE); READ_APPEARANCE("menu.title.bg", theme->a_menu_title, TRUE); READ_APPEARANCE("menu.items.active.bg", theme->a_menu_selected, TRUE); theme->a_menu_disabled_selected = RrAppearanceCopy(theme->a_menu_selected); /* read appearances for non-decorations (on-screen-display) */ if (!read_appearance(db, inst, "osd.bg", theme->osd_hilite_bg, FALSE)) { RrAppearanceFree(theme->osd_hilite_bg); theme->osd_hilite_bg = RrAppearanceCopy(theme->a_focused_title); } if (!read_appearance(db, inst, "osd.label.bg", theme->osd_hilite_label, TRUE)) { RrAppearanceFree(theme->osd_hilite_label); theme->osd_hilite_label = RrAppearanceCopy(theme->a_focused_label); } /* osd_hilite_fg can't be parentrel */ if (!read_appearance(db, inst, "osd.hilight.bg", theme->osd_hilite_fg, FALSE)) { RrAppearanceFree(theme->osd_hilite_fg); if (theme->a_focused_label->surface.grad != RR_SURFACE_PARENTREL) theme->osd_hilite_fg = RrAppearanceCopy(theme->a_focused_label); else theme->osd_hilite_fg = RrAppearanceCopy(theme->a_focused_title); } /* osd_unhilite_fg can't be parentrel either */ if (!read_appearance(db, inst, "osd.unhilight.bg", theme->osd_unhilite_fg, FALSE)) { RrAppearanceFree(theme->osd_unhilite_fg); if (theme->a_unfocused_label->surface.grad != RR_SURFACE_PARENTREL) theme->osd_unhilite_fg=RrAppearanceCopy(theme->a_unfocused_label); else theme->osd_unhilite_fg=RrAppearanceCopy(theme->a_unfocused_title); } /* read buttons textures */ /* bases: unpressed, pressed, disabled */ READ_APPEARANCE("window.active.button.unpressed.bg", a_focused_unpressed_tmp, TRUE); READ_APPEARANCE("window.inactive.button.unpressed.bg", a_unfocused_unpressed_tmp, TRUE); READ_APPEARANCE("window.active.button.pressed.bg", a_focused_pressed_tmp, TRUE); READ_APPEARANCE("window.inactive.button.pressed.bg", a_unfocused_pressed_tmp, TRUE); READ_APPEARANCE("window.active.button.disabled.bg", a_disabled_focused_tmp, TRUE); READ_APPEARANCE("window.inactive.button.disabled.bg", a_disabled_unfocused_tmp, TRUE); /* hover */ READ_APPEARANCE_COPY("window.active.button.hover.bg", a_hover_focused_tmp, TRUE, a_focused_unpressed_tmp); READ_APPEARANCE_COPY("window.inactive.button.hover.bg", a_hover_unfocused_tmp, TRUE, a_unfocused_unpressed_tmp); /* toggled unpressed */ READ_APPEARANCE_("window.active.button.toggled.unpressed.bg", "window.active.button.toggled.bg", a_toggled_focused_unpressed_tmp, TRUE, a_focused_pressed_tmp); READ_APPEARANCE_("window.inactive.button.toggled.unpressed.bg", "window.inactive.button.toggled.bg", a_toggled_unfocused_unpressed_tmp, TRUE, a_unfocused_pressed_tmp); /* toggled pressed */ READ_APPEARANCE_COPY("window.active.button.toggled.pressed.bg", a_toggled_focused_pressed_tmp, TRUE, a_focused_pressed_tmp); READ_APPEARANCE_COPY("window.inactive.button.toggled.pressed.bg", a_toggled_unfocused_pressed_tmp, TRUE, a_unfocused_pressed_tmp); /* toggled hover */ READ_APPEARANCE_COPY("window.active.button.toggled.hover.bg", a_toggled_hover_focused_tmp, TRUE, a_toggled_focused_unpressed_tmp); READ_APPEARANCE_COPY("window.inactive.button.toggled.hover.bg", a_toggled_hover_unfocused_tmp, TRUE, a_toggled_unfocused_unpressed_tmp); /* now do individual buttons, if specified */ /* max button */ /* bases: unpressed, pressed, disabled */ READ_APPEARANCE_COPY("window.active.button-max.unpressed.bg", theme->btn_max->a_focused_unpressed, TRUE, a_focused_unpressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-max.unpressed.bg", theme->btn_max->a_unfocused_unpressed, TRUE, a_unfocused_unpressed_tmp); READ_APPEARANCE_COPY("window.active.button-max.pressed.bg", theme->btn_max->a_focused_pressed, TRUE, a_focused_pressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-max.pressed.bg", theme->btn_max->a_unfocused_pressed, TRUE, a_unfocused_pressed_tmp); READ_APPEARANCE_COPY("window.active.button-max.disabled.bg", theme->btn_max->a_disabled_focused, TRUE, a_disabled_focused_tmp); READ_APPEARANCE_COPY("window.inactive.button-max.disabled.bg", theme->btn_max->a_disabled_unfocused, TRUE, a_disabled_unfocused_tmp); /* hover */ READ_APPEARANCE_COPY("window.active.button-max.hover.bg", theme->btn_max->a_hover_focused, TRUE, theme->btn_max->a_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-max.hover.bg", theme->btn_max->a_hover_unfocused, TRUE, theme->btn_max->a_unfocused_unpressed); /* toggled unpressed */ READ_APPEARANCE_("window.active.button-max.toggled.unpressed.bg", "window.active.button-max.toggled.bg", theme->btn_max->a_toggled_focused_unpressed, TRUE, theme->btn_max->a_focused_pressed); READ_APPEARANCE_("window.inactive.button-max.toggled.unpressed.bg", "window.inactive.button-max.toggled.bg", theme->btn_max->a_toggled_unfocused_unpressed, TRUE, theme->btn_max->a_unfocused_pressed); /* toggled pressed */ READ_APPEARANCE_COPY("window.active.button-max.toggled.pressed.bg", theme->btn_max->a_toggled_focused_pressed, TRUE, theme->btn_max->a_focused_pressed); READ_APPEARANCE_COPY("window.inactive.button-max.toggled.pressed.bg", theme->btn_max->a_toggled_unfocused_pressed, TRUE, theme->btn_max->a_unfocused_pressed); /* toggled hover */ READ_APPEARANCE_COPY("window.active.button-max.toggled.hover.bg", theme->btn_max->a_toggled_hover_focused, TRUE, theme->btn_max->a_toggled_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-max.toggled.hover.bg", theme->btn_max->a_toggled_hover_unfocused, TRUE, theme->btn_max->a_toggled_unfocused_unpressed); /* close button */ READ_APPEARANCE_COPY("window.active.button-close.unpressed.bg", theme->btn_close->a_focused_unpressed, TRUE, a_focused_unpressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-close.unpressed.bg", theme->btn_close->a_unfocused_unpressed, TRUE, a_unfocused_unpressed_tmp); READ_APPEARANCE_COPY("window.active.button-close.pressed.bg", theme->btn_close->a_focused_pressed, TRUE, a_focused_pressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-close.pressed.bg", theme->btn_close->a_unfocused_pressed, TRUE, a_unfocused_pressed_tmp); READ_APPEARANCE_COPY("window.active.button-close.disabled.bg", theme->btn_close->a_disabled_focused, TRUE, a_disabled_focused_tmp); READ_APPEARANCE_COPY("window.inactive.button-close.disabled.bg", theme->btn_close->a_disabled_unfocused, TRUE, a_disabled_unfocused_tmp); READ_APPEARANCE_COPY("window.active.button-close.hover.bg", theme->btn_close->a_hover_focused, TRUE, theme->btn_close->a_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-close.hover.bg", theme->btn_close->a_hover_unfocused, TRUE, theme->btn_close->a_unfocused_unpressed); /* desk button */ /* bases: unpressed, pressed, disabled */ READ_APPEARANCE_COPY("window.active.button-desk.unpressed.bg", theme->btn_desk->a_focused_unpressed, TRUE, a_focused_unpressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-desk.unpressed.bg", theme->btn_desk->a_unfocused_unpressed, TRUE, a_unfocused_unpressed_tmp); READ_APPEARANCE_COPY("window.active.button-desk.pressed.bg", theme->btn_desk->a_focused_pressed, TRUE, a_focused_pressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-desk.pressed.bg", theme->btn_desk->a_unfocused_pressed, TRUE, a_unfocused_pressed_tmp); READ_APPEARANCE_COPY("window.active.button-desk.disabled.bg", theme->btn_desk->a_disabled_focused, TRUE, a_disabled_focused_tmp); READ_APPEARANCE_COPY("window.inactive.button-desk.disabled.bg", theme->btn_desk->a_disabled_unfocused, TRUE, a_disabled_unfocused_tmp); /* hover */ READ_APPEARANCE_COPY("window.active.button-desk.hover.bg", theme->btn_desk->a_hover_focused, TRUE, theme->a_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-desk.hover.bg", theme->btn_desk->a_hover_unfocused, TRUE, theme->btn_desk->a_unfocused_unpressed); /* toggled unpressed */ READ_APPEARANCE_("window.active.button-desk.toggled.unpressed.bg", "window.active.button-desk.toggled.bg", theme->btn_desk->a_toggled_focused_unpressed, TRUE, theme->btn_desk->a_focused_pressed); READ_APPEARANCE_("window.inactive.button-desk.toggled.unpressed.bg", "window.inactive.button-desk.toggled.bg", theme->btn_desk->a_toggled_unfocused_unpressed, TRUE, theme->btn_desk->a_unfocused_pressed); /* toggled pressed */ READ_APPEARANCE_COPY("window.active.button-desk.toggled.pressed.bg", theme->btn_desk->a_toggled_focused_pressed, TRUE, theme->btn_desk->a_focused_pressed); READ_APPEARANCE_COPY("window.inactive.button-desk.toggled.pressed.bg", theme->btn_desk->a_toggled_unfocused_pressed, TRUE, theme->btn_desk->a_unfocused_pressed); /* toggled hover */ READ_APPEARANCE_COPY("window.active.button-desk.toggled.hover.bg", theme->btn_desk->a_toggled_hover_focused, TRUE, theme->btn_desk->a_toggled_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-desk.toggled.hover.bg", theme->btn_desk->a_toggled_hover_unfocused, TRUE, theme->btn_desk->a_toggled_unfocused_unpressed); /* shade button */ /* bases: unpressed, pressed, disabled */ READ_APPEARANCE_COPY("window.active.button-shade.unpressed.bg", theme->btn_shade->a_focused_unpressed, TRUE, a_focused_unpressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-shade.unpressed.bg", theme->btn_shade->a_unfocused_unpressed, TRUE, a_unfocused_unpressed_tmp); READ_APPEARANCE_COPY("window.active.button-shade.pressed.bg", theme->btn_shade->a_focused_pressed, TRUE, a_focused_pressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-shade.pressed.bg", theme->btn_shade->a_unfocused_pressed, TRUE, a_unfocused_pressed_tmp); READ_APPEARANCE_COPY("window.active.button-shade.disabled.bg", theme->btn_shade->a_disabled_focused, TRUE, a_disabled_focused_tmp); READ_APPEARANCE_COPY("window.inactive.button-shade.disabled.bg", theme->btn_shade->a_disabled_unfocused, TRUE, a_disabled_unfocused_tmp); /* hover */ READ_APPEARANCE_COPY("window.active.button-shade.hover.bg", theme->btn_shade->a_hover_focused, TRUE, theme->btn_shade->a_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-shade.hover.bg", theme->btn_shade->a_hover_unfocused, TRUE, theme->btn_shade->a_unfocused_unpressed); /* toggled unpressed */ READ_APPEARANCE_("window.active.button-shade.toggled.unpressed.bg", "window.active.button-shade.toggled.bg", theme->btn_shade->a_toggled_focused_unpressed, TRUE, theme->btn_shade->a_focused_pressed); READ_APPEARANCE_("window.inactive.button-shade.toggled.unpressed.bg", "window.inactive.button-shade.toggled.bg", theme->btn_shade->a_toggled_unfocused_unpressed, TRUE, theme->btn_shade->a_unfocused_pressed); /* toggled pressed */ READ_APPEARANCE_COPY("window.active.button-shade.toggled.pressed.bg", theme->btn_shade->a_toggled_focused_pressed, TRUE, theme->btn_shade->a_focused_pressed); READ_APPEARANCE_COPY("window.inactive.button-shade.toggled.pressed.bg", theme->btn_shade->a_toggled_unfocused_pressed, TRUE, theme->btn_shade->a_unfocused_pressed); /* toggled hover */ READ_APPEARANCE_COPY("window.active.button-shade.toggled.hover.bg", theme->btn_shade->a_toggled_hover_focused, TRUE, theme->btn_shade->a_toggled_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-shade.toggled.hover.bg", theme->btn_shade->a_toggled_hover_unfocused, TRUE, theme->btn_shade->a_toggled_unfocused_unpressed); /* iconify button */ READ_APPEARANCE_COPY("window.active.button-iconify.unpressed.bg", theme->btn_iconify->a_focused_unpressed, TRUE, a_focused_unpressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-iconify.unpressed.bg", theme->btn_iconify->a_unfocused_unpressed, TRUE, a_unfocused_unpressed_tmp); READ_APPEARANCE_COPY("window.active.button-iconify.pressed.bg", theme->btn_iconify->a_focused_pressed, TRUE, a_focused_pressed_tmp); READ_APPEARANCE_COPY("window.inactive.button-iconify.pressed.bg", theme->btn_iconify->a_unfocused_pressed, TRUE, a_unfocused_pressed_tmp); READ_APPEARANCE_COPY("window.active.button-iconify.disabled.bg", theme->btn_iconify->a_disabled_focused, TRUE, a_disabled_focused_tmp); READ_APPEARANCE_COPY("window.inactive.button-iconify.disabled.bg", theme->btn_iconify->a_disabled_unfocused, TRUE, a_disabled_unfocused_tmp); READ_APPEARANCE_COPY("window.active.button-iconify.hover.bg", theme->btn_iconify->a_hover_focused, TRUE, theme->btn_iconify->a_focused_unpressed); READ_APPEARANCE_COPY("window.inactive.button-iconify.hover.bg", theme->btn_iconify->a_hover_unfocused, TRUE, theme->btn_iconify->a_unfocused_unpressed); theme->a_icon->surface.grad = theme->a_clear->surface.grad = theme->a_clear_tex->surface.grad = theme->a_menu_text_title->surface.grad = theme->a_menu_normal->surface.grad = theme->a_menu_disabled->surface.grad = theme->a_menu_text_normal->surface.grad = theme->a_menu_text_selected->surface.grad = theme->a_menu_text_disabled->surface.grad = theme->a_menu_text_disabled_selected->surface.grad = theme->a_menu_bullet_normal->surface.grad = theme->a_menu_bullet_selected->surface.grad = RR_SURFACE_PARENTREL; /* set up the textures */ theme->a_focused_label->texture[0].type = RR_TEXTURE_TEXT; theme->a_focused_label->texture[0].data.text.justify = winjust; theme->a_focused_label->texture[0].data.text.font=theme->win_font_focused; theme->a_focused_label->texture[0].data.text.color = theme->title_focused_color; if (read_string(db, "window.active.label.text.font", &str)) { char *p; gint i = 0; gint j; if (strstr(str, "shadow=y")) { if ((p = strstr(str, "shadowoffset="))) i = parse_inline_number(p + strlen("shadowoffset=")); else i = 1; theme->a_focused_label->texture[0].data.text.shadow_offset_x = i; theme->a_focused_label->texture[0].data.text.shadow_offset_y = i; } if ((p = strstr(str, "shadowtint="))) { i = parse_inline_number(p + strlen("shadowtint=")); j = (i > 0 ? 0 : 255); i = ABS(i*255/100); theme->title_focused_shadow_color = RrColorNew(inst, j, j, j); theme->title_focused_shadow_alpha = i; } else { theme->title_focused_shadow_color = RrColorNew(inst, 0, 0, 0); theme->title_focused_shadow_alpha = 50; } } theme->a_focused_label->texture[0].data.text.shadow_color = theme->title_focused_shadow_color; theme->a_focused_label->texture[0].data.text.shadow_alpha = theme->title_focused_shadow_alpha; theme->osd_hilite_label->texture[0].type = RR_TEXTURE_TEXT; theme->osd_hilite_label->texture[0].data.text.justify = RR_JUSTIFY_LEFT; theme->osd_hilite_label->texture[0].data.text.font = theme->osd_font; theme->osd_hilite_label->texture[0].data.text.color = theme->osd_color; if (read_string(db, "osd.label.text.font", &str)) { char *p; gint i = 0; gint j; if (strstr(str, "shadow=y")) { if ((p = strstr(str, "shadowoffset="))) i = parse_inline_number(p + strlen("shadowoffset=")); else i = 1; theme->a_focused_label->texture[0].data.text.shadow_offset_x = i; theme->a_focused_label->texture[0].data.text.shadow_offset_y = i; theme->osd_hilite_label->texture[0].data.text.shadow_offset_x = i; theme->osd_hilite_label->texture[0].data.text.shadow_offset_y = i; } if ((p = strstr(str, "shadowtint="))) { i = parse_inline_number(p + strlen("shadowtint=")); j = (i > 0 ? 0 : 255); i = ABS(i*255/100); theme->title_focused_shadow_color = RrColorNew(inst, j, j, j); theme->title_focused_shadow_alpha = i; theme->osd_shadow_color = RrColorNew(inst, j, j, j); theme->osd_shadow_alpha = i; } else { theme->title_focused_shadow_color = RrColorNew(inst, 0, 0, 0); theme->title_focused_shadow_alpha = 50; theme->osd_shadow_color = RrColorNew(inst, 0, 0, 0); theme->osd_shadow_alpha = 50; } } else { /* inherit the font settings from the focused label */ theme->osd_hilite_label->texture[0].data.text.shadow_offset_x = theme->a_focused_label->texture[0].data.text.shadow_offset_x; theme->osd_hilite_label->texture[0].data.text.shadow_offset_y = theme->a_focused_label->texture[0].data.text.shadow_offset_y; if (theme->title_focused_shadow_color) theme->osd_shadow_color = RrColorNew(inst, theme->title_focused_shadow_color->r, theme->title_focused_shadow_color->g, theme->title_focused_shadow_color->b); else theme->osd_shadow_color = RrColorNew(inst, 0, 0, 0); theme->osd_shadow_alpha = theme->title_focused_shadow_alpha; } theme->osd_hilite_label->texture[0].data.text.shadow_color = theme->osd_shadow_color; theme->osd_hilite_label->texture[0].data.text.shadow_alpha = theme->osd_shadow_alpha; theme->a_unfocused_label->texture[0].type = RR_TEXTURE_TEXT; theme->a_unfocused_label->texture[0].data.text.justify = winjust; theme->a_unfocused_label->texture[0].data.text.font = theme->win_font_unfocused; theme->a_unfocused_label->texture[0].data.text.color = theme->title_unfocused_color; if (read_string(db, "window.inactive.label.text.font", &str)) { char *p; gint i = 0; gint j; if (strstr(str, "shadow=y")) { if ((p = strstr(str, "shadowoffset="))) i = parse_inline_number(p + strlen("shadowoffset=")); else i = 1; theme->a_unfocused_label->texture[0].data.text.shadow_offset_x = i; theme->a_unfocused_label->texture[0].data.text.shadow_offset_y = i; } if ((p = strstr(str, "shadowtint="))) { i = parse_inline_number(p + strlen("shadowtint=")); j = (i > 0 ? 0 : 255); i = ABS(i*255/100); theme->title_unfocused_shadow_color = RrColorNew(inst, j, j, j); theme->title_unfocused_shadow_alpha = i; } else { theme->title_unfocused_shadow_color = RrColorNew(inst, 0, 0, 0); theme->title_unfocused_shadow_alpha = 50; } } theme->a_unfocused_label->texture[0].data.text.shadow_color = theme->title_unfocused_shadow_color; theme->a_unfocused_label->texture[0].data.text.shadow_alpha = theme->title_unfocused_shadow_alpha; theme->a_menu_text_title->texture[0].type = RR_TEXTURE_TEXT; theme->a_menu_text_title->texture[0].data.text.justify = mtitlejust; theme->a_menu_text_title->texture[0].data.text.font = theme->menu_title_font; theme->a_menu_text_title->texture[0].data.text.color = theme->menu_title_color; if (read_string(db, "menu.title.text.font", &str)) { char *p; gint i = 0; gint j; if (strstr(str, "shadow=y")) { if ((p = strstr(str, "shadowoffset="))) i = parse_inline_number(p + strlen("shadowoffset=")); else i = 1; theme->a_menu_text_title->texture[0].data.text.shadow_offset_x = i; theme->a_menu_text_title->texture[0].data.text.shadow_offset_y = i; } if ((p = strstr(str, "shadowtint="))) { i = parse_inline_number(p + strlen("shadowtint=")); j = (i > 0 ? 0 : 255); i = ABS(i*255/100); theme->menu_title_shadow_color = RrColorNew(inst, j, j, j); theme->menu_title_shadow_alpha = i; } else { theme->menu_title_shadow_color = RrColorNew(inst, 0, 0, 0); theme->menu_title_shadow_alpha = 50; } } theme->a_menu_text_title->texture[0].data.text.shadow_color = theme->menu_title_shadow_color; theme->a_menu_text_title->texture[0].data.text.shadow_alpha = theme->menu_title_shadow_alpha; theme->a_menu_text_normal->texture[0].type = theme->a_menu_text_selected->texture[0].type = theme->a_menu_text_disabled->texture[0].type = theme->a_menu_text_disabled_selected->texture[0].type = RR_TEXTURE_TEXT; theme->a_menu_text_normal->texture[0].data.text.justify = theme->a_menu_text_selected->texture[0].data.text.justify = theme->a_menu_text_disabled->texture[0].data.text.justify = theme->a_menu_text_disabled_selected->texture[0].data.text.justify = RR_JUSTIFY_LEFT; theme->a_menu_text_normal->texture[0].data.text.font = theme->a_menu_text_selected->texture[0].data.text.font = theme->a_menu_text_disabled->texture[0].data.text.font = theme->a_menu_text_disabled_selected->texture[0].data.text.font = theme->menu_font; theme->a_menu_text_normal->texture[0].data.text.color = theme->menu_color; theme->a_menu_text_selected->texture[0].data.text.color = theme->menu_selected_color; theme->a_menu_text_disabled->texture[0].data.text.color = theme->menu_disabled_color; theme->a_menu_text_disabled_selected->texture[0].data.text.color = theme->menu_disabled_selected_color; if (read_string(db, "menu.items.font", &str)) { char *p; gint i = 0; gint j; if (strstr(str, "shadow=y")) { if ((p = strstr(str, "shadowoffset="))) i = parse_inline_number(p + strlen("shadowoffset=")); else i = 1; theme->a_menu_text_normal-> texture[0].data.text.shadow_offset_x = i; theme->a_menu_text_normal-> texture[0].data.text.shadow_offset_y = i; theme->a_menu_text_selected-> texture[0].data.text.shadow_offset_x = i; theme->a_menu_text_selected-> texture[0].data.text.shadow_offset_y = i; theme->a_menu_text_disabled-> texture[0].data.text.shadow_offset_x = i; theme->a_menu_text_disabled-> texture[0].data.text.shadow_offset_y = i; theme->a_menu_text_disabled_selected-> texture[0].data.text.shadow_offset_x = i; theme->a_menu_text_disabled_selected-> texture[0].data.text.shadow_offset_y = i; } if ((p = strstr(str, "shadowtint="))) { i = parse_inline_number(p + strlen("shadowtint=")); j = (i > 0 ? 0 : 255); i = ABS(i*255/100); theme->menu_text_normal_shadow_color = RrColorNew(inst, j, j, j); theme->menu_text_selected_shadow_color = RrColorNew(inst, j, j, j); theme->menu_text_disabled_shadow_color = RrColorNew(inst, j, j, j); theme->menu_text_normal_shadow_alpha = i; theme->menu_text_selected_shadow_alpha = i; theme->menu_text_disabled_shadow_alpha = i; theme->menu_text_disabled_selected_shadow_alpha = i; } else { theme->menu_text_normal_shadow_color = RrColorNew(inst, 0, 0, 0); theme->menu_text_selected_shadow_color = RrColorNew(inst, 0, 0, 0); theme->menu_text_disabled_shadow_color = RrColorNew(inst, 0, 0, 0); theme->menu_text_normal_shadow_alpha = 50; theme->menu_text_selected_shadow_alpha = 50; theme->menu_text_disabled_selected_shadow_alpha = 50; } } theme->a_menu_text_normal->texture[0].data.text.shadow_color = theme->menu_text_normal_shadow_color; theme->a_menu_text_normal->texture[0].data.text.shadow_alpha = theme->menu_text_normal_shadow_alpha; theme->a_menu_text_selected->texture[0].data.text.shadow_color = theme->menu_text_selected_shadow_color; theme->a_menu_text_selected->texture[0].data.text.shadow_alpha = theme->menu_text_selected_shadow_alpha; theme->a_menu_text_disabled->texture[0].data.text.shadow_color = theme->menu_text_disabled_shadow_color; theme->a_menu_text_disabled->texture[0].data.text.shadow_alpha = theme->menu_text_disabled_shadow_alpha; theme->a_menu_text_disabled_selected->texture[0].data.text.shadow_color = theme->menu_text_disabled_shadow_color; theme->a_menu_text_disabled_selected->texture[0].data.text.shadow_alpha = theme->menu_text_disabled_shadow_alpha; theme->a_disabled_focused_max->texture[0].type = theme->a_disabled_unfocused_max->texture[0].type = theme->a_hover_focused_max->texture[0].type = theme->a_hover_unfocused_max->texture[0].type = theme->a_toggled_hover_focused_max->texture[0].type = theme->a_toggled_hover_unfocused_max->texture[0].type = theme->a_toggled_focused_unpressed_max->texture[0].type = theme->a_toggled_unfocused_unpressed_max->texture[0].type = theme->a_toggled_focused_pressed_max->texture[0].type = theme->a_toggled_unfocused_pressed_max->texture[0].type = theme->a_focused_unpressed_max->texture[0].type = theme->a_focused_pressed_max->texture[0].type = theme->a_unfocused_unpressed_max->texture[0].type = theme->a_unfocused_pressed_max->texture[0].type = theme->a_disabled_focused_close->texture[0].type = theme->a_disabled_unfocused_close->texture[0].type = theme->a_hover_focused_close->texture[0].type = theme->a_hover_unfocused_close->texture[0].type = theme->a_focused_unpressed_close->texture[0].type = theme->a_focused_pressed_close->texture[0].type = theme->a_unfocused_unpressed_close->texture[0].type = theme->a_unfocused_pressed_close->texture[0].type = theme->a_disabled_focused_desk->texture[0].type = theme->a_disabled_unfocused_desk->texture[0].type = theme->a_hover_focused_desk->texture[0].type = theme->a_hover_unfocused_desk->texture[0].type = theme->a_toggled_hover_focused_desk->texture[0].type = theme->a_toggled_hover_unfocused_desk->texture[0].type = theme->a_toggled_focused_unpressed_desk->texture[0].type = theme->a_toggled_unfocused_unpressed_desk->texture[0].type = theme->a_toggled_focused_pressed_desk->texture[0].type = theme->a_toggled_unfocused_pressed_desk->texture[0].type = theme->a_focused_unpressed_desk->texture[0].type = theme->a_focused_pressed_desk->texture[0].type = theme->a_unfocused_unpressed_desk->texture[0].type = theme->a_unfocused_pressed_desk->texture[0].type = theme->a_disabled_focused_shade->texture[0].type = theme->a_disabled_unfocused_shade->texture[0].type = theme->a_hover_focused_shade->texture[0].type = theme->a_hover_unfocused_shade->texture[0].type = theme->a_toggled_hover_focused_shade->texture[0].type = theme->a_toggled_hover_unfocused_shade->texture[0].type = theme->a_toggled_focused_unpressed_shade->texture[0].type = theme->a_toggled_unfocused_unpressed_shade->texture[0].type = theme->a_toggled_focused_pressed_shade->texture[0].type = theme->a_toggled_unfocused_pressed_shade->texture[0].type = theme->a_focused_unpressed_shade->texture[0].type = theme->a_focused_pressed_shade->texture[0].type = theme->a_unfocused_unpressed_shade->texture[0].type = theme->a_unfocused_pressed_shade->texture[0].type = theme->a_disabled_focused_iconify->texture[0].type = theme->a_disabled_unfocused_iconify->texture[0].type = theme->a_hover_focused_iconify->texture[0].type = theme->a_hover_unfocused_iconify->texture[0].type = theme->a_focused_unpressed_iconify->texture[0].type = theme->a_focused_pressed_iconify->texture[0].type = theme->a_unfocused_unpressed_iconify->texture[0].type = theme->a_unfocused_pressed_iconify->texture[0].type = theme->a_menu_bullet_normal->texture[0].type = theme->a_menu_bullet_selected->texture[0].type = RR_TEXTURE_MASK; theme->a_disabled_focused_max->texture[0].data.mask.mask = theme->a_disabled_unfocused_max->texture[0].data.mask.mask = theme->max_disabled_mask; theme->a_hover_focused_max->texture[0].data.mask.mask = theme->a_hover_unfocused_max->texture[0].data.mask.mask = theme->max_hover_mask; theme->a_focused_pressed_max->texture[0].data.mask.mask = theme->a_unfocused_pressed_max->texture[0].data.mask.mask = theme->max_pressed_mask; theme->a_focused_unpressed_max->texture[0].data.mask.mask = theme->a_unfocused_unpressed_max->texture[0].data.mask.mask = theme->max_mask; theme->a_toggled_hover_focused_max->texture[0].data.mask.mask = theme->a_toggled_hover_unfocused_max->texture[0].data.mask.mask = theme->max_toggled_hover_mask; theme->a_toggled_focused_unpressed_max->texture[0].data.mask.mask = theme->a_toggled_unfocused_unpressed_max->texture[0].data.mask.mask = theme->max_toggled_mask; theme->a_toggled_focused_pressed_max->texture[0].data.mask.mask = theme->a_toggled_unfocused_pressed_max->texture[0].data.mask.mask = theme->max_toggled_pressed_mask; theme->a_disabled_focused_close->texture[0].data.mask.mask = theme->a_disabled_unfocused_close->texture[0].data.mask.mask = theme->close_disabled_mask; theme->a_hover_focused_close->texture[0].data.mask.mask = theme->a_hover_unfocused_close->texture[0].data.mask.mask = theme->close_hover_mask; theme->a_focused_pressed_close->texture[0].data.mask.mask = theme->a_unfocused_pressed_close->texture[0].data.mask.mask = theme->close_pressed_mask; theme->a_focused_unpressed_close->texture[0].data.mask.mask = theme->a_unfocused_unpressed_close->texture[0].data.mask.mask = theme->close_mask; theme->a_disabled_focused_desk->texture[0].data.mask.mask = theme->a_disabled_unfocused_desk->texture[0].data.mask.mask = theme->desk_disabled_mask; theme->a_hover_focused_desk->texture[0].data.mask.mask = theme->a_hover_unfocused_desk->texture[0].data.mask.mask = theme->desk_hover_mask; theme->a_focused_pressed_desk->texture[0].data.mask.mask = theme->a_unfocused_pressed_desk->texture[0].data.mask.mask = theme->desk_pressed_mask; theme->a_focused_unpressed_desk->texture[0].data.mask.mask = theme->a_unfocused_unpressed_desk->texture[0].data.mask.mask = theme->desk_mask; theme->a_toggled_hover_focused_desk->texture[0].data.mask.mask = theme->a_toggled_hover_unfocused_desk->texture[0].data.mask.mask = theme->desk_toggled_hover_mask; theme->a_toggled_focused_unpressed_desk->texture[0].data.mask.mask = theme->a_toggled_unfocused_unpressed_desk->texture[0].data.mask.mask = theme->desk_toggled_mask; theme->a_toggled_focused_pressed_desk->texture[0].data.mask.mask = theme->a_toggled_unfocused_pressed_desk->texture[0].data.mask.mask = theme->desk_toggled_pressed_mask; theme->a_disabled_focused_shade->texture[0].data.mask.mask = theme->a_disabled_unfocused_shade->texture[0].data.mask.mask = theme->shade_disabled_mask; theme->a_hover_focused_shade->texture[0].data.mask.mask = theme->a_hover_unfocused_shade->texture[0].data.mask.mask = theme->shade_hover_mask; theme->a_focused_pressed_shade->texture[0].data.mask.mask = theme->a_unfocused_pressed_shade->texture[0].data.mask.mask = theme->shade_pressed_mask; theme->a_focused_unpressed_shade->texture[0].data.mask.mask = theme->a_unfocused_unpressed_shade->texture[0].data.mask.mask = theme->shade_mask; theme->a_toggled_hover_focused_shade->texture[0].data.mask.mask = theme->a_toggled_hover_unfocused_shade->texture[0].data.mask.mask = theme->shade_toggled_hover_mask; theme->a_toggled_focused_unpressed_shade->texture[0].data.mask.mask = theme->a_toggled_unfocused_unpressed_shade->texture[0].data.mask.mask = theme->shade_toggled_mask; theme->a_toggled_focused_pressed_shade->texture[0].data.mask.mask = theme->a_toggled_unfocused_pressed_shade->texture[0].data.mask.mask = theme->shade_toggled_pressed_mask; theme->a_disabled_focused_iconify->texture[0].data.mask.mask = theme->a_disabled_unfocused_iconify->texture[0].data.mask.mask = theme->iconify_disabled_mask; theme->a_hover_focused_iconify->texture[0].data.mask.mask = theme->a_hover_unfocused_iconify->texture[0].data.mask.mask = theme->iconify_hover_mask; theme->a_focused_pressed_iconify->texture[0].data.mask.mask = theme->a_unfocused_pressed_iconify->texture[0].data.mask.mask = theme->iconify_pressed_mask; theme->a_focused_unpressed_iconify->texture[0].data.mask.mask = theme->a_unfocused_unpressed_iconify->texture[0].data.mask.mask = theme->iconify_mask; theme->a_menu_bullet_normal->texture[0].data.mask.mask = theme->a_menu_bullet_selected->texture[0].data.mask.mask = theme->menu_bullet_mask; theme->a_disabled_focused_max->texture[0].data.mask.color = theme->a_disabled_focused_close->texture[0].data.mask.color = theme->a_disabled_focused_desk->texture[0].data.mask.color = theme->a_disabled_focused_shade->texture[0].data.mask.color = theme->a_disabled_focused_iconify->texture[0].data.mask.color = theme->titlebut_disabled_focused_color; theme->a_disabled_unfocused_max->texture[0].data.mask.color = theme->a_disabled_unfocused_close->texture[0].data.mask.color = theme->a_disabled_unfocused_desk->texture[0].data.mask.color = theme->a_disabled_unfocused_shade->texture[0].data.mask.color = theme->a_disabled_unfocused_iconify->texture[0].data.mask.color = theme->titlebut_disabled_unfocused_color; theme->a_hover_focused_max->texture[0].data.mask.color = theme->a_hover_focused_close->texture[0].data.mask.color = theme->a_hover_focused_desk->texture[0].data.mask.color = theme->a_hover_focused_shade->texture[0].data.mask.color = theme->a_hover_focused_iconify->texture[0].data.mask.color = theme->titlebut_hover_focused_color; theme->a_hover_unfocused_max->texture[0].data.mask.color = theme->a_hover_unfocused_close->texture[0].data.mask.color = theme->a_hover_unfocused_desk->texture[0].data.mask.color = theme->a_hover_unfocused_shade->texture[0].data.mask.color = theme->a_hover_unfocused_iconify->texture[0].data.mask.color = theme->titlebut_hover_unfocused_color; theme->a_toggled_hover_focused_max->texture[0].data.mask.color = theme->a_toggled_hover_focused_desk->texture[0].data.mask.color = theme->a_toggled_hover_focused_shade->texture[0].data.mask.color = theme->titlebut_toggled_hover_focused_color; theme->a_toggled_hover_unfocused_max->texture[0].data.mask.color = theme->a_toggled_hover_unfocused_desk->texture[0].data.mask.color = theme->a_toggled_hover_unfocused_shade->texture[0].data.mask.color = theme->titlebut_toggled_hover_unfocused_color; theme->a_toggled_focused_unpressed_max->texture[0].data.mask.color = theme->a_toggled_focused_unpressed_desk->texture[0].data.mask.color = theme->a_toggled_focused_unpressed_shade->texture[0].data.mask.color = theme->titlebut_toggled_focused_unpressed_color; theme->a_toggled_unfocused_unpressed_max->texture[0].data.mask.color = theme->a_toggled_unfocused_unpressed_desk->texture[0].data.mask.color = theme->a_toggled_unfocused_unpressed_shade->texture[0].data.mask.color= theme->titlebut_toggled_unfocused_unpressed_color; theme->a_toggled_focused_pressed_max->texture[0].data.mask.color = theme->a_toggled_focused_pressed_desk->texture[0].data.mask.color = theme->a_toggled_focused_pressed_shade->texture[0].data.mask.color = theme->titlebut_toggled_focused_pressed_color; theme->a_toggled_unfocused_pressed_max->texture[0].data.mask.color = theme->a_toggled_unfocused_pressed_desk->texture[0].data.mask.color = theme->a_toggled_unfocused_pressed_shade->texture[0].data.mask.color = theme->titlebut_toggled_unfocused_pressed_color; theme->a_focused_unpressed_max->texture[0].data.mask.color = theme->a_focused_unpressed_close->texture[0].data.mask.color = theme->a_focused_unpressed_desk->texture[0].data.mask.color = theme->a_focused_unpressed_shade->texture[0].data.mask.color = theme->a_focused_unpressed_iconify->texture[0].data.mask.color = theme->titlebut_focused_unpressed_color; theme->a_focused_pressed_max->texture[0].data.mask.color = theme->a_focused_pressed_close->texture[0].data.mask.color = theme->a_focused_pressed_desk->texture[0].data.mask.color = theme->a_focused_pressed_shade->texture[0].data.mask.color = theme->a_focused_pressed_iconify->texture[0].data.mask.color = theme->titlebut_focused_pressed_color; theme->a_unfocused_unpressed_max->texture[0].data.mask.color = theme->a_unfocused_unpressed_close->texture[0].data.mask.color = theme->a_unfocused_unpressed_desk->texture[0].data.mask.color = theme->a_unfocused_unpressed_shade->texture[0].data.mask.color = theme->a_unfocused_unpressed_iconify->texture[0].data.mask.color = theme->titlebut_unfocused_unpressed_color; theme->a_unfocused_pressed_max->texture[0].data.mask.color = theme->a_unfocused_pressed_close->texture[0].data.mask.color = theme->a_unfocused_pressed_desk->texture[0].data.mask.color = theme->a_unfocused_pressed_shade->texture[0].data.mask.color = theme->a_unfocused_pressed_iconify->texture[0].data.mask.color = theme->titlebut_unfocused_pressed_color; theme->a_menu_bullet_normal->texture[0].data.mask.color = theme->menu_color; theme->a_menu_bullet_selected->texture[0].data.mask.color = theme->menu_selected_color; g_free(path); XrmDestroyDatabase(db); /* set the font heights */ theme->win_font_height = RrFontHeight (theme->win_font_focused, theme->a_focused_label->texture[0].data.text.shadow_offset_y); theme->win_font_height = MAX(theme->win_font_height, RrFontHeight (theme->win_font_focused, theme->a_unfocused_label->texture[0].data.text.shadow_offset_y)); theme->menu_title_font_height = RrFontHeight (theme->menu_title_font, theme->a_menu_text_title->texture[0].data.text.shadow_offset_y); theme->menu_font_height = RrFontHeight (theme->menu_font, theme->a_menu_text_normal->texture[0].data.text.shadow_offset_y); /* calculate some last extents */ { gint ft, fb, fl, fr, ut, ub, ul, ur; RrMargins(theme->a_focused_label, &fl, &ft, &fr, &fb); RrMargins(theme->a_unfocused_label, &ul, &ut, &ur, &ub); theme->label_height = theme->win_font_height + MAX(ft + fb, ut + ub); theme->label_height += theme->label_height % 2; /* this would be nice I think, since padding.width can now be 0, but it breaks frame.c horribly and I don't feel like fixing that right now, so if anyone complains, here is how to keep text from going over the title's bevel/border with a padding.width of 0 and a bevelless/borderless label RrMargins(theme->a_focused_title, &fl, &ft, &fr, &fb); RrMargins(theme->a_unfocused_title, &ul, &ut, &ur, &ub); theme->title_height = theme->label_height + MAX(MAX(theme->padding * 2, ft + fb), MAX(theme->padding * 2, ut + ub)); */ theme->title_height = theme->label_height + theme->paddingy * 2; RrMargins(theme->a_menu_title, &ul, &ut, &ur, &ub); theme->menu_title_label_height = theme->menu_title_font_height+ut+ub; theme->menu_title_height = theme->menu_title_label_height + theme->paddingy * 2; } theme->button_size = theme->label_height - 2; theme->grip_width = 25; RrAppearanceFree(a_disabled_focused_tmp); RrAppearanceFree(a_disabled_unfocused_tmp); RrAppearanceFree(a_hover_focused_tmp); RrAppearanceFree(a_hover_unfocused_tmp); RrAppearanceFree(a_focused_unpressed_tmp); RrAppearanceFree(a_focused_pressed_tmp); RrAppearanceFree(a_unfocused_unpressed_tmp); RrAppearanceFree(a_unfocused_pressed_tmp); RrAppearanceFree(a_toggled_hover_focused_tmp); RrAppearanceFree(a_toggled_hover_unfocused_tmp); RrAppearanceFree(a_toggled_focused_unpressed_tmp); RrAppearanceFree(a_toggled_focused_pressed_tmp); RrAppearanceFree(a_toggled_unfocused_unpressed_tmp); RrAppearanceFree(a_toggled_unfocused_pressed_tmp); return theme; } void RrThemeFree(RrTheme *theme) { if (theme) { g_free(theme->name); RrColorFree(theme->menu_border_color); RrColorFree(theme->osd_border_color); RrColorFree(theme->frame_focused_border_color); RrColorFree(theme->frame_unfocused_border_color); RrColorFree(theme->title_separator_focused_color); RrColorFree(theme->title_separator_unfocused_color); RrColorFree(theme->cb_unfocused_color); RrColorFree(theme->cb_focused_color); RrColorFree(theme->title_focused_color); RrColorFree(theme->title_unfocused_color); RrColorFree(theme->titlebut_disabled_focused_color); RrColorFree(theme->titlebut_disabled_unfocused_color); RrColorFree(theme->titlebut_hover_focused_color); RrColorFree(theme->titlebut_hover_unfocused_color); RrColorFree(theme->titlebut_toggled_hover_focused_color); RrColorFree(theme->titlebut_toggled_hover_unfocused_color); RrColorFree(theme->titlebut_toggled_focused_pressed_color); RrColorFree(theme->titlebut_toggled_unfocused_pressed_color); RrColorFree(theme->titlebut_toggled_focused_unpressed_color); RrColorFree(theme->titlebut_toggled_unfocused_unpressed_color); RrColorFree(theme->titlebut_focused_pressed_color); RrColorFree(theme->titlebut_unfocused_pressed_color); RrColorFree(theme->titlebut_focused_unpressed_color); RrColorFree(theme->titlebut_unfocused_unpressed_color); RrColorFree(theme->menu_title_color); RrColorFree(theme->menu_color); RrColorFree(theme->menu_selected_color); RrColorFree(theme->menu_disabled_color); RrColorFree(theme->menu_disabled_selected_color); RrColorFree(theme->title_focused_shadow_color); RrColorFree(theme->title_unfocused_shadow_color); RrColorFree(theme->osd_color); RrColorFree(theme->osd_shadow_color); RrColorFree(theme->menu_title_shadow_color); RrColorFree(theme->menu_text_normal_shadow_color); RrColorFree(theme->menu_text_selected_shadow_color); RrColorFree(theme->menu_text_disabled_shadow_color); RrColorFree(theme->menu_text_disabled_selected_shadow_color); g_free(theme->def_win_icon); RrPixmapMaskFree(theme->max_mask); RrPixmapMaskFree(theme->max_toggled_mask); RrPixmapMaskFree(theme->max_toggled_hover_mask); RrPixmapMaskFree(theme->max_toggled_pressed_mask); RrPixmapMaskFree(theme->max_disabled_mask); RrPixmapMaskFree(theme->max_hover_mask); RrPixmapMaskFree(theme->max_pressed_mask); RrPixmapMaskFree(theme->desk_mask); RrPixmapMaskFree(theme->desk_toggled_mask); RrPixmapMaskFree(theme->desk_toggled_hover_mask); RrPixmapMaskFree(theme->desk_toggled_pressed_mask); RrPixmapMaskFree(theme->desk_disabled_mask); RrPixmapMaskFree(theme->desk_hover_mask); RrPixmapMaskFree(theme->desk_pressed_mask); RrPixmapMaskFree(theme->shade_mask); RrPixmapMaskFree(theme->shade_toggled_mask); RrPixmapMaskFree(theme->shade_toggled_hover_mask); RrPixmapMaskFree(theme->shade_toggled_pressed_mask); RrPixmapMaskFree(theme->shade_disabled_mask); RrPixmapMaskFree(theme->shade_hover_mask); RrPixmapMaskFree(theme->shade_pressed_mask); RrPixmapMaskFree(theme->iconify_mask); RrPixmapMaskFree(theme->iconify_disabled_mask); RrPixmapMaskFree(theme->iconify_hover_mask); RrPixmapMaskFree(theme->iconify_pressed_mask); RrPixmapMaskFree(theme->close_mask); RrPixmapMaskFree(theme->close_disabled_mask); RrPixmapMaskFree(theme->close_hover_mask); RrPixmapMaskFree(theme->close_pressed_mask); RrPixmapMaskFree(theme->menu_bullet_mask); RrFontClose(theme->win_font_focused); RrFontClose(theme->win_font_unfocused); RrFontClose(theme->menu_title_font); RrFontClose(theme->menu_font); RrAppearanceFree(theme->a_disabled_focused_max); RrAppearanceFree(theme->a_disabled_unfocused_max); RrAppearanceFree(theme->a_hover_focused_max); RrAppearanceFree(theme->a_hover_unfocused_max); RrAppearanceFree(theme->a_toggled_hover_focused_max); RrAppearanceFree(theme->a_toggled_hover_unfocused_max); RrAppearanceFree(theme->a_toggled_focused_unpressed_max); RrAppearanceFree(theme->a_toggled_focused_pressed_max); RrAppearanceFree(theme->a_toggled_unfocused_unpressed_max); RrAppearanceFree(theme->a_toggled_unfocused_pressed_max); RrAppearanceFree(theme->a_focused_unpressed_max); RrAppearanceFree(theme->a_focused_pressed_max); RrAppearanceFree(theme->a_unfocused_unpressed_max); RrAppearanceFree(theme->a_unfocused_pressed_max); RrAppearanceFree(theme->a_disabled_focused_close); RrAppearanceFree(theme->a_disabled_unfocused_close); RrAppearanceFree(theme->a_hover_focused_close); RrAppearanceFree(theme->a_hover_unfocused_close); RrAppearanceFree(theme->a_focused_unpressed_close); RrAppearanceFree(theme->a_focused_pressed_close); RrAppearanceFree(theme->a_unfocused_unpressed_close); RrAppearanceFree(theme->a_unfocused_pressed_close); RrAppearanceFree(theme->a_disabled_focused_desk); RrAppearanceFree(theme->a_disabled_unfocused_desk); RrAppearanceFree(theme->a_hover_focused_desk); RrAppearanceFree(theme->a_hover_unfocused_desk); RrAppearanceFree(theme->a_toggled_hover_focused_desk); RrAppearanceFree(theme->a_toggled_hover_unfocused_desk); RrAppearanceFree(theme->a_toggled_focused_unpressed_desk); RrAppearanceFree(theme->a_toggled_focused_pressed_desk); RrAppearanceFree(theme->a_toggled_unfocused_unpressed_desk); RrAppearanceFree(theme->a_toggled_unfocused_pressed_desk); RrAppearanceFree(theme->a_focused_unpressed_desk); RrAppearanceFree(theme->a_focused_pressed_desk); RrAppearanceFree(theme->a_unfocused_unpressed_desk); RrAppearanceFree(theme->a_unfocused_pressed_desk); RrAppearanceFree(theme->a_disabled_focused_shade); RrAppearanceFree(theme->a_disabled_unfocused_shade); RrAppearanceFree(theme->a_hover_focused_shade); RrAppearanceFree(theme->a_hover_unfocused_shade); RrAppearanceFree(theme->a_toggled_hover_focused_shade); RrAppearanceFree(theme->a_toggled_hover_unfocused_shade); RrAppearanceFree(theme->a_toggled_focused_unpressed_shade); RrAppearanceFree(theme->a_toggled_focused_pressed_shade); RrAppearanceFree(theme->a_toggled_unfocused_unpressed_shade); RrAppearanceFree(theme->a_toggled_unfocused_pressed_shade); RrAppearanceFree(theme->a_focused_unpressed_shade); RrAppearanceFree(theme->a_focused_pressed_shade); RrAppearanceFree(theme->a_unfocused_unpressed_shade); RrAppearanceFree(theme->a_unfocused_pressed_shade); RrAppearanceFree(theme->a_disabled_focused_iconify); RrAppearanceFree(theme->a_disabled_unfocused_iconify); RrAppearanceFree(theme->a_hover_focused_iconify); RrAppearanceFree(theme->a_hover_unfocused_iconify); RrAppearanceFree(theme->a_focused_unpressed_iconify); RrAppearanceFree(theme->a_focused_pressed_iconify); RrAppearanceFree(theme->a_unfocused_unpressed_iconify); RrAppearanceFree(theme->a_unfocused_pressed_iconify); RrAppearanceFree(theme->a_focused_grip); RrAppearanceFree(theme->a_unfocused_grip); RrAppearanceFree(theme->a_focused_title); RrAppearanceFree(theme->a_unfocused_title); RrAppearanceFree(theme->a_focused_label); RrAppearanceFree(theme->a_unfocused_label); RrAppearanceFree(theme->a_icon); RrAppearanceFree(theme->a_focused_handle); RrAppearanceFree(theme->a_unfocused_handle); RrAppearanceFree(theme->a_menu); RrAppearanceFree(theme->a_menu_title); RrAppearanceFree(theme->a_menu_text_title); RrAppearanceFree(theme->a_menu_normal); RrAppearanceFree(theme->a_menu_selected); RrAppearanceFree(theme->a_menu_disabled); RrAppearanceFree(theme->a_menu_disabled_selected); RrAppearanceFree(theme->a_menu_text_normal); RrAppearanceFree(theme->a_menu_text_selected); RrAppearanceFree(theme->a_menu_text_disabled); RrAppearanceFree(theme->a_menu_text_disabled_selected); RrAppearanceFree(theme->a_menu_bullet_normal); RrAppearanceFree(theme->a_menu_bullet_selected); RrAppearanceFree(theme->a_clear); RrAppearanceFree(theme->a_clear_tex); RrAppearanceFree(theme->osd_hilite_bg); RrAppearanceFree(theme->osd_hilite_fg); RrAppearanceFree(theme->osd_hilite_label); RrAppearanceFree(theme->osd_unhilite_fg); g_free(theme); } } static XrmDatabase loaddb(const gchar *name, gchar **path) { GSList *it; XrmDatabase db = NULL; gchar *s; if (name[0] == '/') { s = g_build_filename(name, "openbox-3", "themerc", NULL); if ((db = XrmGetFileDatabase(s))) *path = g_path_get_dirname(s); g_free(s); } else { /* XXX backwards compatibility, remove me sometime later */ s = g_build_filename(g_get_home_dir(), ".themes", name, "openbox-3", "themerc", NULL); if ((db = XrmGetFileDatabase(s))) *path = g_path_get_dirname(s); g_free(s); for (it = parse_xdg_data_dir_paths(); !db && it; it = g_slist_next(it)) { s = g_build_filename(it->data, "themes", name, "openbox-3", "themerc", NULL); if ((db = XrmGetFileDatabase(s))) *path = g_path_get_dirname(s); g_free(s); } } if (db == NULL) { s = g_build_filename(name, "themerc", NULL); if ((db = XrmGetFileDatabase(s))) *path = g_path_get_dirname(s); g_free(s); } return db; } static gchar *create_class_name(const gchar *rname) { gchar *rclass = g_strdup(rname); gchar *p = rclass; while (TRUE) { *p = toupper(*p); p = strchr(p+1, '.'); if (p == NULL) break; ++p; if (*p == '\0') break; } return rclass; } static gboolean read_int(XrmDatabase db, const gchar *rname, gint *value) { gboolean ret = FALSE; gchar *rclass = create_class_name(rname); gchar *rettype, *end; XrmValue retvalue; if (XrmGetResource(db, rname, rclass, &rettype, &retvalue) && retvalue.addr != NULL) { *value = (gint)strtol(retvalue.addr, &end, 10); if (end != retvalue.addr) ret = TRUE; } g_free(rclass); return ret; } static gboolean read_string(XrmDatabase db, const gchar *rname, gchar **value) { gboolean ret = FALSE; gchar *rclass = create_class_name(rname); gchar *rettype; XrmValue retvalue; if (XrmGetResource(db, rname, rclass, &rettype, &retvalue) && retvalue.addr != NULL) { *value = retvalue.addr; ret = TRUE; } g_free(rclass); return ret; } static gboolean read_color(XrmDatabase db, const RrInstance *inst, const gchar *rname, RrColor **value) { gboolean ret = FALSE; gchar *rclass = create_class_name(rname); gchar *rettype; XrmValue retvalue; if (XrmGetResource(db, rname, rclass, &rettype, &retvalue) && retvalue.addr != NULL) { RrColor *c = RrColorParse(inst, retvalue.addr); if (c != NULL) { *value = c; ret = TRUE; } } g_free(rclass); return ret; } static gboolean read_mask(const RrInstance *inst, const gchar *path, RrTheme *theme, const gchar *maskname, RrPixmapMask **value) { gboolean ret = FALSE; gchar *s; gint hx, hy; /* ignored */ guint w, h; guchar *b; s = g_build_filename(path, maskname, NULL); if (XReadBitmapFileData(s, &w, &h, &b, &hx, &hy) == BitmapSuccess) { ret = TRUE; *value = RrPixmapMaskNew(inst, w, h, (gchar*)b); XFree(b); } g_free(s); return ret; } static void parse_appearance(gchar *tex, RrSurfaceColorType *grad, RrReliefType *relief, RrBevelType *bevel, gboolean *interlaced, gboolean *border, gboolean allow_trans) { gchar *t; /* convert to all lowercase */ for (t = tex; *t != '\0'; ++t) *t = g_ascii_tolower(*t); if (allow_trans && strstr(tex, "parentrelative") != NULL) { *grad = RR_SURFACE_PARENTREL; } else { if (strstr(tex, "gradient") != NULL) { if (strstr(tex, "crossdiagonal") != NULL) *grad = RR_SURFACE_CROSS_DIAGONAL; else if (strstr(tex, "pyramid") != NULL) *grad = RR_SURFACE_PYRAMID; else if (strstr(tex, "mirrorhorizontal") != NULL) *grad = RR_SURFACE_MIRROR_HORIZONTAL; else if (strstr(tex, "horizontal") != NULL) *grad = RR_SURFACE_HORIZONTAL; else if (strstr(tex, "splitvertical") != NULL) *grad = RR_SURFACE_SPLIT_VERTICAL; else if (strstr(tex, "vertical") != NULL) *grad = RR_SURFACE_VERTICAL; else *grad = RR_SURFACE_DIAGONAL; } else { *grad = RR_SURFACE_SOLID; } } if (strstr(tex, "sunken") != NULL) *relief = RR_RELIEF_SUNKEN; else if (strstr(tex, "flat") != NULL) *relief = RR_RELIEF_FLAT; else if (strstr(tex, "raised") != NULL) *relief = RR_RELIEF_RAISED; else *relief = (*grad == RR_SURFACE_PARENTREL) ? RR_RELIEF_FLAT : RR_RELIEF_RAISED; *border = FALSE; if (*relief == RR_RELIEF_FLAT) { if (strstr(tex, "border") != NULL) *border = TRUE; } else { if (strstr(tex, "bevel2") != NULL) *bevel = RR_BEVEL_2; else *bevel = RR_BEVEL_1; } if (strstr(tex, "interlaced") != NULL) *interlaced = TRUE; else *interlaced = FALSE; } static gboolean read_appearance(XrmDatabase db, const RrInstance *inst, const gchar *rname, RrAppearance *value, gboolean allow_trans) { gboolean ret = FALSE; gchar *rclass = create_class_name(rname); gchar *cname, *ctoname, *bcname, *icname, *hname, *sname; gchar *csplitname, *ctosplitname; gchar *rettype; XrmValue retvalue; gint i; cname = g_strconcat(rname, ".color", NULL); ctoname = g_strconcat(rname, ".colorTo", NULL); bcname = g_strconcat(rname, ".border.color", NULL); icname = g_strconcat(rname, ".interlace.color", NULL); hname = g_strconcat(rname, ".highlight", NULL); sname = g_strconcat(rname, ".shadow", NULL); csplitname = g_strconcat(rname, ".color.splitTo", NULL); ctosplitname = g_strconcat(rname, ".colorTo.splitTo", NULL); if (XrmGetResource(db, rname, rclass, &rettype, &retvalue) && retvalue.addr != NULL) { parse_appearance(retvalue.addr, &value->surface.grad, &value->surface.relief, &value->surface.bevel, &value->surface.interlaced, &value->surface.border, allow_trans); if (!read_color(db, inst, cname, &value->surface.primary)) value->surface.primary = RrColorNew(inst, 0, 0, 0); if (!read_color(db, inst, ctoname, &value->surface.secondary)) value->surface.secondary = RrColorNew(inst, 0, 0, 0); if (value->surface.border) if (!read_color(db, inst, bcname, &value->surface.border_color)) value->surface.border_color = RrColorNew(inst, 0, 0, 0); if (value->surface.interlaced) if (!read_color(db, inst, icname, &value->surface.interlace_color)) value->surface.interlace_color = RrColorNew(inst, 0, 0, 0); if (read_int(db, hname, &i) && i >= 0) value->surface.bevel_light_adjust = i; if (read_int(db, sname, &i) && i >= 0 && i <= 256) value->surface.bevel_dark_adjust = i; if (value->surface.grad == RR_SURFACE_SPLIT_VERTICAL) { gint r, g, b; if (!read_color(db, inst, csplitname, &value->surface.split_primary)) { r = value->surface.primary->r; r += r >> 2; g = value->surface.primary->g; g += g >> 2; b = value->surface.primary->b; b += b >> 2; if (r > 0xFF) r = 0xFF; if (g > 0xFF) g = 0xFF; if (b > 0xFF) b = 0xFF; value->surface.split_primary = RrColorNew(inst, r, g, b); } if (!read_color(db, inst, ctosplitname, &value->surface.split_secondary)) { r = value->surface.secondary->r; r += r >> 4; g = value->surface.secondary->g; g += g >> 4; b = value->surface.secondary->b; b += b >> 4; if (r > 0xFF) r = 0xFF; if (g > 0xFF) g = 0xFF; if (b > 0xFF) b = 0xFF; value->surface.split_secondary = RrColorNew(inst, r, g, b); } } ret = TRUE; } g_free(ctosplitname); g_free(csplitname); g_free(sname); g_free(hname); g_free(icname); g_free(bcname); g_free(ctoname); g_free(cname); g_free(rclass); return ret; } static int parse_inline_number(const char *p) { int neg = 1; int res = 0; if (*p == '-') { neg = -1; ++p; } for (; isdigit(*p); ++p) res = res * 10 + *p - '0'; res *= neg; return res; } static void set_default_appearance(RrAppearance *a) { a->surface.grad = RR_SURFACE_SOLID; a->surface.relief = RR_RELIEF_FLAT; a->surface.bevel = RR_BEVEL_1; a->surface.interlaced = FALSE; a->surface.border = FALSE; a->surface.primary = RrColorNew(a->inst, 0, 0, 0); a->surface.secondary = RrColorNew(a->inst, 0, 0, 0); } /* Reads the output from gimp's C-Source file format into valid RGBA data for an RrTextureRGBA. */ static RrPixel32* read_c_image(gint width, gint height, const guint8 *data) { RrPixel32 *im, *p; gint i; p = im = g_memdup(data, width * height * sizeof(RrPixel32)); for (i = 0; i < width * height; ++i) { guchar a = ((*p >> 24) & 0xff); guchar b = ((*p >> 16) & 0xff); guchar g = ((*p >> 8) & 0xff); guchar r = ((*p >> 0) & 0xff); *p = ((r << RrDefaultRedOffset) + (g << RrDefaultGreenOffset) + (b << RrDefaultBlueOffset) + (a << RrDefaultAlphaOffset)); p++; } return im; }
|
__label__pos
| 0.99725 |
Actions
Tab Separated Value survey structure
From LimeSurvey Manual
(Redirected from Excel Survey Structure)
Other languages:
English • Nederlands • português do Brasil • 日本語
Tab Separated Value Import and Export of Survey Structure
This feature is designed to make it easy to use a spreadsheet software like LibreOffice, Excel or Google Docs to author and edit surveys. It completely eliminates the dependence upon SGQA codes.
This feature supports import from ASCII or UTF-8 encoded Tab Separated Value (TSV) files which have an extension of .txt.
Help.pngCheck the following example to get a better understanding of this functionality.
Getting Started
The easiest way is to take an existing survey and export it in Tab Separated Value format. Use the normal export survey button, and instead of selecting .lss format, select "Tab Separated Values format (*.txt)". It will be saved as a Tab Separated Value file in the proper format (tab delimited unicode file), with all the correct column headings.
Any spreadsheet software that supports tab separated values is fine (e.g., OpenOffice or LibreOffice). LimeSurvey ignores any formatting within the spreadsheet, but feel free to add some if it helps you.
Note that the exported file is in UTF-8 format with the Byte Order Mark (BOM) as the first three (hidden) characters. If you double click on the .txt and try to open it directly with Excel, it will not open properly because Excel does not realize that it is UTF-8 formatted. To open these files with Excel, first open Excel, then select File:Open, select the .txt file, and tell Excel that it is using UTF-8 encoding.
There will be one row for each group, question, subquestion, and answer. There are also rows for global survey variables, and for language-specific survey variables. The primary language will be listed first, followed by any secondary languages. So, if there are multiple languages, the entire contents of the base language will appear first (e.g., all groups, questions, subquestions, and answers). This will be followed by a translated copy for each secondary language (with exactly the same number and order or rows for the translated set).
Relationships are inferred by proximity. So, questions following a group are part of that group; subquestions following a question are part of that question, and answers following a question are part of that question. Thus, you don't need to know the IDs (gid, qid, sqid) for any questions. Those will be computed automatically upon import. In fact, this format does not use gid, qid, or sqid (or SGQA codes) at all.
Tips
The goal of the Tab Separated Value import/export is to let you rapidly design your survey using a spreadsheet. We expect that you will frequently import the sheet, check its validity using the "Show Survey Logic" feature, and test it. Each time you import it, you will get a new survey. So, you might end up with many partially developed surveys, but that is fine. Just get in the habit of keeping track of which is the most recent, or delete the old one after you import the new ones. Since you never use SGQA codes in the Tab Separated Value, you never need to worry about what codes LimeSurvey assigns for the primary survey, group, question and answer keys. So, feel free to import and export as often as you like.
Here are some convenient things you can do with this approach to authoring instruments:
1. Use same Answers for many questions. Just copy the 'A' rows and paste after each question that should have the same set.
2. Use same subquestions for many questions. Just copy the 'SQ' rows and paste them after each question that needs it.
3. "Looping" - use same group many times. After the group is the way you want it, copy it as many times as needed. Use Excel filtering to view just the 'G' rows (for groups), and use the Excel column drag feature to update the relevance equations for each group (e.g., for a census, the first relevance might be "numPeople > 1", the next should be "numPeople > 2". The drag feature will auto-update the number). Filter by 'Q' rows and ensure that each question has a unique value (e.g., say you name your variables g1_q1, g1_q2, g1_qN, use find/replace to convert g1 to g2 the second group; g3 for the third, etc.).
4. Re-ordering questions/groups. Simply re-order the rows of the spreadsheet file.
5. Testing survey modules. For long surveys, you may want to break up the testing into modules. Simply create new spreadsheet files for each module, deleting any rows that you don't need. This avoids the need to enter lots of data to test later sections of the survey.
6. Testing mandatory questions. A common complaint is not the need to make many questions mandatory, but the need to turn off the mandatory feature for testing. Simply create the master spreadsheet with mandatory set to the final desired values. Then, to test it, just delete the "mandatory" column and save the test version of the spreadsheet. When you import that version, none of the questions will be mandatory. After you have finished your testing, import the master copy.
7. Setting defaults. Rather than using the GUI, you can enter any desired defaults in the default column. This is especially helpful for cases where the GUI does not let you enter the desired value, like expressions to set the default for list items (like populating a list from a survey participant attribute).
8. Translation. You can create copies of your spreadsheet - one per language. Include all the rows for the primary language, then copy and paste them below, and use drag to change the language field to the target language. These can be distributed to your translators, and re-integrated into a single spreadsheet file when they are done.
9. Bulk setting of advanced question attributes. You may want all of your equations to start visible (so you can see their values as you collect data), but then hide them all before going to production. Simply filter the spreadsheet on class = 'Q' and question type = '*' (equation), and set always_hide to 1 for each of those questions. Similarly, say after you create the survey, you decide which questions should appear in public statistics. Rather than edit each question through the GUI, filter on class = 'Q', and set public_statistics = 1 for all of the questions that should be visible in statistics.
10. Find and replace. Say you decide you need to change some phrasing across all of your questions, you can use Excel find and replace to make those changes. Similarly, say you decide to do a bulk-renaming of your variables, find and replace can come to the rescue. If you need regular-expression based find and replace, you can select the desired column, copy to a text editor, do your find and replace, and paste the column back into the spreadsheet.
11. Gaining approvals. If you are doing research, you may have an Institutional Review board who insists upon seeing the text of the questions. This may be a convenient way to share it. Similarly for discussions with a client.
12. Team consensus. If you are trying to get a group to agree upon the wording or appearance of a question or group, you can rapidly prototype / edit the spreadsheet, import it, and show the team (via question or group preview) exactly what the users will see. That way you can get approval from the team before they leave the room rather than having to document requirements, build them, and get approval at future meetings.
13. Upgrading from other survey formats. If your survey is in XML, Word, or other format, you can create a translation process to map them to this format. Although you could also try mapping to the .lss format, the advantage of this format is that it doesn't require you to keep track of foreign key relationships between groups, questions, subquestions, answers, and defaults.
Limitations
1. By design, this feature only works properly for surveys that use qcode (rather than SGQA) naming. This feature assumes that variable names (question identifiers) are unique throughout the survey. Subquestion names can be repeated, as long as they are unique within the scope of a particular question.
File Format
General
We use the same set of column headings for multiple purposes. The first 14 columns serve different purposes depending upon the type of entity (e.g., group, question, answer). The remaining columns are an alphabetical list of the database field names for the advanced question codes. Below is the syntax for each entity type
The first 14 columns are:
1. id (New in 3.14.0 )
2. related_id (New in 3.14.0 )
3. class
4. type/scale
5. name
6. relevance
7. text
8. help
9. language
10. validation
11. mandatory
12. other
13. default
14. same_default
Notice.png
Hint: Columns id and related_id are used only for quota and are optional. If you don't have quota, you can directly remove this 2 columns.
Survey Global Parameters
There is one row per parameter in the surveys table.
1. class => 'S'
2. name => database field name
3. text => value
Survey Language-Specific Parameters
There is one row per field per language in the surveys_languagesettings table. All entries for a given language are collected before doing the insert into that table.
1. class => 'SL'
2. name => database field name
3. text => value
4. language => language
Groups
One group row per survey language (e.g., there would be 3 group rows if survey has 3 languages).
1. id => unique numeric identifier for the group, starting with number 1, use the same ID for additional languages belonging to current group
2. class => 'G'
3. name => group_name -- the unique identifier for the group
4. relevance => grelevance -- the group-level relevance equation, without curly braces
5. text => description -- the language-specific description of the group
6. language => language -- the language for the group (e.g., 'en')
Questions
One question row per survey language (e.g., there would be 3 question rows if survey has 3 languages). Questions are assumed to belong to the group that precedes them.
1. id => unique numeric identifier for the question, starting with number 1, use the same ID for additional languages belonging to current question
2. class => 'Q'
3. type/scale => type -- the (usually one letter) question type (e.g., 'M' is Multiple Choice)
4. name => title -- the unique question name (the root of the qcode naming system)
5. relevance => relevance -- the relevance equation for the question
6. text => question -- the language-specific text of the question
7. help => help -- the language-specific help text
8. language => language -- the language for the group (e.g., 'en')
9. validation => preg -- the optional regular expression validation criteria for the question
10. mandatory => mandatory -- 'Y' if mandatory
11. other => other -- 'Y' if the "Other" option should be available (only for some question types)
12. default => default -- if set, this value is inserted into the defaultvalues table for this question
13. same_default => same_default -- 'Y' for true, in which case any defaultvalue set for primary language applies to other languages
Subquestions
One subquestion row per survey language. Subquestions are assumed to belong to the question that precedes them.
1. id => same unique numeric identifier which is used for the questions. Subquestions should use next available value, question and subquestion IDs should be different (e.g. use ID 1 for question and IDs 2, 3 and 4 for subquestions belonging to question 1, next question ID should be 5 and so on). Use the same subquestion ID for additional languages belonging to current subquestions.
2. class => 'SQ'
3. type/scale => scale_id -- 0 or 1, depending upon question type (e.g. array text will have two scales)
4. name => title -- the "name" of the subquestion, e.g. the one used for exclude_all_others
5. relevance => relevance -- (Future) to support subquestion-level relevance
6. text => question -- the language-specific text of the subquestion
7. help => help -- (Future) to support subquestion-level help
8. language => language -- the language for the subquestion
9. validation => preg -- (Future) to support subquestion-level regular expression validation (e.g. for address parts)
10. mandatory => mandatory -- (Future) to support subquestion-level mandatory (e.g. make only a few subquestions mandatory)
11. default => default -- if set, then this is the default value for the subquestion (inserted into defaultvalues table)
12. same_default => same_default -- if set, then the default for the primary language is used for all other languages
Answers
One answer row per survey language (e.g., there would be 3 answer rows if survey has 3 languages). Answers are assumed to belong to the question that precedes them, and be in the desired sort order.
1. id => use the same ID as the ID of the question it belongs to
2. class => 'A'
3. type/scale => scale_id -- 0 or 1 (e.g. for dual-scale)
4. name => code -- the unique answer identifier
5. relevance => assessment_value -- if using assessment option, this is the assessment value for the answer
6. text => answer -- the language-specific text of the answer
7. language => language -- the language for this answer (e.g. 'en')
Assessments
One assessment row per survey language (e.g., there would be 3 assessment rows if survey has 3 languages). Assessments are written at the end of file.
1. id => unique numeric identifier for the assessment, starting with number 1, use the same ID for additional languages belonging to current assessment
2. related_id => id of group to which current assessment belongs to
3. class => 'AS'
4. type/scale => assessment scope: T-Total, G-group
5. name => name
6. text => message
7. min_num_value => Minimum
8. max_num_value => Maximum
9. language => language -- the language for this answer (e.g. 'en')
Quotas
One row per quota. Quotas are written at the end of file.
1. id => unique numeric identifier for the quota, starting with number 1
2. class => 'QTA'
3. name => quota name
4. mandatory => limit
5. other => quota action
6. default => active
7. same_default => autoload URL
Quota language settings
One quota row per survey language. Quota language settings are assumed to belong to the quota that precedes them.
1. id => unique numeric identifier for the quota language settings, starting with number 1. Each row for different survey languages should have different IDs
2. related_id => quota id of quota to which this setting belongs to
3. class => 'QTALS'
4. relevance => message
5. text => URL
6. help => URL description
7. language => language -- the language for this quota (e.g. 'en')
Quota members
One row per quota member, no language dependent. Quota member row should be placed immediately after question it relates to. Quota members are assumed to belong to the question that precedes them.
1. id => unique numeric identifier for the quota members, starting with number 1
2. related_id => quota id of quota to which this member belongs to
3. class => 'QTAM'
4. name => answer code
Conditions
One row per condition, no language dependent. Condition row should be placed immediately after question it relates to. Conditions are assumed to belong to the question that precedes them.
1. id => unique numeric identifier for the condition, starting with number 1.
2. related_id => question id of related question, if applicable
3. class => 'C'
4. type/scale => scenario
5. name => answer field name
6. relevance => comparison operator
7. text => expected answer
|
__label__pos
| 0.972134 |
CREATE TRIGGER
Create a trigger.
Syntax:
CREATE [OR REPLACE] TRIGGER [schema.]trigger
BEFORE event [WHEN (condition)]
{pl_sql_block | call_procedure_statement}
CREATE [OR REPLACE] TRIGGER [schema.]trigger
AFTER event
[WHEN (condition)]
{pl_sql_block | call_procedure_statement}
CREATE [OR REPLACE] TRIGGER [schema.]trigger
INSTEAD OF event
[WHEN (condition)]
{pl_sql_block | call_procedure_statement}
event can be one or more of the following (separate multiple events with OR)
DELETE event_ref referencing_clause
INSERT event_ref referencing_clause
UPDATE event_ref referencing_clause
UPDATE OF column, column… event_ref
db/ddl_event ON [schema.object]
db/ddl_event ON DATABASE
event_ref:
ON [schema.]table
ON [schema.]view
ON [NESTED TABLE nested_table_column OF] [schema.]view
referencing_clause:
FOR EACH ROW
REFERENCING OLD [AS] old [FOR EACH ROW]
REFERENCING NEW [AS] new [FOR EACH ROW]
REFERENCING PARENT [AS] parent [FOR EACH ROW]
db/ddl_event:
ALTER
ANALYSE
ASSOCIATE STATISTICS
AUDIT
COMMENT
CREATE
DDL
DISASSOCIATE STATISTICS
DROP
GRANT
LOGON
LOGOFF
NOAUDIT
RENAME
REVOKE
TRUNCATE
SERVERERROR
STARTUP
SHUTDOWN
SUSPEND
Multiple db/ddl_events can be separated with OR
Multiple OLD, NEW and PARENT correlation names can be defined in one REFERENCING clause.
Database constraints are a factor of 8x faster than triggers.
"A friend told me to shoot first and ask questions later. I was going to ask him why, but I had to shoot him" ~ John Wayne
Related Commands:
ALTER TRIGGER
DROP TRIGGER
ALTER TABLE
Related Views:
DBA_TRIGGERS ALL_TRIGGERS USER_TRIGGERS
DBA_TRIGGER_COLS ALL_TRIGGER_COLS USER_TRIGGER_COLS
DBA_INTERNAL_TRIGGERS ALL_INTERNAL_TRIGGERS USER_INTERNAL_TRIGGERS
Copyright © SS64.com 1999-2018
Some rights reserved
|
__label__pos
| 0.521115 |
Web Analytics
Converting Mixed Numbers to Improper Fractions Worksheet
• 3 min read
• Mar 09, 2020
Some programs that you can download online do not have a working converter for converting mixed numbers to improper fractions. This is a very common problem that can be solved with a little bit of effort and help from a computer repair expert.
8Eb5MWwcMMY
Subtracting mixed numbers 7 6 9 3 2 5 video from converting mixed numbers to improper fractions worksheet , source:khanacademy.org
Since you cannot let go of the fear of a calculator because you want to know how to convert numbers correctly, you may have to find a way to work around this problem. One of the ways is to find an online program that gives you a list of all the numbers in the world. This program will give you a list of the numbers that are used in the different units that are used by your country.
The next step is to import these numbers into a worksheet. Most programs will allow you to work with single digits, two digits, and three-digit numbers. With numbers in this order, you will be able to enter your numbers one by one and work on converting them to proper fractions. If you only have multi-digit numbers, it will take a lot more time to learn the correct conversion.
Converting Decimals to Fractions Worksheet Tes Luxury Converting Improper Fractions to Mixed Numbers Worksheet Tes Fresh
Converting Decimals to Fractions Worksheet Tes Luxury Converting from converting mixed numbers to improper fractions worksheet , source:penlocalmag.com
Before moving on to how to convert these numbers to improper fractions, you need to make sure that you are using the right formula to do the job. This is a very important step that can be overlooked if you are just getting started.
If you are working on a business, use a formula that will show you how much money your business makes on a monthly or yearly basis, and then multiply that number by the profit of your last year. The right formulas for this will come with a trial version of the program that you can download.
Ma17frac l1 w converting between improper fractions and mixed numbers 752x1065 numbers worksheet
worksheet Improper Fractions To Mixed Numbers Worksheet Fun from converting mixed numbers to improper fractions worksheet , source:siteraven.com
For example, you would do the math of, “If this was my first year, what percentage of the amount that I made went back into my business, then I would multiply that number by 30” and then sum the results up to get your financial statement. Then, you would divide by the profit of last year to find out the profit every month. This is an example, so if you find it easier to do it a different way, then do so.
You now know how to convert numbers to improper fractions and get your financial statement done. Now you are ready to go to the next step.
Mixed Number And Improper Fractions Worksheet Tes Fraction Worksheets Grade Convert To Numbers It T
Mixed Number Fraction Worksheets from converting mixed numbers to improper fractions worksheet , source:landofgods.co
Enter all the numbers in the proper order and then divide by your profit for the fiscal year-end to find the proper fraction. Then, you will use this to find the profit every month and compare it to the amount of money that was made for the year. You may find that you will be making more this year and the previous year combined than you did from the year before.
addition of fractions worksheets with answers fresh mixed numbers worksheet year 3 inspirationa subtracting mixed of
27 Fresh Addition Fractions Worksheets with Answers Graphics from converting mixed numbers to improper fractions worksheet , source:grahapada.com
Adding Mixed Numbers Lesson Plan Elegant 714 Best Elementary Math Pinterest 38 Unique
38 Unique Adding Mixed Numbers Lesson Plan from converting mixed numbers to improper fractions worksheet , source:myrawalakot.com
Image result for mixed fraction to improper fraction worksheets
Fraction Worksheet from converting mixed numbers to improper fractions worksheet , source:mychaume.com
Multiplying Mixed Numbers Worksheet Converting Improper Fractions Worksheet New Negative Numbers Easy
Multiplying Mixed Numbers Worksheet Converting Improper Fractions from converting mixed numbers to improper fractions worksheet , source:wp-landingpages.com
Improper Fractions Anchor Chart Improper Fractions Anchor Chart
Converting Mixed Numbers To Improper Fractions Anchor Charts from converting mixed numbers to improper fractions worksheet , source:teacherspayteachers.com
MIXED AND IMPROPER FRACTIONS WORKSHEET 4th grade
Mixed Fractions Worksheets from converting mixed numbers to improper fractions worksheet , source:fronteirastral.com
|
__label__pos
| 0.872985 |
VLAN with BH
Hi Alls,
I have configuration like this below :
PC 1 ----- L2 Switch — BH M ------ BH S ----- L2 Switch ---- PC2
I want to connect between L2 Switch, i configure port 11 each Switch as tag port, Everything okay. Both VLAN at bot switches can communicate each other, but i can’t browse BH web page again. Is that situation normal?
How if with that configuration but i can still access the configuration page?
Regards,
mrdlnf
I am still in the process of learning VLANs myself, but I think I may have an explanation. If you configured port 11 on both switches to be a tagged port, then each packet that is leaving (entering ?) those ports is being tagged with a certain VID. I believe this VID is added to the Link-Layer frame in the packet. The backhauls are transparent Layer-2 bridges, so they will simply forward these packets to the other ends of the link, but since they are not yet VLAN capable, they cannot process any packets that have been VLAN tagged destined for themselves.
So when you try to access the web based config of the modules, that packet is tagged with a VID, and the backhaul discards it because it is not capable of processing the packet.
Can any VLAN experts confirm/deny my attempt here. Acherman?
That is correct. The BH’s are not 802.1q VLAN aware yet. Hopefully they will be soon.
For my managment purposes I keep the BH’s and AP’s on ID 1 and keep that VID untagged. This allows all customer traffic to pass with 802.1q tags but no tags on manamement packets, allowing the BH’s to read and respond to them.
I look forward to the day that Motorola enables VLAN tagging in the BH’s.
Aaron
Does the Ingress VID setting tag packets arriving at the Ethernet inbound, outbound, or both? My guess is outbound, or else anything on the LAN behind the SM would have to have VLAN aware NICs, etc. correct?
Ingress refers to anything coming into the port - in this case, the ethernet port of the SM. So, when a packet comes into the ethernet port of the SM and it does not have an 802.1q tag (ie. from a regular NIC) then the SM adds the tag itself. If the packet already has a tag then the SM passes it unaltered (other than the source address if NAT is turned on and assuming that VID is in it’s member list).
Aaron
|
__label__pos
| 0.940197 |
Preserve Your Favorite Videos: Mastering the Art of YouTube Video Ripping
Are you tired of losing access to your favorite videos on YouTube? Have you ever wished you could save them to watch offline or keep them for future reference? If so, you’re in luck! In this article, we will explore the art of YouTube video ripping, a technique that allows you to preserve your beloved videos and enjoy them whenever you want. So, grab your digital toolkit and let’s get started!
PBN1-4-M
Table of Contents
Introduction: Understanding YouTube Video Ripping
Legal and Ethical Considerations
Finding the Right YouTube Video Ripper
Step-by-Step Guide to Ripping YouTube Videos
4.1. Choosing the Video to Rip
4.2. Selecting the Desired Format and Quality
4.3. Ripping the Video
Offline Viewing: Enjoying Your Ripped Videos Anywhere, Anytime
Organizing and Managing Your Ripped Video Collection
Frequently Asked Questions (FAQs)
7.1. Is YouTube video ripping legal?
7.2. Can I rip videos from YouTube using my mobile device?
7.3. Are there any risks involved in ripping YouTube videos?
7.4. Can I share the ripped videos with others?
7.5. What are the alternative methods for preserving YouTube videos?
1. Introduction: Understanding YouTube Video Ripping
YouTube, the popular video-sharing platform, offers an enormous amount of content ranging from educational videos to music, tutorials, and entertainment. However, due to various reasons, such as changes in content availability, internet connectivity issues, or the desire to watch videos offline, many users seek methods to rip and save YouTube videos.
2. Legal and Ethical Considerations
Before we delve into the world of YouTube video ripping, it’s crucial to understand the legal and ethical implications. While there are legitimate reasons for ripping videos, it’s important to respect copyright laws and only rip videos that you have the right to access.
3. Finding the Right YouTube Video Ripper
To successfully rip YouTube videos, you’ll need a reliable video ripper tool. Numerous online platforms and software solutions are available, each with its own set of features and functionalities. It’s essential to choose a reputable ripper that offers the necessary options and respects the terms of service set by YouTube.
4. Step-by-Step Guide to Ripping YouTube Videos
4.1. Choosing the Video to Rip
Start by browsing YouTube for the video you wish to rip. Whether it’s a tutorial, a music video, or a documentary, find the video that sparks your interest and copy its URL.
4.2. Selecting the Desired Format and Quality
Once you have the URL, open the YouTube video ripper tool of your choice. Depending on the tool, you may be able to select the desired format (e.g., MP4, AVI, or MKV) and quality (e.g., 720p, 1080p, or 4K) for the ripped video. Take into account your storage capacity and the devices you’ll be using to watch the videos.
4.3. Ripping the Video
Paste the copied URL into the designated field in the video ripper tool. Then, initiate the ripping process. The tool will extract the video from YouTube and convert it into the format and quality you specified. The duration of the process depends on factors such as the video’s length and your internet speed.
5. Offline Viewing: Enjoying Your Ripped Videos Anywhere, Anytime
One of the significant advantages of ripping YouTube videos is the ability to watch them offline. After the video ripping process is complete, transfer the ripped file to your preferred device—be it a smartphone, tablet, or computer. Now, you can enjoy your favorite videos even without an internet connection.
6. Organizing and Managing Your Ripped Video Collection
As you accumulate a collection of ripped YouTube videos, it’s essential to keep them organized. Create folders and categorize your videos based on genres, topics, or any other system that makes sense to you. This way, you can easily locate and access the videos whenever you want to revisit them.
7. Frequently Asked Questions (FAQs)
7.1. Is YouTube video ripping legal?
The legality of YouTube video ripping varies depending on your jurisdiction and the intended use of the ripped videos. While it’s generally acceptable for personal use, distributing or profiting from ripped videos without proper authorization is likely to violate copyright laws.
7.2. Can I rip videos from YouTube using my mobile device?
Yes, many video ripper tools offer mobile apps that allow you to rip YouTube videos directly on your smartphone or tablet. Ensure you choose a reliable app from a trusted source to avoid any security risks.
7.3. Are there any risks involved in ripping YouTube videos?
Ripping YouTube videos can pose certain risks, particularly when using unreliable or untrustworthy video ripper tools. These risks may include malware infections, violation of terms of service, or legal consequences. It’s crucial to research and use reputable video ripper tools to minimize such risks.
7.4. Can I share the ripped videos with others?
Sharing ripped YouTube videos may infringe upon copyright laws unless you have obtained the necessary permissions. It’s advisable to use ripped videos strictly for personal purposes and refrain from distributing them without proper authorization.
7.5. What are the alternative methods for preserving YouTube videos?
Aside from video ripping, there are other ways to preserve YouTube videos, such as using YouTube’s offline feature (available in certain countries), bookmarking videos for later viewing, or subscribing to channels and playlists to receive notifications when new videos are uploaded.
Conclusion
YouTube video ripping is a useful technique that allows you to preserve your favorite videos and enjoy them at your convenience. By following the outlined steps and considering the legal and ethical aspects, you can build a collection of ripped videos for offline viewing. Remember to use reputable video ripper tools and respect copyright laws to ensure a positive and enjoyable experience.
FAQs
Q1. Can I rip YouTube videos for commercial use?
No, ripping YouTube videos for commercial use without proper authorization is a violation of copyright laws.
Q2. Is there a limit to the number of videos I can rip from YouTube?
There is no strict limit to the number of videos you can rip from YouTube, but keep in mind that excessive ripping may infringe upon the platform’s terms of service.
Q3. Can I rip videos from YouTube Live streams?
In most cases, video ripper tools do not support ripping videos from YouTube Live streams. It’s recommended to explore alternative methods for capturing or saving live stream content.
Q4. Are there any legal alternatives to ripping YouTube videos?
Yes, YouTube Premium offers an official offline feature that allows you to download and watch videos within the YouTube app. This feature is available in select countries and requires a subscription.
Q5. How can I ensure the quality of the ripped videos?
To ensure the best quality, choose a video ripper tool that supports high-resolution and choose the appropriate format and quality settings before initiating the ripping process.
|
__label__pos
| 0.991566 |
Uploaded image for project: 'Coin'
1. Coin
2. COIN-795
Allow installation of multiple platformDependencies artifacts into separate subdirectories
XMLWordPrintable
Details
• Suggestion
• Resolution: Done
• P2: Important
• None
• master
• None
Description
COIN-646 requested a feature to allow specifying a list of platform dependencies to allow stitching together a multi-abi Qt for Android.
That was implemented, but we need to ensure that the artifacts installed from those dependencies are not installed into the same path, so that files are not overridden.
My proposal would be to add 2 new flags to the artifact installation commands:
installHostDepsPerPlatformSubdir and installTargetDepsPerPlatformSubdir
Af the flag is set to true, then each platform dependency is unpacked into a subdir named by the platform dependency id.
If false, the default current behavior, install all deps into same location.
I'd also add an additional option that takes an env var name, which will be populated with a semicolon separate list of values, where each value is the absolute dir name of the unpacked platform dir.
Affected commands:
InstallSourceArchive
InstallBinaryArchive
InstallTestBinaryArchive
Possibly other conan ones?
Attachments
Issue Links
No reviews matched the request. Check your Options in the drop-down menu of this sections header.
Activity
People
tosaario Toni Saario
alexandru.croitor Alexandru Croitor
Votes:
0 Vote for this issue
Watchers:
3 Start watching this issue
Dates
Created:
Updated:
Resolved:
Gerrit Reviews
There are no open Gerrit changes
|
__label__pos
| 0.766209 |
Changes between Version 1 and Version 2 of TracTicketsCustomFields
Ignore:
Timestamp:
Apr 9, 2018, 7:05:09 AM (5 years ago)
Author:
trac
Comment:
--
Legend:
Unmodified
Added
Removed
Modified
• TracTicketsCustomFields
v1 v2
1 = Custom Ticket Fields =
2 Trac supports adding custom, user-defined fields to the ticket module. Using custom fields, you can add typed, site-specific properties to tickets.
1= Custom Ticket Fields
2Trac supports adding custom, user-defined fields to the ticket module. With custom fields you can add typed, site-specific properties to tickets.
33
4 == Configuration ==
4== Configuration
55Configuring custom ticket fields is done in the [wiki:TracIni trac.ini] file. All field definitions should be under a section named `[ticket-custom]`.
66
1313The example below should help to explain the syntax.
1414
15 === Available Field Types and Options ===
15=== Available Field Types and Options
1616 * '''text''': A simple (one line) text field.
1717 * label: Descriptive label.
1818 * value: Default value.
19 * order: Sort order placement. (Determines relative placement in forms with respect to other custom fields.)
19 * order: Sort order placement; this determines relative placement in forms with respect to other custom fields.
2020 * format: One of:
2121 * `plain` for plain text
22 * `wiki` to interpret the content as WikiFormatting (''since 0.11.3'')
22 * `wiki` to interpret the content as WikiFormatting
2323 * `reference` to treat the content as a queryable value (''since 1.0'')
2424 * `list` to interpret the content as a list of queryable values, separated by whitespace (''since 1.0'')
2525 * '''checkbox''': A boolean value check box.
2626 * label: Descriptive label.
27 * value: Default value (0 or 1).
27 * value: Default value, 0 or 1.
2828 * order: Sort order placement.
2929 * '''select''': Drop-down select box. Uses a list of values.
3535 * label: Descriptive label.
3636 * options: List of values, separated by '''|''' (vertical pipe).
37 * value: Default value (one of the values from options).
37 * value: Default value, one of the values from options.
3838 * order: Sort order placement.
3939 * '''textarea''': Multi-line text area.
4040 * label: Descriptive label.
4141 * value: Default text.
42 * cols: Width in columns.
42 * cols: Width in columns. //(Removed in 1.1.2)//
4343 * rows: Height in lines.
4444 * order: Sort order placement.
45 * format: Either `plain` for plain text or `wiki` to interpret the content as WikiFormatting. (''since 0.11.3'')
45 * format: Either `plain` for plain text or `wiki` to interpret the content as WikiFormatting.
46 * '''time''': Date and time picker. (''Since 1.1.1.'')
47 * label: Descriptive label.
48 * value: Default date.
49 * order: Sort order placement.
50 * format: One of:
51 * `relative` for relative dates.
52 * `date` for absolute dates.
53 * `datetime` for absolute date and time values.
4654
47 === Sample Config ===
55If the `label` is not specified, it will be created by capitalizing the custom field name and replacing underscores with whitespaces.
56
57Macros will be expanded when rendering `textarea` fields with format `wiki`, but not when rendering `text` fields with format `wiki`.
58
59=== Sample Config
4860{{{
4961[ticket-custom]
7688test_six.cols = 60
7789test_six.rows = 30
90
91test_seven = time
92test_seven.label = A relative date
93test_seven.format = relative
94test_seven.value = now
95
96test_eight = time
97test_eight.label = An absolute date
98test_eight.format = date
99test_eight.value = yesterday
100
101test_nine = time
102test_nine.label = A date and time
103test_nine.format = datetime
104test_nine.value = in 2 hours
78105}}}
79106
80 ''Note: To make entering an option for a `select` type field optional, specify a leading `|` in the `fieldname.options` option.''
107'''Note''': To make a `select` type field optional, specify a leading `|` in the `fieldname.options` option.
81108
82 === Reports Involving Custom Fields ===
109=== Reports Involving Custom Fields
83110
84111Custom ticket fields are stored in the `ticket_custom` table, not in the `ticket` table. So to display the values from custom fields in a report, you will need a join on the 2 tables. Let's use an example with a custom ticket field called `progress`.
93120 ORDER BY p.value
94121}}}
95 '''Note''' that this will only show tickets that have progress set in them, which is '''not the same as showing all tickets'''. If you created this custom ticket field ''after'' you have already created some tickets, they will not have that field defined, and thus they will never show up on this ticket query. If you go back and modify those tickets, the field will be defined, and they will appear in the query. If that's all you want, you're set.
122'''Note''': This will only show tickets that have progress set in them. This is '''not the same as showing all tickets'''. If you created this custom ticket field ''after'' you have already created some tickets, they will not have that field defined, and thus they will never show up on this ticket query. If you go back and modify those tickets, the field will be defined, and they will appear in the query.
96123
97 However, if you want to show all ticket entries (with progress defined and without), you need to use a `JOIN` for every custom field that is in the query.
124However, if you want to show all ticket entries (with progress defined and without), you need to use a `JOIN` for every custom field that is in the query:
98125{{{
99126#!sql
114141Note in particular the `LEFT OUTER JOIN` statement here.
115142
116 === Updating the database ===
143Note that if your config file uses an uppercase name, e.g.,
144{{{
145[ticket-custom]
146
147Progress_Type = text
148}}}
149you would use lowercase in the SQL: `AND c.name = 'progress_type'`
150
151=== Updating the database
117152
118153As noted above, any tickets created before a custom field has been defined will not have a value for that field. Here's a bit of SQL (tested with SQLite) that you can run directly on the Trac database to set an initial value for custom ticket fields. Inserts the default value of 'None' into a custom field called 'request_source' for all tickets that have no existing value:
|
__label__pos
| 0.988598 |
Batch File That Appears With Repeated Messages
17/06/2011 18:30
in this post, we will create a batch file that pop-ups keep repeating the message boxes.
Below is the code for it.
: Home
msg * Hi
Msg * Are you having fun?
msg * I am!
msg * https://tipsandtricks.webnode.com admin!
* Message and you're stuck reading
* Msg teach you
msg * Batch Programming Series
Msg * Did you learn something new
msg * and like
* Msg if so, then do not subscribe
Msg * learn hacking
msg * the fastest growing site of ethical hacking
msg online *
And you know what * msg
* Msg has been Pwned with a capital "P"
GOTO
See, it's that simple. I'm sure you could have understood. Now you can use this and annoy your friends and play this trick where you want.
|
__label__pos
| 0.955013 |
MIB Discovery
1856 modules enregistrés
Chemin
MIX : 1 (iso). 3 (org). 6 (dod). 1 (internet). 4 (private). 1 (enterprises). 4491 (cableLabs). 2 (clabProject). 1 (clabProjDocsis). 23 (docsDrfMib). 1 (docsDrfObjects). 3 (docsDrfDownstreamCapabilitiesTable). 1 (docsDrfDownstreamCapabilitiesEntry). 1 (docsDrfDownstreamCapabFrequency)
OID : 1.3.6.1.4.1.4491.2.1.23.1.3.1.1
TXT : iso. org. dod. internet. private. enterprises. cableLabs. clabProject. clabProjDocsis. docsDrfMib. docsDrfObjects. docsDrfDownstreamCapabilitiesTable. docsDrfDownstreamCapabilitiesEntry. docsDrfDownstreamCapabFrequency
Enfants
Pas d'enfants disponibles pour cet OID
Détails
OID1.3.6.1.4.1.4491.2.1.23.1.3.1.1
Module DOCS-DRF-MIB (CISCO)
NomdocsDrfDownstreamCapabFrequency
Accesreadonly
Statuscurrent
DescriptionThe QAM channel frequency capabilities. 'qamDependency' BIT set to '1' indicates the QAM channel frequency value has dependencies with other QAM channels and an entry that includes this QAM channel is in in docsDrfGroupDependencyTable for the PHY parameter 'frequency'. 'adjacentChannel' BIT set to '1' indicates the QAM channel frequencies in the dependency group (DEPI TSID group) are adjacent and constrained in a frequency range based on the number of QAM channels in the dependency group. 'adjacentChannelOrder' BIT set to '1' indicates the QAM channel frequency adjacency is based in the QAM channel sequence like entPhysicalParentRelPos in EntPhysicalTable or other vendor sequence. e.g., a dependency group of four QAM channels with 'adjacentChannelOrder' BIT set to '1': The 4th QAM channel in the sequence gets a frequency assignment f + 1*bandwidth when the frequency value of the 3rd QAM channel in the sequence is set to f. Similarly the 1st QAM channel in the sequence gets a frequency assignment of f - 2*bandwidth and the 2nd QAM channels gets a frequency of f -1*bandwidth. 'adjacentChannel' 'adjacentChannelOrder' BITs may be set to '1' when a dependency group includes the QAM channel of this M-CMTS Downstream interface and the value of the object docsDrfGroupDependencyType is docsDrfPhyParamAdjacentValues. 'adjacentChannel' BIT may be set to '1' if 'qamDependency' BIT is set to '1'. The same way, 'adjacentChannelOrder' BIT may be set to '1' and implies 'adjacentChannel' BIT is set to '1'.
SyntaxeBits (0-qamDependency, 1-adjacentChannel, 2-adjacentChannelOrder)
|
__label__pos
| 0.623094 |
Jump to content
McKay Development
adammo
Member
• Posts
3
• Joined
• Last visited
adammo's Achievements
1. Thank you for your reply. I mean sent offers that get me items not sent items.
2. I know that getReceivedItems working with accepted offers but what I need that get the Items in the sent trade offers "not in the received trade offers" after accepted. Can I do that?how?
3. Hi, I made this code to send offer but the problem that I got that error "Error: HTTP error 401" When I using "manager.setCookies" I got the error access denied because my limited account . So I looked for another module "node-steam-tradeoffers" and it's working with "steam-weblogon" and "steam-web-api-key" and it's send the offers from my limited account, but I need to using your module, so I made this code which can make the api key. var Steam = require('steam'); var SteamWebLogOn = require('steam-weblogon'); var getSteamAPIKey = require('steam-web-api-key'); var SteamCommunity = require('steamcommunity'); var SteamTotp = require('steam-totp'); var TradeOfferManager = require('steam-tradeoffer-manager'); var fs = require('fs'); //var client = new SteamUser(); var community = new SteamCommunity(); var steamClient = new Steam.SteamClient(); var steamUser = new Steam.SteamUser(steamClient); var steamFriends = new Steam.SteamFriends(steamClient); var steamWebLogOn = new SteamWebLogOn(steamClient, steamUser); var manager = new TradeOfferManager({ "steam": steamClient, // Polling every 30 seconds is fine since we get notifications from Steam "domain": "localhost", // Our domain is example.com "language": "en" // We want English item descriptions }); if (fs.existsSync('polldata.json')) { manager.pollData = JSON.parse(fs.readFileSync('polldata.json')); } steamClient.connect(); steamClient.on('connected', function() { steamUser.logOn({ account_name: '*********', password: '***********', two_factor_code: SteamTotp.generateAuthCode('**********************') }); }); steamClient.on('logOnResponse', function(logonResp) { if (logonResp.eresult == Steam.EResult.OK) { console.log('Logged in!'); steamWebLogOn.webLogOn(function(sessionID, newCookie) { getSteamAPIKey({ sessionID: sessionID, webCookie: newCookie }, function(err, APIKey) { manager.apiKey = APIKey; var offer = manager.createOffer("************"); offer.addMyItem({"appid": 730, "contextid": 2, "assetid": "655530455"}); offer.send(function(err, status) { if (err) { console.log("send" + err); } else { console.log("Offer #" + offer.id + " " + status); } }); }); community.setCookies(newCookie); community.startConfirmationChecker(10000, '*********************************'); }); } });
×
×
• Create New...
|
__label__pos
| 0.716699 |
How to use the interact method to make basic widgets
By using the interact method and setting 'x' to 1 by default we get the following points:
1. The little widget pops up automatically, just above the plot:
# Basic interact usage with integer sliderdef f(x): plt.plot(np.arange(0,10), x*np.arange(0,10)) plt.ylim(-30,30)interact(f, x=1)
We will get the following output:
1. Without having to do any extra coding, except for this one very simple function, we actually get an interactive plot. This widget changes the slope of the plot automatically, based on the fact that this argument is an integer. As we change the slider, the line automatically ...
Get Mastering Matplotlib 2.x now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
|
__label__pos
| 0.94874 |
#!/bin/sh die () { echo "$*" >&2 exit 1 } doit () { echo "\$ $*" >&2 $* || die "[ERROR:$?]" } egrep -v '^t/.*\.t$' MANIFEST > MANIFEST~ ls -t t/*.t | sort >> MANIFEST~ diff MANIFEST MANIFEST~ > /dev/null || doit /bin/mv -f MANIFEST~ MANIFEST /bin/rm -f MANIFEST~ [ -f Makefile ] && doit rm -f Makefile doit perl Makefile.PL doit make doit make disttest main=`grep 'lib/.*pm$' < MANIFEST | head -1` [ "$main" == "" ] && die "main module is not found in MANIFEST" doit pod2text $main > README doit make dist doit /bin/rm -fr blib pm_to_blib ls -lt *.tar.gz | head -1
|
__label__pos
| 0.798865 |
when it is generated by a Content Management System (CMS). However, knowing that the specificity of above rule/selector is actually defined by counting the amount of "simple selectors", helped a lot to understand. ), and the second selector represents descendants. There is a
element which will not get selected and the paragraph element inside the div will also not get selected. Suppose we have to select all
elements that are the siblings of
element, then we can write it as: The figure given below helps us to understand the General sibling selector (~). In this article you'll learn about one of the least popular selectors called CSS Combinators. Combinators are extremely useful when you intend to target specific parts of your document, but it's difficult to reuse the CSS code elsewhere because it's solely for that specific part in your HTML document. The child combinator is represented by >, and this symbol is placed between two selectors (or more). All occurrence of the second selector within the first selector. There is plenty in the CSS Styling that you haven’t seen – but they will be covered in future tutorials. JavaTpoint offers too many high quality services. This combinator only matches the elements that are the immediate child in the document tree. The least being a parent element. Consider the clone page created in an earlier lesson, it had a #content section that contained three columns: You can style ALL p elements in the document using: You can also style all p elements that are immediate children of the #content section using the child combinator: But the child combinator will not select p elements if they are nested deeper: The descendant combinator allows you to create a selector for ALL p elements located inside a #content container – you can select immediate children, grandchildren and more deeply nested elements. The descendant combinator is more general than the child combinator and is useful for styling different sections of your document without having to specify the exact parent-child relationships. The first occurrence of the second selector after the first selector in the document hierarchy. The CSS combinators are included in between the simple selector. While
is a child of
and a sibling, to
,
,
, , and
, it is also, , Select a
element if it immediately follows, You might want the first paragraph following,
to be special in some way - perhaps a, slightly larger font or italicized. It is useful when we have to select the siblings of an element even if they are not adjacent directly. Consider the following (based on the More Advanced float Example): This is the most commonly used combinator. It is represented by the addition symbol in mathematics i.e. The descendant combinator — typically represented by a single space character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector. parent-child relationships match the selector. Your email address will not be published. It only selects the element which is just next to the specified first element. So the combinators are just not counted to the specificity declaring number. This combinator matches an element if it is next to an element in a document hierarchy. The position of the child. Between the simple selectors, we can include a combinator. The combinators are classified into four groups: The word "descendant" should give you an idea that for the combinator to match any element, an ancestor element must exist. Save my name, email, and website in this browser for the next time I comment. We're a place where coders share, stay up-to-date and grow their careers. Copies are sold in stores worldwide, or you can buy it in ebook form here . There are other selector types you can use (which will be covered over the next few tutorials) but, for now, it is accurate enough. Consider the following HTML code and the selector declared above: While I wrote the selector with a space around the combinator, there is no need for that. The combinators can be combined and you can more use more specific combinations of html elements, IDs, classes, and attributes: There is no combinator that allows you to select. Mail us on [email protected], to get more information about given services. Open source and radically transparent. In this chapter, you will learn about the descendant combinator and its working. I pulled the CSS from the main landing pages of the following: Take these numbers as a rough guide to their relative use – if you find yourself using a lot of, This is not entirely accurate. The
tag will NOT be selected because the, parent-child relationships do not match the. It can be a direct child or deeper than five levels, but it will still be referred to as a descendant. It only selects those paragraph elements that are the direct child of the div element. In this article we discussed combinator selectors which is a class of CSS selectors that are sparingly used compared to class selectors and ID selectors but sometimes come in handy when the markup is not large (and hopefully not) and you have no control over the HTML markup e.g. Templates let you quickly answer FAQs or store snippets for re-use. This example will illustrate the use of a General sibling selector (~). If we have to select the paragraph that comes immediately after another paragraph, then by using the adjacent selector, it will be written as follows: The figure given below helps us to understand the Adjacent sibling selector (+). It matches the second element only when the element immediately follows the first element, and both of them are the children of the same parent. The word descendant indicates nested anywhere in the DOM tree. In this figure, the blocks with the green color are the selected blocks affected after using the child selector. Assuming "CSS selector" and "CSS rule" being the exact same, your answer might bring some confusion. As well, processing from the inner elements to the outer elements is computationally more expensive – making page renders slower. 'rem' will be covered in a future tutorial. But those
elements that come after the
will be affected. As you recall, when you create your HTML page, you divide the page into various sections. In the example above, it selects an element with the class of .headline only if it is an immediate child of an element with the class of .card AND the element with the class of .card is an immediate child of an element with the class of .column-left.. ... Pseudo-classes can be combined with CSS classes: When you hover over the link in the example, it will change color: Example. This is useful for defining styles that are localized to particular sections of your webpage without having to rigidly follow the structure of your page: Remember to pay attention to the specificity of your selector: This is also known as the first sibling combinator and adjacent sibling combinator. There is an
element that will not be selected, and the paragraph element after the div will also not be selected. This allows for more powerful selection. The first two combinators allow you to select HTML elements based on how they are contained within other HTML elements – either as children, grandchildren, great-grandchildren, etc.
|
__label__pos
| 0.909348 |
Quick Answer: Can I Access My Old Hotmail Account?
Does Hotmail still exist 2020?
Microsoft is moving all of its Hotmail users to Outlook.com by this summer.
Microsoft announced earlier this week that it is closing Hotmail and moving the “hundreds of millions” still using it to Outlook.com by this summer..
Is Hotmail and Outlook the same?
One of many small parts of Microsoft’s communication subdivision, both Outlook and Hotmail are essentially one and the same thing. Microsoft has been using Hotmail as its main brand for its emailing service since 1997. … New users can only create an @Outlook.com account, just to make things more confusing.
Why can’t I access my Hotmail account?
There could be several reasons if you still cannot sign in to your Outlook account, from forgetting your password, to travelling, or using a new device. If you remember your password but it is not working, make sure that Caps Lock is turned off and your email address is spelled correctly.
Why is my Hotmail not working?
Sometimes the issue can be because of minor error or because the server is down. These are temporary issues and can be solved by restarting deice or by waiting for some time. Try these ways and see if the problem resolves. If not, then you can take help from the Hotmail customer support.
Where did my Hotmail emails go?
Outlook is migrating all hotmail.com accounts to Outlook.com. Therefore, Outlook.com is the official name of Microsoft’s email service, which was formerly known as Hotmail and Windows Live Hotmail. This means that your email address would now be @outlook.com instead of @hotmail.com.
Do old Hotmail accounts get deleted?
After 360 days (five days short of a typical year) of inactivity, a Windows Live Hotmail account is permanently deleted. If you don’t use your Windows Live ID (which is your Windows Live Hotmail email address) for 365 days (about a year), it too, can be permanently deleted.
Can I still log into my Hotmail account?
A Hotmail account IS an Outlook.com account. Just connect to https://outlook.live.com/, log in with your Hotmail address and password, and you should see your mail. Hotmail was renamed to Outlook.com back in 2012, but all addresses in use at that time were retained.
Can you have 2 Hotmail accounts?
Each user can create up to five aliases, any of which can be deleted and replaced with another at any time. Over time, Microsoft will increase that limit to 15 aliases per account, making it so that the true heavy users won’t need to juggle between two or more Hotmail accounts.
How do I access another Hotmail account?
Outlook allows you to add as many Hotmail accounts as you need to manage, so you can even add your personal Hotmail account.Click “File” in the top left corner of the Outlook window.Click the “Add Account” button in the Account Information section at the top to open the Add New Account window.More items…
How do I recover my old Hotmail from years ago?
A. Microsoft has a recovery page you can use at https://account.live.com/resetpassword.aspx to regain access to your Hotmail account. Along the way, you may be asked to enter the answers to security questions you previously set up, or to provide details about the account to prove your identity.
How do I reactivate my old Hotmail account?
How to fill out a Hotmail Recovery Form: Begin the process by visiting account.live.com/acsr and enter the email address, phone number, or username for the account you are trying to access. Next, provide an email address that Microsoft can use to contact you concerning your request.
|
__label__pos
| 0.971164 |
rag/rag.py
250 lines
9.6 KiB
Python
from sentence_transformers import SentenceTransformer
import chromadb
from llama_cpp import Llama
import copy
import logging
logging.basicConfig(filename='rag.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class RAG:
def __init__(self, llm_model_path, embed_model_name, collection_name, chromadb_path):
logging.info('INIT')
self.chat_history = []
self.tag_system = '<|system|>'
self.tag_user = '<|user|>'
self.tag_assistant = '<|assistant|>'
self.tag_end = '</s>'
self.rag_prompt = """
{tag_system}
Objectif
========
Vous êtes un assistant IA spécialiste des produits et services de la Caisse d'Epargne Rhône-Alpes, \
une banque régionale française.
Vous aidez un conseiller clientèle de la banque à mieux répondre aux besoins des clients.
Vous fournissez avec soin des réponses précises et factuelles aux questions du conseiller.
Utilisation du contexte
=======================
Vous répondez à la question posée par le conseiller en utilisant un contexte \
formé de passages exraits du site web commercial de la banque.
Votre réponse se base exclusivement sur les informations factuelles présentes dans le contexte.
Si vous ne pouvez pas répondre à la question sur la base des éléments du contexte, \
dites simplement que vous ne savez pas, n'essayez pas d'inventer une réponse.
Voici le format d'un passage du contexte :
```
Titre :
Le titre du passage
Catégorie :
La catégorie du passage
URL :
https://www.caisse-epargne.fr/rhone-alpes/url/du/passage
Contenu :
Le contenu du passage
```
Vos réponses doivent toujours citer l'URL des passages utilisés. \
Assurez-vous que l'URL citée correspond exactement à celle du passage. \
Ne générez pas de nouvelles URLs. \
Les conseillers sont encouragés à vérifier les URLs citées.
Format de réponse
=================
Formulez chaque réponse sous forme de recommandations directes et concises, \
en utilisant le langage et les termes présents dans le contexte.
Citez l'URL en fin de réponse ou immédiatement après la recommandation pertinente.
Vous rédigez votre réponse en français sous forme d'une liste d'informations \
synthétiques extraites du contexte et qui seront utiles au conseiller.
Vos utilisateurs savent qui vous êtes et quelles instructions vous avez reçues, \
il n'est pas nécessaire de le leur rapeler.
Voici le format que doit suivre votre réponse :
```
Voici des informations qui pourront aider votre client :
1. Utilisez [une solution spécifique du contexte] pour [traiter un aspect du problème]. Par exemple, [détail concret tiré du contexte]. Pour plus d'informations voir https://www.caisse-epargne.fr/rhone-alpes/url/du/passage
2. Considérez [une autre solution du contexte], qui est particulièrement adaptée pour [un autre aspect du problème]. Par exemple, [autre détail concret du contexte]. Pour plus d'informations voir https://www.caisse-epargne.fr/rhone-alpes/url/du/passage
```
{tag_end}
{history}
{tag_user}
Contexte :
==========
{context}
Question de l'utilisateur :
===========================
{query}
{tag_end}
{tag_assistant}
Voici des informations qui pourront aider votre client :
1.
"""
self.query_reformulate_prompt = """
{tag_system}
Instructions :
==============
Vous êtes un interprète conversationnel pour une conversation entre un utilisateur et \
un assistant IA spécialiste des produits et services de la Caisse d'Epargne Rhône-Alpes, \
une banque régionale française.
L'utilisateur vous posera une question sans contexte.
Vous devez reformuler la question pour prendre en compte le contexte de la conversation.
Vous devez supposer que la question est liée aux produits et services de la Caisse d'Epargne Rhône-Alpes.
Vous devez également consulter l'historique de la conversation ci-dessous lorsque vous reformulez la question.
Par exemple, vous remplacerez les pronoms par les noms les plus probables dans l'historique de la conversation.
Lorsque vous reformulez la question, accordez plus d'importance à la dernière question et \
à la dernière réponse dans l'historique des conversations.
L'historique des conversations est présenté dans l'ordre chronologique inverse, \
de sorte que l'échange le plus récent se trouve en haut de la page.
Répondez en seulement une phrase avec la question reformulée.
Historique de la conversation :
===============================
{history}
{tag_end}
{tag_user}
Reformulez la question suivante : "{query}"
{tag_end}
{tag_assistant}
Question reformulée : "
"""
self.prefix_assistant_prompt = '1. '
self.embed_model = SentenceTransformer(embed_model_name)
self.chroma_client = chromadb.PersistentClient(path=chromadb_path)
self.collection = self.chroma_client.get_collection(name=collection_name)
self.llm = Llama(model_path=llm_model_path, n_gpu_layers=1, use_mlock=True, n_ctx=4096)
def answer(self, prompt, stream):
response = self.llm(prompt = prompt,
temperature = 0.1,
mirostat_mode = 2,
stream = stream,
max_tokens = -1,
stop = [self.tag_end, self.tag_user])
if stream:
return response
else: return response["choices"][0]["text"]
def query_collection(self, query, n_results=3):
logging.info(f"query_collection / query: \n{query}")
query = 'query: ' + query
query_embedding = self.embed_model.encode(query, normalize_embeddings=True)
query_embedding = query_embedding.tolist()
results = self.collection.query(
query_embeddings=[query_embedding],
n_results=n_results,
)
ids_sources = ""
for i in range(len(results["documents"][0])):
id = results["ids"][0][i]
ids_sources += id + " ; "
logging.info(f"query_collection / sources: \n{ids_sources}")
return results
def format_passages(self, query_results):
result = []
for i in range(len(query_results["documents"][0])):
passage = query_results["documents"][0][i]
url = query_results["metadatas"][0][i]["url"]
category = query_results["metadatas"][0][i]["category"]
lines = passage.split('\n')
if lines[0].startswith('passage: '):
lines[0] = lines[0].replace('passage: ', '')
lines.insert(0, "###")
lines.insert(1, f"Passage {i+1}")
lines.insert(2, "Titre :")
lines.insert(4, "")
lines.insert(5, "Catégorie :")
lines.insert(6, category)
lines.insert(7, "")
lines.insert(8, "URL :")
lines.insert(9, url)
lines.insert(10, "")
lines.insert(11, "Contenu : ")
lines += ['']
result += lines
result = '\n'.join(result)
return result
def answer_rag_prompt_streaming(self, prompt):
logging.info(f"answer_rag_prompt_streaming: \n{prompt}")
ans = self.answer(prompt, stream=True)
yield self.prefix_assistant_prompt
for item in ans:
item = item["choices"][0]["text"]
self.chat_history[-1]['assistant'] += item
yield item
def answer_rag_prompt_non_streaming(self, prompt):
logging.info(f"answer_rag_prompt_non_streaming: \n{prompt}")
ans = self.answer(prompt, stream=False)
self.chat_history[-1]['assistant'] += ans
ans = self.prefix_assistant_prompt + ans
return ans
def prepare_prompt(self, query, query_results):
context = self.format_passages(query_results)
history = ""
for i in range(len(self.chat_history)):
history += f"<|user|>\n{self.chat_history[i]['user']}</s>\n"
history += f"<|assistant|>\n{self.chat_history[i]['assistant']}</s>\n"
self.chat_history.append({'user': query, 'assistant': self.prefix_assistant_prompt})
return self.rag_prompt.format(history=history, query=query, context=context,
tag_user=self.tag_user, tag_system=self.tag_system,
tag_assistant=self.tag_assistant, tag_end=self.tag_end)
def reformulate_query(self, query):
history = ""
for i in reversed(range(len(self.chat_history))):
history += f"Question de l'utilisateur :\n{self.chat_history[i]['user']}\n"
history += f"Réponse de l'assistant :\n{self.chat_history[i]['assistant']}\n"
prompt = self.query_reformulate_prompt.format(history=history, query=query,
tag_user=self.tag_user, tag_system=self.tag_system,
tag_assistant=self.tag_assistant, tag_end=self.tag_end)
logging.info(f"reformulate_query: \n{prompt}")
ans = self.answer(prompt, stream=False)
last_quote_index = ans.rfind('"')
if last_quote_index != -1:
ans = ans[:last_quote_index]
if len(ans) > 10:
logging.info(f"Requête reformulée : \"{ans}\"")
return ans
else:
logging.info(f"La requête n'a pas pu être reformulée.")
return query
def chat(self, query, stream=True):
if len(self.chat_history) > 0:
query = self.reformulate_query(query)
query_results = self.query_collection(query)
prompt = self.prepare_prompt(query, query_results)
if stream:
ans = self.answer_rag_prompt_streaming(prompt)
else:
ans = self.answer_rag_prompt_non_streaming(prompt)
return ans
def reset_history(self):
self.chat_history = []
|
__label__pos
| 0.999333 |
Libor Zahrádka Libor Zahrádka - 1 year ago 162
Javascript Question
NVD3 Chart responsive issue
NVD3 Responsive issue
I have code from my second page where I used the exactly same chart like here. But on that page it is responsive and I am trying to figure out why the chart is not responsive here.
enter image description here
var colors = ["rgba(74, 210, 255, .8)", "rgba(85, 172, 238, .8)", "rgba(205, 32, 31, .8)"];
d3.scale.colors = function() {
return d3.scale.ordinal().range(colors);
};
var colors = d3.scale.colors();
/*var colors = d3.scale.category20();*/
var keyColor = function(d, i) {return colors(d.key)};
var chart;
nv.addGraph(function() {
chart = nv.models.stackedAreaChart()
.useInteractiveGuideline(true)
.x(function(d) { return d[0] })
.y(function(d) { return d[1] })
.showControls(false)
.showYAxis(true)
.showLegend(false)
.rightAlignYAxis(true)
.controlLabels({stacked: "Stacked"})
.color(keyColor)
.duration(500);
chart.xAxis.tickFormat(function(d) { return d3.time.format('%a')(new Date(d)) });
chart.yAxis.tickFormat(d3.format('f'));
chart.legend.margin({
top: 30
});
d3.select('#chart1')
.datum(histcatexplong)
.transition().duration(1000)
.call(chart)
.each('start', function() {
setTimeout(function() {
d3.selectAll('#chart1 *').each(function() {
if(this.__transition__)
this.__transition__.duration = 1;
})
}, 0)
});
nv.utils.windowResize(chart.update);
return chart;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="slide1">
<div class="col-xs-12" id="margin-chart">
<svg id="chart1" style="width: 100%; height: 300px;"></svg>
</div>
</div>
Answer Source
I used the .animate function.
$("#slide").click(function () {
if ($('.slide1').hasClass('showtable')) {
$('.slide1.showtable').animate({height: 300}, 500).removeClass('showtable');
} else {
$('.slide1').animate({height: 0}, 500)
$('.slide1').addClass('showtable');
}
});
.slide1 {
position: relative;
width: 100%;
overflow: hidden;
right: 25px;
}
.slide1.showtable {
height: 0;
}
|
__label__pos
| 0.917941 |
[d299f1]: inst / rlocus.m Maximize Restore History
Download this file
354 lines (314 with data), 10.1 kB
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
## Copyright (C) 1996, 2000, 2004, 2005, 2006, 2007
## Auburn University. All rights reserved.
##
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or (at
## your option) any later version.
##
## 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.
##
## You should have received a copy of the GNU General Public License
## along with this program; see the file COPYING. If not, see
## <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## @deftypefn {Function File} {} rlocus (@var{sys})
## @deftypefnx {Function File} {[@var{rldata}, @var{k}] =} rlocus (@var{sys}, @var{increment}, @var{min_k}, @var{max_k})
## Display root locus plot of the specified @acronym{SISO} system.
##
## @strong{Inputs}
## @table @var
## @item sys
## @acronym{LTI} model. Must be a single-input and single-output (SISO) system.
## @item increment
## The increment used in computing gain values.
## @item min_k
## Minimum value of @var{k}.
## @item max_k
## Maximum value of @var{k}.
## @end table
##
## @strong{Outputs}
## @table @var
## @item rldata
## Data points plotted: in column 1 real values, in column 2 the imaginary values.
## @item k
## Gains for real axis break points.
## @end table
##
## @strong{Block Diagram}
## @example
## @group
## u + +---+ +------+ y
## ------>(+)----->| k |----->| SISO |-------+------->
## ^ - +---+ +------+ |
## | |
## +---------------------------------+
## @end group
## @end example
## @end deftypefn
## Author: David Clem
## Author: R. Bruce Tenison <[email protected]>
## Updated by Kristi McGowan July 1996 for intelligent gain selection
## Updated by John Ingram July 1996 for systems
## Adapted-By: Lukas Reichlin <[email protected]>
## Date: December 2009
## Version: 0.5
## TODO: Improve compatibility
function [rldata_r, k_break, rlpol, gvec, real_ax_pts] = rlocus (sys, increment, min_k, max_k)
## TODO: multiplot feature: rlocus (sys1, "b", sys2, "r", ...)
if (nargin < 1 || nargin > 4)
print_usage ();
endif
if (! isa (sys, "lti") || ! issiso (sys))
error ("rlocus: first argument must be a SISO LTI model");
endif
## Convert the input to a transfer function if necessary
[num, den] = tfdata (sys, "vector"); # extract numerator/denominator polynomials
lnum = length (num);
lden = length (den);
## equalize length of num, den polynomials
## TODO: handle case lnum > lden (non-proper models)
if (lden < 2)
error ("rlocus: system has no poles");
elseif (lnum < lden)
num = [zeros(1,lden-lnum), num]; # so that derivative is shortened by one
endif
olpol = roots (den);
olzer = roots (num);
nas = lden - lnum; # number of asymptotes
maxk = 0;
if (nas > 0)
cas = (sum (olpol) - sum (olzer)) / nas;
angles = (2*[1:nas]-1)*pi/nas;
## printf("rlocus: there are %d asymptotes centered at %f\n", nas, cas);
else
cas = angles = [];
maxk = 100*den(1)/num(1);
endif
## compute real axis break points and corresponding gains
dnum = polyder (num);
dden = polyder (den);
brkp = conv (den, dnum) - conv (num, dden);
real_ax_pts = roots (brkp);
real_ax_pts = real_ax_pts(find (imag (real_ax_pts) == 0));
real_ax_pts(polyval (num, real_ax_pts) == 0) = []; # avoid division by zero and therefore infinite k_break
k_break = -polyval (den, real_ax_pts) ./ polyval (num, real_ax_pts);
idx = find (k_break >= 0);
k_break = k_break(idx);
real_ax_pts = real_ax_pts(idx);
if (! isempty (k_break))
maxk = max (max (k_break), maxk);
endif
if (nas == 0)
maxk = max (1, 2*maxk); # get at least some root locus
else
## get distance from breakpoints, poles, and zeros to center of asymptotes
dmax = 3*max (abs ([vec(olzer); vec(olpol); vec(real_ax_pts)] - cas));
if (dmax == 0)
dmax = 1;
endif
## get gain for dmax along each asymptote, adjust maxk if necessary
svals = cas + dmax * exp (j*angles);
kvals = -polyval (den, svals) ./ polyval (num, svals);
maxk = max (maxk, max (real (kvals)));
endif
## check for input arguments:
if (nargin > 2)
mink = min_k;
else
mink = 0;
endif
if (nargin > 3)
maxk = max_k;
endif
if (nargin > 1)
if (increment <= 0)
error ("rlocus: increment must be positive");
else
ngain = fix ((maxk-mink)/increment);
endif
else
ngain = 30;
endif
## vector of gains
ngain = max (30, ngain);
gvec = linspace (mink, maxk, ngain);
if (length (k_break))
gvec = sort ([gvec, reshape(k_break, 1, [])]);
endif
## Find the open loop zeros and the initial poles
rlzer = roots (num);
## update num to be the same length as den
lnum = length (num);
if (lnum < lden)
num = [zeros(1,lden - lnum),num];
endif
## compute preliminary pole sets
nroots = lden - 1;
for ii = 1:ngain
gain = gvec(ii);
rlpol(1:nroots,ii) = vec(sort (roots (den + gain*num)));
endfor
## set smoothing tolerance
smtolx = 0.01*(max (max (real (rlpol))) - min (min (real (rlpol))));
smtoly = 0.01*(max (max (imag (rlpol))) - min (min (imag (rlpol))));
smtol = max (smtolx, smtoly);
## sort according to nearest-neighbor
rlpol = sort_roots (rlpol, smtolx, smtoly);
done = (nargin == 4); # perform a smoothness check
while (! done && ngain < 1000)
done = 1 ; # assume done
dp = abs (diff (rlpol.')).';
maxdp = max (dp);
## search for poles whose neighbors are distant
if (lden == 2)
idx = find (dp > smtol);
else
idx = find (maxdp > smtol);
endif
for ii = 1:length(idx)
i1 = idx(ii);
g1 = gvec(i1);
p1 = rlpol(:,i1);
i2 = idx(ii)+1;
g2 = gvec(i2);
p2 = rlpol(:,i2);
## isolate poles in p1, p2
if (max (abs (p2-p1)) > smtol)
newg = linspace (g1, g2, 5);
newg = newg(2:4);
gvec = [gvec,newg];
done = 0; # need to process new gains
endif
endfor
## process new gain values
ngain1 = length (gvec);
for ii = (ngain+1):ngain1
gain = gvec(ii);
rlpol(1:nroots,ii) = vec(sort (roots (den + gain*num)));
endfor
[gvec, idx] = sort (gvec);
rlpol = rlpol(:,idx);
ngain = length (gvec);
## sort according to nearest-neighbor
rlpol = sort_roots (rlpol, smtolx, smtoly);
endwhile
rldata = rlpol;
## Plot the data
if (nargout == 0)
rlpolv = vec(rlpol);
axdata = [real(rlpolv), imag(rlpolv); real(olzer), imag(olzer)];
axlim = __axis_limits__ (axdata);
rldata = [real(rlpolv), imag(rlpolv) ];
%inname = get (sys, "inname");
%outname = get (sys, "outname");
## build plot command args pole by pole
n_rlpol = rows (rlpol);
nelts = n_rlpol+1;
if (! isempty (rlzer))
nelts++;
endif
## add asymptotes
n_A = length (olpol) - length (olzer);
if (n_A > 0)
nelts += n_A;
endif
args = cell (3, nelts);
kk = 0;
## asymptotes first
if (n_A > 0)
len_A = 2*max (abs (axlim));
sigma_A = (sum(olpol) - sum(olzer))/n_A;
for i_A=0:n_A-1
phi_A = pi*(2*i_A + 1)/n_A;
args{1,++kk} = [sigma_A sigma_A+len_A*cos(phi_A)];
args{2,kk} = [0 len_A*sin(phi_A)];
if (i_A == 1)
args{3,kk} = "k--;asymptotes;";
else
args{3,kk} = "k--";
endif
endfor
endif
## locus next
for ii = 1:rows(rlpol)
args{1,++kk} = real (rlpol (ii,:));
args{2,kk} = imag (rlpol (ii,:));
if (ii == 1)
args{3,kk} = "b-;locus;";
else
args{3,kk} = "b-";
endif
endfor
## poles and zeros last
args{1,++kk} = real (olpol);
args{2,kk} = imag (olpol);
args{3,kk} = "rx;open loop poles;";
if (! isempty (rlzer))
args{1,++kk} = real (rlzer);
args{2,kk} = imag (rlzer);
args{3,kk} = "go;zeros;";
endif
axes;
set (gcf,"visible","off");
hplt = plot (args{:});
set (hplt(kk--), "markersize", 2);
if (! isempty (rlzer))
set (hplt(kk--), "markersize", 2);
endif
for ii = 1:rows(rlpol)
set (hplt(kk--), "linewidth", 2);
endfor
legend ("boxon", 2);
grid ("on");
axis (axlim);
title (["Root Locus of ", inputname(1)]);
xlabel (sprintf ("Real Axis gain = [%g, %g]", gvec(1), gvec(ngain)));
ylabel ("Imaginary Axis");
set (gcf (), "visible", "on");
else
rldata_r = rldata;
endif
endfunction
function rlpol = sort_roots (rlpol, tolx, toly)
## no point sorting of you've only got one pole!
if (rows (rlpol) == 1)
return;
endif
## reorder entries in each column of rlpol to be by their nearest-neighbors rlpol
dp = diff (rlpol.').';
drp = max (real (dp));
dip = max (imag (dp));
idx = find (drp > tolx | dip > toly);
if (isempty (idx))
return;
endif
[np, ng] = size (rlpol); # num poles, num gains
for jj = idx
vals = rlpol(:,[jj,jj+1]);
jdx = (jj+1):ng;
for ii = 1:rows(rlpol-1)
rdx = ii:np;
dval = abs (rlpol(rdx,jj+1)-rlpol(ii,jj));
mindist = min (dval);
sidx = min (find (dval == mindist)) + ii - 1;
if (sidx != ii)
c1 = norm (diff(vals.'));
[vals(ii,2), vals(sidx,2)] = swap (vals(ii,2), vals(sidx,2));
c2 = norm (diff (vals.'));
if (c1 > c2)
## perform the swap
[rlpol(ii,jdx), rlpol(sidx,jdx)] = swap (rlpol(ii,jdx), rlpol(sidx,jdx));
vals = rlpol(:,[jj,jj+1]);
endif
endif
endfor
endfor
endfunction
function [b, a] = swap (a, b)
endfunction
Get latest updates about Open Source Projects, Conferences and News.
Sign up for the SourceForge newsletter:
No, thanks
|
__label__pos
| 0.946495 |
We believe mastery takes time and you can't learn to be great at something if you're trying to learn in a hurry, but that isn't always the case. Developer entrepreneur Jack Kinsella, founder of Oxbridge Notes, came up with a method to learn to code faster so you can actually start making those apps you've always wanted to make.
Kinsella's approach is called the Janki method, and he designed it to hasten the learning process through a repetitious flashcard system called Anki. It works by following these eight rules:
1. Every time you learn something new create a question and answer flashcard and add this card to Anki.
2. You must use Anki every single day- including weekends and holidays – and commit to doing so indefinitely.
3. Learn in context. Pick a project, and learn only what you need to get it done.
4. Only add a card to your deck after having tried to use the item of knowledge therein.
5. Every time you make a mistake carry out a post-mortem and try to figure out the lessons in the experience. Think about what you would need to know to prevent that mistake from occurring again, and turn this insight into new flashcards.
6. At the end of every project ask yourself what lessons you learned and what you would do differently if you were to repeat the project with the benefit of hindsight.
7. Delete or modify any incorrect, outdated, difficult to remember, incomplete or unnecessary cards. Update existing cards as improved understanding dawns.
8. Read code regularly. If you come across something interesting – be that an algorithm, a hack, or an architectural decision – create a card detailing the technique and showing the code.
Advertisement
It works because you can recall code in an instant:
Knowing thousands of commands saves time otherwise spent looking up reference materials. You instantly recall previous solutions when faced with a problem, and dozen of possibilities spring to mind when architecting a system. You will read other people's code rapidly, confident in your understanding. The closest analogy is fluency in a natural language. You will speak code.
Even though you're inexperienced, you can still perform at a higher level because of that knowledge. Additionally, using this method provides you with a searchable database of everything you know. It's a pretty clever and novel approach to the somewhat daunting task of learning to code. If you're planning to pick up a programming language, you might want to give it a try. Kinsella goes into great detail about the system on his blog, and you can pick up your first few coding lessons from us.
Advertisement
Janki Method | Jack Kinsella
|
__label__pos
| 0.880217 |
专注于做有价值的技术原创
0%
实用 SQL 语句收藏这篇就够了
实用 SQL 语句收藏这篇就够了
1. 创建
1.1 创建数据库
语法:create database db_name
示例:创建应用数据库 awesome_app
1
create database `awesome_app`
1.2 创建表格
语法:create table table_name ( … columns )
示例:创建用户表 users
1
2
3
4
5
6
7
create table `users`
(
`id` int,
`name` char(10),
`avatar` varchar(300),
`regtime` date
)
1.3 创建索引
语法:create index index_name on table_name (column_name)
示例:为用户 id 创建索引 idx_id
1
2
3
create index `idx_id` on `users` (`id`)
/* 创建唯一索引 */
create unique index `idx_id` on `users` (`id`)
1.4 为已存在的列创建主键
更常用的方式是在创建表语句所有列定义的后面添加一行 primary key (column_name)
语法:alter table users add primary key (column_name)
示例:将用户 id 设为主键
1
alter table users add primary key (`id`)
1.5 为已存在的列创建自增约束
更常用的方式是在创建表语句中添加自增列 id int not null auto_increment
1
alter table `users` modify `id` int not null auto_increment
2. 插入
语法:
• insert into table_name values (value1, value2, …)
• insert into table_name (column1, column2, …) values (value1, value2, …)
示例:新增注册用户
1
2
3
insert into `users` values (1, 'ken', 'http://cdn.awesome_app.com/path/to/xxx/avatar1.jpg', curdate())
/* 指定列插入 */
insert into `users` (`name`, `avatar`) values ('bill', 'http://cdn.awesome_app.com/path/to/xxx/avatar2.jpg')
3. 修改
3.1 修改数据记录
语法:
• update table_name set column=new_value where condition
• update table_name set column1=new_value1,column2=new_value2,… where condition
示例:
1
2
3
update `users` set `regtime`=curdate() where `regtime` is null
/* 一次修改多列 */
update `users` set `name`='steven',`avatar`='http://cdn.awesome_app.com/path/to/xxx/steven.jpg' where `id`=1
3.2 修改数据库字符集为 utf8
1
alter database `awesome_app` default character set utf8
3.3 修改表字符集为 utf8
1
alter table `users` convert to character set utf8
3.4 修改表字段字符集为 utf8
1
alter table `users` modify `name` char(10) character set utf8
3.5 修改字段类型
1
alter table `users` modify `regtime` datetime not null
3.5 修改字段默认值
1
2
3
alter table `users` alter `regtime` set default '2019-10-12 00:00:00'
/* 设置默认为当前时间 current_timestamp,需要重新定义整个列 */
alter table `users` modify `regtime` datetime not null default current_timestamp
3.6 修改字段注释
1
2
3
4
alter table `users` modify `id` int not null auto_increment comment '用户ID';
alter table `users` modify `name` char(10) comment '用户名';
alter table `users` modify `avatar` varchar(300) comment '用户头像';
alter table `users` modify `regtime` datetime not null default current_timestamp comment '注册时间';
修改后,查看改动后的列:
1
2
3
4
5
6
7
8
9
mysql> show full columns from users;
+---------+--------------+-----------------+------+-----+-------------------+----------------+---------------------------------+--------------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+---------+--------------+-----------------+------+-----+-------------------+----------------+---------------------------------+--------------+
| id | int(11) | NULL | NO | PRI | NULL | auto_increment | select,insert,update,references | 用户ID |
| name | char(10) | utf8_general_ci | YES | | NULL | | select,insert,update,references | 用户名 |
| avatar | varchar(300) | utf8_general_ci | YES | | NULL | | select,insert,update,references | 用户头像 |
| regtime | datetime | NULL | NO | | CURRENT_TIMESTAMP | | select,insert,update,references | 注册时间 |
+---------+--------------+-----------------+------+-----+-------------------+----------------+---------------------------------+--------------+
4. 删除
4.1 删除数据记录
语法:delete from table_name where condition
示例:删除用户名未填写的用户
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 先增加一条用户名为空的用户
mysql> insert into `users` (`regtime`) values (curdate());
mysql> select * from users;
+----+--------+----------------------------------------------------+------------+
| id | name | avatar | regtime |
+----+--------+----------------------------------------------------+------------+
| 1 | steven | http://cdn.awesome_app.com/path/to/xxx/steven.jpg | 2019-10-12 |
| 2 | bill | http://cdn.awesome_app.com/path/to/xxx/avatar2.jpg | 2019-10-12 |
| 3 | NULL | NULL | 2019-10-12 |
+----+--------+----------------------------------------------------+------------+
# 删除用户名为空的行
mysql> delete from `users` where `name` is null;
mysql> select * from users;
+----+--------+----------------------------------------------------+------------+
| id | name | avatar | regtime |
+----+--------+----------------------------------------------------+------------+
| 1 | steven | http://cdn.awesome_app.com/path/to/xxx/steven.jpg | 2019-10-12 |
| 2 | bill | http://cdn.awesome_app.com/path/to/xxx/avatar2.jpg | 2019-10-12 |
+----+--------+----------------------------------------------------+------------+
4.2 删除数据库
1
drop database if exists `awesome_app`
4.3 删除表
1
drop table if exists `users`
4.4 清空表中所有数据
这个操作相当于先 drop tablecreate table ,因此需要有 drop 权限。
1
truncate table `users`
4.5 删除索引
1
drop index `idx_id` on `users`
5. 查询
5.1 语法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[PARTITION partition_list]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
5.2 单表查询
5.2.1 准备数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
insert into users (`name`, `avatar`) values
('张三', 'http://cdn.awesome_app.com/path/to/xxx/3.jpg'),
('李四', 'http://cdn.awesome_app.com/path/to/xxx/4.jpg'),
('王五', 'http://cdn.awesome_app.com/path/to/xxx/5.jpg'),
('马六', 'http://cdn.awesome_app.com/path/to/xxx/6.jpg'),
('肖七', 'http://cdn.awesome_app.com/path/to/xxx/7.jpg'),
('刘八', 'http://cdn.awesome_app.com/path/to/xxx/8.jpg'),
('杨九', 'http://cdn.awesome_app.com/path/to/xxx/9.jpg'),
('郑十', 'http://cdn.awesome_app.com/path/to/xxx/10.jpg');
/* 增加重复行 */
insert into users (`name`, `avatar`) values
('张三', 'http://cdn.awesome_app.com/path/to/xxx/3.jpg'),
('李四', 'http://cdn.awesome_app.com/path/to/xxx/4.jpg'),
('王五', 'http://cdn.awesome_app.com/path/to/xxx/5.jpg');
5.2.2 查询所有列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> select * from users;
+----+--------+----------------------------------------------------+---------------------+
| id | name | avatar | regtime |
+----+--------+----------------------------------------------------+---------------------+
| 1 | steven | http://cdn.awesome_app.com/path/to/xxx/steven.jpg | 2019-10-12 00:00:00 |
| 2 | bill | http://cdn.awesome_app.com/path/to/xxx/avatar2.jpg | 2019-10-12 00:00:00 |
| 3 | 张三 | http://cdn.awesome_app.com/path/to/xxx/3.jpg | 2019-10-13 10:58:37 |
| 4 | 李四 | http://cdn.awesome_app.com/path/to/xxx/4.jpg | 2019-10-13 10:58:37 |
| 5 | 王五 | http://cdn.awesome_app.com/path/to/xxx/5.jpg | 2019-10-13 10:58:37 |
| 6 | 马六 | http://cdn.awesome_app.com/path/to/xxx/6.jpg | 2019-10-13 10:58:37 |
| 7 | 肖七 | http://cdn.awesome_app.com/path/to/xxx/7.jpg | 2019-10-13 10:58:37 |
| 8 | 刘八 | http://cdn.awesome_app.com/path/to/xxx/8.jpg | 2019-10-13 10:58:37 |
| 9 | 杨九 | http://cdn.awesome_app.com/path/to/xxx/9.jpg | 2019-10-13 10:58:37 |
| 10 | 郑十 | http://cdn.awesome_app.com/path/to/xxx/10.jpg | 2019-10-13 10:58:37 |
| 11 | 张三 | http://cdn.awesome_app.com/path/to/xxx/3.jpg | 2019-10-13 11:20:17 |
| 12 | 李四 | http://cdn.awesome_app.com/path/to/xxx/4.jpg | 2019-10-13 11:20:17 |
| 13 | 王五 | http://cdn.awesome_app.com/path/to/xxx/5.jpg | 2019-10-13 11:20:17 |
+----+--------+----------------------------------------------------+---------------------+
5.2.3 查询指定列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> select id,name from users;
+----+--------+
| id | name |
+----+--------+
| 1 | steven |
| 2 | bill |
| 3 | 张三 |
| 4 | 李四 |
| 5 | 王五 |
| 6 | 马六 |
| 7 | 肖七 |
| 8 | 刘八 |
| 9 | 杨九 |
| 10 | 郑十 |
| 11 | 张三 |
| 12 | 李四 |
| 13 | 王五 |
+----+--------+
5.2.4 查询不重复记录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mysql> select distinct name,avatar from users;
+--------+----------------------------------------------------+
| name | avatar |
+--------+----------------------------------------------------+
| steven | http://cdn.awesome_app.com/path/to/xxx/steven.jpg |
| bill | http://cdn.awesome_app.com/path/to/xxx/avatar2.jpg |
| 张三 | http://cdn.awesome_app.com/path/to/xxx/3.jpg |
| 李四 | http://cdn.awesome_app.com/path/to/xxx/4.jpg |
| 王五 | http://cdn.awesome_app.com/path/to/xxx/5.jpg |
| 马六 | http://cdn.awesome_app.com/path/to/xxx/6.jpg |
| 肖七 | http://cdn.awesome_app.com/path/to/xxx/7.jpg |
| 刘八 | http://cdn.awesome_app.com/path/to/xxx/8.jpg |
| 杨九 | http://cdn.awesome_app.com/path/to/xxx/9.jpg |
| 郑十 | http://cdn.awesome_app.com/path/to/xxx/10.jpg |
+--------+----------------------------------------------------+
5.2.5 限制查询行数
查询前几行
1
2
3
4
5
6
7
mysql> select id,name from users limit 2;
+----+--------+
| id | name |
+----+--------+
| 1 | steven |
| 2 | bill |
+----+--------+
查询从指定偏移(第一行为偏移为0)开始的几行
1
2
3
4
5
6
7
8
mysql> select id,name from users limit 2,3;
+----+--------+
| id | name |
+----+--------+
| 3 | 张三 |
| 4 | 李四 |
| 5 | 王五 |
+----+--------+
5.2.6 排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 正序
mysql> select distinct name from users order by name asc limit 3;
+--------+
| name |
+--------+
| bill |
| steven |
| 刘八 |
+--------+
# 倒序
mysql> select id,name from users order by id desc limit 3;
+----+--------+
| id | name |
+----+--------+
| 13 | 王五 |
| 12 | 李四 |
| 11 | 张三 |
+----+--------+
5.2.7 分组
增加城市字段
1
2
3
4
5
6
7
alter table `users` add `city` varchar(10) comment '用户所在城市' after `name`;
update `users` set `city`='旧金山' where `id`=1;
update `users` set `city`='西雅图' where `id`=2;
update `users` set `city`='北京' where `id` in (3,5,7);
update `users` set `city`='上海' where `id` in (4,6,8);
update `users` set `city`='广州' where `id` between 9 and 10;
update `users` set `city`='深圳' where `id` between 11 and 13;
按城市分组统计用户数
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
mysql> select city, count(name) as num_of_user from users group by city;
+-----------+-------------+
| city | num_of_user |
+-----------+-------------+
| 上海 | 3 |
| 北京 | 3 |
| 广州 | 2 |
| 旧金山 | 1 |
| 深圳 | 3 |
| 西雅图 | 1 |
+-----------+-------------+
mysql> select city, count(name) as num_of_user from users group by city having num_of_user=1;
+-----------+-------------+
| city | num_of_user |
+-----------+-------------+
| 旧金山 | 1 |
| 西雅图 | 1 |
+-----------+-------------+
mysql> select city, count(name) as num_of_user from users group by city having num_of_user>2;
+--------+-------------+
| city | num_of_user |
+--------+-------------+
| 上海 | 3 |
| 北京 | 3 |
| 深圳 | 3 |
+--------+-------------+
5.3 多表关联查询
5.3.1 准备数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
create table if not exists `orders`
(
`id` int not null primary key auto_increment comment '订单ID',
`title` varchar(50) not null comment '订单标题',
`user_id` int not null comment '用户ID',
`cretime` timestamp not null default current_timestamp comment '创建时间'
);
create table if not exists `groups`
(
`id` int not null primary key auto_increment comment '用户组ID',
`title` varchar(50) not null comment '用户组标题',
`cretime` timestamp not null default current_timestamp comment '创建时间'
);
alter table `users` add `group_id` int comment '用户分组' after `city`;
insert into `groups` (`title`) values ('大佬'), ('萌新'), ('菜鸡');
insert into `orders` (`title`, `user_id`) values ('《大佬是怎样炼成的?》', 3), ('《MySQL 从萌新到删库跑路》', 6), ('《菜鸡踩坑记》', 9);
update `users` set `group_id`=1 where `id` between 1 and 2;
update `users` set `group_id`=2 where `id` in (4, 6, 8, 10, 12);
update `users` set `group_id`=3 where `id` in (3, 5, 13);
5.3.2 join
join
用于在多个表中查询相互匹配的数据。
1
2
3
4
5
6
7
8
mysql> select `users`.`name` as `user_name`, `orders`.`title` as `order_title` from `users`, `orders` where `orders`.`user_id`=`users`.`id`;
+-----------+--------------------------------------+
| user_name | order_title |
+-----------+--------------------------------------+
| 张三 | 《大佬是怎样炼成的?》 |
| 马六 | 《MySQL 从萌新到删库跑路》 |
| 杨九 | 《菜鸡踩坑记》 |
+-----------+--------------------------------------+
inner join
内部连接。效果与 join 一样 , 但用法不同,join 使用 whereinner join 使用 on
1
2
3
4
5
6
7
8
mysql> select `users`.`name` as `user_name`, `orders`.`title` as `order_title` from `users` inner join `orders` on `orders`.`user_id`=`users`.`id`;
+-----------+--------------------------------------+
| user_name | order_title |
+-----------+--------------------------------------+
| 张三 | 《大佬是怎样炼成的?》 |
| 马六 | 《MySQL 从萌新到删库跑路》 |
| 杨九 | 《菜鸡踩坑记》 |
+-----------+--------------------------------------+
left join
左连接。返回左表所有行,即使右表中没有匹配的行,不匹配的用 NULL 填充。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> select `users`.`name` as `user_name`, `orders`.`title` as `order_title` from `users` left join `orders` on `orders`.`user_id`=`users`.`id`;
+-----------+--------------------------------------+
| user_name | order_title |
+-----------+--------------------------------------+
| 张三 | 《大佬是怎样炼成的?》 |
| 马六 | 《MySQL 从萌新到删库跑路》 |
| 杨九 | 《菜鸡踩坑记》 |
| steven | NULL |
| bill | NULL |
| 李四 | NULL |
| 王五 | NULL |
| 肖七 | NULL |
| 刘八 | NULL |
| 郑十 | NULL |
| 张三 | NULL |
| 李四 | NULL |
| 王五 | NULL |
+-----------+--------------------------------------+
right join
右连接。和 left join 正好相反,会返回右表所有行,即使左表中没有匹配的行,不匹配的用 NULL 填充。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> select `groups`.`title` as `group_title`, `users`.`name` as `user_name` from `groups` right join `users` on `users`.`group_id`=`groups`.`id`;
+-------------+-----------+
| group_title | user_name |
+-------------+-----------+
| 大佬 | steven |
| 大佬 | bill |
| 萌新 | 李四 |
| 萌新 | 马六 |
| 萌新 | 刘八 |
| 萌新 | 郑十 |
| 萌新 | 李四 |
| 菜鸡 | 张三 |
| 菜鸡 | 王五 |
| 菜鸡 | 王五 |
| NULL | 肖七 |
| NULL | 杨九 |
| NULL | 张三 |
+-------------+-----------+
5.3.3 union
union 用于合并两个或多个查询结果,合并的查询结果必须具有相同数量的列,并且列拥有形似的数据类型,同时列的顺序相同。
1
2
3
4
5
6
7
8
9
10
11
mysql> (select `id`, `title` from `groups`) union (select `id`, `title` from `orders`);
+----+--------------------------------------+
| id | title |
+----+--------------------------------------+
| 1 | 大佬 |
| 2 | 萌新 |
| 3 | 菜鸡 |
| 1 | 《大佬是怎样炼成的?》 |
| 2 | 《MySQL 从萌新到删库跑路》 |
| 3 | 《菜鸡踩坑记》 |
+----+--------------------------------------+
6. 函数
6.1 语法
select function(column) from table_name
6.2 合计函数(Aggregate functions)
合计函数的操作面向一系列的值,并返回一个单一的值。通常与 group by 语句一起用。
函数 描述
avg(column) 返回某列的平均值
count(column) 返回某列的行数(不包括 NULL 值)
count(*) 返回被选行数
first(column) 返回在指定的域中第一个记录的值
last(column) 返回在指定的域中最后一个记录的值
max(column) 返回某列的最高值
min(column) 返回某列的最低值
sum(column) 返回某列的总和
6.3 标量函数(Scalar functions)
函数 描述
ucase(c) 转换为大写
lcase(c) 转换为小写
mid(c, start[, end]) 从文本提取字符
len(c) 返回文本长度
instr(c, char) 返回在文本中指定字符的数值位置
left(c, number_of_char) 返回文本的左侧部分
right(c, number_of_char) 返回文本的右侧部分
round(c, decimals) 对数值指定小数位数四舍五入
mod(x, y) 取余(求模)
now() 返回当前的系统日期
format(c, format) 格式化显示
datediff(d, date1, date2) 日期计算
参考
• [1] www.w3school.com.cn
• [2] dev.mysql.com
• [3] sql-syntax-server-administration
青笔 wechat
我是一条小青蛇 我有很多小秘密
• 本文作者: 青笔
• 本文链接: http://www.qingbii.com/2019/10/13/sql/
• 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
|
__label__pos
| 0.979498 |
DEV Community
Cover image for Don't be an SMS Spammer. Build a tool to help you manage your SMS using Twilio and Retool.
Eric Goldman
Eric Goldman
Posted on • Updated on • Originally published at docs.sequin.io
Don't be an SMS Spammer. Build a tool to help you manage your SMS using Twilio and Retool.
In this tutorial, you'll add text messaging to a Retool app using Twilio and Sequin.
Text messages (SMS) are an excellent medium for chatting with customers or notifying your team. Adding text messaging to a Retool app is easy with Twilio. Still, there are many prerequisites: Before you can send your first SMS from Retool, you'll need to set up and deploy a server that adequately handles Twilio webhooks. Then, as messages come in and out, you'll need to implement middleware to match conversations to your users appropriately. And if you want to pull insights from your conversations, you'll need to work out a process for extracting your data from Twilio.
Using Sequin, you'll skip these prerequisites. Sequin replicates Twilio to your Postgres database in real-time. No need to handle webhooks, deploy a server, or rethink your schema. With all your Twilio data in your database, mapping conversations to users is a simple JOIN. Pair a Sequin database with Retool's first-class support for SQL - and you can add SMS (or phone calls, WhatsApp, etc.) to your app in no time.
To show you how these systems work together, you'll build a Retool app that allows you to select a user, read text message conversation history, and continue the conversation by sending a new reply.
Setting up Twilio
You'll need a Twilio account and a Twilio phone number. Follow Twilio's quickstart guide to get your account and phone number set up.
Out of the box, Twilio uses webhooks to notify you of incoming messages. Without a webhook in place, Twilio will automatically respond to any incoming messages with errors. To assign a webhook to your new phone number, navigate to the active numbers page and select the phone number you just created:
Select phone
Scroll down to the messaging section, and under A message comes in select webhook. Enter Sequin's homepage (https://sequin.io), select HTTP GET, and click Save:
Add webhook
As the last step, you'll want to be able to test your new messaging capabilities. To make testing possible, go to the Verified Caller ID's page and click the + button to enter and verify a phone number you can send and receive texts from:
Verify number
You've now configured Twilio so that you can send and receive text messages. Before moving on, note down your Twilio credentials from your Twilio dashboard:
Twilio details
• Phone number
• Account SID
• Auth token
Setting up Sequin
Sequin will sync your Twilio data to a Postgres database in real-time. Within a couple of seconds, all new Twilio conversation data will be updated in your database.
To get your Twilio sync started, create a Sequin account and then select Twilio as your source:
Select Twilio
Enter your Twilio Account SID and Auth Token (which you noted down earlier).
For your destination, you have two options. You can sync to a Sequin-hosted database that will be immediately provisioned for you. Or, you can select to sync to your self-hosted database. To get up and running quickly in this tutorial, select to sync to a new Sequin database.
Enter twilio details
For your full application, you'll likely want to sync to your database so you have more control and can query across your data with ease. You can learn more about syncing to your database in the Sequin docs.
Now, click Start syncing. Sequin will provision your database and begin syncing your Twilio data. You can learn more about the full sync process in our Twilio reference docs.
You'll be presented with the credentials for your database. Note down these credentials or keep the Sequin tab open as you set up Retool.
Setting up your data
The purpose of your Retool app is to quickly allow you to communicate with users or your team members using SMS. So your app is going to need some user data.
Ideally, you already have this data (i.e., names and phone numbers) in your database. But for this tutorial, we'll use some fake data in Airtable to help jump-start the process:
Airtable base
If you don't have one already, create a free Airtable account. Then, open up the Airtable template we put together for this tutorial and copy it to your workspace by clicking the Copy base link in the top right corner.
Open the Twilio + Retool + Sequin base you just added to your workspace, and in the first row, enter your details - including the phone number that you verified in your Twilio account earlier.
Now, sync your Airtable base to your Sequin database. To do so, head back to Sequin and click the Add Sync button. Select Airtable and enter your Airtable API Key (which you can find on your Airtable account page). Select the Twilio + Retool + Sequin base and sync all the tables:
Sync Airtable
To make things easier, sync your sample user data to the same database you are using for your Twilio data. This way, you'll only need to connect one database to Retool and simplify your queries. To do so, click the Edit button in the Destination section and select Choose existing:
Select existing DB
In the window that appears, select the database that contains your Twilio data:
Select existing DB
Change the name of the schema Sequin will sync to. Something like users will be easy and short. Then click Confirm changes:
Select existing DB
Finally, click the Create button to sync your data into a new schema within the same database containing all your Twilio data.
Setting up Retool
With all your data in place, you're ready to connect your Sequin database and Twilio to Retool.
To get going, create a free Retool account, then go to the Resources tab and click the Create new button. Select Postgres.
Enter the name for your resource (i.e., Sequin) and then enter the Host, Port, Database name, Database username, and Password for your Sequin database (you can use the credentials from either your Twilio resource or your Airtable sample data resource — since both are in the same database, the credentials are the same!). You can copy and paste these from Sequin. Then click the blue Create resource button:
Add Sequin
With your Sequin database connected, you'll now create a Twilio resource so you can easily write to the Twilio API. On the resources tab, click the Create new button again. This time, select Twilio.
Give your resource a name (something like Twilio :) ) and then enter your Twilio Account SID and Twilio Auth token, which you noted earlier. Click Create resource again.
Add Twilio
Building your Retool app
For this Retool app, you want to select a user, see their details and conversation history, and then continue the conversation by sending a new text message to the user.
To build this app, you'll first scaffold the front-end in Retool. Then you'll populate that front-end with data by querying your Sequin database. Finally, you'll add the ability to write and send new text messages to the selected user.
To get started, create a new blank Retool app by clicking the Create new button and selecting Create a blank app. Then name your app something like Comms Central Command.
Scaffold the UI
The interface for this app will have four main components:
1. A table where you can sort, search, and find the user you want to chat with.
2. A user details card that shows some details about the user.
3. A chat timeline that shows the chronological order of sent and received messages.
4. A form where you can compose and send new messages.
Drag and drop the following components onto your canvas and enter placeholder text for now:
Scaffold the UI
If you need more guidance on scaffolding your UI, check out our more thorough step-by-step Retool tutorial here.
Query your data
With your scaffolding in place, begin to add data to your application, starting with the users table.
Open up the bottom drawer where you can create a new query. Select your Sequin Postgres database as the resource and enter the following query:
SELECT
id_,
string_agg(first_name || ' ' || last_name, ',') as "name",
email,
phone
FROM users.users
GROUP BY id_, email, phone;
Enter fullscreen mode Exit fullscreen mode
This query selects several columns from the users table within the users schema. It also performs a string aggregation to concatenate the first_name and last_name columns.
Click Save and run and then rename the query get_users:
Get users
Now, pipe the data from your new get_users query into the table component. Select the table component on the canvas and in the inspector on the right, enter {{get_users.data}} into the data field. The double brackets tell Retool you'll be entering JavaScript. Then the get_users.data pulls the data in from the query.
You'll see the table now contains the data from your query:
Populate table
With your user data in the table, you can now populate the user details card.
Select the First Last placeholder text in the card. In the inspector on the right, replace the value with # {{table1.selectedRow.data.name}}. This javascript statement pulls the name field from the selected row in your table:
Populate card 1
Finish populating the customer card by selecting the 📨 user_email | 💬 user_phone placeholder text. Replace the value in the inspector with 📨 {{table1.selectedRow.data.email}} | 💬 {{table1.selectedRow.data.phone}}. As before, this statement pulls in the user's email and phone details from the selected row in the table component:
Populate card 2
You have your user table and user details card populating with data. Now, pull in the conversations for each user from the message table in your Sequin database.
The first step in pulling in the users's messages is to join the user data to the message data using the phone number. To do so, you need to ensure that the format of the phone number is consistent. Twilio uses the E.164 standard format for phone numbers - so you'll need a helper function to ensure all your user's phone numbers are converted into the E.164 format.
Create a helper function by opening up the bottom drawer, and clicking to create a new JavaScript transformer. Then, paste in the following script:
let newString = {{table1.selectedRow.data.phone}}.match(/[0-9]{0,14}/g);
if (newString === null) {
return '';
}
// Join parts returned from RegEx match
newString = newString.join('');
// Start number with "+"
newString = '+' + newString;
// Limit length to 15 characters
newString = newString.substring(0, 15);
return newString;
Enter fullscreen mode Exit fullscreen mode
This script pulls in the selected phone number from the table and uses RegEx to format and return the phone number in E.164 format.
Save this helper function and name it e164_phone:
Transformer
Now, create a new query on your Sequin Postgres database and paste in the following:
SELECT
message.date_sent,
message.direction,
message.from,
message.to,
message.body
FROM
message
WHERE
message.from = {{e164_phone.value}}
OR message.to = {{e164_phone.value}}
ORDER BY message.date_sent asc;
Enter fullscreen mode Exit fullscreen mode
This query uses the phone number for the selected user (formatted in e.164 by your helper function) to pull in any message sent to or received from that user. Even though the query returns an empty table for now (you haven't sent or received a text yet from your Twilio phone number) can click to save the query and name it get_messages:
Get messages
We'll want to run this query every 15 seconds or so to see if any new messages from the user arrived. Click on the Advanced tab and check the box to Run this query periodically. Then, set the period interval to 15000:
Get messages
Finally, map this query to your UI by selecting the timeline component. In the inspector, make the following changes:
• Select Grouped
• For Items enter: {{get_messages.data.body}}
• For Timestamps enter: {{get_messages.data.date_sent}}
The timeline will appear blank (we still haven't sent a message yet!) but your UI is now pulling in all the data you need from your database:
Set timeline
Send and receive messages
With your database reads working, your Retool app is already configured to receive incoming messages. Now, you'll setup Twilio with the Sequin /wait endpoint to send messages - completing the loop.
Open the bottom drawer in Retool and create a new query on your Twilio resource as follows:
Send SMS
• Operation: POST to the /2010-04-01/Accounts/{AccountSid}/Messages.json
• To: {{format_for_twilio.value}} - this is the phone number of the selected customer.
• From: Your Twilio phone number (enter it as a string using "")
• Body: {{textArea1.value}} - this is the value of the text input in your UI.
Save the query and name it send_sms.
After sending a message to a user, you'll want to run the get_messages query to populate the new message into your UI. Sequin provides a convenient /wait endpoint. It will return a 200 ok after all events have been written to the database. This ensure that when you query your database for new messages it includes the message you just sent.
To configure this into your Retool app, click to create one more query and select RESTQuery as the resource. Then, configure the query as a simple GET request to the wait/ URL for your Twilio resource (you can get the unique wait/ endpoint for your resource from the Sequin console by clicking the Connect button on your resource):
Wait
Click Save and run. Then name your query sync_inc_wait.
Now, you need to chain these queries together: As soon as a message is sent, the /wait endpoint is called, then the get_messages query is run, and simultaneously the form for sending the text messages is cleared.
To do so, open the send_sms query, and under Event handlers click the New link. Configure the event handler to trigger the sync_inc_wait query on success. Then Save your changes:
Event 1
Now, reopen the sync_inc_wait query and add two more event handlers:
Event 2
• On success, trigger the get_messages query.
• On success, clear the value of the textArea1 component.
The last step is to connect the send_sms query to your app.
Select the Send button in your UI, and add an event handler that triggers the send_sms query when clicked:
Event 3
Test your app
Let's see your app in action. Select your test user in the table (i.e., the user with your validated phone number). Then, compose a quick message to yourself and click the Send button.
Voila - the message is sent! On your phone, reply to the message... and it appears in your app:
Final
Next steps
You can now message anyone with a phone number from your Retool app. You didn't need to setup a back-end, deal with webhooks, or think twice about missing an event. You used SQL to quickly pull your data together, and Retools easy to build UI and query management to string it all together.
From here, you can tailor the app to your needs. Add workflows, validation, bulk messaging, and more.
Top comments (0)
|
__label__pos
| 0.58292 |
Trigonometric Substitutions
Trigonometric Substitutions
• Currently 4.0/5 Stars.
3139 views, 1 rating - 00:21:18
Taught by Houston
Meets NCTM Standards:
Copyright 2005, Department of Mathematics, University of Houston. Created by Selwyn Hollis. Find more information on videos, resources, and lessons at http://online.math.uh.edu/HoustonACT/videocalculus/index.html.
Sine, tangent, and secant substitutions.
• What is trig substitution?
• What is sine substitution?
• What is the integral of the square root of 1 - x^2?
• How do you take the integral of the square root of 4 - x^2 / x?
• What is tangent substitution?
• How do you use secant substitution?
This video explains how and why trigonometric substitution works. You will see the right triangle trigonometry that helps you remember how it all works. Then, some really great examples are shown depicting trig substitution. There is a really helpful summary at the end of the video that explains when to use each substitution, when you have a^2 - u^2, a^2 + u^2, or u^2 - a^2.
• Currently 4.0/5 Stars.
Reviewed by MathVids Staff on December 20, 2008.
Browse Store
App_store_badge Smart-logo
|
__label__pos
| 0.872975 |
python直接绘制函数图像用matplot
时间: 2023-08-12 10:03:15 浏览: 20
lib库可以实现。以下是一个简单的例子,展示了如何使用 matplotlib 绘制函数 y = x^2 的图像: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(-5, 5, 0.1) y = x**2 plt.plot(x, y) plt.show() ``` 这个例子中,首先使用 NumPy 库生成了一个从 -5 到 5 的间隔为 0.1 的数组 x,然后计算了对应的 y 值。接着,使用 matplotlib 的 plot 函数将 x 和 y 的值画在坐标系上,并使用 show 函数显示图像。你可以根据需要修改 x 和 y 的值,以及调整坐标系的范围、颜色、线条样式等参数来定制自己的图像。
相关问题
用python编写绘制函数图像程序
Python是一种流行的编程语言,它可以用于多种领域,包括数据分析、机器学习等等。在Python中,我们可以使用不同的库来完成各种任务。绘制函数图像也是其中之一。 绘制函数图像的程序主要使用matplotlib库。Matplotlib是一个常用的绘图库,提供了许多绘图方法,可以绘制线性图、散点图、条形图等多种图形。使用Matplotlib库,我们可以轻松地绘制各种函数图像。 首先,在Python中安装Matplotlib库。安装完成后,我们需要确定绘图范围和细节(例如颜色、线型等)。然后,我们可以使用Matplotlib库中的plot函数,绘制我们所需的图像。 例如,我们想绘制y=x^2的图像。我们首先需要定义一个x的范围。我们可以使用numpy库生成一个等差数列: import numpy as np x = np.linspace(-10,10,1000) 这将创建一个包含1000个从-10到10的等差数列的数组x。现在,我们可以定义一个y的值: y = x**2 现在我们可以使用Matplotlib的plot函数来绘制这个图像: import matplotlib.pyplot as plt plt.plot(x,y) plt.show() 这样,我们就可以得到这个函数的图像了。使用Matplotlib库,您可以轻松地绘制各种函数图像。
python如何绘制函数图像
Python可以使用许多库来绘制函数图像,其中最常用的是matplotlib库。下面是一些示例代码,演示如何使用matplotlib库来绘制函数图像。 首先,需要安装matplotlib库。可以使用以下命令在终端或命令提示符中安装: ``` pip install matplotlib ``` 然后,可以使用以下代码来导入matplotlib库和numpy库: ```python import matplotlib.pyplot as plt import numpy as np ``` 接下来,可以定义要绘制的函数。例如,下面是一个简单的正弦函数: ```python def f(x): return np.sin(x) ``` 然后,可以使用以下代码来生成x和y值,并使用plot函数绘制函数图像: ```python x = np.linspace(-np.pi, np.pi, 100) y = f(x) plt.plot(x, y) plt.show() ``` 这将绘制一个正弦函数的图像,其中x轴的范围为-π到π,y轴的范围为-1到1。 除了基本的plot函数之外,matplotlib还提供了许多其他的绘图函数和选项,可以用来自定义图像的外观和行为。可以查看matplotlib文档以了解更多信息。
相关推荐
### 回答1: 要绘制三角函数图像,需要使用Python中的Matplotlib库。首先,需要导入库和设置x轴的范围: python import numpy as np import matplotlib.pyplot as plt x = np.linspace(-2*np.pi, 2*np.pi, 500) 接下来,可以分别绘制正弦函数、余弦函数和正切函数的图像: python # 绘制正弦函数的图像 y = np.sin(x) plt.plot(x, y) plt.title("Sine Function") # 绘制余弦函数的图像 y = np.cos(x) plt.plot(x, y) plt.title("Cosine Function") # 绘制正切函数的图像 y = np.tan(x) plt.plot(x, y) plt.ylim(-10, 10) # 由于正切函数的值域为实数集,因此需要设置y轴的范围 plt.title("Tangent Function") plt.show() 运行代码后,就可以看到三角函数的图像了。 ### 回答2: 要使用Python绘制三角函数的图像,可以使用matplotlib库来实现。 首先,需要导入相应的库: import numpy as np import matplotlib.pyplot as plt 然后,定义要绘制的x轴范围和间隔: x = np.linspace(-2*np.pi, 2*np.pi, 100) 接下来,可以通过numpy库来计算对应x值的三角函数值: y_sin = np.sin(x) y_cos = np.cos(x) y_tan = np.tan(x) 然后,创建一个图像窗口,并设置x和y轴的标签: plt.figure(figsize=(8, 6)) plt.xlabel('x') plt.ylabel('y') 接着,可以使用plt.plot()函数来绘制三角函数的图像: plt.plot(x, y_sin, label='sin(x)') plt.plot(x, y_cos, label='cos(x)') plt.plot(x, y_tan, label='tan(x)') 然后,可以通过plt.legend()函数来显示每个三角函数的标签: plt.legend() 最后,可以通过plt.show()函数来显示绘制好的图像: plt.show() 这样就可以使用Python绘制三角函数的图像了。可以根据需要调整x轴的范围和间隔以及图像窗口的大小。 ### 回答3: Python是一种功能强大的编程语言,它提供了许多用于绘图的库和工具,其中包括用于绘制三角函数图像的功能。 在Python中,我们可以使用matplotlib库来绘制三角函数图像。首先,我们需要导入matplotlib库的pyplot模块: python import matplotlib.pyplot as plt 然后,我们可以使用numpy库来生成三角函数的数据。numpy是一个用于科学计算的库,可以方便地生成和处理数值数据。首先,我们需要导入numpy库: python import numpy as np 接下来,我们可以使用numpy的linspace函数生成一组等间隔的x值。例如,我们可以生成-2π到2π之间的一组x值: python x = np.linspace(-2*np.pi, 2*np.pi, 100) 然后,我们可以使用numpy的sin和cos函数计算对应的y值,分别表示正弦和余弦函数的值: python y_sin = np.sin(x) y_cos = np.cos(x) 最后,我们可以使用matplotlib的plot函数绘制图像。我们可以通过传入x和y的值来绘制曲线: python plt.plot(x, y_sin, label='sin') plt.plot(x, y_cos, label='cos') plt.xlabel('x') plt.ylabel('y') plt.legend() plt.show() 运行这段代码,就可以在窗口中看到绘制的三角函数图像。在这个例子中,我们绘制了正弦和余弦函数的图像,并使用label函数给每条曲线添加了标签,使用xlabel和ylabel函数给坐标轴添加了标签,并使用legend函数显示图例。 通过上述步骤,我们可以使用Python绘制三角函数的图像。这是一个简单的例子,但在实际应用中,我们可以进一步定制图像的样式和参数,以满足特定需求。
### 回答1: 您可以使用Python中的Matplotlib库来绘制分段函数的图像。以下是一个示例代码,可以绘制分段函数y = |x|和y = x^2-1的图像: python import matplotlib.pyplot as plt import numpy as np x = np.linspace(-5, 5, 1000) y1 = np.abs(x) y2 = x**2 - 1 plt.plot(x, y1, label='y = |x|') plt.plot(x, y2, label='y = x^2-1') plt.legend() plt.show() 该代码将在新窗口中显示两个分段函数的图像,其中y = |x|的图像为一条V形线段,y = x^2-1的图像为一条开口向上的抛物线。您可以根据需要更改x的取值范围和函数的表达式。 ### 回答2: 要绘制一个分段函数的图像,我们可以使用Python的matplotlib库。首先,我们需要先导入matplotlib库和numpy库,它们分别用于绘图和处理数据。 python import matplotlib.pyplot as plt import numpy as np 接下来,我们可以定义我们想要绘制的分段函数。例如,假设我们要绘制以下的分段函数: f(x) = x (x <= 0) f(x) = x^2 (0 < x <= 2) f(x) = -x + 4 (x > 2) 我们可以使用numpy库的linspace函数生成一组x值,然后根据这些x值计算对应的y值。 python x1 = np.linspace(-5, 0, 100) y1 = x1 x2 = np.linspace(0, 2, 100) y2 = x2 ** 2 x3 = np.linspace(2, 5, 100) y3 = -x3 + 4 现在,我们可以绘制函数的图像了。 python plt.plot(x1, y1, label='f(x)=x') plt.plot(x2, y2, label='f(x)=x^2') plt.plot(x3, y3, label='f(x)=-x+4') plt.xlabel('x') plt.ylabel('y') plt.title('Graph of Piecewise Function') plt.legend() plt.show() 这段代码会生成一个分段函数的图像,并在图例中显示出每个分段的函数。 总结起来,要使用Python绘制分段函数的图像,我们需要导入matplotlib和numpy库,定义函数的分段区域和对应的函数表达式,生成x和y值,然后使用plt.plot()函数绘制图像并添加标签和标题,最后使用plt.show()函数显示图像。
最新推荐
Python numpy 常用函数总结
Python代码很多时候看起来就像是伪代码一样,因此你可以使用很少的几行可读性很高的代码来实现一个非常强大的想法。 numpy很简单,Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy、...
python使用Matplotlib绘制分段函数
主要为大家详细介绍了python使用Matplotlib绘制分段函数,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Python使用matplotlib的pie函数绘制饼状图功能示例
主要介绍了Python使用matplotlib的pie函数绘制饼状图功能,结合实例形式分析了Python使用matplotlib的pie函数进行饼状图绘制的具体操作技巧,注释中对pie函数的用法进行了详细的说明,便于理解,需要的朋友可以参考下
python递归函数绘制分形树的方法
主要为大家详细介绍了python递归函数绘制分形树的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
python中format函数如何使用
在本篇内容里小编给大家整理的是一篇关于python的format函数用法以及相关实例,需要的朋友们学习下。
企业人力资源管理系统的设计与实现-计算机毕业论文.doc
企业人力资源管理系统的设计与实现-计算机毕业论文.doc
"风险选择行为的信念对支付意愿的影响:个体异质性与管理"
数据科学与管理1(2021)1研究文章个体信念的异质性及其对支付意愿评估的影响Zheng Lia,*,David A.亨舍b,周波aa经济与金融学院,Xi交通大学,中国Xi,710049b悉尼大学新南威尔士州悉尼大学商学院运输与物流研究所,2006年,澳大利亚A R T I C L E I N F O保留字:风险选择行为信仰支付意愿等级相关效用理论A B S T R A C T本研究进行了实验分析的风险旅游选择行为,同时考虑属性之间的权衡,非线性效用specification和知觉条件。重点是实证测量个体之间的异质性信念,和一个关键的发现是,抽样决策者与不同程度的悲观主义。相对于直接使用结果概率并隐含假设信念中立的规范性预期效用理论模型,在风险决策建模中对个人信念的调节对解释选择数据有重要贡献在个人层面上说明了悲观的信念价值支付意愿的影响。1. 介绍选择的情况可能是确定性的或概率性�
利用Pandas库进行数据分析与操作
# 1. 引言 ## 1.1 数据分析的重要性 数据分析在当今信息时代扮演着至关重要的角色。随着信息技术的快速发展和互联网的普及,数据量呈爆炸性增长,如何从海量的数据中提取有价值的信息并进行合理的分析,已成为企业和研究机构的一项重要任务。数据分析不仅可以帮助我们理解数据背后的趋势和规律,还可以为决策提供支持,推动业务发展。 ## 1.2 Pandas库简介 Pandas是Python编程语言中一个强大的数据分析工具库。它提供了高效的数据结构和数据分析功能,为数据处理和数据操作提供强大的支持。Pandas库是基于NumPy库开发的,可以与NumPy、Matplotlib等库结合使用,为数
devc++6.3大小写字母转换
根据提供的引用内容,无法直接回答关于 Dev-C++ 6.3 的大小写字母转换问题。Dev-C++ 是一个集成开发环境(IDE),用于编写和运行 C/C++ 程序。如果您想要实现大小写字母转换,可以使用 C++ 标准库中的 toupper() 和 tolower() 函数。这两个函数分别将字符转换为大写和小写形式。以下是一个简单的示例程序: ```c++ #include <iostream> #include <string> using namespace std; int main() { string str = "Hello, World!"; for (int
基于ADuC812单片机的温湿度检测仪-毕业设计.doc
基于ADuC812单片机的温湿度检测仪-毕业设计.doc
|
__label__pos
| 0.947665 |
How to Extend Your Android Phone’s Internal Memory
How to Extend Your Android Phone’s Internal Memory – If you’re enough familiar with smartphone memories, this question might be bit confusing for you because internal memory is the memory of a smartphone that is by-default provided by the the manufacturer which can not be actually increased by an end user, whereas the external memory is the memory which user can add from outside (such as microSD cards etc.). So, the surprising thing is that how this article can help you increase your Android phone’s internal memory?
Keep calm guys and read out the article carefully, and I’m sure your doubt will be cleared as the following two methods will definitely help you extend your Android phone’s internal memory. Let me explain how!
Here’s How to Extend Android Phone’s Internal Memory
Degrading the performance of a smartphone or slowing down the speed is one of the main problem we all face, and over-filled internal memory (or phone memory) might be the main reason. So, it’s your primary step to free up your phone memory from useless things, and that’s the exact meaning of increasing the size.
So, apply the following methods to increase the size of your Android phone’s internal memory:
1. Clear Your Android Phone Cache
Android phone’s internal memory can be free up by clearing the waste cache stored in form of the junk files and folders. To clear the smartphone cache go to Settings > Storage and here you will see the Cached Data option with the calculation of how much data is cached. ow, you need to tap on Cached Data option and again tap on Yes on the confirmation message.Yes on the confirmation message
That’s all. It will clear the cache of your Android phone and will free up your internal memory. In the screenshot, my Android phone phone memory was full of more than 800 MB cached data (garbage) that now I removed and increased the size of my phone memory.
Isn’t it easy? So, you can also increase the size of your Android phone’s internal memory by clearing the cache of your Android phone.
2. Move Apps from Phone Memory to SD Card
To improve the performance of your phone you should keep your phone memory as free as possible. So, to increase the size of the internal memory of your Android phone, you can move some of the apps from phone memory to your microSD card.
To do so, go to Settings > Manage Apps and now tap on the app that you want to move in SD card. And finally tap on Move to SD Card option.Move to SD Card option
So, by moving the apps from your internal memory to SD card you can increase the size of internal memory and boost your Android phone’s performance.
Conclusion
So, guys if your Android phone’s internal memory is not that more, still by using the above mentioned methods you can increase its size to improve the performance of your phone. So, I think keeping the Android phone’s internal memory free is the key to boost phone speed and performance.
Other than this, you can write me back anytime if you feel any problem in increasing the size of internal memory by clearing cache or moving apps to SD card.
Read :
Keyword :
best tricks 2017 for samsung e5,how can i expand j1 internal storage,how can i extend my samsung j1 ace phone storage,How to expend the internal storage Samsung E5,how to extend samsung a7 space,how to increase phone storage of j1,samsung j1 how to increase internal memory,www Samsung 530H do not work sd card
How to Extend Your Android Phone’s Internal Memory | Samsung Galaxy Specs | 4.5
|
__label__pos
| 0.965064 |
How to attach hover event to an element in Jquery ?
Posted by Vivek.Ramapuram on 11/5/2014 | Category: jQuery Interview questions | Views: 823 | Points: 40
Answer:
Here in the script in coding we have to attach or we have to use hover()method to hover event to a html element in jquery.
example:
<script type="text/javascript">
$("#pHover").hover(function () { $(this).hide(500); });
</script>
This function runs and shows the output as "when user mouse over “pHover”(pHover means div id name) element,it will hide."
Asked In: spotted while learning | Alert Moderator
Comments or Responses
Login to post response
|
__label__pos
| 0.776607 |
September 17, 2021
How to use CHISQ.INV Function in Excel
The CHISQ.INV function returns the inverse of the left-tailed probability of the chi-squared distribution. The chi-squared distribution is commonly used to study variation in the percentage of something across samples.
Syntax:= CHISQ.INV(probability,deg_freedom)
The CHISQ.INV function syntax has the following arguments:
1. Probability (required argument) – This is the probability associated with the chi-squared distribution.
2. Deg_freedom (required argument) – This is the number of degrees of freedom. It must be an integer between 1 and 1010.
Example: Let’s look at some Excel CHISQ.INV function examples and explore how to use the CHISQ.INV function as a worksheet function in Microsoft Excel:
CHISQ.INV Function 1 - How to use CHISQ.INV Function in Excel
Syntax: =CHISQ.INV(B1,B2)
Result: 3.218875825
CHISQ.INV Function in Excel 1 - How to use CHISQ.INV Function in Excel
Based on the Excel spreadsheet above, the following CHISQ.INV examples would return:
Syntax: =CHISQ.INV(C1,C2)
Result: 1.832581464
Syntax: =CHISQ.INV(D1,D2)
Result: 0.713349888
Syntax: =CHISQ.INV(E1,E2)
Result: 1.323303697
Note:
• If argument is nonnumeric, CHISQ.INV returns the #VALUE! error value.
• If probability < 0 or probability > 1, CHISQ.INV returns the #NUM! error value.
• If deg_freedom is not an integer, it is truncated.
• If deg_freedom < 1 or deg_freedom > 10^10, CHISQ.INV returns the #NUM! error value.
READ: How to use STANDARDIZE Function in Excel
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.569442 |
Current time:0:00Total duration:14:27
0 energy points
Studying for a test? Prepare with these 16 lessons on Matrices.
See 16 lessons
Video transcript
Perhaps even more interesting than finding the inverse of a matrix is trying to determine when an inverse of a matrix doesn't exist. Or when it's undefined. And a square matrix for which there is no inverse, of which an inverse is undefined is called a singular matrix. So let's think about what a singular matrix will look like, and how that applies to the different problems that we've address using matrices. So if I had the other 2 by 2, because that's just a simpler example. But it carries over into really any size square matrix. So let's take our 2 by 2 matrix. And the elements are a, b, c and d. What's the inverse of that matrix? This hopefully is a bit of second nature to you now. It's 1 over the determinant of a, times the adjoint of a. And in this case, you just switch these two terms. So you have a d and an a. And you make these two terms negative. So you have minus c and minus b. So my question to you is, what will make this entire expression undefined? Well it doesn't matter what numbers I have. If I have numbers here that make a defined, then I can obviously swap them or make them negative, and it won't change this part of the expression. But what would create a problem is if we attempted to divide by 0 here. If the determinant of the matrix A were undefined. So A inverse is undefined, if and only if-- and in math they sometimes write it if with two f's-- if and only if the determinant of A is equal to 0. So the other way to view that is, if a determinant of any matrix is equal to 0, then that matrix is a singular matrix, and it has no inverse, or the inverse is undefined. So let's think about in conceptual terms, at least the two problems that we've looked at, what a 0 determinant means, and see if we can get a little bit of intuition for why there is no inverse. So what is a 0 determinant? In this case, what's a determinant of this 2 by 2? Well the determinant of A is equal to what? It's equal to ad minus bc. So this matrix is singular, or it has no inverse, if this expression is equal to 0. So let me write that over here. So if ad is equal to bc-- or we can just manipulate things, and we could say if a/b is equal to c/d-- I just divided both sides by b, and divided both sides by d-- so if the ratio of a:b is the same as the ratio of c:d, then this will have no inverse. Or another way we could write this expression, if a/c-- if I divide both sides by c, and divide both sides by d-- is equal to b/d. So another way that this would be singular is if-- and it's actually the same way. If this is true, then this is true. These are the same. Just a little bit of algebraic manipulation. But if the ratio of a:c is equal to the ratio of b:d, and you can think about why that's the same thing. The ratio of a:b being the same thing as the ratio of c:d. But anyway, I don't want to confuse you. But let's think about how that translates into some of the problems that we looked at. So let's say that we wanted to look at the problem-- Let's say that we had this matrix representing the linear equation problem. Well, actually, this would be either one. So I have a, b, c, d times x, y Is equal to two other numbers that we haven't used yet, e and f. So if we have this matrix equation representing the linear equation problem, then the linear equation problem would be translated a times x plus b times y is equal to e. And c times x plus d times y is equal to f. And we would want to see where these two intersect. That would be the solution, the vector solution to this equation. And so, just to get a visual understanding of what these two lines look like, let's put it into the slope y-intercept form. So this would become what? In this case, y is equal to what? y is equal to minus a/b, x plus e/b. I'm just skipping some steps. But you subtract ax from both sides. And then divide both sides by b, and you get that. And then this equation, if you put it in the same form, just solve for y. You get y is equal to minus c/d x plus f/y. So let's think about this. I should probably change colors because it looks too-- Let's think about what these two equations would look like if this holds. And we said if this holds, then we have no determinant, and this becomes a singular matrix, and it has no inverse. And since it has no inverse, you can't solve this equation by multiplying both sides by the inverse, because the inverse doesn't exist. So let's think about this. If this is true, we have no determinant, but what does that mean intuitively in terms of these equations? Well if a/b is equal to c/d, these two lines will have the same slope. They'll have the same slope. So if these two expressions are different, then what do we know about them? If two lines that have the same slope and different y-intercepts, they're parallel to each other, and they will never, ever intersect. So let me draw that, just so you get the-- this top line-- They don't have to be positive numbers, but since this has a negative, I'll draw it as a negative slope. So that's the first line. And its y-intercept will be e/b. That's this line right here. And then the second line-- let me do it in another color-- I don't know if it's going to be above or below that line, but it's going to be parallel. It'll look something like this. And that line's y-intercept-- so that's this line-- that line's y intercept is going to be f/y. So if e/b and f/y are different terms, but both lines have the same equation, they're going to be parallel and they'll never intersect. So there actually would be no solution. If someone told you-- just the traditional way that you've done it, either through substitution, or through adding or subtracting the linear equations-- you wouldn't be able to find a solution where these two intersect, if a/b is equal to c/d. So one way to view the singular matrix is that you have parallel lines. Well then you might say, hey Sal, but these two lines would intersect if e/b equaled f/y. If this and this were the same, then these would actually be the identical lines. And not only would they intersect, they would intersect in an infinite number of places. But still you would have no unique solution. You'd have no one solution to this equation. It would be true at all values of x and y. So you can kind of view it when you apply the matrices to this problem. The matrix is singular, if the two lines that are being represented are either parallel, or they are the exact same line. They're parallel and not intersecting at all. Or they are the exact same line, and they intersect at an infinite number of points. And so it kind of makes sense that the A inverse wasn't defined. So let's think about this in the context of the linear combinations of vectors. That's not what I wanted to use to erase it. So when we think of this problem in terms of linear combination of factors, we can think of it like this. That this is the same thing as the vector ac times x plus the vector bd times y, is equal to the vector ef. So let's think about it a little bit. We're saying, is there some combination of the vector ac and the vector bd that equals the vector ef. But we just said that if we have no inverse here, we know that because the determinant is 0. And if the determinant is 0, then we know in this situation that a/c must equal b/d. So a/c is equal to b/d. So what does that tell us? Well let me draw it. And maybe numbers would be more helpful here. But I think you'll get the intuition. I'll just draw the first quadrant. I'll just assume both sectors are in the first quadrant. Let me draw. The vector ac. Let's say that this is a. Let me do it in a different color. So I'm gonna draw the vector ac. So if this is a, and this is c, then the vector ac looks like that. Let me draw it. I want to make this neat. The vector ac is like that. And then we have the arrow. And what would the vector bd look like? Well the vector bd-- And I could draw it arbitrarily someplace. But we're assuming that there's no derivative-- sorry, no determinant. Have I been saying derivative the whole time? I hope not. Well, we're assuming that there's no determinant to this matrix. So if there's no determinant, we know that a/c is equal to b/d. Or another way to view it is that c/d is equal to d/b. But what that tells you is that both of these vectors kind of have the same slope. So if they both start at point 0, they're going to go in the same direction. They might have a different magnitude, but they're going to go in the same direction. So if this is point b, and this is point d, vector bd is going to be here. And if that's not obvious to you, think a little bit about why these two vectors, if this is true, are going to point in the same direction. So that vector is going to essentially overlap. It's going to have the same direction as this vector, but it's just going to have a different magnitude. It might have the same magnitude. So my question to you is, vector ef, we don't know where vector ef is. Well let's pick some arbitrary point. Let's say that this is e, and this is f. So this is vector ef up there. Let me do it in a different color. Vector ef, let's say it's there. So my question to you is, if these two vectors are in the same direction. Maybe of different magnitude. Is there any way that you can add or subtract combinations of these two vectors to get to this vector? Well no, you can scale these vectors and add them. And all you're going to do is kind of move along this line. You can get to any other vector. There's a multiple of one of these vectors. But because these are the exact same direction, you can't get to any vector that's in a different direction. So if this vector is in a different direction, there's no solution here. If this vector just happened to be in the same direction as this, then there would be a solution, where you could just scale those. Actually, there would be an infinite number of solutions in terms of x and y. But if the vector is slightly different, in terms of its direction, then there is no solution. There is no combination of this vector and this vector that can add you up to this one. And it's something for you think about a little bit. It might be obvious to you. But another way to think about it is, when you're trying to take sums of vectors, any other vector, in order to move it in that direction, you have to have a little bit of one direction and a little bit of another direction, to get to any other vector. And if both of your ingredient vectors are the same direction, there's no way to get to a different one. Anyway, I'm probably just being circular in what I'm explaining. But that hopefully gives you a little bit of an intuition of well, one, you now know what a singular matrix is. You know when you can not find its inverse. You know that when the determinant is 0, you won't find an inverse. And hopefully-- and this was the whole point of this video-- you have an intuition of why that is. Because if you're looking at the vector problem, there's no way that you can find-- that either there's no solution to finding the combination of the vectors that get you to that vector, or there are an infinite number. And the same thing is true of finding the intersection of two lines. They're either parallel, or they're the same line, if the determinant is 0. Anyway, I will see you in the next video.
|
__label__pos
| 0.983546 |
Internet Exchange Point(IXP) questions
Yaoqing(Joey) Liu joey.liuyq at gmail.com
Thu Feb 17 20:03:12 CST 2011
I'm doing some research on multiple origin AS problems of IXPs. As I know,
generally there are two types of IXPs
type 1: use exchange routers, which works in layer 3
type 2: use switches and Ethernet topology, which works in layer 2.
So I have a couple of qustions:
1. For type 1, the exchange routers may use several IP prefixes for routing,
how often does the IP prefixes have their own AS?
2. For type 2, all peers connected to the IXP must work in the same subnet
required by Ethernet rules. Is possible that the subnet IP prefixes belong
to some private IP address space, such as 192.168.x.x? How often does this
happen? If the subnet only contains public IP addresses, how are the
addresses announced?
Thanks,
Yaoqing
More information about the NANOG mailing list
|
__label__pos
| 0.989223 |
Code-breaking with Markov Chain Monte Carlo (MCMC)
Using cryptography to demonstrate the power of MCMC techniques in computational statistics
Author
Max Rohde
Published
November 10, 2022
Overview
In this post we will show how a common method in computational statistics, Markov Chain Monte Carlo (implemented using the Metropolis algorithm), can be used to decode hidden messages encoded using a substitution cipher1.
• 1 From Merriam-Webster, a cipher is defined as “a method of transforming a text in order to conceal its meaning”.
• To cut to the chase, here’s a video of the algorithm in action running on my laptop:
We see that within a few hundred iterations of the algorithm, the true text is revealed. This post will explain the theory of how this works and will describe the computational details using R. Many of the details were inspired by an example given by Persi Diaconis in his paper “The Markov Chain Monte Carlo Revolution”2.
The substitution cipher
The substitution cipher is one of the simplest cryptographic methods. It works by swapping each letter in the alphabet with another.
One simple type of substitution cipher is a shift cipher, where we shift the alphabet by a certain number of units. So a shift cipher with a shift of 3 would yield:
Original Alpabet: abcdefghijklmnopqrstuvwxyz
Cipher Alphabet: defghijklmnopqrstuvwxyzabc
With this cipher, the word hello would map to:
• h -> k
• e -> h
• l -> o
• l -> o
• o -> r
resulting in the ciphertext khoor.
Terminology
Plaintext refers to the text you input to the cipher (“hello”) and ciphertext refers to the output of the cipher (“khoor”).
We can do this in R using the built-in chartr() function, which encodes a given string from one alphabet to another.
chartr(
x = "hello",
old = "abcdefghijklmnopqrstuvwxyz",
new = "defghijklmnopqrstuvwxyzabc"
)
[1] "khoor"
More generally, we can create an arbitrary substitution cipher by permuting the letters of the alphabet.
letters is a built-in R object that contains the 26 letters of the English alphabet.
paste(collapse = "") is used to turn a vector of characters into a single string.
letters |> paste(collapse = "")
[1] "abcdefghijklmnopqrstuvwxyz"
sample(letters) |> paste(collapse = "")
[1] "xasljwipdrvgfeuohbkmntzyqc"
We can use the above code to create three functions which
1. Generate a random cipher
2. Encode plaintext with a given cipher
3. Decode ciphertext with a given cipher
# Generate a new cipher by permuting the letters of the alphabet
generate_cipher <- function() sample(letters,
replace = FALSE)
# Encode a text using a cipher
encode_text <- function(text, cipher) {
chartr(
x = text,
old = paste(letters, collapse = ""),
new = paste(cipher, collapse = "")
)
}
# Decode a text given a cipher
decode_text <- function(ciphered_text, cipher) {
chartr(
x = ciphered_text,
old = paste(cipher, collapse = ""),
new = paste(letters, collapse = "")
)
}
Let’s test these functions to make sure they’re working correctly:
plaintext <- "to be or not to be that is the question whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune or to take arms against a sea of troubles"
# Create and store the cipher
true_cipher <- generate_cipher()
print(true_cipher)
[1] "w" "r" "j" "n" "p" "t" "a" "q" "k" "y" "l" "h" "b" "z" "u" "s" "i" "o" "e"
[20] "x" "f" "g" "v" "d" "m" "c"
Here’s what the ciphertext looks like:
# Encode the plaintext
ciphertext <- encode_text(plaintext, true_cipher)
print(ciphertext)
[1] "xu rp uo zux xu rp xqwx ke xqp ifpexkuz vqpxqpo xke zurhpo kz xqp bkzn xu efttpo xqp ehkzae wzn woouve ut ufxowapufe tuoxfzp uo xu xwlp wobe wawkzex w epw ut xoufrhpe"
And we see that decoding it with the true cipher recovers the plaintext:
# Decode the ciphertext
decoded_text <- decode_text(ciphertext, true_cipher)
print(decoded_text)
[1] "to be or not to be that is the question whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune or to take arms against a sea of troubles"
Overview of the Metropolis algorithm
Why not use brute force?
Suppose we intercept the ciphertext above, but we didn’t know the true cipher. How could we decode the hidden message?
A brute force idea would be to try all possible ciphers until we find the correct one. How long would that take? There are \(26!\) ciphers to check because each cipher corresponds to a certain permutation of the alphabet.
[1] 4.032915e+26
That’s a very big number! As a thought experiment, let’s assume that we have access to the fastest supercomputer in the world3. It’s reported that it can compute 1.1 quintillion operations (\(1.1 \times 10^{18}\)) per second. Although checking a cipher would take more than a single operation, let’s assume that we can check a cipher in a single operation (since we are seeing if this approach is even feasible).
\[ (4.03 \times 10^{26}) \text{ ciphers} \times \left(\frac{1 \text{ second}}{1.1 \times 10^{18} \text{ciphers}}\right) \approx 366 \text{ million seconds} \approx 11.6 \text{ years} \]
So even with the fastest computer in the world, and with some very generous assumptions about how many operations it takes to check a cipher, it would still take 11.6 years to test all of them. Let’s learn a much faster way to solve this problem. We don’t even need a supercomputer; a laptop will do just fine.
The Metropolis algorithm
So, how can we beat the brute force method? The idea is to use an algorithm that seeks out the likely ciphers, and ignores the ciphers that are unlikely to be correct. This is what the Metropolis algorithm does.
The Metropolis algorithm is a Markov Chain Monte Carlo algorithm, which means that it is used to generate Markov Chains that converge to a desirable stationary distribution4. Markov chains are defined on a state space, where the chain is traveling from state to state. In the framework of our problem, the states our Markov Chain is traveling between are the \(26!\) possible ciphers. We want to the Markov chain to travel to the ciphers that are more “likely to be correct” and stay away from the ciphers that are “unlikely to be correct”. While we will elaborate on this later, we can tentatively define “likely to be correct” ciphers as those that produce text that looks similar to English.
• 4 For a review of Markov chains, see https://setosa.io/ev/markov-chains/ and https://youtu.be/i3AkTO9HLXo
• Let \(\text{sim}(\text{cipher})\) be a function that returns a score from 0 and 1 indicating how similar the text that a cipher produces is to English. With the \(\text{sim}(\text{cipher})\) function defined, the Metropolis algorithm works like this. First, start with a randomly chosen cipher as the initial state. Then repeat the following steps until the code is cracked:
1. Choose a new (but closely related) cipher by swapping two letters in the current cipher at random. This is called the proposal cipher.
2. Compute the quantity \(\frac{\text{sim}(\text{proposal cipher})}{\text{sim}(\text{current cipher})}\). If the proposal cipher produces text more similar to English than the current cipher, this ratio will always be greater than 1. If the current cipher produces text more similar to English than the proposal cipher, this ratio will be between 0 and 1.
3. If the ratio in the previous step is greater than 1, set the current cipher to the proposed cipher. This is called accepting the proposal.
4. If the ratio is less than 1, accept the proposal with probability equal to \(\frac{\text{sim}(\text{proposal cipher})}{\text{sim}(\text{current cipher})}\) and reject it (i.e., stay at the current cipher) with probability \(1 - \frac{\text{sim}(\text{proposal cipher})}{\text{sim}(\text{current cipher})}\).
In other words, if the proposal cipher produces text more similar to English than the current cipher, we always accept it; and if the current cipher produces text more similar to English than the proposal cipher, we accept or reject it with probability given by the ratio of their scores. The worse a proposal performs, the less likely it will be accepted. The intuition behind this method is that it will travel towards ciphers that produce text more similar to English and ignore ciphers that don’t.
The Metropolis algorithm and Bayesian statistics
Technically, the Metropolis algorithm is designed to travel to states in proportion to the probability of each state. So by running the Metropolis algorithm on the space of ciphers, we are approximately sampling from the probability distribution of ciphers given the ciphertext, a concept that will be very familiar to those who use Bayesian statistics. Indeed, the Metropolis algorithm is used to perform Bayesian statistics in a variety of settings where an analytical approach is not feasible.
We are using the Metropolis algorithm here for optimization rather than sampling, a nice side-effect of the property that when sampling according to each state’s probability, high probability states are visited frequently.
To implement this algorithm, we need for formalize our notion of an “English-similarity score”. This will be the topic of the next section.
Defining an “English-similarity score”
We need some way of measuring how similar to English an arbitrary text looks. Even a non-native speaker could likely tell that
[1] "xu rp uo zux xu rp xqwx ke xqp ifpexkuz vqpxqpo xke zurhpo kz xqp bkzn xu efttpo xqp ehkzae wzn woouve ut ufxowapufe tuoxfzp uo xu xwlp wobe wawkzex w epw ut xoufrhpe"
does not look like English. For example, most words don’t have any vowels!
A rough heuristic to see how similar a text is to English is to compute the two letter frequencies and see how similar they are to those in English. Here’s an example. hello there has the following 2-letter combinations: "he" "el" "ll" "lo" "o " " t" "th" "he" "er" "re". You can picture this as a sliding window of width 2.
We could then compare how close the frequencies in this text align with the frequencies in English. Let \(\text{freq}(x)\) be the frequency of two-letter combination \(x\) in English (we’ll see how to compute this soon). Then the “English-similarity” score for hello there could be computed as \[ \text{freq}(\text{he}) \times \text{freq}(\text{el}) \times \text{freq}(\text{ll}) \times \ldots \times \text{freq}(\text{re}) \]
Estimating frequencies based on a sample text
Now let’s return to how we implement the \(\text{freq}(x)\) function. An approximation to the two-letter frequencies in English could be to find a very long English text and use the frequencies within it. The text we’ll use to do this is War and Peace by Leo Tolstoy, a very long book by most standards. Luckily for us, War and Peace is in the public domain, and we can download a text file of the book from https://www.gutenberg.org/.
war_and_peace <- readr::read_file("https://www.gutenberg.org/cache/epub/2600/pg2600.txt")
We’ll clean the text a bit by:
• Converting all letters to lowercase
• Removing all non-alphabetical characters (numbers, symbols, etc…) but keeping spaces
• Removing all accent characters (like é)
so that in the end, the text only contains the 26 lowercase letters and the space character.
war_and_peace <-
war_and_peace |>
stringr::str_to_lower() |>
gsub(pattern = "[^A-Za-z ]+", replacement = "", x=_) |>
stringi::stri_trans_general(id = "Latin-ASCII")
Obtaining two-character frequencies
Now let’s design a function to break the text into two-character chunks. We can use the very fast stringi::stri_sub() function which, given a starting and ending index, extracts the substrings between them. Since our window has length two, we’ll offset the starting and ending indices by one.
We can test this approach on a short phrase to make sure it works.
test_string <- "hello there"
starting_indices <- 1 : (nchar(test_string) - 1)
ending_indices <- starting_indices + 1
starting_indices
[1] 1 2 3 4 5 6 7 8 9 10
ending_indices
[1] 2 3 4 5 6 7 8 9 10 11
stringi::stri_sub(test_string,
from = starting_indices,
to = ending_indices)
[1] "he" "el" "ll" "lo" "o " " t" "th" "he" "er" "re"
Now that we see our code works, let’s put it into a function.
break_into_two_chars <- function(text){
starting_indices <- 1 : (nchar(text) - 1)
ending_indices <- starting_indices + 1
return(stringi::stri_sub(text,
from = starting_indices,
to = ending_indices))
}
We can now break War and Peace into two-character chunks.
war_and_peace_2_characters <- break_into_two_chars(war_and_peace)
# Look at a piece of the results (skipping the table of contents)
war_and_peace_2_characters[10000:10100]
[1] "f " " a" "au" "us" "st" "tr" "ri" "ia" "a " " p" "pe" "er" "rh" "ha" "ap"
[16] "ps" "s " " i" "i " " d" "do" "on" "nt" "t " " u" "un" "nd" "de" "er" "rs"
[31] "st" "ta" "an" "nd" "dt" "th" "hi" "in" "ng" "gs" "s " " b" "bu" "ut" "t "
[46] " a" "au" "us" "st" "tr" "ri" "ia" "a " " n" "ne" "ev" "ve" "er" "r " " h"
[61] "ha" "as" "s " " w" "wi" "is" "sh" "he" "ed" "d " " a" "an" "nd" "d " " d"
[76] "do" "oe" "es" "s " " n" "no" "ot" "t " " w" "wi" "is" "sh" "h " " f" "fo"
[91] "or" "r " " w" "wa" "ar" "r " " s" "sh" "he" "ei" "is"
Estimated frequencies from War and Peace
We can calculate the empirical probability of any two-letter combination by dividing the number of times it occurs by the total number of two-character chunks.
# Ten most common two-character combinations
probability_table <-
table(war_and_peace_2_characters) / length(war_and_peace_2_characters)
head(probability_table, 40)
war_and_peace_2_characters
a b c d e
9.053610e-04 2.097140e-02 7.463716e-03 6.200291e-03 5.077064e-03 3.436817e-03
f g h i j k
6.412562e-03 2.929341e-03 1.512555e-02 9.208617e-03 4.893754e-04 1.194642e-03
l m n o p q
3.989051e-03 5.850455e-03 4.422150e-03 1.038582e-02 5.434799e-03 4.205930e-04
r s t u v w
4.484022e-03 1.219292e-02 2.646478e-02 1.689283e-03 1.191351e-03 1.207313e-02
x y z a aa ab
1.474379e-04 1.931503e-03 4.179602e-05 4.516603e-03 2.369538e-05 1.161074e-03
ac ad ae af ag ah
2.347817e-03 3.736959e-03 2.501179e-05 5.660563e-04 1.129809e-03 1.260463e-04
ai aj ak al
2.882938e-03 5.759294e-05 8.388823e-04 4.695634e-03
Note that two-letter combinations that look like a single letter are actually a letter and a space, since we are including spaces in our frequencies to help the algorithm learn word boundaries.
Here are the 20 most common combinations.
probability_table |>
sort(decreasing = TRUE) |>
head(20)
war_and_peace_2_characters
e t he th d a
0.033159052 0.026464778 0.024673473 0.024416444 0.022819309 0.020971399
s t in h an er
0.018675251 0.017588225 0.015909144 0.015125551 0.014968898 0.014645720
n s w re nd o
0.012217272 0.012192919 0.012073125 0.011726251 0.011409326 0.010385817
ed r
0.009573263 0.009366257
We can also see the probability of any combination we choose:
# Get the probability of "ou"
probability_table["ou"]
ou
0.007754971
However, there are some two-character combinations that do not occur in War and Peace. Instead of estimating the probability of these combinations to be zero, we instead approximate the probability by assuming each of them occurred once in the book. To implement this approximation, we use the below function, which returns the empirical probability of any two-character combination.
get_prob_two_char <- function(two_char){
prob_from_table <- probability_table[two_char]
if (is.na(prob_from_table)) {
return(1 / length(war_and_peace_2_characters))
} else{
return(prob_from_table)
}
}
We can try our function for a combination in War and Peace and a combination that is not:
# Try a combination in War and Peace
get_prob_two_char("ou")
ou
0.007754971
probability_table["ou"]
ou
0.007754971
# Try a combination not in War and Peace
get_prob_two_char("qq")
[1] 3.291025e-07
probability_table["qq"]
<NA>
NA
Getting the probability of a new text
Now that we have a way to estimate the probability of any two character combination in English, we can use it to score how similar a given text is to English. A first approach, as described above, might be to break the new text into two character chunks, compute the probability of each, and multiply them together.
map_dbl() is a function from the purrr package that iterates over each element of an input vector or list, and applies a function to each element. The _dbl in the function name means that the expected output is numeric. We need to use map_dbl() because our get_prob_two_char() function isn’t vectorized.
sample_text <- "this is a text"
sample_text_two_char <- break_into_two_chars(sample_text)
score <-
purrr::map_dbl(sample_text_two_char, get_prob_two_char) |>
prod()
score
[1] 8.63621e-29
However, we see that the score is an extremely small number, about \(10^{-55}\). Therefore, for better numerical precision, we should work on the log scale, and then transform back when we need probabilities. Remember, on the log scale we express products as sums. Below is a function to implement this approach:
1. Break the text into two character chunks
2. Compute the probability of each chunk using our representative English text (War and Peace)
3. Take the log of each probability
4. Sum the probabilities to get a log-likelihood for the text
get_log_lik_text <- function(text){
text |>
break_into_two_chars() |>
purrr::map_dbl(get_prob_two_char) |>
log() |>
sum()
}
Let’s see if our score can differentiate English and non-English: a comparison of English words with me hitting random keys.
get_log_lik_text("This is English text")
[1] -130.5349
get_log_lik_text("fghr gh wghdfrf etfs")
[1] -139.0768
As expected the log-likelihood for the English text is higher than for the non-English text.
Implementing the Metropolis Algorithm
Now we are finally ready to implement our code-breaking algorithm! One helper function we need is a function to swap two elements of a vector. As discussed above, we’ll use this to propose a new cipher given the current cipher.
swap <- function(x){
# Select two distinct indices
rand_indices <- sample(1:length(x), size = 2, replace=FALSE)
element_1 <- x[rand_indices[1]]
element_2 <- x[rand_indices[2]]
x[rand_indices[1]] <- element_2
x[rand_indices[2]] <- element_1
return(x)
}
Below is the full algorithm, the same one I ran to create the video at the beginning of this post. The steps correspond to the description I gave above for the Metropolis algorithm, now substituting in the functions we created. I have added detailed comments for each line of the code. Try running it for yourself and use your own example text.
A few tips:
• The algorithm may take many iterations to converge, sometimes close to 20,000, although this is highly dependent on the cipher chosen and the starting cipher.
• Since this is a relatively short text, it may take more iterations to decode. Long texts contain more information, and so are more easily decoded.
• If the chain doesn’t seem to be converging, try a new random seed. I had to try a few random seeds for the algorithm to converge in a reasonable number of iterations5.
• 5 While this strategy of restarting misbehaving Markov chains isn’t a good strategy for other applications of MCMC like Bayesian statistics, it’s perfectly reasonable for the optimization task we are performing here.
• plaintext <- "to be or not to be that is the question whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune or to take arms against a sea of troubles"
# Generate a random cipher to be the true cipher
true_cipher <- generate_cipher()
# Encode the plaintext
ciphered_text <- encode_text(text = plaintext,
cipher = true_cipher)
# Create another random cipher to be the starting cipher for the Markov Chain
current_cipher <- generate_cipher()
# A counter to track how many decoded texts have been accepted
i <- 0
for (iter in 1:50000) {
# Propose a new cipher by swapping two letters in the current cipher
proposed_cipher <- swap(current_cipher)
# Text decoded from the proposal cipher
decoded_text_proposed <- decode_text(ciphered_text,
cipher = proposed_cipher)
# Text decoded from the current cipher
decoded_text_current <- decode_text(ciphered_text,
cipher = current_cipher)
# Log-likelihood of the decoded text from the proposal cipher
proposed_log_lik <- get_log_lik_text(decoded_text_proposed)
# Log-likelihood of the decoded text from the current cipher
current_log_lik <- get_log_lik_text(decoded_text_current)
# Acceptance probability of the proposal, defined by the Metropolis algorithm
# Remember that subtraction on the log-scale is division on the probability
# scale. We exponentiate to get back to the probability scale.
acceptance_probability <- min(1, exp(proposed_log_lik - current_log_lik))
# Accept or not with probability given by `acceptance_probability`
accept <- sample(c(TRUE, FALSE),
size=1,
prob = c(acceptance_probability,
1-acceptance_probability))
# IF we accept the proposal, set the proposal cipher as the current cipher
# ELSE, go on to the next iteration
if (accept) {
current_cipher <- proposed_cipher
# Print the text as decoded by the current cipher
print(glue::glue("Iteration {i}: {decoded_text_proposed}"))
# Increment the counter so that we can keep track of acceptances
# This is just for printing the output
i <- i + 1
}
}
For clarity, here’s the same code without comments.
plaintext <- "to be or not to be that is the question whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune or to take arms against a sea of troubles"
true_cipher <- generate_cipher()
ciphered_text <- encode_text(text = plaintext,
cipher = true_cipher)
current_cipher <- generate_cipher()
i <- 0
for (iter in 1:50000) {
proposed_cipher <- swap(current_cipher)
decoded_text_proposed <- decode_text(ciphered_text,
cipher = proposed_cipher)
decoded_text_current <- decode_text(ciphered_text,
cipher = current_cipher)
proposed_log_lik <- get_log_lik_text(decoded_text_proposed)
current_log_lik <- get_log_lik_text(decoded_text_current)
acceptance_probability <- min(1, exp(proposed_log_lik - current_log_lik))
accept <- sample(c(TRUE, FALSE),
size=1,
prob = c(acceptance_probability,
1-acceptance_probability))
if (accept) {
current_cipher <- proposed_cipher
print(glue::glue("Iteration {i}: {decoded_text_proposed}"))
i <- i + 1
}
}
|
__label__pos
| 0.995376 |
You can’t hide from the primes
I’ve been traveling so this one is from the archives. Enjoy! – AB
What are primes?
A prime number is a positive integer with exactly two different divisors. For example, 2 is prime, as 1 and 2 divide it. The same is true for 3, 5, and 7. But 6 is not prime as it has four divisors 1, 2, 3 and 6.
Image result for ulam spiral
The Ulam spiral, where colored cells are primes. A larger version is the featured image of the blog.
On first glance, we may think that primes are not so useful. After all, we don’t use primes in daily life. Or do we? Read on!
First, we provide a few basic and not so basic facts about primes.
• A handy fact: to determine that a number n is prime, check for prime divisors at most √n. For example, we can quickly determine that 83 is prime by checking that 2, 3, 5 and 7 are not divisors.
• Every number is a product of primes. For example, 26 = 2• 13, and this is called a prime factorization. Prime factorizations are unique up to the order of the factors. This is one of the simplest reasons why primes matter: in a sense, they form an infinite periodic table of elements from which all other numbers are built. If you know a numbers prime factorization, then it tells you something fundamental about that number. Depending on the work you are doing, it may be better to represent 12,397 as 7 2 • 11 • 23.
• At the time of writing this blog, the largest prime that we know is 274,207,281 − 1, a number with over twenty two million digits. Of course, there are much larger primes. In fact, most primes are larger than this tiny number! As Euclid proved over two thousand years ago, there are infinitely many primes.
• If you look at how they are dispersed on the number line, then the primes are ubiquitous. According to the Bertrand–Chebyshev theorem: if you take an integer n and double it to form 2n, then you know there is always a prime between n and 2n.
• Primes don’t seem to arise according to any fixed pattern that we know. However, long clumps of them do appear in certain kinds of patterns. An arithmetic progression is a sequence of integers of the form an+b. For example, 3, 5, and 7 appear as 2n+3, where n = 0, 1, and 2. A breakthrough result of Ben Green and Terrance Tao from 2004 showed that arbitrarily long, finite sequences of primes are contained in arithmetic progressions.
• There are fast algorithms to check if a number is prime. Agrawal, Kayal, and Saxena proved in 2002 that deciding if a number is prime or composite is in polynomial time. However, we don’t know the computational complexity of finding the prime factorization of an integer.
Primes also have beautiful density patterns as exhibited by the prime number theorem and the Ulam spiral. Check out this video on the density of primes.
Why are primes important to security?
Primes matter in real life. You can’t hide from the primes. Each time you use your bank card or do on-line shopping, primes are likely lurking in the background.
Image result for melissa mccarthy hiding spicy
As Spicey knows, you can’t hide from the primes.
The science of encoding and transmitting secure data is called cryptography. Cryptography has an ancient past, but in the last century mathematicians developed sophisticated cryptographic algorithms that are very hard to crack.
Cryptography algorithms like RSA and others rely on so-called trapdoor functions; that is, functions easy to compute in one direction but not in the reverse. For example, prime factorization is a trap door: if I give you two primes, then it is easy to compute their product. However, if I give you a large number that is the product of two primes like 2997 -1, then it extremely tough to find the two primes.
Many other applications in computer science and engineering use primes. For example, random number generators and error correcting codes exploit properties of primes.
Why are primes interesting to mathematicians?
To put it bluntly, mathematicians don’t understand primes as well as would like.
Primes are the bread and butter of number theory, and in that field, there are many deep, unsolved problems them. One of the simplest to state of these is the Goldbach conjecture: each even integer greater than 2 is a sum of two primes. For example, 8 is 3+5, and 26 is 23+3. The Goldbach conjecture has been open since the 18th century.
The 1742 letter from Christian Goldbach to Leonhard Euler posing his namesake conjecture.
We don’t understand gaps between primes very well. The Twin Prime Conjecture states that there infinitely many primes p so that p+2 is also prime. In other words, we can find infinitely many examples of primes with gap 2. In 2013, Yitang Zhang announced that he could prove there were infinitely many primes with gap less than 70 million. That gap may seem ridiculously large, but it was a major breakthrough. Using his techniques, Terrance Tao and others have reduced the gap down to 246.
Image result for yitang yang math
Yitang Yang, who is the subject of the movie Counting From Infinity.
Another deep unsolved problem connected to primes is the Riemann hypothesis, which is more technical to state. Define the Riemann zeta function (or just zeta function) at value s as the infinite series:\zeta (s)=\sum _{n=1}^{\infty }{\frac {1}{n^{s}}}
The zeta function can take complex values, and is defined if the real part of s is greater than 1; for example, at s=1 it is the divergent harmonic series. At s=2, it has value π2/6.
There are infinitely many zeroes (that is, solutions of the equation ζ(s)=0) of the zeta function, such as the negative even integers, and these are called trivial zeroes. The zeta function also has complex number zeroes. The Riemann hypothesis claims that the real part of any non-trivial zero of the zeta function is 1/2. In other words, all the non-trivial zeroes live on the critical line z = 1/2 in the complex plane.
RiemannZetaZerosContoursReIm
A visualization of the Riemann zeta function in the complex plane, with the black dots representing zeroes. Notice the zeroes on the critical line z = 1/2.
While the Riemann hypothesis appears unrelated to primes on the surface, many conjectures about primes rely on its validity. One consequence has to do with the distribution of primes numbers. When I recently interviewed Barry Mazur (whose book on primes and the Riemann hypothesis came our recently; Barry is one of the leading number theorists), he gave his perspective on this connection. We close with his words.
Image result for prime numbers and the Riemann hypothesis
“Draw a graph (on one standard-size page) that charts the number of primes less than x, and where the range is for values of x between 1 and, say, 40, and it looks like the most randomly constructed staircase. And now draw one where the range is for values of x between 1 and, say, 100,000 primes and you get a strikingly smooth graph! Looking at primes from afar, their erratic turbulence disappears. That is the perplexity: from afar the graph of primes is so smooth, while from near it looks disorganized and complicated. The Riemann hypothesis continues the grand project begun by Gauss of explaining exactly how smooth that progression of primes is.”
Anthony Bonato
Leave a Reply
Fill in your details below or click an icon to log in:
WordPress.com Logo
You are commenting using your WordPress.com account. Log Out / Change )
Twitter picture
You are commenting using your Twitter account. Log Out / Change )
Facebook photo
You are commenting using your Facebook account. Log Out / Change )
Connecting to %s
|
__label__pos
| 0.954294 |
Quickly define and run unit tests in any test framework.
JavaScript
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.settings
bin
lib
samples
src
test
.project
LICENSE.txt
README.md
jsTestDriver.conf
package.json
run-all.js
README.md
JsQuickUnit
Most developers that don't write tests argue that it takes too much time to write them. Moreover, the pause required to write tests will almost surely break your line-of-though if you are developing a more complex algorithm.
By separating tests and source code, whenever there is a change in the code all the tests must be updated. These changes are frequent in the initial stages of a project and because of this, most developers prefer to write tests at a later stage. Big mistake!
JsQuickUnit is the solution: you can quickly define tests diretly from the unit you are developing and all the boilerplate code will be generated for you, in your favorite testing framework.
Example
Consider the following function, defined in file fact.js
var factorial = function (num)
{
if (num < 0) {
return -1;
}
else if (num == 0) {
return 1;
}
else {
return (num * factorial(num - 1));
}
};
In order to generate two tests for this function, just add the following annotations:
/**
* @test generalArgs
* @expect assertEquals(factorial(10), 3628800);
* @expect assertEquals(factorial(5), 120);
*
* @test cornerCases
* @expect assertEquals(factorial(1), 1);
* @expect assertEquals(factorial(0), 1);
* @expect assertEquals(factorial(-10), -1);
*/
var factorial = function (num)
{
if (num < 0) {
return -1;
}
else if (num == 0) {
return 1;
}
else {
return (num * factorial(num - 1));
}
};
Run jsquickunit fact.js test-fact.js and a file fact-test.js will be generated with the following contents:
var factTestCase = TestCase("factTestCase");
factTestCase.prototype.test_generalArgs = function() {
assertEquals(factorial(10), 3628800);
assertEquals(factorial(5), 120);
};
factTestCase.prototype.test_cornerCases = function() {
assertEquals(factorial(1), 1);
assertEquals(factorial(0), 1);
assertEquals(factorial(-10), -1);
};
By default jsquickunit generates code to js-test-driver but it is built to support any testing framework. More testing framework will be added soon.
Install
First make sure you have installed the latest version of node.js (You may need to restart your computer after this step).
From NPM for use as a command line app:
npm install jsquickunit -g
From NPM for programmatic use:
npm install jsquickunit
From Git:
git clone git://github.com/clagms/JsQuickUnit.git
cd JsQuickUnit
npm link .
Usage
jsquickunit sourceFile generatedTargetFile
or
jsquickunit sourceDir generatedTestDir
In the first use case, JsQuickUnit will read the annotations in the sourceFile and write the test code to the generatedTargetFile.
In the second use case, JsQuickUnit will generate test-*.js file in the generatedTestDir for each annotated source file in sourceDir. Note that generatedTestDir must exist. It will not be created.
API Reference
Assuming installation via NPM, you can load JsQuickUnit in your application like this:
var jsquickunit = require('jsquickunit');
It exports the following functions:
Generate a test file from a single source file:
jsquickunit.generateTestToFile('path/to/source/file.js','path/to/target/test/file.js')
Generate a test file for each source file in a specific directory:
jsquickunit.generateTestsToDir('path/to/source/dir','path/to/target/test/dir')
Supported Annotations
Most of the code provided in the annotations will be pasted inside the generated tests, so be carefull with the order in which you specify the tests. Supported annotations (incomplete list):
@test TestName
It marks a test annotation. The name of the test is mandatory and unique inside the current source file.
@with someElement = someExpression
It is usually used to stub elements (see a More Complete Example in the end of this document).
@run arbitraryJSCode
It is usually used to run arbitrary code (see a More Complete Example in the end of this document).
@expect assertionCode
Used to make assertions and invoke framework specific functions (see a More Complete Example in the end of this document).
More Complete Example
Consider the following code, defined in file observable.js
var makeObservable = function(that) {
if (!that) {
that = {};
}
that.observers = [];
/**
* @test addSingle
* @with observer=function() {};
* @with obj = makeObservable({});
* @run obj.addObserver(observer);
* @expect assertEquals(observer, obj.observers[0]);
*
* @test addTwo
* @with observer1 = function() {};
* @with observer2 = function() {};
* @with obj = makeObservable({});
* @run obj.addObserver(observer1);
* @run obj.addObserver(observer2);
* @expect assertEquals(2,obj.observers.length);
* @expect assertEquals(observer1,obj.observers[0]);
* @expect assertEquals(observer2,obj.observers[1]);
*
* @test errorNonFunction
* @with observer={}
* @with obj = makeObservable({});
* @with callback=function(){ obj.addObserver(observer); };
* @expect assertException(callback , "TypeError");
*
*/
that.addObserver = function(observer) {
if (typeof observer != "function") {
throw new TypeError("observer is not function");
}
that.observers.push(observer);
};
return that;
};
Run:
jsquickunit observable.js test-observable.js
or
jsquickunit.generateTestToFile('observable.js','test-observable.js')
And this is the result (using js-test-driver by default as a target):
var observableTestCase = TestCase("observableTestCase");
observableTestCase.prototype.test_addSingle = function() {
observer = function() {};
obj = makeObservable({});
obj.addObserver(observer);
assertEquals(observer, obj.observers[0]);
};
observableTestCase.prototype.test_addTwo = function() {
observer1 = function() {};
observer2 = function() {};
obj = makeObservable({});
obj.addObserver(observer1);
obj.addObserver(observer2);
assertEquals(2, obj.observers.length);
assertEquals(observer1, obj.observers[0]);
assertEquals(observer2, obj.observers[1]);
};
observableTestCase.prototype.test_errorNonFunction = function() {
observer = {};
obj = makeObservable({});
callback = function() {
obj.addObserver(observer);
};
assertException(callback, "TypeError");
};
|
__label__pos
| 0.840932 |
• sql server 2005 slow
Several times during the day SQL Server 2005 Express is becoming very very slow (actually freezes), even if there was no activitry at all. After restart it is normal again for a couple of hours, then freezes again.
Vad20 pointsBadges:
• Why sqlcode error=100 comes ?
sqlcode error=100 comes. The required fields are being populated in table. Still why i am getting this error ?
NAVIN5 pointsBadges:
• DTS Package Schedule runs only once, Status shows executing
Hi, I have set up a DTS Package and schedule it to run every 2 minutes (to prove it will run regularly). Unfortunately the package only runs once. The process only takes a few seconds. The job status shows "Executing Job Step '1 DTS Package1'" Is there something I'm missing? Gabs
Gabs15 pointsBadges:
• SQL Server 2000 Log File Size is increasing
I have a sql server 2000 where log file is increasing very fast. My mdb file is 600 MB and Log file 6GB. How can i reduce the size of the file. Shrinking the file is not working.
Ynaina5 pointsBadges:
• LDF size reduction
How can reduce *.LDF size i have run the command dbcc shrinkfile (Filename,1) but could not reduced.
SAP Cum IT35 pointsBadges:
• ASP.net profile object
I attempted to use the profile object as described in a training video; however when I hit f5(to execute the app in debug mode) the browser begins to opens up but I end up with the debugger telling me it cannot open SQL Server. According to the video the Profile object will default to "string" if...
Alemap5 pointsBadges:
• how to Configure mail profile in MS SQL 2000 ?
I have a requirment to recieve mail from my SQL server 2000 when ever a JOB in my SQL SERVER Agent fails ,I have my MAPI configured and SMPT too but in the SQL SERVER AGENT Properties window , the Mail profile is not enabled , how do i configure this , I want it in SQL SERVER 2000.
SRI HARSHA10 pointsBadges:
• Setting up failover notifications in SQL Server 2005 cluster
We are new to clustering. We have recently successfully implemented a four-node (active/passive config) SQL Server 2005 cluster. How can I be automatically notified when a node within the cluster fails over to the passive standby or other node within the cluster? Thanks, JGalt
JohnGalt35 pointsBadges:
• Command to display virtual nodes hosted by a physical server.
We have a four node (N+1)SQL 2005 cluster. From a DOS prompt, is there a command that can be run on each of the physical servers that will show you if it is hosting one of the virtual nodes of the cluster?
JohnGalt35 pointsBadges:
• Emails go straight to the Task Folder
In outlook 2007, some emails received are being moved straight to the task folder rather than the inbox. There are no rules set in Outlook causing this to happen. Any ideas? Is this a bug?
Lindsey5 pointsBadges:
• Error message in Query Analyzer on SQL Server 2005
I am trying to run the following command in Query Analyzer on SQL Server 2005: use temp alter user [MY-LP79EFIWXO93login_a] with login = [MY-LP79EFIWXO93login_b] However, I keep receiving this error: Msg 102, Level 15, State 1, Line 3 Incorrect syntax near 'login'. Why might this be?
SQL Server Ask the Experts2,585 pointsBadges:
• i5/OS vs MS sequel server 2005
The powers that be would like to replace our 20 year old i5 home grown billing system with a .NET solution (partial) over MS SQL Server 2005. How do we convince the powers that be to keep & improve what they have or should we just surrender and start taking .NET classes?
Soooyeah5 pointsBadges:
• Overlapping data on a merge replication between three SQL Servers
We have a merge replication between our three SQL servers at three different locations. One is the publisher and two are subscribers, and we have a primary key on a table (a unique field with is auto-incremental by one). On the publisher’s server, if the user creates a new order, the table...
SQL Server Ask the Experts2,585 pointsBadges:
• How to create new ramco test server?
Plz help me,when i restore my sql database with ramco backup then my database is restore but problem is that front-end not lounch in my system.
Amitshukla60 pointsBadges:
• Reindex DBF file from Ms-SQL 2000
Is it possible to reindex an extenal dbf file via linked server ?
Mic15 pointsBadges:
• sql reports
Sql Server Reporting service. 1.first query I have given a task of generating reports using sql server reporting service.I need to generate a summary view as below, Fig:1 Jan-08 Feb-08 Mar-08 Bug Trend ECR 3.88 4.06 3.86 Goal 5.00 5.00 5.00 Backlog 70 75 82 Incoming67 71 55 Outgoing62 65 56...
33015 pointsBadges:
• Database tables interrupted…..
Any input at all would be greatly appreciated - All I know is that a companywe provide IT Support to had 4 databases running when the SQL services were shut down on the server. Now the fellow cannot see any of his tables – nothing shows up when he opens SQL, or in his ODBC network connections....
AndreaF9,295 pointsBadges:
• Records with null value not in output
See query: select distinct f2.description Business_Unit, f3.description Department, f4.description Function, a.segment5 Account, f5.description Account_Description, sum(nvl(d.entered_dr,0) - nvl(d.entered_cr,0)) Actual, (Select sum(nvl(dd.entered_dr,0) - nvl(dd.entered_cr,0)) from...
Tams5 pointsBadges:
• SQL Subfile and position to ability
I have a subfile that can be sorted by any of 4 fields, so I want to use imbedded SQL to read the data out of my PF in order to populate the subfile. I want to be able to allow the user to enter position to information, and position to that entry - normally, I would do a SETLL to the file based on...
Klw50 pointsBadges:
• Executing System Stored Procedures
What kind of "Permissions" does a developer need in order to execute sp_fulltext_catalog, sp_fulltext_column, sp_fulltext_database, sp_fulltext_table, sp_addLinkedServer, sp_addLinkedSRVlogin ?
VelameLaCosa110 pointsBadges:
Forgot Password
No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.
Your password has been sent to:
To follow this tag...
There was an error processing your information. Please try again later.
REGISTER or login:
Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Thanks! We'll email you when relevant content is added and updated.
Following
|
__label__pos
| 0.906453 |
Design Pattern: Tagged Data
Problem Statement
Ensure that:
Framework
In addition to the PUBLISH_n/SUBSCRIBE_n service interface types, which use communication networks for exchange of data, and the PUBL_n/SUBL_n service interface types described under the Local Multicast pattern, only the two additional functional block types shown below are required. The function of these these blocks is to translate data from a local multicast group to a remote multicast group ( TAGOUT ) or vice versa ( TAGIN ) according to the following features:
An abstract internal implementation of each of these function block types is shown below for the case when a single data element is being transferred. The actual number and types of data being transferred is determined by the TYPE input as explained above.
TAGIN
TAGOUT
Tool Support
The FBDK provides built-in support for the use of tagged data when a system configuration is being edited:
Methodology
The methodology for using this design pattern consists of the two steps listed below. It can be used as a sub-pattern to simplify and avoid errors in the Distribution phase of other methodologies, such as the layered MVC pattern.
1. Distribute and debug the application among "local" devices such as FRAME_DEVICE, using the local multicast pattern. As an example, see the FLASHER_TESTD system configuration.
• This may be done by re-organizing resources from a single-device configuration such as FLASHER_TESTL, using the Move To pop-up menu item on a resource in the Navigation tree.
2. Replace the local devices with instances of their equivalent remote device types, e.g., RMT_DEV or RMT_FRAME, as appropriate.
• Add a TAGS resource (typically an instance of EMB_RES) to each device to map from local multicast to UDP multicast using instances of TAGIN and TAGOUT as appropriate.
• For example, see the FLASHER_TESTR system configuration.
|
__label__pos
| 0.951694 |
Differences
This shows you the differences between two versions of the page.
Link to this comparison view
field type - multiple part [2016/09/14 14:19] (current)
Line 1: Line 1:
+====== Multiple Part ======
+The multiple part field allows a Software Developer the ability to group several pieces of information together in the same way that an [[Field Type - Address|address]] or [[Field Type - Telephone|telephone]] field does. The Software Developer can define as many parts as they would like.
+
+===== How to Create =====
+ - Click the {{:presentation-layer:field-plus.png|}} to add a field in your [[Form|form]].
+ - Choose "New Field"
+ - Select the table you wish to add the field to. Most of the time, this will be the current [[Table|table]] you are on, called the current [[Context|context]].
+ - Select a field name and click "Choose Type".
+ - Choose "Multi Part" from the list of field types.
+ - You can continue adding fields or click the "Select" button to finish adding.
+ - After the field is added to the screen edit the configuration to add the parts to saved.
+
+
+===== Features =====
+==== Field Label ====
+ * [[Field Setting - Field Label|Field Label]]
+ * [[Field Setting - Display Alternate Label]] (affects this form only)
+==== Grid Appearance ====
+ * [[Field Setting - Column Span|Column Span]]
+ * [[Field Setting - Row Span|Row Span]]
+
+==== Tooltip ====
+ * [[Field Setting - Tooltip|Tooltip]]
+ * [[Field Setting - Descriptive Text|Descriptive Text]]
+ * [[Field Setting - Display Alternate Descriptive Text|Display Alternate Descriptive Text]] (affects this form only)
+==== Block Association ====
+ * [[Field Setting - Temporary Block Association|Temporary Block Association]]
+ * [[Field Setting - Global Block Association|Global Block Association]]
+
+==== Field Parts ====
+ * [[Field Setting - Allow Multiple Values|Allow Multiple Values]]
+ * [[Field Setting - Multiple Value Delimiter|Multiple Value Delimiter]]
+ * [[Field Setting - Field Parts|Field Parts]]
+
+==== Validation ====
+ * [[Field Setting - Required|Required]]
+==== Audit History ====
+ * [[Field Setting - Audit This Field|Audit This Field]]
+ * [[Field Setting - Show Audit History|Show Audit History]]
+==== View Only ====
+ * [[Field Setting - View Only|View Only]]
+
+===== Field parts =====
+The Multiple Part field has a variable number of field parts depending on the builders configuration.
+
+===== Output formats =====
+The Multiple Part field has a variable number of output formats one for each part the builder creates. This allows a builder to pull individual pieces of data from the field in expressions and actions.
field type - multiple part.txt · Last modified: 2016/09/14 14:19 (external edit)
Copyright WorkXpress, 2019
|
__label__pos
| 0.608212 |
Example #1
0
func TestLogout(t *testing.T) {
netrcFile := bytes.NewBufferString(`
machine github.com
login [email protected]
password secretpw
machine 127.0.0.1
login [email protected]
password abcxyz123
`)
config.APIEndpoint = "http://127.0.0.1/api"
loadNetrc = func() *netrc.Netrc {
nrc, _ := netrc.Parse(netrcFile)
return nrc
}
writeNetrcFile = func(body []byte) error {
_, err := netrcFile.Write(body)
return err
}
err := Logout()
if err != nil {
t.Error(err)
}
expectedNetrcFile := `
machine github.com
login [email protected]
password secretpw
`
if netrcFile.String() != expectedNetrcFile {
t.Error("Expected netrcFile to contain github login")
}
}
Example #2
0
func (l *login) updatedNetrcContent(
e *env,
content io.Reader,
credentials *credentials,
) ([]byte, error) {
tokens, err := netrc.Parse(content)
if err != nil {
return nil, stackerr.Wrap(err)
}
server, err := getHostFromURL(e.Server)
if err != nil {
return nil, err
}
machine := tokens.FindMachine(server)
if machine == nil {
machine = tokens.NewMachine(server, "default", credentials.token, "")
} else {
machine.UpdatePassword(credentials.token)
}
updatedContent, err := tokens.MarshalText()
if err != nil {
return nil, stackerr.Wrap(err)
}
return updatedContent, nil
}
Example #3
0
func (l *Login) GetTokenCredentials(e *Env, email string) (bool, *Credentials, error) {
reader, err := l.getTokensReader()
if err != nil {
return false, nil, stackerr.Wrap(err)
}
tokens, err := netrc.Parse(reader)
if err != nil {
return false, nil, stackerr.Wrap(err)
}
server, err := getHostFromURL(e.Server, email)
if err != nil {
return false, nil, err
}
machine := tokens.FindMachine(server)
if machine != nil {
return true,
&Credentials{
Token: machine.Password,
}, nil
}
if email == "" {
return false, nil, stackerr.Newf("Could not find account key for %q", server)
}
// check for system default account key for the given server
// since we could not find account key for the given account (email)
server, err = getHostFromURL(e.Server, "")
if err != nil {
return false, nil, err
}
machine = tokens.FindMachine(server)
if machine != nil {
return false,
&Credentials{
Token: machine.Password,
}, nil
}
return false,
nil,
stackerr.Newf(
`Could not find account key for email: %q,
and default access key not configured for %q
`,
email,
e.Server,
)
}
Example #4
0
func (l *login) getTokenCredentials(e *env) (*credentials, error) {
reader, err := l.getTokensReader()
if err != nil {
return nil, stackerr.Wrap(err)
}
tokens, err := netrc.Parse(reader)
if err != nil {
return nil, stackerr.Wrap(err)
}
server, err := getHostFromURL(e.Server)
if err != nil {
return nil, err
}
machine := tokens.FindMachine(server)
if machine == nil {
return nil, stackerr.Newf("could not find token for %s", server)
}
return &credentials{
token: machine.Password,
}, nil
}
Example #5
0
func TestLogin(t *testing.T) {
// Fake gemnasium api
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check URI
if r.RequestURI != LOGIN_PATH {
t.Errorf("Expected RequestURI to be %s, got: %s", LOGIN_PATH, r.RequestURI)
}
// Check request is a POST
if r.Method != "POST" {
t.Errorf("Expected a POST, got a %s", r.Method)
}
var credentials struct {
Email, Password string
}
err := json.NewDecoder(r.Body).Decode(&credentials)
if err != nil {
t.Error(err)
}
w.Header().Set("Content-Type", "application/json")
if credentials.Email != "" && credentials.Password != "" {
w.Write([]byte(`{"api_token": "abcxyz123"}`))
} else {
w.WriteHeader(http.StatusBadRequest)
}
}))
defer ts.Close()
config.APIEndpoint = ts.URL
// don't try to use stdin
getCredentials = func() (email, password string, err error) {
return "[email protected]", "secret123", nil
}
netrcFile := bytes.NewBufferString("")
loadNetrc = func() *netrc.Netrc {
nrc, _ := netrc.Parse(netrcFile)
return nrc
}
// don't actually write to the file
writeNetrcFile = func(body []byte) error {
_, err := netrcFile.Write(body)
return err
}
err := Login()
if err != nil {
t.Error(err)
}
expectedNetrcFile :=
`machine 127.0.0.1
login [email protected]
password abcxyz123`
if netrcFile.String() != expectedNetrcFile {
t.Errorf("Expected netrcFile to be:\n%#v\ngot:\n%#v\n", expectedNetrcFile, netrcFile.String())
}
}
|
__label__pos
| 0.999955 |
Question about MAC address
(imported topic written by bearandy)
I want to compare if the computers’ Mac address are same.
And to delete the old computer agent.
Are there any relevance that can create a analysis to compare MAC address?
(imported comment written by BenKus)
Hi bearandy,
Try using the Computer Remover utility, which should do almost exactly what you want:
https://www.ibm.com/developerworks/mydeveloperworks/wikis/home?lang=en#/wiki/Tivoli%20Endpoint%20Manager/page/TEM%20Computer%20Remover
(Use the -P option)
Ben
(imported comment written by bearandy)
Thanks for answer.
I do not exactly know how to use it.
download and just execute it?
Should I create an fixlet or something?
(imported comment written by bearandy)
other question:
Is there a relevance could compare each computers about properties like computer name or address and list the same of it.
(imported comment written by bearandy)
It only show the number of duplicate computers.
How could I know which computer to delete?
Is it possible to see the computer?
(imported comment written by Lee Wei)
This Session Relevance statement will list all MAC Addresses with duplicate values.
unique values whose (multiplicity of it > 1) of values of results of bes property "MAC Addresses - Windows"
This is an example statement that can search for some specific MAC Addresses.
(name of item 0 of it, item 1 of it) of (computers of it, values whose (it contains "00-02-a5") of it) of results of bes property "MAC Addresses - Windows"
If we combine the 2, we can return the duplicate values along with the names of the computers. You can also replace “MAC Addresses - Windows” with other properties to find other duplicates.
unique values of (item 1 of it & " - " & name of item 0 of it) of (computers of it, values whose (it is contained by (concatenation "|" of unique values whose (multiplicity of it > 1) of values of results of bes property "MAC Addresses - Windows")) of it) of results of bes property "MAC Addresses - Windows"
Lee Wei
(imported comment written by Lee Wei)
The final statement returns something like the following on my system.
Results
00-02-a5-02-29-82 - SQUEEZE
00-02-a5-02-29-82 - ZENDEN
00-50-56-c0-00-01 - C5DM2
00-50-56-c0-00-01 - CORONA
00-50-56-c0-00-01 - TRADERS
00-50-56-c0-00-01 - ZENDEN
00-50-56-c0-00-08 - C5DM2
00-50-56-c0-00-08 - CORONA
00-50-56-c0-00-08 - TRADERS
00-50-56-c0-00-08 - ZENDEN
Lee Wei
|
__label__pos
| 0.723411 |
64 600
Assignments Done
99,2%
Successfully Done
In September 2018
Answer to Question #12801 in Algebra for Ryan
Question #12801
This problem was used a few times on the classic radio program The Life of Riley in the 1940s. Is there an answer?
A farmer sells 2 bushels of apples at X dollars a bushel. The next day the farmer sells 3 bushels of tomatoes for 1/3 the price of the apples. The day after he sells 1 ½ bushels of potatoes for 4/5 the price of the tomatoes. With the money he receives he buys 3 gallons of kerosene and 6 bags of fertilizer. If kerosene sells at $1 a gallon and fertilizer at $4 a bag, what's the price of … the apples?!
Expert's answer
A farmer sells 2 bushels of apples at X dollars a bushel.
T = 2 * X.
The
next day the farmer sells 3 bushels of tomatoes for 1/3 the price
of the
apples.
T = 2 * X + 3 * (X / 3)
The day after he sells 1 ½ bushels of
potatoes for 4/5 the price of
the tomatoes.
T = 2 * X + 3 * (X / 3) + 1.5
* (4 * (X / 3) / 5)
With the money he receives he buys 3 gallons of kerosene
and 6 bags of
fertilizer:
C = 3 * 1 + 6 * 4 = 27
If T = C:
2 * X + 3
* (X / 3) + 1.5 * (4 * (X / 3) / 5) = 27
2 * X + X + 12 * X / 30 = 27
90 *
X / 30 + 12 * X / 30 = 27
102 * X = 810
X = $7.94
Need a fast expert's response?
Submit order
and get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS!
Comments
No comments. Be first!
Leave a comment
Ask Your question
Submit
Privacy policy Terms and Conditions
|
__label__pos
| 0.996705 |
Python
This is the page of the Maemo/Harmattan Python project. Python is an interpreted, dynamic programming language.
[edit] PyMaemo (Python for Maemo)
The PyMaemo (Python for Maemo) project maintains a set of packages necessary to run and develop Python applications on the Maemo platform.
For all PyMaemo-related content, see:
[edit] MeeGo 1.2 Harmattan Python
The MeeGo 1.2 Harmattan Python project provides a Python runtime environment for Nokia's N9 phone and the N950 developer device built on the MeeGo 1.2 Harmattan platform. It provides a full-featured set of packages and tools to rapidly develop and run Python applications using the PySide: Python for Qt bindings together with the Qt Quick UI definition language.
For all Harmattan-related content, see:
[edit] Documentation and Guides
Please keep documentation pages in the "Python" section by prefixing the page title with "Python/".
[edit] Communication
• IRC: /join #meego-python #pymaemo #pyside on irc.freenode.net
• Mailing list:
[edit] Talks, BoFs and Events
|
__label__pos
| 0.906643 |
Location: PHPKode > projects > My little forum > forum/modules/smarty/internals/core.write_cache_file.php
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Prepend the cache information to the cache file
* and write it
*
* @param string $tpl_file
* @param string $cache_id
* @param string $compile_id
* @param string $results
* @return true|null
*/
// $tpl_file, $cache_id, $compile_id, $results
function smarty_core_write_cache_file($params, &$smarty)
{
// put timestamp in cache header
$smarty->_cache_info['timestamp'] = time();
if ($smarty->cache_lifetime > -1){
// expiration set
$smarty->_cache_info['expires'] = $smarty->_cache_info['timestamp'] + $smarty->cache_lifetime;
} else {
// cache will never expire
$smarty->_cache_info['expires'] = -1;
}
// collapse nocache.../nocache-tags
if (preg_match_all('!\{(/?)nocache\:[0-9a-f]{32}#\d+\}!', $params['results'], $match, PREG_PATTERN_ORDER)) {
// remove everything between every pair of outermost noache.../nocache-tags
// and replace it by a single nocache-tag
// this new nocache-tag will be replaced by dynamic contents in
// smarty_core_process_compiled_includes() on a cache-read
$match_count = count($match[0]);
$results = preg_split('!(\{/?nocache\:[0-9a-f]{32}#\d+\})!', $params['results'], -1, PREG_SPLIT_DELIM_CAPTURE);
$level = 0;
$j = 0;
for ($i=0, $results_count = count($results); $i < $results_count && $j < $match_count; $i++) {
if ($results[$i] == $match[0][$j]) {
// nocache tag
if ($match[1][$j]) { // closing tag
$level--;
unset($results[$i]);
} else { // opening tag
if ($level++ > 0) unset($results[$i]);
}
$j++;
} elseif ($level > 0) {
unset($results[$i]);
}
}
$params['results'] = implode('', $results);
}
$smarty->_cache_info['cache_serials'] = $smarty->_cache_serials;
// prepend the cache header info into cache file
$_cache_info = serialize($smarty->_cache_info);
$params['results'] = strlen($_cache_info) . "\n" . $_cache_info . $params['results'];
if (!empty($smarty->cache_handler_func)) {
// use cache_handler function
call_user_func_array($smarty->cache_handler_func,
array('write', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id'], $smarty->_cache_info['expires']));
} else {
// use local cache file
if(!@is_writable($smarty->cache_dir)) {
// cache_dir not writable, see if it exists
if(!@is_dir($smarty->cache_dir)) {
$smarty->trigger_error('the $cache_dir \'' . $smarty->cache_dir . '\' does not exist, or is not a directory.', E_USER_ERROR);
return false;
}
$smarty->trigger_error('unable to write to $cache_dir \'' . realpath($smarty->cache_dir) . '\'. Be sure $cache_dir is writable by the web server user.', E_USER_ERROR);
return false;
}
$_auto_id = $smarty->_get_auto_id($params['cache_id'], $params['compile_id']);
$_cache_file = $smarty->_get_auto_filename($smarty->cache_dir, $params['tpl_file'], $_auto_id);
$_params = array('filename' => $_cache_file, 'contents' => $params['results'], 'create_dirs' => true);
require_once(SMARTY_CORE_DIR . 'core.write_file.php');
smarty_core_write_file($_params, $smarty);
return true;
}
}
/* vim: set expandtab: */
?>
Return current item: My little forum
|
__label__pos
| 0.995838 |
How to use Open Graph Protocol
What is Open Graph Protocol and why you need it?
Open graph protocol is a protocol (i.e. set of rules) which is used to integrate any web page into the social graph. For example Facebook can be your social graph or social circle. Once the web page is integrated it behaves like the object of the social graph (facebook) i.e. it has same functionality as a facebook page.
Through open graph protocol you can tell Facebook how your shared contents should be displayed on Facebook. This protocol tells facebook which title, URL, image and description of your blog post/page should be used when your content is shared on facebook.
Open Graph Protocol Meta Tags
To turn your web page into a graph object, you need to use open graph protocol meta tags and the ‘like’ button. Following are examples of such Meta tags:
1. <meta property=”og:title” content=” “/>
2. <meta property=”og:type” content=””/>
3. <meta property=”og:url” content=””/>
4. <meta property=”og:image” content=””/>
5. <meta property=”fb:admins” content=””/>
6. <meta property=”og:site_name” content=””/>
7. <meta property=”og:description” content=””/>
Easiest way to Implement Open Graph Protocol
If you are using wordpress, you can use wordpress for SEO Plugin by Yoast to add open graph protocol Meta tags on your website. Once you have added the plugin, follow the steps below:
1. Go to plugin settings (SEO > Social)
2. Click on the checkbox ‘Add Open Graph Meta Data’
3. Click on ‘Add Facebook Admin Button’
4. Click on ‘Save Settings’ button.
Manually Implementing Open Graph Protocol
If you don’t use wordpress or you want to add these Meta tags manually then follow the steps below:
Step-1: Create a Facebook Page or Facebook Application and then claim your domain by associating it with Facebook Page/App. In this way you can use Facebook Page/App insight.
Step-2: Note down the value of the application ID if you have created Facebook App. Otherwise just note down the value of Facebook Admin ID which you can determine from your Facebook Insight Page.
Step-3: Open your theme’s header file (generally header.php) and add following code just before the <head> tag on your web page:
Step-4: Copy-paste the following code at the bottom of your functions.php file and upload it to the server. This code will get the first image from the post and display it.
Step-5: Add following open graph protocol meta tags in the head section (<head>…</head>) of your header.php page:
Tweet to get the code
Replace ‘your_fb_admin_id’ with your Facebook Admin ID.
Note: og:type means type of the object. Since our object is a piece of content (article, blog post, video, photo etc) I have used ‘article’ as object type. You can see the complete list of supported object types here.
Step-6:
Once you have added your special meta tags, you can now add the ‘Facebook like’ button code into the body section (<body>..</body>) of your web pages. You can get the ‘like’ button code from here.
You can either add the HTML 5 code or XFBML (Extensible facebook markup language) code to add ‘like’ button to your web page. Through ‘like’ button, facebook users can share your web page contents with other facebook users.
If a facebook user (who ‘liked’ you content) happens to be your friend and you are already logged into the facebook, then the like button will display the name and photo of that friend.
If you are logged out of facebook, then the ‘like’ button will look like this:
Step-7: Test your open graph meta tags here: http://developers.facebook.com/tools/debug
That’s it. You have successfully used the open graph protocol :)
Example of a web page which uses the open graph protocol
Other Posts you may find useful:
Subscribe to my blog
Join my free newsletter and learn to avoid the analytics mistakes everyone seems to be making over and over again.
About the Author:
Please feel free to endorse/forward my LinkedIn Profile to your clients, colleagues, friends and others you feel would benefit from PPC, Web Analytics or Conversion Optimization.
For any question/comment Contact me
|
__label__pos
| 0.626037 |
Enhanced Balance Mod for 3.x
Did you create a mod, map, music, or a tool? Present them here and earn feedback!
Note: addon requests do not belong here.
Note, everything uploaded to this forum, MUST have a license!
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 18 Apr 2017, 23:15
Hey all thanks for the quick replies,
NoQ wrote:To me, some of the biggest flaws of Nexus included inability to counter spam (tank spam, cyborg spam, tower spam, machinegun spam, rocket spam) by countering them with tech and production choices
I definitely agree. The fact that Nexus doesn’t produce good units or choose good research choices means that it’s essentially unplayable for decent players but newbies don’t realize that. I fixed this by statically populating the template and research arrays. This is an example of what I mean when I say fix something and be done with it. Now that the template and research arrays are ordered from the beginning of the tech tree to the end using each weapon path, this AI essentially cannot be out-researched or produced. The arrays can be adjusted a little bit for specific game/map settings but generally speaking it makes the best units and researches the best things at all times for its chosen profile and the profiles are chosen based on map/game settings so it’s not really possible to achieve anything better in regards to droid designs and research objectives, there’s nothing left to do, it’s fixed and done with.
Nexus pursues research objectives regardless of power and I set power management checks on droid production; cyborgs, tanks and VTOLS only produce with minimum of 25, 50 and 700 power I think. Those numbers can be adjusted but the arrays themselves are pretty much finalized.
Profiles are chosen based on 40/40/20 chance of choosing rocket, cannon, flamer for no allies or no shared research. If shared research then flamer if map size < 130, cannons 130 – 170 and rockets 170+. Likelihood of artillery branch uses the linear function with map size 90 = 0
Code: Select all
Code for selecting research profiles
_ally = 0;
_count = 0;
while(_ally < MAX_PLAYERS)
{
if(allianceExistsBetween(me, _ally)){
_count++;
}
_ally++;
}
if(_count > 0 and multiPlayerAlliancesType == ALLIANCES_TEAMS)
{
if(_mapSize < 130.0)
{
curTech = branchFlameVtolLaser;
dbg("going rockets (" & _y & "/" & _rnd & ")", me);
}
else if(_mapSize < 170.0)
{
curTech = branchCannonMGMortar;
dbg("going cannons (" & _y & "/" & _rnd & ")", me);
}
else
{
curTech = branchRocketMGMortar;
dbg("going Mortar (" & _y & "/" & _rnd & ")", me);
}
}
else
{
//probability to choose artillery branch for map size 90 = 0; probability for map size 200 = 55
//build a linear function: y = ((y2 - y1) / (x2 - x1)) * x + a depending on two values given (short: y = mx+a)
_x1 = 90.0; _y1 = 0.0;
_x2 = 200.0; _y2 = 55.0;
_m = ((_y2 - _y1) / (_x2 - _x1));
_a = -(_m * _x1);
//calculate probability for the current map
_y = _m * _mapSize + _a;
dbg("_m = " & _m & ", a = " & _a, me);
_rnd = (float)random(100);
if(_rnd < _y)
{
curTech = branchArtillery;
dbg("going air (" & _y & "/" & _rnd & ")", me);
}
else
{
__rnd = random(10);
if(__rnd < 4)
{
curTech = branchRocket;
dbg("going rockets (" & _y & "/" & _rnd & ")", me);
}
else if(__rnd > 6)
{
curTech = branchCannon;
dbg("going cannons (" & _y & "/" & _rnd & ")", me);
}
else
{
curTech = branchFlamer;
dbg("going flamer (" & _y & "/" & _rnd & ")", me);
}
}
}
The same goes for the base building. I set base build sequence to factory, research, power, derrick and then the base building triggers for each structure are called every < 7 - 10 seconds. Structure modules are upgraded from nearest to furthest as soon as modules are available. You can attempt to make a bot that builds a better base but programmatically I don’t see how it can be improved much.
There are 4 things I can think of that still need fixing with base building before I would declare that it’s close to perfection. The first is building base structures in the closest spot location instead of elsewhere in the base, the second is to check if there is a cliff between the truck and proposed building location, the third is to set a 3 truck minimum when upgrading structures and the 4th is to create multiple build groups. If I fix those 4 things then base building behavior is essentially done with, it’s not really possible to build a faster base but even without these 4 items the base building performance is still optimized and better than all other bots. Base building is another one of those things that once it’s fixed it’s done with.
Berserk Cyborg wrote:
MIH-XTC wrote:This bot will smash all other current and foreseeable bots most of the time with the exception of certain small map, low oil rush games.
Naturally. How can you expect other AI, which are only 'balanced' in regards to the base game, to be anywhere near as good as your bot when introduced to all of your changes? It is totally unfair to make that judgement unless the other bots are tweaked for your balance. Anyway, the modified Nexus AI you included is amazing none the less.
It doesn’t have anything to do with the stats but rather 3 of the 4 components of a WZ game are near flawless, base building, research objectives and droid designs are all near optimal performance. It’s really just a matter of not being able to make a better AI outside of droid behaviors. Although my bot does take advantage of the fact that I made mortar arrive earlier (after sensor tower instead of factory).
The only remaining and subjective component of a WZ game is droid handling and that’s where things get complicated. I haven’t done much with unit orders as that is the hardest part of making an AI.
NoQ wrote:, and also inability to group up units before engaging in combat. Most of NullBot's complexity is about these features.
I haven’t touched anything with droid behaviors besides changing most of the DORDER_MOVE’s to SCOUT because too many times I seen Nexus droids suicide into other armies because they don’t know to stop on enemy contact. Actually bonecrusher does a really good job of grouping units and then attacking, bonecrusher’s rally points are very observable prior to attacking. Not sure if Nullbot does the same. Bonecrusher also does a really good job of 1v2’ing.
There is a small bug I created in an attempt to get VTOL’s to attack relentlessly in which the VTOL’s remain idle over their target. Instead of attacking targets I made the VTOL’s patrol to their target coordinates meaning they attack anything in sight on their way to their target. The problem is that the secondary patrol order needs to be set after every new DORDER and once the VTOL’s are done attacking an object in route to their target, they proceed to their target without any attack order. One alternative is to set secondary patrol orders on vtols every time they arrive at their destination but then this overrides the rearming orders and the VTOL’s are stuck flying around without ammo. The solution to that is to check vtol ammo levels but there aren’t any functions available in mp for that. Right now I have the VTOL’s set to attack anything in route to their target but after they kill one object the patrol orders come off and then they’re stuck idling around their target until they die.
NoQ wrote:Note that the former is quite useless in AI vs AI matches, because AIs already avoid spam strategies, but newbie humans don't, and the primary sense of having good AIs is to teach humans to play better.
AI vs AI games essentially end up being a spam fast. Testing AI vs AI is almost like creating a droid collider similar to a particle collider. The weapons with longer ranges usually win in AI vs AI, especially grenadier although Nullbot did a really good job of using flamers and mg’s to overcome that. In larger games no AI will be able to stop the spam of this Nexus AI because it’s guaranteed to have superior droid upgrades and designs.
I also agree that the purpose of an AI is not to win but rather to prepare players for mp because mp and base are two totally different games and Nexus does not prepare players for playing in mp. I prioritized variation over winning in terms of droid designs, some of the research choices, some of the strategy choices and decision to build defensive structures. If I wanted to make a bot that would win all of the time then I would just do flamer + truck rush but the default AI should showcase how all of the different strategies are intended to be used.
NoQ wrote:At the same time, winning AI vs AI matches is a good achievement, but i suspect i could easily provide a NullBot personality (~100 lines of code) that would be better than your AI on your test cases (given the test cases);
I think not because the only thing that’s possible to do better is droid handling. The research objectives, droid designs and base building are already optimized to near perfection so the longer the game goes on, the harder it will be to beat this AI. The only time this Nexus AI is vulnerable is in the early base building phase because it takes the gamble of building a base instead of rushing. Other than that, once this bot gets going it will always win in AI vs AI because like I said, the research arrays, template arrays and base building are optimized to the point where you won’t be able to develop a better AI. It’s not really possible unless you have the same or very similar arrays. It’s fixed and done with…
Once I improve the droid behaviors and defend against early rush then this bot will be unbeatable. Actually, the only time it loses now is because some of the droids stand around in the base while it’s being attacked and they don’t do anything. Once that’s fixed, there’s really no chance for this bot to lose vs another bot…
NoQ wrote:Note also that NullBot, with all these features and many other human-oriented tweaks (eg. varied gameplay, and also chat support) has less lines of code than the current Nexus AI, and you are already adding 2000 more lines of code with your patch. From just that i'd conclude that my language choice was correct, and it is a consistent observation that javascript code is generally ~4 times shorter for the same amount of features (we notice it in the campaign as well).
Yea but that stuff is transparent to the end users/players, I don’t mind to use any programming language, I didn’t use .js only because I don't understand how the Nullbot triggers work (where are they?) and I'm very desperate to be finished with this project and move on. I’m under the impression that once I get this stuff “fixed” it’s done with and I’ll never have to return to it. Since I’m already familiar with the .vlo and .slo files I just want to keep going. Someday I will go back and look at the .js for the sake of learning .js but I have too much WZ and IRL stuff to do. I just don't want to invest the time to learn .js right now. I'm actually impressed that you could even pursue something like that. Rewriting the Nexus files in .js sounds like an insane task. Like you said in your dear programmers thread in "other talk" people work on whatever makes them happy.
NoQ wrote:That said, i appreciate your work and i'd approve adding your AI to the game (as long as it's using the base game's data and works without your data mods), probably as an extra AI alongside Nexus if we want to keep Nexus available as a nostalgic "like the old times" option (i personally don't enjoy having Nexus around, so i'd approve replacement as well).
That’s unfortunate you don’t like the stats, I bet it’s about 45% you want to preserve originality in the code and 45% I changed so much stuff that you don’t have any way of verifying the changes, 10% lost credibility of things I might have said in this thread prior to knowing what I know now. The problem with the current stats is that the game is too deterministic in terms of strategy. Everyone thinks that because there are hundreds of research items and thousands of droid designs that WZ offers complex strategy but it’s actually the opposite, you can just straight up calculate the best strategy for any given map/game settings to guarantee victory 100% of the time unless the same exact strategy is employed. That's not obvious to other people but I'm sure I can beat any player in mp. In fact, if you provide me the game and map settings then I can tell you down to the keystroke exactly what I would do before the game begins and still win. The game consists of the 4 components I mentioned above with droid handling being the only subjective one. Here’s an example of the best strategy on Arid map consisting of build order, truck order and research order https://www.youtube.com/watch?v=u8irDuPU7Sk exact instructions are in the description. That’s why I want to change the stats because I already know exactly what to do for all maps and there is no counter strategy. That strategy in the video cannot be countered by flamers or rockets, there’s nothing you can do besides the same thing. I hope you reconsider on the stats. Sorry for coming off as dogmatic but I know WZ very well.
Last edited by MIH-XTC on 18 Apr 2017, 23:51, edited 1 time in total.
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby NoQ » 18 Apr 2017, 23:34
I appreciate rebalancing either, as balancing flaws are well-known, but currently i'm in no position to discuss that, so i skipped that topic (at the risk of being off-topic and not helpful). Balancing is often a matter of hot discussions, and you can't easily include multiple balances with the base game (without mods), so it's not as simple as the common open-source approach of "it's ok as long as you're committing time into maintaining it" - it's a hard decision to be made. So having AI changes separate from balance changes would certainly help.
the research arrays, template arrays and base building are optimized to the point where you won’t be able to develop a better AI
That's great. In the worst case, i'd have to steal these arrays then to fulfill my claim; apologies for not having time to back up my words with any real evidence...
User avatar
NoQ
Special
Special
Posts: 6048
Joined: 24 Dec 2009, 11:35
Location: /var/zone
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 19 Apr 2017, 04:03
That's great. In the worst case, i'd have to steal these arrays then to fulfill my claim; apologies for not having time to back up my words with any real evidence...
Naw man, no need to apologize, I understand that it's just loose talk and that we don't have time to get caught up in petty claims.
NoQ wrote:I appreciate rebalancing either, as balancing flaws are well-known, but currently i'm in no position to discuss that, so i skipped that topic (at the risk of being off-topic and not helpful). Balancing is often a matter of hot discussions, and you can't easily include multiple balances with the base game (without mods), so it's not as simple as the common open-source approach of "it's ok as long as you're committing time into maintaining it" - it's a hard decision to be made. So having AI changes separate from balance changes would certainly help.
Ah okay, I thought you meant that you wanted the stats separate from the AI because you didn't like them. It would take a couple of hours to separate them but I'm done with WZ for awhile, that's why I posted what I have yesterday. I also wasn't mindful that as staff the topic may be out of scope and I don't blame you for avoiding the politics.
I suppose this is an executive decision then? The board of directors? I won't name names but basically the 6 people on the Github splash.
I understand that changing the stats is altering the game at a fundamental level. Heck, I realized that before I started this thread and all of the unnecessary verbosity is me just lobbying for credibility to make such changes. Just to be clear, the stats that I have are only for mp/skirmish games, they don't affect base.
I'm open to adding/removing anything in particular, it doesn't have to come in one package. What is good about the stats and what is bad? I've tried several approaches at how to best categorize and explain stat changes to no avail. If you're not able to open the stats editor in Excel 2010/2013 then it might be hard for that person to understand how to identify what has changed.
I'm done for awhile, too much typing here.
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby Prot » 19 Apr 2017, 09:05
I found some time to test your bot, I will say it was a very entertaining match and a little bit not fair.
I have used my unpublished bot which is under development.
I was very surprised when my builders just die next to the oil extractors which are not protected, then I noticed that your extractors are shot by themselves from a machine gun. Whoooaaa?!
Despite the fact that my bot was holding about 90% of the resources, your bot continued indefinitely to produce an army, how many resources? My bot took about 40 minutes to keep Nexus under siege for the victory.
Too much new technology, which my bot doesn't know, particularly amused by the speed of the units in ~2.5 times the speed of my bot.
Despite such an unfair match, it was very fun to watch.
https://youtu.be/nxntfAP9Uu4
Last edited by Prot on 20 Apr 2017, 06:08, edited 1 time in total.
User avatar
Prot
Trained
Trained
Posts: 58
Joined: 29 Nov 2010, 12:41
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 19 Apr 2017, 23:12
Thanks a lot for uploading a video
I was very surprised when my builders just die next to the oil extractors which are not protected, then I noticed that your extractors are shot by themselves from a machine gun. Whoooaaa?!
Yea, I added a new “guarded” oil derrick that automatically becomes available after researching MG “guard” tower. The stats of the guarded derrick are supposed to be in between a derrick and an MG tower. I got the idea from NoQ here viewtopic.php?f=42&t=11552
Here are the stats for the derricks and guarded tower.
Image
It's very lame that I don't have a different graphical .pie model for the guarded derrick, I don't know how .pie files work. It is a little bit weird to see a magical mg appear from the derrick.
Despite the fact that my boat was holding about 90% of the resources, your bot continued indefinitely to produce an army, how many resources?
That is because the base power on power generators increased from 55 power per minute to 80 and the power module was increased from 28 power per minute to 40 (with 4 derricks). The reason for this is to allow for more power on low oil maps, that’s why there are more units, more research and more “activity” in general when playing with my bot, there is more power. Since all players currently play with the high power setting then they can change it to medium power or low power if it’s too much for them but there’s no such option for players who currently want more power on low oil maps because the high power setting is already maxed out. That’s probably why the AI was able to survive off 4 – 6 derricks and why low oil maps are more fun.
EDIT: hey by the way, when you test, do you use 100X speed?
Last edited by MIH-XTC on 20 Apr 2017, 04:33, edited 1 time in total.
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 20 Apr 2017, 03:54
Here's complete documentation to stat changes from editor for those who can't view excel 2010/2013 (which I have a feeling is everyone).
Green = improvement
Red = nerfed
Yellow = change to text (non-integer)
Unfortunately the editor only shows what has changed, not by how much.
Changes to bodies:
Image
New research items added to the tech tree. Please tell me which ones to remove if you don't like them. Also the names I don't care about, that's overhead to me. I re-used the existing icons to display on the research menu. So range upgrades for weapon lines use icons heavy mg, MRA, medium cannon, bombard, inferno.
Image
Changes to research pre-requisites:
Image
Complete list of all tech tree items with dependencies and upgrade values
Image
Changes to propulsions:
Image
Changes to repair:
Image
Changes to construction:
Image
Changes to sensors:
Image
Changes to structure damage modifiers:
Image
Changes to structures:
Image
New templates added for AI use:
Image
Changes to weapon modifiers:
Image
Changes to weapons: (Note that I created another instance of the weapons for the structures so that they can be modified independently. Programmatically it's ugly but gameplay wise it's the ticket.
Image
I also had to model the cyborg speeds to help make sure they were balanced. Thanks again to crab for showing me this formula
Image
Last edited by MIH-XTC on 20 Apr 2017, 06:01, edited 1 time in total.
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby Prot » 20 Apr 2017, 06:07
New research items added to the tech tree. Please tell me which ones to remove if you don't like them.
here you can't just say "I don't like it, remove it," every change of stats, research, armor, radius, etc. will greatly affect the game overall, as at the beginning and at the end. Here we need many matches to spend with different people, to understand where the imbalance is and then convincingly say "remove it".
as soon as I have free time again, I will continue work on the bot, I was interested in the mod, because there is something new and I think will do a separate tuning my bot, designed straight for your modification.
User avatar
Prot
Trained
Trained
Posts: 58
Joined: 29 Nov 2010, 12:41
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 02 May 2017, 01:04
Status Update:
Still working on improving Nexus AI, I only have a couple of more things I want to improve. I added some behaviors that are outlined below in code chunks
Summary:
- knows how to defend now (automatically attacks anything within 15 tiles of base if we have at least 10 attack droids).
- no longer has droids accumulating in base doing nothing. (caused stalemates in long/big games)
- knows how to help allies and builds base even faster by selecting optimal build locations.
Details are below:
--------- Added some constants for easily modding power management checks
Code: Select all
#define MIN_BUILDPOWER_CYBFACTORY 25
#define MIN_BUILDPOWER_FACTORY 400
#define MIN_BUILDPOWER_RESCENTER 250
#define MIN_BUILDPOWER_VTOLFACTORY 600 // except VTOL research profile
#define MIN_PRODUCTIONPOWER_FACTORY 25
#define MIN_PRODUCTIONPOWER_CYBFACTORY 10
#define MIN_PRODUCTIONPOWER_VTOLFACTORY 100
#define MIN_PRODUCTIONPOWER_TRUCK 150
#define MIN_BUILDPOWER_DEFENSE 200
#define MIN_BUILDPOWER_EXTRASTRUCTS 200
#define MIN_BUILDPOWER_ARTILLERY 0 // only artillery and shared allied research profiles build artillery
-------- Improved buildPowerGenerators() to find the closest truck to the closest available location in a 10x10 area centered on base. Then I copied this event and swapped out the power generators for other base structures. The most optimal location might be off by 2 - 3 tiles (at most) due to how it loops (on diagonal) but it's still a huge improvement over previous Nexus.
I also tried like heck to figure out how to detect a cliff in between a constructor droid and target build location but concluded it's not possible with current WZscript. Below is my failed attempt in the commented out section at the bottom of the code using droidCanReach()
Here's how often I'm calling the base build structure triggers using the code below and the power management checks above. This is how Nexus sets up a base.
(40 = 4 seconds for those who don't know)
trigger upgradeStructuresTr (every, 40);
trigger buildPowerGeneratorsTr (every, 50 ); // for every 4 derricks we have
trigger buildResearchCentersTr (every, 70 ); // for every 4 derricks we have
trigger buildFactoryTr (every, 120 ); // for every 5 derricks we have
trigger buildDerrickTr (every, 140 );
trigger buildCyborgFactoryTr (every, 150 ); // for every 5 derricks we have
trigger finishStructsTr (every, 210);
trigger buildVTOLFactoryTr (every, 350 );
Code: Select all
/////////////////////////////////////////////////////////////////////
// build a power gen for every 4 derricks. VITAL!
event buildPowerGenerators(buildPowerGeneratorsTr)
{
local INT _count,_bestDist,_newDist,_closestX,_closestY,_truckX,_truckY,_buildGenX,_buildGenY;
local DROID _closestTruck;
local bool _obstacle;
_buildGenX = buildX;
_buildGenY = buildY;
if (!isStructureAvailable(powGen, me))
{
exit;
}
initEnumStruct(FALSE,derrick,me,me); // count = numderricks
structure= enumStruct();
count = 0;
while(structure != NULLOBJECT)
{
count = count + 1;
structure= enumStruct();
}
initEnumStruct(FALSE,gderrick,me,me); // count = num Guarded derricks
structure= enumStruct();
_count = 0;
while(structure != NULLOBJECT)
{
_count = _count + 1;
structure= enumStruct();
}
count = _count + count;
initEnumStruct(FALSE,powGen,me,me); // count2 = numpowgens
structure= enumStruct();
count2 = 0;
while(structure != NULLOBJECT)
{
count2 = count2 + 1;
structure= enumStruct();
}
if( (count2 * 4) < count ) // if we need powergen
{
_closestX = 0;
_closestY = 0;
_bestDist = 99999;
initIterateGroup(buildGroup);
droid = iterateGroup(buildGroup);
while(droid != NULLOBJECT)
{
if (droid.order != DORDER_HELPBUILD and droid.order != DORDER_BUILD and droid.order != DORDER_LINEBUILD)
{
_count = 1;
while(_count < 10) // this loop checks a 10x10 area centered on the base for the truck that is closest to an available location for a power generator
{
// Negative X coordinate checks to the left of the base
// Positive X coordinate checks to the right of the base
// Negative Y coordinate checks below the base
// Positive Y coordinate checks above the base
// Positive X, Positive Y
_buildGenX = baseX + _count;
_buildGenY = baseY + _count;
if (pickDroidStructLocation(droid, powGen, ref _buildGenX, ref _buildGenY, me, 1))
{
_newDist = distBetweenTwoPoints(droid.x, droid.y, _buildGenX, _buildGenY);
if (_newDist < _bestDist and droidCanReach(droid, _buildGenX, _buildGenY)) // this one is closer
{
_bestDist = _newDist;
_closestX = _buildGenX;
_closestY = _buildGenY;
_closestTruck = droid;
}
}
// Positive X, Negative Y
_buildGenY = baseY + (_count * -1);
if(_buildGenY > 0 and _buildGenY < mapHeight)
{
if (pickDroidStructLocation(droid, powGen, ref _buildGenX, ref _buildGenY, me, 1))
{
_newDist = distBetweenTwoPoints(droid.x, droid.y, _buildGenX, _buildGenY);
if (_newDist < _bestDist and droidCanReach(droid, _buildGenX, _buildGenY)) // this one is closer
{
_bestDist = _newDist;
_closestX = _buildGenX;
_closestY = _buildGenY;
_closestTruck = droid;
}
}
}
// Negative X, Negative Y
_buildGenX = baseX + (_count * -1);
if(_buildGenX > 0 and _buildGenX < mapWidth)
{
if (pickDroidStructLocation(droid, powGen, ref _buildGenX, ref _buildGenY, me, 1))
{
_newDist = distBetweenTwoPoints(droid.x, droid.y, _buildGenX, _buildGenY);
if (_newDist < _bestDist and droidCanReach(droid, _buildGenX, _buildGenY)) // this one is closer
{
_bestDist = _newDist;
_closestX = _buildGenX;
_closestY = _buildGenY;
_closestTruck = droid;
}
}
}
// Negative X, Positive Y
_buildGenY = baseY + (_count * -1);
if(_buildGenY > 0 and _buildGenY < mapHeight)
{
if (pickDroidStructLocation(droid, powGen, ref _buildGenX, ref _buildGenY, me, 1))
{
_newDist = distBetweenTwoPoints(droid.x, droid.y, _buildGenX, _buildGenY);
if (_newDist < _bestDist and droidCanReach(droid, _buildGenX, _buildGenY)) // this one is closer
{
_bestDist = _newDist;
_closestX = _buildGenX;
_closestY = _buildGenY;
_closestTruck = droid;
}
}
}
_count++;
}
}
droid = iterateGroup(buildGroup);
}
// this checks the reachability of every tile in between the truck that is closest to the nearest available build location for any obstacles on the path e.g. cliffs
// DOES NOT WORK - The logic is correct but droidCanReach was not intended to be used like this, it's not able to detect cliffs.
// I think cliffs are still reachable via the adjacent tile so droidCanReach is not able to detect cliffs with less than 3 tile width.
// _obstacle = FALSE;
// if(_closestTruck != NULLOBJECT)
// {
// _count = _closestTruck.x; // = x coordinate of proposed constructor droid
// count = _closestTruck.y;
//
// if(_closestX > _count) // _closestX = x coordinate of proposed building location
// {
// while(_count < _closestX)
// {
// _count = _count + 1;
//
// if(_closestY > count)
// {
// while(count < _closestY)
// {
// count = count + 1;
// if(!droidCanReach(_closestTruck, _count, count))
// {
// _obstacle = TRUE;
// count = _closestY;
// _count = _closestX;
// }
// }
// }
// else
// {
// while(count > _closestY)
// {
// count = count - 1;
// if(!droidCanReach(_closestTruck, _count, count))
// {
// _obstacle = TRUE;
// count = _closestY;
// _count = _closestX;
// }
// }
// }
// }
// }
// else
// {
// while(_count > _closestX)
// {
// _count = _count - 1;
//
// if(_closestY > count)
// {
// while(count < _closestY)
// {
// count = count + 1;
// if(!droidCanReach(_closestTruck, _count, count))
// {
// _obstacle = TRUE;
// count = _closestY;
// _count = _closestX;
// }
// }
// }
// else
// {
// while(count > _closestY)
// {
// count = count - 1;
// if(!droidCanReach(_closestTruck, _count, count))
// {
// _obstacle = TRUE;
// count = _closestY;
// _count = _closestX;
// }
// }
// }
// }
// }
// }
// if there are no obstacles then have the truck closest to the nearest available location build a generator
if (pickDroidStructLocation(_closestTruck, powGen, ref _closestX, ref _closestY, me, 1) and _closestTruck != NULLOBJECT and _obstacle != TRUE)
{
orderDroidStatsLoc(_closestTruck, DORDER_BUILD, powGen, _closestX, _closestY);
}
}
}
-------- Created event enemyNearBaseTr to manage defending the base. It beacons the closest enemy droid within 15 tiles of the base and automatically requests help from other Nexus allies. Since I have it triggered every 5 seconds I ended up using this for some other house keeping items that need to be frequently checked e.g. make sure all trucks belong to buildGroup, make sure repair droids in our base are repairing instead of getting hung on DORDER_RTR, prevent droids from accumulating in base while doing nothing.
Code: Select all
event enemyNearBase(enemyNearBaseTr)
{
local DROID _droid,_giveTruck,_enemy;
local int _count,_droidAtHq,_numTruck,_powerTransfer,_myPower,_allyPower,_targetX,_targetY,_findEnemyX,_findEnemyY;
local bool _haveTarget,_haveTruck,_droidInRange;
_count = 0;
while(_count < 10)
{
if(!allianceExistsBetween(me, _count))
{
_droidInRange = FALSE;
if(droidInRange(_count, baseX, baseY, (15 * TILE))) // find enemy droids within 15 tiles below and to the right of our base
{
_findEnemyY = baseY + (15 * TILE);
_findEnemyX = baseX + (15 * TILE);
//Positive X, Positive Y
if(_findEnemyY > 0 and _findEnemyY < (mapHeight * TILE) and _findEnemyX > 0 and _findEnemyX < (mapWidth * TILE))
{
_enemy = droidTargetInArea(_count, me, baseX, baseY, _findEnemyX, _findEnemyY);
if (_enemy != NULLOBJECT)
{
_droidInRange = TRUE;
_targetX = _enemy.x;
_targetY = _enemy.y;
}
}
//Positive X, Negative Y
_findEnemyY = baseY + (15 * TILE * -1); // find enemy droids within 15 tiles above and to the right of our base
if(_findEnemyY > 0 and _findEnemyY < (mapHeight * TILE))
{
_enemy = droidTargetInArea(_count, me, baseX, baseY, _findEnemyX, _findEnemyY);
if (_enemy != NULLOBJECT)
{
_droidInRange = TRUE;
_targetX = _enemy.x;
_targetY = _enemy.y;
}
}
// Negative X, Negative Y
_findEnemyX = baseX + (15 * TILE * -1); // find enemy droids within 15 tiles above and to the left of our base
if(_findEnemyX > 0 and _findEnemyX < (mapWidth * TILE))
{
_enemy = droidTargetInArea(_count, me, baseX, baseY, _findEnemyX, _findEnemyY);
if (_enemy != NULLOBJECT)
{
_droidInRange = TRUE;
_targetX = _enemy.x;
_targetY = _enemy.y;
}
}
// Negative X, Positive Y
_findEnemyY = baseY + (15 * TILE * -1); // find enemy droids within 15 tiles below and to the left of our base
if(_findEnemyY > 0 and _findEnemyY < (mapHeight * TILE))
{
_enemy = droidTargetInArea(_count, me, baseX, baseY, _findEnemyX, _findEnemyY);
if (_enemy != NULLOBJECT)
{
_droidInRange = TRUE;
_targetX = _enemy.x;
_targetY = _enemy.y;
}
}
//setEventTrigger(findEnemy,attackStuffTr);
}
}
if(_droidInRange)
{
count = 0;
while(count < 10)
{
if(allianceExistsBetween(me, count))
{
if(!haveBeacon(me))
{
dropBeacon(getPlayerName(me), count, me, _targetX, _targetY, 0); // if we found an enemy droid within 15 tiles drop a beacon on that droid
}
}
count++;
}
}
_count++;
}
_droidAtHq = 0;
InitEnumDroids(me,me);
_droid = EnumDroid();
while (_droid != NULLOBJECT)
{
if(_droid.order == DORDER_RTR or _droid.order == DORDER_GUARD or _droid.action == DACTION_WAITFORREPAIR and _droid.health > 80) // this prevent droids from accumulating in the base while standing around doing nothing
{
_droidAtHq++;
orderDroid(_droid, DORDER_STOP);
groupAddDroid(attackGroup, _droid);
}
if(_droid.droidType == DROID_CONSTRUCT or _droid.droidType == DROID_CYBORG_CONSTRUCT) // make sure all construction droids belong to buildGroup. If ally gives us a truck, this is how it's added to build group
{
groupAddDroid(buildGroup, _droid);
}
if(_droid.droidType == DROID_REPAIR or _droid.droidType == DROID_CYBORG_REPAIR) // sometimes repair droids in our base don't repair because they're waiting for someone to repair them. Let's check for these circumstances and reset orders if so.
{
if(distBetweenTwoPoints(_droid.x,_droid.x,baseX,baseY) <= (15 * TILE))
{
orderDroidLoc(_droid, DORDER_SCOUT, baseX, baseY);
}
}
_droid = EnumDroid();
}
if(_droidAtHq > 9) // if we have 10 weapon droids at the base doing nothing send them into combat. Should never have more then 10 droids in base with full health
{
setEventTrigger(findEnemy,attackStuffTr);
}
}
------ Disabled difficultyModifierTr since it cheat finishes research, I don't like cheat research. Instead I created my own difficulty function by increasing the veterancy/experience of the Nexus AI droids every few minutes but then I realized there's no way to access the chosen difficulty settings from the skirmish menu. I would only want to increase droid experience levels on hard or insane so I disabled abandoned this. GameLevel is for base???
This logic is a little bit mundane but that's because I was trying to debug why it wasn't working at one point.
Code: Select all
event droidBuiltAssign(droidBuiltTr)
{
// local int _difficulty;
//
// _difficulty = gameTime/3000;
//
// if(_difficulty == 1)
// {
// setDroidKills(droid, 4);
// }
// else if(_difficulty == 2)
// {
// setDroidKills(droid, 8);
// }
// else if(_difficulty == 3)
// {
// setDroidKills(droid, 16);
// }
// else if(_difficulty == 4)
// {
// setDroidKills(droid, 32);
// }
// else if(_difficulty == 5)
// {
// setDroidKills(droid, 64);
// }
// else if(_difficulty == 6)
// {
// setDroidKills(droid, 128);
// }
// else if(_difficulty == 7)
// {
// setDroidKills(droid, 256);
// }
// else if(_difficulty == 8)
// {
// setDroidKills(droid, 512);
// }
------ Improved VTOL behavior to attack all droids in sight on way to their target although the VTOL's still retreat after killing an object despite still having extra ammo. I sunk many hours into VTOL behavior trying to figure out how to simultaneously get VTOL's to attack anything in sight AND pursue another target after killing an object but came to the conclusion it's not possible unless there is a way to access VTOL ammo levels. The problem is that
VTOL's go to DACTION_MOVETOREARMPOINT after 1. destroying an object and 2. when they're out of ammo therefore there is no way to distinguish between the two states. The only solution is to have the VTOL's attack despite DACTION_MOVETOREARMPOINT but then the VTOL's will never rearm. I basically set
setDroidSecondary(droid, DSO_PATROL, DSS_PATROL_SET); when a VTOL is produced, when a VTOL arrives at their destination and when a VTOL attacks to achieve the relentless attack behavior. I use scout to x/y coordinates as opposed to attack an object.
------ Added logic to find oils (not to be confused with derricks) with enemy droids in range. It has superior performance over closest oil in beginning of t1 no base rush games. I can improve this by finding the closest oil out of this subset too. I also pursue MG Guard Tower if an oil is found with enemy droid in range. All of this emerged out of my attempts to beat Bonecrusher in low oil rush games :).
Code: Select all
_count = 0;
while(_count < MAX_PLAYERS)
{
if(!allianceExistsBetween(me, _count))
{
_numEnemy++;
initGetFeature(oilRes, -1, me);
_oil = getFeatureB(me);
while (_oil != NULLOBJECT)
{
_droidInRange = FALSE;
if(droidInRange(_count, _oil.x, _oil.y, (8 * TILE)))
{
_enemyOil = _oil;
}
_oil = getFeatureB(me);
}
}
_count++;
}
------ finishStructs() was only being applied to factories. Fixed this to include research centers and power generators. It was an easy copy/paste from the factory code and just replace factory with appropriate structure.
------ on event droidBuiltAssign I put setDroidSecondary(droid, DSO_REPAIR_LEVEL, DSS_REPLEV_LOW); to set all droids to repair at medium damage.
------ on structBuilt event have the trucks build a fortification if the structure was a derrick and there is an enemy droid within 5 tiles. Similar to build fortification if we find an enemy derrick.
Used to protect oils in T1 no base...
Code: Select all
if(structure.stattype == REF_RESOURCE_EXTRACTOR)
{
_count = 0;
while(_count < MAX_PLAYERS)
{
if(!allianceExistsBetween(me, _count))
{
if(droidInRange(_count, structure.x, structure.y, (5 * TILE)))
{
_bestDist = 99999;
initIterateGroup(buildGroup);
droid = iterateGroup(buildGroup);
while(droid != NULLOBJECT)
{
_newDist = distBetweenTwoPoints(droid.x, droid.y, structure.x, structure.y);
if (_newDist < _bestDist) // this one is closer
{
_closestTruck = droid;
_closestX = droid.x;
_closestY = droid.y;
}
droid = iterateGroup(buildGroup);
}
if(_closestTruck != NULLOBJECT)
{
if (pickDroidStructLocation(_closestTruck, gTower, ref _closestX, ref _closestY, me, 1))
{
orderDroidStatsLoc(_closestTruck, DORDER_BUILD, gTower, _closestX, _closestY);
}
}
}
}
_count++;
}
------ check if allies don't have a truck and if we have at least two then give one away.
Code: Select all
_count = 0;
while(_count < 10)
{
if(allianceExistsBetween(me, _count))
{
_haveTruck = FALSE;
InitEnumDroids(_count,_count);
_droid = EnumDroid();
while (_droid != NULLOBJECT)
{
if(_droid.droidType == DROID_CONSTRUCT or _droid.droidType == DROID_CYBORG_CONSTRUCT) // check to see if any of our allies don't have a truck
{
_haveTruck = TRUE;
}
_droid = EnumDroid();
}
if(!_haveTruck)
{
_numTruck = 0;
InitEnumDroids(me,me);
_droid = EnumDroid();
while (_droid != NULLOBJECT)
{
if(_droid.droidType == DROID_CONSTRUCT or _droid.droidType == DROID_CYBORG_CONSTRUCT) // check to see if we have any trucks to give
{
_numTruck++;
_giveTruck = _droid;
}
_droid = EnumDroid();
}
if(_numTruck > 2) // if we have at least two trucks then give one to ally that doesn't
{
takeOverSingleDroid(_giveTruck, _count);
}
}
}
_count++;
}
------ pass 30% of power to ally if we have 2,000 more power then them. Doesn't work. Seems addPower has been disabled in mp??
I can't get it to work at all, even in initialisedEvent although it does complain about invalid ally when I swapped the POWER and ALLY parameters so it's doing at least something...
Code: Select all
// Transfer 30% of power to ally if we have 2000 more power then ally
// This doesn't work because addPower() is only available in campaign - or at least it doesn't work anywhere
_powerTransfer = 0;
_myPower = playerPower(me);
_allyPower = playerPower(_count);
_powerTransfer = _myPower - _allyPower;
if(_powerTransfer > 2000)
{
_powerTransfer = (int)(((float)playerPower(me)) * .30);
addPower(_powerTransfer, _count);
_powerTransfer = _powerTransfer * -1;
addPower(_powerTransfer,me);
}
------ Send all Nexus weapon droids to ally beacons. This way humans can easily play/use Nexus AI just by beaconing where you want Nexus to go.
Nexus also beacons any enemy droids within 15 tiles of base every 10 seconds so if you attack this AI, all ally Nexus AI's will come to help. This way Nexus AI's can play as a team and help each other.
It's just a matter of adding a little snippet to beaconEv()
Code: Select all
if(allianceExistsBetween(me, sender))
{
orderGroupLoc(attackGroup, DORDER_SCOUT, beaconX[sender], beaconY[sender]);
}
------ announce research objectives to allies at 5 second mark. It sounded like a good idea but the message scrolls so fast I hardly even notice. I think I'll abandon this too
Code: Select all
event announceResearch(inactive)
{
if(curTech == branchFlameVtolLaser)
{
messagePlayer(ALL_ALLIES, "I'm researching Flamers then VTOL and lasers if the game is long.", MAX_PROBABILITY);
}
else if(curTech == branchCannonMGMortar)
{
messagePlayer(ALL_ALLIES, "I'm researching Cannons, MG's and mortars. Grenadiers for cyborgs.", MAX_PROBABILITY);
}
else if(curTech == branchRocketMGMortar)
{
messagePlayer(ALL_ALLIES, "I'm researching Rocket MG's and mortars. Grenadiers for cyborgs.", MAX_PROBABILITY);
}
else if(curTech == branchRocket)
{
messagePlayer(ALL_ALLIES, "I think I'll use rockets + MG", MAX_PROBABILITY);
}
else if(curTech == branchMG)
{
messagePlayer(ALL_ALLIES, "I'm researching all MG's", MAX_PROBABILITY);
}
else if(curTech == branchFlamer)
{
messagePlayer(ALL_ALLIES, "I'm going all flamers", MAX_PROBABILITY);
}
else if(curTech == branchCannon)
{
messagePlayer(ALL_ALLIES, "I'm using cannons this game", MAX_PROBABILITY);
}
else if(curTech == branchArtillery)
{
messagePlayer(ALL_ALLIES, "I'm researching Mortars and Artillery Research", MAX_PROBABILITY);
}
setEventTrigger(announceResearch, inactive);
}
-------- added one more profile - pure MG's. Now all of the weapon lines have a dedicate profile so Nexus can play with all weapons
------ Right now I'm working on code to build an "outpost"(fortifications, repair centers, artillery) at some % (say 30%) the distance between baseX/baseY and closest enemy (enemy HQ). I have it partially working but only for players on the bottom of the map... players on top of the map have problems selecting the Y coordinate. It's still a work in progress but this has other applications too such as building repair centers in between base and enemy instead of random place in base
Code: Select all
_closestX = 0;
_closestY = 0;
_bestDist = 99999;
_count = 0;
while(_count < MAX_PLAYERS)
{
if(!allianceExistsBetween(me,_count))
{
structure = getStructure(playerHQ, _count);
if(structure != NULLOBJECT)
{
_newDist = distBetweenTwoPoints(baseX, baseY, structure.x, structure.y);
if (_newDist < _bestDist and droidCanReach(droid, structure.x, structure.y)) // this one is closer
{
_bestDist = _newDist;
_closestX = structure.x;
_closestY = structure.y;
}
}
}
_count++;
}
buildX = 0;
buildY = 0;
if(_closestX > baseX and _closestX != 0)
{
buildX = baseX + (int)((float)(_closestX - baseX) * .30); // this means enemy is to the left of us
}
else
{
buildX = baseX - (int)((float)(baseX - _closestX) * .30); // this means enemy is the right of us
}
if(_closestY > baseY and _closestY != 0)
{
buildY = baseY + (int)((float)(_closestY - baseY) * .30); // this means enemy is below us
}
else
{
buildY = baseY - (int)((float)(baseY - _closestY) * .30); // this means enemy is above us
}
if(buildY > 0 and buildY < mapHeight and buildX > 0 and buildX < mapWidth)
{
//if (pickDroidStructLocation(droid, defStructs[count], ref buildX, ref buildY, me, -1))
boolResult = pickStructLocation(sensorTower, ref buildX, ref buildY,me); // pick spot.
if(boolResult == TRUE)
{
// find unit
initIterateGroup(buildGroup);
droid = iterateGroup(buildGroup);
while(droid != NULLOBJECT)
{
if ((droid.order == DORDER_NONE or droid.order == DORDER_RTB) and droidCanReach(droid, buildX, buildY))
{
orderDroidStatsLoc(droid, DORDER_BUILD, sensorTower, buildX, buildY);
droid = NULLOBJECT;
}
droid = iterateGroup(buildGroup);
}
}
}
I've only been working with scripts in warzone for 3 months. Prior to this I made some speculative comments on making an AI that I now realize may not have made sense. I thought making an AI in Warzone was like building a predictive model of best research, build order and weapon choice based on a set of input variables e.g. game and map settings but it's not like that at all :oops:
Come to find out, this predictive model was only a matter of ordering a couple of arrays... I had no idea how WZ AI worked but I do now...
Attachments
EB.wz
(101.94 KiB) Downloaded 28 times
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 20 May 2017, 06:32
I forgot I still need to update the research messages to reflect the new stats and maybe some of the .po files too.
Now that I think of it, that's probably the most appropriate way to communicate the stats. I just never ever look at that screen because it's purely cosmetic to a veteran player playing an mp game. I forgot all about it. I'll get to it sometime in the next month, just wanted to say it's on to-do list.
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby Admin010 » 22 May 2017, 06:38
thanks
Admin010
New user
Posts: 1
Joined: 22 May 2017, 06:36
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 25 Jun 2017, 18:18
Okay I finally finished the research messages, it took a lot longer than I thought. I added 191 new messages so that all mp research items have a unique message on the intelligence screen displaying the new stats.
I also updated the hitpoint changes to reflect the changes here https://github.com/Warzone2100/warzone2 ... ee2d6f4a8a
I didn't get around to implementing the new commander/brain upgrades. I start a new software development job tomorrow so I won't have any time to do WZ stuff for awhile, maybe forever.
On a side note, I re-enabled the idea of Nexus AI passing a truck to ally if they don't have one. The only reason I disabled it before was because takeOverSingleDroid(); logs a non-fatal error in the log file stating "Script interpreter is already running" but it's harmless.
The below attachment will not work on 3.2.3 because it's only compatible with the hitpoint changes that haven't been deployed yet.
Attachments
EB.wz
Latest/Final Version.
(112.35 KiB) Downloaded 5 times
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 27 Jun 2017, 01:39
whoops, I forgot to uncheck the designable flag on the structure instance of the mortar weapons. (They should not be designable on vehicles).
Image
Also, the stats editor is attached below for the stats in the post above. It's really only possible to analyze the stat changes from the view of the editor because it puts comparable/similar stats into perspective from a single view. From that viewpoint it's easy to see how things are "balanced".
To test EB, just do autogame on and watch Nexus play. 5v5 maps are the best.
I'm going to officially retire on development here for awhile. I started a new software development job today and definitely confirmed I'm going to be busy. I'll come back when I learn to properly use Git on WZ instead of using this thread as my changelog lol. Just j/k.
BTW, Here is my Linkedin profile https://www.linkedin.com/in/jason-breijak-919b0210b/
Attachments
WZ Stats Editor.zip
(1.54 MiB) Downloaded 5 times
weapons.json
Removed "1" flag from 5 mortar weapons
(164.31 KiB) Downloaded 6 times
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Re: Enhanced Balance Mod for 3.x
Postby Legendary » 27 Jun 2017, 16:23
That's very interesting! I have been in deep depresion because of NoQ lack of development on NullBot. Now EB... Hm. Could you please provide some roadmap on what you plan to implement? I would gladly help you to test some games and provide feedback.
Legendary
Greenhorn
Posts: 8
Joined: 04 May 2016, 19:59
Re: Enhanced Balance Mod for 3.x
Postby NoQ » 27 Jun 2017, 17:03
Legendary wrote:I have been in deep depresion because of NoQ lack of development on NullBot.
+1.
User avatar
NoQ
Special
Special
Posts: 6048
Joined: 24 Dec 2009, 11:35
Location: /var/zone
Re: Enhanced Balance Mod for 3.x
Postby MIH-XTC » 28 Jun 2017, 00:44
Legendary wrote:That's very interesting! I have been in deep depresion because of NoQ lack of development on NullBot. Now EB... Hm. Could you please provide some roadmap on what you plan to implement? I would gladly help you to test some games and provide feedback.
Well, I've given up on trying to explain what all I changed because it's too hard to classify/categorize/group the changes together and then explain the implications. The mod is stable I know that so there's no need to test that aspect. Testing is just a matter of whether you personally like it or not. I just created a short video a few minutes ago to give an idea of how I go about modding in the stats editor and testing the changes.
https://youtu.be/cIXpL2ZPiG4
If you want to try the mod for yourself then use the attachment in this post. The attachment in the post above is only compatible with changes in future releases.
BTW, in the video I show the log file at 15:20 that has some errors but none of which are due to the mod (Except for script interpreter is already running). The rest of the errors are inherit to the map.
Attachments
EB.wz
Latest Compatible with 3.2.3
(112.3 KiB) Downloaded 11 times
MIH-XTC
Trained
Trained
Posts: 156
Joined: 31 Jan 2014, 07:06
Previous
Return to Addon discussions
|
__label__pos
| 0.721902 |
Strengthening the foundations of trust in the digital age
Hello, tomorrow.
The speed of technological change requires new thinking about how institutions and businesses deliver on trust.
There appears to be an epidemic of distrust that is eating away at the fabric of society. People have lost faith in institutions’ ability to provide reliable public services and in businesses to provide the jobs that put food on the table and allow workers to lead a dignified life. According to the Edelman Trust Barometer, which measures the levels of trust globally, for the past decade, less than half of the world’s population trusts government, business, or even civil society. The surge in inequality, despite economic gains for millions, is one important factor that has left people questioning whether their government or employer has their best interests at heart.
How businesses can deliver on trust in the digital age
The speed of technological change and the unprecedented volume of information available — anytime, anywhere, via smart devices — is exacerbating this phenomenon. Today, information that weakens our faith in society spreads faster than responses to it. This trend will only grow as 5G mobile networks increase the speed and expand the breadth of connectivity.
Few industries are exempt from the scandals that lead to distrust, be they mining and environmental disasters or the manipulation of benchmark interest rates and air pollution tests. People witness the sometimes devastating results of unethical acts perpetrated by institutions and people that were once synonymous with quality and integrity. People are also discovering that the digital platforms and tools that offer the benefits of convenience, connectivity, and greater transparency also present critical problems that were not envisaged, such as data privacy.
To maintain a stable society, it is crucial that institutions win back trust. Politicians and business leaders must make a concerted effort to understand the causes of the current high levels of mistrust so that they can take the appropriate actions to mitigate the effects. In an overarching way, four key factors directly affect trust in today’s digitally interconnected world:
1. Speed. Technology changes so rapidly that it can disadvantage those who can’t keep up, which leads to greater inequality and uncertainty. One simple example is in financial markets: Access to instantaneous investment information favors those with a technology edge — such as high-frequency traders — on what should be a level playing field.
2. Volume. The amount of data and its complexity are confounding ordinary people along with business and political leaders. The uninformed questioning of Facebook founder Mark Zuckerberg by the U.S. Congress and the European Parliament showed how far behind the curve our politicians are in understanding the technology that underlies some of today’s most successful and influential businesses. This reduces the public’s confidence in governments’ ability to safeguard citizens.
3. Unintended consequences. The speed and volume of technology advancement mean people can’t know the effect of new tools until after they have adopted them. For example, researchers are now beginning to assess the impact of smartphones on brain functions. What else might be affected by this essential device?
4. The generation gap. Children have always adapted faster than their elders to new technology. Today, young adults’ deep familiarity with digital tools and platforms gives them advantages in the workplace as technological change makes some tasks redundant.
Until now, government and business have been slow to react to the implications of these changes. They are not, for example, addressing the monumental and costly task of upskilling workers — helping them acquire the skills they need to contribute in a digital world — to avoid losing a generation of employees just as people’s working life expectancy is on the rise.
But with all this change, people undoubtedly face a conundrum. They want predictability in their lives. They want institutions such as the police, tax authorities, and regulators to be stable, and too much technology, introduced too quickly, contributes to a sense of unease and a lack of trust because people can’t keep up. This explains, in part, the rise of populism as people look for simple answers to complex issues.
The first step to rebuilding trust is to be aware that change and complexity are constant and everyone — customers, regulators, employees, and the general public — are potential stakeholders. Businesses, like governments, now operate in a technologically enhanced fishbowl.
The first step to rebuilding trust is to be aware that change and complexity are constant and that everyone – customers, regulators, employees, and the general public – are potential stakeholders.
In all industries, leaders themselves need to evaluate their own technological understanding. The cycles of change are now so short that the time available to adjust and adapt is limited. Leaders will have to make real-time decisions, sometimes without all the facts. They should be careful to avoid the trap of believing they have mastered the problem when instead they have missed something that will make their solution obsolete. They will have to explain what they are doing: how they are keeping personal data safe, how they are working to prevent discrimination in their use of algorithms, and how they are ensuring quality control across the tech supply chain. Governments must play their part too: Regulations need to be fluid, easily amended, and relevant.
Making a business or institution trustworthy is not a onetime initiative that a mission statement can fix. It is something that has to be intentional, embedded, communicated, and continuous to instill a sense that society’s institutions and economic drivers — businesses — can be trusted to deliver for the good of their wider community. This is harder in an age of accelerating technological change, but being aware of the four factors that can undermine trust, communicating where your business sits on the trust curve, and articulating what you are going to do to address the challenge are important first steps.
Author Profiles:
• Stephanie Hyde is a partner with PwC UK. She is the global clients and industries leader at PricewaterhouseCoopers International Limited.
• Blair Sheppard is the global leader of strategy and leadership for the PwC network of companies. He is also professor emeritus and dean emeritus of Duke University’s Fuqua School of Business. He is based in Durham, N.C.
The business insights you need to succeed. Get s+b’s best ideas delivered to your inbox twice a week.
Get the strategy+business newsletter delivered to your inbox
|
__label__pos
| 0.569341 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.