Q: redux differentiation with context api My understanding is that React's Context API was essentially introduced for quick and dirty global state management, particularly before Redux Toolkit was introduced to simplify the overhead of implementing Redux.
My understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).
I recently explained that downside to someone and he asked why that wouldn't be the case with Redux.  He said Redux uses the Context API under the covers which appears to be the case based on some googling:
https://react-redux.js.org/using-react-redux/accessing-store#:~:text=Internally%2C%20React%20Redux%20uses%20React's,object%20instance%20generated%20by%20React.
A few questions:
1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?
2 - Can you confirm that Redux uses Context API under the covers?  And can you confirm if Redux Toolkit still uses Context API under the covers?
3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux.  But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?
4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render?  I would assume that there's somevtype of mapping layer but I'd be interested to get some more insight into the specific implementation details

A:
My understanding is that React's Context API was essentially introduced for quick and dirty global state management

That's a common misunderstanding. Context is not a state management system, any more than props is a state management system. Context (like props) is a way to get data from one component to another. The difference is that props always passes the data to direct children, while context makes the data available to whichever random components in a subtree are interested.

My understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).

This is true. Similarly, if you change props, the component that receives those props must rerender

1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?

Of the specific components that are listening to that context, yes.

2 - Can you confirm that Redux uses Context API under the covers? And can you confirm if Redux Toolkit still uses Context API under the covers?

React-redux does use context, yes. Pure redux and redux toolkit don't, since they're general purpose libraries not directly related to react, but I think you meant react-redux.
That <Provider store={store}> that you must render at the top of a react-redux app is there to provide a context to the components underneath it. Components that call hooks like useSelector or useDispatch then use the context to find the store that they should interact with.

3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux. But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?

Context has existed for a long time, but it used to be an unofficial feature. They've also made it easier to use over time.

4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render?

The context is only providing a minimal amount of things to the child components, most importantly the store object. The reference to the store object does not typically change, so since the context value does not change, the child components do not need to render. To see exactly what it's providing, see this code: https://github.com/reduxjs/react-redux/blob/master/src/components/Provider.tsx#L33
The contents of the store does change, but that's not what the context is providing. To get the contents of the store, the individual components subscribe to the store, using redux's store.subscribe, plus a special hook called useSyncExternalStore. Basically, redux fires an event when the store's state is updated, and then the individual components set their own local state if it's a change they care about. This local state change is what causes the rerender.

If you're writing code that uses context, you're rarely going to be doing things fancy enough to require useSyncExternalStore or a custom subscription system. So the main things you'll want to keep in mind are:

*

*Keep the context focused on a single task. For example, if you have a theme object to control your app's colors, and also a user object which describes who is currently logged in, put these in different contexts. That way a component that just cares about the theme doesn't need to rerender when the user changes, and vice versa.

*If your context value is an object, memoize it so it's not changing on every render (see this documentation)

A: I'm a Redux maintainer.  @NicholasTower gave a great answer, but to give some more details:
Context and Redux are very different tools that solve different problems, with some overlap.
Context is not a "state management" tool. It's a Dependency Injection mechanism, whose only purpose is to make a single value accessible to a nested tree of React components.  It's up to you to decide what that value is, and how it's created.  Typically, that's done using data from React component state, ie, useState and useReducer.  So, you're actually doing all the "state management" yourself - Context just gives you a way to pass it down the tree.
Redux is a library and a pattern for separating your state update logic from the rest of your app, and making it easy to trace when/where/why/how your state has changed.  It also gives your whole app the ability to access any piece of state in any component.
In addition, there are some distinct differences between how Context and (React-)Redux pass along updates.  Context has some major perf limitations - in particular, any component that consumes a context will be forced to re-render, even if it only cares about part of the context value.
Context is a great tool by itself, and I use it frequently in my own apps.  But, Context doesn't "replace Redux".  Sure, you can use both of them to pass data down, but they're not the same thing.   It's like asking "Can I replace a hammer with a screwdriver?". No, they're different tools, and you use them to solve different problems.
Because this is such a common question, I wrote an extensive post detailing the differences:
Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux)
To answer your questions specifically:

*

*Yes, updating a Context value forces all components consuming that context to re-render... but there's actually a good chance that they would be re-rendering anyway because React renders recursively by default, and setting state in a parent component causes all components inside of that parent to re-render unless you specifically try to avoid it.  See my post A (Mostly) Complete Guide to React Rendering Behavior, which explains how all this works.

*Yes, React-Redux does use Context internally... but only to pass down the Redux store instance, and not the current state value.  This leads to very different update characteristics.  Redux Toolkit, on the other hand, is just about the Redux logic and not related to any UI framework specifically.

*Context was not introduced to be an alternative to Redux.  There was a "legacy Context" API that existed in React well before Redux itself was created, and React-Redux used that up through v5.  However, that legacy context API was broken in some key ways.  The current React Context API was introduced in React 16.3 to fix the problems in legacy Context, not specifically to replace Redux.

*React-Redux uses store subscriptions and selectors in each component instance, which is a completely different mechanism than how Context operates.

I'd definitely suggest reading the posts I linked above, as well as these other related posts:

*

*Redux - Not Dead Yet!

*When (and when not) to Reach for Redux

*React, Redux, and Context Behavior.

A: Original blog post by Mark Erikson:
I'll just copy paste some info, but here's the original source and I recommend going directly here: https://blog.isquaredsoftware.com/2020/01/blogged-answers-react-redux-and-context-behavior/
More links here:

*

*https://github.com/markerikson/react-redux-links

*https://blog.isquaredsoftware.com/2018/11/react-redux-history-implementation/

*https://medium.com/async/how-useselector-can-trigger-an-update-only-when-we-want-it-to-a8d92306f559
An explanation of how React Context behaves, and how React-Redux uses Context internally
There's a couple assumptions that I've seen pop up repeatedly:

*

*React-Redux is "just a wrapper around React context"

*You can avoid re-renders caused by React context if you destructure the context value

Both of these assumptions are incorrect, and I want to clarify how they actually work so that you can avoid mis-using them in the future.
For context behavior, say we have this initial setup:
function ProviderComponent() {
    const [contextValue, setContextValue] = useState({a: 1, b: 2});

    return (
        <MyContext.Provider value={contextValue}>
            <SomeLargeComponentTree />
        </MyContext.Provider>
    )
}

function ChildComponent() {
    const {a} = useContext(MyContext);
    return <div>{a}</div>
}

If the ProviderComponent were to then call setContextValue({a: 1, b: 3}), the ChildComponent would re-render, even though it only cares about the a field based on destructuring. It also doesn't matter how many levels of hooks are wrapping that useContext(MyContext) call. A new reference was passed into the provider, so all consumers will re-render. In fact, if I were to explicitly re-render with <MyContext.Provider value={{a: 1, b: 2}}>, ChildComponent would still re-render because a new object reference has been passed into the provider! (Note that this is why you should never pass object literals directly into context providers, but rather either keep the data in state or memoize the creation of the context value.)
For React-Redux: yes, it uses context internally, but only to pass the Redux store instance down to child components - it doesn't pass the store state using context!. If you look at the actual implementation, it's roughly this but with more complexity:
function useSelector(selector) {
    const [, forceRender] = useReducer( counter => counter + 1, 0);
    const {store} = useContext(ReactReduxContext);

    const selectedValueRef = useRef(selector(store.getState()));

    useLayoutEffect(() => {
        const unsubscribe = store.subscribe(() => {
            const storeState = store.getState();
            const latestSelectedValue = selector(storeState);

            if(latestSelectedValue !== selectedValueRef.current) {
                 selectedValueRef.current = latestSelectedValue;
                 forceRender();
            }
        })

        return unsubscribe;
    }, [store])

    return selectedValueRef.current;
}

So, React-Redux only uses context to pass the store itself down, and then uses store.subscribe() to be notified when the store state has changed. This results in very different performance behavior than using context to pass data.
There was an extensive discussion of context behavior in React issue #14110: Provide more ways to bail out of hooks. In that thread, Sebastian Markbage specifically said:

My personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It's also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions. It's not ready to be used as a replacement for all Flux-like state propagation.

In fact, we did try to pass the store state in context in React-Redux v6, and it turned out to be insufficiently performant for our needs, which is why we had to rewrite the internal implementation to use direct subscriptions again in React-Redux v7.
For complete detail on how React-Redux actually works, read my post The History and Implementation of React-Redux, which covers the changes to the internal implementation over time, and how we actually use context.


Q: ThreadPoolTaskExecutor giving ConnectionPoolTimeOutException Getting this error even though the total count of active thread is less than the corepoolsize.
ThreadPool which I have created :
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(1500);
    executor.setMaxPoolSize(2000);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("MakeShoppingRequest");
    executor.setKeepAliveSeconds(10);
    executor.setAllowCoreThreadTimeOut(true);
    executor.initialize();

