Q: Delay adding a class for 2 seconds in hover() How do I use easing or time delay on addClass();?
$("#date_1").hover(
    function () {
        $(this).addClass("door");
        $(this).addClass("doorstatic", "slow"); // after 2seconds i want to add this class during the hover
    },
    function () {
        $(this).removeClass("door");
        $(this).removeClass("doorstatic"); // both classes are instantly removed when hover off
    }
);

A: The setTimeout method of javascript can be used to run code you specify after a set delay in miliseconds.
Try this:
var timeout;
$("#date_1").hover(
    function () {
        $(this).addClass("door");
        timeout = setTimeout(function() { $(this).addClass("doorstatic"); }, 2000);
    }, function () {
        clearTimeout(timeout);
        $(this).removeClass("door doorstatic");
    }
);

A: Actually you can just append a call to jQuery's delay to you addClass call.
Something like
 $(this).addClass("door").delay(2000).addClass("doorstatic", "slow");

should do the trick.

A: $("#date_1").hover(
    function () {
        var $this = $(this);

        $this.addClass("door");
        setTimeout(function() {
            $this.addClass("doorstatic");
        }, 2000); // 2000 is in mil sec eq to 2 sec.
    },
    function () {
        $(this).removeClass("door doorstatic");
    }
);

You can group your classes like removeClass("door doorstatic")
The problem here is that if you mouseover and before two seconds mouse out you will still have the class doorstatic on you element.
The fix:
$("#date_1").hover(
    function () {
        var $this = $(this),
            timer = $this.data("timer") || 0;

        clearTimeout(timer);
        $this.addClass("door");

        timer = setTimeout(function() {
            $this.addClass("doorstatic");
        }, 2000); // 2000 is in mil sec eq to 2 sec.

        $this.data("timer", timer);
    },
    function () {
        var $this = $(this),
            timer = $this.data("timer") || 0;

        clearTimeout(timer);
        $this.removeClass("door doorstatic");
    }
);

Created a live example of the solution at jsFiddle.


Q: Can i create application in Windows for Linux platform? I have around of 4 years experience in C#.Net programming and i am developing a client server application. The server application will be insalled on CentOS and client application will be installed in Windows OS. But, i don't have much knowledge about c++ programming on linux platform. So, my question is that can i create a console application in Windows OS and compile it for linux platform. it is not necessary that compile it on Windows. but, it should be executed in linux platform. I am new in linux programming.
Presently i am using TC++ editor. Can i use Visual Studio 2010 to build server application for linux platform?
if there are another approach then please suggest me.
Thanks.

A: Maybe you can use VS as an editor ; Make sure that you do not include any windows specific libs; There is an option of using cygwin and doing a cross compilation. Check the links
How to cross compile from windows g++ cygwin to get linux executable file
I guess it will be more of a pain. Better use Virtual Box --> linuxMint/Ubuntu  + Eclipse with C++ plugin or some other C++ editor...

A: You can develop the client in C# and the server in C++, if you prefer. Consider that unlike C#, there is no standard socket library yet, and you'll have to rely on either system calls or their higher level wrappers (like boost).
I've to tell you that Windows uses BSD sockets (its own version, with some modifications though), therefore with a few preprocessors checks, you can make your application portable.
In your case, I'd suggest you to go for boost.asio which will hide all low-level stuff for you. It's even cross-platform.


Q: Font face with Google Chrome Since some days, my Google Chrome browser doesn't show special fonts : CSS with font-face.
@font-face {
    font-family: 'Babel Sans';
    src: url('../fonts/babelsans.eot');
    src: url('../fonts/babelsans.eot?#iefix') format('eot'),
         url('../fonts/babelsans.woff') format('woff'),
         url('../fonts/babelsans.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

All working fine with Safari, Firefox and IE, and it worked fine the last week.
Someone has the same problem and someone know how I can resolve it ?
Thanks,

A: I'm experiencing the same issue since Chrome 20 update. This thing happen in Windows Xp and Mac Os X 10.6.8.
Safari and Mobile Safari (that share WebKit engine with Chrome) works perfectly like Firefox and IE.
My css code is exactly like yours.
Looking in the inspector it seems that the font doesn't get downloaded.
Sometimes while navigating different pages (that share the same css external file) in my website the font loads and get displayed properly.
Still trying to solve this...
EDIT:
I managed to solve this issue.
I don't know why, but using this worked:
http://www.fontsquirrel.com/fontface/generator/
I uploaded my font, got the css and converted files, uploaded them to my server and replaced font-face declaration...bling! It works! Hope that works for you too!

A: It's working now, I think Google has update the browser.

A: Since there was an update of Chrome for about a week, you may try using an older version to find out if it's a bug (I myself didn't notice any problems). Get one at http://www.oldapps.com/google_chrome.php.
Also check if you're using this font in addion to other font-related CSS values (if so, deactivate them). There were some problems in the past which actually have been solved, but you never know...

A: First: Convert you font using this service  as Mr Stefano suggest:
Later use this CSS code to use your font in your project:
@font-face {
    font-family: 'aljazeeraregular';
    src: url('aljazeera-webfont.eot');
    src: url('aljazeera-webfont.eot?#iefix') format('eot'),
         url('aljazeera-webfont.woff') format('woff'),
         url('aljazeera-webfont.ttf') format('truetype'),
         url('aljazeera-webfont.svg') format('svg');
    font-weight: normal;
    font-style: normal;

}

body {
    background-color: #eaeaea;
    font-family: 'Aljazeera';
    font-size: 14px;
}

Note that when you call font-family in your site you have to use its original name not like what you declare it in @font-face.


Q: I want to search list elements in txt file I want to search for list elements in txt file. However with this code I don't get the desired result. I have tried several solutions, but none of them really worked.
def run(self):
    hostname = self.queue.get()
    with open('allhosts.txt', "r+") as file1:
        fileline1 = file1.readlines()
        for x in hostname:
            for line in fileline1:
                if x in line:
                    self.found.emit(hostname)
                else:
                    self.notFound.emit(hostname)

A: Use regx in this case
import re

str = open('a.txt', 'r').read()

m = re.search('(?<=hostname)(.*)', str)
print ("hostname",(m.groups()))

If you dont get output. please drop text file screenshot


Q: how to remove port from x-forwarded-for header in azure webapp? I have a Joomla app on azure's WebApp on Linux.
I want to get the client ip in order to be able to block by ip with the Admin Tools extension.
The admin tools has an option to get the client ip from the x-forwarded-for header, the problem azure is adding a random port to the client ip by so making blocking impossible.
How can I get rid of the port?

A: You can use Azure Application Gateway.
https://learn.microsoft.com/en-gb/azure/application-gateway/features#rewrite-http-headers


Q: C Random Number Generation (pure C code, no libraries or functions) I need to generate some random numbers in C for testing and debugging the system. The system is a custom hardware (SoC) with a limited set of functions so I can only use basic mathematical operations.
And no, I can't use random number generators in stdlib or math.h. I need to write it myself. So is there some sort of algorithm for generating random numbers?
I know that a simple solution is to generate the numbers here on my workstation and embed them into the module, but I don't want to do that.

A: Just dig up the article by Park and Miller in the Oct 88 issue of CACM.
The general algorithm they propose is:
a = 16807;
m = 2147483647;
seed = (a * seed) mod m;
random = seed / m;

Though the article includes several refinements.

A: A random number generator is basically a special* hash function which runs recursively from a starting seed.
I've used the MurmurHash2 algorithm in my C# code to good effect. It's extremely fast and simple to implement and has been tested to be very well distributed with low collision rates. The project has several different open source hash functions written in C++ which should be easily convertible to C.

* By special I mean that running the hash function on a value should return another seemingly random (but determinate) value, so that the output doesn't appear to form patterns. Also, the distribution of the returned value should have a uniform distribution.

A: A linear congruential generator would be simple to implement. A nice implementation in pure C is available here.

A: You can try Multiply-with-carry by George Marsaglia.
Code from Wikipedia:
#include <stdint.h>

#define PHI 0x9e3779b9

static uint32_t Q[4096], c = 362436;

void init_rand(uint32_t x)
{
    int i;

    Q[0] = x;
    Q[1] = x + PHI;
    Q[2] = x + PHI + PHI;

    for (i = 3; i < 4096; i++)
            Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i;
}

uint32_t rand_cmwc(void)
{
    uint64_t t, a = 18782LL;
    static uint32_t i = 4095;
    uint32_t x, r = 0xfffffffe;
    i = (i + 1) & 4095;
    t = a * Q[i] + c;
    c = (t >> 32);
    x = t + c;
    if (x < c) {
            x++;
            c++;
    }
    return (Q[i] = r - x);
}

A: Check the source code of the gsl library, a couple of well tested algorithms are implemented in it.

A: You may want to look for Mersenne Twister. There are lots of algorithms of higher quality. A good article with an overview you find here:
http://en.wikipedia.org/wiki/Pseudorandom_number_generator

A: You might try Isaac which is also available as part of CCAN here


Q: MissingSchema: Invalid URL '/': No schema supplied. Perhaps you meant http:///? for l in l1:
r = requests.get(l)
html = r.content
root = lxml.html.fromstring(html)
urls = root.xpath('//div[@class="media-body"]//@href')
l2.extend(urls)

while running the above code this error coming. any solution??
MissingSchemaTraceback (most recent call last)
MissingSchema: Invalid URL '/': No schema supplied. Perhaps you meant http:///?

A: urls = root.xpath('//div[1]/header/div[3]/nav/ul/li/a/@href')

These HREFs aren't full URLs; they're essentially just pathnames (i.e. /foo/bar/thing.html).
When you click on one of these links in a browser, the browser is smart enough to prepend the current page's scheme and hostname (i.e. https://host.something.com) to these paths, making a full URL.
But your code isn't doing that; you're trying to use the raw HREF value.
Later on in your program you use urljoin() which solves this issue, but you aren't doing that in the for l in l1: loop.  Why not?


Q: Using git and svn I have been trying to solve this problem on my own. However I did not find a solution that really works. All my attempts ended with conflicts, many rebases, etc. etc.
So, I have the following setup:
Git is my main CVS for all my projects.
For one of the projects I am using the wp7 silverlight toolkit from codeplex.com.
However for my project I need to change some lines of code in the toolkit.
So, I would like to have the following scenario:

*

*In Git I would need to have a clone of the SVN repo from codeplex.
So, I could easily work on it.(Btw the SVN repo is read-only)

*However, from time to time I would need to fetch the latest updates
from the SVN repo.

How can I accomplish this scenario?
Thank you for your help!

A: Within your project could the toolkit be in a subfolder which is managed by svn?
A simplistic approach (which misses out the opportunity to import the svn version history git-svn which basicxman mentions) would be to manage the whole project using git including the contents of the folders updated by svn.  You may wish to exclude the .svn directories through.
Try adding a line to  .git/info/exclude for your project to ignore files or folders called .svn

A: You are making changes to the codeplex code. Make those changes on a branch. Keep master up to date with the codeplex svn repo using git-svn. After an update, merge master into your changes branch.
Then share your codeplex repo with your main repo as a submodule as suggested before.


Q: var Hoisting in JavaScript Consider the following code in JavaScript-
var DEFAULT_RATE=0.01;
var rate=0.04;
function getRate() {
  if(!rate) {
    var rate=DEFAULT_RATE;
  }
  return rate;
}
console.log(`Rate is`,getRate());

The output of the following code is 0.01
My takeaway from this is that vars are hoisted(and declared undefined) to the top of the scope pertaining to the where they are used. In case of let and const, they go into TDZ but that is a different thing entirely.
But I also learnt that var has a global scope. Then var show not allow variable redeclaration.
Isn't the global scope mean the scope containing the entire code? Have I understood it wrongly?

A: When using var to declare variables, the variable can take on either function or global scope. If var is used within a function, it has function scope, if var is used outside of any function, the variable has Global scope.
So, your statement of:

But I also learnt that var has a global scope. Then var show not allow
variable redeclaration.

Is actually, not really accurate because it depends on where var is used and redeclaration (more correctly known as variable "hiding") is possible in any smaller scope than the first declaration was made.
When declaring with var, the declaration is hoisted to the top of the scope.
I've written another answer that describes and demonstrates this in detail.

A: In JavaScript, function declarations are hoisted before var declarations, and assignments are not hoisted.
So the sample code from the question:
var DEFAULT_RATE=0.01;
var rate=0.04;
function getRate() {
  if(!rate) {
    var rate=DEFAULT_RATE;
  }
  return rate;
}

has this effective ordering:
// hoisted function
function getRate() {
  var rate = undefined; // <- hoisted local variable
  if(!rate) { // <- always true
    rate = DEFAULT_RATE; // <- always executed
  }
  return rate; // <- always returns DEFAULT_RATE (0.01)
}

// hoisted vars
var DEFAULT_RATE;
var rate;

// not-hoisted assignments
DEFAULT_RATE = 0.01;
rate = 0.04;

// not-hoisted function call
console.log(`Rate is`,getRate());

Since getRate() contains var rate, the function-scoped rate is hoisted to the beginning of getRate(), with a value of undefined.
Therefore if(!rate) evaluates to if(!undefined), which is always true, and getRate() always returns DEFAULT_RATE (0.01).


Q: Creating AppDomain using .net Framework 4 gives OutOfMemoryException I'm trying to create an appdomain in VB / VS2015 using .net Framework 4, 64-bit, but am getting an OutOfMemoryException.
domain = AppDomain.CreateDomain("mydomain")

It works fine if I do it in a Windows Form Application, but I'm trying to do it in a class library (to be called from a 3rd-party application), and it fails every time.
I'd like to know if it is legal to create an appdomain in these circumstances (after all, I'm not creating an application), and the error message is misleading, or is there something else I'm missing (security evidence?).
Microsoft admit to a bug in Framework 4.5 which gives this error (see this), but I'm using Framework 4.
To give a bit more background, I'm using an appdomain to dynamically load and unload a dll which I am creating, so I can unload, recompile and reload during development, as the 3rd-party application which calls my dll is very slow to boot up and load documents. I'd like to get as close as possible to Edit and Continue!

