text:
Q: ASP.NET UnauthorizedAccessException when accessing item from cache We have some code that occasionally flushed out certain keys in the ASP.NET cache in order to make sure that we are getting up to date data from our Dynamics CRM system. It seems to work fine most of the time, however we are getting intermittent exceptions on page reloads that I suspect is related to this forced cache flushing.
Here is the error in the UnauthorizedAccessException:
Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-129326029589946795:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query=953227368' is denied.

In case it is helpful, here is how I am flushing the cache items:
 private void Flush()
    {
        IDictionaryEnumerator cacheEnum = this.HttpContext.Cache.GetEnumerator();
        while (cacheEnum.MoveNext())
        {
            var key = cacheEnum.Key.ToString();

            if (key.StartsWith("Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query"))
                System.Web.HttpContext.Current.Cache.Remove(key);
        }
    }

My questions:

*

*Is there some level of permission required to access or remove cache items? I googled this but did not find anything specific (even in MSDN).

*Have you seen this error before? How did you resolve it?

UPDATE: here is the stacktrace.
Stacktrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Threading.Mutex.MutexTryCodeHelper.MutexTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Lock(String key, Int32 millisecondsTimeout, Action`1 action)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Int32 millisecondsTimeout, Func`2 loadFromCache, Func`2 loadFromService)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Func`2 loadFromCache, Func`2 loadFromService, Action`2 addToCache)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.InnerExecute[TRequest,TResponse,TResult](TRequest request, Func`2 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](MetadataServiceRequest request, Func`5 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](MetadataServiceRequest request, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute(Object request)
at Microsoft.Xrm.Client.Services.IOrganizationServiceExtensions.RetrieveAllEntities(IOrganizationService service, MetadataItems metadataItems, Boolean retrieveAsIfPublished)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.GetId(DynamicEntity entity)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__48.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__41.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__2b.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__13.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.GetCachePolicy(Object query, Object result)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.Insert(String key, Object query, Object result)
at Microsoft.Xrm.Client.Threading.MutexExtensions.<>c__DisplayClass5`1.<Get>b__4(String k)
at Microsoft.Xrm.Client.Threading.MutexExtensions.<>c__DisplayClass2`1.<Get>b__0(Mutex _)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Lock(String key, Int32 millisecondsTimeout, Action`1 action)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Int32 millisecondsTimeout, Func`2 loadFromCache, Func`2 loadFromService)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Func`2 loadFromCache, Func`2 loadFromService, Action`2 addToCache)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.InnerExecute[TRequest,TResponse,TResult](TRequest request, Func`2 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](Request request, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.RetrieveMultiple(QueryBase query)
at Microsoft.Xrm.Client.Services.IOrganizationServiceExtensions.Using[T](Func`1 create, Func`2 action)
at Microsoft.Xrm.Client.Linq.CrmQueryProvider.Execute[TElement](QueryExpression qe, LambdaExpression projection, Delegate postMethodCall, LambdaExpression filter, Type entityType)
at Microsoft.Xrm.Client.Linq.CrmQueryProvider.Execute[TElement](Expression expression)
at Microsoft.Xrm.Client.Linq.QueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Single[TSource](IQueryable`1 source)
at FrontOfficeApp.Controllers.BillingController.GetBillingInstitutions(Requisition req)
at FrontOfficeApp.Controllers.BillingController.InstitutionalBillPartial(Int32 requisitionId)
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Message=Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-119328537521157948:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query=913126368' is denied.
Data=System.Collections.ListDictionaryInternal

UPDATE2:
We just updated to the 4.0.13 version of the SDK in order to turn off caching (actually I could only get it to work by setting the duration to 1 second, see below). This allows us to get around the issue of CRM needing to be flushed, but we are still getting the caching errors in our environment, although they look a little different now:
Message=Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-129341239247458264:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:User=00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000:Query=923237368' is denied.
Data=System.Collections.ListDictionaryInternal

For what is is worth, the context configuration I am using is below. I am adding a bounty to this question as a last ditch attempt.
<microsoft.xrm.client>
    <contexts default="Crm">
        <add name="Crm" type="CRM.XrmDataContext" serviceName="Default" />
    </contexts>
    <services default="Default">
        <add name="Default" cacheProviderName="Default" />
    </services>
    <cache defaultProvider="Default">
        <providers>
            <add name="Default"
               type="Microsoft.Xrm.Client.Caching.InMemoryCacheProvider, Microsoft.Xrm.Client" duration="00:00:01" />
        </providers>
    </cache>
</microsoft.xrm.client>

A: We finally figured out the answer to this issue. The problem was related to impersonation (we had it turned on in the web.config) and the fact that we were accessing XRM using a singleton. Apparently, when multiple users tried to run simultaneous CRM queries through our software, the singleton would make the connection to CRM under their user context. Apparently while this is happening, the cache for the query results are "owned" by that user context. When another user tried to run a query at the same time, they would receive a 401 status code.
The fix ended up being to turn of impersonation and do some minor refactoring so that we did not need it anymore. I imagine we could instead have allowed multiple CRM instances--though we intentionally don't do that for performance reasons.
I hope this helps anyone else who might be seeing these funky errors.

A: I can't imagine that the exception is actually tied to the Cache.Remove call.
Just a guess, but is it possible that the exception is related to the CacheItemRemovedCallback and not the actual removal step (not sure if the call-back is executed synchronously on the same thread)?
Can you post the full stack trace for the exception?


text:
Q: How to configure a DD-WRT (micro) secondary router to prevent LAN access on a specified schedule? I have a NetGear WiFi router configured as the main gateway for internet access in my home, and a secondary router (a Linksys wrt54GS loaded with DD-WRT v24-sp2 micro), configured with a different SSID, for my kids to use to access the internet.  My goal in using DD-WRT is to be able to let my kids use the household Wi-Fi, but to adhere to an electronics curfew  during evening hours, so they are not snap-chatting till the wee hours of the morning.  Here is the link I used to configure my DD-WRT.  Basically my DD-WRT WiFi router is:

*

*Configured in router mode.

*Wireless mode is AP (Access Point)

*SSID is different from my main gateway router.

*Configured on same subnet as main router, as IP 192.168.1.2 (main router is 192.168.1.1).

*DHCP disabled

I have tried setting up a schedule on the Access Restrictions tab, trying several different options (deny access vs filter access to most ports; list individual IPs to deny vs a range of IPs [3-254]; Security->SPI Firewal Enabled vs Disabled).  However, I think this is not the right approach, since this schedule is for "WAN" access, and my 2 routers are chained via LAN ports: the WAN port on the secondary router is not even used.
So far everything I've done is through the web interface.  Is there another way to go about this?  Perhaps write a bash or python script to run on the router that just shuts the LAN off during certain hours?  Any tips or advice would be greatly appreciated!

A: Here's how I would do it:

*

*Connect DD-WRT router to your LAN via its WAN port

*Configure the WAN access rules as you have

This gives you the advantage of shutting down your kids' internet access during the scheduled times. It also allows you to regulate access to other resources within your own network, e.g. a file or media server you might be running.
I implemented a similar setup on my own home network for guest wi-fi access, using it to limit how much of my bandwidth they can consume (I've got more than one friend who doesn't understand the concept of download caps...) and even shutting it down completely when necessary (I had a problem once where a friend, thinking he was being helpful, provided the WPA password to a neighbor who also did not respect bandwidth caps).
If you have your kids' systems in the same subnet as your main LAN, there really shouldn't be a difference in terms of what local resources they can access, however it does give you the control over their WAN access that you want. (Correct me if I'm wrong, but doesn't DD-WRT allow you to define exemptions to the schedule, so you could allow them access to local resources even when their WAN is otherwise shut off?) Of course, you could put them in a different subnet, allowing you to more easily use firewalls to gain fine-grained control over what local resources they can and cannot access.

A: I'm sort of a "networking noob", so I'm not sure if configuring my secondary DD-WRT Linksys router on a schedule didn't work because it was essentially functioning as a pass-through router to the primary, and thus was bypassing the NAT and WAN aspect of the router.  Or perhaps maybe I just had something else misconfigured for the normal GUI scheduling tool to work correctly.
However, I can say that what finally did work for me was to set up a pair of cron jobs to disable and enable the wireless radio at specific times using the wl command.  My solution:  On the router's Administration tab, go to the Management sub-tab, then find the Cron section.  Set Cron to Enable, then enter a crontab similar to the following:
#Clock Minutes
#|  Clock Hour
#|  |      Day of week
#|  |      |   Run as
#|  |      |   |   Command...
#v  v      v   v   v
30 22  * * * root wl radio off
30 7  * * * root wl radio on

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dropbox Djinni - Interface Inheritance Is there a way to inherit / extend interfaces in Djinni's DSL?
For example:
parent = interface +c {
  parentMethod();
}

child1 = interface +c {
  childMethod1();
}

child2 = interface +c {
  childMethod2();
}

I want to inherit child1 and child2 from parent.

A: There's no interface inheritance in Djinni currently.  It's not because we're opposed to it (pull requests welcome!), but simply because it hasn't been a need in Dropbox's development.  You can probably get something close to what you need with some explicit methods.  E.g. add a asParentInterface() method to your child objects.  At the C++ layer you could choose to just return "this" cast to another type, and your impl object would multiply inherit from Djinni base classes.  In the app languages you'd see multiple distinct proxy objects on the same underlying object.


text:
Q: Connect/bridge two networks?
Summary
I have two networks, that I wan't to connect to each other, so I can connect from one machine on one network to another machine on another network.
How things are
At my office, I have a wireless network that I have very limited control over (no port forwarding etc). But it's reliable, no data limit, and fast. Connected to this network I have a server (Mac Mini).
Then I have another server (Linux Desktop), which is connected to my own mobile network through a Teletonika RUT950 modem/router. Here I have full control, and can do port forwarding etc.
What I want to achieve
I can currently SSH into the Linux machine on my own mobile network, but I would love to also be able to SSH (and VNC etc) into the Mac Mini which is on the other corporate network. I can't connect the Mac Mini to the mobile network, because of expense/data limits.
How can I do this? I might be able to connect with cable to the office network, but preferably over wifi. The Linux, Mac Mini and the RUT950 can be co-located.
I would prefer a general solution that maybe uses some native functionality of the RUT950 or something, rather than specialized software setup or similar. But open to anything.

A:
I might be able to connect with cable to the office network, but preferably over wifi.

You need one machine somewhere that is connected to both networks. This can be a machine with two WLAN adapters (or one WLAN adapter that can connect to both WLAN networks at once, but these are rare), or a machine with a WLAN and a LAN.
If you have control over your Mac Mini, the simplest solution would be to connect the LAN on the Mac Mini to the LAN on the RUT950.
Depending on what variant you choose, you'll then have to configure various things (like IP ranges, routes, and so on). If you have control over the Mac Mini and can connect its LAN to the RUT950, the Mac Mini will get two IP address (one in each network), and you just have to make sure that sshd is active on both to be able to ssh into it.
Also, assuming the "wireless network that I have very limited control over" is a corporate network, they usually don't like that their networks get routed to open networks, and may act if they find out you did.

A: In your situation, I would suggest not connecting the two networks at all. Instead connect the hosts to a common network.
If you have an externally accessible server somewhere, set up a VPN service that both your office computer and the personal network connect to. All hosts connected to the VPN will be able to reach each other; the server will relay traffic between them.
Any generic VPN protocol will do, such as OpenVPN or Wireguard; the "Innernet" software looks promising as well.
(On the "personal" side you can have the router itself connect to the VPN, though I'm not sure what the RUT is capable of.)
In addition to basic server-based VPNs, there are also kinda "mesh" VPNs such as Tinc or ZeroTier, which have various levels of sophistication for delivering packets through NATs, relays, firewalls, etc. If you don't have a suitable central server, then one of these might work better.


text:
Q: Why is the × operator not defined for vector × vector? For a vector space, the + operator maps two vectors to another vector while the × operator maps a scalar and a vector to another vector.
To me, it seems strange that scalars are seen as separate to vectors when defining a vector space, with the x operator being specially created to map a scalar and vector to vectors.
Why can't instead the × operator map two vectors to another vector while remaining consistent with the scalar × vector operation?
For example, $(a, b, c) × (d, e, f) = (ad, ae, af) + (bd, be, bf) + (cd, ce, cf)$
where $ad$ scales $d$ by a factor of $a$; $bd$ rotates $d$ by an amount $b$ about some axis, $cd$ rotates $d$ about another axis by $c$.
This way there would be no need to bring in an additional set of scalars, providing it was consistent.

A: The concept of a vector space isn't so much defined as recognized. All over Mathematics there are sets of things that have a natural addition, and a natural multiplication by real or complex numbers, but no natural way to multiply two things in the set to get another thing in the set. Once you've seen enough of these things, you accept that that's what Mathematics is giving you, and you make your definitions accordingly.
The definitions commonly in use lead to a huge number of useful concepts and results. Linear combination, span, linear dependence/independence, basis, dimension for starters - does your proposed multiplication lead to any of those concepts, or to any other concepts even half as useful?


text:
Q: Explanation for angular 2 package.json file I'm not willing to use typescript compiler provided in angular 2 quick start guide and will use gulp.js instead. However there are few questions I have about package.json file provided on angular website:
{
  "name": "angular-starter",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "systemjs": "0.19.6",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.10"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^1.3.1",
    "typescript": "^1.7.3"
  }
}

I'm sure that few things like tsc, tsc:w script comands alongside typescript devDependency can be safely removed, but am not sure about purpose for things like concurently dependency as well as dependency section in general, could you guys provide more info on all dependencies that follow angular2? I tried looking these up in quickstart guide along apendixes, but had no luck as they are very short.

A: concurently is and npm package which allows to run multiple CLI commands in one shot, see line below in package.json. concurrent command is coming from concurrenlty. You can remove that safely.
"start": "concurrent \"npm run tsc:w\" \"npm run lite\" "

dependency section in package.json file lets you keep track of project dependencies. Using reference of these packages in dependency section allows you to use module bundler like webpack, browserify etc. It also keeps your project linked to specific versions of each of these packages if new version introduce any breaking changes etc. Having this section in package.json file lets you remove packages directory (node_modules) to be under source control. Installing these packages again on lets say another machine requires only package.json and dependency section in it.
For each package in dependency section search npmjs website for more details.

A: Well adding some points with @nexus23's answer. my answer is not completed i know but for comment it is too long so posting as answer hope this will help somene.
Package.json is the important file for the project where you import our dependencies list which you used in your project.
Basically there are three types of dependencies

*

*Dependency

*DevDependency

*peerDependency
for more documentation refer here in the answers.
now come to the point i.e answer to this question. there are few dependencies which we have to include for make our angular2 project run.which is listed below.

*

*angular2 -- is the basic file for the angular2 project. which is most important file for our project. (stable latest version is angular2 beta)

*systemjs -- is the Universal dynamic module loader - loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS. Works with both Traceur and Babel.
we use systemjs Config for setup the baseUrl, to Import  main file etc in our main file i.e index.html like following:
<script>
  System.config({
    baseURL: '<%= APP_BASE %>',
    paths: {'*': '*.js?v=<%= VERSION %>'},
    defaultJSExtensions: true
  });
</script>


text:
Q: Как с анимацией движения поменять местами два блока? Надо сделать так
А у меня получается так (CodePen)

let isSwitched = false;
$('.switchers:last-child').on('click', function() {
  if (!isSwitched) {
    $('.switchers:first-child').animate({
      left: 'none',
      right: '5px'
    }, 500);
    $('.switchers:last-child').animate({
      right: 'none',
      left: '5px'
    }, 500);
    isSwitched = false;
  }
  else if (isSwitched) {
        $('.switchers:first-child').animate({
      right: 'none',
      left: '5px'
    }, 500);
    $('.switchers:last-child').animate({
      left: 'none',
      right: '5px'
    }, 500);
    isSwitched = true;
  }

});
* {margin: 0;padding: 0;}
main {
  background-color: #121212;
  width: 100vw;
  height: 100vh;
}
.switcher {
  position: absolute;
  width: 150px;
  height: 25px;
  border: 1px solid #fff;
  right: 45vw;
  top: 45vh;
}
.switchers {
  width: 60px;
  height: 15px;
  border: 1px solid #fff;
  position: absolute;
  top: 4px;
  cursor: pointer;
}
.switchers:first-child {
  left: 5px;
  background-color: #fbfbfb;
}
.switchers:last-child {right: 5px;}

Как видите, правый блок идет влево, но левому блоку вообще все по левому и он стоит на месте, не могу понять почему, как сделать чтобы эти два блока менялись местами с анимацией движения?

A: Нужно анимировать соответственные свойства - left значит left, а не менять его на right.

let isSwitched = false;
$('.switchers:last-child').on('click', function() {
  if (!isSwitched) {
    $('.switchers:first-child').animate({
      left: '84px',
    }, 500);
    $('.switchers:last-child').animate({
      right: '84px',
    }, 500);
    isSwitched = true;
  }
  else if (isSwitched) {
    $('.switchers:first-child').animate({
      left: '5px'
    }, 500);
    $('.switchers:last-child').animate({
      right: '5px'
    }, 500);
    isSwitched = false;
  }
})
* {margin: 0;padding: 0;}
main {
  background-color: #121212;
  width: 100vw;
  height: 100vh;
}
.switcher {
  position: absolute;
  width: 150px;
  height: 25px;
  border: 1px solid #fff;
  right: 45vw;
  top: 45vh;
}
.switchers {
  width: 60px;
  height: 15px;
  border: 1px solid #fff;
  position: absolute;
  top: 4px;
  cursor: pointer;
}
.switchers:first-child {
  left: 5px;
  background-color: #fbfbfb;
}
.switchers:last-child {right: 5px;}


text:
Q: How come I can play audio in my ESP8266? I'm currently messing with the ESP8266Audio Library. I uploaded a sketch to my ESP8266 that uses a HTTP stream of MP3 from the web and plays it using some MP3 decoder. So basically the loop looks like this:

*

*Read input from the web

*Decode next frame

*Get a sample

*Consume the sample

Now I wonder - the ESP8266 doesn't have several cores on it (as far as I know) - there's only one thread of execution. When the processor is busy reading from the TCP socket the next chunk of data, how is it that music is being played?
I'm asking this because I'm currently trying to use a 23LC1024 memory chip as RAM (This is a Microchip SPI RAM), and it's not going so well - the sound sounds broken, fragmented. My suspect is that it just takes time to the ESP to read and write data back and forth to the RAM chip. So I'm currently trying to understand what happens in each step to try to get a picture of the timings of the whole process..

A: 'only one thread of execution' - not quite. Whilst the esp8266 has only one processor core, you can have multiple threads of execution concurrently. I've not looked at the code you're referring to, but the 'usually' methods are:

*

*dma. This is a hardware peripheral that moves a block of data from ram to/from a peripheral (or ram). Your code tells the dma controller where the block of ram is and what peripheral. You tell the peripheral to talk to the dma controller. For example, the I2S peripheral for digital sound (not sure if the esp8266 has this, the esp32 does) when it needs another sample to send, it requests this from the dma controller (this is all done in hardware on the chip) and the dma controller grabs it from ram and gives it to the peripheral. Rinse and repeat. Once set up, the cpu does not need to intervene. The dma controller can interrupt when it is finished.

*Interrupts. An ISR is another thread of execution. You can have multiple ISRs and thus multiple threads of execution. Just that only one is executing at a given instant. You could set up a timer interrupt and the timer ISR reads a value from ram and outputs it.
Both these techniques will probably use what is called a 'pin-pong' buffer. This involves two buffers (or arrays or blocks of memory- however you like to refer to them). Whilst one buffer is being used to output the data, the other is being filled with the next. The idea is that you can fill the one buffer in the time it takes to output the other buffer. Once done, you swap the buffers - the one you just filled is being output and the one that was being used for output now gets loaded with the next load of audio samples. Rinse and repeat.
There other techniques as well, some are just a variation of what I've described.
Tasks like your WiFi are running in the background as another thread of execution. It most likely uses interrupts and dma to do its work.
With the esp8266 the software framework allows the use of FreeRtos - this manages multiple threads of execution. On the esp32 it manages the multiple cores as well.


text:
Q: Rails Carrierwave Base64 image upload What is the best way to upload an image from a client to a Rails backend using Carrierwave. Right now our iOS developer is sending in the files as base64, so the requests come in like this:
"image_data"=>"/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAHqADAAQAAAABAAAAHgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAeAB4DAREAAhEBAxEB/8QAHwAAAQUBAQE....

So, my question is really two questions. Should I tell him to send in a different file format? If base64 is the right way to send these files in, then how do I deal with them in carrierwave?

A: Old question but I had to do a similar thing, upload image from base64 string which was passed on via a json request. This is what I ended up doing:
#some_controller.rb
def upload_image
  set_resource
  image = get_resource.decode_base64_image params[:image_string]
  begin
    if image && get_resource.update(avatar: image)
      render json: get_resource
    else
      render json: {success: false, message: "Failed to upload image. Please try after some time."}
    end
  ensure
    image.close
    image.unlink
  end
end

#some_model.rb
def decode_base64_image(encoded_file)
  decoded_file = Base64.decode64(encoded_file)
  file = Tempfile.new(['image','.jpg'])
  file.binmode
  file.write decoded_file

  return file
end

A: I think that one solution can be to save the decoded data to file and then assign this file to mounted uploader. And after that get rid of that file.
The other (in-memory) solution can be this one:
# define class that extends IO with methods that are required by carrierwave
class CarrierStringIO < StringIO
  def original_filename
    # the real name does not matter
    "photo.jpeg"
  end

  def content_type
    # this should reflect real content type, but for this example it's ok
    "image/jpeg"
  end
end

# some model with carrierwave uploader
class SomeModel
  # the uploader
  mount_uploader :photo, PhotoUploader

  # this method will be called during standard assignment in your controller
  # (like `update_attributes`)
  def image_data=(data)
    # decode data and create stream on them
    io = CarrierStringIO.new(Base64.decode64(data))

    # this will do the thing (photo is mounted carrierwave uploader)
    self.photo = io
  end

end

A: You can easily achieve that using Carrierwave-base64 Gem you don't have to handle the data yourself, all you do is add the gem and change your model from
mount_uploader :file, FileUploader

to
mount_base64_uploader :file, FileUploader

and thats it, now you can easily say:
Attachment.create(file: params[:file])


text:
Q: WIFI of Toshiba Satellite C55-A is slow to unusable I installed Ubuntu and my wifi worked flawlessly for about a week. Then one day it was slow to the point of unusable and so it remains until now. The problem is not the network itself as my desktop has perfectly fine wifi. I uninstalled Ubuntu and reinstalled  - this did not fix the problem. I've read a ton of very confusing answers proporting to solve this problem and I have spent a lot of time copying a hodgepodge of code from these answers to the terminal. Nothing has worked. I tried to install Fedora and it wouldn't install so I'm stuck with Ubuntu. help! :)
edit: I also bought a panda wireless USB adapter to solve this problem but it doesn't fix it. the connection is still slow to the point of timing out.
Edit: I just installed MINT and the same issue arises. Regardless I'm confident it isn't the network or the laptop I'm on. When I connect via a physical connection it works just fine and as i said, the wireless worked prior. It also worked when I was using windows on the same machine.

A: Your wireless interface is softblocked
Try sudo rfkill unblock wlan0

A: There's a few things you can try, but honestly this is very network card dependent; it would be helpful to post the output of lspci and dmesg to check for sure. Looking online, it appears that this laptop has an Atheros 9k series card.
I happen to have a card in the same series, and I've noticed it will get stuck sometimes in a low-performance mode after a suspend, which shows up readily in the dmesg output (I don't have the issue right now, so I cannot provide an example); rebooting a couple of times usually fixed it however, so I'm surprised that yours persisted across multiple reboots. I've had the problem survive a couple of reboots and suddenly start working, but I haven't tracked down the cause. I did notice that rebooting to Windows would always fix the issue, so it may related to some initialization. I know this is probably not the fix you wanted, but if you still have Windows on the machine it's worth a shot.
Removing and reinserting the module (sudo modprobe -r ath9k and sudo modprobe ath9k respectively) didn't seem to fix it, but if the card got stuck the output in dmesg would be different than normal.
However, given that the Panda devices seem to be ralink or realtek, this doesn't explain why the external adapter was slow as well -- there is probably another configuration issue at play there.