Exception:
**org.springframework.ws.client.WebServiceIOException: I/O error: Timeout waiting for connection from pool; nested exception is org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool**
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:561)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)
    at jdk.internal.reflect.GeneratedMethodAccessor66.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.leaseConnection(PoolingHttpClientConnectionManager.java:316)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$1.get(PoolingHttpClientConnectionManager.java:282)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:190)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)
    at org.springframework.ws.transport.http.ClientHttpRequestConnection.onSendAfterWrite(ClientHttpRequestConnection.java:83)
    at org.springframework.ws.transport.AbstractWebServiceConnection.send(AbstractWebServiceConnection.java:48)
    at org.springframework.ws.client.core.WebServiceTemplate.sendRequest(WebServiceTemplate.java:658)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:606)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
    ... 15 more


Q: Is it necessary to hash REST API tokens? So I have a REST API and some socket APIs which use a common token validation module. Here are the things that the token module does:
function tokenManager() {
  this.generate = (db, userId, cacheManager) => {
    /*Generates a token for a user and stores it in a db, also puts it in a cache as token: userId key-
    value pair.*/
  }

  this.verify = async (db, token, cacheManager) => {
    /*Checks the cache if a user is present for the given token and returns the user id. If the token was
    not found in cache, it verifies it from database and puts it in cache.*/

    //Each time for a successful verification, the token validity is increased by one day.
  }
}

This approach works well, however the tokens are stored in database as plain text. If someone gains access to the database they could get the tokens and make API calls, although rate limiting is present, there is some data compromised. I was planning to hash the API tokens and store them, but a hash compare has to be done on literally every request putting extra computation load on server. (especially bad for node). Is there a better way to implement this? Or is it even necessary to hash API tokens?


Q: iOS Firebase ML Kit Simple Audio Recognition "Failed to create a TFLite interpreter for the given model" I have been trying to implement the Simple Audio Recognition Tensorflow sample in iOS using the Firebase's ML kit. I have successfully trained the model and converted it into a TFlite file. The model takes the Audio(wav) file path as input([String]) and gives the predictions as output(float32). My iOS code is fairly simple
func initMLModel(){

        /*Initializing local TFLite model*/
        guard let modelPath = Bundle.main.path(forResource: "converted_model", ofType: "tflite") else {
            return
        }

        let myLocalModel = LocalModelSource.init(modelName: "My", path: modelPath)
        let registrationSuccessful = ModelManager.modelManager().register(myLocalModel)

        let options = ModelOptions(cloudModelName: nil, localModelName: "My")

        let interpreter = ModelInterpreter.modelInterpreter(options: options)

        let ioOptions = ModelInputOutputOptions()
        do {
            try ioOptions.setInputFormat(index: 0, type: .unknown, dimensions: []) /*input is string path. Since string is not defined, setting it as unknown.*/
            try ioOptions.setOutputFormat(index: 0, type: .float32, dimensions: [1,38]) /* output is 1 of 38 labelled classes*/
        } catch let error as NSError {
            print("Failed to set IO \(error.debugDescription)")
        }

        let inputs = ModelInputs()
        var audioData = Data()

        let audiopath = Bundle.main.path(forResource: "audio", ofType: "wav")
        do {
            audioData = try Data.init(contentsOf: URL.init(fileURLWithPath: audiopath!))
            //try inputs.addInput(audioData) /*If the input type is direct audio data*/
            try inputs.addInput([audiopath])
        } catch let error as NSError {
            print("Cannot get audio file data \(error.debugDescription)")
            return
        }

        interpreter.run(inputs: inputs, options: ioOptions) { (outputs, error) in
            if error != nil {
                print("Error running the model \(error.debugDescription)")
                return
            }
            do {
                let output = try outputs!.output(index: 0) as? [[NSNumber]]
                let probabilities = output?[0]

                guard let labelsPath = Bundle.main.path(forResource: "conv_labels", ofType: "txt") else { return }
                let fileContents = try? String.init(contentsOf: URL.init(fileURLWithPath: labelsPath))
                guard let labels = fileContents?.components(separatedBy: "\n") else {return}

                for i in 0 ..< labels.count {
                    if let probability = probabilities?[i] {
                        print("\(labels[i]) : \(probability)")
                    }
                }

            }catch let error as NSError {
                print("Error in parsing the Output \(error.debugDescription)")
                return
            }
        }
    }

But when i run this i get the following error output Failed to create a TFLite interpreter for the given model. The Complete Log of the sample app is as below
    2019-01-07 18:22:31.447917+0530 sample_core_ML[67500:3515789]  - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
    2019-01-07 18:22:33.354449+0530 sample_core_ML[67500:3515686] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
    2019-01-07 18:22:34.789665+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023007] Analytics v.50400000 started
    2019-01-07 18:22:34.790814+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see )
    2019-01-07 18:22:35.542993+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196
    2019-01-07 18:22:35.543205+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196
    2019-01-07 18:22:35.543923+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57
    2019-01-07 18:22:35.544070+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57
    2019-01-07 18:22:39.981492+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1
    2019-01-07 18:22:39.981686+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.
    Failed to set IO Error Domain=com.firebase.ml Code=3 "input format 0 has invalid nil or empty dimensions." UserInfo={NSLocalizedDescription=input format 0 has invalid nil or empty dimensions.}
    2019-01-07 18:22:40.604961+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1
    2019-01-07 18:22:40.605199+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.
    Error running the model Optional(Error Domain=com.firebase.ml Code=2 "Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite)." UserInfo={NSLocalizedDescription=Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite).})

When looked at this line Didn't find custom op for name 'DecodeWav' I looked up on the custom supported ops and found that Tensorflow already supports this in the audio_ops.cc by default.
Details
My Tensorflow Version : 1.12.0
Environment : Conda
OS Version : Mac OSX Mojave 10.14.2
Deployment target : ios 12.0
Installation type : Pod Installation (pod 'Firebase/MLModelInterpreter')
But i ran my training model first in v1.9.0. Then updated the Tensorflow to latest v1.12.0 to run the TFLite Convertor. Both are master branch.
My TFLite Convertor code Python
import tensorflow as tf

graph_def_file = "my_frozen_graph.pb"
input_arrays = ["wav_data"]
output_arrays = ["labels_softmax"]
input_shape = {"wav_data" : [1,99,40,1]}

converter = tf.contrib.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file, input_arrays, output_arrays, input_shape)
converter.allow_custom_ops = True
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

A: I posted this same question in the firebase quickstart iOS repository, And i got the following response DecodeWav op is never supported by TensorFlowLite. So at present Tensorflow Lite does not support audio processing even-though Tensorflow itself supports audio processing.


Q: HTML link with GET parameters: load page html and javascript before executing ajax request When I paste the HTML link below in my address bar or press the browser "previous page" button my ajax GET request is executed before the html content is fully loaded resulting in my ajax returned content being displayed above my nav bar and therefore breaking my site.
If the same request gets executed from within the site then everything is fine.
How can I make sure the page HTML and javascript loads before the ajax request is fired?
EDIT: SOLVED (answer in post below)
HTML LINK
https://domainName/?action=listy&p=test
JS pushstate
var container = document.querySelector('.lnk');
var url = "";

container.addEventListener('click', function(e) {
  if (e.target != e.currentTarget) {
    e.preventDefault();

    if (e.target.getAttribute('name')) {
      var data = e.target.getAttribute('name')
      url = "?action=list&p=" + data;
      history.pushState(data, null, url);
    }

  }
  e.stopPropagation();
}, false);

window.addEventListener('popstate', function(e) {

  window.location.replace(url);

});

JQuery AJAX
$(document).ready(function() {
  // .....
  success: function(dataBack) {
    $('.content-area').html(dataBack);
  },
});

PHP
if(isset($_GET['action']) && !empty($_GET['action'])) {
$action = $_GET['action'];
$var = $_GET['p'];
switch($action) {

    case 'list' : list($var);break;

}
}

A: This works for me (Note this uses the jquery library):
$(document).ready(function () {
     Your code here...
});

This will wait for the page to load then run the function. I personally use this for animations but then the animations also take more time for me so I have to also include the setTimeout function like this:
setTimeout(function () {
       Your code here...
}, 1000);

It waits a specific amount of milliseconds before executing the function.

A: Turns out the issue was coming from my index.php structure;
I moved the php code in separate files and included it at the end of index.php instead of the top.
Now Im having other issues but the main question is resolved.


