instruction
stringlengths
22
34.6k
input
stringclasses
1 value
output
stringlengths
70
4.33k
Failed to load resource: the server responded with a status of 401 (Unauthorized) /App/AngularJS/angular.min.js <sep> I am having the following error: <code>Failed to load resource: the server responded with a status of 401 (Unauthorized) http://localhost/App/AngularJS/angular.min.js </code> The project works fine on localhost. But when I run it on IIS (7.5) I get the above exception. [Image] My project is .net 4.5 project (Web.API 2.2), I am using AngularJS for UI in this project. I have tried running "aspnet_regiis - i" as somewhere this was accepted as solution. But it didn't work in my case. I don't know is there any thing required to execute [AngularJS].js files on IIS for Web.API project? EDIT: I have made following changes to web.config file: <code><location path="AngularJS"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location> <system.web> <authorization> <allow users="*" /> </authorization> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> </code> Also I have set the read/write/modify access for "IUSR" & "IIS_ISURS" users of whole project. But still I get the same exception on IIS. But same running fine with VS2013. Error:
When servers respond with an "access denied" message (401 Unauthorized access), it means the anonymous IIS user account is unable to access resources due to permission issues. By default, the IUSR account is used for anonymous users. All you need to do is: IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity. Problem solved!
Python Django : No module named security <sep> When I deploy my project on an Ubuntu Server, using a virtualenv, I got this error : <code>[17/Sep/2014 22:29:00] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/zat42/myproject/monarch/env/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 64, in __call__ return self.application(environ, start_response) File "/home/zat42/myproject/monarch/env/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 168, in __call__ self.load_middleware() File "/home/zat42/myproject/monarch/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 44, in load_middleware mw_class = import_string(middleware_path) File "/home/zat42/myproject/monarch/env/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named security </code> I don't know why there is this error my configuration works fine with a fresh install... But when I copy my current project, I got Error 500. I tried to deploy "part after part" but I can't find what's wrong. Tell me if you need more of my files because I don't really know where is the problem... Thank you.
I met the same problem. Finally, I found that I was using Django 1.7.1 to run a 1.8dev generated project. When I switched back to 1.7.1 and removed `django.middleware.security.SecurityMiddleware` in `setting.py`, it seems ok.
How to get topic list from kafka server in Java <sep> I am using <code>kafka 0.8</code> version and very much new to it. I want to know the list of topics created in <code>kafka server</code> along with it's metadata. Is there any API available to find out this? Basically, I need to write a Java consumer that should auto-discover any topic in <code>kafka server</code>.There is API to fetch <code>TopicMetadata</code>, but this needs name of topic as input parameters.I need information for all topics present in server.
With Kafka 0.9.0, you can list the topics in the server with the provided consumer method `listTopics()`; e.g., ```java Map<String, List<PartitionInfo>> topics; Properties props = new Properties(); props.put("bootstrap.servers", "1.2.3.4:9092"); props.put("group.id", "test-consumer-group"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); topics = consumer.listTopics(); consumer.close(); ```
Git Giving "fetch first" error when trying to push <sep> I am having my first introduction to git through a class I am taking. I have a number of files in a directory on my computer and am able to stage and commit them without a problem. However, when I try to push files to my github repository, I keep on getting this message: <code>Pushing to https://github.com/BigMeanCat/CMDA To https://github.com/BigMeanCat/CMDA ! [rejected] master -> master (fetch first) error: failed to push some refs to 'https://github.com/BigMeanCat/CMDA' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. </code> Can anybody help me out with what this means and how to fix it? I've seen a few people with similar problems online, but I am BRAND NEW to git and not familiar enough with git's command line language yet. I'm a little hesitant to take certain suggestions, as I don't know whether it will solve the problem or make it worse. Thanks!
Someone else (or you on some other machine) has pushed a changeset to the remote repository. You, on your local machine, don't have those changes yet. So to solve the situation, you first have to `git pull` and then `git push`. However, you won't be able to `git pull` while you have changes in your working tree, so before you pull/push, you first have to `commit` or `stash` your local changes. This potentially might bring up a merge situation if remote changes overlap with your local ones.
summarizing counts of a factor with dplyr <sep> I want to group a data frame by a column (owner) and output a new data frame that has counts of each type of a factor at each observation. The real data frame is fairly large, and there are 10 different factors. Here is some example input: <code>library(dplyr) df = tbl_df(data.frame(owner=c(0,0,1,1), obs1=c("quiet", "loud", "quiet", "loud"), obs2=c("loud", "loud", "quiet", "quiet"))) owner obs1 obs2 1 0 quiet loud 2 0 loud loud 3 1 quiet quiet 4 1 loud quiet </code> I was looking for output that looks like this: <code>out = data.frame(owner=c("0", "0", "1", "1"), observation=c("obs1", "obs2", "obs1", "obs2"), quiet=c(1, 0, 1, 2), loud=c(1, 2, 1, 0)) owner observation quiet loud 1 0 obs1 1 1 2 0 obs2 0 2 3 1 obs1 1 1 4 1 obs2 2 0 </code> Melting gets me partway there: <code>melted = tbl_df(melt(df, id=c("owner"))) owner variable value 1 0 obs1 quiet 2 0 obs1 loud 3 1 obs1 quiet 4 1 obs1 loud 5 0 obs2 loud 6 0 obs2 loud 7 1 obs2 quiet 8 1 obs2 quiet </code> But what's the last step? If 'value' was a numeric, I'd just go: <code>melted %>% group_by(owner, variable) %>% summarise(counts=sum(value)) </code> Thanks so much!
In 2017 the answer is ```R library(dplyr) library(tidyr) gather(df, key, value, -owner) %>% group_by(owner, key, value) %>% tally() %>% spread(value, n, fill = 0) ``` Which gives output: ``` Source: local data frame [4 x 4] Groups: owner, key [4] owner key loud quiet * <dbl> <chr> <dbl> <dbl> 1 0 obs1 1 1 2 0 obs2 2 0 3 1 obs1 1 1 4 1 obs2 0 2 ``` In 2019 the answer is: ```R gather(df, key, value, -owner) %>% count(owner, key, value) %>% spread(value, n, fill = 0) ```
Attribute Unavailable warning on iOS versions prior to 8.0 <sep> What's causing this warning in the interface builder? Attribute Unavailable Layout attributes relative to the layout margin on iOS versions prior to 8.0. I'm using the XCode 6 Beta. The warnings are pointing to lines in the xml source that do not concern attributes.
Since I had already created the constraints, the answer was to click on the constraint and then look in the Utilities bar (on the right). As shown in the picture below, click on an item and then make sure "relative to margin" is unchecked.
Specflow test step inheritance causes "Ambiguous step definitions" <sep> I want to have the following test step class structure: <code>[Binding] public class BaseStep { [Given(@"there is a customer")] public void GivenThereIsACustomer(Table table) { HandleCustomer(table); } protected virtual void HandleCustomer(Table table) { } } [Binding] public class FeatureOneStep : BaseStep { protected override void HandleCustomer(Table table) { // feature one action } [Given(@"feature one specific step")] public void GivenFeatureOneSpecificAction(Table table) { // do something } } [Binding] public class FeatureTwoStep : BaseStep { protected override void HandleCustomer(Table table) { // feature two action } [Given(@"feature two specific step")] public void GivenFeatureTwoSpecificAction(Table table) { // do something } } </code> "Given there is a customer" is a common step that is used in both FeatureOne and FeatureTwo, but it will have different handling logic inside the two features. So I decide to put this step definition into a base class and override the protected methods in two derived classes respectively. However, when I ran the tests, I have the following error: <code>TechTalk.SpecFlow.BindingException: Ambiguous step definitions found for step 'Given there is a customer': CustomerTestBase.GivenThereIsACustomer(Table), CustomerTestBase.GivenThereIsACustomer(Table) </code> Can any one tell me how to fix this issue?
Just figuring this out now myself, so a couple of notes (hopefully somebody can use this in the future): * Don't include the [Binding] attribute on the base class. * Create a derived class for each feature file. * Add the [Binding] attribute to the derived class (this will automatically include all step definitions in the base class). * Add a [Scope] attribute to the derived class; specify the name of the feature for the named parameter "Feature".
Eclipse: JVM terminated. Exit code=2 <sep> I recently decided to start trying Android app development, so I downloaded the Java SE Development Kit 8 (x86) for Windows (I got Windows 8 64bit, but my guide recommends getting the 32bit one), the Android SDK, and the Eclipse IDE for Java Developers (x86). However, my Eclipse won't launch when I double click eclipse.exe! Instead, I get the following error message: I tried adding Java to my Path variable in my Environment variables as suggested in some of the solutions I looked up, but it still doesn't launch properly. Anyone know what else I can try? Also, if possible, please do not use super-technical vocabulary as I'm new to these kinds of stuff and will not understand you...thank you haha :D
I had the same issue and was trying to install different versions of JDK: 1.6, 1.7, 1.8. It didn't help much. The problem was resolved when I changed the PATH variable by removing `C:\ProgramData\Oracle\Java\javapath;`. In the command prompt, I also ran the following commands: `set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25` `set PATH=C:\Program Files\Java\jdk1.8.0_25\bin;%PATH%` But I think the most important step was removing `C:\ProgramData\Oracle\Java\javapath;` from the PATH.
Subversion in Intellij keeps asking for authentication <sep> I hope someone can help me solve this frustrating issue that I am having. I am trying to checkout a project from subversion but for some reason it doesn't let me. At first when I put the URL, it gives me options such as whether I want to authenticate via password,ssh agent or ssh key etc. I choose the authentication with password option. At this stage the login is successful as I can browse my repository. However, when I go to checkout a project from my repository, it asks for authentication again; I input the password but it keeps asking for the password again The following window keeps popping. I have tried the following solution without success: Cleared the authentication cache from the intellij subversion settings. Uninstalled and installed intellij again Found online that the following line might help if added to idea.exe.vmoptions <code>-Dsvnkit.http.methods=Basic,Digest,NTLM</code> but this didn't work either. Any advice?
In IntelliJ, the problem can be solved using the following steps for the following versions: **IntelliJ 2018.1:** Go to `Settings -> Version Control -> Subversion` and check the option `Enable interactive mode`. **IntelliJ 14:** Go to `Settings -> Version Control -> Subversion` and uncheck the option `Use command line client`.
Java - Filtering List Entries by Regex <sep> My code looks like this: <code>List<String> filterList(List<String> list, String regex) { List<String> result = new ArrayList<String>(); for (String entry : list) { if (entry.matches(regex)) { result.add(entry); } } return result; } </code> It returns a list that contains only those entries that match the <code>regex</code>. I was wondering if there was a built in function for this along the lines of: <code>List<String> filterList(List<String> list, String regex) { List<String> result = new ArrayList<String>(); result.addAll(list, regex); return result; } </code>
In addition to Konstantin's answer: Java 8 added `Predicate` support to the `Pattern` class via `asPredicate`, which calls `Matcher.find()` internally: `Pattern pattern = Pattern.compile("..."); List<String> matching = list.stream() .filter(pattern.asPredicate()) .collect(Collectors.toList());` Pretty awesome!
How to return xml as UTF-8 instead of UTF-16 <sep> I am using a routine that serializes <code><T></code>. It works, but when downloaded to the browser I see a blank page. I can view the page source or open the download in a text editor and I see the xml, but it is in UTF-16 which I think is why browser pages show blank? How do I modify my serializer routine to return UTF-8 instead of UTF-16? The XML source returned: <code><?xml version="1.0" encoding="utf-16"?> <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <string>January</string> <string>February</string> <string>March</string> <string>April</string> <string>May</string> <string>June</string> <string>July</string> <string>August</string> <string>September</string> <string>October</string> <string>November</string> <string>December</string> <string /> </ArrayOfString> </code> An example call to the serializer: <code>DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo(); var months = dateTimeFormatInfo.MonthNames.ToList(); string SelectionId = "1234567890"; return new XmlResult<List<string>>(SelectionId) { Data = months }; </code> The Serializer: <code>public class XmlResult<T> : ActionResult { private string filename = DateTime.Now.ToString("ddmmyyyyhhss"); public T Data { private get; set; } public XmlResult(string selectionId = "") { if (selectionId != "") { filename = selectionId; } } public override void ExecuteResult(ControllerContext context) { HttpContextBase httpContextBase = context.HttpContext; httpContextBase.Response.Buffer = true; httpContextBase.Response.Clear(); httpContextBase.Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".xml"); httpContextBase.Response.ContentType = "text/xml"; using (StringWriter writer = new StringWriter()) { XmlSerializer xml = new XmlSerializer(typeof(T)); xml.Serialize(writer, Data); httpContextBase.Response.Write(writer); } } } </code>
```csharp public class Utf8StringWriter : StringWriter { // Use UTF8 encoding but write no BOM to the wire public override Encoding Encoding { get { return new UTF8Encoding(false); } // in real code I'll cache this encoding. } } using (StringWriter writer = new Utf8StringWriter()) { XmlSerializer xml = new XmlSerializer(typeof(T)); xml.Serialize(writer, Data); httpContextBase.Response.Write(writer); } ```
How to check if a file is a valid image? <sep> I am building a web application. On one of the pages there is an upload form, where user can upload a file. After the upload is done, I want to check on the server if the uploaded file is an image. Is it possible to check this beyond simple file extension checking (i.e.not assuming that a <code>*.png</code> filename is actually a PNG image)? For example, if I edit a JPEG image adding/editing a byte in a random place to make an invalid JPEG file, I want to detect that it is not a JPEG image anymore. I used to do such type of thing via PHP some time ago, using a GD library. I would like to know if it is possible to do with Go?
DetectContentType is way better than manual magic number checking. The use is simple: ``` clientFile, _, _ := r.FormFile("img") // or get your file from a file system defer clientFile.Close() buff := make([]byte, 512) // Docs tell that it takes only the first 512 bytes into consideration if _, err := clientFile.Read(buff); err != nil { fmt.Println(err) // do something with that error return } fmt.Println(http.DetectContentType(buff)) // do something based on your detection. ``` Using this method, you need to know that you are still not guaranteed to have a correct file. So I would recommend doing some image manipulation with that file (like resizing it) to make sure it is really an image.
Git GUI Crash Signal 6 <sep> I am using git version 1.9.2 with Xcode6-Beta3. At beginning, git gui works properly. For some reason (which I don't know...) when typing "git gui" on Terminal, I got the following crash message: * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error (1000) creating window shape' SOME CALL STACK INFO libc++abi.dylib: terminating with uncaught exception of type NSException error: git-gui died of signal 6 Most suggestions I found are about "git-gui died of signal 11". Please let me know if any suggestion or question. Thank you for precious time on my question (or crash)
This appears to happen when Git GUI can't create the window in its last position. In my case, it is because the window location is negative. I have multiple monitors, one of which is to the upper left of the primary. You can unset it with this: `git config --local --unset gui.geometry`. The other answer "works" because it doesn't take the config into account. It avoids the issue, but doesn't actually fix it.
Can't open cygwin terminal after installation <sep> I just installed cygwin in my windows7 pc. After installation when i click on 'Cygwin Terminal' from start menu it shows a message like this - message title: Missing Shortcut "Windows is searching for mintty. To locate the file yourself, click Browse" with two buttons below "Browse" and "Cancel". Then if I select mintty.exe manually from "C:\cygwin\bin" by clicking Browse button it doesn't load anything. How can I be get rid of this?
Open the Cygwin Terminal properties (by right-clicking the icon and going to properties), check the path of 'mintty'. If everything looks right and it is still giving an error, change 'mintty' to 'mintty.exe'. This solved my problem.
Swift NSImage to CGImage <sep> How can I convert a NSImage to CGImage in Swift? In Objective-C I did it like this: <code>- (CGImageRef)CGImage { NSData *imageData = self.TIFFRepresentation; CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); CGImageRef maskRef = CGImageSourceCreateImageAtIndex(source, 0, NULL); return maskRef; } </code> Now I tried with: <code>extension NSImage { var CGImage: CGImageRef { get { let imageData = self.TIFFRepresentation let source = CGImageSourceCreateWithData(imageData as CFDataRef, nil) let maskRef = CGImageSourceCreateImageAtIndex(source, UInt(0), nil) return maskRef; } } } </code> I can't compile, I'm getting the error: <code>Could not find an overload for 'init' that accepts the supplied arguments'</code> at the line <code>let maskRef ...</code>
```swift let image = NSImage(named: "image") if let image = image { var imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil) } ```
MongoDB: how to find 10 random document in a collection of 100? <sep> Is MongoDB capable of funding number of random documents without making multiple queries? e.g. I implemented on the JS side after loading all the document in the collection, which is wasteful - hence just wanted to check if this can be done better with one db query? The path I took on the JS side: get all data make an array of the IDs shuffle array of IDs (random order) splice the array to the number of document required create a list of document by selecting them by ID which we have left after two previous operations, one by one from the whole collection Two major drawback are that I am loading all data - or I make multiple queries. Any suggestion much appreciated
Since 3.2, there is an easier way to get a random sample of documents from a collection: > $sample New in version 3.2. Randomly selects the specified number of documents from its input. The $sample stage has the following syntax: > > ``` > { $sample: { size: <positive integer> } } > ``` Source: MongoDB Docs In this case: ```javascript db.products.aggregate([{$sample: {size: 10}}]); ```
I broke my Laravel framework with migration renaming <sep> I had a good working Laravel structure with database migrations and seeding. But I wanted my migration file,classes,db table be renamed to CreateOrganizationsTable instead of CreateOrganisationsTable So I changed the migration filename, all classes and routes. But when I execute <code>php artisan migrate:reset</code> in my Homestead box, I get the following error: <code>PHP Fatal error: Class 'CreateOrganisationsTable' not found in /home/vagrant/Code/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php on line 299 </code> Artisan created some link I'm unable to fix at the moment.
As Morale mentioned, you must reset or rollback to a point before your new migration or make the changes manually. I knew this but was still getting the problem after changing only the timestamps to have the migrations run in a different order. You must run `composer dump-autoload` even if you didn't change the class name.
Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web modules <sep> I'm trying to deploy a very simple HTTPServlet project using Tomcat 7 in my Eclipse J2EE perspective. I am getting the error "Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web modules". I have already tried modifying my org.eclipse.wst.common.project.facet.core.xml as mentioned here file but that doesn't seem to fix the issue. I'm able to deploy just fine by using file->export->.war directly to my installed tomcat server. Any ideas?
Go to Project Properties -> Project Facets and change the version of Dynamic Web Module. If it is set to 3.1, change it to 3.0. If it does not allow you to change the version, uncheck it, press Apply, then select the version, check it, and Apply-OK. Worked for me!
How to do blending in LibGDX <sep> I basically want to play around with blending modes in LibGDX but don't know how to do it. I found this image on internet. I want to do the same thing on LibGDX. Can someone teach me how. I've been playing around using Scene2D. Here's my non-working snippet. <code>private class MyGroup extends Group { Image red, blue; public MyGroup() { Texture texture = new Texture(Gdx.files.internal("images/red.png")); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); red = new Image(texture); texture = new Texture(Gdx.files.internal("images/blue.png")); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); blue = new Image(texture); red.setX(-25); blue.setX(25); } @Override public void draw(Batch batch, float parentAlpha) { batch.end(); batch.begin(); batch.enableBlending(); red.draw(batch, parentAlpha); Gdx.gl.glEnable(Gdx.gl20.GL_BLEND); Gdx.gl.glBlendFuncSeparate( Gdx.gl20.GL_DST_COLOR, Gdx.gl20.GL_SRC_COLOR, Gdx.gl20.GL_ONE, Gdx.gl20.GL_ONE); blue.draw(batch, parentAlpha); } } </code>
I realize this is not a new question, but I thought I would share some information for anyone else who makes it to this question/answer without knowing much about rendering in OpenGL. (Knowing these terms helps a lot so you aren't just guessing and mixing and matching.) Note that this site is how I learned most of this myself, so more complete information can be found there. **Destination Color:** the color in the buffer, which will (eventually) be drawn unless it is modified or overwritten with new values. **Source Color:** the color coming in from additional rendering commands, which may or may not interact with the destination color (depending on our settings). The default blending equation is: **Final Color = (SourceColor * SourceBlendingFactor) + (DestinationColor * DestinationBlendingFactor)** (This default equation can be changed, but I recommend reading my source link at the top for more information on that.) The two BlendingFactors are what we can adjust. We can set them to: * **GL_ZERO:** RGB(0,0,0) A(0) * **GL_ONE:** RGB(1,1,1) A(1) * **GL_SRC_COLOR:** RGB(sourceR, sourceG, sourceB) A(sourceA) * **GL_ONE_MINUS_SRC_COLOR:** RGB(1-sourceR, 1-sourceG, 1-sourceB) A(1-sourceA) * **GL_DST_COLOR:** RGB(destinationR, destinationG, destinationB) A(destinationA) * **GL_ONE_MINUS_DST_COLOR:** RGB(1-destinationR, 1-destinationG, 1-destinationB) A(1-destinationA) * **GL_SRC_ALPHA:** RGB(sourceA, sourceA, sourceA) A(sourceA) * **GL_ONE_MINUS_SRC_ALPHA:** RGB(1-sourceA, 1-sourceA, 1-sourceA) A(1-sourceA) * **GL_DST_ALPHA:** RGB(destinationA, destinationA, destinationA) A(destinationA) * **GL_ONE_MINUS_DST_ALPHA:** RGB(1-destinationA, 1-destinationA, 1-destinationA) A(1-destinationA) * **GL_SRC_ALPHA_SATURATE:** RGB(min(sourceA, 1-destinationA), min(sourceA, 1-destinationA), min(sourceA, 1-destinationA)) A(1) The following also uses some predefined constant colors; by default, it is black. * **GL_CONSTANT_COLOR:** RGB(constantR, constantG, constantB) A(constantA) * **GL_ONE_MINUS_CONSTANT_COLOR:** RGB(1-constantR, 1-constantG, 1-constantB) A(1-constantA) * **GL_CONSTANT_ALPHA:** RGB(constantA, constantA, constantA) A(constantA) * **GL_ONE_MINUS_CONSTANT_ALPHA:** RGB(1-constantA, 1-constantA, 1-constantA) A(1-constantA) So all of these are just predefined float values that are being multiplied with either our source or destination, and then added to the other. The easiest to observe from the image is GL_ZERO and GL_ONE. We end up with whichever image has the ONE. **Understanding GL_ZERO with GL_DST_COLOR** When GL_ZERO is on the destination, we are ignoring any color information currently in the buffer (because multiplying everything by zero). However, with GL_DST_COLOR also on the source image, we end up multiplying the r, g, b, a values of the source and destination. This looks good in the image because of the nature of the example images. One acts as a solid color image, while the other grayscale image looks and acts almost like a beam of light to "reveal" the color out from our GL_ZERO setting. Hopefully, this helps explain the images we can see above and helps everyone understand how those images are actually being blended together.
How to provide default value for a parameter of delegate type in C#? <sep> In C# we can provide default value of the parameters as such: <code>void Foo(int i =0) {} </code> But, when the method signature is: <code>void FooWithDelegateParam(Func<string,string> predicate) {} </code> How can we pass the default parameter: <code>void FooWithDelegateParam(Func<string,string> predicate = (string,string x)=> {return y;}) {} </code> But this won't compile. So, what is the proper syntax for doing so ? Note: I'm trying to provide a way to specify an input-string to output-string mapper through a delegate, and if not provided I simply want to return the input string. So, suggestions on any alternative approach to achieve this is highly appreciated as well. Thanks.
You can't, basically. Default values for parameters have to be compile-time constants. However, if you're happy to use `null` as a value meaning "use the default," you could have: ```csharp void FooWithDelegateParam(Func<string, string> predicate = null) { predicate = predicate ?? (x => x); // Code using predicate } ``` Or use an overload, as per Alireza's suggestion, of course. Each option has different implications: * The overload solution works with languages which don't support optional parameters (e.g., C# before 4.0). * The overload solution differentiates between `null` and "the default." This in itself has pros and cons: * If the caller should never provide a `null` value, the overload version can find bugs where it's accidentally doing so. * If you don't believe there will be any such bugs, the optional parameter version allows the idea of "the default" to be represented in code. You could pass a `"null" meaning default` value through multiple layers, letting only the bottom-most layer determine what that default actually means, and do so more simply than having to explicitly call different overloads. * The optional parameter version is simpler to express in an interface... ...with the downside that the default value would still need to be expressed in the implementation. (This is somewhat common to the overload solution, mind you... in both cases, an abstract class implementing the interface could do the defaulting using the template method pattern.)
HATEOAS methods not found <sep> My controller can't seem to find the HATEOAS methods like "linkTo". Am I missing something? pom.xml <code><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>provider</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Security --> <!-- Auto configured, remove dependencies to disable. --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> </dependency> <!-- OAuth 2.0 --> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test-mvc</artifactId> <version>1.0.0.M2</version> <scope>test</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!-- Spring MongoDB --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> </dependency> <!-- Spring REST MVC --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-rest-webmvc</artifactId> </dependency> <!-- Dozer: DTO/Entity Mapper --> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.3.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency> </dependencies> <properties> <start-class>com.provider.core.Application</start-class> </properties> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <url>http://repo.spring.io/libs-snapshot</url> <snapshots><enabled>true</enabled></snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/libs-snapshot</url> <snapshots><enabled>true</enabled></snapshots> </pluginRepository> </pluginRepositories> </project> </code> Controller <code>package com.provider.core; import org.dozer.DozerBeanMapper; import org.dozer.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.provider.account.Account; import com.provider.account.AccountDTO; @Controller public class AccountController { private static final Logger logger = LoggerFactory.getLogger(AccountController.class); @Autowired private AccountRepository repo; @RequestMapping(value = "account", method = RequestMethod.POST) public @ResponseBody HttpEntity<AccountDTO> createAccount(@RequestBody AccountDTO accountDto) { logger.info("Start createAccount()"); Mapper mapper = new DozerBeanMapper(); Account account = mapper.map(accountDto, Account.class); Account savedAccount = repo.save(account); AccountDTO savedAccountDto = mapper.map(savedAccount, AccountDTO.class); // DOES NOT COMPILE "linkto" not defined. savedAccountDto.add(linkTo(AccountController.class).slash(savedAccountDto.getId()).withSelfRel()); return new ResponseEntity<AccountDTO>(savedAccountDto, HttpStatus.OK); } } </code>
In case you are using HATEOAS v1.0 and above (Spring Boot >= 2.2.0), do note that the class names have changed. Notably, the following classes have been renamed: * `ResourceSupport` changed to `RepresentationModel` * `Resource` changed to `EntityModel` * `Resources` changed to `CollectionModel` * `PagedResources` changed to `PagedModel` * `ResourceAssembler` changed to `RepresentationModelAssembler` More information is available in the official documentation here. When using Spring Boot starter, the following dependency would suffice to include HATEOAS: `<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency>` Hoping this information will help someone like me who searched for hours to find why the `Resource` class was not getting resolved.
Using AudioBufferList with Swift <sep> I have a bridging function in Swift, one of whose arguments in C is <code>AudioBufferList *</code>. In Swift this generates an <code>UnsafePointer<AudioBufferList></code>. I've manage to deference the pointer by calling <code>audioData[0]</code> (is there a better way?). But I'm struggling with the next 2 tiers down: the <code>.mBuffers</code> array of <code>AudioBuffer</code>'s and their <code>void *</code> / <code>UnsafePointer<()></code> <code>.mData</code> members. In C it would simply be <code>Float32 *audioData = (Float 32*)abl->mBuffers[0]->mData; output = audioData[sampleNum]... </code> In Swift the first odd thing is that it won't let me access the elements of <code>mBuffers</code> but is perfectly happy when I access it as a property. In other words, this works and even has correct data (for the first member of <code>mBuffers</code> I presume)... <code>println(abl[0].mBuffers.mNumberChannels) // But .mBuffers should be an []! </code> Second, it let's me print out <code>.mData</code> subscripts but the value is always <code>()</code> <code>println(abl[0].mBuffers.mData[10]) // Prints '()' </code> I've tried various casting ops and accessing with multiple indices but to no avail...any ideas? Here are the C and Swift definitions for <code>AudioBufferList</code> and <code>AudioBuffer</code> for convenience... <code>// C struct AudioBufferList { UInt32 mNumberBuffers; AudioBuffer mBuffers[1]; // this is a variable length array of mNumberBuffers elements // ...and a bit more for c++ } struct AudioBuffer { UInt32 mNumberChannels; UInt32 mDataByteSize; void* mData; }; </code> ... <code>// SWIFT struct AudioBufferList { var mNumberBuffers: UInt32 var mBuffers: (AudioBuffer) } struct AudioBuffer { var mNumberChannels: UInt32 var mDataByteSize: UInt32 var mData: UnsafePointer<()> } </code>
I found this by accident. Oddly, the type ahead was actually working with Swift when it suggested `UnsafeMutableAudioBufferListPointer`. Which you can initialize with an `UnsafeMutablePointer` argument. This type is a `MutableCollectionType` and provides subscript and generator access to the contained Audio Buffers. For example, you can set an ABL to silence with the following code: ```swift func renderCallback(ioData: UnsafeMutablePointer<AudioBufferList>) -> OSStatus { let abl = UnsafeMutableAudioBufferListPointer(ioData) for buffer in abl { memset(buffer.mData, 0, Int(buffer.mDataByteSize)) } return noErr } ```
Remove dtype datetime NaT <sep> I am preparing a pandas df for output, and would like to remove the NaN and NaT in the table, and leave those table locations blank. An example would be <code>mydataframesample col1 col2 timestamp a b 2014-08-14 c NaN NaT </code> would become <code>col1 col2 timestamp a b 2014-08-14 c </code> Most of the values are dtypes object, with the timestamp column being datetime64[ns]. In order to fix this, I attempted to use panda's <code>mydataframesample.fillna(' ')</code> to effectively leave a space in the location. However, this doesn't work with the datetime types. In order to get around this, I'm trying to convert the timestamp column back to object or string type. Is it possible to remove the NaN/NaT without doing the type conversion? If not, how do I do the type conversion (tried str() and astype(str) but difficulty with datetime being the original format)?
I had the same issue: This does it all in place using pandas apply function. Should be the fastest method. ```python import pandas as pd df['timestamp'] = df['timestamp'].apply(lambda x: x.strftime('%Y-%m-%d') if not pd.isnull(x) else '') ``` If your timestamp field is not yet in `datetime` format then: ```python import pandas as pd df['timestamp'] = pd.to_datetime(df['timestamp']).apply(lambda x: x.strftime('%Y-%m-%d') if not pd.isnull(x) else '') ```
How to sort integer list in python descending order <sep> I have tried to figure this out in different ways, to no success. I keep getting ascending order sort, rather than descending order when I print. <code>ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9] sorted(ListB, key=int, reverse=True) print sorted(ListB) </code>
You are printing the list sorted ascending: `print(sorted(ListB))`. If you want it descending, put your print statement on the previous line (where you reverse it): `print(sorted(ListB, key=int, reverse=True))`. Then remove your final print statement. Example: `>>> ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9] >>> print(sorted(ListB, key=int, reverse=True)) [48, 46, 25, 24, 22, 13, 8, -9, -15, -36] `
debugging plunker in chrome developer tools <sep> I created a javascript file in Plunker and I want to debug it. When I open 'Sources' panel, I don't see js file that I created. I only see plenty of Plunker js files. Please advice. Thanks
Another way is to put this in your JavaScript file: `debugger;` and leave the console open, which will force the debugger to not only stop there but also open the file.
How can I access my ViewModel from code behind <sep> I don't understand how I can create a command to create a MVVM clickable rectangle. Here is my code: <code><Rectangle x:Name="Color01" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="10,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100" MouseDown="Color_MouseDown" /> <Rectangle x:Name="Color02" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="115,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/> <Rectangle x:Name="Color03" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="220,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/> <Rectangle x:Name="Color04" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="100" Margin="325,29,0,0" Stroke="Black" VerticalAlignment="Top" Width="100"/> </code> On my first rectangle you can see I created a code behind event. First I don't know how to access my ViewModel from the code behind. Two it's not really MVVM. <code>public partial class MainWindow : Window { /// <summary> /// Initializes a new instance of the MainWindow class. /// </summary> public MainWindow() { InitializeComponent(); Closing += (s, e) => ViewModelLocator.Cleanup(); } private void Color_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { // So what ??? } } </code> I just need to be able to change a simple boolean value stored in a list stored in my viewModel when someone click on my rectangle. Why it is so complicate to do with MVVM?
In MVVM, you shouldn't be accessing your view model from code behind. The view model and view are ignorant of each other; here endeth the lecture :) Instead, you can attach the `EventToCommand` behavior to your control. This lets you bind an event in the control to a command in the data context. See the MSDN commands tutorial here. If you are desperate to do it, you can access the control's data context property and cast it to your view model type to give access to the internals. `var vm = (ViewModelType)this.DataContext; vm.CommandProperty.Execute(null);`
Android.bat file is missing in sdk\tools folder also i do not having AVD &amp; SDK manager in tools so i can replace them <sep> i have also copied android.bat from my backup SDK but it is still not working. thanks in advance.
Probably all the contents of the sdk/tools folder are missing as well? The best method to solve this issue is to go to the sdk/temp folder. There you will find a zip file with a name like "tools_r24.0.1-windows" (the version number will be different). Copy it to a temporary location and extract it. Inside the extracted folder, you'll have a folder named 'tools'. Copy that folder to sdk/ and replace the current tools folder in sdk/. And voila! The SDK and AVD will work again, and all your virtual devices will be restored!
Virtualbox returning errorID=BLKCACHE_IOERR <sep> I was using a guide in order to create a basic Jira plugin as sort of a experimental/hands-on way to get comfortable and familiar with the Jira SDK and with creating plugins regarding Listeners. I am running Ubuntu on a VM, and I followed all the steps included in the guide. My VM started to freeze, and I thought it was maybe Jira at first but now I know there is something wrong with the VM itself. I get this error: <blockquote> An error has occurred during virtual machine execution! The error details are shown below. You may try to correct the error and resume the virtual machine execution. The I/O cache encountered an error while updating data in medium "ahci-0-0"(rc=VERR_DEV_IO_ERROR). Make sure there is enough free space on the disk and that the disk is working properly. Operation can be resumed afterwards. </blockquote> The details say: <blockquote> fatal=false, errorID=BLKCACHE_IOERR </blockquote> I looked into the log file and this is right where it goes wrong/throws an error: <blockquote> 00:01:06.499361 I/O cache: Error while writing entry at offset 102912000 (110592 bytes) to medium "ahci-0-0" (rc=VERR_DEV_IO_ERROR) </blockquote> Not really sure what to do. I have important stuff in the VM and I really don't want to set it up all over again.
The solution is simply to enable the cache I/O host. It can be activated in the machine's configuration, Storage > SATA Controller. Use the "Cache I/O host" (all other values are those used by default in VirtualBox). After this change, the error disappears.
Stop only iPhone screen rotating in Universal Xcode 6 project <sep> With the introduction of Xcode 6, Apple removed the ability to easily have multiple storyboards for iPad and iPhone in Universal apps. Due to this, you cannot differentiate between iPad and iPhone on the rotation panel/settings. How can i stop the iPhone app from Rotating into landscape, while still allowing the iPad app to do so. Is it something you can only do in code? If it is, I am still using Objective C, not Swift.
"Supported Interface Orientations" - Array "Portrait (bottom home button)" - String "Portrait (top home button)" - String "Supported Interface Orientations (iPad)" - Array "Portrait (bottom home button)" - String "Portrait (top home button)" - String "Landscape (left home button)" - String "Landscape (right home button)" - String
Swift: how can String.join() work custom types? <sep> for example: <code>var a = [1, 2, 3] // Ints var s = ",".join(a) // EXC_BAD_ACCESS </code> Is it possible to make the join function return "1,2,3" ? Extend Int (or other custom types) to conform to some protocols ?
From Xcode 7.0 beta 6 in Swift 2, you should use `[String].joinWithSeparator(",")`. In your case, you still need to change `Int` to `String` type, therefore I added `map()`. `var a = [1, 2, 3] // [1, 2, 3] var s2 = a.map { String($0) }.joinWithSeparator(",") // "1,2,3"` From Xcode 8.0 beta 1 in Swift 3, the code slightly changes to `[String].joined(separator: ",")`. `var s3 = a.map { String($0) }.joined(separator: ",") // "1,2,3"`
How to restrict app to Android phones only <sep> Hello I am targeting users to <code>Android</code> phones only. I want to restrict the app to install on <code>Android</code> phones ony not on phablets and tablets. What are the configuration do I need to apply in AndroidManifest.xml so that Google Play app wont show the app in the table and phablets. Thanks in advance.
```xml <compatible-screens> <screen android:screenSize="small" android:screenDensity="ldpi" /> <screen android:screenSize="small" android:screenDensity="mdpi" /> <screen android:screenSize="small" android:screenDensity="hdpi" /> <screen android:screenSize="small" android:screenDensity="xhdpi" /> <screen android:screenSize="small" android:screenDensity="420" /> <screen android:screenSize="small" android:screenDensity="480" /> <screen android:screenSize="small" android:screenDensity="560" /> <screen android:screenSize="small" android:screenDensity="640" /> <screen android:screenSize="normal" android:screenDensity="ldpi" /> <screen android:screenSize="normal" android:screenDensity="mdpi" /> <screen android:screenSize="normal" android:screenDensity="hdpi" /> <screen android:screenSize="normal" android:screenDensity="xhdpi" /> <screen android:screenSize="normal" android:screenDensity="420" /> <screen android:screenSize="normal" android:screenDensity="480" /> <screen android:screenSize="normal" android:screenDensity="560" /> <screen android:screenSize="normal" android:screenDensity="640" /> <screen android:screenSize="large" android:screenDensity="ldpi" /> <screen android:screenSize="large" android:screenDensity="mdpi" /> <screen android:screenSize="large" android:screenDensity="hdpi" /> <screen android:screenSize="large" android:screenDensity="xhdpi" /> <screen android:screenSize="large" android:screenDensity="420" /> <screen android:screenSize="large" android:screenDensity="480" /> <screen android:screenSize="large" android:screenDensity="560" /> <screen android:screenSize="large" android:screenDensity="640" /> </compatible-screens> ```
Float divison and casting in Swift <sep> I'm trying to learn Swift and I made a simple average function: <code>func average(numbers: Int...) -> Float { var sum = 0 for number in numbers { sum += number } return Float(sum)/Float(numbers.count) } average(1,2,3,4,5,6) </code> This gives me the correct result: 3.5 However, I am wondering why I have to cast both sum and numbers.count to floats. I tried casting this way: <code>return Float(sum/numbers.count) </code> but it gives me just 3.0
First, you should use `Double` and not `Float`. `Float` gives you very limited precision. Why you would want 6 digits of precision with `Float` when you could have 15 digits with `Double` is hard to understand. Second, a compiler does exactly what you tell it. `Float(sum) / Float(numbers.count)` takes the integer "sum", takes the integer "numbers.count", converts both to `Float`, and divides. Division of `Float` gives a result in this case of 3.5. `Float(sum / numbers.count)` divides the integer "sum" by the integer "numbers.count". Division of integers gives an integer result, which is the integer quotient disregarding any remainder. 21 / 6 equals 3 with a remainder of 3. So the result of the division is 3, which you then convert to the `Float` 3.0.
Why is a nested struct inside a generic class considered "managed"? <sep> I have the following simple test: <code>class C<T> { public struct A { int x; } } class Program { static unsafe void Main(string[] args) { IntPtr p = new IntPtr(); var a = (C<int>.A*)p.ToPointer(); } } </code> The code generates error CS0208: <code>Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<int>.A') </code> Can anyone explain why the struct is considered "managed" in this scenario?
Section 18.2 of the C# 5 spec: <blockquote> An unmanaged type is any type that isn't a reference type or constructed type, and doesn't contain reference-type or constructed type fields at any level of nesting. </blockquote> Now you might wonder if `C<int>.A` qualifies as a constructed type (it's obviously not a reference type). The answer is yes. Section 4.4 defines constructed types. It specifically says nested types are considered constructed. It uses the `Outer<T>.Inner` below as an example: ```csharp class Outer<T> { public class Inner {...} public Inner i; // Type of i is Outer<T>.Inner } ```
Basic Authentication on IIS Express <sep> I've searched for a while now but I can't seem to find the answer. There are ways of disabling/enabling anonymous and windows authentication. Does anyone know how to enable basic authentication on IIS Express (8.0) in Visual Studio 2013?
An additional heads-up: in Visual Studio 2015, the location of the applicationhost.config file being used is inside a folder called ".vs" inside your solution folder. The one in your user profile is not being used.
how to set font weight in Java for Swing components <sep> I want to set different font weights for components on my JFrame dialog. How do I do this? In the below Java statement <code>setFont(new Font("Dialog", Font.BOLD, 12)); </code> when I use Font.BOLD it is too bold and when I use Font.Plain it is too plain. I want something in-between.
Well, it's partially correct. You can use TextAttributes to obtain a font: ```java Map<TextAttribute, Object> attributes = new HashMap<>(); attributes.put(TextAttribute.FAMILY, Font.DIALOG); attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD); attributes.put(TextAttribute.SIZE, 12); label.setFont(Font.getFont(attributes)); ``` A better approach is to derive your font from the font installed on the Swing component by the look-and-feel: ```java Font font = label.getFont(); font = font.deriveFont(Collections.singletonMap(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD)); label.setFont(font); ``` That will preserve the font's family and size, which users may have set in their desktop preferences for readability reasons.
NodeJS get async return value (callback) <sep> I have read around the internet about callbacks but I just can't understand them in my case. I have this function, and it logs to console when it runs. However I now need this response in another function and I am struggling to do so. <code>var asyncJobInfo = function(jobID, next) { var oozie = oozieNode.createClient({ config: config }); var command = 'job/' + jobID + '?show=info'; console.log("running oozie command: " + command); oozie.get(command, function(error, response) { console.log("*****response would dump to console here:*****"); // console.log(response); return response; }); }; </code> This is where I should get it: (This obviously doesn't work because it doesn't wait for the response.) <code>exports.getJobInfoByID = function(req, res) { var jobIDParam = req.params.id; res.send(asyncJobInfo(jobIDParam)); } </code> I really struggle to wrap my head around callbacks and I'm staring myself blind here.
Callbacks can't return a value as the code they would be returning to has already executed. So you can do a couple of things. One, pass a callback function and once your async function gets the data, call the callback and pass the data. Or, pass the response object and use it in your async function. Passing a callback: ```javascript exports.getJobInfoByID = function(req, res) { var jobIDParam = req.params.id; asyncJobInfo(jobIDParam, null, function(data) { res.send(data); }); }; var asyncJobInfo = function(jobID, next, callback) { // ... oozie.get(command, function(error, response) { // do error check if (ok) { callback(response); } }); }; ``` Passing response object: ```javascript exports.getJobInfoByID = function(req, res) { var jobIDParam = req.params.id; asyncJobInfo(jobIDParam, null, res); }; var asyncJobInfo = function(jobID, next, res) { // ... oozie.get(command, function(error, response) { // do error check if (ok) { res.send(response); } }); }; ```
Visual Studio 2013 randomly changes the theme on its own <sep> I seem to be having a terribly annoying issue with Visual Studio 2013. I am using the "default" Dark theme on my environment, but every few minutes or so it changes its theme to another, which is not even a theme I have on my machine. Has anyone else experienced this? How does one solve it? PS.: Logged in on a shared, corporate account
Turns out the issue was that Synchronized Settings were enabled, so it was trying to sync the theme and other settings across different machines. Solution: In VS13, go to Tools -> Options -> Environment -> Synchronized Settings and uncheck the "Enabled synchronization" box.
CMake generator expression, differentiate C / C++ code <sep> I would like to add <code>-std=c++11</code> to my <code>add_compile_options("-std=c++11") </code> However, this also adds them to compilation of C files, not only C++. I know I can add conditional compile flags depending on the configuration used: <code>add_compile_options("$<$<CONFIG:DEBUG>:-addMeInDebugOnly>") </code> How can I add my flag only to c++ files? I'm looking for something like: <code>add_compile_options("$<$<??:??>:-std=c++11>") </code> But what do I need to fill in with the question marks?
When you have mixed C and C++ sources, the `LINKER_LANGUAGE` property might apply the wrong flags for compilation of individual sources. The solution is to use the `COMPILE_LANGUAGE` generator expression (introduced with CMake 3.3). The simplest example for your original C++11 flag is: ```cmake add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-std=c++11>) ``` When you have a string of compile options (for example, for usage with the `COMPILE_FLAGS` target property), you have to split the flags: ```cmake set(WARNCFLAGS "-Wall -Wextra -Wfuzzle -Wbar") # ... string(REPLACE " " ";" c_flags "${WARNCFLAGS}") string(REPLACE " " ";" cxx_flags "${WARNCXXFLAGS} ${CXX1XCXXFLAGS}") add_compile_options( "$<$<COMPILE_LANGUAGE:C>:${c_flags}>" "$<$<COMPILE_LANGUAGE:CXX>:${cxx_flags}>" ) ``` Two alternative variants for single targets that take strings: ```cmake target_compile_options(some-target PRIVATE "${WARNCFLAGS}") set_target_properties(some-target PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}") ``` Use of strings is, however, deprecated in favor of lists. When lists are in use, you can use: ```cmake set(c_flags -Wall -Wextra -Wfuzzle -Wbar) # ... add_compile_options( "$<$<COMPILE_LANGUAGE:C>:${c_flags}>" "$<$<COMPILE_LANGUAGE:CXX>:${cxx_flags}>" ) ``` Two alternative variants for single targets given a list: ```cmake target_compile_options(some-target PRIVATE ${c_flags}) set_target_properties(some-target PROPERTIES COMPILE_OPTIONS "${c_flags}") ``` Pay attention to the quoting. If a list is not quoted, it is expanded to its items (and is no longer a list). To pass a list between commands, quote it.
How does Tableau run queries on Redshift? (And/or why can't Redshift display Tableau queries?) <sep> I'm kicking tires on BI tools, including, of course, Tableau. Part of my evaluation includes correlating the SQL generated by the BI tool with my actions in the tool. Tableau has me mystified. My database has 2 billion things; however, no matter what I do in Tableau, the query Redshift reports as having been run is "Fetch 10000 in SQL_CURxyz", i.e. a cursor operation. In the screenshot below, you can see the cursor ids change, indicating new queries are being run -- but you don't see the original queries. Is this a Redshift or Tableau quirk? Any idea how to see what's actually running under the hood? And why is Tableau always operating on 10000 records at a time?
```sql SELECT usr.usename AS username, min(cur.starttime) AS start_time, DATEDIFF(second, min(cur.starttime), getdate()) AS run_time, min(cur.row_count) AS row_count, min(cur.fetched_rows) AS fetched_rows, listagg(util_text.text) WITHIN GROUP (ORDER BY sequence) AS query FROM STV_ACTIVE_CURSORS cur JOIN stl_utilitytext util_text ON cur.pid = util_text.pid AND cur.xid = util_text.xid JOIN pg_user usr ON usr.usesysid = cur.userid GROUP BY usr.usename, util_text.xid; ```
Why is the ! in Swift called an 'implicitly' rather than 'explicitly' unwrapped optional? <sep> The name of the <code>!</code> always confuses me: it's called an 'implicitly unwrapped optional'. However, what is implicit about it? Implicit means "implied though not plainly expressed." However, does not adding a <code>!</code> plainly express its purpose? Does not adding a <code>!</code> make it explicit what we are trying to accomplish?
In Swift, trailing exclamation marks (<code>!</code>) are used in two different ways. One is called Forced Unwrapping. This is when you have a variable defined as an Optional and you want to assert that the value is not nil so that you can use it as if it were not an optional: ```swift var optionalName: String? = "World" if optionalName != nil { sayHelloTo(optionalName!) } ``` An alternate way you could describe "Forced Unwrapping" is "Explicit Unwrapping," but "forced" adds the extra hint that the whole program will crash if you try to "Force Unwrap" an optional that is nil. The second way is when you are actually declaring the type of a variable, and it is called an Implicitly Unwrapped Optional. This is for when you want to declare a variable that is technically optional, but you will treat it as if it is not optional. Every time you use this Implicitly Unwrapped Optional, it is in reality doing the "Forced Unwrapping" I described above: ```swift var name: String! = "World" if name != nil { sayHelloTo(name) } ``` You can still test an Implicitly Unwrapped Optional for nil, but you can also use it directly as if it were not optional. That is why it is considered implicit. Every time you use it, it is automatically implicitly unwrapped for you. Like "Forced Unwrapping," an "Implicitly Unwrapped Optional" will still crash the entire program if you try to use it when it is nil.
Sorting objects based on property value in D3 <sep> I have a array of objects for use in D3 e.g <code>var cities = [ { city: "London", country: "United Kingdom", index: 280 }, { city: "Geneva", country: "Switzerland", index: 259 }, { city: "New York City", country: "United States", index: 237 }, { city: "Singapore", country: "Singapore", index: 228 }, { city: "Paris", country: "France", index: 219 }, { city: "San Francisco", country: "United States", index: 218 }, { city: "Copenhagen", country: "Denmark", index: 217 }, { city: "Sydney", country: "Australia", index: 215 }, { city: "Hong Kong", country: "Hong Kong", index: 214 }, { city: "Brisbane", country: "Australia", index: 208 } } </code> I would like to order the objects in ascending order based on their cities.index property. So that I can display them as such in <code>D3.js</code>. Im sure there is a way of doing this in D3 but I am yet to figure it out when dealing with an array of objects. Any help?
You can pass an anonymous function to the JavaScript `Array.prototype.sort` method to sort by index. D3 has a function `d3.ascending` (v3.x) that makes it easy to sort ascending: ```javascript cities.sort(function(x, y){ return d3.ascending(x.index, y.index); }) ``` And here's the output: ```json [ {"city":"Brisbane","country":"Australia","index":208}, {"city":"Hong Kong","country":"Hong Kong","index":214}, {"city":"Sydney","country":"Australia","index":215}, {"city":"Copenhagen","country":"Denmark","index":217}, {"city":"San Francisco","country":"United States","index":218}, {"city":"Paris","country":"France","index":219}, {"city":"Singapore","country":"Singapore","index":228}, {"city":"New York City","country":"United States","index":237}, {"city":"Geneva","country":"Switzerland","index":259}, {"city":"London","country":"United Kingdom","index":280} ] ```
how to unstack (or pivot?) in pandas <sep> I have a dataframe that looks like the following: <code>import pandas as pd datelisttemp = pd.date_range('1/1/2014', periods=3, freq='D') s = list(datelisttemp)*3 s.sort() df = pd.DataFrame({'BORDER':['GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY' ], 'HOUR1':[2 ,2 ,2 ,4 ,4 ,4 ,6 ,6, 6],'HOUR2':[3 ,3 ,3, 5 ,5 ,5, 7, 7, 7], 'HOUR3':[8 ,8 ,8, 12 ,12 ,12, 99, 99, 99]}, index=s) </code> This gives me: <code>Out[458]: df BORDER HOUR1 HOUR2 HOUR3 2014-01-01 GERMANY 2 3 8 2014-01-01 FRANCE 2 3 8 2014-01-01 ITALY 2 3 8 2014-01-02 GERMANY 4 5 12 2014-01-02 FRANCE 4 5 12 2014-01-02 ITALY 4 5 12 2014-01-03 GERMANY 6 7 99 2014-01-03 FRANCE 6 7 99 2014-01-03 ITALY 6 7 99 </code> I want the final dataframe to look something like: <code> HOUR GERMANY FRANCE ITALY 2014-01-01 1 2 2 2 2014-01-01 2 3 3 3 2014-01-01 3 8 8 8 2014-01-02 1 4 4 4 2014-01-02 2 5 5 5 2014-01-02 3 12 12 12 2014-01-03 1 6 6 6 2014-01-03 2 7 7 7 2014-01-03 3 99 99 99 </code> I've done the following but I'm not quite there: <code>df['date_col'] = df.index df2 = melt(df, id_vars=['date_col','BORDER']) #Can I keep the same index after melt or do I have to set an index like below? df2.set_index(['date_col', 'variable'], inplace=True, drop=True) df2 = df2.sort() </code> df <code>Out[465]: df2 BORDER value date_col variable 2014-01-01 HOUR1 GERMANY 2 HOUR1 FRANCE 2 HOUR1 ITALY 2 HOUR2 GERMANY 3 HOUR2 FRANCE 3 HOUR2 ITALY 3 HOUR3 GERMANY 8 HOUR3 FRANCE 8 HOUR3 ITALY 8 2014-01-02 HOUR1 GERMANY 4 HOUR1 FRANCE 4 HOUR1 ITALY 4 HOUR2 GERMANY 5 HOUR2 FRANCE 5 HOUR2 ITALY 5 HOUR3 GERMANY 12 HOUR3 FRANCE 12 HOUR3 ITALY 12 2014-01-03 HOUR1 GERMANY 6 HOUR1 FRANCE 6 HOUR1 ITALY 6 HOUR2 GERMANY 7 HOUR2 FRANCE 7 HOUR2 ITALY 7 HOUR3 GERMANY 99 HOUR3 FRANCE 99 HOUR3 ITALY 99 </code> I thought I could unstack df2 to get something that resembles my final dataframe but I get all sorts of errors. I have also tried to pivot this dataframe but can't quite get what I want.
```python import pandas as pd datelisttemp = pd.date_range('1/1/2014', periods=3, freq='D') s = list(datelisttemp)*3 s.sort() df = pd.DataFrame({'BORDER':['GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY','GERMANY','FRANCE','ITALY' ], 'HOUR1':[2 ,2 ,2 ,4 ,4 ,4 ,6 ,6, 6], 'HOUR2':[3 ,3 ,3, 5 ,5 ,5, 7, 7, 7], 'HOUR3':[8 ,8 ,8, 12 ,12 ,12, 99, 99, 99]}, index=s) df = df.set_index(['BORDER'], append=True) df.columns.name = 'HOUR' df = df.unstack('BORDER') df = df.stack('HOUR') df = df.reset_index('HOUR') df['HOUR'] = df['HOUR'].str.replace('HOUR', '').astype('int') print(df) ``` yields ``` BORDER HOUR FRANCE GERMANY ITALY 0 2014-01-01 1 2 2 2 1 2014-01-01 2 3 3 3 2 2014-01-01 3 8 8 8 3 2014-01-02 1 4 4 4 4 2014-01-02 2 5 5 5 5 2014-01-02 3 12 12 12 6 2014-01-03 1 6 6 6 7 2014-01-03 2 7 7 7 8 2014-01-03 3 99 99 99 ```
Check for equality in Spacebars? <sep> I am trying to do what I think should be a very simple task, but have been failing to do so in the past hour. I want to select a select option by default if the user property matches the value. <code><select name="myName"> {{#each addKeys myTable}} <!-- addKeys creates variables for keys and values --> <option value="{{key}}" {{#if currentUser.property === key}}selected="selected"{{/if}}>{{value}}</option> {{/each}} </select> </code> Now I thought this was straightforward enough to be implemented. But it turns out that Spacebars do not allow conditional operators other than the negation exclamation mark, so equal signs are out of question. I then tried something horrible for the sake of trying: In template <code>myTemplate</code>: <code><select name="myName"> {{#each addKeys myTable}} <option value="{{key}}" {{isSelected currentUser.property key}}>{{value}}</option> {{/each}} </select> </code> In <code>mytemplate.js</code> : <code>Template.myTemplate.helpers({ isSelected: function(v1, v2) { if (v1 === v2) return "selected=\"selected\""; return ''; } }); </code> Not only is this code terrible, terrible to look at, it does not work: <code>Exception in Meteor UI: String contains an invalid character </code> I don't understand why something that simple seems so impossible to achieve. Am I missing something there?
Here's an overview of `{{#if}}` statements in Spacebars. Of course, the simplest possible implementation is when the scoped object has a property that evaluates to a boolean. For example, if you had: ```javascript var item = { text: 'hello', checked: false }; ``` Then you could evaluate an if block like this: ```html class="{{#if checked}}checked{{/if}}" ``` **Function** We could also evaluate a function here as well. Rather than add a function to the item, we can add a function to the helper, and it will inherit the data context of the item being passed to it. So if we had the following helper: ```javascript Template.item.helpers({ saysHi: function() { return this.text === "hi"; } }); ``` Then we could run the following code: ```html <template name="item"> {{text}} {{#if saysHi}} - Hi Back {{/if}} </template> ``` > **Note:** The helper's implementation can access the current data context as `this`. **Function with Parameters** You can also pass any number of parameters to helper functions like this: Template: `{{frob a b c verily=true}}` Helper Call: `frob(a, b, c, Spacebars.kw({verily: true}))` When applied to our if block, we can do the following: ```html {{#if equals owner currentUser._id}} <button class="delete">&times;</button> {{/if}} ``` Then add `equals` to our template helper like this: ```javascript Template.item.helpers({ equals: function(v1, v2) { return (v1 === v2); } }); ``` **Universal Helpers** Since this is a generic method that could be useful anywhere, we should add it to every template instead of recreating it. > **Note:** To create a helper that can be used in any template, use `Template.registerHelper`. ```javascript Template.registerHelper('equals', function(v1, v2) { return (v1 === v2); }); ``` Here's a working Demo in MeteorPad that includes one of each of the types of IF's constructed here.
Install iOS 6 simulator on Xcode 6 <sep> My company still supports iOS 6 apps, but after installing the new Xcode(6) I only see iOS 7 & 8 simulators. Is there a way I can install iOS 6 simulator for Xcode 6?
iOS 6 is unavailable in Xcode 6. You will have to use Xcode 5 and run the simulator in Xcode 5. You can download older versions of Xcode at Apple's Developer Website; click the "Looking for an older version of Xcode?" link. (Xcode -> Open Developer Tools -> iOS Simulator)
How Can I Delete Xampp Permanently on Mac Os? <sep> I used Xampp and deleted it. Then, I tried to use Mamp. There is an error that I don't understand. Mamp is working perfect as webserver. But if I want to use phpmyadmin, it doesn't work. For example, I insert something to database. It isn't showing in phpmyadmin. It is saving to old Xampp database although I deleted Xampp. How does it happen? How Can I delete Xampp permanently(with mysql) on Mac OS?
XAMPP 5.x: You can find `uninstall.app` in `/Applications/XAMPP`. After running this program, you can use this command to delete all XAMPP cache files: `sudo rm -rf /Applications/XAMPP`. XAMPP 7.x: Open Mac OS Finder and go to the `/Applications` folder. You should find an XAMPP icon (e.g., XAMPP.app), right-click it, and choose 'Move to Trash'. In addition, you might want to delete the `~/.bitnami` folder within your home directory.
How to add legend to imshow() in matplotlib <sep> I am using <code>matplotlib</code> In <code>plot()</code> or <code>bar()</code>, we can easily put legend, if we add labels to them. but what if it is a <code>contourf()</code> or <code>imshow()</code> I know there is a <code>colorbar()</code> which can present the color range, but it is not satisfied. I want such a legend which have names(labels). For what I can think of is that, add labels to each element in the matrix, then ,try legend(), to see if it works, but how to add label to the element, like a value?? in my case, the raw data is like: <code>1,2,3,3,4 2,3,4,4,5 1,1,1,2,2 </code> for example, 1 represents 'grass', 2 represents 'sand', 3 represents 'hill'... and so on. imshow() works perfectly with my case, but without the legend. my question is: Is there a function that can automatically add legend, for example, in my case, I just have to do like this: someFunction('grass','sand',...) If there isn't, how do I add labels to each value in the matrix. For example, label all the 1 in the matrix 'grass', labell all the 2 in the matrix 'sand'...and so on. Thank you! Edit: Thanks to @dnalow, it's smart really. However, I still wonder if there is any formal solution.
```python import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np # create some data data = np.random.randint(0, 8, (5,5)) # get the unique values from data # i.e. a sorted list of all values in data values = np.unique(data.ravel()) plt.figure(figsize=(8,4)) im = plt.imshow(data, interpolation='none') # get the colors of the values, according to the # colormap used by imshow colors = [im.cmap(im.norm(value)) for value in values] # create a patch (proxy artist) for every color patches = [mpatches.Patch(color=colors[i], label="Level {l}".format(l=values[i])) for i in range(len(values))] # put those patched as legend-handles into the legend plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.grid(True) plt.show() ```
How to switch view controllers in swift? <sep> I'm trying to switch from one UIViewController to another using code. Right now I have, <code>self.presentViewController(ResultViewController(), animated: true, completion: nil) </code> All this is doing is taking me to a black screen instead of the ResultViewController. Any suggestions?
With Storyboard: Create a Swift file (SecondViewController.swift) for the second view controller and in the appropriate function type this: ```swift let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController self.navigationController.pushViewController(secondViewController, animated: true) ``` Without Storyboard: ```swift let secondViewController = SecondViewController(nibName: NibName, bundle: nil) self.present(secondViewController, animated: true, completion: nil) ```
how to remove brackets character in string (java) <sep> I want to remove all type of brackets character (example: [],(),{}) in string by using java. I tried using this code: <code>String test = "watching tv (at home)"; test = test.replaceAll("(",""); test = test.replaceAll(")",""); </code> But it's not working, help me please.
The first argument of `replaceAll` takes a regular expression. All the brackets have meaning in regex: brackets are used to reference capturing groups, square brackets are used for character classes, and braces are used for matched character occurrence. Therefore, they all need to be escaped. However, here the characters can simply be enclosed in a character class with just escaping required for square brackets: `test = test.replaceAll("[\\[\\](){}]", "");`
jQuery Appending an Object multiple times <sep> I am not sure what exactly is happening here, I think the fact that the variable is a jquery object. This only appends once, my question is why? <code>var newInput = $('<input/>'); $('#newDiv').append(newInput); $('#newDiv').append(newInput); </code> Though this works as I would assume <code>var newInput = '<input>'; $('#newDiv').append(newInput); $('#newDiv').append(newInput); </code> Thank you for your help!
In the first case, `$` will parse your HTML and create a new jQuery object which will wrap over an `HTMLInputElement`. Basically, it's like doing: `var $newDiv = $('#newDiv'), newInput = document.createElement('input'); $newDiv.append(newInput);` In the second case, it's parsing the HTML every time, generating a different jQuery object for every instance. Here's how the first sample could be fixed: `var newInput = $('<input/>'); $('#newDiv').append(newInput); $('#newDiv').append(newInput.clone());`
Understanding @BatchSize in Hibernate <sep> The Hibernate documentation gives some information at @BatchSize as : <blockquote> @BatchSize specifies a "batch size" for fetching instances of this class by identifier. Not yet loaded instances are loaded batch-size at a time (default 1). </blockquote> I am not clear on what is the purpose of this annotation, when we need to use this. Can some please help me in understanding when to use this annotation.
Using batch fetching, Hibernate can load several uninitialized proxies if one proxy is accessed. Batch fetching is an optimization of the lazy select fetching strategy. There are two ways to configure batch fetching: at the class level and the collection level. Batch fetching for classes/entities is easier to understand. Consider the following example: at runtime you have 25 Cat instances loaded in a Session, and each Cat has a reference to its owner, a Person. The Person class is mapped with a proxy, `lazy="true"`. If you now iterate through all cats and call `getOwner()` on each, Hibernate will, by default, execute 25 SELECT statements to retrieve the proxied owners. You can tune this behavior by specifying a `batch-size` in the Person mapping: `<class name="Person" batch-size="10">...</class>`. Hibernate will now execute only three queries: the pattern is 10, 10, 5.
Building for iOS if registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later <sep> If there are breaking changes with how devices register for notifications, and we cannot use registerForRemoteNotificationTypes: anymore, how can we build a new version of the app to support iOS 8 if we cannot use Xcode 6 beta? Will we have to build and submit the day the Xcode 6 GM version is released for our users to continue to get push notifications?
iOS 8 has changed notification registration. So you need to check the device version and then register notification settings. (Please check this link.) I tried this code on Xcode 6, and it worked for me. ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; [[UIApplication sharedApplication] registerForRemoteNotifications]; } else { [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)]; } return YES; } ```
How do you call XCTest in a Swift Playground? <sep> I was looking at Bendyworks' article on Unit testing with Swift: http://bendyworks.com/unit-testing-in-swift/ and as you do with Swift I took the code and threw it in Playground to have poke at it. <code>import Cocoa class Firewood { var charred: Bool init() { println("initializing our firewood") charred = false } func burn() { charred = true } } import XCTest class SimpleFirewoodTests: XCTestCase { func testBurningActuallyChars() { let firewood = Firewood() firewood.burn() assert(firewood.charred, "should be charred after burning") } } </code> But then of course you cannot press the test button as well Playground is a continuous REPL, so you need to know how to call the tests, does someone know the inside of XCTest to know what to call to do a test run?
Here is a full example, which works in Swift 3+, which shows you how to do this. This is nice because now you can use `XCTAssert` and they are easily directly moved to your real test bundle once you get the kinks worked out. import XCTest class MyTestCase: XCTestCase { func testExample() { print("Test1") XCTAssertTrue(true) } func testAnother() { print("Test2") XCTAssertFalse(false) } } MyTestCase.defaultTestSuite().run() // Swift 3 MyTestCase.defaultTestSuite.run() // Swift 4 This is how it will look like: Unfortunately you have to open the log window to see whether it passed or failed. It would be nice if you could see the test results colorized...
In python, how can I print lines that do NOT contain a certain string, rather than print lines which DO contain a certain string: <sep> I am trying to condense a very large log file, and to do so, I must eliminate every line which contains the string "StatusRequest" and "StatusResponse", while printing the other lines w/o this string. The code I have so far is as follows (to run from the command prompt): <blockquote> <code> if (sys.argv[1])=="--help": print ("\n") print ("Argument 1: Enter name of '.py' file") print ("-i or --input: name of Catalina log") print ("-o or --output: file to output to") print ("\n") if (sys.argv[1])=="-h": print ("\n") print ("Argument 1: Enter name of '.py' file") print ("-i or --input: name of Catalina log") print ("-o or --output: file to output to") print ("\n") else: print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) Numarg = (len(sys.argv)) i=1 while i<=(Numarg-4): search1="StatusRequest" search2="StatusResponse" if (sys.argv[Numarg-2])=="-o": outputfile=sys.argv[Numarg-1] if (sys.argv[Numarg-2])=="--output": outputfile=sys.argv[Numarg-1] if (sys.argv[i])=="-i": filename=(sys.argv[i+1]) log=(filename) print ("You entered the log: " + log) f=open(log, 'r') read_data = f.read() f.close f=open(log, 'r') readlines_data=f.readlines() f.close() i=i+1 if (sys.argv[i])=="--input": filename=(sys.argv[i+1]) log=(filename) print ("You entered the log: " + log) f=open(log, 'r') read_data = f.read() f.close f=open(log, 'r') readlines_data=f.readlines() f.close() i=i+1 for line in readlines_data: if not ("StatusRequest" or "StatusResponse") in line: result=line print (line) f=open(outputfile, 'a') f.write(result + "\n") f.close() </code> </blockquote> You can just focus on the end of the script to answer my question, really...Anyways, I am not sure why this doesn't work...It is outputting every line still. And I already tried switching the place of the not so it would make more sense idiomatically, but it didn't change anything with the code. Any help is much appreciated :)
The problem isn't your use of `not`, it's that `or` doesn't mean what you think it does (and if you think it through, it couldn't): `if not ("StatusRequest" or "StatusResponse") in line: ` You're asking whether the expression `("StatusRequest" or "StatusResponse")` appears in `line`. But that expression is just the same thing as `"StatusRequest"`. Put it in English: you're not trying to say "if neither of these is in line". Python doesn't have a `neither`/`none` function, but it does have an `any` function, so you can do this: `if not any(value in line for value in ("StatusRequest", "StatusResponse")): ` This isn't quite as nice as English; in English, you can just say "if none of the values 'StatusRequest' and 'StatusResponse' are in line", but in Python, you have to say "if none of the values coming up are in line, for values 'StatusRequest' and 'StatusResponse'". Or, maybe more simply in this case: `if "StatusRequest" not in line and "StatusResponse" not in line: ` (Also, notice that you can use `not in`, instead of using `in` and then negating the whole thing.)
ng-model is not getting changed in ui-select <sep> I'm trying to achieve something very straightforward: <code><ui-select multiple ng-model="company.stack" theme="bootstrap"> <ui-select-match>{$$item.name$}</ui-select-match> <ui-select-choices repeat="technology in technologies | filter: $select.search"> <div ng-bind-html="technology.name | highlight: $select.search"></div> </ui-select-choices> </ui-select> </code> When changing the objects, the changes are not reflected in the model company.stack. I tried changing it to $parent.company.stack, but it still doesn't work. What am I missing? I'm using AngularJS v1.3.0-beta.17.
I had a similar issue with `angular 1.3.14` and `ui-select` and a multiple-choice `ui-select` directive binding to an array. I was not able to bind the selected items to an array referred to in `ng-model`. I got it to work by wrapping `selectedItems` into an object: `$scope.myObj = { selectedItems : []}; ... <ui-select ng-model="myObj.selectedItems" ...> </ui-select>`. Putting `selectedItems` directly on the `$scope` didn't work for me.
Return null instead default value in LINQ <sep> I have LINQ query which has to retreive some DateTime value. Somethimes I don't have match for and I have to return NULL for that DateTime value instead default value for DateTime. How can I avoid that and return NULL instead defaul value? My LINQ: <code>CreatedDate = ctaMatch.Select(d => d.CreatedDate).DefaultIfEmpty().FirstOrDefault() </code> In DefaultIfEmpty I can put only DateTime.
Cast it to `DateTime?`. This will cause `DefaultIfEmpty` to create a default collection that contains a null value if the collection is empty. `CreatedDate = ctaMatch.Select(d => (DateTime?)d.CreatedDate).FirstOrDefault();` PS: `DefaultIfEmpty` can be omitted because it's followed by `FirstOrDefault`.
chef only_if attribute equals true <sep> Problem: I have a chef statement that should only run if the attribute is "true". But it runs every time. Expected Behavior: When <code>default[:QuickBase_Legacy_Stack][:dotNetFx4_Install] = "false"</code> dotnet4 should not be installed. Actual Behavior: No matter what the attribute is set to, it installs dotnet4. My code: attribute file: <code>default[:QuickBase_Legacy_Stack][:dotNetFx4_Install] = "false" </code> recipe file: <code>windows_package "dotnet4" do only_if node[:QuickBase_Legacy_Stack][:dotNetFx4_Install]=='true' source "#{node[:QuickBase_Legacy_Stack][:dotNetFx4_URL]}" installer_type :custom action :install options "/quiet /log C:\\chef\\installLog4.txt /norestart /skipmsuinstall" end </code>
```ruby guards that run Ruby must be enclosed in a block <code>{}</code> otherwise Chef will try to run the string in the default interpreter (usually bash). windows_package "dotnet4" do only_if { node[:QuickBase_Legacy_Stack][:dotNetFx4_Install] == true } source node[:QuickBase_Legacy_Stack][:dotNetFx4_URL] installer_type :custom action :install options "/quiet /log C:\\chef\\installLog4.txt /norestart /skipmsuinstall" end ```
Java Error: illegal start of expression <sep> I'm basically refining, completing and trying to compile a test code from a reference book for java beginners. The objective is to create a guessing game wherein the target is located in 3 continuous cells (I'm holding the locations in an array) and the user guesses the cell no. to destroy the target cell by cell. I checked out half a dozen posts here on the same error, but I couldn't figure out what was going wrong. This is my error: <code>test.java:5: error: illegal start of expression public int[] locations={1,2,3}; ^ 1 error </code> and my code is: <code>public class test{ public static void main(String[] args){ test dot=new test(); public int[] locations={1,2,3}; dot.setLocationCells(locations); String userGuess="2"; String result = dot.checkYourself(userGuess); String testResult="failed"; if(result.equals("hit")){ testResult="passed"; } System.out.println(testResult); } public String checkYourself(String stringGuess){ int guess=Integer.parseInt(stringGuess); String result="miss"; int numOfHits=0; for(int cell:locations){ if(guess==cell){ result="hit"; numOfHits++; break; } } if(numOfHits==locations.length){ result="kill"; } System.out.println(result); return result; } public void setLocationCells( int[] locations){ int[] locns; locns=locations; } } </code>
```java public class Test { private final int[] locations; public Test(int[] locations) { this.locations = locations; } public boolean checkYourself(int value) { for (int location : locations) { if (location == value) { return true; } } return false; } public static int[] locations = {1, 2, 3}; public static void main(String[] args) { Test test = new Test(Test.locations); String result; if (test.checkYourself(2)) { result = "Hurray"; } else { result = "Try again"; } System.out.println(result); } } ```
How to change the default double quote marks to single quote mark in Intellij(IDEA) once you press tab when you are writing HTML and CSS <sep> This is the default : <code><div class="container"></div> </code> Is there any setting to let it become <code><div class='container'></div> </code> when you press tab?
Editor > Code Style > HTML. I think you might be looking for Code Style Settings. There is a drop-down under "Generated Code" for String literal type: Single Quotes. Change that. You may also want to change it for JavaScript as well; Zhe points out that is in the Punctuation tab.
bash exec sending output to a pipe, how? <sep> I experiment with exec'ing the bash itself only to redirect the output. If I use redirection like <code>exec >bla.log ls exec 1>&2 </code> it works as expected: the <code>ls</code> output ends up in <code>bla.log</code> and after the second <code>exec</code> things are back to normal, mainly because handle 2 is still bound to the terminal. Now I thought to send the output through a pipe instead of into a file, a trivial example being <code>exec | cat >bla.log</code>. However, the command immediately returns. To figure out what is going on, I did this: <code>exec | bash -c 'echo $$; ls -l /proc/$$/fd /proc/23084/fd' </code> where 23084 is the bash currently running and got this: <code>24002 /proc/23084/fd: total 0 lrwx------ 1 harald harald 64 Aug 14 20:17 0 -> /dev/pts/1 lrwx------ 1 harald harald 64 Aug 14 20:17 1 -> /dev/pts/1 lrwx------ 1 harald harald 64 Aug 14 20:17 2 -> /dev/pts/1 lrwx------ 1 harald harald 64 Aug 14 20:17 255 -> /dev/pts/1 /proc/24002/fd: total 0 lr-x------ 1 harald harald 64 Aug 14 21:56 0 -> pipe:[58814] lrwx------ 1 harald harald 64 Aug 14 21:56 1 -> /dev/pts/1 lrwx------ 1 harald harald 64 Aug 14 21:56 2 -> /dev/pts/1 </code> As we can see, the sub-process 24002 is indeed listening to a pipe. But it certainly is not the parent process, 23084, which has this pipe open. Any ideas what is going on here?
What: The proper way to implement something that might otherwise be written `exec | cat > bla.log` is `#!/bin/bash # ^^^^ - IMPORTANT: not /bin/sh exec > >(cat > bla.log)`. Why: This is because `>()` is a process substitution; it's replaced with a filename (of the `/dev/fd/NN` form if possible, or a temporary FIFO otherwise) which, when written to, will deliver to the stdin of the enclosed process. (`<()` is similar, but in the other direction: being substituted with the name of a file-like object which will, when read, return the given process's stdout). Thus, `exec > >(cat > bla.log)` is roughly equivalent to the following (on an operating system that doesn't provide `/dev/fd`, `/proc/self/fds`, or similar): ``` mkfifo "tempfifo.$$" # implicit: FIFO creation cat > bla.log < "tempfifo.$$" & # ...start the desired process within it... exec > "tempfifo.$$" # explicit: redirect to the FIFO rm "tempfifo.$$" # ...and can unlink it immediately. ```
Why does my Cordova WebView have an extra 20px of scrolling? <sep> I am building a Cordova app, and I'm testing it on my iOS 6 device (iPod Touch w/ iOS 6.1.6). For some reason, the WebView is scrollable with an extra 20px, seemingly making up for the 20px status bar at the top of the screen. This sometimes causes the scrollable WebView to take focus, essentially causing "nothing" to scroll in the eyes of the user, rather than allowing scrollable <code>div</code>s in my app to scroll. I have tried numerous fixes pertaining to config.xml changes, plugins, etc, but nothing makes a difference, which I've outlined below. Tried manually hiding the status bar, with no effect. <code>// config.xml: <plugin name="org.apache.cordova.statusbar" version="0.1.7" /> <feature name="StatusBar"> <param name="ios-package" value="CDVStatusBar" /> </feature> // index.js (ondeviceready): window.StatusBar && window.StatusBar.hide(); </code> Tried forcing the status bar to overlay the webview, essentially making the app a full 480px tall (instead of 460px): <code>// config.xml: <plugin name="org.apache.cordova.statusbar" version="0.1.7" /> <preference name="StatusBarOverlaysWebView" value="true" /> </code> Tried forcing the status bar to not overlay the webview: <code>// config.xml: <plugin name="org.apache.cordova.statusbar" version="0.1.7" /> <preference name="StatusBarOverlaysWebView" value="false" /> <preference name="StatusBarBackgroundColor" value="#000000" /> <preference name="StatusBarStyle" value="lightcontent" /> </code> Tried offsetting the body's margin-top by 20px, which just adds an extra 20px of dead whitespace: <code>// index.css: body { margin-top: 20px; } </code> Tried setting the app to fullscreen, which literally has no effect on the app whatsoever: <code>// config.xml: <preference name="Fullscreen" value="true" /> </code> I even used Safari inspector to delete the <code>body</code> DOM node altogether, and it still scrolls 20px, telling me that it has nothing to do with the HTML so much as Cordova's implementation of the WebView. Does anyone have a solution for this? I can't be the only one out there encountering this.
Figured it out after almost 8 hours of tinkering. Had to replace the `<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />` setting to `<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, target-densitydpi=device-dpi" />`. It seems that `height=device-height` was taking the full device height into account, including the status bar. I did see a way to work around this in JavaScript for those who are interested, which is covered by this Stack Overflow answer. I don't see any drawback to removing it altogether though (for a Cordova app targeting iOS 6+).
How do I run livereload server on localhost after running Ionic serve command? <sep> I recently started learning Ionic Framework. You can use <code>Ionic serve</code> command inside the project to run a livereload server. Once in a while it asked whether server should run on <code>localhost</code> or <code>system ip</code>. I chose second option. Now It doesn't ask anything and directly runs on system's <code>ip</code>. How do reset this automatic behaviour? I tried looking into <code>serve.js</code> file in <code>ionic-cli</code> project but no luck.
You can switch between addresses with the command `ionic address`. You'll then get options like this: `Please select which address to use by entering its number from the list below: 1) 10.0.1.7 (en1) 2) localhost`.
how iterate ArrayCollection in symfony2 Controller <sep> I want to iterate <code>ArrayCollection</code> instance in Symfony2 Controller, What is the easiest way? edit: I thought it would work like normal array in php but I got error on this code: <code>foreach ($arrayCollectionInc as $Inc) { } </code>
To those who find this question in the future, there is another way that I would consider to be a better practice than the accepted answer, which just converts the `ArrayCollection` to an array. If you are going to just convert to an array, why bother with the `ArrayCollection` in the first place? You can easily loop over an `ArrayCollection` without converting it to an array by using the `getIterator()` function. `foreach ($arrayCollection->getIterator() as $i => $item) { //do things with $item } `
Is it really necessary to close the unused end of the pipe in a process <sep> I am reading about the pipes in UNIX for inter process communication between 2 processes. I have following question Is it really necessary to close the unused end of the pipe? for example, if my parent process is writing data in to the pipe and child is reading from pipe, is it really necessary to close the read end of the pipe in parent process and close the write end from child process? Are there any side effects if I won't close those ends? Why do we need to close those ends?
Here's the problem if you don't. In your example, the parent creates a pipe for writing to the child. It then forks the child but does not close its own read descriptor. This means there are still two read descriptors on the pipe. If the child had the only one and it closed it (for example, by exiting), the parent would get a SIGPIPE signal, or if that was masked, an error on writing to the pipe. However, there is a second read descriptor on the pipe (the parent's). Now, if the child exits, the pipe will remain open. The parent can continue to write to the pipe until it fills, and then the next write will block (or return without writing if non-blocking). Thus, by not closing the parent's read descriptor, the parent cannot detect that the child has closed its descriptor.
WKWebKit: No dataDetectorTypes parameter <sep> In <code>UIWebView</code>, it was fairly easy to add <code>UIDataDetectorTypes</code> to a view: <code>myUIWebView.dataDetectorTypes = UIDataDetectorTypePhoneNumber; </code> And so on. However, <code>WKWebView</code> does not seem to have a similar property. This reference mentions that it has moved to the <code>WKWebViewConfiguration</code> property at <code>myWebKitView.configuration</code>, but both the official documentation and the headers themselves make no reference to <code>dataDetectorTypes</code>. I'm currently trying to migrate an app from using <code>UIWebView</code> to <code>WKWebView</code>, and this app currently has user-configurable <code>UIDataDetectorTypes</code>. So, is there any way to implement this using the provided API, or would I have to write my own code to parse the HTML?
Actually, WKWebView doesn't have a `dataDetectorTypes` property. But in iOS 10, WKWebViewConfiguration does. Try the following code snippet: ``` WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init]; theConfiguration.dataDetectorTypes = WKDataDetectorTypeNone; WKWebView *webView = [[WKWebView alloc] initWithFrame:_someFrame configuration:theConfiguration]; ``` This will work only from iOS 10 onwards.
Generic Type Inference with Class Argument <sep> I'm having an issue which defining a generic type based on a type I've passed in. I have a piece of code witch activates a class, I cant get the type information from the type parameter so I am passing in class object (not an instance). However this breaks the Type inference. Here is a simplified example of what I'm trying to do: <code>interface IActivatable { id: number; name:string; } class ClassA implements IActivatable { public id: number; public name: string; public address:string; } class ClassB implements IActivatable { public id: number; public name: string; public age: number; } function activator<T extends IActivatable>(type:T): T { // do stuff to return new instance of T. } var classA:ClassA = activator(ClassA); </code> So far the only solution Ive been able to come up with is to change the type of the <code>type</code> argument to <code>any</code> and manually set the generic type also (as shown below). However this seems long winded, is there another way to achieve this. <code>function activator<T extends IActivatable>(type:any): T { // do stuff to return new instance of T. } var classA:ClassA = activator<ClassA>(ClassA); </code> Thanks for any help you can give.
According to the language specification, you need to refer to the class type by its constructor function. So instead of using `type: T`, use `type: { new(): T; }` as follows: ``` function activator<T extends IActivatable>(type: { new(): T; }): T { // do stuff to return new instance of T. return new type(); } var classA: ClassA = activator(ClassA); ```
python moving multiple files from one folder to the other based on text characters in file name <sep> I'm quite new to Python. I've been exploring the <code>shutil</code> module and can move things in general. My question revolves around: Imagine a scenario in which you have hundreds of files in an export folder. While all the files are distinct, 13 of each are for a specific vendor. I would like to create a script that goes through the export folder, evaluates each file name, grabs all the Apple files and puts them in the Apple Folder, Intel files and puts them in the Intel Folder, etc. Any wisdom would be greatly appreciated. I was trying to have wildcards in the <code>shutil</code> copy, but did not have any luck. Thanks, JT
```python import shutil import os source = '/path/to/source_folder' dest1 = '/path/to/apple_folder' dest2 = '/path/to/intel_folder' files = os.listdir(source) for f in files: if f.startswith("Apple") or f.startswith("apple"): shutil.move(f, dest1) elif f.startswith("Intel") or f.startswith("intel"): shutil.move(f, dest2) ``` The destination folders do need to exist.
Swift Navigation Bar Button and Title don't appear <sep> I'd like to create a Navigation bar on top of my App. I created an Navigation Controller -> Tab Bar Controller -> Navigation Controller -> Table Controller I dragged a Bar Button Item on the upper right side. I double clicked the title in the middle of the Table Controller and wrote a text. I also tried it with this code in the viewDidLoad() of my controller: <code>self.navigationController.navigationBar.topItem.title = "some title" self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:"), animated: true) self.navigationItem.title = "YourTitle" </code> Non of it worked - what am I doing wrong? :/
```swift self.title = "Your Title" var homeButton: UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: .plain, target: self, action: "") var logButton: UIBarButtonItem = UIBarButtonItem(title: "RightButtonTitle", style: .plain, target: self, action: "") self.navigationItem.leftBarButtonItem = homeButton self.navigationItem.rightBarButtonItem = logButton ```
angular-translate - Fallback language for determinePreferredLanguage() <sep> I use angular-translate in my app. How can I register a fallback language if the <code>determinePreferredLanguage()</code> returns a language key my code doesn't know? I want to fall back to english if someone from e.g. Sweden visits my site (language key: sv). But since I haven't listed sv in my <code>registerAvailableLanguageKeys</code> function, it fails, and the language-keys are shown to the user instead of the translation. <code>$translateProvider .registerAvailableLanguageKeys(['da-dk','en-us'], { 'en_US': 'en-us', 'en_UK': 'en-us', 'da': 'da-dk', }) .determinePreferredLanguage(); </code>
Using wildcards is the best solution; you can just set `en_*` as follows: ``` $translateProvider.useStaticFilesLoader({ prefix: 'locales/locale-', suffix: '.json' }) .registerAvailableLanguageKeys(['en', 'fr', 'pt'], { 'en_*': 'en', 'fr_*': 'fr', 'pt_*': 'pt', '*': 'en' }) .determinePreferredLanguage() .fallbackLanguage('en'); ``` for files: `locales/locale-en.json locales/locale-fr.json locales/locale-pt.json`
Move one element before another with css/html <sep> Is it possible to "move" one full width element that is below another one so that it appears to be above by only using CSS/HTML? (and not changing the markup order) <code><div id="first">first</div> <div id="second">second</div> #first {} #second {} </code> Desirable result: second first
You can use CSS Flexible Boxes for this. Specifically the `order` property. In this example, I've added width and background-color to help visualize. Please note that browser support for CSS Flexible Boxes is limited to modern browsers such as IE 10+, Chrome 21+, Firefox 20+ and may not work well in mobile browsers (especially older ones). .container { display: flex; flex-direction: column; } #first { order: 2; width: 10em; margin-top: 1em; background-color: orange; } #second { order: 1; width: 10em; background-color: yellow; } <div class='container'> <div id='first'> first </div> <div id='second'> second </div> </div>
How to convert Android.Resource.Color to Android.Graphics.Color <sep> I have a value of <code>Android.Resource.Color</code> like <code>Android.Resource.Color.HoloOrangeDark</code>. I want to covert it to a <code>Android.Graphics.Color</code>. How can I do that?
`Resources.GetColor` has been deprecated. Make sure you use `ContextCompat.GetColor` instead. So `Resources.GetColor(Resource.Color.HoloOrangeDark);` will become `int colorInt = ContextCompat.GetColor(this.Context, Resource.Color.HoloOrangeDark);` ContextCompat returns an `int`, so to get a `Color` out of it, just create a new `Color` and pass in the `int`. `Color color = new Color(colorInt);`
Snapchat-like swipe navigation between views in Xcode 6 and Swift) <sep> I've been trying to implement swipe navigation between View Controllers in my app using the Swipe Gesture Recognizer and embeded Navigation Controller, but it doesn't look even close to the Snapchat's nav. What would be the most efficient and appropiate way to implement such functionality? I'm quite a newbie to Swift and programming really, and I would appreciate every helpful comment.
The short version is to use a container view controller with a scrollView inside the controller. You then create separate view controllers for each screen you want in the application, and make those view controllers' parent the container view controller. A GitHub repo with sample code can be found here.
Best practices on GitHub repos, to Fork or create a New Branch <sep> I'm looking for the best practice, forking vs branching on GitHub. I've read this Forking vs. Branching in GitHub, but it's not relevant. Our team of 5 people are working on the same repository, and we would like to avoid merging problems, conflicts or regression in the code. The goal is for the 5 persons to work on different parts of the project, often on the same file. I would like to know if it's worth it to : fork the project, work and create pull requests, so each persons can review the code easily, or create a new branch - work and merge on master when work is done.
To me, the best practice when dealing with a project with more than one developer is to use the Gitflow branching model. First, the master branch will now only be used to keep track of the releases of your app, major, minor, or patch versions, following Semantic Versioning. The develop branch will be the core of your project, since it will bridge the gap between the different features and your releases. This system helps to reduce the number of merges, just as a simple branching system will do, but adds semantic logic and the friendly, simple commands that come with it. For more info about Gitflow, you can follow this link.
binary operator expected error when checking if a file with full pathname exists <sep> <code>pathname=$(cat $HOME/.rm.cfg) if [ ! -z $pathname/$1 ] </code> <code>.rm.cfg</code> is a file that contains the following directory <blockquote> /home/username/deleted1 </blockquote> <code>$1</code> is the name of a file eg. glass why does the line if <code>[ ! -z $pathname/$1 ]</code> give a binary operator expected error.
I faced the same error (binary operator expected) when receiving more than one word for some variable when using it as shown below: ```bash if [ ! -z ${variable} ]; ``` So to resolve this error, I changed it to: ```bash if [[ ! -z ${variable} ]]; ```
How to get all data from NetworkStream <sep> I am trying to read all data present in the buffer of the Machine connected through <code>TCP/IP</code> but i don't know why i am not getting all data ,some data is getting Missed. Here is the code that i am using .. <code>using (NetworkStream stream = client.GetStream()) { byte[] data = new byte[1024]; int numBytesRead = stream.Read(data, 0, data.Length); if (numBytesRead > 0) { string str= Encoding.ASCII.GetString(data, 0, numBytesRead); } } </code> Please tell me what i am missing to get all the data from the machine. Thanks in advance..
The problem with your code is that you will not get all the data if the data size is bigger than the buffer size (1024 bytes in your case), so you have to read the stream inside the loop. Then you can write all the data inside a `MemoryStream` until the end of the `NetworkStream`. ```C# string str; using (NetworkStream stream = client.GetStream()) { byte[] data = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { int numBytesRead; while ((numBytesRead = stream.Read(data, 0, data.Length)) > 0) { ms.Write(data, 0, numBytesRead); } str = Encoding.ASCII.GetString(ms.ToArray(), 0, (int)ms.Length); } } ```
Git ignoring all minified suffixed files <sep> I currently have something like: <code>javascripts/ plugin.js plugin.min.js stylesheets/ style.css style.min.css </code> How would I get all <code>.gitignore</code> to ignore all minified (<code>.min</code>) files? Would something like <code>**/*.min.*</code> work?
You have several solutions, depending on what you really need. Ignore all minified files in your project: `*.min.*`. Ignore all minified files in a folder: `assets/*.min.*`. Ignore only JS/CSS minified files in your project: `*.min.js *.min.css`.
Turn off designated initializer checking in Xcode 6 <sep> I'm getting the compile error: <code>error: convenience initializer missing a 'self' call to another initializer [-Werror,-Wobjc-designated-initializers] </code> Compile-checked designated initializers might be a good thing, but if I don't want deal with that right now, how can I turn this off?
Following on from Clay's answer: Method 3 You might want to suppress the warning on one occurrence, not all of them: ``` #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-designated-initializers" - (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { // do whatever I was doing.... } return self; } #pragma clang diagnostic pop ``` EDIT: However, I've only actually used this once myself. I find it the same amount (or a little more) effort just to do it properly if it's a single case. So flag up your constructor with `NS_DESIGNATED_INITIALIZER`. And if it then complains about the `init` method not being overridden, add an `init` method to your header with `NS_UNAVAILABLE`.
android: command not found <sep> I tried to make a <code>.jar</code> file from a cloned project: <code>android update project -p . </code> but got the error: <blockquote> android: command not found </blockquote> I tried to set path to Android SDK, but it didn't help: <code>export ANDROID_HOME=D:\java\android-sdk export PATH=$ANDROID_HOME\tools:$PATH export PATH=$ANDROID_HOME\platform-tools:$PATH </code> Is it possible to solve this problem? UPD: I'm using Git Shell from this software: http://git-scm.com/download/win
Finding the Android SDK on Mac and Adding to PATH To fix the "android: command not found" error, follow these two easy steps (Linux and Mac): 1) Export your Android SDK path to the `ANDROID_HOME` variable: ```bash $ export ANDROID_HOME=~/Android/Sdk ``` (change "~" to "$HOME" on Mac) 2) Export the SDK tools path to the `PATH` variable: ```bash $ export PATH=$ANDROID_HOME/tools:$PATH ``` That's it! Run the `android` command again to make sure it works properly.
Can't run "pod install" in jenkins <sep> My slave machine of Jenkins is Mac 10.8. Jenkins run job on my slave machine and run shell command of cocoapods below: <code>pod install </code> and got error from console output of Jenkins job, please check below: <code>pod: command not found </code> I tried to run this command "pod install" in local's terminal of this slave machine and gets succeeds. could you kindly help on me how to fix this problem? Thanks.
In my case, my Ruby is installed by rvm. I need to load rvm to find the pod command. What I did was add this line `#!/bin/bash -l` at the beginning of the Jenkins job.
Where to store constant values in swift? <sep> I'm trying to build my first spritekit game in swift. I don't understand where to store constants so I can make them available to the whole project. I have some experience with C++ and I used to create a Constants.h file. Is there such thing in Swift? What's the recommended practice to do this? Right now I'm using a struct with static constants but I'm not sure if it's the right way to do it: <code>struct Constants { static let gravity : Int = 20 } </code>
```swift struct Constants { static let buildName = "Orange-Pie" struct FacebookConstants { static let clientId = "asdasdsa" } struct TwitterConstants { static let clientId = "asdasdsa" } } use: Constants.FacebookConstants.clientId ```
How to I start a rails console with pry turned off? <sep> Sometimes I have reason to want to start the rails console as an irb repl rather than pry (as awesome as pry is). It will default to pry because pry has in the Gemfile. Hows is that done nowadays? I think there used to be a --irb option when running <code>rails console</code> but that seems to be gone now. I get a deprecation error message when I try it. More details If I just run "rails console" it takes me to pry. If I run "rails console -irb=irb": <code>$ rails c -irb=irb --irb option is no longer supported. Invoke `/your/choice/of/ruby script/rails console` instead </code> Relevent lines from my Gemfile: <code>gem 'rails', '3.2.18' gem 'pry-rails' gem 'pry-plus' </code>
Launching pry when calling `rails console` or `rails c` is set up by the `pry-rails` gem. If you look in the `pry-rails` issues, there is one that describes a solution. Define the environment variable `DISABLE_PRY_RAILS` as `1`. So you can call `rails console` without pry with: `DISABLE_PRY_RAILS=1 rails c`.
unstaged files gone after git reset --hard <sep> I tried the <code>git reset --hard HEAD@{n}</code> from <code>git reflog</code> and I lost everything with my current unstaged files :'( the unstaged files is the last <code>git add</code> I did, before then I tried <code>git reset</code> to the last <code>git commit</code>. And all my files gone, I can't go back to the <code>git add</code> before last commit :'(
It's not clear if you lost files in your working directory or files in the index. You say you lost your "unstaged files," but then you mention you might have run "git add". "Unstaged files" are lost for good. Staged files can be recovered with `git fsck --full --unreachable --no-reflog`. For each file added, there will be a lost blob object, and for each directory entry, there will be a tree object. You would recover your file changes by doing `git cat-file -p SHA` for each file that you had modified. For example: (master) `vi bar` (master) `vi baz` (master) `vi foo` (master) `git add foo bar baz` (master) `git reset --hard HEAD` HEAD is now at ead8fa2 initial (master) `git fsck --full --unreachable --no-reflog` Checking object directories: 100% (256/256), done. unreachable blob 0c29287001b29159f11c4e8a320bce7e9789c00b unreachable blob 1524d3478e3d0b92866a53239b10bcd4b3838c4d unreachable blob 97b724e770249816c61d8a526415986208ed7e15 // take a look at one of the objects (master) `git cat-file -p 0c29287001b29159f11c4e8a320bce7e9789c00b` changes for bar // Here, based on inspecting the output, I can determine that 0c29287 was the file "bar" (master) `git cat-file -p 0c29287 > bar` (note I didn't get any lost trees when I tested, so this part may not work) If you modified a whole bunch of files, it is probably easier to recover via the tree object instead of individual files: `git read-tree SHA`, where SHA is the lost tree object for the root tree.
Type 'ViewController' does not conform to protocol 'UICollectionViewDataSource' <sep> I am following a tutorial where using the <code>UIPickerController</code> to operate the camera. However when implementing <code>UICollectionViewDatsaSource</code>, I get an error saying that <code>ViewController</code> does not conform to the <code>UICollectionViewDataSource</code> protocol. <code>class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate </code> Any idea on how to fix this problem?
You must implement these two methods in your `ViewController` class: `func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {}` `func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {}` P.S. - Your function prototypes should exactly match the above functions. (Remove any `!` if present.)
R: Add text to plots in lower rightern corner outside plot area <sep> I am plotting multiple graphs in baseR and I am trying to plot a text in the lower rightern corner of my plots. I tried using <code>mtext()</code> but this doesn't give me the desired result. How would you do this? The idea in the end is to generate something like the graphic below. How could I do this? Here is my code I use to generate the plots. <code>xy <- data.frame(NAME=c("NAME1", "NAME1","NAME1","NAME1","NAME2","NAME2","NAME2"),ID=c(47,47,47,47,259,259,259),YEAR=c(1932,1942,1965,1989,2007,2008,2014),VALUE=c(0,NA,-6,-16,0,-9,-28), test=c("text1","text1","text1","text1","text2","text2","text2")) # split data by index ind <- split(x = xy,f = xy[,'ID']) plot1 <- function(x) { fname <- paste0(x[1, 'ID'], '.png') png(fname, width=1679, height=1165, res=150) par(mar=c(6,8,6,5)) plot(x = c(1946, 2014), y = range(x$VALUE, na.rm=TRUE), type='n', main=x[1, 'NAME'], xlab="Time [Years]", ylab="Value [m]") axis(2, at = seq(-100000, 100000, 100), cex.axis=1, labels=FALSE, tcl=-0.3) points(x[,c('YEAR','VALUE')], type="l", lwd=2) points(x[,c('YEAR','VALUE')], type="p", lwd=1, cex=0.5, pch=21, bg='white') abline(h=0) mtext(x$test, side=1, ) dev.off() } plot2 <- function(x) { fname <- paste0(x[1, 'ID'], '.png') png(fname, width=1679, height=1165, res=150) par(mar=c(6,8,6,5)) plot(x[,c('YEAR','VALUE')], type='n', main=x[1, 'NAME'], xlab="Time [Years]", ylab="value [m]") axis(2, at = seq(-100000, 100000, 100), cex.axis=1, labels=FALSE, tcl=-0.3) points(x[,c('YEAR','VALUE')], type="l", lwd=2) points(x[,c('YEAR','VALUE')], type="p", lwd=1, cex=0.5, pch=21, bg='white') abline(h=0) mtext(x$test, side=1) dev.off() } lapply(ind, function(x) ifelse(any(x$YEAR < 1946 & x$YEAR < 2014), plot2(x), plot1(x))) </code>
With `mtext()` you can put your text at the plot margin. In your case, you can try playing with the parameters `line` and `at`. See `help(mtext)`. For example: `plot(1:10,10:1) mtext('text is here', side=1, line=3.5, at=9)`
How can I select a specific column from each row in a Pandas DataFrame? <sep> I have a DataFrame in this format: <code> a b c 0 1 2 3 1 4 5 6 2 7 8 9 3 10 11 12 4 13 14 15 </code> and an array like this, with column names: <code>['a', 'a', 'b', 'c', 'b'] </code> and Im hoping to extract an array of data, one value from each row. The array of column names specifies which column I want from each row. Here, the result would be: <code>[1, 4, 8, 12, 14] </code> Is this possible as a single command with Pandas, or do I need to iterate? I tried using indexing <code>i = pd.Index(['a', 'a', 'b', 'c', 'b']) i.choose(df) </code> but I got a segfault, which I couldnt diagnose because the documentation is lacking.
You could use `lookup`, e.g., `>>> i = pd.Series(['a', 'a', 'b', 'c', 'b']) >>> df.lookup(i.index, i.values) array([1, 4, 8, 12, 14])` where `i.index` could be different from `range(len(i))` if you wanted.
Draw a separator or lines between subplots <sep> I have plot four subplots in one figure and they shares xaxis with each other. However, there is no separator between those subplots. I want to draw a line between each of them. or is there any separator could be adopted in those subplots? At least there should be separator between the subplots' axis. I think it should be looked as below figure. \------------------------------------ <code> subplot1 </code> \------------------------------------ <code> subplot2 </code> \------------------------------------ <code> ... </code> \------------------------------------
```python import numpy as np import matplotlib.pyplot as plt import matplotlib.transforms as mtrans fig, axes = plt.subplots(3, 2, squeeze=False) for i, ax in enumerate(axes.flat): ax.plot([1, 2]) ax.set_title('Title ' + str(i + 1)) ax.set_xlabel('xaxis') ax.set_ylabel('yaxis') # Rearrange the axes for no overlap fig.tight_layout() # Get the bounding boxes of the axes including text decorations r = fig.canvas.get_renderer() get_bbox = lambda ax: ax.get_tightbbox(r).transformed(fig.transFigure.inverted()) bboxes = np.array(list(map(get_bbox, axes.flat)), mtrans.Bbox).reshape(axes.shape) # Get the minimum and maximum extent, get the coordinate half-way between those ymax = np.array(list(map(lambda b: b.y1, bboxes.flat))).reshape(axes.shape).max(axis=1) ymin = np.array(list(map(lambda b: b.y0, bboxes.flat))).reshape(axes.shape).min(axis=1) ys = np.c_[ymax[1:], ymin[:-1]].mean(axis=1) # Draw a horizontal line at those coordinates for y in ys: line = plt.Line2D([0, 1], [y, y], transform=fig.transFigure, color="black") fig.add_artist(line) plt.show() ```
Error: Non-static method 'findViewById(int)' cannot be referenced from a static context <sep> I am using Android Studio (Beta), and while using this java code in 'onCreateView()', I get an error. <code>ListView listView = (ListView) findViewById(R.id.someListView); </code> This is the error: <code>Non-static method 'findViewById(int)' cannot be referenced from a static context </code> How do I fix this?
Assuming you have a static fragment inner class inside an activity, you're trying to call the activity's `findViewById()` which you cannot do in a static inner class that doesn't hold a reference to the parent. In `onCreateView()`, you need to call it on the root view you just inflated, e.g., `ListView listView = (ListView) rootView.findViewById(R.id.someListView);`
send email using SMTP SSL/Port 465 <sep> I need to send email using SMTP SSL/Port 465 with my bluehost email.I can't find working code in google i try more than 5 codes. So, please any have working code for sending email using SMTP SSL/port 465 ?
Just to clarify the solution from Dave, here's how I got mine to work with my SSL server (I'm not using Gmail but it's still the same). Mine emails if a specific file is not there (for internal purposes, that is a bad thing). ```python import smtplib import os.path from email.mime.text import MIMEText if (os.path.isfile("filename")): print("File exists, all went well") else: print("File does not exist, emailing") msg = MIMEText("WARNING, FILE DOES NOT EXIST, THAT MEANS UPDATES MAY NOT HAVE BEEN RUN") msg['Subject'] = "WARNING WARNING ON FIRE FIRE FIRE!" # Put your host and port here s = smtplib.SMTP_SSL('host:port') s.login('email', 'serverpassword') s.sendmail('from', 'to', msg.as_string()) s.quit() print("Done") ```
NSFastEnumeration in Swift <sep> I am trying to convert an Objective-C project to swift, but I am unable to find how to use NSFastEnumeration for an object of a class that conforms to NSFastEnumeration. Here is the code in ObjC: <code>// get the decode results id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults]; ZBarSymbol *symbol = nil; for(symbol in results) // just grab the first barcode break; </code> so far I tried to find how to do this, but this doe not seems work, here is the swift code: <code>var results: ZBarSymbolSet = infoDictionary?.objectForKey(ZBarReaderControllerResults) as ZBarSymbolSet var symbol : ZBarSymbol? = nil; for symbol in results { //just grab first barcode break; } </code> the error comes in for condition - "ZBarSymbolSet" does not have a member named "Generator" What am I doing wrong? Here is the screen shot
After a while poking around the Swift framework files, I finally found this nice class called `NSFastGenerator`. `NSSet` and friends seem to be using the same `Generator`. For `ZBarSymbolSet`, here's how you'd extend it to support `for-in` loops: ```swift extension ZBarSymbolSet: SequenceType { public func generate() -> NSFastGenerator { return NSFastGenerator(self) } } ``` Update: Looks like Swift 2.0's protocol extensions fixed this for us!
how to execute pgsql script in pgAdmin? <sep> I want to execute some pgScript directly from the pgAdmin editor UI. <code>FOR i IN 1..10 LOOP PRINT i; -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop END LOOP; </code> But I always got <code>[ERROR ] 1.0: syntax error, unexpected character </code> I also tried to wrap the code with do$$...$$, but does not solve the problem.
Apart from Clodoaldo Neto's answer, you can also try this: ```sql DO $$ BEGIN FOR i IN 1..10 LOOP RAISE NOTICE '%', i; -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop END LOOP; END $$ ```
Creating a vector of indices of a sorted vector <sep> Variable <code>x</code> is a vector of <code>n</code> ints, and I want to sort the vector in ascending order. However, for reasons outside the scope of this question, I want to vector to remain untouched. Therefore, rather than actually sorting the contents of <code>x</code>, I want to create another vector of <code>n</code> indices, where each index refers to the respective value in <code>x</code>, if <code>x</code> were to have been sorted. For example: <code>std::vector<int> x = {15, 3, 0, 20}; std::vector<int> y; // Put the sorted indices of x into the vector y for (int i = 0; i < 4; i++) { std::cout << y[i]; } </code> Should give the output: <code>2 1 0 3 </code> Corresponding to values in x: <code>0 3 15 20 </code> I can think of plenty of timely ways of implementing this, but I'm wondering whether the STL has something build-in to perform this efficiently for me?
```cpp #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> x = {15, 3, 0, 20}; std::vector<int> y(x.size()); std::size_t n = 0; std::generate(std::begin(y), std::end(y), [&]{ return n++; }); std::sort(std::begin(y), std::end(y), [&](int i1, int i2) { return x[i1] < x[i2]; }); for (auto v : y) std::cout << v << ' '; return 0; } ```
how to calculate mean/median per group in a dataframe in r <sep> I have a dataframe recording how much money a costomer spend in detail like the following: <code>custid, value 1, 1 1, 3 1, 2 1, 5 1, 4 1, 1 2, 1 2, 10 3, 1 3, 2 3, 5 </code> How to calcuate the charicteristics using mean,max,median,std, etc like the following? Use some apply function? And how? <code>custid, mean, max,min,median,std 1, .... 2,.... 3,.... </code>
To add to the alternatives, here's `summaryBy` from the "doBy" package, with which you can specify a list of functions to apply. ```R library(doBy) summaryBy(value ~ custid, data = mydf, FUN = list(mean, max, min, median, sd)) # custid value.mean value.max value.min value.median value.sd # 1 1 2.666667 5 1 2.5 1.632993 # 2 2 5.500000 10 1 5.5 6.363961 # 3 3 2.666667 5 1 2.0 2.081666 ``` Of course, you can also stick with base R: ```R myFun <- function(x) { c(min = min(x), max = max(x), mean = mean(x), median = median(x), std = sd(x)) } tapply(mydf$value, mydf$custid, myFun) # $`1` # min max mean median std # 1.000000 5.000000 2.666667 2.500000 1.632993 # # # $`2` # min max mean median std # 1.000000 10.000000 5.500000 5.500000 6.363961 # # # $`3` # min max mean median std # 1.000000 5.000000 2.666667 2.000000 2.081666 cbind(custid = unique(mydf$custid), do.call(rbind, tapply(mydf$value, mydf$custid, myFun))) # custid min max mean median std # 1 1 1 5 2.666667 2.5 1.632993 # 2 2 1 10 5.500000 5.5 6.363961 # 3 3 1 5 2.666667 2.0 2.081666 ```
Makefile rule depend on directory content changes <sep> Using Make is there a nice way to depend on a directories contents. Essentially I have some generated code which the application code depends on. The generated code only needs to change if the contents of a directory changes, not necessarily if the files within change their content. So if a file is removed or added or renamed I need the rule to run. My first thought is generate a text file listing of the directory and diff that with the last listing. A change means rerun the build. I think I will have to pass off the generate and diff part to a bash script. I am hoping somehow in their infinite intelligence might have an easier solution.
Kudos to gjulianm who got me on the right track. His solution works perfectly for a single directory. To get it working recursively, I did the following: ``` ASSET_DIRS = $(shell find ../../assets/ -type d) ASSET_FILES = $(shell find ../../assets/ -type f -name '*') codegen: ../../assets/ $(ASSET_DIRS) $(ASSET_FILES) generate-my-code ``` It appears now any changes to the directory or files (add, delete, rename, modify) will cause this rule to run. There is likely some issue with file names here (spaces might cause issues).
c++ treat the address location as an integer <sep> I want to know if there is anyway that I can store the address location of a variable as an integer value. For example, let's say that I have a number stored in some location in memory <code>int i= 20; </code> and we know that for example, the location of the variable i is 0x77C79AB2. e.g. <code>int * ip = &i; </code> so we know that ip = 0x77C79AB2. But at this point the variable ip is just a pointer. But let's say that I now want to store the address location 0x77C79AB2 into a variable of type int (NOT of type Pointer). so, somehow I want to be able to make another variable of type (int) to actually store the number 0x77C79AB2 as a value not as a address location. <code>int a = 0x77C79AB2; </code> So, I could do whatever I want with the variable a. For example, I want to treat a as an integer and add a hex number 0x20 to it. e.g. <code>int b = a + 0x20 = 0x77C79AB2 + 0x20 = 0x77C79AD2 </code> Is this possible? How could I make this assignment ?
Pointers are not integers. If you want to store a pointer value, you should almost always store it in a pointer object (variable). That's what pointer types are for. You can convert a pointer value to an integer using a cast, either a C-style cast: `int foo; int addr = (int)&foo;` or using a C++-style cast: `int foo; int addr = reinterpret_cast<int>(&foo);`. But this is rarely a useful thing to do, and it can lose information on systems where `int` happens to be smaller than a pointer. C provides two typedefs, `intptr_t` and `uintptr_t`, that are guaranteed to be able to hold a converted pointer value without loss of information. (If no integer types are wide enough for this, `intptr_t` and `uintptr_t` will not be defined). These are declared in the `<stdint.h>` header, or `<cstdint>` in C++: `#include <stdint.h> // ... int foo; uintptr_t addr = reinterpret_cast<uintptr_t>(&foo);` You can then perform integer arithmetic on the value -- but there's no guarantee that the result of any arithmetic is meaningful. I suspect that you're trying to do something that doesn't make much sense. There are rare cases where it makes sense to convert a pointer value to an integer and even rarer cases where it makes sense to perform arithmetic on the result. Reading your question, I don't see any real indication that you actually need to do this. What exactly are you trying to accomplish? It's likely that whatever you're trying to do, there's a cleaner way to do it.
Why does Haskell's foldr NOT stackoverflow while the same Scala implementation does? <sep> I am reading FP in Scala. Exercise 3.10 says that <code>foldRight</code> overflows (See images below). As far as I know , however <code>foldr</code> in Haskell does not. http://www.haskell.org/haskellwiki/ <code>-- if the list is empty, the result is the initial value z; else -- apply f to the first element and the result of folding the rest foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) -- if the list is empty, the result is the initial value; else -- we recurse immediately, making the new initial value the result -- of combining the old initial value with the first element. foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs </code> How is this different behaviour possible? What is the difference between the two languages/compilers that cause this different behaviour? Where does this difference come from ? The platform ? The language? The compiler? Is it possible to write a stack-safe foldRight in Scala? If yes, how?
Haskell is lazy. The definition `foldr f z (x:xs) = f x (foldr f z xs)` tells us that the behavior of `foldr f z xs` with a non-empty list `xs` is determined by the laziness of the combining function `f`. In particular, the call `foldr f z (x:xs)` allocates just one thunk on the heap, `foldr f z xs` (writing `{...}` for a thunk holding an expression `...`), and calls `f` with two arguments: `x` and the thunk. What happens next is `f`'s responsibility. In particular, if it's a lazy data constructor (like e.g. `(:)`), it will immediately be returned to the caller of the `foldr` call (with the constructor's two slots filled by (references to) the two values). And if `f` demands its value on the right, with minimal compiler optimizations, no thunks should be created at all (or one, at most—the current one), as the value of `foldr f z xs` is immediately needed and the usual stack-based evaluation can be used: `foldr f z [a,b,c,....,n] == a `f` (b `f` (c `f` (... (n `f` z)...)))`. So `foldr` can indeed cause stack overflow, when used with a strict combining function on extremely long input lists. But if the combining function doesn't demand its value on the right immediately, or only demands a part of it, the evaluation will be suspended in a thunk, and the partial result as created by `f` will be immediately returned. Same with the argument on the left, but they already come as thunks, potentially, in the input list.
How to calculate byte length containing UTF8 characters using javascript? <sep> I have textbox, in which the user can enter the characters in ASCII/UTF-8 or a combination of both. Is there any API in javascript which we can calculate the length of string in bytes for the characters entered in textbox. Like if i enter ascii chacter let's say : mystring - the length would be calculated as 8. But when UTF8 characters are entered the characters can be 2/3/4 byte. lets say the character entered : i u , the length in bytes is 5. The textbox can accept max length of 31 characters. But in case if UTF8 characters entered, it will not accept character string : i u i u i u i u i u . the length is 30. Can we restrict the user to enter characters not more than 31 even for UTF8 characters.
As of 2018, the most compatible and reliable way to do this seems to be with the Blob API. `new Blob([str]).size` is even supported in IE10, if anyone uses that anymore.
SpringData JPA Repository Method Query with a like? <sep> In Spring-data JPA, is there anyway to create a method query that is essentially searches by like?? I have the following method query <code>public MakeModel findByModelIgnoreCase(String model); </code> What I really want is a like expression. Do I need to just create a Criteria or a @Query annotation? Am I asking too much? <code> //Stupid example of what I want to be able to do public MakeModel findByFuzzyModelIgnoreCase(String model); </code> Really I guess at the heart of it, I want to do a table search. I'm using Hibernate underneath Spring Data so I guess I could use some search api like Hibernate Search. I'm open to recommendations here.
If you don't want to add "%" manually, you can use the following query methods: ``` MakeModel findByModelStartingWithIgnoreCase(String model); //SQL => LIKE 'model%' MakeModel findByModelEndingWithIgnoreCase(String model); //SQL => LIKE '%model' MakeModel findByModelContainingIgnoreCase(String model); //SQL => LIKE '%model%' ```
Java Double Round off to 2 decimal always <sep> I am trying to round off the double values to 2 decimal digits, however it's not working in all scenarios <code>public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } public static void main(String[] args) { System.out.println(round(25.0,2)); //25.0 - expected 25.00 System.out.println(round(25.00d,2)); //25.0 - expected 25.00 System.out.println(round(25,2)); //25.0 - expected 25.00 System.out.println(round(25.666,2)); //25.67 } </code> In short, no matter whether decimal exists or not, always hold the values upto 2 decimal even if it needs to pad additional zeros. Any help is appreciated!
There are two things that can be improved in your code. First, casting double to BigDecimal in order to round it is a very inefficient approach. You should use `Math.round` instead: ``` double value = 1.125879D; double valueRounded = Math.round(value * 100D) / 100D; ``` Second, when you print or convert a real number to a string, you may consider using `System.out.printf` or `String.format`. In your case, using the format "%.2f" does the trick. ``` System.out.printf("%.2f", valueRounded); ```
How to convert TTF to FNT with Fontforge <sep> I have a TTF font, that needs to be converted in FNT (and ideally in pcf too). I tried Fontforge, but when I loaded font and chose to generate font - nothing could be selected from the list on the right, except "No bitmap fonts" though there was WIN FNT. Can anyone help me with this?
I recommend trying Hiero. It can convert any installed system font or font file into a `.fnt` file. You can download it from BadLogicGames. Open runnable-hiero.jar. Select the font you want to convert. For installed fonts on your PC, select "System." For downloaded font files, select "File" and choose a font by clicking the "..." button. In the menubar, select "File" > "Save BMFont files (text)." Choose a save location and filename ending in `.fnt`. If done correctly, you should have two files: `font_name.fnt` and `font_name.png`.
Sencha Cmd build - Failed creating background process <sep> I'm trying to build extjs5 application with Cmd v5.0.0.160. I have ruby2.0 installed and sencha cmd on my PATH var. Here is the error that I get when running <code>sencha app build</code>: <code>... [INF] Capturing theme image [ERR] [ERR] BUILD FAILED [ERR] com.sencha.exceptions.ExProcess: Failed creating background process [ERR] at com.sencha.command.plugin.PluginManager.executeRe [ERR] verseFirst(PluginManager.java:134) [ERR] [ERR] Total time: 9 seconds [ERR] The following error occurred while executing this line: /local/dev/PROJECTS2/loc-ext/loc-ext/.sencha/app/build-impl.xml:326: The following error occurred while executing this line: /local/dev/PROJECTS2/loc-ext/loc-ext/.sencha/app/slice-impl.xml:239: The following error occurred while executing this line: /local/dev/PROJECTS2/loc-ext/loc-ext/.sencha/app/slice-impl.xml:240: The following error occurred while executing this line: /local/dev/PROJECTS2/loc-ext/loc-ext/.sencha/app/slice-impl.xml:111: com.sencha.exceptions.ExProcess: Failed creating background process </code> The application is working OK in development mode (sencha app watch). Since it looks like it's about themes, I'm not using custom theme but ext-theme-neptune. Does anybody have a clue what is it about? I will appreciate any idea! Solution: The debug mode showed that the problem was in missing directory <code>Cmd/5.0.0.160/bin/linux-x64</code>. However there was <code>Cmd/5.0.0.160/bin/linux</code> dir, therefor soft-linking <code>linux</code> to <code>linux-x64</code> fixed the issue.
Same issues with EXT5.0 + EXT CMD Vers. 5.1.2.52 (causing EXT CMD cannot start RUBY). It hangs with Error: ``` [ERR] com.sencha.exceptions.ExProcess: Failed creating background process ``` My solution on Windows (Here Win7, 64Bit): 1) Install Ruby (in my case 1.9.3) 2) Set %PATH% in System Settings to Ruby's EXE (in my case c:\ruby193\bin) 3) Restart CMD window 4) Try again. That solves my problem.
How to create Swift empty two dimensional array with size <sep> I try to do smth like this: <code>let myArray: [[MyClass]] = [5,5] </code> where [5,5] is size of array. I can't do this.
If you want to make a multidimensional array of value types (i.e., `Int`s, `String`s, structs), the syntax in codester's answer works great: Swift 4: `var arr = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)` Swift Earlier: `var arr = [[Int]](count: 5, repeatedValue: [Int](count: 5, repeatedValue: 0))` `arr[0][1] = 1 // arr is [[0, 1, 0, 0, 0], ...` If you make a multidimensional array of reference types (i.e., classes), this gets you an array of many references to the same object: `class C { var v: Int = 0 }` `var cArr = [[C]](count: 5, repeatedValue: [C](count: 5, repeatedValue: C()))` `// cArr is [[{v 0}, {v 0}, {v 0}, {v 0}, {v 0}], ...` `cArr[0][1].v = 1` `// cArr is [[{v 1}, {v 1}, {v 1}, {v 1}, {v 1}], ...` If you want to make an array (uni- or multidimensional) of reference types, you might be better off either making the array dynamically: `var cArr = [[C]]()` `for _ in 0..<5 { var tmp = [C]()` `for _ in 0..<5 { tmp += C() }` `cArr += tmp }` `// cArr is [[{v 0}, {v 0}, {v 0}, {v 0}, {v 0}], ...` `cArr[0][1].v = 1` `// cArr is [[{v 0}, {v 1}, {v 0}, {v 0}, {v 0}], ...` (See slazyk's answer for equivalent shorter syntax using `map()`.) Or making an array of optionals and filling in their values: `var optArr = [[C?]](count: 5, repeatedValue: [C?](count: 5, repeatedValue: nil))` `// optArr is [[nil, nil, nil, nil, nil], ...` `optArr[0][1] = C()` `// optArr is [[nil, {v 0}, nil, nil, nil], ...`