text:
Q: Excel Formula to search with this criteria This is my data

How do i calculate the total of all 'w add' that have non-blank 'g minus' value. For example, in the image i would add 5.61 and 160.11 and store it in a single value. i have no idea how to do this with SUMIF

A: You can try the following:
=SUMIF(D2:D15,"<>",A2:A15)

The <> checks if the cells are not blank


text: Q: [AWS Cognito]: How to send Reset Password one-click link instead of verification code Using the ForgotPassword API of AWS Cognito, we can send a verification code to the end-users. How can we send a one-click Reset password link to the end user instead of this verification code?


text:
Q: Append List of FilesTo Binary Is there a way to append a list of files as an executable to the file itself such that the file is still executable?
For example let's say I have 2 files file1 and file2.  How might I append the the files in a way to the binary.  Again this is a simple example, I would like to have a cross Operating System way to extract Unix and Windows files.  Cross operating system way to append zips (or tar.gz) to a file only to extract it later.
The following illustrates how the files might be extracted and or created.
create ./a.exe ./output.exe file1 file2

extract output.exe

Downvoters please leave comments
copy /b test.exe+test.txt testwithtext.exe
cp /bin/ls test;cat /etc/hosts >> trst

A: On Linux and (which uses the ELF file format for executables) and Mac OS X (which uses Mach-O), and some other systems, you can simply append data to an executable and it will still run.  For example:
cp /bin/ls foo
cat /etc/hosts >> foo
./foo

