id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23537400
I was initially getting an error " The object name 'GBIPS-I-DB324D.CoreReferenceStaging.dbo.FinData2000_1' contains more than the maximum number of prefixes. The maximum is 2." while running the original query. GBIPS-I-DB324D is linked server object. I tried to use execute statement and now getting an error Incorrect syntax near the keyword 'USE'. Original Query BEGIN set nocount on declare @startYear int, @startQuarter int, @sql nvarchar(max), @tableName varchar(50); set @startYear = 2000; set @startQuarter = 1; while(@startYear < 2018) begin set @startQuarter = 1; while(@startQuarter < 5) begin set @tableName = 'FinData' + cast(@startYear as varchar) + '_' + cast(@startQuarter as varchar); set @sql = ' drop table [GBIPS-I-DB324D].[CoreReferenceStaging].[dbo].[' + @tableName + ']; create table [GBIPS-I-DB324D].[CoreReferenceStaging].[dbo].[' + @tableName + '] ( calendarYear int, calendarQuarter int, companyid bigint not null, dataitemid bigint not null, dataitemvalue numeric(28,6), fiscalyear int, fiscalquarter int, periodenddate datetime, filingdate datetime, latestforfinancialperiodflag bit, latestfilingforinstanceflag bit ); insert into [GBIPS-I-DB324D].[CoreReferenceStaging].[dbo].[' + @tableName + '] select fp.calendarYear, fp.calendarQuarter, fp.companyid, fd.dataitemid, fd.dataitemvalue, fp.fiscalyear, fp.fiscalquarter, fi.periodenddate, fi.filingdate, fi.latestforfinancialperiodflag, fi.latestfilingforinstanceflag from [Xpressfeed_dev].[dbo].[ciqFinPeriod] fp inner join [Xpressfeed_dev].[dbo].[ciqFinInstance] fi on fi.financialPeriodId = fp.financialPeriodId inner join [Xpressfeed_dev].[dbo].[ciqFinInstanceToCollection] fc on fc.financialInstanceId = fi.financialInstanceId inner join [Xpressfeed_dev].[dbo].[ciqFinCollection] c on c.financialCollectionId = fc.financialCollectionId inner join [Xpressfeed_dev].[dbo].[ciqFinCollectionData] fd on fd.financialCollectionId = c.financialCollectionId where YEAR(fi.periodenddate) = ' + cast(@startYear as varchar) + ' and QUARTER(fi.periodenddate) = ' + cast(@startQuarter as varchar) EXEC sp_executesql @sql set @startQuarter += 1 end set @startYear += 1; end end modified query BEGIN set nocount on declare @startYear int, @startQuarter int, @sql nvarchar(max), @tableName varchar(50); set @startYear = 2000; set @startQuarter = 1; while(@startYear < 2018) begin set @startQuarter = 1; while(@startQuarter < 5) begin set @tableName = 'FinData' + cast(@startYear as varchar) + '_' + cast(@startQuarter as varchar); set @sql = ' EXECUTE (USE CoreReferenceStaging;drop table [dbo].[' + @tableName + ']) AT [GBIPS-I-DB324D] EXECUTE (USE CoreReferenceStaging;create table [dbo].[' + @tableName + '] ( calendarYear int, calendarQuarter int, companyid bigint not null, dataitemid bigint not null, dataitemvalue numeric(28,6), fiscalyear int, fiscalquarter int, periodenddate datetime, filingdate datetime, latestforfinancialperiodflag bit, latestfilingforinstanceflag bit )) AT [GBIPS-I-DB324D] insert into [GBIPS-I-DB324D].[CoreReferenceStaging].[dbo].[' + @tableName + '] select fp.calendarYear, fp.calendarQuarter, fp.companyid, fd.dataitemid, fd.dataitemvalue, fp.fiscalyear, fp.fiscalquarter, fi.periodenddate, fi.filingdate, fi.latestforfinancialperiodflag, fi.latestfilingforinstanceflag from [Xpressfeed_dev].[dbo].[ciqFinPeriod] fp inner join [Xpressfeed_dev].[dbo].[ciqFinInstance] fi on fi.financialPeriodId = fp.financialPeriodId inner join [Xpressfeed_dev].[dbo].[ciqFinInstanceToCollection] fc on fc.financialInstanceId = fi.financialInstanceId inner join [Xpressfeed_dev].[dbo].[ciqFinCollection] c on c.financialCollectionId = fc.financialCollectionId inner join [Xpressfeed_dev].[dbo].[ciqFinCollectionData] fd on fd.financialCollectionId = c.financialCollectionId where YEAR(fi.periodenddate) = ' + cast(@startYear as varchar) + ' and QUARTER(fi.periodenddate) = ' + cast(@startQuarter as varchar) EXEC sp_executesql @sql set @startQuarter += 1 end set @startYear += 1; end end A: As far as i know, the 'USE' statement cannot be used when working with Linked Servers. This doesn't answer your question about the maximum of 2 but 'Use' is not the way to go. When there is no Linked Server in the game, you can use 'USE', but build the use-statement in the same statement that does the DML operation. You'll have to use Dynamic SQL for that which also have side-effects
doc_23537401
java.security.cert.CertificateParsingException: Caused by: java.io.IOException: Unknown named curve: 1.3.132.0.38 at java.base/sun.security.util.ECParameters.engineInit(ECParameters.java:141) at java.base/java.security.AlgorithmParameters.init(AlgorithmParameters.java:312) at java.base/sun.security.x509.AlgorithmId.decodeParams(AlgorithmId.java:137) at java.base/sun.security.x509.AlgorithmId.<init>(AlgorithmId.java:119) at java.base/sun.security.x509.AlgorithmId.parse(AlgorithmId.java:384) at java.base/sun.security.x509.X509Key.parse(X509Key.java:168) at java.base/sun.security.x509.CertificateX509Key.<init>(CertificateX509Key.java:75) at java.base/sun.security.x509.X509CertInfo.parse(X509CertInfo.java:674) at java.base/sun.security.x509.X509CertInfo.<init>(X509CertInfo.java:169) I assume OpenJDK does not have the license (or so) to include this elliptic curve in their package. Adding JCE did not changed anything. I also tried adding BouncyCastle as dependency, but this did not help either. I saw it is marked as a bug in OpenJDK but did not found if it has been fixed yet. Has anyone found a workaround? A: Later response: the problem for me was being caused by a keystore which contained both RSA and EC keys. From what I saw, OpenJDK11 does not support EC keys. Removing the EC keys and/or replacing them with only RSA keys solved it.
doc_23537402
My restrictions are: * *I am going to use the max size of BQ, columns 10,000 and ~35000 rows (this can be bigger) *Schema autodetect is required *If possible, I would like to use some kind of parallelism to write many tables at the same time asynchronously (for that Apache-beam & dataflow might be the solution) *When using Pandas library for BQ, there is a limit on the size of the dataframe that can be written. this requires partitioning of the data What would be the best way to do so? Many thanks for any advice / comment, eilalan A: Apache beam would be the right component as it supports huge volume data processing in batch and streaming mode. I don't think Beam as "Schema auto-detect". But, you can use BigQuery API to fetch the schema if the table already exists.
doc_23537403
In my program, I create a collection of TableOwner instances. The collection is essentially a set: Logically there is no order of TableOwner's, it only matters how many of each kind exist. Each one's DataTable is populated with different values for amount, but they all have the same primary key. For example, imagine TableOwner is used to store data on bank accounts. Each instance represents one account, then the DataTable might record how much of each currency there is in the account. For every account, the number of dollars, euros or pounds in that account may differ, but for every account, there is data on these same three currencies, even if the amount is 0 (no money in account) or null (perhaps data is missing). So basically I want a 2-D table or matrix, but my class hierarchy impedes me from implementing it as such. What is a sensible way to deal with all of this? I can think of the following approaches: 1) Make a DataColumn first and then pass it to all new instances of TableOwner to be used for their own DataTable's. Downside: If I later decide I want to remove a row from the primary key (eg the user decides "You know what, I don't care about euros anymore, dump all the data on them and remove the column."), I must iterate through the whole collection and remove the row from each TableOwner's table one by one. 2) Make a single DataTable used by all of the TableOwner instances (perhaps make it a static field). Instead of one amount column, the table will have many columns, such as Amount1, Amount2 and so on. Every TableOwner instance creates its own amount column at initialization and remembers its name for later - now removing a row is an elementary DB operation. Downside: Seems inelegant and "wrong". As you can see, both have a downside. Is there a better way? Apologies if the question is very basic or worded strangely, as I don't know much about databases. A: You should have a table with Columns for Owner, Currency and Amount So instead of Owner1 20$ £30 €40 You have three records Owner | Currency | Amount Owner1 $ 20 Owner1 £ 30 Owner1 € 40 (Where the currency symbols represent Currency IDs from a separate Currency table) If a person doesn't have an amount in a particular currency, then there is no record for the combination of person and currency. This is part of the process of normalisation
doc_23537404
<div class="form-group has-success"> <label class="control-label" for="inputSuccess">Input with success</label> <input type="text" class="form-control" id="inputSuccess"> </div> <div class="form-group has-warning"> <label class="control-label" for="inputWarning">Input with warning</label> <input type="text" class="form-control" id="inputWarning"> </div> <div class="form-group has-error"> <label class="control-label" for="inputError">Input with error</label> <input type="text" class="form-control" id="inputError"> </div> I would like that when input lose focus (focusout) in class element div with class form-group add class add, but only one. For ex. if input with id=inputError loses focus in class element <div class="form-group has-error"> add class add: <div class="form-group has-error add"> And I would like that only in one element with class form-group add class "add". I use code: $(".form-control").focusout(function(){ }) but I don't know how get parent div with class form-group... How make this? A: You can use .closest() to find out the nearest ancestor element matching the given selector $(".form-control").focusout(function(){ var $div = $(this).closest('.form-group').addClass('add') }) in you case if the form-group element is always the direct parent of form-control element then you can even use .parent() $(".form-control").focusout(function(){ var $div = $(this).parent().addClass('add') }) A: You can also use parent() method $(".form-control").focusout(function(){ $(this).parent().addClass('add'); }) A: $(".form-control").focusout(function(){ $(this).parent('.form-group').addClass('add'); }); A: You may try this $(".form-control").on('focusout', function(){ $(this).closest('.form-group').addClass('add'); }); or this one $(".form-control").on('focusout', function(){ $(this).parent().addClass('add'); }); A: $(".form-control").focusout(function(){ $(this).parent().addClass('add'); })
doc_23537405
I tried the checkbox "replace by space" in the Settings > Preferences > Language Menu / Tab Settings but it still doesn't work. import sqlite3 conn = sqlite3.connect('corrections.db') c = conn.cursor() for row in c.execute("SELECT * FROM inventory WHERE Name= 'Tim'"):{ if 1<2: print{"hello") } conn.commit() The error displays at the if statement, but if I move the if statement out of the for loop, it works perfectly. A: Context is everything; the if is a problem because of the { preceding it. (You'll also need to change print{ to print(.)
doc_23537406
So I've kind of got an idea of a recursive algorithm I'd like to implement but I want to know if it exists already so I can leverage other's expertise. Here's the algorithm by example: string 1: "Paul Johnson" string 2: "John Paulson" Step 1: find all longest matches Match 1: "Paul" Match 2: "John" Match 3: "son" Match 4: " " Step 2: Calculate scores for each match with this formula: ((match.len/string.len)*match.len) This allows longer strings to be weighted more at a balanced rate based on the length of the string. Match 1: (4/12)*4 = 1.333... Match 2: 1.333... Match 3: .75 Match 4: .083 Step 3: do steps 1 and 2 on larger scales, (matches of matches.) This I don't have figured out exactly. but my thinking is if "son" comes after "Paul John" and it comes after "John Paul" then that should count for something. Step 4: sum all the scores that have been calculated. Scores: 1.333 + 1.333 + .75 + .083333 = 3.4999... (plus whatever scores step 3 produces) Does this look familiar to anyone? I hope someone else has gone to the trouble of actually making an algorithm along these lines so I don't have to figure it out myself. A: What you describe somewhat resembles what the following paper calls the Longest Common Substring (LCS). For a brief description and comparison to other algorithms: A Comparison of Personal Name Matching This algorithm [11] repeatedly finds and removes the longest common sub-string in the two strings compared, up to a minimum lengths (normally set to 2 or 3). ... A similarity measure can be calculated by dividing the total length of the common sub-strings by the minimum, maximum or average lengths of the two original strings (similar to Smith-Waterman). ... this algorithm is suitable for compound names that have words (like given- and surname) swapped.
doc_23537407
Manifest file <uses-sdk android:minSdkVersion="8" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.androiddemos.NotificationActivity" android:label="@string/app_name" > </activity> <activity android:name=".ResultActivity" android:parentActivityName=".MainActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".NotificationActivity" /> </activity> <activity android:name=".GcmActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.example.androiddemos" /> </intent-filter> </receiver> <service android:name=".GCMIntentService" > </service> </application> <permission android:name="com.example.androiddemos.permission.C2D_MESSAGE" android:protectionLevel="signature" > </permission> <!-- App receives GCM messages. --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <!-- GCM connects to Google Services. --> <uses-permission android:name="android.permission.INTERNET" /> <!-- GCM requires a Google account. --> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- Keeps the processor from sleeping when a message is received. --> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.example.androiddemos.permission.C2D_MESSAGE" /> LOgcat 01-09 14:55:27.034: E/AndroidRuntime(25344): java.lang.IllegalArgumentException: android.content.pm.PackageManager$NameNotFoundException: ComponentInfo{com.example.androiddemos/com.example.androiddemos.MainActivity} 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.support.v4.app.TaskStackBuilder.addParentStack(TaskStackBuilder.java:236) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.support.v4.app.TaskStackBuilder.addParentStack(TaskStackBuilder.java:215) 01-09 14:55:27.034: E/AndroidRuntime(25344): at com.example.androiddemos.GcmActivity.sendNotification(GcmActivity.java:70) 01-09 14:55:27.034: E/AndroidRuntime(25344): at com.example.androiddemos.GcmActivity.checkGCM(GcmActivity.java:49) 01-09 14:55:27.034: E/AndroidRuntime(25344): at com.example.androiddemos.GcmActivity$1.onClick(GcmActivity.java:33) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.view.View.performClick(View.java:4084) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.view.View$PerformClick.run(View.java:16966) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.os.Handler.handleCallback(Handler.java:615) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.os.Handler.dispatchMessage(Handler.java:92) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.os.Looper.loop(Looper.java:137) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.app.ActivityThread.main(ActivityThread.java:4745) 01-09 14:55:27.034: E/AndroidRuntime(25344): at java.lang.reflect.Method.invokeNative(Native Method) 01-09 14:55:27.034: E/AndroidRuntime(25344): at java.lang.reflect.Method.invoke(Method.java:511) 01-09 14:55:27.034: E/AndroidRuntime(25344): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 01-09 14:55:27.034: E/AndroidRuntime(25344): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 01-09 14:55:27.034: E/AndroidRuntime(25344): at dalvik.system.NativeStart.main(Native Method) 01-09 14:55:27.034: E/AndroidRuntime(25344): Caused by: android.content.pm.PackageManager$NameNotFoundException: ComponentInfo{com.example.androiddemos/com.example.androiddemos.MainActivity} 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.app.ApplicationPackageManager.getActivityInfo(ApplicationPackageManager.java:225) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.support.v4.app.NavUtils.getParentActivityName(NavUtils.java:298) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.support.v4.app.NavUtils.getParentActivityIntent(NavUtils.java:261) 01-09 14:55:27.034: E/AndroidRuntime(25344): at android.support.v4.app.TaskStackBuilder.addParentStack(TaskStackBuilder.java:229) 01-09 14:55:27.034: E/AndroidRuntime(25344): ... 15 more A: I believe the problem is because you do not have MainActivity defined in your manifest based on this logcat line: 14:55:27.034: E/AndroidRuntime(25344): Caused by: android.content.pm.PackageManager$NameNotFoundException: ComponentInfo{com.example.androiddemos/com.example.androiddemos.MainActivity} 01-09 You have MainActivity referenced as the parentActivityName but not defined in the manifest at all: <activity android:name=".ResultActivity" android:parentActivityName=".MainActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".NotificationActivity" /> </activity> If you are still using MainActivity you will need to add it to the manifest: <activity android:name=".MainActivity"> </activity>
doc_23537408
{"0": "ROLE_USER"} The model of User: /** * @ORM\Column(type="json") */ private $roles = []; The Controller: $user->setRoles(array('{"0": "ROLE_USER"}')); It works adding data to DB: ["{\"0\": \"ROLE_USER\"}"] If I add it with no array - there is an error: Argument 1 passed to App\Entity\User::setRoles() must be of the type array, string given What should I do to have exactly {"0": "ROLE_USER"} in DB? A: Change $user->setRoles(array('{"0": "ROLE_USER"}')); To $user->setRoles(["ROLE_USER"]); That will do the job. Your array declaration is wrong. You push ONE Item to the array and the item is: {"0": "ROLE_USER"} as a plain string. For a doctrine "json" column you dont need to json_encode or json_decode yourself. Doctrine will handle that for you! The Flow: 1) You give Doctrine a array 2) Doctrine will json_encode your array and save it in the column as json_data 3) If you request the column value, doctrine will json_decode your array so you can work with your array again. Your desired goal is also not correct. You want json_data like this: {"0": "ROLE_USER"} But i think you will have data like this: {"ROLE_USER"} But both cases would leed to the same array: array { 0 => ROLE_USER } A: If you use Doctrine as ORM, you should use existing json mapping type that stores array as JSON string and automatically (de)serialize data.
doc_23537409
The second issue I notice is if I enter in a string "1111111111111111111", which is obviously too long, the program says the password is too long, but the entire do/while loop terminates and it asks me to confirm my passcode. It should ask me to enter a password again. If I take out the if statements: if (strlen(strA) > 8) and else if (strlen(strA) < 9), and just run the while loop: while (j<=9), the program works fine, as long as I don't enter in too many characters in the string. Can anyone diagnose the problem? #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char strA[10]; char strB[10]; char strC[] = {'1','2','3','4','5','6','7','8','9','0'}; char strD[] = {'!','@','#','$','%','^','&','*','(',')'}; char strE[] = {'a','b','c','d','e','f','g','h','i','j','k', 'l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z'}; char strF[] = {'A','B','C','D','E','F','G','H','I','J', 'K','L','M','N','O','P','Q','R','S', 'T','U','V','W','X','Y','Z'}; int i, j, k; do { k = 0; j = 0; printf("Please enter your password: "); scanf("%s", &strA); printf("%s\n", strA); if(strlen(strA) > 8) { printf("That password is too long\n"); } else if(strlen(strA) < 9) { while (j <= 9) { for(i = 0; i <= 9; i++) { if(strA[j] == strC[i]) { printf("there is a number in this string.\n"); k++; j = 0; while (j <= 9) { for(i = 0; i <= 9; i++) { if(strA[j] == strD[i]) { printf("there is a character in this string.\n"); k++; j = 0; while(j <= 9) { for(i = 0; i <= 25; i++) { if(strA[j] == strE[i]) { printf("there is a lowercase letter in this string.\n"); k++; j = 0; while(j <= 9) { for(i=0;i<=25;i++) { if(strA[j] == strF[i]) { printf("there is an uppercase letter in this string.\n"); k++; } } j++; } } } j++; } } } j++; } } } j++; } if(k < 4) { printf("Your password must contain at least one uppercase letter, one lowercase letter, a number, and a special character.\n"); } } } while(k < 4); printf("Please confirm your password: "); scanf("%s",&strB); while(strcmp(strA, strB) != 0) { printf("%s\n",strB); printf("Your passwords do not match.\nPlease confirm your password: "); scanf("%s",&strB); } putchar('\n'); printf("%s\n", strA); printf("%s\n", strB); return 0; } A: I think following line is creating the problem: char strA[10]; char strB[10]; Initialize with default values memset(&strA,'\0', sizeof(strA)); memset(&strB,'\0', sizeof(strB)); A: Look at ASCII standards : there is a faster way to test if a char c is a digit (c>47 && c<58)! http://en.wikipedia.org/wiki/ASCII More : look at ctype.h as stated here Determine if char is a num or letter http://www.cplusplus.com/reference/locale/isalpha/ isalpha(c) : true if letter isdigit(c) : true if digit ``isupper(c)` : true if upper case islower(c) : true if lower case Bye, Francis
doc_23537410
* *Importing the project Microsoft.Application.Web.Targets and Microsoft.Web.Publishing.Targets. *Install/Repair using the exe at http://go.microsoft.com/fwlink/?LinkId=253458. But nothing has worked so far. Please help me. A: I managed to resolve this error by adding an empty targets tag in the .csproj file for the project: <Target Name="_CopyBinDeployableAssemblies"></Target> Found this on stackoverflow itelf in the response to a similar question: Why do I get the error "The target GatherAllFilesToPublish does not exist"?
doc_23537411
It is from an anki(a program make in python) add-on source code, where can I find the mw file? I found folder /usr/share/anki/aqt, but I didn't find mw folder or mw.py file, where else could it be? Or is there method to display its path? A: to identify the type of mw, do type(mw) in your python console. It might be something defined in the __init__.py file of the aqtdir. If 'mw' is a module, then you can try mv.__file__. A: Start python interpreter with -v flag, for every import its path will be printed like a comment Here an example with a funny module: user@host ~/$ python -v ### #a bunch of bultin imports ### >>> import sexmachine import sexmachine # directory /usr/local/lib/python2.7/dist-packages/sexmachine # /usr/local/lib/python2.7/dist-packages/sexmachine/__init__.pyc matches /usr/local/lib/python2.7/dist-packages/sexmachine/__init__.py import sexmachine # precompiled from /usr/local/lib/python2.7/dist-packages/sexmachine/__init__.pyc A: You should check this out. from aqt import mw print mw.__file__ Edit: wtf? "Trivial answer converted to comment"?
doc_23537412
doc_23537413
http://www.yiiframework.com/wiki/165/understanding-autoloading-helper-classes-and-helper-functions/ But now problem is that recaptchalib.php is the file required to do the work and this is the file having class and constants and functions and these are interrelated. I want to know that now how I can make it component and use in Yii as it is neither functions only nor only class. Is there a better way to do this? Here is the code for recaptchalib.php <?php /* * This is a PHP library that handles calling reCAPTCHA. * - Documentation and latest version * http://recaptcha.net/plugins/php/ * - Get a reCAPTCHA API Key * https://www.google.com/recaptcha/admin/create * - Discussion group * http://groups.google.com/group/recaptcha * * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net * AUTHORS: * Mike Crawford * Ben Maurer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * The reCAPTCHA server URL's */ define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api"); define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api"); define("RECAPTCHA_VERIFY_SERVER", "www.google.com"); /** * Encodes the given data into a query string format * @param $data - array of string elements to be encoded * @return string - encoded request */ function _recaptcha_qsencode ($data) { $req = ""; foreach ( $data as $key => $value ) $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; // Cut the last '&' $req=substr($req,0,strlen($req)-1); return $req; } /** * Submits an HTTP POST to a reCAPTCHA server * @param string $host * @param string $path * @param array $data * @param int port * @return array response */ function _recaptcha_http_post($host, $path, $data, $port = 80) { $req = _recaptcha_qsencode ($data); $http_request = "POST $path HTTP/1.0\r\n"; $http_request .= "Host: $host\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($req) . "\r\n"; $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; $http_request .= "\r\n"; $http_request .= $req; $response = ''; if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { die ('Could not open socket'); } fwrite($fs, $http_request); while ( !feof($fs) ) $response .= fgets($fs, 1160); // One TCP-IP packet fclose($fs); $response = explode("\r\n\r\n", $response, 2); return $response; } /** * Gets the challenge HTML (javascript and non-javascript version). * This is called from the browser, and the resulting reCAPTCHA HTML widget * is embedded within the HTML form it was called from. * @param string $pubkey A public key for reCAPTCHA * @param string $error The error given by reCAPTCHA (optional, default is null) * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) * @return string - The HTML to be embedded in the user's form. */ function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) { if ($pubkey == null || $pubkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($use_ssl) { $server = RECAPTCHA_API_SECURE_SERVER; } else { $server = RECAPTCHA_API_SERVER; } $errorpart = ""; if ($error) { $errorpart = "&amp;error=" . $error; } return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script> <noscript> <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/> </noscript>'; } /** * A ReCaptchaResponse is returned from recaptcha_check_answer() */ class ReCaptchaResponse { var $is_valid; var $error; } /** * Calls an HTTP POST function to verify if the user's guess was correct * @param string $privkey * @param string $remoteip * @param string $challenge * @param string $response * @param array $extra_params an array of extra variables to post to the server * @return ReCaptchaResponse */ function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) { if ($privkey == null || $privkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($remoteip == null || $remoteip == '') { die ("For security reasons, you must pass the remote ip to reCAPTCHA"); } //discard spam submissions if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { $recaptcha_response = new ReCaptchaResponse(); $recaptcha_response->is_valid = false; $recaptcha_response->error = 'incorrect-captcha-sol'; return $recaptcha_response; } $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", array ( 'privatekey' => $privkey, 'remoteip' => $remoteip, 'challenge' => $challenge, 'response' => $response ) + $extra_params ); $answers = explode ("\n", $response [1]); $recaptcha_response = new ReCaptchaResponse(); if (trim ($answers [0]) == 'true') { $recaptcha_response->is_valid = true; } else { $recaptcha_response->is_valid = false; $recaptcha_response->error = $answers [1]; } return $recaptcha_response; } /** * gets a URL where the user can sign up for reCAPTCHA. If your application * has a configuration page where you enter a key, you should provide a link * using this function. * @param string $domain The domain where the page is hosted * @param string $appname The name of your application */ function recaptcha_get_signup_url ($domain = null, $appname = null) { return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); } function _recaptcha_aes_pad($val) { $block_size = 16; $numpad = $block_size - (strlen ($val) % $block_size); return str_pad($val, strlen ($val) + $numpad, chr($numpad)); } /* Mailhide related code */ function _recaptcha_aes_encrypt($val,$ky) { if (! function_exists ("mcrypt_encrypt")) { die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); } $mode=MCRYPT_MODE_CBC; $enc=MCRYPT_RIJNDAEL_128; $val=_recaptcha_aes_pad($val); return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); } function _recaptcha_mailhide_urlbase64 ($x) { return strtr(base64_encode ($x), '+/', '-_'); } /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ function recaptcha_mailhide_url($pubkey, $privkey, $email) { if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>"); } $ky = pack('H*', $privkey); $cryptmail = _recaptcha_aes_encrypt ($email, $ky); return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail); } /** * gets the parts of the email to expose to the user. * eg, given johndoe@example,com return ["john", "example.com"]. * the email is then displayed as john...@example.com */ function _recaptcha_mailhide_email_parts ($email) { $arr = preg_split("/@/", $email ); if (strlen ($arr[0]) <= 4) { $arr[0] = substr ($arr[0], 0, 1); } else if (strlen ($arr[0]) <= 6) { $arr[0] = substr ($arr[0], 0, 3); } else { $arr[0] = substr ($arr[0], 0, 4); } return $arr; } /** * Gets html to display an email address given a public an private key. * to get a key, go to: * * http://www.google.com/recaptcha/mailhide/apikey */ function recaptcha_mailhide_html($pubkey, $privkey, $email) { $emailparts = _recaptcha_mailhide_email_parts ($email); $url = recaptcha_mailhide_url ($pubkey, $privkey, $email); return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) . "' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]); } ?> A: Use this code. The class is now updated with many private and some public methods, also the constants are now defined as class constants. Save this file with ReCaptcha.php name. protected/components/ReCaptcha.php You will not be able to create a direct instance of this class due to private constructor, the class will return ReCaptcha instance when you call its static method, check_answer() Now, in order to use the ReCaptcha service. Initiate using ReCaptcha::get_html(parameters_values); For checking the recaptcha answer, use this $ReCaptchaResponse = ReCaptcha::check_answer(parameter_values); now this $ReCaptchaResponse is the object instance, and you can use this to find $ReCaptchaResponse->is_valid; //(Boolean, true or false will be vailable) $ReCaptchaResponse->error; // is_valid is false, you can use this to find the actual error returned. Also if the php file consists only php code, it is recommended to leave the closing php tag "?>" <?php /* * This is a PHP library that handles calling reCAPTCHA. * - Documentation and latest version * http://recaptcha.net/plugins/php/ * - Get a reCAPTCHA API Key * https://www.google.com/recaptcha/admin/create * - Discussion group * http://groups.google.com/group/recaptcha * * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net * AUTHORS: * Mike Crawford * Ben Maurer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * A ReCaptcha Library with pubic properties is returned from * ReCaptcha::check_answer() */ class ReCaptcha { public $is_valid; public $error; /** * The reCAPTCHA API server URL */ const RECAPTCHA_API_SERVER = "http://www.google.com/recaptcha/api"; /** * The reCAPTCHA API SECURE server URL */ const RECAPTCHA_API_SECURE_SERVER = "https://www.google.com/recaptcha/api"; /** * The reCAPTCHA VERIFY server URL */ const RECAPTCHA_VERIFY_SERVER = "www.google.com"; /** * A private constructor, * prevents direct creation of object from outside the class. */ private function __construct() { } /** * Encodes the given data into a query string format * @param $data - array of string elements to be encoded * @return string - encoded request */ private static function _recaptcha_qsencode ($data) { $req = ""; foreach ( $data as $key => $value ) $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; // Cut the last '&' $req=substr($req,0,strlen($req)-1); return $req; } /** * Submits an HTTP POST to a reCAPTCHA server * @param string $host * @param string $path * @param array $data * @param int port * @return array response */ private static function _recaptcha_http_post($host, $path, $data, $port = 80) { $req = self::_recaptcha_qsencode ($data); $http_request = "POST $path HTTP/1.0\r\n"; $http_request .= "Host: $host\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($req) . "\r\n"; $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; $http_request .= "\r\n"; $http_request .= $req; $response = ''; if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) { die ('Could not open socket'); } fwrite($fs, $http_request); while ( !feof($fs) ) $response .= fgets($fs, 1160); // One TCP-IP packet fclose($fs); $response = explode("\r\n\r\n", $response, 2); return $response; } /** * Gets the challenge HTML (javascript and non-javascript version). * This is called from the browser, and the resulting reCAPTCHA HTML widget * is embedded within the HTML form it was called from. * @param string $pubkey A public key for reCAPTCHA * @param string $error The error given by reCAPTCHA (optional, default is null) * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) * @return string - The HTML to be embedded in the user's form. */ public static function get_html ($pubkey, $error = null, $use_ssl = false) { if ($pubkey == null || $pubkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($use_ssl) { $server = self::RECAPTCHA_API_SECURE_SERVER; } else { $server = self::RECAPTCHA_API_SERVER; } $errorpart = ""; if ($error) { $errorpart = "&amp;error=" . $error; } return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script> <noscript> <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/> </noscript>'; } /** * Calls an HTTP POST function to verify if the user's guess was correct * @param string $privkey * @param string $remoteip * @param string $challenge * @param string $response * @param array $extra_params an array of extra variables to post to the server * @return ReCaptcha */ public static function check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()) { if ($privkey == null || $privkey == '') { die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($remoteip == null || $remoteip == '') { die ("For security reasons, you must pass the remote ip to reCAPTCHA"); } //discard spam submissions if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { $recaptcha_response = new self(); $recaptcha_response->is_valid = false; $recaptcha_response->error = 'incorrect-captcha-sol'; return $recaptcha_response; } $response = self::_recaptcha_http_post (self::RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", array ( 'privatekey' => $privkey, 'remoteip' => $remoteip, 'challenge' => $challenge, 'response' => $response ) + $extra_params ); $answers = explode ("\n", $response [1]); $recaptcha_response = new self(); if (trim ($answers [0]) == 'true') { $recaptcha_response->is_valid = true; } else { $recaptcha_response->is_valid = false; $recaptcha_response->error = $answers [1]; } return $recaptcha_response; } /** * gets a URL where the user can sign up for reCAPTCHA. If your application * has a configuration page where you enter a key, you should provide a link * using this function. * @param string $domain The domain where the page is hosted * @param string $appname The name of your application */ public static function get_signup_url ($domain = null, $appname = null) { return "https://www.google.com/recaptcha/admin/create?" . self::_recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname)); } private static function _recaptcha_aes_pad($val) { $block_size = 16; $numpad = $block_size - (strlen ($val) % $block_size); return str_pad($val, strlen ($val) + $numpad, chr($numpad)); } /* Mailhide related code */ /** * Gets html to display an email address given a public an private key. * to get a key, go to: * * http://www.google.com/recaptcha/mailhide/apikey */ public static function mailhide_html($pubkey, $privkey, $email) { $emailparts = self::_recaptcha_mailhide_email_parts ($email); $url = self::mailhide_url ($pubkey, $privkey, $email); return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) . "' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]); } private static function _recaptcha_aes_encrypt($val,$ky) { if (! function_exists ("mcrypt_encrypt")) { die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed."); } $mode=MCRYPT_MODE_CBC; $enc=MCRYPT_RIJNDAEL_128; $val=self::_recaptcha_aes_pad($val); return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); } private static function _recaptcha_mailhide_urlbase64 ($x) { return strtr(base64_encode ($x), '+/', '-_'); } /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */ public static function mailhide_url($pubkey, $privkey, $email) { if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) { die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>"); } $ky = pack('H*', $privkey); $cryptmail = self::_recaptcha_aes_encrypt ($email, $ky); return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . self::_recaptcha_mailhide_urlbase64 ($cryptmail); } /** * gets the parts of the email to expose to the user. * eg, given johndoe@example,com return ["john", "example.com"]. * the email is then displayed as john...@example.com */ private static function _recaptcha_mailhide_email_parts ($email) { $arr = preg_split("/@/", $email ); if (strlen ($arr[0]) <= 4) { $arr[0] = substr ($arr[0], 0, 1); } else if (strlen ($arr[0]) <= 6) { $arr[0] = substr ($arr[0], 0, 3); } else { $arr[0] = substr ($arr[0], 0, 4); } return $arr; } }
doc_23537414
After reading the answers and using break and the forgotten secondColor = true, I still have the same problem. Even when sending the clicked object to another function my problem is not solved. So instead of only showing the code for reading out the list I show the code for when the list is filled as well. How can I fix that I only refer to the green object at all times when reading the list but when using the for loop to draw I get every color???? for(KleurWissel i : gameManager.getColorsList()) { i.colorRectangle.draw(batch); } //Welke kleuren kies je? if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)){ Iterator<KleurWissel> iterator = gameManager.getColorsList().iterator(); while(iterator.hasNext()) { KleurWissel item = (KleurWissel) iterator.next(); if(item.getRectangle().contains(input.x, input.y)) { if(firstColor == true && secondColor == false && item.selected == false) { colorArraySecond = item.colorArray; colorArrayUsed = colorArrayFirst; colorSelected = true; item.selected = true; secondColor = true; break; } if(firstColor == false && item.selected == false){ colorArrayFirst = item.colorArray; firstColor = true; item.selected = true; break; } } } } And here the code for filling the list. private int[] colorsRGB = {0, 50, 150, 150, 200, 255}; float[] colorArrayUsed = new float[4]; private ArrayList<KleurWissel> colorsList = new ArrayList<KleurWissel>(); public void setColorsList() { Vector2 tempV; KleurWissel temp; for(int i = 0; i < 6; i++) { if(i<3) { colorArrayUsed[0] = colorsRGB[5-i]; colorArrayUsed[1] = colorsRGB[0+i]; colorArrayUsed[2] = 0; colorArrayUsed[3] = 1; tempV = new Vector2(Gdx.graphics.getWidth()/2 - 150 + i * 150, Gdx.graphics.getHeight()/2 + 130); } else{ if(i == 3) { colorArrayUsed[0] = 0; colorArrayUsed[1] = 0; colorArrayUsed[2] = colorsRGB[5]; colorArrayUsed[3] = 1; tempV = new Vector2(Gdx.graphics.getWidth()/2 - 150, Gdx.graphics.getHeight()/2); } else{ colorArrayUsed[0] = 0; colorArrayUsed[1] = colorsRGB[0+i]; colorArrayUsed[2] = colorsRGB[5-i]; colorArrayUsed[3] = 1; tempV = new Vector2(Gdx.graphics.getWidth()/2 - 600 + i * 150, Gdx.graphics.getHeight()/2); } } temp = new KleurWissel(colorArrayUsed, tempV); colorsList.add(temp); } } public ArrayList<KleurWissel> getColorsList() { return colorsList; } KleurWissel is the color object, sorry for the bit of Dutch >.>. A: Edited based on the comments: The libGDX Rectangle class has a contains method, and it seems like this is what you are checking there manually. You could also print some information that tells you more about whether an object was hit or not. It seems like the intended process is the following: * *When the first item is clicked, its color should be stored as colorArrayFirst *When the second item is clicked, its color should be stored as colorArraySecond, and the colorSelected flag should be set to true The followign code shows how this could be done. But the question still when this information will be "reset". That is, when will both arrays be reset to null, and when will the colorSelected flag be reset to false? private boolean colorSelected = false; private int colorArrayFirst[] = null; private int colorArraySecond[] = null; void someGameLoopMethod() { if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)) { Iterator<ColorObject> iterator = gameManager.getColorsList().iterator(); while(iterator.hasNext()) { ColorObject item = (ColorObject) iterator.next(); float x = Gdx.input.getX(); float y = Gdx.input.getY(); Rectangle r = item.colorRectangle; System.out.println("Check if "+x+" "+y+" is in "+r+": "+r.contains(x,y)); if (r.contains(x,y)) { clickedItem(item); } } } } private void clickedItem(ColorObject item) { if (colorArrayFirst == null) { colorArrayFirst = item.colorArray; } else if (colorArraySecond == null) { colorArraySecond = item.colorArray; colorSelected = true; } } // TODO Think about when this method should be called private void resetClickingInformation() { colorSelected = false; colorArrayFirst = null; colorArraySecond = null; } A: The logic in your original question is fine, except that you need to add either secondColor = true; break; inside the block with if(firstColor == true && secondColor == false). If you don't do this, then after you set the second colour, you will keep iterating through the ColorObject objects, looking for more of them that include the point that was clicked, until eventually, you get to the last one - which presumably spans the whole canvas and has green as its colour. The break; isn't strictly necessary, but it saves you from having redundant iterations.
doc_23537415
I've tried a few different things but end of the day, I am still getting this error: Invoke-SqlVulnerabilityAssessmentScan : SetParent failed for Database '[master]'. At line:1 char:1 + Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstan ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Invoke-SqlVulnerabilityAssessmentScan], FailedOperationException + FullyQualifiedErrorId : Microsoft.SqlServer.Management.Smo.FailedOperationException,Microsoft.SqlServer.Management.PowerShell.VulnerabilityAssessment.InvokeVulnerabilityAssessmentScan $cred = Get-Credential $instance = "server\sqldb" Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstance $srv -DatabaseName "master" I also tried this: $cred = Get-Credential $instance = "server\sqldb" $srv = New-Object Microsoft.SqlServer.Management.Smo.Server -argumentlist $instance $db = New-Object Microsoft.SqlServer.Management.Smo.Database -argumentlist $srv, "master" Invoke-SqlVulnerabilityAssessmentScan -Credential $cred -ServerInstance $srv -DatabaseName $db but still gives me the same result. Any help with this is immensely appreciated!
doc_23537416
* *carousel() in HTML file? This is an automatic slideshow of pictures. how this java script function call into HTML file, so the slideshow display and run automatically? also pictures change after a short time . var slideIndex = 0; carousel(); function carousel() { var i; var x = document.getElementsByClassName("slides"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } slideIndex++; if (slideIndex > x.length) {slideIndex = 1} x[slideIndex-1].style.display = "block"; setTimeout(carousel, 2000); // Change image every 2 seconds } <!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>PUCIT</title> <script type="text/javascript" src="js.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="slideshow" > <img class="slides" src="pic1.jpg"> <img class="slides" src="pic3.jpg"> <img class="slides" src="pic4.jpg"> <img class="slides" src="pic5.jpg"> <img class="slides" src="pic2.jpg"> </div> </body> </html> A: I assume js.js is the file in question , which contain the carousel(). The way you include the file into the HTML: <script type="text/javascript" src="js.js"></script> means it have to be in the same folder as the html file. The only thing you have to do to execute the function is to call it. Put this code before closing tag: <script type="text/javascript"> carousel(); </script>
doc_23537417
<form method="get" action="search.php" name="search" onsubmit="return Validate();"> <input type="text" class="searchit" title="Search..." name="search" id="search" /><br/> <label><span> </span> <input name="submitter" type="submit" value="Search" class="searchsubmitButton" id="submitter" /></label> <span class="searchfor">Search for:</span> <label><span> </span> <input name="c" type="submit" value="Users" class="searchsubmitButton" id="submitter" /></label> <label><span> </span> <input name="c" type="submit" value="Clips" class="searchsubmitButton" id="submitter" /></label> <label><span> </span> <input name="c" type="submit" value="Topics" class="searchsubmitButton" id="submitter" /></label> </form> A: because your input fields are inside the <label></label> tags ? A: Take a look at this thread: Safari and Chrome back button changes hidden and submit values in forms The easiest solution I can think of is for you to create a hidden field called "c". Then, when the submit button is clicked, set the value (Users, Clips or Topics) in "c" hidden field first before submitting the form.
doc_23537418
A: scala> scala.tools.nsc.io.Process("ls -1 /tmp | wc").stdout foreach println 41 63 770 Or there's a repl command: scala> :sh cat /etc/passwd | wc stdout: List[String] = List( 65 185 3667) Shipping any IO code with 2.8 was going to require overcoming more stop energy than I can beat, so I put it all in the compiler. Plenty of reasonably useful stuff in scala.tools.nsc.io. A: As of Scala 2.9, you can do: import scala.sys.process.Process println(Process("uname -a").!!.contains("x86_64")) A: It's not quite right to even say that Java does this, because of differing process/stream handling on different operating systems, much of this functionality is actually passed off to native code. A more interesting question would then be to ask if Scala has any way to work more "idiomatically" with readers and writers (or channels if you're wrapping your streams with NIO functionality) And the answer? At the moment there is work underway on a scala IO library to be based on 2.8, this will almost certainly include a better way to work with streams and channels, but isn't yet available. You might also find actors to be a better way of handling the common practice of using one thread for input and one thread for output when dealing with an exec()'d process.
doc_23537419
A: If you wrap the title in a <label for="checkboxID">, then clicking on the title will fire the checkbox's click event. See here for a quick example. A: $('#myCheckbox').change(function(){ doStuff();}); $('#myCheckboxsLabel').click(function(){ doStuff();}); So long as you use the same doStuff() function for both, you should be ok A: If <label for="id"> tags don't trigger your jQuery you may need a plugin to do it for you. Try labelify, I've heard good things (though not directly related to your question).
doc_23537420
class Base { // ... snipped bool operator==( const Base& other ) const { return name_ == other.name_; } }; class Derived : public Base { // ... snipped bool operator==( const Derived& other ) const { return ( static_cast<const Base&>( *this ) == static_cast<const Base&>( other ) ? age_ == other.age_ : false ); }; Now when I instantiate and compare like this ... Derived p1("Sarah", 42); Derived p2("Sarah", 42); bool z = ( p1 == p2 ); ... all is fine. Here the operator== from Derived gets called, but when I loop over a list, comparing items in a list of pointers to Base objects ... list<Base*> coll; coll.push_back( new Base("fred") ); coll.push_back( new Derived("sarah", 42) ); // ... snipped // Get two items from the list. Base& obj1 = **itr; Base& obj2 = **itr2; cout << obj1.asString() << " " << ( ( obj1 == obj2 ) ? "==" : "!=" ) << " " << obj2.asString() << endl; Here asString() (which is virtual and not shown here for brevity) works fine, but obj1 == obj2 always calls the Base operator== even if the two objects are Derived. I know I'm going to kick myself when I find out what's wrong, but if someone could let me down gently it would be much appreciated. A: That's because you haven't made your operator== virtual so the actual type is not taken into account at runtime. Unfortunately, just making the operator== virtual is not going to solve your problem. The reason why is that when you change the function signature by changing the type of the argument from base to derived, you are actually creating a new function. It sounds like you want to look into double-dispatch to solve your problem. A: There are two ways to fix this. First solution. I would suggest adding some extra type logic to the loop, so you know when you have a Base and when you have a Derived. If you're really only dealing with Derived objects, use list<Derived*> coll; otherwise put a dynamic_cast somewhere. Second solution. Put the same kind of logic into your operator==. First make it virtual, so the type of the left-hand operand is determined at runtime. Then manually check the type of the right-hand operand. virtual bool operator==( const Base& other ) const { if ( ! Base::operator==( other ) ) return false; Derived *other_derived = dynamic_cast< Derived * >( &other ); if ( ! other_derived ) return false; return age_ == other_derived->age_; } but considering that objects of different types probably won't be equal, probably what you want is virtual bool operator==( const Base& other ) const { Derived *other_derived = dynamic_cast< Derived * >( &other ); return other_derived && Base::operator==( other ) && age_ == other_derived->age_; } A: You need to make operator== virtual and you need to make sure that they both methods have the same signature. i.e. they will likely need to both take Base. You could have an overloaded operator== in your derived class that would be able to handle Derived objects. A: When a member function is virtual, the virtual table is used at runtime to polymorphically call the function on the type that the pointer actually points to (in this case, your class Derived). When a function is not virtual, no virtual table lookup is done and the function the given type is called (in this case, your class Base). Here, your operator=() functions are not virtual, so the type of the pointer is used rather than the type that the pointer points to. A: For derived classes to use their own implementation of an operator the operator must be virtual in the base class, otherwise the base classes implementation will be used instead.
doc_23537421
So basically what I have is a 3x3-Matrix and each of the elements has a number from 1 to 3. This Matrix is predefined, now all I need to do is create a function which when I input 1, 2 or 3 tells me how many elements there are in this matrix with this value. I've been trying around with different things but none of them appear to be allowed, for example I've defined 3 variables for each of the possible numbers and tried to define them by value w = let a=0 b=0 c=0 in if matrix 1 1==1 then a=a+1 else if matrix 1 1==2 then b=b+1 etc. etc. for every combination and field. <- ignoring the wrong syntax which I'm really struggling with, the fact that I can't use a "=" with "if, then" is my biggest problem. Is there a way to bypass this or maybe a way to use "stored data" from previously defined functions? I hope I made my question somewhat clear, as I said I've only been at programming for 2 days now and I just can't seem to find a way to make this work! A: By default, Haskell doesn't use updateable variables. Instead, you typically make a new value, and pass it somewhere else (e.g., return it from a function, add it into a list, etc). I would approach this in two steps: get a list of the elements from your matrix, then count the elements with each value. -- get list of elements using list comprehension elements = [matrix i j | i <- [1..3], j <- [1..3]] -- define counting function count (x,y,z) (1:tail) = count (x+1,y,z) tail count (x,y,z) (2:tail) = count (x,y+1,z) tail count (x,y,z) (3:tail) = count (x,y,z+1) tail count scores [] = scores -- use counting function (a,b,c) = count (0,0,0) elements There are better ways of accumulating scores, but this seems closest to what your question is looking for. Per comments below, an example of a more idiomatic counting method, using foldl and an accumulation function addscore instead of the count function above: -- define accumulation function addscore (x,y,z) 1 = (x+1,y,z) addscore (x,y,z) 2 = (x,y+1,z) addscore (x,y,z) 3 = (x,y,z+1) -- use accumulation function (a,b,c) = foldl addscore (0,0,0) elements
doc_23537422
When I say "neto area" I mean - the actual visible area that we see on the screen. for instance, you can see in news websites an image and text/headline on that picture, the text is covering part of the picture. In that case I would like to have the image area without the text area. I have tried many methods such as recursion which is counting area of all elements - without succeed. Is there any simple way to get that information? Thank you very much, A: To get the width/height/area in px Pure JavaScript var el = document.getElementById('myElement'); var width = el.offsetWidth; var height = el.offsetHeight; var area = width * height; jQuery var el = $('#myElement'); var width = el.outerWidth(); var height = el.outerHeight(); var area = width * height;
doc_23537423
Upload component looks like this: class MyUpload extends Component { constructor() { super(); this.state = { src: 'source-to-image', crop: { x: 10, y: 10, aspect: 9 / 16, width: 100 } } } onCropComplete = (crop, pixelCrop) => { this.setState({ crop }) }; render() { return ( <ReactCrop src={this.state.src} onComplete={this.onCropComplete} /> ); } } Method onCropComplete returns only coordinates, width and height of cropped image, not source. I would like to get blob file. EDIT (working solution -- thanks for Mosè Raguzzini reply): If someone has similiar problem, call getCropptedImg function from tutorial in your component and create url from returned Blob object, like this: getCroppedImg(this.state.image, pixelCrop, 'preview.jpg') .then((res) => { const blobUrl = URL.createObjectURL(res); console.log(blobUrl); // it returns cropped image in this shape of url: "blob:http://something..." }) A: react-image-crop is not meant to be used to produce blobs, is only meant to crop images inline. Probably you need something like https://foliotek.github.io/Croppie/ UPDATE: Check the section "What about showing the crop on the client?" at bottom of https://www.npmjs.com/package/react-image-crop, the blob is available as hidden feature /** * @param {File} image - Image File Object * @param {Object} pixelCrop - pixelCrop Object provided by react-image-crop * @param {String} fileName - Name of the returned file in Promise */ function getCroppedImg(image, pixelCrop, fileName) { const canvas = document.createElement('canvas'); canvas.width = pixelCrop.width; canvas.height = pixelCrop.height; const ctx = canvas.getContext('2d'); ctx.drawImage( image, pixelCrop.x, pixelCrop.y, pixelCrop.width, pixelCrop.height, 0, 0, pixelCrop.width, pixelCrop.height ); // As Base64 string // const base64Image = canvas.toDataURL('image/jpeg'); // As a blob return new Promise((resolve, reject) => { canvas.toBlob(file => { file.name = fileName; resolve(file); }, 'image/jpeg'); }); } async test() { const croppedImg = await getCroppedImg(image, pixelCrop, returnedFileName); }
doc_23537424
These controls have some transparency themselves. The problem is that these controls overlap each other a little. The overlapping part is transparent so that shouldn't be a problem. Unfortunately it isn't working like it should instead of the transparency to show the control below it cuts out that part of the control. Does anyone know what could be the problem here and how to solve it?
doc_23537425
=VLOOKUP(a1,SORT(range,1,TRUE),2) =ArrayFormula(iferror(VLOOKUP(Q2:Q,SORT(R2:S,1,TRUE),2),"")) Any other ideas on how to make an array formula which finds the closes value in a row? A: try: =ARRAYFORMULA(IF(ABS(B2:B-C2:C)<ABS(B2:B-D2:D), C2:C, D2:D)) for multiple columns: =ARRAYFORMULA(TRIM(TRANSPOSE(QUERY(TRANSPOSE( IF(QUERY(TRANSPOSE(QUERY(TRANSPOSE(ABS(B2:B-C2:G)), "select "&TEXTJOIN(",", 1, "min(Col"&ROW(B2:B)-ROW(B2)+1&")")&"")), "select Col2")=ABS(B2:B-C2:G), C2:G, )),,99^99))))
doc_23537426
I'm baffled as to how I'm supposed to get both of them to load. I have a function in ThisAddIn.vb that can't possibly do what I want it to do - load both ribbons: Protected Overrides Function CreateRibbonExtensibilityObject() As _ Microsoft.Office.Core.IRibbonExtensibility Return New RibbonAttachAttachmentToPO() Return New RibbonOutlook14ReadMail() End Function What is the best solution to this problem? A: You will have 2 XML files, one for the TabReadMessage and one for the Attachment context menu. And then you will need only one Ribbon class, CreateRibbonExtensibilityObject() loads the Ribbon class. In the Ribbon class's GetCustomUI() function, you will load the corresponding XML file base on which part of the Outlook you are in, whether in the explorer or inspector. You can do this (VB.Net): Public Function GetCustomUI(ByVal ribbonID As String) As String Implements Microsoft.Office.Core.IRibbonExtensibility.GetCustomUI Select Case ribbonID Case "Microsoft.Outlook.Mail.Read" 'For TabReadMessage Return GetResourceText("The.Read.Message.XML") Case "Microsoft.Outlook.Mail.Compose" 'For compose new email message Return GetResourceText(".....") Case ... End Select End Function
doc_23537427
( select add_months(sysdate,-2)dt from dual union select add_months(sysdate,-1) from dual union select add_months(sysdate,2)from dual union select add_months(sysdate,3) from dual ) i want to maximum year of minimum date (" 22.02.2012 12:02:08 ") How to make this? A: use select max(dt) instead of select * Edit: after rereading your question and comparing your desired output, you probably want the minimum date of the dates within the maximum year. In that case, the statement will be with dates as ( select add_months(sysdate,-2)dt from dual union select add_months(sysdate,-1) from dual union select add_months(sysdate,2)from dual union select add_months(sysdate,3) from dual ) select min(dt) from dates where trunc(dt,'YYYY') = (select max(trunc(dt, 'YYYY')) from dates) A: You can use this one: SELECT * FROM ( SELECT add_months(sysdate,-2)dt from dual UNION ALL SELECT add_months(sysdate,-1) from dual UNION ALL SELECT add_months(sysdate,2)from dual UNION ALL SELECT add_months(sysdate,3) from dual ORDER BY trunc(dt,'YEAR') DESC, trunc(dt,'MONTH') ASC ) WHERE rownum = 1 A: Not sure whether that's what you're looking for. The question wasn't really clear to me. SELECT MIN(dt) FROM (SELECT add_months(SYSDATE, -2) dt FROM dual UNION SELECT add_months(SYSDATE, -1) FROM dual UNION SELECT add_months(SYSDATE, 2) FROM dual UNION SELECT add_months(SYSDATE, 3) FROM dual) WHERE trunc(dt, 'YYYY') > trunc(SYSDATE, 'YYYY');
doc_23537428
import random def make_foo(param1, param2): class Foo: def __init__(self, special): self.param1 = param1 self.param2 = param2 self.special = special def do(self): print "%s is doing" % self def __str__(self): return "Foo<%s,%s with %s>" % (self.param1, self.param2, self.special) return Foo def make_bar(foo): class Bar: def __init__(self, special): self.foo = foo(special) def do(self): print "%s is doing" % (self,) def __str__(self): return "Bar<%s>" % self.foo return Bar def make_grouper(foobars): class Grouper: def __init__(self, special): self.foobars = [foobar(special) for foobar in foobars] return Grouper def make_special(howtomake, groups): class Special: def __init__(self): self.important = random.choice(howtomake) self.groups = [group(self) for group in groups] def __str__(self): return "Special<%s>" % self.important return Special Foo10_20 = make_foo(10, 20) Foo30_40 = make_foo(30, 40) Bar = make_bar(Foo10_20) Grouper1 = make_grouper([Foo10_20, Foo30_40]) Grouper2 = make_grouper([Bar, Bar]) Special = make_special("IMPORTANTINFO", [Grouper1, Grouper2]) s = Special() s.groups[0].foobars[0].do() s.groups[0].foobars[1].do() s.groups[1].foobars[0].do() s = Special() s.groups[0].foobars[0].do() s.groups[0].foobars[1].do() s.groups[1].foobars[0].do() Sample output: Foo<10,20 with Special<O>> is doing Foo<30,40 with Special<O>> is doing Bar<Foo<10,20 with Special<O>>> is doing Foo<10,20 with Special<I>> is doing Foo<30,40 with Special<I>> is doing Bar<Foo<10,20 with Special<I>>> is doing It can be summarized as having to create a set of classes which need to be bound to a special argument (so all the constructors, once the classes are done, just take a special argument). Can this be done more elegantly using meta-classes, or is this code fine the way it is? A: Since I generally prefer classes of closures in Python, I'd use factory classes here and avoid the use of dynamically created classes alltogether. Example: class Foo: def __init__(self, param1, param2, special): self.param1 = param1 self.param2 = param2 self.special = special def do(self): print "%s is doing" % self def __str__(self): return "Foo<%s,%s with %s>" % (self.param1, self.param2, self.special) class FooFactory: def __init__(self, param1, param2): self.param1 = param1 self.param2 = param2 def __call__(self, special): return Foo(self.param1, self.param2, special) foo_factory = FooFactory(1, 2) foo = foo_factory(3) An alternative to FooFactory would be the use of functools.partial(). If Foo is defined as above, you could do FooSpecialised = functools.partial(Foo, param1, param2) and create instances of Foo by using FooSpecialised(special) A: This is not strictly an answer (or maybe it is) but I think this quote (MarkLutz, learning python 4 ed) of a quote from Tim Peters could be interesting: To borrow a quote from the comp.lang.python newsgroup by veteran Python core developer Tim Peters (who is also the author of the famous “import this” Python motto): [Metaclasses] are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don’t (the people who actually need them know with certainty that they need them, and don’t need an explanation about why). A: I ended up making a base class: class Base(object): @classmethod def bind_init(cls, *args, **kwargs): def init(special): return cls(special, *args, **kwargs) return init Foo et. al. are a normal-looking non-dynamic classes now: class Foo(Base): def __init__(self, special, param1, param2): self.param1 = param1 self.param2 = param2 self.special = special def do(self): print "%s is doing" % self def __str__(self): return "Foo<%s,%s with %s>" % (self.param1, self.param2, self.special) and they are used as follows: Foo10_20 = Foo.bind_init(10, 20) Foo30_40 = Foo.bind_init(30, 40) Bar = Bar.bind_init(Foo10_20) Grouper1 = Grouper.bind_init([Foo10_20, Foo30_40]) Grouper2 = Grouper.bind_init([Bar, Bar]) Special = Special.bind_init("IMPORTANTINFO", [Grouper1, Grouper2]) this minimizes code repetition (don't have to make tons of factory classes) and I also like the lingo much more than class factory.
doc_23537429
$eventnameentered= strtolower($eventnameentered); $eventindatabase=file('eventname.txt'); if(in_array($eventnameentered,$eventindatabase)){ echo 'Entered Event Name '.$eventnameentered.' Is Already Taken'; }else if($eventnameentered==''){ echo 'Please Enter Name Of New Event'; } else { echo 'Event Name '.$eventnameentered.' Is Available '; } event.txt gaming coding project I'am using AJAX. Everything is working properly, I just need some help with this array thing. I want to compare eventname given by user and eventname already present in event.txt do not clash. So I want event.txt in an array. I am comparing it with in_array as shown in the above code but even if I insert event present in event.txt it shows Event name Available. I even tried using get_file_contents. A: Whitespace is causing your if condition to fail. You need to trim the whitespace first. $eventindatabase = file('eventname.txt'); $eventindatabase = array_map('trim', $eventindatabase); Here's the output of var_dump($eventindatabase) before and after trimming the whitespace: Before: array(3) { [0]=> string(7) "gaming " [1]=> string(7) "coding " [2]=> string(7) "project" } After: array(3) { [0]=> string(6) "gaming" [1]=> string(6) "coding" [2]=> string(7) "project" } As you can see, the first two elements are different, and that'll cause the following condition to evaluate to FALSE, hence triggering the else statement: if(in_array($eventnameentered,$eventindatabase)) Hope this helps!
doc_23537430
345 eee 12 nt 3 s 9 test How can I make it so it sorts it in numerical order with the text there? The output I'm hoping for is 345 eee 12 nt 9 test 3 s Note: I'm grabbing data from text files 45 eee 12 nt 945 test 344 s 45 gh Current Code Credit: @CypherX import pandas as pd s = """ 345 eee 1200 nt 9 test -3 s """ # Custom Function def sort_with_digits(s, ascending = True): lines = s.strip().split('\n') df = pd.DataFrame({'Lines': lines}) df2 = df.Lines.str.strip().str.split(' ', expand=True).rename(columns={0: 'Numbers', 1: 'Text'}) df['Numbers'] = df2['Numbers'].astype(float) df['Text'] = df2['Text'].str.strip() df.sort_values(['Numbers', 'Text'], ascending = ascending, inplace=True) return df.Lines.tolist() print(s) sort_with_digits(s, ascending = True) # this is your output A: Using python and no system calls: # This is the function to amend when you want to change the ordering def key_function(line): # To sort by the first number when there is a space return int(line.split()[0]) To extract any number that begins the line you can use a regex def key_function(line): match = re.match('^\d+', line) if match: return int(match.group()) else: return 0 Then the rest of the method is the same with open(file_name, 'r') as f: # Read all lines into a list lines = f.readlines() with open(file_name, 'w') as f: # Sort all the lines by "key_function" for line in sorted(lines, key=key_function, reverse=True): f.write(line + '\n') A: Here is the solution in bash. you can use subprocess to run it in python. sort -k1 -r -n file > new_file Using this with pyhton subprocess import subprocess # Simple command subprocess.Popen(['sort -k1 -r -n test.txt'], shell=True) A: EDIT: The OP described later that the requirement is to first order by numbers and then order by the rest of text that follows. The solution now reflects this requirement. I wrote a custom function (sort_with_digits) which finds out the numbers and then sorts the lines accordingly using pandas library. All you have to do is: #read-in data from a text file: with open('input.txt', 'r') as f: s = f.read() sort_with_digits(s, ascending = True) Code with Example Data s = """ 345 eee 12 nt 9 test 3 s """ import pandas as pd # Custom Function def sort_with_digits(s, ascending = True): lines = s.strip().split('\n') df = pd.DataFrame({'Lines': lines}) df2 = df.Lines.str.strip().str.split(' ', expand=True).rename(columns={0: 'Numbers', 1: 'Text'}) df['Numbers'] = df2['Numbers'].astype(float) df['Text'] = df2['Text'].str.strip() df.sort_values(['Numbers', 'Text'], ascending = ascending, inplace=True) return df.Lines.tolist() sort_with_digits(s, ascending = True) Output: ['3 s', '9 test', '12 nt', '345 eee'] Note: If you use a simple '\n'.join(result) on a list (result) that will produce a string formatted similar to out the input (s). result = sort_with_digits(s, ascending = True) print('\n'.join(result)) Output: 12 nt 45 eee 45 gh 344 s 945 test With Another Dummy Dataset * *Dummy Data: A s = """ 345 eee 1200 nt 9 test -3 s """ # Expected Result: ['-3 s', '9 test', '345 eee', '1200 nt'] # And the solution produces this as well. *Dummy Data: B s = """ 45 eee 12 nt 945 test 344 s 45 gh """ # Expected Result: ['12 nt', '45 eee', '45 gh', '344 s', '945 test'] # And the solution produces this as well. A: All right, here's a bad answer: #!/usr/bin/python import os os.system('sort -n -r /path/to/file') I used python to run a shell command "sort" using the numeric and reverse options. I used python because you tagged the question python. I used the -r option because your output example seems to be sorted in reverse order. This would be a better answer if it used subprocess instead of os.system (as the other answer mentions).
doc_23537431
I want to validate three form fields. The usual method is like this: class User { String name String password String personalInfo static constraints = { name(size: 4..20, unique:true, blank:false) password(size:8..20, blank:false) personalInfo(size: 1000, nullable:true) } } but in my gsp i'll be having all three textfields in the same name eg: <td>Name:</td><td><g:textfield name="property"/></td> <td>Password:</td><td><g:textfield name="property"/></td> <td>PersonalInfo:</td><td><g:textfield name="property"/></td> How to validate this form???? A: It is a really bad practice to give the same name to input fields in a form that are going to be mapped to different properties in the same domain class. But if you cant, the fields will be sent as a list to your controller. So you can extract values in the controller like this: def parameterList = params.property as List def name = parameterList[0] def password = parameterList[1] def personalInfo = parameterList[2] Then you can create your User object def user = new User(name:name, personalInfo:personalInfo, password:password) if (user.save()){ } else{ } As the best practice you must name your fields in the form differently
doc_23537432
myCars with values: Ford Ford VW Renault Jeep Jeep which is referenced via: myCars.Makers I wish to create a distinct comma delimited string from this such that I get: Ford,VW,Renault,Jeep I am guessing that I need to run a distinct clause on myCars, but then am unsure about how to convert to comma delimited string as above. Many thanks in advance A: use string.Join and Distinct string.Join(",", myCars.Makers.Distinct());
doc_23537433
--detached I would run my container by calling docker run -t -d -p 3333:3333 -p 3000:3000 --name <name> <image_ID> Im using a VM instance on Gcloud and the container option seems to not have this detached argument (which is killing my ubuntu-based container from stopping when not used). Both using the Computing Engine OS and Google Cloud Run service option eventually results in an error. A: Your question lacks detail. Questions benefit from details including the specific steps that were taken, the errors that resulted or the steps that were taken to diagnose the error etc. I assume from your question that you're using Cloud Console to create a Compute Engine instance and your're selecting "Container" to deploy a container image to it. The default configuration is to run the container detached i.e. equivalent to docker run --detach. You can prove this to yourself by SSH'ing in to the instance and running e.g. docker container ls to see the running containers or docker container ls --all to see all containers (stopped too). You can also run the container directly from here too as you would elsewhere although you may prefer to docker run --interactive --stdin or docker container logs ... to determine why it's not starting correctly : docker run \ --stdin \ --detach \ --publish=3333:3333 \ --publish=3000:3000 \ --name=<name> \ <image_ID>
doc_23537434
(in /home/deadpool/Documents/learn_ruby) /home/deadpool/Documents/learn_ruby/rspec_config.rb:3:in `block in <top (required)>': undefined method `color=' for #<RSpec::Core::Configuration:0x0000000293dee0> (NoMethodError) from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core.rb:67:in `configure' from /home/deadpool/Documents/learn_ruby/rspec_config.rb:1:in `<top (required)>' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/configuration.rb:162:in `require' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/configuration.rb:162:in `block in requires=' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/configuration.rb:162:in `map' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/configuration.rb:162:in `requires=' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/configuration_options.rb:22:in `block in configure' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/configuration_options.rb:21:in `each' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/configuration_options.rb:21:in `configure' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/command_line.rb:17:in `run' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/runner.rb:55:in `run_in_process' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/runner.rb:46:in `run' from /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/runner.rb:10:in `block in autorun' rake aborted! ruby -S bundle exec rspec -I/home/deadpool/Documents/learn_ruby/00_hello -I/home/deadpool/Documents/learn_ruby/00_hello/solution -f documentation -r ./rspec_config "/home/deadpool/Documents/learn_ruby/00_hello/hello_spec.rb" failed /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/rake_task.rb:117:in `rescue in block (2 levels) in initialize' /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/rake_task.rb:113:in `block (2 levels) in initialize' /home/deadpool/.rvm/gems/ruby-2.0.0-p481/gems/rspec-core-2.0.0/lib/rspec/core/rake_task.rb:109:in `block in initialize' Tasks: TOP => default => spec (See full trace by running task with --trace) I tried to google some of the errors, but with no success. I had previously another error with the rake file using rspec v2 and the current version is 3.0.0, so I had to install the older and I think it might be another setup problem. Thanks if someone can help me or direct me. rspec_config.rb file : RSpec.configure do |c| c.fail_fast = true c.color = true end hello.rb file: def hello "Hello!" end def greet(who) "Hello, #{who}!" end UPDATE Getting new error as :- While I changed c.color = true to c.color_enabled = true (in /home/deadpool/Documents/learn_ruby) the hello function says hello (FAILED - 1) Failures: 1) the hello function says hello Failure/Error: Unable to find matching line from backtrace undefined method run_all' for []:Array # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/hooks.rb:116:inrun_hook_filtered' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/example_group.rb:176:in eval_before_alls' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/example_group.rb:231:inrun' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/command_line.rb:26:in block (2 levels) in run' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/command_line.rb:26:inmap' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/command_line.rb:26:in block in run' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/reporter.rb:11:inreport' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/command_line.rb:23:in run' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/runner.rb:55:inrun_in_process' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/runner.rb:46:in run' # /home/deadpool/.rvm/gems/ruby-2.1.2/gems/rspec-core-2.0.0/lib/rspec/core/runner.rb:10:inblock in autorun' UPDATE hello_spec.rb file : require "hello" describe "the hello function" do it "says hello" do hello.should == "Hello!" end end describe "the greet function" do it "says hello to someone" do greet("Alice").should == "Hello, Alice!" end it "says hello to someone else" do greet("Bob").should == "Hello, Bob!" end end UPDATE So, I updated rspec to v3.0.0 and changed Rakefile gem 'rspec', '~>3.0.0' and c.color = true back. Everything is working now(getting some deprecation warnings, but nothing critical), getting the output that is in the tutorial. Guess I just had to updae my rspec and change the version in the Rakefile. Thank you so much :) A: Your error log is showing you are in rspec-core-2.0.0 version and your error is saying - rspec_config.rb:3:in `block in <top (required)>': undefined method `color=' for #<RSpec::Core::Configuration:0x0000000293dee0> (NoMethodError) Now Deprecate config options confirms that below versions of 2.99.0.rc1 / 2014-05-18 or 2.99.0 methods were - #color_enabled, #color_enabled= and #color?. Which are changed since 2.99.0 to #color, #color= and #color_enabled?. I got the information from the changelog as I linked - Deprecate #color_enabled, #color_enabled= and #color? in favour of #color, #color= and #color_enabled? output. (Jon Rowe) Thus you need to write as RSpec.configure do |c| c.fail_fast = true c.color_enabled = true end Regarding your new error, I found it as a bug undefined methodrun_all' for []:Array`. Which has been fixed in this patch. Check this Rspec issue. My suggestion use Rspec 3.0, at least you will be happy. In this case revert the color_enabled to color. Hope this would help you.
doc_23537435
str_replace(as.character(iris$Species), "setosa", NA) It says that requires a character for the replacement object, this one actually works: str_replace(as.character(iris$Species), "setosa", "NNAA") Does anybody know if is it possible to replace it with NA without subseting []? Thanks in advance. A: Just because you don't want to subset doesn't mean you should use str_replace where you could do an exact string comparison: library(data.table) setDT(iris) DT[,Species:=ifelse(Species=="setosa", NA_character_, "setosa")] # or simpler DT[,Species:=ifelse(Species=="setosa", NA, "setosa")] # or simpler DT[Species=="setosa",Species:=NA]
doc_23537436
I apologize for the lack of information and quality of the previous version of this question, I will try to rephrase and give more information about my issue. I am currently running a web server using XAMPP in my laptop. The webserver contains several php files that make a website, and a database. Inside the database I created a table for testing purposes called 'test'. This table consists on 2 columns: a timestamp and a value column which accepts integers. One of the php files in the web server is called update.php, and uses GET to write information into the 'test' table in the database, like this: <?php require_once "db.php"; $value = $_GET['value']; $query = " INSERT INTO test(value) VALUES ('".$value."') "; mysqli_query($conn, $query); ?> This works properly, if I go into my browser and type 'http://localhost/swater/update.php?value=2', a new row is successfully added to the table with value 2. This is great, but I need this to be carried out from an ESP8266, which is connected to a button. The goal is that every X seconds the ESP checks if the button is pressed or not. If it is pressed it should add value 1 to the table, and if it is not it should add value 0. I first carried this out connecting the ESP to my house Wi-Fi network, using this code: void loop() { if ((millis() - lastTime) > timerDelay) { if(WiFi.status()== WL_CONNECTED){ WiFiClient client; HTTPClient http; value = digitalRead(4); String serverPath = serverName + "?value=" + value; http.begin(client, serverPath.c_str()); int httpResponseCode = http.GET(); if (httpResponseCode>0) { Serial.print("Response code: "); Serial.println(httpResponseCode); String payload = http.getString(); Serial.println(payload); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); } http.end(); } else { Serial.println("Disconnected"); } lastTime = millis(); } } This worked perfectly fine, and my table started periodically getting values added. However this is not my final goal, as I want the ESP to act as an access point, to which my laptop is connected. I managed to write this code: void setup() { Serial.begin(115200); WiFi.softAP(ssid, pwd); pinMode(4, INPUT); } void loop() { WiFiClient client; HTTPClient http; http.begin(client, "http://192.168.4.2:80/swater/update.php?value=1"); Serial.print("Request sent.\n"); delay(5000); } Note that I am not using the values that the ESP reads, I am just testing so I am skipping that part of the code and just using value=1 all the time. When I run this code in the ESP, I can connect my laptop and my phone to the Wi-Fi that it creates, and I can successfully visit the website from any device connected to it, however no values are added to the 'test' table. I apologize if I now made my explanation too long, but it is my first time working with this kind of systems and it is the first time I ask a question in this platform, I appreciate the help. A: You forget to send your GET request int httpResponseCode = http.GET(); void loop() { WiFiClient client; HTTPClient http; http.begin(client, "http://192.168.4.2:80/swater/update.php?value=1"); int httpResponseCode = http.GET(); if (httpResponseCode>0) { Serial.print("Request sent.\n"); } delay(5000); }
doc_23537437
ImageName UploadStatus test1.jpg 1 test2.jpg 2 I am using cursor to fetch the data as follows: cursor = sqLiteDatabase.rawQuery("SELECT * from activityRes", null); ImageName_Array.clear(); UploadStatus_Array.clear(); if (cursor != null && cursor.getCount() > 0) { if (cursor.moveToFirst()) { do { ImageName_Array.add(cursor.getString(cursor.getColumnIndex("ImageName"))); UploadStatus_Array.add(cursor.getString(cursor.getColumnIndex("UploadStatus"))); // if (cursor.getString(cursor.getColumnIndex("UploadStatus")) == "1") { // UploadStatus_Array.add("Y"); // } else if (cursor.getString(cursor.getColumnIndex("UploadStatus")) == "2") { // UploadStatus_Array.add("N"); // } } while (cursor.moveToNext()); } } The UploadStatus_Array.add gets me the data and displays it as 1 and 2. However, I want to change the display as Y and N. I tried with the commented codes...but it is throwing the entire table out. A: It's better to execute a query that will return the results as you want them and just add them to the lists. All you have to do is use a CASE expression in the SELECT statement and you will have the column UploadStatus populated with Ys and Ns: String sql = "SELECT ImageName, CASE UploadStatus WHEN '1' THEN 'Y' WHEN '2' THEN 'N' END AS UploadStatus FROM activityRes" cursor = sqLiteDatabase.rawQuery(sql, null); ImageName_Array.clear(); UploadStatus_Array.clear(); while (cursor.moveToNext()) { ImageName_Array.add(cursor.getString(cursor.getColumnIndex("ImageName"))); UploadStatus_Array.add(cursor.getString(cursor.getColumnIndex("UploadStatus"))); } There is no need to check if cursor is null. The result of rawQuery() is never null. Also there is no need to check if cursor.getCount() is greater than 0 because while (cursor.moveToNext()) is enough.
doc_23537438
Any ideas? Thanks [2016-02-24 15:15:23,556] ERROR {org.wso2.carbon.device.mgt.ios.util.OAuthUtils} - Error occurred while sending 'Post' request due to failure of server connection javax.net.ssl.SSLException: hostname in certificate didn't match: !=
doc_23537439
E.g, I want to have lib included in every file in my project without having to put the #include <string> in every file A: My answer would be: Don't do that. It will make your code much less portable, harder to read, harder to debug. Headers can be a pain to deal with, but it is what is it until we have a modularized standard library. What you could do though is to create a src/common/includes.h file containing all the stuff you want everywhere: // includes.h #include <string> #include <vector> #include <functional> #include <unordered_map> // ... Add the include directory to your target: target_include_directories(your-exe PUBLIC src/common) Then, in every files, simply include it: #include <includes.h> There exist arguments that will change the compiler behaviour, but this is primarily to deal with precompiled header, which have requirements on the order of inclusion.
doc_23537440
A: Pre filled Realm-database For Android Put your realm database in res/raw folder and execute following code in activity: // Copying realm database copyBundledRealmFile(this.getResources().openRawResource(R.raw.default0), "default0.realm"); RealmConfiguration config0 = new RealmConfiguration.Builder() .name("default0.realm") .build(); realm = Realm.getInstance(config0); private String copyBundledRealmFile(InputStream inputStream, String outFileName) { try { File file = new File(this.getFilesDir(), outFileName); FileOutputStream outputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, bytesRead); } outputStream.close(); return file.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } return null; } A: Realm's documentation has a section on "Bundling a Realm with an App": It’s common to seed an app with initial data, making it available to your users immediately on first launch. Here’s how to do this: * *First, populate the realm. You should use the same data model as your final, shipping app to create a realm and populate it with the data you wish to bundle with your app. Since realm files are cross-platform, you can use an OS X app (see our JSONImport example) or your iOS app running in the simulator. *In the code where you’re generating this realm file, you should finish by making a compacted copy of the file (see -[RLMRealm writeCopyToPath:error:]). This will reduce the Realm’s file size, making your final app lighter to download for your users. *Drag the new compacted copy of your realm file to your final app’s Xcode Project Navigator. *Go to your app target’s build phases tab in Xcode and add the realm file to the “Copy Bundle Resources” build phase. *At this point, your bundled realm file will be accessible to your app. You can find its path by using [[NSBundle mainBundle] pathForResource:ofType:]. *You can either create a read-only realm by calling [RLMRealm realmWithPath:readOnly:error:]. Or, if you’d like to create a writable realm file based on this initial data, you can copy the bundled file to your application’s Documents directory using [[NSFileManager defaultManager] copyItemAtPath:toPath:error:] and then construct your new realm by using [RLMRealm realmWithPath:]. You can refer to our migration sample app for an example of how to use a bundled realm file. A: A much easier way is just creating an ad-hoc function to be called just when there is no data on your realm model ("MyModel", in this example), at first app launch: let realm = try! Realm() lazy var data: Results<MyModel> = { self.realm.objects(MyModel.self) }() func populateDefaultData() { if yourdata.count == 0 { try! realm.write() { let defaultData = ["Data1", "Data2", "Data3"] for data in defaultData { let newData = MyModel() newData.data = data realm.add(newData) } } data = realm.objects(MyModel.self) } } override func viewDidLoad() { super.viewDidLoad() populateDefaultData() }
doc_23537441
vendor date item_price discount_price x 2021-07-08 23:41:10 451,5 0 y 2021-06-14 10:22:10 41,7 0 z 2020-01-03 13:41:12 74 4 s 2020-04-12 01:14:58 88 12 .... exactly what I want is to group this data by month and find the sum of the sales of only the top 20 vendors in that month. Expected output: month vendor_name(top20) sum_of_vendor's_sales sum_of_vendor's_discount item_count(sold) 2020-01 x1 10857 250 150 2020-01 x2 9685 410 50 2020-01 x3 3574 140 45 .... 2021 01 x20 700 15 20 2020-02 y1 7421 280 120 2020-02 y2 6500 250 40 2020-02 y3 4500 200 70 ..... 2020-02 y20 900 70 30 i tried this (source here). But The desired output could not be obtained. select month, (select sum(sum) from t.top_20_vendors) as sum_of_only_top20_vendor_sales from ( select format_datetime('%Y%m', date) month, approx_top_sum(vendor, item_price, 20) top_20_vendors,count(item_price) as count_of_items,sum(discount_price) from my_table group by month ) t A: Consider below approach select format_datetime('%Y%m', date) month, vendor as vendor_name_top20, sum(item_price) as sum_of_vendor_sales, sum(discount_price) as sum_of_vendor_discount, count(*) as item_count_sold from your_table group by vendor, month qualify row_number() over(partition by month order by sum_of_vendor_sales desc) <= 20
doc_23537442
A: You can customize the tooltip behavior by setting the desired values in the tooltip object. In your case valueDecimals property of tooltip is of your concern. See the api docs for the same. tooltip: { valueDecimals: 2 }, Check out: jsFiddle
doc_23537443
There are several options available when launching this module on the command line. For example http-server -p 8085 to launch on port 8085. Is there any way for me to see all of the possible options displayed without having to go online to check the NPM documentation page? Is there A: Just use the --help flag: http-server --help And you will see this: options: -p Port to use [8080] -a Address to use [0.0.0.0] -d Show directory listings [true] -i Display autoIndex [true] -e --ext Default file extension if none supplied [none] -s --silent Suppress log messages from output --cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header Optionally provide CORS headers list separated by commas -o [path] Open browser window after starting the server -c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds. To disable caching, use -c-1. -U --utc Use UTC time format in log messages. -P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com -S --ssl Enable https. -C --cert Path to ssl cert file (default: cert.pem). -K --key Path to ssl key file (default: key.pem). -r --robots Respond to /robots.txt [User-agent: *\nDisallow: /] -h --help Print this list and exit. If you ever forget, just see the last option in the list.
doc_23537444
Front end code: export default function Talento() { const [getFile, setFile] = useState([]); function handleFile(e){ setFile(e.target.files[0]); } async function handleOnSubmit(e){ // e.preventDefault(); let formData = new FormData(); formData.append('file',getFile); await axios({ method: 'post', url: '/api/mail', data: formData, headers: {'Content-Type': 'multipart/form-data' } }).then(function (response) { success() }).catch(function (response) { //handle error notify() }); } return ( <form method="post" encType='multipart/form-data' onSubmit={handleSubmit} id="myForm" autoComplete="off"> <div className="form-group"> <label htmlFor="linkedin">Adjunta tu curriculum*</label> <input type="file" className="form-control" id="uploadFile" accept="application/pdf" name="uploadFile" onChange={handleFile}/> </div> <div className="ip-form-btn-outer text-end"> <button className="btn btn-main">Enviar solicitud</button> </div> </form> ) } Backend Code import nc from "next-connect"; import onError from "./middleware/middleware"; import multer from "multer"; import path from "path"; import mail from '@sendgrid/mail'; import {google} from 'googleapis' import { Storage } from '@google-cloud/storage'; const GOOGLE_PROJECT_ID = "bucket-id"; const GOOGLE_BUCKET_NAME = "bucket-name"; const GOOGLE_PRIVATE_KEY ="key here" const GOOGLE_CLIENT_EMAIL = "test@cloud.com" export const config = { api: { bodyParser: false, }, }; const handler = nc(onError); let storage = multer.diskStorage({}); let upload = multer({ storage: storage, }); let uploadFile = upload.single("file"); handler.use(uploadFile); handler.post(async (req, res) => { const googleStorage = new Storage({ projectId: GOOGLE_PROJECT_ID, credentials: { client_email: GOOGLE_CLIENT_EMAIL, private_key: GOOGLE_PRIVATE_KEY, }, }); const bucket = googleStorage.bucket(GOOGLE_BUCKET_NAME); const file = bucket.file(req.file); const options = { expires: Date.now() + 1 * 60 * 1000, // 1 minute, fields: { 'x-goog-meta-test': 'data' }, }; console.log(await file.generateSignedPostPolicyV4(options)); const [response] = await file.generateSignedPostPolicyV4(options); res.status(200).json(response); }) export default handler; Response I am getting { "url": "https://storage.googleapis.com/magic-storage-bucket/", "fields": { "x-goog-meta-test": "data", "key": { "fieldname": "file", "originalname": "WSIB coverage.jpg", "encoding": "7bit", "mimetype": "image/jpeg", "destination": "C:\\Users\\intel\\AppData\\Local\\Temp", "filename": "fddd2a3b8264bdf557ebb0c0e260df0e", "path": "C:\\Users\\intel\\AppData\\Local\\Temp\\fddd2a3b8264bdf557ebb0c0e260df0e", "size": 411040 }, "x-goog-date": "20220518T111554Z", "x-goog-credential": "credentialshere", "x-goog-algorithm": "GOOG4-RSA-SHA256", "policy": "policy", "x-goog-signature": "signature here" } } A: The generateSignedPostPolicyV4 function is the first step to upload data. Get a v4 signed policy document to allow a user to upload data with a POST request This is found on the official docs. You should make another fetch with the response that are you getting from generateSignedPostPolicyV4. Hopefully this repo that i found can clarify you about the upload method on Cloud Storage.
doc_23537445
In my case the files on disk are together around 800 kB in size (with indentation and comments, pure class declarations, not many strings), however after including them all, memory consumption was around 40 MB higher. I measured like this (PHP 5.3.6): echo memory_get_usage(), "<br>\n"; include($file); echo memory_get_usage(), "<br>\n"; Within a loop over the 600 files I can watch memory consumption grow from basically zero to 40 MB. (There is no autoloader loading additonal classes, or any global code or constructor code that is executed immediately, it's really the pure include only.) Is this normal behaviour? I assumed opcodes are more compact than pure source code (stripping out all spaces and comments, or having for example just one or two instruction bytes instead of a "foreach" string etc.)? If this is normal, is there a way to optimize it? (I assume using an opcode cache would just spare me the compile time, not the actual memory consumption?) A: Apparently that's just the way it is. I've retested this from the ground up: * *Include an empty zero length file: 784 bytes memory consumption increase *Include an empty class X { } definition: 2128 bytes *Include a class with one empty method: 2816 bytes *Include a class with two empty methods: 3504 bytes The filesize of the include file is under 150 bytes in all tests.
doc_23537446
https://hyperledger.github.io/fabric-sdk-node/release-1.4/tutorial-sign-transaction-offline.html I created a complete Hyperledger Fabric network using this guide: https://hyperledger-fabric-ca.readthedocs.io/en/latest/operations_guide.html The Javascript SDK is working well, and I can query/invoke transactions using the client.setUserContext() method. When trying to sign the transaction offline, the transaction proposal is rejected by the peers with the following response: { Error: 2 UNKNOWN: access denied: channel [mychannel] creator org [org1] at Object.exports.createStatusError ([...]/node_modules/grpc/src/common.js:91:15) at Object.onReceiveStatus ([...]/node_modules/grpc/src/client_interceptors.js:1204:28) at InterceptingListener._callNext ([...]/node/node_modules/grpc/src/client_interceptors.js:568:42) at InterceptingListener.onReceiveStatus ([...]/node/node_modules/grpc/src/client_interceptors.js:618:8) at callback ([...]/node/node_modules/grpc/src/client_interceptors.js:845:24) code: 2, metadata: Metadata { _internal_repr: {} }, details: 'access denied: channel [mychannel] creator org [org1]' } In the logs from the peers, I see the following error: peer1-org1 | 2020-01-13 21:47:31.569 UTC [protoutils] ValidateProposalMessage -> WARN 078 channel [mychannel]: creator's signature over the proposal is not valid: The signature is invalid I do not understand why the signature is rejected. I carefully followed all the steps of the tutorial. Here is the complete client code: // // Imports // var Client = require('fabric-client'); var path = require('path'); var util = require('util'); var fs = require('fs'); const crypto = require('crypto'); const elliptic = require('elliptic'); const { KEYUTIL } = require('jsrsasign'); const config = require('./config'); // // Script configuartion variables // var fcn = 'set'; var args = ["a","60"]; var priv = fs.readFileSync(config.PRIV, 'utf8'); var { prvKeyHex } = KEYUTIL.getKey(priv,'passphrase'); var cert = fs.readFileSync(config.CERT, 'utf8'); const EC = elliptic.ec; const ecdsaCurve = elliptic.curves['p256']; const ecdsa = new EC(ecdsaCurve); const signKey = ecdsa.keyFromPrivate(prvKeyHex, 'hex'); // // Config init // var client = Client.loadFromConfig('network_org1.yaml'); var targets = client.getPeersForOrg('org1'); // // Main // client.initCredentialStores() .then((nothing) => { channel = client.getChannel(config.CHANNEL_NAME); // 1. Generate unsigned transaction proposal var transaction_proposal = { chaincodeId: config.CHAINCODE_NAME, channelId: config.CHANNEL_NAME, fcn: fcn, args: args, }; var { proposal, tx_id } = channel.generateUnsignedProposal(transaction_proposal, 'org1', cert); // 2. Hash the transaction proposal var proposalBytes = proposal.toBuffer(); var digest = client.getCryptoSuite().hash(proposalBytes); //const hash = crypto.createHash('sha256'); //hash.update(proposalBytes); //var digest = hash.digest('hex'); // 3. Calculate the signature for this transacton proposal console.log("digest: "+digest); console.log("signKey: "); console.log(util.inspect(signKey)); var sig = ecdsa.sign(Buffer.from(digest, 'hex'), signKey); var signature = Buffer.from(sig.toDER()); var signedProposal = { signature, proposal_bytes: proposalBytes, }; // 4. Send the signed transaction proposal var proposal_request = { signedProposal, targets } channel.sendSignedProposal(proposal_request) .then((proposalResponses) => { console.log('Proposal responses:'); console.log(util.inspect(proposalResponses)); // TODO: Understand why the proposal signature is rejected by the peers // 5. Generate unsigned transaction var transaction_request = { proposalResponses, proposal, }; return channel.generateUnsignedTransaction(transaction_request); }) .then((commitProposal) => { // 6. Sign the unsigned transaction var transactionBytes = commitProposal.toBuffer(); var transaction_digest = client.getCryptoSuite().hash(transactionBytes); var transaction_sig = ecdsa.sign(Buffer.from(transaction_digest, 'hex'), signKey); var transaction_signature = Buffer.from(transaction_sig.toDER()); var signedTransaction = { signedProposal: transaction_signature, request: transaction_request } // 7. Commit the signed transaction return channel.sendSignedTransaction(signedTransaction); }) .then((response) => { console.log('Successfully sent transaction'); console.log('Return code: '+response.status); }); }); Any help from anybody who might have successfully signed transactions offline would be fantastic. A: Answering my own question. There were 2 issues in my code. 1st one was related to the actual signature that needs to be done in a very specific way in Fabric. I had to create this function and apply it to the signature to avoid the issue: function _preventMalleability(sig) { const halfOrder = elliptic.curves.p256.n.shrn(1); if (sig.s.cmp(halfOrder) === 1) { const bigNum = elliptic.curves.p256.n; sig.s = bigNum.sub(sig.s); } return sig; 2d one was related to the formatting of the various proposals/requests/transactions structures: transaction_request = { proposalResponses: proposalResponses, proposal: proposal, } signedTransactionProposal = { signature: transaction_signature, proposal_bytes: transactionBytes, } signedTransaction = { signedProposal: signedTransactionProposal, request: transaction_request, } I have created a complete (working) tutorial with detailed instructions here: https://gitlab.com/guillaume.goutaudier/wisekeydemo
doc_23537447
How can i resolve this problem? Here's one of mine XSD: <?xml version="1.0" encoding="utf-8"?> <xs:schema id="RemoveGroup" targetNamespace="http://tempuri.org/RemoveGroup.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/RemoveGroup.xsd" xmlns:mstns="http://tempuri.org/RemoveGroup.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" > <xs:element name="RemoveGroup"> <xs:complexType> <xs:sequence> <xs:element name="tt_group_id" type="xs:long" /> <xs:element name="tt_network_id" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> I hope there's a way not to write down houndred of "if (input.Parameter != null)" ... A: Using minOccurs="1" at either the <element/> or <sequence/> level is the correct thing to do. What specific error are you getting? UPDATE Actually within a <sequence/> parsers should expect exactly one instance of an element UPDATE Your parser may be emitting errors as events which you need to handle in order to capture the errors - many common parsers have this behaviour. Something which could cause an error is a null value in the long simple type - this type does not allow blanks. If you want to indicate that nulls are allowed you should use nil=true from namespace http://www.w3.org/2001/XMLSchema-instance.
doc_23537448
create table tableB as ( select * from tableA) --this works in oracle but not in sql server A: Use into like this: Select * into TableB from TableA.
doc_23537449
<asp:Panel ID="StateDistrictGrid_pnl" runat="server"> <asp:GridView ID="User_grd" runat="server" DataKeyNames="VoterID" AutoGenerateColumns="False" AllowPaging="True"> <Columns> <asp:TemplateField HeaderText="Edit"> <ItemTemplate> <asp:ImageButton ID="Img_btn" ImageUrl="~/Images/52105-200.png" OnClick="Img_btn_Click" Height="20px" Width="30px" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="ID" Visible="false" /> <asp:BoundField DataField="VoterName" HeaderText="Voter Name" SortExpression="VoterName" /> <asp:BoundField DataField="StateName" HeaderText="State Name" SortExpression="StateName" /> <asp:BoundField DataField="DistrictName" HeaderText="District Name" SortExpression="DistrictName" /> </Columns> </asp:GridView> <asp:Label ID="Lbl_Result" runat="server"> <asp:Button ID="BtnShowPopup" runat="server" Text="Edit" /> <asp:ModalPopupExtender ID="Show_mpe" runat="server" TargetControlID="BtnShowPopup" PopupControlID="PopUp_Pnl" CancelControlID="Btn_Cancel" BackgroundCssClass="textbox_radius"></asp:ModalPopupExtender> <asp:Panel ID="PopUp_Pnl" runat="server" style = "display:none"> <asp:Label Font-Bold = "true" ID = "Details_lbl" runat = "server" Text = "Voter Details" ></asp:Label> <br /> <table align = "center"> <tr> <td> <asp:Label ID = "ID_lbl" runat = "server" Text = "Voter ID" ></asp:Label> </td> <td> <asp:TextBox ID="VoterID_txt" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID = "Voter_lbl" runat = "server" Text = "Voter Name" ></asp:Label> </td> <td> <asp:TextBox ID="VoterName_txt" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID = "Statepnl_lbl" runat = "server" Text = "State Name" ></asp:Label> </td> <td> <asp:TextBox ID="State_txt" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID = "Districtpnl_lbl" runat = "server" Text = "District Name" ></asp:Label> </td> <td> <asp:TextBox ID="District_txt" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Button ID="btnSave" runat="server" Text="Save" /> </td> <td> <asp:Button ID="Btn_Cancel" runat="server" Text="Cancel" /> </td> </tr> </table> </asp:Panel> </asp:Label> </asp:Panel> and the backend code is like this: is thier any problem in In my Code please help thank you protected void Img_btn_Click(object sender, ImageClickEventArgs e) { ImageButton Bt = sender as ImageButton; GridViewRow GVRow = (GridViewRow)Bt.NamingContainer; ID_lbl.Text = User_grd.DataKeys[GVRow.RowIndex].Value.ToString(); VoterName_txt.Text = GVRow.Cells[2].Text; State_txt.Text = GVRow.Cells[3].Text; District_txt.Text = GVRow.Cells[4].Text; } but when i run it the event is not Fired..What's the Problem? A: Your issue is somehow the same that I encountered few months back. This might help you some way or another. try using LinkButton instead of Button... <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:gridview runat="server" id="GridView1" showfooter="true" autogeneratecolumns="false" GridLines="None" CssClass="table1" OnRowCreated="GridView1_RowCreated" BorderColor="#356600" BorderStyle="Solid" > <columns> <asp:TemplateField HeaderText="Date" > <ItemTemplate> <asp:LinkButton ID="Date" runat="server" CausesValidation="false" CommandName="Date_Select" Text='<%#Eval("Date","{0:yyyy-MM-dd}") %>' onclick="Date_Click" EnableTheming="False"></asp:LinkButton> </ItemTemplate> <EditItemTemplate> </EditItemTemplate> </asp:TemplateField> <asp:boundfield datafield="Profit" headertext="Profit" footerstyle-font-bold="true"> <FooterStyle Font-Bold="True"></FooterStyle> </asp:boundfield> </columns> <HeaderStyle BackColor="#CEFF99" ForeColor="Black" BorderColor="#C1FF80" BorderStyle="Solid" BorderWidth="1px"></HeaderStyle> <RowStyle CssClass="td"></RowStyle> </asp:gridview> </ContentTemplate> </asp:UpdatePanel> protected void Date_Click(object sender, EventArgs e) { LinkButton Lnk = (LinkButton)sender; Label1.Text = Lnk.Text; // This one works for me.... OdbcConnection con1 = new OdbcConnection(ConfigurationManager .ConnectionStrings["connect1"] .ConnectionString); OdbcCommand cmd = new OdbcCommand("select a.customer As Customer,a.mins as MIns,a.amount as Amount,a.profit as Profit from summarydatashort a,clientsrecord b where a.orig_clli=b.orig_clli and a.date='" + Label1.Text + "' and b.emplye='Ankit'", con1); con1.Open(); OdbcDataAdapter da = new OdbcDataAdapter(cmd); da.Fill(ds); con1.Close(); GridView17.DataSource = ds; GridView17.DataBind(); }
doc_23537450
I have a dataset that is 1000 elements in 1 column, and most of the elements are numbers but some are NaN's. Is there a way I can, 1. Find them, and 2. Remove them and put them in a variable (or just remove them)? Would I have to do this the reverse way and find and remove the non-NaN's (the numbers) and store them in a variable? A: Use logical indexing to extract the elements that are not NaN and then store them anywhere you like. Here's how it works. If x is your column vector containing NaN, y = ~isnan(x) will give a logical vector y such that |y|=|x| and y(i) is 1 iff x(1) is not NaN. You can use this logical vector to extract non NaN elements: x = [1 2 3 NaN 5 6 NaN NaN 9]; y = ~isnan(x); % now y is [1 1 1 0 1 1 0 0 1] x = x(y) % now x is [1 2 3 5 6 9] Logical indexing is powerful and efficient. You could also say: x = [1 2 3 NaN 5 6 NaN NaN 9]; x(isnan(x)) = -1 % now x is [1 2 3 -1 5 6 -1 -1 9] For more information on logical indexing see the official Matlab documentation here. A: A option equivalent to @sadeghmir's answer: x = [1 2 3 NaN 5 6 NaN NaN 9]; x(x==NaN)=[]; >x 1 2 3 5 6 9
doc_23537451
For this purpose i use AsyncTask. But when thread time finish, in android studio logs, application shows lots of logs and then application crashes after a while application restart automatically. While showing logs application becomes still and does not respond to any action, after that application crashes and restart. TimeThreadInfo.java public class TimeThreadInfo { public String userId; public Long time; } MainActivity.java Time tm = new Time(); tm.setToNow(); TimeThreadInfo info=new TimeThreadInfo(); info.userId=userId; info.time=Long.parseLong(Long.toString(tm.toMillis(false))); TimeThread task=new TimeThread(); task.execute(info); In MainActivity inner-class is private class TimeThread extends AsyncTask<TimeThreadInfo,Void,Void> { @Override protected Void doInBackground(TimeThreadInfo... params) { TimeThreadInfo timeThreadInfo=params[0]; long thredStartTime=timeThreadInfo.time; Long stopTime=thredStartTime+60000; while(true){ SharedPreferences myShared=MainActivity.this.getSharedPreferences("my_application",Context.MODE_PRIVATE); String id=myShared.getString("user_id", "nothing"); Time tm = new Time(); tm.setToNow(); Long currentTime=Long.parseLong(Long.toString(tm.toMillis(false))); if(id.equalsIgnoreCase(timeThreadInfo.userId)&&currentTime<stopTime) { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } else{ if(id.equalsIgnoreCase(timeThreadInfo.userId)&&currentTime>=stopTime) { Config.signout(getApplicationContext()); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } else break; } } return null; } } Logs 06-21 18:33:31.265 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:33:31.426 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:00.965 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 315K, 5% free 12279K/12871K, paused 165ms 06-21 18:34:01.286 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:01.286 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:02.408 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 252K, 4% free 12842K/13319K, paused 72ms 06-21 18:34:02.739 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:02.900 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:03.395 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:03.750 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:03.911 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:04.071 32204-32208/com.example.farhan.fyp D/dalvikvm: GC_CONCURRENT freed 241K, 3% free 13872K/14215K, paused 25ms+13ms 06-21 18:34:04.152 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:04.472 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:04.472 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:04.712 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:04.872 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:05.512 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:05.592 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:05.754 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:05.754 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:06.395 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:06.476 32204-32208/com.example.farhan.fyp D/dalvikvm: GC_CONCURRENT freed 672K, 6% free 14824K/15623K, paused 8ms+18ms 06-21 18:34:06.556 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:06.637 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:07.122 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:07.683 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:23.483 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 500K, 4% free 23494K/24263K, paused 153ms 06-21 18:34:23.724 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:23.724 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:24.783 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:24.863 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:25.184 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 479K, 4% free 24610K/25415K, paused 180ms 06-21 18:34:25.344 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:25.507 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:25.747 32204-32204/com.example.farhan.fyp D/dalvikvm: GREF has increased to 301 06-21 18:34:25.827 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:26.067 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:27.033 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:27.275 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:27.515 32204-32208/com.example.farhan.fyp D/dalvikvm: GC_CONCURRENT freed 671K, 3% free 26005K/26759K, paused 8ms+32ms 06-21 18:34:28.077 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:28.077 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:28.880 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:28.880 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:29.521 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 497K, 3% free 27393K/28039K, paused 183ms 06-21 18:34:29.923 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:30.083 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:30.839 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:31.000 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:31.242 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 480K, 3% free 28524K/29191K, paused 146ms 06-21 18:34:31.963 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:32.286 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:32.963 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 476K, 3% free 29627K/30343K, paused 158ms 06-21 18:34:33.043 32204-32209/com.example.farhan.fyp I/dalvikvm: threadid=3: reacting to signal 3 06-21 18:34:38.460 32204-32204/com.example.farhan.fyp I/dalvikvm-heap: Clamp target GC heap from 33.233MB to 32.000MB 06-21 18:34:38.620 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_FOR_ALLOC freed 250K, 3% free 31911K/32647K, paused 326ms 06-21 18:34:38.620 32204-32204/com.example.farhan.fyp I/dalvikvm-heap: Forcing collection of SoftReferences for 449872-byte allocation 06-21 18:34:38.620 32204-32209/com.example.farhan.fyp I/dalvikvm: Wrote stack traces to '/data/anr/traces.txt' 06-21 18:34:38.861 32204-32204/com.example.farhan.fyp I/dalvikvm-heap: Clamp target GC heap from 33.232MB to 32.000MB 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp D/dalvikvm: GC_BEFORE_OOM freed 1K, 3% free 31910K/32647K, paused 265ms 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp E/dalvikvm-heap: Out of memory on a 449872-byte allocation. 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: "main" prio=5 tid=1 RUNNABLE 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: | group="main" sCount=0 dsCount=0 obj=0x409c0460 self=0x12810 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: | sysTid=32204 nice=0 sched=0/0 cgrp=default handle=1074082952 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: | schedstat=( 23506031393 31239932235 5375 ) utm=1965 stm=390 core=0 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.Bitmap.nativeCreate(Native Method) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.Bitmap.createBitmap(Bitmap.java:605) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.Bitmap.createBitmap(Bitmap.java:551) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:524) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773) 06-21 18:34:38.941 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.content.res.Resources.loadDrawable(Resources.java:1940) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.content.res.TypedArray.getDrawable(TypedArray.java:601) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.View.<init>(View.java:2785) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.ViewGroup.<init>(ViewGroup.java:385) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.widget.LinearLayout.<init>(LinearLayout.java:174) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.widget.LinearLayout.<init>(LinearLayout.java:170) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at java.lang.reflect.Constructor.constructNative(Native Method) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.createView(LayoutInflater.java:586) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.onCreateView(LayoutInflater.java:653) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:678) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.parseInclude(LayoutInflater.java:800) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.rInflate(LayoutInflater.java:729) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at com.example.farhan.fyp.MainActivity.onCreate(MainActivity.java:51) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.app.Activity.performCreate(Activity.java:4466) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.app.ActivityThread.access$600(ActivityThread.java:123) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.os.Handler.dispatchMessage(Handler.java:99) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.os.Looper.loop(Looper.java:137) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at android.app.ActivityThread.main(ActivityThread.java:4424) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at java.lang.reflect.Method.invokeNative(Native Method) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at java.lang.reflect.Method.invoke(Method.java:511) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 06-21 18:34:39.021 32204-32204/com.example.farhan.fyp I/dalvikvm: at dalvik.system.NativeStart.main(Native Method) 06-21 18:34:39.101 32204-32204/com.example.farhan.fyp D/AndroidRuntime: Shutting down VM 06-21 18:34:39.101 32204-32204/com.example.farhan.fyp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x409bf1f8) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: FATAL EXCEPTION: main 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.farhan.fyp/com.example.farhan.fyp.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown> 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:123) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4424) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown> 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.createView(LayoutInflater.java:606) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.onCreateView(LayoutInflater.java:653) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:678) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.parseInclude(LayoutInflater.java:800) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.rInflate(LayoutInflater.java:729) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at com.example.farhan.fyp.MainActivity.onCreate(MainActivity.java:51) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:4466) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:123)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4424)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)  06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: Caused by: java.lang.reflect.InvocationTargetException 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: at java.lang.reflect.Constructor.constructNative(Native Method) 06-21 18:34:39.342 32204-32204/com.example.farhan.fyp E/AndroidRuntime: Caused by: java.lang.OutOfMemoryError A: using: while(true) usually isn't a great idea. Consider putting this in your Application Class: registerActivityLifecycleCallbacks(myActivityLifecycleCallbacks); Then create myActivityLifecycleCallbacks by implementing Application.ActivityLifecycleCallbacks and override in that class: Handler handler; @Override public void notifyUserInteraction(final Activity activity) { handler.removeCallbacks(); handler.postDelayed(yourLogoutRunnable, 60000); } Now every time the user uses your app - you'll be restarting a delayed task that if it's allowed to complete, it will log the user out. Using a Handler call postDelayed with the logout method and the timeout. The idea here is to cancel that postDelayed every time the user touches the app, and if the runnable is allowed to run, it does your logout process.
doc_23537452
library(RODBC) con <- odbcDriverConnect("driver=SQL Server; server=database") df <- data.frame(a=1:10, b=10:1, c=11:20) values <- paste("(",df$a,",", df$b,",",df$c,")", sep="", collapse=",") cmd <- paste("insert into MyTable values ", values) result <- sqlQuery(con, cmd, as.is=TRUE) ..which seems to work but does not scale very well. Is there an easier way? A: This worked for me and I found it to be simpler. library(sqldf) library(odbc) con <- dbConnect(odbc(), Driver = "SQL Server", Server = "ServerName", Database = "DBName", UID = "UserName", PWD = "Password") dbWriteTable(conn = con, name = "TableName", value = x) ## x is any data frame A: Since insert INTO is limited to 1000 rows, you can dbBulkCopy from rsqlserver package. dbBulkCopy is a DBI extension that interfaces the Microsoft SQL Server popular command-line utility named bcp to quickly bulk copying large files into table. For example: url = "Server=localhost;Database=TEST_RSQLSERVER;Trusted_Connection=True;" conn <- dbConnect('SqlServer',url=url) ## I assume the table already exist dbBulkCopy(conn,name='T_BULKCOPY',value=df,overwrite=TRUE) dbDisconnect(conn) A: [edited] Perhaps pasting the names(df) would solve the scaling problem: values <- paste( " df[ , c(", paste( names(df),collapse=",") , ")] ", collapse="" ) values #[1] " df[ , c( a,b,c )] " You say your code is "working".. I would also have thought one would use sqlSave rather than sqlQuery if one wanted to "upload". I would have guessed this would be more likely to do what you described: sqlSave(con, df, tablename = "MyTable")
doc_23537453
I want to know if there is a way to create the proper Fake Controller for this.. so I can have access to an MVC partial view (containing a Kendo Grid) from a static method. Any help with this is appreciated. Thanks in advance!! I kept getting this error: Value cannot be null. Parameter name: controllerContext Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: controllerContext Source Error: Line 8: @(Html.Kendo().Grid<SimpleKendoModelData>() Stack Trace: [ArgumentNullException: Value cannot be null. Parameter name: controllerContext] System.Web.Mvc.ChildActionValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +137 System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +80 System.Web.Mvc.ControllerBase.get_ValueProvider() +39 Kendo.Mvc.UI.Grid`1.ProcessDataSource() +254 Kendo.Mvc.UI.Grid`1.WriteHtml(HtmlTextWriter writer) +818 Kendo.Mvc.UI.WidgetBase.ToHtmlString() +102 Kendo.Mvc.UI.Fluent.WidgetBuilderBase`2.ToHtmlString() +15 System.Web.WebPages.WebPageBase.Write(Object value) +103 ASP._Page_Views_Reporting_ReportElement_SimpleKendoGrid_cshtml.Execute() in c:\Users\xxx\Documents\Visual Studio 2015\Projects\xxx\Views\Reporting\ReportElement_SimpleKendoGrid.cshtml:8 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +253 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +148 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +122 xxx.Api.Ui.Helpers.ViewRenderer.RenderViewToStringInternal(String viewPath, Object model, Boolean partial) in C:\Users\xxx\Documents\Visual Studio 2015\Projects\xxx\Helpers\ViewRenderer.cs:218 xxx.Api.Ui.Helpers.ViewRenderer.RenderPartialView(String viewPath, Object model) in C:\Users\xxx\Documents\Visual Studio 2015\Projects\xxx\Helpers\ViewRenderer.cs:81 xxx.Api.Ui.Helpers.ViewRenderer.RenderPartialView(String viewPath, Object model, ControllerContext controllerContext) in C:\Users\xxx\Documents\Visual Studio 2015\Projects\xxx\Helpers\ViewRenderer.cs:149 xxx.Api.Ui.Controllers.ReportingController.Test() in C:\Users\xxx\Documents\Visual Studio 2015\Projects\xxx\Controllers\ReportingController.cs:86 lambda_method(Closure , ControllerBase , Object[] ) +87 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +229 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35 System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39 System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +67 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +386 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +186 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +157 This is my testing method in a controller: [AllowAnonymous] public ActionResult Test() { var model = new SimpleKendoModel(); for (int x = 0; x < 10; x++) { var result = new SimpleKendoModelData(); result.Data = x; model.Results.Add(result); } var currentContext = ControllerExtensions.GetFakeControllerContext(); //This commented out code works //var html = ViewRenderer.RenderPartialView("~/Views/Reporting/ReportElement_SimpleKendoGrid.cshtml", model, ControllerContext); var html = ViewRenderer.RenderPartialView("~/Views/Reporting/ReportElement_SimpleKendoGrid.cshtml", model, currentContext); return View(); } ControllerExtensions Class: public static class ControllerExtensions { public static ControllerContext GetFakeControllerContext() { var currentContext = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null)); var st = new StringWriter(); var context = new HttpContextWrapper(currentContext); var routeData = new RouteData(); routeData.Values.Add("controller", "someValue"); var controllerContext = new ControllerContext(new RequestContext(context, routeData), new FakeController()); return controllerContext; } } View Renderer Class: // Read: https://weblog.west-wind.com/posts/2012/may/30/rendering-aspnet-mvc-views-to-string /// <summary> /// Class that renders MVC views to a string using the /// standard MVC View Engine to render the view. /// </summary> public class ViewRenderer { /// <summary> /// Required Controller Context /// </summary> protected ControllerContext Context { get; set; } /// <summary> /// Initializes the ViewRenderer with a Context. /// </summary> /// <param name="controllerContext"> /// If you are running within the context of an ASP.NET MVC request pass in /// the controller's context. /// Only leave out the context if no context is otherwise available. /// </param> public ViewRenderer(ControllerContext controllerContext = null) { // Create a known controller from HttpContext if no context is passed if (controllerContext == null) { if (HttpContext.Current != null) { var currentContext = HttpContext.Current; var context = new HttpContextWrapper(currentContext); var routeData = new RouteData(); controllerContext = new ControllerContext(new RequestContext(context, routeData), new FakeController()); } else throw new InvalidOperationException( "ViewRenderer must run in the context of an ASP.NET " + "Application and requires HttpContext.Current to be present."); } Context = controllerContext; } /// <summary> /// Renders a full MVC view to a string. Will render with the full MVC /// View engine including running _ViewStart and merging into _Layout /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to render the view with</param> /// <returns>String of the rendered view or null on error</returns> public string RenderView(string viewPath, object model) { return RenderViewToStringInternal(viewPath, model, false); } /// <summary> /// Renders a partial MVC view to string. Use this method to render /// a partial view that doesn't merge with _Layout and doesn't fire /// _ViewStart. /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to pass to the viewRenderer</param> /// <returns>String of the rendered view or null on error</returns> public string RenderPartialView(string viewPath, object model) { return RenderViewToStringInternal(viewPath, model, true); } /// <summary> /// Renders a partial MVC view to string. Use this method to render /// a partial view that doesn't merge with _Layout and doesn't fire /// _ViewStart. /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to pass to the viewRenderer</param> /// <param name="controllerContext">Active Controller context</param> /// <returns>String of the rendered view or null on error</returns> public static string RenderView(string viewPath, object model, ControllerContext controllerContext) { ViewRenderer renderer = new ViewRenderer(controllerContext); return renderer.RenderView(viewPath, model); } /// <summary> /// Renders a partial MVC view to string. Use this method to render /// a partial view that doesn't merge with _Layout and doesn't fire /// _ViewStart. /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to pass to the viewRenderer</param> /// <param name="controllerContext">Active Controller context</param> /// <param name="errorMessage">optional out parameter that captures an error message instead of throwing</param> /// <returns>String of the rendered view or null on error</returns> public static string RenderView(string viewPath, object model, ControllerContext controllerContext, out string errorMessage) { errorMessage = null; try { ViewRenderer renderer = new ViewRenderer(controllerContext); return renderer.RenderView(viewPath, model); } catch (Exception ex) { errorMessage = ex.GetBaseException().Message; } return null; } /// <summary> /// Renders a partial MVC view to string. Use this method to render /// a partial view that doesn't merge with _Layout and doesn't fire /// _ViewStart. /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to pass to the viewRenderer</param> /// <param name="controllerContext">Active controller context</param> /// <returns>String of the rendered view or null on error</returns> public static string RenderPartialView(string viewPath, object model, ControllerContext controllerContext) { ViewRenderer renderer = new ViewRenderer(controllerContext); return renderer.RenderPartialView(viewPath, model); } /// <summary> /// Renders a partial MVC view to string. Use this method to render /// a partial view that doesn't merge with _Layout and doesn't fire /// _ViewStart. /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">The model to pass to the viewRenderer</param> /// <param name="controllerContext">Active controller context</param> /// <param name="errorMessage">optional output parameter to receive an error message on failure</param> /// <returns>String of the rendered view or null on error</returns> public static string RenderPartialView(string viewPath, object model, ControllerContext controllerContext, out string errorMessage) { errorMessage = null; try { ViewRenderer renderer = new ViewRenderer(controllerContext); return renderer.RenderPartialView(viewPath, model); } catch (Exception ex) { errorMessage = ex.GetBaseException().Message; } return null; } /// <summary> /// Internal method that handles rendering of either partial or /// or full views. /// </summary> /// <param name="viewPath"> /// The path to the view to render. Either in same controller, shared by /// name or as fully qualified ~/ path including extension /// </param> /// <param name="model">Model to render the view with</param> /// <param name="partial">Determines whether to render a full or partial view</param> /// <returns>String of the rendered view</returns> protected string RenderViewToStringInternal(string viewPath, object model, bool partial = false) { // first find the ViewEngine for this view ViewEngineResult viewEngineResult = null; if (partial) viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath); else viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, null); if (viewEngineResult == null) throw new FileNotFoundException("ViewCouldNotBeFound"); // get the view and attach the model to view data var view = viewEngineResult.View; Context.Controller.ViewData.Model = model; string result = null; using (var sw = new StringWriter()) { var ctx = new ViewContext(Context, view, Context.Controller.ViewData, Context.Controller.TempData, sw); view.Render(ctx, sw); result = sw.ToString(); } return result; } /// <summary> /// Creates an instance of an MVC controller from scratch /// when no existing ControllerContext is present /// </summary> /// <typeparam name="T">Type of the controller to create</typeparam> /// <returns></returns> public static T CreateController<T>(RouteData routeData = null) where T : Controller, new() { T controller = new T(); // Create an MVC Controller Context HttpContextBase wrapper = null; if (HttpContext.Current != null) wrapper = new HttpContextWrapper(System.Web.HttpContext.Current); //else // wrapper = CreateHttpContextBase(writer); if (routeData == null) routeData = new RouteData(); if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller")) routeData.Values.Add("controller", controller.GetType().Name .ToLower() .Replace("controller", "")); controller.ControllerContext = new ControllerContext(wrapper, routeData, controller); return controller; } } ~/Views/Reporting/ReportElement_SimpleKendoGrid.cshtml Partial View: @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_ReportTemplateLayout.cshtml"; } @model SimpleKendoModel @(Html.Kendo().Grid<SimpleKendoModelData>() .Name("Results") .BindTo(Model.Results) .Columns(columns => { columns.Bound(x => x.Data).Title("Data").Width(250); }) .DataSource(datasource => datasource .Ajax() .PageSize(5000) .ServerOperation(false) ) ) ~/Views/Shared/_ReportTemplateLayout.cshtml: @RenderBody() MVC Partial View Model: public class SimpleKendoModel { public SimpleKendoModel() { Results = new List<SimpleKendoModelData>(); } public List<SimpleKendoModelData> Results { get; set;} } public class SimpleKendoModelData { public SimpleKendoModelData() { Data = 0; } public int Data { get; set; } } This is the partial view result A: Thanks to this post: Setting HttpContext.Current.Session in a unit test I've actually solved this problem.. Using the class below, I was able to successfully create a template HTML using an MVC Razor partial view (containing Kendo Grids) for email templates purposes.. and allows me to call it from a static method. I created a class called ControllerExtensions public static class ControllerExtensions { public static ControllerContext GetFakeControllerContext() { HttpContext.Current = HttpContext.Current ?? GetFakeHttpContext(); var currentContext = HttpContext.Current; var controller = CreateController<FakeController>(); var st = new StringWriter(); var context = new HttpContextWrapper(currentContext); var routeData = GetFakeRouteData(controller); var controllerContext = new ControllerContext(new RequestContext(context, routeData), controller); return controllerContext; } public static HttpContext GetFakeHttpContext() { var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); return httpContext; } public static RouteData GetFakeRouteData(Controller controller) { var routeData = new RouteData(); if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller")) routeData.Values.Add("controller", controller.GetType().Name .ToLower() .Replace("controller", "")); return routeData; } public static T CreateController<T>(RouteData routeData = null) where T : Controller, new() { T controller = new T(); // Create an MVC Controller Context var wrapper = new HttpContextWrapper(System.Web.HttpContext.Current); if (routeData == null) routeData = new RouteData(); if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller")) routeData.Values.Add("controller", controller.GetType().Name .ToLower() .Replace("controller", "")); controller.ControllerContext = new ControllerContext(wrapper, routeData, controller); return controller; } } public class FakeController : Controller { } And use it the following way: public static string GetHtml() { var model = new SimpleKendoModel(); for (int x = 0; x < 10; x++) { var result = new SimpleKendoModelData(); result.Data = x; model.Results.Add(result); } var currentContext = ControllerExtensions.GetFakeControllerContext(); var html = ViewRenderer.RenderPartialView("~/Views/Reporting/ReportElement_SimpleKendoGrid.cshtml", model, currentContext); return html; }
doc_23537454
A library for creating MS Word (.doc) files would also be helpful. A: Apache POI works well for creating MS Office documents programmatically. PDFBox, as already mentioned, works well for PDF creation. A: PDFBox allows you to create pdf files from a text file. A: ps2pdf is a good unix utility for converting postscript files in to PDFs, and postscript in java is as easy as string manipulation. http://pages.cs.wisc.edu/~ghost/doc/AFPL/6.50/Ps2pdf.htm A: A have experimeted with a number of options, the best one was docx4j
doc_23537455
students = [ ('Anderson', 'Brian', 'junior', 123, ('FIN 365', 'MATH 223', 'CS 410')), ('Brown', 'Charlie', 'sophomore', 456, ('FIN 365', 'ECON 101')), ('Van Pelt', 'Lucy', 'junior', 789, ('FIN 365', 'MED 300', 'NUT 150', 'MED 330')) ] and use a nested for loop in order to print this output: Brian Anderson is a junior with ID=123 studying these classes: FIN 365 MATH 223 CS 410 Charlie Brown is a sophomore with ID=456 studying these classes: FIN 365 ECON 101 Lucy Van Pelt is a junior with ID=789 studying these classes: FIN 365 MED 300 NUT 150 MED 330 I was able to get the first line of each tuple just fine using this code (I know it's sloppy): for row in students: print(f'{row[1] + " " + row[0] + " is a " + row[2] + " with ID="} {row[3]} studying these classes: ') But I can't figure out how to list out the classes now. Any help would be appreciated! A: * *You can use tuple unpacking to give names to the different elements. This is nicer than using indices (e.g. row[0], row[1]). This can be done directly inside the for. *Using f-strings is great, but it looks weird when you still build up the total str via +. Try to just write the whole thing in one go, no +. *The final element (below called classes) is a tuple as well, so this can also be iterated over using for. Below I do all of the above: students = [ ('Anderson', 'Brian', 'junior', 123, ('FIN 365', 'MATH 223', 'CS 410')), ('Brown', 'Charlie', 'sophomore', 456, ('FIN 365', 'ECON 101')), ('Van Pelt', 'Lucy', 'junior', 789, ('FIN 365', 'MED 300', 'NUT 150', 'MED 330')) ] for last, first, title, ID, classes in students: print(f'{first} {last} is a {title} with ID={ID} studying these classes:') for c in classes: print(f' {c}') A: You have the right idea. A "nested for loop" is just a for loop inside another for loop, so just do the same thing for row[4] (the tuple of courses) that you did for the students list: for last, first, year, num, courses in students: print(f"{first} {last} is a {year} with ID={num} studying these classes:") for course in courses: print(f" {course}") Note the use of tuple destructuring to clean up all the row[n] stuff! If you were writing this by subscripting the tuples it'd look more like: for row in students: print(f"{row[1]} {row[0]} is a {row[2]} with ID={row[3]} studying these classes:") for course in row[4]: print(f" {course}")
doc_23537456
times <- c(paste(9, 5*(0:11), sep = ":"),paste(10, 5*(0:11), sep = ":")) times_as_hm <- lubridate::hm(times) A: We may do this as library(lubridate) times_as_hm2 <- hm("9:0")+ seconds_to_period(5 *(0:23) * 60) -testing > all.equal(times_as_hm, times_as_hm2)
doc_23537457
In my case my consuming applications are using SSO. They won't be sending user name and password so I am confused that, how will I generate jwt token authentication without user name/password. Also as its intranet project so I may not able to use OAuth. Which one would be more suitable in my case. If you only list out few options I can dig more on google for it. Thanks in advance.
doc_23537458
According to the user manual, for this to work, the package must be installed with OpenMP enabled. This sentence is very vague to me. I have checked the "MakeConf" file, in which I have found the following lines : SHLIB_OPENMP_CFLAGS = -fopenmp SHLIB_OPENMP_CXXFLAGS = -fopenmp SHLIB_OPENMP_FCFLAGS = -fopenmp SHLIB_OPENMP_FFLAGS = -fopenmp Adding these lines on a file called "MakeVars" did not help either : PKG_CXXFLAGS=-fopenmp PKG_LIBS= -fopenmp -lgomp I am using R 3.4.1 on Windows 10, and installed the package using the standard install.packages() procedure. PS : The answer given in this post was not understandable for me : How do we enable OpenMP to use multiple cores -- glintenet EDIT I have tried installing the package from the Windows terminal. I would say everything is ok since I can see many lines refering to gcc and/or openmp. For instance I can see : c:/Rtools/mingw_64/bin/gcc -I"C:/PROGRA~1/R/R-34~1.1/include" -DNDEBUG -I"d:/Compiler/gcc-4.9.3/local330/include" -fopenmp -O2 -Wall -std=gnu99 -mtune=core2 -c c_routines.c -o c_routines.o However it did not improve the execution time of the package functions.
doc_23537459
Example: Enter first name: Enter last name: Frank The name is Frank Enter Phone: It won't let me put the First Name in. Ideas? if( (fp=fopen("contacts","w")) == NULL ) { printf( "Failed to open file contacts to write.\n" ); exit( 1 ); } printf("Enter first name: "); fgets(first, sizeof(first), stdin); first[strlen(first) - 1] = '\0'; printf("Enter last name: "); fgets(last, sizeof(last), stdin); last[strlen(last) - 1] = '\0'; strcpy(list.name, first); strcat(list.name, " "); strcat(list.name, last); printf("The name is %s\n", list.name); printf("Enter Phone:"); fgets( line, sizeof( line ), stdin ); sscanf( line, "%s",&list.ph); printf("You entered: %s", &list.ph); printf("Enter Address:"); fgets( line, sizeof( line ), stdin ); sscanf( line, "%s", list.add ); printf("Enter Email Address:"); fgets( line, sizeof( line ), stdin ); sscanf( line, "%s", list.email ); printf("\n"); fprintf( fp, "%s\t%s\t%s\t%s", list.name, &list.ph, list.add, list.email ); fclose(fp); A: I suspect you declared "first" as a char pointer, you must declare it as an array if you want that sizeof works otherwise you get the size of the pointer, regardless where it points char first[100]; printf("Enter first name: "); fgets(first, sizeof(first), stdin); disclaimer: you didn't show the decl of any variables A: There probably is some data (a wild \n, for example) in stdin. It is better to run your code under a debugger and see what happens.
doc_23537460
MomentJS moment('06/24/2020').format('DD\'MM yyyy') // output is = 24'06 2020 Luxon console.warn(DateTime.fromJSDate(new Date("06/24/2020")).toFormat('dd\'MM yyyy')); // output is = 24MM yyyy A: Luxon uses single quotes as an escape character, so it's currently not possible to insert a literal single quote. According to Luxon GitHub issue #649 Escaping single quote, it seems like this is a known limitation. Short of opening a PR yourself, you could work around it like this: DateTime.fromJSDate(new Date('06/24/2020')).toFormat('dd!MM yyyy') .replace('!', "'")
doc_23537461
TABLEA id name somefield1 TABLEB id name somefield1 somefield2 How do I structure a SELECT statement so that I can SELECT from both tables simultaneously, and have the result sets merged for the columns that are the same? So for example, I am hoping to do something like... SELECT name, somefield1 FROM TABLEA, TABLEB WHERE name="mooseburgers"; ...and have the name, and somefield1 columns from both tables merged together in the result set. Thank-you for your help! Sample output appended because question unclear: I want the rows from table1 and the rows from table2 appended in the resultset. For example if the tables contain TABLEA id(1) name(zoot) somefield(suit) TABLEB id(1) name(zoot) somefield(flute) The resultet would look like: name | somefield1 zoot suit zoot flute A: I am not sure what you mean by merge, but you can UNION the results: SELECT id, name, somefield1 FROM TABLEA WHERE name="mooseburgers" union all SELECT id, name, somefield1 FROM TABLEB WHERE name="mooseburgers"; A: You can combine columns from both tables using (id,name) as the joining criteria with: select a.id as id, a.name as name, a.somefield1 || ' ' || b.somefied1 as somefield1 from tablea a, tableb b where a.id = b.id and a.name = b.name and b.name = 'mooseburgers'; If you want to join on just the (id) and combine the name and somefield1 columns: select a.id as id, a.name || ' ' || b.name as name, a.somefield1 || ' ' || b.somefied1 as somefield1 from tablea a, tableb b where a.id = b.id and b.name = 'mooseburgers'; Although I have to admit this is a rather unusual way of doing things. I assume you have your reasons however :-) If I've misunderstood your question and you just want a more conventional union of the two tables, use something like: select id, name, somefield1, '' as somefield2 from tablea where name = 'mooseburgers' union all select id, name, somefield1, somefield2 from tableb where name = 'mooseburgers' This won't combine rows but will instead just append the rows from the two queries. Use union on its own if you want to remove duplicate rows but, if you're certain there are no duplicates or you don't want them removed, union all is often more efficient. Based on your edit, the actual query would be: select name, somefield1 from tablea where name = 'zoot' union all select name, somefield1 from tableb where name = 'zoot' (or union if you don't want duplicates where a.name==b.name=='zoot' and a.somefield1==b.somefield1). A: Depending on what you mean by merge, here's a possible solution. Select id,name,somefield1 from TableA WHERE Name ='mooseburgers' UNION Select id,name,somefield1 from TableB WHERE Name ='mooseburgers' Will allow you to show results from both tables with the results merged into 1 table. A: Do you perhaps mean SELECT tableA.id, tableA.name, tableA.somefield1 FROM tableA, tableB WHERE tableA.name = tableB.name AND tableA.name="mooseburgers"
doc_23537462
I am confused whether its code first or model first approach as we had not used any diagram to create entity relation. A: This is model first. But IMO "model first" is a misnomer making it more confusing than it should. In fact, it's "mapping first". An object-relational mapper (ORM), like Entity Framework, always deals with three main components --database, object-oriented code and the mapping between these two. Any of these three parts can be created first. The other flavors are "database first": first the database, then the mapping (edmx) then the code (running t4 templates) and "code first: first the code, then the mapping (conventions, data annotations, and/or fluent) then the database (migrations).
doc_23537463
<xs:element name="Headers"> <xs:annotation> <xs:documentation>Headers Object</xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element name="content-type" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> When I create the class Headers, I get this for the content-type element: @XmlElement(name = "content-type") protected String contentType; I'm using Gson to convert the object to json: "headers": [{ "contentType": "application/x-www-form-urlencoded", }], What I need is to get the contentType element as I had it in the xsd file, so my question is if there is any chance to grab the @XmlElement name value and use that in the convertion instead of the variable name. I tried xstream library also but get the same result. Thanks in advance. A: Yes it is possible. And for this one don't need to modify the xsd to add @SerializedName("content-type") which is not also time taking if xsd is very large. PS: I am using Gson API for this. GsonBuilder gson = new GsonBuilder(); gson.setFieldNamingStrategy(new CustomFieldNamePolicy()); And the CustomFieldNamePolicy class can be defined as : public class CustomFieldNamePolicy implements FieldNamingStrategy{ @Override public String translateName(Field paramField) { Annotation annotationName = null; if(null != (annotationName = paramField.getAnnotation(XmlElement.class))){ return ((XmlElement) annotationName).name(); }else if(null != (annotationName = paramField.getAnnotation(XmlAttribute.class))){ return ((XmlAttribute)annotationName).name(); } return paramField.getName(); } }
doc_23537464
Session is used on another thread... than it was created on ... Session objects are not thread safe. What programming/templating practices are likely to cause this? EDIT: So far we've had some good suggestions: * *Don't store your session object in a static variable (Chris) *Don't store your engine or package in a static variable (Miguel) In fact, both of these are solid gold, and you should be checking your own code for these anti-patterns. (The engine has a reference to a session, so that makes sense.) Still, I've searched the code base that's causing the problem, and I haven't found any of these. So - has anyone got any more ideas? I'd also welcome suggestions on how to debug this kind of thing, or narrow down on the problematic code. A: The problem does not only come about when storing a session, but also when storing any TOM.NET object (Component, Page, etc). Each such object has an internal reference to the Session that it was created from any access to the object may have to go back to the Session to retrieve the requested information from Tridion. Although most properties that are 'native' to the item type seem to be retrieved and kept on an instance, a call like LoadApplicationData may (have to) reach back to the Session to access the requested data. And if this call then happens on a different thread, you'll get the warning message you mention. I've started to look at every TOM.NET object I keep with suspicion and pre-load a lot of data I may need later when I first load the object from its Session. A: I also want to add a comment based on previous experiences. The following scenarios: * *Session and/or engine and/or package are stored in Static Variables *Session and/or engine and/or package are sent as parameter to a method that is Static Can cause several issues apart of the described previously, including memory leaks during publishing. Publisher will start consuming memory till end up in non responding mode (You can't stop, nor restart nor disable) and you need to reboot the server. Those issues can go from bad to worse when doing massive publishing So is recommended that anything that uses session, engine, package should be converted to non static As an example, moving from the following code used for initialize Utilities used across all the templates using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Tridion; using Tridion.ContentManager; using Tridion.ContentManager.CommunicationManagement; using Tridion.ContentManager.ContentManagement; using Tridion.ContentManager.ContentManagement.Fields; using Tridion.ContentManager.Templating; using Tridion.ContentManager.Publishing; namespace sample.sample1 { public class Utilities { private static Engine _engine; private static Package _package; public void InitializeUtilities(Engine e, Package p) { _engine = e; _package = p; } } } into using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Tridion; using Tridion.ContentManager; using Tridion.ContentManager.CommunicationManagement; using Tridion.ContentManager.ContentManagement; using Tridion.ContentManager.ContentManagement.Fields; using Tridion.ContentManager.Templating; using Tridion.ContentManager.Publishing; namespace sample.sample1 { public class Utilities { private Engine _engine; private Package _package; public void InitializeUtilities(Engine e, Package p) { _engine = e; _package = p; } } } Can save a lot of issues A: I have found that if you ever store the session object in a static variable in a template this error occurs. It works fine in debug mode, but as soon as I run a multi-threaded Publisher (i.e. more than one rendering thread) this issue raises it's ugly head. A: Another scenario is if your Event System or Template or Workflow code kicks off child threads and passes the Session or Engine objects into them without appropriate locks in place. Essentially anything that falls outside the Single-Threaded Apartments model, which the Engine and Session objects are based on: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680112(v=vs.85).aspx
doc_23537465
B A T C H R E C U R S I O N exceeds STACK limits ** Recursion Count=1240, Stack Usage=90 percent B A T C H PROCESSING IS A B O R T E D ** Other that this nothing displayed in console. Note: I try to start only empty server (no project is added) Can anyone please help on this? Much appreciated your help!!! A: The error message is specific for the command prompt. You probably are starting the WebSphere form a custom .bat file where there's a subroutine that calls itself. So check the way you are starting the server. You can achieve the same output with this: @echo off call :test exit /b :test call :test exit /b Also check this -> how to start WebLogic in Jdeveloper
doc_23537466
I have created classes such as Allele, Gene, Organism, Population. A Population object contains multiple Organism objects (in an array), each Organism object contains multiple Genes, and so on. Currently, it is very easy to know, for example, what Gene objects a certain Organism object has. However, if all I have is a Gene object, I do no know what Organism it belongs to. One solution I have thought of is: attr_accessor :name, :parent def initialize(name, parent) @name = name @parent = parent #parent will be the parent object end If I do this, will @parent merely be a reference to the parent object in memory, or will it be a whole new object? Is this the best way to do this? Is there another 'better' way of doing this? Thanks! A: JRuby will, as you suggest, just keep a reference to the object rather than creating a copy of it. This is a perfectly sensible way to approach the problem. You are keeping a reference to an object you want to refer to!
doc_23537467
class Cell holds the status of a table cell: public class Cell { // class for holding cell status information public enum cellState { WATER, SCAN, SHIPUNIT, SHOT, HIT } public Cell() { currentCell = cellState.WATER; } public Cell(cellState CellState) { currentCell = CellState; } public cellState currentCell { get; set; } } class GridUnit holds table cell info: public class GridUnit { public GridUnit() { Column = 0; Row = 0; } public GridUnit(int column, int row) { Column = column; Row = row; } public int Column { get; set; } public int Row { get; set; } } finally class Shipunit contains both the above classes and acts as a wrapper for state info of an individual cell: public class ShipUnit { public GridUnit gridUnit = new GridUnit(); public Cell cell = new Cell(Cell.cellState.SHIPUNIT); } at the moment i am thinking about implementing the fleet info in a Jagged Array like this: ShipUnit[][] Fleet = new ShipUnit[][] { new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit,ShipUnit,ShipUnit}, new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit,ShipUnit}, new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit} new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit} new ShipUnit[] {ShipUnit,ShipUnit} }; i realize the last bit of code does not work. it is only for presenting the idea. but the problem being i need a field that states what type of ship each line of jagged array represent and i dont think it is practical to state this info in every cell information. so i would like some ideas of implementation of this issue from you. thank you. A: class Ship { ShipUnit[] shipUnits; string type; public Ship(int length, string type) { shipUnits = new ShipUnit[length]; this.type = type; } } Ship[] fleet = new Ship[5]; fleet[0] = new Ship(5, "Carrier"); fleet[1] = new Ship(4, "Battleship"); fleet[2] = new Ship(3, "Submarine"); fleet[3] = new Ship(3, "Something else"); fleet[4] = new Ship(2, "Destroyer"); A: I think I would define an owning Grid class, the holds all of the GridUnits. Then this Grid would also hold a List. A Ship would just have properties like size, orientation, BowCell. When adding a ship to the grid, the Grid could set the status of the units accordingly. This way, you can have usefull methods on the ship level like IsSunk(), OccupiesUnit(), etc... A: Why don't you create something like this class Ship { public ShipUnits[] _SUParts; public String _strType; public Ship(String styType, int NbPart) { _SUParts = new ShipUnit[length]; _strType = strType; } } that being said, I would not put all members public. I'de use Getter/Setter to change the values I assumed by type you also mean the name of the ship (destroyer,etc.) A: How many types of ships are there. Is that fixed or variable at runtime? If it is fixed and not too many, you should probably just use separate arrays for each. If they are variable AND you have only one array for each type, you could use a generic dictionary (of enumShipUnitType, ShipUnit[]). You can then iterate over the dictionary by getting the KeyValuePair from it like so. For Each kvp As KeyValuePair(Of enumShipUnitType, ShipUnit[]) In m_dictShipUnits For each oShipUnit as Shipunit in kvp.Value 'Do whatever Next Next A: class Ship { public Size Size { get; set; } public Orientation Orientation { get; set; } public Point Position { get; set; } public Boolean Sunk { get; set; } public String Name { get; set; } [...] } Inherit from Ship and create sub classes like Battleship, Cruiser, etc for the different ships. Add a "IsHit(Point shot)" method that compares Size, Orientation, Position and the shot position (the Rectangle class has many nice functions for that). class Grid { private Size size = new Size(10, 10); private List<Ship> ships = new List<Ship>(); private List<Point> shots; [...] } Create two grids (one for each player), add a shoot method that calls IsHit for every Ship and then adds the shot to shots. After each move if every point of a ship is hit (is in shots) and set the ship to Sunk if all are hit.
doc_23537468
Service<Void> cicle = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { String[] map = { "10", "10", "logo" }; boolean waiting = false; Timer.start(); while (Timer.update() / 1000 < time) { if (!waiting) { for (int i = 0; i < map.length; i += 3) { Label gigi = new Label("hi"); gigi.setLayoutX(Integer.parseInt(map[i])); gigi.setLayoutX(Integer.parseInt(map[i + 1])); // HERE is where i shoul add the label gigi } waiting = true; } System.out.println(Timer.update()); } end(); return null; } }; } }; but if i use layout.getChildrens().add(node) it doesn't work and if i rebuild entirely the scene for the stage it stops the program A: Just used Platform.runLater and it works
doc_23537469
This is XML: <record> <field name="Identifier">00000ZG7</field> <field name="ContestNumber">00000ZG7</field> <field name="CareerSiteNo3">spool</field> <field name="OpeningDate">2012-05-14</field> <field name="EndDate">2012-05-14T10:05:00-04:00</field> <field name="HotJobFlag">false</field> </record> This is XSLT: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://www.abc.com/ws/integration/toolkit/2005/07" xmlns:fct="http://www.abc.com/xsl_functions" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:output method="text" encoding="UTF-8"/> <xsl:param name="delimiter">,</xsl:param> <xsl:template match="ns:record"> <xsl:value-of select="ns:field[@name='Identifier']"/> <xsl:value-of select="$delimiter"/> <xsl:value-of select="ns:field[@name='ContestNumber']"/> <xsl:value-of select="$delimiter"/> <xsl:value-of select="ns:field[@name='CareerSiteNo3']"/> <xsl:value-of select="$delimiter"/> <xsl:value-of select="ns:field[@name='OpeningDate']"/> <xsl:value-of select="$delimiter"/> <xsl:variable name="End2Days" select="ns:field[@name='EndDate']"/> <xsl:choose> <xsl:when test="ns:field[@name='CareerSiteNo3']='spool'"> <xsl:value-of select="(xs:date($End2Days)+((xs:dayTimeDuration('P2D'))"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="(xs:date($End2Days)+((xs:dayTimeDuration('P14D'))"/> </xsl:otherwise> </xsl:choose> <xsl:value-of select="$delimiter"/> <xsl:value-of select="ns:field[@name='HotJobFlag']"/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet> If I take out the part <xsl:choose>, I can get a line of the result. However if I include the choose node, I get no result.Basically what I want to do is when "CareerSiteNo3" is "spool", just add 2 days from End Date value, otherwise add 14 days. Please advise me what I am doing wrong....thanks so much. A: You are using XSLT 2.0 features in your code; are you sure that the online testing tool you tried supports XSLT 2.0?
doc_23537470
I tried to open a new WCF client project in VS 2012. I am working by this tutorial: http://mikesknowledgebase.com/pages/Services/WebServices-Page1.htm#comment-949587244 just after opening a new project I tried to run the debugger and I get this error: Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata. Error: Cannot obtain Metadata from htt://localhost:15021/Service1.svc If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) I tried searching the internet for this error but because I am new to this I can't find the resolution to the problem. what am I doing wrong? EDIT: I tried to open a project with .net Framework 4.0 and it worked fine so the problem is with .net Framework 3.5 but I need to work with 3.5 A: I am not sure about underlying error however you can try to check following: 1) Check if WCF service is running and you are able to access it using a browser 2) Check if you have provided correct authentication details in WCF service web.config. Please check if you have provided correct data under identity section, userPrincipalName 3) Under behaviours section, Please enable serviceMetaData httpGetEnabled="true" Under Visual Studio you can use WCF Service Configuration Editor to verify all these values. You can access this tool from Tools menu.
doc_23537471
@interface Contact : NSObject{ NSString *name; NSUInteger age; } define a private variable, it can't be access by any instance. why there is need to do it. i think this scene is no need to exist. now, i want to know which scene will use such way to declare variable, the advantage use this way.
doc_23537472
However it should also filter pooopppp , P00p, Po0p, P0o0o0op, (or whatever trick they try to use) etc. A: You should implement some Machine Learning to filter that. I recommend this : Google Tensorflow. What you should do is to create the tensorflow engine, train them with bad words eg : Poop, P0op, Po0pp, etc... and after several training the engine will able to tell that Po0000p considered as bad word. While Machine Learning might need steep learning curve, you can follow the tutorial at https://developers.google.com/machine-learning/crash-course/.
doc_23537473
$a1 = $_POST['a1'] $a2 = $_POST['a2'] $a3 = $_POST['a3'] $a4 = $_POST['a4'] $a5 = $_POST['a5'] ---- ---- ---- $a150 = $_POST['a150'] I have printed all the text fields in form in using for loop in a form with name a1,a2,a3 and so on. I am wrinting as below but not workng if (isset($_POST['save_exit'])) { for ($j=1; $j<=150; $j++) { ${a.$j} = $_POST['a'.$j]; } echo $a1; } but echo is not printing any value.. A: change this line: ${a.$j} = $_POST['a'.$j]; to: ${"a".$j} = $_POST['a'.$j]; if you want to print, then just use: echo ${"a".$j} = $_POST['a'.$j]; A: You can do some neat stuff with php. To do what you want, just use a loop like this: $post_array[] = array(); for ($i = 0; $i < 150; $i++) { if (isset($_POST["a$i"])) { $post_array[] = $_POST["a$i"]; } } if (count(post_array) < 5) { echo "not validated"; }
doc_23537474
For example: perl my_perl.pl -ARG_1 1234 -ARG_2 "Testing" Where ARG_1 and ARG_2 are the arguments names and 1234 and "Testing" their values. A: See Getopt::Long. If you do not like that, there are many others. In the simplest case, you could do: my %args = @ARGV; print $args{-ARG_1}, "\n"; A: You can get a similar effect by using Getopt::Long. The main difference is that it uses gnu-style --arguments by default. It's very flexible and powerful.
doc_23537475
A: If you are using NodeJS to run something like ExpressJS or another server-app, then you can only deploy your Angular13-App and need to run nodeJs on your server separately. The Tomcat server would be more suitable for java than for Angular and NodeJS.
doc_23537476
if year >= 2101: print('Distant Future') if year >= 2001: print('21st century') if year >= 1901: print('20th century') else: print('Long ago') Issue: when year = 2001 I get both 21st century and 20th. I obviously just want the 21st to print out. A: You're looking for the elif statement. Essentially, with your current code, if the first if fails, then the next one will be evaluated. Now ALSO if the first if succeeds, then the next one will still be evaluated as well. You want to exit after succeeding the first time. Try this: if year >= 2101: print('Distant Future') elif year >= 2001: print('21st century') elif year >= 1901: print('20th century') else: print('Long ago') A: A much shorter one-liner: print(['Distant Future','21st century','20th century','Long ago'][[year>=2101,year>=2001,year>=1901].index(True)]) Demo: year=2018 print(['Distant Future','21st century','20th century','Long ago'][[year>=2101,year>=2001,year>=1901,year<1901].index(True)]) Output: 21st century
doc_23537477
My custom item have: Text View Text View ListView which have other custom adapter for each item. But list view is not best option cause child list view can't be scrolled vertically as parent does. I need replace this listView with other container with custom row view which will be not scrollable as list view but change size with more items. A: Use an ExpandableListView as your "parent" list. There you have to specify groups for your children views. For more information, visit this site with an ExpandableListView sample: http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/
doc_23537478
id int, logtimestamp datetime, serialnumber varchar(255), robotid int, amountconsumed float The robotid's are only from 1 to 4. Every 15-20 minutes, new rows are added. Usually, each robot will report on a single serialnumber but that is not always the case. Periodically, the serialnumber can have duplicates. (This only happens when testing, but it can happen.) My goal is to sum the amountconsumed for each robotid in a given day and place those values in a results table that looks like this: id int, logtimestamp datetime, robot1consumed float, robot2consumed float, robot3consumed float, robot4consumed float I am having difficulty creating a query that will accurately take into account the fact that * *there can exist duplicate serialnumbers *not each serialnumber will have all 4 robotid's (if a robotid does not exist for the day, then the value should be set to 0). Here is what I have come up with so far (@startDate and @endDates are given): SELECT timestamp=dateadd(month,((Year(R1.logtimestamp)-1900)*12)+Month(R1.logtimestamp)-1,Day(R1.logtimestamp)-1), sum(R1.robot1consumed ), sum(R2.robot1consumed ), sum(R3.robot1consumed ), sum(R4.robot1consumed ) FROM Robot_Consumption R1, Robot_Consumption R2, Robot_Consumption R3, Robot_Consumption R4 WHERE R1.robotid = '1' AND R2.robotid = '2' AND R3.robotid = '3' AND R4.robotid = '4' AND R1.logtimestamp BETWEEN @startDate AND @endDate AND R1.serialnumber = R2.serialnumber AND R1.serialnumber = R3.serialnumber AND R1.serialnumber = R4.serialnumber GROUP BY Year(R1.logtimestamp), Month(R1.logtimestamp), Day(R1.logtimestamp) Aside from the constraints listed above, this works fine. Does any have a suggestion to change this query to work given the previously listed constraints? A: SELECT '0000-00-00' + INTERVAL dte DAY AS robot_date, id, SUM(amountconsumed) FROM ( SELECT 1 AS id UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 ) r -- this is to select all robotids JOIN ( SELECT DISTINCT TO_DAYS(logtimestamp) AS dte FROM Robot_Consumption WHERE logtimestamp BETWEEN @startDate AND @endDate ) rd -- this is to select all days that have any records LEFT OUTER JOIN RobotConsumption rc ON rc.robotid = r.id AND rc.logtimestamp BETWEEN '0000-00-00' + INTERVAL dte DAY AND '0000-00-00' + INTERVAL dte + 1 DAY WHERE NOT EXISTS ( SELECT 1 FROM Robot_Consumption rci WHERE rci.robotid = rc.robotid AND rci.serial_number = rc.serial_number AND rci.id < rc.id ) -- this is to handle duplicates GROUP BY dte, id If you need your results in a row, use: SELECT '0000-00-00' + INTERVAL dte DAY AS robot_date, COALESCE( ( SELECT SUM(amountconsumed) FROM Robot_Consumption rc WHERE rc.robotid = 1 AND rc.logtimestamp BETWEEN '0000-00-00' + INTERVAL dte DAY AND '0000-00-00' + INTERVAL dte + 1 DAY AND NOT EXISTS ( SELECT 1 FROM Robot_Consumption rci WHERE rci.robotid = rc.robotid AND rci.serial_number = rc.serial_number AND rci.id < rc.id ) ), 0) AS robot1consumed, COALESCE( ( SELECT SUM(amountconsumed) FROM Robot_Consumption rc WHERE rc.robotid = 2 AND rc.logtimestamp BETWEEN '0000-00-00' + INTERVAL dte DAY AND '0000-00-00' + INTERVAL dte + 1 DAY AND NOT EXISTS ( SELECT 1 FROM Robot_Consumption rci WHERE rci.robotid = rc.robotid AND rci.serial_number = rc.serial_number AND rci.id < rc.id ) ), 0) AS robot2consumed, COALESCE( ( SELECT SUM(amountconsumed) FROM Robot_Consumption rc WHERE rc.robotid = 3 AND rc.logtimestamp BETWEEN '0000-00-00' + INTERVAL dte DAY AND '0000-00-00' + INTERVAL dte + 1 DAY AND NOT EXISTS ( SELECT 1 FROM Robot_Consumption rci WHERE rci.robotid = rc.robotid AND rci.serial_number = rc.serial_number AND rci.id < rc.id ) ), 0) AS robot3consumed, COALESCE( ( SELECT SUM(amountconsumed) FROM Robot_Consumption rc WHERE rc.robotid = 4 AND rc.logtimestamp BETWEEN '0000-00-00' + INTERVAL dte DAY AND '0000-00-00' + INTERVAL dte + 1 DAY AND NOT EXISTS ( SELECT 1 FROM Robot_Consumption rci WHERE rci.robotid = rc.robotid AND rci.serial_number = rc.serial_number AND rci.id < rc.id ) ), 0) AS robot4consumed, FROM ( SELECT DISTINCT TO_DAYS(logtimestamp) AS dte FROM Robot_Consumption WHERE logtimestamp BETWEEN @startDate AND @endDate ) rd
doc_23537479
What if Facebook decides to start charging for Facebook Connect? What if they decide they don't want to let my users log in anymore (for WHATEVER reason). My concern is...If my 3rd party login servicer suddenly goes away or makes life difficult, am I suddenly out of business? A: Facebook will never charge for the login possibility. There are so many other options (like Open-ID and stuff) that are for free, so they would lose a lot of people. If you are unsure, use the Registration Plugin instead. It is much better and you are allowed to store the data you gain with it. For example, according to the Facebook rules you are not allowed to just store the email of the user just because he accepted the email permission. You have to tell him that you will store it, and he has to be able to change it (in a textfield, for example) before you store it. It´s not that simple with the Data Policy. There you go: https://developers.facebook.com/docs/plugins/registration/
doc_23537480
Thanks in advance. A: I am sure it is not supported to record a call but just read the below answer. on the link A: i was looking for same thing, i found arguments here pretty intresting and convincing ! hope this helps you
doc_23537481
Is there any solution such as a script or best practices how to manage them? I know about "config --local", but I don't want to set this variables manually everytime. A: I created a couple of aliases that looks like this: The idea being I can save my credentials (email, username) in the alias definition. Then when I want to clone or initialise, I don't have to perform a git config every time. when initialising: initgithub = !git init && git config user.email [youremailfor@github.com] && git config user.name [yourgithubusername] initbitbucket = !git init && git config user.email [youremailfor@bitbucket.com] && git config user.name [yourbitbucketusername] when cloning: clonegithub = "!f() { git clone $1 $2; cd $2; git config user.email [youremailfor@github.com]; git config user.name [yourgithubusername]; }; f" clonebitbucket = "!f() { git clone $1 $2; cd $2; git config user.email [youremailfor@bitbucket.com]; git config user.name [yourbitbucketusername]; }; f" ussage: when initialising: git initgithub git initbitbucket when cloning: git clonegithub https://github.com/pathtoproject.git /c/temp/somefolder/project git clonebitbucket https://github.com/pathtoproject.git /c/temp/somefolder/project When cloning you can basically create a function that will execute both the normal clone operation and the config operations. For now it requires that you provide the path to the folder you are cloning to in order to configure your credentials properly. A: It looks like just saying git config user.name (or user.email) in a particular repository, without specifying --global or --system would do the trick. The default is to set the configuration in the current repository, and you have to give it explicit options for it to write to your user-level or system-wide configuration instead. I don't know how one would do this if you're freshly cloning repositories that need different configuration, though. Perhaps you could write a small script that wraps git clone to clone some repository, and then set the appropriate configuration based on whatever information? If you drop the script in /usr/lib/git-core named something like git-nclone, you can then run it as git nclone. Edit: Since you don't want to manually set it every time, how about a clone wrapper that remembers the various sets you actually use, and lets you pick the appropriate one for the repository you're cloning. It could even have smart defaults based on where you're clone is coming from.
doc_23537482
[{"name"=>"John Doe", "id"=>"1"}, {"name"=>"Jane Doe", "id"=>"2"}] I would like to get back an array of id only. What would be efficient way to do so? I would prefer to avoid using a loop. Thank you. A: You should do: your_array.map {|h| h["id"]} But basically there is a loop in desguise. Sidenote: Imagine there is no id in one of the hashes, then you'd have a nil. Append compact to solve this A: You should do: your_array.pluck(:id) This is faster than map (loop) Same use compact to remove nil
doc_23537483
That order is supposed to be derived from the value of the "ini" of the creatures (i.e. the ones with the highest values get displayed on top). That order is always to be maintained. So when the value changes (since it is contained in an input field) the creature components are supposed to be sorted again. I have already made the necessary creature components and made a parent component to display them in. But I do not know how to sort them now. I have passed a function from the parent to the children that gets triggered once the value changes. But I do not know how to access the children and sort them based on their state value. I am still quite new to React, so excuse me if this is a trivial thing. I just found no answer anywhere! I have tried using React.Children.toArray(...) but that does not seem to be right. I also wanted to try out using refs to save the child components. But I did not really understand how to use them and didn't know how to approach this. Beyond that I am rather clueless. This is my parent component: export class Encounter extends React.Component<IEncounterProps,IEncounterState> { sortByIni(event) { //somehow trigger something that sorts the creature components } addCreature() { let creature = <Creature name={'Ancient Bugbear'} //I removed other props for the sake of reducing verbosity... ini={12} />; return creature } render(): any { return ( <div> {this.addCreature()} {this.addCreature()} {this.addCreature()} </div> ) } } And this is the creature component: export interface ICreatureProps { name: string, ini: number, //Removing non relevant props for verbosity reducing... } export interface ICreatureState { hitpoints: number armorclass: number ini: number } export class Creature extends React.Component<ICreatureProps, ICreatureState> { constructor(props) { super(props); this.state= { hitpoints: this.props.hitpoints || 0, armorclass: this.props.armorclass || 0, ini: this.props.ini || 0 }; this.handleIniChange = this.handleIniChange.bind(this); this.handleACChange = this.handleACChange.bind(this); this.handleHPChange = this.handleHPChange.bind(this) } handleIniChange(event) { this.setState({ini: event.target.value}) } handleACChange(event) { this.setState({armorclass: event.target.value}) } handleHPChange(event) { this.setState({hitpoints: event.target.value}) } render(): any { return ( <div> <div className={style.creatureContainer}> <div className={style.nextToTitleContainer}> <p className={style.statDisplay}>TP: <input type="number" className={style.inputField} value={this.state.hitpoints} onChange={this.handleHPChange}/></p> <p className={style.statDisplay}>RK: <input type="number" className={style.inputField} value={this.state.armorclass} onChange={this.handleACChange}/></p> //This is the field that is supposed to trigger sorting when it changes value <p className={style.statDisplay}>INI:<input type="number" className={style.inputField} value={this.state.ini} onChange={e=>{this.handleIniChange(e); this.props.sortByIni(e)}}/></p> </div> </div> </div> ) } } This is the supposed outcome when it works. As one sees the creature with the highest value is on top. And of course it is supposed to resort itself whenever a value changes. A: As it always is, soon after you ask, you find the answer yourself: I solved it by using unique keys each time I render the Creature Components. Since react identifies components via keys, they had to be new each time I rendered due to a change of ini value. If not, react would have not changed the dom tree order, since the component with that key was still there. I added this function to Encounter to generate creatures based on a button click: addCreature() { let creatureMap = this.state.creatureMap; let creatureEntry = { id: this.uuidv4(), name: Math.random().toString(36).substring(7), ini: 2, currentIni: Math.floor(Math.random() * 20) + 2, }; creatureMap.push(creatureEntry); let creatureMapSorted = creatureMap.sort((creatureA, creatureB) => { if (creatureA.currentIni < creatureB.currentIni) return 1; if (creatureA.currentIni > creatureB.currentIni) return -1; return 0; }); this.setState({ creatureMap: creatureMapSorted }); } As you can see I gave each creature a unique id. This can most likely also be solved with Refs but I didn't feel fully comfortable with that yet. I am using the uuidv4 Function from this thread (answer from Briguy37). Creatures will give their id when the ini value in their input field changes so it can be changed in the creature map: <p className={style.statDisplay}>INI:<input type="number" className={style.inputField} defaultValue={this.state.currentIni} onBlur={e=>{this.handleIniChange(e); this.props.sortByIni(e,this.props.id)}}/></p> which then triggers this function in Encounter sortByIni(event,id) { let creatureMap = this.state.creatureMap; creatureMap.filter(creature=> { return creature.id == id })[0].currentIni = parseInt(event.target.value); let creatureMapSorted = creatureMap.sort((creatureA,creatureB) => { if (creatureA.currentIni < creatureB.currentIni) return 1; if (creatureA.currentIni > creatureB.currentIni) return -1; return 0; }); this.setState({creatureMap : creatureMapSorted}) } Creatures objects are put into an array and that array then gets sorted based on current initiative value, before getting applied to the state, thus triggering a render. As you can see, just a simple sort function with a custom comparator. Nothing fancy. Now as I said, normally react would not care that this list is sorted because the keys for the components are still the same. So it would not rerender them. I solved that problem like that: render(): any { return ( <div> <button type="button" onClick={this.addCreature}>Add Creature</button> {this.state.creatureMap.map((creature, i) => { return ( <Creature id={creature.id} name={creature.name} hitpoints={creature.hitpoints} key={this.uuidv4()} */Shortened...*/ /> ) })} </div> Like this, the key attribute is unique in every render, thus forcing react to rerender the entire thing and as such keep it sorted!
doc_23537484
<mark>Marked text</mark> This results in this very nice looking pdf-text: But how do I change the colour from it's default yellow to another colour? A: i would suggest something like this (using inline css). Note that i used !important because in some browsers it may be necessary to force the process. <mark style="background: #00ced1!important">Marked text</mark> alternatively, something like this (using external css). mark {background: red!important} <mark>Marked text</mark> in this case the property is applied to all the mark tags in the webpage. While this method works and is absolutely legitimate, it would be better, and more conventional, to use a css property like this: <p>this is a pretty paragraph with some <span style="background: blue">marked text</span></p> hope this helped :) A: The mark tag is not for Markdown, but to mark or highlight text for notation purposes. It essentially is used to make text appear to have been highlighted with a highlighter, which explains the yellow background. Using the inspect tool in my browser, I see that the default styles for mark are: mark { background-color: yellow; color: black; } So, to change the color, define some CSS. For example: mark { background-color: GreenYellow; } A: You can write <mark style="background-color:burlywood;">Marked text</mark> You can replace "burlywood" to any color of your choice.
doc_23537485
[Wed Aug 5 17:51:27 2020] PHP 7.4.8 Development Server (http://localhost:3000) started [Wed Aug 5 17:51:37 2020] 127.0.0.1:37788 Accepted [Wed Aug 5 17:51:37 2020] 127.0.0.1:37792 Accepted [Wed Aug 5 17:51:37 2020] 127.0.0.1:37788 [200]: (null) / [Wed Aug 5 17:51:37 2020] 127.0.0.1:37788 Closing [Wed Aug 5 17:52:02 2020] 127.0.0.1:37808 Closed without sending a request; it was probably just an unused speculative preconnection [Wed Aug 5 17:52:02 2020] 127.0.0.1:37808 Closing I would like to know if there is an option to start the server in a "silent" mode, where the logs would contain only info, warnings, and errors. A: If you are starting the PHP server yourself, passing it the -q or --no-header argument (Quiet-mode) solved it for me: php -q -S 127.0.0.1:8080 index.php See: https://stackoverflow.com/a/66864545
doc_23537486
I am using Ubuntu 16.04.2 LTS, precisely OSGeoLive11 package and files are being uploaded from Desktop of VM itself. Code works over other live server. upload.html <!DOCTYPE html> <html> <head> <title>Upload</title> </head> <body> <form action="../upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="file[]" multiple> <input type="submit" value="Upload"> </form> </body> </html> upload.php <?php // database configuration on oracle VM define('DB_HOST', 'localhost'); define('DB_PORT', 5432); define('DB_NAME', 'test'); define('DB_USER', 'test'); define('DB_PASS', 'test'); // connect to a database $conn = pg_connect("host=" . DB_HOST . " port=" . DB_PORT . " dbname=" . DB_NAME . " user=" . DB_USER . " password=" . DB_PASS); if (!$conn) { $error = error_get_last(); echo "Conn error: " . $error['message'] . "<br>"; } else { echo "Connected! <br>"; if (isset($_FILES['file'])) { print_r($_FILES); } } ?> Output on VM: Connected! Array ( ) What do I need to adjust? Thanks in advance! A: I realized I wasn't owner of any of the files I've been testing on VM. I guess I need to write on my wall sticker - check permissions first!
doc_23537487
But eggs comes from chicken. In many cases , the architecture needs to define the API . It's a connection between web developers and iOS/Android client developers. So is there such kind of tool or web , we can do follow things: New a API write the subURL write the POST/GET method write the post parameters write the returned answers write the sample request , any kinds of condition, error codes. After all this, there is a doc or Online doc html there. We can edit , update it after times pass by. The web/client developer , just need to watch the document ,then they are ready to go. Is there any kind of tool can archive this ? Thank you. A: There are a couple of specs for documents that allow clients to discover RESTful APIs. * *Swagger (demo) *apiary *JSON Home *Google use their own Discovery Service, however unlike the others, unfortunately I don't think there are open sourced libraries that help you use expose it from your own APIs. I have used swagger and it works well. The spec handles the things you have mentioned: * *JSON Schema to describe request/responses *A list of error codes/conditions *A codegen library to generate client side code for a number of languages such as Javascript, Java, Objective-C, Scala, PHP, Python, Ruby, and more.
doc_23537488
The first dataset (df1) is as follows: shark depth temperature   datetime    date      location A     49.5  26.2   20/03/2018 08:00 20/03/2018    SS04 A     49.5  25.3   20/03/2018 08:02 20/03/2018    SS04 A     53.0  NA     20/03/2018 08:04 20/03/2018    SS04 A     39.5  26.5   20/03/2018 08:50 20/03/2018    Absent A     43.0  26.2   21/03/2018 09:10 21/03/2018    Absent A     44.5  NA     21/03/2018 10:18 21/03/2018    SS04 I have reduced the number of columns for simplicity, but my actual dataset has 15 variables. The second dataset tides is a list of tide times: date   time  t_depth t_state  t_datetime 18/03/2018 02:33  2.09  High    20/03/2018 02:33 18/03/2018 08:39  0.45   Low    20/03/2018 08:39 18/03/2018 14:47  2.14  High    20/03/2018 14:47 18/03/2018 20:54  0.41   Low    20/03/2018 20:54 19/03/2018 03:01  2.13  High    21/03/2019 03:01 19/03/2018 09:09  0.41   Low    21/03/2019 09:09 I would like to add the t_state to df1 based on whether df1$datetime is within the tides$t_datetime for that tidal period.   I would also like to add t_depth which corresponds to that tidal state. I am very new to data.table and am getting quite confused by the syntax. I have tried to do this with df1[ copy(tides)t_state := i.t_state,      on = .( datetime >= t_datetime, datetime < end)] which doesn't work, but I'm not sure how to get around this. Ideally my output would be: shark depth temperature   datetime    date    location t_state t_depth A     49.5  26.2   20/03/2018 08:00 20/03/2018  SS04     High  2.09 A     49.5  25.3   20/03/2018 08:02 20/03/2018  SS04     High  2.09 A     53.0  NA    20/03/2018 08:04 20/03/2018  SS04     High  2.09 A     39.5  26.5   20/03/2018 08:50 20/03/2018  Absent   Low   0.45 A     43.0  26.2   20/03/2018 09:10 21/03/2018  Absent   Low   0.45 A     44.5  NA    20/03/2018 10:18 21/03/2018  SS04     Low   0.45 If possible, I would also like to know how to add the extra variables I omitted for simplicity, if there is anything I would need to add in to account for these? Thanks! Data via dput: structure(list(shark = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor"), depth = c(49.5, 49.5, 53, 39.5, 43, 44.5), temperature = c(26.2, 25.3, NA, 26.5, 26.2, NA), datetime = structure(1:6, .Label = c("20/03/2018 08:00", "20/03/2018 08:02", "20/03/2018 08:04", "20/03/2018 08:50", "21/03/2018 09:10", "21/03/2018 10:18"), class = "factor"), date = structure(c(1L, 1L, 1L, 1L, 2L, 2L), .Label = c("20/03/2018", "21/03/2018"), class = "factor"), location = structure(c(2L, 2L, 2L, 1L, 1L, 2L), .Label = c("Absent", "SS04"), class = "factor")), class = "data.frame", row.names = c(NA, -6L)) structure(list(date = structure(c(1L, 1L, 1L, 1L, 2L, 2L), .Label = c("18/03/2018", "19/03/2018"), class = "factor"), time = structure(c(1L, 3L, 4L, 5L, 2L, 2L), .Label = c("02:33", "03:01", "08:39", "14:47", "20:54"), class = "factor"), t_depth = c(2.09, 0.45, 2.14, 0.41, 2.13, 0.41), t_state = structure(c(1L, 2L, 1L, 2L, 1L, 2L), .Label = c("High", "Low"), class = "factor"), t_datetime = structure(c(2L, 3L, 1L, 4L, 5L, 6L), .Label = c(" 20/03/2018 14:47", "20/03/2018 02:33", "20/03/2018 08:39", "20/03/2018 20:54", "21/03/2019 03:01", "21/03/2019 09:09" ), class = "factor")), class = "data.frame", row.names = c(NA, -6L)) A: library( data.table ) #create posix-timestamp setDT(df1)[, timestamp := as.POSIXct( datetime, format = "%d/%m/%Y %H:%M" )] #create start and end of tidal period setDT(tides)[, start := as.POSIXct( t_datetime, format = "%d/%m/%Y %H:%M" )] tides[, end := shift( start, type = "lead" )] #left update non-equi join #left update non-equi join df1[tides, tide:=i.t_state, on=.(timestamp>=start,timestamp<end)][,timestamp:=NULL] shark depth temperature datetime date location tide 1: A 49.5 26.2 20/03/2018 08:00 20/03/2018 SS04 High 2: A 49.5 25.3 20/03/2018 08:02 20/03/2018 SS04 High 3: A 53.0 NA 20/03/2018 08:04 20/03/2018 SS04 High 4: A 39.5 26.5 20/03/2018 08:50 20/03/2018 Absent Low 5: A 43.0 26.2 21/03/2018 09:10 21/03/2018 Absent Low 6: A 44.5 NA 21/03/2018 10:18 21/03/2018 SS04 Low update for comment df1[tides, `:=`(tide=i.t_state, depth = i.t_depth), on=.(timestamp>=start,timestamp<end)][,timestamp:=NULL][]
doc_23537489
package main import ( "log" "sync" "time" ) var pool *sync.Pool type object struct { info string // other stuff } func initPool() { pool = &sync.Pool{ New: func() interface{} { return new(object) }, } } var ( lock sync.RWMutex registry = make(map[string][]chan interface{}) ) func sub(topic string) chan interface{} { ch := make(chan interface{}, 10) lock.Lock() registry[topic] = append(registry[topic], ch) lock.Unlock() return ch } // publish goroutine func pub() { ticker := time.NewTicker(time.Second) o := pool.Get().(*object) o.info = "new" // do something for _ = range ticker.C { lock.RLock() for topic, chs := range registry { if o.info != "new" { log.Printf("error") } if topic == "hello" { for _, ch := range chs { select { case ch <- o: default: } } } } lock.RUnlock() } } func run(topic string) { ch := sub(topic) for { select { case o := <-ch: switch o := o.(type) { case *object: if o.info != "new" { log.Printf("error") } // do something time.Sleep(time.Second) o.info = "used" pool.Put(o) } } } } func main() { initPool() for i := 0; i <= 100; i++ { go run("hello") } pub() } The question is the object borrowed from pool can be accessed by multiple goroutines, so if one goroutine puts it back to the pool after using, it may be modified by other goroutines. I don't know when all goroutines are done with the object, so that I can put it back to pool. A: One should call pool.Put() after he is done with the pooled object, ie it is considered to be "garbage". If you would put the o back into the pool in the pub then the next iteration of the loop could get the same object and assign new values to it's properties before it has been proccessed by the run. So right place to put your object back into pool is in run, after you have proccessed it.
doc_23537490
"real\t0m3.21s" Needs to be 3.21s The output is produced from time function. A: Using sed: sed -n 's/real\\t0m//p' <<< "real\t0m3.21s" Replace "read\t0m" for nothing and print
doc_23537491
I saw this documents but it seemed that there are no API to list sites. And I saw this questions but answer was there were no ways. List Microsoft Sharepoint Sites with Microsoft Graph Could you help me? A: Currently Graph API supported to get all SharePoint sites: https://graph.microsoft.com/v1.0/sites?search=* You can test in Graph Explorer firstly: Reference: Retrieve Site Collections And SubSites Using Microsoft Graph API
doc_23537492
So I can, let's say, insert or show only last 100 instead of entire view. The data is dynamically populated and inserted. Solution int _tableCount = _tableLayout.getChildCount(); if(_tableCount > 100) { _tableLayout.removeViewAt(100); } A: You can check count of rows by getChildCount() method, and add rows only if count is less than 100.
doc_23537493
https://jlultimate.github.io/reacteasy/ and the source code is here: github.com/jlultimate/reacteasy But it doesn't show the react app, but just shows the link to the same page and the README. The way I deployed the project was I used my project folder from my computer, used git remote add origin https://github.com/jlultimate/reacteasy.git, commited, pushed the files, installed gh-pages, added homepage to package.json, added predeploy and deploy to npm scripts, ran npm run predeploy and npm run deploy, and everything worked out nicely (except for showing the react app). First, I tried to change the homepage to https://jlultimate.github.io/reacteasy/public/index.html, I tried to re-build the create-react-app, I commited and pushed again to Github, nothing happened. When I opened https://jlultimate.github.io/reacteasy/public/index.html, it still leaves a blank screen like when I open the file in the project folder itself. Also, I tried to run the development server with "npm start" but instead it opened to localhost:3000/jlultimate.github.io/public/index.html, which I understand works. (And localhost:3000 itself works too, of course.) Please help! I have a million million-dollar react program-ideas to program in the future.
doc_23537494
A: I'm a little lost as to what you are asking about, but maybe the PostgreSQL's EXCEPT [ALL] operator is what you're looking for, e.g. select column_a, column_b, column_c from table_A except all select column_a, column_b, column_c from table_B ; Refer PostgrSQL Documentaion
doc_23537495
The first: http://huntinggrounds.de/test/sessionToken.php openen a new session via session_start() and has the variable $_SESSION['token'] = "123"; By doing an fetch (ajax-call) to my second file (formTest.php) I wolud like to return this $_SESSION['token']. But this is always not valid anymore. I detected that I get also always a new SessionID. What is definetely wrong. If I call http://huntinggrounds.de/test/formTest.php direkt over the browser. Everything is correct. So the issue must be the ajax call. Here are the sources: In start-file sessionToken.php: fetch(form.getAttribute("action"), { method: 'POST', headers: { 'x-csrf-token': token, 'Accept': 'application/json, text/plain, */*', 'credentials': 'include' }, body: data }) my PHP-file formTest.php <?php //session_id('joe'); //session_start(); if (session_status()==1) { session_start(); $sessionStart = "sessionNEU"; } header('Access-Control-Allow-Methods: POST'); header("X-Powered-By: joe"); header("Access-Control-Allow-Headers: x-csrf-token, X-Requested-With"); header("Access-Control-Expose-Headers: x-csrf-token"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Origin: *'); header($_SERVER["SERVER_PROTOCOL"]." 200 Ok"); header('Content-type: application/json'); $response= array(); $tokenNeu = generateToken(16); //$tokenAlt = $_SERVER['HTTP_X_CSRF_TOKEN']; $response["session"]["ID"] = session_id(); $response["session"]["savePath"] = session_save_path(); $response["session"]["startsNew"] = $sessionStart ? "yes" : "no"; $response["session"]["hasToken"] = isset($_SESSION['token']) ? "yes" : "no"; $response["session"]["token"] = $_SESSION['token']; $response["session"]["tokenValid"] = ($_SESSION['token'] == $_SERVER['HTTP_X_CSRF_TOKEN']) ? "valid" : "invalid"; $response["session"]["tokenCSFR"] = $_SERVER['HTTP_X_CSRF_TOKEN']; $response["session"]["tokenNew"] = $tokenNeu; echo json_encode($response);... Any idea what force the testForm.php to give a new SessionID. (When I set in both files session_id('joe'); it works like a charm) Please do not comment that the session_start(); has to be in the first line. This is tested and fails. I'am on PHP7. A: You need to put credentials inside options not in headers, see: http://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch fetch(form.getAttribute("action"), { method: 'POST', headers: { 'x-csrf-token': token, 'Accept': 'application/json, text/plain, */*' }, 'credentials': 'include', body: data })
doc_23537496
I have object with sub-objects like this: var tempForm = { name : {...}, age : {...}, e-mail : {...} } Then i've got function where I need to return htmlElement with id like object name in argument function get(obj){ return document.getElementById(// get obj name //); } So for example: test = get(tempForm.age); Should return HTMLObject < input id="age" > A: Calling get(tempForm.age) will pass the value of tempForm.age. There will be no connection to the string "age" at all. The general way to achieve this is to put the data you care about in the object. var tempForm = { name: { element_id: "name" }, age: { element_id: "age" }, "e-mail": { element_id: "e-mail" } } and function get(obj){ return document.getElementById(obj.element_id); } Alternatively, if you know that the tempFrom variable contains the "parent" object and tempForm is in scope for the get function then you can loop over tempForm and look for a match for the value that was passed in. This isn't a nice way to solve the problem though and you'd be better off structuring your data better or just passing the string "age" explicitly in the first place. A: i'd rewrite your function like: function getSomething(obj, propName) { //and then access property like var propObject = obj[propName]; //.... } if you call it test = getSomething(tempForm, "age"); you'd have in function: obj == tempForm propName == "age" propObject == {... age object of tempForm}
doc_23537497
If I have a Xib with multiple fields that all need their own Picker View, what's an appropriate/canonical way to add multiple picker views on the page without getting the Design View all cluttered up? 1) Only add the PickerView programmatically and not via the XIB? 2) Use only 1 Picker object and populate it with different values based on the field selection? (Possible memory benefits?) 3) Place the UIPickers on the View with a tiny height/width and then programmatically adjust height when necessary? Not even sure if the height is adjustable. 4)Combination of some of the above? You can see in the image below, how cluttered it looks already even with just one picker view: A: The view that you have with the text fields and picker views would lend itself to be part of a UITableView. See the calendar app when you add an event. You can set this up fairly easily by using a static UITableView. I'm replying on my phone at the moment but will look for a tutorial if you would like. A: If only one pickerView will be visible at once, then you should consider using only one pickerView and configure it's delegate/datasource so that you can give it a different datasource for each field. Unless more than one is visible at once, there really isn't any reason to use more than one in your nib file. And even if you used more than one, you would still have to configure you delegate/datasource methods to handle each individual picker. Hope that helps. EDIT: It would be a little bit of work, but if you wanted the pickerView to animate in and out of the view whenever you need and if you wanted to clean your Xib up even more you could do the following: * *Create a subview containing your pickerView *Set up a protocol on the subview to allow you to pass the selected value back to the view controller. *Set up your viewController to conform to the protocol on your picker subview. *Set the pickerView to be each textField's inputView. *Set the textField's delegate methods to configure the dataSource of your subview when editing begins. By doing this, you have set your textField so that when it receives firstResponder that it will display the pickerView instead of a keyboard.
doc_23537498
I am looking for a return on the first line but the others should be null. Essentially I need CT CHEST or CT LUNG Any assistance TIA with test (id, description) as ( select 1, 'CT CHEST HIGH RESOLUTION, NO CONTRAST' from dual union all --want this select 2, 'INJECTION, THORACIC TRANSFORAMEN EPIDURAL, NON NEUROLYTIC W IMAGE GUIDANCE.' from dual union all --do not want this select 3, 'The cow came back. But the dog went for a walk' from dual) --do not want this select id, description, regexp_substr(description, '(?<![a-z]ct).{1,20}(CHEST|THOR|LUNG)',1,1,'i') from test; A: regexp_substr(description,'([^A-Z]|^)[CT].{1,20}(CHEST|THOR|LUNG)',1,1,'i') works A: Leverage Oracle Subexrpession Parameter to Check for CT I would leverage the use of subexpressions to use a pattern like this: 'regexp_substr(description, '(^| )((ct ).*((CHEST)|(THOR)|(LUNG)))', 1, 1,'i', 2)` -subexpression 1 to look for beginning of line or a space: (^| ) -subexpression 3 to look for 'CT': (ct ) -allow for other characters: .* -subexressions 5,6,7: (CHEST)|(THOR)|(LUNG) -subexpression 2 which contain subexpression 3 an subexprssion 4 I use the last optional parameter to identify that I want subexpression 2. WITH test (id, description) as ( SELECT 1 , 'CT CHEST HIGH RESOLUTION , NO CONTRAST' FROM dual UNION ALL --want this SELECT 2 , 'INJECTION , THORACIC TRANSFORAMEN EPIDURAL , NON NEUROLYTIC W IMAGE GUIDANCE.' FROM dual UNION ALL --do not want this SELECT 3 , 'The cow came back. But the dog went FOR a walk' FROM dual ) --do not want this SELECT id , description , regexp_substr(description, '(^| )((ct ).*((CHEST)|(THOR)|(LUNG)))', 1, 1,'i', 2) FROM test;
doc_23537499
@PrepareForTest(Files.class) public void testGetNotExistingRestFile() throws Exception { PowerMockito.mockStatic(Files.class); PowerMockito.doThrow(mock(IOException.class)).when(Files.readAllBytes(any(Path.class))); } Every time an NullPointerException is thrown and I can figure out what I'm doing wrong. java.lang.NullPointerException at java.nio.file.Files.provider(Files.java:67) at java.nio.file.Files.newByteChannel(Files.java:317) at java.nio.file.Files.newByteChannel(Files.java:363) at java.nio.file.Files.readAllBytes(Files.java:2981) at nl.mooij.bob.RestFileProviderTest.testGetNotExistingRestFile(RestFileProviderTest.java:53) How can I stub the function readAllBytes from java.nio.file.Files with PowerMockito? A: Call Mockito, instead of PowerMockito and reverse the stubbing order: @Test(expected=IOException.class) @PrepareForTest(Files.class) public void testGetNotExistingRestFile() throws Exception { // arrange PowerMockito.mockStatic(Files.class); Mockito.when(Files.readAllBytes(Matchers.any(Path.class))).thenThrow(Mockito.mock(IOException.class)); // act Files.readAllBytes(Mockito.mock(Path.class)); } Another possibility is: @Test(expected=IOException.class) @PrepareForTest(Files.class) public void testGetNotExistingRestFile() throws Exception { // arrange PowerMockito.mockStatic(Files.class); Files filesMock = PowerMockito.mock(Files.class); Mockito.when(filesMock.readAllBytes(Matchers.any(Path.class))).thenThrow(Mockito.mock(IOException.class)); // act filesMock.readAllBytes(Mockito.mock(Path.class)); } Reference: Using PowerMockito to Mock Final and Static Methods A: Make sure you are including the class that calls the static method in your @PrepareForTest. @PrepareForTest({Files.class, ClassThatCallsFiles.class}) A: Please add this dependency in pom.xml While Mocking Files class for static method. <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-core</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency> This is also one of the factor you are getting NullPointerException