Q: Get random ID from DB on button click Hi guys (I'm a beginner so take it easy) I have this code which searches my database and brings up the title / artists and that works fine. I am required to make a button which when clicked it brings up a random ID from my database. I have looked around but can't find anything useful.Trying to come up with a lamda expression or something...
Thanks
CONTROLLER
public ActionResult Play(string searchTitle, string searchArtist, string shuffle)
{
    var media = from s in db.UploadTables select s;

    if (!string.IsNullOrEmpty(searchTitle))
    {
        media = media.Where(m => m.MediaTitle.Contains(searchTitle));
    }

    if (!string.IsNullOrEmpty(searchArtist))
    {
        media = media.Where(m => m.MediaArtist.Contains(searchArtist));
    }

    return View(media);
}

VIEW
@using (Html.BeginForm())
{

        Song Name: @Html.TextBox("searchTitle")
        <input type="submit" value="Search" />
        Artist: @Html.TextBox("searchArtist")
        <input type="submit" value="Search" />
        @Html.TextBox("shuffle")
        <input type="submit" value="Search" />

}

A: Random rand = new Random();
int total = db.UploadTables.Count();
var randomId = db.UploadTables.Skip(rand.Next(total)).First().Id;

Random.Next(Int32 maxValue) will get a number between 0 and maxValue-1.
IQueryable<TSource>.Skip(this IQueryable<TSource>, int count) will skip count entries.
You then take the First() of the remaining entries and tadaa you can access its Id field.
Obviously, this is only one way to do it, and as told by others, there are many ways to do that.


Q: Is it possible to develop apps for iOS with iPod? I develop games for Android, but now I want to try the iOS platform. Actually, I have Mac Mini, but I haven't enought money to buy iPhone, so I think about buying iPod Touch instead. Is it possible to develop games (Unity engine) using iPod? What about games performance? Sorry if I ask something stupid, I never developed for iOS before, thanks!

A: We use an iTouch for development (cheaper than buying iPad2's). So yes, you can definitely develop for iOS using an iTouch/iPod.
You will also need to join the Apple developer program before you can deploy to the iTouch - Apple has a $99 annual fee for an individual. Even if you purchase Unity you will need buy into the Apple dev program too.

A: same code will work in iphone,ipad ,ipod .so no problem.so that the name of IDE is xcode.but performance and image accuracy will be varied.
http://unity3d.com/company/news/iphone-press.html

A: Apple provides a SDK including a simulator. Never trust the simulator completely, but you can use it easily for day by day job, and test it on a real iphone, ipod touch or similar only from time to time.


Q: Django tagging migration to GAE I have a Django app that use a django-tagging. I need to port this application to GAE. So, the main problem is to migrate tagging part. It has a complicated model, that should be rewritten to work with Google store. I think tagging is very popular django app and someone has the same problem before. Has someone a rewritten model?

A: Check Nick's post about tagging blog posts. It covers all main tagging issues.

A: There is a modified django-tagging, probably it might work.


Q: How to add delay between jquery steps transition (jquery steps plugin) I am using http://www.jquery-steps.com/Examples#advanced-form plugin.
How can I add delay between the two steps?
I have tried adding the timeout function in onStepChanging and onStepChanged but it's not working.
Here's what my code looks like:
var form = $("#example-advanced-form").show();

form.steps({
    headerTag: "h3",
    bodyTag: "fieldset",
    transitionEffect: "slideLeft",
    onStepChanging: function (event, currentIndex, newIndex)
    {
        // Allways allow previous action even if the current form is not valid!
        if (currentIndex > newIndex)
        {
            return true;
        }
        // Forbid next action on "Warning" step if the user is to young
        if (newIndex === 3 && Number($("#age-2").val()) < 18)
        {
            return false;
        }
        // Needed in some cases if the user went back (clean up)
        if (currentIndex < newIndex)
        {
            // To remove error styles
            form.find(".body:eq(" + newIndex + ") label.error").remove();
            form.find(".body:eq(" + newIndex + ") .error").removeClass("error");
        }
        form.validate().settings.ignore = ":disabled,:hidden";
        return form.valid();
    },
    onStepChanged: function (event, currentIndex, priorIndex)
    {
        // Used to skip the "Warning" step if the user is old enough.
        if (currentIndex === 2 && Number($("#age-2").val()) >= 18)
        {
            form.steps("next");
        }
        // Used to skip the "Warning" step if the user is old enough and wants to the previous step.
        if (currentIndex === 2 && priorIndex === 3)
        {
            form.steps("previous");
        }
    },
    onFinishing: function (event, currentIndex)
    {
        form.validate().settings.ignore = ":disabled";
        return form.valid();
    },
    onFinished: function (event, currentIndex)
    {
        alert("Submitted!");
    }
}).validate({
    errorPlacement: function errorPlacement(error, element) { element.before(error); },
    rules: {
        confirm: {
            equalTo: "#password-2"
        }
    }
});

A: how about this
setTimeout(function(){ /*your function*/ }, 3000);

https://www.w3schools.com/JSREF/met_win_setTimeout.asp


Q: Using Reflection to determine which Fields are backing fields of a Property I'm using reflection to map out objects. These objects are in managed code but I have no visibility into their source code, underlying structure, etc. other than through reflection. The overarching goal of all this is a rudimentary memory map of an object (similar in functionality to SOS.dll DumpObject and !ObjSize commands). As such, I'm trying to determine which members are being "double counted" as both a field and a property.
For example:
public class CalendarEntry
{
    // private property
    private DateTime date { get; set;}

    // public field
    public string day = "DAY";
}

When mapped shows:

*

*Fields

*

*day

*k__BackingField

*Properties

*

*date

Where as a class like this:
public class CalendarEntry
{
    // private field
    private DateTime date;

    // public field
    public string day = "DAY";

    // Public property exposes date field safely.
    public DateTime Date
    {
        get
        {
            return date;
        }
        set
        {
                date = value;
        }
    }
}

When mapped shows:

*

*Fields

*

*day

*date

*Properties

*

*Date

At first glance there's nothing to tell you that the Date property's "backing field" is the field named date. I'm trying to avoid counting date twice in this scenario since that will give me a bad memory size approximation.
What's more confusing/complicated is I've come across scenarios where properties don't always have a corresponding field that will be listed through the Type.GetFields() method so I can't just ignore all properties completely.
Any ideas on how to determine if a field in the collection returned from Type.GetFields() is essentially the backing field of some corresponding property returned from Type.GetProperties()?
Edit- I've had trouble determining what conditions a property will not have a corresponding field in listed in the collection returned from Type.GetFields(). Is anyone familiar with such conditions?
Edit 2- I found a good example of when a property's backing field would not be included in the collection returned from Type.GetFields(). When looking under the hood of a String you have the following:

*

*Object contains Property named FirstChar

*Object contains Property named Chars

*Object contains Property named Length

*Object contains Field named m_stringLength

*Object contains Field named m_firstChar

*Object contains Field named Empty

*Object contains Field named TrimHead

*Object contains Field named TrimTail

*Object contains Field named TrimBoth

*Object contains Field named charPtrAlignConst

*Object contains Field named alignConst

The m_firstChar and m_stringLength are the backing fields of the Properties FirstChar and Length but the actual contents of the string are held in the Chars property. This is an indexed property that can be indexed to return all the chars in the String but I can't find a corresponding field that holds the characters of a string. Any thoughts on why that is? Or how to get the backing field of the indexed property?

A: The name of a property's backing field is a compiler implementation detail and can always change in the future, even if you figure out the pattern.
I think you've already hit on the answer to your question: ignore all properties.
Remember that a property is just one or two functions in disguise.  A property will only have a compiler generated backing field when specifically requested by the source code.  For example, in C#:
public string Foo { get; set; }

But the creator of a class need not use compiler generated properties like this.  For example, a property might get a constant value, multiple properties might get/set different portions of a bit field, and so on.  In these cases, you wouldn't expect to see a single backing field for each property.  It's fine to ignore these properties.  Your code won't miss any actual data.

A: You can ignore all properties completely. If a property doesn't have a backing field, then it simply doesn't consume any memory.
Also, unless you're willing to (try to) parse CIL, you won't be able to get such mapping. Consider this code:
private DateTime today;

public DateTime CurrentDay
{
    get { return today; }
}

How do you expect to figure out that there is some relation between the today field and the CurrentDay property?
EDIT: Regarding your more recent questions:
If you have property that contains code like return 2.6;, then the value is not held anywhere, that constant is embedded directly in the code.
Regarding string: string is handled by CLR in a special way. If you try to decompile its indexer, you'll notice that it's implemented by the CLR. For these few special types (string, array, int, …), you can't find their size by looking at their fields. For all other types, you can.

A: To answer your other question:Under what circumstances do properties not have backing fields?
public DateTime CurrentDay
{
    get { return DateTime.Now; }
}

or property may use any other number of backing fields/classes
public string FullName
{
    get {return firstName + " " + lastName;}
}


Q: Line below link on hover How can I add a short line below link ? The line should be visible only on hover.
I tried with border-bottom, but that way the line is 100% of the link width and I want the line to be shorter than the link .
Here is a example image of the effect that I try to make.

A: This is something I just thought of, check it out see what you think. So we use :after and create a line under the text. This only works if the parent has a width (for centering).
HTML:

Test

CSS:
div {
    width: 30px;
}
div:hover:after {
    content: "";
    display: block;
    width: 5px;
    border-bottom: 1px solid;
    margin: 0 auto;
}

DEMO

Updated CSS:
div {
    display: inline-block;
}

Not sure why I didnt think of this but you can just use inline-block to get it to center without the parent having a width.
DEMO HERE

Here is a link using the same method, just incase you got confused.
DEMO HERE

So I have now be told I should even point out the most obvious thing so here is an update just for the people that don't know width can be a percentage.
width: 70%;

Changed the width from 5px to 70% so it will expand with the width of the text.
DEMO HERE

A: Edit:
Ruddy's solution has the same result and is more elegant so based on that, I used it recently with addition of transition, making it a bit more eye catching and I thought it would be useful to share here:
 a {
   display: inline-block;
   text-decoration:none
 }
 a:after {
   content: "";
   display: block;
   width: 0;
   border-bottom: 1px solid;
   margin: 0 auto;
   transition:all 0.3s linear 0s;
 }

 a:hover:after {
   width: 90%;
 }

jsfiddle link
(Original answer below)
Check this i just came up with, playing in the fiddle:
 I am a link, hover to see

 a.bordered {
 text-decoration:none;
 position: relative;
 z-index : 1;
 display:inline-block;
 }

a.bordered:hover:before {
content : "";
position: absolute;
left    : 50%;
bottom  : 0;
height  : 1px;
width   : 80%;
border-bottom:1px solid grey;
margin-left:-40%;
}

Depending on the percentages, you may play with a.bordered:hover:before margin and left position.

A: Simply use this class:
.link:hover {
    background-image:url("YOUR-SMALL-LINE-BOTTOM.png")
}

like this, the line will appear when you hover over the element. And you can specify in the image, how small or big the line has to be.

A: Try creating another Div for border. And adjust the width of that div according to your choice. I hope this will help.

A: what about this?
a {text-decoration:none;position:relative;}
a:hover:before {content:"_";position:absolute;bottom:-5px;left:50%;width:10px;margin:0 0 0 -5px;}

check this fiddle for more: http://jsfiddle.net/h7Xb5/

A: You can try using ::after pseudo element:

a {
  position: relative;
  text-decoration: none;
}

a:hover::after {
  content: "";
  position: absolute;
  left: 25%;
  right: 25%;
  bottom: 0;
  border: 1px solid black;
}
Demo Link

A: use underline or if u want the line to be much shorter try scalar vector graphics(svg) with this you can have custom lines.
<svg id="line "height="40" width="40">
  <line x1="0" y1="0" x2="700" y2="20" style="stroke:rgb(125,0,0);stroke-width:2" />


Q: EF Insert Array into db With View I have something to ask , i 'm going to create a simple application that store value of student Below is my class which i have tried .
Class Data{
  public int Id {get;set;}
  public string Name {get;set;}
  public int[] ValuesStudent{get;set;}

}
And below is example of the data
id = 1
Name = Jhon
Values = 9,8,7,5,9,7,4,6,4

id = 2
Name = Uncle
Values = 4,7,8,4

id = 3
Name = Jhon
Values = 9,8,7,5,9,7

as you can see above example of the data i can insert multiple value as i need, Student has taken 3 examination so i must insert 3 values for him .
But what i'm confuse is how can i make insert new Data . enter image description here
Oke if you any link which refer about problem , and explain about it , you can directly comment it .


Q: Is there a property I can check to see if code is rendered using hydrate vs render? I have a React app (with SSR) and need to handle things differently for server vs browser renders.

A: I ended up using the following, but my gut feeling is there is a better way.
if (typeof window !== "undefined") {
  // This code is rendered in browser vs server
}


Q: How to abort processing a request in NodeJS http server I have your standard callback-hell http server like (simplified):
http.createServer((req, res) => {
    doSomething(() => {
        doMoreSomethings(() => {
            if (!isIt())
                // explode A

            if (!isItReally())
                // explode B

            req.on('data', (c) => {
                if (bad(c))
                  // explode C
            });

            req.on('end', () => {
                // explode D
            });
        });
    });
};

The only way I know of to end the request is res.end(), which is asynchronous, so stuff after you call that will run (as far as I can tell). Is there a way to do a pseudo-process.exit mid-flight and abort processing the request, so I don't waste time on other stuff? For example how can I stop at the above // explode lines and not process anything else? throw doesn't leap over scope boundaries. Basically, I think, I want to return or break out of the createServer callback from within a nested callback. Is the only way to do this to be able to have code with a single path and just not have more than one statement at each step? Like, horizontal coding, instead of vertical KLOCs.
I'm a Node noob obviously.
Edit: Maybe another way to ask the question is: Is it possible to abort at the // explode C line, not read any more data, not process the end event, and not process any more lines in the doMoreSomethings callback (if there were any)? I'm guessing the latter isn't possible, because as far as I know, doMoreSomethings runs to completion, including attaching the data and end event handlers, and only then will the next event in the queue (probably a data event) get processed, at which point doMoreSomethings is done. But I am probably missing something. Does this code just zip through, call isIt and isItReally, assign the event handlers, hop out of all the callbacks, the createServer callback finishes, and then all the extra stuff (data/end/etc.) runs from the event queue?

A: Typically you will use a return statement. When you call return any code below it will not get executed. Although, if your functions isIt() or isItReally() are asynchronous functions then you will be running into trouble as those are used in a synchronous fashion.


Q: Looking for a script/tool to dump a list of installed features and programs on Windows Server 2008 R2 The same compiled .Net / C++ / Com program does different things on two seemingly same computers. Both have DOZENS of things installed on them. I would like to figure out what the difference between the two is by looking at an ASCII diff. Before that I need to "serialize" the list of installed things in a plain readable format - sorted alphabetically + one item per line.
A Python script would be ideal, but I also have Perl, PowerShell installed.
Thank you.

A: You can get the list of installed programs from the registry. It's under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
If this is a once-off exercise you may not even need to write any code - just use Regedit to export the key to a .REG file. If you do want to automate it Python provides the _winreg module for registry access.

A: There are two tools from Microsoft that may be what you need: RegDump and RegDiff. You can download them from various places, including as part of the Microsoft Vista Logo Testing Toolkit.
Also, there is Microsoft Support article How to Use WinDiff to Compare Registry Files.
For a Pythonic way, here is an ActiveState recipe for getting formatted output of all the subkeys for a particular key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for example).

A: Personally I always liked sysinternals' stuff (powerfull, light, actual tools - no need to install)
There is command line tool psinfo that can get you what you want (and then some) in various formats, distinguishing hotfixes and installed software, on local or remote computer (providing system policies allow it on remote).
You can also run it live from here, so though not strictly pythonic you could plug it in quite nicely.

A: Taken from List installed software from the command line:

If you want to list the software known to Windows Management
  Instrumentation (WMI) from the command line, use WMI command line
  (WMIC) interface.
To list all products installed locally, run the following
  command:
wmic product

Caveat: It seems that this command only list software installed through Windows Installer. See Win32_Product class


Q: Using Python CGI for a big HTML file I have a big html file named exercise.html, I need generate to one  som stuff by Python CGI.
I want to ask you what is the best way to print this HTML.
I know that it is possible by print method with using format methods %s, %i etc.:
print '''
<title>My first Python CGI app</title>

Hello, 'world'!

.
.

%s

.
.

''' % generated_text

But this HTML is really big,so is this only one solution?

A: You should consider using a templating language like Jinja2.
Here is a simple example straight from the link above:
>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')

Generally, though you save templates in a file, and then load / process them:
from jinja2 import Environment, PackageLoader
# The env object below finds templates that are lcated in the `templates`
# directory of your `yourapplication` package.
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')

As demonstrated above, templates let you put variables into the template.  Placing text inside {{ }} makes it a template variable.  When you render the template, pass in the variable value with a keyword argument.  For instance, the template below has a name variable that we pass via template.render

This is my {{name}}.

template.render(name='Jaime')

A: Also consider Python Bottle (SimpleTemplate Engine).  It is worth noting that bottle.py supports mako, jinja2 and cheetah templates.
The % indicates python code and the {{var}} are the substitution variables
HTML:

  % for item in basket:

{{item}}

  % end

Python:
with open('index.html', 'r') as htmlFile:
    return bottle.template(htmlFile.read(), basket=['item1', 'item2'])


Q: Callback parameters gets shifted I have a video c++ callback function where the parameters get suddently shifted after a few hours. In debug, it will assert on this:
void CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)
{
   assert(nWidth < 4000);
   CCameraInstance *pThis = (CCameraInstance*)pContext;
   pThis->PaintFrame(pBuffer, nWidth, nHeight, nFrameErrorNo);
}

When the debugger breaks on the assert, nWidth has a big invalid value. However, nHeight is 320 (the width value) and nFrameErrorNo is 240 (the nHeight value).
How can the parameters get shift that way?

A: The shift could be caused by the hidden this pointer. http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
From the code you have pasted here
void CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)