This will run just like ls but the file also contains a text file at the end.

A: In principle, you could accomplish this by attaching the source as an extra unused section in the binary. For instance, on Linux (or other ELF systems using GNU binutils), we could embed this in a source section:
objcopy yes --add-section source=yes.c yes

and to extract it:
objcopy yes --only-section source --set-section-flags source=alloc -O binary yes.c

Similarly, on Mac OS X, we can pass some extra options to the linker to have it create the section:
gcc -Wl,-sectcreate,source,yes.c,yes.c yes.c -o yes

(Note that the source file name shows up twice in the linker option; this is not a typo! Sections in a Mach-O executable have both a segment and a section name; I'm using the filename as the section name here.)
and to extract it:
otool -s source yes.c -X yes

(This unfortunately gives output as a hexdump, rather than raw data. You'll have to massage it a bit to get it back to text.)

That being said, this is all incredibly silly. Don't use this as a serious method of distributing source code. Embedding the source in an executable is a party trick, not a useful technique.

A: *

* Write a program to read the source code file

*

*Write it to convert line breaks into escaped characters and deal with quotes and other such characters

*Write it to output it as a character array embedded in an appropriate place in the source code and written out as a new file.

* Configure your maker/builder to call the rewriter program to create the new file and then compile and build from the new file.

Note:  This does not meet the strict requirement that the code be "appended" nor a (possible but unstated) requirement that it be "as-is" and unescaped.
Does it have to be C?  Question text does not say the language, though the tag implies it.
If it were Java, you would just build a jar which would have the "executable" and the source as two files in the jar which is itself executable.

A: A possible solution is to create an executable file that will accept the list of paths to the executables to be run in sequence .
eg:runall /home/a.exe /home/output.exe

A: Just pack them inside a zip. ZIP is a cross platform container that can contain multiple files.
This is really the best solution to your problem.
You can also use a self extracting archive using some archiving tool like 7-zip. That is the fastest way to get two executables inside another executable.


text:
Q: How to solve the trouble with running javascript in asp.net app (WebForms) after postback? I have javascript, that scrolled floating block on my web page in asp.net app. After postback script doesn't work. How to solve the problem?

A: You can call your java script function after postback
    Page page = HttpContext.Current.Handler as Page;
    ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "Your Function Name()");


text:
Q: How to detect when dbus app exits or craches? How can a dbus user get notified when the dbus service it is using exits/crashes/restarts?
The tutorial suggests there is a way to do this, but in the specification I only found a signal intended for the name owner.
The dbus tutorial says:

Names have a second important use, other than routing messages. They are used to track lifecycle. When an application exits (or crashes), its connection to the message bus will be closed by the operating system kernel. The message bus then sends out notification messages telling remaining applications that the application's names have lost their owner. By tracking these notifications, your application can reliably monitor the lifetime of other applications.

The dbus specification has a section about the NameLost signal:

org.freedesktop.DBus.NameLost
This signal is sent to a specific application when it loses ownership of a name.

A: One way to find this out is to listen for the org.freedesktop.DBus.NameOwnerChanged signal, as specified in the D-Bus specification
Your client needs to have some logic implemented to analyse the arguments of the signal to figure out when a name has been claimed, when a service has been restarted, when it is gone etc. But the above signal can be used to receive the relevant information at least.
In your handler function you can check if the name argument matches the service name you want to know about. If the old_owner argument is empty, then the service has just claimed the name on the bus. If new_owner is empty then the service has gone away from the bus (for whatever reason).


text:
Q: How to optimize the computation of a for loop using SIMD? I am trying to accelerate a stereo matching algorithm on ODROID XU4 ARM platform using Neon SIMD. For this puropose I am using openMp's
pragmas.
 void StereoMatch:: sadCol(uint8_t* leftRank,uint8_t* rightRank,const int SAD_WIDTH,const int SAD_WIDTH_STEP, const int imgWidth,int j, int d , uint16_t* cost)
  {

   uint16_t sum = 0;
   int n = 0;
   int m =0;
      for ( n = 0; n < SAD_WIDTH+1; n++)
      {

     #pragma omp simd
     for(  m = 0; m< SAD_WIDTH_STEP; m = m + imgWidth )
         {

        sum += abs(leftRank[j+m+n]-rightRank[j+m+n-d]);

         };
         cost[n] = sum;
         sum = 0;

  };

I am fairly new to SIMD and openMp, I understood that using the SIMD pragma in the code will direct the compiler to vectorize the subtraction, but when I executed the code I noticed no difference. What should I add to my code in order to vectorize it ?

A: As said in the comments, ARM-Neon has an instruction which directly does what you want, i.e., compute the absolute difference of unsigned bytes and accumulates it to unsigned short-integers.
Assuming SAD_WIDTH+1==8, here is a very simple implementation using intrinsics (based on the simplified version by @nemequ):
void sadCol(uint8_t* leftRank,
            uint8_t* rightRank,
            int j,
            int d ,
            uint16_t* cost) {
    const int SAD_WIDTH = 7;
    const int imgWidth = 320;
    const int SAD_WIDTH_STEP = SAD_WIDTH * imgWidth;

    uint16x8_t cost_8 = {0};
    for(int m = 0; m < SAD_WIDTH_STEP; m = m + imgWidth )  {
        cost_8 = vabal_u8(cost_8, vld1_u8(&leftRank[j+m]), vld1_u8(&rightRank[j+m-d]));
    };
    vst1q_u16(cost, cost_8);
};

vld1_u8 loads 8 consecutive bytes, vabal_u8 computes the absolute difference and accumulates it to the first register. Finally, vst1q_u16 stores the register to memory.
You can easily make imgWidth and SAD_WIDTH_STEP function parameters. If SAD_WIDTH+1 is a different multiple of 8, you can write another loop for that.
I have no ARM platform at hand to test it, but "it compiles": https://godbolt.org/z/vPqiYI (and the assembly looks fine, in my eyes). If you optimize with -O3 gcc will unroll the loop.


text:
Q: Nltk lesk issue I am running a simple sentence disambiguation test. But the synset returned by nltk Lesk for the word 'cat' in the sentence "The cat likes milk" is 'kat.n.01', synsetid=3608870.
(n) kat, khat, qat, quat, cat, Arabian tea, African tea (the leaves of the shrub Catha edulis which are chewed like tobacco or used to make tea; has the effect of a euphoric stimulant) "in Yemen kat is used daily by 85% of adults"
This is a simple phrase and yet the disambiguation task fails.
And this is happening for many words in a set containing more than one sentence, for example in my test sentences, I would expect 'dog' to be disambiguated as 'domestic dog' but Lesk gives me  'pawl' (a hinged catch that fits into a notch of a ratchet to move a wheel forward or prevent it from moving backward)
Is it related to the size of the training set which is in my test only few sentences?
Here is my test code:
def test_lesk():
    words = get_sample_words()
    print(words)
    tagger = PerceptronTagger()
    tags = tagger.tag(words)
    print (tags[:5])
    for word, tag in tags:
      pos = get_wordnet_pos(tag)
      if pos is None:
          continue
      print("word=%s,tag=%s,pos=%s" %(word, tag, pos))
      synset = lesk(words, word, pos)
      if synset is None:
          print('No synsetid for word=%s' %word)
      else:
          print('word=%s, synsetname=%s, synsetid=%d' %(word,synset.name(), synset.offset()))


text:
Q: Drifting output I have an old power supply that still works, got it from tandy when they were closing down it use to power the display unit of car head units, anyways  the output voltage has drifted up from 12 to 22 vdc so i took it apart as you do to find a little pot it there that wasn't right so i replaced it with what i had at hand but the output doesn't change so if you look at the pictures the transistor looks blackened on the board but i cannot find the same to replace it.... what should i do?
RS found it and gave me a replacement https://uk.rs-online.com/web/cpo/3136916/
https://uk.rs-online.com/web/p/bjt-bipolar-transistors/1686073/
I don't have any of them at hand but i do have  I want its output to be 12vdc like it use to be. I'm guessing it's not regulating itself any more
The pictures are of the power supply
LM317T W994F9505
P88S68 K3679 01
1C21CH FQN 24N50
1C21CL FQA 24N50
MTP8P10R022
MTP12N10925
T 5K 79015P
831 AN7815
NF820 B20100G
pictures
https://drive.google.com/file/d/1h7aVrYnnCxYEgNnTdFzGmcU_3-IrjAjj/view?usp=sharing
https://drive.google.com/file/d/1QAjZzo3oWcA6zCelFyhaVl_cgqMN7Aga/view?usp=sharing
https://drive.google.com/file/d/1wVt9P0TJSX8mqg_NA6NpAidRibxFAvas/view?usp=sharing

A: Found it.
The model number is about the same as the visible PCB number.
Here is a forum that discusses repairing of a Samlex 1203 power supply. The PCB on the page looks nearly identical to yours.
One tricky issue is that the web page is all in German, but not to worry, google translator can take care of that. (Use the translated link below)
https://translate.google.com/translate?hl=en&tab=TT&sl=de&tl=en&u=https%3A%2F%2Fwww.mikrocontroller.net%2Ftopic%2F384176
The power supply on this page is a 220/240VAC version, yours may be similar even if the input voltage is different, (likely just the transformer would be different).
There seems to be two slightly different versions of the schematic.  You should be able to verify which one matches by just checking the components.
Another thing I noticed is that your board looks like there have been a number of repairs made, maybe even a missing (or broken off) diode in the bottom corner near the red transformer wires, it may be good to check on that issue first.
A few more positive things:
1) All of the component values are included on the schematics.
2) One of the schematics has test voltages listed, so  that should go a long way to help with troubleshooting.
3) Someone redrew a full schematic (further down the page) that is much more readable.
This should give you a very good start at repairing your unit. Comparing the listed test voltages should give you more clues as to the problem on your board.
If you do get stuck add a comment below this answer.


