text
stringlengths
64
81.1k
meta
dict
Q: Magento - non eav collection sort order In Magento, when using non eav collections what is the best way to add sort orders? With eav collections i believe there are convenience methods for doing this but with non eav there dont appear to be the same facilities. A: Both Magento collection superclasses (Mage_Core_Model_Resource_Db_Collection_Abstract and Mage_Eav_Model_Entity_Collection_Abstract) inherit three public convenience methods from the collection superclass Varien_Data_Collection_Db: setOrder() addOrder(), an alias for setOrder() unshiftOrder(), for moving a sort parameter to the first position The EAV collection superclass provides another method, addAttributeToSort(), which ensures that the attribute is joined on to the collection for sorting. As Vinai has pointed out on his tumblr, there are some considerations in how and when these methods will behave. A: The only method that worked for me for sorting custom module collection (flat collection) is to use as: $sortField = 'field-goes-here'; $direction = 'ASC'; //or 'DESC' $collection->getSelect()->order($sortField , $direction); Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to change MongoDB _id field name in MongoEngine from $oid to $id? When querying MongoDB using mongoengine it returns result with minor differences to what I expect. One of the important ones is $oid which is returned but I don't like it: "_id": { "$oid": "5e3c0f7f284137537bf7c994" }, Is there a way to project differently in mongoengine? What I want is a simple id field: "id": "5e3c0f7f284137537bf7c994" EDIT1: When I want to get string version of ID I can use .id to get let's say "5e3c0f7f284137537bf7c994". But problem is where I want to get the whole document: MyModel.objects.all() This query returns a list of all documents from MyModel, BUT list of documents contain $oid rather than string version of _id. How should I get _id as is NOT $oid. A: You need to use aggregate method with $toString operator pipeline = [ {"$addFields" : {"_id" : {"$toString" : "$_id"} } } ] data = MyModel.objects().aggregate(pipeline) http://docs.mongoengine.org/guide/querying.html#mongodb-aggregation-api Note: This won't return MyModel instance, you lose mongoengine features But, if you do not want lose features (works only for to_json): from bson import json_util, son .. class MyModel(Document): content = StringField(required=True) #setup your attributes def to_json(self, *args, **kwargs): raw = self.to_mongo() tmp = [(k, str(raw[k]) if k == "_id" else raw[k]) for k in raw] return json_util.dumps(son.SON(tmp), *args, **kwargs) ... # This returns <class 'mongoengine.queryset.queryset.QuerySet'> data = MyModel.objects() print(data[0]) print(data[0].to_json()) print(data.to_json()) print("[%s]" % ",".join([foo.to_json() for foo in data])) ---- MyModel object {"_id": "5e400e737db7d0064937f761", "content": "foo"} [{"content": "foo", "_id": {"$oid": "5e400e737db7d0064937f761"}}, {"content": "bar", "_id": {"$oid": "5e400e737db7d0064937f762"}}] [{"_id": "5e400e737db7d0064937f761", "content": "foo"},{"_id": "5e400e737db7d0064937f762", "content": "bar"}]
{ "pile_set_name": "StackExchange" }
Q: How to do operation on an output tables in sql or php I have these tables courses students_records --------------------- -------------------------------- NO code CRD name ID NO grade --------------------- -------------------------------- 1 COE200 4 Michael 2255 1 A 2 COE305 3 Michael 2255 2 B+ grades --------------------- NO. points --------------------- A 4 B+ 3.5 I wrote this query SELECT courses.code,student_records.grade,courses.crd,grades.points FROM grades INNER JOIN student_records ON grades.letter = student_records.grade INNER JOIN courses ON courses.no = student_records.no WHERE student_records.id=2255; so the out put of this query will be like this grades ------------------------------ code grade CRD points ------------------------------ COE200 A 4 4 COE305 B+ 3 3.5 My question is How I can write function in php or query in order to multiply CRD and points and do sum after multiply like this. (CRD * points) (4*4)+(3*3.5)=26.5 A: You can perform the math in the SQL Select and an aggregation to do the sum. To get the grade/credits to show, you can use this query: SELECT courses.code, student_records.grade, courses.crd,grades.points, courses.crd * grades.points AS grade_credits FROM grades INNER JOIN student_records ON grades.letter = student_records.grade INNER JOIN courses ON courses.no = student_records.no WHERE student_records.id=2255; For the sum, you can use most of the same query: SELECT student_records.id, SUM(courses.crd * grades.points) AS sum_grade_credits FROM grades INNER JOIN student_records ON grades.letter = student_records.grade INNER JOIN courses ON courses.no = student_records.no GROUP BY student_records.id This would give you results for all students.
{ "pile_set_name": "StackExchange" }
Q: Creating Windows Startup Services via REG or Command Line I have a Java program which needs to be a startup program that runs as administrator. It seems that cannot be done without making it a service. I have tried using HKLM\SYSTEM\CurrentControlSet\Services\Services\MyService. I tried something similar to what Google Updater uses (they use ...\Services\gupdate). The process does not start (or at least it stops right away, which I cannot tell for sure. I think it is something wrong with how I am using the registry because the service does not show up in msconfig.exe under the Services tab. Also it doe not show up in the Control Panel "View local services" (Windows 7, found in the Start Menu search for "services") I tried a much simpler approach found here. I create a .reg file with these contents. Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService] "Description"="My Service starts the Special Process." [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\Parameters] "Application"="C:\\Test\\MyProcess.cmd" I am willing to consider an alternative command-line alternative if necessary, but I like the registry approach because if I tell my installer to add certain registry items, it will automatically remove those items on uninstall. Is there any reason that above .reg file would not add an item to msconfig that is named "MyService"? The program which I wrote is written in Java. It does not have a GUI interface. A: You can't create a service by manipulating the registry. Nor can you run an arbitrary application as a service. To run an arbitrary program from within a service, use the srvany.exe service available in the Windows Server 2003 resource kit. See KB137890 for instructions. If you want to write your own service, see this. To create a service you can use the sc command line tool, or the instsrv.exe tool from the Windows Server 2003 resource kit. Or use the CreateService Win32 API function.
{ "pile_set_name": "StackExchange" }
Q: Assembler conditional set not executed movq $0, %r11 movq $5, %r10 cmpq %r11, %r10 setl %r11b After this, r11 is not set. But from what I understand, 0 is less than 5 so it should be. I am using gnu assembler and gcc. as --version GNU assembler (GNU Binutils for Ubuntu) 2.22 A: Um, It seems that you're confused between Intel and AT&T cmpq %r11, %r10 in AT&T is equal to cmp r10, r11 in Intel. Try cmpq %r10, %r11 to get your expected result.
{ "pile_set_name": "StackExchange" }
Q: Parsing mutliple double quoted filename using Java I just want to take a line containing multiple filenames using enclosed by double quotes (this is what Windows seem to use when multiple files are selected in a file dialog" and get them back as separate strings. i.e given "C:\MusicMatched2\Gold Greatest Hits" "C:\MusicMatched2\The Trials of Van Occupanther" I want to decode that to two strings: C:\MusicMatched2\Gold Greatest Hits C:\MusicMatched2\The Trials of Van Occupanther I usually use String.split() but thats no good in this instance, can anyone help Answer, the regexp given in the answer worked implemented as follows: Pattern p = Pattern.compile("\"([^\"]++)\""); Matcher matcher =p.matcher("C:\MusicMatched2\Gold Greatest Hits" "C:\MusicMatched2\The Trials of Van Occupanther"); while(matcher.find()) { System.out.println(matcher.group(1)); } A: The most faster pattern is probably: "\"([^\"]++)\"" with find method, the result is in capturing group 1.
{ "pile_set_name": "StackExchange" }
Q: Linux Mint trigger slowly query on mysql on system booting My debian-based is booting so slow after I installed MySQL and imported some databases on it. Looking for some statement, I found this one during boot: mysql> show full processlist; +----+------------------+-----------+------+---------+------+----------------+----------------------------------------------------------------------+ | Id | User | Host | db | Command | Time | State | Info | +----+------------------+-----------+------+---------+------+----------------+----------------------------------------------------------------------+ | 9 | debian-sys-maint | localhost | NULL | Query | 12 | Opening tables | select count(*) into @discard from `information_schema`.`PARTITIONS` | | 10 | root | localhost | NULL | Query | 0 | NULL | show full processlist | +----+------------------+-----------+------+---------+------+----------------+----------------------------------------------------------------------+ 2 rows in set (0.00 sec) Here the statement that causing trouble: select count(*) into @discard from `information_schema`.`PARTITIONS` I have +-10 databases totaling over 8gb of data. Is there any configuration to disable this query on system booting ? If yes, why run it during boot ? Information I have a standard MySQL installation without custom configs. Best regards. A: It seems Debian, whose Linux Mint is based upon, have scripts that get executed when the mysql server is started or restarted, to check for corrupted tables and make an alert for that. In my Debian server, the culprit seems to be /etc/mysql/debian-start bash script, which in turn calls /usr/share/mysql/debian-start.inc.sh , so check both scripts and comment out the function that is iterating all your tables, from a quick look it seems the following: check_for_crashed_tables; which is called from the debian-start script I mentioned above.
{ "pile_set_name": "StackExchange" }
Q: Rails 3.2: ArgumentError: wrong number of arguments (2 for 1) on create Trying to create an instance of a model, I get the following error... u = User.create # or .where(...).first_or_create # or .where(...).first_or_initialize ArgumentError: wrong number of arguments (2 for 1) Is anyone having the same problem with Rails 3.2? A: Have you overloaded your model's initialize method? In my case, I had overloaded it with: def initialize(attributes=nil) ... end Which I had to fix to: def initialize(attributes = nil, options = {}) ... end In Rails 3.2, the commit 7c5ae0a88fc9406857ee362c827c57eb23fd5f95 (Added mass-assignment security :as and :without_protection support to AR.new) added more arguments to the above method and that's why my previous implementation was failing.
{ "pile_set_name": "StackExchange" }
Q: Server can't set IP after power outage The power went out all of a sudden and when we tried to restart everything when it came back on - our server can't be assigned an IP? We got an error stating that the IP for the server was already in use by another system. We then shut down all systems and restarted the server but then for some reason the server was assigned an IP but no one could connect to it - after restarting the server after setting it to have a dynamically assigned ip - the server now has no ip - just 0.0.0.0 - running an ipconfig/renew or ipconfig /release has no effect.. what should we do!! ============================== OK the server somehow got the ip and only one pc on teh network can access it - however other pcs can't even ping it for some strange reason. Infact one PC which I'm trying desperately to put on the domain gives me a cannot find domain controller error. Plus when I ran an ip config on the other pcs they show a 'media disconnected' on the ipconfig even though they all have ips set up...... whats happening here? A: What happens if you turn it off and ping the server's IP that it's supposed to have? Anything answering? What if you remove and reinstall the network card driver? Does the server have more than one card, or is it teamed with a second card? Redundancy? What kind of hardware is it? Update the driver on the card? Change the port the network cable is plugged into no the switch? Still happen? Could be the switch is confused or damaged. Other possibility is that the network card is damaged. Can you install a third-party card?
{ "pile_set_name": "StackExchange" }
Q: how to use regex to strip the preprocessor directive FI have many code which contains code snippet like: #if wxCHECK_VERSION(2, 9, 0) Codef( _T("%AAppend(%t)"), ArrayChoices[i].wx_str()); #else Codef( _T("%AAppend(%t)"), ArrayChoices[i].c_str()); #endif But I want to clean the code to Codef( _T("%AAppend(%t)"), ArrayChoices[i].wx_str()); I mean, I need to strip the preprocessor directive, and only leave the first branch. The match condition should be: #if wxCHECK_VERSION(2, 9, 0) blablabla1 #else blablabla2 #endif The content of blablabla1 and blablabla2 should be the same only except the wx_str and c_str. See here, someone said it can be handled by regex, but I have no idea, can you help me? Thanks. EDIT: I just want to strip the #else branch, and only keep the first branch contents. Here is the reference page: Re: what's the best and quick way to remove all the wx_str and c_str preprocessor A: Search This regex works for your examples: \s+#if wxCHECK_VERSION\(2\, 9\, 0\)\s*(.*?)wx_str([^\r\n]*?)\s*#else\s*(\1)c_str(\2)\s*#endif Replacement Regexr.com: Replace with: $1wx_str$2. Don't forget to select dotall option. Notepad++: Replace with: \1wx_str\2. Don't forget to select . matches newline option. Batch Mode Notepad++ allows to find/replace in batch mode. Open "Find in Files" dialog pressing Ctrl+Shift+H. Copy-paste above regex to "Find what" box. Copy-paste above replacement (\1wx_str\2) to "Replace with" box. Specify Directory to find/replace in it. Select Regular Expression in Search mode group box. Check the . matches newline box. Click to "Find All" button to view matches. Click to "Replace in Files" button when you are sure to replace everything.
{ "pile_set_name": "StackExchange" }
Q: Prove that $\int _0^1x^a\left(1-x\right)^bdx$ = $\int _0^1x^b\left(1-x\right)^adx$, where $a,b\in \mathbb{R}$ Prove that $$\int _0^1x^a\left(1-x\right)^bdx = \int _0^1x^b\left(1-x\right)^adx$$ How can I even get started on this? I evaluate the integral with parts, but it just gets more and more tedious since I'm working with these constants here. A: Substitute $u=(1-x)$. We then have $du=-dx$ and when $x=0$, we have $u=1$, $x=1$ gives $u=0$. Thus $$\int_0^1x^a(1-x)^bdx=-\int_1^0(1-u)^au^bdu=\int_0^1(1-u)^au^bdu$$ No integration by parts or anything necessary, just a straight substitution. A: Let's change variable $y=1-x$ i.e $dx=-dy$. The integral rewrites as follows $$\int_0^1x^a(1-x)^bdx=-\int_1^0(1-y)^ay^bdy=\int_0^1(1-x)^ax^bdx$$
{ "pile_set_name": "StackExchange" }
Q: New to scikit.learn and kmeans, How to clusterize documents (From File) using K means? What i am trying to do is using Kmeans from scikit.learn to Clusterize pure text documents into Two Categories. Here is use-case scenario. I will recieve a few sample sets which are going to be tagged as "Important" and which are Going to be tagged as "Un-Important". From scikit.learn examples data set is predefined format from newsgroups : dataset = fetch_20newsgroups(subset='all', categories=categories, shuffle=True, random_state=42) What i want to do is to receive data from Text files (20newsgroups seems not text file at all , i cannot even unzip it) What i am not clear is the data structure of that fetch_20newsgroups and how it works. And what should i do to convert Text Files into required format (Such one provided by fetch_20newsgroups) Thanks Phyo. A: The 20 newsgroups dataset loader shipped with scikit-learn fetches the archive of text documents downloaded from the original site at http://kdd.ics.uci.edu/databases/20newsgroups/20newsgroups.html and then cache them in a compressed format in the $HOME/scikit_learn_data folder. Have a look at the source code of the 20 newsgroups dataset loader for more details. To load your own set of text files as a scikit-learn "bunch" object you can use the sklearn.datasets.load_files function directly by pointing it to the right folder. If your data is already categorized into 2 categories (e.g. two subfolders named "Important" and "Un-Important") then what you need to use is not a clustering algorithm which is unsupervised but a classification such as MultinomialNB (Naive Bayes), LinearSVC (Linear Support Vector Machine) or LogisticRegression which are supervised as in the text classification example. If you don't know which document belongs to which category but want to group your corpus into 2 groups of similar documents then you can use unsupervised clustering algorithms such as KMeans but it's very unlikely that the 2 clusters you will get match your idea "Important" and "Un-important".
{ "pile_set_name": "StackExchange" }
Q: Sending Email disable/fixed mailto and subject,i.e., this two sections are not editable format. Is this possible? I am unable to disable mailto and subject section when the intent comes on email section, but I need this two section fixed from my programming part. For an example Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts( "mailto","[email protected]", null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); startActivity(Intent.createChooser(emailIntent, "Send email...")); Here I want mail will be send only "[email protected]" and user will not be able to edit this thing or not to put another email id. Same case for subject also. Is this possible? Please suggest me. A: I don't think that would be possible as you are just launching a third party application which your application have no control over. If you want to implement that feature in your app then you should use an SMTP library to send an email without user intervention. This article might help you.
{ "pile_set_name": "StackExchange" }
Q: expected class, delegate, enum, interface or struct error C# have a php code like this,going to convert it in to C#. function isValid($n){ if (preg_match("/\d+/",$n) > 0 && $n<1000) { return true; } return false; } Here is my try,BUT error shown Error is "expected class, delegate, enum, interface or struct error C#" public string IsValidate(string Item) { string Result = Item; try { Result = System.Text.RegularExpressions.Regex.Replace(InputTxt, @"(\\)([\000\010\011\012\015\032\042\047\134\140])", "$2"); } catch(Exception ex) { console.WriteLine(ex.Message) } return Result; } What is the error,Is there any other way to implement this better than my try ? i got this snippet from here code A: You haven't define this method inside a class/struct that is why you are getting this error. You may define this method inside a class. public class MyValidator { public string IsValidate(string Item) { //Your code here } } Later you can use it like: MyValidator validator = new MyValidator(); validator.IsValid("Your string"); Also you are missing semicolon at the end of the Console.Write statement, plus 'c' for Console should be in uppercase Edit: Since in your php code, it looks like you are trying to see if the string passed is an integer and it is less than 1000, you may use the int.TryParse like the following: public class MyValidator { public bool IsValidate(string Item) { string Result = Item; int val; if (int.TryParse(Item, out val) && val > 0 && val < 1000) { return true; } else { return false; } } } In you main method you can do: static void Main() { MyValidator validator = new MyValidator(); Console.WriteLine(validator.IsValidate("asdf123")); // This will print false Console.WriteLine(validator.IsValidate("999")); //This will print true Console.WriteLine(validator.IsValidate("1001")); //This will print false } A: In C# a method must be placed inside a class or struct: public class Validator { public string IsValidate(string item) { ... } } In this case I would probably translate it like this: public static class Validator { public static bool IsValid(string item) { int value; return int.TryParse(item, out value) && value > 0 && value < 1000; } }
{ "pile_set_name": "StackExchange" }
Q: Publishing a library using jfrog.bintray HTTP/1.1 404 Not Found [message:Repo '' was not found] I've been twisting my head around this issue for far too long today, can't seem to figure out what's wrong with this setup. I've followed this tutorial in order to be able to upload an android library to bintray (and later add it to jcenter). Here are the relevant files: Project level build.gradle: buildscript { ext.kotlin_version = '1.3.20' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.3.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4' classpath "com.github.dcendents:android-maven-gradle-plugin:2.1" } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } Library level build.gradle: apply plugin: 'com.android.library' apply plugin: 'com.jfrog.bintray' apply plugin: 'com.github.dcendents.android-maven' ext{ bintrayRepo = "FlexibleRecyclerView" bintrayName = "com.tornelas.flexiblerecyclerview" libraryName = "flexiblerecyclerview" //artifact publishedGroupId = 'com.tornelas.flexiblerecyclerview' artifact = 'flexiblerecyclerview' libraryVersion = '0.1' libraryDescription = 'A recycler view where you can set the number of columns/rows and orientation on the .xml file instead of setting it on the layout manager.' siteUrl = '' gitUrl = '' developerId = 'tornelas' developerName = 'Tiago Ornelas' developerEmail = '' licenseName = 'The Apache Software License, Version 2.0' licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.text' allLicenses = ['Apache-2.0'] } android { compileSdkVersion 28 defaultConfig { minSdkVersion 14 targetSdkVersion 28 versionCode 1 versionName "0.1" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' } if(project.rootProject.file('local.properties').exists()){ apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle' apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle' } (I've omitted siteUrl, gitUrl and developerEmail for privacy reasons) On the bintray dashboard: http://snpy.in/UwPAv5 When I run 'bintrayUpload' I get the following: 1: Task failed with an exception. Execution failed for task ':flexiblerecyclerview:bintrayUpload'. > Could not create package 'tornelas/FlexibleRecyclerView/com.tornelas.flexiblerecyclerview': HTTP/1.1 404 Not Found [message:Repo 'FlexibleRecyclerView' was not found] 2: Task failed with an exception. Execution failed for task ':bintrayPublish'. > Could not sign version '0.1': HTTP/1.1 404 Not Found [message:Repo 'FlexibleRecyclerView' was not found] I was wondering if this issue was occurring because this library "FlexibleRecyclerView" is part of an organization (called "Frontkom"). But I couldn't get my head around a solution for this. I'm sure the credentials on local.properties are correct as I already authenticated using their REST API with them. Many thanks in advance! A: So, the issue was that I was trying to publish to a repository that belonged to my organization (even though I'm the owner of that organization) and I'm unable to create repos outside that organization. For that reason, just by adding bintray { pkg { userOrg = 'myorganizationname' } } to my module's build.gradle right after the ext{} I was able to upload this successfully.
{ "pile_set_name": "StackExchange" }
Q: How far can a triangle center be from the triangle? As is well known, a triangle center can be exterior to the triangle. So, just how far from the triangle can one of its centers be? A: As far as you want it to be. If you have a triangle whose circumcenter is 1 unit away from the triangle, you can just double all the sides of that triangle, and you get a triangle whose circumcenter is 2 units away. And so on. Even if you limit yourself to, say, triangles with no sides longer than $1$ in order to make this scaling infeasible, you can do it another way. Consider if you have an isosceles triangle where two sides are $0.5$ and the angle between them is close to $180^\circ$. The closer to $180^\circ$ you make that angle (while keeping the triangle isosceles and the two side lengths constant), the further away the circumcenter moves. And there is no bound on how far away the circumcenter can move in this manner; as our triangle comes closer and closer to being a degenerate triangle (three points on a line), the circumcircle comes closer and closer to being that line (which in this case is what a circle with infinite radius looks like).
{ "pile_set_name": "StackExchange" }
Q: ASP.NET - Accessing Active Directory from code behind page I have made a web application, which reads/writes from/to Active Directory. In my web.config file there is <identity impersonate="true"/> and <authentication mode="Windows"/> When I display System.Web.HttpContext.Current.User.Identity.Name in some label, it shows mydomain\myusername, so I think impersonation works. Now to the question. When I access the application on the server, where the IIS web server is running, everything works great. But when I access the web application from a remote PC, I get an exception (the label still shows "mydomain\myusername"). I have traced the problem down. In the code behind when I call Forest currentForest = Forest.GetCurrentForest(); the variable currentForest knows its currentForest.Name, currentForest.RootDomain or currentForest.ForestMode, but any call to currentForest.Domains, currentForest.Sites or currentForest.GlobalCatalogs results in System.DirectoryServices.ActiveDirectory.ActiveDirectoryOperationException. Now I'm lost and don't know what to debug further. The account I'm using is member of Enterprise Admins (multi-domain forest). I have tried it on two different servers with different IIS versions (IIS 7.5 and IIS 6.0) with no luck. And the thrown exception isn't of much help: Exception Details: System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: DirectoryServicesCOMException (0x80072020): An operations error occurred. System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +557 System.DirectoryServices.DirectoryEntry.Bind() +44 System.DirectoryServices.DirectoryEntry.get_AdsObject() +42 System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) +98 System.DirectoryServices.ActiveDirectory.ADSearcher.FindAll() +46 System.DirectoryServices.ActiveDirectory.Forest.GetDomains() +543 [ActiveDirectoryOperationException: An operations error occurred.] System.DirectoryServices.ActiveDirectory.Forest.GetDomains() +512484 System.DirectoryServices.ActiveDirectory.Forest.get_Domains() +44 myWebApp.ASPpage.Button_Click(Object sender, EventArgs e) in C:\Documents and Settings\myUser\documents\visual studio\Projects\MyWebApp\MyWebApp\ASPPage.aspx.cs:158 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +115 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +140 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981 EDIT: If it is not obvious, I want to use currentForest.Domains to search the whole forest (all domains) for a user given by UPN name. A: I found the answer to my question in one of "Related questions" on this page. The answer was in this topic: Why does DirectoryServicesCOMException occur querying Active Directory from a machine other than the web server? I found, that it was exactly my case. After reading the suggested Microsoft article, I learned, that impersonating works only for local resources on the IIS server. To access network resources (SQL, Active Directory), I have to set "Trust this computer for delegation" in the computer object in Active Directory.
{ "pile_set_name": "StackExchange" }
Q: Scrollbar on lightbox showing for just a moment; Please take a look at this site: removed per request When you click Learn More, the Fancybox lightbox window pops up and looks fine, but when you click the right arrow on the lightbox, a scrollbar shows up for just an instant (it reaches all the way to the top of the doctor's picture). This is happening on Chrome and Safari. I can't figure out what code to write to not show that scrollbar. The content will never be long enough to need a scrollbar (except on mobile, etc). Another option would be to just have the scrollbar stop at the top of the content container (not go all the way up to the top of the dr's picture). Please help if you can; it would be much appreciated!! I'm a newb to jQuery/Javascript. Thank you!! A: You can try to solve this with CSS. Set overflow: hidden on the container div. This will hide any content that overflows the container, so use with care.
{ "pile_set_name": "StackExchange" }
Q: Android Q Kotlin - API 29: check if image exists This is the code I'm using to save image in Android Q: private var fileName = "" private fun downloadImage(){ val folderName = "Funny" fileName = "bla_" + dlImageURL.split("/").toTypedArray().last() // find out here if this image already exists val requestOptions = RequestOptions() .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.NONE) val bitmap = Glide.with(this@DownloadImage) .asBitmap() .load(dlImageURL) .apply(requestOptions) .submit() .get() try { val values = ContentValues() values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000) values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/$folderName") values.put(MediaStore.Images.Media.IS_PENDING, true) values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()) values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName) values.put(MediaStore.Images.Media.TITLE, fileName) // RELATIVE_PATH and IS_PENDING are introduced in API 29. val uri: Uri? = [email protected](MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) if (uri != null) { saveImageToStream(bitmap, [email protected](uri)) values.put(MediaStore.Images.Media.IS_PENDING, false) [email protected](uri, values, null, null) } } catch (e: Exception) { } } private fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) { if (outputStream != null) { try { bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream) outputStream.close() } catch (e: Exception) { e.printStackTrace() } } } How can I find out if this image already exists in the gallery before I download it? I commented where it needs to be. I already looked up and can't find out how to get the damn path, it was much easier < API 29 A: I wrote sample code with ContentResolver.query() method. So I tried with Android Q. Sample is like this: val projection = arrayOf( MediaStore.Images.Media.DISPLAY_NAME, MediaStore.MediaColumns.RELATIVE_PATH ) val path = "Pictures/$folderName" val name = fileName val selection = MediaStore.Files.FileColumns.RELATIVE_PATH + " like ? and "+ MediaStore.Files.FileColumns.DISPLAY_NAME + " like ?" val selectionargs = arrayOf("%" + path + "%", "%" + name + "%") val cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionargs, null); val indexDisplayName = cursor?.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME) if(cursor!!.count > 0){ // file is exist } // or you can see displayName while (cursor!!.moveToNext()) { val displayName = indexDisplayName?.let { cursor.getString(it) } }
{ "pile_set_name": "StackExchange" }
Q: how to access a 2D array in ajax So basically a return value of my function is a 2D array and I plan to display every single row and column; however, I am having trouble accessing them individually i.e. row[0][0] I've tried the stringify function from what I've seen in similar questions though have had no luck in making it work. This is the code: ajax: $.ajax({ url: "viewDayDocuments", type: 'post', data: {currentDay: currentDay, currentMonth: currentMonth, currentYear: currentYear}, success: function(result){ $('.list').text(''); $('.list').remove(); incomingDoc = JSON.stringify(result); $(".listIncoming").html("<p class = 'list'>This is the: "+ incomingDoc['referenceNo'] + "</p>"); $("#myform").show(500); } }); controller code: $date = $data['year']."-".$data['month']."-".$data['day']; $this->load->model('search_form'); $output['details'] = $this->search_form->searchDateRetrievedIncoming($date); echo json_encode($output); model code returning a 2D array: $rows[] = array(); $rows2[] = array(); $rows3[] = array(); $i = 0; $companyName = $this->db->query("SELECT id, name from company"); foreach($companyName->result_array() as $row2){ $rows2[$i]['id'] = $row2['id']; $rows2[$i]['name'] = $row2['name']; $i++; } //get all company names $i = 0; $staffName = $this->db->query("SELECT id, surname, firstName, middleInitial from employee"); foreach($staffName->result_array() as $row3){ $rows3[$i]['id'] = $row3['id']; $rows3[$i]['name'] = $row3['surname'].", ".$row3['firstName']." ".$row3['middleInitial']; $i++; } //get all employee names $i= 0; $output = $this->db->query("SELECT * from incoming WHERE dateReceived BETWEEN '$searchQuery' AND DATE(NOW()) ORDER BY incomingId LIMIT 20"); if ($output->num_rows() > 0) { foreach($output->result_array() as $row){ $count = 0; $j = 0; $rows[$i]['incomingId'] = $row['incomingId']; $rows[$i]['referenceNo'] = $row['referenceNo']; $rows[$i]['documentTypeId'] = $row['documentTypeId']; $rows[$i]['documentDate'] = $row['documentDate']; $rows[$i]['dateReceived'] = $row['dateReceived']; $rows[$i]['sender'] = $row['sender']; while($count < sizeof($rows2)){ if($rows2[$j]['id'] != $row['companyId']){ $j++; }else{ $rows[$i]['companyName'] = $rows2[$j]['name']; break; } $count++; } $j= 0; $count = 0; while($count < sizeof($rows3)){ if($rows3[$j]['id'] != $row['responsibleStaffId']){ $j++; }else{ $rows[$i]['responsibleStaffName'] = $rows3[$j]['name']; break; } $count++; } $rows[$i]['subject'] = $row['subject']; $rows[$i]['actionDone'] = $row['actionDone']; $rows[$i]['track'] = $row['track']; $rows[$i]['completed'] = $row['completed']; $rows[$i]['remarks'] = $row['remarks']; $i++; } return $rows; } return false; Working Answer: incomingDoc = JSON.parse(result); for(var i = 0; i < incomingDoc.details.length; i++){ $(".listIncoming").html("<p class = 'list'>This is the: "+ incomingDoc.details[i].referenceNo + "</p>"); } A: DO NOT stringify. PARSE. Based on the object you returned.... $.ajax({ url: "viewDayDocuments", type: 'post', data: {currentDay: currentDay, currentMonth: currentMonth, currentYear: currentYear}, success: function(result){ $('.list').text(''); $('.list').remove(); incomingDoc = JSON.parse(result); incomingDoc.details[/*indexhere*/].referenceNo; //gives you a reference number. } }); I'll leave it up to you to loop through the indeces of incomingDoc.details.
{ "pile_set_name": "StackExchange" }
Q: Will Software RAID And iSCSI Work For A SAN I am looking for a SAN solution, but can't afford even entry level solutions. Basically, the SAN is for development and a proof of concept product. The performance doesn't have to be amazing, but needs to be functional. My buddy says we should just setup sotware RAID and software iSCSI in Linux. Essentially I have a spare server with dual Xeon processors, 4GB of memory, and (2) 500GB 7200RPM drives. It's a bit old but working. I am sure there is reason people don't do software RAID and iSCSI, but will performance be usable? Thinking of configuring the drives in RAID 0 (for performance). A: Try NexentaStor Community Edition. It's a canned NAS/SAN solution. You may need additional disks to hold the OS. Also check FreeNAS or Openfiler. These products are purpose-built for what you're looking to do and they work on a wide range of hardware.
{ "pile_set_name": "StackExchange" }
Q: Page Object Model: How much abstraction is necessary? So i've been working on a Page Object Model framework for a large web application for our current company. It's the first time i've made my own framework and implemented the page object model. Im using Ruby w/Capybara and Selenium-Webdriver for my language/driver of choice. Currently i've divided each page (or obvious "section of the site") into a class file. This class file has methods for just about everything (or an API of sorts). The problem i've ran into is that I am literally writing a method for every single thing....and i've came across 2 ways people seem to do this: Lets pretend for a section/page of the site is a widget creation form, the widget has a name/description and some sort of "type" dropdown. Also a save button to save the widget. Option A (Which is what i've done so far): Make a method for each element (the save button, called save_widget, all the different inputs, etc...) Option B: Have getter and setter methods for each element, then a larger method which uses these private getter and setter methods. With Option A my test scripts end up being longer, and honestly not much different than using selenium calls themselves. Option B would probably call one method (Such as create_widget which would pass in multiple items which that method would call all the smaller getter/setter methods). This would make the test script MUCH shorter and more abstracted. However the getter/setter methods would probably take more actual writing for the page objects themselves (but possibly easier to maintain). Is there a certain style that favors one over the other? The more I think about it the more Option B seems better...but I wonder if in this case abstraction is a good thing. A: Both of your options listed can work. Though, as you mentioned, option A is only slightly better than not using POM. Every time I do test automation, it's always been on teams that have no automation, so I'm always creating frameworks from scratch. In my experience, I favor option B that you have listed. This level of abstraction and encapsulation works best for long term maintenance. And, if there is more than 1 person writing tests, they only need to be concerned with what methods to use and not have to worry about how to use getter/setters. This also allows you to create overloaded methods, when needed, and use the same elements in your getter/setter. Option B allows for more customization and control. Test specs should be short and contain your data, your asserts, and any class/method calls to implement the test. While your POMs contain your elements and methods on how to use the elements. Edit: Note, not all languages support method overloads. An example of overloaded method looks like: public void login () {} public void login (username, password) {} Same name is used for both methods, the take different parameters, and may have different logic/steps to perform. In this case, maybe the first method is used to login as a guest, where the second supports login credentials. A: I might choose option A and do what is needed when it is needed without the extra abstraction. One additional option is also to move away from a strict page object model. My reason for doing this is maintainability. The issue I encounter is the knowledge needed (or gained) for the page breakdown. You'll often find components that are: Universal, e.g. a 'logout' button' Repeated on multiple pages, e.g. a attach document to multi-form submission Common to a certain workflow over different pages Updated via ajax Because of these issues I create Page Objects as: Global. For simple applications I've even just kept them all in that one category. Workflow. Some elements are repeated thru a workflow or multi-form submission Page. The more classic use for objects specific to that page and no other. In fact I often start with just global and wait until I start meetings conflicts / collisions before doing the mroe detailed breakouts. Depends on the situation.
{ "pile_set_name": "StackExchange" }
Q: How can I disable a silverfish spawner? So I just found a stronghold and located the End Portal. I tried lighting up the area to get rid of the silverfish that come from the spawner, but I found out trough the Minecraft Wiki that when there's a spawner they can spawn at any light level. Since I don't want to destroy the spawner, is there any way I can disable it? I know I can fill the room with blocks, but then access to the portal would get quite a bit complicated. A: They actually stop spawning at light level 12 or higher, so surrounding the area with glowstone or redstone lamps should work. Etho, a relatively famous YouTuber who specializes in exotic mob farms, has been working on a silverfish farm for a while: he went over how to disable a silverfish spawner using only light in episode 155 of Etho Plays Minecraft: He had the same scenario you have: he wanted to keep the portal accessible but disable the spawner. He goes into possible caveats and problems you might run into, but he was able to completely disable the spawner by adding redstone lamps across the top of the spawning area. A: If you want to deactivate a silverfish spawner, it is simplicity once you know it spawns in a 9x9x3 area and requires the light to be above 12. Remember that the portal blocks are modeled after glass and are transparent. This configuration requires 13 JackOLanterns, 3 torches, and some dirt. Also, it appears that the lava is positioned to where if it were completely released from its nicely contained reservoirs by removing the stairway and pool walls, it should almost light up the room sufficiently, at which point one may want a glass walkway above it. Happy Crafting
{ "pile_set_name": "StackExchange" }
Q: I can't link validation and form submission. Need help setting the variable (true or false) so that an empty form is not sent? const form = document.querySelector('.form__contact'); const name = document.querySelector('input[name=name]'); const email = document.querySelector('input[name=email]'); const btnSubmit = document.querySelector('.btn-submit') two-field validation function function checkInputs() { let nameValue = name.value.trim(); let emailValue = email.value.trim(); if (nameValue === '') { setErrorFor(name, 'Name cannot be blank'); } else if (!isName(emailValue)) { setErrorFor(name, 'Not a valid name'); } else { setSuccessFor(name); } if (emailValue === '') { setErrorFor(email, 'Email cannot be blank'); } else if (!isEmail(emailValue)) { setErrorFor(email, 'Not a valid email'); } else { setSuccessFor(email); } } function setErrorFor(input, message) { const inputBox = input.parentElement; const errorMessage = inputBox.querySelector('.errors'); inputBox.className = 'form__field error'; errorMessage.textContent = message; } function setSuccessFor(input) { const inputBox = input.parentElement; const errorMessage = inputBox.querySelector('.errors'); inputBox.className = 'form__field success'; errorMessage.textContent = ""; } field verification functions function isName(name) { let regExpName = /^[]{}?/; return regExpName.test(name); } function isEmail(email) { let regExpEmail = /[])?/; return regExpEmail.test(email); } serialize-this function generates a string to send to the server. The function is ready, large, so I didn't throw it all in the post function serialize(form) { if (!form || form.nodeName !== "FORM") { return false; } -- ---- - - - - - } and submit itself btnSubmit.addEventListener('click', event => { event.preventDefault(); Here, need "if else" or anything else for "const isValidate = false" checkInputs(); console.log(serialize(form)); }); A: "return false" if validation error, Try this: function checkInputs() { let nameValue = name.value.trim(); let emailValue = email.value.trim(); if (nameValue === "") { setErrorFor(name, "Name cannot be blank"); return false; // return false } else if (!isName(emailValue)) { setErrorFor(name, "Not a valid name"); return false; // return false } else { setSuccessFor(name); } if (emailValue === "") { setErrorFor(email, "Email cannot be blank"); return false; // return false } else if (!isEmail(emailValue)) { setErrorFor(email, "Not a valid email"); return false; // return false } else { setSuccessFor(email); } return true; // default true } const isValidate = checkInputs(); if (isValidate) { console.log(serialize(form)); }
{ "pile_set_name": "StackExchange" }
Q: How to compose and post a JSON object from jQuery to an MVC3 action method? I have the following JavaScript code that gets the Id property (Guid) from every user row in a Kendo UI grid. Now I am wondering how best to compose these Id's and the owner roleId into a JSON object that I can pass to an MVC3 action method. Versus my silly string concat. $("#command-add-selected").click(function () { var json = "roleId: '51FC554E-353C-4D55-BE52-1B4BF9D2F17F', users: ["; var avail = $("#availableUsersGrid").data().kendoGrid._data; for (var i = 0; i < avail.length; i++) { json += "{ Id: '" + avail[i].Id + "'},"; } json = json.slice(0, -1); json += "]"; alert(json); return false; }); The action method can be GET or POST and need not return any value (this is another puzzle here, no returned view). All it does is domain updates that are fetched by other ajax code subsequent to the above code. How can I pass the above type JSON to an action method essentially of void return type? EDIT: This question answered the minor part of my question nicely, with how to dynamically add items to an array with push. A: 1.first of all u dont need to create the full json ur self use JSON.Stringify() method to change the javascript object to JSON string. 2.after u have created the JSON string u can GET or POST it to any normal method in any MVC Controller of visibility public. even if the signature of the action method is like public ActionResult MehodName(string jsonString) u can always return null. 3. u can use built in JavaScriptSerializer class in System.Web.Script.Serialization namespace to deserialize the json string u recieve in the action to create an object with the same propertiese Edit:- make a javascript array names users then inside the for loop use .push() function of javascript to insert the objects like this var users = []; for(something) { var user = {"Id":"YOUR ID VALUE"}; users.push(user) } var objectToSerialize = {"roleId":"YOUR ROLE GUID","Users":users}; var jsonString = JSON.stringify(objectToSerialize); Edit 2:- so going by your previous comments u dont want that u need to deseralize the whole JSON object. going by your object architecture even if ur action method has a signature like this public ActionResult GetUsersByRole(Users users) { //some code } and Users class like this one class Users { public string RoleId{get; set;} public User[]{get; set;} } and User class like this class User { string Id{get; set;} } it would automatically bind property with your complex users object
{ "pile_set_name": "StackExchange" }
Q: Selenium Firefox webdriver won't load a blank page after changing Firefox preferences everyone. Main question: I am using the Python API for Selenium 2 and want to start a Firefox browser on a blank page (i.e. don't send any requests on browser startup). I created a FirefoxProfile object and changed 'browser.startup.page' to 0. The first time I create a webdriver using this profile it goes to mozilla.org but subsequent webdrivers start on a blank page like I intended. Why is this happening and how can I fix it? Second question: the code below works fine when I enter it line by line in the interpreter but crashes when I try to run it as a script. I get a WebDriverException: "Can't load the profile. Profile Dir: %s If you specified a log_file in the FirefoxBinary constructor, check it for details." I also get a pop up window that says "Your Firefox profile cannot be loaded. It may be missing or inaccessible.". How can I fix this so that it runs as a script? from selenium import webdriver profile = webdriver.FirefoxProfile() # Tell the browser to start on a blank page profile.set_preference('browser.startup.page', 0) # Start first session (doesn't work) driver1 = webdriver.Firefox(profile) driver1.close() # Start second session (this works) driver2 = webdriver.Firefox(profile) A: The setting "browser.startup.page" = 0 is the default for webdriver instances. The setting that works for me (old FF defect) profile.set_preference("browser.startup.homepage_override.mstone", "ignore") A one-liner workaround without using a profile is to just load the empty page after starting the Firefox instance: driver = webdriver.Firefox() driver.get("about:blank") Oh, I forgot the 2nd part: The error message when running your code in a script is because the old Firefox instance is still running when you start the new one with the same profile. It takes some time to close the old browser window. If you add a sleep of 5 seconds before the last line in your sample, it works from a script too. It was tricky to see why it worked without this on two of my machines. The reason: Iceweasel and the Firefox of Linux Mint do not show the update page. BTW: Nice finding, that starting the next Firefox instance will work.
{ "pile_set_name": "StackExchange" }
Q: The localization of an ideal is equal to the localization of the ring Suppose $m\subset R$ is a maximal ideal. Suppose $I\subset R$ is an ideal. I'm trying to understand these claims: If $m$ does not contain $I$, then $I_m=R_m$ as localizations of $R$-modules. If $m$ contains $I$, then $I_m\ne R_m$. First statement: the inclusion $I_m\subset R_m$ is obvious: if $r/s\in I_m$ ($r\in I, s\in R-m)$ them $r/s\in R_m$ because $I\subset R$ so $r\in I\subset R$. But I don't understand why $R_m\subset I_m$ holds. Consider $r/s\in R_m$; here $r\in R$. To show that $r/s\in I_m$, I need to prove that $r\in I$, right? I don't see how it follows from $I\not\subset m$ or from $I\cap (R-m)\ne \emptyset$. Second statement: here I guess I need to find $r/s\in R_m$ such that $r\not\in I$, knowing that $I\subset m$ (then it will follow that $r/s\not\in I_m$). Can I take any $r\not\in I$? But this doesn't use the assumption $I\subset m$... A: For notational convenience, let $S = R \setminus m$. (1) In the localization $R_m$, every element of $R$ that is not in $m$ becomes a unit. An ideal containing a unit is the whole ring. (2) For contradiction, suppose that $I_m = R_m$. Then $1 \in I_m$ so $1 = i/s$ for some $i \in I$ and $s \in S$. Then there exists a $t \in S$ such that $ts = ti \in I$. Can you derive a contradiction from here? Hint: $st \in S$ so $st \notin m$.
{ "pile_set_name": "StackExchange" }
Q: Following up over where I didn't connect with the person well I had a phone interview where I didn’t connect well with the person. There were a few misunderstandings. Is there anything I can now do? Here is one example. We role played where she called me and needed tech support. She had stressed the fact that there were no trick questions and if I didn’t know a technology we could do a different example. I isolated the problem to being the router. I asked which lights were on and she said there were no lights; I took this to mean there physically were no lights but she meant they were all off. I also told her to make sure it had power and to check the cables were secure. She said there was a white cable connected to the wall but after we finished she said that was just the Ethernet cable and the power cable came unplugged. In such situations should I argue my point or explain why I got confused? I know in support related roles the customer can be very unknowledgeable but it’s unlikely they would say the device is plugged in when it’s not, especially when she said it’s not a trick question. I’m thinking of sending an email along the lines of “thanks for taking the time to interview me today. Sorry I misunderstood the status of the router, I think I know a lot more about routers than I made clear in the interview today”. The interviewer suddenly stopped the "role playing" and asked why I didn't follow up with the no lights. I explained when she said it had no lights, I thought it meant there physically were none, not that they were off. Also I did say to check all cables, and to say "one is connected to the wall" does not necessarily imply it was not getting power. Now, if I had some basic training in new that all of this companies routers had lights, this would have been easy. She also got me to talk about a time when I went above and beyond in providing service. I told her about a time where someone had a problem that kept coming back where a printer got disconnected and I stayed late to find the root cause of the problem and fix it so it wouldn’t come back.* She said the person must have been upset with me that the problem kept coming back. I said she wasn’t but offered to talk about a time I had to deal with an angry person. I gave the example of when I worked as a telemarketer and people got mad that I was calling them to try to get their money. She said “why did they get mad when you called them?” … how could a person not understand why it would be annoying for a telemarketer to call them? This is what I mean by not connecting well. Is there anything I can do at this point? *the user was trying to print from a guest operating system in VMware and things were funky with the USB pass through with the host OS. Basically VMware reset the USB pass through settings each time the host was rebooted so I wrote a script to fix this. A: Is there anything I can now do? No, you shouldn't contact her, just hope for the best. You made a kindergarten mistake, so I wouldn't hope too much though. A large part of simple support is making sure you understand what is going on. You never bank on a consumer knowing anything. A: Is there anything you can do? No, there isn't. I hire for support roles and in interviews often roleplay customers in troubleshooting scenarios. If you ask me clarifying questions, I will answer exactly what was asked, and that often means withholding critical information because the customer doesn't know it's critical and it's your job to figure it out regardless. It's OK (not great, but OK) to misunderstand something and go down a rabbit hole for a while. But if you can't figure out your own mistake and get back on track during the interview, sorry, you blew that question -- and in real life too, if you're debugging a customer's production issue today, it's not going to help much if tomorrow you realize you went down the wrong track.
{ "pile_set_name": "StackExchange" }
Q: "function is not defined" after document.write called in setTimeout? Here is the code: function getTime(j){ var stopClock= new Date(); delta[parseInt(j)]=stopClock.getMilliseconds()-start.getMilliseconds(); } //REST OF THE CODE!! function func(){ { for (var i = 0; i < 6; i++){ start = new Date(); document.write('<img src="'+URL[i]+'" width="1" height="1" alt="" onload="getTime('+i+');"/>'); } } //SOME CODE setTimeout(function() { func(); },100); However I got this error: getTime is not defined if I declare getTime like this: document.getTime= function (j) There is no error but it never execute that function. If I remover the setTimeout, it will work with no problem. Any thoughts? Thanks, A: You're destroying the DOM with your document.write call. In some browsers, this also destroys global variables. Instead of document.write, try... for (var i = 0; i < 6; i++){ var img = document.body.appendChild(document.createElement('img')); img.src = URL[i]; img.width = 1; img.height = 1; img.onload = makeHandler(i); } function makeHandler(i) { return function() { getTime(i); }; } Here's a simple demonstration of the globals being cleared... In Firefox, the second alert will be undefined. In Chrome, the global is retained. http://jsfiddle.net/Z9NbR/ window.foo = 'bar'; alert(window.foo); // now we have it setTimeout(function() { document.write('new content'); alert(window.foo); // now we don't }, 100);
{ "pile_set_name": "StackExchange" }
Q: Any way to block/remove keyboard hook in uncontrolled window's Menubar? I'm sending keystrokes to an inactive Adobe Flash Projector window with PostMessage, that part works perfectly. I leave it running in the background and it interferes very little with my normal computer usage, which is the intent. The problem comes when I programmatically send the W (or less frequently Q) key while I happen to be holding Ctrl intended for a different windows shortcut. This triggers Ctrl-Q or Ctrl-W, both of which immediately close the Adobe Flash Projector. Ctrl-F and Ctrl-O have some undesirable effects as well. EDIT: I'm not interested in solutions that briefly release the Ctrl key. Is there anyway I can unhook shortcut keys from a third party window? It uses a standard OS menubar across the top of the window which is where the shortcuts are listed, so surely there's a way to reassign, unassign, or block it, right? In the past I tried using these dlls to break the menu. It made it disappear but didn't break the shortcuts. DllCall("SetMenu", uint, this.id, uint, 0) hMenu := DllCall("GetSystemMenu", "UInt",this.id, "UInt",1) DllCall("DestroyMenu", "Uint",hMenu) Sorry for the strange syntax, this is from an early version of my program written in autohotkey. The language I'm using now is C#, but I assume the solution uses a .dll, so that's not as important. Feel free to suggest or change my tags. A: Using the program Resource Tuner's free trial, I opened up flashplayer_28_sa.exe, went to Accelerator Table (Apparently accelerator means shortcut in the context of Menus), and deleted the offending shortcuts. Then I saved it, and it failed to save, and I saved it again, and again, and again, and then it worked, although I did nothing differently that time. I think it would work with other shortcuts for programs with standard windows menus.
{ "pile_set_name": "StackExchange" }
Q: Як правильно перекласти areal coordinates? Перекладаю сайт комп'ютерної графіки. В просторах Інтернету знаходив варіант - ареальні координати, російською мовою. Чи може бути якийсь інший варіант більш зрозуміліший при вживанні? Додаю рисунок і опис до нього. Рисунок 1: барицентричні координати можна розглядати як області суб-трикутників CAP (для u), ABP (для v) і BCP (для w) в межах площі трикутника АВС, через що їх також називають areal coordinates. A: Переклад areal на e2u areal 1. ареа́льний 2. пло́щевий, пов’я́заний з пло́щею 3. (про похідну) поверхневий підказує такий варіант: Пло́щеві координати також можна ареальні, науковіше звучить. A: Я би не надавав перекладу цього словосполучення великого значення. Як я розумію, основне поняття, якому присвячено матеріал — це барицентричні координати. А «areal coordinates» згадуються лише як алтернативна назва чи то назва для часткового випадку, чи не так? Тобто фразу «через що їх також називають …» можна або взагалі опустити, або залишити англійське «areal coordinates», можливо, надавши в дужках приблизний український переклад (а не шукати точний український відповідник терміну «areal coordinates»). В ролі кандидатів на український переклад я розглядаю «площеві координати» (per Yola) і «площинні координати» («площинний» є в СУМ-11; щоправда, словосполучення «площинні координати» на практиці використовують для позначення звичайних декартових координат, але якщо згадувати їх в тексті лише один раз, як приблизний переклад в дужках для «areal coordinates», то це несуттєво). P.S.: «Площеві координати» Google не знає, а «ареальні координати» згадує один раз — і теж (як і «площинні координати) не в тому значенні.
{ "pile_set_name": "StackExchange" }
Q: What is the different between this 2 statement i am new to APEX and wondering what is the different between the 2 statements below and which should be the best practice? 1) List<Contact> c1 = [select id, firstname from Contact]; for(Contact c2: c1){ c2.firstname = 'Test'; } update c1; 2) List<Contact> c1 = [select id, firstname from Contact]; List<Contact> c3 = new List<Contact>(); for(Contact c2: c1){ c2.firstname = 'Test'; c3.add(c2); } update c3; both update the contact name to 'Test'. i just confuse why the first one works as i'm assigning new value (Test) into c2 but not c1? I though c1 would still have the old value? what would be use case for it? Thanks. A: In the end, both of your approaches are functionally identical. Explaining why this is the case requires some background information... The background (how are variables passed?) The key concept here is distinguishing pass-by-value and pass-by-reference. In a nutshell, when you have something that is passed by-value, you're given an independent copy. We get an entire copy of the variable at a new location in memory. Integer myInt = 1; public class MyClass{ public void changeVariable(Integer input){ System.debug('input before modification: ' + input); input += 1; System.debug('input after modification: ' + input); } } System.debug('myInt before: ' + myInt); MyClass myInstance = new MyClass(); myInstance.changeVariable(myInt); System.debug('myInt after: ' + myInt); // running this code as anoymous apex will produce the following output in your log // myInt before: 1 // input before modification: 1 // input after modification: 2 // myInt after: 1 The Integer is passed by-value, so copies that we make are independent. When we change the value of the integer in the changeVariable() method, we only changed the copy of the integer local to the changeVariable() method's scope. In contrast, when something is passed by-reference, we don't get an independent copy. Instead we are (effectively) given a reference to the memory location of the original copy. Let's modify the previous example a bit... Account myAccount = new Account(Name = 'myAccount'); public class MyClass{ public void changeVariable(Account input){ System.debug('input before modification: ' + input); input.Name += ' modified!'; System.debug('input after modification: ' + input); } } System.debug('myAccount.Name before: ' + myAccount.Name); MyClass myInstance = new MyClass(); myInstance.changeVariable(myAccount); System.debug('myAccount.Name after: ' + myAccount.Name); // running this code as anoymous apex will produce the following output in your log // myAccount.Name before: myAccount // input before modification: myAccount // input after modification: myAccount modified! // myAccount.Name after: myAccount modified! Because we aren't working with an independent copy in this situation, any change to the "reference" copy also changes the original. In Apex, we can't control whether something is passed by-value or passed by-reference. The rule of thumb is: Primitive types (Integer, String, Boolean, etc...) and collections (list, set, map) of primitive types are passed by-value Other types (SObjects like Account or Opportunity, Apex classes that you create) and collections thereof are passed by-reference Why your first code example works (changes the name of the Contact) Lists of SObjects store references. When you use a for loop to iterate over a list of SObjects, the loop variable (c2 in your first example) is populated with a reference to the memory location that actually contains your Contact data. Making a change to the reference changes the original as well. Why your two code examples are (effectively) the same In your second example, the loop variable c2 is still a reference to a Contact record in some memory location. When you store c2 in your other list, c3, you are just creating another reference (so you have 1 original copy and 2 references, c2 and another reference stored in c3). The "original" copy of the Contact (stored in c1) is still modified in your second example. Best practice: Your first example is best practice in this case. It's about as short as can be, doesn't spend time creating things that ultimately don't serve any purpose, and doesn't clutter the namespace. There could be an argument for using a "SOQL for-loop" (i.e. for(Contact c :[<your contact query here>]){). That said, I don't think most people are ever going to encounter a situation where the decision between a SOQL for-loop and directly storing the query results in a collection is going to make any appreciable difference. Just to be clear, there is a difference between those two strategies. It's just not going to be a meaningful difference in most situations. Bonus: How to make an independent copy of an SObject If you use the clone() method on an SObject, or the deepClone() method on a collection of SObjects, then you do get a completely separate, independent copy. This is only true of SObjects (as far as I know). If you clone() an instance of an Apex class, you still get a reference. The deepClone() collection method only works on collections of SObjects, and the regular clone() method does not make an independent copy.
{ "pile_set_name": "StackExchange" }
Q: The wikipedia proof of Bolzano Weierstrass theorem I was going through the proof that has been written for Bolzano-Weierstrass theorem in the respective Wikipedia page. http://en.wikipedia.org/wiki/Bolzano%E2%80%93Weierstrass_theorem I could understand the first part where it assumed the existence of infinite no. of so called peaks but in the part where the finiteness of the peak is assumed I could not understand the logic used after N=n+1. How has it been proven that finite no.of peaks cannot exist or that a convergent sub sequence exists? Waiting for insightful comments. A: This is a pretty cool proof. In the first part, which you understand, we state that any sequence with infinitely many peaks has a monotonically decreasing subsequence. In the next part, we show that if there are only finitely many peaks, there has to be a monotonically increasing subsequence. The key to this next proof is that if a number is not a peak, then there's some greater entry further along in the sequence. Remember: a member $x_n$ of a sequence is a peak if and only if all of the entries coming afterwards are strictly less than $x_n$. So, assuming you only have finitely many peaks: We start with whatever entry comes after the final peak and call this entry $x_{n_1}$. We know that $x_{n_1}$ is not a peak, since we already hit the last peak. Because of this, there is some $x_{n_2}$ that is greater than $x_{n_1}$. $x_{n_2}$ is not a peak, so rinse and repeat and then we have $x_{n_3}$. We can repeat this process since there are no more peaks to produce an infinite subsequence $\{x_{n_j}\}$ that is monotonically increasing. I hope that clears things up.
{ "pile_set_name": "StackExchange" }
Q: CUPS test page successfully print out result in Blank page I have setup successfully with Epson linux driver. When I try to print test page, it is resulting in a blank page with successful print status. The printer is working properly with Google cloud print. Already try to change to multiple protocols (IPP, LPD, HTTPS) Already try with local file PPD in /opt/epson-inkjet-printer-escpr2/ppds/ Already try with some generic printer drivers Are there any way to debug and get a printer work? Ubuntu 16.04, Epson L4160 Ubuntu Package installed printer-driver-escpr, lsb, epson-inkjet-printer-escpr2_1.0.9-1lsb3.2_amd64.deb A: Printer become function properly when do gunzip and manual change driver file to use directly from the ppd file. Step Backup ppd file. Unzip ppd.gz file from epson deb package from download site sudo gunzip /opt/epson-inkjet-printer-escpr2/ppds/Epson/Epson-L4160_Series-epson-inkjet-printer-escpr2.ppd.gz Open Printer Properties Make and Model > Change... Provide PPD file Select a file from /opt/epson-inkjet-printer-escpr2/ppds/Epson/Epson-L4160_Series-epson-inkjet-printer-escpr2.ppd
{ "pile_set_name": "StackExchange" }
Q: Automapper preconditition, if src value is 0 then map null Hi I have a quick question I have a mapper config created that looks like: CreateMap<ModifySystem, Entities.System>() .ForMember(dest => dest.IpAddress, opt => opt.MapFrom(src => IPAddress.Parse(src.IpAddress))) .ForMember(dest => dest.ApplicationId, opt => { opt.PreCondition(src => src.ApplicationId > 0 || src.ApplicationId == null); opt.MapFrom(src => src.ApplicationId); }) .ForMember(dest => dest.Id, opts => opts.Ignore()); Well it works when I get value bigger then 0 or null (ApplicationId is nullable), but I want something that if source value will be 0 then set value as null. Tried opt.MapFrom(src => null); but it does not work as it should. How to solve this problem in autommaper. A: Like you have .ForMember(dest => dest.IpAddress, opt => opt.MapFrom(src => IPAddress.Parse(src.IpAddress))) You could do something like the following: .ForMember(dest => dest.ApplicationId, opt => opt.MapFrom(src => src.ApplicationId == null || src.ApplicationId == 0 ? null : src.ApplicationId ))
{ "pile_set_name": "StackExchange" }
Q: What is the combinatorial proof for the formula of $S(n,k)$ - Stirling numbers of the second kind? What is the combinatorial proof for the formula of Stirling numbers of the second kind ? $${n\brace k}=\frac1{k!}\sum_{j=0}^k(-1)^{k-j}\binom{k}jj^n$$ where ${n\brace k} = S\left(n,k\right)$ is the number of set partitions of a fixed $n$-element set into $k$ parts. A: Count non-surjective functions $[n]\to [k]$. Use inclusion-exclusion by counting functions $A_i$ that miss one particular element $i\in [k]$ and then consider $A_1\cup A_2 \cup \dots \cup A_k$.
{ "pile_set_name": "StackExchange" }
Q: Android Studio missing drawable Folder I've been trying to import an icon into drawable folder, then I found that drawable folders are missing any ideas? A: Android Studio is automatically creating projects with mipmap folder and putting the icons on it. So you simply have to create the drawable folder into res.
{ "pile_set_name": "StackExchange" }
Q: Regex.Replace is stripping out pipe character I have this function which is supposed to swap every spacial char like á, ä, etc for a normal one like a: Private Function QuitaTildes(ByVal texto As String) As String Dim replace_a As Regex, replace_e As Regex, replace_i As Regex, replace_o As Regex, replace_u As Regex replace_a = New Regex("[á|à|ä|â]", RegexOptions.Compiled) replace_e = New Regex("[é|è|ë|ê]", RegexOptions.Compiled) replace_i = New Regex("[í|ì|ï|î]", RegexOptions.Compiled) replace_o = New Regex("[ó|ò|ö|ô]", RegexOptions.Compiled) replace_u = New Regex("[ú|ù|ü|û]", RegexOptions.Compiled) texto = replace_a.Replace(texto, "a") texto = replace_e.Replace(texto, "e") texto = replace_i.Replace(texto, "i") texto = replace_o.Replace(texto, "o") texto = replace_u.Replace(texto, "u") Return texto End Function The problem is, when texto is a regular expression pattern itself like "one|twó|threé" it's returning "onetwothree", this is, it took out every | char, why? this text is in the replace string, not in the pattern so I shouldn't need to escape it. Is there an option for regex to tell it to stop doing that? (this function is done to save some pressor time so if I need to escape | char I won't save that much) Thank you A: You don't need | symbol. replace_a = New Regex("[áàäâ]", RegexOptions.Compiled) replace_e = New Regex("[éèëê]", RegexOptions.Compiled) replace_i = New Regex("[íìïî]", RegexOptions.Compiled) replace_o = New Regex("[óòöô]", RegexOptions.Compiled) replace_u = New Regex("[úùüû]", RegexOptions.Compiled)
{ "pile_set_name": "StackExchange" }
Q: Google Appengine: Java or Python Possible Duplicate: Choosing Java vs Python on Google App Engine We are going to use Google Appengine platform for our next big web project.But we are not sure which flavour to use: Java or Python. Could you please, advise on cons and pros of each approach? Which is the best way in order to build more scalable and efficient solution quicker. Thanks in advance A: I gave the accepted answer to the question a comment claims is "very similar" -- but that was nearly a year ago. I'm still biased the same way (still expert on Python, rusty in Java), but in the intervening year I would say the Java runtime has just about caught up to the Python one -- or, if not quite that yet, it has made serious strides (as have both runtimes "in parallel", of course;-). Most of my general considerations in that answer remain roughly valid. So the main consideration today is, I think, how familiar is the team with Python, and how familiar with Java -- if very familiar with one and not at all with the other, go with what you already know, as the time needed to "catch up" on the other is a cost that's probably larger than the advantages you could get one way or another (to a hobbyist wanting a "mind expanding" experience I'd recommend the reverse: take the opportunity to learn what you don't yet know -- but in terms of immediate productivity, staying with what you know increases it;-). If there's some "killer library" that you've ascertained runs well with one of the runtimes and that you're really keen to use in your apps, that could be the decisive factor, if differences of familiarity with the two languages are not decisive in your case. A: It would be helpful to know what type of things this project needs to do, do you need to integrate with lots of other libraries, applications, etc? This is just one anecdote, but I've recently tried out GAE on both platforms, and found the Python option way easier to get working than using Java with JDO. A part of this had to do with also tackling JDO at the same time, but I found I was able to implement the same exact functionality in Python in just a few days as I was in weeks on the Java side. As someone relatively new to Python still, there are a lot of things I still need to tackle to feel more comfortable in it, such as: the best way to unit test my controllers and model classes best way to structure my controllers determine if Django templates are satisfactory or if I should attempt to use a different template system When I attempted the best way to write Java unit tests for my GAE classes I bounced between a half-dozen different blog articles and suggestions on how to best mock out the App Engine services. Some seemed to work, some seemed like hacks, but the lack of a good and supported solution left me feeling uncomfortable. All things being equal, I would recommend the Python flavor for a greenfield project. Easier to get started, less moving pieces, no nasty JVM startup times in the production environment, no post-compile bytecode enhancement necessary, etc.
{ "pile_set_name": "StackExchange" }
Q: Connection String in Azure while using Spring Boot I can see that we can define a secure connection string form portal, and than can access those variables in our application.I found many examples to do it in ASP.NET, like defining the keys in web.config. But i can not find any example focusing on accessing these connection strings defined via portal from Spring Boot app. Any help in that direction would be useful A: If Azure exposes these secure strings as environment variables, you can name them to override application properties using the following format: Property name my.secret.password can be overriden with environment variable MY_SECRET_PASSWORD. You can also use them directly in your application.properties my.secret.password=${SUPER_SECRET_ENV_VARIABLE}
{ "pile_set_name": "StackExchange" }
Q: CodeIgniter Pagination wrong generate next link I'm Quit New and trying to Make Pagination Inside Codeigniter... I'm to create pagination with one extra argument.. link first argument is for getting ID for database search.. and than create pagination... I've done so far but the next page link is not correct as it should be. please check my code and let me know what's wrong i am doing. this is model code.. my modelclass name is movie public function get_movies_by_actor($actor_id,$num=10,$start=0) { $this->db->select(" f.film_id, f.language_id, a.actor_id, f.title, f.description, l.name AS language, c.name AS category, concat(a.first_name, ' ', a.last_name ) AS actor_name ",FALSE); $this->db->from('actor AS a'); $this->db->join('film_actor AS fa', 'fa.actor_id=a.actor_id'); $this->db->join('film AS f', 'f.film_id=fa.film_id', 'left'); $this->db->join('language AS l', 'l.language_id=f.language_id', 'left'); $this->db->join('film_category AS fc', 'f.film_id=fc.film_id', 'left'); $this->db->join('category AS c', 'c.category_id=fc.category_id', 'left'); $this->db->where('a.actor_id', $actor_id); $this->db->order_by('f.film_id','desc')->limit($start,$num); $query = $this->db->get(); return $query->result(); } this and controller code. my controller class name is movies public function actor_movie($actor_id,$start=0) { $data['movies']=$this->movie->get_movies_by_actor($actor_id,$start,10); $this->load->library('pagination'); $config['base_url'] = base_url().'index.php/movies/actor_movie/'.$actor_id.'/'; $config['total_rows'] = $this->movie->get_total_movies(); $config['per_page'] = 10; $config['display_pages'] = FALSE; $config['first_link'] = FALSE; $config['last_link'] = FALSE; $config['next_tag_open'] = '<li class="next">'; $config['next_link'] = 'Older Post &rarr;'; $config['next_tag_close'] = '</li>'; $config['prev_tag_open'] = '<li class="prev">'; $config['prev_link'] = '&lt Newer Post'; $config['prev_tag_close'] = '</li>'; $this->pagination->initialize($config); $data['pagination_links'] = $this->pagination->create_links(); $data['title'] = '$this->pagination->create_links()'; $this->load->view('header'); $this->load->view('actor_movies',$data); $this->load->view('footer'); } A: just you need to add uri_segment in pagination $config array in Controller Function... $config['uri_segment'] = 4;
{ "pile_set_name": "StackExchange" }
Q: How do I make an element the height of the browser window? I've written code to make a section's height (#home) match the window height, but it's bugging out. Here's what I use: // Make Home section height of window function fitHomeToScreen() { var windowHeight = $(window).innerHeight(); $("#home").css("height", windowHeight); alert(windowHeight); } $(window).load(fitHomeToScreen); $(window).resize(fitHomeToScreen); Every time I refresh the browser (no matter what size I drag the browser to), windowHeight stays the same. Then, if I resize the browser window a bit, the windowHeight doubles. Every time. Forever. Like so: 902px [drag browser a few pixels wider] 1804px [drag browser a few pixels wider] 3608 ... etc. ... Here's all my code: HTML <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic|Montserrat:700|Merriweather:400italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> </head> <body> <section id="main-menu"> <a href="#home" class="logo"></a> <nav> <ul> <li><a href="#whatwedo">What we do</a></li> <li><a href="#howitworks">How it works</a></li> <li><a href="#team">Team</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav> </section> <section id="home"> <div class="content"> <div class="headline">Headline.</div> <div class="explanation">Blah blah blah.</div> </div> </section> <section id="whatwedo"> <h2>What we do</h2> <div class="explanation">Some stuff</div> </section> <section id="howitworks"> <h2>Lorem ipsum</h2> <div class="explanation">Some stuff</div> </section> <section id="team"> <h2>Lorem ipsum</h2> <ul class="team"> <li class="modal-trigger" data-modal="name"> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> </li> <li class="modal-trigger" data-modal="name"> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> </li> <li class="modal-trigger" data-modal="name"> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> </li> <li class="modal-trigger" data-modal="name"> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> </li> <li class="modal-trigger" data-modal="name"> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> </li> <li class="modal-trigger" data-modal="name"> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> </li> <li class="modal-trigger" data-modal="name"> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> </li> </ul> <!-- Team member modals --> <div class="modal team-member name"> <img class="x" src="images/x.svg" alt="Close" /> <img src="images/name.jpg" alt="Firstname Lastname" /> <div class="name">Firstname Lastname</div> <div class="title">Title</div> <p>Some stuff</p> </div> </section> <section id="contact"> <h2>Lorem ipsum</h2> <p>Lorem ipsum dolor sit amet</p> <a class="button" href="mailto:[email protected]">Email us</a> </section> <footer> <div class="info"> <div>Address</div> <div>Phone number</div> <div>[email protected]</div> </div> <div class="legal">Lorem ipsum</div> </footer> <div class="modal-backdrop"></div> <script type="text/javascript"> // ------ Make modal work $(".modal-trigger").click(function() { var modalName = $(this).attr( "data-modal" ); var modal = ".modal." + modalName; // Center modal var modalHeight = $(modal).outerHeight(); var modalWidth = $(modal).outerWidth(); $(modal).css({ "margin-top" : (modalHeight/2)*-1, "margin-left" : (modalWidth/2)*-1, }); $(modal).fadeIn(); $(".modal-backdrop").fadeIn(); function collapseModal() { $(modal).fadeOut(); $(".modal-backdrop").fadeOut(); } $(".modal-backdrop").click(collapseModal); $(".x").click(collapseModal); }); // ------ When an anchor link is clicked, smoothly scroll there, and remove the URL hash $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 600); return false; } } }); }); // ------ Make Home section at least height of window function fitHomeToScreen() { var windowHeight = $(window).innerHeight(); $("#home").css("height", windowHeight); alert(windowHeight); } $(window).load(fitHomeToScreen); $(window).resize(fitHomeToScreen); // ------ Vertically center Home section content function centerHomeContent() { var homeContentHeight = $("#home .content").outerHeight(); var homeContentWidth = $("#home .content").outerWidth(); $("#home .content").css({ "margin-top" : (homeContentHeight/2)*-1, "margin-left" : (homeContentWidth/2)*-1, }); } $(window).load(centerHomeContent); $(window).resize(centerHomeContent); </script> </body> </html> CSS /** * Eric Meyer's Reset CSS v2.0 (http://meyerweb.com/eric/tools/css/reset/) * http://cssreset.com */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } /* End CSS reset */ /* Basic styles */ body { font-family: Lato; font-weight: 300; font-size: 18px; color: #222; text-align: center; } a { text-decoration: none; } h2 { font-size: 60px; } p { line-height: 160%; font-size: 20px; } .explanation { font-size: 28px; line-height: 160%; } /* Modal */ .modal { display: none; position: fixed; top: 50%; left: 50%; width: 80%; height: 80%; background-color: #fff; z-index: 99999; } .modal-backdrop { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,.8); } .modal .x { width: 20px; height: 20px; } /* Section - Main menu */ #main-menu { position: fixed; top: 0; left: 0; width: 100%; height: 60px; background: red; z-index: 9999; padding: 0 30px; box-sizing: border-box; text-align: left; } #main-menu a { color: #fff; } #main-menu .logo { display: inline-block; width: 336px; height: 40px; background-image: url("../images/logo.png"); background-repeat: no-repeat; margin-top: 10px; } #main-menu nav { float: right; } #main-menu nav ul li { display: inline-block; margin: 0 0 0 30px; } #main-menu nav ul li a { letter-spacing: .05em; font-size: 16px; display: table-cell; vertical-align: middle; height: 60px; -webkit-transition: ease-in-out .15s; -moz-transition: ease-in-out .15s; -o-transition: ease-in-out .15s; transition: ease-in-out .15s; } #main-menu nav ul li a:hover { box-shadow: inset 0 -4px 0 0 white; } /* Section - Hero */ #home { display: block; position: relative; width: 100%; background: black; color: white; } #home .content { width: 80%; position: absolute; top: 50%; left: 50%; } #home .headline { font-size: 60px; margin-bottom: 30px; } A: I played around with it a little more and found that it works best without using jQuery (for finding the window height without it adding to become a ridiculous number). Change $(window).innerHeight() to window.innerHeight and it will work like you want it too.
{ "pile_set_name": "StackExchange" }
Q: Unable to use the tableview cell.accessoryView for Click event Hi for this great community. I just need to implement a simple delete functionality in tableView. I know that this can be implemented using swipe delete (table view delegate). But the client needs something like this: I have done this design using cell.accessoryView = trash_icon;. Now the requirement is, when I tap the tableView cell. It must show the details of the vehicle. If I tap the bin/trash icon it must delete that row. I have successfully done the navigation to vehicle Details using cellForRowAtIndexPath for the Cells. But stuck at implementing the delete option. The problem is whenever I tap the trash icon, it goes to vehicle details page. I have looked upon the followings link1 ,link2 ,link3 and more but I'm not able to get the idea for implementing this. Also I tried the accessoryButtonTappedForRowWithIndexPath by specifying the cell as cell.accessoryType = UITableViewCellAccessoryCheckmark, cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton It works but the problem is I'm not able to change the default image of the accessoryType. Please guide me and thanks for reading this patiently! EDIT: What I have tried upto now is: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // cell.backgroundColor = UIColorFromRGB(0x717579); cell.backgroundColor = [UIColor clearColor]; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.backgroundView.backgroundColor = [UIColor clearColor]; cell.textLabel.backgroundColor = [UIColor clearColor]; cell.textLabel.font = [UIFont fontWithName:NSLocalizedString(@"font_name",nil) size:13]; cell.textLabel.textAlignment = NSTextAlignmentLeft; cell.textLabel.textColor = [UIColor whiteColor]; UIImageView *trash_icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_vehicle_delete.png"]]; if(indexPath.section != [vehicleDetails count]) { //cell.accessoryView = trash_icon; --> If I keep this only Image appears but the action doesn't gets triggered } else { cell.accessoryType = UITableViewCellStyleDefault } if(indexPath.section == [vehicleDetails count]) { addnewLabel.font = [UIFont fontWithName:NSLocalizedString(@"font_name",nil) size:13]; addnewLabel.backgroundColor = [UIColor clearColor]; addnewLabel.textColor = [UIColor whiteColor]; addnewLabel.text = NSLocalizedString(@"vehicle_new",nil); [cell addSubview:addnewLabel]; cell.textLabel.text = @""; UIImageView *background = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"input-plus.png"]]autorelease]; background.frame = CGRectMake(0, 0, 300, 35); if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) background.frame = CGRectMake(10, 0, 300, 35); cell.backgroundView = [[[UIView alloc]initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 300, 35)]autorelease]; [cell.backgroundView addSubview:background]; }else { cell.textLabel.text =[NSString stringWithFormat:@"Vehicle #%li: %@",indexPath.section+1,[[vehicleDetails objectAtIndex:indexPath.section] valueForKey:@"make"]]; UIImageView *background = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"text field 2x.png"]]autorelease]; background.frame = CGRectMake(0, 0, 300, 35); if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) background.frame = CGRectMake(10, 0, 300, 35); cell.backgroundView = [[[UIView alloc]initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 300, 35)]autorelease]; [cell.backgroundView addSubview:background]; } return cell; } The above method successfully calls the - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath;{ //here I do the delete stuff But the output looks like: A: So, Finally I got the solution by adding the custom button to the accessory view and added the selector for that, there by handling the delete functionality - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... ... if(indexPath.section != [vehicleDetails count]) { //Adding the custom button to the accessory view UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(275, 140, 30, 30); [button setImage: trash_icon.image forState:UIControlStateNormal]; //Adding the selector for the Button [button addTarget:self action:@selector(vehicleDeleteHandler:) forControlEvents:UIControlEventTouchUpInside]; button.tag = indexPath.section; cell.accessoryView = button; } ... ... } //Defining the selector function for the button. -(void)vehicleDeleteHandler: (id)sender { // if([sender tag] == 0) { NSLog(@"%ld",(long)[sender tag]); //Delete Functionality ... ... }
{ "pile_set_name": "StackExchange" }
Q: How to filter and search in the Nagios XI web interface? Having been given (erroronious?) instructions on how to look at Nagios XI I was wondering the following: If under Service Status Summary I click the number under Critical, I get a filter which states that it is only displaying critical errors, and at the top a message is displayed which reads Filters: Service=Critical. This would indicate that only services on hosts that have critical errors are displayed in the resulting query. However, next I am to use the search box to search for services with a particular string in them...this invalidates the filtering after clicking search Filters: Service=Critical no longer appears and the list needs to be sorted so that criticals appear at the top. Is there a way in the web interface to both search for services of a certain string and apply a filter simultaniously? A: I believe I've figured it out....oddly changing the query string arguments submitted to it seems to allow for what I am requesting but there doesn't appear to be a way to do this using the user interface. Login to nagios... Click the Service Status Summary number under Critical Click the Hamburger button In the menu that appears click Popout (it's got an icon with a little arrow) This will in turn open a new window in which you can see the query arguments submitted from that frame. Within the query string for the window note the value of the servicestatustypes argument, it should be 16 if you are looking for critical service errors. Run a search from the search box. When the results come back up, you will have lost the Filters: Service=Critical (and this is the problem that I had) Append an & to the end of the query string and add servicestatustypes=16 and press enter. Now you will have it both filtered by Status Critical and whatever your search was.
{ "pile_set_name": "StackExchange" }
Q: can I use same functions with the different type of argument inputs If I have a MATLAB lab file contains function foo function [test] = foo(a,b); test = a+b If I want to modified that function foo also receive the addition data c in my input in the same MATLAB file function [test] = foo(a,b,c); test = a+b+c; Can I do this? (I try the similar but when I try to use it said that I have to many argument.) A: The varargin approach is suitable here, although I would do it slightly differently (see below). However, you can simply test for the existence of the third argument with exist (or via nargin, but that is less direct and error prone). exist function test = foo(a,b,c) if exist('c','var'), % nargin>2 test = a + b + c; else test = a + b; end As in the code comment, a test on nargin is also possible, but the exist call is far less ambiguous and will not need a change if the argument list is modified (e.g. order). varargin Note that varargin does not need to be the only argument in the function declaration: function test = foo(a,b,varargin) if nargin>2, % numel(varargin)>0 test = a + b + varargin{1}; else test = a + b; end Also, say you want to have any number of extra inputs (e.g. foo(a,b,c,d,...)), you can do to tricks with the varargin cell array. For instance, you can do [varargin{:}] to horizontally concatenate the elements in to an a new array. For vertical concatenation, you can do vertcat(varargin{:}). I'm assuming the a+b+c example was just an example, so I won't show this in practice, but you can use these arrays any way you like.
{ "pile_set_name": "StackExchange" }
Q: GCC illegal instruction When I compile this code: #include <random> #include <iostream> int main(int argc, char** argv) { std::random_device dev; std::mt19937 mt(dev()); std::cout << mt() << std::endl; return 0; } And then try to run the resulting executable with gdb I get this error: Program received signal SIGILL, Illegal instruction. std::(anonymous namespace)::__x86_rdrand () at /build/gcc/src/gcc/libstdc++-v3/src/c++11/random.cc:69 69 /build/gcc/src/gcc/libstdc++-v3/src/c++11/random.cc: No such file or directory. I use arch linux with a Intel Core 2 Duo CPU T8100. How do I fix this? A: The error message is "Illegal instruction", and the only hint you get is __x86_rdrand(). Googling rdrand leads to the RDRAND instruction, which appears to have been added for Ivy Bridge Processors, which your Core 2 Duo most certainly is not. (It's a Penryn on this chart: https://en.wikipedia.org/wiki/Template:Intel_processor_roadmap) OK, so your CPU doesn't have RDRAND. That means the compiler must have the wrong information about what it's target is. With GCC, the flag to adjust is -march. In your case, -march=core2 should do it. It should also be ok to say -march=native, which will target exactly what you're compiling on.
{ "pile_set_name": "StackExchange" }
Q: Freewheel diode / capacitor with this board? With DC motors, it is common to put a freewheel diode and/or a capacitor in order to protect the equipment as the motor can induce current into the system. I plan to use this board to control a 24V DC motor with a Arduino-like microcontroler. In an example in their documentation, they don't put such protection, so I wanted to know if it's unsafe, or is it that the board already protects the system? The example in question: A: The motor driver board is bidirectional: it uses a transistor arrangement called a H-bridge to drive the motor. The N-type MOSFETs being used as switches in that board inherently contain a "body diode" as a side effect of their construction. That diode is shown as part of the schematic symbol of the transistors. Normally the transistors will take care of the inductive current, but the body diodes will provide a path for the inductive spikes if something goes wrong with the circuitry that controls the transistors. If you were to add a diode in parallel with the motor that diode would not only be unnecessary, but it would short out the power supply trough the diode when you reverse the motor.
{ "pile_set_name": "StackExchange" }
Q: Autocomplete of HTML tags in React aren't working in VS Code I'm using VS Code to code a React project. When I'm typing my HTML tags, the suggestion box pops up and correctly suggests that I'm typing a <div> tag, for exmpale. However, hitting Tab key or Enter key do nothing. Not even using my mouse to click on the autosuggest does anything. I've looked it up and adjusted my user settings with no success. In the bottom right corner, I changed it from JavaScript to JavaScript React". I added these to my settings: { "emmet.includeLanguages": { "javascript": "javascriptreact", "javascript": "html" }, "emmet.triggerExpansionOnTab": true, } These didn't really do anything different. What can do I? It's annoying enough that I'm thiking of going back to Atom. Having to not only type each tag seperately but then having to position the closing tag afterwards is destroying any productivity. A: Try the following steps: From the bottom right click on Language Mode (which might be showing html) In the search section (at the top) of the box that pops up, search for "react". Two React options might appear: javascript react and typescript react. Choose the "Javascript React".
{ "pile_set_name": "StackExchange" }
Q: integrate() in R gives terribly wrong answer I was trying to integrate the following function from -infinity to infinity. The answer should be 0.2, but R gives a ridiculously small number. What's wrong? >f=function(x){exp(-10*abs(x-25))} >integrate(f,-Inf,Inf) 5.329164e-15 with absolute error < 1e-14 A: I'll need a bit longer to explain this fully, and hopefully other users will add to this wiki. From ?integrate, the abs.tol argument is defined as absolute accuracy requested. And further down is the following note: When integrating over infinite intervals do so explicitly, rather than just using a large number as the endpoint. This increases the chance of a correct answer – any function whose integral over an infinite interval is finite must be near zero for most of that interval. So if you want absolute accuracy as opposed to relative accuracy (which is defined as the result from .Machine$double.eps^0.25) then you can do > integrate(f, Inf, -Inf, abs.tol = 0L) 0.2 with absolute error < 8.4e-06 The default argument for abs.tol is passed from rel.tol, which is .Machine$double.eps^0.25 Let's see what goes on "inside" a bit. ifoo<-integrate(f,-Inf,Inf,abs.tol=1e-20) 5.275825e-21 with absolute error < 9.8e-21 str(ifoo) List of 5 $ value : num 5.28e-21 $ abs.error : num 9.81e-21 $ subdivisions: int 3 $ message : chr "OK" $ call : language integrate(f = f, lower = -Inf, upper = Inf, abs.tol = 1e-20) - attr(*, "class")= chr "integrate" ifoo<-integrate(f,-Inf,Inf,abs.tol=1e-40) 0.2 with absolute error < 8.4e-06 str(ifoo) List of 5 $ value : num 0.2 $ abs.error : num 8.36e-06 $ subdivisions: int 21 $ message : chr "OK" $ call : language integrate(f = f, lower = -Inf, upper = Inf, abs.tol = 1e-40) - attr(*, "class")= chr "integrate" Notice the sudden jump in the number of subdivisions. In general, more subdivisions means better accuracy, which after all is the point of Calculus: reduce the subdivision width to nothing to get the exact answer. My guess is that, with a large(ish) abs.tol, it only takes a few subdivisions for the calculated value to agree with some 'estimated tolerance error' , but when the required tolerance gets small enough, more subdivisions are "added." Edit: with thanks to Hong Ooi, who actually looked at the integrand in question. :-) . Because this function has a cusp at x==25, i.e. a discontinuity in the derivative, the optimization algorithm likely gets "misled" about convergence. Oddly enough, by taking advantage of the fact that this integrand goes to near-zero very quickly, the result is better when not integrating out to +/-Inf . In fact: Rgames> integrate(f,20,30) 0.2 with absolute error < 1.9e-06 Rgames> integrate(f,22,27) 0.2 with absolute error < 8.3e-07 Rgames> integrate(f,0,50) 0.2 with absolute error < 7.8e-05 A: While in general the advice in ?integrate to explicitly specify +/-Inf as the limits is valid, it may be wrong in special cases. This is one of them. > integrate(f, 20, 30) 0.2 with absolute error < 1.9e-06 The basic problem seems to be that your function is not smooth, in that its derivative is discontinuous at x=25. This may be fooling the algorithm, in particular its use of Wynn's epsilon method to speed up convergence. Basically there's no real substitute to knowing what your function is like, and how its behaviour could cause problems. As pointed out in the answers here, R isn't a symbolic mathematical solver so you do have to exercise more care when trying to get numerical results.
{ "pile_set_name": "StackExchange" }
Q: Apache Nutch nowhere to be found I'm looking for Nutch installation files but no server has them, they're all empty. http://www.apache.org/dyn/closer.cgi/nutch/ Has it been moved or just retired?? A: i encountered the same problem earlier today. finally one of the mirrors had the actual package. just keep clicking! :-P
{ "pile_set_name": "StackExchange" }
Q: Using a function in a filter query in Solr I want to filter my result set before I search. I know the correct way to do this is by using the filter query (fq) parameter. However, I want to filter based on the output of a function performed on a field. I have a field 'rating' which is an integer in the range of 1 to ~75000. The upper limit may change. I want to filter to the top 500 items with the highest 'rating'. In SQL this would be something like: ... ORDER BY rating DESC LIMIT 500 I think I can get the documents in solr ranked by rating descending by using the function rord(rating), so basically I would like to do: fq=rord(rating):[0 TO 500] But that does not seem possible. Does anyone know what else I could do? A: Thanks to Yonik Seeley on the Solr mailing list: Solr 1.4 can now do range queries on arbitrary functions: http://lucene.apache.org/solr/api/org/apache/solr/search/FunctionRangeQParserPlugin.html Note that ord() and rord() won't work properly in Solr 1.4 trunk. Lucene has changed to searching per-segment in a MultiReader and hence you will currently get the ord() or rord() in that segment, not in the whole index.
{ "pile_set_name": "StackExchange" }
Q: jQuery validate postalcode fill city I'm using jQuery validate for my form, and I have a custom rule for postal codes. I'm using an API to check the postal code and if it's correct, it has to fill the <input type="text" name="city"> field. I'm having this code: $.validator.addMethod('postalcode', function(value, $elem) { var is_success = false; $.ajax({ url: '/ajax/check_postal_code.php', data: {postal_code: value}, json: true, async: false, success: function(msg) { is_success = msg.status === 'OK' if (is_success) { $('input[name="city"]').val(msg.results[0].address_components[1].long_name); $('input[name="city"]').valid(); } } }); return is_success; }, 'Please enter a VALID postal code'); Now this executes the AJAX call correctly, however, it doesn't 'validate' the postalcode field. It only validates my address, captcha and city field (which is done by code). If I remove the $('input[name="city"]').valid(); it validates everything, but doesn't detect the $('input[name="city"]').val(msg.results[0].address_components[1].long_name);. (it fills the input but gives an error that you need to insert the city). How can I fill the city and validate it together with the whole form? This is NOT a duplicate because my AJAX call is synchronous but when I manipulate an input and put data in it, jQuery validate won't see the change and say you have to insert a value. If I do validate the field manually after manipulating the field, some fields won't be validated anymore. A: I believe at least one of the problems was calling .valid() from within .addMethod(). Wrapping it in a setTimeout seems to work better. https://codepen.io/anon/pen/mWqJbo?editors=1011 HTML: <form id='addressForm'> <input id='postalcode' type='postalcode' name='postalcode' placeholder='postal code' /> <br/> <input name='city' required placeholder='city' /> <br/> </form> <button id='submit'>submit</button> <div id='success' style='display:none'>Success</div> JS: var myUrl = "https://api.zippopotam.us/us/"; var postalcode = '' $('input[name=postalcode]').on('change', function() { $('#success').hide(); $(this).valid(); }); $('#submit').on('click', function() { $('#success').hide(); if ($('#addressForm').valid()) { $('#success').show(); } }); //init jquery validation $("#addressForm").validate({ messages: { postalcode: 'Please enter a valid postal code' }, rules: { postalcode: { required: true, postalcode: true }, city: { required: true, } } }); $.validator.addMethod('postalcode', function(value, $elem) { /* don't re-validate postalcode on submit - saves time & prevent edits to the city field from being overwritten. If edits to city shouldn't be allowed, make city field readonly. Note that many zipcodes map to multiple cities (at least in the US). You may want to present user with a selectable list in those cases. */ if (postalcode && value === postalcode) { return true; } var is_success = false; var city = '' $.ajax({ url: myUrl + $('input[name=postalcode]').val(), data: { postal_code: value }, json: true, async: false, success: function(response) { is_success = typeof(response['post code']) !== 'undefined'; city = response.places[0]['place name']; }, error: function(err) { //zippopotam api returns 404 if zip is invalid if (err.status === 404) { //clear last valid postal code postalcode = ''; $('input[name=city]').val(''); $('#success').hide(); } //fixme handle other errors / notify user console.log('error ' + JSON.stringify(err)); } }); if (is_success) { $('input[name=city]').val(city); //remember last valid postal code postalcode = $('input[name=postalcode]').val(); //previous error message(s) may not be cleared if .valid() is called from within .addMethod() setTimeout(function() { $('input[name="city"]').valid(); }, 1); } return is_success; }, 'Please enter a VALID postal code'); Your code uses a synchronous ajax which is generally not a good idea. If you wanted to make it async you would need to use the jquery validation remote method However, that method assumes the ajax response will return "true" if the data is valid. You would need to be able to modify your backend so that there's a "valid" endpoint that will return true if the postal code is valid. I believe you would also need to add a second endpoint that returns the corresponding city. Instead of making your backend conform to what remote requires, you could override it with a custom implementation. Here's an example (codepen): HTML: <form id='addressForm'> <input id='postalcode' type='postalcode' name='postalcode' placeholder='postal code'/> <br/> <input name='city' required placeholder='city'/> <br/> </form> <button id='submit'>submit</button> <div id='success' style='display:none'>Success</div> JS: //override $.validator.methods.remote = function(value, element, param, method) { //zippopotam specific param.url = myUrl + value; if (this.optional(element)) { return "dependency-mismatch"; } method = typeof method === "string" && method || "remote"; var previous = this.previousValue(element, method), validator, data, optionDataString; if (!this.settings.messages[element.name]) { this.settings.messages[element.name] = {}; } previous.originalMessage = previous.originalMessage || this.settings.messages[element.name][method]; this.settings.messages[element.name][method] = previous.message; param = typeof param === "string" && { url: param } || param; optionDataString = $.param($.extend({ data: value }, param.data)); if (previous.old === optionDataString) { return previous.valid; } previous.old = optionDataString; validator = this; this.startRequest(element); data = {}; data[element.name] = value; $.ajax($.extend(true, { mode: "abort", port: "validate" + element.name, dataType: "json", data: data, context: validator.currentForm, success: function(response) { //zippopotam specific -> write your own definition of valid var valid = typeof(response['post code']) !== 'undefined', errors, message, submitted; /////////////// validator.settings.messages[element.name][method] = previous.originalMessage; if (valid) { //your code here $('input[name=city]').val(response.places[0]['place name']) //end your code submitted = validator.formSubmitted; validator.resetInternals(); validator.toHide = validator.errorsFor(element); validator.formSubmitted = submitted; validator.successList.push(element); validator.invalid[element.name] = false; validator.showErrors(); } else { //your code here if api returns successfully with an error object //end your code errors = {}; message = response || validator.defaultMessage(element, { method: method, parameters: value }); errors[element.name] = previous.message = message; validator.invalid[element.name] = true; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); }, error: function(response) { //your code here if api fails on bad zip, e.g. zippopotam returns 404 if (response.status === 404) { $('input[name=city]').val(''); //end your code errors = {}; message = validator.defaultMessage(element, { method: method, parameters: value }); errors[element.name] = previous.message = message; validator.invalid[element.name] = true; validator.showErrors(errors); previous.valid = false; validator.stopRequest(element, false); } else { console.log('problem with validation server'); } } }, param)); return "pending"; }; var myUrl = "https://api.zippopotam.us/us/"; //init jquery validation $("#addressForm").validate({ messages: { postalcode: 'Please enter a valid postal code' }, rules: { postalcode: { required: true, remote: { url: myUrl, type: "get", data: '' } }, city: { required: true, } } }); $('input[name=postalcode]').on('change', function() { $('#success').hide(); $('input[name=postalcode]').valid() }) $('#submit').on('click', function() { if ($("#addressForm").valid()) { $('#success').show(); } else { $('#success').hide(); } })
{ "pile_set_name": "StackExchange" }
Q: How to convert png to tiff? i need to convert png files to tiff. Is there an easy way to do so in Ubuntu 14.04? Thanks! A: Install imagemagick: sudo apt-get install imagemagick An a simple command: convert <your_png> out.tiff Or for all files in your folder: for f in *.png; do convert "$f" "${f%%.*}.tiff"; done A: Try convert: convert blah.png blah.tiff If you don't have it, try: sudo apt-get install graphicsmagick-imagemagick-compat
{ "pile_set_name": "StackExchange" }
Q: Bash variables and outputs grep -A 26 "some text" somefile.txt | awk '/other text/ { gsub(/M/, " "); print $4 }' | while read line do //operations resulting in a true of false answer done The variables declared and used in the while only exist with the sub-shell created by piping to it, how do I keep track of them from outside? I need to use the returned true or false later in the script A: Use process substitution: while read line do # operations resulting in a true of false answer done < <(grep -A 26 "some text" somefile.txt | \ awk '/other text/ { gsub(/M/, " "); print $4 }' )
{ "pile_set_name": "StackExchange" }
Q: Prove/disprove: If $n\in \mathbb N$ with $n>2$ not prime, then $2n + 13$ is not prime. Prove/disprove: If $n\in \mathbb N$ with $n>2$ not prime, then $2n + 13$ is not prime. From the context in which this question was set, I believe I have to prove/disprove it using contraposition. I have assumed that $n$ is natural, $n > 2$ and $2n + 13$ is a prime number and I now have to prove/disprove that $n$ is a prime. Hints? A: Consider the counterexample $n=9$.
{ "pile_set_name": "StackExchange" }
Q: 502 bad gateway error when reloading PHP-FPM I have a problem with PHP-FPM on Debian when trying to reload PHP-FPM configuration with PHP script that runs sudo service php5-fpm reload which will reload the same php-fpm process on which the script is running. The problem is that I get "502 Bad gateway" on the moment when the php-fpm configuration is reloaded. In order to reproduce the issue, run a script like following through your browser and run sudo service php5-fpm reload from your terminal when the script is running: <?php sleep(15); echo 'End'; Is there an easy way to overcome that issue or do I need to find a solution to that problem from a different angle? A: I have no idea why, but changing process_control_timeout = 0 to anything else than 0 (process_control_timeout = 1800s) solved the issue. Now even after reloading php-fpm I get End printed out on the screen. I would be glad if anyone explained why does it actually work.
{ "pile_set_name": "StackExchange" }
Q: function max(bytea) does not exist postgresql I am new to PostgreSQL and I cannot find the solution to this problem, I need to select the maximum value present in a column of type bytea. Any help is appreciated in advance. My Query: select MAX (Blob) from test.final My Error: psycopg2.errors.UndefinedFunction: function max(bytea) does not exist A: Since max(bytea) is not possible, you could try max(encode(...)): postgres=# create table test(name bytea); CREATE TABLE postgres=# insert into test values ('1234567890'); INSERT 0 1 postgres=# insert into test values ('12345678901234567890'); INSERT 0 1 postgres=# select * from test; name -------------------------------------------- \x31323334353637383930 \x3132333435363738393031323334353637383930 (2 rows) postgres=# select encode(name,'escape') from test; encode ---------------------- 1234567890 12345678901234567890 (2 rows) postgres=# select max(encode(name,'escape')) from test; max ---------------------- 12345678901234567890 (1 row)
{ "pile_set_name": "StackExchange" }
Q: Retrive Triggered Send Information by RequestID We perform lots of triggered sends from our .NET code and we store RequestID in our database. I need take that RequestID and request ExactTarget to get the details about that particular Triggered Send by RequestID. How can I do this? What I see in the documentation is - Retrieving a Triggered Send Summary Here is the code sample: RetrieveRequest rr = new RetrieveRequest(); rr.ObjectType = "TriggeredSendSummary"; rr.Properties = new String[] { "Sent", "Bounces", "Opens", "Clicks" }; TriggeredSendSummary tss = new TriggeredSendSummary(); // <=== THIS IS NOT USED. WHY IS IT HERE??? SimpleFilterPart sfp = new SimpleFilterPart(); sfp.SimpleOperator = SimpleOperators.equals; sfp.Property = "CustomerKey"; // <=== ONLY CUSTOMER KEY sfp.Value = new string[] { "Weekly_Newsletter_-_2009_07_16" }; rr.Filter = sfp; string requestID; APIObject[] results; string status = client.Retrieve(rr, out requestID, out results); return results; There is only filter by customer key, not RequestID. Can you help me with this? UPD1: Why is TriggeredSendSummary here? It is not used... A: In order to get tracking for individual triggered sends, you would need to look at this help article. Essentially, you will need to turn on send logging in your account, then do the following steps: Create a new profile attribute - the example code below names the attribute UniqueID, but you can change the name as appropriate. Modify your existing send Log data extension to have a field named UniqueID. Update an existing triggered send definition or create a new one, and be sure to set the IsSendLogging property to true. Trigger an email using the triggered send definition from step 4 with Send Logging passing in a value for the UniqueID attribute. Use the Retrieve method to retrieve the JobID, BatchID, and SubscriberID for that specific send from the send log data extension.
{ "pile_set_name": "StackExchange" }
Q: Reverse String in Lua? I am trying to reverse a string in Lua without using the string.reverse() function. Here is my code - function reverseStr(s) return string.gsub(s, "(.)(.)", "%2%1") end The code is currently only reversing the first two characters in the string, and I am wondering what I can do to make the function reverse every character in the string. abc -- cba bbc -- cbb dka -- akd Thank you! A: You can't make Lua's pattern matching system reverse a string. You have to either write the obvious reversing code (iterating through the string backwards, building a new table from strings in reverse order, and using table.concat) or use string.reverse.
{ "pile_set_name": "StackExchange" }
Q: Code indenting of // postfix functions Preamble Following the recommendation of a presentation or article which I now only vaguely remember I have been experimenting with a particular code format: fn[args_] := ( expr // operation1 // operation2 // operation3 ) Each operation is cast as a Function as necessary, though operator forms are used where available. Some examples: (138146), (138650), (139228). I have found this format to be reasonably general and have above average readability. I note that my use of it (which is by no means unique) seems to be well accepted so I think others must find it readable too. A couple of things keep me from adopting this format as my go-to style: the first is the requirement for additional Function constructs over more heavily bracketed code. The second is the way that this code is automatically formatted in Notebook Input Cells which is what my question is about. (Pardon the long introduction but I feel that context is necessary.) Summary When multiple // postfix operations are written one on each line the standard code indenter does this: I find this indenting weird and inconvenient. I suppose it exists to indicate that operation1 is "inside" operation5, etc., but that's not really how I think about these operations; rather I think of them as a series of sequential steps performed in order from one to five. It also ends up crowding code into the right margin when there would otherwise be plenty of room. Question All that out of the way my actual question is this: do other people regularly benefit from the indenting shown above, and what coding style(s) is it useful for? If this indenting is not of use in other styles or from different perspectives I would perhaps campaign to have the indenting changed in future versions to the vertically aligned form shown in the first code block in this question. A: As requested, I'll expand on my comment a little. The indentation makes sense if you look at the following comparison of four constructs, where the first one is from the original question: You see the same indentation in the first two examples, and the opposite indentation in the remaining two. The examples built with just Lists illustrate that the indentation is determined by the nesting level. The more deeply nested, the larger the automatic number of LineIndents is. Recall that the actual interpretation of the input for fn is operation3[operation2[operation1[expr]]]. This is why the indentation decreases downward in the first two examples but increases in the last two: as the List constructs make explicit, the operations nearest to expr are deepest. The @ operator is the "counterpart" of // in that it allows you to reverse the order of operators and arguments. This reversal is what causes the reversed indentation. In conclusion, the choice of indentation is consistent with the general prescription followed by the notebook interface, to indent according to nesting level. Changing this for // alone would then give you inconsistent indentation if you also use @ (or in fact any other nested expressions).
{ "pile_set_name": "StackExchange" }
Q: generalized principal open set Let $V$ an affine variety. A principal open set is a set of the form $V(f) = V \setminus\{f=0\} $. A well known theorem states that all such sets are affine varieties, and moreover (Shafarevich, p.50) have coordinate ring $k[V(f)]=k[V][f^{-1}]$. Now, I am interested in a more general situation - consider again an affine variety $V$, but now look at $$V_{f_1,\dots,f_t}=V\setminus \{f_1 = \dots = f_t =0\}$$ These are quasiprojective varieties, since $V_{f_1,\dots,f_t}=\bigcup_{i=1}^{t}V_{f_i}$. How can it be shown that such a set is not an affine variety (if it is indeed the case)? In general, what tools are used to show that a given quasiprojective variety is not affine? Are such sets projective varieties? If so, they are automatically not affine, since the only variety which is affine and projective is one point. What about the ring of regular functions of $V_{f_1,\dots,f_t}$? Does it equal to $K[V][f_1^{-1}]\dots[f_t^{-1}]$? If not, what can be said about it? After finding it, can this ring be used to show that the variety is not affine (the equations may be very unpleasant)? A: 1) Your varieties $V_{f_1,\dots,f_t}$ are almost never affine, except in very degenerate cases (like for instance $f_1=\dots=f_t$ !). The basic tool is the following very general and powerful theorem: Given an arbitrary subvariety $Y\subset X$ of the arbitrary variety $X$, if the complement $X\setminus Y$ is affine, then $\operatorname {codim} _X(Y)=1$ Notice that we don't assume $X$ affine here. This is a scandalously underappreciated result due to Goodman (Ann. of Math, vol.89, page 162), which doesn't seem to be mentioned in the standard books . The codimension $1$ condition is of course not sufficient as witnessed by the example $Y=\{*\} \times \mathbb P^1\subset X=\mathbb P^1 \times \mathbb P^1$ 2) An open subset $U\subset X$ of an affine variety $X$ of positive dimension is never projective because the regular functions on $U$ obtained by restriction from the regular functions on $X$ separate the points of $U$ while the regular functions on a projective variety are constant. 3) As for the ring of regular functions on $U=X\setminus Y$ in the case $\operatorname {codim} _X(Y)\geq 2$, it is easy to determine under a mild hypothesis (cf. Matsumura's Commutative Algebra, theorem 38, page 124): If $X$ is normal, then the restriction map $\mathcal O(X)\to \mathcal O(U)$ is bijective This is the algebraic version of an extraordinary result discovered in 1906 by Hartogs in the analytic setting.
{ "pile_set_name": "StackExchange" }
Q: Perform initialization first in Ninject I have an interface like this public interface IPerson { } And implementations public class Fireman : IPerson { public string Name { get; set; } public bool WithAssignedTruck { get; set; } ... } public class Pilot : IPerson { public string Name { get; set; } public int Age { get; set; } ... } And pass them to a constructor public class Registration : IRegistration { private readonly Fireman _fireman; private readonly Pilot _pilot; public Registration(Pilot pilot, Fireman fireman) { this._fireman = fireman; this._pilot = pilot; } } And here's what the initialization method looks like. public T PopulateProfile<T>() where T : IPerson, new() { var personProfile = Activator.CreateInstance<T>(); ... return personProfile; } Please take note that this code is just an example. I have a method that will set the value of each property of these classes which are from database. What I need to do is that, when I ask Ninject for any class that implements IPerson interface, Ninject should execute the method first, thus, Ninject will return an initialized class. Hope you could give me a hand. Thank you. A: You can use Ninject.Extensions.Conventions in combination with an IBindingGenerator which generates a ToMethod binding: BindingGenerator internal class PersonBindingGenerator : IBindingGenerator { private static readonly MethodInfo PopulateOpenGenericMethodInfo = typeof(IProfileService).GetMethod("PopulateProfile"); public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings( Type type, IBindingRoot bindingRoot) { yield return bindingRoot .Bind(type) .ToMethod(x => CreatePerson(x.Kernel.Get<IProfileService>(), type)); } private static object CreatePerson( IProfileService profileService, Type type) { var closedGeneric = PopulateOpenGenericMethodInfo.MakeGenericMethod(type); return closedGeneric.Invoke(profileService, new object[0]); } } Bindings kernel.Bind<IProfileService>().To<ProfileService>(); kernel.Bind(s => s .FromThisAssembly() .IncludingNonePublicTypes() .SelectAllClasses() .InheritedFrom<IPerson>() .BindWith<PersonBindingGenerator>()); Test Complete Test code for reference. using FluentAssertions; using Ninject; using Ninject.Extensions.Conventions; using Ninject.Extensions.Conventions.BindingGenerators; using Ninject.Syntax; using System; using System.Collections.Generic; using System.Reflection; using Xunit; namespace NinjectTest.SO36424126 { public interface IPerson { string SomeValue { get; set; } } class BarPerson : IPerson { public string SomeValue { get; set; } } class FooPerson : IPerson { public string SomeValue { get; set; } } public interface IProfileService { T PopulateProfile<T>() where T : IPerson, new(); } internal class ProfileService : IProfileService { public T PopulateProfile<T>() where T : IPerson, new() { var personProfile = Activator.CreateInstance<T>(); personProfile.SomeValue = "initialized"; return personProfile; } } internal class PersonBindingGenerator : IBindingGenerator { private static readonly MethodInfo PopulateOpenGenericMethodInfo = typeof(IProfileService).GetMethod("PopulateProfile"); public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot) { yield return bindingRoot .Bind(type) .ToMethod(x => CreatePerson(x.Kernel.Get<IProfileService>(), type)); } private static object CreatePerson(IProfileService profileService, Type type) { var closedGeneric = PopulateOpenGenericMethodInfo.MakeGenericMethod(type); return closedGeneric.Invoke(profileService, new object[0]); } } public class Test { [Fact] public void Foo() { var kernel = new StandardKernel(); kernel.Bind<IProfileService>().To<ProfileService>(); kernel.Bind(s => s .FromThisAssembly() .IncludingNonePublicTypes() .SelectAllClasses() .InheritedFrom<IPerson>() .BindWith<PersonBindingGenerator>()); kernel.Get<BarPerson>().SomeValue.Should().Be("initialized"); } } }
{ "pile_set_name": "StackExchange" }
Q: I would like to create a nxn matrix from two length n arrays using an addition function in python I have two arrays n and k and I would like to create a matrix with the formula n + ik. I would like the matrix to have the following form; n[0]+ik[0] n[0]+ik[1] n[0]+ik[2] etc. n[1]+ik[0] n[1]+ik[1] n[0]+ik[2] etc. etc. so far I have; z = 0 + 1j for i,j in n for i,j in k n_com = n + k*z but I know that its not working, and I realise it doesnt really make any sense. Do I have to use append? A: I think the following code is clear n = [1, 2, 3] k = [4, 5, 6] mat = [] for i in range(len(n)): row = [] # ready to make a row for j in range(len(k)): row.append(n[i] + 1j * k[j]) mat.append(row) # add the row to the mat print(mat) # we get it A more pythonic way would be (if you are interested) mat = [[x + 1j * y for y in k] for x in n] Further, many science people would use numpy, you may expect better performance and usability when matrix is large. import numpy as np n = np.array(n) k = np.array(k).reshape((-1, 1)) mat = n + k.repeat(len(n), 1) * 1j
{ "pile_set_name": "StackExchange" }
Q: Pandas Dataframe Manipulation logic Can use please help with below problem: Given two dataframes df1 and df2, need to get something like result dataframe. import pandas as pd import numpy as np feature_list = [ str(i) for i in range(6)] df1 = pd.DataFrame( {'value' : [0,3,0,4,2,5]}) df2 = pd.DataFrame(0, index=np.arange(6), columns=feature_list) Expected Dataframe : Need to be driven by comparing values from df1 with column names (features) in df2. if they match, we put 1 in resultDf Here's expected output (or resultsDf): A: I think you need: (pd.get_dummies(df1['value']) .rename(columns = str) .reindex(columns = df2.columns, index = df2.index, fill_value = 0)) 0 1 2 3 4 5 0 1 0 0 0 0 0 1 0 0 0 1 0 0 2 1 0 0 0 0 0 3 0 0 0 0 1 0 4 0 0 1 0 0 0 5 0 0 0 0 0 1
{ "pile_set_name": "StackExchange" }
Q: RSpec match array of hashes from VCR In the result of my VCR cassette I've got an array of hashes: [{ 'key' => 'TP-123', 'status:' => 'test' }, { 'key' => 'TP-124', 'status:' => 'test' }, { 'key' => 'TP-125', 'status:' => 'test' }, { 'key' => 'TP-126', 'status:' => 'test' }, ] I want to check if there is a hash with 'key' => 'TPFJT-41' expect(fetcher).not_to include('key' => 'TPFJT-41') it seems to not iterate through the whole array of hashes but it takes the first value - when I change it to: expect(fetcher).not_to include('key' => 'TP-126') it will pass either A: it seems to not iterate through the whole array of hashes but it takes the first value No. It doesn't take the first value only. And it does iterate. The issue is that you expect include matcher to do something that it does not do in fact. It is not smart enough to look into the nested objects :) When applied to an array it just checks that the object exists in the array. So, in your case, it checks whether a hash {'key' => 'TPFJT-41'} exists or not. It doesn't, obviously, so your negated expectation is always green (but the spec is broken). One of the ways to fix it is to transform the result before checking it. For example, something like the following should work: expect(fetcher.map { |h| h['key'] }).not_to include('TPFJT-41')
{ "pile_set_name": "StackExchange" }
Q: How does command substitution work with find? I have the following command find . -name "*.tiff" -exec echo `basename -s .tiff {}` \; I expect this to print all my .tiff-files without their file extensions. What I get is ./file1.tiff ./file2.tiff ... The command, find . -name "*.tiff" -exec basename -s .tiff {} \; does yield file1 file2 ... Is this not supposed to be the input of echo? A: The content of the backticks is executed before the find command - yielding just the placeholder {}, which is used in the find command line - hence your result. You can always use set -x to examine what the shell is up to.
{ "pile_set_name": "StackExchange" }
Q: SimpleDateFormat Parsing error with AM/PM I am trying to parse input string date to Date. it is unable to detect AM/PM tag in the input. It should add time to specified date and return date. But its unable to parse AM/PM tag. 03:00 PM is parsed to 03:00:00 in Date. It should be 15:00:00. output: Date : Tue Dec 22 03:00:00 UTC 2015 Calender : Tue Dec 22 11:15:00 UTC 2015 Result : 2015-12-22 11:15 AM Am I using wrong date format? Here's my code: import java.util.*; import java.text.*; public class Main { public static void main(String[] args) throws Exception { System.out.println("Result : "+Main.addHoursToDate("2015-12-22 03:00 `enter code here`PM",8,15,0)); } public static String addHoursToDate(String date, int hoursToAdd, int minsToAdd, int secToAdd){ String result = ""; try{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm aa"); Date dt = sdf.parse(date); System.out.println("Date : " + dt.toString()); Calendar cl = Calendar.getInstance(); cl.setTime(dt); cl.add(Calendar.HOUR_OF_DAY, hoursToAdd); cl.add(Calendar.MINUTE, minsToAdd); cl.add(Calendar.SECOND, secToAdd); SimpleDateFormat dfCal = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); result = Main.formatDate(cl.getTime().toString(),"EEE MMM dd HH:mm:ss z yyyy","yyyy-MM-dd HH:mm aa"); System.out.println("Calender : " + cl.getTime().toString()); }catch(Exception e){ return e.toString(); } return result; } public static String formatDate(String date, String currentFormat, String requiredFormat) throws Exception { String result = ""; boolean flag = false; try { SimpleDateFormat currentFormatter = new SimpleDateFormat(currentFormat); Date currentDate = currentFormatter.parse(date); flag = date.equals(currentFormatter.format(currentDate)); if (!flag){ throw new Exception(); // We are throwing this exception because the date has been parsed "successfully" // but still we are not sure that it has been parsed "correctly"!!! } SimpleDateFormat requiredFormatter = new SimpleDateFormat(requiredFormat); result = requiredFormatter.format(currentDate); }catch (Exception e){ return ""; } return result; } } A: Got Answer myself: I need to use SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm aa"); instead of SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm aa"); H : is used for 24 hour notation. refer to https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
{ "pile_set_name": "StackExchange" }
Q: Smallest number of nodes for an Ethereum private blockchain In a public instance, one would expect the more miners the merrier, as this improves the overall mining diversity and therefore we get better security. Private blockchains, as in the Eris case, tend not to rely on proof of work mining, and use some form of proof of stake instead. My question is: could I run a private blockchain (say using Eris), say, with just two participating nodes? Or is there any inherent lower bound below which security can become compromised? A: Theoretically that would work, practically it likely wouldn't work every well. We recommend a minimum bound of seven validator nodes with stake distributed amongst the various actors within the network (depending on what the application is trying to achieve). This will allow a tolerance of two nodes to be either malicious or offline at any one time. The tendermint consensus engine will not move the chain forward unless there is agreement amongst > 66% of the stake bonded as to the application's state root. Tendermint chains have a strong finality meaning they do not fork. They either move forward or do not depending on whether there is > 66% agreement amongst the validators as to the application's state root.
{ "pile_set_name": "StackExchange" }
Q: IntelliJ - How to define a project SDK where each developer has a different SDK for it? We have numerous developers and we all tend to have a slightly different version of the JDK (whatever was latest when we last updated). We're all 1.8, but the x in 1.8.x.x is all over the place. Is there a way we can define the JDK to use in our project so it is defined in files that are not part of the project and therefore not checked in? And more importantly, are not overwriting our individual choices when pulling the latest? A: Just name your project/module JDK 'JDK', everyone then can point it to wherever they want.
{ "pile_set_name": "StackExchange" }
Q: Edit extension using Regex I have a chrome extension to block images. I want to block two file types. Current code works fine for blocking Gif image. documentUrlPatterns: ['*://*/*'], targetUrlPatterns: ['*://*/*.gif*'] How can I block PNG and Gif images? I mean how can edit the Regex code?I want add another file type. A: Chrome uses match patterns rather than regular expressions in this API. So it's not possible to capture both .gif and .png in a single match pattern. However, because it's an array, you can include multiple patterns, for example: targetUrlPatterns: ['*://*/*.gif', '*://*/*.png']
{ "pile_set_name": "StackExchange" }
Q: What's the meaning of "very much there" in this context? Let them hear once again the strength, courage, and capabilities you see in them, often below the surface, but very much there. I think "very much there" means being close to the surface. A: In this context, very much there emphasizes how accurate it is that those with the capabilities mentioned in the sentence really do have them. (See Macmillan Dictionary) The author apparently felt the need for this emphasis, because the capabilities are not always obvious or visible, hence often below the surface. A: "Often below the surface, but very much there." The phrase "very much there" is used to tell the reader that though the qualities of strength, courage and capabilities are often hidden or dormant or just around the corner, they're certainly still there. Perhaps it may take a while for those qualities to show up or may be a circumstance is required to push them forward. For example, His loving nature is overshadowed by his temper, but it is still very much there. This implies that the person has a temper which sometimes makes him unapproachable but if you look closer, you will certainly be able to see that he is loving in nature. Hope this helps. NS
{ "pile_set_name": "StackExchange" }
Q: Variable string formatting in python 3 Input is a number, e.g. 9 and I want to print decimal, octal, hex and binary value from 1 to 9 like: 1 1 1 1 2 2 2 10 3 3 3 11 4 4 4 100 5 5 5 101 6 6 6 110 7 7 7 111 8 10 8 1000 9 11 9 1001 How can I achieve this in python3 using syntax like dm, oc, hx, bn = len(str(9)), len(bin(9)[2:]), ... print("{:dm%d} {:oc%s}" % (i, oct(i[2:])) I mean if number is 999 so I want decimal 10 to be printed like ' 10' and binary equivalent of 999 is 1111100111 so I want 10 like ' 1010'. A: You can use str.format() and its mini-language to do the whole thing for you: for i in range(1, 10): print("{v} {v:>6o} {v:>6x} {v:>6b}".format(v=i)) Which will print: 1 1 1 1 2 2 2 10 3 3 3 11 4 4 4 100 5 5 5 101 6 6 6 110 7 7 7 111 8 10 8 1000 9 11 9 1001 UPDATE: To define field 'widths' in a variable you can use a format-within-format structure: w = 5 # field width, i.e. offset to the right for all octal/hex/binary values for i in range(1, 10): print("{v} {v:>{w}o} {v:>{w}x} {v:>{w}b}".format(v=i, w=w)) Or define a different width variable for each field type if you want them non-uniformly spaced. Btw. since you've tagged your question with python-3.x, if you're using Python 3.6 or newer, you can use Literal String Interpolation to simplify it even more: w = 5 # field width, i.e. offset to the right for all octal/hex/binary values for v in range(1, 10): print(f"{v} {v:>{w}o} {v:>{w}x} {v:>{w}b}")
{ "pile_set_name": "StackExchange" }
Q: Como puedo crear un objeto html Estoy intentando crear una especie de trello minimalista para aprender un poco mas de javascript, llevo un par de horas intentando hacer esto, pero no consigo forma de crear una nueva lista, a que me refiero, al tocar el + de abajo a la derecha te da la opcion de crear una lista, el tema es que no se como hacerlo, llevo buscando hace un buen rato y no encuentro nada, quiero que en el elemento 'contenedor' se añada una lista nueva copiando el codigo ya escrito adentro de el, gracias de antemano! var addListButton; onload = function(){ addListButton = false; if (addListButton == false){ document.getElementById('add-list').innerHTML="+"; } } function addList(){ if (addListButton == false){ addListButton = true; document.getElementById('add-list-form').style.display = "block"; } else { addListButton = false; document.getElementById('add-list-form').style.display = "none"; } if (addListButton == false){ document.getElementById('add-list').innerHTML="+"; } else { document.getElementById('add-list').innerHTML="x"; } } function addElement(){ if (addListButton == false){ addListButton = true; document.getElementById('add-list-form').style.display = "block"; } else { addListButton = false; document.getElementById('add-list-form').style.display = "none"; } if (addListButton == false){ document.getElementById('add-list').innerHTML="+"; } else { document.getElementById('add-list').innerHTML="x"; } } * { margin: 0; padding:0; font-family: poppins; } .contenedor{ padding:2%; } .lista { display: inline-block; border: 1px solid #000; border-radius: 15px; padding: 2%; margin: 1%; } .lista-head{ margin-bottom: 5%; } .elemento { border: 1px solid #000; padding: 5%; margin-bottom: 3%; } .botones { padding:1%; } .add{ border: 1px solid #000; display: flex; height: 70px; width:70px; margin-left: auto; transition: ease-in-out .2s ; transition-delay: 0ms; } .add > p{ margin: auto; font-size: 2em; } .add:hover { box-shadow: rgba(0,0,0,0.7) 0px 0px 10px; } .add-element { width:50px; margin-left:auto ; height: 50px; background: #000000; color: #fff; font-weight: 600; font-size: 2em; display: flex; border: 1px solid #000; border-radius:30px; transition: ease-in-out .2s; } .add-element > p{ margin:auto; } .add-element:hover { color:#000; background:#fff; box-shadow: rgba(0,0,0,0.5) 0px 0px 10px; } .add-list { background:#000; height:15vh; padding:5%; display: none; transition: ease-in-out .2s; } .minimal-input { background:#000; border: 1px solid #fff; padding:1%; border-radius: 17px; width:100%; color: #fff; margin-bottom: 1.5%; } .minimal-input::placeholder { color:#fff; } .add-list > button { color: #fff; background:#000; border:1px solid #fff; padding:1% 4%; border-radius: 35px; transition: ease-in-out .2s; } .add-list > button:hover { color: #000; background:#fff; } .add-element-modal { background:#000; height:15vh; padding:5%; display:none; transition: ease-in-out .2s; } <div class="contenedor" id="contenedor"> <div class="lista"> <div class="lista-head"> <h2>Titulo</h2> </div> <div class="lista-body"> <div class="elemento"> <div class="elemento-titulo"> <h3>Lorem, ipsum.</h3> </div> <div class="elemento-desc"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam, ullam.</p> </div> </div> <div class="elemento"> <div class="elemento-titulo"> <h3>Lorem, ipsum.</h3> </div> <div class="elemento-desc"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam, ullam.</p> </div> </div> </div> <div class="lista-footer"> <div class="add-element"> <p>+</p> </div> </div> </div> </div> <div class="botones"> <div class="add" onclick="addList()"><p id="add-list"></p></div> </div> <div class="add-list" id="add-list-form"> <input class="minimal-input" type="text" placeholder="Nombre de la lista" name="" id="new-list-name"> <button onclick="newList()">Añadir</button> </div> <div class="add-element-modal"> <input class="minimal-input" type="text" placeholder="Nombre del elemento" name="" id="new-list-name"> <input class="minimal-input" type="text" placeholder="Descripción del elemento" name="" id="new-list-name"> </div> A: En tu pregunta no incluiste la función newList(). Funciona así: Obtienes el campo de texto de la ventana modal, después se va usar el valor nombre.value para asignar el título a la lista. Creas un nuevo elemento div Asignas la clase lista Creas el contenido HTML usando plantilla de texto para evitar concatenaciones y facilitar la lectura Finalmente agregas la nueva lista al contenedor con appendChild() let addListButton; // Crear variable del contenedor donde se van a agregar las listas nuevas let contenedor; window.onload = function(){ contenedor = document.getElementById('contenedor'); addListButton = false; if (addListButton == false){ document.getElementById('add-list').innerHTML="+"; } } function addList(){ if (addListButton == false){ addListButton = true; document.getElementById('add-list-form').style.display = "block"; } else { addListButton = false; document.getElementById('add-list-form').style.display = "none"; } if (addListButton == false){ document.getElementById('add-list').innerHTML="+"; } else { document.getElementById('add-list').innerHTML="x"; } } function addElement(){ if (addListButton == false){ addListButton = true; document.getElementById('add-list-form').style.display = "block"; } else { addListButton = false; document.getElementById('add-list-form').style.display = "none"; } if (addListButton == false){ document.getElementById('add-list').innerHTML="+"; } else { document.getElementById('add-list').innerHTML="x"; } } // Función newList que no incluiste en tu pregunta function newList() { // Obtener campo de texto del modal let nombre = document.getElementById('new-list-name'); // Crear nuevo elemento div let lista = document.createElement('div'); // Asignar clase lista.className = 'lista'; // Contenido de la lista lista.innerHTML = ` <div class="lista-head"> <h2>${nombre.value}</h2> </div> <div class="lista-body"> </div> <div class="lista-footer"> <div class="add-element"><p>+</p></div> </div> `; // Agregar lista al contenedor contenedor.appendChild(lista); } * { margin: 0; padding:0; font-family: poppins; } .contenedor{ padding:2%; } .lista { display: inline-block; border: 1px solid #000; border-radius: 15px; padding: 2%; margin: 1%; } .lista-head{ margin-bottom: 5%; } .elemento { border: 1px solid #000; padding: 5%; margin-bottom: 3%; } .botones { padding:1%; } .add{ border: 1px solid #000; display: flex; height: 70px; width:70px; margin-left: auto; transition: ease-in-out .2s ; transition-delay: 0ms; } .add > p{ margin: auto; font-size: 2em; } .add:hover { box-shadow: rgba(0,0,0,0.7) 0px 0px 10px; } .add-element { width:50px; margin-left:auto ; height: 50px; background: #000000; color: #fff; font-weight: 600; font-size: 2em; display: flex; border: 1px solid #000; border-radius:30px; transition: ease-in-out .2s; } .add-element > p{ margin:auto; } .add-element:hover { color:#000; background:#fff; box-shadow: rgba(0,0,0,0.5) 0px 0px 10px; } .add-list { background:#000; height:15vh; padding:5%; display: none; transition: ease-in-out .2s; } .minimal-input { background:#000; border: 1px solid #fff; padding:1%; border-radius: 17px; width:100%; color: #fff; margin-bottom: 1.5%; } .minimal-input::placeholder { color:#fff; } .add-list > button { color: #fff; background:#000; border:1px solid #fff; padding:1% 4%; border-radius: 35px; transition: ease-in-out .2s; } .add-list > button:hover { color: #000; background:#fff; } .add-element-modal { background:#000; height:15vh; padding:5%; display:none; transition: ease-in-out .2s; } <div class="contenedor" id="contenedor"> <div class="lista"> <div class="lista-head"> <h2>Titulo</h2> </div> <div class="lista-body"> <div class="elemento"> <div class="elemento-titulo"> <h3>Lorem, ipsum.</h3> </div> <div class="elemento-desc"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam, ullam.</p> </div> </div> <div class="elemento"> <div class="elemento-titulo"> <h3>Lorem, ipsum.</h3> </div> <div class="elemento-desc"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam, ullam.</p> </div> </div> </div> <div class="lista-footer"> <div class="add-element"> <p>+</p> </div> </div> </div> </div> <div class="botones"> <div class="add" onclick="addList()"><p id="add-list"></p></div> </div> <div class="add-list" id="add-list-form"> <input class="minimal-input" type="text" placeholder="Nombre de la lista" name="" id="new-list-name"> <button onclick="newList()">Añadir</button> </div> <div class="add-element-modal"> <input class="minimal-input" type="text" placeholder="Nombre del elemento" name="" id="new-list-name"> <input class="minimal-input" type="text" placeholder="Descripción del elemento" name="" id="new-list-name"> </div> Con este ejemplo ya te será fácil agregar elementos a cada lista, lo único que deberás hacer es averiguar en cuál lista se encuentra el botón al que se hizo clic para buscar el lista-body correspondiente.
{ "pile_set_name": "StackExchange" }
Q: What's the best way to set up a content-manageable 404 page? I'd like to make my 404 page editable through Craft, but when I create a single for it, a URI is required. Is there a way to make a single with no URI, or is the best route to setup globals for managing this content? Or is there a better way that I don't know about? A: I would create a Single with the URI set to "404", and also set its Template to "404". That entry will automatically get loaded if you go to http://example.com/404, and load your 404.html template, so at the top of the template you should add this to it: {# # Fetch the 404 Single entry, if we don’t already have it. # (requests to /404 will already have it.) #} {% if entry is not defined %} {% set entry = craft.entries.uri('404').first() %} {% endif %} Craft 3 note: As of Craft 3 the 404.html template is only loaded if devMode is disabled in the current environment. If devMode is enabled, you'll continue get a Yii error message.
{ "pile_set_name": "StackExchange" }
Q: Use one PPA in another PPA I would like to create a PPA for package that is not in Ubuntu yet. It has a dependency on another piece of software which isn't in the official repository either, but available from another PPA. Is it possible to source that PPA into mine without manually copying over the packages for every new upload? A: If you don't need the PPA users to install that package and you only need it as a build dependency, you can add that other PPA as a dependency for your PPA. To do this, go to the PPA page on Launchpad, click "Edit PPA dependencies" and there, add the PPA from which you need the dependency:
{ "pile_set_name": "StackExchange" }
Q: PyCUDA strange error cuLaunchKernel failed: invalid value When I try to use the script underneath to get the data back to the cpu, there is an error. I don't get an error when I try to put some values in "ref" if I would just put: ref[1] = 255; ref[0] = 255; ref[2] = 255; but if I do something like this: if (verschil.a[idx+idy*640]>5){ ref[1] = 255; ref[0] = 255; ref[2] = 255; } the error message I get is: Traceback (most recent call last): File "./zwartwit.py", line 159, in <module> verwerking(cuda.InOut(refe),cuda.InOut(frame), block=(640, 1, 1)) File "/usr/lib/python2.7/dist-packages/pycuda/driver.py", line 374, in function_call func._launch_kernel(grid, block, arg_buf, shared, None) pycuda._driver.LogicError: cuLaunchKernel failed: invalid value Thanks for the help! ps, this is a symplified version of the script I was talking about. to get the same error, the // must be removed. import pycuda.driver as cuda import pycuda.autoinit from pycuda.compiler import SourceModule import numpy import cv2 from time import time,sleep mod = SourceModule(""" struct legear{ int a[307200];}; __global__ void totaal(int *ref){ int idx = threadIdx.x + blockIdx.x * blockDim.x; legear test; for (int idy=0;idy<480;idy++){ if (idy < 480){ if (idx < 640){ if (ref[idx*3+idy*640*3]>100){ test.a[idx+idy*640] = 255; } //if (test.a[idx+idy*640] == 255){ ref[idx*3+idy*640*3] = 255; ref[idx*3+idy*640*3+1] = 255; ref[idx*3+idy*640*3+2] = 255; //} } } } } """) camera = cv2.VideoCapture(0) im2 = numpy.zeros((768, 1024, 1 ),dtype=numpy.uint8) cv2.imshow("projector", im2) key = cv2.waitKey(100) for i in range(0,8): refe = camera.read()[1] im2[500:502] = [100] cv2.imshow("projector", im2) key = cv2.waitKey(100) verwerking = mod.get_function("totaal") refe = refe.astype(numpy.int32) verwerking(cuda.InOut(refe), block=(640, 1, 1)) refe = refe.astype(numpy.uint8) cv2.imshow("test", refe) cv2.waitKey(200) raw_input() A: The basic problem here is the size of test inside your kernel. As you have written it, every thread requires 1228800 bytes of local memory. The runtime must reserve that memory for every thread - so your code would require 750Mb of free memory to allocate for local memory on the device to support the 640 threads per block you are trying to launch. My guess is that your device doesn't have that amount of free memory. The reason why the code you have shown works without the if statement is down to compiler optimisation - in that case test isn't actually used for anything and the compiler simply removes it from the code, which eliminates the huge local memory footprint of the kernel and allows it to run. When you uncomment the if statement, test determines the state of a global memory write, thus the compiler cannot optimise it away and the kernel requires a large amount local memory to run. This is the compiler output I see with the kernel code as you posted it: > nvcc -arch=sm_21 -Xptxas="-v" -m32 -c wnkr_py.cu wnkr_py.cu wnkr_py.cu(7): warning: variable "test" was set but never used tmpxft_00000394_00000000-5_wnkr_py.cudafe1.gpu tmpxft_00000394_00000000-10_wnkr_py.cudafe2.gpu wnkr_py.cu wnkr_py.cu(7): warning: variable "test" was set but never used ptxas : info : 0 bytes gmem ptxas : info : Compiling entry function '_Z6totaalPi' for 'sm_21' ptxas : info : Function properties for _Z6totaalPi 0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads ptxas : info : Used 8 registers, 36 bytes cmem[0], 4 bytes cmem[16] tmpxft_00000394_00000000-5_wnkr_py.cudafe1.cpp tmpxft_00000394_00000000-15_wnkr_py.ii Note the compiler warning and the stack frame size. With the if statement active: >nvcc -arch=sm_21 -Xptxas="-v" -m32 -c wnkr_py.cu wnkr_py.cu tmpxft_000017c8_00000000-5_wnkr_py.cudafe1.gpu tmpxft_000017c8_00000000-10_wnkr_py.cudafe2.gpu wnkr_py.cu ptxas : info : 0 bytes gmem ptxas : info : Compiling entry function '_Z6totaalPi' for 'sm_21' ptxas : info : Function properties for _Z6totaalPi 1228800 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads ptxas : info : Used 7 registers, 36 bytes cmem[0] tmpxft_000017c8_00000000-5_wnkr_py.cudafe1.cpp tmpxft_000017c8_00000000-15_wnkr_py.ii Note the stack frame size changes to 1228800 bytes per thread. My quick reading of the code suggests that test doesn't need to be anything like as large as you have defined it for the code to run, but I leave the required size as an exercise to the reader....
{ "pile_set_name": "StackExchange" }
Q: Creating a deck of cards by adding a card each time a user inputs a value I am trying to make a deck of cards by a user input. E.g. if the user entered 0,4 the card shown would be stored as the 4 of hearts. The code I have so far is not working at all for the suits. I plan to do the same else if for the card values as well. public void addCard() { String suit[] = {"Hearts", "Diamonds", "Spades", "Clubs"}; String value[] = {"ZZZZ", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; System.out.println("Please enter a suit"); Scanner input = new Scanner(System.in); int card[] = card.nextLine(); int i; if(int card[] = 0) { String newSuit [] = String suit[0]; } else if(int card[] = 1){ String newSuit [] = String suit[1]; } else if (int card[] = 2){ String newSuit [] = String suit [2]; } else if (int card[] = 3){ String newSuit [] = String suit [3]; } } A: You probably get a compiler error in this (and the next ones) line: if(int card[] = 0) int card[] is an array, which is eventually an Object, and you are trying to assign to it a primitive value... which won't work. Besides, it looks like you are trying to compare something, which rather uses ==, and not =.
{ "pile_set_name": "StackExchange" }
Q: PhantomJS and Unicode Block 'Private Use Area' PhantomJS has an issues with unicode private blocks. I didn't found any references about it. The test is very simple just render this test page and you will get the results. Has anyone a resolution for this? A: The Private Use Area is one of the blocks allocated for private use codepoints, often called “private use characters”, though this is really misleading. The Unicode FAQ says: “Private-use characters are code points whose interpretation is not specified by a character encoding standard and whose use and interpretation may be determined by private agreement among cooperating users.” Thus, a private use codepoint has no meaning unless one is assigned, by an agreement between interested partied. You should not expect it to be rendered in any useful way. Programs typically render them using some generic glyph, or no glyph, or e.g. a box containing the code number. However, fonts may have glyphs representing characters (typically, characters not yet encoded in Unicode). This is completely font-dependent, though the idea is that such allocating reflects some private agreement on the use of private use code points.
{ "pile_set_name": "StackExchange" }
Q: sql query with condition on date I have a little simple problem. I want to perform a query on a Mysql table to select posts posted after a certain date but I don't manage to get it working by setting that date as a PHP variable. The following query doesn't return anything: $reqsql = "SELECT * FROM posts WHERE post_date <= " . $from_date; The "post_date" field is set as a datetime. I have tried everything for the $from_date PHP variable format: $from_date = date(); $from_date = date('Y-m-d-H-i-s'); $from_date = date('Y-m-d H:i:s'); $from_date = strtodate("now"); None of these work... But it works fine if I put a basic Mysql date like: $reqsql = "SELECT * FROM posts WHERE post_date <= NOW()"; Any idea? Thanks! A: You probably only need to wrap $from_date in single quotes. $reqsql = "SELECT * FROM posts WHERE post_date <= '" . $from_date ."'";
{ "pile_set_name": "StackExchange" }
Q: Given a span of string like [0..2) how to find string equivalent? I am using apache open nlp toolkit in java.I wish to display only name enitites in a given text like geo-graphical, person etc.. Following code snippet gives string spans try { System.out.println("Input : Pierre Vinken is 61 years old"); InputStream modelIn = new FileInputStream("en-ner-person.bin"); TokenNameFinderModel model = new TokenNameFinderModel(modelIn); NameFinderME nameFinder = new NameFinderME(model); String[] sentence = new String[]{ "Pierre", "Vinken", "is", "61", "years", "old", "." }; Span nameSpans[] = nameFinder.find(sentence); for(Span s: nameSpans) System.out.println("Name Entity : "+s.toString()); } catch (IOException e) { e.printStackTrace(); } Output : Input : Pierre Vinken is 61 years old Name Entity : [0..2) person How can i get the equivalent string rather than span, is there any api for that? A: Span has the method getCoveredText(CharSequence text) which will do this. But I don't understand why you need an API method to get the text corresponding to a span. A span clearly provides start (inclusive) and end (exclusive) integer offsets. So the following suffices: StringBuilder builder = new StringBuilder(); for (int i = s.getStart(); i < s.getEnd(); i++) { builder.append(sentences[i]).append(" "); } String name = builder.toString();
{ "pile_set_name": "StackExchange" }
Q: Accessing content file in c# web application I am having this issue on my mind for 3 days now. I have an xml file that is marked as Content and Always Copy. The file was copied to: C:\Users\avi\Documents\Visual Studio 2010\Projects\ExpressBroker\ExpressBroker\bin\XMLMetadata\Actions.1.xml When accessing to the file: //like that: XDocument actions = XDocument.Load("bin\\XMLMetadata\\Actions.1.xml"); //or like that: XDocument actions = XDocument.Load("XMLMetadata\\Actions.1.xml"); //or like that: XDocument actions = XDocument.Load("Actions.1.xml"); I get the following exception: Exception Details: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files\IIS Express\bin\XMLMetadata\Actions.1.xml'. Why is it been searched in the IIS folder? how do i access the file? I am using IIs Express with VWD2010 A: You need to have web application's relative path by using Server.MapPath("/")+"bin\\XMLMetadata\\Actions.1.xml" like that.
{ "pile_set_name": "StackExchange" }
Q: I wan to see the out put of PHP code I am not a PHP person, but want to see the out put of the following PHP codes seperatly. The ref $ref = time().mt_rand(0,9999999); and the Hash $task = 'pay'; $merchant_id = '0001-0000'; $my_username = 'my_username'; $merchant_email_on_voguepay = '[email protected]'; $ref = time().mt_rand(0,9999999); $command_api_token = 'XPuz39v2RFzgdEUbPqcyTMhytstgw'; $hash = hash('sha512',$command_api_token.$task.$merchant_email_on_voguepay.$ref); NB: Please don't worry about the real key, I set it up for experimental purpose. I have tried to get the out put, but I am getting no where. I need the out put please. I want to compare it with what I am getting with C#. A: Use echo ---> http://php.net/manual/en/tutorial.firstpage.php echo $ref; echo $hash;
{ "pile_set_name": "StackExchange" }
Q: Ruby on Rails - How to show foreign key values in one model to another I'am new to Ruby on Rail 4. I have two models Newspaper and Language class Language < ActiveRecord::Base has_many :newspapers end class Newspaper < ActiveRecord::Base belongs_to :language end This is the tables of two models language -------- * id * name newspaper --------- * id * name * language_id After generate controllers and db migration, Newspaper index page populate all records with language_id(means reference id) as a table format. But I need to display newspaper corresponding language name in the table. How to achieve this one? Also is there any problem in making a relationship with these models. A: Instead of: newspaper.language_id you just need to use: newspaper.language.name or, if you aren't sure that every Newspaper belongs to corresponding Language, you could use try method: newspaper.language.try(:name) And BTW, to avoid N+1 queries problem, you should include your language association while fetching newspapers in controller, with includes method: @newspapers = Newspaper.includes(:language).your_other_scopes This way, you need to generate two SQL queries to fetch both newspapers and each one's associated language. If you didn't use includes, there would be a SQL query generated to fetch each newspaper's language, which would be much less efficient. More info here: http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
{ "pile_set_name": "StackExchange" }
Q: Accessing all rows in dataset with powershell I'm looping through a list of sql servers, querying data and creating a dataset which works great. The dataset is piped to a csv file, which has all the rows. I'm then trying to create and array from each row then email the results. The email is being sent but the contents only contain the records from the last server in the list. ForEach ($instance in Get-Content "D:\servers\sqlservers2.txt") { $SQLServer = "$instance" #use Server\Instance for named SQL instances! $SQLDBName = "msdb" $SqlQuery = " Select @@servername as [Server], j.[name] AS [JobName], run_status = CASE h.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' WHEN 2 THEN 'Retry' WHEN 3 THEN 'Canceled' WHEN 4 THEN 'In progress' END, h.run_date AS LastRunDate, h.run_time AS LastRunTime FROM sysjobhistory h INNER JOIN sysjobs j ON h.job_id = j.job_id WHERE j.enabled = 1 and j.name not like 'copytosan' and j.name not like 'syspolicy%' and j.name not like '%log%' AND h.instance_id IN (SELECT MAX(h.instance_id) FROM sysjobhistory h GROUP BY (h.job_id)) " $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet) $SqlConnection.Close() #File is created with all rows from dataset $DataSet.Tables[0] | Out-File D:\servers\myfiles.csv -Append } foreach ($line in $dataset.tables[0]) { $body += $line } # (Out-String -InputObject $body -Width 100) Send-MailMessage -To [email protected] -from [email protected] -Subject Test12345 -body (Out-String -InputObject $body -Width 100) -SmtpServer [email protected] A: You need to nest your second loop. That way it will loop through the rows of each table instead of only the last table. ForEach ($instance in Get-Content "D:\servers\sqlservers2.txt") { # code foreach ($line in $dataset.tables[0]) { $body += $line } }
{ "pile_set_name": "StackExchange" }
Q: SqlCommand execute with multi result When I execute 3 line script(or more) (Example: I UPDATE, II DELETE, III SELECT), SSMS gives me 3 Message(s) and 1 Result(s): I UPDATE -> x row(s) affected II DELETE-> x row(s) affected III SELECT -> x row(s) affected III SELECT -> grid view How can I make it my own? using C#. I'm creating: SqlConnection cn = new SqlConnection("blabla"); SqlCommand cmd = new SqlCommand("my script", cn); now I need execute and get all type of result row(s) affected row(s) affected DataTable (or DataSet) A: If you subscribe to the StatementCompleted event you can get the rowcounts you want. var rowCounts = new List<int>(); var resultSets = new List<DataTable>(); using (SqlConnection cn = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand(myScript, cn)) { cmd.StatementCompleted += (sender, eventArgs) => { rowCounts.Add(eventArgs.RecordCount); }; cn.Open(); using (var rd = cmd.ExecuteReader()) { do { var table = new DataTable(); table.Load(rd); resultSets.Add(table); } while (rd.NextResult()); } } //rowCounts now holds all of the reported rowcounts //resultSets now holds all of the result sets returned. Important note, if someone did SET NOCOUNT ON in their script the event StatementCompleted will not fire, to get rowcounts in that situation you have to use @@rowcount in the script and return it explicitly as a result set in a SELECT.
{ "pile_set_name": "StackExchange" }
Q: Adding hyperlinks in a Google Form How can I add hyperlinks in Google Form? A: Here's how. Add the host (eg. www) and domain name (eg. google.com) without the protocol or an html anchor. In other words: Works www.google.com gmail.google.com Will not work google.com http://google.com <a href="http://www.google.com/">google<a/> A: Currently, the only place you can put hyperlinks in a Google form is in the second box from the top (aka the description box). Anywhere else and the URL wont be clickable. To add a URL to the discription box simply type the URL with or without the http://. You dont need to add any HTML markup. eg Typing google.com will result in google.com Its a feature that has been requested before but so far Google hasn't added it yet. All we can do is wait in anticipation!
{ "pile_set_name": "StackExchange" }
Q: move array field to another field in another array editing it This script should store folders in a dir in fvar2 as folder1/ folder2/ folder3/ and then echo in fvar1 as folder1 folder2 folder3 using "sed" command. In the end it should echo all dirs in the new array fvar1 This is the error ./test.sh: line 18: syntax error near unexpected token ``echo "${fvar2[svar3]}" | sed 's#/##g'`' ./test.sh: line 18: `{fvar1[svar4]}=(`echo "${fvar2[svar3]}" | sed 's#/##g'`)' And This is the Script #!/bin/bash fvar2=(*/) svar3=0 svar4=0 while true do {fvar1[svar4]}=(`echo "${fvar2[svar3]}" | sed 's#/##g'`) svar3=`expr $svar3 + 1` svar4=`expr $svar4 + 1` echo "${fvar1[svar4]}" done A: The proper bash way: #!/bin/bash # When using globs, always use either nullglob or failglob shopt -s nullglob # define your array fvar2 declare -a fvar2=( */ ) # Remove the trailing slash in each field of fvar2, and make an array fvar1 of it declare -a fvar1=( "${fvar2[@]%/}" ) # Print each field of array fvar2, one field per line printf '%s\n' "${fvar1[@]}" This is 100% safe and bullet-proof regarding file names with funny symbols (spaces, newlines, etc.). Now let me extend this answer a little bit, to show you how you would build an array from another one with more involved processing. Usually, simple processings can be done using Shell Parameter Expansions. But if this is not enough, e.g., you want to only keep the substrings of length 4 starting at offset 7 of each field in an array array1. The solution declare -a array2=( "${array1[@]:7:4}" ) will not work, since this will take the fields 7 to 11 of array1, as you will read in the link I gave above. Here, you really need to loop through array1, do the processing, and push this on array2. This is how you'll do: # empty and initialize array2 declare -a array2=() for i in "${array2[@]}"; do array2+=( "${i:7:4}" ) done The += operator will concatenate the arrays of the lhs and rhs, putting the result on the array of the lhs. Look: $ declare -a array1=( banana{00..10}gorilla ) $ printf '%s\n' "${array2[@]}" banana00gorilla banana01gorilla banana02gorilla banana03gorilla banana04gorilla banana05gorilla banana06gorilla banana07gorilla banana08gorilla banana09gorilla banana10gorilla $ declare -a array2=() $ for i in "${array1[@]}"; do array2+=( "${i:7:4}" ); done $ printf '%s\n' "${array2[@]}" 0gor 1gor 2gor 3gor 4gor 5gor 6gor 7gor 8gor 9gor 0gor Request to explain shopt -s nullglob When using bash's globs, always use shopt -s nullglob or shopt -s failglob is you really want a robust script. Why? Look: $ shopt -u nullglob failglob # unsetting nullglob and failglob $ echo there_are_no_files_matching_this_glob_in_this_directory_* there_are_no_files_matching_this_glob_in_this_directory_* As you have seen, when nullglob and failglob are unset, if there are no globbing matches, bash will expand the glob to itself, verbatim. This can lead to terrible stuff inside scripts, e.g., if you want to rename all files that end with .txt by prepending banana to them, you'd do this... but what if there are no files ending with .txt in the directory? $ shopt -u nullglob failglob $ for i in *.txt; do mv "$i" "banana$i.txt"; done mv: cannot stat `*.txt': No such file or directory $ # oh dear :( Yes, oh dear :( because you've run a command without controlling its arguments... this can potentially be dangerous. Now, if you turn nullglob on, and if there are no matches, the glob will expand to nothing! :). Look: $ shopt -s nullglob; shopt -u failglob $ for i in *.txt; do mv "$i" "banana$i.txt"; done $ # Oh... nothing happened, great! Or, if you turn failglob on, and if there are no matches, bash will raise an error: $ shopt -s failglob; shopt -u nullglob $ for i in *.txt; do mv "$i" "banana$i.txt"; done bash: no match: *.txt $ # Good :) and the loop never gets executed (which is good! you don't want to run commands without controlling their arguments). What if you turn both on? $ shopt -s nullglob failglob $ for i in *.txt; do mv "$i" "banana$i.txt"; done bash: no match: *.txt $ # Good :) oh, failglob seems to win. In your case, I guess you want your array to be truly empty if there are no directories. Look: $ # I'm in a directory with no subdirs $ # I'm unsetting nullglob and failglob $ shopt -u nullglob failglob $ array=( */ ) $ declare -p array declare -a array='([0]="*/") $ # Oh dear, my array contains */ verbatim $ # now, let's set nullglob $ shopt -s nullglob $ array=( */ ) $ declare -p array declare -a array='()' $ # Now array is truly empty! :) $ # How about failglob? $ shopt -u nullglob; shopt -s failglob $ # You'll see the failure in $? look: $ echo $? 0 $ # all is good about $? $ array=( */ ) bash: no match: */ $ echo $? 1 $ # :) But with failglob your array will not be reset: $ declare -a array=( some junk in my array ) $ declare -p array declare -a array='([0]="some" [1]="junk" [2]="in" [3]="my" [4]="array")' $ shopt -u nullglob; shopt -s failglob $ array=( */ ) bash: no match: */ $ declare -p array declare -a array='([0]="some" [1]="junk" [2]="in" [3]="my" [4]="array")' $ # Ok, got it! :)
{ "pile_set_name": "StackExchange" }
Q: How to change the default value of a Struct attribute? According to the documentation unset attributes of Struct are set to nil: unset parameters default to nil. Is it possible to specify the default value for particular attributes? For example, for the following Struct Struct.new("Person", :name, :happy) I would like the attribute happy to default to true rather than nil. How can I do this? If I do as follows Struct.new("Person", :name, :happy = true) I get -:1: syntax error, unexpected '=', expecting ')' Struct.new("Person", :name, :happy = true) ^ -:1: warning: possibly useless use of true in void context A: This can also be accomplished by creating your Struct as a subclass, and overriding initialize with default values as in the following example: class Person < Struct.new(:name, :happy) def initialize(name, happy=true); super end end On one hand, this method does lead to a little bit of boilerplate; on the other, it does what you're looking for nice and succinctly. One side-effect (which may be either a benefit or an annoyance depending on your preferences/use case) is that you lose the default Struct behavior of all attributes defaulting to nil -- unless you explicitly set them to be so. In effect, the above example would make name a required parameter unless you declare it as name=nil A: Following @rintaun's example you can also do this with keyword arguments in Ruby 2+ A = Struct.new(:a, :b, :c) do def initialize(a:, b: 2, c: 3); super end end A.new # ArgumentError: missing keyword: a A.new a: 1 # => #<struct A a=1, b=2, c=3> A.new a: 1, c: 6 # => #<struct A a=1, b=2, c=6> UPDATE The code now needs to be written as follows to work. A = Struct.new(:a, :b, :c) do def initialize(a:, b: 2, c: 3) super(a, b, c) end end A: @Linuxios gave an answer that overrides member lookup. This has a couple problems: you can't explicitly set a member to nil and there's extra overhead on every member reference. It seems to me you really just want to supply the defaults when initializing a new struct object with partial member values supplied to ::new or ::[]. Here's a module to extend Struct with an additional factory method that lets you describe your desired structure with a hash, where the keys are the member names and the values the defaults to fill in when not supplied at initialization: # Extend stdlib Struct with a factory method Struct::with_defaults # to allow StructClasses to be defined so omitted members of new structs # are initialized to a default instead of nil module StructWithDefaults # makes a new StructClass specified by spec hash. # keys are member names, values are defaults when not supplied to new # # examples: # MyStruct = Struct.with_defaults( a: 1, b: 2, c: 'xyz' ) # MyStruct.new #=> #<struct MyStruct a=1, b=2, c="xyz" # MyStruct.new(99) #=> #<struct MyStruct a=99, b=2, c="xyz"> # MyStruct[-10, 3.5] #=> #<struct MyStruct a=-10, b=3.5, c="xyz"> def with_defaults(*spec) new_args = [] new_args << spec.shift if spec.size > 1 spec = spec.first raise ArgumentError, "expected Hash, got #{spec.class}" unless spec.is_a? Hash new_args.concat spec.keys new(*new_args) do class << self attr_reader :defaults end def initialize(*args) super self.class.defaults.drop(args.size).each {|k,v| self[k] = v } end end.tap {|s| s.instance_variable_set(:@defaults, spec.dup.freeze) } end end Struct.extend StructWithDefaults
{ "pile_set_name": "StackExchange" }
Q: How to generate a dash address? How can I generate a simple dash address from a public key? How many address formats are there in dash? A: How many address formats are there in dash? Dash seems to be pretty similar to bitcoin when it comes to address and transaction formats. You have your typical P2PK, P2PKH, P2SH. Here is how to generate a standard P2PKH address (and therefore also a P2PK address). var bip39 = require('bip39'); var hdkey = require('hdkey'); var createHash = require('create-hash'); var bs58check = require('bs58check'); //const mnemonic = bip39.generateMnemonic(); //generates string const mnemonic = 'thunder purchase pave tower lecture upgrade supreme half kid fitness tray shove' const seed = bip39.mnemonicToSeed(mnemonic); //creates seed buffer console.log('mnemonic: ' + mnemonic); const root = hdkey.fromMasterSeed(seed); const masterPrivateKey = root.privateKey.toString('hex'); //console.log('extended public key root: ' + root.publicExtendedKey) const addrnode = root.derive("m/44'/5'/0'/0/0"); console.log('addrnodePublicKey: '+ addrnode._publicKey.toString('hex')) console.log('addernodePrivateKey: ' + addrnode._privateKey.toString('hex')) const step1 = addrnode._publicKey; const step2 = createHash('sha256').update(step1).digest(); const step3 = createHash('rmd160').update(step2).digest(); var step4 = Buffer.allocUnsafe(21); step4.writeUInt8(0x4c, 0); step3.copy(step4, 1); //step4 now holds the extended RIPMD-160 result const step9 = bs58check.encode(step4); console.log('Base58Check: ' + step9); Notice the only difference between this and deriving a bitcoin address is the version bytes is not 0x00 but instead 0x4c & the derivation path coin index of 5 instead of 0.
{ "pile_set_name": "StackExchange" }
Q: Missing razor intellisense and keyboard shortcut behavior in MVC 5 - visual studio 2012 with Resharper I have started an MVC 5 empty project and imported most of my stuff from another project to this one using most of this link. However I soon found out that I was having other kinds of troubles. I have since then downloaded ASP.NET and Web Tools 2013.1 for Visual Studio 2012 and installed it, and it only solved my problem partially. As of right now my Razor syntax works, but I lost some really nice functionalities. Here's an example: <li> <a href="@Url.Action("SearchOrders", "ManageOrders")">Orders</a> </li> Today's date: @System.DateTime.Now So when I type the @System.DateTime.Now line, the intellisence does work and offers the good options. However, if I type the <a href="@Url.Action("SearchOrders", "ManageOrders")">Orders</a>, as of before when writing the SearchOrders line the intellisence would provide the names of the actions included in the controller, however with MVC 5 and Visual Studio 2012 it is no more the case. So if I type a missing action the support will not anymore warn me that the action is missing, nor will it offer me to create the action in my controller, and so on. In the same way, if I hit F12 on a View() line, Visual Studio 2012 will open the metadata class instead of showing the .cshtml file. Is there something missing to gain back those functionalities? I've tried with an MVC 4 Web Application framework and things were working fine. EDIT after user Erik pointed out that it was related to Resharper's code completion and other features, I am now searching as to why Resharper v 7.1.x does not seem to be able to deal with MVC 5 and its features. A: As Erik Funkenbush (see comments on my main post) mentioned, the data lacking was actually part of Resharper's behavior and was not related, as I thought, to Visual Studio. The main question was why Resharper 7.1.x did not seem to be able to cope with MVC 5 - Razor 3. I have not found the answer to that question, but I have installed Resharper 8 and all those lost functionality are back. So if you ever stumble upon this problem, try an updated version of Resharper, it might be your solution.
{ "pile_set_name": "StackExchange" }
Q: What does "has been described in other work" mean in this sentence? I'm currently reading a book about chemistry. Here is a sentence that I faced and didn't understand: This procedure has been described in other work from our laboratory I don't get what it means by "describe in other work"! The only thing came to my mind was that it was probably "in other words" and it's a misprint or something. Sorry for my bad English A: This procedure has been described in other work from our laboratory Could be paraphrased: This way of doing things has been described in other research/papers/books written by the researchers from our laboratory
{ "pile_set_name": "StackExchange" }
Q: How to center an absolute block on page I have a menu bar block at http://dev.smithonstocks.com that I wish to center above the body content. The max-width of the body container is 960px. I have tried float:left and display:flex, etc. but I cannot bet the menu block to center on the page. Any suggestions? A: position: absolute; left: 50%; transform: translate(-50%,0); z-index: 1;
{ "pile_set_name": "StackExchange" }
Q: Is linear kernel positive definite? In a lot of articles, the linear kernel (inner product of two matrices) is listed as positive definite however when I try it with a toy dataset, positive definiteness test returns negative result. I checked the MATLAB SVM function for linear kernel. The linear kernel function is one line command, K=(u*v') However after this step in the main svm_train function it does another operation using K, kx= (kx+kx')/2 + diag(1./boxconstraint) Where kx is K and diag(1./boxconstraint) is just a diagonal matrix of size kx and resultant kx pass the positive definiteness test. As an explanation of this step it says '% ensure function is symmetric.' I also checked libsvm but I could not find this additional operation there. However the inner product is already symmetric and this step is usually used to turn indefinite matrices into positive definite matrices. I am a bit confused about why inner product kernel does not pass the positive definiteness test? A: If u,v are both row vectors (i.e. K evaluates to a scalar), K will only be positive definite if K=dot(u,v)>0. If u and v are more general matrices (not row vectors) and u~=v, then K=u*v' will not generally be symmetric, let alone positive definite. Even when u=v, K will be non-negative definite, but will not be strictly positive definite unless u has full row rank. However, the additional matrix 1./diag(boxconstraint) is strictly positive definite assuming all boxconstraint(i)>0. Adding a non-negative definite matrix to a strictly positive definite matrix produces a strictly positive definite result always.
{ "pile_set_name": "StackExchange" }
Q: Coloring a particular Row when creating PDF with XSLT I am currently making a PDF with the XSLT. I am able to generate PDF correctly with proper data and headers. I want to highlight a row whose node <Mold> value is TOTAL as Gray(#CCCCCC). I have written that part in XSLT but somehow it is not working. XML: <?xml version="1.0" encoding="utf-8"?> <Rowsets DateCreated="2015-12-23T14:57:50" EndDate="2015-10-26T17:21:17" StartDate="2015-10-26T17:21:17" Version="15.0 SP4 Patch 4 (Jun 3, 2015)"> <Rowset> <Columns> <Column Description="" MaxRange="1" MinRange="0" Name="Material" SQLDataType="1" SourceColumn="Material"/> <Column Description="" MaxRange="1" MinRange="0" Name="ShiftTime" SQLDataType="1" SourceColumn="ShiftTime"/> <Column Description="" MaxRange="1" MinRange="0" Name="Mold" SQLDataType="1" SourceColumn="Mold"/> <Column Description="" MaxRange="1" MinRange="0" Name="Press" SQLDataType="1" SourceColumn="Press"/> <Column Description="" MaxRange="1" MinRange="0" Name="Total_Scrap" SQLDataType="8" SourceColumn="Total_Scrap"/> <Column Description="" MaxRange="1" MinRange="0" Name="Total_Confirmed" SQLDataType="8" SourceColumn="Total_Confirmed"/> </Columns> <Row> <Material>300</Material> <ShiftTime>18:00</ShiftTime> <Mold>111</Mold> <Press>25</Press> <Total_Scrap>20.0</Total_Scrap> <Total_Confirmed>200.0</Total_Confirmed> </Row> <Row> <Material>300</Material> <ShiftTime>18:00</ShiftTime> <Mold>Summary</Mold> <Press> --- </Press> <Total_Scrap>20.0</Total_Scrap> <Total_Confirmed>200.0</Total_Confirmed> </Row> <Row> <Material>300</Material> <ShiftTime>Total Shift</ShiftTime> <Mold>TOTAL</Mold> <Press> --- </Press> <Total_Scrap>20.0</Total_Scrap> <Total_Confirmed>200.0</Total_Confirmed> </Row> <Row> <Material>300-1</Material> <ShiftTime>18:00</ShiftTime> <Mold>222</Mold> <Press>16</Press> <Total_Scrap>8.0</Total_Scrap> <Total_Confirmed>111.0</Total_Confirmed> </Row> <Row> <Material>300-1</Material> <ShiftTime>18:00</ShiftTime> <Mold>333</Mold> <Press>23</Press> <Total_Scrap>10.0</Total_Scrap> <Total_Confirmed>199.0</Total_Confirmed> </Row> <Row> <Material>300-1</Material> <ShiftTime>18:00</ShiftTime> <Mold>Summary</Mold> <Press> --- </Press> <Total_Scrap>18.0</Total_Scrap> <Total_Confirmed>310.0</Total_Confirmed> </Row> <Row> <Material>300-1</Material> <ShiftTime>Total Shift</ShiftTime> <Mold>TOTAL</Mold> <Press> --- </Press> <Total_Scrap>18.0</Total_Scrap> <Total_Confirmed>310.0</Total_Confirmed> </Row> </Rowset> <Rowset> <Columns> <Column Description="Break" MaxRange="100" MinRange="0" Name="Name" SQLDataType="1" SourceColumn="Name"/> </Columns> </Rowset> <Rowset> <Columns> <Column Description="" MaxRange="1" MinRange="0" Name="Mold" SQLDataType="1" SourceColumn="Mold"/> <Column Description="" MaxRange="1" MinRange="0" Name="Press" SQLDataType="1" SourceColumn="Press"/> <Column Description="" MaxRange="1" MinRange="0" Name="Total_Scrap" SQLDataType="8" SourceColumn="Total_Scrap"/> <Column Description="" MaxRange="1" MinRange="0" Name="Total_Confirmed" SQLDataType="8" SourceColumn="Total_Confirmed"/> </Columns> <Row> <Mold>222</Mold> <Press>16</Press> <Total_Scrap>20</Total_Scrap> <Total_Confirmed>100</Total_Confirmed> </Row> <Row> <Mold>333</Mold> <Press>23</Press> <Total_Scrap>30</Total_Scrap> <Total_Confirmed>200</Total_Confirmed> </Row> <Row> <Mold>111</Mold> <Press>25</Press> <Total_Scrap>30</Total_Scrap> <Total_Confirmed>300</Total_Confirmed> </Row> </Rowset> </Rowsets> Part of XSLT that I'm trying to get above mentioned functionality: <xsl:for-each select="Row"> <fo:table-row height="13pt"> <xsl:choose> <xsl:when test="Mold=Total"> <xsl:variable name="rowcolor">#CCCCCC</xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="rowcolor">#FFFFFF</xsl:variable> </xsl:otherwise> </xsl:choose> <xsl:for-each select="child::*"> <fo:table-cell background-color="{rowcolor}" border-style="solid" border-width="1pt" padding-left="5pt" padding-top="5pt"> <fo:block font-weight="normal" text-align="left"> <xsl:value-of select="."/> </fo:block> </fo:table-cell> </xsl:for-each> </fo:table-row> </xsl:for-each> Entire XSLT as follow: <?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" font-family="Helvetica" font-size="10px"> <fo:layout-master-set> <fo:simple-page-master margin-bottom="0.5cm" margin-left="0.75cm" margin-right="0.75cm" margin-top="0.5cm" master-name="first" page-height="11in" page-width="17in"> <fo:region-body margin-bottom="0.5cm" margin-top="0.25cm"/> <fo:region-before extent="0cm"/> <fo:region-after extent="0.5cm"/> </fo:simple-page-master> </fo:layout-master-set> <xsl:for-each select="Rowsets"> <fo:page-sequence master-reference="first"> <fo:static-content flow-name="xsl-region-after"> <fo:block font-size="8pt" line-height="6pt" text-align-last="justify"> Shift Report <fo:inline id="Date"> Date [currentDate] </fo:inline> <fo:leader leader-pattern="space"/> Page <fo:page-number/> </fo:block> </fo:static-content> <fo:flow flow-name="xsl-region-body"> <xsl:for-each select="Rowset"> <xsl:choose> <xsl:when test="position()=1"> <fo:table border-color="black" border-style="solid" border-width="1pt" table-layout="fixed" width="100%"> <xsl:variable name="columns"> <xsl:value-of select="count(Columns/Column)"/> </xsl:variable> <xsl:for-each select="Columns/Column"> <xsl:choose> <xsl:when test="position()&lt;3"> <fo:table-column column-width="70pt"/> </xsl:when> <xsl:when test="position()&gt;2 and position()&lt;5"> <fo:table-column column-width="60pt"/> </xsl:when> <xsl:otherwise> <fo:table-column/> </xsl:otherwise> </xsl:choose> </xsl:for-each> <fo:table-body font-size="11pt"> <fo:table-row height="14pt"> <fo:table-cell background-color="#000000" border-style="solid" border-width="1pt" number-columns-spanned="{$columns}" padding-left="5pt" padding-top="5pt"> <fo:block color="#FFFFFF" font-weight="bold" text-align="center"> Shift Report </fo:block> </fo:table-cell> </fo:table-row> <fo:table-row height="14pt"> <xsl:for-each select="Columns/Column"> <fo:table-cell background-color="#CCCCCC" border-style="solid" border-width="1pt" padding-left="5pt" padding-top="5pt"> <fo:block color="#000000" font-weight="bold" text-align="left"> <xsl:choose> <xsl:when test="contains(@Name, 'Percent')"> <xsl:value-of select="substring-before(@Name, 'Percent')"/> <xsl:text> %</xsl:text> </xsl:when> <xsl:otherwise> <xsl:value-of select="translate(@Name,'_',' ')"/> </xsl:otherwise> </xsl:choose> </fo:block> </fo:table-cell> </xsl:for-each> </fo:table-row> <xsl:for-each select="Row"> <fo:table-row height="14pt"> *<xsl:choose> <xsl:when test="Mold=TOTAL"> <xsl:variable name="rowcolor">#CCCCCC</xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="rowcolor">#FFFFFF</xsl:variable> </xsl:otherwise> </xsl:choose> <xsl:for-each select="child::*"> <fo:table-cell background-color="{rowcolor}" border-style="solid" border-width="1pt" padding-left="5pt" padding-top="5pt"> <fo:block font-weight="normal" text-align="left"> <xsl:value-of select="."/> </fo:block>* </fo:table-cell> </xsl:for-each> </fo:table-row> </xsl:for-each> </fo:table-body> </fo:table> </xsl:when> <xsl:otherwise> <xsl:choose> <xsl:when test="Columns/Column[1]/@Description = 'Break'"> <fo:block page-break-before="always"/> </xsl:when> <xsl:otherwise> <fo:table border-color="black" border-style="solid" border-width="1pt" table-layout="fixed" width="100%"> <xsl:variable name="columns"> <xsl:value-of select="count(Columns/Column)"/> </xsl:variable> <xsl:for-each select="Columns/Column"> <fo:table-column/> </xsl:for-each> <fo:table-body font-size="10pt"> <fo:table-row height="13pt"> <fo:table-cell background-color="#000000" border-style="solid" border-width="1pt" number-columns-spanned="{$columns}" padding-left="5pt" padding-top="5pt"> <fo:block color="#FFFFFF" font-weight="bold" text-align="center"> Shift Report </fo:block> </fo:table-cell> </fo:table-row> <fo:table-row height="13pt"> <xsl:for-each select="Columns/Column"> <fo:table-cell background-color="#CCCCCC" border-style="solid" border-width="1pt" padding-left="5pt" padding-top="5pt"> <fo:block color="#000000" font-weight="bold" text-align="left"> <xsl:choose> <xsl:when test="contains(@Name, 'Percent')"> <xsl:value-of select="substring-before(@Name, 'Percent')"/> <xsl:text> %</xsl:text> </xsl:when> <xsl:otherwise> <xsl:value-of select="translate(@Name,'_',' ')"/> </xsl:otherwise> </xsl:choose> </fo:block> </fo:table-cell> </xsl:for-each> </fo:table-row> <xsl:for-each select="Row"> <fo:table-row height="13pt"> <xsl:choose> <xsl:when test="Mold=Total"> <xsl:variable name="rowcolor">#CCCCCC</xsl:variable> </xsl:when> <xsl:otherwise> <xsl:variable name="rowcolor">#FFFFFF</xsl:variable> </xsl:otherwise> </xsl:choose> <xsl:for-each select="child::*"> <fo:table-cell background-color="{rowcolor}" border-style="solid" border-width="1pt" padding-left="5pt" padding-top="5pt"> <fo:block font-weight="normal" text-align="left"> <xsl:value-of select="."/> </fo:block> </fo:table-cell> </xsl:for-each> </fo:table-row> </xsl:for-each> </fo:table-body> </fo:table> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </xsl:for-each> </fo:flow> </fo:page-sequence> </xsl:for-each> </fo:root> </xsl:template> </xsl:stylesheet> What am I doing wrong? Can anyone please help? A: There are three things wrong with your current XSLT Your current expression <xsl:when test="Mold=TOTAL"> is comparing the element Mold with an element TOTAL (which does not exist!). You need to enclose it in quote marks to make it a literal string, like so: <xsl:when test="Mold='TOTAL'"> You are defining a variable rowset but it will only be in scope in the xsl:when block, so you won't be able to use it after the xsl:choose You need to use the $ prefix when referencing an attribute. Currently you do <fo:table-cell background-color="{rowcolor}" to set the colour, when you should be doing <fo:table-cell background-color="{$rowcolor}" Try this block of code instead <xsl:for-each select="Row"> <fo:table-row height="14pt"> <xsl:variable name="rowcolor"> <xsl:choose> <xsl:when test="Mold='TOTAL'">#CCCCCC </xsl:when> <xsl:otherwise>#FFFFFF</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:for-each select="child::*"> <fo:table-cell background-color="{$rowcolor}" border-style="solid" border-width="1pt" padding-left="5pt" padding-top="5pt"> <fo:block font-weight="normal" text-align="left"> <xsl:value-of select="."/> </fo:block> </fo:table-cell> </xsl:for-each> </fo:table-row> </xsl:for-each>
{ "pile_set_name": "StackExchange" }
Q: Flutter TabBar and SliverAppBar that hides when you scroll down I am trying to create an app with a top application bar and a tab bar below. When you scroll down, the bar should hide by moving off the screen (but tabs should stay), and when you scroll back up, the application bar should show again. This behaviour can be seen in WhatsApp. Please see this video for a demonstration. (Taken from Material.io). This is a similar behaviour, although the app bar and tab bar are hidden on scroll, so it is not exactly the behaviour I am looking for. I have been able to achieve the autohiding, however, there are a few issues: I have to set the snap of the SliverAppBar to true. Without this, the application bar will not show when I scroll back up. Although this is works, it is not the behaviour I am looking for. I want the application bar to show smoothly (similar to WhatsApp) rather than coming into view even if you scroll very little. When I scroll down and change tabs, a little bit of the content is cut out of view. Below is a GIF showing the behaviour: (See the part when I scroll down on the listView (tab1), then move back to tab2) Here is the code for the DefaultTabController: DefaultTabController( length: 2, child: new Scaffold( body: new NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ new SliverAppBar( title: Text("Application"), floating: true, pinned: true, snap: true, // <--- this is required if I want the application bar to show when I scroll up bottom: new TabBar( tabs: [ ... ], // <-- total of 2 tabs ), ), ]; }, body: new TabBarView( children: [ ... ] // <--- the array item is a ListView ), ), ), ), In case it is needed, the full code is in this GitHub repository. main.dart is here. I also found this related question: Hide Appbar on Scroll Flutter?. However, it did not provide the solution. The same problems persist, and when you scroll up, the SliverAppBar will not show. (So snap: true is required) I also found this issue on Flutter's GitHub. (Edit: someone commented that they are waiting for the Flutter team to fix this. Is there a possibility that there is no solution?) This is the output of flutter doctor -v: Pastebin. Certain issues are found, but from what I have learned, they should not have an impact. Edit: There are two issues for this: https://github.com/flutter/flutter/issues/29561 (closed) https://github.com/flutter/flutter/issues/17518 A: You need to use SliverOverlapAbsorber/SliverOverlapInjector, the following code works for me (Full Code): @override Widget build(BuildContext context) { return Material( child: Scaffold( body: DefaultTabController( length: _tabs.length, // This is the number of tabs. child: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { // These are the slivers that show up in the "outer" scroll view. return <Widget>[ SliverOverlapAbsorber( // This widget takes the overlapping behavior of the SliverAppBar, // and redirects it to the SliverOverlapInjector below. If it is // missing, then it is possible for the nested "inner" scroll view // below to end up under the SliverAppBar even when the inner // scroll view thinks it has not been scrolled. // This is not necessary if the "headerSliverBuilder" only builds // widgets that do not overlap the next sliver. handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), child: SliverSafeArea( top: false, sliver: SliverAppBar( title: const Text('Books'), floating: true, pinned: true, snap: false, primary: true, forceElevated: innerBoxIsScrolled, bottom: TabBar( // These are the widgets to put in each tab in the tab bar. tabs: _tabs.map((String name) => Tab(text: name)).toList(), ), ), ), ), ]; }, body: TabBarView( // These are the contents of the tab views, below the tabs. children: _tabs.map((String name) { return SafeArea( top: false, bottom: false, child: Builder( // This Builder is needed to provide a BuildContext that is "inside" // the NestedScrollView, so that sliverOverlapAbsorberHandleFor() can // find the NestedScrollView. builder: (BuildContext context) { return CustomScrollView( // The "controller" and "primary" members should be left // unset, so that the NestedScrollView can control this // inner scroll view. // If the "controller" property is set, then this scroll // view will not be associated with the NestedScrollView. // The PageStorageKey should be unique to this ScrollView; // it allows the list to remember its scroll position when // the tab view is not on the screen. key: PageStorageKey<String>(name), slivers: <Widget>[ SliverOverlapInjector( // This is the flip side of the SliverOverlapAbsorber above. handle: NestedScrollView.sliverOverlapAbsorberHandleFor( context), ), SliverPadding( padding: const EdgeInsets.all(8.0), // In this example, the inner scroll view has // fixed-height list items, hence the use of // SliverFixedExtentList. However, one could use any // sliver widget here, e.g. SliverList or SliverGrid. sliver: SliverFixedExtentList( // The items in this example are fixed to 48 pixels // high. This matches the Material Design spec for // ListTile widgets. itemExtent: 60.0, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { // This builder is called for each child. // In this example, we just number each list item. return Container( color: Color((math.Random().nextDouble() * 0xFFFFFF) .toInt() << 0) .withOpacity(1.0)); }, // The childCount of the SliverChildBuilderDelegate // specifies how many children this inner list // has. In this example, each tab has a list of // exactly 30 items, but this is arbitrary. childCount: 30, ), ), ), ], ); }, ), ); }).toList(), ), ), ), ), ); } A: --- EDIT 1 -- Alright so I threw together something quick for you. I followed this article (written by Emily Fortuna who is one of the main Flutter devs) to better understand Slivers. Medium: Slivers, Demystified But then found this Youtube video that basically used your code so I opted for this one, rather than try to figure out every small detail about Slivers. Youtube: Using Tab and Scroll Controllers and the NestedScrollView in Dart's Flutter Framework Turns out you were on the right track with your code. You can use SliverAppBar within NestedScrollView (this wasn't the case last time I tried) but I made a few changes. That I will explain after my code: import 'package:flutter/material.dart'; import 'dart:math'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin /*<-- This is for the controllers*/ { TabController _tabController; // To control switching tabs ScrollController _scrollViewController; // To control scrolling List<String> items = []; List<Color> colors = [Colors.red, Colors.green, Colors.yellow, Colors.purple, Colors.blue, Colors.amber, Colors.cyan, Colors.pink]; Random random = new Random(); Color getRandomColor() { return colors.elementAt(random.nextInt(colors.length)); } @override void initState() { super.initState(); _tabController =TabController(vsync: this, length: 2); _scrollViewController =ScrollController(); } @override void dispose() { super.dispose(); _tabController.dispose(); _scrollViewController.dispose(); } @override Widget build(BuildContext context) { // Init the items for (var i = 0; i < 100; i++) { items.add('Item $i'); } return SafeArea( child: NestedScrollView( controller: _scrollViewController, headerSliverBuilder: (BuildContext context, bool boxIsScrolled) { return <Widget>[ SliverAppBar( title: Text("WhatsApp using Flutter"), floating: true, pinned: false, snap: true, bottom: TabBar( tabs: <Widget>[ Tab( child: Text("Colors"), ), Tab( child: Text("Chats"), ), ], controller: _tabController, ), ), ]; }, body: TabBarView( controller: _tabController, children: <Widget>[ ListView.builder( itemBuilder: (BuildContext context, int index) { Color color = getRandomColor(); return Container( height: 150.0, color: color, child: Text( "Row $index", style: TextStyle( color: Colors.white, ), ), ); }, //physics: NeverScrollableScrollPhysics(), //This may come in handy if you have issues with scrolling in the future ), ListView.builder( itemBuilder: (BuildContext context, int index) { return Material( child: ListTile( leading: CircleAvatar( backgroundColor: Colors.blueGrey, ), title: Text( items.elementAt(index) ), ), ); }, //physics: NeverScrollableScrollPhysics(), ), ], ), ), ); } } Alright so on to the explanation. Use a StatefulWidget Most widgets in Flutter are going to be stateful but it depends on the situation. I think in this case it is better because you are using a ListView which could change as users add or erase conversations/chats. SafeArea because this widget is great. Go read about it on Flutter Docs: SafeArea The Controllers I think this was the big issue at first but maybe it was something else. But you should usually make your own controllers if you are dealing with custom behavior in Flutter. So I made the _tabController and the _scrollViewController (I don't think I got every bit of functionality out of them, i.e. keeping track of scroll positions between tabs, but they work for the basics). The tab controller that you use for the TabBar and the TabView should be the same. The Material Widget before the ListTile You probably would have found this out sooner or later but the ListTile widget is a Material widget and therefore requires a "Material ancestor widget" according to the output I got while trying to render it at first. So I saved you a tiny headache with that. I think it is because I didn't use a Scaffold. (Just keep this in mind when you use Material widgets without Material ancestor widgets) Hope this helps you get started, if you need any assistance with it just message me or add me to your Github repo and I'll see what I can do. --- ORIGINAL --- I answered you on Reddit as well, hopefully you see one of these two soon. SliverAppBar Info The key properties you want to have with the SliverAppBar are: floating: Whether the app bar should become visible as soon as the user scrolls towards the app bar. pinned: Whether the app bar should remain visible at the start of the scroll view. (This is the one you are asking about) snap: If snap and floating are true then the floating app bar will "snap" into view. All this came from the Flutter SliverAppBar Docs. They have lots of animated examples with different combos of floating, pinned and snap. So for yours the following should work: SliverAppBar( title: Text("Application"), floating: true, // <--- this is required if you want the appbar to come back into view when you scroll up pinned: false, // <--- this will make the appbar disappear on scrolling down snap: true, // <--- this is required if you want the application bar to 'snap' when you scroll up (floating MUST be true as well) bottom: new TabBar( tabs: [ ... ], // <-- total of 2 tabs ), ), ScrollView with SliverAppBar To answer the underlying question of the NestedScrollView. According to the docs (same as above) a SliverAppBar is: A material design app bar that integrates with a CustomScrollView. Therefore you cannot use a NestedScrollView you need to use a CustomScrollView. This is the intended use of Sliver classes but they can be used in the NestedScrollView Check out the docs.
{ "pile_set_name": "StackExchange" }
Q: Is there a practical difference between [electoral-system] and [voting-systems]? electoral-system - 10 Qs, no excerpt voting-systems - 132 Qs with this excerpt For questions about rule systems for gathering and counting votes. Not for questions about country-specific rules but for the theory and practice of voting systems. Examples include proportional-representation and first-past-the-post. I'm thinking the two tags really mean the same thing, but, ironically, the latter is being misused. electoral-system is clear we're talking about the mechanism by which officials are elected. voting-systems sounds like it could be used to describe the system by which ballots are cast and counted . I would say it needs to be a synonym of electoral-system for disambiguation. A: A difference could be created, but doesn't exist in current usage The most natural distinction to apply comes from the excerpt for voting-systems which states that it is "Not for questions about country-specific rules". A natural conclusion is that a different tag could exist for country-specific rules, and electoral-system seems suitable to me. However, current use of the tags doesn't support that distinction. Right now, questions about voting/election theory and questions about country-specific voting/election systems exist in significant numbers in each tag. Trying to create such a distinction would split both tags and require a lot of manual retagging. Instead I think it's appropriate to simply unify the tags. In terms of which tag should be the "main" one and which should be the synonym, I would usually go with leaving the more popular tag and making the other a synonym, but in this case I have a slight preference for electoral-system. The main reason is that the Wikipedia page for "Voting system", which is currently linked on the voting-systems info page, redirects to the "Electoral System" page; Wikipedia isn't an authority on the subject, but it would be nice for the tag names to reflect the concepts we link to describe them. It's only a slight preference though. I would also remove the "Not about country-specific rules" part of the usage guide. TL;DR The tags are the same in current usage, and merging them seems more beneficial than creating an artificial divide.
{ "pile_set_name": "StackExchange" }
Q: Exception in thread "AWT-EventQueue-0" - maven/gradle Here's code: private whateva loadImage() throws IOException { whateva img = ImageIO.read(getClass().getResource("/images/1.jpg")); return img; } And here's what I get: Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null! Screen of the project's files/packages: Have no idea what is wrong, tried to relocate image to other folders and still haven't worked out. What is more funny - when I compile it in NetBeans, it works. But when I try to compile this as a Maven or Gradle project, I've got this problem. A: There is obviously some difference between how the resource file is loaded between Netbeans and Maven/Gradle. You have to put your file in src/main/resources/images/1.jpg and it should work, unless you have some broken Maven/Gradle configuration or you are trying to run outside of a built jar file.
{ "pile_set_name": "StackExchange" }
Q: Include manually-added lines to ggplot2 guide legend This is question that's been asked many times, I know, but I still can't figure out a good answer. I would like to get a pretty legend that shows manually-added lines in a separate legend on the plot. Here's what I've figured out so far: library(ggplot2) data(mtcars) ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) + theme_bw() + geom_point() + geom_smooth(method = 'lm', se=FALSE) + geom_abline(aes(intercept=40, slope = (-1/10))) + geom_abline(aes(intercept=25, slope = (-1/30))) gives: which has manually-added lines, but no legend entry for them. Attempt 1 Just adding show.legend=TRUE isn't very helpful: ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) + theme_bw() + geom_point() + geom_smooth(method = 'lm', se=FALSE) + geom_abline(aes(intercept=40, slope = (-1/10)), show.legend = TRUE) + geom_abline(aes(intercept=25, slope = (-1/30)), show.legend = TRUE) Attempt 2 Adding an artificial fill for each additional line isn't very helpful, either: ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) + theme_bw() + geom_point() + geom_smooth(method = 'lm', se=FALSE) + geom_abline(aes(intercept=40, slope = (-1/10), fill='Comparison Line 1')) + geom_abline(aes(intercept=25, slope = (-1/30), fill='Comparison Line 2')) it just gives a warning and returns the original plot: Warning: Ignoring unknown aesthetics: fill Warning: Ignoring unknown aesthetics: fill Attempt 3 Adding both show.legend=TRUE and a fake aes fill gets close, but the result is very ugly: ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) + theme_bw() + geom_point() + geom_smooth(method = 'lm', se=FALSE) + geom_abline(aes(intercept=40, slope = (-1/10), fill='Comparison Line 1'), show.legend = TRUE) + geom_abline(aes(intercept=25, slope = (-1/30), fill='Comparison Line 2'), show.legend = TRUE) Finally, my question: How do I get rid of the diagonal lines in the color legend (titled "factor(am)"), and how do I get normal-looking lines next to the items in the fill legend (titled "fill")? A: You were very close! Add dummy variable that is relevant to geom_abline for example size to aes(). And scale size back using scale_size_manual. library(ggplot2) ggplot(mtcars, aes(x=disp, y=mpg, color=factor(am))) + theme_bw() + geom_point() + geom_smooth(method = 'lm', se=FALSE) + geom_abline(aes(intercept=40, slope = (-1/10), size='Comparison Line 1')) + geom_abline(aes(intercept=25, slope = (-1/30), size='Comparison Line 2')) + scale_size_manual(values = c(0.3, 0.3)) PS.: Fill that you were using is unknown aesthetics for the abline (as ggplot2 warns you: Warning: Ignoring unknown aesthetics: fill).
{ "pile_set_name": "StackExchange" }
Q: Question marked as inappropriate and closed The following question has been closed and has been marked as inappropriate for this forum. Free online study materials and codes for Monte Carlo simulation in statistical mechanics But this question can be immensely helpful to students who work in this field of Monte Carlo simulation in statistical physics. For example, a similar and very useful question is this one .. List of freely available physics books, which was not marked as inappropriate. There is another user who also opposes the moderator's decision and posted comments in support of the question. I request you to reconsider your decision. Thanks. A: The book question has been grandfathered in, that's all. Otherwise such questions are more or less off topic. Recommendation questions are off topic network wide (some reasons are given here -- basically they have caused problems in the past) Physics.SE does not try to be a resource for everything useful for physics students. We try to focus on closed-ended, conceptual questions here. You may want to try Quora or a similar website for that question. A: Yes, I do not agree with the reference request/books/study material policy here either, but unfortunately nothing can be done about it. Reference requests should in principle be allowed whereas asking for books is absolutely not, but the definitions of what is a book or valid reference request are applied in a random and unpredictable manner. Valid reference request questions can get retagged and closed as book requests etc. It is a big shame that serious people are (no longer) allowed to ask for any material to (self) study/research physics of more or less advanced and well localized topics at different levels.
{ "pile_set_name": "StackExchange" }
Q: Android NumberPicker without blinking cursor I'm using the NumberPicker under the Android SDK level 13 inside a fragment. Works fine, but each time the activity is started the cursor is blinking behind the number. How can I get rid of the blinking cursor, I don't know why this widget has the focus. This is the xml of the NumberPicker: <NumberPicker android:id="@+id/timer_picker_hrs" android:layout_width="wrap_content" android:layout_height="wrap_content" /> A: I get this solution from somewhere but I don't remember from where. This works good for me, just do this in your activity. myNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); You can also set this in XML: android:descendantFocusability="blocksDescendants" (Borzh comment)
{ "pile_set_name": "StackExchange" }