I can see the callback function is a member of class CCameraInstance
I'm not sure whether you are defining the function as a static function or a normal one. But in theory it should be a static function to avoid the this pointer. Using a C++ class member function as a C callback function
However, I had a problem with C++/CLI even if i have define the member function as static. The this pointer/Handle still exist.
I think you can try to define your function as
void CCameraInstance::VideoCallback(CCameraInstance* test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)

and have try.
If you are using C++/CLI it would be
void CCameraInstance::VideoCallback(CCameraInstance^ test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)


Q: Composite/Combined Indexing vs Single Index vs multiple Combined Indexed on a large table I have a very large table (that is still growing) (around 90GB with ~350mil rows). It is a table that include sales of items, if you were wondering.
In this table, there's (for example), column A,B,C,D,E,F,G.
Currently, I am using a combined index, consisting of (A,B,C,D,E,F).
Usually, the query will consist of A,B,C,D,E. F is included occasionally (hence the indexing).
eg,
SELECT * FROM table WHERE A = ? AND B = ? AND  C = ? AND  D = ? AND  E = ?;
Sometimes, with the addon of AND F = ?;
But on certain occasion, the query will consist of A,B,C,D,G (whereby G is not indexed (not combined nor single indexed).
This causes timeout on certain occasion as the data is quite big.
So my question is, in order to solve this issue in terms of indexing,
should I
Option 1: add G into the combined index, making it become (A,B,C,D,E,F,G).

*

*Does this even work when I query A,B,C,D,G (missing E & F)?

Option 2: add G as a single index.

*

*Based on what i know, this does not work, as my query has A,B,C,D,G. The first combined index will be used instead (correct me if I'm wrong).

Option 3: Go with option 1, combine all the columns, but I change my query instead, to always query A,B,C,D,E,F,G even when F is not needed.
eg,
SELECT * FROM table WHERE A = ? AND B = ? AND  C = ? AND  D = ? AND  E = ? AND F IS NOT NULL AND G = ?;
Thanks

A: Option 1 - Yes, this will work. The server will perform index seek by (A,B,C,D,E) and furter index scan by (G).
Option 2 - Makes no sense in most cases, server uses only one index for one source table copy. But when the selectivity of single index by (G) is higher than one for (A,B,C,D,E) combination then the server will use this single-column index.
Option 3 - The processing is equal to one in Option 2.

A: Are the PRIMARY KEY's column(s) included in A..E ?  If so, none of the indexes are needed.
What datatypes are involved?
Are they all really tests on =?  If not then 'all bets are off'.  More specifically, useful indexes necessarily start with the columns tested with = (in any order).  In particular, F IS NOT NULL is not = (but IS NULL would count as =).
I would expect INDEX(A,B,C,D,E, anything else or nothing else) to work for all of the queries you listed.  (Hence, I suspect there are some details missing from your over-simplified description.)
How "selective" are F and G?  For example, if most of the values of G are distinct, then INDEX(G) would possibly be useful by itself.
Please provide SHOW CREATE TABLE and EXPLAIN SELECT ...


Q: How to convert below javascript code to work in IE11 I want to convert my code from es6 to es4-3 so that it supports IE11. I am trying to toggle the class="open" for the three button which helps me to open a small div.
JS:
let customSelect = document.getElementsByClassName('input-select')

Array.from(customSelect).forEach((element, index) => {
  element.addEventListener('click', function () {
    Array.from(customSelect).forEach((element, index2) => {
      if (index2 !== index) {
        element.classList.remove('open')
      }
    })
    this.classList.add('open')
  })

  for (const option of document.querySelectorAll('.select-option')) {
    option.addEventListener('click', function () {
      if (!this.classList.contains('selected')) {
        this.parentNode
          .querySelector('.select-option.selected')
          .classList.remove('selected')
        this.classList.add('selected')
        this.closest('.input-select').querySelector(
          '.input-select__trigger span'
        ).textContent = this.textContent
      }
    })
  }

  // click away listener for Select
  document.addEventListener('click', function (e) {
    var isClickInside = element.contains(e.target);
    if(!isClickInside) {
      element.classList.remove('open');
    }
    return
  })
})

HTML:

     <button></button>

Hi

Bye

     <button></button>

Hi

Bye

     <button></button>

Hi

Bye

This is pure es6 code i need to convert it into lower version of js

A: This is the Babel's (targeted only to IE 11) answer:
"use strict";

function _createForOfIteratorHelper(o, allowArrayLike) {
  var it =
    (typeof Symbol !== "undefined" && o[Symbol.iterator]) || o["@@iterator"];
  if (!it) {
    if (
      Array.isArray(o) ||
      (it = _unsupportedIterableToArray(o)) ||
      (allowArrayLike && o && typeof o.length === "number")
    ) {
      if (it) o = it;
      var i = 0;
      var F = function F() {};
      return {
        s: F,
        n: function n() {
          if (i >= o.length) return { done: true };
          return { done: false, value: o[i++] };
        },
        e: function e(_e) {
          throw _e;
        },
        f: F
      };
    }
    throw new TypeError(
      "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
    );
  }
  var normalCompletion = true,
    didErr = false,
    err;
  return {
    s: function s() {
      it = it.call(o);
    },
    n: function n() {
      var step = it.next();
      normalCompletion = step.done;
      return step;
    },
    e: function e(_e2) {
      didErr = true;
      err = _e2;
    },
    f: function f() {
      try {
        if (!normalCompletion && it.return != null) it.return();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}

function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
    return _arrayLikeToArray(o, minLen);
}

function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }
  return arr2;
}

var customSelect = document.getElementsByClassName("input-select");
Array.from(customSelect).forEach(function (element, index) {
  element.addEventListener("click", function () {
    Array.from(customSelect).forEach(function (element, index2) {
      if (index2 !== index) {
        element.classList.remove("open");
      }
    });
    this.classList.add("open");
  });

  var _iterator = _createForOfIteratorHelper(
      document.querySelectorAll(".select-option")
    ),
    _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done; ) {
      var option = _step.value;
      option.addEventListener("click", function () {
        if (!this.classList.contains("selected")) {
          this.parentNode
            .querySelector(".select-option.selected")
            .classList.remove("selected");
          this.classList.add("selected");
          this.closest(".input-select").querySelector(
            ".input-select__trigger span"
          ).textContent = this.textContent;
        }
      });
    } // click away listener for Select
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  document.addEventListener("click", function (e) {
    var isClickInside = element.contains(e.target);

    if (!isClickInside) {
      element.classList.remove("open");
    }

    return;
  });
});

A: You can use Babel to transpile the code first. You can also refer to this tutorial about how to use Babel to transpile code.
The code I use Babel to transpile is like below:
'use strict';

var customSelect = document.getElementsByClassName('input-select');

Array.from(customSelect).forEach(function (element, index) {
  element.addEventListener('click', function () {
    Array.from(customSelect).forEach(function (element, index2) {
      if (index2 !== index) {
        element.classList.remove('open');
      }
    });
    this.classList.add('open');
  });

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = document.querySelectorAll('.select-option')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var option = _step.value;

      option.addEventListener('click', function () {
        if (!this.classList.contains('selected')) {
          this.parentNode.querySelector('.select-option.selected').classList.remove('selected');
          this.classList.add('selected');
          this.closest('.input-select').querySelector('.input-select__trigger span').textContent = this.textContent;
        }
      });
    }

    // click away listener for Select
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  document.addEventListener('click', function (e) {
    var isClickInside = element.contains(e.target);
    if (!isClickInside) {
      element.classList.remove('open');
    }
    return;
  });
});