A: I got the same error and tracked it down a little bit inside clr.dll.
The function internally calls GetSystemInfo (kernel32) to check the allocation granularity.
A quick and dirty fix for this issue: Detour GetSystemInfo
see example code here ( I used Process.NET for the detour, it’s quick and easy)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;
using ProcessDotNet;
using ProcessDotNet.Applied.Detours;

namespace Bootstrap
{

    [UnmanagedFunctionPointer(CallingConvention.Winapi)]
    public delegate void GetSystemInfoDelegate(ref SYSTEM_INFO info);

    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEM_INFO
    {
        public ushort processorArchitecture;
        ushort reserved;
        public uint pageSize;
        public IntPtr minimumApplicationAddress;
        public IntPtr maximumApplicationAddress;
        public IntPtr activeProcessorMask;
        public uint numberOfProcessors;
        public uint processorType;
        public uint allocationGranularity;
        public ushort processorLevel;
        public ushort processorRevision;
    }

    class Loader
    {
        static void GetSystemInfoDetoured(ref SYSTEM_INFO info)
        {
            info = new SYSTEM_INFO();
            GetSystemInfoDetour.Disable();
            GetSystemInfo(ref info);

            info.allocationGranularity = 1000000;

            GetSystemInfoDetour.Enable();
        }

        static Detour GetSystemInfoDetour;
        static GetSystemInfoDelegate GetSystemInfo;

        static void Main(string[] args)
        {
            TestDomainCreation();
        }

        static void TestDomainCreation()
        {
            AppDomainSetup setup = new AppDomainSetup();

            ProcessSharp s = new ProcessSharp(Process.GetCurrentProcess(), ProcessDotNet.Memory.MemoryType.Local);

            GetSystemInfo = s["kernel32"]["GetSystemInfo"].GetDelegate<GetSystemInfoDelegate>();
            DetourManager dtm = new DetourManager(s.Memory);
            GetSystemInfoDetour = dtm.CreateAndApply(GetSystemInfo, new GetSystemInfoDelegate(GetSystemInfoDetoured), "GetSystemInfoDetour");

            var tempDomain = AppDomain.CreateDomain("HappyDomain", null, setup);

            GetSystemInfoDetour.Disable();
            GetSystemInfoDetour.Dispose();
        }
    }
}

Regards


Q: DataTable From Session Memory has No Columns Im trying to retrieve a datatable that I put into a session variable, however when i do it apears that there are no columns...
I have done this before in VB.NET, I'n now using C#, and it worked perfectly, and as far as i can see there is no change in the code other than the obvious syntax changes.
EDIT:
The dt (in part 2) variable has the right data when i look in the data visulization window, but i have noticed that the other properties associated with a datatable are abscent. When i hover over a normal looking datatable with my mouse it looks like the following: " dt ----- {System.Data.DataTable}" but in the class im working on it just looks like "dt ----- {}".  Also, after I return the session variable into the dt I clone it (dtclone = dt.clone(); ) and the clone is empty in the data visulizer.... what on earth!
EDIT 2:
I have now also tried converting the first datatable to a dataset, putting this in the session variable, and recoverting it back to a datatable in the class.
Am starting to wonder if it is a probelm with:
    dt.Load(sqlReader);

The data does appear after this step though in the dataset visualiser, but not after being cloned.
Code below.
All help very welcome!
Thanks in advance
Chris
1) SQL command in a webhandler, the results of which populate the datatable to be put into the session variable.
    DataTable dt = new DataTable();

    SqlDataReader sqlReader= default(SqlDataReader);
    SqlDataAdapter sqlAdapter = new SqlDataAdapter();

    sqlReader = storedProc.ExecuteReader(CommandBehavior.CloseConnection);

    dt.Load(sqlReader);
    System.Web.HttpContext.Current.Session["ResultsTable"] = dt;

2) Part of the code in a class which performs calculations on the table:
    DataTable dt = (DataTable)HttpContext.Current.Session["ResultsTable"];

A: did you call DataTable dispose after setting Session Var?
Because if you do this, solution is like this:
System.Web.HttpContext.Current.Session["ResultsTable"] = dt.Copy();