text:
Q: How fast is MySQL replication? I'm considering setting up replication of our mysql db to be able to have local slaves in each of our branch offices, while having the master in the main office to improve application performance (significantly) at our branch offices.
The db itself isn't that large (<1gb) but I'm wondering; considering 200-300 record updates/min tops: how fast is replication? (assuming, first, a 5mb generic dsl connection, faster if necessary - trying to keep costs as low as possible but the money is there for more)
Are whole tables replicated in batches? Is the replication done, on demand, as each record in a table is updated (from the docs, I think I'm seeing that it's configurable)?
Notes:

*

*I'm thinking 1 master, 2 slaves (2 branch offices for now) setup as in the docs here except that it's an app, not a web client

*Any update done on the master needs to replicate to the other slaves in <10 mins.

*All of this assumes that I can get our ORM (DevExpress XPO) happy with the concept of reading from the slave and writing to the master.

A: Replication in MySQL is pretty quick to get the data to the slave (quicker than you'll be able to run the UPDATE on the master, and switch to another window to run a SELECT on the slave, if (and only if) the network connections are all up and everything's running OK.  Any DSL-class connection should be fine for the general case of your regular small queries, but large insert/update queries can take a little while to copy, and re-synchronisation in the event of a replication stuffup (and MySQL is viciously prone to those, unfortunately) will take a while (copying your whole database from the master again).  There are tricks to limiting the impact of resynchronisation on your master, like putting your MySQL on LVM so you can do a very quick lock/snapshot and rsync the snapshot contents to the slave, but ultimately a resync is going to suck.

A: Replication on the slaves side is handled by two independent threads.

*

*The log reader process, which connects to the master, receives each data modifying statement, writes it to the relay log.

*The sql writer process, which takes new items from the relay log, commits the statements on the slaves database, then moves the slave pointer past that statement to indicate receipt of the query.

Replication latency is limited by IO, firstly the IO on the slave database to apply the transactions from the relay log (which may involve complex SQL queries) and secondly by the IO on the master to read it's binlog and transmit it to each slave.
MySQL replication increases read query capacity but does not increase query write performance, which is gated at the speed IO's can be flushed to the binlog on both the master, and the slave

A: MySQL replication happens as close to real-time as possible, as limited by disk and network I/O.  The slaves open a socket to the master, which is kept open.  When a transaction occurs on the master, it gets recorded in the binlog, and is simply replayed on the slave(s).  If the socket between master and slave is interrupted, the binlog is replayed for the slave upon the next successful connection.
Multi-master replication does the same thing, but in both directions.
Some basic calculations will assist you in making a better determination of your bandwidth needs.
Average transaction size * number of slaves * updates/minute = bandwidth needed
Hope this helps.


text:
Q: Got Http response code 403 while accessing this paypal API "https://api.sandbox.paypal.com/v1/payments/payouts" I an trying to implement this paypal payout API. When i was trying to check the api it gives
  -data: "{"name":"AUTHORIZATION_ERROR",
   "debug_id":"27b145efd5d07","message":"Authorization error occurred.",
  "information_link": "https://developer.paypal.com/docs/api/payments.payouts-batch/#errors"}"