Then add this line of code before the script to add a polyfill:


Q: FileNotFoundException : Could not open ServletContext resource [/WEB-INF/spring/root-context.xml] I am facing below exception while building a SpringMVC application through Maven.
Maven builds the application and tries to deploy on already running tomcat which fails.
If I build and run the same code through eclipse+inbuild Tomcat, it runs fine.
Exception coming while building from Maven:
java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/spring/root-context.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1095)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1930)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/spring/root-context.xml]
at

web.xml
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->

<!-- this context-param is needed otherwise app will look for /WEB-INF/applicationContext.xml -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>

    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Here is my project Structure

Is there any way to solve this ?
Thanks

A: @ian-roberts and @bohuslav-burghardt already answered your question: you have created a structure that doesn't conform to the structure that Maven project must have.
To fix it you should put all contents of WebContent directory to src/main/webapp


Q: In python, is it easy to call a function multiple times using threads? Say I have a simple function, it connects to a database (or a queue), gets a url that hasn't been visited, and then fetches the HTML at the given URL.
Now this process is serial, i.e. it will only fetch the html from a given url one at a time, how can I make this faster by doing this in a group of threads?

A: Yes.  Many of the Python threading examples are just about this idea, since it's a good use for the threads.
Just to pick the top four Goggle hits on "python threads url": 1, 2, 3, 4.
Basically, things that are I/O limited are good candidates for threading speed-ups in Python; things the are processing limited usually need a different tool (such as multiprocessing).

A: You can do this using any of:

*

*the thread module (if your task is a function)

*the threading module (if you want to write your task as a subclass of threading.Thread)

*the multiprocessing module (which uses a similar interface to threading)

