prompt
stringlengths
49
4.73k
response
stringlengths
238
35k
Scope of variable inside switch case ``` package main import "fmt" func main() { x := 10 switch x { case 0: y := 'a' fmt.Printf("%c\n", y) case 1: // y = 'b' // this can't compile, y := 'b' fmt.Printf("%c\n", y) default: y := '-' fmt.Printf(...
[Spec: Blocks:](https://go.dev/ref/spec#Blocks) > > A *block* is a possibly empty sequence of declarations and statements within matching brace brackets. > > > > ``` > Block = "{" StatementList "}" . > StatementList = { Statement ";" } . > > ``` > > In addition to explicit blocks in the source code, there are ...
Laravel 4.2 Migrations - Alter decimal precision and scale without dropping column I wish to increase decimal precision and scale for a decimal column. I am aware that I can drop the column, and re-create it, but doing so will mean losing the data in the column. Is there a way using Laravel Schema::table that I can...
Just create another `migration` and in the `up` method add following code: ``` public function up() { // Change db_name and table_name DB::select(DB::raw('ALTER TABLE `db_name`.`table_name` CHANGE COLUMN `buy_price` `buy_price` decimal(10,2) NOT NULL;')); } ``` Also in the `down` method just set the old v...
Transmute struct into array in Rust Let's say we have a structure, all fields of which are of the same sized types: ``` struct Homogeneous { a: u64, b: u64, c: u64, d: u64 } ``` And we have a "safe" way to construct it from array of bytes: ``` impl From<[u8; 32]> for Homogeneous { fn from(sl...
From the [rustlang reference](https://github.com/rust-lang/reference/blob/8e7d614303b0dec7492e048e63855fcd3b944ec8/src/types/struct.md): > > The memory layout of a struct is undefined by default to allow for compiler optimizations like field reordering, but **it can be fixed > with the [repr attribute](https://gith...
Difference between layerX and offsetX in JavaScript There are different co-ordinate system for JavaScript, such as e.clientX, e.screenX. I understand those two well, but there are some like e.layerX and e.offsetX. These two are not very clear to me. Can someone explain those two co-ordinates for me?
`offsetX`/`offsetY` are a neat extension by Microsoft to mouse event objects, and mean the position of the mouse pointer relatively to the target element. Sadly, they're not implemented by Firefox, and there's discordance among the other browsers about what should be the origin point: IE thinks it's the *content* box, ...
ffmpeg join two mp4 files with ffmpeg on command line I can successfully join multiple files using the following command: ``` ffmpeg -f concat -i input.txt -codec copy output.mp4 ``` The only problem with this command is that you need to read the filepaths from the text file called **input.txt** with the following...
## 2019 Update: As mentioned in the comments, Stack Overflow has a great description of the available options for concatenation, as well as a discussion of which method to use depending on the types of files you're using: [How to concatenate two MP4 files using FFmpeg?](https://stackoverflow.com/questions/7333232/h...
How does Groovy resolve method calls with whitespaces I am wondering why Groovy compiler isn't capable to correctly resolve the following calls ``` a = { p -> p } b = { p -> p } a b 1 ``` I would expect that to be interpreted correctly as ``` a(b(1)) ``` Or is there any syntax that could be interpreted diffe...
It tries to evaluate that as: ``` a( b ).1 ``` The way I imagine it, is as if it were a list of symbols, and `collate( 2 )` was called on them... ``` def list = [ 'a', 'b', 'c', 'd', 'e' ] def pairs = list.collate( 2 ) ``` All entries in this list with 2 values are a method/parameter pair, and any single elem...
Match the first 3 characters of a string to specific column I have a dataframe,df, where I would like to take the first 3 characters of a string from a specific column and place these characters under another column **Data** ``` id value stat aaa 10 aaa123 aaa 20 aaa 500 aaa123 bbb 20 bbb 10 b...
One option would be [`Series.fillna`](https://pandas.pydata.org/docs/reference/api/pandas.Series.fillna.html) + [`Series.str`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.html) to slice the first 3 values: ``` df['id'] = df['id'].fillna(df['stat'].str[:3]) ``` ``` id value ...
Simplest Android Activity Lifecycle I noticed that the Android Developers Activity section has been updated since I started my app, but I am still unclear what the simplest Activity Lifecycle is. As far as I can make out: onCreate, onResume and onPause are the essential ones. The activity may be deleted any time ...
Are you looking for this? [![Activity Lifecycle](https://i.stack.imgur.com/1byIg.png)](http://d.android.com/reference/android/app/Activity.html) To further answer your question, yes, as you can plainly see from the above diagram the "simplest" (i.e. smallest number of method calls) lifecycle is indeed `onCreate(); ...
jasmine angular 4 unit test router.url I am unit testing a function in angular 4 project using jasmine which a switch statement like mentioned below: ``` switch(this.router.url) { case 'firstpath': { // some code } break; case 'secondpath': { // some mor...
First you need to mock router in your testing module: ``` TestBed.configureTestingModule({ ... providers: [ { provide: Router, useValue: { url: '/path' } // you could use also jasmine.createSpyObj() for methods } ] }); ``` You can also change the url in the test and ru...
Dictionary in Swift I really confuse with the way we create dictionary in swift. So could you please tell me what is the different between ``` var myDic3 = [String : AnyObject]() ``` and ``` var myDic2 = Dictionary <Int,AnyObject>() ``` and ``` var myDic4 = [ : ] ``` When i declare like myDic4 I cannot...
In Swift, you can declare and initialize an empty Dictionary with type `String` for keys and type `Any` for values in 4 different ways: 1. `var myDic1 = [String : Any]()` 2. `var myDic2 = Dictionary<String, Any>()` 3. `var myDic3: [String : Any] = [:]` 4. `var myDic4: Dictionary<String, Any> = [:]` These will all g...
GAE: unit testing taskqueue with testbed I'm using testbed to unit test my google app engine app, and my app uses a taskqueue. When I submit a task to a taskqueue during a unit test, it appears that the task is in the queue, but the task does not execute. How do I get the task to execute during a unit test?
The dev app server is single-threaded, so it can't run tasks in the background while the foreground thread is running the tests. I modified TaskQueueTestCase in taskqueue.py in gaetestbed to add the following function: ``` def execute_tasks(self, application): """ Executes all currently queued tasks, and a...
Passing a set of NumPy arrays into C function for input and output Let's assume we have a C function that takes a set of one or more input arrays, processes them, and writes its output into a set of output arrays. The signature looks as follows (with `count` representing the number of array elements to be processed): ...
To do this specifically with Numpy arrays, you could use: ``` import numpy as np import ctypes count = 5 size = 1000 #create some arrays arrays = [np.arange(size,dtype="float32") for ii in range(count)] #get ctypes handles ctypes_arrays = [np.ctypeslib.as_ctypes(array) for array in arrays] #Pack into pointer ar...
How can we use SDA or SCL lines for I2C Addresses? TMP102 chip( <http://www.ti.com/lit/ds/symlink/tmp102.pdf> ) can have multiple I2c slave addresses. It has an address pin called ADD0(**Section 5**) which can be used to select multiple addresses(**Section 7.3.4**). The logic level at that pin can be used to select a p...
> > The logic level at that pin can be used to select a particular TMP102 slave device > > > That is not the purpose of ADD0 - it is a configuration pin, not a select pin. It is not used to *select* the device; I2C addresses are part of the data stream on SDA, there is no "*select*" pin as there is on SPI for ex...
Popover segue to static cell UITableView causes compile error I currently have an application with two view controllers. The first is a view controller with an embedded table view that has dynamic cells. The second is a table view controller with static cells. If I add a segue from selecting one of the dynamic table's ...
I figured out how to do this. You can't hook it up from the storyboard but can do it programmatically like this: ``` - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard_iPad" ...
What's the difference between application and request contexts? Flask documentation says that there are 2 local context: application context, and request context. Both are created on request and torn down when it finishes. So, what's the difference? What are the use cases for each? Are there any conditions when only ...
> > Both are created on request and torn down when it finishes. > > > It is true in the request lifecycle. Flask create the app context, the request context, do some magic, destroy request context, destroy app context. The application context can exist without a request and that is the reason you have both. Fo...
Persisting and retrieving a Map of Maps with Morphia and Mongodb I would like to be able to persist and retrieve, amongst other things, a map of maps in a MongoDB collection. I am using Java to access the MongoDB via Morphia. The example I am using below is a collection that contains documents detailing the owners of...
The issue stems from the fact that a Map (being an interface) does not have a default constructor, and while Morphia was correctly assigning the constructor for the concrete HashMap on the outer Map it was failing to resolve a constructor for the inner Map. This was resulting in the NullPointerException. After a lot ...
What does mbstring.strict\_detection do? The mbstring PHP module has a `strict_detection` setting, [documented here](http://www.php.net/manual/en/mbstring.configuration.php#ini.mbstring.strict-detection). Unfortunately, the manual is completely useless; it only says that this option *"enables the strict encoding detect...
Without the *strict* parameter being set, the encoding detection is faster but will not be as accurate. For example, if you had a UTF-8 string with partial UTF-8 sequence like this: ``` $s = "H\xC3\xA9ll\xC3"; $encoding = mb_detect_encoding($s, mb_detect_order(), false); ``` The result of the `mb_detect_encoding` ...
Updating the actual values upon filtering using PrimeNG I am using PrimeNG with Global filter added to my table: ``` <input #gb type="text" pInputText size="50" placeholder="Filter"> ``` Datatable: ``` <p-dataTable *ngIf="users != null && users.length > 0" [value]="users" loadingIcon="fa-spinner" [globalFilter...
`DataTable` component has a variable called `filteredValue` and filtered values are stored in that variable. There are two ways to get filtered values: > > First way > > > You can use `ViewChild` to get a reference to `DataTable` object and get the users you filtered: **Template** ``` <p-dataTable #dataTa...
How to sum N columns in python? I've a pandas df and I'd like to sum N of the columns. The df might look like this: ``` A B C D ... X 1 4 2 6 3 2 3 1 2 2 3 1 1 2 4 4 2 3 5 ... 1 ``` I'd like to get a df like this: ``` A Z 1 15 2 8 3 8 4 11 ``` The A variable is not an index, but a variable.
Use [`join`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html) for new `Series` created by `sum` all columns without `A`: ``` df = df[['A']].join(df.drop('A', 1).sum(axis=1).rename('Z')) ``` Or extract column `A` first by [`pop`](http://pandas.pydata.org/pandas-docs/stable/generated...
Openid is really a nightmare? Is there an open source lib that could "abstract" everything into an internal id? I do not create big websites, so I'm mainly a user of openid and it's various implementations. I use openid here in SO, and I like it because I'm using my gmail account for everything (I plan to exit gmail in...
Libraries do exist (such as [DotNetOpenAuth](http://www.dotnetopenauth.net/)), but these usually only abstract the protocol and spec for you - your application still has to be aware of the individual providers (and their quirks). One of the biggest problems with OpenId/OpenAuth in my opinion is that many providers do...
Dynamic list constraint on Alfresco I'm trying to follow the examples provided in [this post](http://blogs.alfresco.com/wp/jbarmash/2008/08/08/dynamic-data-driven-drop-downs-for-list-properties/), to create a dynamic list constraint in Alfresco 3.3. So, I've created my own class extending `ListOfValuesConstraint`: ...
This dynamic-list-of-values-constraint is a bad idea and I tell you why: The Alfresco repository should be in a valid state all the time. Your (dynamic) list of constraints will change (that's why you want it to be dynamic). Adding items would not be a problem, but editing and removing items are. If you would remove ...
Get the character and its count which has highest occurrence I have this C# method which get the character and its count which has highest occurrence ``` public KeyValuePair<char, int> CountCharMax_Dictionary_LINQ(string s) { char[] chars = s.ToCharArray(); var result = chars.GroupBy(x => x)...
As per [this answer](https://stackoverflow.com/a/19522559/3312), it would be wiser to use a tuple in this case. I use lowercase "t"uple as I highly recommend the built-in language support for tuples `(char, int)` over the explicit `Tuple<T1, T2>` declaration, etc. Few more points: - What should happen in a tie? Which...
How can I use ftd2xx.lib with a C++ program? I am having trouble making a program to interact with an FTDI chip. I don't know how much information I can give in regards to the model number of the chip. I am trying to use the API FTDI provides to communicate with the chip I have. I am using Qt Creator for the program ...
The ftd2xx header has a lot of Windows types in it so you need to include windows.h before including the ftdi header. The .lib file is a DLL link library which provides the linker information required to make use of the DLL at runtime. The following compiles and runs using g++: ``` #include <windows.h> #include <s...
Is the following Assembly Atomic, If not, Why? ``` addl, $9, _x(%rip) ``` \_x is a global variable. Essentially I'm not certain as to how adding to a global variable in this case is implemented and whether or not there are inherent race conditions with this line in a multi processor system.
As duskwuff pointed out, you need a `lock` prefix. The reason why is that: ``` addl $9,_x(%rip) ``` is actually three "micro operations" from the standpoint of the memory system [herein `%eax` just for illustration--never really used]: ``` mov _x(%rip),%eax addl $9,%eax mov %eax,_x(%rip) ``` Here...
Calling C++ from clojure Is it possible to call C++ libraries like CGAL or VTK from Clojure? Can this be possibly done if C++ functions are wrapped with C interface functions, like Haskell does with the c2hs tool and its excellent C FFI? [Can I call clojure code from C++?](https://stackoverflow.com/questions/8650485...
You have several alternatives here: - you can do it the same way as Java does - via [JNI (Java Native Interface)](https://docs.oracle.com/javase/8/docs/technotes/guides/jni/). There is a complete example of using [clojure with JNI](https://github.com/jakebasile/clojure-jni-example). - there is a [JNA project](https:/...
AS3 adding 1 (+1) not working on string cast to Number? just learning as3 for flex. i am trying to do this: ``` var someNumber:String = "10150125903517628"; //this is the actual number i noticed the issue with var result:String = String(Number(someNumber) + 1); ``` I've tried different ways of putting the express...
All numbers in JavaScript/ActionScript are effectively double-precision [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754) floats. These use a 64-bit binary number to represent your decimal, and have a precision of roughly 16 or 17 decimal digits. You've run up against the limit of that format with your 17-digit numbe...
Performing side-effects in Vavr I'm going through [Vavr Usage Guide](http://www.vavr.io/vavr-docs)'s section about performing side-effects with Match and other "syntactic sugar" as they call it. Here is the example given there: ``` Match(arg).of( Case($(isIn("-h", "--help")), o -> run(this::displayHelp)), Ca...
It's [`io.vavr.API.run`](https://www.javadoc.io/doc/io.vavr/vavr/0.9.2). According to the Javadoc, you're supposed to import the basic VAVR functionality via ``` import static io.vavr.API.*; ``` The `run` function calls a `Runnable` (a function `() -> void`) once and returns `(Void)null`. It's used because ``` ...
Ajax render attribute don't work in a h:dataTable in JSF2 I have some problem's with a simple application in JSF 2.0. I try to build a ToDo List with ajax support. I have some todo strings which I display using a datatable. Inside this datatable I have a commandLink to delete a task. The problem is now that the datat...
*(Looks like I don't have enough reputation to comment on others' answers)* I think FRotthowe suggests wrapping the table with another element and referencing it using absolute reference (ie. naming all the parent containers from the root of the document) from the <f:ajax> tag. Something like this: ``` <h:form i...
Azure Data Factory - Insert Sql Row for Each File Found I need a data factory that will: - check an Azure blob container for csv files - for each csv file - insert a row into an Azure Sql table, giving filename as a column value There's just a single csv file in the blob container and this file contains five rows....
You are headed in the right direction, but within the For each you just need a Stored Procedure Activity that will insert the FileName (and whatever other metadata you have available) into Azure DB Table. Like this: [![ADF Pipeline Example](https://i.stack.imgur.com/bCvmg.png)](https://i.stack.imgur.com/bCvmg.png) ...
How to test my servlet using JUnit I have created a web system using Java Servlets and now want to make JUnit testing. My `dataManager` is just a basic piece of code that submits it to the database. How would you test a Servlet with JUnit? My code example that allows a user to register/sign up, which is submitted fro...
You can do this using [Mockito](https://github.com/mockito/mockito) to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct. ``` import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.*;...
How to find the vocabulary size of a spaCy model? I am trying to find the vocabulary size of the large English model, i.e. `en_core_web_lg`, and I find three different sources of information: - spaCy's docs: 685k keys, 685k unique vectors - `nlp.vocab.__len__()`: 1340242 # (number of lexemes) - `len(vocab.strings)`: ...
The most useful numbers are the ones related to word vectors. `nlp.vocab.vectors.n_keys` tells you how many tokens have word vectors and `len(nlp.vocab.vectors)` tells you how many unique word vectors there are (multiple tokens can refer to the same word vector in `md` models). `len(vocab)` is the number of cached le...
rvest: html\_table() only picks up header row. Table has 0 rows I'm learning how to webscrape with `rvest` and I'm running into some issues. Specifically, the code is only picking up the header-row. ``` library(rvest) library(XML) URL1 <- "https://swishanalytics.com/optimus/nba/daily-fantasy-salary-changes?date=20...
You could -- in theory -- extract the data from the `<script>` tag and then process it with `V8` but this is also pretty easy to do with `splashr` or `seleniumPipes`. I wrote `splashr` so I'll show that: ``` library(splashr) library(rvest) start_splash() pg <- render_html(url="https://swishanalytics.com/optimus/nb...
Eclipse: How to import git project as library for Android Project which has to be pushed to Bitbucket Sorry for the long title, here's the jist: - I have a android application project which I'm hosting on bitbucket. - There is a library on github I'd like to add as a dependency. I'm unsure of 1. How to add the gi...
**Setting your dependency as a library:** you'll have to clone the project to a local folder, import it as a project into Eclipse, and in your project configuration you'll have to set the library project as a library: do a right-click in the project's name, go to Properties and under "Android" click in the checkbox "Is...
RuntimeError at / cannot cache function '\_\_shear\_dense': no locator available for file '/home/...site-packages/librosa/util/utils.py' I am trying to host django application with apache2. But getting the following error. ``` RuntimeError at / cannot cache function '__shear_dense': no locator available for file '/...
After spending a couple of days banging my head against this, and reading all I could google on this, I figured it out. Here goes. **TL;DR:** Make very sure you set the `NUMBA_CACHE_DIR` environment variable to something your app can write to, and make sure that the variable is actually propagated to your app, and yo...
Regular expression must contain and may only contain I want a regular expression for python that matches a string which must contain 4 digits, it may not contain any special character other than "-" or ".", and it may only contain uppercase letters. I know the following matches text with 4 digits or more. How would I a...
The pattern: ``` pattern = '^[A-Z.-]*(\d[A-Z.-]*){4,}$' ``` - `^` - start of the word - `[A-Z.-]*` - any number of optional non-digit "good characters": letters, periods or dashes - `(\d[A-Z.-]*){4,}` - 4 or more groups of a digit and other "good characters"; this part provides at least 4 digits - `$` - end of the...
Files to remove from Windows XP to save space I'm in the process of backing up an XP system, and I'm trying to save as much space as I can for long term storage. I would like to know what directories that might accumulate with time I can safely remove, to minimize the space required. What can I do?
Having been concerned about disk space Windows takes for a long time, I'll throw in my share. - Scour through each user's home folder and My Documents folder and remove unneeded files - Run `cleanmgr`. On its Advanced tab, also clear System restore checkpoints (if you have them enabled at all) - Remove the hibernatio...
cleanup tmp directory with carrierwave I use carrierwave for my images upload, in my form i added a hidden field for caching like is described in documentation. ``` = form_for @user, html: {multipart: true} do |f| %p = f.label :image, "your image" = f.file_field :image, id: "img" = f.hidden_field :image_cache ...
CarrierWave will take care of tidying most of the tmp files and folders for you when everything is working properly. To catch the anomalies create a custom rake task to clean up the garbage and then use the Whenever gem to schedule this task to run every day, every hour etc. my\_custom\_task.rake ``` task :delete...
Unhide Excel Application Session I have an Excel VBA method (I didn't write it) that runs and one of the first things it does is hide the Excel session `Application.Visible = False`. However, when the method has finished, it does not unhide the Excel session so it remains open and listed in the Task Manager but is hi...
> > Like I said, it's not a big deal but was just interested if anyone knew of shortcut key or anything to bring it back. > > > There is no shortcut as such that I am aware of but you can do this. Open MS Word and paste this code in the VBA Editor. Close all open instances of Excel which are visible and then ...
How do I implement a member wise comparison in java? I'm from a C++ background and just started Java today. Say I have a class with a couple of data members. For example: ``` public class Person { //Constructors/Destructor public Person(String strFirstName, String strLastName) { m_strFirstName = str...
You do: ``` if (john.equals(johndoe)) { ... } ``` and implement the `equals()` method on your object: ``` public class Person { private String firstName; private String lastName; private String fullName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastN...
How to create a personal git function, usable every time I launch Bash? I am developing a web site and I use git to update the site, and I have two branch so it goes: - git add . - git commit "something" - git push - git checkout "prod" - git merge --no-ff dev - git push - git checkout "dev" I need a lazygit functi...
Another option is to define a Git alias instead of a shell function. Aliases are part of configuration, so let's look at the `gitconfig(7)` manual page (run `git help config` locally): > > `alias.*` > > > Command aliases for the `git(1)` command wrapper - e.g. after defining `"alias.last = cat-file commit > HE...
Should I validate a method call's return value even if I know that the method can't return bad input? I'm wondering if I should defend against a method call's return value by validating that they meet my expectations even if I know that the method I'm calling will meet such expectations. GIVEN ``` User getUser(Int...
That depends on how likely getUser and myMethod are to change, and more importantly, **how likely they are to change independently of each other**. If you somehow know for certain that getUser will never, ever, ever change in the future, then yes it's a waste of time validating it, as much as it is to waste time vali...
How to set the default file(starting point) in dot net core I am trying to explore the dot net core functionality to get better understanding on it, for the same i executed ``` dotnet new dotnet build dotnet run ``` command in command prompt window, it created a project for me and file with name `Project.cs` has b...
You can edit the "Project.csproj" file to specify which `Main` method is used ``` <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.1</TargetFramework> <StartupObject>Project.SampleDotNetCoreApp</StartupObject> </PropertyGroup> ``` Note the `StartupObject` tag, identifying the c...
How do I see a design of my databound ItemTemplate? I have a simple `ListBox` and bound a collection of objects as `ItemsSource`. The DataTemplate I assigned right now is very simple, but how can I see that template in the designer? This is my xaml: ``` <ListBox.ItemTemplate> <DataTemplate> <Grid> ...
You need design time data. You can declare a design-time data context using the [d:DataContext](https://stackoverflow.com/questions/4033600/silverlight-constructor-injection-into-view-model-design-mode/4034057#4034057) property. You can create mock classes that expose mock lists for your the designer to show at design ...
Generating an Existential type with QuickCheck? I'm struggling with this one - how could QuickCheck generate a value *for all* types? Maybe it could forge it, and only test types with the context `Arbitrary a => a`? I'm just wondering how someone could make an instance of arbitrary for data constructors with an exist...
It's a bit hard to tell what you're really trying to do, especially since your example type doesn't make a lot of sense. Consider something else: ``` newtype WrappedLens s t a b = WrappedLens (forall f . Functor f => (a -> f b) -> s -> f t) newtype WL = WL (WrappedLens (Int, Int) (Int, Int) Int Int) ``` Is it pos...
python bokeh: get image from webcam and show it in dashboard I want to display an image - e.g. capture with the webcam - in bokeh. I tried image\_url and image\_rgba, but both are not working. Image\_url is showing nothing, image\_rgb shows something, but there seems to be some index shift. ``` # -*- coding: utf...
After investigation, the return result from OpenCV is a Numpy array of bytes with shape *(M, N, 3)*, i.e. RGB *tuples*. What Bokeh expects is a Numpy array of shape *(M, N)* 32-bit integers representing RGBA values. So you need to convert from one format to the other. Here is a complete example: ``` from bokeh.plott...
Haskell construct analogous to Rust trait objects Haskell supports *type classes*, like equality: ``` class Eq a where (==) :: a -> a -> Bool ``` Rust does the same with *type traits*: ``` pub trait Draw { fn draw(&self); } ``` Now, it's possible to declare in Haskell a list whose elem...
In Haskell, you can use existential types to express "some unknown type of this typeclass". (In older versions of GHC, you will need a few standard extensions on.) ``` class Draw a where -- whatever the methods are data SomeDraw where SD :: Draw a => a -> SomeDraw type MyList = [SomeDraw] ``` However, note...
An example of a simple higher-order function in javascript While going through [Eloquent Javascript (Chapter 6)](http://eloquentjavascript.net/chapter6.html) there is a reference to higher-order functions in Javascript. While there is an example provided in Chapter 3, I believe it could be a bit simpler since I still d...
Higher functions are concepts from [functional programming](http://en.wikipedia.org/wiki/Functional_programming). In briefly, a higher function is a function which takes another function as parameter. In javascript, some higher functions are added recently. ``` Array.prototype.reduce //With this function, we can d...
React input focus event to display other component I was read some tutorial about this. They told me should using ref to do that. But It's very general. Here is my problem: Basically in `Header` component include `NavBar`, `SearchBar` and `ResultSearch` component. ``` const Header = () => { return ( <header cl...
only you should convert Header component like following: ``` class Header extends Component { state = { focus: false }; handleInputFocus = () => { this.setState({ focus: true }); }; handleInputBlur = () => { this.setState({ focus: false }); }; render() { return ( <header classN...
Fixing "Line indented incorrectly" error from phpcs I am validating PHP code with [phpcs](http://pear.php.net/package/PHP_CodeSniffer) using: ``` phpcs --standard=PSR1 . ``` And it produces [this output](https://travis-ci.org/fulldecent/cameralife/builds/21399263) which is littered with: ``` FILE: /home/travis/...
First up, it might be good to know that those indent errors are coming from your PSR2 run and not the PSR1 run. PSR2 contains all of the checks from PSR1, so you don't actually need to do 2 PHPCS runs. You can just use --standard=PSR2 if you want to adhere to both of them. As for fixing, the current alpha release of ...
Dynamic MemberExpression I am wanting to create a MemberExpression knowing only the field name; eg: ``` public static Expression<Func<TModel, T>> GenerateMemberExpression<TModel, T>(string fieldName) { PropertyInfo fieldPropertyInfo; fieldPropertyInfo = typeof(TModel).GetProperty(fieldName); ...
There are a number of issues with your code: 1. The parameter to your method is called `fieldName`, but you are getting a *property* out with it. 2. You are using the non-generic `Expression.Lambda` method to generate the expression, which may choose an inappropriate delegate-type if the type-argument `T` passed to t...
How to get all Kubernetes Deployment objects using kubernetes java client? I am planning to write simple program using kubernetes java client (<https://github.com/kubernetes-client/java/>). I could get all namespaces and pods but how do i get list of deployments in a given namespace? I couldn't find any method. Is ther...
I guess you're looking for the following [example](https://github.com/kubernetes-client/java/blob/5ef1c54d43399ad747bd7f0fc99a63f1e4768b89/kubernetes/docs/AppsV1Api.md#listnamespaceddeployment): ``` public class Example { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefau...
How much does performance change with a VARCHAR or INT column - MySQL I have many tables, with millions of lines, with MySQL. Those tables are used to store log lines. I have a field "country" in VARCHAR(50). There is an index on this column. Would it change the performances a lot to store a countryId in INT instead o...
Your question is a bit more complicated than it first seems. The simple answer is that `Country` is a string up to 50 characters. Replacing it by a 4-byte integer should reduce the storage space required for the field. Less storage means less I/O overhead in processing the query and smaller indexes. There are outlier c...
ng-click in parent div also in child div I've the following code: ``` <table class="table"> <tr> <th>Name___</th> </tr> <tr ng-repeat="app in apps" ng-click="go('/editApp/' + plugin.name);"> <td> <span>{{...
This executing because your `<td>` nested in `<tr>`, and click firstly fired `openPopup()` then fired `go()`. You can use `$event.stopPropagation()` for stop event propagation to `<tr>`. Try ``` <table class="table"> <tr> <th>Name___</th> </tr> <tr ng-repeat="app in app...
Is it wise to rely on optimizations? Should I write my code to be clear what I am doing and rely on the optimizer to clean up my code efficiency, or should I be obsessive about getting every last ounce of power out of my code? And how much speed/size am I losing on by choosing one option over the other?
There are 2 very different kinds of optimisations. The first is micro-optimisations. These are things like (e.g.) changing `x = (y * 4 + z) / 2` into `x = y + y + z / 2`, or `x = y % 8` into `x = y & 7`. Compilers are very good at micro-optimisations, so don't bother. The second is algorithmic optimisations. Things...
How to find out if a Object is a integer or is a string or is a boolean? I have an object and I want to detect what type is, so I can call ``` if (obj isa Integer) put(key,integerval); if (obj isa String) put(key,stringval); if (obj isa Boolean) put(key,booleanval); ```
You're pretty close, actually! ``` if (obj instanceof Integer) put(key,integerval); if (obj instanceof String) put(key,stringval); if (obj instanceof Boolean) put(key,booleanval); ``` From the [JLS 15.20.2](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2): > > *Re...
Use Entity framework I want to include only first children objects and not child of child(sub of sub) Useing Entity framework I want to include an only the first level of children objects and not the children of child I have these two classes: ``` public class BusinessesTBL { public string ID { get; set; } ...
I now see that a big part of the original answer is nonsense. Sure enough, the reason for the endless loop is relationship fixup. But you can't stop EF from doing that. Even when using `AsNoTracking`, EF performs relationship fixup in the objects that are materialized *in one query*. Thus, your query with `Include` w...
Update data property / object in vue.js is there a way I can programmatically update the `data` object / property in vue.js? For example, when my component loads, my data object is: ``` data: function () { return { cars: true, } } ``` And after an event is triggered, I want the `data` object to loo...
Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object, So you may create an object and add a new property like that: ``` data: function () { return { someObject:{ cars: true...
After upgrading to xcode 9, cordova app won't build, error 70, requires provisioning profile Yesterday we upgraded from xcode 8.3.2 to version 9. And now our enterprise distribution apache cordova ios app refuses to build. ``` 2017-09-21 07:37:16.787 xcodebuild[70400:217569] [MT] IDEDistribution: -[IDEDistributionLo...
If you specify your provisioning profile explicitly, like me. Like this in your Cordova build.json: ``` "ios": { "debug": { "codeSignIdentitiy": "iPhone Developer", "developmentTeam":"MYTEAMID", "packageType": "developer", "iCloudContainerEnvironment": "Development" }, "re...
What exactly is the ResourceConfig class in Jersey 2? I have seen a lot of Jersey tutorials that starts with something like ``` @ApplicationPath("services") public class JerseyApplication extends ResourceConfig { public JerseyApplication() { packages("com.abc.jersey.services"); } } ``` without expl...
Standard JAX-RS uses an [`Application`](https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/core/Application.html) as its configuration class. [`ResourceConfig`](https://eclipse-ee4j.github.io/jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/ResourceConfig.html) *extends* `Application`. There ...
@PreAuthorize on spring controller sending redirect if authorization fails I've got spring security successfully evaluating a @PreAuthorize on my controller. If i use "permitAll" then I can view the page, and if I use "isAuthenticated()" then I get an ugly Access is Denied stack trace. If I put the configuration in an ...
I got this to work. There were a couple of things I had to deal with. First, my Spring MVC configuration had a SimpleMappingExceptionResolver with a defaultErrorView configured. That was intercepting the Authentication and Authorization errors before they could get to the access-denied-handler that I had configured i...
307 Redirect when loading analytics.js in Chrome I'm building a web app and using Google Analytics (analytics.js) for analytics. I recently noticed that analytics aren't working properly in Chrome. I'm loading analytics using the standard code snippet in a separate module and included via requirejs. I've verified tha...
`307 Internal Redirect` with `Non-Authorative-Reason: Delegate` indicates that the request was intercepted and modified (redirected) by a Chrome extension via the [webRequest](https://developer.chrome.com/extensions/webRequest) or [declarative webRequest](https://developer.chrome.com/extensions/declarativeWebRequest) e...
Auto grow textarea with knockout js I've implemented the logic of auto-expanding the height of a textarea on the keyup event. However, I want the textarea to also initialise its height once the value is bound to the textarea via a knockout custom binding. Any solutions? (With the use of only KnockoutJS, without using j...
I'd strongly advice against using an event to trigger the resize. Instead, you can use the `textInput` binding to keep track of the input in an observable and subscribe to changes there. Here's an example: ``` <textarea data-bind="textInput: value, autoResize: value"></textarea> ``` ``` ko.bindingHandlers.autoR...
Vue computed setter not working with checkboxes? I have a computed setter: ``` rating: { get() { return this.$store.state.rating; }, set(value) { console.log(value); this.$store.commit('updateFilter', { name: this.name, value }); } } ``` Thi...
`v-model` has somewhat ["magical"](https://v2.vuejs.org/v2/guide/forms.html#Checkbox) behavior, particularly when [applied to checkboxes](https://v2.vuejs.org/v2/guide/forms.html#Checkbox). When bound to an array, the checkbox will add or remove the value to/from the array based on its checked state. It is not clear ...
Android cookies using phonegap I have developed a phonegap application that has a user login page with a text box for username/password, a check box for "remember my info", and a submit button. Pretty standard. When I open it in Firefox, the cookie works fine and my login data is remembered when the box is checked....
For mobile application development HTML5 has new feature for Local Store and Session Store. Same like cookies and session in web development Try with ***localStorage*** option. I worked this way only. For storing values in local storage i.e stored in browser permanently ``` window.localStorage.setItem("key", "V...
Vision API: How to get JSON-output I'm having trouble saving the output given by the Google Vision API. I'm using Python and testing with a demo image. I get the following error: ``` TypeError: [mid:...] + is not JSON serializable ``` Code that I executed: ``` import io import os import json # Imports the Goog...
FYI to anyone seeing this in the future, google-cloud-vision 2.0.0 has switched to using proto-plus which uses different serialization/deserialization code. A possible error you can get if upgrading to 2.0.0 without changing the code is: ``` object has no attribute 'DESCRIPTOR' ``` Using google-cloud-vision 2.0.0,...
Finding the unbiased variance estimator in high dimensional spaces The problem comes from linear regression. Assume the regression function is linear, i.e. $$ f(X) = \beta\_0+\sum\_{j=1}^pX\_j\beta\_j $$ .Given a set of training data $(x\_1, y\_1),\ldots,(x\_N,y\_N)$,we try to estimate the parameters $\beta$ by minimi...
Well it might be an overkill but I think this proof is OK. I would use basic linear algebra tools. Starting with slight change in your notations: Let $X$ denote the matrix $(x\_1\; x\_2 \;...\; x\_N)^T$ where $x\_i=(1 \; x\_{i2} \; x\_{i3} \; ... \; x\_{ip})$. So now we have $p-1$ covariates. Our model is $$ y=X\bet...
How to wait for end of a coroutine I have some code below. Delay (3000) is just replacement for a long loop (or cycle). I’m expecting that after completion of loop `println(res)` will print “Some String” and then enable `button`. But in real life `println(res)` prints an empty string and `button` became enabled at same...
You can try some thing like this: ``` suspend fun saveInDb() { val value = GlobalScope.async { delay(1000) println("thread running on [${Thread.currentThread().name}]") 10 } println("value = ${value.await()} thread running on [${Thread.currentThread().name}]") } ``` await will wa...
Counting the number of times a character occurs in a string in C I'm new to C, and I'm working on my own `explode` like function. I'm trying to count how many times a specified character occurs in a string. ``` int count_chars(char * string, char * chr) { int count = 0; int i; for (i = 0; i < sizeof(str...
Your code is hopelessly flawed. Here's how it *should* look like: ``` int count_chars(const char* string, char ch) { int count = 0; int i; // We are computing the length once at this point // because it is a relatively lengthy operation, // and we don't want to have to compute it anew // eve...
Json.NET does not preserve primitive type information in lists or dictionaries of objects. Is there a workaround? The following example illustrates a fundamental flaw in Json.NET's type handling: ``` List<object> items = new List<object>() {Guid.NewGuid(),DateTime.Now}; var settings = new JsonSerializerSettings() { ...
Here is a solution using a custom `JsonConverter`: ``` public sealed class PrimitiveJsonConverter : JsonConverter { public PrimitiveJsonConverter() { } public override bool CanRead { get { return false; } } public override bool CanConvert(Type object...
How do I publish Gradle plugins to Artifactory? I am working with this example Gradle Plugin project: <https://github.com/AlainODea/gradle-com.example.hello-plugin> When I run **./gradlew publishToMavenLocal** it creates these files in M2\_HOME: 1. com/hello/com.example.hello.gradle.plugin/maven-metadata-local.xml ...
Since you have the **maven-publish** plugin on, the **java-gradle-plugin** already declares publications for you, so you can remove [this explicit publications block](https://github.com/AlainODea/gradle-com.example.hello-plugin/blob/d7a21432311c2d07a29a590638eed71fe3ef50a5/build.gradle.kts#L74-L80) from your build: ...
Can get image from PHAsset of library I am using [QBImagePickerController](https://github.com/questbeat/QBImagePicker) for selecting multiple images at a time. So, here is my whole code I am presenting `imagepickerController` with this code ``` let imagePickerController = QBImagePickerController() imagePickerCo...
You need to use `requestImageForAsset` to get `UIImage`. You can get image like this way ``` func qb_imagePickerController(imagePickerController: QBImagePickerController!, didFinishPickingAssets assets: [AnyObject]!) { let requestOptions = PHImageRequestOptions() requestOptions.resizeMode = PHImageRequestO...
String vs char[] I have some slides from IBM named : ["From Java Code to Java Heap: Understanding the Memory Usage of Your Application"](http://www.ibm.com/developerworks/library/j-codetoheap/#N101DC), that says, when we use `String` instead of `char[]`, there is **Maximum overhead would be 24:1 for a single charact...
This figure relates to JDK 6- 32-bit. ## JDK 6 In pre-Java-7 world strings which were implemented as a pointer to a region of a `char[]` array: ``` // "8 (4)" reads "8 bytes for x64, 4 bytes for x32" class String{ //8 (4) house keeping + 8 (4) class pointer char[] buf; //12 (8) bytes + 2 bytes per c...
R converting integer column to 3 factor columns based on digits I have a column of int's like this: ``` idNums 2 101 34 25 8 ... ``` I need to convert them to 3 factor columns like this: ``` digit1 digit2 digit3 0 0 2 1 0 1 0 ...
Here's a fun solution using the modular arithmetic operators `%%` and `%/%`: ``` d <- c(2, 101, 34, 25, 8) res <- data.frame(digit1 = d %/% 100, digit2 = d %% 100 %/% 10, digit3 = d %% 10) # digit1 digit2 digit3 # 1 0 0 2 # 2 1 0 1 # 3 0 ...
Uncaught TypeError: Cannot read property 'aDataSort' of undefined i am working on pagination and i am using [DataTables](https://www.datatables.net/) plugin , on some tables it's work but on some tables it gives error: > > Uncaught TypeError: Cannot read property 'aDataSort' of undefined > > > my page script l...
use something like the following in your code to disable sorting on `DataTables` (adapted from a project of mine which uses latest `DataTables`) ``` $(document).ready(function() { $('.datatable').dataTable( { 'bSort': false, 'aoColumns': [ { sWidth: "45%", bSearchable: false, bSor...
The difference of parameters between “glm” and “optim” in R I’d like to know the difference of parameters(intercept, slopes) between “glm” and “optim” in R. I think those predictions would be fine, but I can’t understand why those parameters are different. If it’s a misinterpretation, please give me some advice. glm;...
I'm going to answer this in a more general context. You have set up a logistic regression with *complete separation* (you can read about this elsewhere); there is a linear combination of parameters that perfectly separates all-zero from all-one outcomes, which means that the maximum likelihood estimates are actually *i...
Is there an equivalent in ggplot to the varwidth option in plot? I am creating boxplots using ggplot and would like to represent the sample size contributing to each box. In the base `plot` function there is the `varwidth` option. Does it have an equivalent in ggplot? For example, in base plot ``` data <- data.fra...
Not elegant but you can do that by: ``` data <- data.frame(rbind(cbind(rnorm(700, 0,10), rep("1",700)),                          cbind(rnorm(50, 0,10), rep("2",50)))) data[ ,1] <- as.numeric(as.character(data[,1])) w <- sqrt(table(data$X2)/nrow(data)) ggplot(NULL, aes(factor(X2), X1)) + geom_boxplot(width = w[1],...
Ruby Sqlite3 installation sqlite3\_libversion\_number() macOS Sierra I'm trying to install the Metasploit framework (unimportant) and bundler is attempting to install sqlite3, which is where it fails consistently. Sqlite3 is installed (executing sqlite3 at the command line brings me into the environment) and is linked ...
I finally managed to solve this by **specifying the built-in Mac OS X sqlite library directory** on macOS Sierra 10.12.5 (16F73): ``` $ whereis sqlite3 /usr/bin/sqlite3 # if binary is in /usr/bin then library is typically in /usr/lib $ gem install sqlite3 -- --with-sqlite3-lib=/usr/lib Building native extensions wit...
Creating instance of class inside class I am trying to create an instance of class inside class. I have declared two classes = first ``` class Student{ public: Student(string m,int g){ name=m; age=g; } string getName(){ return name; } int getAge(){ return age; ...
Member initialization should be done in your constructors initialization list: ``` Class(string n) : Martin("Martin",10) , Roxy("Roxy",15) { name = n; }; private: string name; Student Martin; Student Roxy; ``` Some more information on member initialization can be found here: <http://en.cpp...
Why does this CSS margin-top style not work? I tried to add `margin` values on a `div` inside another `div`. All works fine except the top value, it seems to be ignored. But why? **What I expected:** [![What I expected with margin:50px 50px 50px 50px;](https://i.stack.imgur.com/ZEuMt.png)](https://i.stack.imgur.co...
You're actually seeing the top margin of the `#inner` element [collapse](http://www.w3.org/TR/CSS21/box.html#collapsing-margins) into the top edge of the `#outer` element, leaving only the `#outer` margin intact (albeit not shown in your images). The top edges of both boxes are flush against each other because their ma...
Inject an integer with Ninject I have folowing class ``` public class Foo { public Foo(int max=2000){...} } ``` and I want to use Ninject to inject a constant value into Foo. I have try this ``` Bind<Foo>().ToSelft().WithConstructorArgument("max", 1000); ``` but I get following error when I try to use `_nin...
the below works for me: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ninject; using Ninject.Activation; using Ninject.Syntax; public class Foo { public int TestProperty { get; set; } public Foo(int max = 2000) { Test...
Should one perform a calculation in a DTO model or in the destination entity model? I'm currently creating various entities in ASP.NET Core 2.2 with accompanying DTOs for a Web API. The client application would submit a DTO object to the relevant controller action. There using the AutoMapper, this would be mapped from ...
It depends on the actual context. Is the `EventTimes` an entity or is it rather part of your domain model? Either way I would not put it in the **dto** as this is really just for transferring data, so it should not contain any logic (besides maybe validation). Since the responsibility for this calculation is neithe...
How to call an Objective-C singleton from Swift? I have an objective-C singleton as follows: ``` @interface MyModel : NSObject + (MyModel*) model; ... + (MyModel*) model { static MyModel *singlton = nil; static dispatch_once_t onceToken; dispatch_...
UPDATE ++++++++++ The workaround below is only necessary if you name your singleton method with a name derived from the suffix of the class name i.e. the OPs question the method name is model and the class is called MyModel. If the method is renamed to something like singleton then it is possible to call it from S...
Is using explicit return type in one translation unit and deduced return type in another allowed? My question is similar to [this one](https://stackoverflow.com/questions/27746467/using-functions-that-return-placeholder-types-defined-in-another-translation-uni), but subtly different. Suppose I have two translation un...
*All standard references below refers to [N4861: March 2020 post-Prague working draft/C++20 DIS.](https://timsong-cpp.github.io/cppwp/n4861/).* --- From [[basic.link]/11](https://timsong-cpp.github.io/cppwp/n4861/basic.link#11) [**emphasis** mine]: > > **After all adjustments of types** (during which typedefs...
iOS Appstore app override enterprise app Our company has both Appstore and Enterprise distribution licence. We are going to make demonstration with current beta version via enterprise licence. Some users going to download enterprise app to test beta release. After appstore publish we want Appstore app override the ente...
Unfortunately, you can not have an Enterprise App and an App Store App share the same Bundle Identifier (= AppID). App Store Apps need be provisioned by a profile created in a normal Developer Account. Enterprise In House Apps need to be provisioned by a separate Enterprise Developer Account, as you can not create Ente...
Should I use mysql for scalability? I'm in the planning phase for developing a web application and am trying to figure out my best bet as far database options goes. I'm already familiar with php and mysql database. Initially, the website won't be handling any transactions, but my hope is that the website will expand to...
Plan for the foreseeable future and not beyond. If utilized correctly MySQL can scale incredibly well (just check out some of the names that use it <http://www.mysql.com/why-mysql/case-studies/> ). As for the security aspect, that's totally up to your coding ability. Security is not inherently better in one language ...
Haskell infinite types and my FSM function I've just come across the "infinite type" in Haskell when I was attempting to write a finite state machine. I thought the following was very intuitive: ``` fsm [] _ acc = Right acc fsm (x:xs) state acc = case state acc x of Left err -> Left err ...
Infinite types like this wreak havoc with the type system; they don't make it unsafe, but they cause a great deal of programs to type which you don't really want to, thus hiding errors, and I believe they make type inference harder too. Thankfully, the solution is simple: you just need to make a `newtype` wrapper. `d...
XNA ViewPort projection and SpriteBatch I'm working on an XNA game and I am using ViewPort.Project and ViewPort.Unproject to translate to and from world coordinates. Currently I use these for each object I draw with SpriteBatch. What I would like to do is calculate a Matrix that I can send to SpriteBatch.Begin to do th...
I've written about `SpriteBatch` and the various "spaces" (world, projection, client, etc) [here](https://stackoverflow.com/questions/3018980/using-createorthographicoffcenter-in-xna/3020190#3020190), [here](https://stackoverflow.com/questions/3495140/letterboxing-and-scaling-in-xna-on-pc/3499671#3499671) and [here](ht...
Extract specific folder from tarball into specific folder I created a tarball on Ubuntu 14.04 with: ``` cd /tmp tar -cfvz archive.tar.gz /folder ``` Now I want to extract a specific folder in the tarball (which inside the tarball lies in `/tmp`) into a specific folder: ``` cd /tmp tar -xfvz archive.tar.gz folde...
# Tl;dr Since you are in `/tmp` already, you can just discard the `-C` option (since by default `tar` will extract files in the current working directory) and just add `--strip-components=2`: ``` tar --strip-components=2 -xfvz archive.tar.gz folder/in/archive ``` --- GNU `tar` by default stores relative path...
How to add build step in team city to run Node Js unit tests (Mocha framework) I have a NodeJs application. Currently I am using team city for build and deployment of this application. Now I want to run unit test cases before deployment. I have used Mocha framework with Chai to write test cases. I don't see any runner ...
You don't have to install any specific TeamCity plugin, you have to use test reporter capable of writing TeamCity [service messages](https://confluence.jetbrains.com/display/TCD10/Build+Script+Interaction+with+TeamCity), e.g. [mocha-teamcity-reporter](https://www.npmjs.com/package/mocha-teamcity-reporter), which is jus...
Extra Characters while using XML PATH I have a table called Map\_Data and the data looks like: ``` ID SoCol Descol 125 case Per_rating when 5 then 'Good' when 4 then 'Ok' else null end D_Code ``` And I wrote a query on this particular row and t...
This slight change will make the ugly entities go away, but they won't eliminate carriage returns (look at the results in Results to Text, not Results to Grid, to see them): ``` SELECT Params = ( SELECT DesCol + ' = ''' + SoCol + '''' FROM dbo.Map_Data t1 WHERE ID = 12...
Why am I getting a NameError when I try to call my function? This is my code: ``` import os if os.path.exists(r'C:\Genisis_AI'): print("Main File path exists! Continuing with startup") else: createDirs() def createDirs(): os.makedirs(r'C:\Genisis_AI\memories') ``` When I execute this, it throws an er...
You can't call a function unless you've already defined it. Move the `def createDirs():` block up to the top of your file, below the imports. Some languages allow you to use functions before defining them. For example, javascript calls this "hoisting". But Python is not one of those languages. --- Note that it'...
Set readonly fields in a constructor local function c# The following does not compile. ``` public class A { private readonly int i; public A() { void SetI() { i = 10; } SetI(); } } ``` It fails with this error: > > CS0191 A readonly field cannot b...
The compiler turns the `SetI` local function into a separate class-level method. Since this separate class-level method is not a constructor, you are not allowed to assign to readonly fields from it. So the compiler takes this: ``` public class A { private readonly int i; public A() { void Set...
Facebook OAuth is not returning email in user info I'm doing a spree 3.0 installation (ROR) and trying to use facebook oauth for authentication, but the fields sent back after a successful oauth, do NOT contain the email, which is critical to our application. here is the return from the facebook successful authenticati...
Facebook just released latest APIv2.4 that does not return email by default but we need to *explicitly* specify what fields to use. [Introducing Graph API v2.4](https://developers.facebook.com/blog/post/2015/07/08/graph-api-v2.4/) Now, on the very latest omniauth-facebook(possibly 2.1.0), "email" fields are specifi...
How to make every Class Method call a specified method before execution? I want to make my Python Class behave in such a way that when any Class method is called a default method is executed first without explicitly specifying this in the called Class. An example may help :) ``` Class animals: def _internalMetho...
You could use a metaclass and [**getattribute**](http://docs.python.org/reference/datamodel.html#object.__getattribute__) to decorate all methods dynamically (if you are using Python 2, be sure to subclass from `object`!). Another option is just to have a fixup on the class, like: ``` def add_method_call(func, met...
Document.referrer wrong when pressing the back button I have a PHP / Javascript page that automatically logs a user into different systems from one log on. These are external sites and all works good except when the user hits the back button. It then redirects them right back where they came from. I'm looking to have...
It sounds like you are trying to go back to a previous page, that is not within the website of the page you're on? A few points: 1) document.referrer will only work if the person got to the current page through a link, or clicking something.... not if they were redirected through other means. 2) Due to browser ...
Is it feasible to use Lisp/Scheme as a scripting language? Is it feasible to script in a Lisp, as opposed to Ruby/Python/Perl/(insert accepted scripting language)? By this I mean do things like file processing (open a text file, count the number of words, return the nth line), string processing (reverse, split, slice, ...
Today, using `LISP` as if it's certain that anyone would understand what language one is talking about is absurd since it hasn't been one language since the 70's or probably some time earlier too. LISP only indicates that it's fully parenthesized Polish prefix notation just like Pascal, Ruby, Python and Perl are just [...
EntityFramework not updating column with default value I am inserting an object into a SQL Server db via the EntityFramework 4 (EF). On the receiving table there is a column of (`CreatedDate`), which has its default value set to `getdate()`. So I do not provide it to the EF assuming its value will be defaulted by SQL S...
If you never want to edit that value (like with a created date), you can use: ``` [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public virtual DateTime CreatedDate { get; set; } ``` This will tell the Entity Framework that the value is controlled by the database, but will still fetch the value. Note that...
Some questions about OpenGL transparency I have two questions about OpenGL blending. 1) I know I have to draw opaque objects first and then draw from back to front the non-opaque ones. So I put them in a list depending in the distance to the center (0,0,0). But do transformations (rotate and translate) affect the "ce...
You certainly need to take the transformations into account for sorting. Applying all the transformations, and then sorting by the resulting depth (z-coordinate), is the most direct approach. A mostly more efficient way of achieving the same thing is to apply the inverse transformations to your view direction once fo...
RegEx with \d doesn’t work in if-else statement with [[ i wrote the following script. It will be used in a build process later. My goal is to decide whether it's a pre release or a release. To archive this i compare $release to a RegEx. If my RegEx matches it's a pre release, if not it's a release. ``` #/bin/bash r...
`\d` and `\w` don't work in [POSIX regular expressions](http://en.wikipedia.org/wiki/Regular_expression#POSIX), you could use `[[:digit:]]` though ``` #/bin/bash release="1.9.2-alpha1" echo "$release" LANG=C # This needed only if script will be used in locales where digits not 0-9 if [[ "$release" =~ ^[[:digit:]]+\....
Adding a field to Scala case class? I've seen some blogs on the `Pimp my Library pattern`, and these seem to work well for adding behavior to classes. But what if I have a `case class` and I want to `add data members` to it? As a case class I can't extend it (*inheriting from a case class is deprecated/strongly disco...
No - I don't see how you could make this work because the *enriched instance* is usually thrown away (note: newly the pimp-my-library pattern is called enrich-my-library). For example: ``` scala> case class X(i: Int, s: String) defined class X scala> implicit class Y(x: X) { | var f: Float = 0F | } def...