Please suggest me this API is working for India (currency INR) or not. If it is not working then let me know alternative for this API.
Basically i want to send amount from one account to another account with the help of API.

A: There may be multiple reason.
1. This API will need to enable by paypal.
2. US merchants— To enable Payouts, you can complete either of the following actions:
Contact your Account Manager or PayPal customer support.
Enable Payouts from My Account:
Log in to the Developer Dashboard and go to My Account.
Under Permissions name, locate Payouts and click the Enable link.
Click Enable, complete the form and click Submit. When you've been approved, you'll receive an email from a PayPal representative.
3. Non-US merchants— To enable Payouts, contact your Account Manager or PayPal customer support.
4. Check whether this API will be available for your country. Some countries it is not allowed to transfer  money (wallet amount) from one account to another.
For information Click here


text:
Q: Web Scraper: I need help pulling out the text in between the attribute... Any help would be appreciate Link =
https://www.imdb.com/search/title/?title_type=video_game&amp&sort=user_rating,desc&amp&after=1&amp&ref_=adv_nxt
My Goal
I need to collect all of the video game titles, genre, description, type, and release year on every page.
My Problem
https://www.imdb.com/search/title/?title_type=video_game&sort=user_rating,desc&start=9951&ref_=adv_nxt
total_games = 26,215
The "start=9951" changes to "after=WzUuNSwidHQ4NjcxMDM2IiwxMDAwMV0%3D" on the next page iteration
I was originally going to loop: pages = np.arange(1, total_games, 50), every page from 1 to 26215 every 50 entries, but then I stumbled upon this problem.
HTML: < a href="/search/title/?title_type=video_game&sort=user_rating,desc&after=WzUuNSwidHQxODAxMDU0IiwxMDA1MV0%3D&ref_=adv_nxt" class="lister-page-next next-page">Next »< /a>
How do I take out a portion of the href link and add to the overall link to loop?
Outcome:
"https://www.imdb.com/search/title/?title_type=video_game&sort=user_rating,desc&" + "after=WzUuNSwidHQ4NjcxMDM2IiwxMDAwMV0%3D" + "&ref_=adv_nxt"
Bold: This is the part of HREF I want to grab on each page to iterate to the next page/This is inside the href that changes.
Any solutions would be greatly appreciated!

A: You can save yourself the headache and simply check if the "Next" button exist in the HTML. If it does you just extract the href and follow the link else you've reached the last page.
Assuming you're using BeautifulSoup and you've prepared your soup:
next_link_tag = soup.find('a', {'class': 'next-page'}) # Find the a tag with a class "next-page"
if next_link_tag: # If there is any
    next_link = next_link_tag.get('href') # Get the href (Don't forget to prepend it with 'https://www.imdb.com/')
else:
    pass # There's no next page. Act accordingly


text:
Q: D3: How to dynamically refresh a graph by changing the data file source? How do I update the data on demand by changing the file d3 accesses? With a click, for example, it would read data from a new data file and add more nodes to the graph like AJAX.
I use d3.tsv to read in data.tsv, one of many files of the same format.
I made a simple graph to illustrate my question. Thanks in advance.

update the graph

A: Try this.
var width = 400,
        height = 200;

    var x = d3.scale.linear().range([0, width]),
        y = d3.scale.linear().range([height, 0]);

    var svg = d3.select("body")
      .append("svg")
        .attr("width", width)
        .attr("height", height);

var dataSource = 'data.tsv',
dataSource2 = 'data2.tsv';

function updateChart(sourcefile) {

    d3.tsv(sourcefile, function(error, data) {
        if (error) console.warn(error);
        x.domain(d3.extent(data, function(q) {return q.xCoord;}));
        y.domain(d3.extent(data, function(q) {return q.yCoord;}));

        svg.selectAll(".dot")
            .data(data)
            .enter().append("circle")
                .attr("r", 10)
                .attr("cx", function(d) { return x(d.xCoord); })
                .attr("cy", function(d) { return y(d.yCoord); })
    });
}

updateChart(dataSource);

//here is where you change the data..
d3.select(#button).on("click", function() {
updateChart(dataSource2)
})


text:
Q: Printing non string values in haskell How can i print a value that is a non string type to console? The type is below.
data Expr = Var String | Con Bool | Uno Unop Expr | Duo Duop Expr Expr | List [Expr]
 deriving Show

I have a list of the above type values and i would like to print them to screen each on a separate line( not the classic list view). Thanks

A: Just use print on each element of your list:
mapM' print exprs


text:
Q: Trying to understand how to formulaically sum a series I thought this was as simple as calculating the area under the linear equation, but I get an answer that differs from the actual sum of values when I try.
I'm starting with a given number - 50,000 as an example and multiplying it by 0.995, and then taking that result and multiplying again by 0.995, and so on over 29 iterations (30 iterations if you consider the 50,000 an iteration). I want to sum of the results of each iteration. The formula for the iterations ought to be 50,000*(0.995^n) where n [0,30].
The area of said line, should be (I believe) 50,000 * 30 - (6,74.613 *30)/2, which is 1,398,531, but the actual sum is 1,396,158.
The subtracted portion is the triangle defined by the height: 50,000 - the value of the last iteration (43,235), multiplied by the base (30), divided by 2.
I'm missing something, right?

A: I think, i solved the puzzle.
We consider the function $f$, given by $f(x) = 50\; 000\cdot 0.995^n$, for $n$ in $0,1,2,\dots,29$ and plot a bar diagram for it. There are many bars, the first one has the height $f(0) = 50\; 000$, the last one has the height $f(29)=43235.3865283767...$ and this differs from the fifty T by $67\color{red}{6}4.61347162332...$ , so we may try to approximate the sum
$$
\sum_{0\le n< 30}S\; r^n=S\frac{1-r^{30}}{1-r}\ ,\qquad S=50\; 000\ ,\ r=0.995\ ,
$$
seen as the "area of the many bars of width one" with the area of the figure obtained by assuming that the bars are "aligned", so that exactly one triangle is missing from the rectangle with height $S=50\; 000$, and width $30$. Well, this is not the case, we have exponential decay, not linear decay, the exact result is thus, using a "calculator" (here sage)
sage: S, r = 50000, 0.995
sage: sum( [ S*r^n for n in [0..29] ] )
1.39615808085304e6
sage: S*(1-r^30)/(1-r)
1.39615808085304e6

To see the difference, let us take $r=0.95$ instead, and raw-plot the function...
? plot( n=0, 29, 50000 * 0.95^n )

    50000 "_'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''|
          | x                                                            |
          |  "_                                                          |
          |    "_                                                        |
          |      x_                                                      |
          |        x                                                     |
          |         "x                                                   |
          |           "x                                                 |
          |             "x_                                              |
          |                x_                                            |
          |                  "_                                          |
          |                    "x_                                       |
          |                       "x                                     |
          |                         "x_                                  |
          |                            "x_                               |
          |                               ""x_                           |
          |                                   "x_                        |
          |                                      ""x_                    |
          |                                          ""x__               |
          |                                               "xx__          |
          |                                                    "xx__     |