All of these are available in the Python standard library (2.6 and later), and you can get the multiprocessing module for earlier versions as well (it just wasn't packaged with Python yet).


Q: password set during checkout issue I have an issue with customer registered through checkout.
After the checkout process, the customer lands in “My Account” but once logged off, he can’t acces "My Account" anymore, the message "Invalid login or password" is displayed.
Setting a new password through “Forgotten Password” button seems to solve the problem for the customer. (But it would be great if the password could work directly without passing through this step.)
I think (but am not sure at all) that the password set through billing.phtml is not stored correctly.
The customers registered through "Register" button are saved correctly and don't encounter any issue.
I have in template/persistent/Customer/form/register.phtml:

                    *<?php echo $this->__('Password') ?>

                        <input type="password" name="password" id="password" title="<?php echo $this->quoteEscape($this->__('Password')) ?>" class="input-text required-entry validate-password" />

                    *<?php echo $this->__('Confirm Password') ?>

                        <input type="password" name="confirmation" title="<?php echo $this->quoteEscape($this->__('Confirm Password')) ?>" id="confirmation" class="input-text required-entry validate-cpassword" />

In template/Customer/form/resetforgottenpassword.phtml:

                *<?php echo $this->__('New Password'); ?>

                    <input type="password" class="input-text required-entry validate-password" name="password" id="password" />

                *<?php echo $this->__('Confirm New Password'); ?>

                    <input type="password" class="input-text required-entry validate-cpassword" name="confirmation" id="confirmation" />

And in template/persistent/checkout/onepage/billing.phtml, which I think is the culprit:

                    *<?php echo $this->__('Password') ?>

                        <input type="password" name="billing[customer_password]" id="billing:customer_password" title="<?php echo $this->quoteEscape($this->__('Password')) ?>" class="input-text required-entry validate-password" />

                    *<?php echo $this->__('Confirm Password') ?>

                        <input type="password" name="billing[confirm_password]" title="<?php echo $this->quoteEscape($this->__('Confirm Password')) ?>" id="billing:confirm_password" class="input-text required-entry validate-cpassword" />

I tried several modifications to billing.phtml, such as:
*<?php echo $this->__('Password') ?>
<input type="password" name="password" id="password" title="<?php echo $this->quoteEscape($this->__('Password')) ?>" class="input-text required-entry validate-password" />
<input type="password" name="password" title="<?php echo $this->quoteEscape($this->__('Confirm Password')) ?>" id="confirmation" class="input-text required-entry validate-cpassword" />

But I’m still leading to the same result.
I’m on a CE 1.9.3.1 patched with SUPEE 9652.
How to make Customer registered during checkout being saved correctly?

A: I have 4 errors concerning lib/Varien/Crypt/Mcrypt.php
Warning: mcrypt_generic_init(): Key size is 0 in /lib/Varien/Crypt/Mcrypt.php on line 94
Warning: mcrypt_generic_init(): Key length incorrect  in /lib/Varien/Crypt/Mcrypt.php on line 94
Warning: mcrypt_generic_deinit(): 495 is not a valid MCrypt resource  in /lib/Varien/Crypt/Mcrypt.php on line 135
Warning: mcrypt_module_close(): 495 is not a valid MCrypt resource  in /lib/Varien/Crypt/Mcrypt.php on line 136

I thought it was relative to a module is missing in PHP Mcrypt on my server (https://magento.stackexchange.com/a/35888). But it's not the case as by installing a fresh CE 1.9.3.1 in a folder in the root of the same Magento installation is doing its job properly with the same server configuration and Mcrypt.php. Moreover, the password set during registration with form (?and using the same encryption?), is set properly.
I'll open a new post with more precisions.
@urfusion, thank you for advice, I was looking at the wrong end of system.log (thought it was writing on the top...)
Edit
I got it, the solution's here:
https://stackoverflow.com/a/42474835/7553582


Q: How to change part of window content upon combo box selection changed event? In my wpf window I want to change part of it (make different controls visible) when combo box selection is changed. Exactly like TabControl works, just with combobox. I know I could just make some controls visible while hiding the others in the c# code behind but I want to find out if there are other -better solutions.

A: You can use two Grid or GroupBox (or other container type) controls and put appropriate set of controls in each of them. This way you can just visibility of panels to hide the whole set of controls instead of hiding each control directly.
It may sometimes be appropriate to create a user control for each set of controls. However, this can depend on a specific case.


Q: How to block mouse click events from another form I have a winforms single form application that uses a "Thickbox" I've created whenever the loads a new view into the application form.
The "Thickbox" shows another form in front of the application's form that is semi-transparent and has a user control that is the box itself.
This thickbox can be shown a modal dialog and in that case I have no problems at all, but it can also be shown as a non modal, for instance, when the user switches views in the main form, it shows thickbox with a loading animated icon.
The problem is that when the thickbox is shown as non modal, it doesn't block the user from clicking on the buttons of main form of the application.
When thickbox is shown nothing happens, but as soon as it's closed, the click is being processed by the click event handler of the relevant button in the main form.
I can't use ShowDialog since I can't block the UI thread, and I need to get the indication from the main form when to close the thickbox,
I can't set the Enabled property of the owner form as described in this answer (though I've tried various versions of this solution, nothing helps)
I've tried using the win API function BlockInput as descried in this answer, but that didn't block the input,
I think my best chance is using the Application.FilterMessage method, but I couldn't get that to block the mouse clicks as well.
It would be great if I could encapsulate the mouse click blocking inside the thickbox form itself, so that it would be usable easily with other applications as well, but
a solution on to the calling form would also be very much appreciated.

A: I'm glad to announce that the problem is finally solved.
After spending a few days attempting to recreate this bug in a new application, re-constructing the main form in the application, comment out parts of the code in the main application, and generally just shooting all over to try and find a lead, It finally hit me.
The application behaved as if the clicks on the thickbox was queued somehow and only activated when the thickbox was closed. This morning, after fixing some other bugs, The penny finally dropped - all I was missing was a single line of code right before closing the thickbox's form:
Application.DoEvents();

The annoying thing is that it's not something that's new to me, I've used it many times before including in the main application and in the thickbox code itself... I guess I just had to let if go for a while to enable my mind to understand what was so painfully obvious in hindsight...


Q: Create twin object a.k.a. inheritance clone The working twin(source) function below generates a new object with the same own properties as source and with the same parents (prototype chain). (e.g. twin(isFinite) would be [object Object] and instanceof Function) Does any native function provide the same effect?
/**
 * @param {Object|Function} source
 * @param {(Object|Function|null)=} parent defaults to source's parents
 * @return {Object}
 */
function twin(source, parent) {
    var twin, owned, i = arguments.length;
    source = i ? source : this; // use self if called w/o args
    parent = 2 == i ? parent : Object.getPrototypeOf(source);
    twin = Object.create(parent);
    owned = Object.getOwnPropertyNames(source);
    for (i = owned.length; i--;) {
        twin[owned[i]] = source[owned[i]];
    }
    return twin;
}

Update: A .twin method is available in blood.

A: You can try something like this:
obj= eval(uneval(objSource));

It only works in FF but the idea is to serialize an object and the eval the serialized string instantiating (prototyping) a new object with the same properties as the first one.
You can use also the function JSON.stringify as the "uneval" function.


Q: Updating parent component only after multiple child components have completed running I have a Parent react component with multiple child components that are created through a .map() function. I am passing in a function addCallback() as child props so I have a reference and can trigger all child's handleRun() function via the Parent.
I'm trying to update state of my Parent component to running = true when all children are running and to running = false and render said status on the parent when all children have completed running. However the state doesn't seem to update in the particular sequence I specify.
Here is how I'm doing it:
let promise1 = this.setState({isRunning:  true},
            () => {
                this.state.childRef.map(x => x())
            });

Promise.all([promise1])
    .then(() => this.setState({isRunning: false}))

Here's the entire code in codesandbox: link
Would appreciate your help as I'm still pretty new to React (and Javascript in general). Thanks!

A: Cause runSomething is not a Promise. You must change.
runSomething() {
  return new Promise((resolve, reject) => {
    this.setState({ status: "running" });
     // simulate running something that takes 8s
     setTimeout(() => {
       this.setState({ status: "idle" });
       resolve(true);
     }, 3000);
  });
}

A working sandbox here https://codesandbox.io/s/fragrant-cloud-5o2um

A: Using async in a function declaration automatically returns a Promise wrapped around whatever you are returning from your function. In your case, it's undefined. This is why your current code is not throwing any errors at the moment.
You will need a mechanism to wait for the setTimeout. Changing the runSomething function like this will work
  async runSomething() {
    this.setState({ status: "running" });

    // simulate running something that takes 8s
    return new Promise(resolve => {
      setTimeout(() => {
        this.setState({ status: "idle" }, resolve);
      }, 3000);
    });
  }

Do notice the line this.setState({ status: "idle" }, resolve);. It makes sure that your promise resolves not only after the setTimeout but also after the child's state is changed to "idle". Which is the correct indication that your child component has moved to "idle" state.
Codesandbox: https://codesandbox.io/s/epic-boyd-12hkj

A: Here is the sandbox implementation of what you are trying to achieve. Sanbox
Here i have created a state in parent component that will be updated when child is running.
this.state = {
  callbacks: [],
  components: [
    {
      index: 0, // we don't need this field its just for your info you can just create [true,false] array and index will represent component index.
      status: false
    },
    {
      index: 1,
      status: false
    }
  ]
};

When all the status in component array is true we update the idle status of parent to running.
  getAllRunningStatus() {
    let { components } = this.state;
    let checkAllRunning = components.map(element => element.status);
    if (checkAllRunning.indexOf(false) === -1) { // you can also use !includes(false)
      return true;
    }
    return false;
  }

inside your render function

Parent {this.getAllRunningStatus() ? "running" : "idle"}

Note:- I have just written a rough code. You can optimise it as per your requirements. Thanks


Q: How to access a variable that was available when an async method was called? The animal names are fetched from an API that could return 404 if the animal is not found. But in order to properly log the error, we need to have access to the animal's country. Is it possible? I've read something from a guy called Stephen Cleary that made me think it is possible with lambdas, but I couldn't find anything.
var gettingNames = new List<Task<string>>();

foreach (var animal in animals)
{
    gettingNames.Add(this.zooApi.GetNameAsync(animal));
}

try
{
    await Task.WhenAll(gettingNames);
}
catch (Exception e)
{
    var exception = gettingNames.Where(task => task.IsFaulted)
        .SelectMany(x => x.Exception.InnerExceptions).First();

    this.logger.LogError("The animal name from {Country} was not found",
        animal.Country); // This is the goal
}

A: One way to solve this problem is to project each Animal to a Task that contains more information than either a naked name or a naked error. For example you could project it to a Task<ValueTuple<Animal, string, Exception>> that contains three pieces of information: the animal, the animal's scientific name from the zooApi, and the error that may have happened while invoking the zooApi.GetScientificNameAsync method.
The easiest way to do this projection is the LINQ Select operator:
List<Task<(Animal, string, Exception)>> tasks = animals.Select(async animal =>
{
    try
    {
        return (animal, await this.zooApi.GetScientificNameAsync(animal),
            (Exception)null);
    }
    catch (Exception ex)
    {
        return (animal, null, ex);
    }
}).ToList();

(Animal, string, Exception)[] results = await Task.WhenAll(tasks);

foreach (var (animal, scientificName, error) in results)
{
    if (error != null)
        this.logger.LogError(error,
            $"The {animal.Name} from {animal.Country} was not found");
}

A: You have almost nailed it. :)
Rather than having a List<Task<string>> you need a Dictionary<Task<string>, string> structure:
static async Task Main()
{
    var taskInputMapping = new Dictionary<Task<string>, string>();
    var inputs = new[] { "input", "fault", "error", "test"};
    foreach (var input in inputs)
    {
        taskInputMapping.Add(DelayEcho(input), input);
    }

    try
    {
        await Task.WhenAll(taskInputMapping.Keys);
    }
    catch
    {
        foreach (var pair in taskInputMapping.Where(t => t.Key.IsFaulted))
        {
            Console.WriteLine($"{pair.Value}: {pair.Key.Exception?.GetType().Name}");
        }
    }
}

