content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
Provided by: libmotif-dev_2.3.8-2build1_amd64 bug
NAME
TransientShell — The TransientShell widget class "TransientShell" "widget class"
"TransientShell"
SYNOPSIS
#include <Xm/Xm.h>
#include <X11/Shell.h>
DESCRIPTION
TransientShell is used for shell windows that can be manipulated by the window manager,
but are not allowed to be iconified separately. For example, DialogBoxes make no sense
without their associated application. They are iconified by the window manager only if
the main application shell is iconified.
Classes
TransientShell inherits behavior and resources from Core, Composite, Shell, WMShell, and
VendorShell.
The class pointer is transientShellWidgetClass.
The class name is TransientShell.
New Resources
The following table defines a set of widget resources used by the programmer to specify
data. The programmer can also set the resource values for the inherited classes to set
attributes for this widget. To reference a resource by name or by class in a .Xdefaults
file, remove the XmN or XmC prefix and use the remaining letters. To specify one of the
defined values for a resource in a .Xdefaults file, remove the Xm prefix and use the
remaining letters (in either lowercase or uppercase, but include any underscores between
words). The codes in the access column indicate if the given resource can be set at
creation time (C), set by using XtSetValues (S), retrieved by using XtGetValues (G), or is
not applicable (N/A).
In addition to these new resources, TransientShell overrides the XmNsaveUnder resource in
Shell and the XmNtransient resource in WMShell.
┌──────────────────────────────────────────────────────────────┐
Binary file (standard input) matches
|
__label__pos
| 0.853045 |
wrong result from CAS
Rune Klarskov Jensen shared this problem 5 years ago
Not a Problem
P:=(1, 25)
f(x):=(10 * x^(4)) + 1 / x
BeregnODE[f, P]
gives me:
y = (2 * x^(5)) + (1 / 5 * log(x^(5))) + 23
but should give me :
y = (2 * x^(5)) + ln(x) + 23
Comments (4)
photo
1
Aren't they the same?
photo
1
Yes it is the same.
I had a laugh when I saw it, I was blinded there :)
Thank you
photo
photo
1
then simplify[]
photo
1
Nice advice
Thank you
photo
© 2021 International GeoGebra Institute
|
__label__pos
| 0.854258 |
DescendantToken
Since Checkstyle 3.2
Description
Checks for restricted tokens beneath other tokens.
WARNING: This is a very powerful and flexible check, but, at the same time, it is low-level and very implementation-dependent because its results depend on the grammar we use to build abstract syntax trees. Thus, we recommend using other checks when they provide the desired functionality. Essentially, this check just works on the level of an abstract syntax tree and knows nothing about language structures.
Properties
name description type default value since
limitedTokens Specify set of tokens with limited occurrences as descendants. subset of tokens TokenTypes {} 3.2
minimumDepth Specify the minimum depth for descendant counts. int 0 3.2
maximumDepth Specify the maximum depth for descendant counts. int 2147483647 3.2
minimumNumber Specify a minimum count for descendants. int 0 3.2
maximumNumber Specify a maximum count for descendants. int 2147483647 3.2
sumTokenCounts Control whether the number of tokens found should be calculated from the sum of the individual token counts. boolean false 5.0
minimumMessage Define the violation message when the minimum count is not reached. String null 3.2
maximumMessage Define the violation message when the maximum count is exceeded. String null 3.2
tokens tokens to check set of any supported tokens empty 3.2
Examples
To configure the check to produce a violation on a switch statement with no default case:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="LITERAL_SWITCH"/>
<property name="maximumDepth" value="2"/>
<property name="limitedTokens" value="LITERAL_DEFAULT"/>
<property name="minimumNumber" value="1"/>
</module>
</module>
</module>
Example:
class Test {
public static void main(String[] args) {
int x = 1;
switch (x) { // ok
case 1:
System.out.println("hi");
break;
default:
System.out.println("Default");
break;
}
int y = 1;
switch (y) { // violation
case 1:
System.out.println("hi");
break;
}
}
}
To configure the check to produce a violation on a switch with too many cases:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="LITERAL_SWITCH"/>
<property name="limitedTokens" value="LITERAL_CASE"/>
<property name="maximumDepth" value="2"/>
<property name="maximumNumber" value="1"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
int x = 1;
switch (x) { // ok
case 1:
// Some code
break;
default:
// Some code
break;
}
switch (x) { // violation
case 1:
// Some code
break;
case 2:
// Some code
break;
default:
// Some code
break;
}
}
}
To configure the check to produce a violation on a switch that is nested in another switch:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="LITERAL_SWITCH"/>
<property name="limitedTokens" value="LITERAL_SWITCH"/>
<property name="maximumNumber" value="0"/>
<property name="minimumDepth" value="1"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
int x = 1;
int y = 2;
switch (x) { // ok
case 1:
System.out.println("xyz");
break;
}
switch (y) { // violation
case 1:
switch (y) {
case 2:
System.out.println("xyz");
break;
}
break;
}
}
}
To configure the check to produce a violation on a condition in for which performs no check:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="FOR_CONDITION"/>
<property name="limitedTokens" value="EXPR"/>
<property name="minimumNumber" value="1"/>
</module>
</module>
</module>
Example:
class Test {
public static void main(String[] args) {
for (int i = 0; i != 10; i++) { // ok
System.out.println(i);
}
int k = 0;
for (; ; ) { // violation
System.out.println(k);
}
}
}
To configure the check to produce a violation on an initializer in for performs no setup (where a while statement could be used instead):
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="FOR_INIT"/>
<property name="limitedTokens" value="EXPR"/>
<property name="minimumNumber" value="1"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
int[] array = new int[] {1, 2, 3, 4, 5};
for (int i = 0; i != array.length; i++) { // ok
System.out.println(i);
}
int j = 0;
for (; j != array.length;) { // violation
System.out.println(j);
j++;
}
}
}
To configure the check to produce a violation on a return statement from within a catch or finally block:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="LITERAL_FINALLY,LITERAL_CATCH"/>
<property name="limitedTokens" value="LITERAL_RETURN"/>
<property name="maximumNumber" value="0"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
try {
// Some code
} catch (Exception e) {
System.out.println("xyz");
return; // violation
} finally {
System.out.println("xyz");
}
}
}
To configure the check to produce a violation on a try statement within a catch or finally block:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="LITERAL_CATCH,LITERAL_FINALLY"/>
<property name="limitedTokens" value="LITERAL_TRY"/>
<property name="maximumNumber" value="0"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
try {
// Some code
} catch (Exception e) { // ok
System.out.println("xyz");
return;
} finally { // ok
System.out.println("xyz");
}
try {
// Some code
} catch (Exception e) {
try { // violation
// Some code
} catch (Exception ex) {
// handle exception
}
} finally {
try { // violation
// Some code
} catch (Exception e) {
// handle exception
}
}
}
}
To configure the check to produce a violation on a method with too many local variables:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="METHOD_DEF"/>
<property name="limitedTokens" value="VARIABLE_DEF"/>
<property name="maximumDepth" value="2"/>
<property name="maximumNumber" value="1"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() { // ok
int var1 = 1;
}
public void boo() { // violation
int var1 = 1;
int var2 = 2;
}
}
To configure the check to produce a violation on a method with too many returns:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="METHOD_DEF"/>
<property name="limitedTokens" value="LITERAL_RETURN"/>
<property name="maximumNumber" value="2"/>
</module>
</module>
</module>
Example:
class Test {
public int foo(int x) { // ok
if (x == -1) {
return -1;
} else if (x == 0) {
return 0;
}
}
public int boo(int x) { // violation
if (x == -1) {
return -1;
} else if (x == 0) {
return 0;
} else {
return x;
}
}
}
To configure the check to produce a violation on a method which throws too many exceptions:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="LITERAL_THROWS"/>
<property name="limitedTokens" value="IDENT"/>
<property name="maximumNumber" value="1"/>
</module>
</module>
</module>
Example:
class Foo {
public void foo() throws ArithmeticException { // ok
// ...
}
}
class Boo {
public void boo() throws ArithmeticException, ArithmeticException { // violation
// ...
}
}
To configure the check to produce a violation on a method with too many expressions:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="METHOD_DEF"/>
<property name="limitedTokens" value="EXPR"/>
<property name="maximumNumber" value="2"/>
</module>
</module>
</module>
Example:
class Foo {
public void foo() { // ok
int x = 1;
int z = x + 2;
}
}
class Boo {
public void boo() { // violation
int x = 1;
int y = 2;
int z = x + y;
}
}
To configure the check to produce a violation on an empty statement:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="EMPTY_STAT"/>
<property name="limitedTokens" value="EMPTY_STAT"/>
<property name="maximumNumber" value="0"/>
<property name="maximumDepth" value="0"/>
<property name="maximumMessage"
value="Empty statement is not allowed."/>
</module>
</module>
</module>
Example:
class Test {
public void foo() { // ok
System.out.println("Hello");
}
public void boo() {
; // violation
}
}
To configure the check to produce a violation on a class or interface with too many fields:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/>
<property name="limitedTokens" value="VARIABLE_DEF"/>
<property name="maximumDepth" value="2"/>
<property name="maximumNumber" value="1"/>
</module>
</module>
</module>
Example:
class A { // ok
private int field1;
// Some code
}
class B { // violation
private int field1;
private int field2;
// Some code
}
interface C { // ok
int FIELD_1 = 1;
}
interface D { // violation
int FIELD_1 = 1;
int FIELD_2 = 2;
}
To configure the check to produce a violation on comparing this with null:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="EQUAL,NOT_EQUAL"/>
<property name="limitedTokens" value="LITERAL_THIS,LITERAL_NULL"/>
<property name="maximumNumber" value="1"/>
<property name="maximumDepth" value="1"/>
<property name="sumTokenCounts" value="true"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
if (this == null) { // violation
System.out.println("xyz");
}
if (this != null) { // violation
System.out.println("xyz");
}
Object obj = new Object();
if (obj == null) { // ok
System.out.println("xyz");
}
if (obj != null) { // ok
System.out.println("xyz");
}
}
}
To configure the check to produce a violation on a String literal equality check:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="EQUAL,NOT_EQUAL"/>
<property name="limitedTokens" value="STRING_LITERAL"/>
<property name="maximumNumber" value="0"/>
<property name="maximumDepth" value="1"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
String str = "abc";
if (str.equals("abc")) { // ok
System.out.println("equal.");
}
if (str == "abc") { // violation
System.out.println("equal.");
}
}
}
To configure the check to produce a violation on an assert statement that may have side effects:
<module name="Checker">
<module name="TreeWalker">
<module name="DescendantToken">
<property name="tokens" value="LITERAL_ASSERT"/>
<property name="limitedTokens" value="ASSIGN,DEC,INC,POST_DEC,
POST_INC,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,DIV_ASSIGN,MOD_ASSIGN,
BSR_ASSIGN,SR_ASSIGN,SL_ASSIGN,BAND_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN,
METHOD_CALL"/>
<property name="maximumNumber" value="0"/>
</module>
</module>
</module>
Example:
class Test {
public void foo() {
int a = 5;
assert a++ == 0 : "is not"; // violation
System.out.println(a);
assert a == 0 : "is not"; // ok
}
}
Example of Usage
Violation Messages
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Package
com.puppycrawl.tools.checkstyle.checks
Parent Module
TreeWalker
|
__label__pos
| 0.999962 |
Java Programing laungage
Core Java Tutorial
Introduction of Core Java
How To Install JDk and Set of Path
Syntax of java Program
Difference between Java and C/C++
Advantage and Disadvantage of Java
What is Java
Why Java is not Pure Object Oriented Language
Java has Following Features/Characteristics
Limitation of Java Language and Java Internet
Common Misconception about Java
Simple Program of Java
Integrated Development Environment in java
Compile and Run Java Program
Applet and Comments in Java
Tokens in Java
Keywords in Java
Identifier and Variables in Java
Literals/Constants
Data Type in Java
Assignments and Initialization in Java
Operators in Java
Rule of Precedence in Java
Operator on Integer and Separators in Java Programming
Java Control Flow of Statements
If and If-else Selection Statement
Nested If-else and If-else-If Selection Statement
switch case and conditional operator Selection Statement
for and while Loop
do..while and for each Loop
break and labeled break statement
continue and labeled continue statement
return Statement and exit() Method
Escape Sequence for Special Characters and Unicode Code
Constants and Block or Scope
Statement in Java
Conversions between Numeric Types in Java
Import Statement in Java
User Input in Java using Scanner Class
User Input in Java using Console Class
Array in Java
One Dimensional Array
Two Dimensional Array
Two Dimensional Array Program
Command Line Argument in Java
String args Types in Java
Uneven/Jagged array in java
Math Class Function and Constant
Math Class all Function used in a program
Enumerated Types in Java
Object Oriented Programming v/s Procedural Programming
Object Oriented Programming Concepts in Java
Introduction to Class,Object and Method in Java
Class Declaration in Java
Class & Objects in java
Encapsulation in Java
Modifiers/Visibility for a Class or Interrface or member of a Class
Polymorphism in Java
Runtime polymorphism (dynamic binding or method overriding)
adplus-dvertising
Nested If-else and If-else-If Selection Statement
Previous Home Next
It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.
syntax :
if(condition)
{
if(condition)
{
true statement;
}
else
{
false statement;
}
}
else
{
if(condition)
{
true statement;
}
else
{
false statement;
}
}
Example :
class Max3
{
public static void main(String args[])
{
int a,b,c,max;
a=3;
b=8;
c=4;
if(a>b)
{
if(a>c)
{
max=a;
}
else
{
max=c;
}
}
else
{
if(b>c)
{
max=b;
}
else
{
max=c;
}
}
System.out.print("Max is "+max);
}
}
output :
Max is 8
If-else-If Selection Statement
An if statement can be followed by an optional else if...else statement,
syntax :
if(condition 1)
{
//Executes when the condition 1 is true
}
else if(condition 2)
{
//Executes when the condition 2 is true
}
else if(condition 3)
{
//Executes when the condition 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example :
class Day
{
public static void main(String args[])
{
int n;
n=5;
if(n==1)
{
System.out.print("sunday");
}
else if(n==2)
{
System.out.print("Monday");
}
else if(n==3)
{
System.out.print("tuesday");
}
else if(n==4)
{
System.out.print("Wednesday");
}
else
{
System.out.print("Invalid !");
}
}
}
output :
Invalid !
Previous Home Next
|
__label__pos
| 0.698417 |
The Blog
rkhunter, a better e-mail integration / alert
13 Mag 15
We all know that RootKit Hunter is a must have for paranoids and responsible SysOps even if it lacks on two things IMHO:
1. RootKit Updates
2. E-Mail alerts
In this post you can find an improved version for the 2nd point 😉
RootKit Hunter E-Mail Alerts
rkhunter already have a MAIL-ON-WARNING configuration on /etc/rkhunter.conf
1. # Email a message to this address if a warning is found when the system is
2. # being checked. Multiple addresses may be specified simply be separating
3. # them with a space. To disable the option, simply set it to the null string
4. # or comment it out.
5. #
6. # The option may be specified more than once.
7. #
8. # The default value is the null string.
9. #
10. # Also see the MAIL_CMD option.
11. #
12. #MAIL-ON-WARNING="[email protected]"
13.
14. #
15. # This option specifies the mail command to use if MAIL-ON-WARNING is set.
16. #
17. # NOTE: Double quotes are not required around the command, but are required
18. # around the subject line if it contains spaces.
19. #
20. # The default is to use the ‘mail’ command, with a subject line
21. # of ‘[rkhunter] Warnings found for ${HOST_NAME}’.
22. #
23. #MAIL_CMD=mail -s "[rkhunter] Warnings found for ${HOST_NAME}"
# Email a message to this address if a warning is found when the system is
# being checked. Multiple addresses may be specified simply be separating
# them with a space. To disable the option, simply set it to the null string
# or comment it out.
#
# The option may be specified more than once.
#
# The default value is the null string.
#
# Also see the MAIL_CMD option.
#
#MAIL-ON-WARNING="[email protected]"
#
# This option specifies the mail command to use if MAIL-ON-WARNING is set.
#
# NOTE: Double quotes are not required around the command, but are required
# around the subject line if it contains spaces.
#
# The default is to use the 'mail' command, with a subject line
# of '[rkhunter] Warnings found for ${HOST_NAME}'.
#
#MAIL_CMD=mail -s "[rkhunter] Warnings found for ${HOST_NAME}"
As you can see I commented the lines #12 and #23, this because the e-mail message is not configurable (except the mail object).
rkhunter-email
So basically I wanted to receive inside the email body the content of the RootKit Hunter report, if any.
I LOVE BASH SCRIPTING <3
1. #!/bin/bash
2.
3. #/usr/bin/rkhunter –versioncheck –nocolors
4.
5. /usr/bin/rkhunter –update –nocolors
6.
7. OUTPUT=`/usr/bin/rkhunter –cronjob –report-warnings-only –nocolors`
8.
9. if [ "$OUTPUT" != "" ]
10. then
11. echo $OUTPUT | mail -s "WARNING!!! – rkhunter report" [email protected]
12. else
13. echo ‘EVERYTHING IS FINE 🙂 HOPEFULLY’ | mail -s "OK 🙂 – rkhunter report" [email protected]
14. fi
#!/bin/bash
#/usr/bin/rkhunter --versioncheck --nocolors
/usr/bin/rkhunter --update --nocolors
OUTPUT=`/usr/bin/rkhunter --cronjob --report-warnings-only --nocolors`
if [ "$OUTPUT" != "" ]
then
echo $OUTPUT | mail -s "WARNING!!! - rkhunter report" [email protected]
else
echo 'EVERYTHING IS FINE 🙂 HOPEFULLY' | mail -s "OK 🙂 - rkhunter report" [email protected]
fi
Installing the above bash script in the crontab allows you to receive two types of output:
1. an “EVERYTHING IS FINE 🙂 HOPEFULLY” mail – if there are no warnings (god bless rkhunter –report-warnings-only option)
2. a “WARNING!!!” message containing in the body mail only the warnings output of rkhunter
Hope this short post helped you somehow 😉
S
Comments
|
__label__pos
| 0.536169 |
Addressing TM Enqueue Contention – What is Wrong with this Quote?
19 06 2011
June 19, 2011
Currently, the most viewed article in the past 90 days on this blog demonstrates a deadlock situation that is present in Oracle Database 11.1.0.6 and above that is not present in Oracle Database 10.2.0.1 through 10.2.0.5 (someone else might be able to check the earlier releases). This particular deadlock was the result of a missing foreign key index, which resulted in TM enqueues and an eventual deadlock when the first of three sessions issued a COMMIT. From this bit of information, hopefully it is clear that foreign key columns should usually be indexed (especially if the primary/unique column in in the parent table is subject to UPDATE statements).
While reading the alpha edition of the “Oracle Database 11g Performance Tuning Recipes” book, I noticed a test case in Recipe 5-15 that is intended to demonstrate how an index on a foreign key’s column(s) helps to resolve the most common cause of TM enqueues. While the test case included the DDL to create a parent and child table, it did not include the DML to create test data. The DDL for the two tables looks something like the following:
CREATE TABLE STORES (
STORE_ID NUMBER(10) NOT NULL,
SUPPLIER_NAME VARCHAR2(40) NOT NULL,
CONSTRAINT STORES_PK PRIMARY KEY (STORE_ID));
CREATE TABLE PRODUCTS (
PRODUCT_ID NUMBER(10) NOT NULL,
PRODUCT_NAME VARCHAR2(30) NOT NULL,
SUPPLIER_ID NUMBER(10) NOT NULL,
STORE_ID NUMBER(10) NOT NULL,
CONSTRAINT FK_STORES FOREIGN KEY (STORE_ID) REFERENCES STORES(STORE_ID) ON DELETE CASCADE);
Immediately after the above DDL statements appears the following claim is made by the alpha copy of the book:
“If you now delete any rows in the STORES table, you’ll notice waits due to locking.”
Interesting observation… I hope that the final copy of the book includes the DML to populate those tables. In the mean time, let’s create our own test data to see if the claim made in the quote is correct:
INSERT INTO
STORES
SELECT
ROWNUM STORE_ID,
'SUPPLIER NAME '||TO_CHAR(ROWNUM) SUPPLIER_NAME
FROM
DUAL
CONNECT BY
LEVEL<=10;
INSERT INTO
PRODUCTS
SELECT
ROWNUM PRODUCT_ID,
'PRODUCT NAME '||TO_CHAR(ROWNUM) PRODUCT_NAME,
TRUNC((ROWNUM-1)/10)+100 SUPPLIER_ID,
TRUNC((ROWNUM-1)/10)+1 STORE_ID
FROM
DUAL
CONNECT BY
LEVEL<=100;
COMMIT;
We now have 10 rows in the parent table and 100 rows in the child table (side note: is there something strange about the names of the columns in the tables?). Let’s connect to the database using two sessions. In Session 1, execute the following to delete a row from the STORES table:
DELETE FROM
STORES
WHERE
STORE_ID=1;
Here is the challenge, what happens if we attempt to execute the following script in Session 2 (the values to be inserted should not conflict with existing rows in the tables):
INSERT INTO
STORES
SELECT
ROWNUM+10 STORE_ID,
'SUPPLIER NAME '||TO_CHAR(ROWNUM+10) SUPPLIER_NAME
FROM
DUAL
CONNECT BY
LEVEL<=10;
INSERT INTO
PRODUCTS
SELECT
ROWNUM PRODUCT_ID,
'PRODUCT NAME '||TO_CHAR(ROWNUM+100) PRODUCT_NAME,
TRUNC((ROWNUM+100-1)/10)+100 SUPPLIER_ID,
TRUNC((ROWNUM+100-1)/10)+1 STORE_ID
FROM
DUAL
CONNECT BY
LEVEL<=100;
Which of the following will happen?
a. Session 2 will be blocked by session 1, with session 2 waiting in the “enq: TM – contention” wait event when it attempts to execute the first of the two SQL statements.
b. Session 2 will be blocked by session 1, with session 2 waiting in the “enq: TM – contention” wait event when it attempts to execute the second of the two SQL statements.
c. Session 2 will receive the following error message “ERROR at line 1: ORA-02291: integrity constraint (TESTUSER.FK_STORES) violated – parent key not found”.
d. Session 2 will corrupt the database due to the missed TM enqueue.
e. Session 2 will be waiting in the “SQL*Net message from client” wait event after it attempts to execute the second of the two SQL statements.
—–
Think about the above for a moment before scrolling down. Does the Oracle release version make a difference?
Now that you have thought about the question for a minute or two, take a look at the output I received on Oracle Database 11.2.0.2:
SQL> INSERT INTO
2 STORES
3 SELECT
4 ROWNUM+10 STORE_ID,
5 'SUPPLIER NAME '||TO_CHAR(ROWNUM+10) SUPPLIER_NAME
6 FROM
7 DUAL
8 CONNECT BY
9 LEVEL<=10;
10 rows created.
SQL> INSERT INTO
2 PRODUCTS
3 SELECT
4 ROWNUM PRODUCT_ID,
5 'PRODUCT NAME '||TO_CHAR(ROWNUM+100) PRODUCT_NAME,
6 TRUNC((ROWNUM+100-1)/10)+100 SUPPLIER_ID,
7 TRUNC((ROWNUM+100-1)/10)+1 STORE_ID
8 FROM
9 DUAL
10 CONNECT BY
11 LEVEL<=100;
100 rows created.
So, the answer to the multiple choice question is…
Wait… we are not done yet. Back in Session 2 execute the following which will delete a previously committed row (Session 1 previously deleted the row with STORE_ID=1, but has yet to COMMIT):
DELETE FROM
STORES
WHERE
STORE_ID=10;
The output I received on Oracle Database 11.2.0.2:
SQL> DELETE FROM
2 STORES
3 WHERE
4 STORE_ID=10;
(session is hung - reporting wait event "enq: TM - contention")
So, the answer to the multiple choice question is… Wait, does the Oracle Database release version matter?
The point of blog articles like this one is not to insult authors who have spent thousands of hours carefully constructing an accurate and helpful book, but instead to suggest that readers investigate when something stated does not exactly match what one believes to be true. It could be that the author “took a long walk down a short pier”, or that the author is revealing accurate information which simply cannot be found through other resources (and may in the process be directly contradicting information sources you have used in the past). If you do not investigate in such cases, you may lose an important opportunity to learn something that could prove to be extremely valuable.
Actions
Information
3 responses
20 06 2011
Charles Hooper
It is interesting to note that the two sample tables for recipe 5-15 and the SQL statement used to detect missing indexes on the foreign key columns in that recipe appear to be very similar to those found on this website page:
http://www.confio.com/blog/solving-waits-on-enq-tm-contention
Recipe 5-15 claims that the SQL statement used to detect missing indexes on the foreign key columns (also found in the above linked article with a very small modification to the table aliases and capitalization) finds “all unindexed foreign key constraints in your database.” For extra credit, identify three problems with this claim (I am currently aware of three problems, but there may be more).
24 06 2011
Log Buffer #226, A Carnival of the Vanities for DBAs | The Pythian Blog
[…] Charles Hopper tells us what is wrong with the quote – Addressing TM Enqueue Contention […]
18 01 2012
Leave a Reply
Fill in your details below or click an icon to log in:
WordPress.com Logo
You are commenting using your WordPress.com account. Log Out / Change )
Twitter picture
You are commenting using your Twitter account. Log Out / Change )
Facebook photo
You are commenting using your Facebook account. Log Out / Change )
Google+ photo
You are commenting using your Google+ account. Log Out / Change )
Connecting to %s
Follow
Get every new post delivered to your Inbox.
Join 179 other followers
%d bloggers like this:
|
__label__pos
| 0.818857 |
C# task应用实例详解
Task的应用
Task的MSDN的描述如下:
【Task类的表示单个操作不会返回一个值,通常以异步方式执行。
Task对象是一种的中心思想基于任务的异步模式首次引入.NETFramework 4 中。
因为由执行工作Task对象通常以异步方式执行线程池线程上而不是以同步方式在主应用程序线程中,可以使用Status属性,并将IsCanceled, IsCompleted,和IsFaulted属性,以确定任务的状态。
大多数情况下,lambda 表达式用于指定该任务所执行的工作量。
对于返回值的操作,您使用Task类。】
我对于Task的理解是这样的,Task是FrameWork4引进的新功能,他和ConCurrent命名空间一起被引进,用来替代Thread的使用。
根据我的使用,个人觉得,他确实比Thead的功能要丰富一些。
下面我们一起看一个最简单的例子:
using System;
using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace TaskConsole
{ class Program
{ static void Main(string[] args)
{ //当前线程标识 Console.WriteLine(Thread.CurrentThread.GetHashCode());
Task task = new Task(run);
Console.WriteLine("任务标识:" + task.GetHashCode() + ",状态:" + task.Status);//状态 task.Start();
Console.WriteLine("任务标识:" + task.GetHashCode() + ",状态:" + task.Status);//状态 //任务完成后执行新任务
Action ation = new Action(taskStart);
task.ContinueWith(ation);
Console.Read();
} public static void taskStart(Task task)
{
task = new Task(run);
task.Start(); //如果注释上面两句话,则任务标识为 task.ContinueWith(ation)中task的任务
Console.WriteLine("任务标识:" + task.GetHashCode() + ",状态:" + task.Status + ",当前线程:" + Thread.CurrentThread.GetHashCode());//状态
} public static void run()
{
Console.WriteLine("this is run");
}
}
}
一,task.GetHashCode(),是获取Task实例的唯一标识,每个Task都不一样。
测试发现,Task.GetHashCode()并不等于Thread.CurrentThread.GetHashCode()。
二,task.ContinueWith(),是任务结束后继续执行任务的方法,传一个Action,当任务结束后,触发该Action。
任务刚new出来的时候,task就又状态了,是Created,一但运行了,状态就是WaitingToRun。
运行结果如下:
根据MSDN的说明,Task.State是获取TaskState的枚举值,其枚举值代表的意义如下
|Canceled |该任务已通过对其自身的 CancellationToken 引发 OperationCanceledException 对取消进行了确认,此时该标记处于已发送信号状态;或者在该任务开始执行之前,已向该任务的 CancellationToken 发出了信号。 有关更多信息,请参见任务取消。
| Created |该任务已初始化,但尚未被计划。
| Faulted |由于未处理异常的原因而完成的任务。
| RanToCompletion |已成功完成执行的任务。
| Running |该任务正在运行,但尚未完成。
| WaitingForActivation |该任务正在等待 .NET Framework 基础结构在内部将其激活并进行计划。
| WaitingForChildrenToComplete |该任务已完成执行,正在隐式等待附加的子任务完成。
| WaitingToRun |该任务已被计划执行,但尚未开始执行。
任务嵌套
任务嵌套就是指在一个任务中又创建了一个任务。
而新建的任务就是子任务。在没有特殊声明的情况下,父子任务是一起运行的。
如SimpleNestedTask方法。
父子任务关联需要在创建子任务的时候,增加参数TaskCreationOptions.AttachedToParent。
将父子任务关联起来,此时父任务将等待子任务结束,才会完成。
如果使用Task创建任务,不需要使用TaskCreationOptions.AttachedToParent参数,因为只要父任务使用了子任务的返回结果,父任务自然就会等待子任务完成。
public class Program
{
static void Main(string[] args)
{
WaitForSimpleNestedTask();
Console.WriteLine("=====================================================");
SimpleNestedTask();
Thread.SpinWait(600000);//等待SimpleNestedTask结束 再运行
Console.WriteLine("=====================================================");
//SimpleNestedTaskAttachedToParent();
Console.Read();
}
static void WaitForSimpleNestedTask()
{
var outer = Task.Factory.StartNew(() =>
{
Console.WriteLine("Outer1 task executing.");
var nested = Task.Factory.StartNew(() =>
{
Console.WriteLine("Nested1 task starting.");
Thread.SpinWait(5000000);
Console.WriteLine("Nested1 task completing.");
return 42;
});
return nested.Result;
return 1;
});
Console.WriteLine("Outer1 has returned {0}.", outer.Result);
}
static void SimpleNestedTask()
{
var parent = Task.Factory.StartNew(() =>
{
Console.WriteLine("Outer2 task executing.");
var child = Task.Factory.StartNew(() =>
{
Console.WriteLine("Nested2 task starting.");
Thread.SpinWait(500000);
Console.WriteLine("Nested2 task completing.");
});
});
parent.Wait();
Console.WriteLine("Outer2 has completed.");
}
static void SimpleNestedTaskAttachedToParent()
{
var parent = Task.Factory.StartNew(() =>
{
Console.WriteLine("Outer3 task executing.");
var child = Task.Factory.StartNew(() =>
{
Console.WriteLine("Nested3 task starting.");
Thread.SpinWait(500000);
Console.WriteLine("Nested3 task completing.");
}, TaskCreationOptions.AttachedToParent);
});
parent.Wait();
Console.WriteLine("Outer has completed.");
}
ConCurrent的线程安全的
因为,MSDN将在System.Collections.Concurrent命名空间下的集合,都称为线程安全的集合。
线程安全可以理解为可以被多个线程同时使用的集合,而且同时使用的时候是该集合的值是准确的。
下面举一个使用线程安全集合的例子,使用的是BlockingCollection。
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelConsole
{
class Program
{
//定义集合大小为51个,也可以不定义大小
static BlockingCollection blocking = new BlockingCollection(51);
static void Main(string[] args)
{
blocking = new BlockingCollection();
Console.WriteLine("当前blocking为:" + blocking.IsCompleted + "设置了集合大小count一样是0,blocking.Count:" + blocking.Count());
//当前线程标识
Console.WriteLine(Thread.CurrentThread.GetHashCode());
for (int i = 0; i < 3; i++)
{
////如果添加到第3个,就设置添加完成,这时在添加就会抛异常
//if (i == 3)
//{
// blocking.CompleteAdding();
//}
Action action = new Action(run);
Task task = new Task(action,i);
task.RunSynchronously();
}
Console.WriteLine("设置添加完成前:" + blocking.IsAddingCompleted);
//设置添加完成后
blocking.CompleteAdding();
Console.WriteLine("设置添加完成后:" + blocking.IsAddingCompleted);
#region 同步取 取3个
//for (int i = 0; i < 3; i++)
//{
// Action actionTake = new Action(take);
// actionTake();
//}
#endregion
//并发读取
#region 并发步取 取3个
//blocking.IsCompleted 只有当集合被添加进内容,然后又都被取光了以后,他才会等于ture,否则都是false
//当IsCompleted为ture时,就不能再取了否则会抛异常
//同时取,结果是
//blocking:0
//blocking:2
//blocking:1
if (!blocking.IsCompleted)//如果集合没取光
{
Action actionTake2 = new Action(take);
Parallel.Invoke(actionTake2, actionTake2, actionTake2);
}
#endregion
Console.WriteLine("当前blocking为:" + blocking.IsCompleted + ",blocking数量为:" + blocking.Count());
//数据被取光了以后, blocking.Count()为0
Console.Read();
}
public static void take()
{
//同步取,blocking.Count()会真实的表现,而异步取,Count是不准确的,因为我取count的时候,可能集合已经又被取出数据了,测试10次肯定会出现不真实的情况
Console.WriteLine("blocking:" + blocking.Take() + ",blocking数量为:" + blocking.Count());
}
public static void run(object i)
{
int currentI = int.Parse(i.ToString());
blocking.TryAdd(currentI);
}
}
}
Parallel
Parallel.Invoke(),并发调用Action,可以传多个Action,也可以传一个Action数据组。
Task
Task(Action,object),这是Task的构造方法,接收Action,object是Action的参数,。
task.RunSynchronously(),他是同步运行任务计划用的,同时他和task.Start()一样,也可以启动线程。
BlockingCollection集合
属性一:IsCompleted,他是表示集合是否有数据,只有当集合被添加进内容,然后又都被取光了以后,他才会等于ture,否则都是false。
属性一:BlockingCollection.IsAddingCompleted,表示是否添加完成。针对blocking.CompleteAdding()的使用,当调用了该方法IsAddingCompleted就为true。
方法一:BlockingCollection.blocking.CompleteAdding(),设置IsAddingCompleted用的。
方法二:BlockingCollection.Add,添加一个实体
方法三:BlockingCollection.TryAdd,添加一个实体,我这里用的是这个方法,区别是,如果添加重复项,他会引发InvalidOperationException这个异常。
方法四:BlockingCollection.Take,从集合中取一个值,注意,是真的取出来,取出来后,BlockingCollection.cout会减一。
运行结果如下:
到此这篇关于C# task应用实例的文章就介绍到这了,更多相关c#task应用内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!
您可能感兴趣的文章:C#中Task.Yield的用途深入讲解C#利用Task实现任务超时多任务一起执行的方法windows下C#定时管理器框架Task.MainForm详解详解C#中 Thread,Task,Async/Await,IAsyncResult的那些事儿c#异步task示例分享(异步操作)
相关推荐
ASP中SELECT下拉菜单同时获取VALUE和TEXT值的实现代码
ASP基础知识Command对象讲解
ASP.NET Core MVC如何实现运行时动态定义Controller类型
解决Tensorflow2.0 tf.keras.Model.load_weights() 报错处理问题
|
__label__pos
| 0.909754 |
Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author
question about quoting % in preexec
I am using the following preexec-function to display the currently running
process in my xterm-title:
preexec () {
print -Pn "\033]0;%n@%m <${(Vq)2}> %~\007"
print -Pn $icontitle
}
But if I run a command with "%" in the arguments, e.g.:
date "+%Y-%m-%d %H:%M:%S"
it leads to very unwanted results because zsh interprets it as variables.
How can I avoid this? I suppose I have to quote the %s but how?
Thanks so much for your help,
Andy.
--
o _ _ _
------- __o __o /\_ _ \\o (_)\__/o (_) -o)
----- _`\<,_ _`\<,_ _>(_) (_)/<_ \_| \ _|/' \/ /\\
---- (_)/ (_) (_)/ (_) (_) (_) (_) (_)' _\o_ _\_v
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Money often costs to much. -- Ralph Waldo Emerson
Messages sorted by: Reverse Date, Date, Thread, Author
|
__label__pos
| 0.976698 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I have a multiplatform Adobe Air Native Extension (ANE) that I have created. The Android portion of the ANE includes resources (i.e. res/drawable, res/drawable-hdpi, res/layout, res/values).
When I create the ANE, the resources are included in the ANE properly. (I have determined this by pulling apart the ANE and I see all my resources in the proper directories)
However, when I create the APK, it includes all my resources EXCEPT the res/values directory. That whole directory and it's resources are not included. (I have determined this by pulling apart the APK and looking at the res directory)
Does anyone know if there is something special in Adobe packaging of APK's that prevents res/values folder from ANE's being included in the final APK?
share|improve this question
1 Answer 1
What is happening in this situation is that the resources are being compiled into a binary format (in the resources.arsc file) so the original source files are not packaged into the APK.
If you dump the resources in the apk using aapt you can see that the resources are there:
aapt dump --values resources your_app.apk
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.801488 |
[AWS][EKS] Best practice for load balancing - 3. what controller should I use
5 minute read
This article is sharing the best practice for doing load balancing on Amazon EKS, learn what is advantage and disadvantage of using different controller. We will discuss what controller should you use.
Compare different controller options
Here are some common load balancing solutions that can be applied on Amazon EKS:
Kubernetes in-tree load balancer controller
This is the easiest way to provision your Elastic Load Balancer resource, which could be done by using default Kubernetes service deployment with type: LoadBalancer. In most case, the in-tree controller can quickly spin up the load balancer for experiment purpose; or, offers production workload.
However, you need to aware the problem as we mentioned in the previous posts 1 2 because it generally can add a hop for your load balancing behavior on AWS and also can increase the complexity for your traffic.
In addition, you need to aware this method only applies for creating Classic Load Balancer and Network Load Balancer (by using annotation 3).
nginx ingress controller
If you are using nginx Ingress controller in AWS, it will deploy Network load balancer (NLB) to expose the NGINX Ingress controller behind a Service of type=LoadBalancer. Here is an example for deploying Kubernetes service of nginx Ingress controller 1.1.3:
apiVersion: v1
kind: Service
metadata:
annotations:
service.beta.kubernetes.io/aws-load-balancer-backend-protocol: tcp
service.beta.kubernetes.io/aws-load-balancer-cross-zone-load-balancing-enabled: "true"
service.beta.kubernetes.io/aws-load-balancer-type: nlb
labels:
app.kubernetes.io/component: controller
app.kubernetes.io/instance: ingress-nginx
app.kubernetes.io/name: ingress-nginx
app.kubernetes.io/part-of: ingress-nginx
app.kubernetes.io/version: 1.1.3
name: ingress-nginx-controller
namespace: ingress-nginx
spec:
externalTrafficPolicy: Local
ports:
- appProtocol: http
name: http
port: 80
protocol: TCP
targetPort: http
- appProtocol: https
name: https
port: 443
protocol: TCP
targetPort: https
selector:
app.kubernetes.io/component: controller
app.kubernetes.io/instance: ingress-nginx
app.kubernetes.io/name: ingress-nginx
type: LoadBalancer
Guess what, yes, it is still can rely on the in-tree controller. On the other hand, the problem we were mentioning can persist. It can be hard to expect which Pods will receive the traffic; however, the main issue is that an Ingress controller does not typically eliminate the need for an external load balancer, it simply adds an additional layer of routing and control behind the load balancer.
An architecture overview of using nginx Ingress controller
Figure 1. An architecture overview of using nginx Ingress controller
So why to choose Nginx Ingress controller? It probably can be the reason why as mentioned in the post 4 as mentioned on the AWS Blog:
• By default, the NGINX Ingress controller will listen to all the ingress events from all the namespaces and add corresponding directives and rules into the NGINX configuration file. This makes it possible to use a centralized routing file which includes all the ingress rules, hosts, and paths.
• With the NGINX Ingress controller you can also have multiple ingress objects for multiple environments or namespaces with the same network load balancer.
AWS Load Balancer Controller
AWS Load Balancer Controller is similar to the in-tree Kubernetes controller and use native AWS APIs to provision and manage Elastic Load Balancers. The controller was an open-source project originally named ALB Ingress Controller because it was only provides capability to manage Application Load Balancer at the intial stage, lately, it officially renamed as ** AWS Load Balancer Controller** 5, which is maintaining by AWS product team and open-source community.
Unlike in-tree Kubernetes controller needs to wait the upstream code to be updated and requires you to upgrade Kubernetes control plane version if the controller has any bug or any new ELB features need to be supported. Using AWS Load Balancer Controller, it can gracefully to be replaced in this scenario because it will be running as Kubernetes deployment instead of integrating in the Kubernetes upstream source code.
The controller has flexibility to maintain your Elastic Load Balancer resources with up-to-date annotations. For example, if you are nginx ingress controller in order to provide Kubernetes Ingress object management, it requires you to provision and add an extra load balancing layer with Network Load Balancer, the traffic generally pass through the controller itself (nginx); instead, if you are using AWS Load Balancer, it doesn’t involve and it will directly control the Elastic Load Balancer and pass the traffic to your Pods (by using IP mode).
The AWS Load Balancer Controller also start to support TargetGroupBinding 6 and IngressGroup 7 feature since v2.2, which enables you to group multiple Ingress resources together. This also enhance the capability to shared the same Elastic Load Balancer resource.
Conclusion: What controller should I use?
After comparing different load balancer controllers, generally speaking, using AWS Load Balancer basically can have better feature supports as well as adopt with the performance optimization by configuring AWS Load Balancer attributes correctly. It is essential to enable IP mode when applying the Kubernetes service deployment with AWS Load Balancer Controller to reduce unnecessary hop that can be caused by Kubernetes networking itself, which is generally not totally suitable for AWS networking and elastic load balancing feature.
However, the disadvantage of using AWS Load Balancer can be all features require to be supported by Elastic Load Balancer itself because the controller doesn’t involve additional functions to extend the traffic control. Using other controller still can have its benefit and provide different features that Elastic Load Balancer doesn’t have, such as using nginx Ingress controller you may be able to define forward service to external FastCGI targets, using Regular Expression to perform path matching … etc.
By the end of this article, I hope the comparison and information can better help you understand how to select load balancer controller that will be running in Amazon EKS, and choose the right option for your environment.
Thanks for reading! If you have any feedback or opinions, please feel free to leave the comment below.
References
Leave a comment
|
__label__pos
| 0.645289 |
reusable input component react
Reusable Input Component in React Typescript [with useInput hook and error]
Author Profile
Abdul Basit OnLinkedIn
Every website has to deal with a form, and one of the most important and most used form elements is input. Today, we shall explore constructing a reusable input component in React using Typescript, we will also learn how to show errors and how to make it modular via useInput custom hook, and what are best UI UX practices to consider while creating an input component.
This comprehensive guide will equip you with the knowledge and skills to create an efficient and user-friendly input component for your web applications. In the first step, we will build components architecture and UI, and in the second step, we will work on functionality and see how to use it form.
Here is the design of our input component with and without error. The Codepen demo is also available at the end of the article.
React Input UI without Error
react login form ui
React Input UI with Error
react login form with error
Reusable Input Component Architecture
Let's talk about component architecture.
The input component has multiple props. It depends on your choice that what you want to keep and remove as required. The following are the possible props:
• type: Specifies the type of input (e.g., 'text', 'number', 'email', 'password').
• label: The text for the input label.
• value: The current value of the input.
• error: An error message to display which is optional and shown on the basis of condition.
• name: Represents the name attribute of the input element to identify and group the data submitted from different input fields
• placeholder: The placeholder text to display when the input is empty.
• onChange: The function to handle changes in the input value. It takes an event of type ChangeEvent<HTMLInputElement> as a parameter.
• disabled: which is optional (indicated by the ? symbol). It specifies whether the input should be disabled or not
JSX for React Input Component with label and error
import { ChangeEvent, FC } from 'react'
interface InputProps {
type: 'text' | 'number' | 'email' | 'password'
label: string
value: string | number
name: string
placeholder: string
error: boolean
disabled?: boolean
onChange: (e: ChangeEvent<HTMLInputElement>) => void
}
const Input: FC<InputProps> = ({
type,
label,
value,
name,
placeholder,
error,
disabled,
onChange,
}) => {
return (
<div className="input-wrapper">
<label htmlFor={label}>{label}</label>
<input
type={type}
id={label}
value={value}
name={name}
placeholder={placeholder}
onChange={onChange}
disabled={disabled}
/>
{error && <p className="error">Input filed can't be empty!</p>}
</div>
)
}
export default Input
CSS for Reusable Input Component
.input-wrapper {
margin-top: 20px;
}
/* Input style */
/* Label */
label {
font-weight: 600;
font-size: 18px;
color: #344054;
display: block;
margin-bottom: 8px;
}
/* Input field */
input {
font-size: 16px;
font-weight: 400;
width: 250px;
color: #344054;
background: #ffffff;
border: 1px solid #d0d5dd;
box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
border-radius: 8px;
padding: 10px 14px;
}
input::placeholder {
font-size: 16px;
font-weight: 400;
color: #667085;
}
/* Input field focus */
input:focus {
}
.error {
color: #db4437;
font-size: 14px;
font-weight: 400;
margin-left: 12px;
margin-top: 4px;
}
This is how our input component UI will look like if we will render it in App or parent component
react reusable input component with typescript
We are done with component structure, architecture, and UI, now let's make it functional and see how we can use it in real world applications.
How to use Input Component with form
Let's say we are working on a login form in React App and want to use this input component there. In the below-given component, we import the Input component first and make two states, one for input value and the other for error.
While submitting the form, we check for an error and then show the error.
import React, { ChangeEvent, FormEvent, useState } from 'react'
import './App.css'
import Input from './components/Input'
const App: React.FC = () => {
const [name, setName] = useState('')
const [error, setError] = useState(false)
const handleNameChange = (e: ChangeEvent<HTMLInputElement>) => {
setName(e.target.value)
}
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
if (!name.trim()) {
setError(true)
} else {
setError(false)
}
}
return (
<div className="page-center">
<form onSubmit={handleSubmit}>
<h3 className="form-title">Login Form</h3>
<Input
type="text"
label="Name"
value={name}
name="name"
error={error}
onChange={handleNameChange}
placeholder="Please enter your name"
/>
<button type="submit">Submit</button>
</form>
</div>
)
}
export default App
Note
This is the boilerplate code you can tweak it as per your need.
Best Practices for Creating Reusable Input Components in React
You can get most out of reusable input components with some best practices. You must consider these while working on forms or input in React APP.
So, let’s see what are these practices:
1. Call handleSubmit function in form
Always wrap input inside form and call submit function in form tag and make the submit button type="submit", it will invoke submit function both ways, by pressing submit button and enter key on the keyboard.
2. When to disable Input in React
Input tag also supports disabled prop, when to use it? It depends on the app use case, some developers make the input and submit form button both disable while submitting data to database to prevent retyping in input until you get the response back from database.
You can also learn more about how to use the loading spinner button in React, which I have discussed in this article.
3. Using htmlFor attribute for activating input by clicking a label
We also need to improve the UX of input component. There are two ways to activate input.
1. Click the input box
2. Click the label
We also have to implement the second point to improve the UX of the component.
The label element is associated with the input using the htmlFor attribute, which matches the id of the input element. This helps in accessibility by associating the label with the correct input.
4. useInput custom hook
Using the custom useInput hook we can further improve input component by making it modular and scalable.
import { ChangeEvent, useState } from 'react'
const useInput = (initialValue: string) => {
const [value, setValue] = useState(initialValue)
const [error, setError] = useState(false)
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
}
return {
value,
error,
onChange: handleChange,
setError,
}
}
export default useInput
How to use useInput hook in form;
import React, { FormEvent } from 'react'
import './App.css'
import Input from './components/Input'
import useInput from './hooks/useInput'
const App: React.FC = () => {
const { value, error, onChange, setError } = useInput('')
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
if (!value.trim()) {
setError(true)
} else {
setError(false)
}
}
return (
<div className="page-center">
<form onSubmit={handleSubmit}>
<Input
type="text"
label="Name"
name="name"
value={value}
error={error}
onChange={onChange}
placeholder="Please enter your name"
/>
<button type="submit">Submit</button>
</form>
</div>
)
}
export default App
What if you want to use two inputs in the form and that is email and password? If this is the case I will refactor the code this way;
import React, { FormEvent } from 'react'
import './App.css'
import Input from './components/Input'
import useInput from './hooks/useInput'
const App: React.FC = () => {
const emailInput = useInput('')
const passwordInput = useInput('')
const handleSubmit = (e: FormEvent) => {
e.preventDefault()
validateInput(emailInput)
validateInput(passwordInput)
console.log('email ==>', emailInput.value, 'password ==>', passwordInput.value)
}
const validateInput = (input: { value: string, setError: (value: boolean) => void }) => {
if (!input.value.trim()) {
input.setError(true)
} else {
input.setError(false)
}
}
return (
<div className="page-center">
<form onSubmit={handleSubmit}>
<h3 className="form-title">Login Form</h3>
<Input
type="email"
label="Email"
name="email"
placeholder="Please enter your email"
{...emailInput}
/>
<Input
type="password"
label="Password"
name="password"
placeholder="Please enter your password"
{...passwordInput}
/>
<button className="submit-btn">Submit</button>
</form>
</div>
)
}
export default App
While submitting the form we are checking if the input values are safely added to our state and verify the functionality of the useInput hook with console.log()
login form console data
Further Read
If you have a form with more than one input, there is one more pattern useForm custom hook I teach in React forms best practices article.
Codepen Demo | Reusable Input Component
I hope you learned something new in this article that helps you in your React journey. Want to learn more about React? Do subscribe to the newsletter for more insightful content.
|
__label__pos
| 0.998979 |
Method stub
From Wikipedia, the free encyclopedia
Jump to: navigation, search
A method stub[citation needed] or simply stub[1] in software development is a piece of code used to stand in for some other programming functionality. A stub may simulate the behavior of existing code (such as a procedure on a remote machine) or be a temporary substitute for yet-to-be-developed code. Stubs are therefore most useful in porting, distributed computing as well as general software development and testing.
An example of a stub in pseudocode might be as follows:
BEGIN
Temperature = ThermometerRead(Outside)
IF Temperature > 40 THEN
PRINT "It's HOT!"
END IF
END
BEGIN ThermometerRead(Source insideOrOutside)
RETURN 28
END ThermometerRead
The above pseudocode utilises the function ThermometerRead, which returns a temperature. While ThermometerRead would be intended to read some hardware device, this function currently does not contain the necessary code. So ThermometerRead does not, in essence, simulate any process, yet it does return a legal value, allowing the main program to be at least partially tested. Also note that although it accepts the parameter of type Source, which determines whether inside or outside temperature is needed, it does not use the actual value passed (argument insideOrOutside) by the caller in its logic.
A stub [2] is a routine that doesn't actually do anything other than declaring itself and the parameters it accepts and returning something that is usually the values expected in one of the "happy scenarios" for the caller. Stubs are used commonly as placeholders for implementation of a known interface, where the interface is finalized/known but the implementation is not yet known/finalized. The stub contains just enough code to allow it to be compiled and linked with the rest of the program. In RMI nomenclature, a stub communicates on the server-side with a skeleton.[3]
See also[edit]
References[edit]
1. ^ Nell B. Dale; Chip Weems (2004). Programming in C++. Jones & Bartlett Learning. p. 308. ISBN 978-0-7637-3234-9.
2. ^ "stub". WEBOPEDIA. Retrieved 2012-08-28.
3. ^ Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bert, Bates (2004). Hendrickson, Mike; Loukides, Mike, eds. "Head First Design Patterns" (paperback). 1. O'REILLY: 440. ISBN 978-0-596-00712-6. Retrieved 2012-08-28.
External links[edit]
|
__label__pos
| 0.529194 |
0
I am currently trying to get the text from a DBLookUpComboBox but it wont let me retrieve it i have a number and 2 strings in the box which is an ID and first and last name. I cannot retrieve anything from the box unless i use a edit box but i cannot imput it into a database which is using the type number.
Please help if you need more info or example of the code i can do this.
3
Contributors
14
Replies
17
Views
8 Years
Discussion Span
Last Post by fayyaz
0
I am currently trying to get the text from a DBLookUpComboBox but it wont let me retrieve it i have a number and 2 strings in the box which is an ID and first and last name. I cannot retrieve anything from the box unless i use a edit box but i cannot imput it into a database which is using the type number.
Please help if you need more info or example of the code i can do this.
Dear My Friend
your question contain of tow parts
1- using DBLookup Combobox for retrieving data
2- using Edit box for Input data to database
for first part of your question I say that DBLookupComboBox can not retrieve data from database automatically and don't let you to put data into its text property at run time by program code for example you can not write "DBLookupComboBox1.Text:=table1.FieldByname('firstName').asstring;"
in your Program. but you can use "Volga" Components.
Volga Components have a component Named VolgaDBEdit that can use as DBLookupComboBox it have some features that may be helpful for you
about second part of your question I Write sample Code as below
Table1.insert; //Or Table1.Edit;
Table1.FielsByname('ID').asstring:=Trim(Edit1.Text);
Table1.FielsByname('FirstName').asstring:=Trim(Edit2.Text);
Table1.FielsByname('LastName').asstring:=Trim(Edit3.Text);
Table1.Post
For Retrieving data from Data Base you can use this Below code
Edit1.Text:=Table1.FieldByname('ID').asstring;
Edit2.Text:=Table1.FieldByname('FirstName').asstring;
Edit3.Text:=Table1.FieldByname('LastName').asstring;
if you have any problem with this codes Please tel me More information For Example :
What is your Data Base engine , What is the Error message etc.
0
What i am looking for is a way of getting one peice of data out of the DBLookUpComboBox this is the code i am using
procedure TForm6.Button1Click(Sender: TObject);
begin
adotable1.Close;
with adoquery3 do
begin
active:=false;
SQL.Clear;
SQL.Add('insert into StudentPayments(Student_ID)' +
'values(:p1)');
parameters.paramvalues['p1']:=DBLookupComboBox1.Text ;
execSQL;
end;
adotable1.active:=true;
end;
Once executed the error i am getting is "Data Type Mismatch In Criteria expression." The parameter is simply defined as "p1" with a value of "%"
Also about the Volga Component where can i find this? and woudl i go about installing it?
Edited by HelpMeIT: n/a
1
Dear My Frind
you can change your code to one of the tow below code
1- Using a String Variable
procedure TForm6.Button1Click(Sender: TObject);
Var
STD_ID:String;
begin
STD_ID:=Trim(DBLookupComboBox1.Text);
adotable1.Close;
with adoquery3 do
begin
active:=false;
SQL.Clear;
SQL.Add('insert into StudentPayments(Student_ID)' +
'values(:p1)');
parameters.paramvalues['p1']:=StrToInt(Trim(STD_ID)) ;
execSQL;
end;
adotable1.active:=true;
end;
2- Directly Use DBLookupCombobox
procedure TForm6.Button1Click(Sender: TObject);
begin
adotable1.Close;
with adoquery3 do
begin
active:=false;
SQL.Clear;
SQL.Add('insert into StudentPayments(Student_ID)' +
'values(:p1)');
parameters.paramvalues['p1']:=DBLookupComboBox1.KeyValue;
execSQL;
end;
adotable1.active:=true;
end;
In this method at first you must assign Corresponding field to Key Field of DBLookupComboBox1 by same type of STudent_ID Type (For Example "Numeric")
All of tow mwthod is tested and work properly .
About Volga DB Library : It is a Free Component and you can download it from this address http://wareseeker.com/screenshot/volgadb-controls-library-3.2.exe/385330
0
Hi,
I haven't used paramvalues till now, so I write my way to do this:
procedure TForm6.Button1Click(Sender: TObject);
begin
adotable1.Close;
with adoquery3 do
begin
if Active then Close;
SQL.Clear;
SQL.Add('insert into StudentPayments(Student_ID)' +
'values(:p1)');
if StrToIntDef(DBLookupComboBox1.Text, -1) <> -1
Parameters.ParamByName('p1').Value:= StrToInt(DBLookupComboBox1.Text) //value is a variant, but, to be sure you will not get any error, make the explicit conversion
else
begin
//some safety code
Exit;
end;
execSQL;
end;
adotable1.active:=true;
end;
Cheers,
Ionut
Edited by Ionelul: n/a
0
Thanks fayyaz,
i used the second solution and it worked perfectly!
any ideas on how to insert a data using similar code as above only selecting a date from a edit box? im using strtodate to insert but it still isnt working?
procedure TForm2.Button1Click(Sender: TObject);
begin
adotable1.Close;
with adoquery1 do
begin
active:=false;
SQL.Clear;
SQL.Add('insert into StudentDetails(StudentFirstNameForeign,StudentLastNameForeign,' +
'StudentFirstNameEnglish,StudentLastNameEnglish,' +
'StudentsForeignAddress,StudentsEnglishAddress,DOB,Gender)' +
'values(:p1,:p2,:p3,:p4,:p5,:p6,:p7,:p8)');
parameters.paramvalues['p1']:=Edit1.Text ;
parameters.paramvalues['p2']:=Edit2.Text ;
parameters.paramvalues['p3']:=Edit3.Text ;
parameters.paramvalues['p4']:=Edit4.Text ;
parameters.paramvalues['p5']:=Edit5.Text ;
parameters.paramvalues['p6']:=Edit6.Text ;
parameters.paramvalues['p7']:=strtodate(trim(DBEdit1.Text)) ;
parameters.paramvalues['p8']:=ComboBox1.Text ;
execSQL;
end;
adotable1.active:=true;
end;
The line that is causing a problem is
parameters.paramvalues['p7']:=strtodate(trim(DBEdit1.Text)) ;
i have also tried just
parameters.paramvalues['p7']:=DBEdit1.Text ;
as i do have a DBEdit which is connected to the table and the date field unfortunatly i cannot get it to insert the date i recieved an error in executing with the second code and using the first code i am recieving an error that it is not a date but the date i am inserting is 25/02/1910 i have also tried other dates but they will not work.
thanks
Edited by HelpMeIT: n/a
0
Dear My Friend
your code is Correct But I should hint you tow points
1- When you use SQL Statements(that I think it is a very good method for working by Database) you should better to use MaskEdit Instead Edit Or DBEdit for user interface
2- the error that you detect to is not because of your Code rather than it is because of Date Display Format of your Computer for Example on my Computer the date display format is "yyyy/mm/dd" and "1910/2/25" is a correct date but "25/2/1910" is not a correct date
you can change date format from your "Control panel->Regional and language option->Regional options->Customize->Date"
Best regards
0
I am wondering where can i find maskedit?
also i have tried changing the date options but they are correct after following your instructions and it still didnt work
0
I am wondering where can i find maskedit?
also i have tried changing the date options but they are correct after following your instructions and it still didnt work
Dear Friend
1- about MaskEdit you can find it in Aditional palet of Delphi IDE
2- About your problem with date format although I Dont know what is your Data base System (SQLServer , Paradox , Oracle ,...)? but I still think that by seting date format in control panel correctly your program will work properly
you should set "calendar Type" , "Short date format" and "Long Date format" in control panel. I test it on SQLServer Tables and get a good result.
0
The date is now working after following your advice again i did the same thing but it has decided to work.
also i found the mask edit but i cannot see why i would replace dbedit with maskedit? as i cannot link maskedit to my database and what is the advantage of using the maskedit?
0
Dear friend
the usage of DBEdit is for entering data to a table immediately for example when you have a table with ID,FName,LName you can use 3 DBEdit on your form and connect them to tables fields.
with this method if you enter data to DBEdits the data will save to table immediately and it is not necessary to writing any code for inserting or editing data in to table
by this method you can locate to a record (the contents of corrent record fields will be appear in DBEdits) and chage DBEdits values this change replace to Table immediately it is very easy But I don't like that becouse by this method you can not control validation of Entered data Befor Saving to table
I saw that you use SQL Statement for inserting Data to table so I think that you dont need to use DBEdit you can use MaskEdit
The advantage of mask edit is that you can format input data for example you can configur Editmask Property by Typing ####/##/##
for Date Data entry this seting couse that user can not enter alphabet in date position.
MaskEdit can not connect to Database tables but it have meny validation control that you can use it
however using MaskEdit is only an offer and you can use anythig else that is easy for you.
Edited by fayyaz: n/a
0
I was wondering if when using a MaskEdit which i am considering using would i be able to show £#####.## but only select the numbers? like would i select the '£' or would i have to trim it to remove the '£'?
0
I was wondering if when using a MaskEdit which i am considering using would i be able to show £#####.## but only select the numbers? like would i select the '£' or would i have to trim it to remove the '£'?
If you want to show £ in MaskEdit but it don't appear in entered data you must remove it before using entered data for example you can use this Code before using entered data
TempVar:=Trim(MaskEdit1.Text);
TempVar:=Copy(TempVar,2,Length(TempVar)-1);
(TempVar Is a String Variable)
By this Code you can remove £ from entered data.
0
I decided to just use a label and put it to the side as it helps to avoid more errors.
I am getting a problem after using a parameter twice in the program and it keeps giving me an error. the first time it works without a problem but the second time i receive an error telling me that the parameter is imcomplete amongst other reasons which i cannot remember off the top of my head but if you need more information ask. here is the code that is having the problem.
procedure TForm13.Button1Click(Sender: TObject);
begin
dbgrid4.visible := true;
q1.parameters.parambyname('p1').value:='%';
q1.parameters.parambyname('p2').value:='%';
with q1 do
begin
close;
sql.add('Select * FROM StudentDetails ' +
'WHERE StudentFirstNameForeign = :p1 ' +
'AND StudentLastNameForeign = :p2');
parameters.parambyname('p1').value:=edit2.text;
parameters.parambyname('p2').value:=edit3.text;
open;
end;
thanks
0
I decided to just use a label and put it to the side as it helps to avoid more errors.
I am getting a problem after using a parameter twice in the program and it keeps giving me an error. the first time it works without a problem but the second time i receive an error telling me that the parameter is imcomplete amongst other reasons which i cannot remember off the top of my head but if you need more information ask. here is the code that is having the problem.
procedure TForm13.Button1Click(Sender: TObject);
begin
dbgrid4.visible := true;
q1.parameters.parambyname('p1').value:='%';
q1.parameters.parambyname('p2').value:='%';
with q1 do
begin
close;
sql.add('Select * FROM StudentDetails ' +
'WHERE StudentFirstNameForeign = :p1 ' +
'AND StudentLastNameForeign = :p2');
parameters.parambyname('p1').value:=edit2.text;
parameters.parambyname('p2').value:=edit3.text;
open;
end;
thanks
you must add bellow code after Close; and befor sql.add(..
sql.Clear;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.
|
__label__pos
| 0.918518 |
Jump to content
Preencher Campos?
bonucci
Recommended Posts
Boas pessoal, podem me ajudar, aqui o envio do formulario dizme para preencher os campos, mas pelo codigo pareceme tudo bem.
Aqui deixo o codigo
Cumprimentos
PRimeiro o de Enviar:
<?php
$nome=$_POST["nome"];
$entidade=$_POST["empresa"];
$telefone=$_POST["telefone"];
$email=$_POST["email"];
$comentarios=$_POST["comentarios"];
$headers = "From: $email" . "\r\n" .
"Content-type: text/plain; charset=utf-8" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
$to = "[email protected]";
$subject = "Pedido de orçamento - meusite";
$body = "nome: $nome,
empresa: $empresa,
telefone: $telefone,
email: $email,
mensagem: $comentarios";
if (mail( $to , $subject , $body, $headers )) {
echo("$nome, o seu pedido foi enviado com sucesso.<br />
Em breve entraremos em contacto consigo.<br />
Obrigado.");
} else {
echo("$nome, ocorreu um erro no envio do seu pedido.<br />
<br />
Obrigado.");
}
?></p>
</div>
No fim so me diz:
"Preencha os Campos em Falta"
Alguem sabe o que se passa?
Link to post
Share on other sites
<?php
$nome=$_POST["nome"];
$entidade=$_POST["empresa"];
$telefone=$_POST["telefone"];
$email=$_POST["email"];
$comentarios=$_POST["comentarios"];
if (($nome != null) && ($entidade != null) && ($telefone != null) && ($email != null) && ($comentarios != null))
{
include "final_informacoes.php";
}
else
{
$dados=true;
include "informacoes.php";
}
?>
E agora, já deu para perceber?
Link to post
Share on other sites
foi o "else"? Desculpa la pelo meu noob, não sou nenhum ás do php, oq eu costumo fazer em php é mais pelo dreamweaver, e isso faz quase tudo por nos, poderias me dar umas luzes do problema?
Cumprimentos
Link to post
Share on other sites
Não te vou ajudar em nada enquanto não entenderes aquilo a que te chamaram à atenção inicialmente. Usa as tags code, com a linguagem que tens nos blocos de código que vais usar. É difícil ler código todo com a mesma cor, e é para isso que elas servem. Deu para perceber agora?
O dreamweaver é lixo.
Link to post
Share on other sites
Guest
This topic is now closed to further replies.
×
×
• Create New...
Important Information
By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.
|
__label__pos
| 0.655061 |
Google Analytics Simple Bookmark Icon
Google Analytics is a powerful digital tool that allows businesses to track, analyze, and report on their website's traffic and performance to optimize their online strategies.
Last Updated November 13, 2023
Purple to white gradient footer header design
Google Analytics is a free website analytics platform provided by Google that allows you to track, measure, and evaluate various metrics to measure the success of your digital marketing strategies. Keep reading to learn more about Google Analytics!
What is Google Analytics?
Google Analytics is a free website analytics platform for tracking, measuring, and evaluating online traffic, user events, conversions, and more for websites and mobile apps. It’s one of the most popular website SEO analytics tools today. In 2023, Google Analytics 4 replaced Google Analytics.
What is the difference between Google Analytics and Google Analytics 4?
The difference between Google Analytics and Google Analytics 4 is Google Analytics 4 is event-based while Google Analytics is session-based. Google Analytics 4 also provides enhanced, cookie-free user tracking to paint the user journey better.
That’s why this guide on Google Analytics’ definition focuses on Google Analytics 4.
What is Google Analytics used for?
Google Analytics is used for several things, including:
• Measuring traffic and its sources, like organic, paid, and social
• Tracking micro- and macro-conversions, like a newsletter sign-up or product purchase
• Evaluating digital marketing services and their return on investment (ROI)
• Visualizing user journeys based on website interactions
• Proving the value of SEO with useful reports
You can also use Google Analytics to send and share data with other platforms in your tech stack, like your content management system (CMS), customer relationship software (CRM), and reporting tools like Looker (formerly known as Google Data Studio).
How does Google Analytics work?
Google Analytics works via a JavaScript tag, which you can add via Google Tag Manager to your site.
Once installed, Google Analytics works as follows:
1. A user visits a page
2. The tag collects event data, like page visited, traffic source, and more
3. The tag sends that data to Google Analytics for processing
4. The data enters your database and becomes available in Google Analytics
5. You evaluate the data and make data-driven decisions about what’s next
For more information on how to install Google Analytics 4, refer to Google’s official documentation.
Why use Google Analytics?
Google Analytics is worth using for a few reasons, including:
• Measure your online performance
• Improve your understanding of your market’s online journey
• Understand your sources for generating online leads or revenue, like a referral site
• Expand your buyer persona with demographic data, like preferred device
• Tell your business’s marketing story with helpful graphs and dashboards
• Find your drop-off points in the buyer journey and brainstorm solutions
When it comes to what Google Analytics is used for, it’s used for making more informed marketing decisions. Without that website or app analytics data, your business can only make decisions based on what it thinks and not what it knows.
What data is available in Google Analytics?
You’ll find plenty of data in Google Analytics, which falls into one of two categories:
• Metrics, which measure your data, like the number of U.S. users.
• Dimensions, which describe your data, like a user’s location.
Learn more about the data you’ll find in these two hubs below:
Metrics
The most common metrics in Google Analytics include:
• Advertising, like Google Ads clicks, cost per click, and impressions
• Page / screen, like entrances, exits, and views
• Session, like bounce rate, number of sessions, and engagement rate
• Event, like conversions, event value, and events per session
• Search Console, like average search position, clicks, and impressions on Google
Dimensions
The most common dimension groups in Google Analytics include:
• Attributions, like medium, source, and source platform
• Demographics, like age, gender, and interests
• Geography, like city, region, and country
• Video, like video title, video URL, and video source
• Platform / device, like browser, device, and operating system
Learn more about the dimensions available in Google Analytics with Google’s official documentation.
What can you use Google Analytics for?
You can use Google Analytics for several applications. Here are some ideas:
• Create custom dimensions and metrics based on your business’s needs
• Set up custom conversions to measure your online performance
• Measure last month’s organic traffic
• Compare this quarter’s leads to last quarter’s
• Find the top 10 URLs with the highest bounce rate and evaluate
• Determine the highest source of paid traffic based on country
• Research the most common search terms and determine if content needs to be created
• Identify the top referral sources based on new leads
• Evaluate how mobile and desktop user interactions vary
• Investigate the effectiveness of a new landing page, month over month
With the range of data points available in Google Analytics, you won’t get bored with analyzing your data and finding actionable takeaways for you and your team. Your proactive approach will also help you stay ahead of the competition.
Get started with Google Analytics
With Google Analytics, your business can make smarter, more informed decisions about how you market your business online. Setting up Google Analytics 4 can be challenging, though, which is why our award-winning team is here to help.
Contact us today to learn how we can set up and optimize your Google Analytics 4 account!
Don’t fail your website’s most important test
Get an SEO scorecard of your website for free in less than 30 seconds.
|
__label__pos
| 0.795293 |
Editing Ettercap Password Sniffer Engine
I recently started using Ettercap as a Man-in-the-Middle (MITM) tool for testing and sniffing passwords. However, I encountered an issue where I was not able to capture the POST request data containing the ‘usuario’ (user in Spanish) and ‘clave’ (password in Spanish) fields.
After some research, I found a solution that allows me to add these fields to the Ettercap sniffing engine. Here’s how you can do it:
1. Open the etter.fields file. This file is located at /usr/share/ettercap/etter.fields on my system.
2. Inside the file, locate the section that contains the recognized form fields for user and password by the HTTP dissector.
3. Add ‘usuario’ to the ‘[USER]’ field and ‘clave’ to the ‘[PASS]’ field.
4. Save the file and restart Ettercap.
By making this simple modification, you will be able to capture the desired POST request data and sniff passwords effectively.
Remember to use this knowledge responsibly and only on systems that you have proper authorization to test.
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.940828 |
Stats with R and RStudio
Probabilité et statistique pour la biologie (STAT1)
Jacques van Helden
2017-09-12
Scope
In this session we will explore basic manipulations of variables.
R is a calculator
Convention:
Example: compute a simple addition.
2 + 5
[1] 7
Assign a value to a variable
In R <- means “create a variable and assign its value.”
Example:
a <- 2
print(a)
[1] 2
Computing with variables
Example:
b <- 5
c <- a + b
print(c)
[1] 7
Variables need to be updated
Example:
a <- 3 ## Change the value of a
print(c) ## Print the value of c
[1] 7
## Check whether c equals a + b
c == a + b
[1] FALSE
Note: == is used to test whether two variables have the same content.
Updating variable contents
Example:
a <- 27 ## Change the value of a
c <- a + b
print(c) ## Print the value of c
[1] 32
## Check whether c equals a + b
c == a + b
[1] TRUE
Vectors of values
The simplest data structure in R is a vector. In the previous example, the variable a was actually a vector with a single value.
Example: create a variable named three.numbers, and initialize it with a vector with values 27, 12 and 3000.
Tips: - variable names can comprize several parts, separated by dots. - the function c() combines several values into a vector
three.numbers <- c(27,12,3000)
print(three.numbers)
[1] 27 12 3000
Series
The simple way to create a series of numbers. The column operator permits to generate all integer values between two limits.
x <- 0:14
print(x)
[1] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Computing with vectors
R handles vectors in a very convenient way. An operation on a vector applies to all its elements.
x <- 1:10 # Define a series from 1 to 10
print(x)
[1] 1 2 3 4 5 6 7 8 9 10
y <- x^2 # Compute the square of each number
print(y)
[1] 1 4 9 16 25 36 49 64 81 100
Scatter plot
x <- -10:10
y <- x^2
plot(x,y)
Line plot
x <- -10:10
y <- x^2
plot(x,y, type="l")
Variables can also contain strings
# The # symbol allows to insert comments in R code
# Define a vector named "whoami", and
# containing two names
whoami <- c("Denis", "Siméon")
print(whoami) # Comment at the end of a line
[1] "Denis" "Siméon"
String concatenation
# Define a vector named "names", and
# containing two names
whoami <- c("Denis", "Siméon")
# Paste the values of a vector of string
print(paste(sep=" ", whoami[1], whoami[2]))
[1] "Denis Siméon"
Carl’s preferred distribution
The function dpois() computes the Poisson density, i.e. the probability to observe exactly \(x\) successes in a series of independent trials with equal probability.
The Poisson distribution is defined by a single parameter: the expected number of successes \(\lambda\) (read “lambda”).
\[P(X=x) = \frac{e^{-\lambda}\lambda^x}{x!}\]
x <- 0:14 # Define the X values from 0 to 14
y <- dpois(x, lambda = 2.5) # Poisson density
print(y) # Check the result
Plotting the Poisson distribution
x <- 0:14 # Define the X values from 0 to 14
y <- dpois(x, lambda = 2.5) # Poisson density
plot(x,y) # Check the result
This first plot is not very nice. Let us get some help to improve it.
Getting help for R functions
Need help? Type help().
help(plot)
A question? Type ?
?plot
Result: R displays the help message for the function dpois().
Exercise: improve Poisson density plot
1. Do not (yet) look the next slide.
2. Read the help page for the dpois()function.
3. draw a plot that provides a didactic illustration of the Poisson density.
Improve the plot: type = histogram
x <- 0:14
lambda <- 2.54
y <- dpois(x, lambda)
plot(x,y, type="h")
|
__label__pos
| 0.825789 |
Blame view
matlab/bsq2tensorflow.m 354 Bytes
33171769 David Mayerich added hsiproc to ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function T = bsq2tensorflow(I, n)
sx = size(I, 1);
sy = size(I, 2) / n; %get the size of the tensor along Y
sb = size(I, 3);
T = zeros(sx * sy * sb, n); %allocate space for the output matrix
for i = 0:n-1
ti = I(:, i * sy + 1 : i * sy + sy, :);
T(:, i+1) = ti(:);
end
end
|
__label__pos
| 0.731087 |
Date Histogram Aggregation - decade interval
Can anybody explain how and if it is possible to build a decade interval with date histogram aggregation?
I tried interval 10y which isn't supported. As possible solution used 3650d as interval which seems to work but not completely.
Here is my agg:
"decades": {
"date_histogram": {
"field": "bc_dat",
"interval": "3650d",
"format": "dd.MM.yyyy"
}
}
and here are some results:
"decades": {
"buckets": [
{
"key_as_string": "06.01.1950",
"key": -630720000000,
"doc_count": 20
},
{
"key_as_string": "04.01.1960",
"key": -315360000000,
"doc_count": 100
},
{
"key_as_string": "01.01.1970",
"key": 0,
"doc_count": 166
},
{
"key_as_string": "30.12.1979",
"key": 315360000000,
"doc_count": 547
},
{
"key_as_string": "27.12.1989",
"key": 630720000000,
"doc_count": 669
},
{
"key_as_string": "25.12.1999",
"key": 946080000000,
"doc_count": 842
},
{
"key_as_string": "22.12.2009",
"key": 1261440000000,
"doc_count": 108
}
]
}
as you can see it works until 01.01.1970 but afterwards ist gets e.g. 1979 and 1989 instead of 1980 and 1990. Any ideas how to solve this?
It's sadly not doable ATM: https://github.com/elastic/elasticsearch/issues/8939
What I'm doing in that case is doing that on the client side. So I build aggs per year and aggregate on client.
Works well but if you need to have sub aggs that becomes tricky...
1 Like
:pensive:
anyway thank's for your fast response
|
__label__pos
| 0.999758 |
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
# 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/.
from __future__ import absolute_import, print_function
import codecs
import fnmatch
import io
import json
import os
import shutil
import sys
import types
from six import string_types, StringIO
from .ini import read_ini
from .filters import (
DEFAULT_FILTERS,
enabled,
exists as _exists,
filterlist,
)
__all__ = ['ManifestParser', 'TestManifest', 'convert']
relpath = os.path.relpath
# path normalization
def normalize_path(path):
"""normalize a relative path"""
if sys.platform.startswith('win'):
return path.replace('/', os.path.sep)
return path
def denormalize_path(path):
"""denormalize a relative path"""
if sys.platform.startswith('win'):
return path.replace(os.path.sep, '/')
return path
# objects for parsing manifests
class ManifestParser(object):
"""read .ini manifests"""
def __init__(self, manifests=(), defaults=None, strict=True, rootdir=None,
finder=None, handle_defaults=True):
"""Creates a ManifestParser from the given manifest files.
:param manifests: An iterable of file paths or file objects corresponding
to manifests. If a file path refers to a manifest file that
does not exist, an IOError is raised.
:param defaults: Variables to pre-define in the environment for evaluating
expressions in manifests.
:param strict: If False, the provided manifests may contain references to
listed (test) files that do not exist without raising an
IOError during reading, and certain errors in manifests
are not considered fatal. Those errors include duplicate
section names, redefining variables, and defining empty
variables.
:param rootdir: The directory used as the basis for conversion to and from
relative paths during manifest reading.
:param finder: If provided, this finder object will be used for filesystem
interactions. Finder objects are part of the mozpack package,
documented at
http://firefox-source-docs.mozilla.org/python/mozpack.html#module-mozpack.files
:param handle_defaults: If not set, do not propagate manifest defaults to individual
test objects. Callers are expected to manage per-manifest
defaults themselves via the manifest_defaults member
variable in this case.
"""
self._defaults = defaults or {}
self.tests = []
self.manifest_defaults = {}
self.source_files = set()
self.strict = strict
self.rootdir = rootdir
self._root = None
self.finder = finder
self._handle_defaults = handle_defaults
if manifests:
self.read(*manifests)
def path_exists(self, path):
if self.finder:
return self.finder.get(path) is not None
return os.path.exists(path)
@property
def root(self):
if not self._root:
if self.rootdir is None:
self._root = ""
else:
assert os.path.isabs(self.rootdir)
self._root = self.rootdir + os.path.sep
return self._root
def relative_to_root(self, path):
# Microoptimization, because relpath is quite expensive.
# We know that rootdir is an absolute path or empty. If path
# starts with rootdir, then path is also absolute and the tail
# of the path is the relative path (possibly non-normalized,
# when here is unknown).
# For this to work rootdir needs to be terminated with a path
# separator, so that references to sibling directories with
# a common prefix don't get misscomputed (e.g. /root and
# /rootbeer/file).
# When the rootdir is unknown, the relpath needs to be left
# unchanged. We use an empty string as rootdir in that case,
# which leaves relpath unchanged after slicing.
if path.startswith(self.root):
return path[len(self.root):]
else:
return relpath(path, self.root)
# methods for reading manifests
def _read(self, root, filename, defaults, parentmanifest=None):
"""
Internal recursive method for reading and parsing manifests.
Stores all found tests in self.tests
:param root: The base path
:param filename: File object or string path for the base manifest file
:param defaults: Options that apply to all items
:param parentmanifest: Filename of the parent manifest, relative to rootdir (default None)
"""
def read_file(type):
include_file = section.split(type, 1)[-1]
include_file = normalize_path(include_file)
if not os.path.isabs(include_file):
include_file = os.path.join(here, include_file)
if not self.path_exists(include_file):
message = "Included file '%s' does not exist" % include_file
if self.strict:
raise IOError(message)
else:
sys.stderr.write("%s\n" % message)
return
return include_file
# get directory of this file if not file-like object
if isinstance(filename, string_types):
# If we're using mercurial as our filesystem via a finder
# during manifest reading, the getcwd() calls that happen
# with abspath calls will not be meaningful, so absolute
# paths are required.
if self.finder:
assert os.path.isabs(filename)
filename = os.path.abspath(filename)
filename_rel = self.relative_to_root(filename)
self.source_files.add(filename)
if self.finder:
fp = codecs.getreader('utf-8')(self.finder.get(filename).open())
else:
fp = io.open(filename, encoding='utf-8')
here = os.path.dirname(filename)
else:
fp = filename
filename = here = None
filename_rel = None
defaults['here'] = here
# read the configuration
sections, defaults = read_ini(fp=fp, defaults=defaults, strict=self.strict,
handle_defaults=self._handle_defaults)
if parentmanifest and filename:
# A manifest can be read multiple times, via "include:", optionally
# with section-specific variables. These variables only apply to
# the included manifest when included via the same parent manifest,
# so they must be associated with (parentmanifest, filename).
#
# |defaults| is a combination of variables, in the following order:
# - The defaults of the ancestor manifests if self._handle_defaults
# is True.
# - Any variables from the "[include:...]" section.
# - The defaults of the included manifest.
self.manifest_defaults[(parentmanifest, filename)] = defaults
else:
self.manifest_defaults[filename] = defaults
# get the tests
for section, data in sections:
# a file to include
# TODO: keep track of included file structure:
# self.manifests = {'manifest.ini': 'relative/path.ini'}
if section.startswith('include:'):
include_file = read_file('include:')
if include_file:
include_defaults = data.copy()
self._read(root, include_file, include_defaults, parentmanifest=filename_rel)
continue
# otherwise an item
test = data.copy()
test['name'] = section
# Will be None if the manifest being read is a file-like object.
test['manifest'] = filename
test['manifest_relpath'] = None
if filename:
test['manifest_relpath'] = filename_rel
# determine the path
path = test.get('path', section)
_relpath = path
if '://' not in path: # don't futz with URLs
path = normalize_path(path)
if here and not os.path.isabs(path):
# Profiling indicates 25% of manifest parsing is spent
# in this call to normpath, but almost all calls return
# their argument unmodified, so we avoid the call if
# '..' if not present in the path.
path = os.path.join(here, path)
if '..' in path:
path = os.path.normpath(path)
_relpath = self.relative_to_root(path)
test['path'] = path
test['relpath'] = _relpath
if parentmanifest is not None:
# If a test was included by a parent manifest we may need to
# indicate that in the test object for the sake of identifying
# a test, particularly in the case a test file is included by
# multiple manifests.
test['ancestor_manifest'] = parentmanifest
# append the item
self.tests.append(test)
def read(self, *filenames, **defaults):
"""
read and add manifests from file paths or file-like objects
filenames -- file paths or file-like objects to read as manifests
defaults -- default variables
"""
# ensure all files exist
missing = [filename for filename in filenames
if isinstance(filename, string_types) and not self.path_exists(filename)]
if missing:
raise IOError('Missing files: %s' % ', '.join(missing))
# default variables
_defaults = defaults.copy() or self._defaults.copy()
_defaults.setdefault('here', None)
# process each file
for filename in filenames:
# set the per file defaults
defaults = _defaults.copy()
here = None
if isinstance(filename, string_types):
here = os.path.dirname(os.path.abspath(filename))
defaults['here'] = here # directory of master .ini file
if self.rootdir is None:
# set the root directory
# == the directory of the first manifest given
self.rootdir = here
self._read(here, filename, defaults)
# methods for querying manifests
def query(self, *checks, **kw):
"""
general query function for tests
- checks : callable conditions to test if the test fulfills the query
"""
tests = kw.get('tests', None)
if tests is None:
tests = self.tests
retval = []
for test in tests:
for check in checks:
if not check(test):
break
else:
retval.append(test)
return retval
def get(self, _key=None, inverse=False, tags=None, tests=None, **kwargs):
# TODO: pass a dict instead of kwargs since you might hav
# e.g. 'inverse' as a key in the dict
# TODO: tags should just be part of kwargs with None values
# (None == any is kinda weird, but probably still better)
# fix up tags
if tags:
tags = set(tags)
else:
tags = set()
# make some check functions
if inverse:
def has_tags(test):
return not tags.intersection(test.keys())
def dict_query(test):
for key, value in list(kwargs.items()):
if test.get(key) == value:
return False
return True
else:
def has_tags(test):
return tags.issubset(test.keys())
def dict_query(test):
for key, value in list(kwargs.items()):
if test.get(key) != value:
return False
return True
# query the tests
tests = self.query(has_tags, dict_query, tests=tests)
# if a key is given, return only a list of that key
# useful for keys like 'name' or 'path'
if _key:
return [test[_key] for test in tests]
# return the tests
return tests
def manifests(self, tests=None):
"""
return manifests in order in which they appear in the tests
If |tests| is not set, the order of the manifests is unspecified.
"""
if tests is None:
manifests = []
# Make sure to return all the manifests, even ones without tests.
for manifest in list(self.manifest_defaults.keys()):
if isinstance(manifest, tuple):
parentmanifest, manifest = manifest
if manifest not in manifests:
manifests.append(manifest)
return manifests
manifests = []
for test in tests:
manifest = test.get('manifest')
if not manifest:
continue
if manifest not in manifests:
manifests.append(manifest)
return manifests
def paths(self):
return [i['path'] for i in self.tests]
# methods for auditing
def missing(self, tests=None):
"""
return list of tests that do not exist on the filesystem
"""
if tests is None:
tests = self.tests
existing = list(_exists(tests, {}))
return [t for t in tests if t not in existing]
def check_missing(self, tests=None):
missing = self.missing(tests=tests)
if missing:
missing_paths = [test['path'] for test in missing]
if self.strict:
raise IOError("Strict mode enabled, test paths must exist. "
"The following test(s) are missing: %s" %
json.dumps(missing_paths, indent=2))
print("Warning: The following test(s) are missing: %s" %
json.dumps(missing_paths, indent=2), file=sys.stderr)
return missing
def verifyDirectory(self, directories, pattern=None, extensions=None):
"""
checks what is on the filesystem vs what is in a manifest
returns a 2-tuple of sets:
(missing_from_filesystem, missing_from_manifest)
"""
files = set([])
if isinstance(directories, string_types):
directories = [directories]
# get files in directories
for directory in directories:
for dirpath, dirnames, filenames in os.walk(directory, topdown=True):
# only add files that match a pattern
if pattern:
filenames = fnmatch.filter(filenames, pattern)
# only add files that have one of the extensions
if extensions:
filenames = [filename for filename in filenames
if os.path.splitext(filename)[-1] in extensions]
files.update([os.path.join(dirpath, filename) for filename in filenames])
paths = set(self.paths())
missing_from_filesystem = paths.difference(files)
missing_from_manifest = files.difference(paths)
return (missing_from_filesystem, missing_from_manifest)
# methods for output
def write(self, fp=sys.stdout, rootdir=None,
global_tags=None, global_kwargs=None,
local_tags=None, local_kwargs=None):
"""
write a manifest given a query
global and local options will be munged to do the query
globals will be written to the top of the file
locals (if given) will be written per test
"""
# open file if `fp` given as string
close = False
if isinstance(fp, string_types):
fp = open(fp, 'w')
close = True
# root directory
if rootdir is None:
rootdir = self.rootdir
# sanitize input
global_tags = global_tags or set()
local_tags = local_tags or set()
global_kwargs = global_kwargs or {}
local_kwargs = local_kwargs or {}
# create the query
tags = set([])
tags.update(global_tags)
tags.update(local_tags)
kwargs = {}
kwargs.update(global_kwargs)
kwargs.update(local_kwargs)
# get matching tests
tests = self.get(tags=tags, **kwargs)
# print the .ini manifest
if global_tags or global_kwargs:
print('[DEFAULT]', file=fp)
for tag in global_tags:
print('%s =' % tag, file=fp)
for key, value in list(global_kwargs.items()):
print('%s = %s' % (key, value), file=fp)
print(file=fp)
for test in tests:
test = test.copy() # don't overwrite
path = test['name']
if not os.path.isabs(path):
path = test['path']
if self.rootdir:
path = relpath(test['path'], self.rootdir)
path = denormalize_path(path)
print('[%s]' % path, file=fp)
# reserved keywords:
reserved = [
'path',
'name',
'here',
'manifest',
'manifest_relpath',
'relpath',
'ancestor_manifest'
]
for key in sorted(test.keys()):
if key in reserved:
continue
if key in global_kwargs:
continue
if key in global_tags and not test[key]:
continue
print('%s = %s' % (key, test[key]), file=fp)
print(file=fp)
if close:
# close the created file
fp.close()
def __str__(self):
fp = StringIO()
self.write(fp=fp)
value = fp.getvalue()
return value
def copy(self, directory, rootdir=None, *tags, **kwargs):
"""
copy the manifests and associated tests
- directory : directory to copy to
- rootdir : root directory to copy to (if not given from manifests)
- tags : keywords the tests must have
- kwargs : key, values the tests must match
"""
# XXX note that copy does *not* filter the tests out of the
# resulting manifest; it just stupidly copies them over.
# ideally, it would reread the manifests and filter out the
# tests that don't match *tags and **kwargs
# destination
if not os.path.exists(directory):
os.path.makedirs(directory)
else:
# sanity check
assert os.path.isdir(directory)
# tests to copy
tests = self.get(tags=tags, **kwargs)
if not tests:
return # nothing to do!
# root directory
if rootdir is None:
rootdir = self.rootdir
# copy the manifests + tests
manifests = [relpath(manifest, rootdir) for manifest in self.manifests()]
for manifest in manifests:
destination = os.path.join(directory, manifest)
dirname = os.path.dirname(destination)
if not os.path.exists(dirname):
os.makedirs(dirname)
else:
# sanity check
assert os.path.isdir(dirname)
shutil.copy(os.path.join(rootdir, manifest), destination)
missing = self.check_missing(tests)
tests = [test for test in tests if test not in missing]
for test in tests:
if os.path.isabs(test['name']):
continue
source = test['path']
destination = os.path.join(directory, relpath(test['path'], rootdir))
shutil.copy(source, destination)
# TODO: ensure that all of the tests are below the from_dir
def update(self, from_dir, rootdir=None, *tags, **kwargs):
"""
update the tests as listed in a manifest from a directory
- from_dir : directory where the tests live
- rootdir : root directory to copy to (if not given from manifests)
- tags : keys the tests must have
- kwargs : key, values the tests must match
"""
# get the tests
tests = self.get(tags=tags, **kwargs)
# get the root directory
if not rootdir:
rootdir = self.rootdir
# copy them!
for test in tests:
if not os.path.isabs(test['name']):
_relpath = relpath(test['path'], rootdir)
source = os.path.join(from_dir, _relpath)
if not os.path.exists(source):
message = "Missing test: '%s' does not exist!"
if self.strict:
raise IOError(message)
print(message + " Skipping.", file=sys.stderr)
continue
destination = os.path.join(rootdir, _relpath)
shutil.copy(source, destination)
# directory importers
@classmethod
def _walk_directories(cls, directories, callback, pattern=None, ignore=()):
"""
internal function to import directories
"""
if isinstance(pattern, string_types):
patterns = [pattern]
else:
patterns = pattern
ignore = set(ignore)
if not patterns:
def accept_filename(filename):
return True
else:
def accept_filename(filename):
for pattern in patterns:
if fnmatch.fnmatch(filename, pattern):
return True
if not ignore:
def accept_dirname(dirname):
return True
else:
def accept_dirname(dirname):
return dirname not in ignore
rootdirectories = directories[:]
seen_directories = set()
for rootdirectory in rootdirectories:
# let's recurse directories using list
directories = [os.path.realpath(rootdirectory)]
while directories:
directory = directories.pop(0)
if directory in seen_directories:
# eliminate possible infinite recursion due to
# symbolic links
continue
seen_directories.add(directory)
files = []
subdirs = []
for name in sorted(os.listdir(directory)):
path = os.path.join(directory, name)
if os.path.isfile(path):
# os.path.isfile follow symbolic links, we don't
# need to handle them here.
if accept_filename(name):
files.append(name)
continue
elif os.path.islink(path):
# eliminate symbolic links
path = os.path.realpath(path)
# we must have a directory here
if accept_dirname(name):
subdirs.append(name)
# this subdir is added for recursion
directories.insert(0, path)
# here we got all subdirs and files filtered, we can
# call the callback function if directory is not empty
if subdirs or files:
callback(rootdirectory, directory, subdirs, files)
@classmethod
def populate_directory_manifests(cls, directories, filename, pattern=None, ignore=(),
overwrite=False):
"""
walks directories and writes manifests of name `filename` in-place;
returns `cls` instance populated with the given manifests
filename -- filename of manifests to write
pattern -- shell pattern (glob) or patterns of filenames to match
ignore -- directory names to ignore
overwrite -- whether to overwrite existing files of given name
"""
manifest_dict = {}
if os.path.basename(filename) != filename:
raise IOError("filename should not include directory name")
# no need to hit directories more than once
_directories = directories
directories = []
for directory in _directories:
if directory not in directories:
directories.append(directory)
def callback(directory, dirpath, dirnames, filenames):
"""write a manifest for each directory"""
manifest_path = os.path.join(dirpath, filename)
if (dirnames or filenames) and not (os.path.exists(manifest_path) and overwrite):
with open(manifest_path, 'w') as manifest:
for dirname in dirnames:
print('[include:%s]' % os.path.join(dirname, filename), file=manifest)
for _filename in filenames:
print('[%s]' % _filename, file=manifest)
# add to list of manifests
manifest_dict.setdefault(directory, manifest_path)
# walk the directories to gather files
cls._walk_directories(directories, callback, pattern=pattern, ignore=ignore)
# get manifests
manifests = [manifest_dict[directory] for directory in _directories]
# create a `cls` instance with the manifests
return cls(manifests=manifests)
@classmethod
def from_directories(cls, directories, pattern=None, ignore=(), write=None, relative_to=None):
"""
convert directories to a simple manifest; returns ManifestParser instance
pattern -- shell pattern (glob) or patterns of filenames to match
ignore -- directory names to ignore
write -- filename or file-like object of manifests to write;
if `None` then a StringIO instance will be created
relative_to -- write paths relative to this path;
if false then the paths are absolute
"""
# determine output
opened_manifest_file = None # name of opened manifest file
absolute = not relative_to # whether to output absolute path names as names
if isinstance(write, string_types):
opened_manifest_file = write
write = open(write, 'w')
if write is None:
write = StringIO()
# walk the directories, generating manifests
def callback(directory, dirpath, dirnames, filenames):
# absolute paths
filenames = [os.path.join(dirpath, filename)
for filename in filenames]
# ensure new manifest isn't added
filenames = [filename for filename in filenames
if filename != opened_manifest_file]
# normalize paths
if not absolute and relative_to:
filenames = [relpath(filename, relative_to)
for filename in filenames]
# write to manifest
write_content = '\n'.join([
'[{}]'.format(denormalize_path(filename)) for filename in filenames
])
print(write_content, file=write)
cls._walk_directories(directories, callback, pattern=pattern, ignore=ignore)
if opened_manifest_file:
# close file
write.close()
manifests = [opened_manifest_file]
else:
# manifests/write is a file-like object;
# rewind buffer
write.flush()
write.seek(0)
manifests = [write]
# make a ManifestParser instance
return cls(manifests=manifests)
convert = ManifestParser.from_directories
class TestManifest(ManifestParser):
"""
apply logic to manifests; this is your integration layer :)
specific harnesses may subclass from this if they need more logic
"""
def __init__(self, *args, **kwargs):
ManifestParser.__init__(self, *args, **kwargs)
self.filters = filterlist(DEFAULT_FILTERS)
self.last_used_filters = []
def active_tests(self, exists=True, disabled=True, filters=None, **values):
"""
Run all applied filters on the set of tests.
:param exists: filter out non-existing tests (default True)
:param disabled: whether to return disabled tests (default True)
:param values: keys and values to filter on (e.g. `os = linux mac`)
:param filters: list of filters to apply to the tests
:returns: list of test objects that were not filtered out
"""
tests = [i.copy() for i in self.tests] # shallow copy
# mark all tests as passing
for test in tests:
test['expected'] = test.get('expected', 'pass')
# make a copy so original doesn't get modified
fltrs = self.filters[:]
if exists:
if self.strict:
self.check_missing(tests)
else:
fltrs.append(_exists)
if not disabled:
fltrs.append(enabled)
if filters:
fltrs += filters
self.last_used_filters = fltrs[:]
for fn in fltrs:
tests = fn(tests, values)
return list(tests)
def test_paths(self):
return [test['path'] for test in self.active_tests()]
def fmt_filters(self, filters=None):
filters = filters or self.last_used_filters
names = []
for f in filters:
if isinstance(f, types.FunctionType):
names.append(f.__name__)
else:
names.append(str(f))
return ', '.join(names)
|
__label__pos
| 0.918952 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I'm having a hard time getting a filter working. I'm roughly following the example at http://www.knockmeout.net/2011/06/10-things-to-know-about-knockoutjs-on.html, but I just can't seem to make it work. Any help is greatly appreciated.
HTML:
<h1><b>Medical Product Survey</b></h1>
<div class='facilities available'>
<div class='bar'>
<h2>Hospitals / Facilities</h2>
<a class='button add'>+</a>
</div>
<table>
<thead>
<tr>
<th>
<input data-bind="value: filter, valueUpdate: 'afterkeydown'" />
</th>
<th>Modified</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="template: { name: 'facilitiesAvailableRow', foreach: filteredFacilties }"></tbody>
</table>
<!-- Row template for available facilities -->
<script type="text/html" id="facilitiesAvailableRow">
<tr>
<td>${name}</td>
<td>${modified}</td>
<td>${status}</td>
</tr>
</script>
</div>
<div class='facilities available'>
<div class='bar'>
<h2>Archived</h2>
</div>
<table>
<thead>
<tr>
<th><input type='search' id='facility_search' /></th>
<th>Archive Date</th>
<th>Size</th>
<th></th>
</tr>
</thead>
<tbody data-bind="template: { name: 'facilitiesArchivedRow', foreach: facilitiesArchived }"></tbody>
</table>
<!-- Row template for available facilities -->
<script type="text/html" id="facilitiesArchivedRow">
<tr>
<td>${name}</td>
<td>${modified}</td>
<td>${size}mb</td>
<td><input type='button' value='restore' /></td>
</tr>
</script>
</div>
Javascript:
//Model for facilities interaction on the front page.
var viewModel = {
facilitiesAvailable: ko.observableArray([
{ name: "Test 1", modified: "1/20/1986", status: "Good to go" },
{ name: "Test 2", modified: "1/21/1987", status: "Good to go2" },
{ name: "Test 3", modified: "1/22/1988", status: "Good to go3" },
{ name: "Test 4", modified: "1/23/1989", status: "Good to go4" },
{ name: "Test 5", modified: "1/24/1990", status: "Good to go5" }
]),
facilitiesArchived: ko.observableArray([
{ name: "Archive 1", modified: "1/20/1982", size: 123 },
{ name: "Archive 2", modified: "1/21/1983", size: 198 },
{ name: "Archive 3", modified: "1/22/1984", size: 340 }
]),
filter: ko.observable(""),
};
//Filtering.
viewModel.filteredFacilities = ko.dependentObservable(function() {
var filter = this.filter().toLowerCase();
if(!filter) {
return this.facilitiesAvailable();
} else {
return ko.utils.arrayFilter(this.facilitiesAvailable(), function(item) {
if(item.name.toLowerCase().search(filter) != -1) {
return true;
}
});
}
}, viewModel);
ko.applyBindings(viewModel);
The error I'm getting is:
Uncaught Error: Unable to parse binding attribute.
Message: ReferenceError: filteredFacilties is not defined;
Attribute value: template: { name: 'facilitiesAvailableRow', foreach: filteredFacilties }
share|improve this question
I was looking for a way to do filtering with knockout and your example spelled it out perfectly. Thanks! I hadn't realized that simply accessing an observable variable inside a ko.computed would cause the ko.computed to re-evaluate when the observable changed. – Greg Feb 27 '12 at 9:00
add comment
1 Answer
up vote 6 down vote accepted
You misspelled filteredFacilties. It should be filteredFacilities in your template binding.
Change:
data-bind="template: { name: 'facilitiesAvailableRow', foreach: filteredFacilties }"
to:
data-bind="template: { name: 'facilitiesAvailableRow', foreach: filteredFacilities }"
share|improve this answer
Wow, I can't believe I missed that. Thanks for the quick help. – Jack Slingerland Sep 13 '11 at 19:20
1
@Jack - glad I can help! – Sean Vieira Sep 13 '11 at 19:21
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.540945 |
Create a gist now
Instantly share code, notes, and snippets.
Embed
What would you like to do?
ODE example
// Build with: clang++ -Wall -I . -isystem lib/eigen_3.3.3 -isystem lib/boost_1.64.0 -isystem lib/cvodes_2.9.0/include -std=c++1y -DBOOST_RESULT_OF_USE_TR1 -DBOOST_NO_DECLTYPE -DBOOST_DISABLE_ASSERTS -Wno-unused-function -Wno-uninitialized -DNO_FPRINTF_OUTPUT -pipe test2.cpp -O3 -o test2 lib/cvodes_2.9.0/lib/libsundials_nvecserial.a lib/cvodes_2.9.0/lib/libsundials_cvodes.a
#include <iostream>
#include "stan/math.hpp"
using namespace stan::math;
// This is a 1D diffusion PDE with a spatially varying diffusion coefficient.
// So if the domain is like this:
// x--o--x--o--x--o--x
// Then diffusion coefficients are defined at the xs and the state is at the o
// values. This is an N = 3 system. There are N + 1 parameters.
template<typename T1, typename T2>
std::vector<typename stan::return_type<T1, T2>::type > ode(const double& t,
const std::vector<T1>& u,
const std::vector<T2>& D,
const std::vector<double>& x_r,
const std::vector<int>& x_i,
std::ostream* pstream) {
int N = u.size();
std::vector<typename stan::return_type<T1, T2>::type > dudt(N, 0.0);
double dx = x_r[0];
dudt[0] = (D[1] * (u[1] - u[0]) - D[0] * (u[0] - 1.0)) / (dx * dx);
dudt[N - 1] = (D[N] * (1.0 - u[N - 1]) - D[N - 1] * (u[N - 1] - u[N - 2])) / (dx * dx);
for(int i = 1; i < N - 1; i++) {
dudt[i] = (D[i + 1] * (u[i + 1] - u[i]) - D[i] * (u[i] - u[i - 1])) / (dx * dx);
}
return dudt;
}
struct ode_functor {
template<typename T1, typename T2>
std::vector<typename stan::return_type<T1, T2>::type > operator()(const double& t,
const std::vector<T1>& state,
const std::vector<T2>& theta,
const std::vector<double>& x_r,
const std::vector<int>& x_i,
std::ostream* pstream__) const {
return ode(t, state, theta, x_r, x_i, pstream__);
}
};
int main(int argc, char **argv) {
std::ostream pstream(std::cout.rdbuf());
int N = 20;
double dx = 1.0 / N;
for(int j = 0; j < 100; j++) {
std::vector<var> D;
std::vector<var> y0;
std::vector<double> ts;
std::vector<double> x_r = { dx };
std::vector<int> x_i;
for(int i = 0; i < N; i++) {
y0.push_back(0.0);
D.push_back(1.0e-3);
}
D.push_back(1.0e-3);
// Start with a delta in the leftmost point of space
y0[0] = 100.0;
//for(int i = 0; i < 10; i++)
// ts.push_back((i + 1) * 1.0);
ts.push_back(10.0);
std::vector<std::vector<var> > y = integrate_ode_bdf(ode_functor(),
y0,
0.0,
ts,
D,
x_r,
x_i,
&pstream);
// Make our output just the sum of everything
var sum = 0.0;
for(int i = 0; i < ts.size(); i++) {
for(int j = 0; j < y[i].size(); j++) {
sum += y[i][j];
}
}
sum.grad();
for(int i = 0; i < D.size(); i++)
std::cout << D[i].adj() << " ";
std::cout << std::endl;
//print_stack(pstream);
set_zero_all_adjoints();
recover_memory(); // Not really haha!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
|
__label__pos
| 0.996241 |
Blog Archive
RPGLE string manipulation - find and replace using %replace() and %scan()
%REPLACE returns the character string produced by inserting a replacement string into the source string, starting at the start position and replacing the specified number of characters.
%REPLACE(replacement string: source string{:start position {:source
length to replace}})
%SCAN returns the first position of the search argument in the source string, or 0 if it was not found. If the start position is specified, the search begins at the starting position. The result is always the position in the source string even if the starting position is specified. The starting position defaults to 1.
%SCAN(search argument : source string {: start})
Just doing a replace with a string data is fun to learn but not practical. In daily use we have to find something and then replace that with a new string data. To achieve that we need the help of two BIFs %replace() and %scan().
Simple Find and Replace
d $string_data s 52a
d $scan_data s 10a inz('&')
d $replace_data s 10a inz('&')
d $pos s 10i 0
/free
$string_data = 'Drink water & juice, Drink water & juice!';
$pos = %scan(%trim($scan_data):$string_data);
if ($pos > 0);
$string_data = %replace( %trim($replace_data)
: $string_data
: $pos
: %len(%trim($scan_data)));
dsply $string_data;
//Drink water & juice, Drink water & juice!
endif;
*inlr = *on;
/end-free
There is still an issue with the above code. The character "&" is twice in there and it will only replace the first instance. We have to modify the above code to put in a loop.
Find and Replace All
$pos = 1;
$string_data = 'Drink water & juice, Drink water & juice!';
dou $pos <= 0;
$pos = %scan(%trim($scan_data):$string_data:$pos);
if ($pos = 0);
leave;
endif;
$string_data = %replace( %trim($replace_data)
: $string_data
: $pos
: %len(%trim($scan_data)));
if ($pos + %len(%trim($replace_data)) > %len($string_data));
leave;
endif;
enddo;
dsply $string_data;
//Drink water & juice, Drink water & juice!
This loop scans for the "&" string, and when it finds that string, it replaces that with "&" and then it continues to do the same for the resulting string until there is nothing left to replace.
%REPLACE()
• The first and second parameter must be of type character, graphic, or UCS-2 and can be in either fixed- or variable-length format. The second parameter must be the same type as the first.
• The third parameter represents the starting position, measured in characters, for the replacement string. If it is not specified, the starting position is at the beginning of the source string. The value may range from one to the current length of the source string plus one.
• The fourth parameter represents the number of characters in the source string to be replaced. If zero is specified, then the replacement string is inserted before the specified starting position. If the parameter is not specified, the number of characters replaced is the same as the length of the replacement string. The value must be greater than or equal to zero, and less than or equal to the current length of the source string.
• The starting position and length may be any numeric value or numeric expression with no decimal positions.
• The returned value is varying length if the source string or replacement string are varying length, or if the start position or source length to replace are variables. Otherwise, the result is fixed length.
%SCAN()
• The first parameter must be of type character, graphic, or UCS-2. The second parameter must be the same type as the first parameter. The third parameter, if specified, must be numeric with zero decimal positions.
• When any parameter is variable in length, the values of the other parameters are checked against the current length, not the maximum length.
• The type of the return value is unsigned integer. This built-in function can be used anywhere that an unsigned integer expression is valid.
4 comments :
1. You may want to increment the $pos position after the %replace so you do not find the & in & again on the next loop after the first replacement.
ReplyDelete
2. What Bob said - this will loop otherwise, building the resultant string up...
Drink water &amp;amp;.....
ReplyDelete
3. For me, work this:
// add a counter
d $pos1 s 10i 0
...
$pos = 1;
$pos1 = 1;
dou $pos <= 0;
$pos = %scan(%trim($scan_data):$string_data:$pos1);
if ($pos = 0);
leave;
endif;
// increase the counter by lenght of replace data
$pos1 = $pos + 4;
$string_data = %replace( %trim($replace_data)
: $string_data
: $pos
: %len(%trim($scan_data)));
enddo;
dsply $string_data;
...
Luca
ReplyDelete
|
__label__pos
| 0.544633 |
PageRenderTime 127ms CodeModel.GetById 95ms RepoModel.GetById 0ms app.codeStats 1ms
/libgxim/gximprotocol10.c
https://bitbucket.org/tagoh/libgxim
C | 2304 lines | 1902 code | 315 blank | 87 comment | 103 complexity | ac0a6a7fcfec031a91c1c6c2107b1687 MD5 | raw file
Possible License(s): LGPL-2.1
1. /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2. /*
3. * gximprotocol10.c
4. * Copyright (C) 2008-2011 Akira TAGOH
5. *
6. * Authors:
7. * Akira TAGOH <[email protected]>
8. *
9. * This library is free software; you can redistribute it and/or
10. * modify it under the terms of the GNU Lesser General Public
11. * License as published by the Free Software Foundation; either
12. * version 2 of the License, or (at your option) any later version.
13. *
14. * This library is distributed in the hope that it will be useful,
15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17. * Lesser General Public License for more details.
18. *
19. * You should have received a copy of the GNU Lesser General Public
20. * License along with this library; if not, write to the
21. * Free Software Foundation, Inc., 51 Franklin Street, Fifth
22. * Floor, Boston, MA 02110-1301 USA
23. */
24. #ifdef HAVE_CONFIG_H
25. #include "config.h"
26. #endif
27. #ifdef HAVE_STRING_H
28. #include <string.h>
29. #endif
30. #include <gdk/gdkkeysyms.h>
31. #include <gio/gio.h>
32. #include "gximattr.h"
33. #include "gximconnection.h"
34. #include "gximsrvconn.h"
35. #include "gximmarshal.h"
36. #include "gximmessages.h"
37. #include "gximmisc.h"
38. #include "gximprotocol.h"
39. #include "gximprotocol10.h"
40. #define PROTO_ERROR(_m_,_n_) (g_xim_protocol_raise_parser_error(proto, G_ ## _m_, (_n_), 0, 0))
41. #define PROTO_ERROR_IM(_m_,_n_,_imid_) (g_xim_protocol_raise_parser_error(proto, G_ ##_m_, (_n_), (_imid_), 0))
42. #define PROTO_ERROR_IMIC(_m_,_n_,_imid_,_icid_) (g_xim_protocol_raise_parser_error(proto, G_ ##_m_, (_n_), (_imid_), (_icid_)))
43. #define SIG_NOIMPL(_s_) (g_xim_protocol10_closure_signal_no_impl(proto, #_s_, G_XIM_EMASK_NO_VALID_ID, 0, 0))
44. #define SIG_NOIMPL_IM(_s_,_imid_) (g_xim_protocol10_closure_signal_no_impl(proto, #_s_, G_XIM_EMASK_VALID_IMID, (_imid_), 0))
45. #define SIG_NOIMPL_IMIC(_s_,_imid_,_icid_) (g_xim_protocol10_closure_signal_no_impl(proto, #_s_, G_XIM_EMASK_VALID_IMID|G_XIM_EMASK_VALID_ICID, (_imid_), (_icid_)))
46. #define MSG_NOIMPL(_s_) (g_xim_messages_error(G_XIM_PROTOCOL_GET_IFACE (proto)->message, "No implementation or an error occurred in %s", #_s_))
47. #define MSG_NOIMPL_IM(_s_,_imid_) (g_xim_messages_error(G_XIM_PROTOCOL_GET_IFACE (proto)->message, "No implementation or an error occurred in %s [imid: %d]", #_s_, (_imid_)))
48. #define MSG_NOIMPL_IMIC(_s_,_imid_,_icid_) (g_xim_messages_error(G_XIM_PROTOCOL_GET_IFACE (proto)->message, "No implementation or an error occurred in %s [imid: %d, icid: %d]", #_s_, (_imid_), (_icid_)))
49. /*
50. * Private functions
51. */
52. static gboolean
53. g_xim_protocol10_closure_XIM_CONNECT(GXimProtocolClosure *closure,
54. GXimProtocol *proto,
55. GDataInputStream *stream,
56. GError **error,
57. gpointer user_data)
58. {
59. guint8 b;
60. guint16 major = 0, minor = 0;
61. GSList *list = NULL;
62. gboolean retval = FALSE;
63. if (g_xim_protocol_read_format(proto, stream, NULL, error, 6,
64. G_XIM_TYPE_BYTE, &b,
65. G_XIM_TYPE_PADDING, 1,
66. G_XIM_TYPE_WORD, &major,
67. G_XIM_TYPE_WORD, &minor,
68. G_XIM_TYPE_MARKER_N_ITEMS_2, G_XIM_TYPE_LIST_OF_STRING,
69. G_XIM_TYPE_LIST_OF_STRING, &list)) {
70. retval = g_xim_protocol_closure_emit_signal(closure, proto,
71. major, minor, list);
72. } else {
73. /* better handling error */
74. PROTO_ERROR (XIM_CONNECT, 0);
75. }
76. g_slist_foreach(list, (GFunc)g_xim_string_free, NULL);
77. g_slist_free(list);
78. return retval;
79. }
80. static gboolean
81. g_xim_protocol10_closure_XIM_CONNECT_REPLY(GXimProtocolClosure *closure,
82. GXimProtocol *proto,
83. GDataInputStream *stream,
84. GError **error,
85. gpointer user_data)
86. {
87. guint16 major, minor;
88. gboolean retval = FALSE;
89. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
90. G_XIM_TYPE_WORD, &major,
91. G_XIM_TYPE_WORD, &minor)) {
92. retval = g_xim_protocol_closure_emit_signal(closure, proto,
93. major, minor);
94. } else {
95. /* better handling error */
96. PROTO_ERROR (XIM_CONNECT_REPLY, 0);
97. }
98. return retval;
99. }
100. static gboolean
101. g_xim_protocol10_closure_XIM_DISCONNECT(GXimProtocolClosure *closure,
102. GXimProtocol *proto,
103. GDataInputStream *stream,
104. GError **error,
105. gpointer user_data)
106. {
107. gboolean retval = FALSE;
108. retval = g_xim_protocol_closure_emit_signal(closure, proto);
109. return retval;
110. }
111. static gboolean
112. g_xim_protocol10_closure_XIM_DISCONNECT_REPLY(GXimProtocolClosure *closure,
113. GXimProtocol *proto,
114. GDataInputStream *stream,
115. GError **error,
116. gpointer user_data)
117. {
118. GXimProtocolPrivate *priv;
119. gboolean retval = FALSE;
120. priv = g_xim_protocol_get_private(proto);
121. retval = g_xim_protocol_closure_emit_signal(closure, proto);
122. priv->is_disconnected = TRUE;
123. return retval;
124. }
125. static gboolean
126. g_xim_protocol10_closure_XIM_AUTH_REQUIRED(GXimProtocolClosure *closure,
127. GXimProtocol *proto,
128. GDataInputStream *stream,
129. GError **error,
130. gpointer user_data)
131. {
132. gboolean retval = FALSE;
133. /* XXX */
134. PROTO_ERROR (XIM_AUTH_REQUIRED, 0);
135. return retval;
136. }
137. static gboolean
138. g_xim_protocol10_closure_XIM_AUTH_REPLY(GXimProtocolClosure *closure,
139. GXimProtocol *proto,
140. GDataInputStream *stream,
141. GError **error,
142. gpointer user_data)
143. {
144. gboolean retval = FALSE;
145. /* XXX */
146. PROTO_ERROR (XIM_AUTH_REPLY, 0);
147. return retval;
148. }
149. static gboolean
150. g_xim_protocol10_closure_XIM_AUTH_NEXT(GXimProtocolClosure *closure,
151. GXimProtocol *proto,
152. GDataInputStream *stream,
153. GError **error,
154. gpointer user_data)
155. {
156. gboolean retval = FALSE;
157. /* XXX */
158. PROTO_ERROR (XIM_AUTH_NEXT, 0);
159. return retval;
160. }
161. static gboolean
162. g_xim_protocol10_closure_XIM_AUTH_SETUP(GXimProtocolClosure *closure,
163. GXimProtocol *proto,
164. GDataInputStream *stream,
165. GError **error,
166. gpointer user_data)
167. {
168. gboolean retval = FALSE;
169. /* XXX */
170. PROTO_ERROR (XIM_AUTH_SETUP, 0);
171. return retval;
172. }
173. static gboolean
174. g_xim_protocol10_closure_XIM_AUTH_NG(GXimProtocolClosure *closure,
175. GXimProtocol *proto,
176. GDataInputStream *stream,
177. GError **error,
178. gpointer user_data)
179. {
180. gboolean retval = FALSE;
181. retval = g_xim_protocol_closure_emit_signal(closure, proto);
182. return retval;
183. }
184. static gboolean
185. g_xim_protocol10_closure_XIM_ERROR(GXimProtocolClosure *closure,
186. GXimProtocol *proto,
187. GDataInputStream *stream,
188. GError **error,
189. gpointer user_data)
190. {
191. gboolean retval = FALSE;
192. guint16 imid, icid, flag, detail;
193. GXimErrorCode error_code = 0;
194. gchar *error_message = NULL;
195. if (g_xim_protocol_read_format(proto, stream, NULL, error, 8,
196. G_XIM_TYPE_WORD, &imid,
197. G_XIM_TYPE_WORD, &icid,
198. G_XIM_TYPE_WORD, &flag,
199. G_XIM_TYPE_WORD, &error_code,
200. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_CHAR,
201. G_XIM_TYPE_WORD, &detail,
202. G_XIM_TYPE_CHAR, &error_message,
203. G_XIM_TYPE_AUTO_PADDING, 0)) {
204. retval = g_xim_protocol_closure_emit_signal(closure, proto,
205. imid, icid, flag, error_code, detail, error_message);
206. }
207. g_free(error_message);
208. return retval;
209. }
210. static gboolean
211. g_xim_protocol10_closure_XIM_OPEN(GXimProtocolClosure *closure,
212. GXimProtocol *proto,
213. GDataInputStream *stream,
214. GError **error,
215. gpointer user_data)
216. {
217. GXimStr *locale = NULL;
218. gboolean retval = FALSE;
219. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
220. G_XIM_TYPE_STR, &locale,
221. G_XIM_TYPE_AUTO_PADDING, 0)) {
222. retval = g_xim_protocol_closure_emit_signal(closure, proto,
223. locale);
224. } else {
225. /* better handling error */
226. PROTO_ERROR (XIM_OPEN, 0);
227. }
228. g_xim_str_free(locale);
229. return retval;
230. }
231. static gboolean
232. g_xim_protocol10_closure_XIM_OPEN_REPLY(GXimProtocolClosure *closure,
233. GXimProtocol *proto,
234. GDataInputStream *stream,
235. GError **error,
236. gpointer user_data)
237. {
238. GSList *imlist = NULL, *iclist = NULL, *l;
239. GXimAttr *imattr = NULL, *icattr = NULL;
240. guint16 imid = 0;
241. gboolean retval = FALSE;
242. if (g_xim_protocol_read_format(proto, stream, NULL, error, 6,
243. G_XIM_TYPE_WORD, &imid,
244. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_IMATTR,
245. G_XIM_TYPE_LIST_OF_IMATTR, &imlist,
246. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_ICATTR,
247. G_XIM_TYPE_PADDING, 2,
248. G_XIM_TYPE_LIST_OF_ICATTR, &iclist)) {
249. imattr = g_object_new(G_TYPE_XIM_IM_ATTR, NULL);
250. icattr = g_object_new(G_TYPE_XIM_IC_ATTR, NULL);
251. for (l = imlist; l != NULL; l = g_slist_next(l)) {
252. g_xim_attr_set_raw_attr(imattr, l->data);
253. g_xim_raw_attr_free(l->data);
254. }
255. for (l = iclist; l != NULL; l = g_slist_next(l)) {
256. g_xim_attr_set_raw_attr(icattr, l->data);
257. g_xim_raw_attr_free(l->data);
258. }
259. g_slist_free(imlist);
260. g_slist_free(iclist);
261. retval = g_xim_protocol_closure_emit_signal(closure, proto,
262. imid, imattr, icattr);
263. } else {
264. /* better handling error */
265. PROTO_ERROR_IM (XIM_OPEN_REPLY, 0, imid);
266. }
267. if (imattr)
268. g_object_unref(imattr);
269. if (icattr)
270. g_object_unref(icattr);
271. return retval;
272. }
273. static gboolean
274. g_xim_protocol10_closure_XIM_CLOSE(GXimProtocolClosure *closure,
275. GXimProtocol *proto,
276. GDataInputStream *stream,
277. GError **error,
278. gpointer user_data)
279. {
280. gboolean retval = FALSE;
281. guint16 imid = 0;
282. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
283. G_XIM_TYPE_WORD, &imid,
284. G_XIM_TYPE_PADDING, 2)) {
285. retval = g_xim_protocol_closure_emit_signal(closure, proto,
286. imid);
287. } else {
288. /* better handling error */
289. PROTO_ERROR_IM (XIM_CLOSE, 0, imid);
290. }
291. return retval;
292. }
293. static gboolean
294. g_xim_protocol10_closure_XIM_CLOSE_REPLY(GXimProtocolClosure *closure,
295. GXimProtocol *proto,
296. GDataInputStream *stream,
297. GError **error,
298. gpointer user_data)
299. {
300. gboolean retval = FALSE;
301. guint16 imid = 0;
302. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
303. G_XIM_TYPE_WORD, &imid,
304. G_XIM_TYPE_PADDING, 2)) {
305. retval = g_xim_protocol_closure_emit_signal(closure, proto,
306. imid);
307. } else {
308. /* better handling error */
309. PROTO_ERROR_IM (XIM_CLOSE_REPLY, 0, imid);
310. }
311. return retval;
312. }
313. static gboolean
314. g_xim_protocol10_closure_XIM_REGISTER_TRIGGERKEYS(GXimProtocolClosure *closure,
315. GXimProtocol *proto,
316. GDataInputStream *stream,
317. GError **error,
318. gpointer user_data)
319. {
320. gboolean retval = FALSE;
321. guint16 imid;
322. GSList *onkeys = NULL, *offkeys = NULL;
323. if (g_xim_protocol_read_format(proto, stream, NULL, error, 4,
324. G_XIM_TYPE_WORD, &imid,
325. G_XIM_TYPE_PADDING, 2,
326. G_XIM_TYPE_MARKER_N_BYTES_4, G_XIM_TYPE_LIST_OF_HOTKEY_TRIGGER,
327. G_XIM_TYPE_LIST_OF_HOTKEY_TRIGGER, &onkeys)) {
328. /* check the off-keys list separately.
329. * some IMs sends XIM_REGISTER_TRIGGERKEYS without
330. * the off-keys list.
331. */
332. g_xim_protocol_read_format(proto, stream, NULL, error, 2,
333. G_XIM_TYPE_MARKER_N_BYTES_4, G_XIM_TYPE_LIST_OF_HOTKEY_TRIGGER,
334. G_XIM_TYPE_LIST_OF_HOTKEY_TRIGGER, &offkeys);
335. if (*error) {
336. g_xim_messages_warning(G_XIM_PROTOCOL_GET_IFACE (proto)->message,
337. "No off-keys received in XIM_REGISTER_TRIGGERKEYS:\n %s",
338. (*error)->message);
339. g_clear_error(error);
340. }
341. retval = g_xim_protocol_closure_emit_signal(closure, proto,
342. imid, onkeys, offkeys);
343. }
344. g_slist_foreach(onkeys, (GFunc)g_xim_hotkey_trigger_free, NULL);
345. g_slist_foreach(offkeys, (GFunc)g_xim_hotkey_trigger_free, NULL);
346. g_slist_free(onkeys);
347. g_slist_free(offkeys);
348. return retval;
349. }
350. static gboolean
351. g_xim_protocol10_closure_XIM_TRIGGER_NOTIFY(GXimProtocolClosure *closure,
352. GXimProtocol *proto,
353. GDataInputStream *stream,
354. GError **error,
355. gpointer user_data)
356. {
357. gboolean retval = FALSE;
358. guint16 imid = 0, icid = 0;
359. guint32 flag, index_, mask;
360. if (g_xim_protocol_read_format(proto, stream, NULL, error, 5,
361. G_XIM_TYPE_WORD, &imid,
362. G_XIM_TYPE_WORD, &icid,
363. G_XIM_TYPE_LONG, &flag,
364. G_XIM_TYPE_LONG, &index_,
365. G_XIM_TYPE_LONG, &mask)) {
366. retval = g_xim_protocol_closure_emit_signal(closure, proto,
367. imid, icid, flag, index_, mask);
368. } else {
369. /* better handling error */
370. PROTO_ERROR_IMIC (XIM_TRIGGER_NOTIFY, 0, imid, icid);
371. }
372. return retval;
373. }
374. static gboolean
375. g_xim_protocol10_closure_XIM_TRIGGER_NOTIFY_REPLY(GXimProtocolClosure *closure,
376. GXimProtocol *proto,
377. GDataInputStream *stream,
378. GError **error,
379. gpointer user_data)
380. {
381. gboolean retval = FALSE;
382. guint16 imid = 0, icid = 0;
383. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
384. G_XIM_TYPE_WORD, &imid,
385. G_XIM_TYPE_WORD, &icid)) {
386. retval = g_xim_protocol_closure_emit_signal(closure, proto,
387. imid, icid);
388. } else {
389. /* better handling error */
390. PROTO_ERROR_IMIC (XIM_TRIGGER_NOTIFY_REPLY, 0, imid, icid);
391. }
392. return retval;
393. }
394. static gboolean
395. g_xim_protocol10_closure_XIM_SET_EVENT_MASK(GXimProtocolClosure *closure,
396. GXimProtocol *proto,
397. GDataInputStream *stream,
398. GError **error,
399. gpointer user_data)
400. {
401. gboolean retval = FALSE;
402. guint16 imid, icid;
403. guint32 forward_mask, sync_mask;
404. if (g_xim_protocol_read_format(proto, stream, NULL, error, 4,
405. G_XIM_TYPE_WORD, &imid,
406. G_XIM_TYPE_WORD, &icid,
407. G_XIM_TYPE_LONG, &forward_mask,
408. G_XIM_TYPE_LONG, &sync_mask)) {
409. retval = g_xim_protocol_closure_emit_signal(closure, proto,
410. imid, icid, forward_mask, sync_mask);
411. }
412. return retval;
413. }
414. static gboolean
415. g_xim_protocol10_closure_XIM_ENCODING_NEGOTIATION(GXimProtocolClosure *closure,
416. GXimProtocol *proto,
417. GDataInputStream *stream,
418. GError **error,
419. gpointer user_data)
420. {
421. gboolean retval = FALSE;
422. GSList *list = NULL, *enclist = NULL;
423. guint16 imid = 0;
424. if (g_xim_protocol_read_format(proto, stream, NULL, error, 7,
425. G_XIM_TYPE_WORD, &imid,
426. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_STR,
427. G_XIM_TYPE_LIST_OF_STR, &list,
428. G_XIM_TYPE_AUTO_PADDING, 0,
429. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_ENCODINGINFO,
430. G_XIM_TYPE_PADDING, 2,
431. G_XIM_TYPE_LIST_OF_ENCODINGINFO, &enclist)) {
432. retval = g_xim_protocol_closure_emit_signal(closure, proto,
433. imid, list, enclist);
434. } else {
435. /* better handling error */
436. PROTO_ERROR_IM (XIM_ENCODING_NEGOTIATION, 0, imid);
437. }
438. g_slist_foreach(list,
439. (GFunc)g_xim_str_free,
440. NULL);
441. g_slist_foreach(enclist,
442. (GFunc)g_xim_encodinginfo_free,
443. NULL);
444. g_slist_free(list);
445. g_slist_free(enclist);
446. return retval;
447. }
448. static gboolean
449. g_xim_protocol10_closure_XIM_ENCODING_NEGOTIATION_REPLY(GXimProtocolClosure *closure,
450. GXimProtocol *proto,
451. GDataInputStream *stream,
452. GError **error,
453. gpointer user_data)
454. {
455. gboolean retval = FALSE;
456. guint16 imid = 0, category;
457. gint16 index_;
458. if (g_xim_protocol_read_format(proto, stream, NULL, error, 4,
459. G_XIM_TYPE_WORD, &imid,
460. G_XIM_TYPE_WORD, &category,
461. G_XIM_TYPE_WORD, &index_,
462. G_XIM_TYPE_PADDING, 2)) {
463. retval = g_xim_protocol_closure_emit_signal(closure, proto,
464. imid, category, index_);
465. } else {
466. /* better handling error */
467. PROTO_ERROR_IM (XIM_ENCODING_NEGOTIATION_REPLY, 0, imid);
468. }
469. return retval;
470. }
471. static gboolean
472. g_xim_protocol10_closure_XIM_QUERY_EXTENSION(GXimProtocolClosure *closure,
473. GXimProtocol *proto,
474. GDataInputStream *stream,
475. GError **error,
476. gpointer user_data)
477. {
478. gboolean retval = FALSE;
479. GSList *list = NULL;
480. guint16 imid = 0;
481. if (g_xim_protocol_read_format(proto, stream, NULL, error, 4,
482. G_XIM_TYPE_WORD, &imid,
483. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_STR,
484. G_XIM_TYPE_LIST_OF_STR, &list,
485. G_XIM_TYPE_AUTO_PADDING, 0)) {
486. retval = g_xim_protocol_closure_emit_signal(closure, proto,
487. imid, list);
488. } else {
489. /* better handling error */
490. PROTO_ERROR_IM (XIM_QUERY_EXTENSION, 0, imid);
491. }
492. g_slist_foreach(list,
493. (GFunc)g_xim_str_free,
494. NULL);
495. g_slist_free(list);
496. return retval;
497. }
498. static gboolean
499. g_xim_protocol10_closure_XIM_QUERY_EXTENSION_REPLY(GXimProtocolClosure *closure,
500. GXimProtocol *proto,
501. GDataInputStream *stream,
502. GError **error,
503. gpointer user_data)
504. {
505. gboolean retval = FALSE;
506. GSList *list = NULL;
507. guint16 imid;
508. if (!g_xim_protocol_read_format(proto, stream, NULL, error, 1,
509. G_XIM_TYPE_WORD, &imid)) {
510. /* XXX: There may be no way of recoverying from here */
511. return FALSE;
512. }
513. g_xim_protocol_read_format(proto, stream, NULL, error, 2,
514. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_EXT,
515. G_XIM_TYPE_LIST_OF_EXT, &list);
516. if (*error) {
517. /* deal with it as warning really, because we can
518. * recover it.
519. */
520. g_xim_messages_warning(G_XIM_PROTOCOL_GET_IFACE (proto)->message,
521. "%s", (*error)->message);
522. g_clear_error(error);
523. }
524. /* ignore an error. we could just send the null list */
525. retval = g_xim_protocol_closure_emit_signal(closure, proto,
526. imid, list);
527. g_slist_foreach(list,
528. (GFunc)g_xim_ext_free,
529. NULL);
530. g_slist_free(list);
531. return retval;
532. }
533. static gboolean
534. g_xim_protocol10_closure_XIM_SET_IM_VALUES(GXimProtocolClosure *closure,
535. GXimProtocol *proto,
536. GDataInputStream *stream,
537. GError **error,
538. gpointer user_data)
539. {
540. gboolean retval = FALSE;
541. guint16 imid = 0;
542. GSList *list = NULL;
543. if (g_xim_protocol_read_format(proto, stream, NULL, error, 3,
544. G_XIM_TYPE_WORD, &imid,
545. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_IMATTRIBUTE,
546. G_XIM_TYPE_LIST_OF_IMATTRIBUTE, &list)) {
547. retval = g_xim_protocol_closure_emit_signal(closure, proto,
548. imid, list);
549. } else {
550. /* better handling error */
551. PROTO_ERROR_IM (XIM_SET_IM_VALUES, 0, imid);
552. }
553. g_slist_foreach(list,
554. (GFunc)g_xim_attribute_free,
555. NULL);
556. g_slist_free(list);
557. return retval;
558. }
559. static gboolean
560. g_xim_protocol10_closure_XIM_SET_IM_VALUES_REPLY(GXimProtocolClosure *closure,
561. GXimProtocol *proto,
562. GDataInputStream *stream,
563. GError **error,
564. gpointer user_data)
565. {
566. gboolean retval = FALSE;
567. guint16 imid = 0;
568. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
569. G_XIM_TYPE_WORD, &imid,
570. G_XIM_TYPE_PADDING, 2)) {
571. retval = g_xim_protocol_closure_emit_signal(closure, proto,
572. imid);
573. } else {
574. /* better handling error */
575. PROTO_ERROR_IM (XIM_SET_IM_VALUES_REPLY, 0, imid);
576. }
577. return retval;
578. }
579. static gboolean
580. g_xim_protocol10_closure_XIM_GET_IM_VALUES(GXimProtocolClosure *closure,
581. GXimProtocol *proto,
582. GDataInputStream *stream,
583. GError **error,
584. gpointer user_data)
585. {
586. gboolean retval = FALSE;
587. GSList *list = NULL;
588. guint16 imid = 0;
589. if (g_xim_protocol_read_format(proto, stream, NULL, error, 4,
590. G_XIM_TYPE_WORD, &imid,
591. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_CARD16,
592. G_XIM_TYPE_LIST_OF_CARD16, &list,
593. G_XIM_TYPE_AUTO_PADDING, 0)) {
594. retval = g_xim_protocol_closure_emit_signal(closure, proto,
595. imid, list);
596. } else {
597. /* better handling error */
598. PROTO_ERROR_IM (XIM_GET_IM_VALUES, 0, imid);
599. }
600. g_slist_free(list);
601. return retval;
602. }
603. static gboolean
604. g_xim_protocol10_closure_XIM_GET_IM_VALUES_REPLY(GXimProtocolClosure *closure,
605. GXimProtocol *proto,
606. GDataInputStream *stream,
607. GError **error,
608. gpointer user_data)
609. {
610. gboolean retval = FALSE;
611. GSList *list = NULL;
612. guint16 imid;
613. GError *err = NULL;
614. if (!g_xim_protocol_read_format(proto, stream, NULL, error, 1,
615. G_XIM_TYPE_WORD, &imid)) {
616. /* XXX: There may be no way of recovering from here. */
617. return FALSE;
618. }
619. g_xim_protocol_read_format(proto, stream, NULL, &err, 2,
620. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_IMATTRIBUTE,
621. G_XIM_TYPE_LIST_OF_IMATTRIBUTE, &list);
622. if (err) {
623. /* deal with it as warning really, because we can
624. * recover it.
625. */
626. g_xim_messages_warning(G_XIM_PROTOCOL_GET_IFACE (proto)->message,
627. "%s", err->message);
628. g_error_free(err);
629. }
630. /* ignore an error. we could just send the null list */
631. retval = g_xim_protocol_closure_emit_signal(closure, proto,
632. imid, list);
633. g_slist_foreach(list, (GFunc)g_xim_attribute_free, NULL);
634. g_slist_free(list);
635. return retval;
636. }
637. static gboolean
638. g_xim_protocol10_closure_XIM_CREATE_IC(GXimProtocolClosure *closure,
639. GXimProtocol *proto,
640. GDataInputStream *stream,
641. GError **error,
642. gpointer user_data)
643. {
644. gboolean retval = FALSE;
645. GSList *list = NULL;
646. guint16 imid;
647. if (!g_xim_protocol_read_format(proto, stream, NULL, error, 1,
648. G_XIM_TYPE_WORD, &imid))
649. return FALSE;
650. g_xim_protocol_read_format(proto, stream, NULL, error, 2,
651. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_ICATTRIBUTE,
652. G_XIM_TYPE_LIST_OF_ICATTRIBUTE, &list);
653. /* deal with all of errors as warnings to give aid to
654. * the attributes retrieved successfully.
655. */
656. /* XXX: or should we just send back the error? */
657. if (*error) {
658. g_xim_messages_warning(G_XIM_PROTOCOL_GET_IFACE (proto)->message,
659. "%s", (*error)->message);
660. g_clear_error(error);
661. }
662. retval = g_xim_protocol_closure_emit_signal(closure, proto,
663. imid, list);
664. g_slist_foreach(list, (GFunc)g_xim_attribute_free, NULL);
665. g_slist_free(list);
666. return retval;
667. }
668. static gboolean
669. g_xim_protocol10_closure_XIM_CREATE_IC_REPLY(GXimProtocolClosure *closure,
670. GXimProtocol *proto,
671. GDataInputStream *stream,
672. GError **error,
673. gpointer user_data)
674. {
675. gboolean retval = FALSE;
676. guint16 imid = 0, icid = 0;
677. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
678. G_XIM_TYPE_WORD, &imid,
679. G_XIM_TYPE_WORD, &icid)) {
680. retval = g_xim_protocol_closure_emit_signal(closure, proto,
681. imid, icid);
682. } else {
683. /* better handling error */
684. PROTO_ERROR_IMIC (XIM_CREATE_IC_REPLY, 0, imid, icid);
685. }
686. return retval;
687. }
688. static gboolean
689. g_xim_protocol10_closure_XIM_DESTROY_IC(GXimProtocolClosure *closure,
690. GXimProtocol *proto,
691. GDataInputStream *stream,
692. GError **error,
693. gpointer user_data)
694. {
695. gboolean retval = FALSE;
696. guint16 imid = 0, icid = 0;
697. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
698. G_XIM_TYPE_WORD, &imid,
699. G_XIM_TYPE_WORD, &icid)) {
700. retval = g_xim_protocol_closure_emit_signal(closure, proto,
701. imid, icid);
702. } else {
703. /* better handling error */
704. PROTO_ERROR_IMIC (XIM_DESTROY_IC, 0, imid, icid);
705. }
706. return retval;
707. }
708. static gboolean
709. g_xim_protocol10_closure_XIM_DESTROY_IC_REPLY(GXimProtocolClosure *closure,
710. GXimProtocol *proto,
711. GDataInputStream *stream,
712. GError **error,
713. gpointer user_data)
714. {
715. gboolean retval = FALSE;
716. guint16 imid = 0, icid = 0;
717. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
718. G_XIM_TYPE_WORD, &imid,
719. G_XIM_TYPE_WORD, &icid)) {
720. retval = g_xim_protocol_closure_emit_signal(closure, proto,
721. imid, icid);
722. } else {
723. /* better handling error */
724. PROTO_ERROR_IMIC (XIM_DESTROY_IC_REPLY, 0, imid, icid);
725. }
726. return retval;
727. }
728. static gboolean
729. g_xim_protocol10_closure_XIM_SET_IC_VALUES(GXimProtocolClosure *closure,
730. GXimProtocol *proto,
731. GDataInputStream *stream,
732. GError **error,
733. gpointer user_data)
734. {
735. gboolean retval = FALSE;
736. guint16 imid = 0, icid = 0;
737. GSList *list = NULL;
738. if (g_xim_protocol_read_format(proto, stream, NULL, error, 5,
739. G_XIM_TYPE_WORD, &imid,
740. G_XIM_TYPE_WORD, &icid,
741. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_ICATTRIBUTE,
742. G_XIM_TYPE_PADDING, 2,
743. G_XIM_TYPE_LIST_OF_ICATTRIBUTE, &list)) {
744. retval = g_xim_protocol_closure_emit_signal(closure, proto,
745. imid, icid, list);
746. } else {
747. /* better handling error */
748. PROTO_ERROR_IMIC (XIM_SET_IC_VALUES, 0, imid, icid);
749. }
750. g_slist_foreach(list,
751. (GFunc)g_xim_attribute_free,
752. NULL);
753. g_slist_free(list);
754. return retval;
755. }
756. static gboolean
757. g_xim_protocol10_closure_XIM_SET_IC_VALUES_REPLY(GXimProtocolClosure *closure,
758. GXimProtocol *proto,
759. GDataInputStream *stream,
760. GError **error,
761. gpointer user_data)
762. {
763. gboolean retval = FALSE;
764. guint16 imid = 0, icid = 0;
765. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
766. G_XIM_TYPE_WORD, &imid,
767. G_XIM_TYPE_WORD, &icid)) {
768. retval = g_xim_protocol_closure_emit_signal(closure, proto,
769. imid, icid);
770. } else {
771. /* better handling error */
772. PROTO_ERROR_IMIC (XIM_SET_IC_VALUES_REPLY, 0, imid, icid);
773. }
774. return retval;
775. }
776. static gboolean
777. g_xim_protocol10_closure_XIM_GET_IC_VALUES(GXimProtocolClosure *closure,
778. GXimProtocol *proto,
779. GDataInputStream *stream,
780. GError **error,
781. gpointer user_data)
782. {
783. gboolean retval = FALSE;
784. guint16 imid = 0, icid = 0;
785. GSList *list = NULL;
786. if (g_xim_protocol_read_format(proto, stream, NULL, error, 5,
787. G_XIM_TYPE_WORD, &imid,
788. G_XIM_TYPE_WORD, &icid,
789. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_CARD16,
790. G_XIM_TYPE_LIST_OF_CARD16, &list,
791. G_XIM_TYPE_AUTO_PADDING, 2)) {
792. retval = g_xim_protocol_closure_emit_signal(closure, proto,
793. imid, icid, list);
794. } else {
795. /* better handling error */
796. PROTO_ERROR_IMIC (XIM_GET_IC_VALUES, 0, imid, icid);
797. }
798. g_slist_free(list);
799. return retval;
800. }
801. static gboolean
802. g_xim_protocol10_closure_XIM_GET_IC_VALUES_REPLY(GXimProtocolClosure *closure,
803. GXimProtocol *proto,
804. GDataInputStream *stream,
805. GError **error,
806. gpointer user_data)
807. {
808. gboolean retval = FALSE;
809. guint16 imid = 0, icid = 0;
810. GSList *list = NULL;
811. if (g_xim_protocol_read_format(proto, stream, NULL, error, 5,
812. G_XIM_TYPE_WORD, &imid,
813. G_XIM_TYPE_WORD, &icid,
814. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_ICATTRIBUTE,
815. G_XIM_TYPE_PADDING, 2,
816. G_XIM_TYPE_LIST_OF_ICATTRIBUTE, &list)) {
817. retval = g_xim_protocol_closure_emit_signal(closure, proto,
818. imid, icid, list);
819. } else {
820. /* better handling error */
821. PROTO_ERROR_IMIC (XIM_GET_IC_VALUES_REPLY, 0, imid, icid);
822. }
823. g_slist_foreach(list, (GFunc)g_xim_attribute_free, NULL);
824. g_slist_free(list);
825. return retval;
826. }
827. static gboolean
828. g_xim_protocol10_closure_XIM_SET_IC_FOCUS(GXimProtocolClosure *closure,
829. GXimProtocol *proto,
830. GDataInputStream *stream,
831. GError **error,
832. gpointer user_data)
833. {
834. gboolean retval = FALSE;
835. guint16 imid, icid;
836. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
837. G_XIM_TYPE_WORD, &imid,
838. G_XIM_TYPE_WORD, &icid)) {
839. retval = g_xim_protocol_closure_emit_signal(closure, proto,
840. imid, icid);
841. }
842. return retval;
843. }
844. static gboolean
845. g_xim_protocol10_closure_XIM_UNSET_IC_FOCUS(GXimProtocolClosure *closure,
846. GXimProtocol *proto,
847. GDataInputStream *stream,
848. GError **error,
849. gpointer user_data)
850. {
851. gboolean retval = FALSE;
852. guint16 imid, icid;
853. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
854. G_XIM_TYPE_WORD, &imid,
855. G_XIM_TYPE_WORD, &icid)) {
856. retval = g_xim_protocol_closure_emit_signal(closure, proto,
857. imid, icid);
858. }
859. return retval;
860. }
861. static gboolean
862. g_xim_protocol10_closure_XIM_FORWARD_EVENT(GXimProtocolClosure *closure,
863. GXimProtocol *proto,
864. GDataInputStream *stream,
865. GError **error,
866. gpointer user_data)
867. {
868. gboolean retval = FALSE;
869. guint16 imid = 0, icid = 0, flag = 0;
870. GdkEvent *event = NULL;
871. if (g_xim_protocol_read_format(proto, stream, NULL, error, 4,
872. G_XIM_TYPE_WORD, &imid,
873. G_XIM_TYPE_WORD, &icid,
874. G_XIM_TYPE_WORD, &flag,
875. G_XIM_TYPE_GDKEVENT, &event)) {
876. retval = g_xim_protocol_closure_emit_signal(closure, proto,
877. imid, icid, flag, event);
878. } else {
879. /* better handling error */
880. if (flag & G_XIM_Event_Synchronous)
881. g_xim_connection_cmd_sync_reply(G_XIM_CONNECTION (proto), imid, icid);
882. retval = g_xim_connection_cmd_forward_event(G_XIM_CONNECTION (proto), imid, icid, flag & ~G_XIM_Event_Synchronous, event);
883. }
884. if (event)
885. gdk_event_free(event);
886. return retval;
887. }
888. static gboolean
889. g_xim_protocol10_closure_XIM_SYNC(GXimProtocolClosure *closure,
890. GXimProtocol *proto,
891. GDataInputStream *stream,
892. GError **error,
893. gpointer user_data)
894. {
895. gboolean retval = FALSE;
896. guint16 imid = 0, icid = 0;
897. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
898. G_XIM_TYPE_WORD, &imid,
899. G_XIM_TYPE_WORD, &icid)) {
900. retval = g_xim_protocol_closure_emit_signal(closure, proto,
901. imid, icid);
902. } else {
903. /* better handling error */
904. PROTO_ERROR_IMIC (XIM_SYNC, 0, imid, icid);
905. }
906. return retval;
907. }
908. static gboolean
909. g_xim_protocol10_closure_XIM_SYNC_REPLY(GXimProtocolClosure *closure,
910. GXimProtocol *proto,
911. GDataInputStream *stream,
912. GError **error,
913. gpointer user_data)
914. {
915. gboolean retval = FALSE;
916. guint16 imid, icid;
917. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
918. G_XIM_TYPE_WORD, &imid,
919. G_XIM_TYPE_WORD, &icid)) {
920. retval = g_xim_protocol_closure_emit_signal(closure, proto,
921. imid, icid);
922. }
923. return retval;
924. }
925. static gboolean
926. g_xim_protocol10_closure_XIM_COMMIT(GXimProtocolClosure *closure,
927. GXimProtocol *proto,
928. GDataInputStream *stream,
929. GError **error,
930. gpointer user_data)
931. {
932. gboolean retval = FALSE;
933. guint16 imid = 0, icid = 0, flag = 0;
934. gint padding = 0;
935. guint32 keysym = GDK_KEY_VoidSymbol;
936. GString *string = NULL;
937. if (!g_xim_protocol_read_format(proto, stream, NULL, error, 3,
938. G_XIM_TYPE_WORD, &imid,
939. G_XIM_TYPE_WORD, &icid,
940. G_XIM_TYPE_WORD, &flag))
941. goto fail;
942. if (flag & G_XIM_XLookupKeySym) {
943. if (!g_xim_protocol_read_format(proto, stream, NULL, error, 2,
944. G_XIM_TYPE_PADDING, 2,
945. G_XIM_TYPE_LONG, &keysym))
946. goto fail;
947. padding += 2;
948. }
949. if (flag & G_XIM_XLookupChars) {
950. if (!g_xim_protocol_read_format(proto, stream, NULL, error, 2,
951. G_XIM_TYPE_GSTRING, &string,
952. G_XIM_TYPE_AUTO_PADDING, padding))
953. goto fail;
954. }
955. retval = g_xim_protocol_closure_emit_signal(closure, proto,
956. imid, icid, flag, keysym, string);
957. if (string)
958. g_string_free(string, TRUE);
959. return retval;
960. fail:
961. if (string)
962. g_string_free(string, TRUE);
963. if (flag & G_XIM_XLookupSynchronous)
964. return g_xim_connection_cmd_sync_reply(G_XIM_CONNECTION (proto), imid, icid);
965. return FALSE;
966. }
967. static gboolean
968. g_xim_protocol10_closure_XIM_RESET_IC(GXimProtocolClosure *closure,
969. GXimProtocol *proto,
970. GDataInputStream *stream,
971. GError **error,
972. gpointer user_data)
973. {
974. gboolean retval = FALSE;
975. guint16 imid = 0, icid = 0;
976. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
977. G_XIM_TYPE_WORD, &imid,
978. G_XIM_TYPE_WORD, &icid)) {
979. retval = g_xim_protocol_closure_emit_signal(closure, proto,
980. imid, icid);
981. } else {
982. /* better handling error */
983. PROTO_ERROR_IMIC (XIM_RESET_IC, 0, imid, icid);
984. }
985. return retval;
986. }
987. static gboolean
988. g_xim_protocol10_closure_XIM_RESET_IC_REPLY(GXimProtocolClosure *closure,
989. GXimProtocol *proto,
990. GDataInputStream *stream,
991. GError **error,
992. gpointer user_data)
993. {
994. gboolean retval = FALSE;
995. guint16 imid = 0, icid = 0;
996. GString *string = NULL;
997. if (g_xim_protocol_read_format(proto, stream, NULL, error, 5,
998. G_XIM_TYPE_WORD, &imid,
999. G_XIM_TYPE_WORD, &icid,
1000. G_XIM_TYPE_MARKER_N_BYTES_2, G_XIM_TYPE_LIST_OF_BYTE,
1001. G_XIM_TYPE_LIST_OF_BYTE, &string,
1002. G_XIM_TYPE_AUTO_PADDING, 2)) {
1003. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1004. imid, icid, string);
1005. } else {
1006. /* better handling error */
1007. PROTO_ERROR_IMIC (XIM_RESET_IC_REPLY, 0, imid, icid);
1008. }
1009. g_string_free(string, TRUE);
1010. return retval;
1011. }
1012. static gboolean
1013. g_xim_protocol10_closure_XIM_GEOMETRY(GXimProtocolClosure *closure,
1014. GXimProtocol *proto,
1015. GDataInputStream *stream,
1016. GError **error,
1017. gpointer user_data)
1018. {
1019. gboolean retval = FALSE;
1020. guint16 imid, icid;
1021. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
1022. G_XIM_TYPE_WORD, &imid,
1023. G_XIM_TYPE_WORD, &icid)) {
1024. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1025. imid, icid);
1026. }
1027. return retval;
1028. }
1029. static gboolean
1030. g_xim_protocol10_closure_XIM_STR_CONVERSION(GXimProtocolClosure *closure,
1031. GXimProtocol *proto,
1032. GDataInputStream *stream,
1033. GError **error,
1034. gpointer user_data)
1035. {
1036. gboolean retval = FALSE;
1037. guint16 imid = 0, icid = 0;
1038. /* XXX */
1039. g_xim_protocol_read_format(proto, stream, NULL, error, 2,
1040. G_XIM_TYPE_WORD, &imid,
1041. G_XIM_TYPE_WORD, &icid);
1042. PROTO_ERROR_IMIC (XIM_STR_CONVERSION, 0, imid, icid);
1043. return retval;
1044. }
1045. static gboolean
1046. g_xim_protocol10_closure_XIM_STR_CONVERSION_REPLY(GXimProtocolClosure *closure,
1047. GXimProtocol *proto,
1048. GDataInputStream *stream,
1049. GError **error,
1050. gpointer user_data)
1051. {
1052. gboolean retval = FALSE;
1053. /* XXX */
1054. return retval;
1055. }
1056. static gboolean
1057. g_xim_protocol10_closure_XIM_PREEDIT_START(GXimProtocolClosure *closure,
1058. GXimProtocol *proto,
1059. GDataInputStream *stream,
1060. GError **error,
1061. gpointer user_data)
1062. {
1063. gboolean retval = FALSE;
1064. guint16 imid = 0, icid = 0;
1065. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
1066. G_XIM_TYPE_WORD, &imid,
1067. G_XIM_TYPE_WORD, &icid)) {
1068. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1069. imid, icid);
1070. } else {
1071. /* better handling error */
1072. /* XXX: should we send back PREEDIT_START_REPLY with an error in the return value? */
1073. PROTO_ERROR_IMIC (XIM_PREEDIT_START, 0, imid, icid);
1074. }
1075. return retval;
1076. }
1077. static gboolean
1078. g_xim_protocol10_closure_XIM_PREEDIT_START_REPLY(GXimProtocolClosure *closure,
1079. GXimProtocol *proto,
1080. GDataInputStream *stream,
1081. GError **error,
1082. gpointer user_data)
1083. {
1084. gboolean retval = FALSE;
1085. guint16 imid, icid;
1086. gint32 ret;
1087. if (g_xim_protocol_read_format(proto, stream, NULL, error, 3,
1088. G_XIM_TYPE_WORD, &imid,
1089. G_XIM_TYPE_WORD, &icid,
1090. G_XIM_TYPE_LONG, &ret)) {
1091. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1092. imid, icid, ret);
1093. }
1094. return retval;
1095. }
1096. static gboolean
1097. g_xim_protocol10_closure_XIM_PREEDIT_DRAW(GXimProtocolClosure *closure,
1098. GXimProtocol *proto,
1099. GDataInputStream *stream,
1100. GError **error,
1101. gpointer user_data)
1102. {
1103. gboolean retval = FALSE;
1104. guint16 imid, icid;
1105. GXimPreeditDraw *draw;
1106. if (g_xim_protocol_read_format(proto, stream, NULL, error, 3,
1107. G_XIM_TYPE_WORD, &imid,
1108. G_XIM_TYPE_WORD, &icid,
1109. G_XIM_TYPE_PREEDIT_DRAW, &draw)) {
1110. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1111. imid, icid, draw);
1112. }
1113. g_xim_preedit_draw_free(draw);
1114. return retval;
1115. }
1116. static gboolean
1117. g_xim_protocol10_closure_XIM_PREEDIT_CARET(GXimProtocolClosure *closure,
1118. GXimProtocol *proto,
1119. GDataInputStream *stream,
1120. GError **error,
1121. gpointer user_data)
1122. {
1123. gboolean retval = FALSE;
1124. guint16 imid = 0, icid = 0;
1125. GXimPreeditCaret *caret;
1126. if (g_xim_protocol_read_format(proto, stream, NULL, error, 3,
1127. G_XIM_TYPE_WORD, &imid,
1128. G_XIM_TYPE_WORD, &icid,
1129. G_XIM_TYPE_PREEDIT_CARET, &caret)) {
1130. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1131. imid, icid, caret);
1132. } else {
1133. /* better handling error */
1134. /* XXX: should we send back PREEDIT_CARET_REPLY with an error in the return value? */
1135. PROTO_ERROR_IMIC (XIM_PREEDIT_CARET, 0, imid, icid);
1136. }
1137. g_xim_preedit_caret_free(caret);
1138. return retval;
1139. }
1140. static gboolean
1141. g_xim_protocol10_closure_XIM_PREEDIT_CARET_REPLY(GXimProtocolClosure *closure,
1142. GXimProtocol *proto,
1143. GDataInputStream *stream,
1144. GError **error,
1145. gpointer user_data)
1146. {
1147. gboolean retval = FALSE;
1148. guint16 imid, icid;
1149. guint32 position;
1150. if (g_xim_protocol_read_format(proto, stream, NULL, error, 3,
1151. G_XIM_TYPE_WORD, &imid,
1152. G_XIM_TYPE_WORD, &icid,
1153. G_XIM_TYPE_LONG, &position)) {
1154. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1155. imid, icid, position);
1156. }
1157. /* XXX */
1158. return retval;
1159. }
1160. static gboolean
1161. g_xim_protocol10_closure_XIM_PREEDIT_DONE(GXimProtocolClosure *closure,
1162. GXimProtocol *proto,
1163. GDataInputStream *stream,
1164. GError **error,
1165. gpointer user_data)
1166. {
1167. gboolean retval = FALSE;
1168. guint16 imid, icid;
1169. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
1170. G_XIM_TYPE_WORD, &imid,
1171. G_XIM_TYPE_WORD, &icid)) {
1172. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1173. imid, icid);
1174. }
1175. return retval;
1176. }
1177. static gboolean
1178. g_xim_protocol10_closure_XIM_STATUS_START(GXimProtocolClosure *closure,
1179. GXimProtocol *proto,
1180. GDataInputStream *stream,
1181. GError **error,
1182. gpointer user_data)
1183. {
1184. gboolean retval = FALSE;
1185. guint16 imid, icid;
1186. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
1187. G_XIM_TYPE_WORD, &imid,
1188. G_XIM_TYPE_WORD, &icid)) {
1189. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1190. imid, icid);
1191. }
1192. return retval;
1193. }
1194. static gboolean
1195. g_xim_protocol10_closure_XIM_STATUS_DRAW(GXimProtocolClosure *closure,
1196. GXimProtocol *proto,
1197. GDataInputStream *stream,
1198. GError **error,
1199. gpointer user_data)
1200. {
1201. gboolean retval = FALSE;
1202. guint16 imid, icid;
1203. GXimStatusDraw *draw;
1204. if (g_xim_protocol_read_format(proto, stream, NULL, error, 3,
1205. G_XIM_TYPE_WORD, &imid,
1206. G_XIM_TYPE_WORD, &icid,
1207. G_XIM_TYPE_STATUS_DRAW, &draw)) {
1208. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1209. imid, icid, draw);
1210. }
1211. g_xim_status_draw_free(draw);
1212. return retval;
1213. }
1214. static gboolean
1215. g_xim_protocol10_closure_XIM_STATUS_DONE(GXimProtocolClosure *closure,
1216. GXimProtocol *proto,
1217. GDataInputStream *stream,
1218. GError **error,
1219. gpointer user_data)
1220. {
1221. gboolean retval = FALSE;
1222. guint16 imid, icid;
1223. if (g_xim_protocol_read_format(proto, stream, NULL, error, 2,
1224. G_XIM_TYPE_WORD, &imid,
1225. G_XIM_TYPE_WORD, &icid)) {
1226. retval = g_xim_protocol_closure_emit_signal(closure, proto,
1227. imid, icid);
1228. }
1229. return retval;
1230. }
1231. static gboolean
1232. g_xim_protocol10_closure_XIM_PREEDITSTATE(GXimProtocolClosure *closure,
1233. GXimProtocol *proto,
1234. GDataInputStream *stream,
1235. GError **error,
1236. gpointer user_data)
1237. {
1238. gboolean retval = FALSE;
1239. /* XXX */
1240. return retval;
1241. }
1242. static void
1243. gxim_marshal_FIXME(GClosure *closure,
1244. GValue *return_value,
1245. guint n_param_values,
1246. const GValue *param_values,
1247. gpointer invocation_hint,
1248. gpointer marshal_data)
1249. {
1250. g_warning("FIXME");
1251. }
1252. static void
1253. g_xim_protocol10_closure_signal_no_impl(GXimProtocol *proto,
1254. const gchar *func,
1255. GXimErrorMask flag,
1256. guint16 imid,
1257. guint16 icid)
1258. {
1259. GXimProtocolIface *iface;
1260. static const gchar message[] = "Not yet implemented or any errors occurred";
1261. static size_t len = 0;
1262. iface = G_XIM_PROTOCOL_GET_IFACE (proto);
1263. if (len == 0)
1264. len = strlen(message);
1265. g_xim_messages_bug(iface->message, "No real implementation of `%s' or any errors occurred.", func);
1266. g_xim_connection_cmd_error(G_XIM_CONNECTION (proto), imid, icid, flag,
1267. G_XIM_ERR_BadSomething, 0, message);
1268. }
1269. static gboolean
1270. g_xim_protocol10_closure_signal_XIM_CONNECT(GXimProtocol *proto,
1271. guint16 major_version,
1272. guint16 minor_version,
1273. const GSList *list)
1274. {
1275. return g_xim_connection_cmd_auth_ng(G_XIM_CONNECTION (proto));
1276. }
1277. static gboolean
1278. g_xim_protocol10_closure_signal_XIM_CONNECT_REPLY(GXimProtocol *proto,
1279. guint16 major_version,
1280. guint16 minor_version)
1281. {
1282. MSG_NOIMPL(XIM_CONNECT_REPLY);
1283. return TRUE;
1284. }
1285. static gboolean
1286. g_xim_protocol10_closure_signal_XIM_DISCONNECT(GXimProtocol *proto)
1287. {
1288. SIG_NOIMPL(XIM_DISCONNECT);
1289. return TRUE;
1290. }
1291. static gboolean
1292. g_xim_protocol10_closure_signal_XIM_DISCONNECT_REPLY(GXimProtocol *proto)
1293. {
1294. MSG_NOIMPL(XIM_DISCONNECT_REPLY);
1295. return TRUE;
1296. }
1297. static gboolean
1298. g_xim_protocol10_closure_signal_XIM_AUTH_REQUIRED(GXimProtocol *proto,
1299. const gchar *auth_data,
1300. gsize length)
1301. {
1302. return g_xim_connection_cmd_auth_ng(G_XIM_CONNECTION (proto));
1303. }
1304. static gboolean
1305. g_xim_protocol10_closure_signal_XIM_AUTH_REPLY(GXimProtocol *proto,
1306. const gchar *auth_data,
1307. gsize length)
1308. {
1309. return g_xim_connection_cmd_auth_ng(G_XIM_CONNECTION (proto));
1310. }
1311. static gboolean
1312. g_xim_protocol10_closure_signal_XIM_AUTH_NEXT(GXimProtocol *proto,
1313. const gchar *auth_data,
1314. gsize length)
1315. {
1316. return g_xim_connection_cmd_auth_ng(G_XIM_CONNECTION (proto));
1317. }
1318. static gboolean
1319. g_xim_protocol10_closure_signal_XIM_AUTH_SETUP(GXimProtocol *proto,
1320. const GSList *list)
1321. {
1322. return g_xim_connection_cmd_auth_ng(G_XIM_CONNECTION (proto));
1323. }
1324. static gboolean
1325. g_xim_protocol10_closure_signal_XIM_AUTH_NG(GXimProtocol *proto)
1326. {
1327. MSG_NOIMPL(XIM_AUTH_NG);
1328. return TRUE;
1329. }
1330. static gboolean
1331. g_xim_protocol10_closure_signal_XIM_ERROR(GXimProtocol *proto,
1332. guint16 imid,
1333. guint16 icid,
1334. GXimErrorMask flag,
1335. GXimErrorCode error_code,
1336. guint16 detail,
1337. const gchar *error_message)
1338. {
1339. gchar *simid, *sicid;
1340. if (flag & G_XIM_EMASK_VALID_IMID)
1341. simid = g_strdup_printf("imid: %d, ", imid);
1342. else
1343. simid = g_strdup("");
1344. if (flag & G_XIM_EMASK_VALID_ICID)
1345. sicid = g_strdup_printf("icid: %d, ", icid);
1346. else
1347. sicid = g_strdup("");
1348. g_xim_messages_error(G_XIM_PROTOCOL_GET_IFACE (proto)->message,
1349. "Received an error: %s%s error_code: %d, detail: %d, message: %s",
1350. simid, sicid, error_code, detail, error_message);
1351. g_free(simid);
1352. g_free(sicid);
1353. return TRUE;
1354. }
1355. static gboolean
1356. g_xim_protocol10_closure_signal_XIM_OPEN(GXimProtocol *proto,
1357. const GXimStr *locale)
1358. {
1359. SIG_NOIMPL(XIM_OPEN);
1360. return TRUE;
1361. }
1362. static gboolean
1363. g_xim_protocol10_closure_signal_XIM_OPEN_REPLY(GXimProtocol *proto,
1364. guint16 imid,
1365. GXimIMAttr *imattr,
1366. GXimICAttr *icattr)
1367. {
1368. MSG_NOIMPL_IM(XIM_OPEN_REPLY, imid);
1369. return TRUE;
1370. }
1371. static gboolean
1372. g_xim_protocol10_closure_signal_XIM_CLOSE(GXimProtocol *proto,
1373. guint16 imid)
1374. {
1375. SIG_NOIMPL_IM(XIM_CLOSE, imid);
1376. return TRUE;
1377. }
1378. static gboolean
1379. g_xim_protocol10_closure_signal_XIM_CLOSE_REPLY(GXimProtocol *proto,
1380. guint16 imid)
1381. {
1382. MSG_NOIMPL_IM(XIM_CLOSE_REPLY, imid);
1383. return TRUE;
1384. }
1385. static gboolean
1386. g_xim_protocol10_closure_signal_XIM_REGISTER_TRIGGERKEYS(GXimProtocol *proto,
1387. guint16 imid,
1388. const GSList *onkeys,
1389. const GSList *offkeys)
1390. {
1391. MSG_NOIMPL_IM(XIM_REGISTER_TRIGGERKEYS, imid);
1392. return TRUE;
1393. }
1394. static gboolean
1395. g_xim_protocol10_closure_signal_XIM_TRIGGER_NOTIFY(GXimProtocol *proto,
1396. guint16 imid,
1397. guint16 icid,
1398. guint32 flag,
1399. guint32 index_,
1400. guint32 mask)
1401. {
1402. SIG_NOIMPL_IMIC(XIM_TRIGGER_NOTIFY, imid, icid);
1403. return TRUE;
1404. }
1405. static gboolean
1406. g_xim_protocol10_closure_signal_XIM_TRIGGER_NOTIFY_REPLY(GXimProtocol *proto,
1407. guint16 imid,
1408. guint16 icid)
1409. {
1410. MSG_NOIMPL_IMIC(XIM_TRIGGER_NOTIFY_REPLY, imid, icid);
1411. return TRUE;
1412. }
1413. static gboolean
1414. g_xim_protocol10_closure_signal_XIM_SET_EVENT_MASK(GXimProtocol *proto,
1415. guint16 imid,
1416. guint16 icid,
1417. guint32 forward_event_mask,
1418. guint32 synchronous_event_mask)
1419. {
1420. MSG_NOIMPL_IMIC(XIM_SET_EVENT_MASK, imid, icid);
1421. return TRUE;
1422. }
1423. static gboolean
1424. g_xim_protocol10_closure_signal_XIM_ENCODING_NEGOTIATION(GXimProtocol *proto,
1425. guint16 imid,
1426. const GSList *encodings,
1427. const GSList *details)
1428. {
1429. SIG_NOIMPL_IM(XIM_ENCODING_NEGOTIATION, imid);
1430. return TRUE;
1431. }
1432. static gboolean
1433. g_xim_protocol10_closure_signal_XIM_ENCODING_NEGOTIATION_REPLY(GXimProtocol *proto,
1434. guint16 imid,
1435. guint16 category,
1436. gint16 index_)
1437. {
1438. MSG_NOIMPL_IM(XIM_ENCODING_NEGOTIATION_REPLY, imid);
1439. return TRUE;
1440. }
1441. static gboolean
1442. g_xim_protocol10_closure_signal_XIM_QUERY_EXTENSION(GXimProtocol *proto,
1443. guint16 imid,
1444. const GSList *extensions)
1445. {
1446. SIG_NOIMPL_IM(XIM_QUERY_EXTENSION, imid);
1447. return TRUE;
1448. }
1449. static gboolean
1450. g_xim_protocol10_closure_signal_XIM_QUERY_EXTENSION_REPLY(GXimProtocol *proto,
1451. guint16 imid,
1452. const GSList *extensions)
1453. {
1454. MSG_NOIMPL_IM(XIM_QUERY_EXTENSION_REPLY, imid);
1455. return TRUE;
1456. }
1457. static gboolean
1458. g_xim_protocol10_closure_signal_XIM_SET_IM_VALUES(GXimProtocol *proto,
1459. guint16 imid,
1460. const GSList *attributes)
1461. {
1462. SIG_NOIMPL_IM(XIM_SET_IM_VALUES, imid);
1463. return TRUE;
1464. }
1465. static gboolean
1466. g_xim_protocol10_closure_signal_XIM_SET_IM_VALUES_REPLY(GXimProtocol *proto,
1467. guint16 imid)
1468. {
1469. MSG_NOIMPL_IM(XIM_SET_IM_VALUES_REPLY, imid);
1470. return TRUE;
1471. }
1472. static gboolean
1473. g_xim_protocol10_closure_signal_XIM_GET_IM_VALUES(GXimProtocol *proto,
1474. guint16 imid,
1475. const GSList *attr_id)
1476. {
1477. SIG_NOIMPL_IM(XIM_GET_IM_VALUES, imid);
1478. return TRUE;
1479. }
1480. static gboolean
1481. g_xim_protocol10_closure_signal_XIM_GET_IM_VALUES_REPLY(GXimProtocol *proto,
1482. guint16 imid,
1483. const GSList *attributes)
1484. {
1485. MSG_NOIMPL_IM(XIM_GET_IM_VALUES_REPLY, imid);
1486. return TRUE;
1487. }
1488. static gboolean
1489. g_xim_protocol10_closure_signal_XIM_CREATE_IC(GXimProtocol *proto,
1490. guint16 imid,
1491. const GSList *attributes)
1492. {
1493. SIG_NOIMPL_IM(XIM_CREATE_IC, imid);
1494. return TRUE;
1495. }
1496. static gboolean
1497. g_xim_protocol10_closure_signal_XIM_CREATE_IC_REPLY(GXimProtocol *proto,
1498. guint16 imid,
1499. guint16 icid)
1500. {
1501. MSG_NOIMPL_IMIC(XIM_CREATE_IC_REPLY, imid, icid);
1502. return TRUE;
1503. }
1504. static gboolean
1505. g_xim_protocol10_closure_signal_XIM_DESTROY_IC(GXimProtocol *proto,
1506. guint16 imid,
1507. guint16 icid)
1508. {
1509. MSG_NOIMPL_IMIC(XIM_DESTROY_IC, imid, icid);
1510. if (!G_IS_XIM_SERVER_CONNECTION (proto)) {
1511. g_xim_messages_error(G_XIM_PROTOCOL_GET_IFACE (proto)->message,
1512. "Non-server connection received XIM_DESTROY_IC [imid: %d, icid: %d]",
1513. imid, icid);
1514. return FALSE;
1515. }
1516. return g_xim_server_connection_cmd_destroy_ic_reply(G_XIM_SERVER_CONNECTION (proto), imid, icid);
1517. }
1518. static gboolean
1519. g_xim_protocol10_closure_signal_XIM_DESTROY_IC_REPLY(GXimProtocol *proto,
1520. guint16 imid,
1521. guint16 icid)
1522. {
1523. MSG_NOIMPL_IMIC(XIM_DESTROY_IC_REPLY, imid, icid);
1524. return TRUE;
1525. }
1526. static gboolean
1527. g_xim_protocol10_closure_signal_XIM_SET_IC_VALUES(GXimProtocol *proto,
1528. guint16 imid,
1529. guint16 icid,
1530. const GSList *attributes)
1531. {
1532. SIG_NOIMPL_IMIC(XIM_SET_IC_VALUES, imid, icid);
1533. return TRUE;
1534. }
1535. static gboolean
1536. g_xim_protocol10_closure_signal_XIM_SET_IC_VALUES_REPLY(GXimProtocol *proto,
1537. guint16 imid,
1538. guint16 icid)
1539. {
1540. MSG_NOIMPL_IMIC(XIM_SET_IC_VALUES_REPLY, imid, icid);
1541. return TRUE;
1542. }
1543. static gboolean
1544. g_xim_protocol10_closure_signal_XIM_GET_IC_VALUES(GXimProtocol *proto,
1545. guint16 imid,
1546. guint16 icid,
1547. const GSList *attr_id)
1548. {
1549. SIG_NOIMPL_IMIC(XIM_GET_IC_VALUES, imid, icid);
1550. return TRUE;
1551. }
1552. static gboolean
1553. g_xim_protocol10_closure_signal_XIM_GET_IC_VALUES_REPLY(GXimProtocol *proto,
1554. guint16 imid,
1555. guint16 icid,
1556. const GSList *attributes)
1557. {
1558. MSG_NOIMPL_IMIC(XIM_GET_IC_VALUES_REPLY, imid, icid);
1559. return TRUE;
1560. }
1561. static gboolean
1562. g_xim_protocol10_closure_signal_XIM_SET_IC_FOCUS(GXimProtocol *proto,
1563. guint16 imid,
1564. guint16 icid)
1565. {
1566. MSG_NOIMPL_IMIC(XIM_SET_IC_FOCUS, imid, icid);
1567. return TRUE;
1568. }
1569. static gboolean
1570. g_xim_protocol10_closure_signal_XIM_UNSET_IC_FOCUS(GXimProtocol *proto,
1571. guint16 imid,
1572. guint16 icid)
1573. {
1574. MSG_NOIMPL_IMIC(XIM_UNSET_IC_FOCUS, imid, icid);
1575. return TRUE;
1576. }
1577. static gboolean
1578. g_xim_protocol10_closure_signal_XIM_FORWARD_EVENT(GXimProtocol *proto,
1579. guint16 imid,
1580. guint16 icid,
1581. guint16 flag,
1582. GdkEvent *event)
1583. {
1584. MSG_NOIMPL_IMIC(XIM_FORWARD_EVENT, imid, icid);
1585. if (flag & G_XIM_Event_Synchronous)
1586. g_xim_connection_cmd_sync_reply(G_XIM_CONNECTION (proto), imid, icid);
1587. g_xim_connection_cmd_forward_event(G_XIM_CONNECTION (proto), imid, icid, flag & ~G_XIM_Event_Synchronous, event);
1588. return TRUE;
1589. }
1590. static gboolean
1591. g_xim_protocol10_closure_signal_XIM_SYNC(GXimProtocol *proto,
1592. guint16 imid,
1593. guint16 icid)
1594. {
1595. MSG_NOIMPL_IMIC(XIM_SYNC, imid, icid);
1596. return g_xim_connection_cmd_sync_reply(G_XIM_CONNECTION (proto), imid, icid);
1597. }
1598. static gboolean
1599. g_xim_protocol10_closure_signal_XIM_SYNC_REPLY(GXimProtocol *proto,
1600. guint16 imid,
1601. guint16 icid)
1602. {
1603. MSG_NOIMPL_IMIC(XIM_SYNC_REPLY, imid, icid);
1604. return TRUE;
1605. }
1606. static gboolean
1607. g_xim_protocol10_closure_signal_XIM_COMMIT(GXimProtocol *proto,
1608. guint16 imid,
1609. guint16 icid,
1610. guint16 flag,
1611. guint32 keysym,
1612. GString *string)
1613. {
1614. MSG_NOIMPL_IMIC(XIM_COMMIT, imid, icid);
1615. if (flag & G_XIM_XLookupSynchronous)
1616. return g_xim_connection_cmd_sync_reply(G_XIM_CONNECTION (proto), imid, icid);
1617. return TRUE;
1618. }
1619. static gboolean
1620. g_xim_protocol10_closure_signal_XIM_RESET_IC(GXimProtocol *proto,
1621. guint16 imid,
1622. guint16 icid)
1623. {
1624. SIG_NOIMPL_IMIC(XIM_RESET_IC, imid, icid);
1625. return TRUE;
1626. }
1627. static gboolean
1628. g_xim_protocol10_closure_signal_XIM_RESET_IC_REPLY(GXimProtocol *proto,
1629. guint16 imid,
1630. guint16 icid,
1631. const GString *string)
1632. {
1633. MSG_NOIMPL_IMIC(XIM_RESET_IC_REPLY, imid, icid);
1634. return TRUE;
1635. }
1636. static gboolean
1637. g_xim_protocol10_closure_signal_XIM_GEOMETRY(GXimProtocol *proto,
1638. guint16 imid,
1639. guint16 icid)
1640. {
1641. SIG_NOIMPL_IMIC(XIM_GEOMETRY, imid, icid);
1642. return TRUE;
1643. }
1644. static gboolean
1645. g_xim_protocol10_closure_signal_XIM_STR_CONVERSION(GXimProtocol *proto,
1646. guint16 imid,
1647. guint16 icid,
1648. guint16 position,
1649. guint32 caret_direction,
1650. guint16 factor,
1651. guint16 operation,
1652. gint16 type_length)
1653. {
1654. /* XXX */
1655. SIG_NOIMPL_IMIC(XIM_STR_CONVERSION, imid, icid);
1656. return TRUE;
1657. }
1658. static gboolean
1659. g_xim_protocol10_closure_signal_XIM_STR_CONVERSION_REPLY(GXimProtocol *proto,
1660. guint16 imid,
1661. guint16 icid,
1662. guint32 feedback,
1663. GXimStrConvText *text)
1664. {
1665. MSG_NOIMPL_IMIC(XIM_STR_CONVERSION_REPLY, imid, icid);
1666. return TRUE;
1667. }
1668. static gboolean
1669. g_xim_protocol10_closure_signal_XIM_PREEDIT_START(GXimProtocol *proto,
1670. guint16 imid,
1671. guint16 icid)
1672. {
1673. /* XXX */
1674. SIG_NOIMPL_IMIC(XIM_PREEDIT_START, imid, icid);
1675. return TRUE;
1676. }
1677. static gboolean
1678. g_xim_protocol10_closure_signal_XIM_PREEDIT_START_REPLY(GXimProtocol *proto,
1679. guint16 imid,
1680. guint16 icid,
1681. gint32 return_value)
1682. {
1683. SIG_NOIMPL_IMIC(XIM_PREEDIT_START_REPLY, imid, icid);
1684. return TRUE;
1685. }
1686. static gboolean
1687. g_xim_protocol10_closure_signal_XIM_PREEDIT_DRAW(GXimProtocol *proto,
1688. guint16 imid,
1689. guint16 icid,
1690. GXimPreeditDraw *draw)
1691. {
1692. MSG_NOIMPL_IMIC(XIM_PREEDIT_DRAW, imid, icid);
1693. return TRUE;
1694. }
1695. static gboolean
1696. g_xim_protocol10_closure_signal_XIM_PREEDIT_CARET(GXimProtocol *proto,
1697. guint16 imid,
1698. guint16 icid,
1699. GXimPreeditCaret *caret)
1700. {
1701. /* XXX */
1702. SIG_NOIMPL_IMIC(XIM_PREEDIT_CARET, imid, icid);
1703. return TRUE;
1704. }
1705. static gboolean
1706. g_xim_protocol10_closure_signal_XIM_PREEDIT_CARET_REPLY(GXimProtocol *proto,
1707. guint16 imid,
1708. guint16 icid,
1709. guint32 position)
1710. {
1711. MSG_NOIMPL_IMIC(XIM_PREEDIT_CARET_REPLY, imid, icid);
1712. return TRUE;
1713. }
1714. static gboolean
1715. g_xim_protocol10_closure_signal_XIM_PREEDIT_DONE(GXimProtocol *proto,
1716. guint16 imid,
1717. guint16 icid)
1718. {
1719. MSG_NOIMPL_IMIC(XIM_PREEDIT_DONE, imid, icid);
1720. return TRUE;
1721. }
1722. static gboolean
1723. g_xim_protocol10_closure_signal_XIM_STATUS_START(GXimProtocol *proto,
1724. guint16 imid,
1725. guint16 icid)
1726. {
1727. MSG_NOIMPL_IMIC(XIM_STATUS_START, imid, icid);
1728. return TRUE;
1729. }
1730. static gboolean
1731. g_xim_protocol10_closure_signal_XIM_STATUS_DRAW(GXimProtocol *proto,
1732. guint16 imid,
1733. guint16 icid,
1734. GXimStatusDraw *draw)
1735. {
1736. MSG_NOIMPL_IMIC(XIM_STATUS_DRAW, imid, icid);
1737. return TRUE;
1738. }
1739. static gboolean
1740. g_xim_protocol10_closure_signal_XIM_STATUS_DONE(GXimProtocol *proto,
1741. guint16 imid,
1742. guint16 icid)
1743. {
1744. MSG_NOIMPL_IMIC(XIM_STATUS_DONE, imid, icid);
1745. return TRUE;
1746. }
1747. static gboolean
1748. g_xim_protocol10_closure_signal_XIM_PREEDITSTATE(GXimProtocol *proto,
1749. guint16 imid,
1750. guint16 icid,
1751. guint32 mask)
1752. {
1753. MSG_NOIMPL_IMIC(XIM_PREEDITSTATE, imid, icid);
1754. return TRUE;
1755. }
1756. static gboolean
1757. g_xim_protocol10_closure_real_parser_error(GXimProtocol *proto,
1758. guint major_opcode,
1759. guint minor_opcode,
1760. guint imid,
1761. guint icid,
1762. gpointer data)
1763. {
1764. gboolean retval = TRUE;
1765. gchar *msg;
1766. guint flag = G_XIM_EMASK_NO_VALID_ID;
1767. if (minor_opcode != 0)
1768. return FALSE;
1769. msg = g_strdup_printf("Unable to parse the protocol %s properly",
1770. g_xim_protocol_name(major_opcode));
1771. g_xim_messages_error(G_XIM_PROTOCOL_GET_IFACE (proto)->message, "%s", msg);
1772. switch (major_opcode) {
1773. case G_XIM_CONNECT:
1774. case G_XIM_AUTH_REQUIRED:
1775. case G_XIM_AUTH_REPLY:
1776. case G_XIM_AUTH_NEXT:
1777. case G_XIM_AUTH_SETUP:
1778. retval = g_xim_connection_cmd_auth_ng(G_XIM_CONNECTION (proto));
1779. break;
1780. case G_XIM_SYNC:
1781. retval = g_xim_connection_cmd_sync_reply(G_XIM_CONNECTION (proto), imid, icid);
1782. break;
1783. default:
1784. if (imid > 0)
1785. flag |= G_XIM_EMASK_VALID_IMID;
1786. if (icid > 0)
1787. flag |= G_XIM_EMASK_VALID_ICID;
1788. retval = g_xim_connection_cmd_error(G_XIM_CONNECTION (proto),
1789. imid, icid, flag,
1790. G_XIM_ERR_BadProtocol, 0, msg);
1791. break;
1792. }
1793. g_free(msg);
1794. return retval;
1795. }
1796. /*
1797. * Public functions
1798. */
1799. gboolean
1800. g_xim_protocol10_closure_init(GXimProtocol *proto,
1801. gpointer data)
1802. {
1803. GXimProtocolPrivate *priv = g_xim_protocol_get_private(proto);
1804. #define SET(_m_,_n_,_f_,...) \
1805. G_STMT_START { \
1806. GXimProtocolClosure *_c_; \
1807. \
1808. _c_ = g_xim_protocol_closure_new(G_ ## _m_, (_n_), #_m_, FALSE); \
1809. G_XIM_CHECK_ALLOC (_c_, FALSE); \
1810. g_xim_protocol_closure_set_marshal(_c_, g_xim_protocol10_closure_ ## _m_, data); \
1811. g_xim_protocol_closure_add_signal(_c_, (_f_), __VA_ARGS__); \
1812. g_xim_protocol_add_protocol(proto, _c_); \
1813. priv->base_signal_ids[G_ ## _m_] = g_xim_protocol_connect_closure_by_id(proto, \
1814. G_ ## _m_, \
1815. (_n_), \
1816. G_CALLBACK (g_xim_protocol10_closure_signal_ ## _m_), \
1817. NULL); \
1818. } G_STMT_END
1819. SET (XIM_CONNECT, 0, gxim_marshal_BOOLEAN__UINT_UINT_POINTER,
1820. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_POINTER);
1821. SET (XIM_CONNECT_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1822. 2, G_TYPE_UINT, G_TYPE_UINT);
1823. SET (XIM_DISCONNECT, 0, gxim_marshal_BOOLEAN__VOID,
1824. 0);
1825. SET (XIM_DISCONNECT_REPLY, 0, gxim_marshal_BOOLEAN__VOID,
1826. 0);
1827. SET (XIM_AUTH_REQUIRED, 0, gxim_marshal_FIXME, 0);
1828. SET (XIM_AUTH_REPLY, 0, gxim_marshal_FIXME, 0);
1829. SET (XIM_AUTH_NEXT, 0, gxim_marshal_FIXME, 0);
1830. SET (XIM_AUTH_SETUP, 0, gxim_marshal_FIXME, 0);
1831. SET (XIM_AUTH_NG, 0, gxim_marshal_BOOLEAN__VOID,
1832. 0);
1833. SET (XIM_ERROR, 0, gxim_marshal_BOOLEAN__UINT_UINT_UINT_UINT_UINT_STRING,
1834. 6, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_STRING);
1835. SET (XIM_OPEN, 0, gxim_marshal_BOOLEAN__BOXED,
1836. 1, G_TYPE_XIM_STR);
1837. SET (XIM_OPEN_REPLY, 0, gxim_marshal_BOOLEAN__UINT_OBJECT_OBJECT,
1838. 3, G_TYPE_UINT, G_TYPE_XIM_IM_ATTR, G_TYPE_XIM_IC_ATTR);
1839. SET (XIM_CLOSE, 0, gxim_marshal_BOOLEAN__UINT,
1840. 1, G_TYPE_UINT);
1841. SET (XIM_CLOSE_REPLY, 0, gxim_marshal_BOOLEAN__UINT,
1842. 1, G_TYPE_UINT);
1843. SET (XIM_REGISTER_TRIGGERKEYS, 0, gxim_marshal_BOOLEAN__UINT_POINTER_POINTER,
1844. 3, G_TYPE_UINT, G_TYPE_POINTER, G_TYPE_POINTER);
1845. SET (XIM_TRIGGER_NOTIFY, 0, gxim_marshal_BOOLEAN__UINT_UINT_ULONG_ULONG_ULONG,
1846. 5, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_ULONG, G_TYPE_ULONG, G_TYPE_ULONG);
1847. SET (XIM_TRIGGER_NOTIFY_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1848. 2, G_TYPE_UINT, G_TYPE_UINT);
1849. SET (XIM_SET_EVENT_MASK, 0, gxim_marshal_BOOLEAN__UINT_UINT_ULONG_ULONG,
1850. 4, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_ULONG, G_TYPE_ULONG);
1851. SET (XIM_ENCODING_NEGOTIATION, 0, gxim_marshal_BOOLEAN__UINT_POINTER_POINTER,
1852. 3, G_TYPE_UINT, G_TYPE_POINTER, G_TYPE_POINTER);
1853. SET (XIM_ENCODING_NEGOTIATION_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT_INT,
1854. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_INT);
1855. SET (XIM_QUERY_EXTENSION, 0, gxim_marshal_BOOLEAN__UINT_POINTER,
1856. 2, G_TYPE_UINT, G_TYPE_POINTER);
1857. SET (XIM_QUERY_EXTENSION_REPLY, 0, gxim_marshal_BOOLEAN__UINT_POINTER,
1858. 2, G_TYPE_UINT, G_TYPE_POINTER);
1859. SET (XIM_SET_IM_VALUES, 0, gxim_marshal_BOOLEAN__UINT_POINTER,
1860. 2, G_TYPE_UINT, G_TYPE_POINTER);
1861. SET (XIM_SET_IM_VALUES_REPLY, 0, gxim_marshal_BOOLEAN__UINT,
1862. 1, G_TYPE_UINT);
1863. SET (XIM_GET_IM_VALUES, 0, gxim_marshal_BOOLEAN__UINT_POINTER,
1864. 2, G_TYPE_UINT, G_TYPE_POINTER);
1865. SET (XIM_GET_IM_VALUES_REPLY, 0, gxim_marshal_BOOLEAN__UINT_POINTER,
1866. 2, G_TYPE_UINT, G_TYPE_POINTER);
1867. SET (XIM_CREATE_IC, 0, gxim_marshal_BOOLEAN__UINT_POINTER,
1868. 2, G_TYPE_UINT, G_TYPE_POINTER);
1869. SET (XIM_CREATE_IC_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1870. 2, G_TYPE_UINT, G_TYPE_UINT);
1871. SET (XIM_DESTROY_IC, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1872. 2, G_TYPE_UINT, G_TYPE_UINT);
1873. SET (XIM_DESTROY_IC_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1874. 2, G_TYPE_UINT, G_TYPE_UINT);
1875. SET (XIM_SET_IC_VALUES, 0, gxim_marshal_BOOLEAN__UINT_UINT_POINTER,
1876. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_POINTER);
1877. SET (XIM_SET_IC_VALUES_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1878. 2, G_TYPE_UINT, G_TYPE_UINT);
1879. SET (XIM_GET_IC_VALUES, 0, gxim_marshal_BOOLEAN__UINT_UINT_POINTER,
1880. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_POINTER);
1881. SET (XIM_GET_IC_VALUES_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT_POINTER,
1882. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_POINTER);
1883. SET (XIM_SET_IC_FOCUS, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1884. 2, G_TYPE_UINT, G_TYPE_UINT);
1885. SET (XIM_UNSET_IC_FOCUS, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1886. 2, G_TYPE_UINT, G_TYPE_UINT);
1887. SET (XIM_FORWARD_EVENT, 0, gxim_marshal_BOOLEAN__UINT_UINT_UINT_BOXED,
1888. 4, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT, GDK_TYPE_EVENT);
1889. SET (XIM_SYNC, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1890. 2, G_TYPE_UINT, G_TYPE_UINT);
1891. SET (XIM_SYNC_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1892. 2, G_TYPE_UINT, G_TYPE_UINT);
1893. SET (XIM_COMMIT, 0, gxim_marshal_BOOLEAN__UINT_UINT_UINT_ULONG_BOXED,
1894. 5, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_ULONG, G_TYPE_GSTRING);
1895. SET (XIM_RESET_IC, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1896. 2, G_TYPE_UINT, G_TYPE_UINT);
1897. SET (XIM_RESET_IC_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT_BOXED,
1898. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_GSTRING);
1899. SET (XIM_GEOMETRY, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1900. 2, G_TYPE_UINT, G_TYPE_UINT);
1901. SET (XIM_STR_CONVERSION, 0, gxim_marshal_FIXME, 0);
1902. SET (XIM_STR_CONVERSION_REPLY, 0, gxim_marshal_FIXME, 0);
1903. SET (XIM_PREEDIT_START, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1904. 2, G_TYPE_UINT, G_TYPE_UINT);
1905. SET (XIM_PREEDIT_START_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT_LONG,
1906. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_LONG);
1907. SET (XIM_PREEDIT_DRAW, 0, gxim_marshal_BOOLEAN__UINT_UINT_BOXED,
1908. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_XIM_PREEDIT_DRAW);
1909. SET (XIM_PREEDIT_CARET, 0, gxim_marshal_BOOLEAN__UINT_UINT_BOXED,
1910. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_XIM_PREEDIT_CARET);
1911. SET (XIM_PREEDIT_CARET_REPLY, 0, gxim_marshal_BOOLEAN__UINT_UINT_ULONG,
1912. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_ULONG);
1913. SET (XIM_PREEDIT_DONE, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1914. 2, G_TYPE_UINT, G_TYPE_UINT);
1915. SET (XIM_STATUS_START, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1916. 2, G_TYPE_UINT, G_TYPE_UINT);
1917. SET (XIM_STATUS_DRAW, 0, gxim_marshal_BOOLEAN__UINT_UINT_BOXED,
1918. 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_XIM_STATUS_DRAW);
1919. SET (XIM_STATUS_DONE, 0, gxim_marshal_BOOLEAN__UINT_UINT,
1920. 2, G_TYPE_UINT, G_TYPE_UINT);
1921. SET (XIM_PREEDITSTATE, 0, gxim_marshal_FIXME, 0);
1922. #undef SET
1923. g_signal_connect_after(proto, "parser_error",
1924. G_CALLBACK (g_xim_protocol10_closure_real_parser_error),
1925. NULL);
1926. return TRUE;
1927. }
1928. void
1929. g_xim_protocol10_closure_finalize(GXimProtocol *proto)
1930. {
1931. #define UNSET(_m_,_n_) \
1932. g_xim_protocol_remove_protocol_by_id(proto, G_ ## _m_, (_n_))
1933. UNSET (XIM_CONNECT, 0);
1934. UNSET (XIM_CONNECT_REPLY, 0);
1935. UNSET (XIM_DISCONNECT, 0);
1936. UNSET (XIM_DISCONNECT_REPLY, 0);
1937. UNSET (XIM_AUTH_REQUIRED, 0);
1938. UNSET (XIM_AUTH_REPLY, 0);
1939. UNSET (XIM_AUTH_NEXT, 0);
1940. UNSET (XIM_AUTH_SETUP, 0);
1941. UNSET (XIM_AUTH_NG, 0);
1942. UNSET (XIM_ERROR, 0);
1943. UNSET (XIM_OPEN, 0);
1944. UNSET (XIM_OPEN_REPLY, 0);
1945. UNSET (XIM_CLOSE, 0);
1946. UNSET (XIM_CLOSE_REPLY, 0);
1947. UNSET (XIM_REGISTER_TRIGGERKEYS, 0);
1948. UNSET (XIM_TRIGGER_NOTIFY, 0);
1949. UNSET (XIM_TRIGGER_NOTIFY_REPLY, 0);
1950. UNSET (XIM_SET_EVENT_MASK, 0);
1951. UNSET (XIM_ENCODING_NEGOTIATION, 0);
1952. UNSET (XIM_ENCODING_NEGOTIATION_REPLY, 0);
1953. UNSET (XIM_QUERY_EXTENSION, 0);
1954. UNSET (XIM_QUERY_EXTENSION_REPLY, 0);
1955. UNSET (XIM_SET_IM_VALUES, 0);
1956. UNSET (XIM_SET_IM_VALUES_REPLY, 0);
1957. UNSET (XIM_GET_IM_VALUES, 0);
1958. UNSET (XIM_GET_IM_VALUES_REPLY, 0);
1959. UNSET (XIM_CREATE_IC, 0);
1960. UNSET (XIM_CREATE_IC_REPLY, 0);
1961. UNSET (XIM_DESTROY_IC, 0);
1962. UNSET (XIM_DESTROY_IC_REPLY, 0);
1963. UNSET (XIM_SET_IC_VALUES, 0);
1964. UNSET (XIM_SET_IC_VALUES_REPLY, 0);
1965. UNSET (XIM_GET_IC_VALUES, 0);
1966. UNSET (XIM_GET_IC_VALUES_REPLY, 0);
1967. UNSET (XIM_SET_IC_FOCUS, 0);
1968. UNSET (XIM_UNSET_IC_FOCUS, 0);
1969. UNSET (XIM_FORWARD_EVENT, 0);
1970. UNSET (XIM_SYNC, 0);
1971. UNSET (XIM_SYNC_REPLY, 0);
1972. UNSET (XIM_COMMIT, 0);
1973. UNSET (XIM_RESET_IC, 0);
1974. UNSET (XIM_RESET_IC_REPLY, 0);
1975. UNSET (XIM_GEOMETRY, 0);
1976. UNSET (XIM_STR_CONVERSION, 0);
1977. UNSET (XIM_STR_CONVERSION_REPLY, 0);
1978. UNSET (XIM_PREEDIT_START, 0);
1979. UNSET (XIM_PREEDIT_START_REPLY, 0);
1980. UNSET (XIM_PREEDIT_DRAW, 0);
1981. UNSET (XIM_PREEDIT_CARET, 0);
1982. UNSET (XIM_PREEDIT_CARET_REPLY, 0);
1983. UNSET (XIM_PREEDIT_DONE, 0);
1984. UNSET (XIM_STATUS_START, 0);
1985. UNSET (XIM_STATUS_DRAW, 0);
1986. UNSET (XIM_STATUS_DONE, 0);
1987. UNSET (XIM_PREEDITSTATE, 0);
1988. #undef UNSET
1989. }
|
__label__pos
| 0.99987 |
Chat Zalo Chat Messenger Phone Number Đăng nhập
13 Basic Cat Command Examples in Linux Terminal - Tecmint
13 Basic Cat Command Examples in Linux Terminal – Tecmint
The cat command (short for “concatenate“) is one of the most commonly used commands in Linux/Unix-like operating systems. The cat command allows us to create one or more files, view the contents of a file, concatenate files and redirect the output in terminal or files.
In this article, we will discover the practical use of cat commands with their examples in Linux.
Also read: Learn how to use ‘cat’ and ‘tac’ (reverse of the cat command) in Linux
General syntax of the cat
$ cat command [OPTION] [FILE]… 1. Display the contents of the file
The following example will display the contents of the /etc/passwd file. # cat /etc/passwd
root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin narad:x:500:500::/home/narad:/bin/bash
2. View the contents of multiple files
in the terminal
In the following example, it will display the contents of the test and test1 file in the terminal
. # cat test1 Hello everyone Hello world,
3. Create
a file with the cat command
We will create a file called test2 file with the following command
. # cat >test2
Wait for user input, type the desired text, and press CTRL+D (hold down the Ctrl key and type ‘d‘) to exit. The text will be written to the test2 file. You can view the contents of the file with the following cat command.
# Cat test2 Hello everyone, how do you do it?
4. Use
the cat command with more and less options
If a file that has a lot of content that does not fit in the output terminal and the screen scrolls very fast, we can use plus and minus parameters with the cat command as shown below
. # Cat Song.txt | More # Cat Song.txt | Minus
5. Show
line numbers in the file With the
-n option you can view the line numbers of a stock song.txt in the output terminal.
# cat -n song.txt 1 “Heal the world” 2 There is a place in 3 Your heart 4 And I know it is love 5 And this place could 6 be much brighter than tomorrow 8 And if you really try 9 you will find that there is no need to cry 10 in 11 In this place you will feel 12 There is no pain or sadness
6. Show
$ at the end of the file
You can then see with the -e option that ‘$’ is displayed at the end of the line and also in the space showing ‘$‘ if there is any space between paragraphs. This option is useful for compressing multiple lines into a single line.
# cat -e test hello everyone, how’s it going?$ $ Hey, I’m fine.$ How is your training going?$
$7. Show tab-separated lines in
the
file In the next output, we could see that the TAB space is filled with the characters ‘^I’.
# cat -T try hello ^I everyone, how do you do it? Hey, ^I’mfine. ^ I^IHow’s your training ^Igoing on? Let’s ^Ido some practice on Linux.
8. Show multiple files at once
In the following example we have three test files, test1 and test2, and we can see the contents of those files as shown above. We need to separate each file with ; (semicolon).
# cat test; cat test1; cat test2 This is a test file This is the test1 file. This is the test2 file. 9. Use standard output with
redirection operator We can redirect
the standard output of a file to a new file or existing file with a ‘>‘ symbol (greater than). The careful and existing content of the test1 will be overwritten with the contents of the test file.
# Cat test > test1
10. Append standard output with redirection operator
Appended to existing file with symbol ‘>>‘ (twice greater than). Here, the contents of the test file will be appended to the end of the test1 file.
# Cat test >> test1 11
. Standard input
redirection with redirection operator When you use
the redirection with standard input ‘<‘ (less than symbol), you use the filename test2 as input for the command and the output will be displayed in a terminal. # cat < test2 This is the test2 file. 12.
Redirect multiple files contained
in a single file
This will create a file called test3 and all output will be redirected into a newly created file
. # Cat test1 test2 > test3 13
. Sort the contents of multiple files into a single
file
This will create a test4 file and the output of the cat command will be piped to sort and the result will be redirected to a newly created file
. # cat test1 test2 test3 | sort > test4
This article lists basic commands that can help you explore cat commands. You can refer to the cat command man page for more options.
In our next article, we will cover more advanced cat commands. Please share it if you find this article useful via our comment box below.
Contact US
|
__label__pos
| 0.876732 |
ClassesClassesClassesClasses | | | | Operators
create_calib_datacreate_calib_dataCreateCalibDatacreate_calib_dataCreateCalibDataCreateCalibData (Operator)
Name
create_calib_datacreate_calib_dataCreateCalibDatacreate_calib_dataCreateCalibDataCreateCalibData — Create a HALCON calibration data model.
Signature
create_calib_data( : : CalibSetup, NumCameras, NumCalibObjects : CalibDataID)
Herror create_calib_data(const char* CalibSetup, const Hlong NumCameras, const Hlong NumCalibObjects, Hlong* CalibDataID)
Herror T_create_calib_data(const Htuple CalibSetup, const Htuple NumCameras, const Htuple NumCalibObjects, Htuple* CalibDataID)
Herror create_calib_data(const HTuple& CalibSetup, const HTuple& NumCameras, const HTuple& NumCalibObjects, Hlong* CalibDataID)
void HCalibData::CreateCalibData(const HTuple& CalibSetup, const HTuple& NumCameras, const HTuple& NumCalibObjects)
void CreateCalibData(const HTuple& CalibSetup, const HTuple& NumCameras, const HTuple& NumCalibObjects, HTuple* CalibDataID)
void HCalibData::HCalibData(const HString& CalibSetup, Hlong NumCameras, Hlong NumCalibObjects)
void HCalibData::HCalibData(const char* CalibSetup, Hlong NumCameras, Hlong NumCalibObjects)
void HCalibData::CreateCalibData(const HString& CalibSetup, Hlong NumCameras, Hlong NumCalibObjects)
void HCalibData::CreateCalibData(const char* CalibSetup, Hlong NumCameras, Hlong NumCalibObjects)
void HOperatorSetX.CreateCalibData(
[in] VARIANT CalibSetup, [in] VARIANT NumCameras, [in] VARIANT NumCalibObjects, [out] VARIANT* CalibDataID)
void HCalibDataX.CreateCalibData(
[in] BSTR CalibSetup, [in] Hlong NumCameras, [in] Hlong NumCalibObjects)
static void HOperatorSet.CreateCalibData(HTuple calibSetup, HTuple numCameras, HTuple numCalibObjects, out HTuple calibDataID)
public HCalibData(string calibSetup, int numCameras, int numCalibObjects)
void HCalibData.CreateCalibData(string calibSetup, int numCameras, int numCalibObjects)
Description
The operator create_calib_datacreate_calib_dataCreateCalibDatacreate_calib_dataCreateCalibDataCreateCalibData creates a generic calibration data model that stores
In the parameter CalibSetupCalibSetupCalibSetupCalibSetupCalibSetupcalibSetup, you specify the calibration setup type. Currently, three types are supported. A model of the type 'calibration_object'"calibration_object""calibration_object""calibration_object""calibration_object""calibration_object" is used to calibrate the internal camera parameters and the camera poses of one or more cameras based on the metric information extracted from observations of calibration objects. A model of type 'hand_eye_moving_cam'"hand_eye_moving_cam""hand_eye_moving_cam""hand_eye_moving_cam""hand_eye_moving_cam""hand_eye_moving_cam" or 'hand_eye_stationary_cam'"hand_eye_stationary_cam""hand_eye_stationary_cam""hand_eye_stationary_cam""hand_eye_stationary_cam""hand_eye_stationary_cam" is used to perform a hand-eye calibration based on observations of a calibration object and corresponding poses of a robot tool in the robot base coordinate system. NumCamerasNumCamerasNumCamerasNumCamerasNumCamerasnumCameras specifies the number of cameras that are calibrated simultaneously in the setup. NumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsnumCalibObjects specifies the number calibration objects observed by the cameras. Please note that for camera calibrations with line-scan cameras only a single calibration object is allowed (NumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsnumCalibObjects=1). For hand-eye calibrations, only two setups are currently supported: either one area-scan projective camera and one calibration object (NumCamerasNumCamerasNumCamerasNumCamerasNumCamerasnumCameras=1, NumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsnumCalibObjects=1) or a general sensor with no calibration object (NumCamerasNumCamerasNumCamerasNumCamerasNumCamerasnumCameras=0, NumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsnumCalibObjects=0).
CalibDataIDCalibDataIDCalibDataIDCalibDataIDCalibDataIDcalibDataID returns a handle of the new calibration data model. You pass this handle to other operators to collect the description of the camera setup, the calibration settings, and the calibration data. For camera calibrations, you pass it to calibrate_camerascalibrate_camerasCalibrateCamerascalibrate_camerasCalibrateCamerasCalibrateCameras, which performs the actual camera calibration and stores the calibration results in the calibration data model. For a detailed description of the preparation process, please refer to the operator calibrate_camerascalibrate_camerasCalibrateCamerascalibrate_camerasCalibrateCamerasCalibrateCameras. For hand-eye calibrations, you pass it to calibrate_hand_eyecalibrate_hand_eyeCalibrateHandEyecalibrate_hand_eyeCalibrateHandEyeCalibrateHandEye, which performs the actual hand-eye calibration and stores the calibration results in the calibration data model. For a detailed description of the preparation process, please refer to the operator calibrate_hand_eyecalibrate_hand_eyeCalibrateHandEyecalibrate_hand_eyeCalibrateHandEyeCalibrateHandEye.
Attention
A camera calibration data model CalibDataID cannot be shared between two or more user's threads. Different camera calibration data models can be used independently and safely in different threads.
Parallelization
Parameters
CalibSetupCalibSetupCalibSetupCalibSetupCalibSetupcalibSetup (input_control) string HTupleHTupleHTupleVARIANTHtuple (string) (string) (HString) (char*) (BSTR) (char*)
Type of the calibration setup.
Default value: 'calibration_object' "calibration_object" "calibration_object" "calibration_object" "calibration_object" "calibration_object"
List of values: 'calibration_object'"calibration_object""calibration_object""calibration_object""calibration_object""calibration_object", 'hand_eye_moving_cam'"hand_eye_moving_cam""hand_eye_moving_cam""hand_eye_moving_cam""hand_eye_moving_cam""hand_eye_moving_cam", 'hand_eye_stationary_cam'"hand_eye_stationary_cam""hand_eye_stationary_cam""hand_eye_stationary_cam""hand_eye_stationary_cam""hand_eye_stationary_cam"
NumCamerasNumCamerasNumCamerasNumCamerasNumCamerasnumCameras (input_control) number HTupleHTupleHTupleVARIANTHtuple (integer) (int / long) (Hlong) (Hlong) (Hlong) (Hlong)
Number of cameras in the calibration setup.
Default value: 1
Restriction: NumCameras >= 0
NumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsNumCalibObjectsnumCalibObjects (input_control) number HTupleHTupleHTupleVARIANTHtuple (integer) (int / long) (Hlong) (Hlong) (Hlong) (Hlong)
Number of calibration objects.
Default value: 1
Restriction: NumCalibObjects >= 0
CalibDataIDCalibDataIDCalibDataIDCalibDataIDCalibDataIDcalibDataID (output_control) calib_data HCalibData, HTupleHTupleHCalibData, HTupleHCalibDataX, VARIANTHtuple (integer) (IntPtr) (Hlong) (Hlong) (Hlong) (Hlong)
Handle of the created calibration data model.
Possible Successors
set_calib_data_cam_paramset_calib_data_cam_paramSetCalibDataCamParamset_calib_data_cam_paramSetCalibDataCamParamSetCalibDataCamParam, set_calib_data_calib_objectset_calib_data_calib_objectSetCalibDataCalibObjectset_calib_data_calib_objectSetCalibDataCalibObjectSetCalibDataCalibObject
Module
Calibration
ClassesClassesClassesClasses | | | | Operators
|
__label__pos
| 0.786279 |
The Revised Definition of Network Protocol
Hey Team,
The post below is my revised version of the assignment 1:3 writing definition based on the suggestions from Amy.
Term
Network Protocol
Situation
A software developer in a mobile application company is explaining to the product manager about how their mobile application communicates with each other through the network.
Parenthetical Definition
Communication contract between network devices
Sentence Definition
A network protocol is a set of rules and standards that devices need to follow when they are communicating with each other through the network.
Extended definition
Comparison and Contrast: The communication between network devices is similar to communication between people. When living in Canada, people from different countries talk in the same language (English or French) to understand each other. Similarly, network devices also need to use the same “device language” so that they can exchange information with each other, and the definition of the “device language” here is the network protocol.
Analysis of Parts: Basically, the network protocol is a set of rules that governs data communication between network devices. It has 3 key elements:
1. Syntax: Format of the basic data unit. e.g. A network protocol may define that it only supports one kind of message, which comprises 2 parts. A first part is a number called “header”, while the second part is called “body” which consists of some English characters.
2. Semantics: The meaning of different values in each part. e.g. If the header of a network protocol is a number, it may also define the number 0 in the header means “Hello”, while number 1 represents “Goodbye”.
3. Timing: The time and sequence packets should be sent. e.g. A network protocol may define that the two network devices should always begin their conservation with “Hello”.
Examples: People use network protocol almost every day when they are using the Internet. For example, when sending email messages to others, the Simple Mail Transfer Protocol (SMTP) is used under the hood. As shown in Figure 1, when the user clicked the sent button of their email application, the application (represented as “C” in the figure) and email server (represented as “S” in the figure) will communicate with each other via SMTP protocol. Based on the timing rules, they will always begin their conversation with 220 (service ready) and HELO (hello). During the conversation, code 250 is used multiple times, which means acknowledgment (or Ok) based on the definition of semantics. When the server is ready to accept email, the application will follow the syntax rules to encode the email message (there are different kinds of messages in SMTP). The addresses of sender/recipients and the title will be encoded as Email Header, while the content of the email will be encoded as Email Body.
Negation: Since the Internet is so popular nowadays, many people may assume that network protocol is the same are “Internet Protocol”. However, this idea is wrong since network protocol is a generic term of network communication contract, while the “Internet Protocol” (or IP) is just a specific network protocol that defines the way to represent the addresses of source and destination during the Internet communication.
References
Kurose, James F. Computer networking: A top-down approach featuring the internet, 3/E. Pearson Education India, 2005.
Wikipedia. Simple Mail Transfer Protocol. https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol
Stevens, W. Richard. TCP/IP illustrated vol. I: the protocols. Pearson Education India, 1994.
Leave a Reply
Your email address will not be published. Required fields are marked *
Spam prevention powered by Akismet
|
__label__pos
| 0.932797 |
Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
QtScrollBar right border in QTextEdit is not shown
• Hi everyone,
I want a QTextEdit with a scroll bar as shown in the picture below, but I am not able to display the
right border of the QTextEdit and it looks like the scroll bar is covering it. Has someone an idea,
how I can make the border on the right hand side appear again?
0_1552328829524_ScrollBar border.png
• Lifetime Qt Champion
Hi
Could you post the stylesheet code as text so one can try it out?
• Ye, sorry for that:
QTextEdit {
color:black;
background-color: white;
border-style: outset;
border-width: 2px;
border-radius: 16px;
border-color: black;
font: bold 12px;
min-width: 1em;
padding:16px;
}
QScrollBar:vertical {
background: transparent;
background-color: transparent;
width: 15px;
margin: 10px 10px 0px -5px;
}
QScrollBar::handle {
background: rgb(211,211, 211);;
border: 2px solid black;
border-radius: 6px;
margin: 0px 2px 0px 2px;
}
QScrollBar::add-line:vertical {
height: 0px;
subcontrol-position: bottom;
subcontrol-origin: margin;
}
QScrollBar::sub-line:vertical {
height: 0 px;
subcontrol-position: top;
subcontrol-origin: margin;
}
• Lifetime Qt Champion
Hi
Np. its just with stylesheet its often impossible to just guess :)
Anyway, i get another result than you.
alt text
So i wonder if you have some stylesheet on the parent ( blue box) that target QWidget and also
affect the scrollbar/text edit also.
• Thank you, indeed it was a scroll area in the background, that leaded to this behaviour.
I put it now in a QGroupBox and everything works fine.
Log in to reply
|
__label__pos
| 0.930795 |
Nature Of Force Venn Diagram
Rated 4 / 5 based on 0 reviews. | Review Me
Nature Of Force Venn Diagram - because of their high metabolic rates birds must consume more food in proportion to their size than most animals for ex le a warbler might eat 80 percent of its body weight in a day as a group birds consume just about any type of food you can imagine including hibians ants buds carrion crustaceans fish fruit grass insects larvae leaves molluscs nectar other birds pollen span class news dt dec 02 2010 span nbsp 0183 32 we learned about force and motion this week on monday we learned about push and pull and created a class double bubble map of what pushes and what pulls and what does both venn diagrams venn diagrams venn diagrams are a convenient way of visually representing information and illustrating simple relationships between two or more ideas you can teach your third graders all about this type of diagram using this printable math lesson plan taking two familiar concepts that of addition.
and multiplication you can show your students how the mon and unique preamble we the people of the state of florida being grateful to almighty god for our constitutional liberty in order to secure its benefits perfect our government insure domestic tranquility maintain public order and guarantee equal civil and political rights to all do ordain and establish this constitution the karnaugh map km or k map is a method of simplifying boolean algebra expressions maurice karnaugh introduced it in 1953 as a refinement of edward veitch s 1952 veitch chart which actually was a rediscovery of allan marquand s 1881 logical diagram aka marquand diagram but with a focus now set on its utility for switching circuits veitch charts are therefore also known as marquand there are different models definitions frameworks maps and ways to e up with an effective stakeholder strategy glad you ask it means.
you are a people manager or aware of the risks of ignoring this crucial process in effective efficient project management a named e plural as a s as a s or aes is the first letter and the first vowel of the modern english alphabet and the iso basic latin alphabet it is similar to the ancient greek letter alpha from which it derives the uppercase version consists of the two slanting sides of a triangle crossed in the middle by a horizontal bar the lowercase version can be written in two forms dear twitpic munity thank you for all the wonderful photos you have taken over the years we have now placed twitpic in an archived state
Related Wiring Diagrams
Related Diagrams
|
__label__pos
| 0.799791 |
Chapter 1: Introduction to Zokrates
Zokrates is a toolbox for zkSNARK, hiding significant complexity inherent to zero-knowledge proofs (ZKP). It provides a python-like higher-level language for developers to code the computational problem they want to prove.
We extend it to generate and verify proofs on Bitcoin.
Install
From binary
curl -Ls https://scrypt.io/scripts/setup-zokrates.sh | sh -s -
From source
You can build our extended version from source with the following commands:
git clone https://github.com/sCrypt-Inc/zokrates cd ZoKrates cargo +nightly build -p zokrates_cli --release cd target/release
Note Zokrates itself was written in Rust Language, you may need to set up the Rust environment first before trying to build it.
Workflow
The whole workflow is the same as the original ZoKrates, except that the verification step is done on Bitcoin. Generally speaking, it contains the following steps:
1. Design a circuit
Implement the circuit in the Zokrates language. For example, this simple circuit/program named factor.zok proves one knows the factorization of an integer n into two integers, without revealing the integers. The circuit has two private inputs named p and q and one public input named n. You can refer to https://zokrates.github.io/ for more information on how to use Zokrates.
// p and q are factorization of n def main(private field p, private field q, field n) { assert(p * q == n); assert(p > 1); assert(q > 1); return; }
2. Compile the circuit
Compile the circuit with the following command:
zokrates compile -i my_circuit.zok
3. Setup
This generates a proving key and a verification key for this circuit.
zokrates setup
4. Calculating a witness
A proof attests that a prover knows some secret/private information that satisfies the original program. This secret information is called a witness. In the following example, 7 and 13 are the witnesses, as they are factors of 91.
zokrates compute-witness -a 7 13 91
5. Create a proof
It produces a proof, using both the proving key and the witness.
zokrates generate-proof
6. Export an sCrypt verifier
This outputs a smart contract verifier project under verifier/, containing all the necessary code to verify a proof on chain.
zokrates export-verifier-scrypt
7. Verify the proof
You can verify it off-chain locally:
zokrates verify
Put it to the test
Complete the circuit on the right to ensure that the square of the private input x equals y .
|
__label__pos
| 0.751288 |
cancel
Showing results for
Search instead for
Did you mean:
cancel
1904
Views
25
Helpful
12
Replies
ether-channel load balance
Roel Reyes
Level 1
Level 1
Hi,
Is there any documents that states methods of load balancing works or not depending on type of operation?
like src-ip will not work on L2 etherchannel since it will be based on frames not packets or l3 addresses?
Thanks,
2 Accepted Solutions
Accepted Solutions
just confused here, if i understand correctly you have CISCO 2960 ( since @Giuseppe Larosa confused with 2950 i guess)
here is 2960 Loadbalance mechanism mentioned in the document ?
port-channel load-balance { dst-ip | dst-mac | src-dst-ip | src-dst-mac | src-ip | src-mac }
https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst2960/software/release/12-2_55_se/configuration/guide/scg_2960/swethchl.html#78975
BB
***** Rate All Helpful Responses *****
How to Ask The Cisco Community for Help
View solution in original post
A "pure" L2 switch cannot read more than the frame information but enhanced/smart/plus/etc. "L2 switches" often can examine and/or use L3 information. A 2960 falls into the latter, which is why there are load-balancing options using IP.
View solution in original post
12 Replies 12
balaji.bandi
Hall of Fame
Hall of Fame
here is the good reference document for various models :
https://www.cisco.com/c/en/us/support/docs/lan-switching/etherchannel/12023-4.html
BB
***** Rate All Helpful Responses *****
How to Ask The Cisco Community for Help
Yes,
But still they do not mention properly that using layer 3 load balancing like src ip or dst ip will not work on layer 2 etherchannel,
Hello Roel,
Layer2 etherchannels are not limited to load balancing methods at OSI Layer2.
For IPv4 traffic they can use methods like source IP and destination IP addresses.
The method uses an EXOR of last significant three bits of both source and destination addresses.
To see load balancing happening a variety of IP flows are needed.
For non IP traffic they will use L2 only methods.
What switch model are you using and what IOS version is running on it?
Hope to help
Giuseppe
I'm using old cisco 2960, im just confused, what happen if i tried to use SRC ip or DST ip as method of load balancing on L2 etherchannel? ofcourse it will not work and no load balancing will happen right?
Hello Roel,
in the case of old Cisco 2950 switches load balancing is not supported at all, they are just able to use the second link if the first link fails.
I had this issue and I have found this limitation.
IF you have a cisco 2950 switch the support is limited.
Hope to help
Giuseppe
just confused here, if i understand correctly you have CISCO 2960 ( since @Giuseppe Larosa confused with 2950 i guess)
here is 2960 Loadbalance mechanism mentioned in the document ?
port-channel load-balance { dst-ip | dst-mac | src-dst-ip | src-dst-mac | src-ip | src-mac }
https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst2960/software/release/12-2_55_se/configuration/guide/scg_2960/swethchl.html#78975
BB
***** Rate All Helpful Responses *****
How to Ask The Cisco Community for Help
Hello Balaji,
yes I thought the original poster has a C2950.
Best Regards
Giuseppe
"ofcourse it will not work and no load balancing will happen right?"
No, it can work assuming the frames on the link are contain IP packets. I.e. it doesn't matter the link is L2, it matters what kind of traffic is crossing the link. BTW, generally the "best" choice with your 2960 would be to use src-dst-ip, but the real best choice would depend on the nature of your traffic. In some situations like traffic between a pair of hosts, src-dst-ip with port numbers is needed, but that's only available on higher end switches, like the Catalyst 6K series.
Hi,
“No, it can work assuming the frames on the link are contain IP packets.”
Yes frames do contain ip packets, but how do the switch read the ip packets? As far as i know, switch or the l2 operation will only read L2 data’s like physical or mac addresses not the L3 or logical addresses. Kindly enlighten me.
Thank you,
A "pure" L2 switch cannot read more than the frame information but enhanced/smart/plus/etc. "L2 switches" often can examine and/or use L3 information. A 2960 falls into the latter, which is why there are load-balancing options using IP.
|
__label__pos
| 0.774563 |
-- trimet transit tracker -- 7536 = 75 southbound @42nd and sumner -- 11503 = MAX Yellowline southbound @Killingsworth and Interstate. -- (C) 2013 Donald Delmar Davis, Suspect Devices. -- THIS IS FREE SOFTWARE, released under Modified BSD (look it up) http = require("socket.http") checktime=0 estimates={} scheduled={} -- I want to do a list comprehension here current_platform = io.popen("uname -m"):read("*l") if current_platform == 'i386' then io_output = io.stdout elseif current_platform == 'x86_64' then io_output = io.stdout else io_output = '/dev/ttyATH0' end io.output(io_output) -- still trying to figure this out. -- from http://lua-users.org/wiki/FiltersSourcesAndSinks function mysink(chunk,src_err) local mycontent="" if chunk == nil then if src_err then -- source reports an error else -- do something with concatenation of chunks end return true elseif chunk == "" then return true else mycontent=chunk -- print(mycontent) checktime=string.match(mycontent,'queryTime="(%d+)') print (os.date("%d %b %X", string.sub(checktime,1,10))) io.write("\254\001",os.date("%d %b %X", string.sub(checktime,1,10)),"\254\192") i=0 while true do i,j=string.find(mycontent,"",j)) status=string.match(arrival,'status="(%a+)') local thetime=0 local marker="~" local minutes_till = '' if string.find(status,'estimated') then marker="" thetime=string.match(arrival,'estimated="(%d+)') else thetime=string.match(arrival,'scheduled="(%d+)') end thetime = string.sub(thetime,1,10) local timerep=os.date("%c", thetime ) print(status.."("..thetime..")="..timerep ) local delta = (os.difftime(thetime, os.time()) / 60) print("delta: "..delta) if delta > 60 then marker = '' minutes_till = '(z_z)' elseif delta < 1 then minutes_till = 'Due' else minutes_till = string.format("%.0f min", delta) end print("minutes_till: "..minutes_till) io.write(marker .. minutes_till .." ") end return true end -- in case of error return nil, err end --- Delay for a number of seconds. -- @param delay Number of seconds function delay_s(delay) delay = delay or 1 local time_to = os.time() + delay while os.time() < time_to do end end while true do http.request{ url="http://developer.trimet.org/ws/V1/arrivals?locIDs=11503&appID=EC36A740E55BB5A803BB2602B"; sink=mysink; } io.flush() delay_s(7) end
|
__label__pos
| 0.799169 |
10
I am using the scrbook (KOMA Script) class, as this MWE shows:
\documentclass[11pt,a5paper,twoside,BCOR=8mm,DIV=12,headings=normal,open=right]{scrbook}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{chngcntr}
\begin{document}
\part{Introduction}
\chapter{Lorem ipsum}
\counterwithout{figure}{chapter}
\begin{figure}[h!]
My figure here.
\caption{My caption}
\end{figure}
\end{document}
It's working, by and large, with one exception: The caption reads
Abbildung 1.: My caption
Notice the superfluous dot before the colon? It's clearly due to using parts; if I stick to chapters and sections only it's formatted as intended.
Any bright ideas?
0
1 Answer 1
10
By default, the KOMA-Script classes will add a period at the end of sectioning numbers, float numbers etc. if a \part or \appendix command was issued. To counter this behaviour, add the class option numbers=noendperiod. See section 3.16 of the KOMA-Script manual for further details.
If you want to change the default behaviour only for figure and table captions, add the following to your preamble:
\renewcommand*{\figureformat}{%
\figurename~\thefigure%
% \autodot% DELETED
}
\renewcommand*{\tableformat}{%
\tablename~\thetable%
% \autodot% DELETED
}
1
• 1
Works like a charm! You, sir, are a gentleman and a scholar.
– Ingmar
May 20, 2014 at 13:18
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.999791 |
Software
Five tips for handling errors in VBA
Effective error handling can mean the difference between a seamless, user-friendly experience and a problem-plagued application. These best practices will help ensure your apps run as intended, without a hitch.
A professional application always includes adequate error-handling routines to trap unexpected errors. Sometimes, the right handling means the user never knows the error occurred. At the very least, error-handling routines should address the problem, share adequate information on what the user should do next, and exit the program (if absolutely necessary) gracefully. You put a lot of effort into writing the procedures that run your custom applications. Why let a runtime error ruin it all? By employing a few best practices, you can improve error handling.
1: Verify and configure error settings
Before you do anything, check the error-trapping settings. VBA, via the Visual Basic Editor (VBE), is flexible and allows you to determine how it responds to errors. To access these settings (shown in Figure A), in the VBE, choose Options from the Tools menu, and click the General tab:
• Break On All Errors: Stops on every error, even errors following a Resume Next statement.
• Break On Unhandled Errors: Stops for unhandled errors, but stops on the line calling the class (in class modules) rather than the line with the error, which can be problematic during debugging.
• Break In Class Modules: Stops at the actual error (line of code), but doesn't work as expected with Err.Raise, which generates an error of its own.
Figure A
error handling settings
Choose the most appropriate error-handling setting.
Well-informed users can change this setting, so I recommend that you include a procedure, similar to the one in Listing A, to your application's startup routine.
Listing A
Function SetErrorTrappingOption()
'Set Error Trapping to Break on Unhandled Errors.
Application.SetOption "Error Trapping", 2
End Function
2: Every procedure needs error handling
Occasionally, you'll write a simple procedure where's there's no potential for error. But most procedures should have an error-handling routine, even if it's as basic as this one:
Private | Public Function | Sub procedurename()
On Error GoTo errHandler
...
Exit Function | Sub
errHandler:
MsgBox "Error " & Err.Number & ": " & Err.Description & " in " & _
VBE.ActiveCodePane.CodeModule, vbOKOnly, "Error"
End Sub
This is error handling at its simplest. The above handler displays the error number, a description, and the name of the module. Some developers prefer to control the exit by using Resume to point to an exit procedure, which is helpful when performing specific maintenance or cleanup tasks before exiting (see Tip #5).
During the development stage, this basic handler can be helpful (or not; see Tip #3). Later, during the testing phase, you can enhance the basic routine to handle the error or to tell the user what to do next.
3: Control error trapping during development
I just told you to add a generic error-handling routine to every procedure, which can be helpful during development. However, some developers find these generic routines annoying. Here's why. When the debugger encounters an error, one of two things happens:
• If there's no error-handling routine, the debugger stops at the offending line of code, which can be convenient.
• When there is an error-handling routine, the debugger executes it, which can make debugging more difficult.
If you're in the camp that finds error handling during the development phase too invasive, you can add a generic handler and comment it out until you're ready for it. That can be a bit of a pain, though. Alternatively, forget the commenting and rely on a constant instead. Specifically, set a global Boolean constant, as follows:
Public Const gEnableErrorHandling As Boolean = False
Then, run each call to the error-handling routine by the constant, like this:
If gEnableErrorHandling Then On Error GoTo errHandler
As long as the constant is False, the code skips the error-handling routine. When you're ready to enable error handling, simply reset the constant to True. The constant method might wear on you too because you have to run every error-handling call by it. In the end, the route you take isn't as important as knowing the alternatives and how to properly implement them.
4: Inhibiting errors
Sometimes, the best way to handle an error is to ignore it. This situation arises when you want to execute a task knowing that it might generate an error, and often, the error is what you're after! For instance, if a subsequent task relies on a specific file, you should test for the file's existence before executing that task. If the statement errors, you know the file isn't available and you can include code that takes appropriate action.
Admittedly, this setup makes some developers cringe — you are purposely introducing an error into your code. On the other hand, properly handled, it can be a much more efficient route than alternative solutions.
To ignore an error, precede the statement with the Resume Next statement, as follows:
On Error Resume Next
This statement allows the program to continue to the next line of code, totally ignoring the error. In short, Resume Next disables error handling from that line forward (within the procedure). That's the easy part, but you're not done. Anytime you use Resume Next, you need to reset error handling by using the following statement:
On Error GoTo 0
GoTo 0 disables enabled error handling in the current procedure and resets it to Nothing — that's the technical explanation. In a nutshell, Resume Next skips an error and GoTo 0 tells the debugger to stop skipping errors.
Be sure to insert the GoTo 0 statement as early as possible. You don't want to mask other errors.
5: Handle the exit
Once the error-handling routine completes its task, be sure to route control appropriately:
• By exiting the procedure
• By returning control to the procedure
Both strategies are appropriate; the code's purpose will dictate your choice.
Tip #2 contains the simplest error-handling routine. It displays information about the error and exits the procedure. You can control that exit by including an exit routine like this:
Private | Public Function | Sub procedurename()
On Error GoTo errHandler
...
exitHere:
...
errHandler:
MsgBox "Error " & Err.Number & ": " & Err.Description & " in " & _
VBE.ActiveCodePane.CodeModule, vbOKOnly, "Error"
Resume exitHere
End Sub
Once the error-handling routine is complete, the Resume exitHere statement routes the flow to exitHere. You won't always need this much control, but it's standard practice in more robust procedures.
Both of the above routines exit the procedure, but sometimes, you'll want to continue executing the procedure — not exit it. Specifically, Resume returns control to the line that generated the error. Resume Next returns control to the line immediately following the line of code that generated the error. The distinction is important. If your error-handling routine corrected the error, returning to the line that generated the error might be the appropriate action. Then again, skipping that line might be the appropriate action. Exiting an error this way can be complex, so use care and be sure to thoroughly test your routines.
About Susan Harkins
Susan Sales Harkins is an IT consultant, specializing in desktop solutions. Previously, she was editor in chief for The Cobb Group, the world's largest publisher of technical journals.
Editor's Picks
Free Newsletters, In your Inbox
|
__label__pos
| 0.514096 |
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up
Join the Stack Overflow community to:
1. Ask programming questions
2. Answer and help your peers
3. Get recognized for your expertise
I've enabled code-first migrations on my entity framework project, and have added several migrations which do things like rename tables. However, I have now deleted the database and caused entity framework to generate a brand new database based on my latest data model. If I try to run:
PM> Add-Migration TestMigration
... it tells me that I need to apply the existing migrations first. So I run:
PM> Update-Database
... but the trouble is that it's trying to update a database that doesn't need updating; it's already based on the latest data model. So I get an error when it tries to rename a table that now doesn't exist.
Is there some way I can indicate to data migrations that my database is up-to-date and doesn't need any migrations running on it? What should I do?
share|improve this question
Have you tried Update-Database -Force? (this is just a wild guess) – Jcl Oct 27 '12 at 19:32
@Jcl doesn't make any difference. – Jez Oct 27 '12 at 20:10
This implementation does not need to manually maintain records to be inserted to __MigrationHistory. Migrations are determined from assembly specified.
Maybe this helps.
My thanks goes to @Jez for initial idea.
/// <summary>
/// An implementation of IDatabaseInitializer that will:
/// 1. recreate database only if the database does not exist
/// 2. actualize __MigrationHistory to match current model state (i.e. latest migration)
/// </summary>
/// <typeparam name="TContext">The type of the context.</typeparam>
public class CreateDatabaseIfNotExistsAndMigrateToLatest<TContext> : CreateDatabaseIfNotExists<TContext>
where TContext : DbContext
{
private readonly Assembly migrationsAssembly;
/// <summary>
/// Gets the migration metadata for types retrieved from <paramref name="assembly"/>. Types must implement <see cref="IMigrationMetadata"/>.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns></returns>
private static IEnumerable<IMigrationMetadata> GetMigrationMetadata(Assembly assembly)
{
var types = assembly.GetTypes().Where(t => typeof(IMigrationMetadata).IsAssignableFrom(t));
var migrationMetadata = new List<IMigrationMetadata>();
foreach (var type in types)
{
migrationMetadata.Add(
(IMigrationMetadata)Activator.CreateInstance(type));
}
return migrationMetadata.OrderBy(m => m.Id);
}
/// <summary>
/// Gets the provider manifest token.
/// </summary>
/// <param name="db">The db.</param>
/// <returns></returns>
private static string GetProviderManifestToken(TContext db)
{
var connection = db.Database.Connection;
var token = DbProviderServices.GetProviderServices(connection).GetProviderManifestToken(connection);
return token;
}
/// <summary>
/// Gets the migration SQL generator. Currently it is <see cref="SqlServerMigrationSqlGenerator"/>.
/// </summary>
/// <returns></returns>
private static MigrationSqlGenerator GetMigrationSqlGenerator()
{
return new SqlServerMigrationSqlGenerator();
}
/// <summary>
/// Creates the operation for inserting into migration history. Operation is created for one <paramref name="migrationMetadatum"/>.
/// </summary>
/// <param name="migrationMetadatum">The migration metadatum.</param>
/// <returns></returns>
private static InsertHistoryOperation CreateInsertHistoryOperation(IMigrationMetadata migrationMetadatum)
{
var model = Convert.FromBase64String(migrationMetadatum.Target);
var op = new InsertHistoryOperation(
"__MigrationHistory",
migrationMetadatum.Id,
model,
null);
return op;
}
/// <summary>
/// Generates the SQL statements for inserting migration into history table.
/// </summary>
/// <param name="generator">The generator.</param>
/// <param name="op">The operation.</param>
/// <param name="token">The token.</param>
/// <returns></returns>
private static IEnumerable<MigrationStatement> GenerateInsertHistoryStatements(
MigrationSqlGenerator generator,
InsertHistoryOperation op,
string token)
{
return generator.Generate(new[] { op }, token);
}
/// <summary>
/// Runs the SQL statements on database specified by <paramref name="db"/> (<see cref="DbContext.Database"/>).
/// </summary>
/// <param name="statements">The statements.</param>
/// <param name="db">The db.</param>
private static void RunSqlStatements(IEnumerable<MigrationStatement> statements, TContext db)
{
foreach (var statement in statements)
{
db.Database.ExecuteSqlCommand(statement.Sql);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="CreateDatabaseIfNotExistsAndMigrateToLatest{TContext}"/> class.
/// </summary>
/// <param name="migrationsAssembly">The migrations assembly.</param>
public CreateDatabaseIfNotExistsAndMigrateToLatest(Assembly migrationsAssembly)
{
this.migrationsAssembly = migrationsAssembly;
}
protected override void Seed(TContext context)
{
base.Seed(context);
// Get migration metadata for migrationAssembly
var migrationMetadata = GetMigrationMetadata(migrationsAssembly);
// Crate DbContext
var db = Activator.CreateInstance<TContext>();
// Remove newly created record in __MigrationHistory
db.Database.ExecuteSqlCommand("DELETE FROM __MigrationHistory");
// Get provider manifest token
var token = GetProviderManifestToken(db);
// Get sql generator
var generator = GetMigrationSqlGenerator();
foreach (var migrationMetadatum in migrationMetadata)
{
// Create history operation
var op = CreateInsertHistoryOperation(migrationMetadatum);
// Generate history insert statements
var statements = GenerateInsertHistoryStatements(generator, op, token);
// Run statements (SQL) over database (db)
RunSqlStatements(statements, db);
}
}
}
share|improve this answer
I've been running into this issue with EF6. I tried to implement this solution, but it appears that InsertHistoryOperation is no longer available. Is there another way we can generate the operation for inserting history without InsertHistoryOperation? – goodface87 Dec 12 '14 at 20:57
1
Anyone know how this approach could be taken in EF6? seems like they modified the HistoryOperation/MigrationOperation classes in such a way to stop this sort of manual insert. – WillEllis Sep 24 '15 at 17:07
up vote 8 down vote accepted
I've found a way to indicate that my database is up-to-date, and it's (unsurprisingly) based on modifying the __MigrationHistory table, which code-first migrations uses to determine which migrations to apply to the DB when you run Update-Database.
By the way, whilst researching this answer I came across a very nice reference for code-first migrations commands, which can be found at: http://dotnet.dzone.com/articles/ef-migrations-command
When the database is created from scratch automatically by EF, it will always put a single entry into the __MigrationHistory table, and that entry will have the MigrationId (currentDateTime)_InitialCreate. This represents the initial creation of the database that EF has just carried out. However, your migration history is not going to begin with that MigrationId because you will have started with something else.
To "fool" code-first migrations into thinking that you're on the latest migration, you need to delete that (currentDateTime)_InitialCreate entry from the __MigrationHistory table of the newly-created DB, and insert what would have been there if you still had the old DB which had had the migrations applied to it.
So, first delete everything from the newly-generated DB's __MigrationHistory table. Then, go into package manager console and run:
PM> Update-Database -Script
From the resulting SQL script, pull out all the lines beginning with:
INSERT INTO [__MigrationHistory]...
Then, run those INSERT statements within the context of the newly-created database. Check that each of those rows now exists in your __MigrationHistory table. When you next run:
PM> Update-Database
... you should get a message saying "No pending code-based migrations." Congratulations - you've fooled code-first migrations into thinking you're now on the latest migration, and you can continue where you left off adding new migrations from here.
I do think there should be some automated way of doing this built into EF code-first, though... maybe they should add something like:
PM> Update-Database -MigrationsTableOnly
... whereby it would clobber the existing entries in the migrations table, and just insert the new entries into migrations history for each migration defined in your project, but not actually try and run the migrations. Ah well.
UPDATE
I've found a way to automate this nicely, using a custom initializer's Seed method. Basically the Seed method deletes the existing migration history data when the DB is created, and inserts your migrations history. In my database context constructor, I register the custom initializer like so:
public class MyDatabaseContext : DbContext {
public MyDatabaseContext() : base() {
Database.SetInitializer(new MyDatabaseContextMigrationHistoryInitializer());
}
The custom initializer itself looks like this:
/// <summary>
/// This initializer clears the __MigrationHistory table contents created by EF code-first when it first
/// generates the database, and inserts all the migration history entries for migrations that have been
/// created in this project, indicating to EF code-first data migrations that the database is
/// "up-to-date" and that no migrations need to be run when "Update-Database" is run, because we're
/// already at the latest schema by virtue of the fact that the database has just been created from
/// scratch using the latest schema.
///
/// The Seed method needs to be updated each time a new migration is added with "Add-Migration". In
/// the package manager console, run "Update-Database -Script", and in the SQL script which is generated,
/// find the INSERT statement that inserts the row for that new migration into the __MigrationHistory
/// table. Add that INSERT statement as a new "ExecuteSqlCommand" to the end of the Seed method.
/// </summary>
public class MyDatabaseContextMigrationHistoryInitializer : CreateDatabaseIfNotExists<MyDatabaseContext> {
/// <summary>
/// Sets up this context's migration history with the entries for all migrations that have been created in this project.
/// </summary>
/// <param name="context">The context of the database in which the seed code is to be executed.</param>
protected override void Seed(MyDatabaseContext context) {
// Delete existing content from migration history table, and insert our project's migrations
context.Database.ExecuteSqlCommand("DELETE FROM __MigrationHistory");
context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210091606260_InitialCreate', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4AF54AD7E074A..., '5.0.0.net40')");
context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210102218467_MakeConceptUserIdNullable', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4..., '5.0.0.net40')");
context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210231418163_ChangeDateTimesToDateTimeOffsets', 0x1F8B0800000000000400ECBD07601C499625262F6D..., '5.0.0.net40')");
context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210251833252_AddConfigSettings', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4AF54AD7E..., '5.0.0.net40')");
context.Database.ExecuteSqlCommand("INSERT INTO __MigrationHistory (MigrationId, Model, ProductVersion) VALUES ('201210260822485_RenamingOfSomeEntities', 0x1F8B0800000000000400ECBD07601C499625262F6DCA7B7F4AF5..., '5.0.0.net40')");
}
}
share|improve this answer
Thanks for this. This is a bit crap really - there should be a better story for creating a clean database based on the latest schema. – Isaac Abraham Feb 8 '13 at 14:21
I just wanted to add a computed column... Maybe ADO .NET is easier than Entity Framework after all... viva new SqlCommand() – Mzn Mar 4 '14 at 8:33
Go to MigrationHistory table in sql server (under system folder) it has row for your migration and db hash in it which must be the same with one in your migration file, just copy it from db to file.
In other words you need to sync your MigrationHistory table with actual migrations.
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.779936 |
Security RPC XSRF
Cross-Site Request Forgery (XSRF or CSRF) is a type of web attack where an attacker can perform actions on behalf of an authenticated user without user‘s knowledge. Typically, it involves crafting a malicious HTML page, which, once visited by a victim, will cause the victim’s browser to issue an attacker-controlled request to a third-party domain. If the victim is authenticated to the third-party domain, the request will be sent with the browser‘s cookies for that domain, and could potentially trigger an undesirable action on behalf of the victim and without victim’s consent - for example, delete or modify a blog or add a mail forward rule.
This document explains how developers can protect GWT RPCs against XSRF attacking using GWT's builtin XSRF protection introduced in GWT 2.3
1. Overview
2. Server-side changes
3. Client-side changes
Overview
RPC XSRF protection is built using RpcToken feature, which lets a developer set a token on a RPC endpoint using HasRpcToken interface and have that token included with each RPC call made via that endpoint.
Default XSRF protection implementation derives XSRF token from a session authentication cookie by generating an MD5 hash of the session cookie value and using the resulting hash as XSRF token. This stateless XSRF protection implementation relies on the fact that attacker doesn't have access to the session cookie and thus is unable to generate valid XSRF token.
Server-side changes
Configure XsrfTokenServiceServlet
Client-side code will obtain XSRF tokens by calling XsrfTokenService.getNewXsrfToken() server-side implementation configured in web.xml:
<servlet>
<servlet-name>xsrf</servlet-name>
<servlet-class>
com.google.gwt.user.server.rpc.XsrfTokenServiceServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xsrf</servlet-name>
<url-pattern>/gwt/xsrf</url-pattern>
</servlet-mapping>
Since XSRF token is tied to an authentication session cookie, the name of that cookie must be passed to the XsrfTokenServiceServlet as well as all XSRF-protected RPC service servlets. This is done via context parameter in web.xml:
<context-param>
<param-name>gwt.xsrf.session_cookie_name</param-name>
<param-value>JSESSIONID</param-value>
</context-param>
Note: Servlet initialization parameter (<init-param>) can also be used to pass the name of the session cookie to each servlet individually.
Make RPC servlets XSRF protected
All server-side implementations of RPC services must extend XsrfProtectedServiceServlet:
package com.example.foo.server;
import com.google.gwt.user.server.rpc.XsrfProtectedServiceServlet;
import com.example.client.MyService;
public class MyServiceImpl extends XsrfProtectedServiceServlet implements
MyService {
public String myMethod(String s) {
// Do something interesting with 's' here on the server.
return s;
}
}
Client-side changes
Make client RPC interfaces XSRF protected
Client-side RPC interfaces can be marked as XSRF protected using one of the following ways:
package com.example.foo.client;
import com.google.gwt.user.client.rpc.XsrfProtectedService;
public interface MyService extends XsrfProtectedService {
public String myMethod(String s);
}
• by explicitly annotating interface or methods with @XsrfProtect annotation. @NoXsrfProtect annotation can be used to disable XSRF protection on a method or service to disable XSRF protection:
package com.example.foo.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.server.rpc.XsrfProtect
@XsrfProtect
public interface MyService extends RemoteService {
public String myMethod(String s);
}
Method level annotations override RPC interface level annoatations. If no annotations are present and the RPC interface contains a method that returns RpcToken or its implementation, then XSRF token validation is performed on all methods of that interface except for the method returning RpcToken.
Tip: To specify which RpcToken implementation GWT should generate serializers for use @RpcTokenImplementation annotation.
Include XsrfToken with RPC calls
To make a call to an XSRF protected service client must obtain a valid XsrfToken and set it on the service endpoint by casting the service's asynchronous interface to HasRpcToken and calling setRpcToken() method:
XsrfTokenServiceAsync xsrf = (XsrfTokenServiceAsync)GWT.create(XsrfTokenService.class);
((ServiceDefTarget)xsrf).setServiceEntryPoint(GWT.getModuleBaseURL() + "xsrf");
xsrf.getNewXsrfToken(new AsyncCallback<XsrfToken>() {
public void onSuccess(XsrfToken token) {
MyServiceAsync rpc = (MyServiceAsync)GWT.create(MyService.class);
((HasRpcToken) rpc).setRpcToken(token);
// make XSRF protected RPC call
rpc.doStuff(new AsyncCallback<Void>() {
// ...
});
}
public void onFailure(Throwable caught) {
try {
throw caught;
} catch (RpcTokenException e) {
// Can be thrown for several reasons:
// - duplicate session cookie, which may be a sign of a cookie
// overwrite attack
// - XSRF token cannot be generated because session cookie isn't
// present
} catch (Throwable e) {
// unexpected
}
});
Tip: If you would like to register a special handler for exceptions generated during XsrfToken validation use HasRpcToken.setRpcTokenExceptionHandler()
|
__label__pos
| 0.842064 |
使用 Media3 ExoPlayer 建立基本媒體播放器應用程式
Jetpack Media3 定義了 Player 介面,概述影片和音訊檔案的基本播放功能。ExoPlayer 是此介面在 Media3 中的預設實作方式。建議您使用 ExoPlayer,因為這項工具可提供一系列涵蓋大部分播放用途的功能,並能自訂來處理您可能有的任何其他用途。ExoPlayer 也會抽離裝置和 OS 零散,因此您的程式碼在整個 Android 生態系統中穩定運作。ExoPlayer 包含下列項目:
本頁將逐步說明建構播放應用程式的一些重要步驟,詳情請參閱 Media3 ExoPlayer 的完整指南。
開始使用
如要開始使用,請新增 ExoPlayer、UI 和 Jetpack Media3 常見模組的依附元件:
implementation "androidx.media3:media3-exoplayer:1.3.1"
implementation "androidx.media3:media3-ui:1.3.1"
implementation "androidx.media3:media3-common:1.3.1"
視您的用途而定,您可能也需要 Media3 的其他模組,例如 exoplayer-dash,才能以 DASH 格式播放串流。
請務必將 1.3.1 替換為您偏好的程式庫版本。請參閱版本資訊查看最新版本。
建立媒體播放器
在 Media3 中,您可以使用隨附的 Player 介面 ExoPlayer 實作,也可以建構自己的自訂實作。
建立 ExoPlayer
建立 ExoPlayer 例項最簡單的方式如下:
Kotlin
val player = ExoPlayer.Builder(context).build()
Java
ExoPlayer player = new ExoPlayer.Builder(context).build();
您可以在其所在的 ActivityFragmentServiceonCreate() 生命週期方法中建立媒體播放器。
Builder 包含您可能會感興趣的一系列自訂選項,例如:
Media3 提供 PlayerView UI 元件,您可以加入應用程式的版面配置檔案。這個元件會封裝播放控制項的 PlayerControlView、用於顯示字幕的 SubtitleView,以及用於轉譯影片的 Surface
準備播放器
使用 setMediaItem()addMediaItem() 等方法,將媒體項目新增至播放的播放清單。然後,呼叫 prepare() 即可開始載入媒體,並取得必要資源。
您不應在應用程式於前景執行前執行這些步驟。如果玩家位於 ActivityFragment,就表示在 API 級別 24 以上級別的 onStart() 生命週期方法中準備玩家,或在 API 級別 23 以下的 onResume() 生命週期方法中準備玩家。如果玩家位於 Service,您可以在 onCreate() 中準備該玩家。
控製播放器
玩家準備好後,您可以透過呼叫播放器的方法控製播放,例如:
繫結至玩家時,PlayerViewPlayerControlView 等 UI 元件會自動更新。
放開播放器
播放作業需要有限的資源 (例如影片解碼器),因此對於不再需要播放器時,請務必呼叫播放器上的 release(),以便釋出資源。
如果您的玩家位於 ActivityFragment,請在 API 級別 24 及以上級別的 onStop() 生命週期方法中釋出玩家,或在 API 級別 23 及以下級別中發布 onPause() 方法。如果玩家位於 Service,您可以在 onDestroy() 中發布該玩家。
透過媒體工作階段管理播放
在 Android 中,媒體工作階段是跨程序邊界與媒體播放器互動的標準化方式。將媒體工作階段連線至播放器,即可在外部通告媒體播放,以及接收外部來源的播放指令,例如整合行動裝置和大螢幕裝置上的系統媒體控制項
如要使用媒體工作階段,請在 Media3 Session 模組中新增依附元件:
implementation "androidx.media3:media3-session:1.3.1"
建立媒體工作階段
將播放器初始化後,您可以建立一個 MediaSession,如下所示:
Kotlin
val player = ExoPlayer.Builder(context).build()
val mediaSession = MediaSession.Builder(context, player).build()
Java
ExoPlayer player = new ExoPlayer.Builder(context).build();
MediaSession mediaSession = new MediaSession.Builder(context, player).build();
Media3 會自動將 Player 的狀態與 MediaSession 的狀態同步處理。這項功能適用於所有 Player 實作項目,包括 ExoPlayerCastPlayer 或自訂實作項目。
將控制權授予其他用戶端
用戶端應用程式可以實作媒體控制器,控制媒體工作階段的播放。如要接收這些要求,請在建構 MediaSession 時設定回呼物件。
當控制器要連線至媒體工作階段時,系統會呼叫 onConnect() 方法。您可以使用提供的 ControllerInfo,決定要接受拒絕要求。如要查看範例,請參見 Media3 Session 試用版應用程式
連線後,控制器就能傳送播放指令給工作階段。接著,工作階段會將這些指令委派給玩家。工作階段會自動處理 Player 介面中定義的播放和播放清單指令。
其他回呼方法則可讓您處理,例如自訂播放指令修改播放清單等要求。這些回呼同樣包含 ControllerInfo 物件,因此您可以依要求判斷存取權控管。
在背景播放媒體
如要在應用程式不在前景時繼續播放媒體 (例如播放音樂、有聲書或 Podcast),讓使用者在未開啟應用程式的情況下,PlayerMediaSession 應封裝在前景服務中。為此,Media3 提供 MediaSessionService 介面。
實作 MediaSessionService
建立擴充 MediaSessionService 的類別,並在 onCreate() 生命週期方法中將 MediaSession 執行個體化。
Kotlin
class PlaybackService : MediaSessionService() {
private var mediaSession: MediaSession? = null
// Create your Player and MediaSession in the onCreate lifecycle event
override fun onCreate() {
super.onCreate()
val player = ExoPlayer.Builder(this).build()
mediaSession = MediaSession.Builder(this, player).build()
}
// Remember to release the player and media session in onDestroy
override fun onDestroy() {
mediaSession?.run {
player.release()
release()
mediaSession = null
}
super.onDestroy()
}
}
Java
public class PlaybackService extends MediaSessionService {
private MediaSession mediaSession = null;
@Override
public void onCreate() {
super.onCreate();
ExoPlayer player = new ExoPlayer.Builder(this).build();
mediaSession = new MediaSession.Builder(this, player).build();
}
@Override
public void onDestroy() {
mediaSession.getPlayer().release();
mediaSession.release();
mediaSession = null;
super.onDestroy();
}
}
在您的資訊清單中,具有 MediaSessionService 意圖篩選器的 Service 類別,並要求 FOREGROUND_SERVICE 權限以執行前景服務:
<service
android:name=".PlaybackService"
android:foregroundServiceType="mediaPlayback"
android:exported="true">
<intent-filter>
<action android:name="androidx.media3.session.MediaSessionService"/>
</intent-filter>
</service>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
最後,在您建立的類別中覆寫 onGetSession() 方法,控制媒體工作階段的用戶端存取權。傳回 MediaSession 以接受連線要求,或傳回 null 以拒絕要求。
Kotlin
// This example always accepts the connection request
override fun onGetSession(
controllerInfo: MediaSession.ControllerInfo
): MediaSession? = mediaSession
Java
@Override
public MediaSession onGetSession(MediaSession.ControllerInfo controllerInfo) {
// This example always accepts the connection request
return mediaSession;
}
連線至使用者介面
現在媒體工作階段與播放器 UI 所在的 ServiceActivityFragment 是分開的,您可以使用 MediaController 連結這兩個工作階段。在 ActivityFragmentonStart() 方法中,為 MediaSession 建立 SessionToken,然後使用 SessionToken 建構 MediaController。建構 MediaController 會以非同步方式發生。
Kotlin
override fun onStart() {
val sessionToken = SessionToken(this, ComponentName(this, PlaybackService::class.java))
val controllerFuture = MediaController.Builder(this, sessionToken).buildAsync()
controllerFuture.addListener(
{
// Call controllerFuture.get() to retrieve the MediaController.
// MediaController implements the Player interface, so it can be
// attached to the PlayerView UI component.
playerView.setPlayer(controllerFuture.get())
},
MoreExecutors.directExecutor()
)
}
Java
@Override
public void onStart() {
SessionToken sessionToken =
new SessionToken(this, new ComponentName(this, PlaybackService.class));
ListenableFuture<MediaController> controllerFuture =
new MediaController.Builder(this, sessionToken).buildAsync();
controllerFuture.addListener(() -> {
// Call controllerFuture.get() to retrieve the MediaController.
// MediaController implements the Player interface, so it can be
// attached to the PlayerView UI component.
playerView.setPlayer(controllerFuture.get());
}, MoreExecutors.directExecutor())
}
MediaController 會實作 Player 介面,因此您可以使用相同的方法 (例如 play()pause()) 控製播放。與其他元件類似,請記得不再需要使用 MediaController 時 (例如 ActivityonStop() 生命週期方法),方法是呼叫 MediaController.releaseFuture()
發布通知
需要使用前景服務才能發布通知。MediaSessionService 會以 MediaNotification 的形式自動為您建立 MediaStyle 通知。如要提供自訂通知,請使用 DefaultMediaNotificationProvider.Builder 建立 MediaNotification.Provider,或建立自訂的供應商介面實作方式。使用 setMediaNotificationProvider 將提供者新增至 MediaSession
宣傳你的內容資料庫
MediaLibraryService 是在 MediaSessionService 上建構,可讓用戶端應用程式瀏覽應用程式提供的媒體內容。用戶端應用程式會實作 MediaBrowser,以與您的 MediaLibraryService 互動。
實作 MediaLibraryService 與實作 MediaSessionService 類似,差別在於在 onGetSession() 中應傳回 MediaLibrarySession,而非 MediaSession。與 MediaSession.Callback 相比,MediaLibrarySession.Callback 包含其他方法,可讓瀏覽器用戶端瀏覽程式庫服務提供的內容。
MediaSessionService 類似,請在資訊清單中宣告 MediaLibraryService,並要求 FOREGROUND_SERVICE 權限以執行前景服務:
<service
android:name=".PlaybackService"
android:foregroundServiceType="mediaPlayback"
android:exported="true">
<intent-filter>
<action android:name="androidx.media3.session.MediaLibraryService"/>
<action android:name="android.media.browse.MediaBrowserService"/>
</intent-filter>
</service>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
上述範例包含同時適用於 MediaLibraryService 和舊版 MediaBrowserService 的意圖篩選器,用於回溯相容性。額外的意圖篩選器可讓用戶端應用程式使用 MediaBrowserCompat API 辨識您的 Service
MediaLibrarySession 可讓您透過單一根層級 MediaItem,以樹狀結構提供內容資料庫。樹狀結構中的每個 MediaItem 都可以擁有任意數量的子項 MediaItem 節點。您可以根據用戶端應用程式的要求提供不同的根或不同的樹狀結構。舉例來說,您迴向尋找推薦媒體項目清單的用戶端可能只包含根 MediaItem 和單一子項 MediaItem 節點層級,而返回不同用戶端應用程式的樹狀結構,可能代表更完整的內容資料庫。
建立 MediaLibrarySession
MediaLibrarySession 會擴充 MediaSession API,用於新增內容瀏覽 API。相較於 MediaSession 回呼MediaLibrarySession 回呼會新增以下方法:
• onGetLibraryRoot() 用於用戶端要求內容樹狀結構的根層級 MediaItem
• onGetChildren() 用於用戶端要求內容樹狀結構中 MediaItem 的子項時
• onGetSearchResult() 適用於用戶端針對特定查詢的內容樹狀結構要求搜尋結果時
相關的回呼方法將包含 LibraryParams 物件,並提供有關用戶端應用程式感興趣的內容樹狀結構類型的其他信號。
|
__label__pos
| 0.606269 |
# HG changeset patch # User Steve Losh # Date 1488650247 0 # Node ID dd8289802cdaa950fe2aa8495de02a5cc906d352 # Parent 6dd2cb3e5f2767f79ffd198dd3abf286fe38b069 Problem 63 diff -r 6dd2cb3e5f27 -r dd8289802cda src/euler.lisp --- a/src/euler.lisp Sat Mar 04 12:04:57 2017 +0000 +++ b/src/euler.lisp Sat Mar 04 17:57:27 2017 +0000 @@ -2028,6 +2028,26 @@ ((> score target) (removef candidates first)))) ; tricksy hobbitses (thereis (apply (nullary #'min) candidates)))))) +(defun problem-63 () + ;; The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the + ;; 9-digit number, 134217728=8^9, is a ninth power. + ;; + ;; How many n-digit positive integers exist which are also an nth power? + (flet ((score (n) + ;; 10^n will have n+1 digits, so we never need to check beyond that + (iterate (for base :from 1 :below 10) + (for value = (expt base n)) + (counting (= n (digits-length value))))) + (find-bound () + ;; it's 21.something, but I don't really grok why yet + (iterate + (for power :from 1) + (for maximum-possible-digits = (digits-length (expt 9 power))) + (while (>= maximum-possible-digits power)) + (finally (return power))))) + (iterate (for n :from 1 :below (find-bound)) + (sum (score n))))) + (defun problem-74 () ;; The number 145 is well known for the property that the sum of the factorial @@ -2160,6 +2180,7 @@ (test p60 (is (= 26033 (problem-60)))) (test p61 (is (= 28684 (problem-61)))) (test p62 (is (= 127035954683 (problem-62)))) +(test p63 (is (= 49 (problem-63)))) (test p74 (is (= 402 (problem-74))))
|
__label__pos
| 0.711286 |
How do i Edit the Date() function?
Hello.
When i use “timestamp: new Date()” i get this "Sun Apr 03 2016 16:31:10 GMT+0200 (W. Europe Daylight Time)"
I dont want to show that much data when i print timestamp.
1. How do i modify what data i want to print, i want to remove (W. Europe Daylight Time)?
2. Do the function Date() collect the time from my PC so it knows what timezone im in?
BR
Dimi
Hi @emilkl: Have a look at moment.js: http://momentjs.com/ That’s exactly what you need. There’s also an official Meteor integration: The trusted source for JavaScript packages, Meteor resources and tools | Atmosphere.
Yes, the browser knows your timezone from your operating system. Both JavaScript and moment will acknowledge that. moment.js is also timezone aware and allows you to do conversions.
That was what i was looking for :)Thank you
Dimi
1 Like
|
__label__pos
| 0.954917 |
whatisconvert Search
Unit Converter
Convert 600 Acres to Hectares
To calculate 600 Acres to the corresponding value in Hectares, multiply the quantity in Acres by 0.40468564224 (conversion factor). In this case we should multiply 600 Acres by 0.40468564224 to get the equivalent result in Hectares:
600 Acres x 0.40468564224 = 242.811385344 Hectares
600 Acres is equivalent to 242.811385344 Hectares.
How to convert from Acres to Hectares
The conversion factor from Acres to Hectares is 0.40468564224. To find out how many Acres in Hectares, multiply by the conversion factor or use the Area converter above. Six hundred Acres is equivalent to two hundred forty-two point eight one one Hectares.
Definition of Acre
The acre (symbol: ac) is a unit of land area used in the imperial and US customary systems. It is defined as the area of 1 chain by 1 furlong (66 by 660 feet), which is exactly equal to 1⁄640 of a square mile, 43,560 square feet, approximately 4,047 m2, or about 40% of a hectare. The most commonly used acre today is the international acre. In the United States both the international acre and the US survey acre are in use, but differ by only two parts per million, see below. The most common use of the acre is to measure tracts of land. One international acre is defined as exactly 4,046.8564224 square metres.
Definition of Hectare
The hectare (symbol: ha) is an SI accepted metric system unit of area equal to 100 ares (10,000 m2) and primarily used in the measurement of land as a metric replacement for the imperial acre. An acre is about 0.405 hectare and one hectare contains about 2.47 acres. In 1795, when the metric system was introduced, the "are" was defined as 100 square metres and the hectare ("hecto-" + "are") was thus 100 "ares" or 1⁄100 km2. When the metric system was further rationalised in 1960, resulting in the International System of Units (SI), the are was not included as a recognised unit. The hectare, however, remains as a non-SI unit accepted for use with the SI units, mentioned in Section 4.1 of the SI Brochure as a unit whose use is "expected to continue indefinitely".
Using the Acres to Hectares converter you can get answers to questions like the following:
• How many Hectares are in 600 Acres?
• 600 Acres is equal to how many Hectares?
• How to convert 600 Acres to Hectares?
• How many is 600 Acres in Hectares?
• What is 600 Acres in Hectares?
• How much is 600 Acres in Hectares?
• How many ha are in 600 ac?
• 600 ac is equal to how many ha?
• How to convert 600 ac to ha?
• How many is 600 ac in ha?
• What is 600 ac in ha?
• How much is 600 ac in ha?
|
__label__pos
| 0.585339 |
Calculus Formula For Volume Of A Cylinder: What Is Calculus 3
Yan Zeng Stochastic Calculus For Finance Courses – Effective Method to Attain Guaranteed Success
Calculus is one of the most feared subjects among students pursuing degree in math. |} Since calculus blends impeccably in various streams of science like physics and engineering, students taking these streams up inside their higher education of necessity must go through the subject of calculus.
Most students seek online calculus courses to obtain a better comprehension of the concepts and total homework economically.
The field of calculus is separated in to 2 parts, the integral calculus and differential calculus. While the key calculus is about the idea of overall modification, differential calculus is around the idea of instantaneous rate of change.
It is necessary for your students to obtain clarity in regards to the essential concepts to have the ability to manage problems and situations introduced in calculus. Deciding on an internet calculus course will greatly help master the fundamental concepts and improve the problem solving skills with amazing ease.
Significance of calculus in a individual’s career
Using a good understanding of the notions of calculus is extremely critical for success in many areas such as math, engineering, math and computer science, banking, and finance. Great calculus understanding not just aids the students excel in the academic parameters but also within their selected career path. Students learning the fundamentals of calculus while in the right way can contribute to aspects of economics, business, finance, banking, sports, statistics, mechanics, and even drug. The online calculus courses are incredibly helpful to students willing to make their livelihood in just about any of the above mentioned fields as professionals or professors.
Calculus Solver For X classes offer the best aid
Online calculus courses provide the most effective help the students seeking additional help by customizing the program based on the educational demands. The courses are made creatively by combining the traditional system of classroom training with the innovative online interactive programs to give calculus help students staying even at distant places.
The online calculus courses provide the following attributes:
Understanding calculus the easy way
The online calculus classes offered either for free or to get several nominal fees by the internet institutes empower the students to know calculus the easy way by breaking down the complex notions into easy-to-understand and easy-to-practice measures. Through the stepbystep customized and instructions approach, online coaches help the students learn the basic theories of both integral and differential calculus the perfect way.
The best way to find the Perfect Trigonometry Formula For Calculus Program
As a way to get a better understanding of the fundamental concepts of calculus and implement exactly the same in solving complex calculus problems, it is vital to find the best calculus help. While choosing the online calculus help, it is essential to look at the credentials of the class and the online tutors either through testimonials, references or individual interactions.
It is imperative to decide on a class that provides personalized calculus help, higher amount of exercise customization and sessions to add expertise within the topic.
An online calculus course could be your best resource for students trying calculus help to crack the difficult problems, pass on the competitive assessments, and also achieve ensured success from the chosen career.
Calculus Homework Help: Reduction Formula For Integral Calculus
It is not unusual the calculus is considered to be a hard discipline. It is well known that people with a good math background detect difficulties learning mathematics. Pre-calculus help is needed at early stages of higher education in mathematics. If you don’t know just how to do calculus then you want some kind of precalculus help. If you’re assigned assignments then you want to discover calculus homework assistance as soon as you can. And we cannot do enough to stress that the fact it could definitely happen you’ll come across issues with your own class. There certainly are a lot of individuals out there that struggle with calculus because of its sophistication. What’s generally not correctly known is that your success in calculus can definitely shape your future. Additionally, that you don’t just must need become a mathematics scientist in order to benefit from these equipment it can offer. Getting good in calculus is essential as a way to comprehend rocket science.
Without a simple understanding of rocket science, you will not be able todo breakthrough work or even contribute properly to the said field. In the event that you would want to make sure that you create your fantasies come true you then want some sort of calculus help right a way.
Take for example the instance of Finance and Economics, that might be the fantasy profession for many. They will ask that you have a fairly solid comprehension of the most important calculus fundamentals.
You name a profession you’ll see that mathematics and calculus features a lot todo with it in one way or another. Under that perspective, it is clear that people facing issues with mathematics is likely to decide to try hard to over come it, because a lot is at a stake.
Pre calculus assistance and calculus assistance will probably be necessary on your journey to being a prosperous banker.
If you wish to go somewhere and earn a name for yourself then you’ve got to know calculus as it is necessary in a lot of professions, but perhaps not only in rocket science and also in banking.
So, next time you obtain your calculus homework, make sure you put the most useful of you personally, since it’s truly important. And don’t feel shy of needing to look for assistance, because the major issue is the final goal, that will be learning.
Calculus is normally broken up in two areas, differential and key. The area of differential calculus is mainly consideration the concept of instantaneous rate of change, whereas integral calculus is all about the idea of total shift. These two are as blend perfectly in many areas of science, such as physics and engineering.
If you can’t explain things like this you need to discover a way to do so. You should not quit on your own dreams.If calculus seems to be an obstacle in the way of achieving your dreams, so you shouldn’t be scared of seeking for support.
Calculus Formula
1. The concept of function is one of the most important in mathematics. It is defined as follows. Let two sets X and Y be given. If for every element x in the set X there is exactly one element (an image) y=f(x) in the set Y, then it is said that the function f is defined on the set X. The element x is called the independent variable, and respectively, the output y of the function is called the dependent variable. If we consider the number sets XRYR (where R is the set of real numbers), then the function y=f(x) can be represented as a graph in a Cartesian coordinate system Oxy.
2. Even function
f(x)=f(x)
3. Odd function
f(x)=f(x)
4. Periodic function
f(x+kT)=f(x),
where k is an integer, T is the period of the function.
5. Inverse function
Given a function y=f(x). To find its inverse function of it, it is necessary solve the equation y=f(x) for x and then switch the variables x and y. The inverse function is often denoted as y=f1(x). The graphs of the original and inverse functions are symmetric about the line y=x.
Inverse function
1. Composite function
Suppose that a function y=f(u) depends on an intermediate variable u, which in turn is a function of the independent variable xu=g(x). In this case, the relationship between y and x represents a “function of a function” or a composite function, which can be written as y=f(g(x)). The two-layer composite functions can be easily generalized to an arbitrary number of “layers”.
2. Linear function
y=ax+b, xR.
Here the number a is called the slope of the straight line. It is equal to the tangent of the angle between the straight line and the positive direction of the x-axis: a=tanα. The number b is the y-intercept.
Linear function
1. Quadratic function
The simplest quadratic function has the form
y=x2, xR.
In general, a quadratic function is described by the formula
y=ax2+bx+c, xR,
where abc are real numbers (in this case a0.) The graph of a quadratic function is called a parabola. The direction of the branches of the parabola depends on the sign of the coefficient a. If a>0, the parabola is concave upwards. If a<0, the parabola is concave downwards.
Quadratic function
Quadratic functions at different coefficients a
2 Cubic function
The simplest cubic function is given by
y=x3, xR.
In general, a cubic function is described by the formula
y=ax3+bx2+cx+d, xR,
where abcd are real numbers (a0). The graph of a cubic function is called a cubic parabola. When a>0, the cubic function is increasing, and when a<0, the cubic function is, respectively, decreasing.
Cubic function
Power function
y=xn, xR, nN.
Power functions for even powers
Power functions for odd powers
Square root function
y=x, x[0,).
Square root function
1. Exponential functions
y=ax, xR, a>0, a1,
y=ex when a=e2.71828182846
An exponential function increases when a>1 and decreases when 0<a<1.
Exponential functions
Logarithmic functions
y=logax, x(0,), a>0, a1,
y=lnx, when a=e,x(0,).
A logarithmic function increases if a>1 and decreases if 0<a<1.
Continue to keep your spirit and don’t quit too early. Consider how much is at the stake and place the very best of you. Perseverance is your secret, continue trying and only like that you’ll create it.
In the event that you’d like to be a success in life then you’ve got to get a solution to know calculus.
Truly there are lots of resources both offline and online. If you would want to ensure that your life is likely to be quite a nice one afterward understanding calculus could be critical.
The crucial issue is your perseverance and never give up, which will certainly lead you to victory.
Reference:
Functions and Their Graphs
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.951368 |
flash sale banner
HomeBlogWeb DevelopmentGetting Started with MongoDB and Java
Getting Started with MongoDB and Java
Published
05th Sep, 2023
Views
view count loader
Read it in
10 Mins
Getting Started with MongoDB and Java
MongoDB is being used extensively across several high-performing apps all around the world. In this article, we gain a thorough understanding of how to interact with MongoDB using Java Drivers and explore the different functionalities and features that can be used.
What is MongoDB?
MongoDB commonly referred to as just “Mongo” is a NoSQL document-based database that is used to store and organize data without using a relational table or columnar format.
MongoDB adopts a JSON-like structure to persist data, and a single such entity is called a document. If you’d like to derive a similarity from the relational database world, in most cases one could consider a document in NoSQL terminology to mean the same thing as a record in a SQL DB. A group of these documents is called a collection.
Why Use MongoDB?
Mongo forms the persistent entity in the MERN stack. It is an extremely useful database to work with when it is difficult or impossible to predict the schema of data to be stored in the database by an application.
Since Mongo also does not have the overhead to maintain tabular relations, it has an edge in performance over its SQL counterparts.
Setting up MongoDB
The MongoDB installation document which is available at docs.mongodb.com has step-by-step instructions to install MongoDB locally on your system for various popular operating systems. If you’d like to save all the hassle of installing things on your system and just get started working with Mongo, you could also explore the free tier of MongoDB Atlas by registering on their portal available at mongodb.com.
The Mongo Java Driver
To interact with MongoDB from our Java application, we will use a piece of software called the Java Driver, which is an official and recommended MongoDB driver application for the Java language.
If you are using a different programming language, you would need to use the specific driver for that language of your choice. Mongo provides official drivers for the most commonly used programming languages.
The driver exposes certain APIs which makes working with the database much easier and simplifies the interaction between the business logic and the data store in our applications.
A highly simplified illustration depicting the role of the driver in an application is as follows:
The Mongo Java Driver
Using the Mongo Java Driver
Let’s create some example snippets to demonstrate CRUD operations in a Java application, using the Java driver. But before we dive into writing our code to manipulate data, let’s first add the MongoDB driver dependency to our project.
In our example, we are going to use Maven to build our project. So let’s add the following dependency in the `pom.xml` file, which could be found in the project’s root directory:
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.0</version>
</dependency>
</dependencies>
At the time of writing this article, the latest driver version was 4.4.0. Feel free to change this as per the latest version at the time when you are reading this. Also make sure to read the driver’s documentation if the version you would be using is different from the one described here.
Now, let’s create a singleton connector class named `MongoConnector.java` under the same directory where the `Main` class file resides (in this example the path is `src/main/java/ MongoConnector.java`), to centralize the database connection and its related logic and expose some methods for our application to consume:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class MongoConnector {
private static MongoClient instance = null;
public MongoConnector(String dbUri) throws InstantiationException {
if(instance == null) {
instance = MongoClients.create(dbUri);
}else{
throw new InstantiationException("Connector Instance Already Exists");
}
}
public MongoClient getInstance() {
return instance;
}
public void listDatabases(){
try {
List<Document> databases = instance.listDatabases().into(new ArrayList<>());
databases.forEach(db -> System.out.println(db.get("name")));
} catch(Exception err){
System.out.println(err.getMessage());
}
}
}
For now, we have a method to get the connection instance and another one to list the database names.
To test if the driver is integrated successfully into the project and is working as expected, from our `Main` class, let’s pull the list of database names in the local Mongo instance:
public class Main {
public static void main(String args[]){
try{
MongoConnector dbConnection = new MongoConnector("mongodb://localhost:27017");
dbConnection.listDatabases();
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
When we compile (Press `crtl+F9` in intelliJ) and run (`shift+F10`) this project, we’ll see the list of database names printed on the console, indicating that the driver integration and the database connection works as expected.
Using the Mongo Java Driver
Thus we have set up the driver successfully. Now, let’s look at some ways to read and write data from our application.
Create a Database with a Collection:
In this section and the following ones, we will be looking at performing CRUD (Create Read Update Delete) operation from our application code on a Mongo database.
Let’s assume that we’d want to maintain a menu for a restaurant in our database
We’ll extend our connector class with the following methods so that we could programmatically create a database and a collection from our code:
public MongoDatabase createDB(String dbName){
return instance.getDatabase(dbName);
}
public void createCollection(MongoDatabase db, String collectionName){
db.createCollection(collectionName);
}
public void printCollectionNames(MongoDatabase db){
List<String> collections = db.listCollectionNames().into(new ArrayList<>());
collections.forEach(name -> System.out.println(name));
The `getDatabase` method will create a new database if the specified database is not present.
Now we’ll modify the Main class code to use the connector methods for creating a restaurant database with a menu collection, programmatically:
import com.mongodb.client.MongoDatabase;
public class Main {
public static void main(String args[]){
try{
MongoConnector dbInstance = new MongoConnector("mongodb://localhost:27017");
MongoDatabase restaurantDB = dbInstance.createDB("restaurant");
dbInstance.createCollection(restaurantDB,"menu");
dbInstance.listDatabases();
System.out.println("***********");
dbInstance.printCollectionNames(restaurantDB);
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
Insert A Document:
We can modify the main class as follows to insert a single document:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
menu.insertOne(new Document("name","Test Item 1").append("price",120.50));
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
When we compile and run this code, a new document will be inserted into the menu collection in the restaurant’s database.
We can also verify that from the mongo shell as follows:
Using the Mongo Java Driver
When the _id is not provided, the driver automatically adds it during insertion.
Insert Many Documents:
We could also perform multiple insertions at once programmatically using the `insertMany` method on the collection.
The code snippet to demonstrate `insertMany` is as follows:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
// prepare document list
List<Document> foodList = new ArrayList<>();
int counter = 1;
Random random = new Random();
String namePrefix = "Item";
while(counter < 6){
String itemName = namePrefix + String.valueOf((counter+1));
foodList.add(new Document("name",itemName).append("price",random.nextDouble() * 100));
++counter;
}
// insert many documents into the collection
menu.insertMany(foodList);
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
After the code is executed, we could get the following result from the shell:
Using the Mongo Java Driver
Read Documents:
The simplest way to query data from mongo is to find everything in a collection. This is the default behaviour of the find method when no arguments are passed to it.
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
MongoCursor<Document> menuCursor = menu.find().iterator();
try {
while (menuCursor.hasNext()) {
System.out.println(menuCursor.next().toJson());
}
}finally {
menuCursor.close();
}
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
There is a couple of important things to be noted here: First is that we use a cursor to retrieve data and the second is the `hasNext()` method on the cursor.
Like with most other databases, in the interest of optimizing read performance, a cursor is used to retrieve data. The `find` method returns an Iterable, on which, when we call the `iterator` method we get a cursor.
Calling the `next` method directly on the cursor will throw an exception if the collection is empty or when there’s no more data to retrieve. Hence we first check if data exists by using the `hasNext` method which returns a boolean based on the availability of data to retrieve.
When we execute the above snippet of code, we would get the following result:
Using the Mongo Java Driver
Projecting the Result-Set:
Those familiar with a SQL database would already know how the projections in the returned result-set of a query could be modified with the select statement. Similar projection of fields could be done in Mongo by using the `Projections` class.
By default, as shown in the section above, all the fields are projected. Let’s modify and project only the `name` field:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.conversions.Bson;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
Bson projectedFields = Projections.fields(
Projections.include("name"),
Projections.excludeId());
MongoCursor<Document> menuCursor = menu.find().projection(projectedFields).iterator();
try {
while (menuCursor.hasNext()) {
System.out.println(menuCursor.next().toJson());
}
}finally {
menuCursor.close();
}
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
When we execute the above code, only the name field from the documents in the collection will be projected the result-set of the query:
Using the Mongo Java Driver
Querying With Filters:
Another most common use case in reading data from a database is applying some sort of filters to find the data that satisfies a certain condition or a set of conditions.
We could do that using `Filters` in the Java Mongo Driver as follows:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.conversions.Bson;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
Bson projectedFields = Projections.fields(Projections.excludeId());
Bson priceFilter = Filters.and(Filters.gt("price", 70), Filters.lt("price", 98));
MongoCursor<Document> menuCursor = menu.find(priceFilter).projection(projectedFields).iterator();
try {
while (menuCursor.hasNext()) {
System.out.println(menuCursor.next().toJson());
}
}finally {
menuCursor.close();
}
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
Now that we have placed a price filter to filter items that have a price greater than 70 and lesser than 98, our result-set will be as follows:
Using the Mongo Java Driver
Update Documents:
To update a single document, we could use the `updateOne` method and update multiple documents the `updateMany` method. We can modify one or more fields in the documents through an update operation.
A code snippet for a single document update can be given as follows:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
import org.bson.conversions.Bson;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
Bson priceQuery = Filters.gt("price", 55);
Bson priceMutation = Updates.inc("price", -20);
UpdateResult resultSet = menu.updateOne(priceQuery,priceMutation);
System.out.println("Number of Documents Filtered By the Query : " + resultSet.getMatchedCount());
System.out.println("Number of Documents Modified By the Query : " + resultSet.getModifiedCount());
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
The above code will find the first document that matches the query and will decrease the price by 20 in the found document.
We can confirm that only a single document was affected by observing the output of the code:
Using the Mongo Java Driver
Let’s modify the above code to update multiple documents filtered with the same query:
UpdateResult resultSet = menu.updateMany(priceQuery,priceMutation);
If we looked at the output, we can infer that multiple documents were actually modified:
Using the Mongo Java Driver
Delete Documents:
Similar to other write operations, it is possible to delete one or many documents by using the appropriate methods exposed by the driver. Let’s look at a snippet to delete a single document from the collection:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import org.bson.conversions.Bson;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
System.out.println("Number of Documents In Collection Before Delete Operation: " + menu.countDocuments());
Bson nameFilter = Filters.eq("name", "Item3");
DeleteResult resultSet = menu.deleteOne(nameFilter);
System.out.println("Number of Documents Deleted: " + resultSet.getDeletedCount());
System.out.println("Number of Documents In Collection After Delete Operation: " + menu.countDocuments());
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
The code will find a single document that has the value “Item3” for the field “name” and will delete it from the collection. We can verify this from the output logged in the console on executing the code:
Using the Mongo Java Driver
To delete many documents, let’s modify the filter query to match all documents that have a price greater than 70.
Our collection’s current state is as follows:
[
{
_id: ObjectId("619767db0e4cbd63a03cd155"),
name: 'Test Item 1',
price: 80.5
},
{
_id: ObjectId("61976d76077b0c0b360b744b"),
name: 'Item2',
price: 56.80710292448832
},
{
_id: ObjectId("61976d76077b0c0b360b744d"),
name: 'Item4',
price: 73.7484483637489
},
{
_id: ObjectId("61976d76077b0c0b360b744e"),
name: 'Item5',
price: 53.243517433833034
},
{
_id: ObjectId("61976d76077b0c0b360b744f"),
name: 'Item6',
price: 73.84947772559507
}
]
So, with the discussed filter, we should be deleting 3 documents from the collection.
Let’s do that with the following code:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import org.bson.conversions.Bson;
public class Main {
public static void main(String args[]){
try{
MongoClient dbInstance = new MongoConnector("mongodb://localhost:27017").getInstance();
MongoCollection menu = dbInstance.getDatabase("restaurant").getCollection("menu");
System.out.println("Number of Documents In Collection Before Delete Operation: " + menu.countDocuments());
Bson priceFilter = Filters.gt("price", 70);
DeleteResult resultSet = menu.deleteMany(priceFilter);
System.out.println("Number of Documents Deleted: " + resultSet.getDeletedCount());
System.out.println("Number of Documents In Collection After Delete Operation: " + menu.countDocuments());
}catch(InstantiationException error){
System.out.println(error.getMessage());
}
}
}
As expected, on execution, the above code deletes 3 documents and leaves us with 2 documents in the collection:
Using the Mongo Java Driver
Looking to land a job? Discover the best programming course to boost your career! Gain valuable skills and knowledge with our unique programming courses. Start your journey today!
Using the Mongo Java Driver:
We just saw how to use Java Driver for Mongo in our codebase and perform the fundamental operations of creating, reading, updating and deleting documents from a collection.
Additionally, we also discussed how to programmatically create databases and collections using the APIs exposed by the driver.
The Java driver for Mongo is feature-packed with advanced capabilities such as aggregation. If you are interested in furthering your depths about it, the official documentation might be a good starting point.
Profile
Parthipan Natkunam
Author
Parthipan is a full-stack capable, software engineer with 7 years of industry experience, specialized in front-end engineering. Certified "AWS Developer Associate", who has worked in industries such as Ed-tech, IoT and Cyber security with companies spanning across multiple countries with varied tech stacks. Language agnostic by practice but fluent in TypeScript and JavaScript. Loves open-source and enjoys creating quality software products from scratch.
Share This Article
Ready to Master the Skills that Drive Your Career?
Avail your free 1:1 mentorship session.
Select
Your Message (Optional)
Upcoming Web Development Batches & Dates
NameDateFeeKnow more
Course advisor icon
Course Advisor
|
__label__pos
| 0.971028 |
AnteriorPosterior
5. Vectores y matrices
Por: Nacho Cabanes
Actualizado: 20-04-2019 09:52
Tiempo de lectura estimado: 16 min.
C++
5. Vectores y matrices
5.1. Definición de una tabla y acceso a los datos
Una tabla, vector, matriz o array (que algunos autores traducen por “arreglo”) es un conjunto de elementos, todos los cuales son del mismo tipo. Estos elementos tendrán todos el mismo nombre, y ocuparán un espacio contiguo en la memoria.
Por ejemplo, si queremos definir un grupo de 4 números enteros, usaríamos
int ejemplo[4];
Podemos acceder a cada uno de los valores individuales indicando su nombre (ejemplo) y el número de elemento que nos interesa, pero con una precaución: se empieza a numerar desde 0, así que en el caso anterior tendríamos 4 elementos, que serían ejemplo[0], ejemplo[1], ejemplo[2], ejemplo[3].
Como ejemplo, vamos a definir un grupo de 5 números enteros y hallar su suma:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.01:
// Primer ejemplo de tablas
#include <iostream>
using namespace std;
int main()
{
int numero[5]; // Un array de 5 numeros enteros
int suma; // Un entero que guardará la suma
numero[0] = 200; // Les damos valores
numero[1] = 150;
numero[2] = 100;
numero[3] = -50;
numero[4] = 300;
suma = numero[0] + // Y hallamos la suma
numero[1] + numero[2] + numero[3] + numero[4];
cout << "Su suma es " << suma;
/* Nota: esta es la forma más ineficiente e incómoda...
Ya lo iremos mejorando */
return 0;
}
Ejercicios propuestos:
• (5.1.1) Un programa que pida al usuario 4 números, los memorice (utilizando una tabla), calcule su media aritmética y después muestre en pantalla la media y los datos tecleados.
• (5.1.2) Un programa que pida al usuario 5 números reales y luego los muestre en el orden contrario al que se introdujeron.
5.2. Valor inicial de una tabla
Al igual que ocurría con las variables “normales”, podemos dar valor a los elementos de una tabla al principio del programa. Será más cómodo que dar los valores uno por uno, como hemos hecho antes. Esta vez los indicaremos todos entre llaves, separados por comas:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.02:
// Segundo ejemplo de tablas
#include <iostream>
using namespace std;
int main()
{
int numero[5] = // Un array de 5 números enteros
{200, 150, 100, -50, 300};
int suma; // Un entero que guardará la suma
suma = numero[0] + // Y hallamos la suma
numero[1] + numero[2] + numero[3] + numero[4];
cout << "Su suma es " << suma;
/* Nota: esta forma es algo menos engorrosa, pero todavía no */
/* está bien hecho. Lo seguiremos mejorando */
return 0;
}
Ejercicios propuestos:
• (5.2.1) Un programa que almacene en una tabla el número de días que tiene cada mes (supondremos que es un año no bisiesto), pida al usuario que le indique un mes (1=enero, 12=diciembre) y muestre en pantalla el número de días que tiene ese mes.
• (5.2.2) Un programa que almacene en una tabla el número de días que tiene cada mes (año no bisiesto), pida al usuario que le indique un mes (ej. 2 para febrero) y un día (ej. el día 15) y diga qué número de día es dentro del año (por ejemplo, el 15 de febrero sería el día número 46, el 31 de diciembre sería el día 365).
5.3. Recorriendo los elementos de una tabla
Es de esperar que exista una forma más cómoda de acceder a varios elementos de un array, sin tener siempre que repetirlos todos, como hemos hecho en
suma = numero[0] + numero[1] + numero[2] + numero[3] + numero[4];
El “truco” consistirá en emplear cualquiera de las estructuras repetitivas que ya hemos visto (while, do..while, for). Lo más habitual, ya que sabemos cuántos elementos tiene un array, es usar un "for" para contar, así:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.03:
// Tercer ejemplo de tablas (for)
#include <iostream>
using namespace std;
int main()
{
int numero[5] = // Un array de 5 números enteros
{200, 150, 100, -50, 300};
int suma; // Un entero que guardará la suma
int i; // Para recorrer el array
suma = 0; // Valor inicial
for (i=0; i<=4; i++) // Y hallamos la suma
suma += numero[i];
cout << "Su suma es " << suma;
return 0;
}
En este caso, que sólo sumábamos 5 números, no hemos escrito mucho menos, pero si trabajásemos con 100, 500 o 1000 números, la ganancia en comodidad sí que está clara.
Ejercicios propuestos:
• (5.3.1) A partir del programa propuesto en 5.2.2, que almacenaba en una tabla el número de días que tiene cada mes, crear otro que pida al usuario que le indique la fecha, detallando el día (1 al 31) y el mes (1=enero, 12=diciembre), como respuesta muestre en pantalla el número de días que quedan hasta final de año.
• (5.3.2) Crear un programa que pida al usuario 10 números enteros y luego los muestre en orden inverso (del último al primero), usando "for".
• (5.3.3) Crear un programa que pida al usuario 10 números reales, calcule su media y luego muestre los que están por encima de la media.
• (5.3.4) Un programa que pida al usuario 10 números enteros y calcule (y muestre) cuál es el mayor de ellos.
En física se usan mucho los "vectores", para representar magnitudes que no se pueden expresar sólo con un número. Por ejemplo, para una temperatura basta con decir cosas como "tengo 39 grados", pero para una fuerza no basta con decir que es de 200 N, sino que también es importante en qué dirección (y sentido) se aplica esa fuerza: no tendrá el mismo efecto si se aplica en el centro de un cuerpo o en un extremo, ni si comprime que si estira. Un vector se suele representar a partir de sus "componentes", que son las coordenadas de su extremo (suponiendo que comienza en el punto (0,0). Un vector en el plano tendrá dos componentes (x,y) y un vector en el espacio tendrá 3 componentes (x,y,z).como un conjunto de varias coordenadas. Así, un programa que pida al usuario las coordenadas de 2 vectores en el espacio y halle su vector suma sería:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.04:
// Vectores, primer contacto
#include <iostream>
using namespace std;
int main()
{
float vector1[3];
float vector2[3];
float vectorSuma[3];
int i;
// Pedimos los datos del primer vector
for (i=0; i<3; i++)
{
cout << "Introduce la componente " << i
<< " del primer vector: ";
cin >> vector1[i];
}
// Pedimos los datos del segundo vector
for (i=0; i<3; i++)
{
cout << "Introduce la componente " << i
<< " del segundo vector: ";
cin >> vector2[i];
}
// Calculamos la suma
for (i=0; i<3; i++)
vectorSuma[i] = vector1[i] + vector2[i];
// Y mostramos el resultado
cout << "El vector suma es ";
for (i=0; i<3; i++)
cout << vectorSuma[i] << " ";
return 0;
}
No veremos más detalles sobre vectores, porque este no es un curso de física. Pero sí propondemos algunos ejercicios para que pueda aplicar sus conocimientos quien ya ha estudiado con anterioridad lo que es un vector...
Ejercicios propuestos sobre vectores:
• (5.3.5) Un programa que pida al usuario los datos de dos vectores en el plano (2 coordenadas) y calcule su diferencia.
• (5.3.6) Un programa que pida al usuario las componentes de dos vectores en el espacio (3 coordenadas) y calcule su producto escalar.
• (5.3.7) Un programa que pida al usuario las componentes de dos vectores en el espacio y calcule su producto vectorial.
• (5.3.8) Un programa que pida al usuario dos vectores en el plano (2 coordenadas) y diga si son linealmente dependientes (sus componentes son proporcionales).
5.4. Tablas bidimensionales
Podemos declarar tablas de dos o más dimensiones. Por ejemplo, si queremos guardar datos de dos grupos de alumnos, cada uno de los cuales tiene 20 alumnos, tenemos dos opciones:
• Podemos usar int datosAlumnos[40] y entonces debemos recordar que los 20 primeros datos corresponden realmente a un grupo de alumnos y los 20 siguientes a otro grupo.
• O bien podemos emplear int datosAlumnos[2][20] y entonces sabemos que los datos de la forma datosAlumnos[0][i] son los del primer grupo, y los datosAlumnos[1][i] son los del segundo.
En cualquier caso, si queremos indicar valores iniciales, lo haremos entre llaves, igual que si fuera una tabla de una única dimensión. Vamos a verlo con un ejemplo de su uso:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.05:
// Array de dos dimensiones
#include <iostream>
using namespace std;
int main()
{
int notas[2][10] =
{
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }
};
cout << "La nota del tercer alumno del grupo 1 es "
<< notas[0][2];
return 0;
}
Este tipo de tablas son las que se usan también para guardar matrices, cuando hay que resolver problemas matemáticos más complejos. Por ejemplo, un programa que pida al usuario los datos de dos matrices de 3x3 y luego muestre su suma podría ser así:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.06
// Matrices, primer contacto
#include <iostream>
using namespace std;
int main()
{
float matriz[2][3][3];
float matrizSuma[3][3];
int m, fila, columna;
// Pedimos los datos de las dos matrices
for (m=0; m<2; m++)
for (fila=0; fila<3; fila++)
for (columna=0; columna<3; columna++)
{
cout << "En la matriz " << m+1
<< ", dime el dato de la fila " << fila+1
<< " y la columna " << columna+1 << ": ";
cin >> matriz[m][fila][columna];
}
// Calculamos la suma
for (fila=0; fila<3; fila++)
for (columna=0; columna<3; columna++)
matrizSuma[fila][columna] = matriz[0][fila][columna]
+ matriz[1][fila][columna];
// Y mostramos el resultado (puede salir un poco descolocado)
cout << "La matriz suma es " << endl;
for (fila=0; fila<3; fila++)
{
for (columna=0; columna<3; columna++)
cout << matrizSuma[fila][columna] << " ";
cout << endl;
}
return 0;
}
Cuidado: no podemos dar por sentado que los datos de un array tengan valor inicial 0, sino que pueden contener "basura" (lo que hubiera en cada posición de memoria anteriormente), de modo que este programa es incorrecto y puee mostrar resultados incorrectos:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.06b:
// Matrices, lógica errónea (sin dar valor inicial)
#include <iostream>
using namespace std;
int main()
{
float matriz[2][3][3];
float matrizSuma[3][3];
int m, fila, columna;
// Pedimos los datos de las dos matrices
for (m=0; m<2; m++)
for (fila=0; fila<3; fila++)
for (columna=0; columna<3; columna++)
{
cout << "En la matriz " << m+1
<< ", dime el dato de la fila " << fila+1
<< " y la columna " << columna+1 << ": ";
cin >> matriz[m][fila][columna];
}
// Calculamos la suma
for (m=0; m<2; m++)
for (fila=0; fila<3; fila++)
for (columna=0; columna<3; columna++)
matrizSuma[fila][columna] += matriz[m][fila][columna];
// La línea anterior es errónea: estamos dando por sentado
// que la matriz suma contiene ceros, y quizá no sea así
// Y mostramos el resultado (puede salir un poco descolocado)
cout << "La suma es ";
for (fila=0; fila<3; fila++)
{
for (columna=0; columna<3; columna++)
cout << matrizSuma[fila][columna] << " ";
cout << endl;
}
return 0;
}
Ejercicios propuestos sobre matrices:
• (5.4.1) Un programa pida datos al usuario los datos de una matriz de 2x2 y muestra su traspuesta (el resultado de intercambiar filas por columnas).
• (5.4.2) Un programa que pida al usuario los datos de una matriz de 3x3, y muestre su determinante.
• (5.4.3) Un programa que pida al usuario los datos de una matriz de 3x3, y calcule y muestre su matriz adjunta.
• (5.4.4) Un programa que pida al usuario los datos de una matriz de 3x3, y calcule y muestre su matriz inversa.
• (5.4.5) Un programa que pida al usuario los datos de dos matrices de 2x2, y calcule y muestre su producto.
• (5.4.6) Un programa que use una matriz de 3x4 para resolver un sistema de 3 ecuaciones con 3 incógnitas usando el método de Gauss (hacer ceros por debajo de la diagonal principal para luego aplicar sustitución regresiva).
5.5. Arrays indeterminados.
Si damos un valor inicial a un array, no será necesario que indiquemos su tamaño, porque el compilador lo puede saber contando cuantos valores hemos detallado, así:
// Introducción a C++, Nacho Cabanes
// Ejemplo 05.07:
// Arrays en los que no se indica el tamaño
#include <iostream>
using namespace std;
int main()
{
int diasMes[] = // Días de cada mes
{31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
cout << "Los días de noviembre son: " << diasMes[10];
return 0;
}
Ejercicios propuestos:
• (5.5.1) Un programa que, a partir de los datos prefijados de los días de cada mes, diga qué meses tienen 30 días. Se deberá mostrar el número de cada mes, pero empezando a contar desde 1 (abril será el mes 4).
265234 visitas desde el 20-04-2019
AnteriorPosterior
|
__label__pos
| 0.863737 |
Which of the following is equivalent to 3^-8 × 3^4 3^-4 3^-2 3^-12 3^-32
Question
Which of the following is equivalent to 3^-8 × 3^4
3^-4
3^-2
3^-12
3^-32
in progress 0
Ben Gia 3 months 2021-08-19T05:32:25+00:00 1 Answers 1 views 0
Answers ( )
0
2021-08-19T05:33:44+00:00
i believe the answer is the first option
Leave an answer
Browse
Giải phương trình 1 ẩn: x + 2 - 2(x + 1) = -x . Hỏi x = ? ( )
|
__label__pos
| 0.954333 |
What Are Residential Proxies, And Why Do You Need Them?
What Are Residential Proxies, And Why Do You Need Them?
Internet Service Provider, SEO
When working on online projects requiring data scraping and/or bots, your IP can be banned from websites. Residential proxies are an effective way to avoid getting banned. These proxies are linked to a real device and appear on target sites as if they belong to a regular user while protecting your privacy. This makes them safe for mission-critical projects like scraping coupon aggregators, ticket sites, or buying sneakers online. Hide Your IP Address Every device that is connected to the internet has an IP address. These addresses are what identifies you on the internet and allow other users to track your activity. Residential proxies are a great way to hide your IP address and protect your privacy. They are a more reliable option than data center proxies because they are…
Read More
|
__label__pos
| 0.996184 |
Using 3rd party packages for Powershell Install-Module
It make sense by default if you download 3rd party powershell packages like kbupdate, it should not run right away until you’ve done your due dilligence. You’ll get a warning like this during installation:
Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?
But when I try to use it, I get an error message:
Get-KbUpdate : The 'Get-KbUpdate' command was found in the module 'kbupdate', but the module could not be loaded. For more information, run 'Import-Module kbupdate'.
Import-Module gives a cryptic message like this:
Import-Module : Errors occurred while loading the format data file:
D:\Administrator\Documents\WindowsPowerShell\Modules\PSFramework\1.6.214\xml\PSFramework.Format.ps1xml, ,
D:\Administrator\Documents\WindowsPowerShell\Modules\PSFramework\1.6.214\xml\PSFramework.Format.ps1xml: The file was
skipped because of the following validation exception: File
D:\Administrator\Documents\WindowsPowerShell\Modules\PSFramework\1.6.214\xml\PSFramework.Format.ps1xml cannot be
loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170..
Turns out either the package needs to be marked safe or just stop checking altogether:
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
24 total views
Text manipulation idioms in linux
awk: select columns
sed: stream editor (operations like select, substitute, add/delete lines, modify)
sed expressions can be separated by ";"
sed can substitute all occurrences with 'g' modified at the end: 's/(find)/(replace)/g'
# https://unix.stackexchange.com/questions/92187/setting-ifs-for-a-single-statement
# arg I/O
$@: unpack all input args
$*: join all inputs as ONE arg, separated by FIRST character of IFS (empty space if unspecified)
# Remember the double quotes around "$*" or "$array[*]" usages or else IFS won't function
array[@]: entire array
${array[@]}: unpacks entire array into MULTIPLE arguments
${array[*]}: join entire array into ONE argument separated by FIRST character of IFS (defaults to an empty space if unspecified)
( IFS=$'\n'; echo "${my_array[*]}" )
${#str}: length of string
${#array[@]}: length of array
${#array[@]:start:after_stop}: select array[start] ... array[after_stop-1]
${str:="my_string"}: initializes variable str with "my_string" (useful for side-effect)
$(str##my_pattern}: delete front matching my_pattern
${str%%my_pattern}: deletes tail matching my_pattern (can use one % instead)
$(str%?}: delete last character (the my_pattern is a single character wildcard "?")
$( whatever_command ): captures stdout created by running whatever_command
( $str ): tokenize to string array, governed by IFS (specify delimiter)
( $( whatever_command ) ): combines the two operations above: capture stdout from command and tokenize the results
# https://unix.stackexchange.com/questions/92187/setting-ifs-for-a-single-statement
function strjoin { local IFS="$1"; shift; echo "$*"; }
51 total views
Auto mount USB drives
Raspbian OS (Raspberry Pi) do not mount USB drives automatically out of the box.
I’m pretty annoyed by the lack of easy to use packages by 2021 and I still have to do it myself with the instructions here: https://github.com/avanc/mopidy-vintage/wiki/Automount-USB-sticks
These are cookbook instructions, but I’ll add some insights to what each component means so it’s easier to remember the steps.
At top level, to auto-detect and mount USB drives, we need the following components
• udev: analogous to what happens behind device manager, it keeps track of and updates devices as they are connected and disconnected immediately. Need to register USB sticks by adding a event handler, which triggers a systemd service (see below)
• systemd: analogous to Windows’ services. Need to register the service by stating what commands it will call on start (mostly mounting) and cleanup (mostly unmounting)
• automount script: it’s a user defined script that abstracts most of the hard work detecting the partitions on the USB stick, assign the mount point names, and mount them
# Register udev event handler (rules)
# /etc/udev/rules.d/usbstick.rules
ACTION=="add", KERNEL=="sd[a-z][0-9]", TAG+="systemd", ENV{SYSTEMD_WANTS}="usbstick-handler@%k"
# It triggers a systemd call to "usbstick-handler@" service registered under /etc/systemd/system/
# Register systemd service
# /etc/systemd/system/[email protected]
# (Note: instructions used /lib instead of /etc. It's better to add it as /etc as this is manually registered as user-defined service rather than from a package)
[Unit]
Description=Mount USB sticks
BindsTo=dev-%i.device
After=dev-%i.device
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/automount %I
ExecStop=/usr/bin/pumount /dev/%I
# %I is the USB stick's device name under /dev, usually sda
# Abstracted the logic of determining the mount point name and mounting to 'automount' (see below)
Create the file /usr/local/bin/automount and give it execution permission: chmod +x /usr/local/bin/automount
#!/bin/bash
# $1 (first argument) is usually "sda" (supposedly USB stick device name) seen from %I in the systemd service commands
PART=$1
# Within the "sda" (USB stick device of interest), extract the partition labels (if applicable) from lsblk command. The first column (name) is dropped
FS_LABEL=`lsblk -o name,label | grep ${PART} | awk '{print $2}'`
# Decide the mount point name {partition label}_{partition name}
# e.g. MS-DOS_sda1
tokens=($FS_LABEL)
tokens+=($PART)
MOUNT_LABEL=$(IFS='_'; echo "${tokens[*]}")
# Using string array makes it easier to drop the prefix if there's no {partition label}
# Bash use IFS to specify separators for listing all elements of the array
# Suggestion: drop --sync for faster USB access (if you can umount properly)
/usr/bin/pmount --umask 000 --noatime -w --sync /dev/${PART} /media/${MOUNT_LABEL}
This automount script is adapted from https://raspberrypi.stackexchange.com/questions/66169/auto-mount-usb-stick-on-plug-in-without-uuid with my improvements.
62 total views
Descriptive names for logic operations on a pair (x, y)
It reads as “The output is TRUE only when the reduction (x,y)\rightarrow z meets the description of the operations below”
0 inputs:
• Constant: gives the same hard-coded result regardless of inputs
1 input:
• Transfer: Hardwired to one of the inputs
• Complement: NOT
2 inputs (symmetric):
• Comparison: different (XOR), identical (NXOR or equivalence)
• Arithmetic: AND, OR and its complements NAND, NOR
2 inputs (asymmetric):
• Inhibition: ONLY 1 followed by 0 is an inhibition. It’s a WHITE-list: anything else is not an inhibition (starting with 0 doesn’t inhibit)
• Implication: ANYTHING GOES as long as 1 is be followed by 1. It’s a BLACK-list: anything else qualifies as an implication (starting with 0 does not break the implication)
Implication is the complement of Inhibition, as the only case that breaks an implication is inhibition.
This ‘operator’ instead of truth-table view is more often used in electrical engineering than in computer science. There are many names for the same thing, but I put in some thought to find the intuitive words to make it easy to understand and remember
WARNING: Those there are tempting faint similarities between logic and set theory, there’s no direct tight duality between the two. Whitelist/Blacklist in inhibition/implication do not make sense with set-diff/subset as we are talking about a one-shot relationship here in logic, while set theory talks about the relationship between elements picked after it is quantified by “for all” vs “there is”. i.e. Truth table do not mix with sets
48 total views
Experimental Worldview Framework Desires x Problems x Mechanisms x Device
I am experimenting with a framework to summarize how I observe things that are going on around me, analyzing situations and coming up with solution approaches. Currently this is what I have:
{Desires} × {Problems} × {Mechanisms} × {Devices}
Everything I see can be analyzed as a result of the cross-product (a fancy word for combinations of contents) between these 4 broad categories. To make it easier to remember, they can be factored into 2 major categories:
{Questions} × {Answers}
Where obviously
• [Questions] Desires (objectives) lead to problems (practicalities) to solve
• [Answers] Mechanisms (abstract concepts) hosted by a device (implementation) to address questions
Why the cross product? By tabulating everything I learned or know in 4 columns (categories), I can always select a few of them (subset) and notice a lot of recurring themes (questions) and common solution approaches (answers). This corresponds to an old saying “there’s nothing new under the sun”.
Then what about innovations? Are we constantly creating something new? Yes, we still are, but if you look closely, there are very few ideas that are fundamentally new that cannot be synthesized by combining the old ones (sometimes recursively).
Let me use the framework itself as an example on how to apply this framework (yes, it’s recursive):
• Desires: predict and understand many phenomenon
• Problems: mental capacity is limited
• Mechanisms: this framework (breaking observations into 4 categories)
• Devices: tabulation (cross-products, order reduction)
Feedback as an example:
• Desires: have good outcomes (or meet set objectives)
• Problems: not there yet
• Mechanism: take advantage of past data for future outputs (through correction)
• Devices: feedback path (e.g. regulator or control systems.)
Feedforward as an example that shares a lot of properties as feedback:
• Desires: have good outcomes (or meet set objectives)
• Problems: not there yet
• Mechanism: take advantage of past data for future outputs (through prediction)
• Devices: predictor (e.g. algorithm or formula)
Abstraction as an example:
• Desires: understand complexities (e.g. large code base)
• Problems: limited mental capacity (programmers are humans after all)
• Mechanism: abstraction (generic view grouping similar ideas together)
• Devices: black-boxes (e.g. functions, classes)
Trade as an example:
• Desires: improves utility (utility = happiness in economics lingo)
• Problems: one cannot do everything on its own (limited capacity)
• Mechanism: exchange competitive advantages
• Devices: market (goods and services)
Business as an example:
• Desires: improves utility (through trade)
• Problems: need to offer something for trade
• Mechanism: create value
• Devices: operations
Money (and Markets) as two examples:
• Desires: facilitate trade
• Problems: difficult valuation and transfer through barter, decentralized
• Mechanism: a common medium
• Devices: money (currencies), markets (platform for trade)
Law as an example:
• Desires: make the pie bigger by working cooperatively
• Problems: every individual tries to maximize their own interest but mentally too limited to consider working together to grow the pie (pareto efficient solutions)
• Mechanism: set rules and boundaries (I personally think it’s a sloppy patch fix that is way overused and way abused) and get everybody to buy it
• Devices: law and enforcement
Religion as an example
• Desires: coexist peacefully
• Problems: irreconcilable differences
• Mechanism: blind unverified trust (faith)
• Devices: Deities and religion
Just with the examples above, many desires can be consolidated along the lines of making ourselves better off, and many problems can be consolidated along the lines of we’re too stupid. Of course it’s not everything, but it shows the power of tabulating into 4 categories and consolidating the parts into few unique themes.
I chose to abstract the framework into 4 broad categories instead of 2 because two are too simplified to be useful: since the framework is a way to organize (compactify) observations into manageable number of unique items, there will be too many distinct entries if I have only two categories. Nonetheless, I would refrain from having more than 7 categories because most humans cannot reason effectively with that many levels of nested for-loops (that’s what cross products boils down to).
I also separated desires from problems because I realized that way too often people (manager, clients, customers, government, etc.) ask the wrong question (because they narrowed it to the wrong problem) that leads to a lot of wasted work and frequent direction changes. People are too often asked to solve hard problems that turns out to be the wrong ones for fulfilling the motivating desires. Very few learn to trace it back to the source (desires) and find the correct problem to address, which often have easy solutions that’s more valuable to the requester than what was originally asked. This often leads to unhappy outcomes for everybody that’s avoidable. An emphasis on desires is one of my frequently used approaches to prevent these kind of mishaps.
876 total views
Title of this blog site
Initially I started with “TMI: Too Much Information” as the title of this blog, given that my plan was to put fragments of technical information or insights I came across that might be useful for solving problems. That means the blog posts contain more than what you want to know, unless you are looking to solve a specific problem with the help of the post or you are just outright nerdy.
But soon I realized I have some non-technical stuff like gags, music, and the technical stuff covers more than just electronic measurement instruments, so I need a title that’s less common and more catchy.
Today, I came across a reddit post, which user “llllIlllIllIlIRogue Sysadmin “says:
If you don’t they’ll just hear jargon and glaze over completely and not even try to follow you. If you draw a pretty layout of everything, though, they’ll make some token effort to follow along.
They’ll still get lost but now you’re not just a nerd rambling… you’re a rambling nerd with a plan.
Very catchy! Also, I liked the original comment because it covers:
• Passion for geeky topics
• It’s important to communicate well so that people will bother to follow what we have to say.
I did a google search with quotes “rambling nerd with a plan” and only one entry: the original post, showed up, so it’s not a commonly used phrase. I’ll take it 🙂
1,246 total views
|
__label__pos
| 0.792909 |
ToolStrip.Anchor ToolStrip.Anchor ToolStrip.Anchor ToolStrip.Anchor Property
Definizione
Ottiene o imposta i bordi del contenitore a cui è associato un oggetto ToolStrip e determina la modalità con cui un oggetto ToolStrip viene ridimensionato con il relativo elemento padre.Gets or sets the edges of the container to which a ToolStrip is bound and determines how a ToolStrip is resized with its parent.
public:
virtual property System::Windows::Forms::AnchorStyles Anchor { System::Windows::Forms::AnchorStyles get(); void set(System::Windows::Forms::AnchorStyles value); };
public override System.Windows.Forms.AnchorStyles Anchor { get; set; }
member this.Anchor : System.Windows.Forms.AnchorStyles with get, set
Public Overrides Property Anchor As AnchorStyles
Valore della proprietà
Esempi
Esempio di codice seguente viene illustrata la sintassi per l'impostazione comune ToolStrip proprietà, tra cui il Anchor proprietà.The following code example demonstrates the syntax for setting common ToolStrip properties, including the Anchor property.
// This is an example of some common ToolStrip property settings.
//
toolStrip1.AllowDrop = false;
toolStrip1.AllowItemReorder = true;
toolStrip1.AllowMerge = false;
toolStrip1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
toolStrip1.AutoSize = false;
toolStrip1.CanOverflow = false;
toolStrip1.Cursor = System.Windows.Forms.Cursors.Cross;
toolStrip1.DefaultDropDownDirection = System.Windows.Forms.ToolStripDropDownDirection.BelowRight;
toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
toolStrip1.GripMargin = new System.Windows.Forms.Padding(3);
toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
toolStripButton1});
toolStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
toolStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
toolStrip1.Location = new System.Drawing.Point(0, 0);
toolStrip1.Margin = new System.Windows.Forms.Padding(1);
toolStrip1.Name = "toolStrip1";
toolStrip1.Padding = new System.Windows.Forms.Padding(0, 0, 2, 0);
toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
toolStrip1.ShowItemToolTips = false;
toolStrip1.Size = new System.Drawing.Size(109, 273);
toolStrip1.Stretch = true;
toolStrip1.TabIndex = 0;
toolStrip1.TabStop = true;
toolStrip1.Text = "toolStrip1";
toolStrip1.TextDirection = System.Windows.Forms.ToolStripTextDirection.Vertical90;
' This is an example of some common ToolStrip property settings.
'
toolStrip1.AllowDrop = False
toolStrip1.AllowItemReorder = True
toolStrip1.AllowMerge = False
toolStrip1.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles)
toolStrip1.AutoSize = False
toolStrip1.CanOverflow = False
toolStrip1.Cursor = Cursors.Cross
toolStrip1.Dock = System.Windows.Forms.DockStyle.None
toolStrip1.DefaultDropDownDirection = ToolStripDropDownDirection.BelowRight
toolStrip1.GripMargin = New System.Windows.Forms.Padding(3)
toolStrip1.ImageScalingSize = New System.Drawing.Size(20, 20)
toolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {toolStripButton1})
toolStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow
toolStrip1.Location = New System.Drawing.Point(0, 0)
toolStrip1.Margin = New System.Windows.Forms.Padding(1)
toolStrip1.Name = "toolStrip1"
toolStrip1.Padding = New System.Windows.Forms.Padding(0, 0, 2, 0)
toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System
toolStrip1.ShowItemToolTips = False
toolStrip1.Size = New System.Drawing.Size(109, 273)
toolStrip1.Stretch = True
toolStrip1.TabIndex = 0
toolStrip1.TabStop = True
toolStrip1.Text = "toolStrip1"
toolStrip1.TextDirection = System.Windows.Forms.ToolStripTextDirection.Vertical90
Commenti
Usare la Anchor proprietà da definire come un ToolStrip viene ridimensionato automaticamente secondo il relativo controllo padre viene ridimensionato.Use the Anchor property to define how a ToolStrip is automatically resized as its parent control is resized. L'ancoraggio di un controllo al relativo controllo padre assicura che quando il controllo padre viene ridimensionato, dei bordi ancorati rimangano nella stessa posizione in relazione ai bordi del controllo padre.Anchoring a control to its parent control ensures that the anchored edges remain in the same position relative to the edges of the parent control when the parent control is resized.
Nota
Il Anchor e Dock proprietà si escludono a vicenda.The Anchor and Dock properties are mutually exclusive. Solo uno può essere impostato contemporaneamente e l'ultima ha la precedenza.Only one can be set at a time, and the last one set takes precedence.
Si applica a
|
__label__pos
| 0.934287 |
What does it mean when Snapchat says took a screenshot of friendship profile?
Answered by Willian Lymon
When Snapchat says that someone “took a screenshot of your friendship profile,” it means that the person captured an image of your profile and saved it to their device. In other words, they took a screenshot of the information displayed on your profile, including your display name, Bitmoji, and any other visible details.
This feature on Snapchat is designed to notify users when someone takes a screenshot of their friendship profile. However, it’s important to note that this notification is only triggered when the person taking the screenshot is on your friends list. If someone who is not your friend takes a screenshot of your profile, you will not receive any notification.
The purpose of this notification is to let users know that someone has saved an image of their profile. It can be useful in situations where you want to keep track of who is taking screenshots of your profile or if you are concerned about your privacy.
It’s worth mentioning that Snapchat also notifies users when someone takes a screenshot of a Snap or a chat conversation. This notification is sent to both parties involved, regardless of their friendship status on Snapchat.
To summarize, when Snapchat says that someone “took a screenshot of your friendship profile,” it means that the person captured an image of your profile and saved it to their device. This notification is only triggered if the person taking the screenshot is on your friends list. It serves as a way to alert you that someone has saved an image of your profile.
|
__label__pos
| 0.728931 |
Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
PerlMonks
Comment on
( #3333=superdoc: print w/ replies, xml ) Need Help??
There is alot of code around for doing this, here are a few methods to save you the search. They all involve running a loop of some kind. In the Glib examples, you can substitute another event loop of your choosing.
Term-ReadKey in a thread
#!/usr/bin/perl use warnings; use strict; use Term::ReadKey; use threads; $|++; ReadMode('cbreak'); # works non-blocking if read stdin is in a thread my $count = 0; my $thr = threads->new(\&read_in)->detach; while(1){ print "test\n"; sleep 1; } ReadMode('normal'); # restore normal tty settings sub read_in{ while(1){ my $char; if (defined ($char = ReadKey(0)) ) { print "\t\t$char->", ord($char),"\n"; #process key presses here if($char eq 'q'){exit} #if(length $char){exit} # panic button on any key :-) } } } __END__
And an event loop based example using Glib
#!/usr/bin/perl use warnings; use strict; use Glib; my $main_loop = Glib::MainLoop->new; Glib::IO->add_watch (fileno 'STDIN', [qw/in/], \&watch_callback, 'STDI +N'); #just to show it's non blocking my $timer1 = Glib::Timeout->add (1000, \&testcallback, undef, 1 ); $main_loop->run; sub watch_callback { # print "@_\n"; my ($fd, $condition, $fh) = @_; my $line = readline STDIN; print $line; #always return TRUE to continue the callback return 1; } sub testcallback{ print "\t\t\t".time."\n"; } __END__
Another one combining an eventloop Glib with threads
#!/usr/bin/perl use warnings; use strict; use Glib; use Term::ReadKey; use threads; $|++; ReadMode('cbreak'); # works non-blocking if read stdin is in a thread my $count = 0; my $thr = threads->new(\&read_in)->detach; my $main_loop = Glib::MainLoop->new; my $timer = Glib::Timeout->add (1000, \&timer_callback, undef, 1 ); # can also have filehandle watches #my $watcher; #$watcher = Glib::IO->add_watch( fileno( $pty ), ['in', 'hup'], \&call +back); # must be done after main_loop is running #Glib::Idle->add( sub{}); #print "$ps\n"; my $timer1 = Glib::Timeout->add (10, \&testcallback, undef, 1 ); $main_loop->run; ReadMode('normal'); # restore normal tty settings sub testcallback{ my $ps = `ps auxww`; print "$ps\n"; return 0; #only run once } sub timer_callback{ #do stuff $count++; print "\n$count\n"; return 1; } sub read_in{ while(1){ my $char; if (defined ($char = ReadKey(0)) ) { print "\t\t$char->", ord($char),"\n"; #process key presses here if($char eq 'q'){exit} #if(length $char){exit} # panic button on any key :-) if($char eq 'p'){ Glib::Idle->add( sub{ my $ps = `ps auxww`; print "$ps\n"; return 0; # run only once } ); } } } } __END__
And finally an IO::Select based solution to avoid threads
#!/usr/bin/perl use warnings; use strict; use IO::Select; # remember what select says about mixing # buffered reading and "select", so even though the # code works, you might want to substitute # the read via <$fh> with: # my $input; # sysread( $fh, $input, 1024); # loop every 5 second my $timeout = 5; my $s = IO::Select->new(); $s->add( \*STDIN ); while (1) { if ( my @ready = $s->can_read($timeout) ) { # we got input for my $fh (@ready) { print "$fh\n"; my $input = <$fh>; print "got: $input"; } } else { # no input } # just to show that we're looping print scalar localtime,"\n"; }
I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku ................... flash japh
In reply to Re: Ask for STDIN but don't pause for it by zentara
in thread Ask for STDIN but don't pause for it by Anonymous Monk
Title:
Use: <p> text here (a paragraph) </p>
and: <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":
• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Please read these before you post! —
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• Outside of code tags, you may need to use entities for some characters:
For: Use:
& &
< <
> >
[ [
] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?
• See Writeup Formatting Tips and other pages linked from there for more info.
• Log In?
Username:
Password:
What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...
How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (14)
As of 2014-07-28 17:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favorite superfluous repetitious redundant duplicative phrase is:
Results (204 votes), past polls
|
__label__pos
| 0.943866 |
Fixing Firefox’s Backspace Behavior in Linux
If you are coming from Windows background, you might have hard time adapting to how Firefox behaves under Linux. Basically Firefox does not go back to the previous page when the backspace key is pressed.
After making a thorough search on the web, I came to the conclusion that this is indeed an intended behavior and have some philosophical roots. To make long short, the proponents of this behavior state that backspace key is intended to be used when correcting a mistake. And since going back to a page is not result of an error but simply part of surfing the web it should “not” use backspace for this.
Although I can appreciate the logic behind it, I’m against challenging well-established habits that have no practical implications just to be logically sound.
Here’s how to bend Firefox to respect your old habit.
1. Type about:config to the address bar.
2. Start typing “browse” to locate the entry browser.backspace_action
3. Double-click on the “value” column to change it 0 (it is set as 2 by default)
4. Done!
|
__label__pos
| 0.784569 |
macOS* Catalina Machine Learning on Intel® Processor Graphics
By Hisham Chowdhury,
Published: 01/14/2020 Last Updated: 01/14/2020
Introduction
This paper describes advancements and improvements made to the macOS* machine learning stack on Intel® Processor Graphics through Apple*’s latest Mac* operating system, macOS Catalina* (macOS 10.15). It summarizes some of the improvements Intel and Apple have made to Core ML*, the Metal Performance Shaders (MPS) software stack, to take full advantage of Intel Processor Graphics architecture. The paper also describes the Create ML feature, through which a model (mlmodel) can be created on an Intel® powered device running macOS without the need for data leaving the device.
A follow up to the Apple Machine Learning on Intel Processor Graphics paper, the information here builds on the content of this previous paper
Target Audience
Software developers, platform architects, data scientists, and academics seeking to maximize machine learning performance on Intel Processor Graphics on macOS platforms will find this content useful.
Architecture
Read this section for a recap on inference and training architecture with macOS Catalina on Intel Processor Graphics.
Core ML*
Core ML, available on Apple devices, is the main framework for accelerating domain-specific ML inference capability such as image analysis, object detection, natural language processing, and more. Core ML allows you to take advantage of Intel processors and Intel Processor Graphics technology to build and run ML workloads on a device so that your data does not need to leave it. This removes the dependency on network connectivity, security, and privacy concerns. Core ML is built on top of low-level frameworks such as MPS (Intel Processor Graphics) and accelerates basic neural network subroutines (BNNS on Intel processors) that are highly tuned and optimized for Intel hardware to maximize the hardware capability.
Metal Performance Shaders
MPS is the main building block for Core ML to run ML workloads on graphics processing units (GPUs). To target underlying GPU devices, you can write applications to use the MPS API directly. With MPS, you can encode the machine learning dispatches and commands tasks using the same command buffers that are used with metal-based 3D, and compute workloads for traditional graphics applications.
Create ML
Create ML, upgraded to be a standalone app, lets you build various types of custom machine learning models, including image classifier, object detector, activity classifier, and others. It uses transfer learning technology with Intel Processor Graphics to train models faster. Major improvements and additions were made to Create ML so you can now create and train custom machine learning models on macOS platforms that use Intel Processor Graphics. You can integrate those improvements into part of your Core ML applications.
catalina machine learning process
Figure 1. macOS Catalina machine learning on Intel Processor Graphics.
Performance
Significant improvements were made with macOS Catalina on top of the earlier release, with macOS Mojave* using Intel Processor Graphics technology. As previously mentioned, with macOS Catalina we deployed an improved machine learning algorithm for key primitives, optimized how we deploy work to the underlying hardware, and more. Such improvements are a continuous process, and Figure 2 gives you an idea on where the performance gains are (see the disclaimer). The numbers in Figure 2 were generated from macOS Catalina and Mojave using a 13-inch MacBook Pro* running Intel® Processor Graphics Architecture.
core m l improvements
Figure 2. Performance improvements using Core ML.
The denoiser model is using an Intel® Open Image Denoise trained model to denoise a high-resolution noisy image. Figure 3 shows the output running Intel Open Image Denoise through Core ML on a 13-inch MacBook Pro 2016 powered by Intel Processor Graphics Gen9 architecture. Figure 3 and figure 4 from below demonstrates the result of running Intel® Open Image Denoiser using CoreML through Intel Processor Graphics Gen9 architecture.
denoised bistro comparison
Figure 3. Denoised bistro.
denoised sponza comparison
Figure 4. Denoised Sponza.
Figure 5 shows Web Machine Learning (WebML) improvements compared to a legacy WebGL* API, with macOS Catalina on a 13-inch MacBook Pro 2016 powered by Intel Processor Graphics Gen9 architecture.
web m l improvements compared to a legacy web g l a p i
Figure 5. Chromium* open source project running with WebGL API.
Figure 6 shows running the same model using WebML implementation and performance gain that can be achieved with WebML powered by Metal Performance Shaders and Intel Processor Graphics compared to WebGL implementation running on the same hardware.
implementation and performance gain with web m l
Figure 6. Chromium open source project running with WebML API powered by MPS.
Note The examples from Figures 5 and 6 can be found here.
Significant improvements were made to third-party applications such as Adobe Lightroom* Enhance Detail, Pixelmator Pro*, and others. The chart in Figure 7 shows an example of the improvement we deployed for an Adobe Lightroom Enhance Detail application.
performance improvement mojave to catalina
Figure 7. Performance improvement with Adobe Lightroom Enhance Detail.
What's New
For full list of new capabilities and features, visit the Apple Machine Learning and Metal Performance Shaders pages for detailed information on Core ML, Create ML, and others.
With macOS Catalina, Apple and Intel improved performance of all the key neural network layers by deploying new convolution algorithms, optimizing memory usage, reducing network build time, adding batch inference support to better use the underlying hardware, including smart heuristics to deploy the best algorithm or kernel for specific layers, and more.
Batching
To keep the hardware fairly occupied, we recommend using MPS encode batch API and or Core ML batch interfaces to submit your neural network. With the new batching API, instead of sending one input to process you can send multiple inputs to process, and the hardware can schedule the work more efficiently to take better advantage of the underlying hardware. Also, the API seamlessly gets improvements when upgrading to newer generations of Intel Processor Graphics. With these approaches, the underlying driver keeps the hardware consistently occupied with the high utilization of Intel Processor Graphics execution units.
The chart in Figure 8 shows some of the performance improvements that can be achieved using the batch API.
performance improvements achieved using the batch a p i
Figure 8: Metal Performance Shader improvements with batching.
Create ML
Using Create ML, you can create your ML models directly on your macOS device running on Intel Processor Graphics. You can create ML models on the device to perform several types of tasks, including image classification, activity classification, object detection, and more.
Simple Image Classifier Using Create ML
The following simple example shows how to quickly create a custom image-classifier model using Create ML on an Intel Processor Graphics powered platform.
To create a simple “car make” classifier that can detect the differences between Tesla*, BMW*, and other cars, follow these steps:
1. Open the Create ML app on your macOS machine.
create m l app
2. Select the model type to create. For this example, it is the Image Classifier model.
model type selection
3. Add a description of the model.
description model
4. Select the training data set with labels. For this training data set, you create three folders (BMW, Tesla, Other) to contain images of the car categories. The folder name is the prediction label for that category of cars.
selecting data sets
creating folders
5. Select the images to be used to test the model. Use different images of the same category from the ones that we have used in our training set.
select files
looking in folders
same category images
6. Select Train to start the model training.
starting model training
testing images
7. As the above status shows, it took only two minutes to process and train the model with the training data set. When the training phase is complete, the Create ML interface gives additional information, such as the precision of the model based on the testing data set. It’s now time to test the model with some custom images the model has not previously seen.
As the following four screens show, the car models were identified correctly.
first identification tesla
second tesla identification
b m w identification
other car identification
second bmw identification
8. The fifth screen above shows that the BMW car was not correctly identified. For incorrect predictions you need to adjust several knobs in the Create ML app, such as training data set, iteration, and others to improve the model’s accuracy.
9. After these knob adjustments, you save the model .mlmodel for deployment with the Core ML application.
saving models
using m l model in core m l
10. You can now use the .mlmodel in the Core ML application to detect the differences between these three types of cars.
This example shows how Intel Processor Graphics enables CreateML, Core ML, and MPS (on macOS platforms) to simplify the training process with transfer learning technology.
For more information and all the latest features, visit Create ML.
Summary
This paper shows how the improvements that Apple and Intel made to the existing and new software stack with Core ML, Create ML, and MPS, take advantage of the underlying Intel Processor Graphics hardware.
References
For more information or to get started, download the tools or libraries from the following links:
Apple Machine Learning
Apple Machine Learning Resources
Metal Performance Shaders
The Compute Architecture of Intel Processor Graphics Gen9
Apple Machine Learning on Intel Processor Graphics
WebML
WebML Examples
Adobe Enhance Detail
Pixelmator Pro
Intel Open Image Denoise
Product and Performance Information
1
Performance varies by use, configuration and other factors. Learn more at www.Intel.com/PerformanceIndex.
|
__label__pos
| 0.598136 |
Agar
Agar 1.7 Manual
VG_View(3)
SYNOPSIS
#include <agar/core.h>
#include <agar/gui.h>
#include <agar/vg.h>
DESCRIPTION
ScreenshotThe VG_View widget displays a VG(3) vector graphics object. VG_View also provides a simple "tool" registration interface which allows modular editors to be implemented quickly.
INHERITANCE HIERARCHY
AG_Object(3)-> AG_Widget(3)-> VG_View.
INTERFACE
VG_View * VG_ViewNew (void *parent, VG *vg, Uint flags)
void VG_ViewSetVG (VG_View *vv, VG *vg)
void VG_ViewSetScale (VG_View *vv, float c)
void VG_ViewSetScalePreset (VG_View *vv, int index)
void VG_ViewSetScaleMin (VG_View *vv, float c)
void VG_ViewSetScaleMax (VG_View *vv, float c)
void VG_ViewSetSnapMode (VG_View *vv, enum vg_snap_mode mode)
void VG_ViewSetGrid (VG_View *vv, int gridID, VG_GridType type, int interval, VG_Color color)
Uint VG_AddEditArea (VG_View *vv, void *widget)
void VG_ClearEditAreas (VG_View *vv)
void VG_Status (VG_View *vv, const char *format, ...)
void VG_StatusS (VG_View *vv, const char *text)
void VG_EditNode (VG_View *vv, Uint editArea, VG_Node *vn)
void VG_ApplyConstraints (VG_View *vv, VG_Vector *pos)
void VG_GetVGCoords (VG_View *vv, int x, int y, VG_Vector *v)
void VG_GetVGCoordsFlt (VG_View *vv, VG_Vector pos, VG_Vector *v)
void VG_GetViewCoords (VG_View *vv, VG_Vector v, int *x, int *y)
void VG_GetViewCoordsFlt (VG_View *vv, VG_Vector v, float *x, float *y)
void * VG_Nearest (VG_View *vv, VG_Vector vPos)
void * VG_NearestPoint (VG_View *vv, VG_Vector vPos, void *ignore)
The VG_ViewNew() function allocates, initializes, and attaches a VG_View widget displaying the specified vg object. Acceptable flags include:
VG_VIEW_GRIDDisplay the grid; see VG_ViewSetGrid().
VG_VIEW_EXTENTSDisplay the bounding boxes of the VG elements. This option is only implemented in debug mode.
VG_VIEW_DISABLE_BGDisable the VG-specific background.
VG_VIEW_CONSTRUCTIONDisplay VG elements marked as "for construction", such as the points used to construct a polygon. The exact interpretation of this setting is element-specific.
VG_VIEW_HFILLExpand horizontally in parent container.
VG_VIEW_VFILLExpand vertically in parent container.
VG_VIEW_EXPANDShorthand for VG_VIEW_HFILL VG_VIEW_VFILL|.
The VG object displayed can be changed at runtime with VG_ViewSetVG(). If a VG tool (see TOOL INTERFACE) is currently in use, changing the VG has the side effect of deselecting the tool.
VG_ViewSetScale() sets the scaling factor at which the vector scene will be displayed. The VG_ViewSetScalePreset() variant accepts an index into the table of preset scaling factors as an argument (0..nScaleFactors). VG_ViewSetScaleMin() and VG_ViewSetScaleMax() specify the range of scaling factors the user is allowed to select.
VG_ViewSetSnapMode() selects the snapping constraint mode for the cursor. Acceptable values of mode include:
VG_FREE_POSITIONINGNo snapping constraint.
VG_GRIDSnap cursor to active grid.
VG_ENDPOINTSnap to line endpoints.
VG_CLOSEST_POINTSnap to closest point on nearest entity.
VG_ViewSetGrid() either creates a new grid, or changes the parameters of an existing grid gridID. The interval argument specifies the interval of the grid (in pixels). color sets the color which will be used to display the grid. type sets the style of rendering:
VG_GRID_POINTSDraw the grid as an array of points.
VG_GRID_LINESDraw the grid using lines only.
The VG_AddEditArea() routine indicates a container widget which the VG_View should use to display tool-specific GUI elements. Whenever a tool (or a VG_Node) is selected, its optional edit() operation may create one or more GUI elements bound to various parameters. Multiple edition areas are allowed. VG_AddEditArea() returns an index into the editAreas array of VG_View.
VG_ClearEditAreas() destroys all widgets currently attached to the container(s) registered by VG_AddEditArea().
VG_Status() sets the text displayed by any AG_Statusbar(3) associated with the VG_View.
VG_EditNode() populates the specified edit area (index as returned by VG_AddEditArea()) with the controls returned by the edit() operation of the specified VG_Node. VG_EditNode() is automatically invoked by the stock selection tool vgSelectTool when an entity is selected.
The VG_ApplyConstraints() routine applies effective position constraints (e.g., the snapping mode given by VG_ViewSetSnapMode()) on the given position, overwriting the contents of pos with the result.
The VG_GetVGCoords() routine converts the given integer coordinates (relative to the VG_View widget), into real coordinates in the VG scene. The VG_GetVGCoordsFlt() variant accepts view coordinates in floating-point format.
Conversely, VG_GetViewCoords() and VG_GetViewCoordsFlt() convert the specified real VG coordinates v to integer (or floating-point) view coordinates into x, y.
The VG_Nearest() routine returns a pointer to the entity nearest to the given coordinates. The VG_NearestPoint() variant searches the scene for a point which intersects a VG element and is closest to the specified VG coordinates vPos. ignore is an optional pointer to an element which should be ignored in the computation.
RENDERING ROUTINES
The draw() operation of most VG(3) elements will use the standard GUI rendering routines (see AG_Widget(3), RENDERING AND PRIMITIVES), or perform direct OpenGL calls. Vector coordinates are typically translated to view coordinates using VG_GetViewCoords(). The following rendering routines are specific to VG_View and must be invoked from VG_Node() draw() context.
void VG_DrawSurface (VG_View *vv, int x, int y, float degs, int su)
The VG_DrawSurface() routine renders the contents of a surface at view coordinates x, y in pixels, rotated clockwise by degs degrees. The surface su must have been previously mapped to the VG_View object (see AG_WidgetMapSurface(3)).
TOOL INTERFACE
VG_Tool * VG_ViewRegTool (VG_View *vv, const VG_ToolOps *classInfo, void *userPtr)
void VG_ViewSelectTool (VG_View *vv, VG_Tool *tool, void *userPtr)
VG_Tool * VG_ViewFindTool (VG_View *vv, const char *name)
VG_Tool * VG_ViewFindToolByOps (VG_View *vv, const VG_ToolOps *classInfo)
void VG_ViewSetDefaultTool (VG_View *vv, VG_Tool *tool)
Implementing an editor using VG_View is typically done by registering a set of tools which are invoked using a callback-style interface.
VG_ViewRegTool() registers a new tool class (described by the provided classInfo structure) with the VG_View. userPtr is an optional user pointer which will be passed to the tool. The VG_ToolOps structure is as follows. Any of the callback functions may be set to NULL.
typedef struct vg_tool_ops {
const char *name; /* Tool name */
const char *desc; /* Optional description */
AG_StaticIcon *icon; /* Optional GUI icon */
AG_Size len; /* Size of instance structure */
Uint flags; /* Options (see below) */
void (*init)(void *);
void (*destroy)(void *);
void *(*edit)(void *, struct vg_view *);
void (*predraw)(void *, struct vg_view *);
void (*postdraw)(void *, struct vg_view *);
void (*selected)(void *, struct vg_view *);
void (*deselected)(void *, struct vg_view *);
int (*mousemotion)(void *, VG_Vector vPos, VG_Vector vRel,
int buttons);
int (*mousebuttondown)(void *, VG_Vector vPos, int button);
int (*mousebuttonup)(void *, VG_Vector vPos, int button);
int (*keydown)(void *, int ksym, int kmod, Uint32 unicode);
int (*keyup)(void *, int ksym, int kmod, Uint32 unicode);
} VG_ToolOps;
The name field specifies a short name for the tool. desc is a short description of the purpose of the tool. icon is an optional AG_StaticIcon(3) for the GUI.
The len value specifies the size, in bytes, of the structure which will be used to describe an instance of the tool (either VG_Tool or a derivative of it).
Acceptable flags options include:
VG_NOSNAPDisable position constraints in any context.
VG_MOUSEMOTION_NOSNAPDisable position constraints when communicating mouse motion events to the tool.
VG_BUTTONUP_NOSNAPDisable position constraints when communicating mouse button release events to the tool.
VG_BUTTONDOWN_NOSNAPDisable position constraints when communicating mouse button press events to the tool.
VG_BUTTON_NOSNAPImplies VG_BUTTONUP_NOSNAP and VG_BUTTONDOWN_NOSNAP
VG_NOEDITCLEARWhen the tool is selected, do not perform automatic removal of GUI elements in the containers specified by VG_AddEditArea().
The init() callback initializes an instance of the tool. destroy() releases resources allocated by an instance of the tool.
The edit() operation creates one or more GUI elements, typically used to set various tool-specific options. The object returned by edit() should be a derivative of AG_Widget(3).
The predraw() and postdraw() callbacks are invoked prior to, and after rendering of the scene by the VG_View. Typically, postdraw() is used to render specialized cursors or provide visual feedback to the user in a manner specific to the tool.
selected() and deselected() are invoked whenever the tool is, respectively, selected or deselected by the user.
Low-level mouse and keyboard events can be handled directly by the tool using mousemotion() mousebuttondown(), mousebuttonup(), keydown() and keyup(). The coordinates passed to mouse-related callbacks are subject to the current position constraints, unless disabled by one of the VG_*_NOSNAP flags in the flags field.
SEE ALSO
VG(3)
HISTORY
The VG_View interface first appeared in Agar 1.3.0, and was first documented in Agar 1.3.3.
Csoft.net ElectronTubeStore www.libAgar.org is © 2022 Julien Nadeau Carriere <[email protected]>.
Support LibAgar: www.patreon.com/libAgar.
|
__label__pos
| 0.533961 |
Home » Need for Indian Government to emphasise blockchain education initiative
Need for Indian Government to emphasise blockchain education initiative
by admin
Tapang Sanggar
The term blockchain was out of common usage a few years ago, but it is now the talk of the town due to its application to the financial ecosystem. But its impact extends beyond the financial sector. Being decentralized and immutable, blockchain can find applications in healthcare, defense, infrastructure, and education.
Blockchain education: key to economic growth
Blockchain technology is making waves as one of the most disruptive and promising technologies of our time. Most people have associated it with the dawn of the dotcom era. The dot-com era revolutionized the way businesses operate and created a multi-billion dollar industry. This analogy directly invokes the need to accelerate deeper research into this revolutionary new technology.
Blockchain education can be delivered in multiple ways. Educational curricula can accommodate subjects that teach students about blockchain in schools and higher education institutions. The central government may introduce blockchain education into the National Education Policy (NEP). Special courses can also be curated at universities/institutions to teach people how to create and implement blockchain.
Companies developing blockchain technology, and even those adopting it, can launch initiatives to educate and educate the public about blockchain, its uses, and its potential. I can do it. Governments should also focus on creating legal provisions for cybercrime, smart contracts, etc.
Why Do We Need Blockchain Education?
Blockchain education is essential to achieving financial freedom and personal wealth growth. To understand the importance of blockchain education, we must first understand the technology itself and how it works.
The most basic description of this modern technology is that it is a distributed ledger that can store data incrementally, but the stored data cannot be modified or altered. The decentralized nature of blockchain makes the ecosystem anti-fraud and transparent. Additionally, blockchain networks are supported by globally distributed computers, rather than the traditional approach of a central server supporting the network.
In today’s world, blockchain technology is revolutionizing every aspect of human life. Artificial intelligence, the advent of the Internet of Things (IoT), the availability of cheap computing, and global internet services have enabled highly granular processes and applications, from financial transactions and election voting to academic teaching and testimony. can bring innovation to .
Why is blockchain the future?
Blockchain education produces more skilled blockchain professionals, leading to secondary benefits of blockchain education such as job creation. It offers a creative approach to storing information, conducting transactions, performing tasks, and building trust.
Blockchain also benefits education by increasing transparency, improving accountability through smart contracts, and encouraging learning. For example, blockchain immutable ledger technology drafts a chronological list of events that occur in real time. This unique property helps track student academic and career trajectories.
Global spending on blockchain technology is expected to grow by more than $14 billion by 2023, according to the International Data Corporation (IDC).
The Ministry of Electronics and Information Technology (MeitY) has released a “National Strategy on Blockchain” to enable trusted digital platforms to create a blockchain framework for developing applications based on this latest technology. It’s movement.
How can business organizations help?
Organizations can initiate and promote apprenticeship and internship programs to advance the state of blockchain education. We also feel an urgent need to initiate legal blockchain education initiatives to remove roadblocks in the field of distributed ledger technology. There are also significant gaps in the area of blockchain regulatory compliance. We feel organizations need to start focusing on this neglected area that has the potential to leapfrog the blockchain space.
Author is Founder, Chief, Evangelist, P2E Pro. Views are personal.
Also read: UOLO Appoints Former Amazon’s Anshu Sharma as CTO
Please follow us twitter, Facebook, LinkedIn
Related Posts
Leave a Comment
|
__label__pos
| 0.869486 |
Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.
Possible Duplicate:
Private variable vs property?
I have a public property with a get and set accessor. Associated with this property is a private field.
Is it best practice when referencing these values in other parts of a classes code to use the private field or the public exposed property. Although I release I have made a private bool personFieldSpecified field when I probably didn't need to I did this to better explain my question.
private SimplePerson personField;
private bool personFieldSpecified;
public SimplePerson Person
{
get
{
if (personField == null)
personField = new SimplePerson();
return personField;
}
set
{
personField = value;
// Q) Should I access the public property here or the private field
PersonSpecified = true;
}
}
public bool PersonSpecified
{
get
{
return personFieldSpecified;
}
set
{
personFieldSpecified = value;
}
}
Because I'm aware of the inner implementation of the set I know that it will effect the end result if I set either, however I am wondering which is the better practice to do for long term maintainability. This could apply to methods of my class as well!
What would be the reasons for choosing one particular method over the other. Does it depend on what the property itself is doing in which case I have to have knowledge of it's inner workings or does it come down to design?
share|improve this question
@pdr Yes it is thanks. I did do a search but couldn't find a question on this. The duplicate question has answered mine. – dreza Mar 12 '12 at 23:04
add comment
marked as duplicate by pdr, Karl Bielefeldt, Walter, jmort253, Yannis Rizos Mar 13 '12 at 13:12
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
1 Answer
If a property exists for a field, I would recommend always using it to access the property even within the class. This will help prevent you introducing bugs in future if you do add other logic in the property getter or setter which you would then bypass if you directly accessed the field.
The rule I follow is if a property exists for a field, only access the field from the class construtor or the property. I'd even go so far as to add a private setter to ensure that any 'set' logic is still encapsulated against further change.
The only time to go against this is if you have a field which is not exposed outside the class (e.g. a bool field to determine whether the class has been disposed).
share|improve this answer
Thanks Trevor. It appears my question is a duplicate of programmers.stackexchange.com/questions/133015/… but what you said makes sense. – dreza Mar 12 '12 at 23:05
add comment
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.601358 |
There are many ways that you can store and retrieve information
There are many ways that you can store and retrieve information. For instance, if your information is physical, such as a printed document, you can you a filing system to store information in such a way that it is easy to find the information again when you need it.
You can also use electronic means of storing information, such as a computer hard drive, or a memory stick. These can make information easy to access for yourself, but you would have to use a different method if you wanted to share it with someone else. You would also need to encrypt the data, as if you lost the USB stick whoever found it would be able to access the data on it.
You can also store information online, by using the systems such as OneDrive or SharePoint, which can only be accessed by people that have permission. In work, we often save documents onto our SharePoint system so that they are safely stored and that our whole team can access the documents.
|
__label__pos
| 0.829047 |
Release: 1.1.0b3 | Release Date: July 26, 2016
SQLAlchemy 1.1 Documentation
Contents | Index
Source code for examples.dogpile_caching.environment
"""environment.py
Establish data / cache file paths, and configurations,
bootstrap fixture data if necessary.
"""
from . import caching_query
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from dogpile.cache.region import make_region
import os
from hashlib import md5
import sys
py2k = sys.version_info < (3, 0)
if py2k:
input = raw_input
# dogpile cache regions. A home base for cache configurations.
regions = {}
# scoped_session. Apply our custom CachingQuery class to it,
# using a callable that will associate the dictionary
# of regions with the Query.
Session = scoped_session(
sessionmaker(
query_cls=caching_query.query_callable(regions)
)
)
# global declarative base class.
Base = declarative_base()
root = "./dogpile_data/"
if not os.path.exists(root):
input("Will create datafiles in %r.\n"
"To reset the cache + database, delete this directory.\n"
"Press enter to continue.\n" % root
)
os.makedirs(root)
dbfile = os.path.join(root, "dogpile_demo.db")
engine = create_engine('sqlite:///%s' % dbfile, echo=True)
Session.configure(bind=engine)
def md5_key_mangler(key):
"""Receive cache keys as long concatenated strings;
distill them into an md5 hash.
"""
return md5(key.encode('ascii')).hexdigest()
# configure the "default" cache region.
regions['default'] = make_region(
# the "dbm" backend needs
# string-encoded keys
key_mangler=md5_key_mangler
).configure(
# using type 'file' to illustrate
# serialized persistence. Normally
# memcached or similar is a better choice
# for caching.
'dogpile.cache.dbm',
expiration_time=3600,
arguments={
"filename": os.path.join(root, "cache.dbm")
}
)
# optional; call invalidate() on the region
# once created so that all data is fresh when
# the app is restarted. Good for development,
# on a production system needs to be used carefully
# regions['default'].invalidate()
installed = False
def bootstrap():
global installed
from . import fixture_data
if not os.path.exists(dbfile):
fixture_data.install()
installed = True
|
__label__pos
| 0.778505 |
offer avx and sse to speed up float->uint8 for tx
This commit is contained in:
Hoernchen 2013-05-06 21:52:19 +02:00
parent 2d9e29ee46
commit 80b4ad2921
2 changed files with 132 additions and 29 deletions
View file
@ -43,6 +43,15 @@ include(GrVersion) #setup version info
########################################################################
# Compiler specific setup
########################################################################
SET(USE_SIMD "no" CACHE STRING "Use SIMD instructions")
SET(USE_SIMD_VALUES "no" "SSE2" "AVX")
SET_PROPERTY(CACHE USE_SIMD PROPERTY STRINGS ${USE_SIMD_VALUES})
LIST(FIND USE_SIMD_VALUES ${USE_SIMD} USE_SIMD_INDEX)
IF(${USE_SIMD_INDEX} EQUAL -1)
message(FATAL_ERROR "Option ${USE_SIMD} not supported, valid entries are ${USE_SIMD_VALUES}")
ENDIF()
IF(CMAKE_COMPILER_IS_GNUCXX)
ADD_DEFINITIONS(-Wall)
ADD_DEFINITIONS(-Wextra)
@ -56,6 +65,23 @@ IF(CMAKE_COMPILER_IS_GNUCXX)
ADD_DEFINITIONS(-fvisibility=hidden)
ADD_DEFINITIONS(-fvisibility-inlines-hidden)
ENDIF(NOT WIN32)
IF(USE_SIMD MATCHES SSE2)
ADD_DEFINITIONS(-msse2)
ADD_DEFINITIONS(-DUSE_SSE2)
ENDIF()
IF(USE_SIMD MATCHES AVX)
ADD_DEFINITIONS(-march=native)
ADD_DEFINITIONS(-DUSE_AVX)
ENDIF()
ELSEIF(MSVC)
IF(USE_SIMD MATCHES SSE2)
ADD_DEFINITIONS(/arch:SSE2)
ADD_DEFINITIONS(-DUSE_SSE2)
ENDIF()
IF(USE_SIMD MATCHES AVX)
ADD_DEFINITIONS(/arch:AVX)
ADD_DEFINITIONS(-DUSE_AVX)
ENDIF()
ENDIF(CMAKE_COMPILER_IS_GNUCXX)
########################################################################
View file
@ -29,6 +29,12 @@
#include <stdexcept>
#include <iostream>
#include <algorithm>
#ifdef USE_AVX
#include <immintrin.h>
#elif USE_SSE2
#include <emmintrin.h>
#endif
#include <boost/assign.hpp>
#include <boost/format.hpp>
@ -126,10 +132,10 @@ hackrf_sink_c_sptr make_hackrf_sink_c (const std::string & args)
* are connected to this block. In this case, we accept
* only 0 input and 1 output.
*/
static const int MIN_IN = 1; // mininum number of input streams
static const int MAX_IN = 1; // maximum number of input streams
static const int MIN_OUT = 0; // minimum number of output streams
static const int MAX_OUT = 0; // maximum number of output streams
static const int MIN_IN = 1; // mininum number of input streams
static const int MAX_IN = 1; // maximum number of input streams
static const int MIN_OUT = 0; // minimum number of output streams
static const int MAX_OUT = 0; // maximum number of output streams
/*
* The private constructor
@ -320,9 +326,74 @@ bool hackrf_sink_c::stop()
return ! (bool) hackrf_is_streaming( _dev );
}
#ifdef USE_AVX
void convert_avx(const float* inbuf, unsigned char* outbuf,const unsigned int count)
{
__m256 mulme = _mm256_set_ps(127.0f, 127.0f, 127.0f, 127.0f, 127.0f, 127.0f, 127.0f, 127.0f);
__m128i addme = _mm_set_epi16(127, 127, 127, 127, 127, 127, 127, 127);
for(unsigned int i=0; i<count;i++){
__m256i itmp3 = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(&inbuf[i*16+0]), mulme));
__m256i itmp4 = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(&inbuf[i*16+8]), mulme));
__m128i a1 = _mm256_extractf128_si256(itmp3, 1);
__m128i a0 = _mm256_castsi256_si128(itmp3);
__m128i a3 = _mm256_extractf128_si256(itmp4, 1);
__m128i a2 = _mm256_castsi256_si128(itmp4);
__m128i outshorts1 = _mm_add_epi16(_mm_packs_epi32(a0, a1), addme);
__m128i outshorts2 = _mm_add_epi16(_mm_packs_epi32(a2, a3), addme);
__m128i outbytes = _mm_packus_epi16(outshorts1, outshorts2);
_mm_storeu_si128 ((__m128i*)&outbuf[i*16], outbytes);
}
}
#elif USE_SSE2
void convert_sse2(const float* inbuf, unsigned char* outbuf,const unsigned int count)
{
const register __m128 mulme = _mm_set_ps( 127.0f, 127.0f, 127.0f, 127.0f );
__m128i addme = _mm_set_epi16( 127, 127, 127, 127, 127, 127, 127, 127);
__m128 itmp1,itmp2,itmp3,itmp4;
__m128i otmp1,otmp2,otmp3,otmp4;
__m128i outshorts1,outshorts2;
__m128i outbytes;
for(unsigned int i=0; i<count;i++){
itmp1 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+0]), mulme);
itmp2 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+4]), mulme);
itmp3 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+8]), mulme);
itmp4 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+12]), mulme);
otmp1 = _mm_cvtps_epi32(itmp1);
otmp2 = _mm_cvtps_epi32(itmp2);
otmp3 = _mm_cvtps_epi32(itmp3);
otmp4 = _mm_cvtps_epi32(itmp4);
outshorts1 = _mm_add_epi16(_mm_packs_epi32(otmp1, otmp2), addme);
outshorts2 = _mm_add_epi16(_mm_packs_epi32(otmp3, otmp4), addme);
outbytes = _mm_packus_epi16(outshorts1, outshorts2);
_mm_storeu_si128 ((__m128i*)&outbuf[i*16], outbytes);
}
}
#endif
void convert_default(float* inbuf, unsigned char* outbuf,const unsigned int count)
{
for(unsigned int i=0; i<count;i++){
outbuf[i]= inbuf[i]*127+127;
}
}
int hackrf_sink_c::work( int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items )
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items )
{
const gr_complex *in = (const gr_complex *) input_items[0];
@ -334,34 +405,40 @@ int hackrf_sink_c::work( int noutput_items,
}
unsigned char *buf = _buf + _buf_used;
int items_consumed = 0;
unsigned int prev_buf_used = _buf_used;
for (int i = 0; i < noutput_items; i++) {
if ( _buf_used + BYTES_PER_SAMPLE > BUF_LEN ) {
{
boost::mutex::scoped_lock lock( _buf_mutex );
unsigned int remaining = (BUF_LEN-_buf_used)/2; //complex
if ( ! cb_push_back( &_cbuf, _buf ) ) {
_buf_used = prev_buf_used;
items_consumed = 0;
std::cerr << "O" << std::flush;
break;
} else {
// std::cerr << "." << std::flush;
}
unsigned int count = std::min((unsigned int)noutput_items,remaining);
unsigned int sse_rem = count/8; // 8 complex = 16f==512bit for avx
unsigned int nosse_rem = count%8; // remainder
#ifdef USE_AVX
convert_avx((float*)in, buf, sse_rem);
convert_default((float*)(in+sse_rem*8), buf+(sse_rem*8*2), nosse_rem*2);
#elif USE_SSE2
convert_sse2((float*)in, buf, sse_rem);
convert_default((float*)(in+sse_rem*8), buf+(sse_rem*8*2), nosse_rem*2);
#else
convert_default((float*)in, buf, count*2);
#endif
_buf_used += (sse_rem*8+nosse_rem)*2;
int items_consumed = sse_rem*8+nosse_rem;
if(noutput_items >= remaining) {
{
boost::mutex::scoped_lock lock( _buf_mutex );
if ( ! cb_push_back( &_cbuf, _buf ) ) {
_buf_used = prev_buf_used;
items_consumed = 0;
std::cerr << "O" << std::flush;
} else {
// std::cerr << "." << std::flush;
_buf_used = 0;
}
_buf_used = 0;
break;
}
*buf++ = (in[i].real() + 1.0) * 127;
*buf++ = (in[i].imag() + 1.0) * 127;
_buf_used += BYTES_PER_SAMPLE;
items_consumed++;
}
noutput_items = items_consumed;
|
__label__pos
| 0.971889 |
OpenGL is a graphics standard and API which targets the desktop and workstation markets. It is designed to be easy to accelerate with dedicated computer hardware, and hence most implementations give greatly improved performance over traditional software rendering. Currently, OpenGL is used for ...
learn more… | top users | synonyms
10
votes
3answers
5k views
Animation in OpenGL using 3D Models
I have created a model in Blender. Now i want to read that 3D model in my c++ program. I figured that a model can be exported to various file formats e.g. .obj, .3ds or COLLADA and then can be read in ...
10
votes
2answers
4k views
Efficient skeletal animation
I am looking at adopting a skeletal animation format (as prompted here) for an RTS game. The individual representation of each model on-screen will be small but there will be lots of them! In ...
9
votes
2answers
5k views
OpenGL: Is it possible to use VAO's without specifying a VBO
On all the tutorials I can find about VAO's (Vertex Array Objects), they show on how to use them by configuring vertex attributes and binding a VBO (Vertex Buffer Object). But I want to create a VAO ...
9
votes
1answer
18k views
How does gluLookAt work?
From my understanding, gluLookAt( eye_x, eye_y, eye_z, center_x, center_y, center_z, up_x, up_y, up_z ); is equivalent to: glRotatef(B, 0.0, 0.0, 1.0); ...
8
votes
3answers
3k views
What state is stored in an OpenGL Vertex Array Object (VAO) and how do I use the VAO correctly?
I was wondering what state is stored in an OpenGL VAO. I've understood that a VAO contains state related to the vertex specifications of buffered vertices (what attributes are in the buffers, and what ...
8
votes
3answers
3k views
Font outline in OpenGL, FTGL
I'm using FTGL library to render fonts in my game, but I have completely no idea how to create an outline around text. Achieving a shadow could be easy, because I can simply do it like this: (pseudo ...
8
votes
3answers
2k views
Deferred shading - how to combine multiple lights?
I'm starting out with GLSL and I've implemented simple deferred shading that outputs G-buffer with positions, normals and albedo. I've also written a simple point light shader. Now I draw a sphere ...
7
votes
4answers
1k views
glsl demo suggestions?
In a lot of places I interviewed recently, I have been asked many a times if I have worked with shaders. Even though, I have read and understand the pipeline, the answer to that question has been no. ...
5
votes
1answer
592 views
How to insert and remove blocks quickly in a Minecraftian world?
I currently have volume data for the world stored as an array of booleans. I then check each empty block and if it has non-empty neighbors the faces get drawn. This prevents me from sending a bunch ...
2
votes
2answers
6k views
What is the best method to update shader uniforms?
What is the most accepted way for keeping a shader's matrices up to date, and why? For example, at the moment I have a Shader class that stores the handles to the GLSL shader program & uniforms. ...
12
votes
12answers
13k views
Is it a waste to learn OpenGL?
What I've gathered around the internet and various sources is that DirectX has pretty much taken a stronghold grip onto the graphics API domain. And to be honest, I gave learning DirectX10 a chance, ...
12
votes
1answer
6k views
How can I tell how much video card memory I'm using?
I want to programmatically determine at runtime how much video card memory is being used by my program. Specifically I'm wondering about how to do it on a Windows machine using OpenGL, but am ...
11
votes
8answers
20k views
Getting Started with 2d Game Dev (C++): DirectX or OpenGL? [closed]
So, i'm a student looking to get my foot in the door of game development and im looking to do something 2D, maybe a tetris/space invaders/something-with-a-little-mouse-interaction clone. I pointed ...
10
votes
1answer
2k views
Should I give each character its own VBO or should I batch them into a single VBO?
I'm making a 3D first person game. Should I give each character its own VBO or should I batch all characters into a single VBO? What are the pros/cons?
7
votes
1answer
2k views
Most efficient way to draw large number of the same objects, but with different transforms
I'd like to draw a large number (multiple thousands) of simple meshes (each maybe... a maximum of 50 triangles, but even that is a very large upper bound), all of which are exactly the same. As a ...
7
votes
2answers
2k views
OpenGL 2 and back vs 3 and forward: What are the key differences for 2D graphics?
OpenGL contexts before and after OpenGL 3.0 are rather different. So far I've really only worked with buffers on either side anyway, I do know the most notable difference is lack of Immediate Mode. ...
6
votes
1answer
1k views
How to implement translation, scale, rotation gizmos for manipulating 3D object's transforms?
I am in the process of developing a basic 3D editor. It uses OpenGL for rendering a 3D world. Right now my scene is just a few boxes of different sizes and I am at the stage where I want to be able to ...
6
votes
1answer
412 views
With what projection matrix should I render a portal to a texture?
I'm using OpenGL. I have problem with my engine's portal implementation. To create the first portal I do: create a virtual camera with the position of the second portal and the correct orientation ...
6
votes
1answer
5k views
Interleaving Arrays in OpenGL
In my pursuit to write code that matches todays OpenGL standards I have found that I am completely clueless about interleaving arrays. I've tried and debugged just about everywhere I can think of but ...
6
votes
1answer
6k views
GLSL if-else statement unexpected behaviour
This question is related to this other one I asked a few days ago. Because I have finally get to the bottom of the issue, I have rather preferred to open a new question with a more detailed ...
5
votes
3answers
7k views
Open Source Engine for RTS [closed]
I must write a cross-platform real-time-strategy game within 2-3 months. I want use C++ and OpenGL and am looking for an engine. The engine must be open source and work under both Linux and Windows. ...
4
votes
1answer
5k views
Combining rotation,scaling around a pivot with translation into a matrix
In short: I need to combine rotation (in the form of a quaternion), scaling around a pivot point along with translation into a transformation matrix. The long: I am trying to implement a proprietary ...
4
votes
2answers
8k views
How to draw a smooth circle in Android using OpenGL?
I am learning about OpenGL API on Android. I just drew a circle. Below is the code I used. public class MyGLBall { private int points=360; private float vertices[]={0.0f,0.0f,0.0f}; private ...
4
votes
2answers
4k views
How does one write to another process's OpenGL/DirectX context?
I want to write a short of chat client that display the messages in-game (OpenGL/DirectX), but I really don't know how to handle this. It is easy to write my client in my graphic context... but what ...
4
votes
2answers
7k views
View matrix in opengl
Sorry for my clumsy question. But I don't know where I am wrong at creating view matrix. I have the following code: createMatrix(vec4f(xAxis.x, xAxis.y, xAxis.z, dot(xAxis,eye)), vec4f( ...
3
votes
2answers
1k views
Checking if an object is inside bounds of an isometric chunk
How would I check if an object is inside the bounds of an isometric chunk? for example I have a player and I want to check if its inside the bounds of this isometric chunk. I draw the isometric ...
7
votes
1answer
4k views
How to invert background pixel's color
I'm writing a game and map editor using Java and jMonkeyEngine. In the map editor, I've got a brush done by wireframed sphere. My problem is: I want to make it visible everywhere, so I want to invert ...
6
votes
1answer
6k views
GLSL - Rewriting shaders from #330 to #130
I recently created a game (LD21) that uses a geometry shader to convert points into textured triangles/culling. Since I was under the impression that the support for #330 was widespread I only wrote ...
5
votes
2answers
1k views
OpenGL behaviour depending on the graphics card?
This is something that never happened to me before. I have an OpenGL code that uses GLSL shaders to texture a 3D model. The code involves a lot of GPU texture processing, blending, etc... I wanted to ...
5
votes
2answers
2k views
Should the modelview and projection matrices be calculated in the shader or on the CPU?
At minimum I would have a camera with rotation and world position; projections parameters such as angle of view and perspective vs. orthographic; and meshes with scale, angle, and world position. ...
5
votes
1answer
843 views
How do particle systems work?
I want to implement a particle system in my game, but I've never programmed a particle system and don't know where to start. I only want to display pixels (GL_POINTs) with different sizes in ...
4
votes
2answers
234 views
How do I separate physics from framerate?
Skyrim (Creation Engine / Gamebryo) is a prime example of a game that has its physics tied to the framerate for which it has been heavily criticized, because if you disable vsync / have a > 60 HZ ...
4
votes
2answers
9k views
OpenGL - Understanding the relationship between Model, View and World Matrix
I am having a bit of trouble understanding how these matrixes work and how to set them up in relation to one another to get a proper system running. In my understanding the Model Matrix is the matrix ...
4
votes
3answers
3k views
What method replaces GL_SELECT for box selection?
Last 2 weeks I started working on a box selection that selects shapes using GL_SELECT and I just got it working finally. When looking up resources online, there is a significant number of posts that ...
4
votes
1answer
3k views
Access vertex data stored in VBO in the shader
If I wanted to store extra data in a VBO for skinning (indices for indexing into an array of matrices of bones and floats for applying weights to those bones) How would I go about accessing that data ...
4
votes
2answers
6k views
Texture antialiasing?
In my Minecraft-clone style game, blocks are textured with a border that is lighter then the block color. See picture below: To achieve this effect without the textures being blurry I use this ...
4
votes
3answers
2k views
Question About An Implementation Of Parallax Scrolling In C++/SDL/OpenGL
I been working in a project with a team for a Software Engineering class and we think that using the parallax scrolling will help our game to look really nice but we are not really sure if our idea ...
4
votes
1answer
801 views
In an artillery game how do I mask out the part of the terrain that was hit
Let's say I want to make a really simple artillery game, something like Gorillas. I don't have any experience in games, just some basic understanding of OpenGL. I want to do this for fun and to learn ...
3
votes
1answer
2k views
How do I fit the camera frustum inside directional light space?
I'm trying to improve the coverage of a shadow map for a directional light. Currently, it works great if the camera is looking straight down. However, if the camera is close to the ground and looking ...
3
votes
1answer
6k views
How to implement a basic arcball camera in OpenGL with GLM
I only just started learning OpenGL and even things like vector maths etc a couple of days ago, so I am having a bit of trouble figuring out exactly what to do to implement an arcball camera system. ...
3
votes
1answer
1k views
OpenGL ES drop shadows for 2D sprites
I've got a an OpenGL scene rendered with a bunch of sprites, and I'd like to automagically add drop shadows to all of them. Here's a picture showing what I mean: The scene uses orthographic ...
2
votes
1answer
2k views
Pygame water ripple effect
I have Googled for it but there are no ready scripts - as opposed to the same effect on Flash. I have checked the algorithm on The Water Effect Explained and also tested an implementation of the ...
-1
votes
1answer
474 views
Detailed Modern Opengl Tutorial? [duplicate]
I am asking for a specific modern opengl tutorial. I need a tutorial that does not skip to explain any lines of code. It should also include different independent objects moving/rotating (most ...
-2
votes
1answer
463 views
What are some good resources for learning OpenGL on Android? [closed]
Mainly I learned how to develop Android applications, but now I want to know how to make high resolution games, so does someone have a good book or a video that teaches OpenGL?
11
votes
3answers
5k views
What is the difference between OpenGL 1.x and 2.x?
Is there a good tutorial that shows the difference between OpenGL 1.* and 2.*? It would be very helpful to know which functions I should not be calling (like glBegin(), I assume).
8
votes
2answers
2k views
How do I apply skeletal animation from a .x (Direct X) file?
Using the .x format to export a model from Blender, I can load a mesh, armature and animation. I have no problems generating the mesh and viewing models in game. Additionally, I have animations and ...
7
votes
2answers
238 views
Can applications using old versions of Opengl still run on newer cards?
OpenGl 3.0 and up has a quite big difference from the older versions like OpenGl 2.x and opengl 1.x in terms of implementation, does that mean applications which are written with the old versions of ...
7
votes
2answers
2k views
Getting the number of fragments which passed the depth test
In "modern" environments, the "NV Occlusion Query" extension provides a method to get the number of fragments which passed the depth test. However, on the iPad / iPhone using OpenGL ES, the extension ...
6
votes
1answer
1k views
exporting bind and keyframe bone poses from blender to use in OpenGL
EDIT: I decided to reformulate the question in much simpler terms to see if someone can give me a hand with this. Basically, I'm exporting meshes, skeletons and actions from blender into an engine ...
6
votes
3answers
1k views
Understanding how to create/use textures for games when limited by power of two sizes
I have some questions about the creating graphics for a game. As an example. I want to create a motorbike. (1pixel = 1centimeter) So my motorbike will have 200 width and 150 height. (200x150) But the ...
|
__label__pos
| 0.69241 |
4
$\begingroup$
I think there should be an easy way to accomplish my task but I have not found it yet. I would like Graphics3D to plot a simple sphere, radius $1$, centered on ${0,0,0}$. And, the plot should be without a box (easy to do) but with coordinate axis that are centered on the sphere itself. With Graphics3D those coordinate axis are outside of the sphere as if they were labeling 3 edges of the bounding box.
The surface of the sphere should be viewed as somewhat transparent where the axis inside the sphere can be viewed.
I would like guidance on how to go about this, thinking it must be a common need there must be a simple parameter that I have not yet found. I am sure that I could construct such a 3D image manually by drawing each axis but I am hoping to avoid that.
I admit to being an novice with Mathematica graphics and especially Graphics3D.
$\endgroup$
9
• 3
$\begingroup$ us e AxesOrigin -> {0, 0, 0}? $\endgroup$
– kglr
Jun 24 '18 at 19:47
• 2
$\begingroup$ And Boxed -> False? And Opacity[0.5] for the sphere? $\endgroup$ Jun 24 '18 at 20:06
• $\begingroup$ You missed Axes -> True ! $\endgroup$
– rhermans
Jun 24 '18 at 21:09
• 1
$\begingroup$ @K7PEH next time, instead of saying "easy to do", please show us the code you have, so we can know how far you have done yourself. The question itself, if you share what you have learned, could be good help for other users visiting the site. $\endgroup$
– rhermans
Jun 24 '18 at 21:13
• 1
$\begingroup$ @rhermans -- Actually, your answer was exactly the sort of thing I was looking for and in fact assumed to exist in Mathematica but I just didn't see it in my reading of the docs (as I explained above). If you re-read my question, you see that I mention "easy" and that "...there must be a parameter [to do this]". And, you showed me that very parameter, the very one I assume should exist, the very one I in fact did use already from your info. It fit my need. This is why I accepted your answer. Jens answer is interesting and probably useful but his extra work was what I wanted to avoid. $\endgroup$
– K7PEH
Jun 25 '18 at 14:51
5
$\begingroup$
The Graphics3D
Graphics3D[
{Opacity[0.5], Sphere[{0, 0, 0}]}
, AxesOrigin -> {0, 0, 0}
, Boxed -> False
, Axes -> True
, PlotRange -> {{-2, 2}, {-2, 2}, {-2, 2}}
]
Mathematica graphics
How to go about this.
A good starting point is to look at the documentation about Graphics3D, search this site, and look at the Options of the relevant functions.
Options[Graphics3D]
(* {AlignmentPoint -> Center, AspectRatio -> Automatic,
AutomaticImageSize -> False, Axes -> False, AxesEdge -> Automatic,
AxesLabel -> None, AxesOrigin -> Automatic, AxesStyle -> {},
Background -> None, BaselinePosition -> Automatic, BaseStyle -> {},
Boxed -> True, BoxRatios -> Automatic, BoxStyle -> {},
ClipPlanes -> None, ClipPlanesStyle -> Automatic,
ColorOutput -> Automatic, ContentSelectable -> Automatic,
ControllerLinking -> Automatic, ControllerMethod -> Automatic,
ControllerPath -> Automatic, CoordinatesToolOptions -> Automatic,
DisplayFunction :> $DisplayFunction, Epilog -> {}, FaceGrids -> None,
FaceGridsStyle -> {}, FormatType :> TraditionalForm,
ImageMargins -> 0., ImagePadding -> All, ImageSize -> Automatic,
ImageSizeRaw -> Automatic, LabelStyle -> {}, Lighting -> Automatic,
Method -> Automatic, PlotLabel -> None, PlotRange -> All,
PlotRangePadding -> Automatic, PlotRegion -> Automatic,
PreserveImageOptions -> Automatic, Prolog -> {},
RotationAction -> "Fit", SphericalRegion -> False,
Ticks -> Automatic, TicksStyle -> {}, TouchscreenAutoZoom -> False,
ViewAngle -> Automatic, ViewCenter -> Automatic,
ViewMatrix -> Automatic, ViewPoint -> {1.3, -2.4, 2.},
ViewProjection -> Automatic, ViewRange -> All,
ViewVector -> Automatic, ViewVertical -> {0, 0, 1}} *)
$\endgroup$
5
$\begingroup$
Even though an answer was already accepted, let me post how I like to make axes in 3D:
First, define a general 3D arrow, called arrowLine (it allows a more robust way of specifying the proportions of the shape, compared to the built-in Arrow command). See this answer. Then I combine three such arrows in the function arrowAxes to make a coordinate system:
Options[arrowLine] = {Thickness -> .1, "HeadScale" -> 3};
arrowLine[{p1_, p2_},
OptionsPattern[]] :=
(*p1 and p2 are 3D points. They are passed as a list*)
Module[{p3, scale2, norm, pyramidHeight = 3/2},
scale2 = OptionValue["HeadScale"]*OptionValue[Thickness];
norm = Norm[p2 - p1];
If[norm > scale2*pyramidHeight,
p3 = p1 + (p2 - p1)/norm (norm - scale2 pyramidHeight);
{EdgeForm[], Cylinder[{p1, p3}, OptionValue[Thickness]],
GeometricTransformation[
GraphicsComplex[{{0, 0, pyramidHeight}, {0, -1, 0}, {0, 1,
0}, {-1, 0, 0}, {1, 0, 0}},
Polygon[{{3, 4, 1}, {4, 2, 1}, {2, 5, 1}, {5, 3, 1}, {5, 2, 4,
3}}]], Composition[TranslationTransform[p3],
Quiet[RotationTransform[{{0, 0, 1},
p2 - p1}], {RotationMatrix::degen, RotationTransform::spln}],
ScalingTransform[scale2 {1, 1, 1}]]]}, {}]]
arrowAxes[forwardLength_, backwardLength_: 0] :=
Map[{Apply[RGBColor, #],
arrowLine[{-backwardLength #, forwardLength #},
Thickness -> .05]} &, IdentityMatrix[3]]
Now the 3D axes can be combined with a partially translucent sphere as follows:
Graphics3D[{{Opacity[.7], Orange, Sphere[]}, arrowAxes[3, 3]},
Boxed -> False, Lighting -> "Neutral", Background -> Gray]
Mathematica graphics
The translucent effect is created by Opacity and the axes are drawn by arrowAxes[3, 3]. Here, the first argument is the length of the arrows in the forward direction from the origin, and the second argument is the length in the reverse direction. You can omit the second argument to get axes that only extend in the forward direction (bordering the first octant).
$\endgroup$
1
• $\begingroup$ Thanks for the effort in your answer. I have copied your arrowAxes code to save for some other use I might have in the future. However, I do have to say that the AxesOrigin option parameter is exactly what I was looking for and hoping to find for my current need. But, I am already thinking of ways to use your code and more importantly to learn more skills in writing such things in Mathematica. $\endgroup$
– K7PEH
Jun 25 '18 at 15:04
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.882635 |
Kafka topic replication factor only 1 - how to increase?
639
0
07-11-2018 05:18 PM
LorenMueller
New Contributor III
I am attempting to set up a multi-machine GeoEvent system. Currently I only have two machines and hope to be getting a third online. The issue I am having is that there is no replication occurring, even though zookeeper sees both machines (screenshot below). The top cmd windows are from machine 01, and the bottom from machine 02.
screenshot
As you can see (or not see, that img might be too small) zookeeper is reporting that there are two machines ([1002, 1001]), yet the topic (one of many Outputs that I have) is not replicating to 1002. How can I get that replication factor to 2 as it should be?
Thanks for any help,
Loren
UPDATE:
Appears it is that one Output that is having an issue. Comparing to another Output that is replicating ok in screenshot below. I am going to try to recreate the Input/Output/Service trio in geoevent and see if this old one was just corrupt.
UPDATE:
So deleting and re-creating the Output now has the ReplicationFactor at 2 (as reported from both machines).
Still not sure why it was stuck at ReplicationFactor of 1 at first. Now going to check all of my input and outputs to make sure replication is occurring.
Loren
0 Kudos
0 Replies
|
__label__pos
| 0.737102 |
Token balances not showing in javascript dex project
hello everyone
im really truly frusted.
i followed the course exactly andi have coins in my metamask. but the code says my balance is blank nothing is showing in my dex
this is the code
// connect to Moralis server
const serverUrl = "https://hzgprsd3s1da.usemoralis.com:2053/server";
const appId = "YwMvfUyGm50mRIrKsXsWCwlkPjQxji5zCuVNP3xe";
Moralis.start({ serverUrl, appId });
Moralis.initPlugins().then(console.log('Plugins have been initialized'))
const $tokenBalanceTBody = document.querySelector(".js-token-balances");
const $selectedToken = document.querySelector('.js-from-token');
const $amountInput = document.querySelector('.js-from-amount')
//Converting from wei using custom function
const tokenValue = (value, decimals) => (decimals ? value / Math.pow(10, decimals): value);
// add from here down
async function login() {
let user = Moralis.User.current();
if (!user) {
user = await Moralis.authenticate({ signingMessage: "Log in using Moralis" })
.then(function(user) {
console.log("logged in user:", user);
console.log(user.get("ethAddress"));
})
.catch(function(error) {
console.log(error);
});
}
getStats()
}
async function getStats() {
await Moralis.enableWeb3();
const balances = await Moralis.Web3API.account.getTokenBalances({ chain: 'polygon' });
console.log(balances)
$tokenBalanceTBody.innerHTML = balances.map((token, index) => `
<tr>
<td>${index + 1}</td>
<td>${token.symbol}</td>
<td>${Moralis.Units.FromWei(token.balance, token.decimals)}</td>
<td>
<button
class="js-swap btn btn-success"
data-address="${token.token_address}"
data-symbol="${token.symbol}"
data-decimals="${token.decimals}"
data-max="${Moralis.Units.FromWei(token.balance, token.decimals)}"
>
Swap
</button>
</td>
</tr>
`).join('');
}
async function initSwapForm(event) {
event.preventDefault();
$selectedToken.innerText = event.target.dataset.symbol;
$selectedToken.dataset.address = event.target.dataset.address;
$selectedToken.dataset.decimals = event.target.dataset.decimals;
$selectedToken.dataset.max = event.target.dataset.max;
$amountInput.removeAttribute('disabled');
$amountInput.value = '';
document.querySelector('.js-submit').removeAttribute('disabled');
document.querySelector('.js-cancel').removeAttribute('disabled');
document.querySelector('.js-quote-container').innerHTML = '';
document.querySelector('.js-amount-error').innerText = ''
}
for ( let $btn of $tokenBalanceTBody.querySelectorAll('js-initSwapForm')) {
$btn.addEventListener('click',swap);
}
async function buyCrypto() {
Moralis.Plugins.fiat.buy()
}
async function logOut() {
await Moralis.User.logOut();
console.log("logged out");
}
document.querySelector("#btn-login").addEventListener('click', login)
document.getElementById("btn-buy-crypto").addEventListener('click', buyCrypto)
document.querySelector("#btn-logout").addEventListener('click', logOut)
/** Quote / Swap */
async function formSubmitted(event) {
event.preventDefault()
const fromAmount = Number.parseFloat($amountInput.value);
const fromMaxValue = Number.parseFloat($selectedToken.dataset.max);
if (Number.isNaN(fromAmount) || fromAmount > fromMaxValue) {
//invalid input
document.querySelector('.js-amount-error').innerText = 'Invalid Amount'
return
} else {
document.querySelector('.js-amount-error').innerText = ''
}
// submission of the quote request
const fromDecimals = $selectedToken.dataset.decimals;
const fromTokenAddress = $selectedToken.dataset.address;
const [toTokenAddress, toDecimals] = document.querySelector('[name=to-token]').value.split('-');
try {
const quote = await Moralis.Plugins.oneInch.quote({
chain: 'polygon', // The blockchain you want to use (eth/bsc/polygon)
fromTokenAddress, // The token you want to swap
toTokenAddress, // The token you want to receive
amount: Moralis.Units.Token(fromAmount, fromDecimals).toString(),
});
const toAmount = Moralis.Units.FromWei(quote.toTokenAmount, toDecimals)
document.querySelector('.js-quote-container').innerHTML = `
<p>
${fromAmount} ${quote.fromToken.symbol} = ${toAmount} ${quote.toToken.symbol}
</p>
<p> Gas fee: ${quote.estimatedGas} </p>
`;
} catch (e) {
document.querySelector('.js-quote-container').innerHTML = `
<p class="error">The conversion didn't succed.</p>
`;
}
}
async function formCanceled(event){
event.preventDefault()
document.querySelector('.js-submit').setAttribute('disabled', '');
document.querySelector('.js-cancel').setAttribute('disabled', '');
$amountInput.value = '';
$amountInput.setAttribute('disabled', '');
delete $selectedToken.dataset.address;
delete $selectedToken.dataset.decimals;
delete $selectedToken.dataset.max;
document.querySelector('.js-quote-container').innerHTML = '';
document.querySelector('.js-amount-error').innerText = ''
}
document.querySelector('.js-submit').addEventListener('click', formSubmitted)
document.querySelector('.js-cancel').addEventListener('click', formCanceled)
/** to token dropdown preparation */
async function getTop10Tokens() {
const response = await fetch('https://api.coinpaprika.com/v1/coins');
const tokens = await response.json();
return tokens
.filter(token => token.rank >= 1 && token.rank <= 10)
.map(token => token.symbol)
}
async function getTickerData(tickerList) {
const tokens = await Moralis.Plugins.oneInch.getSupportedTokens({
chain: 'polygon', // The blockchain you want to use (eth/bsc/polygon)
});
console.log(tokens)
const tokenList = Object.values(tokens.tokens);
return tokenList.filter(token => tickerList.includes(token.symbol))
}
function renderTokenDropDown(tokens) {
const options = tokens.map(token => `
<option value="${token.address}-${token.decimals}">
${token.name}
</option>
`).join('');
document.querySelector('[name=to-token]').innerHTML = options;
}
/* Check if user is connected, IF true, execute stats */
function isUserConnected() {
let user = Moralis.User.current();
if (user) {
getStats();
}
}
isUserConnected()
getTop10Tokens()
.then(getTickerData)
.then(renderTokenDropDown)
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="shortcut icon" href="#">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Moralis SDK code -->
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
<script src="https://unpkg.com/moralis/dist/moralis.js"></script>
<title>Moralis Dex </title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12 col-md-6">
<h1>MoralisSwap</h1>
</div>
<div class="col-12 col-md-6 d-flex align-items-center justify-content-md-center">
<button class="btn btn-success btn-sm" id="btn-login">Moralis login</button>
<button class="btn btn-success btn-sm" id="btn-buy-crypto">Buy Crypto</button>
<button class="btn btn-danger btn-sm" id="btn-logout">Logout</button>
</div>
</div>
<table class="table table-dark table-striped">
<thead>
<tr>
<th>#</th>
<th>Symbol</th>
<th>Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody class="js-token-balances"></tbody>
</table>
<form action="#" method="POST" class="exchange-form">
<div class="row">
<div class="col-12 col-md-6 mb-2">
<label>
<span class="js-from-token"></span>
Amount:
<input type="text" name="from-amount" class="js-from-amount" disabled>
</label>
<div class="js-amount-error error"></div>
</div>
<div class="col-12 col-md-6">
<label>
Swap to:
<select name="to-token"></select>
</label>
</div>
</div>
<div class="row">
<div class="col">
<button type="submit" class="js-submit btn btn-success btn-sm" disabled > Get Qoute</button>
<button class="js-cancel btn btn-warning btn-sm" disabled > Cancel</button>
</div>
<div class="js-qoute-container"></div>
</form>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="./dex.js"></script>
</body>
</html>
.error {
color: red;
}
body {
background-color: black;
color:whitesmoke;
}
.btn-sm {
margin: 10px
}
i followed the tutorial exactly and i even compared the final project code too mine and my balances arnt showing no matter what i do.
can anyone point out what im doing wrong"
2 Likes
Hey @Jeremiah, hope you are great.
I have just copy/paste your project and run it on my side, after login, it successfully get all the tokens i have with my address, are you sure that your address does have any token within it?
Carlos Z
hey can you share the code to your repository. i will have a look for you
ahahah @thecil to the rescue. your in good hands @Jeremiah
2 Likes
@thecil thank you for taking time too reply too me
i have eth in my wallet. i dont think this project can detect eth. im not really sure
this is my current github repository for this project
https://github.com/ghostoftheshell/moralis-crypto-dex-project
yes. ive also seen @thecil replies too alot of people. im supper grateful he replied. he has alot of knowledge
You are specifying to fetch your tokens from the polygon network, if you dont have any, the function will return an empty array.
await Moralis.Web3API.account.getTokenBalances({ chain: 'polygon' });
If you delete the option { chain: 'polygon' }, it will fetch the tokens from the ethereum network, and if your wallet have any, will return an array of them.
Carlos Z
const balances = await Moralis.Web3API.account.getTokenBalances({ chain: ‘’ });
is this the way too do it?
1 Like
no just dont pass in anything. so this const balances = await Moralis.Web3API.account.getTokenBalances();
1 Like
|
__label__pos
| 0.946688 |
0
I would like to do a progress bar for the time when the database synchronize. The request which counts the number of documents to synchronize is too long. I tried with the request GET _active_tasks on the couchdb database but it returns an empty json. I tried with the change event of the Pouchdb function replicate but the info variable doesn't display. Have you others technics for the progress bar or would you know how used the technics I have ever tried ?
1
I have not found a perfect solution, but one that seemed 'good enough' for us has been
1. get info about source db, to know what the 'end goal' is.
2. Add a 'changes' callback (like you mentioned in your answer), where you receive an info object with the last_seq that has been replicated. Divide this with the update_seq you got from the source, and update your progress bar.
~
Q.all(source.info())
.then(function(sourceInfo) {
var replication = source.replicate.to(target);
var startingpoint;
replication.on('change', function(info) {
// the first time we get a replication change,
// take the last_seq as starting point for the replication
// and calc fractions based on that
var fraction = 0;
if(typeof startingpoint === "undefined") {
startingpoint = info.last_seq;
} else {
fraction = (info.last_seq - startingpoint) / (sourceInfo.update_seq - startingpoint);
}
// Whatever you need to do to update ui here
updateUi(fraction);
});
})
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.982004 |
Mark All Google Tasks Complete at the end of the day
Greetings Makers! I am completely new to automation and am currently on the free plan so I can evaluate it. I have searched for google task automation in the Make.com help but cannot find what I am looking for.
I have a different set of tasks that I need to perform each day of the week. I created a single list of google tasks containing recurring tasks to generate the list for each day. I have this list of google tasks displayed on a monitor in my office. Currently today’s tasks and all past tasks are displaying (today, yesterday, 2 days ago, etc…) and it is bleeding into the information I have displayed below the task list.
I want to have Make monitor the google task list and automatically mark all open tasks as completed every day at 11:59pm so each day I only see tasks for “Today”. Is this possible? Where can I find how to do this?
I assume I would use the Google Tasks Modules for “Watch Tasks” and “Update Tasks” but I haven’t been able to figure out how to:
1. watch all tasks
2. set all open tasks to completed
3. do it on a schedule
Any help would be greatly appreciated!
Many Thanks!
1 Like
I found the schedule, and it looks like I can filter between the modules based on:
Condition “2. Status” Equal to “needsAction”
But the last module (Google Tasks - Update a Task" I am REALLY struggling with…
How do I get this to set all the open tasks to completed?
Am I on the right track?
Thanks in advance!
1 Like
HI @Juoquim
Thanks for reaching out to the community.
To solve your issue, you can configure the module “Update a Task” as shown below:
Best regards,
Msquare Automation
Gold Partner of Make
@Msquare_AutomationExplore our automation insights in our profile.
Thanks for the response @Msquare_Automation!
I was able to get it to complete 1 task. Then I changed the Task ID to a different task and saved it. It won’t complete the new task:
What am I missing?
Is it possible to use a wildcard, or what do I need to do to get it to close all open tasks? Am I going to need to have 20 “Update a Task” modules in order to process 20 tasks every day?
Thanks in advance!
Juoquim
Newbie to Automation
I’m abandoning this path as it appears that this will not work with recurring tasks. Each recurring task has a unique ID and pulling the Task ID (text name of the task) will not work on successive recurrences of the task.
|
__label__pos
| 0.934977 |
• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
Deployment SW
#1
[eluser]Unknown[/eluser]
Hi there,
first of all: Thy very much for taking time for me.
I'm writing a web based deployment website (based on codigniter) which allowes me to upload a file for one specific user. During the upload process a new record will be added into a db with the state 'pending'. Once the user access the download page the state of the entry in the db should change to 'deployed' and the file should be forced to download (by this awesome download-helper-function).
So: User access the download page
if the file is still pending, change it to deployed and download it.
if the file is already deployed, display an error.
My problem is, on the first time the user access the download-page, the db entry changes to 'deployed', he gets NO file but the error message.
Here's a part of my code:
Code:
<?php
$query = $this->db->query("
SELECT
d.state,
d.time_expire,
z.filename_real,
z.filename_mask,
z.encryption_key,
d.download_timestamp
FROM
tbl_deployments d
INNER JOIN
tbl_zip_files z
ON
(
z.id = d.id_zip_file
)
WHERE d.access_code = " . $this->db->escape($access_code));
$result = $query->result();
if(count($result) != 0)
{
if($result[0]->state == "pending")
{
$download_file = $result[0];
$this->db->query("UPDATE tbl_deployments SET state = 'deployed', download_timestamp = ".date("U")." WHERE access_code = '".$access_code."'");
force_download($download_file->filename_real,$this->encrypt->decrypt_file("./upload/".$download_file->filename_mask,"",$download_file->encryption_key,FALSE,TRUE));
} else {
echo "the file is not pending";
}
} else {
echo "wrong access code";
}
the user uses an access code to access his file. On upload i'm encrypting the file, so I have to decrypt it first
Thank you for all replies!
Pfammi
Digg Delicious Reddit Facebook Twitter StumbleUpon
Theme © 2014 iAndrew
Powered By MyBB, © 2002-2019 MyBB Group.
|
__label__pos
| 0.819457 |
Properties
Label 8.0.356265625.1
Degree $8$
Signature $[0, 4]$
Discriminant $5^{6}\cdot 151^{2}$
Root discriminant $11.72$
Ramified primes $5, 151$
Class number $1$
Class group Trivial
Galois Group $C_2^2:C_4$ (as 8T10)
Related objects
Downloads
Learn more about
Show commands for: Magma / SageMath / Pari/GP
magma: R<x> := PolynomialRing(Rationals()); K<a> := NumberField(R![121, 11, -61, -28, 29, 4, -4, -2, 1]);
sage: x = polygen(QQ); K.<a> = NumberField(x^8 - 2*x^7 - 4*x^6 + 4*x^5 + 29*x^4 - 28*x^3 - 61*x^2 + 11*x + 121)
gp: K = bnfinit(x^8 - 2*x^7 - 4*x^6 + 4*x^5 + 29*x^4 - 28*x^3 - 61*x^2 + 11*x + 121, 1)
Normalized defining polynomial
\(x^{8} \) \(\mathstrut -\mathstrut 2 x^{7} \) \(\mathstrut -\mathstrut 4 x^{6} \) \(\mathstrut +\mathstrut 4 x^{5} \) \(\mathstrut +\mathstrut 29 x^{4} \) \(\mathstrut -\mathstrut 28 x^{3} \) \(\mathstrut -\mathstrut 61 x^{2} \) \(\mathstrut +\mathstrut 11 x \) \(\mathstrut +\mathstrut 121 \)
magma: DefiningPolynomial(K);
sage: K.defining_polynomial()
gp: K.pol
Invariants
Degree: $8$
magma: Degree(K);
sage: K.degree()
gp: poldegree(K.pol)
Signature: $[0, 4]$
magma: Signature(K);
sage: K.signature()
gp: K.sign
Discriminant: \(356265625=5^{6}\cdot 151^{2}\)
magma: Discriminant(K);
sage: K.disc()
gp: K.disc
Root discriminant: $11.72$
magma: Abs(Discriminant(K))^(1/Degree(K));
sage: (K.disc().abs())^(1./K.degree())
gp: abs(K.disc)^(1/poldegree(K.pol))
Ramified primes: $5, 151$
magma: PrimeDivisors(Discriminant(K));
sage: K.disc().support()
gp: factor(abs(K.disc))[,1]~
This field is not Galois over $\Q$.
This is not a CM field.
Integral basis (with respect to field generator \(a\))
$1$, $a$, $a^{2}$, $a^{3}$, $a^{4}$, $a^{5}$, $\frac{1}{3} a^{6} + \frac{1}{3} a^{5} + \frac{1}{3} a^{4} + \frac{1}{3} a^{2} - \frac{1}{3} a + \frac{1}{3}$, $\frac{1}{74283} a^{7} - \frac{3737}{24761} a^{6} + \frac{8927}{24761} a^{5} - \frac{35383}{74283} a^{4} - \frac{13622}{74283} a^{3} - \frac{36878}{74283} a^{2} + \frac{30068}{74283} a + \frac{1321}{6753}$
magma: IntegralBasis(K);
sage: K.integral_basis()
gp: K.zk
Class group and class number
Trivial group, which has order $1$
magma: ClassGroup(K);
sage: K.class_group().invariants()
gp: K.clgp
Unit group
magma: UK, f := UnitGroup(K);
sage: UK = K.unit_group()
Rank: $3$
magma: UnitRank(K);
sage: UK.rank()
gp: K.fu
Torsion generator: \( -\frac{784}{74283} a^{7} - \frac{731}{74283} a^{6} + \frac{1024}{74283} a^{5} + \frac{7952}{74283} a^{4} - \frac{17104}{74283} a^{3} - \frac{2832}{24761} a^{2} - \frac{280}{24761} a + \frac{8800}{6753} \) (order $10$)
magma: K!f(TU.1) where TU,f is TorsionUnitGroup(K);
sage: UK.torsion_generator()
gp: K.tu[2]
Fundamental units: Units are too long to display, but can be downloaded with other data for this field from 'Stored data to gp' link to the right
magma: [K!f(g): g in Generators(UK)];
sage: UK.fundamental_units()
gp: K.fu
Regulator: \( 46.2094024438 \)
magma: Regulator(K);
sage: K.regulator()
gp: K.reg
Galois group
$C_2^2:C_4$ (as 8T10):
magma: GaloisGroup(K);
sage: K.galois_group(type='pari')
gp: polgalois(K.pol)
A solvable group of order 16
The 10 conjugacy class representatives for $C_2^2:C_4$
Character table for $C_2^2:C_4$
Intermediate fields
\(\Q(\sqrt{5}) \), \(\Q(\zeta_{5})\), 4.2.18875.1, 4.2.3775.1
Fields in the database are given up to isomorphism. Isomorphic intermediate fields are shown with their multiplicities.
Sibling fields
Galois closure: data not computed
Degree 8 sibling: data not computed
Frobenius cycle types
$p$ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
Cycle type ${\href{/LocalNumberField/2.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/3.4.0.1}{4} }^{2}$ R ${\href{/LocalNumberField/7.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/11.1.0.1}{1} }^{8}$ ${\href{/LocalNumberField/13.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/17.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/19.2.0.1}{2} }^{4}$ ${\href{/LocalNumberField/23.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/29.2.0.1}{2} }^{4}$ ${\href{/LocalNumberField/31.2.0.1}{2} }^{4}$ ${\href{/LocalNumberField/37.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/41.2.0.1}{2} }^{2}{,}\,{\href{/LocalNumberField/41.1.0.1}{1} }^{4}$ ${\href{/LocalNumberField/43.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/47.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/53.4.0.1}{4} }^{2}$ ${\href{/LocalNumberField/59.2.0.1}{2} }^{4}$
In the table, R denotes a ramified prime. Cycle lengths which are repeated in a cycle type are indicated by exponents.
magma: p := 7; // to obtain a list of $[e_i,f_i]$ for the factorization of the ideal $p\mathcal{O}_K$:
magma: idealfactors := Factorization(p*Integers(K)); // get the data
magma: [<primefactor[2], Valuation(Norm(primefactor[1]), p)> : primefactor in idealfactors];
sage: p = 7; # to obtain a list of $[e_i,f_i]$ for the factorization of the ideal $p\mathcal{O}_K$:
sage: [(e, pr.norm().valuation(p)) for pr,e in K.factor(p)]
gp: p = 7; \\ to obtain a list of $[e_i,f_i]$ for the factorization of the ideal $p\mathcal{O}_K$:
gp: idealfactors = idealprimedec(K, p); \\ get the data
gp: vector(length(idealfactors), j, [idealfactors[j][3], idealfactors[j][4]])
Local algebras for ramified primes
$p$LabelPolynomial $e$ $f$ $c$ Galois group Slope content
$5$5.8.6.1$x^{8} - 5 x^{4} + 400$$4$$2$$6$$C_4\times C_2$$[\ ]_{4}^{2}$
$151$151.2.1.1$x^{2} - 151$$2$$1$$1$$C_2$$[\ ]_{2}$
151.2.0.1$x^{2} - x + 12$$1$$2$$0$$C_2$$[\ ]^{2}$
151.2.0.1$x^{2} - x + 12$$1$$2$$0$$C_2$$[\ ]^{2}$
151.2.1.1$x^{2} - 151$$2$$1$$1$$C_2$$[\ ]_{2}$
|
__label__pos
| 0.996643 |
„Hallo Amigo! Jetzt möchte ich dir erzählen, wie Objekte erstellt werden.“
„Was ist daran so kompliziert, Onkel Ritschie? Man schreibt einfach new gefolgt vom Klassennamen, gibt den richtigen Konstruktor an und fertig!“
„Das stimmt. Aber was passiert innerhalb des Objekts, wenn du das tust?“
„Was passiert?“
„Das hier passiert: Das Objekt wird in mehreren Schritten erstellt.“
1) Zunächst wird Speicher für alle Member-Variablen der Klasse zugewiesen.
2) Dann wird die Basisklasse initialisiert.
3) Dann werden allen Variablen Werte zugewiesen, falls diese angegeben sind.
4) Schließlich wird der Konstruktor aufgerufen.
„Das sieht nicht sehr kompliziert aus: erst die Variablen, dann der Konstruktor.“
„Sehen wir uns mal an einem Beispiel mit zwei Klassen an, wie das funktioniert:“
Code Beschreibung
class Pet
{
int x = 5, y = 5; ←-
int weight = 10; ←-
Pet(int x, int y)
{
this.x = x; ←-
this.y = y; ←-
}
}
class Cat extends Pet
{
int tailLength = 8; ←-
int age;
Cat(int x, int y, int age)
{
super(x, y); ←-
this.age = age; ←-
}
}
Deklariere zwei Klassen: Pet(pet) und Cat(cat).
In der Cat-Klasse sehen wir einen expliziten Aufruf des Konstruktors der Basisklasse.
Er muss immer in der ersten Zeile des Konstruktors stehen.
Folgendes geschieht nach der Zuweisung des Speichers:
18 – Aufruf des Konstruktors der Basisklasse.
3, 4 – Variablen in Pet initialisieren.
8, 9 – Code im Pet-Konstruktor ausführen.
Dann beginnt die Initialisierung der Cat-Klasse.
14 – Variablen in Cat initialisieren.
19 – Code im Cat-Konstruktor ausführen.
public static void main(String[] args)
{
Cat cat = new Cat (50, 50, 5);
}
„Das ist ein etwas verwirrend. Warum ist das so kompliziert?“
„Es ist eigentlich nicht so schwierig, wenn man weiß, was wirklich passiert:“
Wenn eine Klasse keine Konstruktoren besitzt, wird automatisch einer erzeugt.
Standardkonstruktor
class Cat
{
int x = 5;
int y = 5;
}
class Cat
{
int x = 5;
int y = 5;
public Cat()
{
}
}
Wenn du den Basisklassenkonstruktor nicht aufrufst, wird er automatisch aufgerufen.
Aufruf des Konstruktors der Basisklasse
class Pet
{
public String name;
}
class Pet extends Object
{
public String name;
public Pet()
{
super();
}
}
class Cat extends Pet
{
int x = 5;
int y = 5;
}
class Cat extends Pet
{
int x = 5;
int y = 5;
public Cat()
{
super();
}
}
Member-Variablen werden im Konstruktor initialisiert.
Initialisierung von Member-Variablen
class Cat
{
int x = 5;
int y = 5;
}
class Cat
{
int x;
int y;
public Cat()
{
super();
this.x = 5;
this.y = 5;
}
}
Das passiert tatsächlich
class Pet
{
int x = 5, y = 5;
int weight = 10;
Pet(int x, int y)
{
this.x = x;
this.y = y;
}
}
class Cat extends Pet
{
int tailLength = 8;
int age;
Cat(int x, int y, int age)
{
super(x, y);
this.age = age;
}
}
class Pet extends Object
{
int x;
int y;
int weight;
Pet(int x, int y)
{
//call of the base class's constructor
super();
//initialize variables
this.x = 5;
this.y = 5;
this.weight = 10;
//execute the constructor code
this.x = x;
this.y = y;
}
}
class Cat extends Pet
{
int tailLength;
int age;
Cat(int x, int y, int age)
{
//call of the base class's constructor
super(x, y);
//initialize variables
this.tailLength = 8;
//execute the constructor code
this.age = age;
}
}
„Jetzt verstehe ich es besser: zuerst die Basisklasse, dann Variablen außerhalb des Konstruktors, dann der Konstruktorcode.“
„Sehr gut, Amigo! Das war‘s!“
|
__label__pos
| 0.996189 |
Manage Scheduled Tasks Via Cron in SiteWorx
How to: Update the Cron Variables
1. Click the Hosting Features menu item if it is not already open.
2. Click the Cron Jobs menu item.
3. Select the linux shell you’d like the cron jobs to be run on from the SHELL drop down.
4. Enter the paths you’d like to be in the search path for the cron jobs in the PATH field.
5. Enter the email address you’d like to receive all output from the cron jobs in the MAILTO field.
6. Click the button to submit your changes.
How to: Change the Cron Interface
1. Click the Hosting Features menu item if it is not already open.
2. Click the Cron Jobs menu item.
3. Select the desired interface from the Cron Editor drop down.
How to: Add a Cron Job
1. Click the Hosting Features menu item if it is not already open.
2. Click the Cron Jobs menu item.
3. Using the Simple Interface:
1. Choose the Minute, Hour, Day, Month and Day of Week that you’d like your cron job to run from the select Boxes.
4. Using the Advanced Interface:
1. Enter the Minute, Hour, Day, Month and Day of Week numerically in the fields beneath each column. Use the * symbol for All.
5. Enter the path or url to the script you’d like to run in the script box.
6. Click the button to add your Cron Job.
How to: Delete a Cron Job
1. Click the Hosting Features menu item if it is not already open.
2. Click the Cron Jobs menu item.
3. Check the box next to the Cron Job that you wish to delete
4. Select delete from the With Selected drop down.
How to: Edit a Cron Job
1. Click the Hosting Features menu item if it is not already open.
2. Click the Cron Jobs menu item.
3. Click the [ Edit ] link next to the cron job you’d like to edit.
4. Change the Minute, Hour, Day, Month, Day of Week and/or Script field.
5. Click the button to update the changes to the Cron Job.
Was this answer helpful?
Print this Article
Also Read
InterWorx Server Administrator FTP Guide
1.1 What is FTP? FTP, or File Transfer Protocol, is a standard network protocol used to...
Why my Firewall goes down every 5 minutes?
Ensure that Debug Mode is Disabled When debug mode is enabled, all firewall rules are...
How to Add / Edit / Delete Reseller Accounts?
NodeWorx Reseller accounts can be used to allow customers to create their own SiteWorx accounts....
How to Import Interworx Hosting Accounts?
Import a Single Account Import Through NodeWorx If you prefer to use the web interface, follow...
How to Install InterWorx Control Panel?
Login to your Linux server as root, via SSH or Terminal. Download and run the installer: sh...
|
__label__pos
| 0.986114 |
Unity - Scripting API: ExecuteInEditMode
Script language:
• JS
• C#
• Boo
Script language
Select your preferred scripting language. All code snippets will be displayed in this language.
ExecuteInEditMode
Namespace: UnityEngine
Description
Makes a script execute in edit mode.
By default, script components are only executed in play mode. By adding this attribute, each script component will also have its callback functions executed while the Editor is not in playmode.
The functions are not called constantly like they are in play mode.
- Update is only called when something in the scene changed.
- OnGUI is called when the Game View recieves an Event.
- OnRenderObject and the other rendering callback functions are called on every repaint of the Scene View or Game View.
// Make the script also execute in edit mode.
@script ExecuteInEditMode()
// Just a simple script that looks at the target transform. var target : Transform; function Update () { if (target) transform.LookAt(target); }
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ExampleClass : MonoBehaviour {
public Transform target;
void Update() {
if (target)
transform.LookAt(target);
}
}
import UnityEngine
import System.Collections
[ExecuteInEditMode]
public class ExampleClass(MonoBehaviour):
public target as Transform
def Update() as void:
if target:
transform.LookAt(target)
|
__label__pos
| 0.982362 |
Next lesson playing in 5 seconds
Cancel
• Overview
• Transcript
1.2 JavaScript Without jQuery
In this lesson, we’ll take some jQuery-enabled code and convert it to vanilla JavaScript step by step. We’ll look at several common parts of jQuery’s API, and I’ll show you how we can accomplish the same thing using the standard DOM and JavaScript ES6.
Code Snippets
For HTTP requests, we’ll use fetch:
fetch("data.json").then((response) => {
response.json().then((obj) => {
});
});
For selecting elements, we’ll use methods of the document object:
let doc = document;
doc.getElementById();
doc.querySelectorAll();
For manipulating an element’s CSS classes, we’ll use the classList object:
element.classList.add("my-class");
1.JavaScript Without jQuery
2 lessons, 12:42
1.1
Introduction
00:58
1.2
JavaScript Without jQuery
11:44
1.2 JavaScript Without jQuery
[SOUND] In order to demonstrate this idea of going from jQuery to just pure vanilla JavaScript, I thought that we could rewrite a jQuery enabled script. So, this is the page. There is a button that whenever you click, it's going to make an HTTP request to retrieve a JSON file. And inside of this JSON file is a title, and then the items that are displayed here. So, we are basically going to populate the content of this page. Now, if you'll notice whenever you load the content, the items fade in, so that's something that we also want to replicate as we are rewriting this code. Now, let's look at the HTML, it's very simple. We have our button element, and has an idea of container loader, and then there is this dev element with an idea of container inside of it is an H three element for the title. Then there is a UL element for our list of items. As far as jQuery is concerned, I'm using a CDN, just to keep things simple. And then script.JS is the file that we are going to be editing. Now, as far as CSS, there's just a font size set to make the fonts larger, so that you can see them easier on the screen. And then the UI element has a display of none, so that it will fade in. We will need to change the CSS because in order to make this element fade in, we're going to use CSS transitions, because that's how we do animation now. We don't do it with JavaScript. So, as far as the data is concerned, we have our title. We have our items, and that's basically it. So, here's the script. It's very simple, but it also uses a lot of the API that we would use on a daily basis. For example, we have set up click event a listener, we're using the Get JSON method to retrieve our JSON file. We're using the jQuery function to get elements in the DOM to find elements to set the HTML of elements, as well as appending to another element, then finally, the fade end. So, let's get started. And we'll start at the very top by changing the way that we set our event listener. So, we're going to be using standard methods. That means that we're going to use the document object. Document is quite a bit to type. So, I'm going to create a variable something called Doc, so that we can get to those methods much faster. So, instead of using the jQuery method, we're going to say Doc, and then get element by ID. Now, of course, this is more code, but our code is going to execute faster because, well, it's using the standard API. So, we are retrieving that elements. We want to call the addEventListener method, and we pass and click for the click event, and then we will use the existing function that we have now, except that now, our event object is not a jQuery event object that is going to be a standard Dom event object. Now, let's go ahead and save it. Let's go and look at the browser and make sure that that works. Of course it does, that wasn't a very big change. So now, let's talk about how we can make an http request. Now of course, there is the xml http request object that we could use, but, that's old school. Today, we have the new sexiness that's called fetch, now, all of the modern browsers support fetch. However, if you want to use fetch in older browsers, you have to use a poly fill. Which, in my book, is okay, actually, it's more than okay. Because it allows us to use new standard APIs in older browsers. And while it is technically a dependency, it's one that will eventually go away, and we won't have to rewrite any of our code, unless if the API changes, and we would have to update it, which we would have to do anyway. So, we're calling fetch, and that's going to return a promise. So instead of saying dumb, we're going to say then. And instead of getting the parsed JSON object, we get a response, because that makes sense. We are fetching data using an HTTP request. We are getting a response in return. And with that response, we can get a lot of information. One of those is the parsed JSON. So, we're going to call this JSON helper method, and this returns a promise. So we're going to say then. And we will have a callback, but the argument that's going to be passed to this callback is our parsed JSON object. So basically, we're going to take this code that we had, going to cut it and paste it inside of this callback, and everything should still work. So, let's just make sure, let's go the browser. Let's load content, everything's fine. So, now we want to retrieve our container, well, that's easy enough to do, we'll use the get element by ID method, but then we also want to find the UL element inside of the container. Now, we can do that with querySelector. Because some people, and maybe a lot of people don't fully know that you can use the querySelector method and the query selector all method on element objects in order to search within that element. So, it's exactly like the find, except that it's native, and it's going to execute faster. So, we are retrieving that ul elements, we're going to do the same thing for the h3 element. But instead of calling this nonexistent HTML method, we're going to say innerHTML = the title on our object. And so, next, we want to iterate over our items, which we are already doing, but we want to create an li element. Now, here's where things become less than desirable, because there's no great way to take a string of HTML and say, hey, give me HTML from the string. I mean, yes, we can do it. We can use DOM parser. We can also create an element, set the inner HTML, and then get that HTML, but, those aren't really good solutions. I would like something native so that we can say give me HTML from the string, get it back. But, until that day, we're just going to have to do things. I'm not gonna say the hard way, but the less than ideal way. So, we are going to create an element, that is an LI element, and we are going to set its inner HTML equal to the item, because our item's array is simply an array of strings. So, each item is going to be the string data itself, and then we want to append that LI element to the UL element. So, that's it. Let's go ahead and comment out this call to fade in. And whenever we go to the browser, we click on Load Content, but we don't see anything. Why is that? So, , we have , that's because the CSS, it is hidden. So, yeah, never mind that little faux pas, everything's there. So let's go ahead and modify our CSS. Instead of setting the display property to none, we're going to use opacity. So, opacity, in this case, is going to default to 0. And then let's add a class called fade-in. And we will say opacity is going to be 1, and we will set a transition for opacity. And as far as the time, let's do 500 milliseconds. So, inside of our script, we are going to add that class to the UL element. We're going to do so with the class list property. Going to call the add method, and that is called fade in. So, whenever we go back to the browser, let's close that, we should see that fade in. It doesn't. So, let's inspect once again. Well, at least items are being added. Let's look at the CSS. And the opacity of one is being overridden. So, let's just take the easy way, and let's say, important. So now we'll go back, refresh, and that fades in. So we have, essentially, replicated that jQuery code using standards compliant code. And it is a little bit extra to type, but in the grand scheme of things, it really wasn't. Now, just for kicks, let's do this, let's add another class. We're going to say color-red where we are going to set the color to red, naturally, and let's select all of those LI elements and add that class to them. Now, of course, the best thing to do would be inside of this for each loop, but I don't want to do that because I want to illustrate this. So, we are going to select container ul li. We're going to call the add class method color-red, and if we look at this in the browser, we are going to see those items are now red. So, now let's change this to standards code. So, instead of calling the jQuery function, we're going to use queries selector all. We're going to use that same selector. And instead, we're going to have to iterate over the result sets from calling queries selector all. So we're going to use for each, our callback will have elements, and then index. And then inside of this callback, we will say element class list add, and then color red. So, we will get the same results with just a little bit of extra code. Now, this is one of the things that I've never truly liked about jQuery is that a lot of the methods are iterative, it takes whatever elements you have selected with the jQuery function, or with the find method. And it iterates over all of those elements. Now, I understand the reasoning behind that. But people didn't fully understand what was going on behind the scenes. So, people were actually iterating multiple times over the same elements. When really, they didn't need to, so, here, having an explicit for each is nice, because we know that we are iterating here. And there's no extra iteration, there's no chance of iterating over the same elements, unless if we perform the query selector all again. So, as far as clarity is concerned, I much prefer this, even though it does require extra code. So, with Vanilla JavaScript, you can do anything that you could with jQuery. Now, it might require a little bit of extra code, but the trade off is faster execution, as well as no dependencies, and that's a fair trade in my book.
Back to the top
|
__label__pos
| 0.985136 |
blob: 5bcff485be3591f26c0a9dc1d00bedc5151d52de [file] [log] [blame]
#
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.12 FATAL_ERROR)
#
PROJECT(libarchive C)
#
SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/build/cmake")
if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${libarchive_BINARY_DIR}/bin)
endif()
#
# Set the Build type for make based generators.
# You can choose following types:
# Debug : Debug build
# Release : Release build
# RelWithDebInfo : Release build with Debug Info
# MinSizeRel : Release Min Size build
IF(NOT CMAKE_BUILD_TYPE)
SET(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Build Type" FORCE)
ENDIF(NOT CMAKE_BUILD_TYPE)
# Set a value type to properly display CMAKE_BUILD_TYPE on GUI if the
# value type is "UNINITIALIZED".
GET_PROPERTY(cached_type CACHE CMAKE_BUILD_TYPE PROPERTY TYPE)
IF("${cached_type}" STREQUAL "UNINITIALIZED")
SET(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING "Build Type" FORCE)
ENDIF("${cached_type}" STREQUAL "UNINITIALIZED")
# Check the Build Type.
IF(NOT "${CMAKE_BUILD_TYPE}"
MATCHES "^(Debug|Release|RelWithDebInfo|MinSizeRel)\$")
MESSAGE(FATAL_ERROR
"Unknown keyword for CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}\n"
"Acceptable keywords: Debug,Release,RelWithDebInfo,MinSizeRel")
ENDIF(NOT "${CMAKE_BUILD_TYPE}"
MATCHES "^(Debug|Release|RelWithDebInfo|MinSizeRel)\$")
# On MacOS, prefer MacPorts libraries to system libraries.
# I haven't come up with a compelling argument for this to be conditional.
list(APPEND CMAKE_PREFIX_PATH /opt/local)
# Enable @rpath in the install name.
# detail in "cmake --help-policy CMP0042"
SET(CMAKE_MACOSX_RPATH ON)
#
# Version - read from 'version' file.
#
FILE(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/build/version _version)
STRING(REGEX REPLACE
"^([0-9])[0-9][0-9][0-9][0-9][0-9][0-9][a-z]*$" "\\1" _major ${_version})
STRING(REGEX REPLACE
"^[0-9]([0-9][0-9][0-9])[0-9][0-9][0-9][a-z]*$" "\\1" _minor ${_version})
STRING(REGEX REPLACE
"^[0-9][0-9][0-9][0-9]([0-9][0-9][0-9])[a-z]*$" "\\1" _revision ${_version})
STRING(REGEX REPLACE
"^[0-9][0-9][0-9][0-9][0-9][0-9][0-9]([a-z]*)$" "\\1" _quality ${_version})
SET(_version_number ${_major}${_minor}${_revision})
STRING(REGEX REPLACE "[0]*([^0]*[0-9])$" "\\1" _trimmed_minor ${_minor})
STRING(REGEX REPLACE "[0]*([^0]*[0-9])$" "\\1" _trimmed_revision ${_revision})
#
SET(VERSION "${_major}.${_trimmed_minor}.${_trimmed_revision}${_quality}")
SET(BSDCPIO_VERSION_STRING "${VERSION}")
SET(BSDTAR_VERSION_STRING "${VERSION}")
SET(BSDCAT_VERSION_STRING "${VERSION}")
SET(LIBARCHIVE_VERSION_NUMBER "${_version_number}")
SET(LIBARCHIVE_VERSION_STRING "${VERSION}")
# INTERFACE_VERSION increments with every release
# libarchive 2.7 == interface version 9 = 2 + 7
# libarchive 2.8 == interface version 10 = 2 + 8
# libarchive 2.9 == interface version 11 = 2 + 9
# libarchive 3.0 == interface version 12
# libarchive 3.1 == interface version 13
math(EXPR INTERFACE_VERSION "13 + ${_minor}")
# Set SOVERSION == Interface version
# ?? Should there be more here ??
SET(SOVERSION "${INTERFACE_VERSION}")
# Enalbe CMAKE_PUSH_CHECK_STATE() and CMAKE_POP_CHECK_STATE() macros
# saving and restoring the state of the variables.
INCLUDE(CMakePushCheckState)
# Initialize the state of the variables. This initialization is not
# necessary but this shows you what value the variables initially have.
SET(CMAKE_REQUIRED_DEFINITIONS)
SET(CMAKE_REQUIRED_INCLUDES)
SET(CMAKE_REQUIRED_LIBRARIES)
SET(CMAKE_REQUIRED_FLAGS)
# Especially for early development, we want to be a little
# aggressive about diagnosing build problems; this can get
# relaxed somewhat in final shipping versions.
IF (CMAKE_C_COMPILER_ID MATCHES "^GNU$")
SET(CMAKE_REQUIRED_FLAGS "-Wall -Wformat -Wformat-security")
#################################################################
# Set compile flags for all build types.
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wformat -Wformat-security")
#################################################################
# Set compile flags for debug build.
# This is added into CMAKE_C_FLAGS when CMAKE_BUILD_TYPE is "Debug"
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Werror")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wextra")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wunused")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wshadow")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wmissing-prototypes")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wcast-qual")
ENDIF (CMAKE_C_COMPILER_ID MATCHES "^GNU$")
IF (CMAKE_C_COMPILER_ID MATCHES "^Clang$")
SET(CMAKE_REQUIRED_FLAGS "-Wall -Wformat -Wformat-security")
#################################################################
# Set compile flags for all build types.
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wformat -Wformat-security")
#################################################################
# Set compile flags for debug build.
# This is added into CMAKE_C_FLAGS when CMAKE_BUILD_TYPE is "Debug"
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Werror")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wextra")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wunused")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wshadow")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wmissing-prototypes")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wcast-qual")
ENDIF (CMAKE_C_COMPILER_ID MATCHES "^Clang$")
IF (CMAKE_C_COMPILER_ID MATCHES "^XL$")
SET(CMAKE_C_COMPILER "xlc_r")
SET(CMAKE_REQUIRED_FLAGS "-qflag=e:e -qformat=sec")
#################################################################
# Set compile flags for all build types.
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -qflag=e:e -qformat=sec")
#################################################################
# Set compile flags for debug build.
# This is added into CMAKE_C_FLAGS when CMAKE_BUILD_TYPE is "Debug"
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -qhalt=w")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -qflag=w:w")
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -qinfo=pro:use")
ENDIF(CMAKE_C_COMPILER_ID MATCHES "^XL$")
IF (MSVC)
#################################################################
# Set compile flags for debug build.
# This is added into CMAKE_C_FLAGS when CMAKE_BUILD_TYPE is "Debug"
# Enable level 4 C4061: The enumerate has no associated handler in a switch
# statement.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4061")
# Enable level 4 C4254: A larger bit field was assigned to a smaller bit
# field.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4254")
# Enable level 4 C4295: An array was initialized but the last character in
# the array is not a null; accessing the array may
# produce unexpected results.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4295")
# Enable level 4 C4296: An unsigned variable was used in a comparison
# operation with zero.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4296")
# Enable level 4 C4389: An operation involved signed and unsigned variables.
# This could result in a loss of data.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4389")
# Enable level 4 C4505: The given function is local and not referenced in
# the body of the module; therefore, the function is
# dead code.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4505")
# Enable level 4 C4514: The optimizer removed an inline function that is not
# called.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4514")
# Enable level 4 C4702: Unreachable code.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4702")
# Enable level 4 C4706: The test value in a conditional expression was the
# result of an assignment.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /we4706")
# /WX option is the same as gcc's -Werror option.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /WX")
# /Oi option enables built-in functions.
SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /Oi")
#################################################################
# Set compile flags for release build.
SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /Oi")
ENDIF (MSVC)
# Enable CTest/CDash support
include(CTest)
OPTION(ENABLE_NETTLE "Enable use of Nettle" ON)
OPTION(ENABLE_OPENSSL "Enable use of OpenSSL" ON)
OPTION(ENABLE_LZO "Enable the use of the system LZO library if found" OFF)
OPTION(ENABLE_LZMA "Enable the use of the system LZMA library if found" ON)
OPTION(ENABLE_ZLIB "Enable the use of the system ZLIB library if found" ON)
OPTION(ENABLE_BZip2 "Enable the use of the system BZip2 library if found" ON)
OPTION(ENABLE_LIBXML2 "Enable the use of the system libxml2 library if found" ON)
OPTION(ENABLE_EXPAT "Enable the use of the system EXPAT library if found" ON)
OPTION(ENABLE_PCREPOSIX "Enable the use of the system PCREPOSIX library if found" ON)
OPTION(ENABLE_LibGCC "Enable the use of the system LibGCC library if found" ON)
# CNG is used for encrypt/decrypt Zip archives on Windows.
OPTION(ENABLE_CNG "Enable the use of CNG(Crypto Next Generation)" ON)
OPTION(ENABLE_TAR "Enable tar building" ON)
OPTION(ENABLE_TAR_SHARED "Enable dynamic build of tar" FALSE)
OPTION(ENABLE_CPIO "Enable cpio building" ON)
OPTION(ENABLE_CPIO_SHARED "Enable dynamic build of cpio" FALSE)
OPTION(ENABLE_CAT "Enable cat building" ON)
OPTION(ENABLE_CAT_SHARED "Enable dynamic build of cat" FALSE)
OPTION(ENABLE_XATTR "Enable extended attribute support" ON)
OPTION(ENABLE_ACL "Enable ACL support" ON)
OPTION(ENABLE_ICONV "Enable iconv support" ON)
OPTION(ENABLE_TEST "Enable unit and regression tests" ON)
OPTION(ENABLE_COVERAGE "Enable code coverage (GCC only, automatically sets ENABLE_TEST to ON)" FALSE)
OPTION(ENABLE_INSTALL "Enable installing of libraries" ON)
SET(POSIX_REGEX_LIB "AUTO" CACHE STRING "Choose what library should provide POSIX regular expression support")
SET(ENABLE_SAFESEH "AUTO" CACHE STRING "Enable use of /SAFESEH linker flag (MSVC only)")
SET(WINDOWS_VERSION "WIN7" CACHE STRING "Set Windows version to use (Windows only)")
IF(ENABLE_COVERAGE)
include(LibarchiveCodeCoverage)
ENDIF(ENABLE_COVERAGE)
IF(ENABLE_TEST)
ENABLE_TESTING()
ENDIF(ENABLE_TEST)
IF(WIN32)
IF(WINDOWS_VERSION STREQUAL "WIN8")
SET(NTDDI_VERSION 0x06020000)
SET(_WIN32_WINNT 0x0602)
SET(WINVER 0x0602)
ELSEIF(WINDOWS_VERSION STREQUAL "WIN7")
SET(NTDDI_VERSION 0x06010000)
SET(_WIN32_WINNT 0x0601)
SET(WINVER 0x0601)
ELSEIF(WINDOWS_VERSION STREQUAL "WS08")
SET(NTDDI_VERSION 0x06000100)
SET(_WIN32_WINNT 0x0600)
SET(WINVER 0x0600)
ELSEIF(WINDOWS_VERSION STREQUAL "VISTA")
SET(NTDDI_VERSION 0x06000000)
SET(_WIN32_WINNT 0x0600)
SET(WINVER 0x0600)
ELSEIF(WINDOWS_VERSION STREQUAL "WS03")
SET(NTDDI_VERSION 0x05020000)
SET(_WIN32_WINNT 0x0502)
SET(WINVER 0x0502)
ELSEIF(WINDOWS_VERSION STREQUAL "WINXP")
SET(NTDDI_VERSION 0x05010000)
SET(_WIN32_WINNT 0x0501)
SET(WINVER 0x0501)
ELSE(WINDOWS_VERSION STREQUAL "WIN8")
# Default to Windows Server 2003 API if we don't recognize the specifier
SET(NTDDI_VERSION 0x05020000)
SET(_WIN32_WINNT 0x0502)
SET(WINVER 0x0502)
ENDIF(WINDOWS_VERSION STREQUAL "WIN8")
ENDIF(WIN32)
IF(MSVC)
IF(ENABLE_SAFESEH STREQUAL "YES")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH")
SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SAFESEH")
SET(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /SAFESEH")
SET(ENV{LDFLAGS} "$ENV{LDFLAGS} /SAFESEH")
ELSEIF(ENABLE_SAFESEH STREQUAL "NO")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO")
SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /SAFESEH:NO")
SET(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /SAFESEH:NO")
SET(ENV{LDFLAGS} "$ENV{LDFLAGS} /SAFESEH:NO")
ENDIF(ENABLE_SAFESEH STREQUAL "YES")
ENDIF(MSVC)
IF("${CMAKE_C_PLATFORM_ID}" MATCHES "^(HP-UX)$")
ADD_DEFINITIONS(-D_XOPEN_SOURCE=500) # Ask wchar.h for mbstate_t
ENDIF()
#
INCLUDE(CheckCSourceCompiles)
INCLUDE(CheckCSourceRuns)
INCLUDE(CheckFileOffsetBits)
INCLUDE(CheckFuncs)
INCLUDE(CheckHeaderDirent)
INCLUDE(CheckIncludeFile)
INCLUDE(CheckIncludeFiles)
INCLUDE(CheckLibraryExists)
INCLUDE(CheckStructHasMember)
INCLUDE(CheckSymbolExists)
INCLUDE(CheckTypeExists)
INCLUDE(CheckTypeSize)
#
# Generate list.h
#
MACRO (GENERATE_LIST_H _listfile _cmlist __list_sources)
SET(_argv ${ARGV})
# Remove _listfile and _cmlist from _argv
LIST(REMOVE_AT _argv 0 1)
IF (NOT EXISTS "${_listfile}" OR
${_cmlist} IS_NEWER_THAN "${_listfile}")
MESSAGE(STATUS "Generating ${_listfile}")
FILE(WRITE ${_listfile} "")
FOREACH (testfile ${_argv})
IF (testfile MATCHES "^test_[^/]+[.]c$")
FILE(STRINGS ${testfile} testvar REGEX "^DEFINE_TEST")
FOREACH (deftest ${testvar})
FILE(APPEND ${_listfile} "${deftest}\n")
ENDFOREACH (deftest)
ENDIF (testfile MATCHES "^test_[^/]+[.]c$")
ENDFOREACH (testfile)
ENDIF (NOT EXISTS "${_listfile}" OR
${_cmlist} IS_NEWER_THAN "${_listfile}")
ENDMACRO (GENERATE_LIST_H)
#
# Generate installation rules for man pages.
#
MACRO (INSTALL_MAN __mans)
FOREACH (_man ${ARGV})
STRING(REGEX REPLACE "^.+[.]([1-9])" "\\1" _mansect ${_man})
INSTALL(FILES ${_man} DESTINATION "share/man/man${_mansect}")
ENDFOREACH (_man)
ENDMACRO (INSTALL_MAN __mans)
#
# Find out what macro is needed to use libraries on Windows.
#
MACRO (TRY_MACRO_FOR_LIBRARY INCLUDES LIBRARIES
TRY_TYPE SAMPLE_SOURCE MACRO_LIST)
IF(WIN32 AND NOT CYGWIN)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
SET(CMAKE_REQUIRED_INCLUDES ${INCLUDES})
SET(CMAKE_REQUIRED_LIBRARIES ${LIBRARIES})
FOREACH(VAR ${MACRO_LIST})
# Clear ${VAR} from CACHE If the libraries which ${VAR} was
# checked with are changed.
SET(VAR_WITH_LIB "${VAR}_WITH_LIB")
GET_PROPERTY(PREV_VAR_WITH_LIB VARIABLE PROPERTY ${VAR_WITH_LIB})
IF(NOT "${PREV_VAR_WITH_LIB}" STREQUAL "${LIBRARIES}")
UNSET(${VAR} CACHE)
ENDIF(NOT "${PREV_VAR_WITH_LIB}" STREQUAL "${LIBRARIES}")
# Check if the library can be used with the macro.
IF("${TRY_TYPE}" MATCHES "COMPILES")
CHECK_C_SOURCE_COMPILES("${SAMPLE_SOURCE}" ${VAR})
ELSEIF("${TRY_TYPE}" MATCHES "RUNS")
CHECK_C_SOURCE_RUNS("${SAMPLE_SOURCE}" ${VAR})
ELSE("${TRY_TYPE}" MATCHES "COMPILES")
MESSAGE(FATAL_ERROR "UNKNOWN KEYWORD \"${TRY_TYPE}\" FOR TRY_TYPE")
ENDIF("${TRY_TYPE}" MATCHES "COMPILES")
# Save the libraries which ${VAR} is checked with.
SET(${VAR_WITH_LIB} "${LIBRARIES}" CACHE INTERNAL
"Macro ${VAR} is checked with")
ENDFOREACH(VAR)
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
ENDIF(WIN32 AND NOT CYGWIN)
ENDMACRO (TRY_MACRO_FOR_LIBRARY)
#
# Check compress/decompress libraries
#
IF(WIN32 AND NOT CMAKE_CL_64 AND NOT CYGWIN)
# GnuWin32 is only for Win32, not Win64.
SET(__GNUWIN32PATH "C:/Program Files/GnuWin32")
ENDIF(WIN32 AND NOT CMAKE_CL_64 AND NOT CYGWIN)
IF(DEFINED __GNUWIN32PATH AND EXISTS "${__GNUWIN32PATH}")
# You have to add a path availabel DLL file into PATH environment variable.
# Maybe DLL path is "C:/Program Files/GnuWin32/bin".
# The zlib and the bzip2 Setup program have installed programs and DLLs into
# "C:/Program Files/GnuWin32" by default.
# This is convenience setting for Windows.
SET(CMAKE_PREFIX_PATH ${__GNUWIN32PATH} $(CMAKE_PREFIX_PATH))
#
# If you didn't use Setup program or installed into nonstandard path,
# cmake cannot find out your zlib or bzip2 libraries and include files,
# you should execute cmake with -DCMAKE_PREFIX_PATH option.
# e.g.
# cmake -DCMAKE_PREFIX_PATH=<your-GnuWin32-path> <path-to-source>
#
# If compiling error occurred in zconf.h, You may need patch to zconf.h.
#--- zconf.h.orig 2005-07-21 00:40:26.000000000
#+++ zconf.h 2009-01-19 11:39:10.093750000
#@@ -286,7 +286,7 @@
#
# #if 1 /* HAVE_UNISTD_H -- this line is updated by ./configure */
# # include <sys/types.h> /* for off_t */
#-# include <unistd.h> /* for SEEK_* and off_t */
#+# include <stdio.h> /* for SEEK_* and off_t */
# # ifdef VMS
# # include <unixio.h> /* for off_t */
# # endif
ENDIF(DEFINED __GNUWIN32PATH AND EXISTS "${__GNUWIN32PATH}")
SET(ADDITIONAL_LIBS "")
#
# Find ZLIB
#
IF(ENABLE_ZLIB)
FIND_PACKAGE(ZLIB)
ELSE()
SET(ZLIB_FOUND FALSE) # Override cached value
ENDIF()
IF(ZLIB_FOUND)
SET(HAVE_LIBZ 1)
SET(HAVE_ZLIB_H 1)
INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${ZLIB_LIBRARIES})
IF(WIN32 AND NOT CYGWIN)
#
# Test if ZLIB_WINAPI macro is needed to use.
#
TRY_MACRO_FOR_LIBRARY(
"${ZLIB_INCLUDE_DIR}" "${ZLIB_LIBRARIES}"
RUNS
"#include <zlib.h>\nint main() {uLong f = zlibCompileFlags(); return (f&(1U<<10))?0:-1; }"
ZLIB_WINAPI)
IF(ZLIB_WINAPI)
ADD_DEFINITIONS(-DZLIB_WINAPI)
ELSE(ZLIB_WINAPI)
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${ZLIB_INCLUDE_DIR}" "${ZLIB_LIBRARIES}"
COMPILES
"#include <zlib.h>\nint main() {return zlibVersion()?1:0; }"
"ZLIB_DLL;WITHOUT_ZLIB_DLL")
IF(ZLIB_DLL)
ADD_DEFINITIONS(-DZLIB_DLL)
ENDIF(ZLIB_DLL)
ENDIF(ZLIB_WINAPI)
ENDIF(WIN32 AND NOT CYGWIN)
ENDIF(ZLIB_FOUND)
MARK_AS_ADVANCED(CLEAR ZLIB_INCLUDE_DIR)
MARK_AS_ADVANCED(CLEAR ZLIB_LIBRARY)
#
# Find BZip2
#
IF(ENABLE_BZip2)
FIND_PACKAGE(BZip2)
ELSE()
SET(BZIP2_FOUND FALSE) # Override cached value
ENDIF()
IF(BZIP2_FOUND)
SET(HAVE_LIBBZ2 1)
SET(HAVE_BZLIB_H 1)
INCLUDE_DIRECTORIES(${BZIP2_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${BZIP2_LIBRARIES})
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${BZIP2_INCLUDE_DIR}" "${BZIP2_LIBRARIES}"
COMPILES
"#include <bzlib.h>\nint main() {return BZ2_bzlibVersion()?1:0; }"
"USE_BZIP2_DLL;USE_BZIP2_STATIC")
IF(USE_BZIP2_DLL)
ADD_DEFINITIONS(-DUSE_BZIP2_DLL)
ELSEIF(USE_BZIP2_STATIC)
ADD_DEFINITIONS(-DUSE_BZIP2_STATIC)
ENDIF(USE_BZIP2_DLL)
ENDIF(BZIP2_FOUND)
MARK_AS_ADVANCED(CLEAR BZIP2_INCLUDE_DIR)
MARK_AS_ADVANCED(CLEAR BZIP2_LIBRARIES)
#
# Find LZMA
#
IF(ENABLE_LZMA)
FIND_PACKAGE(LibLZMA)
ELSE()
SET(LIBZMA_FOUND FALSE) # Override cached value
ENDIF()
IF(LIBLZMA_FOUND)
SET(HAVE_LIBLZMA 1)
SET(HAVE_LZMA_H 1)
SET(CMAKE_REQUIRED_INCLUDES ${LIBLZMA_INCLUDE_DIR})
SET(CMAKE_REQUIRED_LIBRARIES ${LIBLZMA_LIBRARIES})
INCLUDE_DIRECTORIES(${LIBLZMA_INCLUDE_DIRS})
LIST(APPEND ADDITIONAL_LIBS ${LIBLZMA_LIBRARIES})
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${LIBLZMA_INCLUDE_DIRS}" "${LIBLZMA_LIBRARIES}"
COMPILES
"#include <lzma.h>\nint main() {return (int)lzma_version_number(); }"
"WITHOUT_LZMA_API_STATIC;LZMA_API_STATIC")
IF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
ADD_DEFINITIONS(-DLZMA_API_STATIC)
ENDIF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
ELSE(LIBLZMA_FOUND)
# LZMA not found and will not be used.
ENDIF(LIBLZMA_FOUND)
#
# Find LZO2
#
IF(ENABLE_LZO)
IF (LZO2_INCLUDE_DIR)
# Already in cache, be silent
SET(LZO2_FIND_QUIETLY TRUE)
ENDIF (LZO2_INCLUDE_DIR)
FIND_PATH(LZO2_INCLUDE_DIR lzo/lzoconf.h)
FIND_LIBRARY(LZO2_LIBRARY NAMES lzo2 liblzo2)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LZO2 DEFAULT_MSG LZO2_LIBRARY LZO2_INCLUDE_DIR)
ELSE(ENABLE_LZO)
SET(LIBZMA_FOUND FALSE) # Override cached value
ENDIF(ENABLE_LZO)
IF(LZO2_FOUND)
SET(HAVE_LIBLZO2 1)
SET(HAVE_LZO_LZOCONF_H 1)
SET(HAVE_LZO_LZO1X_H 1)
INCLUDE_DIRECTORIES(${LZO2_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${LZO2_LIBRARY})
#
# TODO: test for static library.
#
ENDIF(LZO2_FOUND)
MARK_AS_ADVANCED(CLEAR LZO2_INCLUDE_DIR)
MARK_AS_ADVANCED(CLEAR LZO2_LIBRARY)
#
# Find LZ4
#
IF (LZ4_INCLUDE_DIR)
# Already in cache, be silent
SET(LZ4_FIND_QUIETLY TRUE)
ENDIF (LZ4_INCLUDE_DIR)
FIND_PATH(LZ4_INCLUDE_DIR lz4.h)
FIND_LIBRARY(LZ4_LIBRARY NAMES lz4 liblz4)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LZ4 DEFAULT_MSG LZ4_LIBRARY LZ4_INCLUDE_DIR)
IF(LZ4_FOUND)
SET(HAVE_LIBLZ4 1)
SET(HAVE_LZ4_H 1)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
SET(CMAKE_REQUIRED_INCLUDES ${LZ4_INCLUDE_DIR})
CHECK_INCLUDE_FILES("lz4hc.h" HAVE_LZ4HC_H)
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
INCLUDE_DIRECTORIES(${LZ4_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${LZ4_LIBRARY})
#
# TODO: test for static library.
#
ENDIF(LZ4_FOUND)
MARK_AS_ADVANCED(CLEAR LZ4_INCLUDE_DIR)
MARK_AS_ADVANCED(CLEAR LZ4_LIBRARY)
#
# Check headers
#
CHECK_HEADER_DIRENT()
SET(INCLUDES "")
MACRO (LA_CHECK_INCLUDE_FILE header var)
CHECK_INCLUDE_FILES("${INCLUDES};${header}" ${var})
IF (${var})
SET(INCLUDES ${INCLUDES} ${header})
ENDIF (${var})
ENDMACRO (LA_CHECK_INCLUDE_FILE)
# Some FreeBSD headers assume sys/types.h was already included.
LA_CHECK_INCLUDE_FILE("sys/types.h" HAVE_SYS_TYPES_H)
# Alphabetize the rest unless there's a compelling reason
LA_CHECK_INCLUDE_FILE("acl/libacl.h" HAVE_ACL_LIBACL_H)
LA_CHECK_INCLUDE_FILE("ctype.h" HAVE_CTYPE_H)
LA_CHECK_INCLUDE_FILE("copyfile.h" HAVE_COPYFILE_H)
LA_CHECK_INCLUDE_FILE("direct.h" HAVE_DIRECT_H)
LA_CHECK_INCLUDE_FILE("dlfcn.h" HAVE_DLFCN_H)
LA_CHECK_INCLUDE_FILE("errno.h" HAVE_ERRNO_H)
LA_CHECK_INCLUDE_FILE("ext2fs/ext2_fs.h" HAVE_EXT2FS_EXT2_FS_H)
CHECK_C_SOURCE_COMPILES("#include <sys/ioctl.h>
#include <ext2fs/ext2_fs.h>
int main(void) { return EXT2_IOC_GETFLAGS; }" HAVE_WORKING_EXT2_IOC_GETFLAGS)
LA_CHECK_INCLUDE_FILE("fcntl.h" HAVE_FCNTL_H)
LA_CHECK_INCLUDE_FILE("grp.h" HAVE_GRP_H)
LA_CHECK_INCLUDE_FILE("inttypes.h" HAVE_INTTYPES_H)
LA_CHECK_INCLUDE_FILE("io.h" HAVE_IO_H)
LA_CHECK_INCLUDE_FILE("langinfo.h" HAVE_LANGINFO_H)
LA_CHECK_INCLUDE_FILE("limits.h" HAVE_LIMITS_H)
LA_CHECK_INCLUDE_FILE("linux/types.h" HAVE_LINUX_TYPES_H)
LA_CHECK_INCLUDE_FILE("linux/fiemap.h" HAVE_LINUX_FIEMAP_H)
LA_CHECK_INCLUDE_FILE("linux/fs.h" HAVE_LINUX_FS_H)
CHECK_C_SOURCE_COMPILES("#include <sys/ioctl.h>
#include <linux/fs.h>
int main(void) { return FS_IOC_GETFLAGS; }" HAVE_WORKING_FS_IOC_GETFLAGS)
LA_CHECK_INCLUDE_FILE("linux/magic.h" HAVE_LINUX_MAGIC_H)
LA_CHECK_INCLUDE_FILE("locale.h" HAVE_LOCALE_H)
LA_CHECK_INCLUDE_FILE("memory.h" HAVE_MEMORY_H)
LA_CHECK_INCLUDE_FILE("paths.h" HAVE_PATHS_H)
LA_CHECK_INCLUDE_FILE("poll.h" HAVE_POLL_H)
LA_CHECK_INCLUDE_FILE("process.h" HAVE_PROCESS_H)
LA_CHECK_INCLUDE_FILE("pthread.h" HAVE_PTHREAD_H)
LA_CHECK_INCLUDE_FILE("pwd.h" HAVE_PWD_H)
LA_CHECK_INCLUDE_FILE("readpassphrase.h" HAVE_READPASSPHRASE_H)
LA_CHECK_INCLUDE_FILE("regex.h" HAVE_REGEX_H)
LA_CHECK_INCLUDE_FILE("signal.h" HAVE_SIGNAL_H)
LA_CHECK_INCLUDE_FILE("spawn.h" HAVE_SPAWN_H)
LA_CHECK_INCLUDE_FILE("stdarg.h" HAVE_STDARG_H)
LA_CHECK_INCLUDE_FILE("stdint.h" HAVE_STDINT_H)
LA_CHECK_INCLUDE_FILE("stdlib.h" HAVE_STDLIB_H)
LA_CHECK_INCLUDE_FILE("string.h" HAVE_STRING_H)
LA_CHECK_INCLUDE_FILE("strings.h" HAVE_STRINGS_H)
LA_CHECK_INCLUDE_FILE("sys/acl.h" HAVE_SYS_ACL_H)
LA_CHECK_INCLUDE_FILE("sys/cdefs.h" HAVE_SYS_CDEFS_H)
LA_CHECK_INCLUDE_FILE("sys/ioctl.h" HAVE_SYS_IOCTL_H)
LA_CHECK_INCLUDE_FILE("sys/mkdev.h" HAVE_SYS_MKDEV_H)
LA_CHECK_INCLUDE_FILE("sys/mount.h" HAVE_SYS_MOUNT_H)
LA_CHECK_INCLUDE_FILE("sys/param.h" HAVE_SYS_PARAM_H)
LA_CHECK_INCLUDE_FILE("sys/poll.h" HAVE_SYS_POLL_H)
LA_CHECK_INCLUDE_FILE("sys/select.h" HAVE_SYS_SELECT_H)
LA_CHECK_INCLUDE_FILE("sys/stat.h" HAVE_SYS_STAT_H)
LA_CHECK_INCLUDE_FILE("sys/statfs.h" HAVE_SYS_STATFS_H)
LA_CHECK_INCLUDE_FILE("sys/statvfs.h" HAVE_SYS_STATVFS_H)
LA_CHECK_INCLUDE_FILE("sys/time.h" HAVE_SYS_TIME_H)
LA_CHECK_INCLUDE_FILE("sys/utime.h" HAVE_SYS_UTIME_H)
LA_CHECK_INCLUDE_FILE("sys/utsname.h" HAVE_SYS_UTSNAME_H)
LA_CHECK_INCLUDE_FILE("sys/vfs.h" HAVE_SYS_VFS_H)
LA_CHECK_INCLUDE_FILE("sys/wait.h" HAVE_SYS_WAIT_H)
LA_CHECK_INCLUDE_FILE("time.h" HAVE_TIME_H)
LA_CHECK_INCLUDE_FILE("unistd.h" HAVE_UNISTD_H)
LA_CHECK_INCLUDE_FILE("utime.h" HAVE_UTIME_H)
LA_CHECK_INCLUDE_FILE("wchar.h" HAVE_WCHAR_H)
LA_CHECK_INCLUDE_FILE("wctype.h" HAVE_WCTYPE_H)
LA_CHECK_INCLUDE_FILE("windows.h" HAVE_WINDOWS_H)
IF(ENABLE_CNG)
LA_CHECK_INCLUDE_FILE("Bcrypt.h" HAVE_BCRYPT_H)
ELSE(ENABLE_CNG)
UNSET(HAVE_BCRYPT_H CACHE)
ENDIF(ENABLE_CNG)
# Following files need windows.h, so we should test it after windows.h test.
LA_CHECK_INCLUDE_FILE("wincrypt.h" HAVE_WINCRYPT_H)
LA_CHECK_INCLUDE_FILE("winioctl.h" HAVE_WINIOCTL_H)
#
# Check whether use of __EXTENSIONS__ is safe.
# We need some macro such as _GNU_SOURCE to use extension functions.
#
SET(_INCLUDE_FILES)
FOREACH (it ${_HEADER})
SET(_INCLUDE_FILES "${_INCLUDE_FILES}#include <${it}>\n")
ENDFOREACH (it)
CHECK_C_SOURCE_COMPILES(
"#define __EXTENSIONS__ 1
${_INCLUDE_FILES}
int main() { return 0;}"
SAFE_TO_DEFINE_EXTENSIONS)
#
# Find Nettle
#
IF(ENABLE_NETTLE)
FIND_PACKAGE(Nettle)
IF(NETTLE_FOUND)
SET(HAVE_LIBNETTLE 1)
LIST(APPEND ADDITIONAL_LIBS ${NETTLE_LIBRARIES})
INCLUDE_DIRECTORIES(${NETTLE_INCLUDE_DIR})
LIST(APPEND CMAKE_REQUIRED_INCLUDES ${NETTLE_INCLUDE_DIR})
LA_CHECK_INCLUDE_FILE("nettle/aes.h" HAVE_NETTLE_AES_H)
LA_CHECK_INCLUDE_FILE("nettle/hmac.h" HAVE_NETTLE_HMAC_H)
LA_CHECK_INCLUDE_FILE("nettle/md5.h" HAVE_NETTLE_MD5_H)
LA_CHECK_INCLUDE_FILE("nettle/pbkdf2.h" HAVE_NETTLE_PBKDF2_H)
LA_CHECK_INCLUDE_FILE("nettle/ripemd160.h" HAVE_NETTLE_RIPEMD160_H)
LA_CHECK_INCLUDE_FILE("nettle/sha.h" HAVE_NETTLE_SHA_H)
ENDIF(NETTLE_FOUND)
MARK_AS_ADVANCED(CLEAR NETTLE_INCLUDE_DIR)
MARK_AS_ADVANCED(CLEAR NETTLE_LIBRARIES)
ENDIF(ENABLE_NETTLE)
#
# Find OpenSSL
# (Except on Mac, where OpenSSL is deprecated.)
#
IF(ENABLE_OPENSSL AND NOT CMAKE_SYSTEM_NAME MATCHES "Darwin")
FIND_PACKAGE(OpenSSL)
IF(OPENSSL_FOUND)
SET(HAVE_LIBCRYPTO 1)
INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${OPENSSL_CRYPTO_LIBRARY})
ENDIF(OPENSSL_FOUND)
ELSE()
SET(OPENSSL_FOUND FALSE) # Override cached value
ENDIF()
# FreeBSD libmd
IF(NOT OPENSSL_FOUND)
CHECK_LIBRARY_EXISTS(md "MD5Init" "" LIBMD_FOUND)
IF(LIBMD_FOUND)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
SET(CMAKE_REQUIRED_LIBRARIES "md")
FIND_LIBRARY(LIBMD_LIBRARY NAMES md)
LIST(APPEND ADDITIONAL_LIBS ${LIBMD_LIBRARY})
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
ENDIF(LIBMD_FOUND)
ENDIF(NOT OPENSSL_FOUND)
#
# How to prove that CRYPTO functions, which have several names on various
# platforms, just see if archive_digest.c can compile and link against
# required libraries.
#
MACRO(CHECK_CRYPTO ALGORITHMS IMPLEMENTATION)
FOREACH(ALGORITHM ${ALGORITHMS})
IF(NOT ARCHIVE_CRYPTO_${ALGORITHM})
STRING(TOLOWER "${ALGORITHM}" lower_algorithm)
STRING(TOUPPER "${ALGORITHM}" algorithm)
IF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND NOT OPENSSL_FOUND)
SET(ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} FALSE)
ELSEIF("${IMPLEMENTATION}" MATCHES "^NETTLE$" AND NOT NETTLE_FOUND)
SET(ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} FALSE)
ENDIF("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND NOT OPENSSL_FOUND)
IF(NOT DEFINED ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
# Probe the local implementation for whether this
# crypto implementation is available on this platform.
SET(TRY_CRYPTO_REQUIRED_INCLUDES
"-DINCLUDE_DIRECTORIES:STRING=${CMAKE_BINARY_DIR};${CMAKE_CURRENT_SOURCE_DIR}/libarchive;${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp")
SET(TRY_CRYPTO_REQUIRED_LIBS)
IF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
SET(TRY_CRYPTO_REQUIRED_INCLUDES
"${TRY_CRYPTO_REQUIRED_INCLUDES};${OPENSSL_INCLUDE_DIR}")
SET(TRY_CRYPTO_REQUIRED_LIBS
"-DLINK_LIBRARIES:STRING=${OPENSSL_LIBRARIES}")
ELSEIF("${IMPLEMENTATION}" MATCHES "^NETTLE$" AND NETTLE_FOUND)
SET(TRY_CRYPTO_REQUIRED_INCLUDES
"${TRY_CRYPTO_REQUIRED_INCLUDES};${NETTLE_INCLUDE_DIR}")
SET(TRY_CRYPTO_REQUIRED_LIBS
"-DLINK_LIBRARIES:STRING=${NETTLE_LIBRARY}")
ELSEIF("${IMPLEMENTATION}" MATCHES "^LIBMD$" AND LIBMD_FOUND)
SET(TRY_CRYPTO_REQUIRED_LIBS
"-DLINK_LIBRARIES:STRING=${LIBMD_LIBRARY}")
ENDIF("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/build/cmake/config.h.in
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h)
FILE(READ "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h"
CONFDEFS_H)
FILE(READ "${CMAKE_CURRENT_SOURCE_DIR}/libarchive/archive_digest.c"
ARCHIVE_CRYPTO_C)
SET(SOURCE "${CONFDEFS_H}
#define ARCHIVE_${algorithm}_COMPILE_TEST
#define ARCHIVE_CRYPTO_${algorithm}_${IMPLEMENTATION}
#define PLATFORM_CONFIG_H \"check_crypto_md.h\"
${ARCHIVE_CRYPTO_C}
int
main(int argc, char **argv)
{
archive_${lower_algorithm}_ctx ctx;
archive_${lower_algorithm}_init(&ctx);
archive_${lower_algorithm}_update(&ctx, *argv, argc);
archive_${lower_algorithm}_final(&ctx, NULL);
return 0;
}
")
FILE(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_md.h" "")
FILE(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_md.c" "${SOURCE}")
MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION}")
TRY_COMPILE(ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION}
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_md.c
CMAKE_FLAGS
"${TRY_CRYPTO_REQUIRED_LIBS}"
"${TRY_CRYPTO_REQUIRED_INCLUDES}"
OUTPUT_VARIABLE OUTPUT)
# Inform user whether or not we found it; if not, log why we didn't.
IF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} -- found")
SET(ARCHIVE_CRYPTO_${ALGORITHM} 1)
ELSE (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} -- not found")
FILE(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"Checking support for ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION} failed with the following output:\n"
"${OUTPUT}\n"
"Source file was:\n${SOURCE}\n")
ENDIF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
ENDIF(NOT DEFINED ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
# Add appropriate libs/includes depending on whether the implementation
# was found on this platform.
IF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
IF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${OPENSSL_LIBRARIES})
LIST(REMOVE_DUPLICATES ADDITIONAL_LIBS)
ENDIF ("${IMPLEMENTATION}" MATCHES "^OPENSSL$" AND OPENSSL_FOUND)
ENDIF (ARCHIVE_CRYPTO_${ALGORITHM}_${IMPLEMENTATION})
ENDIF(NOT ARCHIVE_CRYPTO_${ALGORITHM})
ENDFOREACH(ALGORITHM ${ALGORITHMS})
ENDMACRO(CHECK_CRYPTO ALGORITHMS IMPLEMENTATION)
#
# CRYPTO functions on Windows is defined at archive_windows.c, thus we do not
# need the test what the functions can be mapped to archive_{crypto name}_init,
# archive_{crypto name}_update and archive_{crypto name}_final.
# The functions on Windows use CALG_{crypto name} macro to create a crypt object
# and then we need to know what CALG_{crypto name} macros is available to show
# ARCHIVE_CRYPTO_{crypto name}_WIN macros because Windows 2000 and earlier version
# of Windows XP do not support SHA256, SHA384 and SHA512.
#
MACRO(CHECK_CRYPTO_WIN CRYPTO_LIST)
IF(WIN32 AND NOT CYGWIN)
FOREACH(CRYPTO ${CRYPTO_LIST})
IF(NOT ARCHIVE_CRYPTO_${CRYPTO})
IF(NOT DEFINED ARCHIVE_CRYPTO_${CRYPTO}_WIN)
STRING(TOUPPER "${CRYPTO}" crypto)
SET(ALGID "")
IF ("${CRYPTO}" MATCHES "^MD5$")
SET(ALGID "CALG_MD5")
ENDIF ("${CRYPTO}" MATCHES "^MD5$")
IF ("${CRYPTO}" MATCHES "^SHA1$")
SET(ALGID "CALG_SHA1")
ENDIF ("${CRYPTO}" MATCHES "^SHA1$")
IF ("${CRYPTO}" MATCHES "^SHA256$")
SET(ALGID "CALG_SHA_256")
ENDIF ("${CRYPTO}" MATCHES "^SHA256$")
IF ("${CRYPTO}" MATCHES "^SHA384$")
SET(ALGID "CALG_SHA_384")
ENDIF ("${CRYPTO}" MATCHES "^SHA384$")
IF ("${CRYPTO}" MATCHES "^SHA512$")
SET(ALGID "CALG_SHA_512")
ENDIF ("${CRYPTO}" MATCHES "^SHA512$")
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/build/cmake/config.h.in
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h)
FILE(READ "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/confdefs.h"
CONFDEFS_H)
SET(SOURCE "${CONFDEFS_H}
#define ${crypto}_COMPILE_TEST
#include <windows.h>
#include <wincrypt.h>
int
main(int argc, char **argv)
{
return ${ALGID};
}
")
SET(SOURCE_FILE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/check_crypto_win.c")
FILE(WRITE "${SOURCE_FILE}" "${SOURCE}")
MESSAGE(STATUS "Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN")
TRY_COMPILE(ARCHIVE_CRYPTO_${CRYPTO}_WIN
${CMAKE_BINARY_DIR}
${SOURCE_FILE}
CMAKE_FLAGS "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_BINARY_DIR};${CMAKE_CURRENT_SOURCE_DIR}/libarchive"
OUTPUT_VARIABLE OUTPUT)
IF (ARCHIVE_CRYPTO_${CRYPTO}_WIN)
MESSAGE(STATUS
"Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN -- found")
SET(ARCHIVE_CRYPTO_${CRYPTO} 1)
ELSE (ARCHIVE_CRYPTO_${CRYPTO}_WIN)
MESSAGE(STATUS
"Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN -- not found")
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"Checking support for ARCHIVE_CRYPTO_${CRYPTO}_WIN failed with the following output:\n"
"${OUTPUT}\n"
"Source file was:\n${SOURCE}\n")
ENDIF (ARCHIVE_CRYPTO_${CRYPTO}_WIN)
ENDIF(NOT DEFINED ARCHIVE_CRYPTO_${CRYPTO}_WIN)
ENDIF(NOT ARCHIVE_CRYPTO_${CRYPTO})
ENDFOREACH(CRYPTO)
ENDIF(WIN32 AND NOT CYGWIN)
ENDMACRO(CHECK_CRYPTO_WIN CRYPTO_LIST)
#
# Find iconv
# POSIX defines the second arg as const char **
# and requires it to be in libc. But we can accept
# a non-const argument here and can support iconv()
# being in libiconv.
#
MACRO(CHECK_ICONV LIB TRY_ICONV_CONST)
IF(NOT HAVE_ICONV)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
IF (CMAKE_C_COMPILER_ID MATCHES "^GNU$" OR
CMAKE_C_COMPILER_ID MATCHES "^Clang$")
#
# During checking iconv proto type, we should use -Werror to avoid the
# success of iconv detection with a warnig which success is a miss
# detection. So this needs for all build mode(even it's a release mode).
#
SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror")
ENDIF (CMAKE_C_COMPILER_ID MATCHES "^GNU$" OR
CMAKE_C_COMPILER_ID MATCHES "^Clang$")
IF (CMAKE_C_COMPILER_ID MATCHES "^XL$")
SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -qhalt=w -qflag=w:w")
ENDIF (CMAKE_C_COMPILER_ID MATCHES "^XL$")
IF (MSVC)
# NOTE: /WX option is the same as gcc's -Werror option.
SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} /WX")
ENDIF (MSVC)
#
CHECK_C_SOURCE_COMPILES(
"#include <stdlib.h>
#include <iconv.h>
int main() {
${TRY_ICONV_CONST} char *ccp;
iconv_t cd = iconv_open(\"\", \"\");
iconv(cd, &ccp, (size_t *)0, (char **)0, (size_t *)0);
iconv_close(cd);
return 0;
}"
HAVE_ICONV_${LIB}_${TRY_ICONV_CONST})
IF(HAVE_ICONV_${LIB}_${TRY_ICONV_CONST})
SET(HAVE_ICONV true)
SET(ICONV_CONST ${TRY_ICONV_CONST})
ENDIF(HAVE_ICONV_${LIB}_${TRY_ICONV_CONST})
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
ENDIF(NOT HAVE_ICONV)
ENDMACRO(CHECK_ICONV TRY_ICONV_CONST)
IF(ENABLE_ICONV)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
FIND_PATH(ICONV_INCLUDE_DIR iconv.h)
IF(ICONV_INCLUDE_DIR)
#SET(INCLUDES ${INCLUDES} "iconv.h")
SET(HAVE_ICONV_H 1)
INCLUDE_DIRECTORIES(${ICONV_INCLUDE_DIR})
SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
CHECK_ICONV("libc" "const")
CHECK_ICONV("libc" "")
# If iconv isn't in libc and we have a libiconv, try that.
FIND_LIBRARY(LIBICONV_PATH NAMES iconv libiconv)
IF(NOT HAVE_ICONV AND LIBICONV_PATH)
LIST(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBICONV_PATH})
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${ICONV_INCLUDE_DIR}" "${LIBICONV_PATH}"
COMPILES
"#include <iconv.h>\nint main() {return iconv_close((iconv_t)0);}"
"WITHOUT_LIBICONV_STATIC;LIBICONV_STATIC")
IF(NOT WITHOUT_LIBICONV_STATIC AND LIBICONV_STATIC)
ADD_DEFINITIONS(-DLIBICONV_STATIC)
ENDIF(NOT WITHOUT_LIBICONV_STATIC AND LIBICONV_STATIC)
#
# Set up CMAKE_REQUIRED_* for CHECK_ICONV
#
SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
SET(CMAKE_REQUIRED_LIBRARIES ${LIBICONV_PATH})
IF(LIBICONV_STATIC)
# LIBICONV_STATIC is necessary for the success of CHECK_ICONV
# on Windows.
SET(CMAKE_REQUIRED_DEFINITIONS "-DLIBICONV_STATIC")
ELSE(LIBICONV_STATIC)
SET(CMAKE_REQUIRED_DEFINITIONS)
ENDIF(LIBICONV_STATIC)
CHECK_ICONV("libiconv" "const")
CHECK_ICONV("libiconv" "")
IF (HAVE_ICONV)
LIST(APPEND ADDITIONAL_LIBS ${LIBICONV_PATH})
ENDIF(HAVE_ICONV)
ENDIF(NOT HAVE_ICONV AND LIBICONV_PATH)
ENDIF(ICONV_INCLUDE_DIR)
#
# Find locale_charset() for libiconv.
#
IF(LIBICONV_PATH)
SET(CMAKE_REQUIRED_DEFINITIONS)
SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
SET(CMAKE_REQUIRED_LIBRARIES)
CHECK_INCLUDE_FILES("localcharset.h" HAVE_LOCALCHARSET_H)
FIND_LIBRARY(LIBCHARSET_PATH NAMES charset libcharset)
IF(LIBCHARSET_PATH)
SET(CMAKE_REQUIRED_LIBRARIES ${LIBCHARSET_PATH})
IF(WIN32 AND NOT CYGWIN)
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${ICONV_INCLUDE_DIR}" "${LIBCHARSET_PATH}"
COMPILES
"#include <localcharset.h>\nint main() {return locale_charset()?1:0;}"
"WITHOUT_LIBCHARSET_STATIC;LIBCHARSET_STATIC")
IF(NOT WITHOUT_LIBCHARSET_STATIC AND LIBCHARSET_STATIC)
ADD_DEFINITIONS(-DLIBCHARSET_STATIC)
ENDIF(NOT WITHOUT_LIBCHARSET_STATIC AND LIBCHARSET_STATIC)
IF(WITHOUT_LIBCHARSET_STATIC OR LIBCHARSET_STATIC)
SET(HAVE_LOCALE_CHARSET ON CACHE INTERNAL
"Have function locale_charset")
ENDIF(WITHOUT_LIBCHARSET_STATIC OR LIBCHARSET_STATIC)
ELSE(WIN32 AND NOT CYGWIN)
CHECK_FUNCTION_EXISTS_GLIBC(locale_charset HAVE_LOCALE_CHARSET)
ENDIF(WIN32 AND NOT CYGWIN)
IF(HAVE_LOCALE_CHARSET)
LIST(APPEND ADDITIONAL_LIBS ${LIBCHARSET_PATH})
ENDIF(HAVE_LOCALE_CHARSET)
ENDIF(LIBCHARSET_PATH)
ENDIF(LIBICONV_PATH)
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
ELSE(ENABLE_ICONV)
# Make sure ICONV variables are not in CACHE after ENABLE_ICONV disabled
# (once enabled).
UNSET(HAVE_LOCALE_CHARSET CACHE)
UNSET(HAVE_ICONV CACHE)
UNSET(HAVE_ICONV_libc_ CACHE)
UNSET(HAVE_ICONV_libc_const CACHE)
UNSET(HAVE_ICONV_libiconv_ CACHE)
UNSET(HAVE_ICONV_libiconv_const CACHE)
UNSET(ICONV_INCLUDE_DIR CACHE)
UNSET(LIBICONV_PATH CACHE)
UNSET(LIBICONV_DLL CACHE)
UNSET(LIBICONV_STATIC CACHE)
UNSET(LIBCHARSET_DLL CACHE)
UNSET(LIBCHARSET_STATIC CACHE)
ENDIF(ENABLE_ICONV)
#
# Find Libxml2
#
IF(ENABLE_LIBXML2)
FIND_PACKAGE(LibXml2)
ELSE()
SET(LIBXML2_FOUND FALSE)
ENDIF()
IF(LIBXML2_FOUND)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
INCLUDE_DIRECTORIES(${LIBXML2_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${LIBXML2_LIBRARIES})
SET(HAVE_LIBXML2 1)
# libxml2's include files use iconv.h
SET(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR} ${LIBXML2_INCLUDE_DIR})
CHECK_INCLUDE_FILES("libxml/xmlreader.h" HAVE_LIBXML_XMLREADER_H)
CHECK_INCLUDE_FILES("libxml/xmlwriter.h" HAVE_LIBXML_XMLWRITER_H)
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${ICONV_INCLUDE_DIR};${LIBXML2_INCLUDE_DIR}"
"ws2_32.lib;${ZLIB_LIBRARIES};${LIBICONV_PATH};${LIBXML2_LIBRARIES}"
COMPILES
"#include <stddef.h>\n#include <libxml/xmlreader.h>\nint main() {return xmlTextReaderRead((xmlTextReaderPtr)(void *)0);}"
"WITHOUT_LIBXML_STATIC;LIBXML_STATIC")
IF(NOT WITHOUT_LIBXML_STATIC AND LIBXML_STATIC)
ADD_DEFINITIONS(-DLIBXML_STATIC)
ENDIF(NOT WITHOUT_LIBXML_STATIC AND LIBXML_STATIC)
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
ELSE(LIBXML2_FOUND)
#
# Find Expat
#
IF(ENABLE_EXPAT)
FIND_PACKAGE(EXPAT)
ELSE()
SET(EXPAT_FOUND FALSE)
ENDIF()
IF(EXPAT_FOUND)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
INCLUDE_DIRECTORIES(${EXPAT_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${EXPAT_LIBRARIES})
SET(HAVE_LIBEXPAT 1)
LA_CHECK_INCLUDE_FILE("expat.h" HAVE_EXPAT_H)
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
ENDIF(EXPAT_FOUND)
ENDIF(LIBXML2_FOUND)
MARK_AS_ADVANCED(CLEAR LIBXML2_INCLUDE_DIR)
MARK_AS_ADVANCED(CLEAR LIBXML2_LIBRARIES)
#
# POSIX Regular Expression support
#
IF(POSIX_REGEX_LIB MATCHES "^(AUTO|LIBC|LIBREGEX)$")
#
# If PCREPOSIX is not found or not requested, try using regex
# from libc or libregex
#
FIND_PATH(REGEX_INCLUDE_DIR regex.h)
IF(REGEX_INCLUDE_DIR)
CHECK_FUNCTION_EXISTS_GLIBC(regcomp HAVE_REGCOMP_LIBC)
#
# If libc does not provide regex, find libregex.
#
IF(NOT HAVE_REGCOMP_LIBC)
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
FIND_LIBRARY(REGEX_LIBRARY regex)
IF(REGEX_LIBRARY)
SET(CMAKE_REQUIRED_LIBRARIES ${REGEX_LIBRARY})
CHECK_FUNCTION_EXISTS_GLIBC(regcomp HAVE_REGCOMP_LIBREGEX)
IF(HAVE_REGCOMP_LIBREGEX)
LIST(APPEND ADDITIONAL_LIBS ${REGEX_LIBRARY})
#
# If regex.h is not found, retry looking for regex.h at
# REGEX_INCLUDE_DIR
#
IF(NOT HAVE_REGEX_H)
UNSET(HAVE_REGEX_H CACHE)
INCLUDE_DIRECTORIES(${REGEX_INCLUDE_DIR})
SET(CMAKE_REQUIRED_INCLUDES ${REGEX_INCLUDE_DIR})
LA_CHECK_INCLUDE_FILE("regex.h" HAVE_REGEX_H)
ENDIF(NOT HAVE_REGEX_H)
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${REGEX_INCLUDE_DIR}" "${REGEX_LIBRARY}"
COMPILES
"#include <stddef.h>\n#include <regex.h>\nint main() {regex_t r;return regcomp(&r, \"\", 0);}"
"USE_REGEX_DLL;USE_REGEX_STATIC")
IF(USE_REGEX_DLL)
ADD_DEFINITIONS(-DUSE_REGEX_DLL)
ELSEIF(USE_REGEX_STATIC)
ADD_DEFINITIONS(-DUSE_REGEX_STATIC)
ENDIF(USE_REGEX_DLL)
ENDIF(HAVE_REGCOMP_LIBREGEX)
ENDIF(REGEX_LIBRARY)
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
ENDIF(NOT HAVE_REGCOMP_LIBC)
ENDIF(REGEX_INCLUDE_DIR)
IF(HAVE_REGCOMP_LIBC OR HAVE_REGCOMP_LIBREGEX)
SET(FOUND_POSIX_REGEX_LIB 1)
ENDIF(HAVE_REGCOMP_LIBC OR HAVE_REGCOMP_LIBREGEX)
ENDIF(POSIX_REGEX_LIB MATCHES "^(AUTO|LIBC|LIBREGEX)$")
IF(NOT FOUND_POSIX_REGEX_LIB AND POSIX_REGEX_LIB MATCHES "^(AUTO|LIBPCREPOSIX)$")
#
# If requested, try finding library for PCREPOSIX
#
IF(ENABLE_LibGCC)
FIND_PACKAGE(LibGCC)
ELSE()
SET(LIBGCC_FOUND FALSE) # Override cached value
ENDIF()
IF(ENABLE_PCREPOSIX)
FIND_PACKAGE(PCREPOSIX)
ELSE()
SET(PCREPOSIX_FOUND FALSE) # Override cached value
ENDIF()
IF(PCREPOSIX_FOUND)
INCLUDE_DIRECTORIES(${PCRE_INCLUDE_DIR})
LIST(APPEND ADDITIONAL_LIBS ${PCREPOSIX_LIBRARIES})
# Test if a macro is needed for the library.
TRY_MACRO_FOR_LIBRARY(
"${PCRE_INCLUDE_DIR}" "${PCREPOSIX_LIBRARIES}"
COMPILES
"#include <pcreposix.h>\nint main() {regex_t r;return regcomp(&r, \"\", 0);}"
"WITHOUT_PCRE_STATIC;PCRE_STATIC")
IF(NOT WITHOUT_PCRE_STATIC AND PCRE_STATIC)
ADD_DEFINITIONS(-DPCRE_STATIC)
ELSEIF(NOT WITHOUT_PCRE_STATIC AND NOT PCRE_STATIC AND PCRE_FOUND)
# Determine if pcre static libraries are to be used.
LIST(APPEND ADDITIONAL_LIBS ${PCRE_LIBRARIES})
SET(TMP_LIBRARIES ${PCREPOSIX_LIBRARIES} ${PCRE_LIBRARIES})
MESSAGE(STATUS "trying again with -lpcre included")
TRY_MACRO_FOR_LIBRARY(
"${PCRE_INCLUDE_DIR}" "${TMP_LIBRARIES}"
COMPILES
"#include <pcreposix.h>\nint main() {regex_t r;return regcomp(&r, \"\", 0);}"
"WITHOUT_PCRE_STATIC;PCRE_STATIC")
IF(NOT WITHOUT_PCRE_STATIC AND PCRE_STATIC)
ADD_DEFINITIONS(-DPCRE_STATIC)
ELSEIF(NOT WITHOUT_PCRE_STATIC AND NOT PCRE_STATIC AND MSVC AND LIBGCC_FOUND)
# When doing a Visual Studio build using pcre static libraries
# built using the mingw toolchain, -lgcc is needed to resolve
# ___chkstk_ms.
MESSAGE(STATUS "Visual Studio build detected, trying again with -lgcc included")
LIST(APPEND ADDITIONAL_LIBS ${LIBGCC_LIBRARIES})
SET(TMP_LIBRARIES ${PCREPOSIX_LIBRARIES} ${PCRE_LIBRARIES} ${LIBGCC_LIBRARIES})
TRY_MACRO_FOR_LIBRARY(
"${PCRE_INCLUDE_DIR}" "${TMP_LIBRARIES}"
COMPILES
"#include <pcreposix.h>\nint main() {regex_t r;return regcomp(&r, \"\", 0);}"
"WITHOUT_PCRE_STATIC;PCRE_STATIC")
IF(NOT WITHOUT_PCRE_STATIC AND PCRE_STATIC)
ADD_DEFINITIONS(-DPCRE_STATIC)
ENDIF(NOT WITHOUT_PCRE_STATIC AND PCRE_STATIC)
ENDIF(NOT WITHOUT_PCRE_STATIC AND PCRE_STATIC)
ENDIF(NOT WITHOUT_PCRE_STATIC AND PCRE_STATIC)
ENDIF(PCREPOSIX_FOUND)
MARK_AS_ADVANCED(CLEAR PCRE_INCLUDE_DIR)
MARK_AS_ADVANCED(CLEAR PCREPOSIX_LIBRARIES)
MARK_AS_ADVANCED(CLEAR PCRE_LIBRARIES)
MARK_AS_ADVANCED(CLEAR LIBGCC_LIBRARIES)
ENDIF(NOT FOUND_POSIX_REGEX_LIB AND POSIX_REGEX_LIB MATCHES "^(AUTO|LIBPCREPOSIX)$")
#
# Check functions
#
CMAKE_PUSH_CHECK_STATE() # Save the state of the variables
IF (CMAKE_C_COMPILER_ID MATCHES "^GNU$" OR
CMAKE_C_COMPILER_ID MATCHES "^Clang$")
#
# During checking functions, we should use -fno-builtin to avoid the
# failure of function detection which failure is an error "conflicting
# types for built-in function" caused by using -Werror option.
#
SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fno-builtin")
ENDIF (CMAKE_C_COMPILER_ID MATCHES "^GNU$" OR
CMAKE_C_COMPILER_ID MATCHES "^Clang$")
CHECK_SYMBOL_EXISTS(_CrtSetReportMode "crtdbg.h" HAVE__CrtSetReportMode)
CHECK_FUNCTION_EXISTS_GLIBC(arc4random_buf HAVE_ARC4RANDOM_BUF)
CHECK_FUNCTION_EXISTS_GLIBC(chflags HAVE_CHFLAGS)
CHECK_FUNCTION_EXISTS_GLIBC(chown HAVE_CHOWN)
CHECK_FUNCTION_EXISTS_GLIBC(chroot HAVE_CHROOT)
CHECK_FUNCTION_EXISTS_GLIBC(ctime_r HAVE_CTIME_R)
CHECK_FUNCTION_EXISTS_GLIBC(dirfd HAVE_DIRFD)
CHECK_FUNCTION_EXISTS_GLIBC(fchdir HAVE_FCHDIR)
CHECK_FUNCTION_EXISTS_GLIBC(fchflags HAVE_FCHFLAGS)
CHECK_FUNCTION_EXISTS_GLIBC(fchmod HAVE_FCHMOD)
CHECK_FUNCTION_EXISTS_GLIBC(fchown HAVE_FCHOWN)
CHECK_FUNCTION_EXISTS_GLIBC(fcntl HAVE_FCNTL)
CHECK_FUNCTION_EXISTS_GLIBC(fdopendir HAVE_FDOPENDIR)
CHECK_FUNCTION_EXISTS_GLIBC(fork HAVE_FORK)
CHECK_FUNCTION_EXISTS_GLIBC(fstat HAVE_FSTAT)
CHECK_FUNCTION_EXISTS_GLIBC(fstatat HAVE_FSTATAT)
CHECK_FUNCTION_EXISTS_GLIBC(fstatfs HAVE_FSTATFS)
CHECK_FUNCTION_EXISTS_GLIBC(fstatvfs HAVE_FSTATVFS)
CHECK_FUNCTION_EXISTS_GLIBC(ftruncate HAVE_FTRUNCATE)
CHECK_FUNCTION_EXISTS_GLIBC(futimens HAVE_FUTIMENS)
CHECK_FUNCTION_EXISTS_GLIBC(futimes HAVE_FUTIMES)
CHECK_FUNCTION_EXISTS_GLIBC(futimesat HAVE_FUTIMESAT)
CHECK_FUNCTION_EXISTS_GLIBC(geteuid HAVE_GETEUID)
CHECK_FUNCTION_EXISTS_GLIBC(getgrgid_r HAVE_GETGRGID_R)
CHECK_FUNCTION_EXISTS_GLIBC(getgrnam_r HAVE_GETGRNAM_R)
CHECK_FUNCTION_EXISTS_GLIBC(getpwnam_r HAVE_GETPWNAM_R)
CHECK_FUNCTION_EXISTS_GLIBC(getpwuid_r HAVE_GETPWUID_R)
CHECK_FUNCTION_EXISTS_GLIBC(getpid HAVE_GETPID)
CHECK_FUNCTION_EXISTS_GLIBC(getvfsbyname HAVE_GETVFSBYNAME)
CHECK_FUNCTION_EXISTS_GLIBC(gmtime_r HAVE_GMTIME_R)
CHECK_FUNCTION_EXISTS_GLIBC(lchflags HAVE_LCHFLAGS)
CHECK_FUNCTION_EXISTS_GLIBC(lchmod HAVE_LCHMOD)
CHECK_FUNCTION_EXISTS_GLIBC(lchown HAVE_LCHOWN)
CHECK_FUNCTION_EXISTS_GLIBC(link HAVE_LINK)
CHECK_FUNCTION_EXISTS_GLIBC(localtime_r HAVE_LOCALTIME_R)
CHECK_FUNCTION_EXISTS_GLIBC(lstat HAVE_LSTAT)
CHECK_FUNCTION_EXISTS_GLIBC(lutimes HAVE_LUTIMES)
CHECK_FUNCTION_EXISTS_GLIBC(mbrtowc HAVE_MBRTOWC)
CHECK_FUNCTION_EXISTS_GLIBC(memmove HAVE_MEMMOVE)
CHECK_FUNCTION_EXISTS_GLIBC(mkdir HAVE_MKDIR)
CHECK_FUNCTION_EXISTS_GLIBC(mkfifo HAVE_MKFIFO)
CHECK_FUNCTION_EXISTS_GLIBC(mknod HAVE_MKNOD)
CHECK_FUNCTION_EXISTS_GLIBC(mkstemp HAVE_MKSTEMP)
CHECK_FUNCTION_EXISTS_GLIBC(nl_langinfo HAVE_NL_LANGINFO)
CHECK_FUNCTION_EXISTS_GLIBC(openat HAVE_OPENAT)
CHECK_FUNCTION_EXISTS_GLIBC(pipe HAVE_PIPE)
CHECK_FUNCTION_EXISTS_GLIBC(poll HAVE_POLL)
CHECK_FUNCTION_EXISTS_GLIBC(posix_spawnp HAVE_POSIX_SPAWNP)
CHECK_FUNCTION_EXISTS_GLIBC(readlink HAVE_READLINK)
CHECK_FUNCTION_EXISTS_GLIBC(readpassphrase HAVE_READPASSPHRASE)
CHECK_FUNCTION_EXISTS_GLIBC(select HAVE_SELECT)
CHECK_FUNCTION_EXISTS_GLIBC(setenv HAVE_SETENV)
CHECK_FUNCTION_EXISTS_GLIBC(setlocale HAVE_SETLOCALE)
CHECK_FUNCTION_EXISTS_GLIBC(sigaction HAVE_SIGACTION)
CHECK_FUNCTION_EXISTS_GLIBC(statfs HAVE_STATFS)
CHECK_FUNCTION_EXISTS_GLIBC(statvfs HAVE_STATVFS)
CHECK_FUNCTION_EXISTS_GLIBC(strchr HAVE_STRCHR)
CHECK_FUNCTION_EXISTS_GLIBC(strdup HAVE_STRDUP)
CHECK_FUNCTION_EXISTS_GLIBC(strerror HAVE_STRERROR)
CHECK_FUNCTION_EXISTS_GLIBC(strncpy_s HAVE_STRNCPY_S)
CHECK_FUNCTION_EXISTS_GLIBC(strrchr HAVE_STRRCHR)
CHECK_FUNCTION_EXISTS_GLIBC(symlink HAVE_SYMLINK)
CHECK_FUNCTION_EXISTS_GLIBC(timegm HAVE_TIMEGM)
CHECK_FUNCTION_EXISTS_GLIBC(tzset HAVE_TZSET)
CHECK_FUNCTION_EXISTS_GLIBC(unsetenv HAVE_UNSETENV)
CHECK_FUNCTION_EXISTS_GLIBC(utime HAVE_UTIME)
CHECK_FUNCTION_EXISTS_GLIBC(utimes HAVE_UTIMES)
CHECK_FUNCTION_EXISTS_GLIBC(utimensat HAVE_UTIMENSAT)
CHECK_FUNCTION_EXISTS_GLIBC(vfork HAVE_VFORK)
CHECK_FUNCTION_EXISTS_GLIBC(wcrtomb HAVE_WCRTOMB)
CHECK_FUNCTION_EXISTS_GLIBC(wcscmp HAVE_WCSCMP)
CHECK_FUNCTION_EXISTS_GLIBC(wcscpy HAVE_WCSCPY)
CHECK_FUNCTION_EXISTS_GLIBC(wcslen HAVE_WCSLEN)
CHECK_FUNCTION_EXISTS_GLIBC(wctomb HAVE_WCTOMB)
CHECK_FUNCTION_EXISTS_GLIBC(_ctime64_s HAVE__CTIME64_S)
CHECK_FUNCTION_EXISTS_GLIBC(_fseeki64 HAVE__FSEEKI64)
CHECK_FUNCTION_EXISTS_GLIBC(_get_timezone HAVE__GET_TIMEZONE)
CHECK_FUNCTION_EXISTS_GLIBC(_localtime64_s HAVE__LOCALTIME64_S)
CHECK_FUNCTION_EXISTS_GLIBC(_mkgmtime64 HAVE__MKGMTIME64)
SET(CMAKE_REQUIRED_LIBRARIES "")
CHECK_FUNCTION_EXISTS(cygwin_conv_path HAVE_CYGWIN_CONV_PATH)
CHECK_FUNCTION_EXISTS(fseeko HAVE_FSEEKO)
CHECK_FUNCTION_EXISTS(strerror_r HAVE_STRERROR_R)
CHECK_FUNCTION_EXISTS(strftime HAVE_STRFTIME)
CHECK_FUNCTION_EXISTS(vprintf HAVE_VPRINTF)
CHECK_FUNCTION_EXISTS(wmemcmp HAVE_WMEMCMP)
CHECK_FUNCTION_EXISTS(wmemcpy HAVE_WMEMCPY)
CHECK_FUNCTION_EXISTS(wmemmove HAVE_WMEMMOVE)
CMAKE_POP_CHECK_STATE() # Restore the state of the variables
CHECK_C_SOURCE_COMPILES(
"#include <sys/types.h>\n#include <sys/mount.h>\nint main(void) { struct vfsconf v; return sizeof(v);}"
HAVE_STRUCT_VFSCONF)
CHECK_C_SOURCE_COMPILES(
"#include <sys/types.h>\n#include <sys/mount.h>\nint main(void) { struct xvfsconf v; return sizeof(v);}"
HAVE_STRUCT_XVFSCONF)
# Make sure we have the POSIX version of readdir_r, not the
# older 2-argument version.
CHECK_C_SOURCE_COMPILES(
"#include <dirent.h>\nint main() {DIR *d = opendir(\".\"); struct dirent e,*r; return readdir_r(d,&e,&r);}"
HAVE_READDIR_R)
# Only detect readlinkat() if we also have AT_FDCWD in unistd.h.
# NOTE: linux requires fcntl.h for AT_FDCWD.
CHECK_C_SOURCE_COMPILES(
"#include <fcntl.h>\n#include <unistd.h>\nint main() {char buf[10]; return readlinkat(AT_FDCWD, \"\", buf, 0);}"
HAVE_READLINKAT)
# To verify major(), we need to both include the header
# of interest and verify that the result can be linked.
# CHECK_FUNCTION_EXISTS doesn't accept a header argument,
# CHECK_SYMBOL_EXISTS doesn't test linkage.
CHECK_C_SOURCE_COMPILES(
"#include <sys/mkdev.h>\nint main() { return major(256); }"
MAJOR_IN_MKDEV)
CHECK_C_SOURCE_COMPILES(
"#include <sys/sysmacros.h>\nint main() { return major(256); }"
MAJOR_IN_SYSMACROS)
CHECK_C_SOURCE_COMPILES(
"#include <lzma.h>\n#if LZMA_VERSION < 50020000\n#error unsupported\n#endif\nint main(void){lzma_stream_encoder_mt(0, 0); return 0;}"
HAVE_LZMA_STREAM_ENCODER_MT)
IF(HAVE_STRERROR_R)
SET(HAVE_DECL_STRERROR_R 1)
ENDIF(HAVE_STRERROR_R)
#
# Check defines
#
SET(headers "limits.h")
IF(HAVE_STDINT_H)
LIST(APPEND headers "stdint.h")
ENDIF(HAVE_STDINT_H)
IF(HAVE_INTTYPES_H)
LIST(APPEND headers "inttypes.h")
ENDIF(HAVE_INTTYPES_H)
CHECK_SYMBOL_EXISTS(EFTYPE "errno.h" HAVE_EFTYPE)
CHECK_SYMBOL_EXISTS(EILSEQ "errno.h" HAVE_EILSEQ)
CHECK_SYMBOL_EXISTS(D_MD_ORDER "langinfo.h" HAVE_D_MD_ORDER)
CHECK_SYMBOL_EXISTS(INT32_MAX "${headers}" HAVE_DECL_INT32_MAX)
CHECK_SYMBOL_EXISTS(INT32_MIN "${headers}" HAVE_DECL_INT32_MIN)
CHECK_SYMBOL_EXISTS(INT64_MAX "${headers}" HAVE_DECL_INT64_MAX)
CHECK_SYMBOL_EXISTS(INT64_MIN "${headers}" HAVE_DECL_INT64_MIN)
CHECK_SYMBOL_EXISTS(INTMAX_MAX "${headers}" HAVE_DECL_INTMAX_MAX)
CHECK_SYMBOL_EXISTS(INTMAX_MIN "${headers}" HAVE_DECL_INTMAX_MIN)
CHECK_SYMBOL_EXISTS(UINT32_MAX "${headers}" HAVE_DECL_UINT32_MAX)
CHECK_SYMBOL_EXISTS(UINT64_MAX "${headers}" HAVE_DECL_UINT64_MAX)
CHECK_SYMBOL_EXISTS(UINTMAX_MAX "${headers}" HAVE_DECL_UINTMAX_MAX)
CHECK_SYMBOL_EXISTS(SIZE_MAX "${headers}" HAVE_DECL_SIZE_MAX)
CHECK_SYMBOL_EXISTS(SSIZE_MAX "limits.h" HAVE_DECL_SSIZE_MAX)
#
# Check struct members
#
# Check for tm_gmtoff in struct tm
CHECK_STRUCT_HAS_MEMBER("struct tm" tm_gmtoff
"time.h" HAVE_STRUCT_TM_TM_GMTOFF)
CHECK_STRUCT_HAS_MEMBER("struct tm" __tm_gmtoff
"time.h" HAVE_STRUCT_TM___TM_GMTOFF)
# Check for f_namemax in struct statfs
CHECK_STRUCT_HAS_MEMBER("struct statfs" f_namemax
"sys/param.h;sys/mount.h" HAVE_STRUCT_STATFS_F_NAMEMAX)
# Check for birthtime in struct stat
CHECK_STRUCT_HAS_MEMBER("struct stat" st_birthtime
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_BIRTHTIME)
# Check for high-resolution timestamps in struct stat
CHECK_STRUCT_HAS_MEMBER("struct stat" st_birthtimespec.tv_nsec
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC)
CHECK_STRUCT_HAS_MEMBER("struct stat" st_mtimespec.tv_nsec
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
CHECK_STRUCT_HAS_MEMBER("struct stat" st_mtim.tv_nsec
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
CHECK_STRUCT_HAS_MEMBER("struct stat" st_mtime_n
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIME_N)
CHECK_STRUCT_HAS_MEMBER("struct stat" st_umtime
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_UMTIME)
CHECK_STRUCT_HAS_MEMBER("struct stat" st_mtime_usec
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_MTIME_USEC)
# Check for block size support in struct stat
CHECK_STRUCT_HAS_MEMBER("struct stat" st_blksize
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_BLKSIZE)
# Check for st_flags in struct stat (BSD fflags)
CHECK_STRUCT_HAS_MEMBER("struct stat" st_flags
"sys/types.h;sys/stat.h" HAVE_STRUCT_STAT_ST_FLAGS)
IF(HAVE_SYS_STATVFS_H)
CHECK_STRUCT_HAS_MEMBER("struct statvfs" f_iosize
"sys/types.h;sys/statvfs.h" HAVE_STRUCT_STATVFS_F_IOSIZE)
ENDIF()
#
#
CHECK_STRUCT_HAS_MEMBER("struct tm" tm_sec
"sys/types.h;sys/time.h;time.h" TIME_WITH_SYS_TIME)
#
# Check for integer types
#
#
CHECK_TYPE_SIZE("short" SIZE_OF_SHORT)
CHECK_TYPE_SIZE("int" SIZE_OF_INT)
CHECK_TYPE_SIZE("long" SIZE_OF_LONG)
CHECK_TYPE_SIZE("long long" SIZE_OF_LONG_LONG)
CHECK_TYPE_SIZE("unsigned short" SIZE_OF_UNSIGNED_SHORT)
CHECK_TYPE_SIZE("unsigned" SIZE_OF_UNSIGNED)
CHECK_TYPE_SIZE("unsigned long" SIZE_OF_UNSIGNED_LONG)
CHECK_TYPE_SIZE("unsigned long long" SIZE_OF_UNSIGNED_LONG_LONG)
CHECK_TYPE_SIZE("__int64" __INT64)
CHECK_TYPE_SIZE("unsigned __int64" UNSIGNED___INT64)
CHECK_TYPE_SIZE(int16_t INT16_T)
CHECK_TYPE_SIZE(int32_t INT32_T)
CHECK_TYPE_SIZE(int64_t INT64_T)
CHECK_TYPE_SIZE(intmax_t INTMAX_T)
CHECK_TYPE_SIZE(uint8_t UINT8_T)
CHECK_TYPE_SIZE(uint16_t UINT16_T)
CHECK_TYPE_SIZE(uint32_t UINT32_T)
CHECK_TYPE_SIZE(uint64_t UINT64_T)
CHECK_TYPE_SIZE(uintmax_t UINTMAX_T)
CHECK_TYPE_SIZE(dev_t DEV_T)
IF(NOT HAVE_DEV_T)
IF(MSVC)
SET(dev_t "unsigned int")
ENDIF(MSVC)
ENDIF(NOT HAVE_DEV_T)
#
CHECK_TYPE_SIZE(gid_t GID_T)
IF(NOT HAVE_GID_T)
IF(WIN32)
SET(gid_t "short")
ELSE(WIN32)
SET(gid_t "unsigned int")
ENDIF(WIN32)
ENDIF(NOT HAVE_GID_T)
#
CHECK_TYPE_SIZE(id_t ID_T)
IF(NOT HAVE_ID_T)
IF(WIN32)
SET(id_t "short")
ELSE(WIN32)
SET(id_t "unsigned int")
ENDIF(WIN32)
ENDIF(NOT HAVE_ID_T)
#
CHECK_TYPE_SIZE(mode_t MODE_T)
IF(NOT HAVE_MODE_T)
IF(WIN32)
SET(mode_t "unsigned short")
ELSE(WIN32)
SET(mode_t "int")
ENDIF(WIN32)
ENDIF(NOT HAVE_MODE_T)
#
CHECK_TYPE_SIZE(off_t OFF_T)
IF(NOT HAVE_OFF_T)
SET(off_t "__int64")
ENDIF(NOT HAVE_OFF_T)
#
CHECK_TYPE_SIZE(size_t SIZE_T)
IF(NOT HAVE_SIZE_T)
IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
SET(size_t "uint64_t")
ELSE("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
SET(size_t "uint32_t")
ENDIF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
ENDIF(NOT HAVE_SIZE_T)
#
CHECK_TYPE_SIZE(ssize_t SSIZE_T)
IF(NOT HAVE_SSIZE_T)
IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
SET(ssize_t "int64_t")
ELSE("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
SET(ssize_t "long")
ENDIF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
ENDIF(NOT HAVE_SSIZE_T)
#
CHECK_TYPE_SIZE(uid_t UID_T)
IF(NOT HAVE_UID_T)
IF(WIN32)
SET(uid_t "short")
ELSE(WIN32)
SET(uid_t "unsigned int")
ENDIF(WIN32)
ENDIF(NOT HAVE_UID_T)
#
CHECK_TYPE_SIZE(pid_t PID_T)
IF(NOT HAVE_PID_T)
IF(WIN32)
SET(pid_t "int")
ELSE(WIN32)
MESSAGE(FATAL_ERROR "pid_t doesn't exist on this platform?")
ENDIF(WIN32)
ENDIF(NOT HAVE_PID_T)
#
CHECK_TYPE_SIZE(intptr_t INTPTR_T)
IF(NOT HAVE_INTPTR_T)
IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
SET(intptr_t "int64_t")
ELSE()
SET(intptr_t "int32_t")
ENDIF()
ENDIF(NOT HAVE_INTPTR_T)
#
CHECK_TYPE_SIZE(uintptr_t UINTPTR_T)
IF(NOT HAVE_UINTPTR_T)
IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
SET(uintptr_t "uint64_t")
ELSE()
SET(uintptr_t "uint32_t")
ENDIF()
ENDIF(NOT HAVE_UINTPTR_T)
#
CHECK_TYPE_SIZE(wchar_t SIZEOF_WCHAR_T)
IF(HAVE_SIZEOF_WCHAR_T)
SET(HAVE_WCHAR_T 1)
ENDIF(HAVE_SIZEOF_WCHAR_T)
#
# Check if _FILE_OFFSET_BITS macro needed for large files
#
CHECK_FILE_OFFSET_BITS()
#
# Check for Extended Attribute libraries, headers, and functions
#
IF(ENABLE_XATTR)
LA_CHECK_INCLUDE_FILE(attr/xattr.h HAVE_ATTR_XATTR_H)
LA_CHECK_INCLUDE_FILE(sys/xattr.h HAVE_SYS_XATTR_H)
LA_CHECK_INCLUDE_FILE(sys/extattr.h HAVE_SYS_EXTATTR_H)
CHECK_LIBRARY_EXISTS(attr "setxattr" "" HAVE_LIBATTR)
IF(HAVE_LIBATTR)
SET(CMAKE_REQUIRED_LIBRARIES "attr")
ENDIF(HAVE_LIBATTR)
CHECK_SYMBOL_EXISTS(EXTATTR_NAMESPACE_USER "sys/types.h;sys/extattr.h" HAVE_DECL_EXTATTR_NAMESPACE_USER)
CHECK_FUNCTION_EXISTS_GLIBC(extattr_get_file HAVE_EXTATTR_GET_FILE)
CHECK_FUNCTION_EXISTS_GLIBC(extattr_list_file HAVE_EXTATTR_LIST_FILE)
CHECK_FUNCTION_EXISTS_GLIBC(extattr_set_fd HAVE_EXTATTR_SET_FD)
CHECK_FUNCTION_EXISTS_GLIBC(extattr_set_file HAVE_EXTATTR_SET_FILE)
CHECK_FUNCTION_EXISTS_GLIBC(fgetxattr HAVE_FGETXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(flistxattr HAVE_FLISTXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(fsetxattr HAVE_FSETXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(getxattr HAVE_GETXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(lgetxattr HAVE_LGETXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(listxattr HAVE_LISTXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(llistxattr HAVE_LLISTXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(lsetxattr HAVE_LSETXATTR)
CHECK_FUNCTION_EXISTS_GLIBC(fgetea HAVE_FGETEA)
CHECK_FUNCTION_EXISTS_GLIBC(flistea HAVE_FLISTEA)
CHECK_FUNCTION_EXISTS_GLIBC(fsetea HAVE_FSETEA)
CHECK_FUNCTION_EXISTS_GLIBC(getea HAVE_GETEA)
CHECK_FUNCTION_EXISTS_GLIBC(lgetea HAVE_LGETEA)
CHECK_FUNCTION_EXISTS_GLIBC(listea HAVE_LISTEA)
CHECK_FUNCTION_EXISTS_GLIBC(llistea HAVE_LLISTEA)
CHECK_FUNCTION_EXISTS_GLIBC(lsetea HAVE_LSETEA)
ELSE(ENABLE_XATTR)
SET(HAVE_ATTR_LIB FALSE)
SET(HAVE_ATTR_XATTR_H FALSE)
SET(HAVE_DECL_EXTATTR_NAMESPACE_USER FALSE)
SET(HAVE_EXTATTR_GET_FILE FALSE)
SET(HAVE_EXTATTR_LIST_FILE FALSE)
SET(HAVE_EXTATTR_SET_FD FALSE)
SET(HAVE_EXTATTR_SET_FILE FALSE)
SET(HAVE_FGETEA FALSE)
SET(HAVE_FGETXATTR FALSE)
SET(HAVE_FLISTEA FALSE)
SET(HAVE_FLISTXATTR FALSE)
SET(HAVE_FSETEA FALSE)
SET(HAVE_FSETXATTR FALSE)
SET(HAVE_GETEA FALSE)
SET(HAVE_GETXATTR FALSE)
SET(HAVE_LGETEA FALSE)
SET(HAVE_LGETXATTR FALSE)
SET(HAVE_LISTEA FALSE)
SET(HAVE_LISTXATTR FALSE)
SET(HAVE_LLISTEA FALSE)
SET(HAVE_LLISTXATTR FALSE)
SET(HAVE_LSETEA FALSE)
SET(HAVE_LSETXATTR FALSE)
SET(HAVE_SYS_EXTATTR_H FALSE)
SET(HAVE_SYS_XATTR_H FALSE)
ENDIF(ENABLE_XATTR)
#
# Check for ACL libraries, headers, and functions
#
# The ACL support in libarchive is written against the POSIX1e draft,
# which was never officially approved and varies quite a bit across
# platforms. Worse, some systems have completely non-POSIX acl functions,
# which makes the following checks rather more complex than I would like.
#
IF(ENABLE_ACL)
CHECK_LIBRARY_EXISTS(acl "acl_get_file" "" HAVE_LIBACL)
IF(HAVE_LIBACL)
SET(CMAKE_REQUIRED_LIBRARIES "acl")
FIND_LIBRARY(ACL_LIBRARY NAMES acl)
LIST(APPEND ADDITIONAL_LIBS ${ACL_LIBRARY})
ENDIF(HAVE_LIBACL)
#
CHECK_FUNCTION_EXISTS_GLIBC(acl_create_entry HAVE_ACL_CREATE_ENTRY)
CHECK_FUNCTION_EXISTS_GLIBC(acl_init HAVE_ACL_INIT)
CHECK_FUNCTION_EXISTS_GLIBC(acl_set_fd HAVE_ACL_SET_FD)
CHECK_FUNCTION_EXISTS_GLIBC(acl_set_fd_np HAVE_ACL_SET_FD_NP)
CHECK_FUNCTION_EXISTS_GLIBC(acl_set_file HAVE_ACL_SET_FILE)
CHECK_TYPE_EXISTS(acl_permset_t "${INCLUDES}" HAVE_ACL_PERMSET_T)
# The "acl_get_perm()" function was omitted from the POSIX draft.
# (It's a pretty obvious oversight; otherwise, there's no way to
# test for specific permissions in a permset.) Linux uses the obvious
# name, FreeBSD adds _np to mark it as "non-Posix extension."
# Test for both as a double-check that we really have POSIX-style ACL support.
CHECK_FUNCTION_EXISTS(acl_get_fd_np HAVE_ACL_GET_FD_NP)
CHECK_FUNCTION_EXISTS(acl_get_perm HAVE_ACL_GET_PERM)
CHECK_FUNCTION_EXISTS(acl_get_perm_np HAVE_ACL_GET_PERM_NP)
CHECK_FUNCTION_EXISTS(acl_get_link HAVE_ACL_GET_LINK)
CHECK_FUNCTION_EXISTS(acl_get_link_np HAVE_ACL_GET_LINK_NP)
CHECK_FUNCTION_EXISTS(acl_is_trivial_np HAVE_ACL_IS_TRIVIAL_NP)
CHECK_FUNCTION_EXISTS(acl_set_link_np HAVE_ACL_SET_LINK_NP)
CHECK_SYMBOL_EXISTS(ACL_TYPE_NFS4 "${INCLUDES}" HAVE_DECL_ACL_TYPE_NFS4)
# MacOS has an acl.h that isn't POSIX. It can be detected by
# checking for ACL_USER
CHECK_SYMBOL_EXISTS(ACL_USER "${INCLUDES}" HAVE_DECL_ACL_USER)
CHECK_C_SOURCE_COMPILES("#include <sys/types.h>
#include <sys/acl.h>
int main(void) { return ACL_TYPE_EXTENDED; }" HAVE_DECL_ACL_TYPE_EXTENDED)
CHECK_C_SOURCE_COMPILES("#include <sys/types.h>
#include <sys/acl.h>
int main(void) { return ACL_SYNCHRONIZE; }" HAVE_DECL_ACL_SYNCHRONIZE)
# Solaris and derivates ACLs
CHECK_TYPE_EXISTS(aclent_t "${INCLUDES}" HAVE_ACLENT_T)
CHECK_TYPE_EXISTS(ace_t "${INCLUDES}" HAVE_ACE_T)
CHECK_FUNCTION_EXISTS(acl HAVE_ACL)
CHECK_FUNCTION_EXISTS(facl HAVE_FACL)
CHECK_SYMBOL_EXISTS(GETACL "${INCLUDES}" HAVE_DECL_GETACL)
CHECK_SYMBOL_EXISTS(GETACLCNT "${INCLUDES}" HAVE_DECL_GETACLCNT)
CHECK_SYMBOL_EXISTS(SETACL "${INCLUDES}" HAVE_DECL_SETACL)
CHECK_SYMBOL_EXISTS(ACE_GETACL "${INCLUDES}" HAVE_DECL_ACE_GETACL)
CHECK_SYMBOL_EXISTS(ACE_GETACLCNT "${INCLUDES}" HAVE_DECL_ACE_GETACLCNT)
CHECK_SYMBOL_EXISTS(ACE_SETACL "${INCLUDES}" HAVE_DECL_ACE_SETACL)
ELSE(ENABLE_ACL)
# If someone runs cmake, then disables ACL support, we need
# to forcibly override the cached values for these.
SET(HAVE_ACL_CREATE_ENTRY FALSE)
SET(HAVE_ACL_GET_LINK FALSE)
SET(HAVE_ACL_GET_LINK_NP FALSE)
SET(HAVE_ACL_GET_PERM FALSE)
SET(HAVE_ACL_GET_PERM_NP FALSE)
SET(HAVE_ACL_INIT FALSE)
SET(HAVE_ACL_LIB FALSE)
SET(HAVE_ACL_PERMSET_T FALSE)
SET(HAVE_ACL_SET_FD FALSE)
SET(HAVE_ACL_SET_FD_NP FALSE)
SET(HAVE_ACL_SET_FILE FALSE)
SET(HAVE_ACL_TYPE_EXTENDED FALSE)
SET(HAVE_ACLENT_T FALSE)
SET(HAVE_ACE_T FALSE)
SET(HAVE_DECL_ACL_TYPE_NFS4 FALSE)
SET(HAVE_DECL_ACL_USER FALSE)
SET(HAVE_DECL_ACL_SYNCHRONIZE FALSE)
SET(HAVE_DECL_GETACL FALSE)
SET(HAVE_DECL_GETACLCNT FALSE)
SET(HAVE_DECL_SETACL FALSE)
SET(HAVE_DECL_ACE_GETACL FALSE)
SET(HAVE_DECL_ACE_GETACLCNT FALSE)
SET(HAVE_DECL_ACE_SETACL FALSE)
SET(HAVE_ACL FALSE)
SET(HAVE_FACL FALSE)
ENDIF(ENABLE_ACL)
#
# Check MD5/RMD160/SHA support
# NOTE: Crypto checks must be run last before generating config.h
#
CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA384;SHA512" LIBC)
CHECK_CRYPTO("SHA256;SHA384;SHA512" LIBC2)
CHECK_CRYPTO("SHA256;SHA384;SHA512" LIBC3)
CHECK_CRYPTO("MD5;SHA1;SHA256;SHA384;SHA512" LIBSYSTEM)
CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA384;SHA512" NETTLE)
CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA384;SHA512" OPENSSL)
# Libmd has to be probed after OpenSSL.
CHECK_CRYPTO("MD5;RMD160;SHA1;SHA256;SHA512" LIBMD)
CHECK_CRYPTO_WIN("MD5;SHA1;SHA256;SHA384;SHA512")
# Generate "config.h" from "build/cmake/config.h.in"
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/build/cmake/config.h.in
${CMAKE_CURRENT_BINARY_DIR}/config.h)
INCLUDE_DIRECTORIES(BEFORE ${CMAKE_CURRENT_BINARY_DIR})
ADD_DEFINITIONS(-DHAVE_CONFIG_H)
# Handle generation of the libarchive.pc file for pkg-config
INCLUDE(CreatePkgConfigFile)
#
# Register installation of PDF documents.
#
IF(WIN32 AND NOT CYGWIN)
#
# On Windows platform, It's better that we install PDF documents
# on one's computer.
# These PDF documents are available in the release package.
#
IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/doc/pdf)
INSTALL(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc/pdf
DESTINATION share/man
FILES_MATCHING PATTERN "*.pdf"
)
ENDIF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/doc/pdf)
ENDIF(WIN32 AND NOT CYGWIN)
#
#
#
INCLUDE_DIRECTORIES(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/libarchive)
#
IF(MSVC)
ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE)
ENDIF(MSVC)
IF(ENABLE_TEST)
ADD_CUSTOM_TARGET(run_all_tests)
ENDIF(ENABLE_TEST)
add_subdirectory(libarchive)
add_subdirectory(cat)
add_subdirectory(tar)
add_subdirectory(cpio)
|
__label__pos
| 0.680057 |
Sleeper9 Sleeper9 - 4 months ago 11
Javascript Question
Angular2 'this' is undefined
I have a code that looks like this:
export class CRListComponent extends ListComponent<CR> implements OnInit {
constructor(
private router: Router,
private crService: CRService) {
super();
}
ngOnInit():any {
this.getCount(new Object(), this.crService.getCount);
}
The ListComponent code is this
@Component({})
export abstract class ListComponent<T extends Listable> {
protected getCount(event: any, countFunction: Function){
let filters = this.parseFilters(event.filters);
countFunction(filters)
.subscribe(
count => {
this.totalItems = count;
},
error => console.log(error)
);
}
And the appropriate service code fragment from CRService is this:
getCount(filters) {
var queryParams = JSON.stringify(
{
c : 'true',
q : filters
}
);
return this.createQuery(queryParams)
.map(res => res.json())
.catch(this.handleError);
}
Now when my
ngOnInit()
runs, I get an error:
angular2.dev.js:23925 EXCEPTION: TypeError: Cannot read property
'createQuery' of undefined in [null]
ORIGINAL EXCEPTION:
TypeError: Cannot read property 'createQuery' of undefined
So basically, the
this
in the
return this.createQuery(queryParams)
statement will be null. Does anybody have an idea how is this possible?
Answer
The problem is located here:
gOnInit():any {
this.getCount(new Object(), this.crService.getCount); // <----
}
Since you reference a function outside an object. You could use the bind method on it:
this.getCount(new Object(), this.crService.getCount.bind(this.crService));
or wrap it into an arrow function:
this.getCount(new Object(), (filters) => {
return this.crService.getCount(filters));
});
The second approach would be the preferred one since it allows to keep types. See this page for more details:
Comments
|
__label__pos
| 0.998212 |
PHP PDO statements
Is there any risk in using integers (and other hardcoded variables) in PDO statments?
ie
$STH=$DBH->prepare("SELECT name FROM Employees WHERE active=1");
$STH->execute();
Seems like it would be a lot of hassle to write it like this:
$STH=$DBH->prepare("SELECT name FROM Employees WHERE active=:active_status");
$STH->execute(array(':active_status'=>1));
(Also, is my syntax ok in the 2nd example?)
jeff_zuckerAsked:
Who is Participating?
I wear a lot of hats...
"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.
Julian HansenCommented:
Risk from?
The risk comes when you insert external variables into the statement without first sterilising them which is the basis for an injection attack - if you hard code the values the only risk is that the programmer does not know what they are doing.
If your statement will always use a particular (constant) value can't see any benefit in parameterising it.
Syntax looks fine see sample below that uses a cut and paste of your code
<pre>
<?php
$dsn = 'mysql:dbname=ee;host=localhost';
$user = 'user';
$password = 'password';
try {
$DBH = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$employees = array(
'Chico',
'Harpo',
'Groucho',
'Gummo',
'Zeppo'
);
$query = <<< QUERY
CREATE TEMPORARY TABLE `Employees` (
`id` INT NOT NULL,
`name` VARCHAR(100),
`active` INT
)
QUERY;
$DBH->exec($query);
$k = 1;
foreach($employees as $id => $emp) {
$query = "INSERT INTO `Employees` (id, name, active) VALUES ({$id},'{$emp}',{$k})";
$DBH->exec($query);
$k = 1 - $k;
}
$STH=$DBH->prepare("SELECT `name` FROM `Employees` WHERE `active`=:active_status");
$STH->execute(array(':active_status'=>1));
$result = $STH->fetchAll();
print_r($result);
?>
Open in new window
0
Ray PaseurCommented:
This article maps the familiar but obsolete MySQL extension to the MySQLi and PDO extensions, with code examples of "how to" throughout.
http://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
Think of query strings as computer programs that drive the behaviors of SQL engine. If you let non-programmers (or worse, malicious programmers) inject parts of the computer program, you've got a risk. This is part of the reason why PDO separates the query string from the data and sends them to SQL separately. If you insert your own data into a query string, you somewhat frustrate the design of PDO that keeps the programming and data separate.
"Is there any risk" requires an answer that paints with a pretty broad brush, so I'll try to answer it from the extremes, then give you a rule that works for me.
1. Let's assume you hardcode data in your script using a literal. You use this hardcoded data in a query string. Because PHP cannot reassign literals, you're safe - if it "works" once, it works always. I put "works" in quotes because there is no guarantee that the query will get you the results set you expect, just that it will be syntactically correct and will be usable by the SQL engine.
2. Let's assume that you need an integer in a query. If your script contains the literal integer, you're safe. If your script computes the integer, some level of risk is introduced. PHP uses type-juggling and what may look like an integer computation to our eyes may result in something other than an integer. The query will probably still work, just not as you expected, unless you cast the data to integer before injecting it into the SQL statement.
3. Let's assume you need some information for a table lookup, perhaps to find a user-id. You get this information from the URL. Now there is more risk because the URL could contain malicious statements that will become part of your SQL program, so data sanitation is an obvious requirement. But even benign external data can have an adverse effect on SQL query strings. Consider a search for the client last name. With 'Zucker' there is no problem. With 'O'Reilly' there is a problem because the quotation marks are unbalanced by the quotation mark that is part of the name. MySQL, MySQLi, and PDO handle this issue differently.
The MySQL variants inject the data directly into the SQL query string, surrounded by quotes. They require the programmer to escape the quotes that are part of the data (not part of the query). PDO avoids the risk by sending the data separately, in separate PHP variables, so no quotes are required in the PDO query string at all.
I'm not sure what you mean by the oxymoron, "hardcoded variables" but I can tell you this rule is good enough to pass a professional code review. If there is a quote mark in a PDO query string, you're doing it wrong. If there are no quote marks, just the colon-prefixed placeholders, you're probably on firm ground.
0
Experts Exchange Solution brought to you by
Your issues matter to us.
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.
Start your 7-day free trial
jeff_zuckerAuthor Commented:
Two great answers. Thank you.
0
Ray PaseurCommented:
Glad to help; thanks for using E-E and best of luck with your project, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server
From novice to tech pro — start learning today.
Question has a verified solution.
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
|
__label__pos
| 0.944968 |
Geometric Algebra, prerequisites to studying? Anyone here study it?
• #1
DrummingAtom
659
2
I was curious if anyone here ever studied Geometric Algebra? It seems not so mainstream and fairly new and I feel intrigued by the subject but I don't want to get in over my head. Just browsing through the table of contents of some books has a lot of unfamiliar terms to me.
Here was a couple books that I was thinking of buying:
Geometric Algebra for Physicists: https://www.amazon.com/Geometric-Algebra-Physicists-Chris-Doran/dp/0521480221/ref=sr_1_16?s=books&ie=UTF8&qid=1347885363&sr=1-16&keywords=%22geometric+algebra%22
Linear and Geometric Algebra:
https://www.amazon.com/Linear-Geometric-Algebra-Alan-Macdonald/product-reviews/1453854932/ref=dp_top_cm_cr_acr_txt?ie=UTF8&showViewpoints=1
Any guidance would be appreciated, thanks.
Answers and Replies
• #2
chiro
Science Advisor
4,815
134
Hey DrummingAtom.
One thing that I think is important when looking at geometric algebra intuitively, is to consider what it means to not only be able to multiply two vectors, but to invert the process (i.e. division).
This problems leads the consideration of multi-dimensional division algebras and the first non-commutative extension in four dimensions was the quaternion. There are of course lots of things that relate to this object, but one core idea you should be aware of is that it is a division algebra.
What happens when you consider this idea of inverting multiplication is that in the generalized form, you get a geometric product which can be used to define the inner and outer products.
From this idea, you get rotation and this is required in a geometric algebra if you want to have a division (or at least be able to invert a multiplication of vectors) since a division will end up "un-rotating" things in orientability as well as un-doing directional changes and scaling changes.
You do this in the complex numbers, and Hamilton extended these to four dimensions, and the general idea of geometric algebra is to extend this concept to any dimension that allows one to do this multiplication and inversion.
From the complex numbers on-ward you get orientation in terms of the chirality of the system and orientation is defined in an intricate way between the two products (inner and outer) as defined by the one unifying geometric product, where the two products are considered a bivector (just like a complex number has real and imaginary parts, a bivector as a scalar part and a vector part corresponding to the inner and outer products).
Now you have two kinds of ways of thinking about this: You have the whole linear algebra way which looks at vectors, matrices, determinants and all that and you also have the way that Hamilton did which is to use multiplication tables and then expand out the multiplication of two objects in the same way we do it for complex numbers (so just like we use i^2 = 1, in quaternions we get ij = k and so on which we can simplify and then collect terms to get a quantity).
There is actually a well developed theory of the 2nd way as opposed to the first way which is based on matrices and linear and tensor algebra and if I can dig up the resource for this (which I know I have) I can point it out (it is a free document on arxiv if I recall correctly).
Now you have simplifications in physics for these things for all that theoretical stuff, but the idea of having this multiplication and division in both the linear algebra, determinant, exterior algebra formulation (and other similar ways) as well as in the way that Hamilton did it (which as I said, has been extended to arbitrary cases in many ways) look at the same kind of thing.
• #4
rhombusjr
96
1
For prerequisites, it might be helpful to understand traditional vector/tensor algebra/calculus. Usually in physics oriented books, the authors will assume you already know the physics of the situation they're applying GA to. This makes understanding GA rather tricky when they say "let's use the Dirac equation as an example to show how GA works" when you've never seen the Dirac Equation before and don't have a clue what they're talking about.
In the early stages, be sure to take the time to learn all the arithmetic regarding the geometric, inner, and outer products. These things can seem trivial, but it can actually get quite complicated. Having a good command of how the different products work will make more advanced material easier to digest.
Be sure check out anything written by D. Hestenes of Arizona State University, he has a lot of material available on his website. He's really the guy who got people interested in GA. His book New Foundations for Classical Mechanics is a good starting point if you can find a copy. He started promoting GA back in the 1960's but it didn't really catch on until more recently, though rather slowly. The biggest community seems to be the field of computer graphics.
Doran and Lasenby is probably the best single source for a wide variety of different physics applications. Personally, I've found that books for computer graphics applications provide a very good introduction to GA and how to visually interpret the various objects and operations.
One thing you'll find when using multiple sources is that everyone pretty much uses different notation, which can get annoying and confusing when you're just starting out. Some people write vectors in regular font, some use bold font, etc. Also, since there are so many different types of objects in GA, it's really hard to figure out how to handwrite things. For instance Doran and Lasenby write linear functions in capitalized non-italicized sans-serif font and bivectors in capitalized italicized serif font. In my handwriting, these two look identical.
Check out things categorized under the name Clifford algebra too. It's essentially another name for GA, though there are subtle differences between the two. The Clifford algebra formalism is a little more mainstream than GA, so there's more written about it.
• #5
marmoset
42
6
I started learning about Clifford algebra recently. Tensors are familiar in physics; the algebra of tensors is built up from vectors using the tensor product, and it includes the vectors as a special kind of tensor. Similarly a Clifford algebra is an algebra built up from the vectors, but using a different product called the Clifford (or geometric) product. A Clifford algebra contains the vectors as well as more general elements (comparable to higher rank tensors) called multivectors.
Given any vector space we can build a tensor algebra from it. But to build a Clifford algebra we need to be given an inner (that is 'dot') product along with the vector space. Pure mathematicians (e.g. Chevalley, E. Cartan) have studied Clifford algebras in the abstract, with arbitrary vector spaces, fields and inner products. The corner of Clifford algebra known as geometric algebra deals mainly with 'ordinary space,' i.e. R^3 with the ordinary dot product, and 'Minkowski space,' i.e. R^4 with the inner product familiar from special relativity. The Clifford algebras in each case can be used much like the tensor algebras; you can use multivectors, like tensors, to represent things which vectors don't suit, like the electromagnetic field.
There are several books that I've found really helpful (I'm a beginner).
Pertti Lounesto's Clifford Algebras and Spinors starts right from the beginning, introducing vector spaces before building up the Clifford algebra in 2-D. The first half of the book introduces Clifford algebra and some physical applications, the second half covers more advanced mathematical topics (I haven't looked at the second half). It is fairly concise, and has lots of exercises with answers, which include lots of chances to get used to actually calculating things and a few proofs too.
Geometric Algebra for Physicists by Doran and Lasenby, mentioned above, is also very useful. It contains a free standing introduction to Clifford algebras, as well as 'geometric calculus,' which is (multivariable) calculus with Clifford algebra. It covers a wide variety of physical applications including point and rigid body mechanics, electromagnetism, and spinors in quantum mechanics. The applications chapters aren't stand-alone introductions, and as mentioned above they probably won't make sense unless you know the physics before.
For a summary of the maths A Survey of Geometric Algebra and Geometric Calculus by Alan Macdonald (available here http://faculty.luther.edu/~macdonal/ ) is very clear.
The (partly unfinished) notes Clifford algebra, geometric algebra and applications of Lundholm and Svensson, found here http://arxiv.org/abs/0907.5356, are much more mathematical and looked a bit intimidating to me, but they define the various products of Clifford algebra in a very simple way which allows you to prove identities essentially by verifying obvious Venn-diagram type set theory relations. They also treat duality, and how it relates the various products, very clearly (these duality relations speed up derivations a lot).
Hestenes' Spacetime Calculus, here http://geocalc.clas.asu.edu/html/STC.html, is a concise introduction to Clifford algebra in relativity, I found the section on electromagnetism very helpful. I haven't looked much at Hestenes' New Foundations for Classical Mechanics, and Hestenes and Sobczyk's Clifford Algebra to Geometric Calculus.
As an aside, some books on geometric algebra are written from the point of view of trying to establish geometric algebra as the 'universal mathematical language' or 'a grand unifying nexus for the whole of mathematics' (quotes from Hestenes website http://geocalc.clas.asu.edu/ ). This involves reformulating everything in terms of geometric algebra and criticising other ways of doing things. As a result these books can sound a bit 'cult-like', which can be off-putting. It is not true that tensors and differential forms lack geometric interpretation; looking in the 1951 edition of 'Tensor Analysis for Physicists' by Schouten (one of the founders of tensor analysis), you find a glossy page with photos of wire and foam models of geometric representations of various kinds of tensor! Emphasising geometric interpretation is helpful, but not as revolutionary as you'd guess from reading some geometric algebra books. Also, the conviction that everything must be done using geometric algebra leads to squeezing subjects like differentiable manifolds into a formalism that doesn't seem to suit them (to me).
Geometric algebra does suit some things extremely well though, for example:
(i) Describing spinors, and understanding the Pauli and Dirac matrices as representations of basis vectors in space and spacetime respectively. This speeds up calculations and makes some Pauli and Dirac matrix identities obvious. For example the Pauli matrix identity [itex](\vec{x}\cdot\vec{\sigma})(\vec{y}\cdot\vec{\sigma}) = (\vec{x}\cdot\vec{y})I+i\vec\sigma\cdot(\vec{x} \times \vec{y})[/itex] expresses the simple GA relation [itex]\vec{x}\vec{y} = \vec{x}\cdot\vec{y}+\vec{x}\wedge\vec{y}[/itex] via a matrix representation using the 'vector of matrices' [itex]\vec\sigma[/itex].
(ii) Doing electromagnetism. Maxwell's equations reduce to a single GA equation [itex] \nabla F = J[/itex] and, more importantly, in GA [itex]\nabla[/itex] can be inverted (i.e. has a Green's function), so you can solve for the 'field tensor' [itex]F[/itex] in terms of the four-current [itex]J[/itex] directly without introducing potentials. As another example, Coulomb's law in electrostatics follows simply from [itex]\vec\nabla\cdot\vec{E}=\rho[/itex] and [itex]\vec\nabla\times\vec{E}=0[/itex], since together these can be written [itex]\vec\nabla\vec{E}=\rho[/itex], and we can invert [itex]\vec\nabla[/itex] by integrating with its Green's function.
In short, while some people get overzealous, Clifford algebra is frequently very useful.
Last edited:
• Like
Likes SolarisOne
• #6
mathwonk
Science Advisor
Homework Helper
11,391
1,628
this seems based on work by grassmann and clifford from the 1840's and 1870's. classic mathematical discussions include the famous book by emil artin, geometric algebra 1957, and various papers in topology from the 1960's by bott and atiyah relating clifford algebras to K theory and periodicity theorems. apparently hestenes introduced the subject to physicists somewhat later.
a nice book for undergraduates that explains clearly the geometric version of multiplication involved in its fundamental setting, is a geometric approach to differential forms, by david bachmann, a work that was read communally here a few years ago of PF.
• #7
brombo
13
0
GA Note and Software
You may wish to check out
https://github.com/brombo/GA [Broken]
The repository contains my notes on GA (following Doran and Lasenby with the blanks filled in) and python software (detailed documentation in LaTeX docs) for symbolic manipulation of multivectors.
Last edited by a moderator:
Suggested for: Geometric Algebra, prerequisites to studying? Anyone here study it?
• Last Post
Replies
11
Views
588
Replies
1
Views
279
Replies
11
Views
456
Replies
2
Views
411
Replies
3
Views
783
• Last Post
Replies
2
Views
439
Replies
3
Views
249
• Last Post
Replies
7
Views
824
• Last Post
Replies
7
Views
416
Top
|
__label__pos
| 0.623577 |
ConstrainedSolver.hh 18 KB
Newer Older
Henrik Zimmer's avatar
Henrik Zimmer committed
1
2
/*===========================================================================*\
* *
Henrik Zimmer's avatar
Henrik Zimmer committed
3
* CoMISo *
Henrik Zimmer's avatar
Henrik Zimmer committed
4
* Copyright (C) 2008-2009 by Computer Graphics Group, RWTH Aachen *
Henrik Zimmer's avatar
Henrik Zimmer committed
5
* www.rwth-graphics.de *
Henrik Zimmer's avatar
Henrik Zimmer committed
6
* *
Henrik Zimmer's avatar
Henrik Zimmer committed
7
8
*---------------------------------------------------------------------------*
* This file is part of CoMISo. *
Henrik Zimmer's avatar
Henrik Zimmer committed
9
* *
Henrik Zimmer's avatar
Henrik Zimmer committed
10
11
12
13
* CoMISo 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. *
Henrik Zimmer's avatar
Henrik Zimmer committed
14
* *
Henrik Zimmer's avatar
Henrik Zimmer committed
15
16
17
* CoMISo 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 *
Henrik Zimmer's avatar
Henrik Zimmer committed
18
* GNU General Public License for more details. *
Henrik Zimmer's avatar
Henrik Zimmer committed
19
* *
Henrik Zimmer's avatar
Henrik Zimmer committed
20
21
* You should have received a copy of the GNU General Public License *
* along with CoMISo. If not, see <http://www.gnu.org/licenses/>. *
Henrik Zimmer's avatar
Henrik Zimmer committed
22
23
* *
\*===========================================================================*/
Henrik Zimmer's avatar
Henrik Zimmer committed
24
25
26
27
28
29
30
31
32
//=============================================================================
//
// CLASS ConstrainedSolver
//
//=============================================================================
33
34
#ifndef COMISO_CONSTRAINEDSOLVER_HH
#define COMISO_CONSTRAINEDSOLVER_HH
35
36
37
//== INCLUDES =================================================================
Henrik Zimmer's avatar
Henrik Zimmer committed
38
#include <CoMISo/Config/CoMISoDefines.hh>
39
40
41
42
43
44
45
46
47
48
49
#include "GMM_Tools.hh"
#include "MISolver.hh"
#include <vector>
//== FORWARDDECLARATIONS ======================================================
//== DEFINES ==================================================================
#define ROUND(x) ((x)<0?int((x)-0.5):int((x)+0.5))
//== NAMESPACES ===============================================================
50
namespace COMISO {
51
52
53
54
55
56
57
58
59
60
//== CLASS DEFINITION =========================================================
/** \class ConstrainedSolver ConstrainedSolver.hh <ACG/.../ConstrainedSolver.hh>
Takes a linear (symmetric) system of equations and a set of linear constraints and solves it.
*/
class COMISODLLEXPORT ConstrainedSolver
{
public:
61
62
typedef gmm::csc_matrix<double> CSCMatrix;
typedef gmm::row_matrix< gmm::wsvector< double > > RowMatrix;
63
64
65
/// default Constructor
Henrik Zimmer's avatar
Henrik Zimmer committed
66
67
/** _do_gcd specifies if a greatest common devisor correction should be used when no (+-)1-coefficient is found*/
ConstrainedSolver( bool _do_gcd = true): do_gcd_(_do_gcd)
David Bommes's avatar
David Bommes committed
68
{ epsilon_ = 1e-8; noisy_ = 1; }
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/// Destructor
~ConstrainedSolver() { }
/** @name Contrained solvers
* Functions to solve constrained linear systems of the form Ax=b (stemming from quadratic energies).
* The constraints can be linear constraints of the form \f$ x_1*c_1+ \cdots +x_n*c_n=c \f$ as well as integer constraints \f$x_i\in \mathbf{Z}\f$.
* The system is then solved with these constraints in mind. For solving the system the Mixed-Integer Solver \a MISolver is used.
*/
/*@{*/
/// Quadratic matrix constrained solver
/**
* Takes a system of the form Ax=b, a constraint matrix C and a set of variables _to_round to be rounded to integers. \f$ A\in \mathbf{R}^{n\times n}\f$
83
* @param _constraints row matrix with rows of the form \f$ [ c_1, c_2, \cdots, c_n, c_{n+1} ] \f$ corresponding to the linear equation \f$ c_1*x_1+\cdots+c_n*x_n + c_{n+1}=0 \f$.
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
* @param _A nxn-dimensional column matrix of the system
* @param _x n-dimensional variable vector
* @param _rhs n-dimensional right hand side.
* @param _idx_to_round indices i of variables x_i that shall be rounded
* @param _reg_factor regularization factor. Helps unstable, low rank system to become solvable. Adds \f$ \_reg\_factor*mean(trace(_A))*Id \f$ to A.
* @param _show_miso_settings should the (QT) dialog of the Mixed-Integer solver pop up?
* @param _show_timings shall some timings be printed?
*/
template<class RMatrixT, class CMatrixT, class VectorT, class VectorIT >
void solve(
RMatrixT& _constraints,
CMatrixT& _A,
VectorT& _x,
VectorT& _rhs,
VectorIT& _idx_to_round,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
David Bommes's avatar
David Bommes committed
103
104
105
106
107
108
109
110
111
112
113
114
// const version of above function
template<class RMatrixT, class CMatrixT, class VectorT, class VectorIT >
void solve_const(
const RMatrixT& _constraints,
const CMatrixT& _A,
VectorT& _x,
const VectorT& _rhs,
const VectorIT& _idx_to_round,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// efficent re-solve with modified _rhs by keeping previous _constraints and _A fixed
template<class RMatrixT, class VectorT >
void resolve(
VectorT& _x,
VectorT& _rhs,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
// const version of above function
template<class RMatrixT, class VectorT >
void resolve_const(
VectorT& _x,
const VectorT& _rhs,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
132
133
134
/// Non-Quadratic matrix constrained solver
/**
135
136
* Same as above, but performs the elimination of the constraints directly on the B matrix of \f$ x^\top B^\top Bx \f$, where B has m rows (equations) and (n+1) columns \f$ [ x_1, x_2, \cdots, x_n, -rhs ] \f$.
* \note This function might be more efficient in some cases, but generally the solver for the quadratic matrix above is a safer bet. Needs further testing.
137
* \note Internally the \f$ A=B^\top B \f$ matrix is formed.
138
* @param _constraints row matrix with rows of the form \f$ [ c_1, c_2, \cdots, c_n, c_{n+1} ] \f$ corresponding to the linear equation \f$ c_1*x_1+\cdots+c_n*x_n + c_{n+1}=0 \f$.
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
* @param _B mx(n+1)-dimensional column matrix of the system
* @param _x n-dimensional variable vector
* @param _idx_to_round indices i of variables x_i that shall be rounded
* @param _reg_factor regularization factor. Helps unstable, low rank system to become solvable.
* @param _show_miso_settings should the (QT) dialog of the Mixed-Integer solver pop up?
* @param _show_timings shall some timings be printed?
*/
template<class RMatrixT, class VectorT, class VectorIT >
void solve(
RMatrixT& _constraints,
RMatrixT& _B,
VectorT& _x,
VectorIT& _idx_to_round,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
David Bommes's avatar
David Bommes committed
155
156
157
158
// const version of above function
template<class RMatrixT, class VectorT, class VectorIT >
void solve_const(
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
const RMatrixT& _constraints,
const RMatrixT& _B,
VectorT& _x,
const VectorIT& _idx_to_round,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
// efficent re-solve with modified _rhs by keeping previous _constraints and _A fixed
template<class RMatrixT, class VectorT >
void resolve(
const RMatrixT& _B,
VectorT& _x,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
// const version of above function
template<class RMatrixT, class VectorT >
void resolve_const(
const RMatrixT& _B,
David Bommes's avatar
David Bommes committed
180
181
182
183
184
VectorT& _x,
double _reg_factor = 0.0,
bool _show_miso_settings = true,
bool _show_timings = true );
185
186
/*@}*/
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/** @name Eliminate constraints
* Functions to eliminate (or integrate) linear constraints from an equation system. These functions are used internally by the \a solve functions.
*/
/*@{*/
/// Make constraints independent
/**
* This function performs a Gauss elimination on the constraint matrix making the constraints easier to eliminate.
* \note A certain amount of independence of the constraints is assumed.
* \note contradicting constraints will be ignored.
* \warning care must be taken when non-trivial constraints occur where some of the variables contain integer-variables (to be rounded) as the optimal result might not always occur.
* @param _constraints row matrix with constraints
* @param _idx_to_round indices of variables to be rounded (these must be considered.)
* @param _c_elim the "returned" vector of variable indices and the order in which the can be eliminated.
*/
template<class RMatrixT, class VectorIT >
void make_constraints_independent(
RMatrixT& _constraints,
VectorIT& _idx_to_round,
std::vector<int>& _c_elim );
David Bommes's avatar
David Bommes committed
209
210
211
212
213
214
template<class RMatrixT, class VectorIT >
void make_constraints_independent_reordering(
RMatrixT& _constraints,
VectorIT& _idx_to_round,
std::vector<int>& _c_elim );
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
/// Eliminate constraints on a factored matrix B
/**
* \note Constraints are assumed to have been made independent by \a make_constraints_independent.
* @param _constraints row matrix with constraints (n+1 columns)
* @param _B system row matrix mx(n+1)
* @param _idx_to_round indices to be rounded
* @param _c_elim the indices of the variables to be eliminated.
* @param _new_idx the created re-indexing map. new_idx[i] = -1 means x_i eliminated, new_idx[i] = j means x_i is now at index j.
* @param _Bcol resulting (smaller) column matrix to be used for future computations. (e.g. convert to CSC and solve)
*/
template<class SVector1T, class SVector2T, class VectorIT, class SVector3T>
void eliminate_constraints(
gmm::row_matrix<SVector1T>& _constraints,
gmm::row_matrix<SVector2T>& _B,
VectorIT& _idx_to_round,
std::vector<int>& _c_elim,
std::vector<int>& _new_idx,
gmm::col_matrix<SVector3T>& _Bcol);
/// Eliminate constraints on a quadratic matrix A
/**
* \note Constraints are assumed to have been made independent by \a make_constraints_independent.
* \note _x must have correct size (same as _rhs)
* @param _constraints row matrix with constraints (n+1 columns)
* @param _A system row matrix nxn)
* @param _x variable vector
* @param _rhs right hand side
* @param _idx_to_round indices to be rounded
* @param _c_elim the indices of the variables to be eliminated.
* @param _new_idx the created re-indexing map. new_idx[i] = -1 means x_i eliminated, new_idx[i] = j means x_i is now at index j.
* @param _Acsc resulting (smaller) column (csc) matrix to be used for future computations.
*/
template<class SVector1T, class SVector2T, class VectorIT, class CSCMatrixT>
void eliminate_constraints(
gmm::row_matrix<SVector1T>& _constraints,
gmm::col_matrix<SVector2T>& _A,
std::vector<double>& _x,
std::vector<double>& _rhs,
VectorIT& _idx_to_round,
std::vector<int>& _c_elim,
std::vector<int>& _new_idx,
CSCMatrixT& _Acsc);
/// Restore a solution vector to the un-eliminated size
/**
* @param _constraints row matrix with constraints (n+1 columns)
* @param _x solution vector to reduced/eliminated system (result will also be written here)
* @param _c_elim vector of eliminated indices
* @param _new_idx re-indexing vector
*/
template<class RMatrixT, class VectorT >
void restore_eliminated_vars( RMatrixT& _constraints,
VectorT& _x,
std::vector<int>& _c_elim,
std::vector<int>& _new_idx);
/*@}*/
276
/// Set numerical epsilon for valid constraint coefficient
David Bommes's avatar
David Bommes committed
277
void set_epsilon( double _epsilon) { epsilon_ = _epsilon; }
278
279
280
281
/// Set noise-level (how much std output is given) 0 basically none, 1 important stuff (warning/timing, is default), 2+ not so important
void set_noisy( int _noisy) { noisy_ = _noisy;}
282
283
284
// Get/Set whether the constraint reordering is used (default true)
bool& use_constraint_reordering() { return miso_.use_constraint_reordering(); }
285
286
287
288
289
290
291
292
293
294
295
/** @name Verify the result.
* Functions to verify the result of the constrained solver. Are the constraints met, are the correct variables correctly rounded ...
*/
/*@{*/
template<class RMatrixT, class CMatrixT, class VectorT>
double verify_constrained_system(
const RMatrixT& _conditions,
const CMatrixT& _A,
const VectorT& _x,
David Bommes's avatar
David Bommes committed
296
297
const VectorT& _rhs,
double _eps = 1e-9);
298
299
300
301
302
303
304
template<class RMatrixT, class CMatrixT, class VectorT, class VectorIT>
double verify_constrained_system_round(
const RMatrixT& _conditions,
const CMatrixT& _A,
const VectorT& _x,
const VectorT& _rhs,
David Bommes's avatar
David Bommes committed
305
306
const VectorIT& _idx_to_round,
double _eps = 1e-9);
307
308
309
310
311
312
313
314
template<class RMatrixT, class VectorT, class VectorIT>
void verify_mi_factored( const RMatrixT& _conditions,
const RMatrixT& _B,
const VectorT& _x,
const VectorIT& _idx_to_round );
/*@}*/
David Bommes's avatar
David Bommes committed
315
316
317
318
/// Access the MISolver (e.g. to change settings)
COMISO::MISolver& misolver() { return miso_;}
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
private:
template<class RowT, class MatrixT>
void add_row( int _row_i,
double _coeff,
RowT _row,
MatrixT& _mat );
template<class RowT, class RMatrixT, class CMatrixT>
void add_row_simultaneously( int _row_i,
double _coeff,
RowT _row,
RMatrixT& _rmat,
CMatrixT& _cmat );
template<class CMatrixT, class VectorT, class VectorIT>
double setup_and_solve_system( CMatrixT& _B,
VectorT& _x,
VectorIT& _idx_to_round,
double _reg_factor,
bool _show_miso_settings);
// warning: order of replacement not the same as in _columns (internal sort)
template<class CMatrixT>
void eliminate_columns( CMatrixT& _M,
const std::vector< int >& _columns);
Henrik Zimmer's avatar
Henrik Zimmer committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
inline int gcd( int _a, int _b)
{
while( _b != 0)
{
int t(_b);
_b = _a%_b;
_a = t;
}
return _a;
}
int find_gcd(std::vector<int>& _v_gcd, int& _n_ints);
// TODO if no gcd correction was possible, at least use a variable divisible by 2 as new elim_j (to avoid in-exactness e.g. 1/3)
template<class RMatrixT>
bool update_constraint_gcd( RMatrixT& _constraints,
int _row_i,
int& _elim_j,
std::vector<int>& _v_gcd,
int& _n_ints);
368
369
370
371
372
373
374
private:
/// Copy constructor (not used)
ConstrainedSolver(const ConstrainedSolver& _rhs);
/// Assignment operator (not used)
ConstrainedSolver& operator=(const ConstrainedSolver& _rhs);
375
David Bommes's avatar
David Bommes committed
376
377
378
// MISO solver
COMISO::MISolver miso_;
379
double epsilon_;
380
int noisy_;
Henrik Zimmer's avatar
Henrik Zimmer committed
381
bool do_gcd_;
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
// --------------- Update by Marcel to enable efficient re-solve with changed rhs ----------------------
// Store for symbolic elimination information for rhs
class rhsUpdateTable {
public:
void append(int _i, double _f, int _j = -1) { table_.push_back(rhsUpdateTableEntry(_i, _j, _f)); }
void add_elim_id(int _i) { elim_var_ids_.push_back(_i); }
void clear() { table_.clear(); elim_var_ids_.clear(); }
// apply stored transformations to _rhs
void apply(std::vector<double>& _rhs)
{
std::vector<rhsUpdateTableEntry>::const_iterator t_it, t_end;
t_end = table_.end();
int cur_j = -1;
double cur_rhs = 0.0;
for(t_it = table_.begin(); t_it != t_end; ++t_it)
{
if(t_it->j >= 0) {
if(t_it->j != cur_j) { cur_j = t_it->j; cur_rhs = _rhs[cur_j]; }
_rhs[t_it->i] += t_it->f * cur_rhs;
}
else
_rhs[t_it->i] += t_it->f;
}
}
// remove eliminated elements from _rhs
void eliminate(std::vector<double>& _rhs)
{
std::vector<int> evar( elim_var_ids_ );
std::sort( evar.begin(), evar.end() );
evar.push_back( std::numeric_limits<int>::max() );
int cur_evar_idx=0;
unsigned int nc = _rhs.size();
for( unsigned int i=0; i<nc; ++i )
{
unsigned int next_i = evar[cur_evar_idx];
if ( i != next_i ) _rhs[i-cur_evar_idx] = _rhs[i];
else ++cur_evar_idx;
}
_rhs.resize( nc - cur_evar_idx );
}
// store transformed constraint matrix and index map to allow for later re-substitution
template<class RMatrixT>
void store(const RMatrixT& _constraints, const std::vector<int>& _c_elim, const std::vector<int>& _new_idx)
{
constraints_p_.resize( gmm::mat_nrows(_constraints), gmm::mat_ncols(_constraints));
gmm::copy(_constraints, constraints_p_);
c_elim_ = _c_elim;
new_idx_ = _new_idx;
}
private:
class rhsUpdateTableEntry {
public:
rhsUpdateTableEntry(int _i, int _j, double _f) : i(_i), j(_j), f(_f) {}
int i;
int j;
double f;
};
std::vector<rhsUpdateTableEntry> table_;
std::vector<int> elim_var_ids_;
public:
std::vector<int> c_elim_;
std::vector<int> new_idx_;
RowMatrix constraints_p_;
} rhs_update_table_;
453
454
455
456
};
//=============================================================================
457
} // namespace COMISO
458
//=============================================================================
459
460
#if defined(INCLUDE_TEMPLATES) && !defined(COMISO_CONSTRAINEDSOLVER_C)
#define COMISO_CONSTRAINEDSOLVER_TEMPLATES
461
462
463
#include "ConstrainedSolverT.cc"
#endif
//=============================================================================
464
#endif // COMISO_CONSTRAINEDSOLVER_HH defined
465
466
//=============================================================================
|
__label__pos
| 0.90826 |
#!/usr/bin/env python # coding: utf-8 # /*########################################################################## # # Copyright (c) 2016 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # ###########################################################################*/ """Module for basic linear algebra in OpenCL""" from __future__ import absolute_import, print_function, with_statement, division __authors__ = ["P. Paleo"] __license__ = "MIT" __date__ = "10/08/2017" import numpy as np from .common import pyopencl from .processing import EventDescription, OpenclProcessing import pyopencl.array as parray cl = pyopencl class LinAlg(OpenclProcessing): kernel_files = ["linalg.cl"] def __init__(self, shape, do_checks=False, ctx=None, devicetype="all", platformid=None, deviceid=None, profile=False): """ Create a "Linear Algebra" plan for a given image shape. :param shape: shape of the image (num_rows, num_columns) :param do_checks (optional): if True, memory and data type checks are performed when possible. :param ctx: actual working context, left to None for automatic initialization from device type or platformid/deviceid :param devicetype: type of device, can be "CPU", "GPU", "ACC" or "ALL" :param platformid: integer with the platform_identifier, as given by clinfo :param deviceid: Integer with the device identifier, as given by clinfo :param profile: switch on profiling to be able to profile at the kernel level, store profiling elements (makes code slightly slower) """ OpenclProcessing.__init__(self, ctx=ctx, devicetype=devicetype, platformid=platformid, deviceid=deviceid, profile=profile) self.d_gradient = parray.zeros(self.queue, shape, np.complex64) self.d_image = parray.zeros(self.queue, shape, np.float32) self.add_to_cl_mem({ "d_gradient": self.d_gradient, "d_image": self.d_image }) self.wg2D = None self.shape = shape self.ndrange2D = ( int(self.shape[1]), int(self.shape[0]) ) self.do_checks = bool(do_checks) OpenclProcessing.compile_kernels(self, self.kernel_files) @staticmethod def check_array(array, dtype, shape, arg_name): if array.shape != shape or array.dtype != dtype: raise ValueError("%s should be a %s array of type %s" %(arg_name, str(shape), str(dtype))) def get_data_references(self, src, dst, default_src_ref, default_dst_ref): """ From various types of src and dst arrays, returns the references to the underlying data (Buffer) that will be used by the OpenCL kernels. # TODO documentation This function will make a copy host->device if the input is on host (eg. numpy array) """ if dst is not None: if isinstance(dst, cl.array.Array): dst_ref = dst.data elif isinstance(dst, cl.Buffer): dst_ref = dst else: raise ValueError("dst should be either pyopencl.array.Array or pyopencl.Buffer") else: dst_ref = default_dst_ref if isinstance(src, cl.array.Array): src_ref = src.data elif isinstance(src, cl.Buffer): src_ref = src else: # assuming numpy.ndarray evt = cl.enqueue_copy(self.queue, default_src_ref, src) self.events.append(EventDescription("copy H->D", evt)) src_ref = default_src_ref return src_ref, dst_ref def gradient(self, image, dst=None, return_to_host=False): """ Compute the spatial gradient of an image. The gradient is computed with first-order difference (not central difference). :param image: image to compute the gradient from. It can be either a numpy.ndarray, a pyopencl Array or Buffer. :param dst: optional, reference to a destination pyopencl Array or Buffer. It must be of complex64 data type. :param return_to_host: optional, set to True if you want the result to be transferred back to host. if dst is provided, it should be of type numpy.complex64 ! """ n_y, n_x = np.int32(self.shape) if self.do_checks: self.check_array(image, np.float32, self.shape, "image") if dst is not None: self.check_array(dst, np.complex64, self.shape, "dst") img_ref, grad_ref = self.get_data_references(image, dst, self.d_image.data, self.d_gradient.data) # Prepare the kernel call kernel_args = [ img_ref, grad_ref, n_x, n_y ] # Call the gradient kernel evt = self.kernels.kern_gradient2D( self.queue, self.ndrange2D, self.wg2D, *kernel_args ) self.events.append(EventDescription("gradient2D", evt)) # TODO: should the wait be done in any case ? # In the case where dst=None, the wait() is mandatory since a user will be doing arithmetic on dst afterwards if dst is None: evt.wait() if return_to_host: if dst is not None: res_tmp = self.d_gradient.get() else: res_tmp = np.zeros(self.shape, dtype=np.complex64) cl.enqueue_copy(self.queue, res_tmp, grad_ref) res = np.zeros((2,) + self.shape, dtype=np.float32) res[0] = np.copy(res_tmp.real) res[1] = np.copy(res_tmp.imag) return res else: return dst def divergence(self, gradient, dst=None, return_to_host=False): """ Compute the spatial divergence of an image. The divergence is designed to be the (negative) adjoint of the gradient. :param gradient: gradient-like array to compute the divergence from. It can be either a numpy.ndarray, a pyopencl Array or Buffer. :param dst: optional, reference to a destination pyopencl Array or Buffer. It must be of complex64 data type. :param return_to_host: optional, set to True if you want the result to be transferred back to host. if dst is provided, it should be of type numpy.complex64 ! """ n_y, n_x = np.int32(self.shape) # numpy.ndarray gradients are expected to be (2, n_y, n_x) if isinstance(gradient, np.ndarray): gradient2 = np.zeros(self.shape, dtype=np.complex64) gradient2.real = np.copy(gradient[0]) gradient2.imag = np.copy(gradient[1]) gradient = gradient2 elif self.do_checks: self.check_array(gradient, np.complex64, self.shape, "gradient") if dst is not None: self.check_array(dst, np.float32, self.shape, "dst") grad_ref, img_ref = self.get_data_references(gradient, dst, self.d_gradient.data, self.d_image.data) # Prepare the kernel call kernel_args = [ grad_ref, img_ref, n_x, n_y ] # Call the gradient kernel evt = self.kernels.kern_divergence2D( self.queue, self.ndrange2D, self.wg2D, *kernel_args ) self.events.append(EventDescription("divergence2D", evt)) # TODO: should the wait be done in any case ? # In the case where dst=None, the wait() is mandatory since a user will be doing arithmetic on dst afterwards if dst is None: evt.wait() if return_to_host: if dst is not None: res = self.d_image.get() else: res = np.zeros(self.shape, dtype=np.float32) cl.enqueue_copy(self.queue, res, img_ref) return res else: return dst
|
__label__pos
| 0.976945 |
socket_accept
(PHP 4 >= 4.1.0, PHP 5)
socket_acceptAccetta una connessione su un socket
Descrizione
resource socket_accept ( resource $socket )
Avviso
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.
Dopo la creazione del socket socket con socket_create(), l'assegnazione di un nome con socket_bind(), e averlo messo in attesa di connessione con socket_listen(), con questa funzione si inizia ad accettare le richieste di connessione su quel socket. Una volta avuta una connessione, la funzione restituisce un nuovo socket che può essere usato per la comunicazione. Se vi sono diverse richieste di connessioni pendenti verrà utilizzata la prima. Viceversa se non vi sono richieste in attesa, la funzione socket_accept() si blocca in attesa di una richiesta. Se il socket è stato configurato "non-blocking" con socket_set_blocking() o con socket_set_nonblock(), la funzione restituirà FALSE.
La risorsa socket restituita da socket_accept() non può essere utilizzata per acquisire nuove connesioni. Per questo scopo occorre continuare ad usare il socket originale, indicato in socket, che rimane aperto.
La funzione restistuisce una risorsa di tipo socket se ha successo, oppure FALSE se si verifica un errore. Il codice di errore può essere recuperato chiamando la funzione socket_last_error(). Questo codice può essere passato a socket_strerror() per ottenere una descrizione dell'errore.
Vedere anche socket_bind(), socket_connect(), socket_listen(), socket_create() e socket_strerror().
add a note add a note
User Contributed Notes 6 notes
up
20
lars at opdenkamp dot eu
9 years ago
If you want to make a daemon process that forks on each client connection, you'll find out that there's a bug in PHP. The child processes send SIGCHLD to their parent when they exit but the parent can't handle signals while it's waiting for socket_accept (blocking).
Here is a piece of code that makes a non-blocking forking server.
#!/usr/bin/php -q
<?php
/**
* Listens for requests and forks on each connection
*/
$__server_listening = true;
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
declare(
ticks = 1);
become_daemon();
/* nobody/nogroup, change to your host's uid/gid of the non-priv user */
change_identity(65534, 65534);
/* handle signals */
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
pcntl_signal(SIGCHLD, 'sig_handler');
/* change this to your own host / port */
server_loop("127.0.0.1", 1234);
/**
* Change the identity to a non-priv user
*/
function change_identity( $uid, $gid )
{
if( !
posix_setgid( $gid ) )
{
print
"Unable to setgid to " . $gid . "!\n";
exit;
}
if( !
posix_setuid( $uid ) )
{
print
"Unable to setuid to " . $uid . "!\n";
exit;
}
}
/**
* Creates a server socket and listens for incoming client connections
* @param string $address The address to listen on
* @param int $port The port to listen on
*/
function server_loop($address, $port)
{
GLOBAL
$__server_listening;
if((
$sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0)
{
echo
"failed to create socket: ".socket_strerror($sock)."\n";
exit();
}
if((
$ret = socket_bind($sock, $address, $port)) < 0)
{
echo
"failed to bind socket: ".socket_strerror($ret)."\n";
exit();
}
if( (
$ret = socket_listen( $sock, 0 ) ) < 0 )
{
echo
"failed to listen to socket: ".socket_strerror($ret)."\n";
exit();
}
socket_set_nonblock($sock);
echo
"waiting for clients to connect\n";
while (
$__server_listening)
{
$connection = @socket_accept($sock);
if (
$connection === false)
{
usleep(100);
}elseif (
$connection > 0)
{
handle_client($sock, $connection);
}else
{
echo
"error: ".socket_strerror($connection);
die;
}
}
}
/**
* Signal handler
*/
function sig_handler($sig)
{
switch(
$sig)
{
case
SIGTERM:
case
SIGINT:
exit();
break;
case
SIGCHLD:
pcntl_waitpid(-1, $status);
break;
}
}
/**
* Handle a new client connection
*/
function handle_client($ssock, $csock)
{
GLOBAL
$__server_listening;
$pid = pcntl_fork();
if (
$pid == -1)
{
/* fork failed */
echo "fork failure!\n";
die;
}elseif (
$pid == 0)
{
/* child process */
$__server_listening = false;
socket_close($ssock);
interact($csock);
socket_close($csock);
}else
{
socket_close($csock);
}
}
function
interact($socket)
{
/* TALK TO YOUR CLIENT */
}
/**
* Become a daemon by forking and closing the parent
*/
function become_daemon()
{
$pid = pcntl_fork();
if (
$pid == -1)
{
/* fork failed */
echo "fork failure!\n";
exit();
}elseif (
$pid)
{
/* close the parent */
exit();
}else
{
/* child becomes our daemon */
posix_setsid();
chdir('/');
umask(0);
return
posix_getpid();
}
}
?>
up
11
Boylett
9 years ago
If you want to have multiple clients on a server you will have to use non blocking.
<?php
$clients
= array();
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'127.0.0.1',$port);
socket_listen($socket);
socket_set_nonblock($socket);
while(
true)
{
if((
$newc = socket_accept($socket)) !== false)
{
echo
"Client $newc has connected\n";
$clients[] = $newc;
}
}
?>
up
0
mightyplow at gmail dot com
2 years ago
In order to make many clients connectable to the server, you have to set the accepted socket also to non-blocking. Otherwise the accepted connection will block further incoming connections.
while (true) {
$newSock = @socket_accept($sock);
if ($newSock) {
echo 'client connected';
socket_set_nonblock($newSock);
}
}
up
0
gmkarl at gmail dot com
9 years ago
Be aware signal handler functions set with pcntl_signal are not called while a socket is blocking waiting for a connection; the signal is absorbed silently and the handler called when a connection is made.
up
-1
Greg MacLellan
13 years ago
The socket returned by this resource will be non-blocking, regardless of what the listening socket is set to. This is actually true for all FCNTL modifiers.
up
-3
simon at 180solutions dot com
11 years ago
>Accepting a connection using php-sockets:
>
>$fd = socket_create(AF_INET, SOCK_STREAM, 6 /* OR >getprotobyname("TCP")*/);
>
>$PORT = 5000;
>
>socket_bind($fd, "0.0.0.0", $PORT);
>
>while(true)
>{
>$remote_fd = socket_accept($fd);
>
>remote_socket_client_handle($remote_fd);
>
>}
>
>It is simple!
This example doesn't work. You have to call socket_listen($fd) after your bind in order to accept incoming connections.
Simon
To Top
|
__label__pos
| 0.889471 |
Category:
What Is a Fax Viewer?
Article Details
• Written By: Alex Newth
• Edited By: Angela B.
• Last Modified Date: 25 October 2019
• Copyright Protected:
2003-2019
Conjecture Corporation
• Print this Article
Free Widgets for your Site/Blog
Scientists use the term "boring billion" to describe when evolution stalled and life on Earth was basically slime. more...
November 12 , 1927 : Joseph Stalin became the leader of the Soviet Union. more...
A fax viewer is a computer program made for viewing electronic fax images. Unless a fax machine is connected to the computer or wirelessly connected to the Internet, it may be difficult or impossible for the fax viewer to obtain a fax image. One common function of this viewer is to allow users to add notes to an electronic fax file. This program typically will have some basic image processing functions, such as rotating the image or changing colors. While not true with every viewer, most will encode fax images into tagged image file format (TIFF), because these images are easily faxed.
Many fax machines are just connected to a phone line, which allows them to send faxes to other fax machines. While this is enough for basic fax functioning, a fax viewer will usually be unable to obtain the file being faxed, because these machines have no connection to the computer. For the viewer to get the image, it must be sent from a fax machine that is connected to a computer or from a fax machine that sends out a wireless signal that can be picked up by the computer.
Ad
Annotations on a fax document are commonly used to clarify ideas or to fix minor spelling mistakes, but handmade annotations may look sloppy and illegible. Fax viewer programs often have an annotation feature that can add these notes electronically. This commonly makes the notes easier to read, because they are written in a clear computer font, and it may be easier to organize the annotations.
Most fax viewer programs also will come with basic image processing tools so the user can make some changes to the file. For example, these programs may have rotating functions, they may be able to change how wide the text is, and they typically can add colors. Colors may not appear if this file is sent to a black and white fax machine but, if a word or segment is highlighted, this will typically show up as a dull gray that helps emphasize a section.
The majority of fax viewer programs are made to encode images into TIFF files, or to understand only TIFF images. This is because TIFF is the most commonly used image format for faxing, because the characters can be easily recognized, this image format normally has good quality, and the memory compression makes the files lightweight. At the same time, some fax viewers may be able to view images in other formats.
Ad
You might also Like
Recommended
Discuss this Article
Post your comments
Post Anonymously
Login
username
password
forgot password?
Register
username
password
confirm
email
|
__label__pos
| 0.824046 |
Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:
I'm trying to check if a key is pressed without focus on any sort of field.
The goal is to allow users to press left and right arrow to get to the next image. There is no need for them to click into any text field or anything... just simply press those keys to scroll to the next or last image.
Like:
function keyEvent(e) {
if(e.keyCode == 39) {
run some code to get next image
}
else if (e.keyCode == 37) {
run some code to get last image
}
}
It seems like jquery always needs a "selector", as though I need to bind it to a field or something.
$('input[type=text]').on('keyup', function(e) {
if (e.which == 39) {
run some code
} });
Any ideas?
EDIT:
I have this script in my viewimage.php file body... the javascript still isn't running on page load:
<script type="text/javascript">
$(document).ready(function() {
$(document).keydown(function (e) {
if (e.which == 39) {
alert("39");
}
});
});
</script>
Thank you
share|improve this question
The question seems ambiguous to me. The first statement implies that you're trying to make the arrow keys move between pages without breaking text input functionality, but the code you posted below does exactly the opposite. One way or another, you have enough answers to make it work both ways. – Fabrício Matté Oct 10 '12 at 21:05
6 Answers 6
up vote 6 down vote accepted
$(document).ready(function() {
$(document).keydown(function(e) {
e.preventDefault();
if (e.which == 13) {
// Whatever...
}
});
});
share|improve this answer
I have that inside <script type="text/javascript></script> tags inside page.php template. Why won't the code run when I load page.php? – Growler Oct 10 '12 at 20:54
1
is it inside $(document).ready(function() { }); ? – castillo.io Oct 10 '12 at 20:55
no. Does it need to be? – Growler Oct 10 '12 at 21:00
yes :) give it a try. – castillo.io Oct 10 '12 at 21:03
2
Check if jQuery is correctly included above your script. – Fabrício Matté Oct 10 '12 at 21:20
Add the listener to the document.
$(document).on("keyup", function (e) {
console.log(e.keyCode);
});
share|improve this answer
Not sure if I'm the only one reading the question correctly or the only one reading it wrong but: "if a key is pressed without focus on any sort of field", if you bind a handler at document level, any keypress on an input field will bubble up to document level. – Fabrício Matté Oct 10 '12 at 20:58
Bind the keyup (or press or down) to the body, document, or window. Use any or all (belt+suspenders) of them.
$('body',document,window).on('keyup', function(e) {
if (e.which == 13) {
e.preventDefault();
console.log('enter');
}
});
share|improve this answer
Use $(document).on() or $(window).on()
share|improve this answer
Surprisingly, this had better support for pages without any focus than did the .keypress, .keyup, or .keydown methods for handling those events. – cjbarth Jul 10 '14 at 14:01
I'm trying to check if a key is pressed without focus on any sort of field.
If by field you mean input/textearea/select elements, all you have to do is attach a handler to the document and cancel the aforementioned handler if the event target is an input element:
$(document).on('keyup', function(e) {
if ($(e.target).is('input, textarea, select')) return;
if (e.which == 39) {
console.log('move foward');
}
});
Fiddle
share|improve this answer
First off, keypress is safer I think. I've heard that keyup and keydown get missed in some browsers.
I got that backwards... keydown is safest.
The answer to your question is to bind the document:
$(document).on('keydown', function(){
...
});
share|improve this answer
1
It is the other way around. Firefox doesn't fire the keypress event for arrow keys, but all browsers fire it for keydown/keyup. – Fabrício Matté Oct 10 '12 at 20:52
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.899775 |
Source
SCons / src / engine / SCons / Tool / link.py
"""SCons.Tool.link
Tool-specific initialization for the generic Posix linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Defaults
import SCons.Tool
import SCons.Util
import SCons.Warnings
from SCons.Tool.FortranCommon import isfortran
cplusplus = __import__('c++', globals(), locals(), [])
issued_mixed_link_warning = False
def smart_link(source, target, env, for_signature):
has_cplusplus = cplusplus.iscplusplus(source)
has_fortran = isfortran(env, source)
if has_cplusplus and has_fortran:
global issued_mixed_link_warning
if not issued_mixed_link_warning:
msg = "Using $CXX to link Fortran and C++ code together.\n\t" + \
"This may generate a buggy executable if the '%s'\n\t" + \
"compiler does not know how to deal with Fortran runtimes."
SCons.Warnings.warn(SCons.Warnings.FortranCxxMixWarning,
msg % env.subst('$CXX'))
issued_mixed_link_warning = True
return '$CXX'
elif has_fortran:
return '$FORTRAN'
elif has_cplusplus:
return '$CXX'
return '$CC'
def shlib_emitter(target, source, env):
for tgt in target:
tgt.attributes.shared = 1
return (target, source)
def generate(env):
"""Add Builders and construction variables for gnulink to an Environment."""
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['SHLINK'] = '$LINK'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
env['SHLINKCOM'] = '$SHLINK -o $TARGET $SHLINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
# don't set up the emitter, cause AppendUnique will generate a list
# starting with None :-(
env.Append(SHLIBEMITTER = [shlib_emitter])
env['SMARTLINK'] = smart_link
env['LINK'] = "$SMARTLINK"
env['LINKFLAGS'] = SCons.Util.CLVar('')
# __RPATH is only set to something ($_RPATH typically) on platforms that support it.
env['LINKCOM'] = '$LINK -o $TARGET $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
env['LIBDIRPREFIX']='-L'
env['LIBDIRSUFFIX']=''
env['_LIBFLAGS']='${_stripixes(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, LIBPREFIXES, LIBSUFFIXES, __env__)}'
env['LIBLINKPREFIX']='-l'
env['LIBLINKSUFFIX']=''
if env['PLATFORM'] == 'hpux':
env['SHLIBSUFFIX'] = '.sl'
elif env['PLATFORM'] == 'aix':
env['SHLIBSUFFIX'] = '.a'
# For most platforms, a loadable module is the same as a shared
# library. Platforms which are different can override these, but
# setting them the same means that LoadableModule works everywhere.
SCons.Tool.createLoadableModuleBuilder(env)
env['LDMODULE'] = '$SHLINK'
# don't set up the emitter, cause AppendUnique will generate a list
# starting with None :-(
env.Append(LDMODULEEMITTER='$SHLIBEMITTER')
env['LDMODULEPREFIX'] = '$SHLIBPREFIX'
env['LDMODULESUFFIX'] = '$SHLIBSUFFIX'
env['LDMODULEFLAGS'] = '$SHLINKFLAGS'
env['LDMODULECOM'] = '$LDMODULE -o $TARGET $LDMODULEFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
def exists(env):
# This module isn't really a Tool on its own, it's common logic for
# other linkers.
return None
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
__label__pos
| 0.766559 |
26
$\begingroup$
At the moment I am trying to construct a bifurcation diagram of the iterative function $f(x)=$ $ax-1.1975x^3$. I've scoured the internet for pre-made bifurcation diagrams and found many (mostly of the logistic map). However, as the code is quite complicated I am not sure how to edit the code so that it deals with my function instead of the logistic one. Would anyone have a general template for the code to create a bifurcation diagram of a function? Ideally, I would like to have $a$ on the x-axis and equilibrium values on the y-axis.
$\endgroup$
45
$\begingroup$
There are two aspects of this question that distinguish it from previous questions:
1. The request for a general template, as opposed to just a single example.
2. The fact that the given example is a polynomial of degree three, whereas as opposed to the quadratic examples which appear in many places, including Stan's book.
To deal with the first issue, in part, let's simply define the function and then refer only to that definition throughout the code.
f[a_][x_] := a*x - 1.19 x^3;
A well known and important fact in dynamics is that each attractive orbit must attract at least one critical point. Thus, to detect attractive behavior for a given $a$, we should iterate from each critical point. Let's find the critical points in terms of $a$.
cps[a_] = x /. Quiet[Solve[D[f[a][x], x] == 0, x],
Solve::ratnz]
enter image description here
Next, given a parameter value $a$ and critical point cp, we need to find the resulting critical orbit, after dropping some transient behavior. Then we write a function points which does this for each critical point.
criticalOrbits[a_, cp_] := Module[{try},
If[Head[cp] === Real,
try = NestWhileList[f[a], cp, Abs[#] < 100 &, 1, 500];
If[Abs[Last[try]] >= 100, try = {},
try = Drop[{a, #} & /@ try, 100]
],{}]];
points[k_] := Partition[Flatten[Table[criticalOrbits[a, cps[a][[k]]],
{a, -2, 4, 0.002}]], 2]
A little experimentation shows that a natural range for the parameter $a$ would be $0$ to $3$. I've allowed $a$ to range from $-2$ to $4$ to illustrate the fact that the code takes care to exit gracefully if given a divergent orbit or non-real critical point is input - necessary, if we would like this to work with a variety of functions.
Finally, we generate the image using color to differentiate the orbits of the critical points.
Graphics[{Opacity[0.02], PointSize[0.002],
Table[{ColorData[1, k], Point[points[k]]},
{k, 1, Length[cps[a]]}]}, Frame -> True]
enter image description here
| improve this answer | |
$\endgroup$
• $\begingroup$ From page 207 of Wagon's book: "Note that BifurcationPlot was written so that we can use any function in place of $x(1-x)$..." $\endgroup$ – J. M.'s technical difficulties Oct 19 '12 at 13:15
• 1
$\begingroup$ @J.M. I don't have the text handy but I actually collaborated with Stan on that chapter and related material, although I'm only credited in the complex dynamics chapter. I don't recall the text dealing with multiple critical points, which it must do to work as advertised. I certainly could be mistaken, though, and will look at a copy a bit later today. $\endgroup$ – Mark McClure Oct 19 '12 at 13:32
• 1
$\begingroup$ Yes, I saw your name in the bibliography. :) If memory serves, the version in the second edition indeed is unable to cope with things more complicated than the good ol' logistic map, but the new edition seems to imply that things have changed... $\endgroup$ – J. M.'s technical difficulties Oct 19 '12 at 13:39
• $\begingroup$ @J.M. Ahh, I'm thinking third edition. Again, I'll check in a bit. $\endgroup$ – Mark McClure Oct 19 '12 at 13:46
• 1
$\begingroup$ @J.M. Having looked into this further, I stand by my assertion that Stan's code is not ready to accept a cubic with parameter. I quite literally sat down with him, opened up the notebook file that forms that chapter in his book, and tried it. Boom. $\endgroup$ – Mark McClure Oct 19 '12 at 22:41
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.750757 |
Logo Search packages:
Sourcecode: libnl version File versions Download package
utils.c
/*
* lib/utils.c Utility Functions
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Copyright (c) 2003-2005 Thomas Graf <[email protected]>
*/
/**
* @defgroup utils Utilities
* @{
*/
#include <netlink-local.h>
#include <netlink/netlink.h>
#include <netlink/utils.h>
#include <linux/socket.h>
/**
* Debug level
*/
00025 int nl_debug = 0;
/**
* @name Error Code Helpers
* @{
*/
static char *errbuf;
static int nlerrno;
/** @cond SKIP */
int __nl_error(int err, const char *file, unsigned int line, const char *func,
const char *fmt, ...)
{
char *user_err;
va_list args;
if (errbuf) {
free(errbuf);
errbuf = NULL;
}
nlerrno = err;
if (fmt) {
va_start(args, fmt);
vasprintf(&user_err, fmt, args);
va_end(args);
}
#ifdef VERBOSE_ERRORS
asprintf(&errbuf, "%s:%u:%s: %s (errno = %s)",
file, line, func, fmt ? user_err : "", strerror(err));
#else
asprintf(&errbuf, "%s (errno = %s)",
fmt ? user_err : "", strerror(err));
#endif
if (fmt)
free(user_err);
return -err;
}
int nl_get_errno(void)
{
return nlerrno;
}
/** @endcond */
/**
* Return error message for an error code
* @return error message
*/
00080 char *nl_geterror(void)
{
return errbuf ? : "Success\n";
}
/** @} */
/**
* @name Unit Pretty-Printing
* @{
*/
/**
* Cancel down a byte counter
* @arg l byte counter
* @arg unit destination unit pointer
*
* Cancels down a byte counter until it reaches a reasonable
* unit. The chosen unit is assigned to \a unit.
*
* @return The cancelled down byte counter in the new unit.
*/
00102 double nl_cancel_down_bytes(unsigned long long l, char **unit)
{
if (l >= 1099511627776LL) {
*unit = "TiB";
return ((double) l) / 1099511627776LL;
} else if (l >= 1073741824) {
*unit = "GiB";
return ((double) l) / 1073741824;
} else if (l >= 1048576) {
*unit = "MiB";
return ((double) l) / 1048576;
} else if (l >= 1024) {
*unit = "KiB";
return ((double) l) / 1024;
} else {
*unit = "B";
return (double) l;
}
}
/**
* Cancel down a bit counter
* @arg l bit counter
* @arg unit destination unit pointer
*
* Cancels downa bit counter until it reaches a reasonable
* unit. The chosen unit is assigned to \a unit.
*
* @return The cancelled down bit counter in the new unit.
*/
00132 double nl_cancel_down_bits(unsigned long long l, char **unit)
{
if (l >= 1099511627776ULL) {
*unit = "Tbit";
return ((double) l) / 1099511627776ULL;
} else if (l >= 1073741824) {
*unit = "Gbit";
return ((double) l) / 1073741824;
} else if (l >= 1048576) {
*unit = "Mbit";
return ((double) l) / 1048576;
} else if (l >= 1024) {
*unit = "Kbit";
return ((double) l) / 1024;
} else {
*unit = "bit";
return (double) l;
}
}
/**
* Cancel down a micro second value
* @arg l micro seconds
* @arg unit destination unit pointer
*
* Cancels down a microsecond counter until it reaches a
* reasonable unit. The chosen unit is assigned to \a unit.
*
* @return The cancelled down microsecond in the new unit
*/
00163 double nl_cancel_down_us(uint32_t l, char **unit)
{
if (l >= 1000000) {
*unit = "s";
return ((double) l) / 1000000;
} else if (l >= 1000) {
*unit = "ms";
return ((double) l) / 1000;
} else {
*unit = "us";
return (double) l;
}
}
/** @} */
/**
* @name Generic Unit Translations
* @{
*/
/**
* Convert a character string to a size
* @arg str size encoded as character string
*
* Converts the specified size as character to the corresponding
* number of bytes.
*
* Supported formats are:
* - b,kb/k,m/mb,gb/g for bytes
* - bit,kbit/mbit/gbit
*
* @return The number of bytes or -1 if the string is unparseable
*/
00197 long nl_size2int(const char *str)
{
char *p;
long l = strtol(str, &p, 0);
if (p == str)
return -1;
if (*p) {
if (!strcasecmp(p, "kb") || !strcasecmp(p, "k"))
l *= 1024;
else if (!strcasecmp(p, "gb") || !strcasecmp(p, "g"))
l *= 1024*1024*1024;
else if (!strcasecmp(p, "gbit"))
l *= 1024*1024*1024/8;
else if (!strcasecmp(p, "mb") || !strcasecmp(p, "m"))
l *= 1024*1024;
else if (!strcasecmp(p, "mbit"))
l *= 1024*1024/8;
else if (!strcasecmp(p, "kbit"))
l *= 1024/8;
else if (!strcasecmp(p, "bit"))
l /= 8;
else if (strcasecmp(p, "b") != 0)
return -1;
}
return l;
}
/**
* Convert a character string to a probability
* @arg str probability encoded as character string
*
* Converts the specified probability as character to the
* corresponding probability number.
*
* Supported formats are:
* - 0.0-1.0
* - 0%-100%
*
* @return The probability relative to NL_PROB_MIN and NL_PROB_MAX
*/
00239 long nl_prob2int(const char *str)
{
char *p;
double d = strtod(str, &p);
if (p == str)
return -1;
if (d > 1.0)
d /= 100.0f;
if (d > 1.0f || d < 0.0f)
return -1;
if (*p && strcmp(p, "%") != 0)
return -1;
return rint(d * NL_PROB_MAX);
}
/** @} */
/**
* @name Time Translations
* @{
*/
#ifdef USER_HZ
static uint32_t user_hz = USER_HZ;
#else
static uint32_t user_hz = 100;
#endif
static double ticks_per_usec = 1.0f;
/* Retrieves the configured HZ and ticks/us value in the kernel.
* The value is cached. Supported ways of getting it:
*
* 1) environment variable
* 2) /proc/net/psched and sysconf
*
* Supports the environment variables:
* PROC_NET_PSCHED - may point to psched file in /proc
* PROC_ROOT - may point to /proc fs */
static void __init get_psched_settings(void)
{
char name[FILENAME_MAX];
FILE *fd;
int got_hz = 0, got_tick = 0;
if (getenv("HZ")) {
long hz = strtol(getenv("HZ"), NULL, 0);
if (LONG_MIN != hz && LONG_MAX != hz) {
user_hz = hz;
got_hz = 1;
}
}
if (!got_hz)
user_hz = sysconf(_SC_CLK_TCK);
if (getenv("TICKS_PER_USEC")) {
double t = strtod(getenv("TICKS_PER_USEC"), NULL);
ticks_per_usec = t;
got_tick = 1;
}
if (getenv("PROC_NET_PSCHED"))
snprintf(name, sizeof(name), "%s", getenv("PROC_NET_PSCHED"));
else if (getenv("PROC_ROOT"))
snprintf(name, sizeof(name), "%s/net/psched",
getenv("PROC_ROOT"));
else
strncpy(name, "/proc/net/psched", sizeof(name) - 1);
if ((fd = fopen(name, "r"))) {
uint32_t tick, us, nom;
int r = fscanf(fd, "%08x%08x%08x%*08x", &tick, &us, &nom);
if (4 == r && nom == 1000000 && !got_tick)
ticks_per_usec = (double)tick/(double)us;
fclose(fd);
}
}
/**
* Return the value of HZ
*/
00332 int nl_get_hz(void)
{
return user_hz;
}
/**
* Convert micro seconds to ticks
* @arg us micro seconds
* @return number of ticks
*/
00343 uint32_t nl_us2ticks(uint32_t us)
{
return us * ticks_per_usec;
}
/**
* Convert ticks to micro seconds
* @arg ticks number of ticks
* @return microseconds
*/
00354 uint32_t nl_ticks2us(uint32_t ticks)
{
return ticks / ticks_per_usec;
}
long nl_time2int(const char *str)
{
char *p;
long l = strtol(str, &p, 0);
if (p == str)
return -1;
if (*p) {
if (!strcasecmp(p, "min") == 0 || !strcasecmp(p, "m"))
l *= 60;
else if (!strcasecmp(p, "hour") || !strcasecmp(p, "h"))
l *= 60*60;
else if (!strcasecmp(p, "day") || !strcasecmp(p, "d"))
l *= 60*60*24;
else if (strcasecmp(p, "s") != 0)
return -1;
}
return l;
}
/**
* Convert milliseconds to a character string
* @arg msec number of milliseconds
* @arg buf destination buffer
* @arg len buffer length
*
* Converts milliseconds to a character string split up in days, hours,
* minutes, seconds, and milliseconds and stores it in the specified
* destination buffer.
*
* @return The destination buffer.
*/
00392 char * nl_msec2str(uint64_t msec, char *buf, size_t len)
{
int i, split[5];
char *units[] = {"d", "h", "m", "s", "msec"};
#define _SPLIT(idx, unit) if ((split[idx] = msec / unit) > 0) msec %= unit
_SPLIT(0, 86400000); /* days */
_SPLIT(1, 3600000); /* hours */
_SPLIT(2, 60000); /* minutes */
_SPLIT(3, 1000); /* seconds */
#undef _SPLIT
split[4] = msec;
memset(buf, 0, len);
for (i = 0; i < ARRAY_SIZE(split); i++) {
if (split[i] > 0) {
char t[64];
snprintf(t, sizeof(t), "%s%d%s",
strlen(buf) ? " " : "", split[i], units[i]);
strncat(buf, t, len - strlen(buf) - 1);
}
}
return buf;
}
/** @} */
/**
* @name Link Layer Protocol Translations
* @{
*/
static struct trans_tbl llprotos[] = {
{0, "generic"},
__ADD(ARPHRD_ETHER,ether)
__ADD(ARPHRD_EETHER,eether)
__ADD(ARPHRD_AX25,ax25)
__ADD(ARPHRD_PRONET,pronet)
__ADD(ARPHRD_CHAOS,chaos)
__ADD(ARPHRD_IEEE802,ieee802)
__ADD(ARPHRD_ARCNET,arcnet)
__ADD(ARPHRD_APPLETLK,atalk)
__ADD(ARPHRD_DLCI,dlci)
__ADD(ARPHRD_ATM,atm)
__ADD(ARPHRD_METRICOM,metricom)
__ADD(ARPHRD_IEEE1394,ieee1394)
#ifdef ARPHRD_EUI64
__ADD(ARPHRD_EUI64,eui64)
#endif
__ADD(ARPHRD_INFINIBAND,infiniband)
__ADD(ARPHRD_SLIP,slip)
__ADD(ARPHRD_CSLIP,cslip)
__ADD(ARPHRD_SLIP6,slip6)
__ADD(ARPHRD_CSLIP6,cslip6)
__ADD(ARPHRD_RSRVD,rsrvd)
__ADD(ARPHRD_ADAPT,adapt)
__ADD(ARPHRD_ROSE,rose)
__ADD(ARPHRD_X25,x25)
#ifdef ARPHRD_HWX25
__ADD(ARPHRD_HWX25,hwx25)
#endif
__ADD(ARPHRD_PPP,ppp)
__ADD(ARPHRD_HDLC,hdlc)
__ADD(ARPHRD_LAPB,lapb)
__ADD(ARPHRD_DDCMP,ddcmp)
__ADD(ARPHRD_RAWHDLC,rawhdlc)
__ADD(ARPHRD_TUNNEL,ipip)
__ADD(ARPHRD_TUNNEL6,tunnel6)
__ADD(ARPHRD_FRAD,frad)
__ADD(ARPHRD_SKIP,skip)
__ADD(ARPHRD_LOOPBACK,loopback)
__ADD(ARPHRD_LOCALTLK,localtlk)
__ADD(ARPHRD_FDDI,fddi)
__ADD(ARPHRD_BIF,bif)
__ADD(ARPHRD_SIT,sit)
__ADD(ARPHRD_IPDDP,ip/ddp)
__ADD(ARPHRD_IPGRE,gre)
__ADD(ARPHRD_PIMREG,pimreg)
__ADD(ARPHRD_HIPPI,hippi)
__ADD(ARPHRD_ASH,ash)
__ADD(ARPHRD_ECONET,econet)
__ADD(ARPHRD_IRDA,irda)
__ADD(ARPHRD_FCPP,fcpp)
__ADD(ARPHRD_FCAL,fcal)
__ADD(ARPHRD_FCPL,fcpl)
__ADD(ARPHRD_FCFABRIC,fcfb_0)
__ADD(ARPHRD_FCFABRIC+1,fcfb_1)
__ADD(ARPHRD_FCFABRIC+2,fcfb_2)
__ADD(ARPHRD_FCFABRIC+3,fcfb_3)
__ADD(ARPHRD_FCFABRIC+4,fcfb_4)
__ADD(ARPHRD_FCFABRIC+5,fcfb_5)
__ADD(ARPHRD_FCFABRIC+6,fcfb_6)
__ADD(ARPHRD_FCFABRIC+7,fcfb_7)
__ADD(ARPHRD_FCFABRIC+8,fcfb_8)
__ADD(ARPHRD_FCFABRIC+9,fcfb_9)
__ADD(ARPHRD_FCFABRIC+10,fcfb_10)
__ADD(ARPHRD_FCFABRIC+11,fcfb_11)
__ADD(ARPHRD_FCFABRIC+12,fcfb_12)
__ADD(ARPHRD_IEEE802_TR,tr)
__ADD(ARPHRD_IEEE80211,ieee802.11)
#ifdef ARPHRD_IEEE80211_PRISM
__ADD(ARPHRD_IEEE80211_PRISM, ieee802.11_prism)
#endif
#ifdef ARPHRD_VOID
__ADD(ARPHRD_VOID,void)
#endif
};
/**
* Convert a link layer protocol to a character string (Reentrant).
* @arg llproto link layer protocol
* @arg buf destination buffer
* @arg len buffer length
*
* Converts a link layer protocol to a character string and stores
* it in the specified destination buffer.
*
* @return The destination buffer or the type encoded in hexidecimal
* form if no match was found.
*/
00514 char * nl_llproto2str(int llproto, char *buf, size_t len)
{
return __type2str(llproto, buf, len, llprotos, ARRAY_SIZE(llprotos));
}
/**
* Convert a character string to a link layer protocol
* @arg name name of link layer protocol
*
* Converts the provided character string specifying a link layer
* protocl to the corresponding numeric value.
*
* @return link layer protocol or a negative value if none was found.
*/
00528 int nl_str2llproto(const char *name)
{
return __str2type(name, llprotos, ARRAY_SIZE(llprotos));
}
/** @} */
/**
* @name Ethernet Protocol Translations
* @{
*/
static struct trans_tbl ether_protos[] = {
__ADD(ETH_P_LOOP,loop)
__ADD(ETH_P_PUP,pup)
__ADD(ETH_P_PUPAT,pupat)
__ADD(ETH_P_IP,ip)
__ADD(ETH_P_X25,x25)
__ADD(ETH_P_ARP,arp)
__ADD(ETH_P_BPQ,bpq)
__ADD(ETH_P_IEEEPUP,ieeepup)
__ADD(ETH_P_IEEEPUPAT,ieeepupat)
__ADD(ETH_P_DEC,dec)
__ADD(ETH_P_DNA_DL,dna_dl)
__ADD(ETH_P_DNA_RC,dna_rc)
__ADD(ETH_P_DNA_RT,dna_rt)
__ADD(ETH_P_LAT,lat)
__ADD(ETH_P_DIAG,diag)
__ADD(ETH_P_CUST,cust)
__ADD(ETH_P_SCA,sca)
__ADD(ETH_P_RARP,rarp)
__ADD(ETH_P_ATALK,atalk)
__ADD(ETH_P_AARP,aarp)
#ifdef ETH_P_8021Q
__ADD(ETH_P_8021Q,802.1q)
#endif
__ADD(ETH_P_IPX,ipx)
__ADD(ETH_P_IPV6,ipv6)
#ifdef ETH_P_WCCP
__ADD(ETH_P_WCCP,wccp)
#endif
__ADD(ETH_P_PPP_DISC,ppp_disc)
__ADD(ETH_P_PPP_SES,ppp_ses)
__ADD(ETH_P_MPLS_UC,mpls_uc)
__ADD(ETH_P_MPLS_MC,mpls_mc)
__ADD(ETH_P_ATMMPOA,atmmpoa)
__ADD(ETH_P_ATMFATE,atmfate)
__ADD(ETH_P_EDP2,edp2)
__ADD(ETH_P_802_3,802.3)
__ADD(ETH_P_AX25,ax25)
__ADD(ETH_P_ALL,all)
__ADD(ETH_P_802_2,802.2)
__ADD(ETH_P_SNAP,snap)
__ADD(ETH_P_DDCMP,ddcmp)
__ADD(ETH_P_WAN_PPP,wan_ppp)
__ADD(ETH_P_PPP_MP,ppp_mp)
__ADD(ETH_P_LOCALTALK,localtalk)
__ADD(ETH_P_PPPTALK,ppptalk)
__ADD(ETH_P_TR_802_2,tr_802.2)
__ADD(ETH_P_MOBITEX,mobitex)
__ADD(ETH_P_CONTROL,control)
__ADD(ETH_P_IRDA,irda)
__ADD(ETH_P_ECONET,econet)
__ADD(ETH_P_HDLC,hdlc)
};
/**
* Convert a ethernet protocol to a character string (Reentrant).
* @arg eproto ethernet protocol
* @arg buf destination buffer
* @arg len buffer length
*
* Converts a ethernet protocol to a character string and stores
* it in the specified destination buffer.
*
* @return The destination buffer or the type encoded in hexidecimal
* form if no match was found.
*/
00607 char *nl_ether_proto2str(int eproto, char *buf, size_t len)
{
return __type2str(eproto, buf, len, ether_protos,
ARRAY_SIZE(ether_protos));
}
/**
* Convert a character string to a ethernet protocol
* @arg name name of ethernet protocol
*
* Converts the provided character string specifying a ethernet
* protocl to the corresponding numeric value.
*
* @return ethernet protocol or a negative value if none was found.
*/
00622 int nl_str2ether_proto(const char *name)
{
return __str2type(name, ether_protos, ARRAY_SIZE(ether_protos));
}
/** @} */
/** @} */
Generated by Doxygen 1.6.0 Back to index
|
__label__pos
| 0.818139 |
Creating a New Group Policy Object for Devices
10/3/2008
The following procedures show you how to create a new Group Policy object (GPO) for managed Windows Mobile powered devices. To create a new GPO for managed devices, you must first create a new GPO and then add the administrative template (ADM) file for managed devices to the new GPO. During installation of MDM Administrator Tools the ADM template is installed in %windir%\inf, the default windows directory, for example D:\Windows\inf.
For instructions on creating custom ADM template files, see this Microsoft Web site:
https://go.microsoft.com/fwlink/?LinkId=128439.
To have MDM use the custom ADM template, the registry key in the template should take the following format:
KEYNAME "SOFTWARE\Policies\Microsoft\Windows Mobile Settings\<CSPName>\..."
For example, to set a registry value RegValue on the device, the ADM template might look like:
POLICY !!Policy_MyPolicy
PART !!Part_MyPolicy EDITTEXT REQUIRED
KEYNAME "SOFTWARE\Policies\Microsoft\Windows Mobile Settings\Registry\HKLM\Software\MyApp"
VALUENAME "RegValue"
END PART
END POLICY
After you add the ADM file to the GPO, policies related to security, encryption and device management appear in the navigation pane under Computer Configuration/Administrative Templates/Windows Mobile Settings. User related settings are located under User Configuration/Administrative Templates/Windows Mobile Settings.
To create a new Group Policy Object
1. In the Group Policy Management Console, locate the Group Policy Objects node.
2. Right-click Group Policy Objects and then choose New.
3. In the New GPO dialog box, type the name that you want to use to use, and then choose OK.
To add the Administrative Template file to a new Group Policy Object
1. In the Group Policy Management Console, expand Group Policy Objects and then locate the new GPO.
2. Right-click the new GPO and then select Edit.
3. In the Group Policy Object Editor, expand Computer Configuration, and then locate Administrative Templates.
4. Right-click Administrative Templates and then choose Add/Remove Templates.
5. In the Add/Remove Templates dialog box, choose Add.
6. In the Policy Templates dialog box, select the file Mobile.adm, and then choose Open. The selected ADM file appears in the list of current policy templates in the Add/Remove Templates dialog box.
7. In the Add/Remove Templates dialog box, choose Close.
Upgrading Server Builds with ADM File Changes
If you upgrade a server build that has ADM file changes, then existing GPOs might contain out-dated or excess registry keys, which results in the wrong data being sent to the device. Use the following steps in the Group Policy Management Console to resolve this issue.
To upgrade server builds with ADM File Changes
• Manually re-create the GPO; or
• Select Remove a template, and then select Add to force the GPO to pick up a different ADM file; or
• Create a centralized repository for ADM templates.
To create a centralized repository for ADM templates
1. Delete the ADM templates from each Group Policy template (GPT).
2. Place a copy of the latest version of every ADM template (default and customized) into the C:\Windows\Inf folder on every desktop that will administer GPOs.
3. Create a GPO that targets the computers modified in step 2.
4. In the GPO, modify the Always Use Local ADM Files for Group Policy Editor setting to Enabled. This setting is located under Computer Configuration\Administrative Templates\System\Group Policy.
5. Create a GPO that targets the user accounts that have privileges to edit GPOs.
6. In the GPO, modify the Turn off Automatic Updates of ADM files setting to Enabled. This setting is located under User Configuration\Administrative Templates\System\Group Policy.
See Also
Other Resources
|
__label__pos
| 0.85135 |
Saltar al contenido principal
Repara tus cosas
Derecho a Reparar
Partes y Herramientas
I replaced the keyboard keys don't work now
Laptop powers up, works with a wireless mouse & keyboard but the new keyboard keys don't work!! The mouse on the laptop still works.
Contesta esta pregunta Yo también tengo este problema
Es esta una buena pregunta?
Puntuación 0
Agregar un comentario
1 Respuesta
Hello Mike
Was it a "official" keyboard or a third party keyboard?
Did you checked the connector? and the flat cable?
Mouse is a different component of the laptop , has nothing to do with the keyboard ( other connectors)
Fue útil esta respuesta?
Puntuación 0
Comentarios:
Kevin -
Ya it was a Dell keyboard not a knockoff.
I got it figured out... I was getting irritated with it not working and trying multiple ideas to either restart and hold power ect or update driver's ect.
So I looked at the back of the keyboard to see it the main ribbon cable housing was loose like it was on the new keyboard when I saw the lock tab on that ribbon.
I tore it apart again flipped up the new keyboard and that main ribbon cable wasn't locked in. I made sure it was secure and reassembled the laptop, powered it up and problem solved.
Thanks for your answer
- Por
Agregar un comentario
Añadir tu respuesta
Mike estará eternamente agradecido.
Ver Estadísticas:
Ultimas 24 horas: 0
Ultimos 7 días: 0
Ultimos 30 días: 0
Todo El Tiempo: 52
|
__label__pos
| 0.63575 |
Howdy, Stranger!
It looks like you're new here. If you want to get involved, click one of these buttons!
Welcome to the CollectiveAccess support forum! Here the developers and community answer questions related to use of the software. Please include the following information in every new issue posted here:
1. Version of the software that is used, along with browser and version
2. If the issue pertains to Providence, Pawtucket or both
3. What steps you’ve taken to try to resolve the issue
4. Screenshots demonstrating the issue
5. The relevant sections of your installation profile or configuration including the codes and settings defined for your local elements.
If your question pertains to data import or export, please also include:
1. Data sample
2. Your mapping
Answers may be delayed for posts that do not include sufficient information.
Thumbnails for videos
We are testing importing videos into our CollectiveAccess instance. Just wondering if having thumbnails cut from the content is possible (for display in Providence but especially Pawtucket2)? Is there a way to manually upload a cut thumbnail that can be appointed to the video and not as an additional media representation?
Thanks!
Comments
• Hi clovescat,
Yes, there is a metadata element available on the object representation level that allows you to set the thumbnail from a particular timecode. You can also manually upload thumbnails for use in the various derivative images that CA produces.
• edited October 2018
Hello Sofhie
This would be helpful to know more about.
Can you please, be a little more specific on how use the element to set a timecode for preveiw images?
• Sorry, found it
Sign In or Register to comment.
|
__label__pos
| 0.953007 |
What is IdFix tool and how to use it?
IdFix tool is an inevitable tool while deploying Microsoft Azure or Office 365 etc. What it does is, it prepare directory attributes for synchronization with Microsoft cloud services. The tool helps to find any errors on the user objects and help to fix it before it sync it to the Microsoft cloud.
1. Once you have download the tool you can run it on the domain controller. You can follow the installation instructions as per the Microsoft documentation. Once installed launch the tool then click on the Query button to query the user objects and then it will display the errors on the screen.
2. Based on the Error displayed on the tool you can check on this page to fid the fix.
Here is a screenshot from my lab. On the bottom of the tool you will notice the number of users it queried and the number of errors it found.
3. You don’t have to click Apply after each update. Instead, you can fix several errors before you click Apply and IdFix will change them all at the same time. You can sort the errors by error type by clicking ERROR at the top of the column that lists the error types.
4. One strategy is to fix all the errors of the same type; for example, fix all the duplicates first, and apply them. Next, fix the character format errors, and so on. Each time you apply the changes, the IdFix tool creates a separate log file that you can use to undo your changes in case you make a mistake. The transaction log is stored in the folder that you installed IdFix in. C:\Deployment Tools\IdFix by default.
5. After all of your changes are made to the directory, run IdFix again to ensure that the fixes you made didn’t introduce new errors. You can repeat these steps as many times as you need to. It’s a good idea to go through the process a few times before you synchronize.
Here is video explaining the same. Do check it out.
You can download the IdFix tool from here
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.716547 |
Click here to Skip to main content
13,248,562 members (85,322 online)
Rate this:
Please Sign up or sign in to vote.
See more:
Hello everyone
just a quick question I have a javascript client implementation for WCF data services currently where I am required to do partial data updates due to the complexity of the model. I have successfully implemented the Data Services MERGE operation and it seems to work correctly for everything except complex Types. When a merge operation is performed a new instance of the complex type is initialized, the changed values are set correctly but the values that were not affected are reset to default values (because the complex type is re-instantiated). Is there anyway to prevent this behavior within the service?
basically if you have the following EntityModel exposed
class EntityModel
{
public int Id {get; set;}
public ComplexObject Obj {get; set;}
}
class ComplexObject()
{
public string A {get; set;}
public string B {get; set;}
public string C {get; set;}
}
and i do a merge request changing the value of only the B property within the Obj property of my Entity.
OData.request(
{
requestUri: baseUrl + '(' + model.Id + ')',
method: "MERGE",
data: { Id: model.Id, Obj: { B : 'Foo' } }
},
function () {
alert("ok");
},
function (err) {
alert(err.message);
}
How do i ensure the A and C properties maintain their original values ?
Thank You
Posted 10-Jan-12 8:20am
none222153
Updated 10-Jan-12 10:17am
Wendelius364.5K
v3
Comments
killabyte 8-Feb-12 20:32pm
when you change the complex object in your Entity Model do you set the EntityState.Modified on said entity model?
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Print Answers RSS
Top Experts
Last 24hrsThis month
Advertise | Privacy |
Web04 | 2.8.171114.1 | Last Updated 10 Jan 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid
CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100
|
__label__pos
| 0.966465 |
Home Videos Photos Shop
PerezHilton CocoPerez Selena Gomez Kim K. Mariah Carey Trump PerezTV
2 comments to “Facebook Phone In The Works…And It's Named After A Vampire Slayer!”
1. 1
Just more ways for us human beings to distance ourselves from each other and then complain about depression and then get on antidepressants and then get sick from those and dependent and never know how to walk on your own 2 feet w out a pill and be stuck playing on a phone for the rest of your sad lonely life talking to strangers and reading about ppl you'll never meet. And we wonder whats wrong w todays society….I worry for my children sooo much. Man is it gonna be rough on them when they grow up. :( Will they even have REAL friends or only ones from a tiny electronic device?
2. 2
this shit its crazy and odd what the fuk
|
__label__pos
| 0.811723 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
In my scripts, which I am currently making into a package, a number of "global settings" are needed. Currently, these settings are in global variables and were usually changed by editing the script directly. (The script produces entries for a database, and you need to adjust stuff like "author name" and other custom "constant" part of the entries.)
Again, currently I used const_author <- "Meow The Scientist Cat"et al. I can, of course, leave this exactly as is, and export all the global variables, so the user can set them to whatever. However, this is ugly and pollutes the namespace.
What is the standard method in R to make such settings available to the user? Using options()? And at which point in the package should these options be loaded?
Maybe using a function like settingsTemplate(filename) which exports a file with default settings, which the user then can customize; and he has to source the file or loadSettings(filename) before using the scripts?
share|improve this question
1 Answer 1
up vote 5 down vote accepted
You could create something similar to xcms: in zzz.R we call .setXCMSOptions (from init.R upon package loading, where xcms specific options are inserted into the generic BioC options:
getOption("BioC")$xcms
You could provide getter and setter methods for your options.
share|improve this answer
Thanks, that's what I was looking for :) – meow Mar 12 '12 at 8:59
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.659757 |
• Teacher Note: Math in Data Representation
A lot of the exercises in this chapter involve simple arithmetic. If students struggle to do this by hand, a lot can be done using spreadsheets.
Computers are machines that do stuff with information. They let you view, listen, create, and edit information in documents, images, videos, sound, spreadsheets and databases. They let you play games in simulated worlds that don’t really exist except as information inside the computer’s memory and displayed on the screen. They let you compute and calculate with numerical information; they let you send and receive information over networks. Fundamental to all of this is that the computer has to represent that information in some way inside the computer’s memory, as well as storing it on disk or sending it over a network.
To make computers easier to build and keep them reliable, everything is represented using just two values. You may have seen these two values represented as 0 and 1, but on a computer they are represented by anything that can be in two states. For example, in memory a low or high voltage is used to store each 0 or 1. On a magnetic disk it's stored with magnetism (whether a tiny spot on the disk is magnetised north or south).
The idea that everything stored and transmitted in our digital world is stored using just two values might seem somewhat fantastic, but here's an exercise that will give you a little experience using just black and white cards to represent numbers. In the following interactive, click on the last card (on the right) to reveal that it has one dot on it. Now click on the previous card, which should have two dots on it. Before clicking on the next one, how many dots do you predict it will have? Carry on clicking on each card moving left, trying to guess how many dots each has.
The challenge for you now is to find a way to have exactly 22 dots showing (the answer is in the spoiler below). Now try making up other numbers of dots, such as 11, 29 and 19. Is there any number that can't be represented? To test this, try counting up from 0.
• Teacher Note: Patterns in the cards
This exercise comes up again below as an introduction to representing numbers. The card interactive can also be done with physical cards as a change from doing things on a computer.
If students have trouble solving the puzzles, start at the left and ask "Can you use the 16 dots? 8 dots?" and so on. Each one will either be obviously too big, or otherwise it should be used.
With some guidance students should notice patterns, for example, that the one-dot card is coming up every second time (the odd numbers).
• Spoiler: Solution to card puzzles
You may have noticed that each card shows twice as many dots as the one to its right. This is an important pattern in data representation on computers.
The number 22 requires the cards to be "white, black, white, white, black", 11 is "black, white, black, white, white", 29 is "white, white, white, black, white", and 19 is "white, black, black, black, white".
You should have found that any number from 0 to 31 can be represented with 5 cards. Each of the numbers could be communicated using just two words: black and white. For example, 22 dots is "white, black, white, white, black". Or you could decode "black, black, white, white, white" to the number 7. This is the basis of data representation - anything that can have two different states can represent anything on a digital device.
When we write what is stored in a computer on paper, we normally use “0” for one of the states, and “1” for the other state. For example, a piece of computer memory could have the following voltages:
low low high low high high high high low high low low
We could allocate “0” to “low”, and “1” to “high” and write this sequence down as:
0 0 1 0 1 1 1 1 0 1 0 0
While this notation is used extensively, and you may often hear the data being referred to as being “0’s and 1’s”, it is important to remember that a computer does not store 0’s and 1’s; it has no way of doing this. They are just using physical mechanisms such as high and low voltage, north or south polarity, and light or dark materials.
• Jargon Buster: Bits
The use of the two digits 0 and 1 is so common that some of the best known computer jargon is used for them. Since there are only two digits, the system is called binary. The short word for a "binary digit" is made by taking the first two letters and the last letter --- a bit is just a digit that can have two values.
Every file you save, every picture you make, every download, every digital recording, every web page is just a whole lot of bits. These binary digits are what make digital technology digital! And the nature of these digits unlock a powerful world of storing and sharing a wealth of information and entertainment.
Computer scientists don't spend a lot of time reading bits themselves, but knowing how they are stored is really important because it affects the amount of space that data will use, the amount of time it takes to send the data to a friend (as data that takes more space takes longer to send!) and the quality of what is being stored. You may have come across things like "24-bit colour", "128-bit encryption", "32-bit IPv4 addresses" or "8-bit ASCII". Understanding what the bits are doing enables you to work out how much space will be required to get high-quality colour, hard-to-crack secret codes, a unique ID for every device in the world, or text that uses more characters than the usual English alphabet.
This chapter is about some of the different methods that computers use to code different kinds of information in patterns of these bits, and how this affects the cost and quality of what we do on the computer, or even if something is feasible at all.
To begin with, we'll look at Braille. Braille is not actually a way that computers represent data, but is a great introduction to the topic.
• Additional Information: Representing Braille without making holes in paper
When working through the material in this section, a good way to draw braille on paper without having to actually make raised dots is to draw a rectangle with 6 small circles in it, and to colour in the circles that are raised, and not colour in the ones that aren’t raised.
More than 200 years ago a 15-year-old French boy invented a system for representing text using combinations of flat and raised dots on paper so that they could be read by touch. The system became very popular with people who had visual impairment as it provided a relatively fast and reliable way to "read" text without seeing it. Louis Braille's system is an early example of a "binary" representation of data --- there are only two symbols (raised and flat), and yet combinations of them can be used to represent reference books and works of literature. Each character in braille is represented with a cell of 6 dots. Each dot can either be raised or not raised. Different numbers and letters can be made by using different patterns of raised and not raised dots.
Let's work out how many different patterns can be made using the 6 dots in a Braille character. If braille used only 2 dots, there would be 4 patterns. And with 3 dots there would be 8 patterns
You may have noticed that there are twice as many patterns with 3 dots as there are with 2 dots. It turns out that every time you add an extra dot, that gives twice as many patterns, so with 4 dots there are 16 patterns, 5 dots has 32 patterns, and 6 dots has 64 patterns. Can you come up with an explanation as to why this doubling of the number of patterns occurs?
• Spoiler: Why does adding one more dot double the number of possible patterns?
The reason that the number of patterns doubles with each extra dot is that with, say, 3 dots you have 8 patterns, so with 4 dots you can use all the 3-dot patterns with the 4th dot flat, and all of them with it raised. This gives 16 4-dot patterns. And then, you can do the same with one more dot to bring it up to 5 dots. This process can be repeated infinitely.
• Teacher Note: Importance of students understanding why the number of patters double with every dot
This concept is a fundamental one for students to grasp with binary representation: each extra bit doubles the number of values that can be stored. This becomes very important in choosing the right number of bits for a value. For example, a 101-bit encryption key is twice as hard to crack as a 100-bit key, even though it's only 1% larger!
So, Braille, with its 6 dots, can make 64 patterns. That's enough for all the letters of the alphabet, and other symbols too, such as digits and punctuation.
The reason we're looking at Braille in this chapter is because it is a representation using bits. That is, it contains 2 different values (raised and not raised) and contains sequences of these to represent different patterns. The letter m, for example, could be written as 110010, where "1" means raised dot, and "0" means not raised dot (assuming we're reading from left to right and then down). This is the same as how we sometimes use 1's and 0's to show how a computer is representing data.
Braille also illustrates why binary representation is so popular. It would be possible to have three kinds of dot: flat, half raised, and raised. A skilled braille reader could distinguish them, and with three values per dot, you would only need 4 dots to represent 64 patterns. The trouble is that you would need more accurate devices to create the dots, and people would need to be more accurate at sensing them. If a page was squashed, even very slightly, it could leave the information unreadable.
Digital devices almost always use two values (binary) for similar reasons: computer disks and memory can be made cheaper and smaller if they only need to be able to distinguish between two extreme values (such as a high and low voltage), rather than fine-grained distinctions between very subtle differences in voltages. Using ten digits (like we do in our every day decimal counting system) would obviously be too challenging.
• Curiosity: Decimal-based computers
Why are digital systems so hung up on only using two digits? After all, you could do all the same things with a 10 digit system?
As it happens, people have tried to build decimal-based computers, but it's just too hard. Recording a digit between 0 and 9 involves having accurate equipment for reading voltage levels, magnetisation or reflections, and it's a lot easier just to check if it's mainly one way or the other.
There's a more in-depth discussion on why we use binary here:
• Teacher Note: CS Unplugged activity
If you are doing a warm up exercise with the class, the CS Unplugged binary activity http://csunplugged.org/binary-numbers provides scaffolding and can be used to teach concepts around binary numbers using only counting or simple addition. We also have an interactive which emulates the physical binary cards here:
In the chapter we have decided to approach this section by starting with number systems. While this may appear “scary” because of the math, most students should be quite familiar with it as it is first introduced very early in primary school in the form of recognising that numbers are made up of the “ones”, “tens”, “hundreds”, etc, and is further built on until eventually in high school they learn about the exponent notation, i.e. \(541 = 5 \times 10^2 + 4 \times 10^1 + 1 \times 10^0\). As explained in this section, binary numbers are a base 2 number system, rather than the base 10 number system we are all familiar with. The idea of number systems provides a good stepping stone into binary numbers
We are assuming that students already know about base 10 number systems, including the exponent notation. The initial information in this section on them is only intended to trigger recall, rather than actually teaching them the concept.
Less mathematically able students who are really struggling with number systems should be able to skip over it, and instead go directly to making binary numbers in the interactive.
In this section, we will look at how computers represent numbers. To begin with, we'll revise how the base-10 number system that we use every day works, and then look at binary, which is base-2. After that, we'll look at some other charactertistics of numbers that computers must deal with, such as negative numbers and numbers with decimal points.
The number system that humans normally use is in base 10 (also known as decimal). It's worth revising quickly, because binary numbers use the same ideas as decimal numbers, just with fewer digits!
In decimal, the value of each digit in a number depends on its place in the number. For example, in $123, the 3 represents $3, whereas the 1 represents $100. Each place value in a number is worth 10 times more than the place value to its right, i.e. there are the “ones”, the “tens”, the “hundreds”, the “thousands” the “ten thousands”, the “hundred thousands”, the “millions”, and so on. Also, there are 10 different digits (0,1,2,3,4,5,6,7,8,9) that can be at each of those place values.
If you were only able to use one digit to represent a number, then the largest number would be 9. After that, you need a second digit, which goes to the left, giving you the next ten numbers (10, 11, 12... 19). It's because we have 10 digits that each one is worth 10 times as much as the one to its right.
You may have encountered different ways of expressing numbers using “expanded form”. For example, if you want to write the number 90328 in expanded form you might have written it as:
\(90328 = 90000 + 300 + 20 + 8\)
A more sophisticated way of writing it is:
\(90328 = (9 \times 10000) + (0 \times 1000) + (3 \times 100) + (2 \times 10) + (8 \times 1)\)
If you've learnt about exponents, you could write it as \(90328 = (9 \times 10^4) + (0 \times 10^3) + (3 \times 10^2) + (2 \times 10^1) + (8 \times 10^0)\)
Remember that any number to the power of 0 is 1. i.e. the 8 x \(10^0\) is 8, because the \(10^0\) is 1.
The key ideas to notice from this are:
• Decimal has 10 digits -- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
• A place is the place in the number that a digit is, i.e. ones, tens, hundreds, thousands, and so on. For example, in the number 90328, 3 is in the "hundreds" place, 2 is in the "tens" place, and 9 is in the "ten thousands" place.
• Numbers are made with a sequence of digits.
• The right-most digit is the one that's worth the least (in the "ones" place).
• The left-most digit is the one that's worth the most.
• Because we have 10 digits, the digit at each place is worth 10 times as much as the one immediately to the right of it.
All this probably sounds really obvious, but it is worth thinking about consciously, because binary numbers have the same properties.
• Teacher Note: Teaching binary numbers
{panel type="teacher-note" summary="Binary pianos"} The "binary piano" is a simple binary conversion device that can be printed on paper, and enables students to experiment with these concepts physically. It can be downloaded here or as a 4-up version here. These versions have 9 bits; if you want to emphasise that bytes use 8 bits, you can have students ignore the 9th bit (perhaps by sticking it on 0), but it is useful when they want to remember the largest 8-bit value, since they can get it by subtracting one from the value of the 9th bit.
As discussed earlier, computers can only store information using bits, which only have 2 possible states. This means that they cannot represent base 10 numbers using digits 0 to 9, the way we write down numbers in decimal. Instead, they must represent numbers using just 2 digits -- 0 and 1.
Binary works in a very similar way to Decimal, even though it might not initially seem that way. Because there are only 2 digits, this means that each digit is 2 times the value of the one immediately to the right.
• Curiosity: The Denary number system
The base 10 (decimal) system is sometimes called denary, which is more consistent with the the name binary for the base 2 system. The word "denary" also refers to the Roman denarius coin, which was worth ten asses (an "as" was a copper or bronze coin). The term "denary" seems to be used mainly in the UK; in the US, Australia and NZ the term "decimal" is more common.
The interactive below illustrates how this binary number system represents numbers. Have a play around with it to see what patterns you can see.
To ensure you are understanding correctly how to use the interactive, verify that when you enter the binary number 101101 it shows that the decimal representation is 45, that when you enter 100000 it shows that the decimal representation is 32, and when you enter 001010 it shows the decimal representation is 10.
• Teacher Note: Using the binary number interactive
With the interactive, students should discover that they can convert a number by working from left to right through the digits, setting the digit to 1, and resetting it to zero if the total is higher than the number being sought. After converting a few numbers they will start to anticipate what to do. This algorithm is fairly intuitive, and discoverable by quite young students. Discovering it for themselves will give a lot of confidence in their ability to convert numbers. If they need some help, get them to set the left-most bit to one, and ask if the total is too high. If it is, set the bit back to zero, otherwise leave it as one. Then repeat this for each bit from left to right. For example, for the number 37, the first bit gives a total of 32, which isn't too high; setting the second bit brings the total to 48, which is too high, so it stays at zero; the third bit gives a total of 32+8 = 40, which is too high; the fourth bit gives 32+4 = 36, which is ok, so that bit is a 1. The fifth bit would give 38 (too high), and the sixth bit gives the required 37, giving the binary number 100101. This approach is explained for students later in the text, but it's better if they can discover it for themselves.
There are a lot of interactive games for exploring binary numbers. The following one works in a web browser: Cisco Binary game. While there's a limit to the value of being able to make binary conversions, doing a number of them helps student to discover the kinds of patterns that occur in the binary number system.
There is another algorithm for conversion that is often found in textbooks, and it is easier to write a program for, but a little harder for learners. It isn't necessary to explore the concepts of this chapter, but in case a student wants to implement it, the algorithm is to work from right to left; set the right-most bit to one if the decimal number is odd, otherwise set it to zero, then divide the decimal number by 2 (rounding down), and repeat the procedure for the next digit to the left (set it to one if the number is odd, otherwise zero, then divide by 2). This is repeated until the decimal number has been reduced to zero.
Find the representations of 4, 7, 12, and 57 using the interactive.
What is the largest number you can make with the interactive? What is the smallest? Is there any integer value in between the biggest and the smallest that you can’t make? Are there any numbers with more than one representation? Why/ why not?
• Spoiler: Largest and smallest numbers
• 000000 in binary, 0 in decimal is the smallest number.
• 111111 in binary, 63 in decimal is the largest number
• All the integer values (0, 1, 2... 63) in the range can be represented (and there is a unique representation for each one). This is exactly the same as decimal!
• Teacher Note: Understanding unique representations
The question of uniqueness will be challenging for some students. It addresses the idea that every number has a unique binary representation; students who struggle with the reasoning may be prepared to just accept that this is the case. However, the following reasoning introduces the idea: have a student work out a 5-bit binary representation for, say, 12 (which is 01100). The left-most 0 represents the 16; ask if it would be possible to represent 12 if that bit is a 1 (it's not possible because you'd already have 16, which is more than 12). Now consider the next bit (the 1 represents 8). Is it possible to represent 12 without the 8? (No, because the remaining bits only add up to 7). Following on with this reasoning, the student will establish that 12 has to be represented as 01100.
Another way of showing the uniqueness is to work out how many bit combinations there are. For 5 bits, there are two choices for each bit, so 2x2x2x2x2 (i.e. 32) distinct 5-bit binary numbers. Since the 5-bit binary numbers cover the range from 0 to 31, there are 32 numbers, so there's a one-to-one relationship between all possible bit patterns and all numbers they can represent i.e. each number has a unique representation.
You have probably noticed from the interactive that when set to 1, the leftmost bit (the “most significant bit”) adds 32 to the total, the next adds 16, and then the rest add 8, 4, 2, and 1 respectively. When set to 0, a bit does not add anything to the total. So the idea is to make numbers by adding some or all of 32, 16, 8, 4, 2, and 1 together, and each of those numbers can only be included once.
Choose a number less than 61 (perhaps your house number, your age, a friend's age, or the day of the month you were born on), set all the binary digits to zero, and then start with the left-most digit (32), trying out if it should be zero or one. See if you can find a method for converting the number without too much trial and error. Try different numbers until you find a quick way of doing this.
Figure out the binary representation for 23 without using the interactive? What about 4, 0, and 32? Check all your answers using the interactive to verify they are correct.
• Challenge: Counting in binary
Can you figure out a systematic approach to counting in binary? i.e. start with the number 0, then increment it to 1, then 2, then 3, and so on, all the way up to the highest number that can be made with the 7 bits. Try counting from 0 to 16, and see if you can detect a pattern. Hint: Think about how you add 1 to a number in base 10. e.g. how do you work out 7 + 1, 38 + 1, 19 + 1, 99 + 1, 230899999 + 1, etc? Can you apply that same idea to binary?
Using your new knowledge of the binary number system, can you figure out a way to count to higher than 10 using your 10 fingers? What is the highest number you can represent using your 10 fingers? What if you included your 10 toes as well (so you have 20 fingers and toes to count with).
• Spoiler: Counting in binary
A binary number can be incremented by starting at the right and flipping all consecutive bits until a 1 comes up (which will be on the very first bit half of the time).
Counting on fingers in binary means that you can count to 31 on 5 fingers, and 1023 on 10 fingers. There are a number of videos on YouTube of people counting in binary on their fingers. One twist is to wear white gloves with the numbers 16, 8, 4, 2, 1 on the 5 fingers respectively, which makes it easy to work out the value of having certain fingers raised.
The interactive used exactly 6 bits. In practice, we can use as many or as few bits as we need, just like we do with decimal. For example, with 5 bits, the place values would be 16, 8, 4, 2 and 1, so the largest value is 11111 in binary, or 31 in decimal. Representing 14 with 5 bits would give 01110.
• Challenge: Representing numbers with bits
Write representations for the following. If it is not possible to do the representation, put "Impossible".
• Represent 101 with 7 bits
• Represent 28 with 10 bits
• Represent 7 with 3 bits
• Represent 18 with 4 bits
• Represent 28232 with 16 bits
• Spoiler: Answers for above challenge
The answers are (spaces are added to make the answers easier to read, but are not required)
• 101 with 7 bits is: 110 0101
• 28 with 10 bits is: 00 0001 1100
• 7 with 3 bits is: 111
• 18 with 4 bits is: Impossible to represent (not enough bits)
• 28232 with 16 bits is: 0110 1110 0100 1000
An important concept with binary numbers is the range of values that can be represented using a given number of bits. When we have 8 bits the binary numbers start to get useful --- they can represent values from 0 to 255, so it is enough to store someone's age, the day of the month, and so on.
• Jargon Buster: What is a byte?
Groups of 8 bits are so useful that they have their own name: a byte. Computer memory and disk space are usually divided up into bytes, and bigger values are stored using more than one byte. For example, two bytes (16 bits) are enough to store numbers from 0 to 65,535. Four bytes (32 bits) can store numbers up to 4,294,967,295. You can check these numbers by working out the place values of the bits. Every bit that's added will double the range of the number.
In practice, computers store numbers with either 16, 32, or 64 bits. This is because these are full numbers of bytes (a byte is 8 bits), and makes it easier for computers to know where each number starts and stops.
• Curiosity: Binary cakes -- preventing fires
Candles on birthday cakes use the base 1 numbering system, where each place is worth 1 more than the one to its right. For example, the number 3 is 111, and 10 is 1111111111. This can cause problems as you get older --- if you've ever seen a cake with 100 candles on it, you'll be aware that it's a serious fire hazard.
Luckily it's possible to use binary notation for birthday candles --- each candle is either lit or not lit. For example, if you are 18, the binary notation is 10010, and you need 5 candles (with only two of them lit).
There's a video on using binary notation for counting up to 1023 on your hands, as well as using it for birthday cakes.
It
It's a lot smarter to use binary notation on candles for birthdays as you get older, as you don't need as many candles.
Most of the time binary numbers are stored electronically, and we don't need to worry about making sense of them. But sometimes it's useful to be able to write down and share numbers, such as the unique identifier assigned to each digital device (MAC address), or the colours specified in an HTML page.
Writing out long binary numbers is tedious --- for example, suppose you need to copy down the 16-bit number 0101001110010001. A widely used shortcut is to break the number up into 4-bit groups (in this case, 0101 0011 1001 0001), and then write down the digit that each group represents (giving 5391). There's just one small problem: each group of 4 bits can go up to 1111, which is 15, and the digits only go up to 9.
The solution is simple: we introduce symbols for the digits from 1010 (10) to 1111 (15), which are just the letters A to F. So, for example, the 16-bit binary number 1011 1000 1110 0001 can be written more concisely as B8E1. The "B" represents the binary 1011, which is the decimal number 11, and the E represents binary 1110, which is decimal 14.
Because we now have 16 digits, this representation is base 16, and known as hexadecimal (or hex for short). Converting between binary and hexadecimal is very simple, and that's why hexadecimal is a very common way of writing down large binary numbers.
Here's a full table of all the 4-bit numbers and their hexadecimal digit equivalent:
Binary Hex
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 8
1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
1111 F
For example, the largest 8-bit binary number is 11111111. This can be written as FF in hexadecimal. Both of those representations mean 255 in our conventional decimal system (you can check that by converting the binary number to decimal).
Which notation you use will depend on the situation; binary numbers represent what is actually stored, but can be confusing to read and write; hexadecimal numbers are a good shorthand of the binary; and decimal numbers are used if you're trying to understand the meaning of the number or doing normal math. All three are widely used in computer science.
It is important to remember though, that computers only represent numbers using binary. They cannot represent numbers directly in decimal or hexadecimal.
A common place that numbers are stored on computers is in spreadsheets or databases. These can be entered either through a spreadsheet program or database program, through a program you or somebody else wrote, or through additional hardware such as sensors, collecting data such as temperatures, air pressure, or ground shaking.
Some of the things that we might think of as numbers, such as the telephone number (03) 555-1234, aren't actually stored as numbers, as they contain important characters (like dashes and spaces) as well as the leading 0 which would be lost if it was stored as a number (the above number would come out as 35551234, which isn't quite right). These are stored as text, which is discussed in the next section.
On the other hand, things that don't look like a number (such as "30 January 2014") are often stored using a value that is converted to a format that is meaningful to the reader (try typing two dates into Excel, and then subtract one from the other --- the result is a useful number). In the underlying representation, a number is used. Program code is used to translate the underlying representation into a meaningful date on the user interface.
• Curiosity: More on date representation
The difference between two dates in Excel is the number of days between them; the date itself (as in many systems) is stored as the amount of time elapsed since a fixed date (such as 1 January 1900). You can test this by typing a date like "1 January 1850" --- chances are that it won't be formatted as a normal date. Likewise, a date sufficiently in the future may behave strangely due to the limited number of bits available to store the date.
Numbers are used to store things as diverse as dates, student marks, prices, statistics, scientific readings, sizes and dimensions of graphics.
The following issues need to be considered when storing numbers on a computer
• What range of numbers should be able to be represented?
• How do we handle negative numbers?
• How do we handle decimal points or fractions?
In practice, we need to allocate a fixed number of bits to a number, before we know how big the number is. This is often 32 bits or 64 bits, although can be set to 16 bits, or even 128 bits, if needed. This is because a computer has no way of knowing where a number starts and ends, otherwise.
Any system that stores numbers needs to make a compromise between the number of bits allocated to store the number, and the range of values that can be stored.
In some systems (like the Java and C programming languages and databases) it's possible to specify how accurately numbers should be stored; in others it is fixed in advance (such as in spreadsheets).
Some are able to work with arbitrarily large numbers by increasing the space used to store them as necessary (e.g. integers in the Python programming language). However, it is likely that these are still working with a multiple of 32 bits (e.g. 64 bits, 96 bits, 128 bits, 160 bits, etc). Once the number is too big to fit in 32 bits, the computer would reallocate it to have up to 64 bits.
In some programming languages there isn't a check for when a number gets too big (overflows). For example, if you have an 8-bit number using two's complement, then 01111111 is the largest number (127), and if you add one without checking, it will change to 10000000, which happens to be the number -128. This can cause serious problems if not checked for, and is behind a variant of the Y2K problem, called the Year 2038 problem, involving a 32-bit number overflowing for dates on Tuesday, 19 January 2038.
On tiny computers, such as those embedded inside your car, washing machine, or a tiny sensor that is barely larger than a grain of sand, we might need to specify more precisely how big a number needs to be. While computers prefer to work with chunks of 32 bits, we could write a program (as an example for an earthquake sensor) that knows the first 7 bits are the lattitude, the next 7 bits are the longitude, the next 10 bits are the depth, and the last 8 bits are the amount of force.
Even on standard computers, it is important to think carefully about the number of bits you will need. For example, if you have a field in your database that could be either "0", "1", "2", or "3" (perhaps representing the four bases that can occur in a DNA sequence), and you used a 64 bit number for every one, that will add up as your database grows. If you have 10,000,000 items in your database, you will have wasted 62 bits for each one (only 2 bits is needed to represent the 4 numbers in the example), a total of 620,000,000 bits, which is around 74 MB. If you are doing this a lot in your database, that will really add up -- human DNA has about 3 billion base pairs in it, so it's incredibly wasteful to use more than 2 bits for each one.
And for applications such as Google Maps, which are storing an astronomical amount of data, wasting space is not an option at all!
• Challenge: How many bits will you need?
It is really useful to know roughly how many bits you will need to represent a certain value. Have a think about the following scenarios, and choose the best number of bits out of the options given. You want to ensure that the largest possible number will fit within the number of bits, but you also want to ensure that you are not wasting space.
1. Storing the day of the week
• a) 1 bit
• b) 4 bits
• c) 8 bits
• d) 32 bits
2. Storing the number of people in the world
• a) 16 bits
• b) 32 bits
• c) 64 bits
• d) 128 bits
3. Storing the number of roads in New Zealand
• a) 16 bits
• b) 32 bits
• c) 64 bits
• d) 128 bits
4. Storing the number of stars in the universe
• a) 16 bits
• b) 32 bits
• c) 64 bits
• d) 128 bits
• Spoiler: Answers for above challenge
1. b (actually, 3 bits is enough as it gives 8 values, but amounts that fit evenly into 8-bit bytes are easier to work with)
2. c (32 bits is slightly too small, so you will need 64 bits)
3. c (This is a challenging question, but one a database designer would have to think about. There's about 94,000 km of roads in NZ, so if the average length of a road was 1km, there would be too many roads for 16 bits. Either way, 32 bits would be a safe bet.)
4. d (Even 64 bits is not enough, but 128 bits is plenty! Remember that 128 bits isn't twice the range of 64 bits.)
The binary number representation we have looked at so far allows us to represent positive numbers only. In practice, we will want to be able to represent negative numbers as well, such as when the balance of an account goes to a negative amount, or the temperature falls below zero. In our normal representation of base 10 numbers, we represent negative numbers by putting a minus sign in front of the number. But in binary, is it this simple?
We will look at two possible approaches: Adding a simple sign bit, much like we do for decimal, and then a more useful system called Two's Complement.
On a computer we don’t have minus signs for numbers (it doesn't work very well to use the text based one when representing a number because you can't do arithmetic on characters), but we can do it by allocating one extra bit, called a sign bit, to represent the minus sign. Just like with decimal numbers, we put the negative indicator on the left of the number --- when the sign bit is set to “0”, that means the number is positive and when the sign bit is set to “1”, the number is negative (just as if there were a minus sign in front of it).
For example, if we wanted to represent the number 41 using 7 bits along with an additional bit that is the sign bit (to give a total of 8 bits), we would represent it by 00101001. The first bit is a 0, meaning the number is positive, then the remaining 7 bits give 41, meaning the number is +41. If we wanted to make -59, this would be 10111011. The first bit is a 1, meaning the number is negative, and then the remaining 7 bits represent 59, meaning the number is -59.
• Challenge: Representing negative numbers with sign bit
Using 8 bits as described above (one for the sign, and 7 for the actual number), what would be the binary representations for 1, -1, -8, 34, -37, -88, and 102?
• Spoiler: Representing negative numbers with sign bit
The spaces are not necessary, but are added to make reading the binary numbers easier
• 1 is 0000 0001
• -1 is 1000 0001
• -8 is 1000 1000
• 34 is 0010 0010
• -37 is 1010 0101
• -88 is 1101 1000
• 102 is 0110 0110
Going the other way is just as easy. If we have the binary number 10010111, we know it is negative because the first digit is a 1. The number part is the next 7 bits 0010111, which is 23. This means the number is -23.
• Challenge: Converting binary with sign bit to decimal
What would the decimal values be for the following, assuming that the first bit is a sign bit?
• 00010011
• 10000110
• 10100011
• 01111111
• 11111111
• Spoiler: Converting binary with sign bit to decimal
• 00010011 is 19
• 10000110 is -6
• 10100011 is -35
• 01111111 is 127
• 11111111 is -127
But what about 10000000? That converts to -0. And 00000000 is +0. Since -0 and +0 are both just 0, it is very strange to have two different representations for the same number.
This is one of the reasons that we don't use a simple sign bit in practice. Instead, computers usually use a more sophisticated representation for negative binary numbers called Two's Complement.
There's an alternative representation called Two's Complement, which avoids having two representations for 0, and more importantly, makes it easier to do arithmetic with negative numbers.
Representing positive numbers with Two's Complement
Representing positive numbers is the same as the method you have already learnt. Using 8 bits, the leftmost bit is a zero and the other 7 bits are the usual binary representation of the number; for example, 1 would be 00000001, and 65 would be 00110010.
Representing negative numbers with Two's Complement
This is where things get more interesting. In order to convert a negative number to its two's complement representation, use the following process.
1. Convert the number to binary (don't use a sign bit, and pretend it is a positive number).
2. Invert all the digits (i.e. change 0's to 1's and 1's to 0's).
3. Add 1 to the result (Adding 1 is easy in binary; you could do it by converting to decimal first, but think carefully about what happens when a binary number is incremented by 1 by trying a few; there are more hints in the panel below).
For example, assume we want to convert -118 to its Two's Complement representation. We would use the process as follows.
1. The binary number for 118 is 01110110
2. 01110110 with the digits inverted is 10001001
3. 10001001 + 1 is 10001010
Therefore, the Two's Complement representation for -118 is 10001010.
• Challenge: Adding one to a binary number
The rule for adding one to a binary number is pretty simple, so we'll let you figure it out for yourself. First, if a binary number ends with a 0 (e.g. 1101010), how would the number change if you replace the last 0 with a 1? Now, if it ends with 01, how much would it increase if you change the 01 to 10? What about ending with 011? 011111?
The method for adding is so simple that it's easy to build computer hardware to do it very quickly.
• Teacher Note: Method for adding one to a binary number
Students should be able to work out the rule for adding 1 to a binary number by trying it out with a few numbers.
There are different ways to express the process. In the "Unplugged" exercise at the start of this chapter one of the challenges was to count up through the numbers, which is adding one repeatedly, and it's not unusual for students to see the pattern when they do that. In that situation the rule could be expressed as "start at the right hand end, and flip bits from right to left until you change a 0 to a 1." (If the number ends in zero then that would be immediately.)
Another way to express the rule is to find the right most zero in the number, change it to a 1, and change all 1's to its right to zero. For example, consider adding 1 to 10010111. The right-most 0 is shown in bold; it changes to 1, and the three 1's to its right change to 0, giving 10011000.
If you get a number with no zeroes in it (e.g. 1111111), you can put one on the left (01111111), then apply the rule, which in this case gives 10000000.
It may help some students to consider what the equivalent rule is in decimal for adding 1 -- how do you add one to 284394? To 38999? 9999799?
• Challenge: Determining the Two's Complement
What would be the two's complement representation for the following numbers, using 8 bits? Follow the process given in this section, and remember that you do not need to do anything special for positive numbers.
1. 19
2. -19
3. 107
4. -107
5. -92
• Spoiler: Determining the Two's Complement
1. 19 in binary is 0001 0011, which is the two's complement for a positive number.
2. For -19, we take the binary of the positive, which is 0001 0011 (above), invert it to 1110 1100, and add 1, giving a representation of 1110 1101.
3. 107 in binary is 0110 1011, which is the two's complement for a positive number.
4. For -107, we take the binary of the positive, which is 0110 1011 (above), invert it to 1001 0100, and add 1, giving a representation of 1001 0101.
5. For -92, we take the binary of the positive, which is 0101 1100, invert it to 1010 0011, and add 1, giving a representation of 1010 0100. (If you have this incorrect, double check that you incremented by 1 correctly).
Converting a Two's Complement number back to decimal
In order to reverse the process, we need to know whether the number we are looking at is positive or negative. For positive numbers, we can simply convert the binary number back to decimal. But for negative numbers, we first need to convert it back to a normal binary number.
So how do we know if the number is positive or negative? It turns out (for reasons you will understand later in this section) that Two's Complement numbers that are negative always start in a 1, and positive numbers always start in a 0. Have a look back at the previous examples to double check this.
So, if the number starts with a 1, use the following process to convert the number back to a negative decimal number.
1. Subtract 1 from the number
2. Invert all the digits
3. Convert the resulting binary number to decimal
4. Add a minus sign in front of it.
So if we needed to convert 11100010 back to decimal, we would do the following.
1. Subtract 1 from 11100010, giving 11100001.
2. Invert all the digits, giving 00011110.
3. Convert 00011110 to a binary number, giving 30.
4. Add a negative sign, giving -30.
• Challenge: Reversing Two's Complement
Convert the following Two's Complement numbers to decimal.
1. 00001100
2. 10001100
3. 10111111
• Spoiler: Reversing Two's Complement
1. 12
2. 10001100 -> (-1) 10001011 -> (inverted) 01110100 -> (to decimal) 116 -> (negative sign added) -116
3. 10111111 -> (-1) 10111110 -> (inverted) 01000001 -> (to decimal) 65 -> (negative sign added) -65
How many numbers can be represented using Two's Complement?
While it might initially seem that there is no bit allocated as the sign bit, the left-most bit behaves like one. With 8 bits, you can still only make 256 possible patterns of 0's and 1's. If you attempted to use 8 bits to represent positive numbers up to 255, and negative numbers down to -255, you would quickly realise that some numbers were mapped onto the same pattern of bits. Obviously, this will make it impossible to know what number is actually being represented!
In practice, numbers within the following ranges can be represented. Unsigned Range is how many numbers you can represent if you only allow positive numbers (no sign is needed), and Two's Complement Range is how many numbers you can represent if you require both positive and negative numbers. You can work these out because the range of unsigned values (for 8 bits) will be from 00000000 to 11111111, while the unsigned range is from 10000000 (the lowest number) to 01111111 (the highest).
Number Unsigned Range Two's Complement Range
8 bit 0 to 255 -128 to 127
16 bit 0 to 65,535 -32,768 to 32,767
32 bit 0 to 4,294,967,295 −2,147,483,648 to 2,147,483,647
64 bit 0 to 18,446,744,073,709,551,615 −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Before adding negative binary numbers, we'll look at adding positive numbers. It's basically the same as the addition methods used on decimal numbers, except the rules are way simpler because there are only two different digits that you might add!
You've probably learnt about column addition. For example, the following column addition would be used to do 128 + 255.
1 (carries)
128
+255
----
383
When you go to add 5 + 8, the result is higher than 9, so you put the 3 in the one's column, and carry the 1 to the 10's column. Binary addition works in exactly the same way.
Adding positive binary numbers
If you wanted to add two positive binary numbers, such as 00001111 and 11001110, you would follow a similar process to the column addition. You only need to know 0+0, 0+1, 1+0, and 1+1, and 1+1+1. The first three are just what you might expect. Adding 1+1 causes a carry digit, since in binary 1+1 = 10, which translates to "0, carry 1" when doing column addition. The last one, 1+1+1 adds up to 11 in binary, which we can express as "1, carry 1". For our two example numbers, the addition works like this:
111 (carries)
11001110
+00001111
---------
11011101
Remember that the digits can be only 1 or 0. So you will need to carry a 1 to the next column if the total you get for a column is (decimal) 2 or 3.
Adding negative numbers with a simple sign bit
With negative numbers using sign bits like we did before, this does not work. If you wanted to add +11 (01011) and -7 (10111), you would expect to get an answer of +4 (00100).
11111 (carries)
01011
+10111
100010
Which is -2.
One way we could solve the problem is to use column subtraction instead. But this would require giving the computer a hardware circuit which could do this. Luckily this is unnecessary, because addition with negative numbers works automatically using Two's Complement!
Adding negative numbers with Two's Complement
For the above addition (+11 + -7), we can start by converting the numbers to their 5-bit Two's Complement form. Because 01011 (+11) is a positive number, it does not need to be changed. But for the negative number, 00111 (-7) (sign bit from before removed as we don't use it for Two's Complement), we need to invert the digits and then add 1, giving 11001.
Adding these two numbers works like this:
01011
11001
100100
Any extra bits to the left (beyond what we are using, in this case 5 bits) have been truncated. This leaves 00100, which is 4, like we were expecting.
We can also use this for subtraction. If we are subtracting a positive number from a positive number, we would need to convert the number we are subtracting to a negative number. Then we should add the two numbers. This is the same as for decimal numbers, for example 5 - 2 = 3 is the same as 5 + (-2) = 3.
This property of Two's Complement is very useful. It means that positive numbers and negative numbers can be handled by the same computer circuit, and addition and subtraction can be treated as the same operation.
• Curiosity: What's going on with Two's complement?
The idea of using a "complementary" number to change subtraction to addition can be seen by doing the same in decimal. The complement of a decimal digit is the digit that adds up to 10; for example, the complement of 4 is 6, and the complement of 8 is 2. (The word "complement" comes from the root "complete" - it completes it to a nice round number.)
Subtracting 2 from 6 is the same as adding the complement, and ignoring the extra 1 digit on the left. The complement of 2 is 8, so we add 8 to 6, giving (1)4.
For larger numbers (such as subtracting the two 3-digit numbers 255 - 128), the complement is the number that adds up to the next power of 10 i.e. 1000-128 = 872. Check that adding 872 to 255 produces (almost) the same result as subtracting 128.
Working out complements in binary is way easier because there are only two digits to work with, but working them out in decimal may help you to understand what is going on.
We have now looked at two different ways of representing negative numbers on a computer. In practice, a simple sign bit is rarely used, because of having two different representations of zero, and requiring a different computer circuit to handle negative and positive numbers, and to do addition and subtraction.
Two's Complement is widely used, because it only has one representation for zero, and it allows positive numbers and negative numbers to be treated in the same way, and addition and subtraction to be treated as one operation.
There are other systems such as "One's Complement" and "Excess-k", but Two's Complement is by far the most widely used in practice.
There are several different ways in which computers use bits to store text. In this section, we will look at some common ones and then look at the pros and cons of each representation.
We saw earlier that 64 unique patterns can be made using 6 dots in Braille. A dot corresponds to a bit, because both dots and bits have 2 different possible values.
Count how many different characters -- upper-case letters, lower-case letters, numbers, and symbols -- that you could type into a text editor using your keyboard. (Don’t forget to count both of the symbols that share the number keys, and the symbols to the side that are for punctuation!)
• Jargon Buster: Characters
The collective name for upper-case letters, lower-case letters, numbers, and symbols is characters e.g. a, D, 1, h, 6, *, ], and ~ are all characters. Importantly, a space is also a character.
If you counted correctly, you should find that there were more than 64 characters, and you might have found up to around 95. Because 6 bits can only represent 64 characters, we will need more than 6 bits; it turns out that we need at least 7 bits to represent all of these characters as this gives 128 possible patterns. This is exactly what the ASCII representation for text does.
• Challenge: Why 7 bits?
In the previous section, we explained what happens when the number of dots was increased by 1 (remember that a dot in Braille is effectively a bit). Can you explain how we knew that if 6 bits is enough to represent 64 characters, then 7 bits must be enough to represent 128 characters?
Each pattern in ASCII is usually stored in 8 bits, with one wasted bit, rather than 7 bits. However, the left-most bit in each 8-bit pattern is a 0, meaning there are still only 128 possible patterns. Where possible, we prefer to deal with full bytes (8 bits) on a computer, this is why ASCII has an extra wasted bit.
Here is a table that shows the patterns of bits that ASCII uses for each of the characters.
Binary Char Binary Char Binary Char
0100000 Space 1000000 @ 1100000 `
0100001 ! 1000001 A 1100001 a
0100010 " 1000010 B 1100010 b
0100011 # 1000011 C 1100011 c
0100100 $ 1000100 D 1100100 d
0100101 % 1000101 E 1100101 e
0100110 & 1000110 F 1100110 f
0100111 ' 1000111 G 1100111 g
0101000 ( 1001000 H 1101000 h
0101001 ) 1001001 I 1101001 i
0101010 * 1001010 J 1101010 j
0101011 + 1001011 K 1101011 k
0101100 , 1001100 L 1101100 l
0101101 - 1001101 M 1101101 m
0101110 . 1001110 N 1101110 n
0101111 / 1001111 O 1101111 o
0110000 0 1010000 P 1110000 p
0110001 1 1010001 Q 1110001 q
0110010 2 1010010 R 1110010 r
0110011 3 1010011 S 1110011 s
0110100 4 1010100 T 1110100 t
0110101 5 1010101 U 1110101 u
0110110 6 1010110 V 1110110 v
0110111 7 1010111 W 1110111 w
0111000 8 1011000 X 1111000 x
0111001 9 1011001 Y 1111001 y
0111010 : 1011010 Z 1111010 z
0111011 ; 1011011 [ 1111011 {
0111100 < 1011100 \ 1111100 \
0111101 = 1011101 ] 1111101 }
0111110 > 1011110 ^ 1111110 ~
0111111 ? 1011111 _ 1111111 Delete
For example, the letter c (lower-case) in the table has the pattern “01100011” (the 0 at the front is just extra padding to make it up to 8 bits). The letter o has the pattern “01101111”. You could write a word out using this code, and if you give it to someone else, they should be able to decode it exactly.
• Teacher Note: Using the table
Exchanging short messages in code will force students to use the table, and they should start to pick up some of the patterns (e.g. capital letters have a different code to lower case letters, but they only have one bit different.)
Computers can represent pieces of text with sequences of these patterns, much like Braille does. For example, the word “computers” (all lower-case) would be 01100011 01101111 01101101 01110000 01110101 01110100 01100101 01110010 01110011. This is because "c" is "01100011", "o" is "01101111", and so on. Have a look at the ASCII table above to check that we are right!
• Curiosity: What does ASCII stand for?
The name "ASCII" stands for "American Standard Code for Information Interchange", which was a particular way of assigning bit patterns to the characters on a keyboard. The ASCII system even includes "characters" for ringing a bell (useful for getting attention on old telegraph systems), deleting the previous character (kind of an early "undo"), and "end of transmission" (to let the receiver know that the message was finished). These days those characters are rarely used, but the codes for them still exist (they are the missing patterns in the table above). Nowadays ASCII has been supplanted by a code called "UTF-8", which happens to be the same as ASCII if the extra left-hand bit is a 0, but opens up a huge range of characters if the left-hand bit is a 1.
• Challenge: More practice at ASCII
Have a go at the following ASCII exercises
• How would you represent “science” in ASCII?
• How would you represent "Wellington" in ASCII? (note that it starts with an upper-case “W”)
• How would you represent “358” in ASCII (it is three characters, even though it looks like a number)
• How would you represent "Hello, how are you?" (look for the comma, question mark, and space characters in ASCII table)
Be sure to have a go at all of them before checking the answer!
• Spoiler: Answers to questions above
These are the answers.
• "science" = 01110011 01100011 01101001 01100101 01101110 01100011 01100101
• "Wellington" = 01010111 01100101 01101100 01101100 01101001 01101110 01100111 01110100 01101111 01101110
• "358" = 00110011 00110101 00111000
Note that the text "358" is treated as 3 characters in ASCII, which may be confusing, as the text "358" is different to the number 358! You may have encountered this distinction in a spreadsheet e.g. if a cell starts with an inverted comma in Excel, it is treated as text rather than a number. One place this comes up is with phone numbers; if you type 027555555 into a spreadsheet as a number, it will come up as 27555555, but as text the 0 can be displayed. In fact, phone numbers aren't really just numbers because a leading zero can be important, as they can contain other characters -- for example, +64 3 555 1234 extn. 1234.
ASCII was first used commercially in 1963, and despite the big changes in computers since then, it is still the basis of how English text is stored on computers. ASCII assigned a different pattern of bits to each of the characters, along with a few other “control” characters, such as delete or backspace.
English text can easily be represented using ASCII, but what about languages such as Chinese where there are thousands of different characters? Unsurprisingly, the 128 patterns aren’t nearly enough to represent such languages. Because of this, ASCII is not so useful in practice, and is no longer used widely. In the next sections, we will look at Unicode and its representations. These solve the problem of being unable to represent non-English characters.
• Curiosity: What came before ASCII?
There are several other codes that were popular before ASCII, including the Baudot code and EBCDIC. A widely used variant of the Baudot code was the "Murray code", named after New Zealand born inventor Donald Murray. One of Murray's significant improvements was to introduce the idea of "control characters", such as the carriage return (new line). The "control" key still exists on modern keyboards.
In practice, we need to be able to represent more than just English characters. To solve this problem, we use a standard called Unicode. Unicode is a character set with around 120,000 different characters, in many different languages, current and historic. Each character has a unique number assigned to it, making it easy to identify.
Unicode itself is not a representation -- it is a character set. In order to represent Unicode characters as bits, a Unicode encoding scheme is used. The Unicode encoding scheme tells us how each number (which corresponds to a Unicode character) should be represented with a pattern of bits.
The following interactive will allow you to explore the Unicode character set. Enter a number in the box on the left to see what Unicode character corresponds to it, or enter a character on the right to see what its Unicode number is (you could paste one in from a foreign language web page to see what happens with non-English characters).
Unicode Characters
The most widely used Unicode encoding schemes are called UTF-8, UTF-16, and UTF-32; you may have seen these names in email headers or describing a text file. Some of the Unicode encoding schemes are fixed length, and some are variable length. Fixed length means that each character is represented using the same number of bits. Variable length means that some characters are represented with fewer bits than others. It's better to be variable length, as this will ensure that the most commonly used characters are represented with fewer bits than the uncommonly used characters. Of course, what might be the most commonly used character in English is not necessarily the most commonly used character in Japanese. You may be wondering why we need so many encoding schemes for Unicode. It turns out that some are better for English language text, and some are better for Asian language text.
The remainder of the text representation section will look at some of these Unicode encoding schemes so that you understand how to use them, and why some of them are better than others in certain situations.
UTF-32 is a fixed length Unicode encoding scheme. The representation for each character is simply its number converted to a 32 bit binary number. Leading zeroes are used if there are not enough bits (just like how you can represent 254 as a 4 digit decimal number -- 0254). 32 bits is a nice round number on a computer, often referred to as a word (which is a bit confusing, since we can use UTF-32 characters to represent English words!)
For example, the character H in UTF-32 would be:
00000000 00000000 00000000 01001000
The character $ in UTF-32 would be:
00000000 00000000 00000000 00100100
And the character in UTF-32 would be:
00000000 00000000 01110010 10101100
The following interactive will allow you to convert a Unicode character to its UTF-32 representation. The Unicode character's number is also displayed. The bits are simply the binary number form of the character number.
• Project: Represent your name with UTF-32
1. Represent each character in your name using UTF-32.
2. Check how many bits your representation required, and explain why it had this many (remember that each character should have required 32 bits)
3. Explain how you knew how to represent each character. Even if you used the interactive, you should still be able to explain it in terms of binary numbers.
ASCII actually took the same approach. Each ASCII character has a number between 0 and 255, and the representation for the character the number converted to an 8 bit binary number. ASCII is also a fixed length encoding scheme -- every character in ASCII is represented using 8 bits.
In practice, UTF-32 is rarely used -- you can see that it's pretty wasteful of space. UTF-8 and UTF-16 are both variable length encoding schemes, and very widely used. We will look at them next.
• Challenge: How big is 32 bits?
1. What is the largest number that can be represented with 32 bits? (In both decimal and binary).
2. The largest number in Unicode that has a character assigned to it is not actually the largest possible 32 bit number -- it is 00000000 00010000 11111111 11111111. What is this number in decimal?
3. Most numbers that can be made using 32 bits do not have a Unicode character attached to them -- there is a lot of wasted space. There are good reasons for this, but if you had a shorter number that could represent any character, what is the minimum number of bits you would need, given that there are currently around 120,000 Unicode characters?
• Spoiler: Answers to above challenge
1. The largest number that can be represented using 32 bits is 4,294,967,295 (around 4.3 billion). You might have seen this number before -- it is the largest unsigned integer that a 32 bit computer can easily represent in programming languages such as C.
2. The decimal number for the largest character is 1,114,111.
3. You can represent all current characters with 17 bits. The largest number you can represent with 16 bits is 65,536, which is not enough. If we go up to 17 bits, that gives 131,072, which is larger than 120,000. Therefore, we need 17 bits.
UTF-8 is a variable length encoding scheme for Unicode. Characters with a lower Unicode number require fewer bits for their representation than those with a higher Unicode number. UTF-8 representations contain either 8, 16, 24, or 32 bits. Remembering that a byte is 8 bits, these are 1, 2, 3, and 4 bytes.
For example, the character H in UTF-8 would be:
01001000
The character ǿ in UTF-8 would be:
11000111 10111111
And the character in UTF-8 would be:
11100111 10001010 10101100
The following interactive will allow you to convert a Unicode character to its UTF-8 representation. The Unicode character's number is also displayed.
So how does UTF-8 actually work? Use the following process to do what the interactive is doing and convert characters to UTF-8 yourself.
1. Lookup the Unicode number of your character.
2. Convert the Unicode number to a binary number, using as few bits as necessary. Look back to the section on binary numbers if you cannot remember how to convert a number to binary.
3. Count how many bits are in the binary number, and choose the correct pattern to use, based on how many bits there were. Step 4 will explain how to use the pattern.
7 or fewer bits: 0xxxxxxx
11 or fewer bits: 110xxxxx 10xxxxxx
16 or fewer bits: 1110xxxx 10xxxxxx 10xxxxxx
21 or fewer bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
4. Replace the x's in the pattern with the bits of the binary number you converted in 2. If there are more x's than bits, replace extra left-most x's with 0's.
For example, if you wanted to find out the representation for (cat in Chinese), the steps you would take would be as follows.
1. Determine that the Unicode number for is 35987.
2. Convert 35987 to binary -- giving 10001100 10010011.
3. Count that there are 16 bits, and therefore the third pattern 1110xxxx 10xxxxxx 10xxxxx should be used.
4. Substitute the bits into the pattern to replace the x's -- 11101000 10110010 10010011.
Therefore, the representation for is 11101000 10110010 10010011 using UTF-8.
Just like UTF-8, UTF-16 is a variable length encoding scheme for Unicode. Because it is far more complex than UTF-8, we won't explain how it works here.
However, the following interactive will allow you to represent text with UTF-16. Try putting some text that is in English and some text that is in Japanese into it. Compare the representations to what you get with UTF-8.
We have looked at ASCII, UTF-32, UTF-8, and UTF-16.
The following table summarises what we have said so far about each representation.
Representation Variable or Fixed Bits per Character Real world Usage
ASCII Fixed Length 8 bits No longer widely used
UTF-8 Variable Length 8, 16, 24, or 32 bits Very widely used
UTF-16 Variable Length 16 or 32 bits Widely used
UTF-32 Fixed Length 32 bits Rarely used
In order to compare and evaluate them, we need to decide what it means for a representation to be "good". Two useful criteria are:
1. Can represent all characters, regardless of language.
2. Represents a piece of text using as few bits as possible.
We know that UTF-8, UTF-16, and UTF-32 can represent all characters, but ASCII can only represent English. Therefore, ASCII fails the first criterion. But for the second criteria, it isn't so simple.
The following interactive will allow you to find out the length of pieces of text using UTF-8, UTF-16, or UTF-32. Find some samples of English text and Asian text (forums or a translation site are a good place to look), and see how long your various samples are when encoded with each of the three representations. Copy paste or type text into the box.
Unicode Encoding Size
Enter text for length calculation:
Calculate Bit Lengths
Encoding lengths:
UTF-8: 0 bits
UTF-16: 0 bits
UTF-32: 0 bits
As a general rule, UTF-8 is better for English text, and UTF-16 is better for Asian text. UTF-32 always requires 32 bits for each character, so is unpopular in practice.
• Curiosity: Emoji and Unicode
Those cute little characters that you might use in your Facebook statuses, tweets, texts, and so on, are called "emojis", and each one of them has their own Unicode value. Japanese mobile operators were the first to use emojis, but their recent popularity has resulted in many becoming part of the Unicode Standard and today there are well over 1000 different emojis included. A current list of these can be seen here. What is interesting to notice is that a single emoji will look very different across different platforms, i.e. 😆 ("smiling face with open mouth and tightly-closed eyes") in my tweet will look very different to what it does on your iPhone. This is because the Unicode Consortium only provides the character codes for each emoji and the end vendors determine what that emoji will look like, e.g. for Apple devices the "Apple Color Emoji" typeface is used (there are rules around this to make sure there is consistency across each system).
There are messages hidden in this video using a 5-bit representation. See if you can find them! Start by reading the explanation below to ensure you understand what we mean by a 5-bit representation.
If you only wanted to represent the 26 letters of the alphabet, and weren’t worried about upper-case or lower-case, you could get away with using just 5 bits, which allows for up to 32 different patterns.
You might have exchanged notes which used 1 for "a", 2 for "b", 3 for "c", all the way up to 26 for "z". We can convert those numbers into 5 digit binary numbers. In fact, you will also get the same 5 bits for each letter by looking at the last 5 bits for it in the ASCII table (and it doesn't matter whether you look at the upper case or the lower case letter).
Represent the word "water" with bits using this system. Check the below panel once you think you have it.
• Spoiler
w: 10111
a: 00001
t: 10111
e: 10100
r: 10010
Now, have a go at decoding the music video!
• Teacher Note: More information about the video
The video actually contains over 20 hidden messages, all using the 5-bit system. An easy one to start with is the drum solo at the beginning. The first 5 sounds are "kick kick snare kick kick". Students need to decide which is 0 and which is 1; this number could either be 00100 (letter number 4, which is "d") or 11011 (letter number 27, which doesn't exist!) Carrying on with the first option, the first few letters will spell "drum".
The challenges get harder (there are messages in most instrument parts and singing, as well as the dancing and background colours). The song itself talks about how it is a form of "steganography", a term that students might like to research.
In school or art class you may have mixed different colours of paint or dye together in order to make new colours. In painting it's common to use red, yellow and blue as three "primary" colours that can be mixed to produce lots more colours. Mixing red and blue give purple, red and yellow give orange, and so on. By mixing red, yellow, and blue, you can make many new colours.
For printing, printers commonly use three slightly different primary colours: cyan, magenta, and yellow (CMY). All the colours on a printed document were made by mixing these primary colours.
Both these kinds of mixing are called "subtractive mixing", because they start with a white canvas or paper, and "subtract" colour from it. The interactive below allows you to experiment with CMY incase you are not familiar with it, or if you just like mixing colours.
CMY Colour Mixer - Used by Printers
Cyan - Currently set to 127
Magenta - Currently set to 127
Yellow - Currently set to 127
Computer screens and related devices also rely on mixing three colours, except they need a different set of primary colours because they are additive, starting with a black screen and adding colour to it. For additive colour on computers, the colours red, green and blue (RGB) are used. Each pixel on a screen is typically made up of three tiny "lights"; one red, one green, and one blue. By increasing and decreasing the amount of light coming out of each of these three, all the different colours can be made. The following interactive allows you to play around with RGB.
RGB Colour Mixer - Used by Screens
Red - Currently set to 127
Green - Currently set to 127
Blue - Currently set to 127
See what colours you can make with the RGB interactive. Can you make black, white, shades of grey, yellow, orange, and purple?
• Spoiler: Hints for above
Having all the sliders at the extremes will produce black and white, and if they are all the same value but in between, it will be grey (i.e. between black and white).
Yellow is not what you might expect - it's made from red and green, with no blue.
• Curiosity: Primary colours and the human eye
There's a very good reason that we mix three primary colours to specify the colour of a pixel. The human eye has millions of light sensors in it, and the ones that detect colour are called "cones". There are three different kinds of cones, which detect red, blue, and green light respectively. Colours are perceived by the amount of red, blue, and green light in them. Computer screen pixels take advantage of this by releasing the amounts of red, blue, and green light that will be perceived as the desired colour by your eyes. So when you see "purple", it's really the red and blue cones in your eyes being stimulated, and your brain converts that to a perceived colour. Scientists are still working out exactly how we perceive colour, but the representations used on computers seem to be good enough give the impression of looking at real images.
For more information about RGB displays, see RGB on Wikipedia; for more information about the eye sensing the three colours, see Cone cell and trichromacy on Wikipedia.
Because a colour is simply made up of amounts of the primary colours -- red, green and blue -- three numbers can be used to specify how much of each of these primary colours is needed to make the overall colour.
• Jargon Buster: Pixel
The word pixel is short for "picture element". On computer screens and printers an image is almost always displayed using a grid of pixels, each one set to the required colour. A pixel is typically a fraction of a millimeter across, and images can be made up of millions of pixels (one megapixel is a million pixels), so you can't usually see the individual pixels. Photographs commonly have several megapixels in them.
It's not unusual for computer screens to have millions of pixels on them, and the computer needs to represent a colour for each one of those pixels.
A commonly used scheme is to use numbers in the range 0 to 255. Those numbers tell the computer how fully to turn on each of the primary colour "lights" in an individual pixel. If red was set to 0, that means the red "light" is completely off. If the red "light" was set to 255, that would mean the "light" was fully on.
With 256 possible values for each of the three primary colours (don't forget to count 0!), that gives 256 x 256 x 256 = 16,777,216 possible colours -- more than the human eye can detect!
• Challenge: What is special about 255?
Think back to the binary numbers section. What is special about the number 255, which is the maximum colour value?
We'll cover the answer later in this section if you are still not sure!
The following interactive allows you to zoom in on an image to see the pixels that are used to represent it. Each pixel is a solid colour square, and the computer needs to store the colour for each pixel. If you zoom in far enough, the interactive will show you the red-green-blue values for each pixel. You can pick a pixel and put the values on the slider above - it should come out as the same colour as the pixel.
• Curiosity: Alternative material on bits and colour
Another exercise to see the relationship between bit patterns and colour images is provided here.
The next thing we need to look at is how bits are used to represent each colour in a high quality image. Firstly, how many bits do we need? Secondly, how should we decide the values of each of those bits? This section will work through those problems.
With 256 different possible values for the amount of each primary colour, this means 8 bits would be needed to represent the number.
\(2^8 = 2 \times 2 \times 2 \times 2 \times 2 \times 2 \times 2 \times 2 = 256\)
The smallest number that can be represented using 8 bits is 00000000 -- which is 0. And the largest number that can be represented using 8 bits is 11111111 -- which is 255.
Because there are three primary colours, each of which will need 8 bits to represent each of its 256 different possible values, we need 24 bits in total to represent a colour.
\(3 \times 8 = 24\)
So, how many colours are there in total with 24 bits? We know that there is 256 possible values each colour can take, so the easiest way of calculating it is:
\(256 \times 256 \times 256 = 16,777,216 \)
This is the same as \(2^{24}\).
Because 24 bits are required, this representation is called 24 bit colour. 24 bit colour is sometimes referred to in settings as "True Color" (because it is more accurate than the human eye can see). On Apple systems, it is called "Millions of colours".
A logical way is to use 3 binary numbers that represent the amount of each of red, green, and blue in the pixel. In order to do this, convert the amount of each primary colour needed to an 8 bit binary number, and then put the 3 binary numbers side by side to give 24 bits.
Because consistency is important in order for a computer to make sense of the bit pattern, we normally adopt the convention that the binary number for red should be put first, followed by green, and then finally blue. The only reason we put red first is because that is the convention that most systems assume is being used. If everybody had agreed that green should be first, then it would have been green first.
For example, suppose you have the colour that has red = 145, green = 50, and blue = 123 that you would like to represent with bits. If you put these values into the interactive, you will get the colour below.
Start by converting each of the three numbers into binary, using 8 bits for each.
You should get:
• red = 10010001,
• green = 00110010,
• blue = 01111011.
Putting these values together gives 100100010011001001111011, which is the bit representation for the colour above.
There are no spaces between the three numbers, as this is a pattern of bits rather than actually being three binary numbers, and computers don’t have any such concept of a space between bit patterns anyway --- everything must be a 0 or a 1. You could write it with spaces to make it easier to read, and to represent the idea that they are likely to be stored in 3 8-bit bytes, but inside the computer memory there is just a sequence of high and low voltages, so even writing 0 and 1 is an arbitrary notation.
Also, all leading and trailing 0’s on each part are kept --- without them, it would be representing a shorter number. If there were 256 different possible values for each primary colour, then the final representation must be 24 bits long.
• Curiosity: Monochromatic images
"Black and white" images usually have more than two colours in them; typically 256 shades of grey, represented with 8 bits.
Remember that shades of grey can be made by having an equal amount of each of the 3 primary colours, for example red = 105, green = 105, and blue = 105.
So for a monochromatic image, we can simply use a representation which is a single binary number between 0 and 255, which tells us the value that all 3 primary colours should be set to.
The computer won’t ever convert the number into decimal, as it works with the binary directly --- most of the process that takes the bits and makes the right pixels appear is typically done by a graphics card or a printer. We just started with decimal, because it is easier for humans to understand. The main point about knowing this representation is to understand the trade-off that is being made between the accuracy of colour (which should ideally be beyond human perception) and the amount of storage (bits) needed (which should be as little as possible).
• Curiosity: Hexadecimal colour codes
If you haven't already, read the section on Hexadecimal, otherwise this section might not make sense!
When writing HTML code, you often need to specify colours for text, backgrounds, and so on. One way of doing this is to specify the colour name, for example “red”, “blue”, “purple”, or “gold”. For some purposes, this is okay.
However, the use of names limits the number of colours you can represent and the shade might not be exactly the one you wanted. A better way is to specify the 24 bit colour directly. Because 24 binary digits are hard to read, colours in HTML use hexadecimal codes as a quick way to write the 24 bits, for example #00FF9E. The hash sign means that it should be interpreted as a hexadecimal representation, and since each hexadecimal digit corresponds to 4 bits, the 6 digits represent 24 bits of colour information.
This "hex triplet" format is used in HTML pages to specify colours for things like the background of the page, the text, and the colour of links. It is also used in CSS, SVG, and other applications.
In the 24 bit colour example earlier, the 24 bit pattern was 100100010011001001111011.
This can be broken up into groups of 4 bits: 1001 0001 0011 0010 0111 1011.
And now, each of these groups of 4 bits will need to be represented with a hexadecimal digit.
• 1001 -> 5
• 0001 -> 1
• 0011 -> 3
• 0010 -> 2
• 0111 -> 7
• 1011 -> B
Which gives #51327B.
Understanding how these hexadecimal colour codes are derived also allows you to change them slightly without having to refer back the colour table, when the colour isn’t exactly the one you want. Remember that in the 24 bit color code, the first 8 bits specify the amount of red (so this is the first 2 digits of the hexadecimal code), the next 8 bits specify the amount of green (the next 2 digits of the hexadecimal code), and the last 8 bits specify the amount of blue (the last 2 digits of the hexadecimal code). To increase the amount of any one of these colours, you can change the appropriate hexadecimal letters.
For example, #000000 has zero for red, green and blue, so setting a higher value to the middle two digits (such as #004300) will add some green to the colour.
You can use this HTML page to experiment with hexadecimal colours. Just enter a colour in the space below:
RGB Backround Colour Changer
What if we were to use fewer than 24 bits to represent each colour? How much space will be saved, compared to the impact on the image?
The following interactive gets you to try and match a specific colour using 24 bits, and then 8 bits.
It should be possible to get a perfect match using 24 bit colour. But what about 8 bits?
The above system used 3 bits to specify the amount of red (8 possible values), 3 bits to specify the amount of green (again 8 possible values), and 2 bits to specify the amount of blue (4 possible values). This gives a total of 8 bits (hence the name), which can be used to make 256 different bit patterns, and thus can represent 256 different colours.
You may be wondering why blue is represented with fewer bits than red and green. This is because the human eye is the least sensitive to blue, and therefore it is the least important colour in the representation. The representation uses 8 bits rather than 9 bits because it's easiest for computers to work with full bytes.
Using this scheme to represent all the pixels of an image takes one third of the number of bits required for 24-bit colour, but it is not as good at showing smooth changes of colours or subtle shades, because there are only 256 possible colors for each pixel. This is one of the big tradeoffs in data representation: do you allocate less space (fewer bits), or do you want higher quality?
• Jargon Buster: Colour depth
The number of bits used to represent the colours of pixels in a particular image is sometimes referred to as its "colour depth" or "bit depth". For example, an image or display with a colour depth of 8-bits has a choice of 256 colours for each pixel. There is more information about this in Wikipedia. Drastically reducing the bit depth of an image can make it look very strange; sometimes this is used as a special effect called "posterisation" (ie. making it look like a poster that has been printed with just a few colours).
• Curiosity: Colour depth and compression
There's a subtle boundary between low quality data representations (such as 8-bit colour) and compression methods. In principle, reducing an image to 8-bit colour is a way to compress it, but it's a very poor approach, and a proper compression method like JPEG will do a much better job.
The following interactive shows what happens to images when you use a smaller range of colours (including right down to zero bits!) You can choose an image using the menu or upload your own one. In which cases is the change in quality most noticeable? In which is it not? In which would you actually care about the colours in the image? In which situations is colour actually not necessary (i.e. when are we fine with two colours)?
• Additional Information: Software for exploring colour depth
Although we provide a simple interactive for reducing the number of bits in an image, you could also use software like Gimp or Photoshop to save files with different colour depths.
You probably noticed that 8-bit colour looks particularly bad for faces, where we are used to seeing subtle skin tones. Even the 16-bit colour is noticably worse for faces.
In other cases, the 16-bit images are almost as good as 24-bit images unless you look really carefully. They also use two-thirds (16/24) of the space that they would with 24-bit colour. For images that will need to be downloaded on 3G devices where internet is expensive, this is worth thinking about carefully.
Have an experiement with the following interactive, to see what impact different numbers of bits for each colour has. Do you think 8 bit colour was right in having 2 bits for blue, or should it have been green or red that got only 2 bits?
• Curiosity: Do we ever need more than 24 bit colour?
One other interesting thing to think about is whether or not we’d want more than 24 bit colour. It turns out that the human eye can only differentiate around 10 million colours, so the ~ 16 million provided by 24 bit colour is already beyond what our eyes can distinguish. However, if the image were to be processed by some software that enhances the contrast, it may turn out that 24-bit colour isn't sufficient. Choosing the representation isn't simple!
An image represented using 24 bit colour would have 24 bits per pixel. In 600 x 800 pixel image (which is a reasonable size for a photo), this would contain \(600 \times 800 = 480,000 \) pixels, and thus would use \(480,000 \times 24 bits = 11,520,000 \) bits. This works out to around 1.44 megabytes. If we use 8-bit colour instead, it will use a third of the memory, so it would save nearly a megabyte of storage. Or if the image is downloaded then a megabyte of bandwidth will be saved.
8 bit colour is not used much anymore, although it can still be helpful in situations such as accessing a computer desktop remotely on a slow internet connection, as the image of the desktop can instead be sent using 8 bit colour instead of 24 bit colour. Even though this may cause the desktop to appear a bit strange, it doesn’t stop you from getting whatever it was you needed to get done, done. Seeing your desktop in 24 bit colour would not be very helpful if you couldn't get your work done!
In some countries, mobile internet data is very expensive. Every megabyte that is saved will be a cost saving. There are also some situations where colour doesn’t matter at all, for example diagrams, and black and white printed images.
If space really is an issue, then this crude method of reducing the range of colours isn't usually used; instead, compression methods such as JPEG, GIF and PNG are used.
These make much more clever compromises to reduce the space that an image takes, without making it look so bad, including choosing a better palette of colours to use rather than just using the simple representation discussed above. However, compression methods require a lot more processing, and images need to be decoded to the representations discussed in this chapter before they can be displayed.
The ideas in this present chapter more commonly come up when designing systems (such as graphics interfaces) and working with high-quality images (such as RAW photographs), and typically the goal is to choose the best representation possible without wasting too much space.
Have a look at the Compression Chapter to find out more!
In a similar fashion to representing text or numbers using binary, we can represent an entire actual program using binary. Since a program is just a sequence of instructions, we need to decide how many bits will be used to represent a single instruction and then how we are going to interpret those bits. Machine code instructions typically have a combination of two pieces: operation and operand.
li $t0, 10 #Load the value 10 into register $t0
li $t1, 20 #Load the value 20 into register $t1
#Add the values in $t0 and $t1, put the result in register $a0
add $a0, $t0, $t1
In the above machine code program li and add are considered to be operations to "load an integer" and "add two integers" respectively. $t0, $t1, and $a0 are register operands and represent a place to store values inside of the machine. 10 and 20 are literal operands and allow instructions to represent the exact integer values 10 and 20. If we were using a 32-bit operating system we might encode the above instructions with each instruction broken into 4 8-bit pieces as follows:
Operation Op1 Op2 Op3
00001000 00000000 00000000 00001010
00001000 00000001 00000000 00010100
00001010 10000000 00000000 00000001
Our operation will always be determined by the bits in the first 8-bits of the 32-bit instruction. In this example machine code, 00001000 means li and 00001010 means add. For the li operation, the bits in Op1 are interpreted to be a storage place, allowing 00000000 to represent $t0. Similarly the bits in Op1 for the add instruction represent $a0. Can you figure out what the bits in Op3 for each instruction represent?
Using bits to represent both the program instructions and data forms such as text, numbers, and images allows entire computer programs to be represented in the same binary format. This allows programs to be stored on disks, in memory, and transferred over the internet as easily as data.
The kind of image representations covered here are the basic ones used in most digital systems, and the main point of this chapter is to understand how digital representations work, and the compromises needed between the number of bits, storage used, and quality.
The colour representation discussed is what is often referred to as "raw" or "bitmap" (bmp) representation. For large images, real systems use compression methods such as JPEG, GIF or PNG to reduce the space needed to store an image, but at the point where an image is being captured or displayed it is inevitably represented using the raw bits as described in this chapter, and the basic choices for capturing and displaying images will affect the quality and cost of a device. Compression is regarded as a form of encoding, and is covered in a later chapter.
The representation of numbers is a whole area of study in itself. The choice of representation affects how quickly arithmetic can be done on the numbers, how accurate the results are, and how much memory or disk space is used up storing the data. Even integers have issues like the order in which a large number is broken up across multiple bytes. Floating point numbers generally follow common standards (the IEEE 754 standard is the most common one) to make it easy to design compatible hardware to process them. Spreadsheets usually store numbers using a floating point format, which limits the precision of calculations (typically about 64 bits are used for each number). There are many experiments that can be done (such as calculating 1/3, or adding a very large number to a very small one) that demonstrate the limitations of floating point representations.
This puzzle can be solved using the pattern in binary numbers: http://www.cs4fn.org/binary/lock/
This site has more complex activities with binary numbers, including fractions, multiplication and division.
|
__label__pos
| 0.989878 |
Provided by: libsystemd-dev_245.4-4ubuntu3_amd64 bug
NAME
sd_event_source_set_destroy_callback, sd_event_source_get_destroy_callback,
sd_event_destroy_t - Define the callback function for resource cleanup.
SYNOPSIS
#include <systemd/sd-event.h>
typedef int (*sd_event_destroy_t)(void *userdata);
int sd_event_source_set_destroy_callback(sd_event_source *source,
sd_event_destroy_t callback);
int sd_event_source_get_destroy_callback(sd_event_source *source,
sd_event_destroy_t *callback);
DESCRIPTION
sd_event_source_set_destroy_callback() sets callback as the callback function to be called
right before the event source object source is deallocated. The userdata pointer from the
event source object will be passed as the userdata parameter. This pointer can be set by
an argument to the constructor functions, see sd_event_add_io(3), or directly, see
sd_event_source_set_userdata(3). This callback function is called even if userdata is
NULL. Note that this callback is invoked at a time where the event source object itself is
already invalidated, and executing operations or taking new references to the event source
object is not permissible.
sd_event_source_get_destroy_callback() returns the current callback for source in the
callback parameter.
RETURN VALUE
On success, sd_event_source_set_destroy_callback() returns 0 or a positive integer. On
failure, it returns a negative errno-style error code.
sd_event_source_get_destroy_callback() returns positive if the destroy callback function
is set, 0 if not. On failure, returns a negative errno-style error code.
Errors
Returned errors may indicate the following problems:
-EINVAL
The source parameter is NULL.
NOTES
These APIs are implemented as a shared library, which can be compiled and linked to with
the libsystemd pkg-config(1) file.
SEE ALSO
systemd(1), sd-event(3), sd_event_add_io(3), sd_event_add_time(3), sd_event_add_signal(3),
sd_event_add_child(3), sd_event_add_inotify(3), sd_event_add_defer(3),
sd_event_source_set_userdata(3)
|
__label__pos
| 0.675363 |
Accessing and altering a variable across classes
I am currently on Ex 45, making my own game. I am trying to build in a guess system, where if you guess incorrectly 10 times across the whole game, you lose. How do I get a class to access this variable, alter it and hand it off to the next class?
You probably want to use the global keyword:
THE_STATE = 0
def somefunc():
global THE_STATE
THE_STATE = 1000
That will change the variable.
A free service run by Zed A. Shaw for learncodethehardway.org.
|
__label__pos
| 0.950052 |
sasser worm
Anna makes a lame joke about Sasser.
Is it just me, or do the descriptions of the symptoms of the Sasser worm sound a lot like what happens after you install Windows as your operating system?
Home users would likely first notice an infection if their computer mysteriously rebooted or their Internet connection slowed dramatically.
css.php
|
__label__pos
| 0.999912 |
Version: 7.x-50.0.0
Community
Get Settings API
Endpoint
GET /_signals/settings
GET /_signals/settings/{key}
Retries all Signals settings or a single setting item.
Path Parameters
{key} The configuration setting to be retrieved. See (Signals Administration)[administration.md] for a list of the available settings.
Responses
200 OK
The setting could be successfully retrieved. The value of the settings is returned in the response body. The response format is JSON. This means, that if a setting as a simple textual value, the value will be returned in double quotes. If you specify the header Accept: text/plain in the request, you will get a plain text response with unquoted textual values.
403 Forbidden
The user does not have the permission to retrieve settings.
404 Not Found
A setting does not exist for the particular key.
Permissions
For being able to access the endpoint, the user needs to have the privilege cluster:admin:searchguard:signals:settings/put.
This permission is included in the following built-in action groups:
• SGS_SIGNALS_ALL
Examples
GET /_signals/settings
Response
{
"active": "true",
"http": {
"allowed_endpoints": [
"https://www.example.com/*",
"https://intra.example.com/*"
]
},
"tenant": {
"_main": {
"active": "true",
"node_filter": "node.attr.signals: true"
}
}
}
GET /_signals/settings/watchlog.index
Response
"<.signals_log_{now/d}>"
Not what you were looking for? Try the search.
|
__label__pos
| 0.898018 |
Databases Reporting with SQL Working with Text Getting the Length of a String
Casey Fulmore
Casey Fulmore
1,804 Points
I'm not sure why I'm getting an error when trying to run this code. My notes show that this should be accurate.
"There's something wrong with your SQL code"
2 Answers
Casey Fulmore
Casey Fulmore
1,804 Points
SELECT title, LENGTH(title) AS length FROM books ORDER BY length DESC LIMIT 1;
KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 50,933 Points
You have two issues:
1) The alias name is longest_length
2) length is a function and can't be used on its own in an order by clause. You can however order by the alias longest_ length or by length(title).
|
__label__pos
| 0.546074 |
Admin block
From UnrealIRCd documentation wiki
Jump to navigation Jump to search
The admin block defines the text displayed in a /admin request. You can specify as many lines as you want and they can contain whatever information you choose, but it is standard to include the admins nickname and email address at a minimum. Other information may include any other contact information you wish to give.
Syntax:
admin {
<text-line>;
<text-line>;
};
Example:
admin {
"Bob Smith";
"bob";
"[email protected]";
};
|
__label__pos
| 0.902639 |
GATE | Sudo GATE 2020 Mock II (10 January 2019) | Question 35
When two 8-bit numbers (A7 A6 … A0) and (B7 B6 … B0) in 2’s complement representation (with A0 and B0 as the least significant bits) are added using ripple carry adder, the sum bits obtained are (S7 S6 … S0) and the carry bits are (C7 C6 … C0). Which of the following statement(s) is/are correct ?
1. If two numbers with the same sign (both positive or both negative) are added, then overflow occurs if and only if the result has the opposite sign.
2. The overflow and carry out can each occur without the other. In unsigned numbers, carry out is equivalent to overflow. In two’s complement, carry out tells you nothing about overflow.
(A) Only 1
(B) Only 2
(C) Both 1 and 2
(D) None of these.
Answer: (C)
Explanation: Both statements are correct regarding overflow. Option (C) is true.
Quiz of this Question
My Personal Notes arrow_drop_up
Article Tags :
Be the First to upvote.
Please write to us at [email protected] to report any issue with the above content.
|
__label__pos
| 0.968676 |
FakeFork API Documentation
FakeFork provides some simple API calls to help you use FakeFork in your game, software, or bot. Use these calls to get details about your wallet or address.
Pull details for a wallet
[GET] https://fakefork.com/api/wallet/[wallet-uuid]
If you know your wallet uuid, use this call to pull the wallet balance, settings, as well as listing the recipients in the wallet.
Example Response
{
"data": {
"wallet": {
"uuid": "6bd81970-8d4b-11ea-bf60-03e5e62b3535",
"name": "Live tester",
"nano_address": "nano_35ujas6amsk7niuak3bdstk5ep3gbr71znc5g4nsef8xu99yrade8o4a6xjn",
"currency_name": "Gold",
"conversion_wallet_amount": "100000",
"conversion_nano_amount": "1",
"conversion_nano_unit": "ticker",
"recipient_data": {
"nano_31som8fezsjs441tg8nuah5f59ejehfmxwfsryann4x1c5eu3w39omzbxbpn": {
"name": "Bill"
},
"nano_3ka84awawkhtb5uxe5f47dyjwherqyedwhszixeaceg3hz3dm765jx3kgh5x": {
"name": "Bob"
},
"nano_31srphe3mbmkfeg3wwbn4i3ir78zt6oh3o4wrbii36umbytiowydwoa5m1w3": {
"name": "Jim"
}
},
"current_nano_balance": 7.0e+27,
"current_balance": 700
},
"recipients": [
{
"name": "Bill",
"address": "nano_31som8fezsjs441tg8nuah5f59ejehfmxwfsryann4x1c5eu3w39omzbxbpn",
"nano_balance": "900000000000000000000000000",
"balance": 90
},
{
"name": "Bob",
"address": "nano_3ka84awawkhtb5uxe5f47dyjwherqyedwhszixeaceg3hz3dm765jx3kgh5x",
"nano_balance": "1000000000000000000000000000",
"balance": 100
},
{
"name": "Jim",
"address": "nano_31srphe3mbmkfeg3wwbn4i3ir78zt6oh3o4wrbii36umbytiowydwoa5m1w3",
"nano_balance": "1100000000000000000000000000",
"balance": 110
}
]
}
}
Pull details for a Nano Address
[GET] https://fakefork.com/api/address/[address]
Using this call, you can check an address and see if this address is the starting point for a wallet, or if it has recieved funds from a FakeFork wallet.
Example Response
{
"data": {
"address": "nano_31som8fezsjs441tg8nuah5f59ejehfmxwfsryann4x1c5eu3w39omzbxbpn",
"wallets": [],
"received": [
{
"uuid": "6bd81970-8d4b-11ea-bf60-03e5e62b3535",
"name": "DnD Session"
}
]
}
}
|
__label__pos
| 0.934566 |
What time is it? - a word about consistency and consensus in distributed systems
Thanks to the microservices concept applications can scale more than ever before. You can have multiple instances of the same service to distribute the data and decrease the load. What about data consistency? How to determine which service instance has the most actual version of the data?
In this talk, I would like to cover the data consistency in the microservices architecture problem. The talk is described in the below points:
1. Introduction -> what is the microservices concept? How does it help with heavy loaded systems?
2. Distributed systems mechanics ->how data is spread across different service instances? Explaining the concept of single-leader and multi-leader replication.
3. What can be the problem? -> How to deal with concurrent writes? What about “concurrent” reads (from different instances)?
4. What are the strategies to respond with consistent data? What are their pros and cons?
I am going to cover the following issues: - Linearizability - Ordering Guarantees - Distributed Transactions and Consensus
• Neos Conference 2020
• 20.06.2020
• 12:20
• Studio Stage
|
__label__pos
| 0.999919 |
开发者社区> 北在南方> 正文
【案例】BNL算法导致性能下降一则
简介:
+关注继续查看
前面介绍了BNL算法,相信不少人会认为BNL会有利于数据库性能的提升(我也是这么认为滴),本文讲述一例生产上因为升级使用BNL 算法导致性能下降的案例。
一 背景
生产上将一实例MySQL版本从5.5升级到5.6,一条sql在5.5版本的MySQL执行只需要零点几秒,而在5.6 版本的环境下则需要10多秒,这个问题定位是5.6的优化器策略与5.5不同,导致了SQL执行计划发生变化,进而导致了sql的性能急剧下降.
二 案例
1) 5.5的优化器策略:
index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on
2) 5.6的优化器策略:
index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,
index_condition_pushdown=on,mrr=on,mrr_cost_based=on,block_nested_loop=on,batched_key_access=on,materialization=on,semijoin=on,loosescan=on,firstmatch=on,subquery_materialization_cost_based=on,use_index_extensions=on
mysql> show global variables like '%optimizer_switch%';
+------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Variable_name | Value |
+------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
optimizer_switch | index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,index_condition_pushdown=on,mrr=on,
mrr_cost_based=on,block_nested_loop=on,batched_key_access=off,materialization=on,semijoin=on,loosescan=on,firstmatch=on,subquery_materialization_cost_based=on,
use_index_extensions=on |
+------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------1 row in set (0.00 sec)
5.6版本的执行的执行计划如下所示:
mysql> explain SELECT *
-> FROM s_gm_info this_
-> LEFT OUTER JOIN s_gm_item gmitem2_ ON this_.itemId = gmitem2_.id
-> LEFT OUTER JOIN s_gm_group gmgroup3_ ON gmitem2_.groupId =gmgroup3_.id
-> LEFT OUTER JOIN stm_info teaminfo4_ ON this_.guestId = teaminfo4_.id
-> LEFT OUTER JOIN s_lgue_info lgueinfo5_ ON teaminfo4_.lgueId =lgueinfo5_.id
-> LEFT OUTER JOIN stm_info teaminfo6_ ON this_.homeId = teaminfo6_.id
-> LEFT OUTER JOIN s_lgue_info lgueinfo7_ ON this_.lgueId =lgueinfo7_.id
-> LEFT OUTER JOIN s_area_info areainfo8_ ON lgueinfo7_.areaId =areainfo8_.id
-> LEFT OUTER JOIN s_lgue_group lguegrou9_ ON lgueinfo7_.groupId =lguegrou9_.id
-> LEFT OUTER JOIN s_lgue_item lgueitem10_ ON lgueinfo7_.itemId =lgueitem10_.id
-> ORDER BY this_.id ASC LIMIT 20;
+----+-------------+---------------+--------+---------------+---------+---------+-----------------------------+--------+----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------+--------+---------------+---------+---------+-----------------------------+--------+----------------------------------------------------+
| 1 | SIMPLE | this_ | ALL | NULL | NULL | NULL | NULL | 257312 | Using temporary; Using filesort |
| 1 | SIMPLE | gmitem2_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.this_.itemId | 1 | NULL |
| 1 | SIMPLE | gmgroup3_ | ALL | PRIMARY | NULL | NULL | NULL | 6 | Using where; Using join buffer (Block Nested Loop) |
| 1 | SIMPLE | teaminfo4_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.this_.guestId | 1 | NULL |
| 1 | SIMPLE | lgueinfo5_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.teaminfo4_.lgueId | 1 | NULL |
| 1 | SIMPLE | teaminfo6_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.this_.homeId | 1 | NULL |
| 1 | SIMPLE | lgueinfo7_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.this_.lgueId | 1 | NULL |
| 1 | SIMPLE | areainfo8_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.lgueinfo7_.areaId | 1 | NULL |
| 1 | SIMPLE | lguegrou9_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.lgueinfo7_.groupId | 1 | NULL |
| 1 | SIMPLE | lgueitem10_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.lgueinfo7_.itemId | 1 | NULL |
+----+-------------+---------------+--------+---------------+---------+---------+-----------------------------+--------+----------------------------------------------------+
this_ 表原来可以通过主键来获取数据,在使用了BNL算法之后却导致全表扫描。
关闭BNL优化器
mysql> set optimizer_switch='index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,
index_condition_pushdown=on,mrr=on,mrr_cost_based=on,block_nested_loop=off,batched_key_access=on,materialization=on,semijoin=on,loosescan=on,firstmatch=on,
subquery_materialization_cost_based=on,use_index_extensions=on'
新的执行计划如下:
+----+-------------+---------------+--------+---------------+---------+---------+-----------------------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------+--------+---------------+---------+---------+-----------------------------+------+-------+
| 1 | SIMPLE | this_ | index | NULL | PRIMARY | 4 | NULL | 20 | NULL |
| 1 | SIMPLE | gmitem2_ | eq_ref | PRIMARY | PRIMARY | 4 |app_db.this_.itemId | 1 | NULL |
| 1 | SIMPLE | gmgroup3_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.gmitem2_.groupId | 1 | NULL |
| 1 | SIMPLE | teaminfo4_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.this_.guestId | 1 | NULL |
| 1 | SIMPLE | lgueinfo5_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.teaminfo4_.lgueId | 1 | NULL |
| 1 | SIMPLE | teaminfo6_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.this_.homeId | 1 | NULL |
| 1 | SIMPLE | lgueinfo7_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.this_.lgueId | 1 | NULL |
| 1 | SIMPLE | areainfo8_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.lgueinfo7_.areaId | 1 | NULL |
| 1 | SIMPLE | lguegrou9_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.lgueinfo7_.groupId | 1 | NULL |
| 1 | SIMPLE | lgueitem10_ | eq_ref | PRIMARY | PRIMARY | 4 | app_db.lgueinfo7_.itemId | 1 | NULL |
+----+-------------+---------------+--------+---------------+---------+---------+-----------------------------+------+-------+
关闭该特性之后 ,执行计划选择了正确的索引,执行时间大幅度下降。
三 总结
通过这个例子,想告诉大家对线上数据库的升级操作,最好做必要的压测。先升级日常环境,然后选择升级线上环境。对于MySQL新的优化点有必要深入研究,了解其原理,多做测试。才能发现其中可能隐藏的问题。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
相关文章
《算法技术手册》一2.4.7 性能不明显的计算
本节书摘来华章计算机《算法技术手册》一书中的第2章 ,第2.4.7节, George T.Heineman Gary Pollice Stanley Selkow 著 杨晨 曹如进 译 译更多章节内容可以访问云栖社区“华章计算机”公众号查看。
922 0
一致性哈希算法的php实现与分析-算法
<?php/** 一致性哈希算法* 过程:* 1,抽象一个圆,然后把服务器节点按一定算法得到整数有序顺时针放到圆上,圆环用2^32 个点来进行均匀切割。* hash函数的结果应该均匀分布在[0,2^32-1]区间* 2,由于服务器少,在圆上分布不均匀会造成数据倾斜,所以我们使用虚拟节点代替服务器的节点,一个服务器生成32个虚拟节点,或者更多。
1391 0
一致性哈希算法应用与分析
一致性哈希算法主要使用在分布式数据存储系统中,按照一定的策略将数据尽可能均匀分布到所有的存储节点上去,使得系统具有良好的负载均衡性能和扩展性。感觉一致性哈希与数据结构中的“循环队列”还是有一点联系的。
786 0
阿里巴巴达摩院夺得首届“马栏山杯”国际音视频算法优化大赛【画质损伤修复赛道】冠军
首届“马栏山杯”国际音视频算法优化大赛颁奖盛典暨高峰论坛于9月8日举行。这场由中国工业与应用数学学会、中国网络社会组织联合会作为指导单位,湖南省互联网信息办公室、湖南省科学技术协会主办,中国(长沙)马栏山视频文创产业园、芒果TV承办的算法盛事,云集了全球优秀的算法精英。一大批来自高校、科研院所、互联网企业才子才女们,共1294支队伍报名参赛,其中北京大学34支,清华大学25支,麻省理工学院等国外顶级名校37支。
614 0
【愚公系列】2021年11月 C#版 数据结构与算法解析 for和foreach性能分析
【愚公系列】2021年11月 C#版 数据结构与算法解析 for和foreach性能分析
26 0
常见的一致性哈希算法#Java实现#
之前参与过缓存框架的封装与测试工作,并对一致性哈希算法进行了相关的调研。通过对spymemcached与jedis等客户端源码的阅读对一致性哈希算法的Java实现进行调研: 1. 使用TreeMap实现,TreeMap本身继承NavigatableMap,因此具备节点导航的特点 2. 通
2256 0
+关注
640
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
JS零基础入门教程(上册)
立即下载
性能优化方法论
立即下载
手把手学习日志服务SLS,云启实验室实战指南
立即下载
|
__label__pos
| 0.956359 |
Jump to: navigation, search
Difference between revisions of "EclipseLink/Examples/JPA/ORMTransactions"
(Creating an Object: Alternative Method)
(Deleting an Object)
(One intermediate revision by the same user not shown)
Line 82: Line 82:
Both approaches produce the following SQL:
Both approaches produce the following SQL:
<source lang="java">
+
<source lang="sql">
UPDATE PET SET NAME = 'Furry' WHERE (ID = 100)
UPDATE PET SET NAME = 'Furry' WHERE (ID = 100)
</source>
</source>
Line 100: Line 100:
The above code generates the following SQL:
The above code generates the following SQL:
<source lang="java">
+
<source lang="sql">
DELETE FROM PET WHERE (ID = 100)
DELETE FROM PET WHERE (ID = 100)
</source>
</source>
Latest revision as of 09:49, 24 June 2008
A database transaction is a set of operations (create, read, update, or delete) that either succeed or fail as a single operation. The database discards, or rolls back, unsuccessful transactions, leaving the database in its original state. In EclipseLink, transactions are encapsulated by the Unit of Work object. Using the Unit of Work, you can transactionally modify objects directly or by way of a Java 2 Enterprise Edition (J2EE) external transaction controller such as the Java Transaction API (JTA).
Unit Of Work
The EclipseLink Unit of Work simplifies transactions and improves transactional performance. It is the preferred method of writing to a database in EclipseLink because it:
• sends a minimal amount of SQL to the database during the commit by updating only the exact changes down to the field level
• reduces database traffic by isolating transaction operations in their own memory space
• optimizes cache synchronization, in applications that use multiple caches, by passing change sets (rather than objects) between caches
• isolates object modifications in their own transaction space to allow parallel transactions on the same objects
• ensures referential integrity and minimizes deadlocks by automatically maintaining SQL ordering
• orders database inserts, updates, and deletes to maintain referential integrity for mapped objects
• resolves bidirectional references automatically
• frees the application from tracking or recording its changes
• simplifies persistence with persistence by reachability
Acquiring a Unit of Work
This example shows how to acquire a Unit of Work from a client session object.
Server server = (Server) SessionManager.getManager().getSession(sessionName, MyServerSession.class.getClassLoader());
Session session = (Session) server.acquireClientSession();
UnitOfWork uow = session.acquireUnitOfWork();
You can acquire a Unit of Work from any session type. Note that you do not need to create a new session and login before every transaction. The Unit of Work is valid until the commit or release method is called. After a commit or release, a Unit of Work is not valid even if the transaction fails and is rolled back.
Creating Objects
When you create new objects in the Unit of Work, use the registerObject method to ensure that the Unit of Work writes the objects to the database at commit time. The Unit of Work calculates commit order using foreign key information from one-to-one and one-to-many mappings. If you encounter constraint problems during commit, verify your mapping definitions. The order in which you register objects with the registerObject method does not affect the commit order.
Creating an Object: Preferred Method
UnitOfWork uow = session.acquireUnitOfWork();
Pet pet = new Pet();
Pet petClone = (Pet)uow.registerObject(pet);
petClone.setId(100);
petClone.setName("Fluffy");
petClone.setType("Cat");
uow.commit();
Creating an Object: Alternative Method
UnitOfWork uow = session.acquireUnitOfWork();
Pet pet = new Pet();
pet.setId(100);
pet.setName("Fluffy");
pet.setType("Cat");
uow.registerObject(pet);
uow.commit();
Both approaches produce the following SQL:
INSERT INTO PET (ID, NAME, TYPE, PET_OWN_ID) VALUES (100, 'Fluffy', 'Cat', NULL)
However the first example is preferred since it gets you into the pattern of working with clones and provides the most flexibility for future code changes. Working with combinations of new objects and clones can lead to confusion and unwanted results.
Modifying Objects
Modifying an Object: Using the Registration Step
In this example, a Pet is read prior to a Unit of Work: the variable pet is the cache copy for that Pet. Inside of the Unit of Work, we must register the cache copy to get a working copy. We then modify the working copy and commit the Unit of Work.
// Read in any pet.
Pet pet = (Pet)session.readObject(Pet.class);
UnitOfWork uow = session.acquireUnitOfWork();
Pet petClone = (Pet) uow.registerObject(pet);
petClone.setName("Furry");
uow.commit();
Modifying an Object: Skipping the Registration Step
In this example, we take advantage of the fact that you can query through a Unit of Work and get back clones, saving the registration step. However, the drawback is that we do not have a handle to the cache copy. If we wanted to do something with the updated Pet after commit, we would have to query the session to get it (remember that after a Unit of Work is committed, its clones are invalid and must not be used).
UnitOfWork uow = session.acquireUnitOfWork();
Pet petClone = (Pet) uow.readObject(Pet.class);
petClone.setName("Furry");
uow.commit();
Both approaches produce the following SQL:
UPDATE PET SET NAME = 'Furry' WHERE (ID = 100)
Take care when querying through a Unit of Work. All objects read in the query are registered in the Unit of Work and therefore will be checked for changes at commit time. Rather than do a ReadAllQuery through a Unit of Work, it is better for performance to design your application to do the ReadAllQuery through a session and then only register in a Unit of Work the objects that need to be changed.
Deleting Objects
To delete objects in a Unit of Work, use the deleteObject or deleteAllObjects method. When you delete an object that is not already registered in the Unit of Work, the Unit of Work registers the object automatically.
Deleting an Object
UnitOfWork uow = session.acquireUnitOfWork();
pet petClone = (Pet)uow.readObject(Pet.class);
uow.deleteObject(petClone);
uow.commit();
The above code generates the following SQL:
DELETE FROM PET WHERE (ID = 100)
|
__label__pos
| 0.9429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.