11296.777 |.........................................................""xx__
          0                                                             29
?

Here we expect a bigger difference between the exponential decay and the linear decay...


text:
Q: Rails 4 | Assign Role to User in Form using Bitmask | RoleModel I got stuck on the following issue - I suspect there is a simple solution to it, but I just can't figure it out.
I am using Role Model Gem with Rails 4.
All works well, and the assigned roles are stored perfectly well in the roles_mask attribute (integer) of the user model as internal bitmask.
Now, I would like that Admins can assign as well as remove Roles from users via a FORM (view). I am not a Rails Ninja, so there might be a trick to do this.
According to the Doc, I can do the following:
# role assignment
>> u.roles = [:admin]  # ['admin'] works as well
=> [:admin]

# adding roles (remove via delete or re-assign)
>> u.roles << :manager
=> [:admin, :manager]

So that is understood.
And my approach was to query for all valid roles in the form:
# get all valid roles that have been declared
>> User.valid_roles
=> [:admin, :manager, :author]

Then list them as checkbox. Once the form gets submitted I assign / remove roles.
The question:
Is that the right approach, does this even work, and if so how?

A: Since I had the problem not once I figured out a way - here is the solution:
More details here.
Many roles per user
I assume in this answer that you have roles in form of symbols (below I modified this solution in a way that it works with symbols) - so to work with Pundit in case you are using it.
# in models/user.rb
ROLES = [:admin, :manager, :general, :custom_role, :another_custome_role, :banned]

It is possible to assign multiple roles to a user and store it into a single integer column using a bitmask. First add a roles_mask integer column to your users table.
rails generate migration add_roles_mask_to_users roles_mask:integer
rake db:migrate
Next you'll need to add the following code to the User model for getting and setting the list of roles a user belongs to. This will perform the necessary bitwise operations to translate an array of roles into the integer field.
# in models/user.rb
def roles=(roles)
  self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end

def roles
  ROLES.reject do |r|
    ((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
  end
end

Here a tiny modification to make it work with Rolify & Pundit
  def roles=(roles)
    self.roles_mask = (roles.map { |x| x.to_sym } & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
  end

If you're using devise without strong parameters, don't forget to add attr_accessible :roles to you user model.
If you're using devise with strong_parameters, either as a gem in a Rails 3 app, or as is built-in in Rails 4, dont forget to add the roles to the permitted list in the controller
class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:email, :password, :password_confirmation, roles: [])}
  end
end

See the section on strong parameters in the Devise documentation.
You can use checkboxes in the view for setting these roles.
<% for role in User::ROLES %>
  <%= check_box_tag "user[roles][#{role}]", role, @user.roles.include?(role), {:name => "user[roles][]"}%>
  <%= label_tag "user_roles_#{role}", role.humanize %><br />
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>

Finally, you can then add a convenient way to check the user's roles in the Ability class.
# in models/user.rb
def is?(role)
  roles.include?(role.to_s)
end

# in models/ability.rb
can :manage, :all if user.is? :admin

See Custom Actions for a way to restrict which users can assign roles to other users.
This functionality has also been extracted into a little gem called role_model (code & howto).
If you do not like this bitmask solution, see Separate Role Model for an alternative way to handle this.


text:
Q: Python NameError, works fine on other machines I have a weird python NameError that is confounding me, and completely stopping the work on the project I am working on.  When I run the code on my machine running python 2.7.1 I get a NameError, but a coworker can run the code fine on his machine.  The indentation is all spaces around the line the error occurs as well.  Here's the code
"""File: GatoTest.py"""
""" bunch of imports """
from Gato import *

def usage():
  """irrelevant code"""
  app = AlgoWin()

And the code in Gato does include a class AlgoWin with an empty constructor
class AlgoWin(Frame):
  def __init__(self, parent=None, graph_panes=None, paned=False, experimental=False):
    """irrelevant code"""

The error is thrown on the line app=AlgoWin(), and the exact message is
NameError: name 'AlgoWin' is not defined
I'm at a complete loss at this point, thanks in advance for any help or direction.

A: This seems like the import isn't importing the right code. Try using from Gato import AlgoWin (which is better practice anyway); you'll probably get an ImportError there.
Have you moved Gato.py? Check for any stray .pyc files that might be confusing the interpreter.

A: Do you have a Gato.py (or Gato.pyc) in your source tree that it shadowing the Gato you want to import?
Is the output of import Gato; print Gato.__file__ what you expect?


text:
Q: What does specifying a vector of means/standard deviations for rnorm do? The following line produces 1000 random draws from the normal distribution with mean 0 and sd 1.
rnorm(1000,0,1)
## [1] -0.3314116  2.3704895 -0.8110266  1.0777301 -0.8812868  0.3292315

The following line also produces 1000 draws, but now the mean varies between 0 and 100 for each observation.
rnorm(1000,c(0,100),1)
## [1]  -1.12269954  98.83932359   0.07735428  99.91774166   0.60986243 101.50529435

So what happens in this case? What is the general logic?
rnorm(1000,c(0,100),c(1,10))

Thank you for the link to vector recycling, that is one piece I was missing. Another is which combination of means and standard deviation are used. For example, does
rnorm(1000,c(0,100),c(1,10))

ever draw from the normal distribution with mean 0 and standard deviation 10? The below answer addresses this.

A: I created an example to express the third example in your question.
set.seed(1337)
x=rnorm(2000,c(0,100),c(1,10))
even=1:500*2
odd=0:499*2+1
mean(x[odd]) #0.00427
mean(x[even]) #99.5
sd(x[odd]) #1.01
sd(x[even]) #9.49

You can see that the function alternates between the first and second input of each vector. As Alex commented, if one of the vectors was a different length than the other (your second example), then the shorter vector would "recycle" the inputs until it is as long as the longer vector. So, rnorm(1000,c(0,100),1) is converted to rnorm(1000,c(0,1000),c(1,1)) by recycling the input of the second vector.


text:
Q: Show 2 initial items in a list view and then show all the items I have a list view which has to be populated with multiple elements. Initially, I want to display the first two elements and subsequently show the other elements when the user begins to scroll.
The code that I have is as follows:
ListView in XML
<LinearLayout
        android:id="@+id/layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <ListView
            android:id="@+id/options"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

ListView Item Definition
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="52dp"
    android:gravity="center_vertical"
    android:background="@color/white">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:inputType="textMultiLine"
        android:lines="2" />

</RelativeLayout>

Adapter :
String[] mobileArray = {"Android", "iPhone","Windows", "Mac", "Moto", "Oneplus", "Random A", "Random B", "Random C", "Random D"};

ListView listView = (ListView) getActivity().findViewById(R.id.options);

LinearLayout responseLayout = (LinearLayout) getActivity().findViewById(R.id.layout);

ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(), R.layout.item, R.id.text,mobileArray);

listView.setAdapter(adapter);

listView.setVisibility(View.VISIBLE);

responseLayout.setVisibility(View.VISIBLE);

In this example I want Android and iPhone to be visible initially and then the user should be able to scroll to the other options.
Currently all the options are visible, where am I going wrong?

A: I didn't try that, but what if you make custom adapter and in getView() will return null when you don't want item to be visible?

A: May be you need to assign list cell height dynamically. In order to display only first two items, each cell height should be half of the screen size.
Point size = new Point();
    Display display=getWindowManager().getDefaultDisplay();
    int screenWidth;
    int screenHeight;
    if(Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB_MR2)
    {
        screenWidth=display.getWidth();
        screenHeight=display.getHeight();
    }
    else
    {
        display.getSize(size);
        screenWidth = size.x;
        screenHeight=size.y;
    }
int halfScreenHeight = (int)(screenHeight*0.5);

You need to set the halfscreenHeight for the list item relativelayout.

A: Just create your own custom adapter and override getCount method so it return 2 when it is necessary. Then, when you need to show all the items you should set flag that notify that you have more items and after that call adapter.notifydatasetchanged
Something like this:
    class CustomAdapter extends BaseAdapter {
    private List elements;
    private boolean showAll;
    private int resId;

    public CustomAdapter(List elements, boolean showAll, int resId) {
        this.elements = elements;
        this.showAll = showAll;
        this.resId = resId;
    }

    @Override
    public int getCount() {
        if (elements == null) {
            return 0;
        } else if (elements.size() < 2 || showAll) {
            return elements.size();
        } else {
            return 2;
        }
    }

    public void setShowAll(boolean showAll) {
        this.showAll = showAll;
        notifyDataSetChanged();
    }

    @Override
    public Object getItem(int position) {
        return elements.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Todo inflate your element
        return null;
    }
}


text:
Q: Rewriting python script to work with python3 I have the following piece of code that I need help rewriting it to work with python3
from urllib2 import Request, urlopen

headers = {'Authorization': '< Enter your Basic Authorization string here >'}
request = Request('https://ssapi.shipstation.com/orders/orderId', headers=headers)
request.get_method = lambda: 'DELETE'

response_body = urlopen(request).read()
print response_body

A: Change the imports
try:
    from urllib2 import Request, urlopen
except ImportError:
    # python3
    from urllib.request import Request, urlopen

Also change the print
print(response_body)

Your code is now cross-compatible and should run on both Python 2 and Python 3.


