instruction
stringlengths
22
34.6k
input
stringclasses
1 value
output
stringlengths
70
4.33k
Is there a way to view all images loaded in the browser using Chrome Developer Tools? <sep> I know that I am supposed to be able to see this in the "resources" tab -section of Chrome developer tools. Maybe I am not getting something, but I don't see any images listed in this section. Does anyone know if / how this can be accomplished?
Open Google Chrome Console (F12). Go to the Network tab. Enable the Filter, if it's not enabled. Select the "Img" tag to filter for image requests. Refresh the page to see a list of all images as they are requested.
Liquibase: How to Set Foreign Key(s) Constraint in Column Tag? <sep> How can I configure foreign keys through column tag attributes <code>foreignKeyName</code> and <code>references</code>? The only example I've found demonstrates how to add foreign keys after the fact.
```yaml - changeSet: id: create_account_table author: ankit changes: - createTable: tableName: account columns: - column: name: accn_id type: uuid constraints: primaryKey: true primaryKeyName: pk_account - changeSet: id: create_table_abc author: ankit changes: - createTable: tableName: abc columns: - column: name: id type: uuid constraints: primaryKey: true primaryKeyName: pk_abc - column: name: accn_id type: UUID constraints: nullable: false foreignKeyName: fk_abc_account references: account(accn_id) ```
How can I use a cursor.forEach() in MongoDB using Node.js? <sep> I have a huge collection of documents in my DB and I'm wondering how can I run through all the documents and update them, each document with a different value.
Using the `mongodb` driver, and modern NodeJS with async/await, a good solution is to use `next()`: ```javascript const collection = db.collection('things'); const cursor = collection.find({ bla: 42 }); // find all things where bla is 42 let document; while ((document = await cursor.next())) { await collection.findOneAndUpdate({ _id: document._id }, { $set: { blu: 43 } }); } ``` This results in only one document at a time being required in memory, as opposed to e.g. the accepted answer, where many documents get sucked into memory before processing starts. In cases of "huge collections" (as per the question), this may be important. If documents are large, this can be improved further by using a projection, so that only the required fields of documents are fetched from the database.
Android Studio - Push failed: fatal: Could not read from remote repository <sep> I have a git project at Android Studio and a remote at BitBucket and I changed it to use SSH instead of HTTPS. I can make everything work using Atlassian's SourceTree, but in Android Studio every time I try to push the project it says <blockquote> Push failed: fatal: Could not read from remote repository. </blockquote> Does anyone have a clue about what could be happening?
This is probably an IntelliJ problem. Your keys are managed natively by SSH, and IntelliJ has its own SSH program. Go to the settings, search "Git" -> "SSH Executable," then choose "native." As seen here: git with IntelliJ IDEA: Could not read from remote repository.
rake db:create throws "database does not exist" error with postgresql <sep> I'm using rails 4.1.5 with postgresql 9.1 under Debian 7, and I'm not able to create a database in my development environment. When I run <code>bin/rake db:create </code> I get <code>home/rs/.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql_adapter.rb:898:in `rescue in connect': FATAL: database "direct-dev" does not exist Run `$ bin/rake db:create db:migrate` to create your database (ActiveRecord::NoDatabaseError) from /home/rs/.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql_adapter.rb:888:in `connect' from ... </code> I am trying to create the database so, naturally, it does not exist. However rails should create it ... Here's my config/database.yml: <code>default: &default adapter: postgresql encoding: unicode pool: 5 development: <<: *default database: direct-dev </code> And here's a part of the postgresql log: <code>2014-09-01 19:30:40 CEST LOG: connection received: host=[local] 2014-09-01 19:30:40 CEST LOG: connection authorized: user=rs database=direct-dev 2014-09-01 19:30:40 CEST FATAL: database "direct-dev" does not exist </code> Do you have any pointers? I've been at this for more than an hour, and still can't understand why this is happening ... Thanks!
Rails 4.1 ships with Spring preloader, and <blockquote> New Rails 4.1 applications will ship with "springified" bin stubs. This means that `bin/rails` and `bin/rake` will automatically take advantage of preloaded Spring environments. </blockquote> which means the "springified" `bin/rake` will attempt to preload the app, which in turn will attempt to run the initializers resulting in the problem you're seeing. To fix/work around this, you want to run the initial setup rake tasks without Spring. One way to achieve that is to run it with Bundler instead: `bundle exec rake db:create`.
Await Tasks in Test Setup Code in xUnit.net? <sep> The exact situation is I'm doing E2E tests with Protractor.NET (.NET port of AngularJS's Protractor E2E framework) and I would like to make some web requests (and the API -- <code>System.Net.Http.HttpClient</code> -- has all Async/<code>Task</code> methods) to Arrange my test before I Act/Assert, only I need to do this same Arrange-ing for several tests. I'm using xUnit.net as my test runner they use an interface (<code>IUseFixture<T></code>) for per-fixture setup code. It would be nice if there was a <code>IAsyncUseFixture<T></code> that had a <code>Task SetFixtureAsync(T t);</code> or something. I don't think such a thing exists. Additionally I don't think constructors can use <code>await</code> either, and constructors are the only other way to execute the same block of code per-test in xUnit.net. What are my options? <code>.Result</code>? Isn't that bad practice (deadlock)?
```csharp xUnit has an `IAsyncLifetime` interface for async setup/teardown. The methods you need to implement are `Task InitializeAsync()` and `Task DisposeAsync()`. `InitializeAsync` is called immediately after the class has been created, before it is used. `DisposeAsync` is called just before `IDisposable.Dispose` if the class also implements `IDisposable`. e.g. ```csharp public class MyTestFixture : IAsyncLifetime { private string someState; public async Task InitializeAsync() { await Task.Run(() => someState = "Hello"); } public Task DisposeAsync() { return Task.CompletedTask; } [Fact] public void TestFoo() { Assert.Equal("Hello", someState); } } ```
Disable magnification gesture in WKWebView <sep> I'm looking for a way to disable the "pinch to zoom" magnification gesture on the iOS implementation of WKWebView. There is a magnification BOOL property available for OS X but it doesn't seem to be available on iOS. WKWebView.h <code>#if !TARGET_OS_IPHONE /* @abstract A Boolean value indicating whether magnify gestures will change the web view's magnification. @discussion It is possible to set the magnification property even if allowsMagnification is set to NO. The default value is NO. */ @property (nonatomic) BOOL allowsMagnification; </code> I've, also, tried look at the WKWebView's gesture recognizers but that seems to be turning up an empty array. I'm assuming the actual recognizers are bured deeper in the component's structure (fairly complex, by the looks of it) and would rather not go digging for them if at all possible. I know of possible hacks that could potentially disable the gesture from firing (selectively passing gestures to the WebView, add child view to capture pinch gesture, etc) but I've always found those introduce lag into the event and want to keep the implementation as clean/hack free as possible.
```swift class MyClass { let webView = WKWebView() init() { super.init() webView.scrollView.delegate = self } deinit() { // Without this, it'll crash when your MyClass instance is deinit'd webView.scrollView.delegate = nil } } extension MyClass: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return nil } } ```
Catching Errors in JavaScript Promises with a First Level try ... catch <sep> So, I want my first level catch to be the one that handles the error. Is there anyway to propagate my error up to that first catch? Reference code, not working (yet): <code>Promise = require('./framework/libraries/bluebird.js'); function promise() { var promise = new Promise(function(resolve, reject) { throw('Oh no!'); }); promise.catch(function(error) { throw(error); }); } try { promise(); } // I WANT THIS CATCH TO CATCH THE ERROR THROWN IN THE PROMISE catch(error) { console.log('Caught!', error); } </code>
```javascript With the new async/await syntax you can achieve this. Please note that at the moment of writing this is not supported by all browsers, you probably need to transpile your code with Babel (or something similar). ``` ```javascript // Because of the "async" keyword here, calling getSomeValue() // will return a promise. async function getSomeValue() { if (somethingIsNotOk) { throw new Error('uh oh'); } else { return 'Yay!'; } } async function() { try { // "await" will wait for the promise to resolve or reject // if it rejects, an error will be thrown, which you can // catch with a regular try/catch block const someValue = await getSomeValue(); doSomethingWith(someValue); } catch (error) { console.error(error); } } ```
Find child element in AngularJS directive <sep> I am working in a directive and I am having problems using the parameter <code>element</code> to find its childs by class name. <code>.directive("ngScrollList", function(){ return { restrict: 'AE', link: function($scope, element, attrs, controller) { var scrollable = element.find('div.list-scrollable'); ... } }; }) </code> I can find it by the tag name but it fails to find it by class name as I can see in the console: <code>element.find('div') [<div class="list-viewport"></div>,<div class="list-scrollable"></div>] element.find('div.list-scrollable') [] </code> Which would be the right way of doing such thing? I know I can add jQuery, but I was wondering if wouldn't that be an overkill....
jQlite (Angular's "jQuery" port) doesn't support lookup by classes. One solution would be to include jQuery in your app. Another is using `querySelector` or `querySelectorAll`: `link: function(scope, element, attrs) { console.log(element[0].querySelector('.list-scrollable')) }` We use the first item in the `element` array, which is the HTML element. `element.eq(0)` would yield the same. Fiddle
What is the difference among the functions doall dorun doseq and for? <sep> What is the difference between the functions <code>doall</code>, <code>dorun</code>, <code>doseq</code>, and <code>for</code> ? I found some information scattered throughout the internet, but I think it would be better to centralize that information here.
`dorun`, `doall`, and `doseq` are all for forcing lazy sequences, presumably to get side effects. `dorun` - don't hold the whole seq in memory while forcing, return `nil`. `doall` - hold the whole seq in memory while forcing (i.e. all of it) and return the seq. `doseq` - same as `dorun`, but gives you a chance to do something with each element as it's forced; returns `nil`. `for` is different in that it's a list comprehension, and isn't related to forcing effects. `doseq` and `for` have the same binding syntax, which may be a source of confusion, but `doseq` always returns `nil`, and `for` returns a lazy seq.
json unmarshal time that isn't in RFC 3339 format <sep> What is the appropriate way to handle deserialization of different time formats in Go? The encoding/json package seems to be entirely rigid in only accepted RFC 3339. I can deserialize into a string, transform that into RFC 3339 and then unmarshal it but I don't really want to do that. Any better solutions?
```go You will have to implement the `json.Marshaler`/`json.Unmarshaler` interfaces on a custom type and use that instead, an example: type CustomTime struct { time.Time } const ctLayout = "2006/01/02|15:04:05" func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) { s := strings.Trim(string(b), "\"") if s == "null" { ct.Time = time.Time{} return } ct.Time, err = time.Parse(ctLayout, s) return } func (ct *CustomTime) MarshalJSON() ([]byte, error) { if ct.Time.UnixNano() == nilTime { return []byte("null"), nil } return []byte(fmt.Sprintf("\"%s\"", ct.Time.Format(ctLayout))), nil } var nilTime = (time.Time{}).UnixNano() func (ct *CustomTime) IsSet() bool { return ct.UnixNano() != nilTime } type Args struct { Time CustomTime } var data = ` {"Time": "2014/08/01|11:27:18"} ` func main() { a := Args{} fmt.Println(json.Unmarshal([]byte(data), &a)) fmt.Println(a.Time.String()) } ``` Let me know if you have any other text you'd like me to review!
Swift frameworks do not work with build configurations named other than 'Debug' or 'Release': No such module <sep> Whenever I try to use a build configuration named other than 'Debug' or 'Release', Xcode suddenly cannot find my Swift frameworks. The configurations are the exact same other than their name (in fact, the new configuration was duplicated from the working 'Debug' configuration). Xcode reports 'No such module' This seems like a really strange bug. Surely someone has come across this before? My Google search yielded no results. Does anyone have any idea what may be causing this issue? I'm pretty sure I added the framework correctly. I've created a short screencast to show you exactly what I'm doing: http://www.screencast.com/t/zpgZ5ZYgvH Bottom line: Make sure project currently builds using third-party Swift frameworks Select the project in the project/file navigator Select the project above Targets in the editor left sidebar and make sure you are on the Info tab Duplicate the current configuration (likely 'Debug') by clicking the + button below the list of configurations and selecting 'Duplicate XXX Configuration' Modify your scheme to use the new configuration by going to Product (menu) > Scheme > Edit Scheme... Select Run in the left sidebar Select your new configuration under Build Configuration Attempt to build again You can also download the sample project: http://s000.tinyupload.com/?file_id=48797763216274271820 I'm running Xcode 6.0.1 (6A317) and Yosemite 10.10 (14A361c).
Add the following `Framework Search Path` in the `Build Settings` of your target: `$(SYMROOT)/Release$(EFFECTIVE_PLATFORM_NAME)` and make it `non-recursive`. In my case, this was for Alamofire, which was added to my project as a git submodule. The framework was being built correctly, which can be seen in the build logs, but I assume the default framework search path is derived from the scheme name. The Alamofire framework & dSYM file are in `Release-iphoneos` and `Release-iphonesimulator`. This should work with any Swift framework as long as its scheme name is default. If not, check the build logs and adjust the framework search path accordingly.
Sharing code and schema between microservices <sep> If you go for a microservices architecture in your organization, they can share configuration via zookeeper or its equivalent. However, how should the various services share a common db schema? common constants? and common utilities? One way would be to place all the microservices in the same code repository, but that would contradict the decoupling that comes with microservices... Another way would be to have each microservice be completely independent, however that would cause code duplication and data duplication in the separate databases each microservice would have to hold. Yet another way would be to implement functional microservices with no context\state, but that's usually not realistic and would push the architecture to having a central hub that maintains the context\state and a lot of traffic from\to it. What would be a scalable, efficient practical and hopefully beautiful way to share code and schema between microservices?
Regarding common code, the best practice is to use a packaging system. So if you use Java, then use Maven, if you use Ruby, then use Gems, and if you use Python, then use PyPI, etc. Ideally, a packaging system adds little friction, so you may have a (say, Git) repository for a common library (or several common libraries for different topics) and publish their artifacts through an artifact repository (e.g., private Maven/Gems/PyPI). Then, at the microservice, you add a dependency on the required libraries. So code reuse is easy. In some cases, packaging systems do add some friction (Maven, for one), so one might prefer using a single Git repository for everything and a multi-module project setup. That isn't as clean as the first approach but works as well and isn't too bad. Other options are to use Git submodules (less desired) or Git subtree (better) in order to include the source code in a single "parent" repository. Regarding schema, if you want to play by the book, then each microservice has its own database. They don't touch each other's data. This is a very modular approach which, at first, seems to add some friction to your process, but eventually, I think you'll thank me. It will allow fast iteration over your microservices; for example, you might want to replace one database implementation with another database implementation for one specific service. Imagine doing this when all your services use the same database! Good luck with that... But if each single service uses its own database, and the service abstracts the database correctly (e.g., it does not accept SQL queries as API calls for example ;-)), then changing MySQL to Cassandra suddenly becomes feasible. There are other upsides to having completely isolated databases, for example, load and scaling, finding out bottlenecks, management, etc. So, in short, common code (utilities, constants, etc.)—use a packaging system or some source code linkage such as Git subtree. Database—you don't touch mine, I don't touch yours. That's the better way around this. HTH, Ran.
String.Format Argument Null Exception <sep> The below code will throw Argument Null Exception <code>var test = string.Format("{0}", null); </code> However, this will give back an empty string <code>string something = null; var test = string.Format("{0}", something); </code> Just curious to know why the second piece of code doesn't throw up exception. Is this a bug ?
The difference is that the first piece of code is calling `string.Format(string, object[])`... whereas the second piece of code is calling `string.Format(string, object)`. `null` is a valid argument for the second method (it's just expected to be the value for the first placeholder), but not the first (where the `null` would usually be the array of placeholders). In particular, compare the documentation for when `NullArgumentException` is thrown: > `string.Format(string, object)`: format is `null` But: > `string.Format(string, object[])`: format or args is `null` Think of `string.Format(string, object)` as being implemented something like: `public static string Format(string format, Object arg0) { return string.Format(format, new object[] { arg0 } ); }` So after a bit of replacement, your code is closer to: // Broken code object[] args = null; // No array at all var test = string.Format("{0}", args); // // Working code object[] args = new object[] { null }; // Array with 1 value var test = string.Format("{0}", args);
UIWebView delegate method shouldStartLoadWithRequest: equivalent in WKWebView? <sep> I have a module inside my iOS 7+ app which is a UIWebView. The html page loads a javascript that creates custom-shaped buttons (using the Raphaeljs library). With UIWebView, I set delegate to self. The delegate method <code>webView: shouldStartLoadWithRequest: navigationType:</code> is called each time one of my custom button is pressed. The requests should not be handled by the html, but rather by the iOS code. So I used a request convention (read somewhere here on stackoverflow) using "inapp" as the scheme of my requests. I then check for the host and take the appropriate action. This code works fine on iOS 7. But the web views appear blank on iOS 8 (bug?), so I decided to use WKWebView for iOS 8 devices. The web views now render fine (and amazingly faster!), but my buttons have no effect. I tried using <code>- (WKNaviation *)loadRequest:(NSURLRequest *)request</code>, but it's not called. I can't find a direct equivalent of the UIWebView delegate method <code>webView: shouldStartLoadWithRequest: navigationType:</code>. What's the best way of handling those requests with WKWebView?
To answer the original question, the equivalent of `webView:shouldStartLoadWithRequest:navigationType:` in UIWebView is `webView:decidePolicyForNavigationAction:decisionHandler:` in WKWebView. These methods are called before each request is made (including the initial request) and provide the ability to allow or disallow it.
Change colour of small triangle on spinner in android <sep> How can I change the colour of small triangle at the bottom right corner of spinner like shown in the image? It is showing default grey colour right now. like this
The best and easiest solution: ```java spinner.getBackground().setColorFilter(getResources().getColor(R.color.red), PorterDuff.Mode.SRC_ATOP); ``` Other solution (Thanks to Simon) if you don't want to change all Spinners: ```java Drawable spinnerDrawable = spinner.getBackground().getConstantState().newDrawable(); spinnerDrawable.setColorFilter(getResources().getColor(R.color.red), PorterDuff.Mode.SRC_ATOP); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { spinner.setBackground(spinnerDrawable); } else { spinner.setBackgroundDrawable(spinnerDrawable); } ```
Uses for the '&quot;' entity in HTML <sep> I am revising some XHTML files authored by another party. As part of this effort, I am doing some bulk editing via Linq to XML. I've just noticed that some of the original source XHTML files contain the <code>&quot;</code> HTML entity in text nodes within those files. For instance: <code><p>Greeting: &quot;Hello, World!&quot;</p> </code> And that when recovering the XHTML text via XElement.ToString(), the <code>&quot;</code> entities are being replaced by plain double-quotes: <code><p>Greeting: "Hello, World!"</p> </code> Question: Can anyone tell me what the motivation might have been for the original author to use the <code>&quot;</code> entities instead of plain double-quotes? Did those entities serve a purpose which I don't fully appreciate? Or, were they truly unnecessary as I suspect? I do understand that <code>&quot;</code> would be necessary in certain contexts, such as when there is a need to place a double-quote within an HTML attribute. For instance: <code><a href="/images/hello_world.jpg" alt="Greeting: &quot;Hello, World!&quot;"> Greeting</a> </code>
It is impossible, and unnecessary, to know the motivation for using `&quot;` in element content, but possible motives include: misunderstanding of HTML rules; use of software that generates such code (probably because its author thought it was safer); and misunderstanding of the meaning of `&quot;`: many people seem to think it produces smart quotes (they apparently never looked at the actual results). Anyway, there is never any need to use `&quot;` in element content in HTML (XHTML or any other HTML version). There is nothing in any HTML specification that would assign any special meaning to the plain character " there. As the question says, it has its role in attribute values, but even in them, it is mostly simpler to just use single quotes as delimiters if the value contains a double quote, e.g., `alt='Greeting: "Hello, World!"'` or, if you are allowed to correct errors in natural language texts, to use proper quotation marks, e.g., `alt="Greeting: Hello, World!"`
Swift equivalent of Array.componentsJoinedByString? <sep> In Objective-C we can call <code>componentsJoinedByString</code> to produce a string with each element of the array separated by the supplied string. While Swift has a <code>componentsSeparatedByString</code> method on String, there doesn't appear to be the inverse of this on Array: <code>'Array<String>' does not have a member named 'componentsJoinedByString' </code> What is the inverse of <code>componentsSeparatedByString</code> in Swift?
Swift 3.0: Similar to Swift 2.0, but `joinWithSeparator` has been renamed to `joined(separator:)`. ```swift let joinedString = ["1", "2", "3", "4", "5"].joined(separator: ", ") // joinedString: String = "1, 2, 3, 4, 5" ``` See `Sequence.joined(separator:)` for more information. Swift 2.0: You can use the `joinWithSeparator` method on `SequenceType` to join an array of strings with a string separator. ```swift let joinedString = ["1", "2", "3", "4", "5"].joinWithSeparator(", ") // joinedString: String = "1, 2, 3, 4, 5" ``` See `SequenceType.joinWithSeparator(_:)` for more information. Swift 1.0: You can use the `join` standard library function on `String` to join an array of strings with a string. ```swift let joinedString = ", ".join(["1", "2", "3", "4", "5"]) // joinedString: String = "1, 2, 3, 4, 5" ``` Or, if you'd rather, you can use the global standard library function: ```swift let joinedString = join(", ", ["1", "2", "3", "4", "5"]) // joinedString: String = "1, 2, 3, 4, 5" ```
Why is Haskell missing "obvious" Typeclasses <sep> Consider the Object-Oriented Languages: Most people coming from an object-oriented programming background, are familiar with the common and intuitive interfaces in various languages that capture the essence of Java's <code>Collection</code> & <code>List</code> interfaces. <code>Collection</code> refers to a collection of objects which doesn't necessarily have an natural ordering/indexing. A <code>List</code> is a collection which has a natural ordering/indexing. These interfaces abstract many library data-structures in Java, as do their equivalent interfaces in other languages, and an intimate understanding of these interfaces are required to work effectively with most library data-structures. Transition to Haskell: Haskell has a type-class system which acts on types analogously to interfaces on objects. Haskell seems to have a well designed type-class hierarchy with regard to Functors, Applicative, Monads, etc. when the type regard functionality. They obviously want correct and well-abstracted type-classes. Yet when you look at many Haskell's containers (<code>List</code>,<code>Map</code>,<code>Sequence</code>,<code>Set</code>,<code>Vector</code>) they almost all have very similar (or identical) functions, yet aren't abstracted through type-classes. Some Examples: <code>null</code> for testing "emptyness" <code>length</code>/<code>size</code> for element count <code>elem</code>/<code>member</code> for set inclusion <code>empty</code> and/or <code>singleton</code> for default construction <code>union</code> for set union <code>(\\)</code>/<code>diff</code> for set difference <code>(!)</code>/<code>(!!)</code> for unsafe indexing (partial function) <code>(!?)</code>/<code>lookup</code> for safe indexing (total function) If I want to use any of the functions above, but I have imported two or more containers I have to start hiding functions from the imported modules, or explicitly import only the necessary functions from the modules, or qualifying the imported modules. But since all the functions provide the same logical functionality, it just seems like a hassle. If the functions were defined from type-classes, and not separately in each module, the compiler's type inference mechanics could resolve this. It would also make switching underlying containers simple as long as they shared the type-classes (ie: lets just use a <code>Sequence</code> instead of <code>List</code> for better random access efficiency). Why doesn't Haskell have a <code>Collection</code> and/or <code>Indexable</code> type-class(es) to unify & generalize some of these functions?
As other answers have pointed out, Haskell tends to use different vocabulary. However, I don't think they've explained the reason for the difference very well. In a language like Java, functions are not "first-class citizens"; it's true that anonymous functions are available in the latest versions, but this style of interface (Collection, Indexable, Iterable, etc.) was designed before that. This makes it tedious to pass our code around, so we prefer other people's data to be passed to our code. For example: - Data implementing Java's `Iterable` lets us write `for (Foo x : anIterable) { ... }` - Data implementing PHP's `ArrayAccess` lets us write `anArrayAccess[anIndex]` This style can also be seen in object-oriented languages which implement generators, since that's another way for us to write `for yieldedElement in aGenerator: ...` Haskell takes a different approach with its typeclasses: we prefer our code to be passed to other people's data. Some (simplified) examples: - `Functor`s accept our code and apply it to any elements they 'contain'. - `Monad`s accept our code and apply it in some kind of 'sequence'. - `Foldable`s accept our code and use it to 'reduce' their contents. Java only needs `Iterable` since we have to call our code in our `for` loop, so we can make sure it's called correctly. Haskell requires more specific typeclasses since someone else's code will be calling ours, so we need to specify how it should be called; is it a `map`, a `fold`, an `unfold`, etc.? Thankfully, the type system helps us choose the right method ;)
How do I get Android Studio to stop returning generated code in search results? <sep> Every time I use <code>Search In Path</code> in Android Studio, I end up with generated code being returned as the first section of results. I usually search for something in <code>*.java,*.xml</code>, and usually investigate the first few results before I realize I'm looking at <code>Generated Code</code>. Is there a way to omit the generated code results from being returned as part of the result list, while still allowing the search to read all of the *.java and *.xml files in my project? I have a feeling this is something beyond ridiculously simple, but I just can't find the right button to toggle. In the same vein, is it possible to ignore generated classes when loading files or types? I keep getting the generated <code>MyClass$$ViewInjector</code> classes appearing first in open files, and it's just annoying...
The way I've been ignoring generated classes in advanced search is by adding `!file:*intermediates*/&&!file:*generated*/` to a new Custom Scope. 14-October-2015 Update: I improved the pattern by excluding `!lib:*..*` from the search. Thanks.
Connect Bluestacks to Android Studio <sep> I have recently shifted to android studio. I would like to know how I can test my apps in Bluestacks app player. I had already had the bluestacks connected and working with eclipse using <code>adb connect localhost:5555</code> but it doesn't seem to work with android studio. Didn't find any help anywhere. If anyone has done this, please help.
Steps to connect BlueStack with Android Studio: Close Android Studio. Go to the adb.exe location (default location: `%LocalAppData%\Android\sdk\platform-tools`). Run `adb connect localhost:5555` from this location. Start Android Studio, and you will get BlueStack as an emulator when you run your app.
How to show space and tabs with git-diff <sep> I have the following output with git-diff. <code>- // sort list based on value + // sort list based on value </code> How can I see easily see the number of removed tabs/spaces at the end of the line ?
``` diff.c: --ws-error-highlight=<kind> option Traditionally, we only cared about whitespace breakages introduced in new lines. Some people want to paint whitespace breakages on old lines, too. When they see a whitespace breakage on a new line, they can spot the same kind of whitespace breakage on the corresponding old line and want to say "Ah, those breakages are there but they were inherited from the original, so let's not touch them for now." Introduce the `--ws-error-highlight=<kind>` option, which lets them pass a comma-separated list of `old`, `new`, and `context` to specify which lines to highlight whitespace errors on. The documentation now includes: `--ws-error-highlight=<kind>` Highlight whitespace errors on lines specified by `<kind>` in the color specified by `color.diff.whitespace`. `<kind>` is a comma-separated list of `old`, `new`, and `context`. When this option is not given, only whitespace errors in `new` lines are highlighted. E.g., `--ws-error-highlight=new,old` highlights whitespace errors on both deleted and added lines. `all` can be used as a shorthand for `old,new,context`. For instance, the old commit had one whitespace error (bbb), but you can focus on the new errors only: (test done after `t/t4015-diff-whitespace.sh`) Update Git 2.11+ (Q4 2016, a year and a half later): `git config diff.wsErrorHighlight [old,new,context]` `git diff/log --ws-error-highlight=<kind>` lacked the corresponding configuration variable to set it by default. That is added in Git 2.11. See commit 0b4b42e, commit 077965f, commit f3f5c7f (04 Oct 2016) by Junio C Hamano (gitster). (Merged by Junio C Hamano -- gitster -- in commit e5272d3, 26 Oct 2016) ```
Detecting iPhone 6/6+ screen sizes in point values <sep> Given the newly announced iPhone 6 screen sizes: <code>iPhone 6: 1334h * 750w @2x (in points: 667h * 375w) iPhone 6+: 1920 * 1080 @3x (in points: 640h * 360w) </code> I was wondering if there is code that allows me to detect which screen size the user's device is, so that I could adjust and size <code>UIImages</code> and other materials accordingly with the user's device. So far, I have been using the following: <code>- (NSString *) platform{ size_t size; sysctlbyname("hw.machine", NULL, &size, NULL, 0); char *machine = malloc(size); sysctlbyname("hw.machine", machine, &size, NULL, 0); NSString *platform = [NSString stringWithUTF8String:machine]; free(machine); return platform; } - (NSString *) platformString{ NSString *platform = [self platform]; if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G"; if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G"; if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS"; if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4"; if ([platform isEqualToString:@"iPhone3,3"]) return @"Verizon iPhone 4"; if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S"; if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)"; if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)"; if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)"; if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)"; if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)"; if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)"; if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G"; if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G"; if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G"; if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G"; if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G"; if ([platform isEqualToString:@"iPad1,1"]) return @"iPad"; if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)"; if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)"; if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)"; if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2 (WiFi)"; if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)"; if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini (GSM)"; if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini (GSM+CDMA)"; if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)"; if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM+CDMA)"; if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (GSM)"; if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)"; if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (GSM)"; if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (GSM+CDMA)"; if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)"; if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)"; if ([platform isEqualToString:@"iPad4,4"]) return @"iPad mini 2G (WiFi)"; if ([platform isEqualToString:@"iPad4,5"]) return @"iPad mini 2G (Cellular)"; if ([platform isEqualToString:@"i386"]) return @"Simulator"; if ([platform isEqualToString:@"x86_64"]) return @"Simulator"; return platform; } </code> As such, should I assume <code>iPhone7,1</code> and <code>iPhone7,2</code> are the iPhone 6 while <code>iPhone7,3</code> and <code>iPhone7.4</code> are the pluses? If anyone has more concrete way to tell it'd be great, thanks.!
Here are the macros you can use to differentiate between iPhone models. These are based on the point values: ``` #define IS_IPHONE_4 (fabs((double)[[UIScreen mainScreen] bounds].size.height - (double)480) < DBL_EPSILON) #define IS_IPHONE_5 (fabs((double)[[UIScreen mainScreen] bounds].size.height - (double)568) < DBL_EPSILON) #define IS_IPHONE_6 (fabs((double)[[UIScreen mainScreen] bounds].size.height - (double)667) < DBL_EPSILON) #define IS_IPHONE_6_PLUS (fabs((double)[[UIScreen mainScreen] bounds].size.height - (double)736) < DBL_EPSILON) ```
Android Studio doesn't recognize my device <sep> Here is the problem. I want to run my Android Studio apps on my device (Samsung Galaxy Ace 2). But nothing works for me. Tell me what I've missed: 1) USB debugging is on 2) ADB driver is installed (in device manager i can see Android Composite ADB Interface) 3) ADB device list is still clear, even if i reset server(adb kill-server, adb start-server, adb devices - list of devices is clear) 4) in google usb driver directory, in android_winusb.inf file I added my device identificators 5) Android device manager still cannot connect to my device, showing this error when I reset it: "adb connection error an existing connection was forcibly closed by the remote host" So I will be glad to hear any advices. Hope you'll help me
I have tried numerous ways of handling that issue. Finally, it has worked! I am using an LG Optimus II, but I believe the following steps are generic to other Android devices as well. Step 1: Make sure your device is enabled for development. If so, go to Step 2; otherwise, go to `Settings > About phone` and tap `Build number` seven times (this is the magic number :-)). Now `Developer Options` is available in the `Settings`. Step 2: Before you plug your device to your PC, go to `Settings > Developer Options` and select `USB Connection method`. Step 3: Plug the phone to your PC. You are given options for the `USB Connection method`, and please select `Internet connection`. Make sure you are connected to the Internet. By the way, I changed `MTP` to `PTP`, but it did not work for me. Therefore, I tried `Internet connection mode`, and then it worked. Step 4: Run the app in Android Studio. It will ask you to authorize the device for development; select YES! Step 5: Run the application via Android Studio and choose the device, not the emulator, and BINGO! Welcome to Android development.
Launching into portrait-orientation from an iPhone 6 Plus home screen in landscape orientation results in wrong orientation <sep> The actual title for this question is longer than I can possibly fit: Launching an app whose root view controller only supports portrait-orientation but which otherwise supports landscape orientations on an iPhone 6 Plus while the home screen is in a landscape orientation results in a limbo state where the app's window is in a landscape orientation but the device is in a portrait orientation. In short, it looks like this: When it is supposed to look like this: Steps to Reproduce: iPhone 6 Plus running iOS 8.0. An app whose plist supports all-but-portrait-upside-down orientations. The root view controller of the app is a UITabBarController. Everything, the tab bar controller and all its descendent child view controllers return <code>UIInterfaceOrientationMaskPortrait</code> from <code>supportedInterfaceOrientations</code>. Start at iOS home screen. Rotate to landscape orientation (requires iPhone 6 Plus). Cold-launch the app. Result: broken interface orientations. I can't think of any other way to enforce a portrait orientation except to disable landscape altogether, which I can't do: our web browser modal view controllers need landscape. I even tried subclassing UITabBarController and overriding supportedInterfaceOrientations to return the portrait-only mask, but this (even with all the other steps above) did not fix the issue. Here's a link to a sample project showing the bug.
I had the same issue when launching our app in landscape on an iPhone 6 Plus. Our fix was to remove landscape supported interface orientations from the plist via project settings and implement `application:supportedInterfaceOrientationsForWindow:` in the app delegate: ```objectivec - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return UIInterfaceOrientationMaskAllButUpsideDown; } ``` Apparently, the information in your plist is to specify what orientations your app is allowed to launch to.
Refreshing static content with Spring MVC and Boot <sep> I'm evaluating Spring MVC & Boot and AngularJs for building web applications. I've run into the problem that when I make modifications to my static content (html, js, css), I have to restart the application every time. I hope there is a some way of solving that because restarting the whole application for static content changes is not efficient. Every other web app framework I've tried allows updating static content files on the fly(even just Spring MVC and plain old WAR application). I've setup my project from "Building a RESTful Web Service with Spring Boot Actuator" guide (http://spring.io/guides/gs/actuator-service/). Basically it uses Spring Boot and MVC controllers to create a REST service. In addition, I've used "Consuming a RESTful Web Service with AngularJS" guide (http://spring.io/guides/gs/consuming-rest-angularjs/) to build a frontend with AngularJS. It creates a web page that displays the response from the REST service. The only change I've made is that the requests are made to my application instead of "http://rest-service.guides.spring.io/greeting". My static content is stored in "src/main/resources/public" folder. This setup works correctly except it doesn't reload static content.
A recap of the original problem: > I've run into the problem that when I make modifications to my static content (HTML, JS, CSS), I have to restart the application every time. I had the same problem and finally solved it by adding `<configuration><addResources>true</addResources></configuration>` to `spring-boot-maven-plugin` in the `pom.xml`. I got confused by this spring-boot-devtools thing, but it had no effect, whatever I did. > My static content is stored in the "src/main/resources/public" folder. Your path is just fine. `src/main/resources/static` is also fine.
UIAlertView/UIAlertController iOS 7 and iOS 8 compatibility <sep> I am using Swift to write an app and I need to show an alert. The app must be iOS 7 and iOS 8 compatible. Since <code>UIAlertView</code> has been replaced with <code>UIAlertController</code>, how can I check if the <code>UIAlertController</code> is available without checking the system version? I have been hearing that Apple recommends that we should not check the system version of the device in order to determine the availability of an API. This is what I am using for iOS 8 but this crashes on iOS 7 with "<code>dyld: Symbol not found: _OBJC_CLASS_$_UIAlertAction</code>" : <code>let alert = UIAlertController(title: "Error", message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) </code> If I use the UIAlertView for iOS 8, I get this warning: <code>Warning: Attempt to dismiss from view controller <_UIAlertShimPresentingViewController: 0x7bf72d60> while a presentation or dismiss is in progress!</code>
The detection pattern is identical to the Objective-C style. You need to detect whether the current active runtime has the ability to instantiate this class: ```objectivec if objc_getClass("UIAlertController") != nil { println("UIAlertController can be instantiated") // make and use a UIAlertController } else { println("UIAlertController can NOT be instantiated") // make and use a UIAlertView } ``` Don't try to work this out based on the OS version. You need to detect abilities, NOT OS. EDIT: The original detector for this answer (`NSClassFromString("UIAlertController")`) fails under `-O` optimization, so it's been changed to the current version which does work for Release builds. EDIT 2: `NSClassFromString` is working at all optimizations in Xcode 6.3/Swift 1.2.
How do I ask for "at least" a size of an int in C <sep> The situation: I have an application written in C which is resource intensive, and designed to be portable. I want to allow the compiler to select the fastest int size for the architecture, provided it is at least 32 bits. Is it possible to select a size of "at least" 32 bits, or will the compiler optimize these kinds of things form me automatically?
As others have noted, the standard include files define `int_fast32_t`, `int_least32_t`, `uint_fast32_t`, and `uint_least32_t`, which should likely behave as you want, but such types need to be used with extreme care. Because of integer promotion rules, there is no way for C code to avoid using types `int` and `unsigned int`. Further, integer literals may not always be of the types one expects. A comparison between an `int_fast32_t` and the literals `0xABCD1234` or `12345u`, for example, may be performed as either signed or unsigned, depending upon whether `int` is 16, 32, or 64 bits. Likewise, if `n` is 32 bits or larger, the meaning of `n &= ~0x8000;` would be different on a 16-bit machine from on a larger one. The C standard was never particularly designed to facilitate writing code which cares about integer sizes, but will nonetheless work compatibly on hardware with different sizes. Types like `int_fast32_t` make it easy to write code which seems like it should be portable, but may encourage complacency with respect to all of the nasty little traps hidden in the language.
Why can't I update props in react.js? <sep> Why do we have both <code>state</code> and <code>props</code>? Why don't we just have one source of data? I'd like to update a component's <code>props</code> and have it re-render itself and all of its children. Seems simple but I can't figure out how to let a component update its own or its parent's props. Thanks for any help.
The React philosophy is that props should be immutable and top-down. This means a parent can send any prop values it likes to a child, but the child cannot modify its own props. You react to incoming props and, if desired, modify your child's state based on them. You never update your own props or a parent's props. Ever. You only ever update your own state and react to prop values given by the parent. If you want an action on a child to modify something in the state, pass a callback to the child that it can execute upon the given action. This callback can then modify the parent's state, which can, in turn, send different props to the child on re-render.
upload a directory to s3 with boto <sep> I am already connected to the instance and I want to upload the files that are generated from my python script directly to S3. I have tried this: <code>import boto s3 = boto.connect_s3() bucket = s3.get_bucket('alexandrabucket') from boto.s3.key import Key key = bucket.new_key('s0').set_contents_from_string('some content') </code> but this is rather creating a new file s0 with the context "same content" while I want to upload the directory s0 to mybucket. I had a look also to s3put but I didn't manage to get what I want.
```python def uploadDirectory(path, bucketname): for root, dirs, files in os.walk(path): for file in files: s3.upload_file(os.path.join(root, file), bucketname, file) Provide a path to the directory and bucket name as inputs. The files are placed directly into the bucket. Alter the last variable of the upload_file() function to place them in subdirectories. ```
Apache HttpClient Android (Gradle) <sep> I have added this line to my build.gradle <code>compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5' </code> and I want to use MultipartEntityBuilder in my code. However Android studio doesn't add the library to my code. Can anyone help me with this?
If you are using target SDK as 23, add the below code in your build.gradle: ```groovy android { useLibrary 'org.apache.http.legacy' } ``` Additional note: Don't try using the Gradle versions of those files. They are broken (August 28, 2015). I tried for over 5 hours to get it to work; it just doesn't. Not working: ```groovy compile 'org.apache.httpcomponents:httpcore:4.4.1' compile 'org.apache.httpcomponents:httpclient:4.5' ``` Another thing: don't use: ```groovy 'org.apache.httpcomponents:httpclient-android:4.3.5.1' ``` It's referring to API level 21.
When to use case class or regular class <sep> I have some misunderstanding in what cases I should use case class or regular class following by best practices. I have already read about differences of both classes but cannot imagine myself real-life examples where is reccommended to use case or regular class. Could anybody show me real examples with explanation why it's reccommended to do so and not otherwise?
If you are going to write purely functional code with immutable objects, you should try to avoid using regular classes. The main idea of the functional paradigm is the separation of data structures and operations on them. Case classes are a representation of a data structure with the necessary methods. Functions on the data should be described in different software entities (e.g., traits, objects). Regular classes, on the contrary, link data and operations to provide mutability. This approach is closer to the object-oriented paradigm. As a result, do not use case classes if: - Your class carries mutable state. - Your class includes some logic. - Your class is not a data representation and you do not require structural equality. However, in these cases, you should really think about the style of your code because it probably is not functional enough.
Does it make sense to dockerize (containerize) databases? <sep> I can understand the benfits behind dockerizing stateless services, such as web servers, appservers, load balancers, etc... If you are running these services on a cluster of machines, it is very easy to move these containers around with low overhead. What I don't understand though is the purpose behind containerizing databases? databases are connected to a data volume that is persistent in a specific hard disk. Because of state, it is not easy, and not efficient to actually move the database container around. So can anyone see why dockerizing a database can be useful at all?
"So can anyone see why dockerizing a database can be useful at all?" Good question, Keeto. One of the main reasons for containerizing your databases is so that you can have the same consistent environment for your entire app, not just the stateless parts, across dev, staging, and production. A consistent environment is one of the promises of Docker, but when your database lives outside this model, there is a big difference that can't be accounted for in your testing. Also, by containerizing your database as well as the rest of your app, you are more likely to be able to move your entire app between hosting providers (say, from AWS to Google Compute). If you use Amazon RDS, for example, even if you can move your web nodes to Google, you won't be able to move your database, meaning that you are heavily dependent on your cloud provider. Another reason for containerizing data services is performance. This is particularly true for service providers (all the database-as-a-service offerings—e.g., Rackspace Cloud Databases—run in containers) because containers allow you to provide service guarantees that aren't possible using virtualization, and running one database per physical machine is not financially viable. Chances are you aren't running a database hosting service, but this analogy makes similar sense if you are running on bare metal and want to use containers for process isolation, instead of VMs. You'll get better performance for your databases because of the well-known I/O hit you take when running a database in a VM. I'm not saying that you should containerize your database, but these are some of the reasons why it would make sense. Full disclosure, I work for ClusterHQ, that new project that Mark O'Connor mentioned in his answer. We have an open-source project called Flocker that makes it much easier to migrate databases and their volumes between hosts so that the benefits I mentioned above aren't completely outweighed by the negatives that you raised in your question.
Scrolling to an Anchor using Transition/CSS3 <sep> I have a series of links which are using an anchor mechanism: <code><div class="header"> <p class="menu"><a href="#S1">Section1</a></p> <p class="menu"><a href="#S2">Section2</a></p> ... </div> <div style="width: 100%;"> <a name="S1" class="test">&nbsp;</a> <div class="curtain"> Lots of text </div> <a name="S2" class="test">&nbsp;</a> <div class="curtain"> lots of text </div> ... </div> </code> I am using the following CSS: <code>.test { position:relative; margin: 0; padding: 0; float: left; display: inline-block; margin-top: -100px; /* whatever offset this needs to be */ } </code> It's working fine. But of course, it's jumping from one section to the next when we click on the link. So I'd like to have a smooth transition, using a scroll of some sort to the start of selected section. I think I read on Stackoverflow that this is not possible (yet) with CSS3 but I'd like a confirmation and also I'd like to know what 'could' be the solution. I am happy to use JS but I can't use jQuery. I tried to use an on click function on the link, retrieve the "vertical position" of the div that needs to be displayed but I was unsuccessful. I am still learning JS and don't know it well enough to come up with a solution of my own. Any help/ideas would be greatly appreciated.
You can use the `scroll-behavior` CSS property (which is supported in all browsers except Internet Explorer and Safari): ```css a { display: inline-block; padding: 5px 7%; text-decoration: none; } nav, section { display: block; margin: 0 auto; text-align: center; } nav { width: 350px; padding: 5px; } section { width: 350px; height: 130px; overflow-y: scroll; border: 1px solid black; font-size: 0; scroll-behavior: smooth; /* <----- THE SECRET ---- */ } section div { display: flex; align-items: center; justify-content: center; height: 100%; font-size: 8vw; } ``` ```html <nav> <a href="#page-1">1</a> <a href="#page-2">2</a> <a href="#page-3">3</a> </nav> <section> <div id="page-1">1</div> <div id="page-2">2</div> <div id="page-3">3</div> </section> ```
How to get the first day of the current year? <sep> I need to use PHP DateTime to get the first day of the current year. I've tried: <code>$year = new DateTime('first day of this year'); var_dump($year); </code> But this seems to be returning the first day of the current month: 2014-09-01 09:28:56 Why? How do I correctly get the first day of the current year?
Your relative date format `'first day of this year'` is correct because it returns the first day of the month. This is due to the definition of `first day of`: > Sets the day of the first of the current month. This phrase is best used together with a month name following it. (See PHP-doc) To get the first day of the current year with the relative format you can use something like this: `'first day of January ' . date('Y')`
Running a native library on Android L. error: only position independent executables (PIE) are supported <sep> When I run native code on Android L (Nexus 5), I get the error. <blockquote> error: only position independent executables (PIE) are supported. </blockquote> The same code is executed correctly on my Samsung Galaxy S3 (Android 4.3). Here is my Application.mk <code>APP_PROJECT_PATH := $(call my-dir)/.. APP_ABI := armeabi NDK_TOOLCHAIN_VERSION := 4.7 APP_PLATFORM := android-9 APP_GNUSTL_FORCE_CPP_FEATURES := exceptions rtti </code> However when I replace <code>APP_PLATFORM := android-9</code> with <code>APP_PLATFORM := android-16</code> (As I read here, PIE support appeared in Jelly Been (API level 16)), the same executable file works fine on Android L. Is there a way to compile native code using <code>APP_PLATFORM := android-9</code> and run it on Android L?
If you can live with only supporting Android 4.1+, just set `APP_PLATFORM := android-16` and you'll be good to go. Behind the scenes it sets `APP_PIE := true`. Your binary will segfault on older SDKs. If you also need to support lower SDK levels, you'll need to create two binaries. Some other answers I've seen have recommended maintaining two separate source trees with different `APP_PLATFORM`s, but you don't need to do that. It's possible to make a single Android.mk output both a PIE and a non-PIE binary. NDK 10c and later: Make sure that PIE is disabled by default since enabling it manually is easier than disabling it. PIE doesn't get enabled by default unless your `APP_PLATFORM` is >=16. Make sure that your `APP_PLATFORM` is either not set (defaulting to android-3, or android-14 since NDK 15), lower than android-16, or set `APP_PIE := false`. The following Android.mk then creates a PIE and a non-PIE binary, but has a caveat (see below): ``` LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) # Enable PIE manually. Will get reset on $(CLEAR_VARS). # This is what enabling PIE translates to behind the scenes. LOCAL_CFLAGS += -fPIE LOCAL_LDFLAGS += -fPIE -pie LOCAL_MODULE := mymod LOCAL_SRC_FILES := \ mymod.c include $(BUILD_EXECUTABLE) include $(CLEAR_VARS) LOCAL_MODULE := mymod-nopie LOCAL_SRC_FILES := \ mymod.c include $(BUILD_EXECUTABLE) ``` You'll then have to add some sort of logic to invoke the correct binary in your code. Unfortunately, this means you'll have to compile the executable module twice, which can be slow. You also need to specify `LOCAL_SRC_FILES` and any libraries twice, which can be frustrating and difficult to keep track of. What you can do is to compile the main executable as a static library, and build executables from nothing but that static library. Static libraries do not require PIE. ``` LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := mymod-common LOCAL_SRC_FILES := \ mymod.c include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) # Enable PIE manually. Will get reset on $(CLEAR_VARS). # This is what enabling PIE translates to behind the scenes. LOCAL_CFLAGS += -fPIE LOCAL_LDFLAGS += -fPIE -pie LOCAL_MODULE := mymod LOCAL_STATIC_LIBRARIES := mymod-common include $(BUILD_EXECUTABLE) include $(CLEAR_VARS) LOCAL_MODULE := mymod-nopie LOCAL_STATIC_LIBRARIES := mymod-common include $(BUILD_EXECUTABLE) ``` This seems to work quite nicely, although a certain amount of boilerplate is still required. NDK 10b: NDK 10b enables PIE by default and doesn't let you disable it, except with terrible hacks. Really, just update to 10c. I'm leaving my old answer here for reference but I wouldn't recommend it to anyone. ``` LOCAL_PATH := $(call my-dir) # Forcefully disable PIE globally. This makes it possible to # build some binaries without PIE by adding the necessary flags # manually. These will not get reset by $(CLEAR_VARS). # PIE is force-enabled on NDK 10b so we'll need this even if # APP_PIE is set to false. TARGET_PIE := false NDK_APP_PIE := false include $(CLEAR_VARS) # Enable PIE manually. Will get reset on $(CLEAR_VARS). # This is what enabling PIE translates to behind the scenes. LOCAL_CFLAGS += -fPIE LOCAL_LDFLAGS += -fPIE -pie LOCAL_MODULE := mymod LOCAL_SRC_FILES := \ mymod.c include $(BUILD_EXECUTABLE) include $(CLEAR_VARS) LOCAL_MODULE := mymod-nopie LOCAL_SRC_FILES := \ mymod.c include $(BUILD_EXECUTABLE) ```
Is there a standard definition for __cplusplus in c++14? <sep> I'm looking to setup some preprocessor stuff, and I'd like a more exact number for what <code>__cplusplus</code> in C++14 should be defined as. Is there one mandated by the standard?
cppreference has information on the standard values of the `__cplusplus` macro in the section "Predefined macros." Currently, the standard values are: `199711L` (C++98 or C++03), `201103L` (C++11), `201402L` (C++14), `201703L` (C++17), and `202002L` (C++20). The macro's value for any given version isn't firmly established until the final standard is published. Therefore, as of June 2019, there was no way to know what the macro value for C++2a would be (and as of February 2021, there's no way to know what the value will be for C++2b). Library vendors typically gate their "C++2a" features on `#if __cplusplus > 201703L`, and their "C++2b" features on `__cplusplus > 202002L`, and so on. Compiler vendors with a "C++2a" mode simply picked any arbitrary value for `__cplusplus` that made the library vendors' checks happy: GCC (8.x through 10.x) `-std=c++2a` mode uses `__cplusplus == 201709L`. Clang (5.x through 9.x) `-std=c++2a` mode uses `__cplusplus == 201707L`. Microsoft Visual Studio (19.20 through 19.28) `/std:c++latest` mode uses `__cplusplus == 201705L` if and only if you pass `/Zc:__cplusplus`! Otherwise, it uses `199711L`. So watch out for that! How have transitions historically been handled?: Clang 4.0.1 `-std=c++1z` set `__cplusplus == 201406L`. Clang 5.0.0 introduced `-std=c++17` and `-std=c++2a`, made `-std=c++1z` a synonym for `-std=c++17`, and bumped the macro (no matter which of `17`/`1z` you used) to the standard value `201703L`. Clang 10.0 introduced `-std=c++20`, made `-std=c++2a` a synonym for `-std=c++20`, and bumped the macro to the standard value `202002L`. As of February 2021, Clang has no formal "C++2b" mode. GCC 5.1 introduced `-std=c++1z` and `-std=c++17` as synonyms out of the gate, setting `__cplusplus == 201500L`. GCC 7.1 bumped the value (no matter which spelling you used) to the standard value of `201703L`. GCC 8.1 introduced `-std=c++2a` with `__cplusplus == 201709L`. GCC 10.1 introduced `-std=c++20` as a synonym for `-std=c++2a` (but left the macro at `201709L`). As of February 2021, GCC trunk has introduced `-std=c++2b` with `__cplusplus == 202100L`. Oddly, according to Godbolt Compiler Explorer, MSVC bumped the macro for `-std:c++latest` mode from `201704L` to `201705L` sometime between MSVC 19.16 and 19.20. As of February 2021, as far as I know, MSVC has no formal "C++20" mode.
Writing .csv files from C++ <sep> I'm trying to output some data to a .csv file and it is outputting it to the file but it isn't separating the data into different columns and seems to be outputting the data incorrectly. <code> ofstream Morison_File ("linear_wave_loading.csv"); //Opening file to print info to Morison_File << "Time Force(N/m)" << endl; //Headings for file for (t = 0; t <= 20; t++) { u = sin(omega * t); du = cos(omega * t); F = (0.5 * rho * C_d * D * u * fabs(u)) + rho * Area * C_m * du; cout << "t = " << t << "\t\tF = " << F << endl; Morison_File << t; //Printing to file Morison_File << F; } Morison_File.close(); </code> Time and Force(N/m) are in columns A and B respectively but the t and F values are both printing the first row. What is the syntax to separate them to print t into column A and F into column B?
There is nothing special about a CSV file. You can create them using a text editor by simply following the basic rules. The RFC 4180 (tools.ietf.org/html/rfc4180) accepted separator is the comma, ',' not the semicolon, ';'. Programs like MS Excel expect a comma as a separator. There are some programs that treat the comma as a decimal and the semicolon as a separator, but these are technically outside of the "accepted" standard for CSV formatted files. So, when creating a CSV, you create your filestream and add your lines like so: ```c++ #include <iostream> #include <fstream> int main( int argc, char* argv[] ) { std::ofstream myfile; myfile.open ("example.csv"); myfile << "This is the first cell in the first column.\n"; myfile << "a,b,c,\n"; myfile << "c,s,v,\n"; myfile << "1,2,3.456\n"; myfile << "semi;colon"; myfile.close(); return 0; } ``` This will result in a CSV file that looks like this when opened in MS Excel:
How to determine if one array contains all elements of another array in Swift? <sep> I have 2 arrays: <code>var list:Array<Int> = [1,2,3,4,5] var findList:Array<Int> = [1,3,5] </code> I want to determine if <code>list</code> Array contains all <code>findList</code> elements. By the way, elements might be <code>String</code> as well or other type. How to do that? I know that Swift provides <code>contains</code> method that works with one item.
`allSatisfy` seems to be what you want, assuming you can't conform your elements to `Hashable` and use the set intersection approach others have mentioned: `let containsAll = subArray.allSatisfy { largerArray.contains($0) }`
Use sudo without password INSIDE a script <sep> For some reason I need, as user, to run without sudo a script script.sh which needs root privileges to work. I saw as the only solution to put sudo INSIDE script.sh. Let's take an example : <code>script.sh : #!/bin/sh sudo apt-get update </code> Of course, if I execute this script, I get a prompt asking me for a password. Then I added to my sudoers file (at the end to override everything else) : <code>user ALL=(ALL:ALL) NOPASSWD:/path/to/script.sh </code> By the way, I also tried the line : <code>user ALL=(ALL) NOPASSWD:/path/to/script.sh </code> (I think I didn't fully understand the difference) But this doesn't solve my problem if I don't use sudo to execute this script : <code># ./script.sh [sudo] password for user: # sudo ./script.sh Starts updating... </code> Well, so I say to myself "Ok, that means that if I have a file refered in sudoers as I did, it will work without prompt only if I call him with sudo, what is not what I want". So, ok, I create another script script2.sh as following : <code>script2.sh #!/bin/sh sudo /path/to/script.sh </code> In fact it works. But I am not truly satisfied of this solution, particularly by the fact that I have to use 2 scripts for every command. This post is then for helping people having this problem and searching for the same solution (I didn't find a good post on it), and perhaps have better solutions coming from you guys. Feel free to share your ideas ! EDIT 1 : I want to insist on the fact that this "apt-get update" was just an example FAR from whhat my script actually is. My script has a lot of commands (with some cd to root-access-only config files), and the solution can't be "Well, just do it directly with apt-get". The principle of an example is to help the understanding, not to be excuse to simplify the answer of the general problem.
From my blog: IDMRockstar.com: The kicker is that sometimes, I need to run commands as root. Here's the quick and dirty way I accomplish that without divulging the passwords: ```bash #! /bin/bash read -s -p "Enter Password for sudo: " sudoPW echo $sudoPW | sudo -S yum update ``` This way the user is prompted for the password (and hidden from the terminal) and then passed into commands as needed, so I'm not running the entire script as root. =) If you have a better way, I'd love to hear it! I'm not a shell scripting expert by any means. Cheers! .: Adam
Get a Swift Variable's Actual Name as String <sep> So I am trying to get the Actual Variable Name as String in Swift, but have not found a way to do so... or maybe I am looking at this problem and solution in a bad angle. So this is basically what I want to do: <code>var appId: String? = nil //This is true, since appId is actually the name of the var appId if( appId.getVarName = "appId"){ appId = "CommandoFurball" } </code> Unfortunately I have not been able to find in apple docs anything that is close to this but this: <code>varobj.self or reflect(var).summary </code> however, this gives information of what is inside the variable itself or the type of the variable in this case being String and I want the Actual name of the Variable.
```swift class Test { var name: String = "Ido" var lastName: String = "Cohen" } let t = Test() let mirror = Mirror(reflecting: t) for child in mirror.children { print(child.label ?? "") } // print will be: name lastName ```
Prevent dismissal of UIAlertController <sep> I am adding a <code>UITextField</code> to a <code>UIAlertController</code>, which appears as an <code>AlertView</code>. Before dismissing the <code>UIAlertController</code>, I want to validate the input of the <code>UITextField</code>. Based on the validation I want to dismiss the <code>UIAlertController</code> or not. But I have no clue how to prevent the dismissing action of the <code>UIAlertController</code> when a button is pressed. Has anyone solved this problem or any ideas where to start ? I went to google but no luck :/ Thanks!
```swift weak var actionToEnable: UIAlertAction? func showAlert() { let titleStr = "title" let messageStr = "message" let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: .alert) let placeholderStr = "placeholder" alert.addTextField(withConfigurationHandler: { (textField: UITextField) in textField.placeholder = placeholderStr textField.addTarget(self, action: "textChanged:", for: .editingChanged) }) let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (_) in } let action = UIAlertAction(title: "Ok", style: .default) { (_) in let textfield = alert.textFields!.first! //Do what you want with the textfield! } alert.addAction(cancel) alert.addAction(action) self.actionToEnable = action action.enabled = false self.present(alert, animated: true) } func textChanged(sender: UITextField) { self.actionToEnable?.enabled = (sender.text == "Validation") } ```
Why do C++ classes without member variables occupy space? <sep> I found that both MSVC and GCC compilers allocate at least one byte per each class instance even if the class is a predicate with no member variables (or with just static member variables). The following code illustrates the point. <code>#include <iostream> class A { public: bool operator()(int x) const { return x>0; } }; class B { public: static int v; static bool check(int x) { return x>0; } }; int B::v = 0; void test() { A a; B b; std::cout << "sizeof(A)=" << sizeof(A) << "\n" << "sizeof(a)=" << sizeof(a) << "\n" << "sizeof(B)=" << sizeof(B) << "\n" << "sizeof(b)=" << sizeof(b) << "\n"; } int main() { test(); return 0; } </code> Output: <code>sizeof(A)=1 sizeof(a)=1 sizeof(B)=1 sizeof(b)=1 </code> My question is why does compiler need it? The only reason that I can come up with is ensure that all member var pointers differ so we can distinguish between two members of type A or B by comparing pointers to them. But the cost of this is quite severe when dealing with small-size containers. Considering possible data alignment, we can get up to 16 bytes per class without vars (?!). Suppose we have a custom container that will typically hold a few int values. Then consider an array of such containers (with about 1000000 members). The overhead will be 16*1000000! A typical case where it can happen is a container class with a comparison predicate stored in a member variable. Also, considering that a class instance should always occupy some space, what type of overhead should be expected when calling A()(value) ?
Basically, it's an interplay between two requirements: two different objects of the same type must be at different addresses. In arrays, there may not be any padding between objects. Note that the first condition alone does not require a non-zero size: given `struct empty {}; struct foo { empty a, b; };`, the first requirement could easily be met by having a zero-size `a` followed by a single padding byte to enforce a different address, followed by a zero-size `b`. However, given `empty array[2];`, that no longer works because padding between the different objects `empty[0]` and `empty[1]` would not be allowed.
How to import a tsv file with SQLite3 <sep> I have a tsv (tab separated file) that I would like to import with sqlite3. Does someone know a clear way to do it? I have installed sqlite3, but not created any database or tables yet. I've tried the command <code>.import /path/filename.tsv my_new_table </code> but it gives me the error: no such table: my_new_table. However, from what I'd read it should create the table automatically if it does't exist. Does it mean I need to create and use a database first, or is there another trick to importing a .tsv file into sqlite?
There is actually a dedicated mode for importing tab-separated files: ```sql sqlite> .mode tabs sqlite> .import data.tsv people ``` Also, if you include a header row in your TSV file, you can let SQLite automatically create the table. Just use an unused table name during import and change the TSV file to: ``` name param1 param2 Bob 30 1000 Wendy 20 900 ```
Pass parameter to Angular ng-include <sep> I am trying to display a binary tree of elements, which I go through recursively with ng-include. What is the difference between <code>ng-init="item = item.left"</code> and <code>ng-repeat="item in item.left"</code> ? In this example it behaves exactly the same, but I use similiar code in a project and there it behaves differently. I suppose it's because of Angular scopes. Maybe I shouldn't use ng-if, please explain me how to do it better. The pane.html is: <code><div ng-if="!isArray(item.left)"> <div ng-repeat="item in [item.left]" ng-include="'Views/pane.html'"> </div> </div> <div ng-if="isArray(item.left)"> {{item.left[0]}} </div> <div ng-if="!isArray(item.right)"> <div ng-repeat="item in [item.right]" ng-include="'Views/pane.html'"> </div> </div> <div ng-if="isArray(item.right)"> {{item.right[0]}} </div> <div ng-if="!isArray(item.left)"> <div ng-init = "item = item.left" ng-include="'Views/pane.html'"> </div> </div> <div ng-if="isArray(item.left)"> {{item.left[0]}} </div> <div ng-if="!isArray(item.right)"> <div ng-init="item = item.right" ng-include="'Views/pane.html'"> </div> </div> <div ng-if="isArray(item.right)"> {{item.right[0]}} </div> </code> The controller is: <code>var app = angular.module('mycontrollers', []); app.controller('MainCtrl', function ($scope) { $scope.tree = { left: { left: ["leftleft"], right: { left: ["leftrightleft"], right: ["leftrightright"] } }, right: { left: ["rightleft"], right: ["rightright"] } }; $scope.isArray = function (item) { return Array.isArray(item); } }); </code> EDIT: First I run into the problem that the directive ng-repeat has a greater priority than ng-if. I tried to combine them, which failed. IMO it's strange that ng-repeat dominates ng-if.
It's a little hacky, but I am passing variables to an ng-include with an ng-repeat of an array containing a JSON object: `<div ng-repeat="pass in [{'text':'hello'}]" ng-include="'includepage.html'"></div>` In your include page you can access your variable like this: `<p>{{pass.text}}</p>`
Jira: assign an existing git branch to an issue <sep> In JIRA connected with STASH you can create a feature branch for an issue using the button 'create branch'. (That is nice to track the commits in this issue.) If a developer started working but did not know that there is such an issue he did not click the 'create branch'. Is there any possibility to assign an existing git branch to an issue?
Update: As of January 2017, if you have an already existing branch and you want to attach it to a Jira issue, you can do the following: 1. Checkout to the branch you want to rename. 2. Execute the following command: `git branch -m JIRA_ISSUE_ID-Whatever` Assuming that my Jira issue is `SO-01`, I can do the following: `git branch -m SO-01-Whatever` This will change the name locally. Push it to remote with: `git push origin :old_name` **Command Syntax:** `git branch (-m | -M) [<oldbranch>] <newbranch>` Related question for more info.
SQL Server 2008 R2 Stuck in Single User Mode <sep> Having executed a DB deploy (from a VS SQL Server database project) on a local database, which failed, the database has been left in a state where it has single user mode left on (the deploy runs as single user mode). When I connect to it from SSMS and try something like the following: <code>ALTER DATABASE MyDatabase SET MULTI_USER; GO </code> I get the error: <blockquote> Changes to the state or options of database 'MyDatabase' cannot be made at this time. The database is in single-user mode, and a user is currently connected to it. </blockquote> I tried taking the database offline, which SSMS tells me succeeds, but it doesn't appear to actually do anything. So far, I've only been able to get around this by dropping and recreating the database (which is kind of okay, because it's only a local test database). However, I'd like to be able to reset the status. How can I convince SQL Server to take this database out of single user mode?
In the first run, following query in the master database: `exec sp_who`. If you can't find the culprit, try: `SELECT request_session_id FROM sys.dm_tran_locks WHERE resource_database_id = DB_ID('YourDatabase')`. Then kill all processes that use your database with the following query: `KILL spid`. Then run the following query: `USE Master ALTER DATABASE YourDatabase SET MULTI_USER`.
Executing a Bash Script from Golang <sep> I am trying to figure out a way to execute a script (.sh) file from Golang. I have found a couple of easy ways to execute commands (e.g. os/exec), but what I am looking to do is to execute an entire sh file (the file sets variables etc.). Using the standard os/exec method for this does not seem to be straightforward: both trying to input "./script.sh" and loading the content of the script into a string do not work as arguments for the exec function. for example, this is an sh file that I want to execute from Go: <code>OIFS=$IFS; IFS=","; # fill in your details here dbname=testDB host=localhost:27017 collection=testCollection exportTo=../csv/ # get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys keys=`mongo "$host/$dbname" --eval "rs.slaveOk();var keys = []; for(var key in db.$collection.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`; # now use mongoexport with the set of keys to export the collection to csv mongoexport --host $host -d $dbname -c $collection --fields "$keys" --csv --out $exportTo$dbname.$collection.csv; IFS=$OIFS; </code> from the Go program: <code>out, err := exec.Command(mongoToCsvSH).Output() if err != nil { log.Fatal(err) } fmt.Printf("output is %s\n", out) </code> where mongoToCsvSH can be either the path to the sh or the actual content - both do not work. Any ideas how to achieve this?
For your shell script to be directly runnable, you have to: start it with `#!/bin/sh` (or `#!/bin/bash`, etc.). You have to make it executable, aka `chmod +x script`. If you don't want to do that, then you will have to execute `/bin/sh` with the path to the script. `cmd := exec.Command("/bin/sh", mongoToCsvSH)`
Verifying PEP8 in iPython notebook code <sep> Is there an easy way to check that iPython notebook code, while it's being written, is compliant with PEP8?
This text appears to be instructions for using code style checking tools. Here's a cleaned-up version: "Make sure you have the `pycodestyle` or `flake8` module to check your code against style guides. Then enable the magic function by using the `pycodestyle_magic` module (GitHub repo): `pip install flake8 pycodestyle_magic` First, load the magic in a Jupyter Notebook cell: `%load_ext pycodestyle_magic` and then turn on the magic to do compliance checking for each cell using: `%pycodestyle_on` or `%flake8_on` depending on which style guide you want to check. To turn off the auto-compliance-checking run: `%pycodestyle_off` or `%flake8_off`. " Let me know if you have any other text you'd like me to review!
This compilation unit is not on the build path of a Java project <sep> When I try to use <code>ctrl+space</code> this error is shown: <code>This compilation unit is not on the build path of a Java project. </code> I see that there are similar topics but my work environment is Eclipse and i pull my project from Git (I import project as general project) and i use Apache Ant. Can anyone help me?
Another alternative to Loganathan Mohanraj's solution (which effectively does the same, but from the GUI): Right-click on your project, go to "Properties," choose "Project Natures," click "Add," choose "Java," click "Apply and Close."
Branching and merging best practices in Git <sep> We have a developer team of 4 and have recently moved to Git. We want to learn best practices regarding workflow with branching and merging. We are using a lightweight version of Git Flow. We have a dev, staging and a master branch which are all linear with each other. staging is branched from master dev is branched from staging On top of that we use feature and hotfix branches to work on new features and fix bugs. I have the following questions: Should we branch feature branches from dev or from master? When a feature branch is ready, should we merge the feature branch into dev, then merge dev into staging, or merge the feature branch into staging and then the feature branch into master? I think we should branch from master and merge the feature branch up, because there might be something in dev that we might not want to merge to staging and master. What is your opinion? What are the best practices?
While Git Flow is an excellent branching model, the questions you are asking are a symptom of a bigger problem: Git Flow is too heavy for a small team working on a consumer web product (I'm assuming you are working on a consumer web product; feel free to ignore this if you are coding nuclear power plant control room software). I would like to encourage you to consider Continuous Deployment (CD) with an extremely simple branching model: It is very easy to set up CD nowadays. Use Travis, CodeShip, Jenkins, or a similar system to run a full build and test suite on every commit pushed to every branch of your codebase. Set up Travis/CodeShip/Jenkins to deploy to production every commit to `master` that passes the tests. Create a new branch from `master` for every new feature. Code a new feature and test it on a branch. Merge a feature branch into `master`, and watch it go live. There are a lot of common objections to this, all of which can be summarized as "but what if I introduce a bug?!" The answer is "You'll fix it!". If you write tests, monitor your production site, do code reviews, practice pair programming, use feature flags, and keep your features small, then the benefits you get from CD will outweigh the occasional problems any day. I encourage you to try it. It will free your mind to focus on what truly matters: building a great product! If you don't believe me, take a look at this excellent presentation from GitHub.
Converting pandas.tslib.Timestamp to datetime python <sep> I have a <code>df</code> time series. I extracted the indexes and want to convert them each to <code>datetime</code>. How do you go about doing that? I tried to use <code>pandas.to_datetime(x)</code> but it doesn't convert it when I check after using <code>type()</code>
```python Just try to_pydatetime() >>> import pandas as pd >>> t = pd.tslib.Timestamp('2016-03-03 00:00:00') >>> type(t) pandas.tslib.Timestamp >>> t.to_pydatetime() datetime.datetime(2016, 3, 3, 0, 0) Change to datetime.date type >>> t.date() datetime.date(2016, 3, 3) ```
How to extract some value from cookie in nginx <sep> I am new to Nginx and hope to get some help. I want to extract certain data (certain fields set by my PHP scripts) from browser cookie in nginx so that I can log it. If possible, I want to do this just by modifying nginx configuration. Any pointer/help would be greatly appreciated.
If anyone is using the previous answer with several different cookies in the response, the correct regex is: ``` map $http_cookie $auth_header { default ""; "~*OAuth.AccessToken=(?<token>[^;]+)" "Bearer $token"; } ``` or for more general usage: ``` map $http_cookie $auth_header { default ""; "~*yourCookieName=(?<variable>[^;]+)" "the value you wanna set $variable"; } ```
How to edit Docker container files from the host? <sep> Now that I found a way to expose host files to the container (-v option) I would like to do kind of the opposite: How can I edit files from a running container with a host editor? sshfs could probably do the job but since a running container is already some kind of host directory I wonder if there is a portable (between aufs, btrfs and device mapper) way to do that?
The best way is: ``` $ docker cp CONTAINER:FILEPATH LOCALFILEPATH $ vi LOCALFILEPATH $ docker cp LOCALFILEPATH CONTAINER:FILEPATH ``` Limitations with `docker exec`: it can only attach to a running container. Limitations with `docker run`: it will create a new container.
Can neural networks approximate any function given enough hidden neurons? <sep> I understand neural networks with any number of hidden layers can approximate nonlinear functions, however, can it approximate: <code>f(x) = x^2 </code> I can't think of how it could. It seems like a very obvious limitation of neural networks that can potentially limit what it can do. For example, because of this limitation, neural networks probably can't properly approximate many functions used in statistics like Exponential Moving Average, or even variance. Speaking of moving average, can recurrent neural networks properly approximate that? I understand how a feedforward neural network or even a single linear neuron can output a moving average using the sliding window technique, but how would recurrent neural networks do it without X amount of hidden layers (X being the moving average size)? Also, let us assume we don't know the original function f, which happens to get the average of the last 500 inputs, and then output a 1 if it's higher than 3, and 0 if it's not. But for a second, pretend we don't know that, it's a black box. How would a recurrent neural network approximate that? We would first need to know how many timesteps it should have, which we don't. Perhaps a LSTM network could, but even then, what if it's not a simple moving average, it's an exponential moving average? I don't think even LSTM can do it. Even worse still, what if f(x,x1) that we are trying to learn is simply <code>f(x,x1) = x * x1 </code> That seems very simple and straightforward. Can a neural network learn it? I don't see how. Am I missing something huge here or are machine learning algorithms extremely limited? Are there other learning techniques besides neural networks that can actually do any of this?
The key point to understand is this: Neural networks (as any other approximation structure, like polynomials, splines, or radial basis functions) can approximate any continuous function only within a compact set. In other words, the theory states that, given a continuous function *f(x)*, a finite range for the input *x* , [a,b], and a desired approximation accuracy ε > 0, then there exists a neural network that approximates *f(x)* with an approximation error less than ε, everywhere within [a,b]. Regarding your example of *f(x)* = *x*², yes, you can approximate it with a neural network within any finite range: [-1,1], [0, 1000], etc. To visualize this, imagine approximating *f(x)* within [-1,1] with a step function. Can you do it on paper? Note that if you make the steps narrow enough, you can achieve any desired accuracy. The way neural networks approximate *f(x)* is not much different than this. But again, there is no neural network (or any other approximation structure) with a finite number of parameters that can approximate *f(x)* = *x*² for all *x* in [-∞, +∞].
How to use git branch with Android Studio <sep> I am new to git. I have a very simple scenario for using git. I had my first release written with Android Studio. Now I want to work with some new features. What I did so far: enabled the VCS in my Android Studio created a local repository for my project from Android Studio pushed my local repository to my Bitbucket remote repository (<code>$git push -u origin master</code>) Now I am confused for the next step: create a feature branch. Should I create a branch in the local repository: <code>$ git branch --track feature1 origin/master </code> or should I create a new branch from the Bitbucket web portal, and clone the new branch? I also want to know how I can switch branches with Android Studio? For example, switch from feature branch to master branch to work on some hotfix. Do I need to use the Bitbucket plugin to checkout the project very time from the remote repository every time I switch branches or I can hot switch it inside Android Studio? Thanks!
Here's the best way I know to update the remote branches in Android Studio 1.5: 1) Go to VCS > Git > Pull (make sure you've pulled your latest changes from master first). 2) Click the blue refresh button on this screen. 3) Notice all your new branches show up. Click the checkbox of the one you want to switch to and click the "Pull" button. 4) Go back to the "Git:master" menu in the bottom right of Android Studio, and you'll notice your new branch showed up in the remote section. 5) Click on the branch you want to checkout and select "Check out as new local branch."
Does spring boot support using both properties and yml files at the same time? <sep> I have a spring boot application and I want to use both a yml file for my application properties and also a plain application-${profile}.properties file set to configure my application. So my question is can this be done and if so, how do you configure spring boot to look for both the yml file and the properties and merge them into one set per environment? As to why I want/need to use both, it is because I like the flexibility and ease of use of yml files but an internal component (for encryption) requires using the properties file set. I did see this point being made YAML files cant be loaded via the @PropertySource annotation but nothing stating whether both can be used together. Please provide detailed configuration (XML or Java config) on how to get this working. TIA, Scott
Yes, you can use both YAML and properties at the same time in the same project. When you use both, for example, `application.yml` and `application.properties` at the same time in the same project, `application.yml` will be loaded first, and then `application.properties`. An important point to note is that if `application.yml` and `application.properties` have the same keys—for example, `application.yml` has `spring.app.name = testYML` and `application.properties` has `spring.app.name = testProperties`—then the value in `application.yml` will be overwritten by the value in `application.properties` since it is loaded last. The final value in `spring.app.name` will be `testProperties`.
Uninstall packages in Mac OS X <sep> How can you completely uninstall (remove files that belong to a certain package) in Mac OS X? Can this be done using a command in the terminal? I have installed a .pkg package on my Mac and I am wondering as to how I can uninstall the entire package without using a third party application such as UninstallPKG? I am wondering whether uninstalling .dmg files also require third party applications or is it possible to uninstall them entering a command in the terminal?
Use this command in terminal to check the list of packages and uninstall your files: ``` $ pkgutil --pkgs # list all installed packages ``` Once you've uninstalled the files, you can remove the receipt with: ``` $ sudo pkgutil --forget the-package-name.pkg ``` After visually inspecting the list of files, you can do something like: ``` $ pkgutil --pkg-info the-package-name.pkg # check the location $ cd / # assuming the package is rooted at /... $ pkgutil --only-files --files the-package-name.pkg | tr '\n' '\0' | xargs -n 1 -0 sudo rm -i ``` Be careful of this last step. The list of directories output by `pkgutil --files` can include important shared directories like `/usr`, which you don't want to remove. ``` $ pkgutil --only-dirs --files the-package-name.pkg | tr '\n' '\0' | xargs -n 1 -0 sudo rm -ir ``` Copied from here (Wayback Machine snapshot of the original).
How to customize the APK file name for product flavors? <sep> I am customizing the name of the APK file of my Android application within the <code>build.gradle</code> script as follows: <code>android { defaultConfig { project.ext.set("archivesBaseName", "MyApplication"); } } </code> Now that I am using product flavors: <code>android { productFlavors { green { applicationId "com.example.myapplication.green" } blue { applicationId "com.example.myapplication.blue" } } } </code> Is there a way to customize the name of each APK? I experimented with <code>archiveBaseName</code> and <code>baseName</code> without success. In the end I want to come up with the following files: <code>build/outputs/apk/Blue-debug-1.2.1.apk build/outputs/apk/Blue-debug-unaligned.apk build/outputs/apk/Blue-release-1.2.1.apk build/outputs/apk/Blue-release-unaligned.apk build/outputs/apk/Green-debug-1.2.1.apk build/outputs/apk/Green-debug-unaligned.apk build/outputs/apk/Green-release-1.2.1.apk build/outputs/apk/Green-release-unaligned.apk </code>
This will help you in 2022. ```android { //........ flavorDimensions "version" productFlavors { Free { dimension "version" applicationId "com.exampleFree.app" } Paid { dimension "version" applicationId "com.examplePaid.app" } } applicationVariants.all { variant -> variant.outputs.all { output -> def appId = variant.applicationId // com.exampleFree.app OR com.examplePaid.app def versionName = variant.versionName def versionCode = variant.versionCode // e.g. 1.0 def flavorName = variant.flavorName // e.g. Free def buildType = variant.buildType.name // e.g. debug def variantName = variant.name // e.g. FreeDebug //customize your app name by using variables outputFileName = "${variantName}.apk" } } } ``` Apk name: FreeDebug.apk Proof
NewtonSoft add JSONIGNORE at runTime <sep> Am looking to Serialize a list using NewtonSoft JSON and i need to ignore one of the property while Serializing and i got the below code <code>public class Car { // included in JSON public string Model { get; set; } // ignored [JsonIgnore] public DateTime LastModified { get; set; } } </code> But am using this Specific class Car in many places in my application and i want to Exclude the option only in one place. Can i dynamically add [JsonIgnore] in the Specific Place where i need ? How do i do that ?
NewtonSoft JSON has a built-in feature for that: `public bool ShouldSerializeINSERT_YOUR_PROPERTY_NAME_HERE() { if (someCondition) { return true; } else { return false; } }` It is called "conditional property serialization" and the documentation can be found here. Warning: first of all, it is important to get rid of `[JsonIgnore]` above your `{get;set;}` property. Otherwise, it will overwrite the `ShouldSerializeXYZ` behavior.
What is setContentView(R.layout.main)? <sep> I understand that it has to do with the App layout, but when do I have to use it? I tried to look for a link that explained this method, but I couldn't find it. Thank you in advance!
In Android, the visual design is stored in XML files, and each Activity is associated with a design. `setContentView(R.layout.main)`: `R` means Resource, `layout` means design, and `main` is the XML you have created under `res->layout->main.xml`. Whenever you want to change the current look of an Activity, or when you move from one Activity to another, the new Activity must have a design to show. We call `setContentView` in `onCreate` with the desired design as an argument.
What's a good regex to include accented characters in a simple way? <sep> Right now my regex is something like this: [a-zA-Z0-9] but it does not include accented characters like I would want to. I would also like - ' , to be included.
You put in your expression: `\p{L}\p{M}`. This in Unicode will match: any letter character (L) from any language and marks (M) (i.e., a character that is to be combined with another: accent, etc.).
Ansible copy ssh key from one host to another <sep> I have 2 app servers with a loadbalancer in front of them and 1 database server in my system. I'm provisioning them using Ansible. App servers has Nginx + Passenger and running for a Rails app. Will use capistrano for deployment but I have an issue about ssh keys. My git repo is in another server and I have to generate ssh public keys on appservers and add them to the Git server(To authorized_keys file). How can I do this in ansible playbook? PS: I may have more than 2 app servers.
This does the trick for me; it collects the public SSH keys on the nodes and distributes them over all the nodes. This way, they can communicate with each other. ```yaml - hosts: controllers gather_facts: false remote_user: root tasks: - name: fetch all public SSH keys shell: cat ~/.ssh/id_rsa.pub register: ssh_keys tags: - ssh - name: check keys debug: msg="{{ ssh_keys.stdout }}" tags: - ssh - name: deploy keys on all servers authorized_key: user=root key="{{ item[0] }}" delegate_to: "{{ item[1] }}" with_nested: - "{{ ssh_keys.stdout }}" - "{{ groups['controllers'] }}" tags: - ssh ``` Info: This is for the user `root`.
IntelliJ IDEA cannot resolve import javax.servlet.*; <sep> So I had my project working perfectly and I decided to install a new hard drive (SSD) and now I cannot get it to run correctly. I am using Intellij and am having all of these imports have issues. <code>import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; </code> They are saying cannot resolve symbol. Also in my web.xml I have this. <code><filter> <filter-name>LoginFilter</filter-name> <filter-class>com.mkyong.LoginFilter</filter-class> </filter> </code> it states <code>com.mkyong.LoginFilter is not assignable to javax.servlet.Filter </code> Im going to include my web.xml just in case someone needs it. <code><?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>JavaServerFaces</display-name> <resource-ref> <description>MySQL Datasource example</description> <res-ref-name>jdbc/mkyongdb</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> <!-- Change to "Production" when you are ready to deploy --> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <!-- Welcome page --> <welcome-file-list> <welcome-file>faces/default.xhtml</welcome-file> </welcome-file-list> <!-- JSF mapping --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Map these files with JSF --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.mkyong.LoginFilter</filter-class> </filter> <!-- Set the login filter to secure all the pages in the /secured/* path of the application --> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/secured/*</url-pattern> </filter-mapping> <!-- By default go to secured welcome page --> <welcome-file-list> <welcome-file>secured/welcome.xhtml</welcome-file> </welcome-file-list> </web-app> </code> This is the error I am getting now. <code> javax.servlet.ServletException: Servlet.init() for servlet Faces Servlet threw exception org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277) org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2381) org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2370) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) root cause java.lang.IllegalStateException: Application was not properly initialized at startup, could not find Factory: javax.faces.context.FacesContextFactory javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:800) javax.faces.FactoryFinder.getFactory(FactoryFinder.java:302) javax.faces.webapp.FacesServlet.init(FacesServlet.java:186) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277) org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2381) org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2370) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) </code> I was also using apache tomcat 8 at first then I thought that might be the issue and I changed it to 7 then to 6. If you need anything else please let me know! here is the POM.xml as requested. <code> <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong.common</groupId> <artifactId>JavaServerFaces</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>JavaServerFaces Maven Webapp</name> <url>http://maven.apache.org</url> <repositories> <repository> <id>java.net.m2</id> <name>java.net m2 repo</name> <url>http://download.java.net/maven/2</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>3.2.5.RELEASE</version> </dependency> <!-- MySQL database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>2.5.6</version> </dependency> <!-- For Servlet Container like Tomcat --> <!-- http://download.java.net/maven/2 --> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.0-b03</version> </dependency> <!-- EL 2.2 to support method parameter in EL --> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> </dependency> <!-- http://repo1.maven.org/maven2/ --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <finalName>JavaServerFaces</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </code>
As someone mentioned above, these libraries are part of an application server, so they should not be deployed to the server as other libraries like Spring. You need to reference them as a provided resource. If you are not using Maven for your project (e.g., tutorials), you can go to your Project Structure settings / Modules / your module / Dependencies... and down under the list of dependencies is a small plus symbol (+) where you can select "Library" and after that, the popup with Application Server Libraries will show. It should be selected as provided afterward.
Is it possible to delete issues on GitLab? <sep> I recently installed GitLab to try it out and I am really enjoying it. It's very easy to install and use, still, I found an annoying "problem". I haven't yet found a way to delete Issues associated to projects. I know that it's not a good practice to remove Issues from the system, but there are some specific occasions where this is really useful, such as when you create an Issue that makes no sense and don't want to be in the system, even after being closed. So, my question, really simple: Is it possible to delete Issues on GitLab? If so, how can I do it? I am using GitLab 7.2.1, on Debian wheezy. Many thanks
It is now possible to delete issues starting with GitLab 8.6: GitLab 8.6 released with Deploy to Kubernetes and Subscribe to Label. > Delete Issues Sometimes, simply closing an issue or merge request is not sufficient. For those times, we are now making it possible to delete issues and merge requests. Only `owners` can delete issues by editing the issue or merge request and clicking, you guessed it, `Delete`.
How to use Objective-C enum in Swift <sep> I have 2 enum definition in Objective-C file and Swift file. Japanese.h <code>typedef enum { JapaneseFoodType_Sushi = 1, JapaneseFoodType_Tempura = 2, } JapaneseFoodType; </code> US.swift <code>enum USFoodType { case HUMBERGER; case STEAK; } </code> as we know, I can use Objective-C enum like following; Japanese.m <code>- (void)method { JapaneseFoodType type1 = JapaneseFoodType_Sushi; JapaneseFoodType type2 = JapaneseFoodType_Tempura; if (type1 == type2) {// this is no problem } } </code> But I can not use Objective-C enum in Swift file like following; <code> func method() { var type1: USFoodType = USFoodType.HUMBERGER// no problem var type2: USFoodType = USFoodType.HUMBERGER// no problem if type1 == type2 { } var type3: JapaneseFoodType = JapaneseFoodType_Sushi// no problem var type4: JapaneseFoodType = JapaneseFoodType_Tempura// no problem if type3 == type4 {// 'JapaneseFoodType' is not convertible to 'Selector' } } </code> Is this a bug of Swift? And how can I use Objective-C (C) enum in Swift file?
I think this is a bug because Swift should define `==` for C enums or provide an "to Int" conversion, but it doesn't. The simplest workaround is to redefine your C enum as: ``` typedef NS_ENUM(NSUInteger, JapaneseFoodType) { JapaneseFoodType_Sushi = 1, JapaneseFoodType_Tempura = 2, }; ``` which will allow LLVM to process the enum and convert it to a Swift enum ( `NS_ENUM` also improves your Obj-C code!). Another option is to define the equality using a reinterpret cast: ```swift public func ==(lhs: JapaneseFoodType, rhs: JapaneseFoodType) -> Bool { var leftValue: UInt32 = reinterpretCast(lhs) var rightValue: UInt32 = reinterpretCast(rhs) return (leftValue == rightValue) } ```
Error 6002: The table/view does not have a primary key defined <sep> I am getting a couple of these errors that make perfect sense as they are on views. I understand what they mean, however I am looking for a way to prevent that warning message from being generated with the model. I thought I could edit the .edmx XML to remove the errors but the warnings get regenerated. I have a key defined on the views although it doesn't seem to have helped. Any way to get rid of these warnings? Or is there someway to have the Entity Framework realize that this is not an editable table and that is doesn't need a primary key? I'm asking mostly from a project aesthetics point-of-view (I don't like seeing warnings in my Error List).
In my case, this was easily solved. Here are the steps: 1. Clean the solution. 2. Close Visual Studio. 3. Open Visual Studio. 4. Clean and build the solution. Before trying anything else, you can try this to make sure you're not manually changing anything in the edmx file. I hope this helps.
Mongoose, find, return specific properties <sep> I have this get call: <code>exports.getBIMFromProject = function(req, res){ mongoose.model('bim').find({projectId: req.params['prj_id']}, function(err, bim){ if(err){ console.error(err); res.send(500) } res.send(200, bim); }); }; </code> Where do I specify which properties I want to return? Can't find it in the docs. The above returns the entire object. I only want a few properties returned. This is my schema: <code>var mongoose = require('mongoose'), Schema = mongoose.Schema; var bimSchema = new Schema({ projectId: Number, user: String, items:[ { bimObjectId: Number, typeId: String, position:{ floor: String, room:{ name: String, number: String } } } ] }); mongoose.model('bim', bimSchema); </code> I don't want the items array included in my rest call.
Mongoose provides multiple ways to project documents with `find`, `findOne`, and `findById`. 1. Projection as String: // INCLUDE SPECIFIC FIELDS // `User.findOne({ email: email }, 'name phone');` // EXCLUDE SPECIFIC FIELD // `User.findOne({ email: email }, '-password');` 2. Projection by passing `projection` property: `User.findOne({ email: email }, { projection: { _id: 1 } });` 3. Using `.select` method: `// find user and return just _id and name field User.findOne({ email: email }).select('name');` `// find user and return all fields except _id User.findOne({ email: email }).select({ _id: 0 });` You can do the same with `find` and `findById` methods too.
UICollectionView insert cells above maintaining position (like Messages.app) <sep> By default Collection View maintains content offset while inserting cells. On the other hand I'd like to insert cells above the currently displaying ones so that they appear above the screen top edge like Messages.app do when you load earlier messages. Does anyone know the way to achieve it?
This is the technique I use. I've found others cause strange side effects, such as screen flicker: ``` CGFloat bottomOffset = self.collectionView.contentSize.height - self.collectionView.contentOffset.y; [CATransaction begin]; [CATransaction setDisableActions:YES]; [self.collectionView performBatchUpdates:^{ [self.collectionView insertItemsAtIndexPaths:indexPaths]; } completion:^(BOOL finished) { self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentSize.height - bottomOffset); }]; [CATransaction commit]; ```
how to lock portrait orientation for only main view using swift <sep> I have created an application for iPhone, using swift, that is composed from many views embedded in a navigation controller. I would like to lock the main view to Portrait orientation and only a subview of a navigation controller locked in Landscape orientation. Here is an example of what i mean: UINavigationController UiViewController1 (Locked in Portrait) Initial view controller with a button placed on the navigation bar that give to the user the possibility to access to a lists where can be selected other views UIViewController2 (Locked in Landscape) UiViewController3 (Portrait and Landscape) UiViewController4 (Portrait and Landscape) ... ... How Can i do that?
Things can get quite messy when you have a complicated view hierarchy, like having multiple navigation controllers and/or tab view controllers. This implementation puts it on the individual view controllers to set when they would like to lock orientations, instead of relying on the App Delegate to find them by iterating through subviews or relying on inheritance. Swift 3 In `AppDelegate`: ```swift /// Set orientations you want to be allowed in this property by default var orientationLock = UIInterfaceOrientationMask.all func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return self.orientationLock } ``` In some other global struct or helper class, here I created `AppUtility`: ```swift struct AppUtility { static func lockOrientation(_ orientation: UIInterfaceOrientationMask) { if let delegate = UIApplication.shared.delegate as? AppDelegate { delegate.orientationLock = orientation } } /// OPTIONAL Added method to adjust lock and rotate to the desired orientation static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) { self.lockOrientation(orientation) UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation") } } ``` Then in the desired `ViewController` you want to lock orientations: ```swift override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) AppUtility.lockOrientation(.portrait) // Or to rotate and lock // AppUtility.lockOrientation(.portrait, andRotateTo: .portrait) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Don't forget to reset when view is being removed AppUtility.lockOrientation(.all) } ```
Run a function periodically in Scala <sep> I want to call an arbitrary function every <code>n</code> seconds. Basically I want something identical to <code>SetInterval</code> from Javascript. How can I achieve this in Scala?
If you happen to be on Akka, Scheduler is quite convenient for this: ```scala val system = ActorSystem("mySystem", config) // ... now with system in current scope: import system.dispatcher system.scheduler.schedule(10 seconds, 1 seconds) { doSomeWork() } ``` There is also `scheduleOnce` for one-off execution. The usual warnings about closing over mutable state apply.
Unable to apply methods on timestamps using Series built-ins <sep> On the following series: <code>0 1411161507178 1 1411138436009 2 1411123732180 3 1411167606146 4 1411124780140 5 1411159331327 6 1411131745474 7 1411151831454 8 1411152487758 9 1411137160544 Name: my_series, dtype: int64 </code> This command (convert to timestamp, localize and convert to EST) works: <code>pd.to_datetime(my_series, unit='ms').apply(lambda x: x.tz_localize('UTC').tz_convert('US/Eastern')) </code> but this one fails: <code>pd.to_datetime(my_series, unit='ms').tz_localize('UTC').tz_convert('US/Eastern') </code> with: <code>TypeError Traceback (most recent call last) <ipython-input-3-58187a4b60f8> in <module>() ----> 1 lua = pd.to_datetime(df[column], unit='ms').tz_localize('UTC').tz_convert('US/Eastern') /Users/josh/anaconda/envs/py34/lib/python3.4/site-packages/pandas/core/generic.py in tz_localize(self, tz, axis, copy, infer_dst) 3492 ax_name = self._get_axis_name(axis) 3493 raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' % -> 3494 ax_name) 3495 else: 3496 ax = DatetimeIndex([],tz=tz) TypeError: index is not a valid DatetimeIndex or PeriodIndex </code> and so does this one: <code>my_series.tz_localize('UTC').tz_convert('US/Eastern') </code> with: <code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-0a7cb1e94e1e> in <module>() ----> 1 lua = df[column].tz_localize('UTC').tz_convert('US/Eastern') /Users/josh/anaconda/envs/py34/lib/python3.4/site-packages/pandas/core/generic.py in tz_localize(self, tz, axis, copy, infer_dst) 3492 ax_name = self._get_axis_name(axis) 3493 raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' % -> 3494 ax_name) 3495 else: 3496 ax = DatetimeIndex([],tz=tz) TypeError: index is not a valid DatetimeIndex or PeriodIndex </code> As far as I understand, the second approach above (the first one that fails) should work. Why does it fail?
As Jeff's answer mentions, `tz_localize()` and `tz_convert()` act on the index, not the data. This was a huge surprise to me too. Since Jeff's answer was written, Pandas 0.15 added a new `Series.dt` accessor that helps your use case. You can now do this: `pd.to_datetime(my_series, unit='ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern')`
Docker interactive mode and executing script <sep> I have a Python script in my docker container that needs to be executed, but I also need to have interactive access to the container once it has been created ( with /bin/bash ). I would like to be able to create my container, have my script executed and be inside the container to see the changes/results that have occurred (no need to manually execute my python script). The current issue I am facing is that if I use the CMD or ENTRYPOINT commands in the docker file I am unable to get back into the container once it has been created. I tried using docker start and docker attach but I'm getting the error: <code>sudo docker start containerID sudo docker attach containerID "You cannot attach to a stepped container, start it first" </code> Ideally, something close to this: <code>sudo docker run -i -t image /bin/bash python myscript.py </code> Assume my python script contains something like (It's irrelevant what it does, in this case it just creates a new file with text): <code>open('newfile.txt','w').write('Created new file with text\n') </code> When I create my container I want my script to execute and I would like to be able to see the content of the file. So something like: <code>root@66bddaa892ed# sudo docker run -i -t image /bin/bash bash4.1# ls newfile.txt bash4.1# cat newfile.txt Created new file with text bash4.1# exit root@66bddaa892ed# </code> In the example above my python script would have executed upon creation of the container to generate the new file newfile.txt. This is what I need.
My way of doing it is slightly different and has some advantages. It is actually a multi-session server rather than a script, but could be even more usable in some scenarios: ``` # Just create an interactive container. No start but named for future reference. # Use your own image. docker create -it --name new-container <image> # Now start it. docker start new-container # Now attach a bash session. docker exec -it new-container bash ``` The main advantage is that you can attach several bash sessions to a single container. For example, I can `exec` one session with bash for viewing logs and in another session do actual commands. BTW, when you detach the last `exec` session, your container is still running so it can perform operations in the background.
Charles proxy not working with Chrome <sep> I am working on Mac and have identical Proxy settings for the System and Firefox browser. However, I am able to see my Firefox traffic in Chrales but I don't see my Chrome and Safari traffic (which use System Proxy Settings). What do I need to do? How can I check the debug this? Already restarted my browser but it didn't help. I have set and reset proxy settings, but of no use. One thing to note: I am on a VPN although I don't think this should affect Chrome as Firefox is going through the proxy.
For anyone else using a VPN: Charles must be turned on before the VPN. So quitting the VPN after turning on Charles won't work either. Also, in my case, the VPN can't be turned on at all.
collecting HashMap&gt; java 8 <sep> I want to be able to convert a <code>List</code> to a <code>HashMap</code> where the key is the <code>elementName</code> and the values is a list of something random (in this case its the Element Name). So in short I want (<code>A->List(A), B->List(B), C-> List(C)</code>). I tried using <code>toMap()</code> and passing it the <code>keyMapper</code> and <code>ValueMapper</code> but I get a compilation error. I would really appreciate if someone can help me out. Thanks! <code>public static void main(String[] args) { // TODO Auto-generated method stub List<String> list = Arrays.asList("A","B","C","D"); Map<String, List<String>> map = list.stream().map((element)->{ Map<String, List<String>> map = new HashMap<>(); map.put(element, Arrays.asList(element)); return map; }).collect(??); } Function<Map<String, String>, String> key = (map) -> { return map.keySet().stream().findFirst().get(); }; Function<Map<String, String>, String> value = (map) -> { return map.values().stream().findFirst().get(); }; </code> === This worked for me Thanks for all the help guys! @izstas "they should operate on the elements" helped a lot :). Actually this is what I was looking for to be exact <code>public static void test2 (){ Function<Entry<String, List<String>>, String> key = (entry) -> { return entry.getKey(); }; Function<Entry<String, List<String>>, List<String>> value = (entry) -> { return new ArrayList<String>(entry.getValue()); }; BinaryOperator<List<String>> merge = (old, latest)->{ old.addAll(latest); return old; }; Map<String, List<String>> map1 = new HashMap<>(); map1.put("A", Arrays.asList("A1", "A2")); map1.put("B", Arrays.asList("B1")); map1.put("D", Arrays.asList("D1")); Map<String, List<String>> map2 = new HashMap<>(); map2.put("C", Arrays.asList("C1","C2")); map2.put("D", Arrays.asList("D2")); Stream<Map<String, List<String>>> stream =Stream.of(map1, map2); System.out.println(stream.flatMap((map)->{ return map.entrySet().stream(); }).collect(Collectors.toMap(key, value, merge))); } </code>
You can use the `groupingBy` method to manage aggregation, for example: ```java public static void main(String[] args) { List<String> list = Arrays.asList("A", "B", "C", "D", "A"); Map<String, List<String>> map = list.stream().collect(Collectors.groupingBy(Function.identity())); } ``` If you want more flexibility (for example, to map the value and return a Set instead of a List), you can always use the `groupingBy` method with more parameters as specified in the javadoc: ```java Map<City, Set<String>> namesByCity = people.stream().collect(Collectors.groupingBy(Person::getCity, mapping(Person::getLastName, toSet()))); ```
how do you set up a required select without a default value selected <sep> I'm trying force the user to make a selection, rather than just using the first field. How do I prevent the user from submitting this form without using javascript? <code><select required> <option >Make a selection</option> <option value="saab">Saab</option> <option value="vw">VW</option> <option value="audi">Audi</option> </select> </code>
Per this answer, you can use HTML5's `required` attribute on a `<select>` if you give the default `<option>` an empty `value` attribute (among other criteria; see the `<select>` docs). > If a select element has a `required` attribute specified, does not have a `multiple` attribute specified, and has a display size of 1; and if the value of the first option element in the select element's list of options (if any) is the empty string, and that option element's parent node is the select element (and not an `optgroup` element), then that option is the select element's placeholder label option. So you would want `<select required> <option value="">Make a selection</option> <!-- more <option>s --> </select>`. Older browsers will need a JavaScript solution, as they do not support HTML5.
Swift subclassing - how to override Init() <sep> I have the following class, with an init method: <code>class user { var name:String var address:String init(nm: String, ad: String) { name = nm address = ad } } </code> I'm trying to subclass this class but I keep getting errors on the <code>super.init()</code> part: <code>class registeredUser : user { var numberPriorVisits: Int // This is where things start to go wrong - as soon as I type 'init' it // wants to autocomplete it for me with all of the superclass' arguments, // and I'm not sure if those should go in there or not: init(nm: String, ad: String) { // And here I get errors: super.init(nm: String, ad: String) // etc.... </code> Apple's iBook has examples of subclassing, but none those feature classes that have an <code>init()</code> method with any actual arguments in it. All their init's are devoid of arguments. So, how do you do this?
In addition to Chuck's answer, you also have to initialize your newly introduced property before calling `super.init`. >A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer. (The Swift Programming Language -> Language Guide -> Initialization) Thus, to make it work: ```swift init(nm: String, ad: String) { numberPriorVisits = 0 super.init(nm: nm, ad: ad) } ``` This simple initialization to zero could have been done by setting the property's default value to zero too. It's also encouraged to do so: ```swift var numberPriorVisits: Int = 0 ``` If you don't want such a default value, it would make sense to extend your initializer to also set a new value for the new property: ```swift init(name: String, ads: String, numberPriorVisits: Int) { self.numberPriorVisits = numberPriorVisits super.init(nm: name, ad: ads) } ```
Facebook login is currently unavailable <sep> I'm setting up a 'Login with Facebook' button and have it on a test page. http://www.digitalinkmultimedia.com/my-account I believe I have things set up correctly for the app at developers.facebook.com. The app says it's public and available. I'm using Business Catalyst as the CRM, and the facebook integration appears to be correct (App ID, App Secret, etc) When I click the login with facebook button the first time I get the message about my profile info being shared....but when I continue I get a 'Facebook login is currently unavailable'. One thing I noticed is that when the popup first loads the FBTOKEN parameter has a number in it, then it quickly changes to FBUTOKEN=00000000-0000-0000-0000-000000000000#= Any suggestions would be appreciated.
In the Facebook Developers Console for your app, please go to App Review > Permission Features and grant Advanced Access for "public_profile" and "email". Facebook Login for the iOS app is working well without the Advanced Access setting.
Stop Angular Animation from happening on ng-show / ng-hide <sep> In my AngularJS application I'm using fontawesome for my loading spinners: <code><i class="fa fa-spin fa-spinner" ng-show="loading"></i> </code> I'm also using AngularToaster for notification messages which has a dependency on ngAnimate. When I include ngAnimate in my AngularJS application, it messes up my loading spinners by animating them in a weird way. I want to stop this from happening but cant find a way to disable the animation on just these loaders (it would also stink to have to update every loader I have in my app). Heres a plunkr showing my exact problem. http://plnkr.co/edit/wVY5iSpUST52noIA2h5a
I had a similar problem where my icon would keep spinning until the animation finished, even after the $scope variable turned off. What worked for me was to wrap the <i> fa-icon element in a span. `<span ng-if="loading"><i class="fa fa-refresh fa-spin"></i></span>` Try it!
List all files changed in a pull request in Git/GitHub <sep> Is there a way (from the command line) to list the names of all files changed in a PR in Git/GitHub? This would be used to find what tests need to be run in a Travis CI build for that PR. The CI build runs these commands before it calls our script: <code>git clone --depth=50 git://github.com/jekyll/jekyll.git jekyll/jekyll cd jekyll/jekyll git fetch origin +refs/pull/2615/merge git checkout -qf FETCH_HEAD </code>
Using GitHub CLI (gh) you can run: ``` gh pr view 2615 --json files --jq '.files.[].path' ``` I have made a `gh alias` because I use it regularly: ``` gh alias set pr_files "pr view $1 --json files --jq '.files.[].path'" ``` and then I call it with `gh pr_files 2615` or `gh pr_files 2615 | cat`
Jenkins Git Plugin not pulling latest changes before building job <sep> I am working with Jenkins CI and am trying to properly configure my jobs to use git. I have the git plugin installed and configured for one of my jobs. When I build the job, I expect it to pull the latest changes for the branch I specify and then continue with the rest of the build process (e.g., unit tests, etc.). When I look at the console output, I see <code>> git fetch --tags --progress ssh://gerrit@git-dev/Util +refs/heads/*:refs/remotes/origin/* > git rev-parse origin/some_branch^{commit} Checking out Revision <latest_SHA1> (origin/some_branch) > git config core.sparsecheckout > git checkout -f <latest_SHA1> > git rev-list <latest_SHA1> </code> I see that the plugin fetches and checks out the proper commit hash, but when the tests run it seems as though the repo wasn't updated at all. If I go into the repository in Jenkins, I see there that the latest changes were never pulled. Shouldn't it pull before it tries to build? I have git 1.8.5 installed on my Jenkins machine, which is a recommended version. https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin After checking other similar sounding questions on SO, their answers weren't helpful for my problem.
Relates me to scenarios where the workspace wasn't getting cleaned up. Used: Source Code Management --> Additional Behaviours --> Clean after checkout. Other option is to use the Workspace Cleanup Plugin.
What is the python equivalent to a Java .jar file? <sep> Java has the concept of packaging all of the code into a file called a Jar file. Does Python have an equivalent idea? If so, what is it? How do I package the files?
Python doesn't have an exact equivalent to a `.jar` file. There are many differences, and without knowing exactly what you want to do, it's hard to explain how to do it. But the Python Packaging User Guide does a pretty good job of explaining just about everything relevant. Here are some of the major differences. A `.jar` file is a compiled collection of classes that can be dropped into your application or installed anywhere on your `CLASSPATH`. In Python: * A `.py` (or `.pyc`) module can be dropped into your application or installed anywhere on your `sys.path` and it can be imported and used. * A directory full of modules can be treated the same way; it becomes a package (or, if it doesn't contain an `__init__.py`, it merges with other directories of the same name elsewhere on `sys.path` into a single package). * A `.zip` archive containing any number of modules and packages can be stored anywhere, and its path added to your `sys.path` (e.g., at runtime or via `PYTHONPATH`), and all of its contents become importable. Most commonly, you want things to be installed into a system, user, or virtualenv `site-packages` directory. The recommended way to do that is to create a `pip`-compatible package distribution; people then install it (and possibly automatically download it from PyPI or a private repo) via `pip`. `pip` does a lot more than that, however. It also allows you to manage dependencies between packages. So ideally, instead of listing a bunch of prerequisites that someone has to go download and install manually, you just make them dependencies, and someone just has to `pip install your-library`. And it keeps track of the state of your site-packages, so you can uninstall or upgrade a package without having to track down the specific files. Meanwhile, in Java, most `.jar` files are cross-platform; build once, run anywhere. A few packages have JNI native code and can't be used this way, but it's not the norm. In Python, many packages have C extensions that have to be compiled for each platform, and even pure-Python packages often need to do some install-time configuration. And meanwhile, "compiling" pure Python doesn't do anything that can't be done just as well at runtime. So in Python, you generally distribute source packages, not compiled packages. However, `.wheel` is a binary package format. You can `pip wheel` to build binary packages for different targets from the source package; then, if someone tries to `pip install` your package, if there's a wheel for his system, that will be downloaded and installed.
I am getting the error 'redefined-outer-name' <sep> When running my lint, I am getting the error below: <code>Redefining name 'tmp_file' from outer scope (line 38) (redefined-outer-name) </code> Here is my snippet of code in that line: <code>tmp_file = open('../build/' + me_filename + '.js','w') </code>
```python def main(): x, y = 2, 4 print(pow(x)) print(add(x, y)) def pow(x): return x ** 2 def add(x, y): return x + y if __name__ == '__main__': main() ``` Explanation: This works because every new function instance creates a new local scope.
Get index in C++11 foreach loop <sep> Is there a convenient way to get the index of the current container entry in a C++11 foreach loop, like <code>enumerate</code> in python: <code>for idx, obj in enumerate(container): pass </code> I could imagine an iterator that can also return the index or similar. Of course I could have a counter, but often iterators don't give guarantees of the order they iterate over a container.
```cpp // Distributed under the terms of the GPLv2 or newer #include <iostream> #include <vector> #include <tuple> // Wrapper class template template <typename T> class enumerate_impl { public: // The return value of the operator* of the iterator, this // is what you will get inside of the for loop struct item { size_t index; typename T::value_type& item; }; typedef item value_type; // Custom iterator with minimal interface struct iterator { iterator(typename T::iterator _it, size_t counter = 0) : it(_it), counter(counter) {} iterator operator++() { return iterator(++it, ++counter); } bool operator!=(iterator other) { return it != other.it; } typename T::iterator::value_type item() { return *it; } value_type operator*() { return value_type{counter, *it}; } size_t index() { return counter; } private: typename T::iterator it; size_t counter; }; enumerate_impl(T& t) : container(t) {} iterator begin() { return iterator(container.begin()); } iterator end() { return iterator(container.end()); } private: T& container; }; // A templated free function allows you to create the wrapper class // conveniently template <typename T> enumerate_impl<T> enumerate(T& t) { return enumerate_impl<T>(t); } int main() { std::vector<int> data = {523, 1, 3}; for (auto x : enumerate(data)) { std::cout << x.index << ": " << x.item << std::endl; } } ```
Switch statement in Swift <sep> I'm learning syntax of Swift and wonder, why the following code isn't working as I expect it to: <code>for i in 1...100{ switch (i){ case 1: Int(i%3) == 0 println("Fizz") case 2: Int(i%5) == 0 println("Buzz") default: println("\(i)") } } </code> I want to print Fizz every time number is divisible by 3 (3, 6, 9, 12, etc) and print Buzz every time it's divisible by 5. What piece of the puzzle is missing? Note: I did solve it using the following: <code>for ( var i = 0; i < 101; i++){ if (Int(i%3) == 0){ println("Fizz") } else if (Int(i%5) == 0){ println("Buzz") } else { println("\(i)") } } </code> I want to know how to solve this using Switch. Thank you.
This is a more general answer for people who come here just wanting to know how to use the `switch` statement in Swift. General usage: ```swift switch someValue { case valueOne: // executable code case valueTwo: // executable code default: // executable code } ``` Example: ```swift let someValue = "horse" switch someValue { case "horse": print("eats grass") case "wolf": print("eats meat") default: print("no match") } ``` Notes: * No `break` statement is necessary. It is the default behavior. * Swift `switch` cases do not "fall through". If you want them to fall through to the code in the next case, you must explicitly use the `fallthrough` keyword. * Every case must include executable code. If you want to ignore a case, you can add a single `break` statement. * The cases must be exhaustive. That is, they must cover every possible value. If it is not feasible to include enough `case` statements, a `default` statement can be included last to catch any other values. The Swift `switch` statement is very flexible. The following sections include some other ways of using it. **Matching Multiple Values** You can match multiple values in a single case if you separate the values with commas. This is called a compound case. ```swift let someValue = "e" switch someValue { case "a", "b", "c": // executable code case "d", "e": // executable code default: // executable code } ``` You can also match whole intervals. ```swift let someValue = 4 switch someValue { case 0..<10: // executable code case 10...100: // executable code default: // executable code } ``` You can even use tuples. This example is adapted from the documentation. ```swift let aPoint = (1, 1) switch aPoint { case (0, 0): // only catches an exact match for first and second case (_, 0): // any first, exact second case (-2...2, -2...2): // range for first and second default: // catches anything else } ``` **Value Bindings** Sometimes you might want to create a temporary constant or variable from the `switch` value. You can do this right after the `case` statement. Anywhere that a value binding is used, it will match any value. This is similar to using `_` in the tuple example above. The following two examples are modified from the documentation. ```swift let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): // can use x here case (0, let y): // can use y here case let (x, y): // can use x or y here, matches anything so no "default" case is necessary } ``` You can further refine the matching by using the `where` keyword. ```swift let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: // executable code case let (x, y) where x == -y: // executable code case let (x, y): // executable code } ``` **Further Study** This answer was meant to be a quick reference. Please read the full documentation for more. It isn't difficult to understand.
Laravel Eloquent: How to order results of related models? <sep> I have a model called School and it has many Students . Here is the code in my model: <code>public function students() { return $this->hasMany('Student'); } </code> I am getting all the students with this code in my controller: <code>$school = School::find($schoolId); </code> and in the view: <code>@foreach ($school->students as $student) </code> Now I want to order the Students by some field in the <code>students</code> table. How can I do that?
You can add `orderBy` to your relation, so the only thing you need to change is `public function students() { return $this->hasMany('Student'); }` to `public function students() { return $this->hasMany('Student')->orderBy('id', 'desc'); }`.
why `git diff` reports no file change after `git add` <sep> Why is that <code>git diff</code> thinks there are no changes ..even if <code>git status</code> reports them as modified? <code>$ git status On branch master Your branch is ahead of 'origin/master' by 2 commits. (use "git push" to publish your local commits) Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: file-added modified: file-with-changes << it knows there are changes </code> but in order to see the difference, I need to explicitly add the last reversion hash.. <code>$ git diff (nothing) $ git diff rev-hash diff --git a/file-with-changes b/file-with-changes index d251979..a5fff1c 100644 --- a/file-with-changes +++ b/file-with-changes . .. </code>
``` `git diff --staged` shows changes between HEAD and index/staging. `git diff --cached` also does the same thing. `staged` and `cached` can be used interchangeably. `git diff HEAD` shows changes between HEAD and working files. `git diff $commit $commit` shows changes between two commits. `git diff origin` shows diff between HEAD & remote/origin ```
ViewPager animation fade in/out instead of slide <sep> I got the FragmentBasics example from here. Is there a way make the ViewPager animation simply fade in and out when I swipe instead of sliding left and right? I've been trying some stuff with PageTransformer, but no success, I can still see it sliding. So I guess I need to somehow force its position to stay put, while sliding my finger only affects the alpha. <code>public class SecondActivity extends Activity { SectionsPagerAdapter mSectionsPagerAdapter; ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setPageTransformer(false, new FadePageTransformer()); mViewPager.setAdapter(mSectionsPagerAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.second, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_second, container, false); TextView textView = (TextView) rootView.findViewById(R.id.section_label); textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))); return rootView; } } public class FadePageTransformer implements ViewPager.PageTransformer { public void transformPage(View view, float position) { if (position < -1 || position > 1) { view.setAlpha(0); } else if (position <= 0 || position <= 1) { // Calculate alpha. Position is decimal in [-1,0] or [0,1] float alpha = (position <= 0) ? position + 1 : 1 - position; view.setAlpha(alpha); } else if (position == 0) { view.setAlpha(1); } } } </code>
```java public void transformPage(View view, float position) { view.setTranslationX(view.getWidth() * -position); if (position <= -1.0F || position >= 1.0F) { view.setAlpha(0.0F); } else if (position == 0.0F) { view.setAlpha(1.0F); } else { // position is between -1.0F & 0.0F OR 0.0F & 1.0F view.setAlpha(1.0F - Math.abs(position)); } } ```
Laravel Homestead: 403 forbidden on nginx <sep> I just installed Laravel Homestead according to their instructions. When I open http://homestead.app:8000 I get the nginx 403 forbidden HTTP Response. I have tried setting app/storage permissions to 755, but that didn't work, so I reloaded Vagrant. With no further result. I also tried changing the nginx configuration, but with no success.
I had the same problem, and for me the cause was that in the Homestead.yaml file, I had incorrectly put this: ``` sites: - map: homestead.app to: /home/vagrant/Code ``` Instead of the correct syntax: ``` sites: - map: homestead.app to: /home/vagrant/Code/path/to/public ```
iOS compile error: no visible @interface for 'CDVCommandDelegateImpl' declares the selector 'execute:' <sep> After upgrading to latest Cordova version (3.6.3) i get this error when running the <code>cordova build ios</code> command. The error: <code>/Volumes/local.uhmuhm.net/projectxxx/htdocs/phonegap/src/Projectxxx/platforms/ios/Projectxxx/Classes/MainViewController.m:154:19: error: no visible @interface for 'CDVCommandDelegateImpl' declares the selector 'execute:' return [super execute:command]; </code> Other info: Installed platforms: android 3.6.3, ios 3.6.3 I'm on last xcode version (6.0.1) Everything started after upgrading Cordova to 3.6.3 (i was running 3.4.1 before that) Any idea on how to solve this?
Building on what Nazar said, the only significant difference when creating a new app and comparing an existing `platforms/ios/Classes` folder was removing the `execute` method from `MainViewController.m`. This cleared up the build error for me.
Read Command : Display the prompt in color (or enable interpretation of backslash escapes) <sep> I often use something like <code>read -e -p "> All good ? (y/n)" -n 1 confirm;</code> to ask a confirm to the user. I'm looking for a way to colorize the output, as the command <code>echo -e</code> does : <code>echo -e "\033[31m"; echo "Foobar"; // will be displayed in red echo -e "\033[00m"; </code> I'm using xterm. In <code>man echo</code>, it says : <blockquote> -e enable interpretation of backslash escapes </blockquote> Is there a way to do the same thing with the <code>read</code> command ? (nothing in the man page :( <code>-r</code> option doesn't work)
`read` won't process any special escapes in the argument to `-p`, so you need to specify them literally. `bash`'s ANSI-quoted strings are useful for this: `read -p "$'\e[31mFoobar\e[0m: ' foo` You should also be able to type a literal escape character with Control-v Escape, which will show up as `^[` in the terminal: `read -p '^[[31mFoobar^[[0m: ' foo`
Imported module in Android Studio can't find imported class <sep> I recently downloaded the ViewPagerIndicator library and imported it into android studio. After adding it to my project I get a rendering error "The following classes could not be found:" and points to com.viewpagerindicator.IconPageIndicator. The steps I took were <code>Files->Import Module->'library name'</code>, <code>Project Structure -> Dependencies -> + the imported module</code>. Then to my layout xml file I added the <code><com.viewpagerindicator.IconPageIndicator /></code>, after that I got the missing class problem. It compiles just fine and I went through all of the build.gradle and settings.gradle files and compared them to what they should be online. <code>MyApp->build.gradle</code> has <code>compile project(':library')</code> under <code>dependencies</code> <code>settings.gradle</code> has <code>include ':library'</code> with no build errors.
First of all, you must import your library project by following this path: `File --> New --> Import Module`. After you have imported the library project successfully, check your build.gradle file inside your project's folder to see if the following line is present in the "dependencies" section: `implementation project(':NameOfTheLibProject')`. Then, your project must build successfully.
Does iPhone 6 / 6 Plus simulator supports changing of Display Zoom mode? <sep> How to change Display Zoom feature in iPhone 6 and 6 Plus simulators? Original iPhone 6 and 6 Plus have this feature in Settings -> Display & Brightness -> Display Zoom (View) with values Standard and Zoomed.
As of Xcode 12 (and perhaps earlier), `Settings -> Developer -> View -> Zoomed` (tap Set) will adjust the simulator to show with Display Zoom. This is helpful as the iPhone 11 Pro, iPhone 12 mini, iPhone 12, and iPhone 12 Pro all run at a previously unused resolution of 320 x 693. For more information, check out this excellent article by Geoff Hackworth.
Update if exists or add new element to array of objects - elegant way in javascript + lodash <sep> So I have an array of objects like that: <code>var arr = [ {uid: 1, name: "bla", description: "cucu"}, {uid: 2, name: "smth else", description: "cucarecu"}, ] </code> <code>uid</code> is unique id of the object in this array. I'm searching for the elegant way to modify the object if we have the object with the given <code>uid,</code> or add a new element, if the presented <code>uid</code> doesn't exist in the array. I imagine the function to be behave like that in js console: <code>> addOrReplace(arr, {uid: 1, name: 'changed name', description: "changed description"}) > arr [ {uid: 1, name: "bla", description: "cucu"}, {uid: 2, name: "smth else", description: "cucarecu"}, ] > addOrReplace(arr, {uid: 3, name: 'new element name name', description: "cocoroco"}) > arr [ {uid: 1, name: "bla", description: "cucu"}, {uid: 2, name: "smth else", description: "cucarecu"}, {uid: 3, name: 'new element name name', description: "cocoroco"} ] </code> My current way doesn't seem to be very elegant and functional: <code>function addOrReplace (arr, object) { var index = _.findIndex(arr, {'uid' : object.uid}); if (-1 === index) { arr.push(object); } else { arr[index] = object; } } </code> I'm using lodash, so I was thinking of something like modified <code>_.union</code> with custom equality check.
In your first approach, no need for Lodash thanks to `findIndex()`: ```javascript function upsert(array, element) { const i = array.findIndex(_element => _element.id === element.id); if (i > -1) array[i] = element; else array.push(element); } ``` Example: ```javascript const array = [ { id: 0, name: 'Apple', description: 'fruit' }, { id: 1, name: 'Banana', description: 'fruit' }, { id: 2, name: 'Tomato', description: 'vegetable' } ]; upsert(array, { id: 2, name: 'Tomato', description: 'fruit' }); console.log(array); /* => [ { id: 0, name: 'Apple', description: 'fruit' }, { id: 1, name: 'Banana', description: 'fruit' }, { id: 2, name: 'Tomato', description: 'fruit' } ] */ upsert(array, { id: 3, name: 'Cucumber', description: 'vegetable' }); console.log(array); /* => [ { id: 0, name: 'Apple', description: 'fruit' }, { id: 1, name: 'Banana', description: 'fruit' }, { id: 2, name: 'Tomato', description: 'fruit' }, { id: 3, name: 'Cucumber', description: 'vegetable' } ] */ ``` (1) other possible names: `addOrReplace()`, `addOrUpdate()`, `appendOrUpdate()`, `insertOrUpdate()`, ... (2) can also be done with `array.splice(i, 1, element)` Note that this approach is "mutable" (vs "immutable"): it means instead of returning a new array (without touching the original array), it modifies directly the original array.
Recursively copy a set of files from one directory to another in PowerShell <sep> I'm trying to copy all <code>*.csproj.user</code> files recursively from <code>C:\Code\Trunk</code> to <code>C:\Code\F2</code>. For example: <code>C:\Code\Trunk\SomeProject\Blah\Blah.csproj.user</code> Would get copied to: <code>C:\Code\F2\SomeProject\Blah\Blah.csproj.user</code> My current attempt is: <blockquote> Copy-Item C:\Code\Trunk -Filter *.csproj.user -Destination C:\Code\F2 -Recurse -WhatIf </blockquote> However I get: <blockquote> What if: Performing operation "Copy Directory" on Target "Item: C:\Code\Trunk Destination: C:\Code\F2\Trunk". </blockquote> First, it wants to put them all in a new folder called <code>F2\Trunk</code> which is wrong. Second, it doesn't list any of the files. There should be about 10 files to be copied over. What's the correct syntax for the command? Thanks! Update: Okay, it seems to have something to do with the fact that <code>C:\Code\F2</code> already exists. If I try copying the files over to a destination that does not exist, it works. I want to overwrite any existing <code>.csproj.user</code> files in the destination.
You guys are making this hideously complicated. It's really simple: ```powershell Copy-Item C:\Code\Trunk -Filter *.csproj.user -Destination C:\Code\F2 -Recurse ``` This will copy the directory, creating a "Trunk" directory in F2. If you want to avoid creating the top-level Trunk folder, stop telling PowerShell to copy it: ```powershell Get-ChildItem C:\Code\Trunk | Copy-Item -Destination C:\Code\F2 -Recurse -Filter *.csproj.user ```
Error inflating class android.support.v7.widget.RecyclerView <sep> I'm trying to use RecyclerView in my existing project, builds without errors but getting no class found error for the RecyclerView while inflating. Cannot see what I'm doing wrong. Thanks for helping! //activity_main.xml <code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> //MainActivity.onCreate @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); ItemData itemsData[] = { new ItemData("Help",R.drawable.visa), new ItemData("Delete",R.drawable.sample), new ItemData("Cloud",R.drawable.sample), new ItemData("Favorite",R.drawable.sample), new ItemData("Like",R.drawable.sample), new ItemData("Rating",R.drawable.sample)}; // 2. set layoutManger recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 3. create an adapter MyAdapter mAdapter = new MyAdapter(itemsData); // 4. set adapter recyclerView.setAdapter(mAdapter); // 5. set item animator to DefaultAnimator //recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setHasFixedSize(true); } </code> //build.gradle <code>apply plugin: 'com.android.application' android { compileSdkVersion 20 buildToolsVersion '19.1.0' defaultConfig { applicationId "com.domain.project" minSdkVersion 19 targetSdkVersion 20 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:support-v4:+' compile 'com.android.support:support-v13:+' compile project(':facebook-3.15') compile project(':parse-1.5.1') compile project(':viewpagerindicator-2.4.1') compile 'com.github.manuelpeinado.fadingactionbar:fadingactionbar:3.1.2' compile 'com.android.support:cardview-v7:+' compile 'com.android.support:recyclerview-v7:+' compile 'com.google.android.gms:play-services:+' } configurations { // to avoid double inclusion of support libraries all*.exclude group: 'com.android.support', module: 'support-v4' } </code> //LOGCAT <code>08-24 17:49:27.626 27544-27544/com.domain.project E/AndroidRuntime FATAL EXCEPTION: main Process: com.domain.project, PID: 27544 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.domain.project/com.domain.project.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class android.support.v7.widget.RecyclerView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5139) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) at dalvik.system.NativeStart.main(Native Method) Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class android.support.v7.widget.RecyclerView at android.view.LayoutInflater.createView(LayoutInflater.java:620) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696) at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at android.view.LayoutInflater.inflate(LayoutInflater.java:397) at android.view.LayoutInflater.inflate(LayoutInflater.java:353) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:343) at android.app.Activity.setContentView(Activity.java:1929) at com.domain.project.MainActivity.onCreate(MainActivity.java:35) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5139) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.constructNative(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at android.view.LayoutInflater.createView(LayoutInflater.java:594) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696) at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at android.view.LayoutInflater.inflate(LayoutInflater.java:397) at android.view.LayoutInflater.inflate(LayoutInflater.java:353) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:343) at android.app.Activity.setContentView(Activity.java:1929) at com.domain.project.MainActivity.onCreate(MainActivity.java:35) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5139) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.Pools$SimplePool at android.support.v7.widget.RecyclerView.<init>(RecyclerView.java:121) at android.support.v7.widget.RecyclerView.<init>(RecyclerView.java:213) at java.lang.reflect.Constructor.constructNative(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at android.view.LayoutInflater.createView(LayoutInflater.java:594) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696) at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at android.view.LayoutInflater.inflate(LayoutInflater.java:397) at android.view.LayoutInflater.inflate(LayoutInflater.java:353) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:343) at android.app.Activity.setContentView(Activity.java:1929) at com.domain.project.MainActivity.onCreate(MainActivity.java:35) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5139) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) at dalvik.system.NativeStart.main(Native Method) </code>
Or... in my case, I was including the androidx version of RecyclerView in my dependencies (build.gradle) but using the other in my XML... Doh. Replaced `android.support.v7.widget.RecyclerView` with `androidx.recyclerview.widget.RecyclerView` and it worked! :)
Dynamically hide certain columns when returning an Eloquent object as JSON? <sep> How do dynamically hide certain columns when returning an Eloquent object as JSON? E.g. to hide the 'password' column: <code>$users = User::all(); return Response::json($users); </code> I'm aware I can set protected properties in the model ($hidden or $visible), but how do I set these dynamically? I might want to hide or show different columns in different contexts.
From Laravel 5.3 Documentation: Temporarily Modifying Attribute Visibility If you would like to make some typically hidden attributes visible on a given model instance, you may use the `makeVisible` method. The `makeVisible` method returns the model instance for convenient method chaining: `return $user->makeVisible('attribute')->toArray();` Likewise, if you would like to make some typically visible attributes hidden on a given model instance, you may use the `makeHidden` method. `return $user->makeHidden('attribute')->toArray();`
Get "does not implement methodSignatureForSelector" when try to store Array in NSUserDefaults,Swift? <sep> I try to store Array of objects in <code>NSUserDefaults</code>. I have following snippets of code: <code> var accounts = MyAccounts() var array:Array<MyAccounts.MyCalendar> = accounts.populateFromCalendars() NSUserDefaults.standardUserDefaults(). setObject(array, forKey: "test_storeAccounts_array") // <- get error here NSUserDefaults.standardUserDefaults().synchronize() </code> But I get Exception: <code>does not implement methodSignatureForSelector: -- trouble ahead </code> my class structure: <code>class MyAccounts { /* ... */ class MyCalendar { var title:String? var identifier:String? var email:String? var calType:String? var isActive:Bool? var isMainAcount:Bool? init(){} } } </code> Any ideas?
I was getting this exception in Swift 3.0. In my case, my model class was not inheriting from the `NSObject` base class. I just had my class inherit from the `NSObject` base class and implement the `NSCoding` protocol (if your container array has custom objects). ```swift class Stock: NSObject, NSCoding { var stockName: String? override init() { } // MARK: NSCoding protocol methods func encode(with aCoder: NSCoder) { aCoder.encode(self.stockName, forKey: "name") } required init(coder decoder: NSCoder) { if let name = decoder.decodeObject(forKey: "name") as? String { self.stockName = name } } func getStockDataFromDict(stockDict: [String: AnyObject]) -> Stock { if let stockName = stockDict["name"] { self.stockName = stockName as? String } return self } } ```
Grunt wiredep:app no such file or directory bower.json <sep> I'm trying to deploy my Yeoman's Angular app to my production server. When I try to run the grunt build command I get this error: <blockquote> Running "wiredep:app" (wiredep) task Warning: ENOENT, no such file or directory '/usr/share/nginx/html/data/gaia-app/app/bower.json' Use --force to continue. </blockquote> If I use <code>grunt --force</code> my app is broken... I'm on Ubuntu 14.04 Any ideas?
There are two solutions to this issue, depending on which version of Wiredep you want to use. If you want to use '^1.9.0', remove the `cwd` property from your Gruntfile.js. This is a common issue for Angular Generator users, which currently specifies a `cwd` property in the config for the Wiredep task. If you don't mind using '1.8.0', make sure to pin that version in your `package.json`. If you are including Wiredep via grunt-wiredep, you will have to add Wiredep manually and pin it. In the case that you stick with '1.8.0', leave the `cwd` property in the config for the task.
Git merge strategy 'theirs' is not resolving modify/delete conflict <sep> When performing a <code>git merge</code> with the following options: <code>git merge -X theirs master</code> There are occasionally conflicted files like so: <blockquote> CONFLICT (modify/delete): File_A.java deleted in master and modified in HEAD. Version HEAD of File_A.java left in tree. </blockquote> However, I would like for the <code>-X theirs</code> option to be recognized in these cases, and use the <code>theirs</code> version of the change, which is for the file to be deleted. Is there a reason this type of conflict is not automatically resolved, especially since I'm providing a specific merge strategy that suggests it should remove the file? Further, how (if possible) can I update my <code>merge</code> command to use the <code>theirs</code> version of this type of conflict?
A bit late, but this might be useful: you can resolve this type of conflict with: ``` git merge -X theirs master git diff --name-only --diff-filter=U | xargs git rm ``` Basically, it means "delete all unmerged files" during conflict resolution.