Q: replacing escape character with double qoutes in c# I have the following string in a variable called,
s:
[{\"roleIndex\":0,\"roleID\":\"c1_r0_23\",\"roleName\":\"Chief Executive\"},
{\"roleIndex\":1,\"roleID\":\"c1_r1_154\",\"roleName\":\"Chief Operator\"}]

and I'm trying to replace \" with " with the following command:
   s.ToString().Replace("\"", """");

but this is not working.
What is the correct syntax in c#?

A: Try s.ToString().Replace(@"\""", "\"").
The @ tells C# to interpret the string literally and not treat \ as an escape character. "\"" as the second argument uses \ as an escape character to escape the double quotes.
You also don't need to call ToString() if s is already of type string.
Last but not least, don't forget that string replacement is not done in place and will create a new string. If you want to preserve the value, you need to assign it to a variable:
var newString = s.ToString().Replace(@"\""", "\"");
// or s = s.Replace(@"\""", "\"");  if "s" is already a string.

A: Update
if you have a string containing ", when you view this string in the Visual Studio immediate window it will display it as \". That does not mean that your string contains a backslash! To prove this to yourself, use Console.WriteLine to display the actual value of the string in a console, and you will see that the backslash is not there.
Here's a screenshot showing the backslash in the immediate window when the string contains only a single quote.

Original answer
Three things:

*

*Strings are immutable. Replace doesn't mutate the string - it returns a new string.

*Do you want to replace a quote "\"" or a backslash followed by a quote "\\\"". If you want the latter, it would be better to use a verbatim string literal so that you can write @"\""" instead.

*You don't need to call ToString on a string.

Try this:
s = s.Replace(@"\""", "\"");

See it on ideone.

A: Ironically, you need to escape your quote marks and your backslash like so:
s.ToString().Replace("\\\"", "\"");
Otherwise it will cat your strings together and do the same as this (if you could actually use single quotes like this):
s.ToString().Replace('"', "");
(your second string has four quotes... that's why you're not getting a compile error from having """)


Q: Merge two Pandas DataFrames based on approximate or exact matches Below is the DataFrames example I want to merge.
#!/usr/bin/env python

import pandas as pd

countries   = ['Germany', 'France', 'Indonesia']
rank_one    = [1, 5, 7]
capitals    = ['Berlin', 'Paris', 'Jakarta']
df1         = pd.DataFrame({'country': countries,
                            'rank_one': rank_one,
                            'capital': capitals})

df1 = df1[['country', 'capital', 'rank_one']]

population = ['8M', '82M', '66M', '255M']
rank_two   = [0, 1, 6, 9]
df2        = pd.DataFrame({'population': population,
                           'rank_two': rank_two})

df2        = df2[['rank_two', 'population']]

I want to merge the both DataFrames based on an exact or approximate match.
if rank_two is equal to rank_one
OR
rank_two is the closest and next bigger number from rank_one.
Example :
df1 :
     country  capital  rank_one
0    Germany   Berlin         1
1     France    Paris         5
2  Indonesia  Jakarta         7

df2 :
   rank_two population
0         0         8M
1         1        82M
2         6        66M
3         9       255M

df3_result :
     country  capital  rank_one  rank_two population
0    Germany   Berlin         1         1        82M
1     France    Paris         5         6        66M
2  Indonesia  Jakarta         7         9       255M

A: By using merge_asof
pd.merge_asof(df1,df2,left_on='rank_one',right_on='rank_two',direction='forward')
Out[1206]:
     country  capital  rank_one  rank_two population
0    Germany   Berlin         1         1        82M
1     France    Paris         5         6        66M
2  Indonesia  Jakarta         7         9       255M

A: You can use the pandas 'merge_asof' function
pd.merge_asof(df1, df2, left_on="rank_one", right_on="rank_two", direction='forward')

alternatively if you want to merge by closest and you don't mind if it's higher or lower you can use:
direction="nearest"


Q: undefined method `<' for nil:NilClass While creating a bubble sort program i ran into this error:
test.rb:8:in `block in bubble_sort': undefined method `<' for nil:NilClass (NoMethodError)
    from test.rb:6:in `downto'
    from test.rb:6:in `bubble_sort'
    from test.rb:16:in `<main>

does anyone know what does that mean? Here is the code:
def bubble_sort(arr)
    length = arr.length
    sorted = false

    length.downto(0) do |cntr|

        if arr[cntr] < arr[cntr + 1]

        end

    end
end

bubble_sort([2,6,8,1,0,2])

A: The error message undefined method '<' for nil:NilClass means that you are trying to call < on something that is nil.
In your example that must be the if arr[cntr] < arr[cntr + 1] comparison. In a next step we need to find out why arr[cntr] is nil. One reason could be that there is no element in the arr array at the cntr index, another reason might be that the index cntr is out of bounds of the array. In your example it is the second reason that is causing the problem.
Why is the index out of bounds? Let's have a closer look how the loop is build and use an example array [a, b, c] to do so:
length = arr.length              # length = 3             # [a, b, c].length
length.downto(0) do |cntr|       # 3.downto(0) do |cntr|
  if arr[cntr] < arr[cntr + 1]   #   if arr[3] < arr[4]   # in the first iteration

Ops, there aren't not indexes 3 and 4 in the arr array, because indexes start counting with 0 and there are only 3 elements in my example (that makes the last element's index 2).
The fix:
def bubble_sort(array)
  (array.length - 2).downto(0).each do |index|
    if array[index] < array[index + 1]
      # ...
    end
  end
end

A:
does anyone know what does that mean?

It means that arr[cntr] is nil in this expression
if arr[cntr] < arr[cntr + 1]

Oh, and if this one is nil, then arr[cntr + 1] is definitely nil.
Hint: you're accessing elements out of bounds of the array.

A: In your code length variable value will be 6(length = arr.length).
When you iterate it down to 0 ... in the first iteration cntr variable value will be 6.
so arr[cntr] is getting nil value because you are accessing elements out of bounds of the array. That's why you are getting undefined method < for nil:NilClass (NoMethodError) error.


Q: How to scan image taken by camera intent to update gallery in android I have this code in my app but it doesn't seem to be working.  Only after restarting my phone then all the images are displayed in the gallery.  No i am wondering is there a way to do this as soon as the photo is taken and then update the gallery without the need to restart the phone.
this is what i have:
protected void mediaScan() {
  sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                 + Environment.getExternalStorageDirectory() + "/" +getResources().getString(R.string.app_name))));

Could anyone please help?

A: Use MediaScannerConnection and its static scanFile() method:
MediaScannerConnection.scanFile(this, new String[] { yourPath }, null, null);


Q: change/modify the dropdownlist text by value using jquery i have dropdownlist with the values:
<select id="myddl" name="myddl">
  <option value="1">One</option>
  <option value="2">Twooo</option>
  <option value="3">Three</option>
</select>

I need to change the text Twooo to Two using the value of the dropdownlist option(2). How can i do it in jquery?

A: $('#myddl option[value=2]').text('Two');

A: var myDLLField = $('select[id="myddl"]');
myDLLField.find('option[value="2"]').text("Two");

or, in one line...
$('select[id="myddl"]').find('option[value="2"]').text("Two");


Q: Unable to register Google Play - Developer console Are we able to be both user of a developer account and owner of a developer console ?
The fact is that my personal Google address is linked to a developer console for my work and I wanted to create my own developer console to publish my personal apps.
Unfortunately, I got the error below while creating my own developer console on Google Play Services. I look for leaving the other account but I wasn't able to find anything like this.

Oh oh ! An error occurred. An unexpected error has occurred. Please retry later.

If possible, I don't want to create a new account but unlink my personal account from my work developer console.
Thanks in advance for your help.

A: After looking at network requests, I saw a request going to Google Payments Services which end to a 500 error. At this moment, I just remember that I've conflict with my Google Payments account. When I solved it, I was totally able to be both member of a Developer Console and owner of my own Developer Console. On the Developer Console UI, I'm able to switch between the 2 accounts thanks to the menu on top right corner.


Q: Bitbucket - push a new projet to my bitbucket repo I have the folder in my htdocs and I want to push it to an empty bitbucket repo.
So far I've followed the instructions on bitbuket website
git init
git remote add origin https://andradebuddha@bitbucket.org/musica.git

cd /path/to/my/repo
git remote add origin https://andradebuddha@bitbucket.org/musica.git
git push -u origin --all # pushes up the repo and for the first time

But And I'm getting this error
No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
Everything up-to-date

A: Solved - I've missed a step.
git add -A # to add the brand new folders structure

And
git commit -m 'inicio do projeto'

and finaly
git push -u origin all

A: Try specifying the branch as indicated in the error message.
instead of git push -u origin --all try git push origin master


Q: How to divide one row in various? I have a column data in a postgresql table that receive data like this: |A|C|F|L|T|U|
The others columns are name, date
Example:
NAME    | DATE       | DATA
ALYSSON | 2019-01-01 | |A|B|C|

How to create a select that return:
NAME    | DATE       | DATA
ALYSSON | 2019-01-01 | A
ALYSSON | 2019-01-01 | B
ALYSSON | 2019-01-01 | C

A: You can use string_to_array along with unnest to break your data into first an array and then separate rows.
select * FROM (
  select name, date, unnest(string_to_array(data, '|')) as data from stuff
) AS sub
WHERE sub.data != '';

The WHERE clause is required to remove the empty strings at the beginning and end of your data.


Q: Can HTTP-header LAST-UPDATED be trusted? I have been using Rex Swain's HTTP Viewer to verify that none of the texts on a certain webpage has been changed recently.
The response was: "Code last updated 21 January 2012", so as I understand it, I can't really assume that anything was actually changed on that date but is it safe to assume that none of the texts on the webpage has been changed since that date?
I am not an HTTP expert, so please use layman terms where possible, thanks :-)
BR

A: A web server typically uses the corresponding file's last updated attribute as the value for the HTTP Last-Modified header, so in general it can be trusted, but it's always possible that the date is wrong, for whatever reason.
The Last-Modified header is usually used for caches, to populate the If-Modified-Since header in subsequent requests.


Q: Make a fixed position element appear behind a static position element How can you make an element that has a position: fixed display behind an element with position: static? Changing z-index doesn't seem to matter since they are not absolute.

A: You can use negative z-index on the fixed element.

This is fixed

This is static

#fixed {
    position:fixed;
    z-index:-1;
}

Fiddle Demonstration


Q: TinyMCE editor dislikes being moved around On a page I have, I need to move TinyMCE editors in the DOM tree once in a while. However, for some reason, the editor doesn't like it: it clears itself completely and becomes unusable. As far as I can see, this behavior is consistent between Safari 4 and Firefox 3.6, but not Internet Explorer 7/8. Here's an example.
It truly is annoying to do something that works in Internet Explorer but not with more appreciable browsers. Is there something I missed in the docs about never trying to move an editor in the DOM tree? Is there some kind of workaround?

A: This is a browser bug/issue not a problem with TinyMCE. It's impossible to retain iframe contents in some browsers since once you remove the node from the dom the document/window unloads. I suggest first removing the editor instance then re-adding it instead of moving it in the DOM.

A: Had the same issue and here's how I resolved it...
Create the issue
I use jquery to move the dom element that contains the tinymce editor that causes it to lose all it's contents:
$('.form-group:last').after($('.form-group:first'))

After this point, the editor's iframe contents are removed.
The Solution
var textareaId = 'id_of_textarea';
tinyMCE.get(textareaId).remove();
tinyMCE.execCommand("mceAddEditor", false, textareaId);

There are times when the editor will add the iframe back, but not be visible.  If that's the case, unhide the container:
$textarea = $('#' + textareaId)
$textarea.closest('.mce-tinymce.mce-container').show()

Note, this is using tinymce 4.x.


Q: Subsetting a vector base on another vector I have 2 input vectors, iv1 and iv2, as shown below. I would like to separate the elements of the second vector according to elements of the first. It works like this: The values in iv2 between the first 2 values of iv1 are stored in ov1, the values in iv2 between the second and third values of iv1 are stored in ov2, and so on. Note: The values in iv1 and iv2 are already in ascending order. Any thoughts please?
Input:
iv1 <- c(100, 200, 300, 400, 435)
iv2 <- c(60, 120, 140, 160, 180, 230, 250, 255, 265, 270, 295, 340, 355, 401, 422, 424, 430)

Desired output:
ov1 = c(120, 140, 160, 180)
ov2 = c(230, 250, 255, 265, 270, 295)
ov3 = c(340, 355)
ov4 = c(401, 422, 424, 430)

A: As @RonakShah suggested, the most efficient way in this case may be this:
split(iv2, cut(iv2, breaks = iv1,labels = paste0('ov',1:4)))

Output:
$ov1
[1] 120 140 160 180

$ov2
[1] 230 250 255 265 270 295

$ov3
[1] 340 355

$ov4
[1] 401 422 424 430


Q: Unable to invalidate Asp.Net Session during IdP initiated Single LogOut with WSO2 we are implementing a Single Sign On process using WSO2 Identity Server. We have both Microsoft and Java web applications involved and we are facing a problem during the Single LogOut processing with Microsoft based web apps. The issue is related to session invalidation on Identity Provider initiated SLO.
This is the scenario:

*

*WSO2 Identity Server with a single Identity Provider configured

*an Asp.Net MVC application using ComponentSpace SAML2 assembly and Forms authentication marking controllers with the [Authorize] attribute to ensure that users are authenticated to access them.

*the DEMO Java Web application provided by WSO2 to test SSO

The login process works fine. We get a session ID from WSO2 and the user is authenticated landing on WSO2 login form in the first app, and transparently in the sencond one.
In the Asp.Net webapp, when a successfull login occurs, we authenticate the user to access [Authorize] marked controllers calling FormsAuthentication.SetAuthCookie(userName, false); . When the user logout from one of the apps, WSO2 sends a SLO request to other partecipants on a configured URI. When this request is reveived by the Microsoft one, we call the FormsAuthentication.SignOut(); method but the session is not destroyed. If the user refresh the browser page its User.Authenticated property is still True so he can still access [Authorize] marked controllers. This makes sense in my opinion because the caller is WSO2 and not the user browser.
We performed some investigation in the code of the JAR provided by WSO2 for Java applications and it creates a filter on Tomcat implementing a singleton to store WSO2 Session ID relation with Session objects each time a success login operation occurs. When WSO2 request a SLO the filter gets WSO2 Session ID as parameter, accesses the singleton HashTable to retrieve the Session object and calls the Session.Invalidate() method of the session object. If the user refreshes the browser, he gets redirected to login page. We tryied to implement something similar on Asp.Net side but even if we get the Session object on server side and call the Session.Abandon() method nothing happens when the user refresh the browser. He is still marked as authenticated.
I am not very familiar with Cookies and I have the feeling that is something related to them.
Had anyone faced a similar issue?
Any advice or suggestion will be very appreciated.
Thanks

A: Calling FormsAuthentication.SignOut should clear the authentication cookie. I suggest capturing the HTTP flow and confirming whether the authentication cookie has been deleted. The default name for the authentication cookie is .ASPXAUTH. Alternatively it will be the name specified in your web.config's  section. For example, forms name="mycookie" would rename the cookie to mycookie. You shouldn't have to delete the ASP.NET_SessionId session ID cookie.


Q: How to add fail to ant macrodef I created a macro to search for a file in a number of directories. That part is working.
Now I'm trying to add fail to the macro if no file is found but this gives me an error
macrodef doesn't support the nested "fail" element.
Is there a way to achieve this ?
<macrodef name="searchfile">
    <attribute name="file" />
    <attribute name="path" default="${custom.buildconfig},${wst.basedir}" />
    <attribute name="name" />
    <attribute name="verbose" default="false" />
    <sequential>
        <first id="@{name}">
            <multirootfileset basedirs="@{path}" includes="@{file}" erroronmissingdir="false" />
        </first>
        <property name="@{name}" value="${toString:@{name}}" />
        <echo>property @{name} ${@{name}}</echo>
    </sequential>
    <fail message="${file}was not found in ${custom.buildconfig},${wst.basedir}">
        <condition>
            <equals arg1="${@{name}" arg2=""/>
        </condition>
    </fail>
</macrodef>

A: Credits to martin clayton for his comment, moving fail in the sequential fixes the issue.
   <macrodef name="searchfile">
        <attribute name="file" />
        <attribute name="path" default="${custom.buildconfig},${wst.basedir}" />
        <attribute name="name" />
        <attribute name="verbose" default="false" />
        <sequential>
            <first id="@{name}">
                <multirootfileset basedirs="@{path}" includes="@{file}" erroronmissingdir="false" />
            </first>
            <property name="@{name}" value="${toString:@{name}}" />
            <echo>property @{name}=${toString:@{name}}</echo>
            <fail message="@{file} was not found in ${custom.buildconfig},${wst.basedir}, customdir=${customdir}">
                <condition>
                    <equals arg1="${toString:@{name}}" arg2=""/>
                </condition>
            </fail>
        </sequential>
    </macrodef>


Q: POST to https://www.sandbox.paypal.com/cgi-bin/webscr gives 500 error , Classic asp I am working on classic asp to create donation site and payment gateway is paypal.
I have implemented IPN and paypal is sending notification on that notify_url that i pass with form.
Also payment is also working correctly i.e i can get payment history and IPN history in my sandbox paypal account.
Now the problem is in IPN handler file, when i use sandbox.paypal url to post back to paypal, it give 500 error. Same thing is not true for live paypal url.
Below it the code that will explain better.
Test Form
<form action="zPaypalTest.asp" method="POST">
<input name="mc_gross" type="hidden" value="500.00" />
<input name="custom" type="hidden" value="some custom data" />
<input name="address_status" type="hidden" value="confirmed" />
<input name="item_number1" type="hidden" value="6" />
<input name="item_number2" type="hidden" value="4" />
<input name="payer_id" type="hidden" value="FW5W7ZUC3T4KL" />
<input name="tax" type="hidden" value="0.00" />
<input name="address_street" type="hidden" value="1234 Rock Road" />
<input name="payment_date" type="hidden" value="14:55 15 Jan 07 2005 PST" />
<input name="payment_status" type="hidden" value="Completed" />
<input name="address_zip" type="hidden" value="12345" />
<input name="mc_shipping" type="hidden" value="0.00" />
<input name="mc_handling" type="hidden" value="0.00" />
<input name="first_name" type="hidden" value="Jason" />
<input name="last_name" type="hidden" value="Anderson" />
<input name="mc_fee" type="hidden" value="0.02" />
<input name="address_name" type="hidden" value="Jason Anderson" />
<input name="notify_version" type="hidden" value="1.6" />
<input name="payer_status" type="hidden" value="verified" />
<input name="business" type="hidden" value="paypal@emailaddress.com" />
<input name="address_country" type="hidden" value="United States" />
<input name="num_cart_items" type="hidden" value="2" />
<input name="mc_handling1" type="hidden" value="0.00" />
<input name="mc_handling2" type="hidden" value="0.00" />
<input name="address_city" type="hidden" value="Los Angeles" />
<input name="verify_sign" type="hidden" value="AlUbUcinRR5pIo2KwP4xjo9OxxHMAi6.s6AES.4Z6C65yv1Ob2eNqrHm" />
<input name="mc_shipping1" type="hidden" value="0.00" />
<input name="mc_shipping2" type="hidden" value="0.00" />
<input name="tax1" type="hidden" value="0.00" />
<input name="tax2" type="hidden" value="0.00" />
<input name="txn_id" type="hidden" value="TESTER" />
<input name="payment_type" type="hidden" value="instant" />
<input name="last_name=Borduin" type="hidden" />
<input name="payer_email" type="hidden" value="test@domain.com" />
<input name="item_name1" type="hidden" value="Rubber+clog" />
<input name="address_state" type="hidden" value="CA" />
<input name="payment_fee" type="hidden" value="0.02" />
<input name="item_name2" type="hidden" value="Roman sandal" />
<input name="invoice" type="hidden" value="123456" />
<input name="quantity" type="hidden" value="1" />
<input name="quantity1" type="hidden" value="1" />
<input name="receiver_id" type="hidden" value="5HRS8SCK9NSJ2" />
<input name="quantity2" type="hidden" value="1" />
<input name="txn_type" type="hidden" value="web_accept" />
<input name="mc_gross_1" type="hidden" value="0.01" />
<input name="mc_currency" type="hidden" value="USD" />
<input name="mc_gross_2" type="hidden" value="0.01" />
<input name="payment_gross" type="hidden" value="0.02" />
<input name="subscr_id" type="hidden" value="PP-1234" />
<input name="test" type="submit" value="test" />
</form>

MY IPN handler File
zPaypalTest.asp
                <%@  language="VBScript" %>
            <%
            Dim Item_name, Item_number, Payment_status, Payment_amount
            Dim Txn_id, Receiver_email, Payer_email
            Dim objHttp, str
            DIM ApplicationRootPath
            ApplicationRootPath = Request.ServerVariables("APPL_PHYSICAL_PATH")

            ' read post from PayPal system and add 'cmd'
            str = Request.Form& "&cmd=_notify-validate"

            ' post back to PayPal system to validate
            set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
            'Set objHttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
            ' set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP.4.0")
            'set objHttp = Server.CreateObject("Microsoft.XMLHTTP")
            'objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr", false
            objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false
            'objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false
            'Send response message back to paypal'

            'objHttp.open "POST", "https://ipnpb.paypal.com/cgi-bin/webscr", false
            'objHttp.open "POST", "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", false

            Response.write "IPN-Sand"
            Response.write "<br/>"

            objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
            objHttp.Send str

            Response.write objHttp.status

            if (objHttp.status <> 200 ) then
            ' HTTP error handling
            elseif (objHttp.responseText = "VERIFIED") then
            Response.write "VERIFIED"
            elseif (objHttp.responseText = "INVALID") then
            Response.write "INVALID"
            else
            Response.write "ERROR"

            end if
            set objHttp = nothing
            %>

Above is the example file.
Here is the code sample that i used. https://github.com/paypal/ipn-code-samples
I test it on localhost IIS and it work fine there too.
So only problem is when i use ,
objHttp.open "POST", "https://www.sandbox.paypal.com/cgi-bin/webscr", false

OR
objHttp.open "POST", "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", false

I get 500 server error and this 500 server is only on my server that runs both in http or https, but in localhost IIS it works.
Also
If i change that url to live url
objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr", false

OR
objHttp.open "POST", "https://ipnpb.paypal.com/cgi-bin/webscr", false

It works.
If i just browse that page in my browser in my server i.e https://myserver.com/zPaypalTest.asp, it gives error when using sandbox url only.
I am not able to think what is the error here. Why it gives 500 error.
I will be very thankful if any one could give me any clue what's wrong.


Q: Unary operators, binary expression tree and shunting yard algorithm I am writing the mathematics expression solver which takes infix expression and solves them, both binary expression tree and shunting-yard are doing good for me (I have even solved the problem of handling unary and ternary operators). Encountered an issue with trigonometric functions. When I write 45sin or (45)sin or (44+1)sin, shunting-yard converts it to valid Reverse Polish Notation(RPN) and evaluation is successful. Though the valid infix expression is sin(44+1) or sin45 + 1. Please suggest to solve this pr1oblem.
Here is the java code from class ExpressionEval which converts infix to RPN.
public String infixToPostFix2(String[] expression)
{
    String val = "";

    if (expression == null || expression.length <= 0)
    return "";

    Stack<String> stack = new Stack<String>();
    ArrayList<String> exp = new ArrayList<String>();

    for (String token : expression)
    {
        if (OperatorList.isOperator(token))
        {
            Operator o1 = OperatorList.getOperator(token);
            Operator o2 = null;
            while (!stack.empty() && OperatorList.isOperator(stack.peek()))
            {
                o2 = OperatorList.getOperator(stack.peek());
                if (    (o1.getAssociativity() == Associativity.LEFT && o1.lessThanEqual(o2))
                    || (o1.getAssociativity() == Associativity.RIGHT && o1.lessThan(o2))
                    )
                {
                    exp.add(stack.pop());
                    continue;
                }
                break;
            }
            stack.push(token);
        }
        else if(OperatorList.isLeftParenthesis(token))
        {
            stack.push(token);
        }
        else if (OperatorList.isRightParentheis(token))
        {
            while(!OperatorList.isLeftParenthesis(stack.peek()))
            {
                if (stack.empty())
                {
                    this.error = Error.MISMATCHED_PARANTHESIS;
                    return ""; //Mismatched paranthesis
                }
                exp.add(stack.pop());
            }

            stack.pop();//Pop off the left paranthesis but not move to output
        }
        else //Operands
        {
            exp.add(token);
        }
        }

        while(!stack.empty())
        {
        String s = stack.pop();
        if (OperatorList.isParanthesis(s))
        {
            this.error = Error.MISMATCHED_PARANTHESIS;
            return "";
        }
        exp.add(s);
    }

    postfixExpression = new String[exp.size()];
    int index = 0;
    for (String elem : exp)
    {
    postfixExpression[index++] = elem;
    }

    CalcDebug.printArray(postfixExpression);

    return val;
}

Once we have post-fix expression the evaluation is done in this function of ExpressionEval class
 public double evaluateExpression(String[] postfixExpression) {

    CalcDebug.Debug("evaluateExpression()");

    double val = 0.0;
    if (postfixExpression == null || postfixExpression.length <= 0)
        return val;

    Stack<String> operationStack = new Stack<String>();

    CalcDebug.printArray(postfixExpression);

    for (String elem : postfixExpression) {

        CalcDebug.Debug("elem = " + elem);

        if (!OperatorList.isOperator(elem)) {
            operationStack.push(elem);
        } else {
            double arg0 = 0.0;
            double arg1 = 0.0;
            double arg2 = 0.0;

            OperatorType t = OperatorList.getOperatorType(elem);
            if (t == OperatorType.BINARY) {
                arg1 = Double.parseDouble(operationStack.pop());
                arg0 = Double.parseDouble(operationStack.pop());
                val = CalculatorBrain.performCalculation(elem, arg0, arg1);
            } else if (t == OperatorType.UNARY) {
                arg0 = Double.parseDouble(operationStack.pop());
                val = CalculatorBrain.performCalculation(elem, arg0);
            } else if (t == OperatorType.TERNARY) {
                arg2 = Double.parseDouble(operationStack.pop());
                arg1 = Double.parseDouble(operationStack.pop());
                arg0 = Double.parseDouble(operationStack.pop());
                val = CalculatorBrain.performCalculation(elem, arg0, arg1,
                        arg2);
            }
            operationStack.push(Double.toString(val));
        }

        CalcDebug.printStack(operationStack);
    }

    val = Double.parseDouble(operationStack.pop());

    CalcDebug.Debug("val = " + val);

    return val;
}

Operator class is somewhat similar to this.
package com.studentscalculator;

import com.studentscalculator.OperatorComparator.OPERATOR_PRIORITY;

public class Operator
{

    public enum OperatorType
    {
        UNARY, BINARY, TERNARY
    }

    public enum Associativity
    {
        LEFT, RIGHT
    }

    private String operator;
    public String getOperator(){return operator;}
    public void setOperator(String operator){this.operator = operator;}

    private int order;
    public int getOrder(){return order;}
    public void setOrder(int order){this.order = order;}

    private OperatorType type;
    public OperatorType getType(){ return type; }
    public void setType(OperatorType type){ this.type = type; }

    private Associativity associativity;
    public Associativity getAssociativity(){ return associativity;}
    public void setAssociativity(Associativity associativity){ this.associativity = associativity; }

    //Constructors
    public Operator(String operator)
    {
        this.setOperator(operator);
        this.setOrder(OperatorList.getOperatorOrder(operator));
        this.setType(OperatorList.getOperatorType(operator));
        this.setAssociativity(OperatorList.getOperatorAssociativity(operator));
    }

    public Operator(String operator, int order)
    {
        this.setOperator(operator);
        this.setOrder(order);
        this.setType(OperatorList.getOperatorType(operator));
    }

    public Operator(String operator, int order, OperatorType t)
    {
       init(operator, order, t, Associativity.LEFT);
    }

    public Operator(String operator, int order, OperatorType t, Associativity a)
    {
       init(operator, order, t, a);
    }

    void init(String operator, int order, OperatorType t, Associativity a)
    {
        this.setOperator(operator);
        this.setOrder(order);
        this.setType(t);
        this.setAssociativity(a);
    }

    public boolean lessThanEqual(Operator arg0)
    {
        int val = -(this.order - arg0.order);
        if (val <= 0)
            return true;
        else
            return false;
    }

    public boolean lessThan(Operator arg0)
    {
        int val = -(this.order - arg0.order);
        if (val < 0)
            return true;
        else
            return false;
    }

    @Override
    public String toString()
    {
        String val = String.format("Operator = %s : Order %s", getOperator(), getOrder());
        return val;
    }

}


Q: AnimationDrawable Thread skipping frames I am in an Activity which must play an AnimationDrawable (a 'loading' animation) while the rest of the content loads.
I started the animation in another thread since animations tend to give a lot of work to the main thread, however the animation can't be displayed correctly, and the Logcat shows several times to have skipped 40 frames or so.
I'll post the code tomorrow, sorry for the delay.
Meanwhile what can be causing this? all the thread has inside is the start method for the animation drawable.

A: You should not run animation off of the UI thread ("main" thread) - you should load your content in another thread by using a Loader (or something similar) and play the animation on the UI thread. That's what it's for.
Here are official thread guidelines:

Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread

More here


Q: Has the generic version of HttpResponseMessage been removed from the ASP.NET WebApi? I just finished installing VS 2012 RC and have started working with the ASP.NET Web API. I am basing my work on some tutorials from PluralSight which I've been using as reference.
In every tutorial and article which I've used, I notice that they are using a generic version of HttpResponseMessage in the return type of Action, but to my surprise this object was not available to me while coding. I thought perhaps the issue was just an incorrect namespace reference, but that does not seem to be the case.
Can anyone point me toward some source code or reference material on how to utilize the generic HttpResponseMessage object that PluralSight uses in their videos?

A: yes i was also looking through the same thing.. the generic version of the HttpResponseMessage was remove recently.. because it was not type safe

A: Searching for the answer i found this article
and it states that the generic version has been removed
so now just mention the return type to be of type HttpresponseMessage and when actually returning the response use Request.CreateResponse<T>(params);


Q: Inconsistent ParseExeption with Data Format in Java I wrote a simple Util method to convert a String in Java to util.Date. What I am not able to figure out is why the method works for the first input, and fails for the second one, given that the inputs are identical:
Code:
package util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate {

    public Date getDateFromString(String strDate, String dateFormat) {

        DateFormat df = new SimpleDateFormat(dateFormat);
        Date date = null;

        try {

            date = df.parse(strDate);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println(date);

        return date;
    }

    public static void main(String[] args)  {

        StringToDate s2d = new StringToDate();

        s2d.getDateFromString("12-18-11, 10:36 AM","MM-dd-yy, hh:mm a");
        s2d.getDateFromString("02-04-12, 01:17 PM","MM-dd-yy, hh:mm a");
    }
}

Output:
Sun Dec 18 10:36:00 CET 2011
null
java.text.ParseException: Unparseable date: "02-04-12, 01:17 PM"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at util.StringToDate.getDateFromString(StringToDate.java:17)
    at util.StringToDate.main(StringToDate.java:33)

Logically, the output should've been Sat Feb 04 13:17:00 CET 2012 going by the first output. Why is the ParseException being thrown?
EDIT: The following two lines work correctly:
s2d.getDateFromString("02-04-12", "MM-dd-yy");
s2d.getDateFromString("01:17 PM", "hh:mm a");

Output:
Sat Feb 04 00:00:00 CET 2012
Thu Jan 01 13:17:00 CET 1970

But the exception happens when I try to parse both date and time together.

A: Do you have a non-breaking space, or some other Unicode space character, somewhere in either your date string or format mask?
I was able to reproduce your error if I replaced one of the spaces in the second of your date strings with a non-breaking space, such as Unicode character 160.


Q: How to import moment.js angular2 I'm trying to import moment.js into my angular2 application.
First of all I have followed this guide, and I've found this answer but even if I've tried to follow the proposed solutions I'm still unable to import moment.js.
The package is present, and in fact my IDE (visual studio) is able to find the moment.d.ts file without any problem, but when I run my application with npm start, I get this two errors in the console:

"NetworkError: 404 Not Found - http://localhost:3000/node_modules/moment/"
  /node_m...moment/
  Error: patchProperty/desc.set/wrapFn@http://localhost:3000/node_modules/zone.js/dist/zone.js:769:27
      Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:356:24
      Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:256:29
      ZoneTask/this.invoke@http://localhost:3000/node_modules/zone.js/dist/zone.js:423:29
Error loading http://localhost:3000/node_modules/moment as "moment" from 'my file'

I've tried to import moment in this way
import * as moment from 'moment'

and in this way to
import * as moment from 'moment/moment.d'

but nothing, I'm still get the error. My SystemJs'map property is this one
 var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'services':                   'app/service',
    'moment':                     'node_modules/moment',//moment.js
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
 };

If I try to install with typings i get this error:

Typings for "moment" already exist in "node_modules/moment/moment.d.ts". You should let TypeScript resolve the packaged typings and uninstall the copy installed by Typings

so I had uninstalled it, and retype the commands, well I get this error

typings ERR! message Unable to find "moment" ("npm") in the registry.

so is ther a way to get out from this dilemma?

A: Firstly, install the moment package via npm:
npm install moment --save

Secondly change your systemjs config (2 lines):
(function (global) {
  // map tells the System loader where to look for things
  var map = {
    'app': 'app', // 'dist',
    '@angular': 'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs': 'node_modules/rxjs',
    'moment': 'node_modules/moment', <== add this line
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app': { main: 'main.js', defaultExtension: 'js' },
    'rxjs': { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    'moment': { main: 'moment.js', defaultExtension: 'js' } <== add this line
  };

Then you can use it:
import * as moment from 'moment';

Typings will be available from node_modules/moment/moment.d.ts


Q: Get dictionary values as List I know this is asked earlier, but I tried but could not help.
I have below dictionary, want to convert to List, What is the best way to convert to List
dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}

dList = list(dct.values())

Result:
[['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']]

I need splitted List:
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']

Later, I want to compare list of items in "dList" with another List.

A: If you know that the list is the value associated to the 'result' key, simply call dct['result'].
>>> dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct
{'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct['result']
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']

Converting the values to a list is unneeded, inefficient and might return the wrong value if your dict has more than 1 (key, value) pair.

A: Your dictionary have only one value and that itself is a list of elements. So just call the result key and you will get the list value.
If you want the list from your code add the index [0] like,
dList = list(dct.values())[0]
Hope this helps! Cheers!


Q: How to loop between two dates I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and ending with the selected end date, obviously including all of the dates inbetween, regardless of how many days are inbetween the selected start and end dates.
Below I have the beginning of the method which takes the date strings and converts them into DateTime variables so that I can make use of the DateTime calculation functions. However, I cannot seem to work out how to calculate all of the dates inbetween the start and end date?
Obviously the first stage is to subtract the start date from the end date, but I cannot calculate the rest of the steps.
Help appreciated greatly,
kind regards.
public void DTCalculations()
{
List<string> calculatedDates = new List<string>();
string startDate = "2009-07-27";
string endDate = "2009-07-29";

//Convert to DateTime variables
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);

//Calculate difference between start and end date.
TimeSpan difference =  end.Subtract(start);

//Generate list of dates beginning at start date and ending at end date.
//ToDo:
}

A: static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end)
{
    for(var day = start.Date; day <= end; day = day.AddDays(1))
        yield return day;
}

Edit: Added code to solve your particular example and to demonstrate usage:
var calculatedDates =
    new List<string>
    (
        AllDatesBetween
        (
            DateTime.Parse("2009-07-27"),
            DateTime.Parse("2009-07-29")
        ).Select(d => d.ToString("yyyy-MM-dd"))
    );

A: The easiest thing to do would be take the start date, and add 1 day to it (using AddDays) until you reach the end date. Something like this:
DateTime calcDate = start.Date;
while (calcDate <= end)
{
    calcDate = calcDate.AddDays(1);
    calculatedDates.Add(calcDate.ToString());
}

Obviously, you would adjust the while conditional and the position of the AddDays call depending on if you wanted to include the start and end dates in the collection or not.
[Edit: By the way, you should consider using TryParse() instead of Parse() in case the passed in strings don't convert to dates nicely]

A: for( DateTime i = start; i <= end; i = i.AddDays( 1 ) )
{
    Console.WriteLine(i.ToShortDateString());
}

A: You just need to iterate from start to end, you can do this in a for loop
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);

for(DateTime counter = start; counter <= end; counter = counter.AddDays(1))
{
    calculatedDates.Add(counter);
}

A: An alternative method
public static class MyExtensions
{
    public static IEnumerable EachDay(this DateTime start, DateTime end)
    {
        // Remove time info from start date (we only care about day).
        DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
        while (currentDay <= end)
        {
            yield return currentDay;
            currentDay = currentDay.AddDays(1);
        }
    }
}

Now in the calling code you can do the following:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
    ...
}

Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.


Q: Jest encountered an unexpected token when working with React TypeScript I am building a reusable react component without using react-app and I am very new to Jest. I keep on getting this message. I have tried several post solutions on Stackoverflow but I am stuck at the moment:
● Test suite failed to run
Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

C:\Users\User\Documents\accessible-date-picker\src\__tests__\DatePicker.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { DatePicker } from '../containers/DatePicker';
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)

I have the following configuration but I cannot figure out why I cannot resolve the problem:
//jest.config.js
module.exports = {
  roots: ["<rootDir>/src"],
  testMatch: [
    "**/__tests__/**/*.+(ts|tsx|js)",
    "**/?(*.)+(spec|test).+(ts|tsx|js)",
  ],
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  coveragePathIgnorePatterns: [
    "/node_modules/"
  ],
  moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy",
  }
};

Here is my tsconfigurations:
{
    "compilerOptions": {
        "lib": [
            "dom",
            "dom.iterable",
            "esnext"
        ],
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react"
    },
    "include": [
        "src"
    ]
}

Here are my dev dependencies:
 "devDependencies": {
    "@babel/core": "^7.12.7",
    "@babel/plugin-transform-runtime": "^7.12.1",
    "@babel/preset-env": "^7.12.7",
    "@babel/preset-react": "^7.12.7",
    "@babel/preset-typescript": "^7.12.7",
    "@babel/runtime": "^7.12.5",
    "@teamsupercell/typings-for-css-modules-loader": "^2.4.0",
    "@types/fork-ts-checker-webpack-plugin": "^0.4.5",
    "@types/jest": "^26.0.15",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/webpack": "^4.41.25",
    "@types/webpack-dev-server": "^3.11.1",
    "@typescript-eslint/eslint-plugin": "^4.8.1",
    "@typescript-eslint/parser": "^4.8.1",
    "babel-loader": "^8.2.1",
    "css-loader": "^5.0.1",
    "eslint": "^7.14.0",
    "eslint-plugin-react": "^7.21.5",
    "eslint-plugin-react-hooks": "^4.2.0",
    "fork-ts-checker-webpack-plugin": "^6.0.3",
    "jest": "^26.6.3",
    "style-loader": "^2.0.0",
    "ts-jest": "^26.4.4",
    "ts-node": "^9.0.0",
    "typescript": "^4.1.2",
    "webpack": "^5.6.0",
    "webpack-cli": "^4.2.0",
    "webpack-dev-server": "^3.11.0"
  }
}

Any help will be much appreaciated!

A: Looks like your test file is a js file (src\__tests__\DatePicker.spec.js) instead of ts?x file which means this pattern will never meet "^.+\\.(ts|tsx)$": "ts-jest".
However, you might know tsc can also have capability to transpile your js code as well as long as you set allowJs: true as you already did. So I think your problem would be fixed as you refine your pattern to to transform above including jsx file:
{
  transform: {
    "^.+\\.(t|j)sx?$": "ts-jest",
  }
}


Q: How to reload a entire component with angular when route changes? I want to reload or rerender a sidebar component when route change i have the following code:
  constructor(
    private auth: AuthService,
    private router: Router,
    private changeDetector: ChangeDetectorRef
  ) {
    this.auth.currentUser.subscribe(x => this.userData = x);
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
        this.changeDetector.detectChanges();
        console.log('enter');
      }
    });
  }

This enter to show the log 'enter' but not reload the component. Anybody can help with an example?

A: Usually component routing doesn't reload because angular works as SPA(single page application) - but you can make your components to load in order to reduce the browser size if that is the only case
Use href and your path name insted of routerLink on your sidebar anchor link - this will make your component to reload everytime when you click - everytime it will load all your js from server - if you are using lazy load this process is not the right way - this will only helps you to reduce the browser RAM usage on every click and doesn't maintain any previous data but routing will work as the same
So href will be the word for your question - but make sure that you really want to load your components
Hope it helps - Happy Coding:)

A: If you want to reload the entire page, just use
window.location.reload();


Q: adding items to deep List of KeyValuePairs I wrote a deep list:
public static List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>> ListBoxes = new List<KeyValuePair<string,List<KeyValuePair<string,List<KeyValuePair<string,bool>>>>>>();

Anybody has an idea how to add to this list any items?
For example:
("A",LIST("B",LIST("C",true)))

A: Easy:
ListBoxes.Add(
    new KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>("A",
        new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>
        {
            new KeyValuePair<string,List<KeyValuePair<string,bool>>>("B",
                new List<KeyValuePair<string,bool>>() {
                    new KeyValuePair<string,bool>("C", true)
                }
            )
        }
    )
);

It looks like you could use some helper methods or something.
Edit
If you create a simple extension method, then the task becomes maybe a bit more readable.
public static List<KeyValuePair<TKey, TValue>> AddKVP<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> self, TKey key, TValue value)
{
    self.Add(
        new KeyValuePair<TKey, TValue>(key, value)
    );

    // return self for "fluent" like syntax
    return self;
}

var c = new List<KeyValuePair<string, bool>>().AddKVP("c", true);
var b = new List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>().AddKVP("b", c);
var a = new List<KeyValuePair<string, List<KeyValuePair<string, List<KeyValuePair<string, bool>>>>>>().AddKVP("a", b);

Edit #2
If you define a simple type, then it helps a bit more:
public class KVPList<T> : List<KeyValuePair<string, T>> { }

public static KVPList<TValue> AddKVP<TValue>(this KVPList<TValue> self, string key, TValue value)
{
    self.Add(new KeyValuePair<string, TValue>(key, value));
    return self;
}

var ListBoxes = new KVPList<KVPList<KVPList<bool>>>()
   .AddKVP("A", new KVPList<KVPList<bool>>()
       .AddKVP("B", new KVPList<bool>()
           .AddKVP("C", true)));

Edit #3
One more and I promise I'll stop.  If you define "Add" on the type, then you can use implicit initialization:
public class KVPList<T> : List<KeyValuePair<string, T>>
{
    public void Add(string key, T value)
    {
        base.Add(new KeyValuePair<string,T>(key, value));
    }
}

var abc = new KVPList<KVPList<KVPList<bool>>> {
    { "A", new KVPList<KVPList<bool>> {
        { "B", new KVPList<bool> {
            { "C", true }}
        }}
    }};


Q: Python - How to get all possible combinations from nested list I have a nested list like this :
values = [['DNO', 0.2], ['Equinor', 0.4], ['Petoro', 0.2], ['Total', 0.2]]

How to get all possible combinations of elements that will have a sum(2nd element of each sub list) greater than 0.5?
This is what I am using :
def getCombinations(values, min_len):
    combo = "\n"
    numbers = []
    doc = {}
    for val in values:
        doc[val[0]] = val[1]
        numbers.append(val[1])

    result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) >= 0.5]
    temp = doc.copy()

    for r in result:
        doc = temp.copy()
        if len(r) >= min_len:
            for rr in r:
                combo = combo + get_key(doc, rr) + " "

                doc.pop(get_key(doc, rr))
            combo = combo + "\n"
    return combo

My algorithm have some problem when there are multiple values like 0.2 in above list.
Currently it is returning this with min_length=3:
Total Equinor Petoro DNO
Total Equinor Petoro
Total Equinor Petoro
Total Petoro DNO
Equinor Total Petoro

A: The following should work:
import itertools
result=[]
for k in range(2,len(values)+1):
    temp=[tuple(x[0] for x in i) for i in list(itertools.combinations(values,k))if sum([p[1] for p in i]) >0.5]
    result.append(temp)
result=sum(result, [])
print(result)

Output:
[('DNO', 'Equinor'), ('Equinor', 'Petoro'), ('Equinor', 'Total'), ('DNO', 'Equinor', 'Petoro'), ('DNO', 'Equinor', 'Total'), ('DNO', 'Petoro', 'Total'), ('Equinor', 'Petoro', 'Total'), ('DNO', 'Equinor', 'Petoro', 'Total')]

A: You can use a list comprehension like this:
Explanation:

*

*The first for defines the length of the combinations. Every length from 2 to the length of values is used.

*The second for creates the actual combinations

*The if uses a generator method to sum the numbers of the items

from itertools import combinations

combis = [
    item
    for length in range(2, len(values)+1)
    for item in combinations(values, length)
    if sum(i[1] for i in item) >= 0.5
]


Q: Does extraction workers in google bigquery save the data into Columnar Storage follows a FIFO pattern? As I understand from bigquery streaming insert lifecycle  also shown in the image below. The data goes through streaming buffer before it is available in the Columnar Storage. The work of processing the data is done by the Extraction Workers.
However, in the documentation, it is not mentioned how the extraction workers process the data. Do they follow a random order for processing or it is FIFO processing?

A: The streaming buffer is a queue, and the extraction worker processes rows in order. The extraction workers take from the queue either when it reaches a certain volume of data or when a certain amount of time has elapsed in order to write sufficiently large chunks of data to managed storage. The underlying storage format in BigQuery is Capacitor, which reorders rows as it is persisting them to disk and performs a variety of other optimizations as well.


Q: Use case for Lock.tryLock() At API docs of Lockinterface for method tryLock(), this code sample is pasted,

A typical usage idiom for this method would be:
  Lock lock = ...;
  if (lock.tryLock()) {
      try {
          // manipulate protected state
      } finally {
          lock.unlock();
      }
  } else {
      // perform alternative actions
  }

My question is , does this use case not existed before Java 5 or folks used to implement it via some other techniques?
I am not able to comprehend the need to execute perform alternative actions based on lock availability.
Can somebody please explain real use cases for this?
I am sure this technique is not a straight forward replacement of synchronizedto write deadlock free code.

A: One straight-forward use case is a thread processing a batch of elements, occasionally trying to commit the elements that have been processed. If acquiring the lock fails, the elements will be committed in the next successful attempt or at the final, mandatory commit.
Another example can be found within the JRE itself, ForkJoinTask.helpExpungeStaleExceptions() is a method for performing a task that can be done by an arbitrary thread, but only one at a time, so only the one thread successfully acquiring the lock will perform it, all others will return, as the unavailability of the lock implies that there is already a thread performing the task.

It is possible to implement a similar feature before Java 5, if you separate the intrinsic locking feature, which doesn’t support being optional, from the locking logic, that can be represented as an ordinary object state. This answer provides an example.

A:
My question is, does this use case not existed before Java 5 or folks used to implement it via some other techniques?

The Lock interface was added in Java 5, is that what you mean?  Not sure what was there before.

I am not able to comprehend the need to execute perform alternative actions based on lock availability.  Can somebody please explain real use cases for this?

Sure.  Just wrote one of these today actually.  My specific Lock implementation is a distributed lock that is shared among a cluster of servers using the Jgroups protocol stack.  The lock.tryLock(...) method makes RPC calls to the cluster and waits for responses.  It is very possible that multiple nodes maybe trying to lock and their actions might clash causing delays and certainly one lock to fail.  This either could return false or timeout in which case my code just waits and tries again.  My code is literally:
if (!clusterLock.tryLock(TRY_LOCK_TIME_MILLIS, TimeUnit.MILLISECONDS)) {
    logger.warn("Could not lock cluster lock {}", beanName);
    return;
}

Another use case might be a situation where one part of the code holds a lock for a large amount of time and other parts of the code might not want to wait that long and instead want to get other work done.
Here's another place in my code where I'm using tryLock(...)
// need to wait for the lock but log
boolean locked = false;
for (int i = 0; i < TRY_LOCK_MAX_TIMES; i++) {
    if (lock2.tryLock(100, TimeUnit.MILLISECONDS)) {
        logger.debug("Lock worked");
        locked = true;
        break;
    } else {
        logger.debug("Lock didn't work");
    }
}

A: The reason for writing code like that example is if you have a thread that is doing more than one job.
Imagine you put it in a loop:
while (true) {
    if (taskA_needsAttention() && taskA_lock.tryLock()) {
        try {
            ...do some work on task A...
        } finally {
            taskA_lock.unlock();
        }
    } else if (taskB_needsAttention() && taskB_lock.tryLock()) {
        try {
            ...do some work on task B...
        } finally {
            taskB_lock.unlock();
        }
    } else ...
}

Personally, I would prefer not to write code like that.  I would prefer to have different threads responsible for task A and task B or better still, to use objects submitted to a thread pool.

A: Use case 1
One use case would be to completely avoid running the thread. Like in the example below, for example a very strict internet hotspot where you can only access one webpage at once, and other requests are cancelled.
With synchronized you cannot cancel it, since it waits until it can obtain the lock. So tryLock just gives you flexibility to cancel something or to run other behavior instead.
package Concurrency;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LimitedHotspotDemo
{
    private static Lock webAccessLock = new ReentrantLock();

    private static class AccessUrl implements Runnable
    {
        private String url;

        public AccessUrl(String url)
        {
            this.url = url;
        }

        @Override
        public void run()
        {
            if(webAccessLock.tryLock()) {
                System.out.println("Begin request for url " + url);
                try {
                    Thread.sleep(1500);
                    System.out.println("Request completed for " + url);
                } catch (InterruptedException e) {
                    webAccessLock.unlock();
                    return;
                } finally {
                    webAccessLock.unlock();
                }
            } else {
                System.out.println("Cancelled request " + url + "; already one request running");
            }
        }
    }

    public static void main(String[] args)
    {
        for(String url : Arrays.asList(
            "https://www.google.com/",
            "https://www.microsoft.com/",
            "https://www.apple.com/"
        )) {
            new Thread(new AccessUrl(url)).start();
        }
    }
}

Output:
Begin request for url https://www.microsoft.com/
Cancelled request https://www.google.com/; already one request running
Cancelled request https://www.apple.com/; already one request running
Request completed for https://www.microsoft.com/

Use case 2
Another use case would be a light sensor which keeps the light on when there is movement in the room (with Sensor thread). There is another thread (TurnOffLights) running to switch the light off when there is no more movement in the room for a few seconds.
The TurnOffLights thread uses tryLock to obtain a lock. If no lock can be obtained, the process is delayed for 500ms. The last Sensor thread is blocking the lock for 5 seconds, after which the TurnOffLights thread can obtain the lock and turn off the lights.
So in this case the TurnOffLights thread is only allowed to turn off the lights when there are no more signals to the Sensor for 5 seconds. The TurnOffLights thread is using tryLock to obtain the lock.
package Concurrency;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LightSensorDemo
{
    private static volatile Lock lock = new ReentrantLock();
    private static volatile Thread lastSignal = null;
    private static Sensor sensor = new Sensor();

    private static class Sensor implements Runnable
    {
        private static Boolean preparing = false;
        public static Boolean isPreparing()
        {
            return preparing;
        }

        @Override
        public void run()
        {
            System.out.println("Signal send " + Thread.currentThread().getName());
            try {
                invalidatePreviousSignalsAndSetUpCurrent();
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                //System.out.println("Signal interrupted " + Thread.currentThread().getName());
                return;
            } finally {
                lock.unlock();
            }
        }

        private static synchronized void invalidatePreviousSignalsAndSetUpCurrent() throws InterruptedException
        {
            preparing = true;
            if(lastSignal != null) {
                lastSignal.interrupt();
            }
            lastSignal = Thread.currentThread();
            lock.lockInterruptibly();
            preparing = false;
        }
    }

    private static class TurnOffLights implements Runnable
    {
        @Override
        public void run()
        {
            while(true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    System.out.println("Interrupted" + this.getClass().getName());
                    return;
                }
                if (!Sensor.isPreparing()) {
                    if(lock.tryLock()) {
                        try {
                            System.out.println("Turn off lights");
                            break;
                        } finally {
                            lock.unlock();
                        }
                    }  else {
                        System.out.println("Cannot turn off lights yet");
                    }
                } else {
                    System.out.println("Cannot turn off lights yet");
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Thread turnOffLights = new Thread(new TurnOffLights());
        turnOffLights.start();

        //Send 40 signals to the light sensor to keep the light on
        for(int x = 0; x < 10; x++) {
            new Thread(sensor).start(); //some active movements
            new Thread(sensor).start(); //some active movements
            new Thread(sensor).start(); //some active movements
            new Thread(sensor).start(); //some active movements
            Thread.sleep(250);
        }

        turnOffLights.join();
    }
}

Notice also that I use lock.lockInterruptibly(); to interrupt previous signals. So the 5 second countdown always starts from the last signal.
Output is something like:
...
Cannot turn off lights yet
Cannot turn off lights yet
Signal send Thread-19
Signal send Thread-20
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Cannot turn off lights yet
Turn off lights

Process finished with exit code 0


Q: Javascript giving me Uncaught ReferenceError: require is not defined error I have a file structure that looks like this:

My index.js has this code
const THREE = require("three")

var scene = new THREE.scene();
console.log(scene)

My index.html
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

What the hell

I did not use the tag { type : "modules } in my package.json. However, I am still getting the Uncaught ReferenceError: require is not defined error. May I know what is the reason? Thanks!
Error in my live server looks like this

This is my package.json if you are interested
{
  "name": "threejs-playground",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "three": "^0.133.1"
  }
}


Q: problem in making records of a file by perl I'm trying putting a file into records with number starting from record 0 to n and saving it into an output file. my file is starting from AA to // and there are several AA's and //  so I'm putting record number for each AA to // as there are 2000 to 3000 AA's so I want to put them in records with number. Could someone please help me.
//
AA  r00001
FA  tea
OS  fskjkterjykjlt
//
AA  T00002
FA  ACE2
OS  coffee
SQ  MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY
//
AA  T00003
FA  Diet coke
OS  ewtji34ut893u569
SQ  MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV
//
AA  T00004
FA  coke
OS  jgerjgkhjetkh
SQ  MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ
SQ  RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA
//
#!/usr/bin/env perl
use strict;
use warnings;

my $ifh;

my $ofh;

my $line;
my $recnum = 0;
my $ifn  = "factor data 1.txt";
my $ofn  = "try.txt";
open ($ifh, "<$ifn") || die "can't open $ifn";
open ($ofh, ">$ofn") or die "can't open $ofn";
my $a = "\/\/ ";

while ($line = <$ifh>)
{
chomp $line ;

    if ($line =~ m/$a\$/)
        {

         print "$ofh $line\n";

         $recnum++;
  }
         else
 {
        print "$ofh $recnum $line\n";
  }
 }
       close ($ifh);
       close ($ofh);

A: These types of record I/O problems are simplified if you use the Perl idiom of changing the record separator.  Now each record becomes a line and lines are easy to count.
NOTE: I also removed the last // so we don't count the empty record.
Ok... I'm guessing that you may want something like this
#! /usr/bin/env perl

 use strict;
 use warnings;

 my $cntr = 0;

 print "Starting\n";

 # change record seperator
 $/ = '//';

 while ((<DATA>))
 {
   print"============== Record number $cntr ======================\n";
   print "$_\n";
   print "========================================================\n";

   $cntr++;
 }

 exit 0;

 __DATA__

 /

 AA r00001

 FA tea

 OS fskjkterjykjlt

 //

 AA T00002

 FA ACE2

 OS coffee

 SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY

 //

 AA T00003

 FA Diet coke

 OS ewtji34ut893u569

 SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV

 //

 AA T00004

 FA coke

 OS jgerjgkhjetkh

 SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ

 SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA

 //

With output like this
 Starting
 ============== Record number 0 ======================

 /

 AA r00001

 FA tea

 OS fskjkterjykjlt

 //
 ========================================================
 ============== Record number 1 ======================

 AA T00002

 FA ACE2

 OS coffee

 SQ MDNVVDPWYINPSGFAKDTQDEEYVQHHDNVNPTIPPPDNYILNNENDDGLDNLLGMDYY

 //
 ========================================================
 ============== Record number 2 ======================

 AA T00003

 FA Diet coke

 OS ewtji34ut893u569

 SQ MTSICSSKFQQQHYQLTNSNIFLLQHQHHHQTQQHQLIAPKIPLGTSQLQNMQQSQQSNV

 //
 ========================================================
 ============== Record number 3 ======================

 AA T00004

 FA coke

 OS jgerjgkhjetkh

 SQ MKNNNNTTKSTTMSSSVLSTNETFPTTINSATKIFRYQHIMPAPSPLIPGGNQNQ

 SQ RLRQHIPQSIITDLTKGGGRGPHKKISKVDTLRIAVEYIRSLQDLVDDLNGGSNIGANNA


Q: CLLocationManager does not work for non-wireless connection? I have a Mac app and would like to use core location, however, when I am not on wifi but connected using an ethernet cable, core location (CLLocationManager) reports that the operation could not be completed.
The exact error message is
The operation couldn't be completed. (kCLErrorDomain error 0.)

If I am always connected to the same router (ie. either wifi or ethernet cable) why does CLLocationManager only work for wifi and not for the ethernet connection?
Any suggestions would greatly be appreciated.
Thanks.
Edit:
Here is some code.
I define my location manager as an instance variable like so
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDistanceFilter:ICMinimumUpdateDistance];

I then monitor the location manager's delegate method like so,
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

// Filter out points before the last update
NSTimeInterval timeSinceLastUpdate = [newLocation.timestamp timeIntervalSinceDate:dateOfLastUpdate];

if (timeSinceLastUpdate > 0)
{
    //Do stuff
}

}

I also check for errors using the delegate method
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Location Error:%@", [error localizedDescription]);
}

In the code above, the location manager updates with an invalid newLocation (bad time stamp) and then the location manager calls the delegate error method.

A: For lack of a GPS in your laptop, core-location on OSX uses the (skyhook) service, or something similar.
The service maintains a database of WIFI access-points and  their positions (possibly updated by iPhones that do have GPS and wifi enabled) which is queried.
So by feeding a list of access points you can see, and their relative signal strengths the system is able to triangulate roughly where you are.
So you need both wifi enabled, and a working internet link (but internet shouldn't need to be over wifi, you can leave the airport un-associated)

A: I've noticed this too. If you open the Time Zone tab of the Date & Time pane in System Preferences while connected to the internet via ethernet, it says to connect to a wireless network to determine your current location. This leads me to believe that CoreLocation does, in fact, require a wireless connection.


Q: MetaMask RPC error? 'MetaMask - RPC Error: Internal JSON-RPC error.' I'm developing the front-end to an application that I'm trying to test. However, MetaMask keeps giving me this error? I tried changing the gas limit like previously suggested and nothing. Any ideas?
Error:
MetaMask - RPC Error: Internal JSON-RPC error.
code: -32603
data: {code: -32000, message: "gas required exceeds allowance (30000000) or always failing transaction"}
message: "Internal JSON-RPC error."

A: Without seeing the code, it's hard to say for sure but you could try:

*

*Check any code you changed in the front end, specifically in your code you may have something like this:

const contractInstance = new state.web3.eth.Contract(
    MyContract.abi,
    "0x.....",            // contract address
    {
        from: state.accounts[0],
        gasPrice: 1000,
        gas: 100000
    }
);

Make sure the gas prices are similar to those, you may have to adjust for your case.

*Re-compile and redeploy --> for truffle, run truffle develop first, then compile then migrate --reset for local deployment.

*In Metamask, reset your test account. Metamask > Select Account > Settings > Advanced > Reset account. Only do this for testing accounts

A: Previously it used to happen in older versions due to a gas specification issue which was fixed. rpcErrors.internal` expects a string as the first argument, with arbitrary data being the optional second argument. Passing in a non-
string first argument results in the error being shadowed by an error
from eth-json-rpc-errors.
Please check what you are passing to Metamask.

A: In my case, after trying so many options I have restarted Ganache and re-imported new account from Ganache to Metamask.
I connected this new account with localhost application.
This resoles my issue.

A: Before performing any transaction the sending ETH address must be connected to your own site or UI. So it can get the address of sending account and goes towards the further transaction in the metamask.
Make sure Your sending account address must be connected to your UI.


Q: Is it possible for a translucent  to have to affect on the items below it? I have kind of a weird situation, while trying to make a simple chrome plugin. The idea of the plugin is that it constantly overlays a half-transparent image on top of the page you are viewing. To accomplish this, I have the plugin inject JavaScript, which appends an  tag with the following CSS rules:
img.class#id {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%
  width: 100%;
  opacity: 0.5;
  z-index: 9999999;
}

This already works, but it introduces a new problem. Since the z-index of the image is intentionally large, it overrides the left and right click actions of the user, on the elements with a lower z-index. I can't change the z-index to be smaller, since that would defeat the purpose of the plugin, and I can't change the transparency of the other things on the page, since there's too much variability. Is there a way to ensure that the page is still usable, even with the image overlayed on it?

A: set pointer-events: none in css
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

The pointer-events CSS property specifies under what circumstances (if
  any) a particular graphic element can become the target of mouse
  events.

*

*Note that while only mouse events are stated, it is in fact valid for all kinds of pointer events - mouse, touch.

From the possible values:

none The element is never the target of mouse events; however, mouse
  events may target its descendant elements if those descendants have
  pointer-events set to some other value. In these circumstances, mouse
  events will trigger event listeners on this parent element as
  appropriate on their way to/from the descendant during the event
  capture/bubble phases.