text:
Q: Device ready function not firing alert? I'm attempting to use the cordova local notifications plugin and from what I can see it won't work until a device ready function is activated.
I've seen quite a few questions on StackOverflow and I've tried to implement the solution below, however when I build the app (Using PhoneGap build) the alert inside the device ready function simply isn't appearing.
I'll try to keep my code as minified as possible.
config:
<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns   = "http://www.w3.org/ns/widgets"
    xmlns:gap   = "http://phonegap.com/ns/1.0"
    id          = "com.phonegap.example"
    version     = "1.0.1" >

  <name>1.0.1</name>

  <description>
      hgfdngf
  </description>

  <author href="https://build.phonegap.com" email="*****">
      ****
  </author>

    <content src="index.html" />

    <plugin name="org.apache.cordova.device" />
    <plugin name="de.appplant.cordova.plugin.local-notification" />

</widget>

index.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <title>NRL</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300" rel="stylesheet">
    <link rel="stylesheet" href="css/main.css"> <!-- Link to main style sheet -->
    <script src="js/jquery-1.12.4.min.js"></script>
    <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css">
    <script src="js/jquery.mobile-1.4.5.min.js"></script>-->
    <script src="js/javascript.js"></script>
</head>

    <body onload="onLoad()">

</body>

</html>

JS:
function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
    alert("deviceready");
}

A: You need to reference cordova.js like this
 <script type="text/javascript" src="cordova.js"></script>

Replace path for your path to cordova.js


text:
Q: Solve the recurrence using backwards substitution Here is what I have so far for this recurrence relation problem.
$$
\left\lbrace
\begin{array}{l}
x(0) = 0 \\
x(n) =  x(n-1) + n
\end{array}
\right.
$$
I have tried substituting to get $x (n-1)  = x (n-2) + n-1$, but this is where I'm getting stuck at.

A: Let's compute some of the first terms
$$x_1=x_0+1=0+1=1$$
$$x_2=x_1+2=0+1+2=3$$$$x_3=x_2+3=0+1+2+3=6$$
We see a pattern! We can rewrite the formula for $x_n$ as $$x_n=\sum\limits_{k=0}^n k$$This sequence is known as the triangular numbers. The explicit formula for it is $$x_n=\frac{n\cdot(n+1)}2$$


text:
Q: Oracle SQL Developer doesn't start I've tried everything on this site, but I can't seem to start SQL Developer properly. I am using Oracle express edition and windows 7. My SQL Developer version is 4.1.3 and JDK version is jdk1.8.0_101.
It gets stuck on here and doesn't start:

I tried moving SQL Developer to different folders. I tried installing different versions. I tried everything on this site but nothing solves my problem or when something works it is temporary and next time I open it, it is stuck again.
Please help, and moderators please don't close my question because nothing on here works for me!

A: I faced this issue on Windows 10 system and Oracle SQL Developer v 18.1

Start -> Run -> %AppData%\SQL Developer\

It will open a folder in explorer. Delete this folder.
Now restart the SQL Developer. It will ask if you would like to import existing profile? Select 'No' and click Next.
SQL developer worked properly after that.

A: Go to your AppData folder under your Windows OS User's home directory.
Under there is a roaming profiles directory, and under that there should be a SQL Developer folder.
In THERE, you'll see a systemW.X.Y.Z... folder - rename that.
This stores the application settings, including things like your connections for a specific version of SQL Developer.
Try starting SQL Developer again.
You can go back into your renamed folder to recover things as needed if starting fresh fixes the issue.

A: close all sql developer instances
go in the directory %AppData%\SQL Developer\system..... rename all the files system_cache..
now start sql developer

A: In my case to run SQL Developer - needed to place SQL Developer folder to disk C:\ but not disk D:\


text:
Q: Multiple series calculation Let $n$ be a positive integer.
I would like to find a numerical evaluation of the convergent (!) series
$$
S_{n,s}=\sum_{k\in \mathbb Z^{n}}\frac{1}{(1+\vert k\vert^{2})^{s/2}},\quad s> n,
$$
where $\vert k\vert$ stands for the standard Euclidean norm in $\mathbb R^n$. As mentioned above,  the convergence is easily proven and follows from a comparison with an integral. However the numerical evaluation requires to take care of the small values of $\vert k\vert$. Maybe there is a close formula either for $S_{n,s}$ or for
$$
\tilde S_{n,s}=\sum_{k\in \mathbb Z^{n}\backslash\{0\}}\vert k\vert^{-s}.
$$
I am in fact interested in the case $n\ge 2$.

A: $\newcommand{\vpi}{\varphi}
\newcommand{\vp}{\varepsilon}$
We have
\begin{align*}
S_{n,s}&=\sum_{k\in \mathbb Z^{n}}\frac{1}{\Gamma(s/2)}\int_0^\infty u^{s/2-1}
e^{-(1+|k|^2)u}\,du \\
&=\frac{1}{\Gamma(s/2)}\,\int_0^\infty du\, u^{s/2-1}e^{-u}
\sum_{k\in \mathbb Z^{n}}e^{-|k|^2u} \\
&=\frac{1}{\Gamma(s/2)}\,\int_0^\infty du\, u^{s/2-1}e^{-u}
\Big(\sum_{k\in \mathbb Z}e^{-k^2u}\Big)^n \\
&=\frac{1}{\Gamma(s/2)}\,\int_0^\infty du\, u^{s/2-1}e^{-u}\,
\vpi(u)^n,
\end{align*}
where $\vpi(u):=\vartheta_3(0,e^{-u})$ and $\vartheta_a(u,q)$ is the elliptic theta function.
So, instead of an $n$-fold sum, we now only need to compute an ordinary integral of a special function.

E.g., it takes the Mathematica command NSum[] 22 sec to output the value $12.6028$ for the double sum $S_{2,2.5}$ computed according to its definition. In comparison, it takes Mathematica command NIntegrate[] only 0.054 sec to output the value $12.6001$ for the integral expression of this double sum, and only 0.023 sec to output the value $22.0645$ for the integral expression of the triple sum $S_{3,3.5}$. (I have not attempted an evaluation of a triple sum using NSum[]. Even for $n=2$, I tend to believe NIntegrate[] more than NSum[], which latter lacks in accuracy and speed even for ordinary sums.)
Here is a copy of the corresponding Mathematica notebook:

Added:
As pointed out in the comments and answer by Henri Cohen, the Mathematica calculations of the above integral expression for $S_{n,s}$ are probably faulty. This can be helped as follows. Note that the series
\begin{equation}
 \vpi(u)=\sum_{k\in \mathbb Z}e^{-k^2u}
\end{equation}
converges very fast if $u>0$ is bounded away from $0$. In particular, for any natural $m$ and all $u\ge\pi$
\begin{equation}
 \vpi_m(u)<\vpi(u)<\vpi_m(u)(1+\vp_m),
\end{equation}
where
\begin{equation}
 \vpi_m(u):=1+2\sum_{k=1}^{m-1}e^{-k^2u},\quad \vp_m:=\frac{2e^{-m^2\pi}}{1-e^{-5\pi}}<2.000001e^{-m^2\pi};
\end{equation}
here we used the inequality $\sum_{k=m}^\infty e^{-k^2u}\le\sum_{k=m}^\infty e^{-k^2\pi}$ and bounded the latter sum by the sum of a geometric series.
Using the Jacobi identity $\vpi(u)=\pi^{1/2}u^{-1/2}\vpi(\pi^2/u)$ for $u>0$ (which is an instance of the Poisson summation formula), we now represent $\vpi(u)$ as the sum of a series that converges very fast if $u>0$ is bounded away from $\infty$. In particular, for any natural $m$ and all $u\in(0,\pi]$
\begin{equation}
 \pi^{1/2}u^{-1/2}\vpi_m(\pi^2/u)<\vpi(u)<\pi^{1/2}u^{-1/2}\vpi_m(\pi^2/u)(1+\vp_m).
\end{equation}
Thus,
\begin{equation}
 S_{m;n,s}<S_{n,s}<S_{m;n,s}(1+\vp_m), \tag{$\ast$}
\end{equation}
where
\begin{align*}
 S_{m;n,s}&:=\frac{1}{\Gamma(s/2)}\,\int_\pi^\infty du\, u^{s/2-1}e^{-u}\vpi_m(u)^n \\
 &+\frac{\pi^{n/2}}{\Gamma(s/2)}\,\int_0^\pi du\, u^{s/2-1-n/2}e^{-u}\vpi_m(\pi^2/u)^n,
\end{align*}
so that now we only have to integrate elementary functions.
E.g., using $(\ast)$ with $m=2$, in 0.014 sec we get the approximate value $12.602759835$ for $S_{2,2.5}$, which agrees with Henri Cohen's Pari/GP calculation.