static readonly ImmutableArray<string> wrongInputs =
    ImmutableArray.Create("error", "fault");
static async Task<string> DelayEcho(string input)
{
    if (wrongInputs.Contains(input)) throw new ArgumentException();
    await Task.Delay(10);
    return input;
}

*

*taskInputMapping.Add(DelayEcho(input), input): Stores the input next to the Task itself

*taskInputMapping.Where(t => t.Key.IsFaulted): Iterates through the faulted tasks

*$"{pair.Value}: {pair.Key.Exception?.GetType().Name}": Retrieves the input + the related error

A: I combined the answers and came up with this:
var tasks = animals.Select(async animal =>
{
    try
    {
        return await this.zooApi.GetNameAsync(animal);
    }
    catch (Exception ex)
    {
        this.logger.LogError(error,
            $"The {animal.Name} from {animal.Country} was not found");

        return null;
    }
});

var results = await Task.WhenAll(tasks);

foreach (var name in results.Where(x => x != null))...


Q: HTML divide and conquer i am looking for the best pratice when it comes to HTML.
Now my normal programming instincts tells me to always divide and conquer but i am not sure how or even if it is recommended when it comes to HTML.
So say for example i have the following index file:
        <!DOCTYPE html>

        <title>Dinner plans</title>

               <?php
               if(isset($_SESSION['loggedin'])){
                 echo "Du er logged ind";
               }else
                ?>

                <input type="text" name="username" id="username"> <input type="password" name="password" id="password">

now i would devide some of this code for example the menu into another HTML file for instance menu.html and then place the content of the file within the index file.
My question is simple is this recommended and if so how is it achieved?

A: I think what you are asking is if you can separate parts of an HTML page into smaller pages, so you can separate concerns.
In PHP this can be accomplished by referencing other files by a require() or include(). But I still don't believe this really answers your question. ASP.NET MVC allows you to render partial views within a webpage through `RenderPartial() but you didn't mention anything about using this.
You can find more at http://www.asp.net/mvc/videos/mvc-2/how-do-i/how-do-i-work-with-data-in-aspnet-mvc-partial-views

A: If you want to divide a single webpage into multiple hmtl files you can do it by inserting frames. This is an old way of programming and you don't really see it these days but its efficient at doing what you are asking.

A: Yes, this is highly recommended. You are trying to apply the DRY principle (see: http://en.wikipedia.org/wiki/Don't_repeat_yourself). It's an excellent idea to apply this to your HTML. You can achieve this using require, require_once, include, and include_once in PHP. If you want to get a bit fancier, take a look at templating systems like Smarty (see: http://www.smarty.net/)


Q: Select ScrollView element (Button) by code I would like to set my scrollView element seleted, using code.
Here is what I have so far (commented code is not working):
public class Dictionary extends Activity implements Runnable, OnClickListener {
    //Candidates
    candidatesScrollView = (HorizontalScrollView) findViewById(R.id.activity_dictionary_horizontalScrollView1);

    candidatesButtons = new ArrayList<Button>();
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button1));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button2));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button3));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button4));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button5));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button6));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button7));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button8));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button9));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button10));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button11));
    candidatesButtons.add((Button) findViewById(R.id.activity_dictionary_horizontalscrollview1_button12));
    for(int i = 0; i < candidatesButtons.size(); i++)
        ((Button) candidatesButtons.get(i)).setOnClickListener(this);

    (...)
}