A: What follows is an answer to Iosif Pinelis, hence not directly to the OP, but
may be useful nonetheless.
1) Although the elliptic theta function is available in GP under the name mfTheta(),
I just discovered a bug (to be corrected this week-end), so I will not use it.
2) The correct way to sum in a stupid way (i.e., without using specific clever summation methods) in GP is the suminf command which stops when the summand becomes negligible,
hence is useable only for geometrically convergent series, not for $1/n^2$. Hence one could in principle write th(u)=1+2*suminf(n=1,exp(-n^2*u)) but this would fail for
two different reasons. First, the convergence for $u$ close to $0$ is too slow: for
this, we use the functional equation. Second, when $u$ is large, even exp(-u) will
underflow. Thus I first write the following:
th0(u) = if(u>1000, 1, 1+2*suminf(n=1, exp(-n^2*u)));
th(u) = if(u>Pi, th0(u), sqrt(Pi/u)*th0(Pi^2/u));
3) The integration process: the most robust method is the doubly-exponential
integration method, which in GP is the command intnum. But we must be careful about the endpoints:
-- At infinity, the integrand is like exp(-u) times something much less important, so
is coded [oo,1] (exponential decrease).
-- At 0, the integrand is asymptotic to a constant times u^{s/2-1-n/2}, the n/2
comming from theta.
Thus, the GP command that I use is:
S(n,s) = 1/gamma(s/2)*intnum(u=[0,s/2-1-n/2], [oo,1], u^(s/2-1)*exp(-u)*th(u)^n);
4) Concerning accuracy of integration: you are right, nothing is guaranteed. However,
consider for instance S(2,2.5). Let $S_1$, $S_2$, $S_3$, and $S_4$ be the result
at $38$, $77$, $154$, and $308$ decimals respectively (note that even at $154$
digits the computation requires only $0.3$ seconds). Then $S_1-S_4$, $S_2-S_4$,
$S_3-S_4$ are of the order of $10^{-25}$, $10^{-37}$, $10^{-59}$, admittedly not great, but with extreme confidence I would say that $S_1$ is correct to $24$
decimal digits, $S_2$ to $36$, and $S_3$ to $58$, thus giving the answers that I wrote in my comments.


text:
Q: Why does it jump to my else statement immediately? Hey I am trying to add a class and an attribute to my nav elements and for some reason my code jumps to the else statement. Appreciate any help what so ever.
This is my Html
    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Portfolio</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Poppins:400,300,500,600,700' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/styleC.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>

HOME (current)

WORK

ABOUT ME

CONTACT

Hy, I'm Robert and I am a webdesigner based in Aarhus.

                        All

All

Constructing Architecture

Photography

Multimedia Design

No results found

About Me

To tell you a little more about me, I have decided to make this short
personal description. I love doing many things: design, photography, architecture, coffee
and all of these traits represent me. I thrive in a social environment, loving the interaction between
co-workers and clients. People say I'm funny and this makes working with me an ease.

Feel free to contact me at info@freirobert.com

You can also find me on social media on the links below

©Robert Frei 2016

The css to the item required
.pagetwo {
    background-color: white;
    background-size: cover;
}

.darkNav {
    background-color: black !important;
}

And my JS which does not work....
$(function () {
var header = $('.navbar-default .navbar-toggle .icon-bar');
var logo = $('#logo');
var hieghtThreshold = $(".pagetwo").offset().top;
var hieghtThreshold_end  = $(".pagetwo").offset().top + $(".pagetwo").height();
$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= hieghtThreshold && scroll <=  hieghtThreshold_end ) {
        console.log("WORKS!!!!!");
        //logo.attr("src","/images/Logo-black.png");
        //header.addClass("darkNav");
    } else {
        alert("IT BROKE!");
        //logo.attr("src","/images/Logo.png");
        //header.removeClass("darkNav");
    }

});

})

A: This will execute every time when the window is scrolled. Go to the magic threshold and see that the WORKS!!!!! comment comes in the console. Replacing alert() with console.log() will throw nice light on it.
The $(window).scroll() fires continuously while scrolling the page. So since you have used alert() it keeps firing every time you scroll, and shows you BROKE!.


text:
Q: What is the usage difference between dilemma and quandary
Between dilemma and quandary, what are the various denotations and connotations.

*

*A dilemma is a difficult choice, not just any difficulty or problem.

The dictionaries put them as synonyms.

*

*I'm in a quandary about whether I should try to repair my stereo or buy a new one

*I don't know what to do; it's a real dilemma.

If you're at the mall choosing between red, green or blue socks, it is dilemma or quandary.
It's so confusing.

A: A dilemma is a choice between several options that are equally unfavourable.
A quandary is the state of being uncertain as to what you should do.
But dilemma is also used of the state of having a dilemma to solve, while quandary is also used of the cause of the quandary, so there is certainly a large overlap between these two.
Dilemma is still used by some to refer only two options (the original meaning) or at least where there are known options (as opposed to just "I don't know what to do about this"). Some people though use it more loosely to be more fully synonymous with quandary.

If you're at the mall choosing between red, green or blue socks, it is dilemma or quandary.

It would be an example of hyperbole to describe it as either. If you aren't a stickler for the dilemma = 2 things rule, then either is equally good (if over the top), otherwise it's only a quandary.
While they can be used interchangeably (hence the dictionaries listing them as synonyms as you say), dilemma does more often refer to the choice and quandary the mental and moral state of having to make it, which gives dilemma a slightly greater nuance of the difficulty faced, quandary a slightly greater nuance of the emotional response to it.

A: Per the definitions you link to, a quandary is:

a situation in which you are confused about what to do

This could be any sort of situation where the "best" choice is not obvious.
A dilemma is:

a situation in which you have to make a difficult choice

The intent here is that every option available to you is undesirable, but you nevertheless have to choose.
Often, when you have a dilemma, it is also a quandary, because which of the bad choices is "least bad" is not at all obvious and it is difficult to decide what to do.  (This is not always the case, though; sometimes you might easily choose a "known to be about X bad" over an "I have no idea how bad it could get" option.)
On the other hand, when you have a quandary, it is entirely possible to be picking from a set of choices that are entirely good in different ways, or that balance good and bad aspects, or that are a relatively meaningless set of choices that you just can't decide between.
Picking socks may constitute a quandary if you simply can't determine which set of socks will best match your outfit, but it is definitely NOT a dilemma, where no matter what socks you pick your life will be difficult and the only question is how it will become difficult.


text:
Q: Mouse-over objects not possible in HTML export of Enterprise Architect I need help with mouse over content of the HTML export from Enterprise Architect. I would like the HTML output from Enterprise Architect to also contain the 'Notes' of the element when I mouse over them. Currently this is not possible with the standard HTML export from Enterprise Architect.
Actually there is no way to see the contents and tags of the element if it has a composite child structure except for you have to find it in the side window like project browser and then click the individual object from there.
Please let me know if there are some ways I can achieve these.
Cheers!
Neha

A: I don't think the mouseover option is possible since the actual clickable areas are not related to the elements, they just redirect to the elements page.
But when clicking on an element on the HTML model, it should show you its details :notes, attributes, diagram, etc...(If it shows you the diagram, rest of the content should be below it)


text:
Q: How to check if columns are being used by views? I have an excel sheet with list of columns mentioned in it. I would now like to know what all columns present in the excel sheet are being used by the views in sql(working in ssms).
The data in excel is just the list of column names.
It looks like.
ColumnNames
DimCurrencyId
Dimzoneid
.......
Nearly 1000 column names.
Now I need to find whether if these are being used in sql views or not?
i have nearly 500 views
Can anyone please let me know the simplest way to do this so that i can skip the lot of manual work?

A: There is probably a much more elegant way to do this, but what I would do is use the Excel file to generate a list of SQL statements, then copy and paste them into SQL Server Management Studio and execute the entire list.
Assuming your column names begin in cell A2 I would put the following formula in cell B2 (or the next available column):
="select distinct sys.all_views.name from sys.all_views join sys.all_columns on sys.all_views.object_id = sys.all_columns.object_id where sys.all_columns.name = '"&A2&"' union"

OR, without needing a join (from ElenaDBA's answer):
="SELECT TABLE_NAME as [View Name] FROM   INFORMATION_SCHEMA.VIEWS WHERE  VIEW_DEFINITION LIKE '%"&A2&"%' UNION"

Drag the formula down to the end of your list of columns.
Copy and paste the resulting SQL statements into SSMS and be sure to remove the trailing union at the very end (the last query won't be unioning anything and you'll get an error if you try to execute the SQL with a trailing union statement).
Execute the SQL and you should get a list of the names of the views. Union automatically eliminates duplicates.
Again, not elegant, but I believe that will get the job done.
Update
To display the view name and the column name, you can simply add another reference to cells in column A to pick up your column as well.  Additionally, we can modify the WHERE clause to only look at the dbo schema.
For the first formula that would change to (schema_id of dbo is 1):
="select distinct sys.all_views.name, '"&A2&"' as 'colName' from sys.all_views join sys.all_columns on sys.all_views.object_id = sys.all_columns.object_id where sys.all_columns.name = '"&A2&"'  and schema_id = 1 union"

Basically adding the value you are searching for in the where clause to the select part.
The second formula, using the same idea, would look like this (with the schema being referenced by name):
="SELECT TABLE_NAME as [View Name] , '"&A2&"' as 'colName' FROM   INFORMATION_SCHEMA.VIEWS WHERE  VIEW_DEFINITION LIKE '%"&A2&"%' AND TABLE_SCHEMA = 'dbo'  UNION"

A: try:
SELECT TABLE_NAME as [View Name]
FROM   INFORMATION_SCHEMA.VIEWS
WHERE  VIEW_DEFINITION LIKE '%YourColumnName%'