And then in another method:
private void recognize() {

    (...)

    byte buffer[];
    buffer = RecogEngine.setResult(0); // and set the remaining data to engine
    try {
        candidatesString = new String(buffer, "UTF-8");

    for (int i = 0; i < candidatesString.length(); i++)
    {
        candidatesButtons.get(i).setTextColor(getResources().getColor(R.color.Celadon));
        candidatesButtons.get(i).setTypeface(null,Typeface.BOLD);
        candidatesButtons.get(i).setText(String.valueOf(candidatesString.charAt(i)));
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    //HERE_I_WANT_TO_SELECT_AND_HIGHLIGHT (like in default HOLO_DARK THEME)
    //candidatesButtons.get(0).requestFocus();
    //candidatesButtons.get(0).setSelected(true);
    (...)
}

How to do this?

A: I have found the solution for my problem. You should use the following code to set the Button selected:
//HERE THE CODE IS WORKING
candidatesButtons.get(0).requestFocusFromTouch();
candidatesButtons.get(0).setSelected(true);

Maybe it will be useful to someone


Q: Writing unit tests that work with the DOM I have some functionality that works with the DOM, specifically dealing with resizing elements. I looked over the Unit Testing documentation here and couldn't find anything on doing this.  Is it possible?  Is there any existing documentation that shows how to do it?

A: Try DumpRenderTree - headless chrome which outputs a textual version of layout.
eg:
Content-Type: text/plain
layer at (0,0) size 808x820
  RenderView at (0,0) size 800x600
layer at (0,0) size 800x820
  RenderBlock {HTML} at (0,0) size 800x820
    RenderBody {BODY} at (8,8) size 784x804
      RenderHTMLCanvas {CANVAS} at (0,0) size 800x800 [bgcolor=#808080]
      RenderText {#text} at (0,0) size 0x0
#EOF
#EOF

Kevin Moore's blog post "Headless Browser Testing with Dart" explains the details (and the above snippet is taken from that)


Q: C# Object reference not set to an instance of an object. Instantiating Class within a List? public class OrderItem
{
    public string ProductName { get; private set; }
    public decimal LatestPrice { get; private set; }
    public int Quantity { get; private set; }
    public decimal TotalOrder { get {return LatestPrice * Quantity;}}

    public OrderItem(string name, decimal price, int quantity)
    {

    }

    public OrderItem(string name, decimal price) : this(name, price, 1)
    {

    }
}

Above is the class, just for some background.
public void AddProduct(string name, decimal price, int quantity)
{
    lstOrderitem.Add(new OrderItem(name, price, quantity));
}

On the code inside the AddProduct method is where I am getting the error stated in the title.
I'm just trying to instantiate the class and add it to a collection to be displayed in a listbox on my form program.
The "AddProduct" will be called on a button click event

Error = NullReferenceException - Object reference not set to an instance of an object.

I was wondering if anybody knew why this was happening since I thought that since I am making a NEW instance of the class while adding it to the list that it would have something to reference too. Thank you if anybody knows what the problem is.
Edit
    public List<OrderItem> lstOrderitem{ get; private set; }
    public int NumberOfProducts { get; private set; }
    public decimal BasketTotal { get; private set; }

    public ShoppingBasket()
    {
        //List<OrderItem> lstOrderitem = new List<OrderItem>();
    }

    public void AddProduct(string name, decimal price, int quantity)
    {
        lstOrderitem.Add(new OrderItem(name, price, quantity));

    }

A: It looks like you didn't initialize your reference lstOrderitem. Debug your code if your references value is null, you need to initialize lstOrderitem before using it.

A: You should initialize lstOrderitem property in the constructor, like this:
EDIT
public MyClass() {
    lstOrderitem = new List<OrderItem>();
}

P.S. Microsoft suggests starting the names of your properties in capital letters, to avoid confusion with member variables, which should be named starting with a lowercase letter.

A: It looks like you didn't initialize your reference lstOrderitem. Debug your code if your reference value is null, you need to initialize lstOrderitem before using it.
public MyClass() {
    lstOrderitem = new List<OrderItem>();
}


Q: Is there a way to make app engine turn off when no traffic I am currently using App Engine in Google Cloud with Docker to handle Mux Video requests. The problem is I am being charged over $40 when the app is in development and there is virtually no traffic on the app. Is there a way to turn off the App Engine when no requests are being sent so the hours of operation are less or this not possible with app Engine? I am quite new to App Engine.
runtime: custom
env: flex

manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10

A: No, you can't scale to 0 the Flex instances. It's the main problem of the flex instances.
You have to replace the current service by a APp Engine standard service version that can scale to 0 and stop paying.

If your application doesn't run background processes, and the request handling doesn't take more than 60 minutes, I strongly recommend you to have a look to Cloud Run


Q: "save link as" bulk download I have a list of links in an html file and I want to perform a "save link as" for all of them so it downloads all the files into one folder.
Is this possible? I need to do this from within firefox or chrome as I am required to be logged in to the website,
Thanks,
A

A: Whilst it's possible to do this with curl (including the login), I would recommend using a browser extension. Flashgot for Firefox is excellent, you can tell it to download all files of a certain extension, or do things like pattern matching.
http://flashgot.net/


Q: Why do we need to define a function to call another function? In the implementation of ResNet architecture in Pytorch I encountered the code below which is from line 264 til 283:
def _forward_impl(self, x: Tensor) -> Tensor:
    # See note [TorchScript super()]
    x = self.conv1(x)
    x = self.bn1(x)
    x = self.relu(x)
    x = self.maxpool(x)

    x = self.layer1(x)
    x = self.layer2(x)
    x = self.layer3(x)
    x = self.layer4(x)

    x = self.avgpool(x)
    x = torch.flatten(x, 1)
    x = self.fc(x)

    return x

def forward(self, x: Tensor) -> Tensor:
    return self._forward_impl(x)

What is the purpose of _forward_impl? Why didn't the coder bring what is happening inside _forward_impl into forward itself and getting ride of _forward_impl? I see _forward_impl looks like a private method, since it has underscore at the start of its name, however, I cannot yet see what the purpose of _forward_impl is.


Q: How to read logging configuration from appsettings.json in .net Core 2.2 In .net Core 2.1 it was done like this
var loggingConfig = configuration.GetSection("Logging");
loggerFactory.AddConsole(loggingConfig);

I have moved it to ConfigureServices and now I get

Error CS1503  Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action Microsoft.Extensions.Logging.Console.ConsoleLoggerOptions'

A: Base on this you may have to change the way you are configuring your application:
var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json",
                      optional: true, reloadOnChange: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();

1 Microsoft ASP.NET Core 2.2 Logging documentation


Q: Facebook Likeview is not working I have implemented Like as suggested on Facebook developer site
I just added Likeview and set Object id for post code is as below
likeView  = (LikeView)findViewById(R.id.like_view);
    likeView.setObjectId("https://www.facebook.com/karan.raj.5070276/posts/396696657159566");

My layout file has LikeView widget
<com.facebook.widget.LikeView
    android:id="@+id/like_view"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="30dp" />

On clicking it just opens Dialog for sometime and it disappears without any action
and In log-cat I finds error message like
"Like dialog is only available to developers and tester"
What should I do In my Facebook app. Should I add Roles for developer and tester
Please help any help will be appreciated

A: Login your facebook with same user which you have created facebook app with. This error appeared because you logged in facebook with other user.
Note: By default Facebook app app is in development mode and can only be used by app admins, developers and testers.


Q: Offsets to create n-sided shape around starting point in Javascript I would like to find an function where, given a starting point (x, y) P, a radius r, and an integer n, I can generate offsets from P to create n well-placed points to create a shape (within a circle of radius r) around P.
For example:
For P = {x: 0, y: 0}, r = 25.
Where "offsets" is the return value of the desired function...
Let n = 0:
    offsets = [];
Let n = 1:
    // Note 25 here is simply P.x + r, where P.x = 0 for simplicity's sake.
    // So x: 25 is actually x: P.x + 25
    // And y: 0 is actually y: P.y + 0
    // I've kept the simplified notation here and below for readability.
    offsets = [{x: 25, y: 0}];
Let n = 2: // Line
    offsets = [{x: 25, y: 0}, {x: -25, y: 0}];
Let n = 3: // Triangle
    offsets = [{x: 25, y: 0}, {x: -25, y: 0}, {x: 0, y: 25}];
Let n = 4: // Square
    offsets = [
      {x: 25, y: 0},
      {x: -25, y: 0},
      {x: 0, y: 25},
      {x: 0, y: -25}
    ];
Let n = 5: // Pentagon
    offsets = [
      {x: 25, y: 0},
      {x: -25, y: 0},
      {x: 0, y: 25},
      {x: -12.5, y: -25},
      {x: 12.5, y: -25}
    ];

.... and so on.

A: Just sample a circle:
allocate offset array
var angle = 2 * Math.PI / n;
for(var i = 0; i < n; ++i)
    offsets[i] = {x: r * Math.cos(i * angle), y: r * Math.sin(i * angle)};


Q: Why is setuid not running as the owner? I am currently trying to learn what the special bits in file permissions do but am currently stuck trying to understand what the setuid bit does. From all the online resources it says:

Commonly noted as SUID, the special permission for the user access level has a single function: A file with SUID always executes as the user who owns the file, regardless of the user passing the command

However in a simple experiment this just doesn't appear to be true (unless I have misunderstood and am doing something wrong?)  i.e.
mkdir /tmp/foo
mkdir /tmp/foo/bar
chmod 0700 /tmp/foo/bar                        # Restrict directory so only current user can access
echo content > /tmp/foo/bar/baz.txt            # Create content in the restricted directory
echo "ls /tmp/foo/bar" > /tmp/foo/myscript.sh  # Script to access content of restricted directoy
chmod 4777 /tmp/foo/myscript.sh                # Set setuid bit so the script runs as current user
/tmp/foo/myscript.sh                           # Show it works when run as current user

#> baz.txt

su bob                 # Switch to a new user
/tmp/foo/myscript.sh   # Run script again

#> ls: cannot open directory '/tmp/foo/bar': Permission denied

My expectation was that as the setuid bit was set the script should have been executed as the original user and as such should have had permissions to ls into the restricted directory. But instead I got a permissions denied error indicating that the script was not run as the original user.
Any help into understanding what I'm doing wrong would be greatly appreciated. (example was run on zsh / ubuntu 20.04 / wsl2)

A: The suid bit works only on binary executable programs, not on shell scripts. You can find more info here: https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts


Q: Managing users in the TFS work items "Assigned To" field So I know there have been a couple of posts around about this topic, but I don't think they've quite got to the bottom of it!
So my problem is that when I create a new work item in TFS, the users which I can assign it to include NT Authority\Local Service (which is also the TFS service account). I'm not asking why, as I know that this field, by default is populated by the Valid Users group, and upon inspecting the groups, I can see that the group permissions hierarchy looks like this:
 -> Valid Users
   -> Project Collection Admistrators
      -> Project Collection Service Accounts
         -> NT Authority\Local Service

And you can't change anything in the project collection service accounts, so surely by default, everyone has this user in the assign to field? So does this mean everyone accepts it, or do they modify their process templates to filter it out (see the blog here)?
Just seems a bit odd to me that by default is isn't filtered out already! Clearly I don't want to be removing this from any permissions either (even if I could) as I'm worried it'll cause problems later.
So is filtering in the process template the only way (which looks like a bit of effort to maintain), or is there a simpler way?

A: Under TFS2008, you do need to do it this way.  Under 2010, there might be an "exclude", but I'm not able to check that at the moment.
To keep from having a whole lot of maintenance, instead of listing each user individually, what we did was just pared down the list from "Valid Users" to the "Moderators" and "Contributors".  We know that we can control those groups without affecting service permissions:
        <FIELD name="Assigned To" refname="System.AssignedTo" type="String" reportable="dimension">
            <ALLOWEDVALUES expanditems="true">
                <LISTITEM value="[Project]\Contributors"/>
                <LISTITEM value="[Project]\Moderators"/>
            </ALLOWEDVALUES>
        </FIELD>