text:
Q: NodeJS XMLHttpRequest response I'm making and app and I need do get the number of verses of a chapter of the bible.
I'm getting the info from http://www.kingjamesbibleonline.org/
In order to do that I am making an XMLHttpRequest to send to the server from the function getVerses() from the site.
The problem that I am facing is that I'm not getting a .responseText from the XMLHttpRequest. When I use firebug and call that function, in the Network tab > Response tab I get nothing but on Network tab > Preview I get the answer.
Where is this answer coming from and what is the variable that has this value?
My node code is as follows:
let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;

function getVerses() {
    let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == xmlhttp.DONE ) {
            if(xmlhttp.status == 200){
                console.log(xmlhttp.responseText);
            }
            else if(xmlhttp.status == 400) { }
            else { }
            }
    }
    xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send('callFunc=getMaxVerseForChapter&book='+'"Genesis"'+'&chapter='+'"2"');
}

getVerses();

A: Apparently the server is very strict and it expects the header to be called Content-Type and not Content-type. Some kind of poorly written stuff obviously (in PHP). Also get rid of the double quotes around the values you are sending.
Here you go:
let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;

function getVerses() {
    let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == xmlhttp.DONE ) {
            if(xmlhttp.status == 200){
                console.log(xmlhttp.responseText);
            }
            else if(xmlhttp.status == 400) { }
            else { }
        }
    }
    xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xmlhttp.send('callFunc=getMaxVerseForChapter&book=' + 'Genesis' + '&chapter=' + '2');
}

getVerses();

and since you are hardcoding the values, you don't really need string concatenation:
xmlhttp.send('callFunc=getMaxVerseForChapter&book=Genesis&chapter=2);


text:
Q: Hiding scroll bar causes the body to scroll up I've noticed that if trying to hide the scroll bar using overflow:hidden scrolls the site to the top if this CSS style is used for html and body elements:
html,body {
    height: 100%;
}

This is the jQuery code used:
$('#end').click(function(){
        $("html, body").css("overflow", "hidden");
});

Living demo: http://jsfiddle.net/hYNGn/
This happens in all major browsers: Chrome, Firefox, IE9, Opera...
How can avoid this behavior?
Thanks.

A: The body has height: 100% but the children nodes make him overflow. When you set the overflow to hidden result the body back to height: 100% relative to the window so it looks like an scroll.
You can do this to keep the height, but I don't see the point of doing this, and it's bugs the scrollbar on Chrome/Chromium
$("html, body").css({
    "overflow": "hidden",
    "height": "auto"
});

A: Maybe this?
http://jsfiddle.net/hYNGn/2/
$('#end').click(function(){
    var thetop = - $(window).scrollTop();
    $("div.demo").css("margin-top",thetop);
    $("html, body").css("overflow", "hidden");
});

A: Only set the body to hide the overflow:
$('#end').click(function(){
  $("body").css("overflow", "hidden");
});

http://jsfiddle.net/jaap/hYNGn/5/

A: try this:
$('#end').click(function(){
        $("html, body").css("overflow", "hidden");
        var bodyElement = $("body");
        bodyElement.scrollTop(bodyElement.height());
});

A: Best workaround your problem would be moving the scroll part to the div instead.
Ad:
overflow hidden to the body
html,body {
 height: 100%;
 overflow: hidden;
}

Ad this:
.demo {
 width: 100%;
 height: 100%;
 overflow: auto;
 position: absolute;
}

And use this click event:
$('#end').click(function(){
 $("div.demo").css("overflow", "hidden");
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detect if window.print is confirm or cancel hello i have a code for print, i do a window open, and this pop-up contain all info for print, and i using the kiosk-printing for automatic printing but that fails sometime, if chrome is open with other instance for example, them i having problems because i need to confirm each print, then i need to know if exist a method for confirm what button press the client in Print Dialog(Print or Cancel).
 var printWindow = window.open(windowUrl, windowName, 'left=500,top=100,width=10,height=10');
             printWindow.document.body.innerHTML = HTL;
             printWindow.document.close();
             printWindow.focus();
             printWindow.print(); // maybe here return if user press print or cancel

           // if(ConfirmPrint=="print"){
            // alert('Print Button');
            //}else{
           //    alert('Cancel Button');
           //   }

A: Sadly, window.print() doesn't return any value. So, there's no way to know if the user clicked Save or Cancel. It's more of your operating system's job to watch what's going on in there. There're, however, two event handlers: window.onbeforeprint and window.onafterprint.

The afterprint event is raised after the user prints or aborts a print dialog.

But again, it's a simple event and it's not telling you which option is selected by the user. And also these two events are not well supported.


text:
Q: Propagation delay when changing In-app Product price & description in Google Play developer console How long does it usually take for the price / description change made in the Google Play Developer console to take effect and propagate to devices?
I have two In-App products I am testing with a price and description change.
Using getSkuDetails() from the IabHelper library I am able to query this information at app runtime.  After changing the information in the Google Play developer console, the description change showed up fairly quickly in app.  However, it's been 2 hours and the price change has yet to query with updated info - it's still getting the original price.
Given that I changed both at the same time, I would expect both to have the same propagation delay.
Which brings up a new question:  If the delay is significant, what happens in this interim? Has the price changed for purchases such that going through the Google Wallet workflow will show the new price, but the value shown to customers in the app, gotten via getSkuDetails(), will reflect the original price?
I've scoured the documentation, but there is very little info on what happens when changing prices.  This blog post was useful, at a high-level:
http://android-developers.blogspot.ca/2012/12/in-app-billing-version-3.html

A: I was observing the same behaviour. Clearing the cache on the "Google Play Store" app fixed it for me.
Simply force stopping my app or the Google Play Store did not. Nor did clearing cache on either my own app or "Google Play services".

A: I believe this should happen instantaneously if everything is done properly. If that isn't the case, it isn't an issue for stackoverflow but rather Google. I'd recommend you contact their support.
Sorry for the short answer =/

A: I had a similar issue today, which turned out to be an error with the way I changed the
prices. I'm based in the UK and changed the default price field value from 1 GBP to 30 GBP.
The app isn't live yet so I didn't bother to change the local prices further down the page
which meant that the store was returning the local price for the UK, which was still the
original 1 GBP.
I had to check the "Overwrite existing prices" option and click the Auto-convert prices now button and, finally I had to save the product before it would return the correct price. It still wasn't immediately updated, but did eventually return the correct price after about 3 hours.

A: I have found the google console IAP cost/price updates to be nearly instantaneous.
But I always have to clear the Google Play app's cache on my local device/simulator.

*

*Open up the App Management and find Google Play (in your android
device's settings usually, this has morphed over the years.)

*Clear the cache of the app.

*Then... just to be safe... kill and restart your app you are testing to be sure.

*If that doesn't cause it to work. Restart the device.

This has worked for me every time. The local instance of Google Play app caches those values (to save on chatty network bandwidth requests if I was to guess...)
One other thing to remember... if you using the file import function to set your products/prices and you set prices per region... the base region (US for me) will have a SECOND entry... make you to set that value too. Your prices will NEVER change if you don't and it will say the price you set overall in the console.


text:
Q: Django DeprecationWarning Use of .. or absolute path I am getting a lot of these warnings in production but not on devstack which is making me curious to know about this warning and how to get rid of this. Apparently there is no information which imports is causing the issue.
I am looking for any tools, documentation that explains this Deprecation warning when this will raise an exception in the future and steps to get rid of this warning.
thank you!
[__init__.py:1566] - /edx/app/edxapp/venvs/edxapp/lib/python3.5/site-packages/pkg_resources/__init__.py:1158: DeprecationWarning: Use of .. or absolute path in a resource path is not allowed and will raise exceptions in a future release.

A: The issue was that in the code I was using resource_filename from pkg_resources
` in a way that would raise the warning.
import pkg_resources
pkg_resources.resource_filename(resource,'/translations')

Fix
import pkg_resources
pkg_resources.resource_filename(resource,'translations')


text:
Q: How to use regular expression to replace non-digits and math operators together? How do I only keep chars of [0-9] and [+-*/] in a string in Java?  My approach is to use a union to create a single character class comprised of [0-9] and [+-*/] character classes, but I got an empty string.
Here is an example string I use: 10+2*2-5
public void cleanup(String s){
    String regex = "[^0-9[^+-*//]]";
    String tmp = s.replaceAll(regex, "");
    System.out.println(tmp);
}

A: You have an issue there with the way you have use - in the second part, if you use - in the middle of an expression like you have in [^+-*/] it thinks that is part of a range expression like you did with 0-9 so you need to put the - at the end of the expression so that it isn't treated as a range.
The following expression should do what you are after:
[^0-9*/+-]

A: You want you character class ([...]) to include the range 0-9 and the additional characters *, /, - and +. All you need is to put them one after the other and escape - (\\-), unless it's the last character. Then, use a negation construct (^) inside at the beginning:
public class Example {

    public static void main(String[] args) {

        String test = "a3f6+[,b7*\"d/-8u";
        System.out.println(test.replaceAll("[^0-9/*+-]", ""));
    }
}

Outputs
36+7*/-8

A: What about s/[^0-9]|[^+-*//]//g for the regex?


text:
Q: What happens after EntityManager.persist() The EntityManger is injected with @PersistenceContext annotation. This is a method from my "DAO/Repository" class which is not annotated. This class is injected into the EJB's that needs to get data from/to the database.
Until now I thought that after the persist method below is finished the persistencecontext is flushed and the data is stored to the database but from what happening in my app I start to doubt that. I have made the datasource and connection pool in Glassfish so I am using container managed transactions as far I know, however I do not use any transaction annotations.
Could somebody throw some light over it for me?
public void persist(QuestionFeedback questionFeedback) {
    questionFeedback.setCreated(new Date());
    entityManager.persist(questionFeedback);
}

Using Glassfish 3, Java EE6 compatiblity

A: The persist method makes the entity persistent, but doesn't yet write the change to the database. This normally happens when the transaction commits (the provider is free to optimize this, it could happen earlier).
With flush you can force the write to happen earlier, but it will still be visible only to code that participates in the current transaction. To make the write permanent (visible to all external code), the transaction still needs to be committed.
Without any explicit annotations, your EJB bean will be transactional by default.

A: If you don't use any transaction annotations the default will be transactions being required. Thus your DAO will run in a transaction and the persistence context will no later be flushed than when the transaction is committed.
From the JavaDoc on TransactionAttribute:

If the TransactionAttribute annotation is not specified, and the bean uses container managed transaction demarcation, the semantics of the REQUIRED transaction attribute are assumed.

From the JavaDoc on FlushModeType:

When queries are executed within a transaction, if FlushModeType.AUTO is set on the Query or TypedQuery object, or if the flush mode setting for the persistence context is AUTO (the default) and a flush mode setting has not been specified for the Query or TypedQuery object, the persistence provider is responsible for ensuring that all updates to the state of all entities in the persistence context which could potentially affect the result of the query are visible to the processing of the query.

This means that the persistence context might be flushed earlier, if you use a query whose result might be influenced by that flush.

A: Because EntityManager is injected via @PersistenceContext annotation, you are for sure using container managed transactions.
Anyway, your assumption that persist causes transaction commit is wrong. Change performed via persist is made to the database in commit. Documentation of EntityManager says that "new instance becomes both managed and persistent by invoking persist". In this context "becomes persist" does not mean entity is persisted to the database on that moment. On the moment when persist is called, entity is persisted in the terms of PersistenceContext. It is then later on  persisted to the database latest when transaction commits.
Because you are not using any @TransactionAttribute annotations for your methods, default will apply. Default is TransactionAttributeType.REQUIRED. This will cause container to create transaction when first business method is called and propagate this on to other methods. Your transaction will commit when the call to the first business method is completed. Then your changes are in database (if no rollback was performed).


text:
Q: AWS ELB Autoscaling group with common filesystem (e.g. EBS) I am using AWS elastic beanstalk with autoscaling group
I wish to log events into files and be able to finish processing the files before instances terminate during a shutdown.
I read that lifecycle hooks can answer my requirement.
My question is: is there an alternative like using a common EBS file system for all the instances in the group that will always be kept live. If that is possible, is there any cons using that approach? Is IO slower?

A: EBS volume can not be attached to several EC2 instances at the same time.
But shared storage is possible with EFS — Elastic File System. It's pricey, so EFS is not suitable for large amounts of data. But it is as fast as any NFS share and can be mounted to hundreds of servers at the same time.
The only consideration is how you will mount EFS volume. Since Elastic Beanstalk doesn't support cloud-init, you will have to build an AMI or issue a mount command from your code.


text:
Q: How to debug theme (Theme is causing pages to have no style or HTML  section) I have a WordPress theme given to me by a client, so not familiar with it at all. Activating the Twenty Sixteen theme resolves the problem, so it's not a plugin but definitely the client's theme.
Certain pages are being displayed with no  or  sections. Just the <div>....</div> fragment.
The content of the page is therefore just black text on white background. No errors in log files. Have set the following debug options in wp-config.php:-
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', true );
@ini_set( 'display_errors',1 );

But no errors shown.
Any ideas where in the theme I should start looking?

A: Thanks for the helpful comments, turned out it was the CiviCRM 4.7 plugin that was using a 'base page' and always calling page.php as the default theme template. BUT our Theme was not implementing page.php so no <html> or <head> content was being injected.
Debugged by installing XDebug on the server running on port 9000 and PHPStorm on the client (there are free ones, but this is so easy to set up!) and finally the 'Chrome XDebug helper extension'. Sorry, no more links due to reputation :(
Stepping through the code showed the template hierarchy that had been implemented by the original theme developers, always bypassing page.php and calling partials/front-page.php, which is a common pattern used in some themes, e.g. Virtue.
So the resolution was to add a filter to the bottom of the 'functions.php' file in the Theme route and override the CiviCRM plugin action that was calling page.php:-
add_filter( 'civicrm_basepage_template', 'front_page_for_civi' );
function front_page_for_civi( $template ) {
    if ($template=='page.php') {
        return 'partials/front-page.php';
    }
    return $template;
}
Depending on the plug-in, this filter will obviously need to be called something other than civicrm_basepage_template, but hope it points people in the right direction!
Kudos to @christian-wach for originally answering this in the CiviCRM stack exchange forum.


text:
Q: hide the first number of the section I would like to hide the section number from the subsection.
From this:
1 Section
  1.1 Subsection
   1.1.1 Subsubsection
   1.1.2 Subsubsection
  1.2 Subsection
   1.2.1 Subsubsection
   1.2.2 Subsubsection
   etc.....

To this:
1 Section
  1 Subsection
   1.1 Subsubsection
   1.2 Subsubsection
  2 Subsection
   2.1 Subsubsection
   2.2 Subsubsection
   etc.....

A: Welcome to TeX.SE!
That is bad idea! How you will distinguish between section and subsection? Anyway, you can try:
\documentclass{article}
\renewcommand\thesubsection{\arabic{subsection}}
\renewcommand\thesubsubsection{\thesubsection.\arabic{subsubsection}}

\begin{document}
\section{first}
\subsection{first subsection}
\subsubsection{first subsubsection}
\end{document}


text:
Q: Lazarus: stacking images, paint order I want to design a simple game (lazarus 1.8.4) with an image as playing field and some figures (transparent images) over it, created on runtime. So typically more than one images are at the same position. How can I make sure, that the figures are above the playing field?

A: TControl has a function called BringToFront which will move the Control to the first position in the Z-Axis (the opposing function would be SendToBack). As TImage is derived from TControl the function applies to TImage as well.


text:
Q: After Validations go to next fragment In my app I want to go next fragment after validation of checkboxes and Edit text

*

*I wrote code for validation but not able to put logics to go to next fragment after pressing Next Button

EXPLANATION
Fragment contain two checkboxes, user have a choice to select either checkbox 1 or checkbox 2 or both
and for each checkboxes it contains Edit texts
so how can put logics so that it should validate and should go to next fragment
EXAMPLE

*

*If user checked only checkbox 1 so it should validate the Edit text and then go to next fragment after pressing next button

*Similarly if user checked only checkbox 2

*And last if user checked both checkBoxes so it should validate both the Edit Text specified with it and then after pressing next button it will go to next fragment
Note - Validation means here edit text should not empty or blank. And check box should not unchecked.
I hope i explained my doubt Clearly

A: You mean something like this?
class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            val EditText_1 = findViewById<EditText>(R.id.et1)
            val EditText_2 = findViewById<EditText>(R.id.et2)

            val CheckBox_1 = findViewById<CheckBox>(R.id.cb1)
            val CheckBox_2 = findViewById<CheckBox>(R.id.cb2)

            val Button = findViewById<Button>(R.id.bt)

            Button.setOnClickListener {
                when {
                    CheckBox_1.isChecked && CheckBox_2.isChecked && EditText_1.text.isNotBlank() && EditText_2.text.isNotBlank() -> {
                        // Proceed To next fragment
                    }
                    CheckBox_1.isChecked && EditText_1.text.isNotBlank() -> {
                        // Proceed To next Fragment
                    }
                    CheckBox_2.isChecked && EditText_2.text.isNotBlank() -> {
                        // Proceed To next Fragment
                    }
                }
            }
        }
    }


text:
Q: How to replace a given substring with "" from a given string? I went through a couple of examples to replace a given sub-string from a given string with "" but could not achieve the result. The String is too long to post and it contains a sub-string which is as follows:-
/image/journal/article?img_id=24810&t=1475128689597

I want to replace this sub-string with "".Here the value of  img_id and t can vary, so I would have to use regular expression. I tried with the following code:-
String regex="^/image/journal/article?img_id=([0-9])*&t=([0-9])*$";
content=content.replace(regex,"");

Here content is the original given string. But this code is actually not replacing anything from the content. So please help..any help would be appreciated .thanx in advance.

A: Use replaceAll works in nice way with regex
content=content.replaceAll("[0-9]*","");

Code
String content="/image/journal/article?img_id=24810&t=1475128689597";
content=content.replaceAll("[0-9]*","");
System.out.println(content);

Output :
/image/journal/article?img_id=&t=

Update : simple, might be little less cozy but easy one
    String content="sas/image/journal/article?img_id=24810&t=1475128689597";
    content=content.replaceAll("\\/image.*","");
    System.out.println(content);

Output:
sas

If there is something more after t=1475128689597/?tag=343sdds and you want to retain ?tag=343sdds then use below
    String content="sas/image/journal/article?img_id=24810&t=1475128689597/?tag=343sdds";
    content=content.replaceAll("(\\/image.*[0-9]+[\\/])","");
    System.out.println(content);
    }

Output:
sas?tag=343sdds

A: If you're trying to replace the substring of the URL with two quotations like so:
/image/journal/article?img_id=""&t=""
Then you need to add escaped quotes \"\" inside your content assignment, edit your regex to only look for the numbers, and change it to replaceAll:
content=content.replaceAll(regex,"\"\"");

A: You can use Java regex Utility to replace your String with "" or (any desired String literal), based on given pattern (regex) as following:
String content = "ALPHA_/image/journal/article?img_id=24810&t=1475128689597_BRAVO";
String regex = "\\/image\\/journal\\/article\\?img_id=\\d+&t=\\d+";
Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
    String replacement = matcher.replaceAll("PK");
    System.out.println(replacement); // Will print ALPHA_PK_BRAVO
}


text:
Q: Bootstrap 4 drop-down menu fade out ( Анимация исчезновения )? Хочу сделать, чтобы при наведении на кнопку, появлялось все меню.
Пока что нашел только это, но проблема в том, что все меню открывается при наведении на блок с меню, а не на кнопку ( смотрите скриншот)
Есть идеи ребят ?

 .d-flex>.dropdown:hover>.dropdown-menu {
    display: block;
    opacity: 1;
 }

 .d-flex>.dropdown>.dropdown-menu {
    display: block;
    opacity: 0;
    -webkit-transition: all 200ms ease-in;
    -moz-transition: all 200ms ease-in;
    -ms-transition: all 200ms ease-in;
    -o-transition: all 200ms ease-in;
    transition: all 200ms ease-in;
 }

                <button class="btn  dropdown-toggle " style= "display: block" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                РАСПРОДАЖА
                </button>

                                    Женщины
                                    Распродажа - Последний шанс
купить
                                    Посмотреть все
                                    Платья
                                    Топы


text:
Q: How can i get the difference between two starting dates using awk? I need to print the difference (in days) between the oldest date of $4 and $2 for each unique Id ($1).
here is the data
32070  2010-12-14    13:25:30  20101211 13:25:30
41920  2010-12-14    11:30:45  20101213 11:30:45
29446  2010-12-14    04:15:25  20101211 04:15:25
32070  2011-05-11    08:14:20  20101211 08:12:23
29446  2011-6-22     07:13:24  20101211 10:13:50
41920  2011-5-14     06:15:25  20101213 12:14:05
32070  2011-5-13     12:11:05  20101211 06:12:30
41920  2011-5-16     05:15:08  20101213 15:13:30
29446  2011-6-23     10:20:15  20101211 10:12:16

out put will look like this
32070  2010-12-14    13:25:30  20101211 03:25:30 3
41920  2010-12-14    11:30:45  20101213 08:30:15 1
29446  2010-12-14    04:15:25  20101211 09:15:25 3
32070  2011-05-11    08:14:20  20101211 04:12:23 3
29446  2011-6-22     07:13:24  20101211 10:13:50 3
41920  2011-5-14     06:15:25  20101213 12:14:05 1
32070  2011-5-13     12:11:05  20101211 06:12:30 3
41920  2011-5-16     05:15:08  20101213 15:13:30 1
29446  2011-6-23     10:20:15  20101211 10:12:16 3

A: @Alula- I think there is a mistake in your output from 4th line eg-> how come difference of 2011-05-11(5th month of 2011) and 20101211(12th month of 2010) difference could be 3 days?
If this is a typo, could you please try following and let me know if this helps.
awk '{gsub(/-/," ",$2);;printf("%s %d\n",$0,(mktime($2 FS 0 FS 0 FS 0)-mktime(substr($4,1,4) FS substr($4,5,2) FS substr($4,7,2) FS 0 FS 0 FS 0))/(3600 * 24))}'  Input_file

Let me know if this helps you.
EDIT: Adding answer as per OP's request now too.
awk '!A[$2,$4]++{E=$2;R=$4;gsub(/-/," ",E);;printf("%s %d\n",$0,(mktime(E FS 0 FS 0 FS 0)-mktime(substr(R,1,4) FS substr(R,5,2) FS substr(R,7,2) FS 0 FS 0 FS 0))/(3600 * 24))}'  Input_file

@Alula: Kindly do let me know if this helps you.


text:
Q: True leak or false analyzer report? I have code that looks like the following:
CFDictionaryRef myFunction()
{
    CFIndex myNumberIndex = 1234;
    CFNumberRef myNumber = NULL;
    CFMutableDictionaryRef theDict =  CFDictionaryCreateMutable(kCFAllocatorDefault, 0, 0, 0);

    myNumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &myNumberIndex);
    CFDictionaryAddValue(theDict, kSomeKeyConstant, myNumber);

    return theDict;
}

The clang static analyzer reports that myNumber is a leaked object. Obviously since there's no call to CFRelease() I'm inclined to understand the issue, but I'm not well versed enough with CF in general so I want to verify: does myNumber need to be released here even though it's added to a CFDictionary that gets returned? That is... is what I'm adding to the dictionary a copy having its own retain/release needs (in which case I do need to release it here)? I assume the answer has to do with the kCFAllocatorDefault parameter used when the dictionary was created but I don't see a clear indication of ownership of the object.

A:
does myNumber need to be released here even though it's added to a CFDictionary that gets returned?

Yes, you need to release it. If the dictionary wants to retain that object, it will -- what the dictionary does with it isn't your problem. But you created the object, so you need to release it.
It might help to look at the issue from the perspective of the function that calls myFunction(). myFunction() returns a CFDictionary. Is the caller supposed to release every object in that dictionary when it no longer needs the dictionary? Of course not. But if the caller doesn't do it, and if you don't release myNumber, the object will never be released, right? That's a leak.
See the Core Foundation memory management rules for further explanation. One of the examples there is nearly the same situation and shows the release being performed as required:
float myFloat = 10.523987;
CFNumberRef myNumber = CFNumberCreate(kCFAllocatorDefault,
                                    kCFNumberFloatType, &myFloat);
CFMutableArrayRef myArray = CFArrayCreateMutable(kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks);
CFArrayAppendValue(myArray, myNumber);
CFRelease(myNumber);


text:
Q: parseable git log output You can customize the output of git log using --pretty and you can show the number of added and deleted lines using --numstat. It looks like this:
$ git log --pretty=format:"%h - %ar : %s" --numstat config*.ini

f665c63 - 6 months ago : fixes session end post
1       1       config.ini

4541de2 - 7 months ago : fixes missing strings
6       1       config.ini
3       1       config_office.ini

But what I want is the output of both, the commit information and the changes in the files, to show in one line each. Something like this:
1       1       config.ini            f665c63 - 6 months ago : fixes session end post
6       1       config.ini            4541de2 - 7 months ago : fixes missing strings
3       1       config_office.ini     4541de2 - 7 months ago : fixes missing strings

This way it would be straightforward to parse this output using grep, sort, etc. Does git already provide this functionality?

A: As far as I can tell, git log can't do that natively. However, this sed command will do it:
sed '/^[0-9]\+\t[0-9]\+\t[^\t]\+$/ b file; h; d; : file; G; s/\n/\t/'

It looks for the --numstat lines. Any non-numstat line is copied into the hold buffer and not printed. Lines with numstat output get the current contents of the hold buffer appended, leaving a newline in the middle, which is then replaced with a tab.


text:
Q: Difference between boost::any and boost::variant when we use cout<< I have run the following piece of code successfully using boost::variant<string, float>. However, when I tried to use boost::any instead, I face mismatch operand error at cout<< instruction, the piece of code is :
for( vector<vector<vector<boost::any>>>::const_iterator i = masterList.begin(); i != masterList.end(); ++i)
{
    for( vector<vector<boost::any>>::const_iterator j = i->begin(); j != i->end(); ++j)
    {
        for( vector<boost::any>::const_iterator k = j->begin(); k != j->end(); ++k)
        {
            cout<<*k<<' ';
        }
    }
}

A: Boost.Any offers full type erasure, all characteristics (such as streaming to a std::ostream) of the underlying type are erased. The only way to get back the type is by using the any_cast functions.
If you want partial type erasure, look at the Boost.TypeErasure library of Steven Watanabe. Note that TypeErasure is an official Boost library since Boost 1.54.


text:
Q: Dynamic SSRS LInk I am creating a SSRS report with dynamic URL. Content which is in bold is the system generated ticket number which I want to pull my the Fields!Change_Number.Value column.
Original URL
https://sm.com/webtier-9.50/index.do?ctx=docEngine&file=cm3r&query=number%3D%22C945212658%22&action=&title=Change%20C945212658
This is what I have tried
="https://sm.com/webtier-9.50/index.do?ctx=docEngine&file=cm3r&query=number%3D%22Fields!Change_Number.Value%22&action=&title=Change%20"Fields!Change_Number.Value
Error:
The ActionInfo.Action.Hyperlink expression for the text box 'Change_Number2' contains an error: [BC30205] End of statement expected.
Thank you

A: You need to concatenate those fields: the first is within the double quote block, so it is being taken literally and adding the string 'Fields!Change_Number.Value' to the URL, not the value that you want. The second field is just bare outside the double quotes, so it doesn't know what to do with it - that is the one causing the error.
You can concatenate strings using either + or &. See: Operators in Expressions
="https://sm.com/webier-9.50/index.do?ctx=docEngine&file=cm3r&query=number%3D%22" & Fields!Change_Number.Value & "%22&action=%title=Change%20" & Fields!Change_Number.Value

A: To embed a field into a dynamic URL, you don't actually embed it - you append it. Here is your URL corrected:
="https://sm.com/webtier-9.50/index.do?ctx=docEngine&file=cm3r&query=number%3D" + Fields!Change_Number.Value + "&action=&title=Change%20" + Fields!Change_Number.Value


text:
Q: Reading big files in Java using readfully I have a big file of size 10gb,
If i read its whole contents using readfully() in java, I get a outofmemoryerror,
so i decided to read the big 10gb file in parts using same readfully(), for this i need to pass the offset and length parameters for readfully(). The offset must be of long or double datatype so that it can point to different parts of the file. But the readfully() accepts only int offset. How to read the big data?
try {
    IOUtils.readFully(in, contents, minOffset, maxOffset);
    value.set(contents, 0, contents.length);
} finally {
    IOUtils.closeStream(in);
}

Can I use seek() to get to a specific position and then use readfully() from that position?

A: Use the class java.util.Scanner to run through the contents of the file and retrieve lines serially, one by one:
FileInputStream inputStream = null;
Scanner sc = null;
try {
    inputStream = new FileInputStream(path);
    sc = new Scanner(inputStream, "UTF-8");
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        // System.out.println(line);
    }
    // note that Scanner suppresses exceptions
    if (sc.ioException() != null) {
        throw sc.ioException();
    }
}
finally {
    if (inputStream != null) {
        inputStream.close();
    }
    if (sc != null) {
        sc.close();
    }
}

This solution will iterate through all the lines in the file – allowing for processing of each line – without keeping references to them – and in conclusion, without keeping them in memory. For more details see this.


text:
Q: java code that i am unable to rectify I wrote this java code for a project I am working on. I have gone as far as I can, but still can't get it to work, so I thought I would try here.
The program is supposed to use a JOptionPane to ask the user what to city's he would like to see the mileage distance between. Those numbers come from a .txt file.
I always get an error that "j" cant be found.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Mileage
{
    public static void main(String[] paramArrayOfString)
    throws IOException
    {
        String str3 = "";

        Scanner localScanner = new Scanner(new File(JOptionPane.showInputDialog("Enter the name of the data file.")));

        String str1 = localScanner.nextLine() + " Cities:\n\n";

        int i = localScanner.nextInt();

        ArrayList localArrayList = new ArrayList(i);

        int[][] arrayOfInt = new int[i][i];
        for (int j = 0; j < i; j++)
        {
            localScanner.nextLine();
            localArrayList.add(localScanner.nextLine());
            for (int k = 0; k < i; k++)
            {

                arrayOfInt[j][k] = localScanner.nextInt();
            }
        }
        j = 1 ;
        for (String str4 : localArrayList)
        {
            str1 = str1 + j++ + ". " + str4 + "\n"; str1 = str1 + "\nEnter from and to cities for mileage, \"Quit\" or \"quit\" to quit.";
            String str2;
        }
        do
        {
            str2 = JOptionPane.showInputDialog(str3 + str1);
            if (str2.equalsIgnoreCase("quit"))
            {
                continue;
            }
            localScanner = new Scanner(str2);
            int m = localScanner.nextInt();
            int n = localScanner.nextInt();
            if ((m < 1) || (m > i) || (n < 1) || (n > i))
                str3 = "Invalid values, try again.\n\n";
            else {
                str3 = "The distance between " + (String)localArrayList.get(m - 1) + " and " + (String)localArrayList.get(n - 1) + " is " + arrayOfInt[(m - 1)][(n - 1)] + " miles.\n\n";
            }
        }

        while (!str2.equalsIgnoreCase("quit"));
    }
}

and here is another form I tried, little is different, but both have same error:
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class MileageTest
{
    public static void main(String[] paramArrayOfString)
    throws IOException
    {
        String str5 = "";

        String str1 = JOptionPane.showInputDialog("Enter the name of the data file.");
        Scanner localScanner = new Scanner(new File(str1));

        String str2 = localScanner.nextLine();

        int i = localScanner.nextInt();

        ArrayList localArrayList = new ArrayList(i);

        int[][] arrayOfInt = new int[i][i];
        for (int j = 0; j < i; j++)
        {
            localScanner.nextLine();
            localArrayList.add(localScanner.nextLine());
            for (int k = 0; k < i; k++)
            {
                arrayOfInt[j][k] = localScanner.nextInt();
            }
        }
        String str3 = str2 + " Cities:\n\n";
        j = 1;
        for (String str6 : localArrayList)
            str3 = str3 + j++ + ". " + str6 + "\n";
            str3 = str3 + "\nEnter from and to cities for mileage, \"Quit\" or \"quit\" to quit.";
            String str4;
        do {
            str4 = JOptionPane.showInputDialog(str5 + str3);
            if (str4.equalsIgnoreCase("quit"))
                continue;
            localScanner = new Scanner(str4);
            int m = localScanner.nextInt();
            int n = localScanner.nextInt();
            if ((m < 1) || (m > i) || (n < 1) || (n > i))
                str5 = "Invalid values, try again.\n\n";
            else
            {
                str5 = "The distance between " + (String)localArrayList.get(m - 1) + " and " + (String)localArrayList.get(n - 1) + " is " + arrayOfInt[(m - 1)][(n - 1)] + " miles.\n\n";
            }
        }

        while (!str4.equalsIgnoreCase("quit"));
        test();
    }

   private static void test()
   {
        System.out.println("Testing...");
   }
}

A:     for (int j = 0; j < i; j++)
    {
        localScanner.nextLine();
        localArrayList.add(localScanner.nextLine());
        for (int k = 0; k < i; k++)
        {

            arrayOfInt[j][k] = localScanner.nextInt();
        }
    }
    j = 1 ; <--- THIS IS THE PROBLEM. j does not exist at this scope.

A: In both versions of your code you're declaring the variable j in your for statement:
for (int j = 0; j < i; j++)

When you declare j this way, it's scope is limited to the for loop, and it isn't usable outside the loop. But you're trying to use it outside the loop.
If you want to continue to use j after that for loop, declare it outside the loop:
int j = 0;
for (j = 0; j < i; j++)

A: In the first snippet, the j variable is declared inside the for loop which means it is local to the for loop. It is not visible from the outside. Just declare it before the for loop:
int j = 0;

and then
for (j = 0; j < i; j++)

The above is true for the second piece of code, too.


text:
Q: how to trigger an event when an item is selected from combobox in c#.net         string Sql_type = "select property_type_id,type_name from lk_tb_property_type";

        OleDbCommand cmd_type = new OleDbCommand(Sql_type, con);

        OleDbDataReader DR_two = cmd_type.ExecuteReader();
        DataTable table_two = new DataTable();
        table_two.Load(DR_two);

        //begin adding line
        DataRow row_two = table_two.NewRow();
        row_two["type_name"] = "Select Poperty Name";
        row_two["property_type_id"] = 0;
        table_two.Rows.InsertAt(row_two, 0);
        //end adding a line

        combo_type.DataSource = table_two;

        combo_type.DisplayMember = "type_name";
        combo_type.ValueMember = "property_type_id";
        combo_type.Text = "Select Poperty Name";

with this code i am fetching values for a combobox from database.now suppose my combobx is having 2 items named A and B..I have one more combobox...now what i want is that when user chooses item A from combobox the second combobox should display  data related to item A when  user chooses item B then data related to item B should be displayed...sohow to achieve this...??

A: you can fetch the data and bind it to combobox2 on SelectedIndexChanged event of combobox1
private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
     var val = combobox1.SelectedValue;
     // fetch data from database
     // you need to set SQL parameter value form SelectedValue

     combobox2.DataSource = ...; // set this value
     combobox2.DisplayMember = .....; // set this value
     combobox2.ValueMember = ....; // set this value

}

A: Please assign an event SelectedIndexChanged and AutoPostBack = true is this is a web Application in C#

A: In SelectedIndexChanged of combo box write your code. and make AutoPostBack = true of your combobox

A: You can do like these steps.
First, bind data to comboBox1 (I suppose that your first ComboBox named "comboBox1", and your form named "Form1"), please make sure that your SQL query command is correct for comboBox1
private void Form1_Load(object sender, EventArgs e)
{
    OleDbConnection con = new OleDbConnection(constr);

    con.Open();
    string Sql_cust_name = "select customer_name from tb_customer";

    OleDbCommand cmd_cust_name = new OleDbCommand(Sql_cust_name, con);

    OleDbDataReader DR_cust_name = cmd_cust_name.ExecuteReader();
    DataTable table_cust_name = new DataTable();
    table_cust_name.Load(DR_cust_name);

    DataRow row_cust_name = table_cust_name.NewRow();
    row_cust_name["customer_name"] = "Select Customer Name";

    table_cust_name.Rows.InsertAt(row_cust_name, 0);

    combo_cust_name.DataSource = table_cust_name;
    combo_cust_name.DisplayMember = "customer_name";
    combo_cust_name.ValueMember = "customer_name";
    combo_cust_name.Text = "Select Customer Name";

    con.Close();
}

Next, bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed, this value will be used in the filtering for data in comboBox2, so you have to handle SelectedIndexChanged event for comboBox1, please make sure that you have this code somewhere in your project: this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
To bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed
private void combo_cust_name_SelectedIndexChanged(object sender, EventArgs e)
{
    OleDbConnection con = new OleDbConnection(constr);

    con.Open();

    string customerName = "";
    if (combo_cust_name.SelectedValue.GetType() == typeof(DataRowView))
    {
        DataRowView selectedRow = (DataRowView)combo_cust_name.SelectedValue;
        customerName = selectedRow["customer_name"].ToString();
    }
    else
    {
        customerName = combo_cust_name.SelectedValue.ToString();
    }

    string Sql2 = "SELECT customer_number FROM tb_customer WHERE customer_name = '" + customerName + "'";
    OleDbCommand cmd_type = new OleDbCommand(Sql2, con);

    OleDbDataReader DR_two = cmd_type.ExecuteReader();
    DataTable table_two = new DataTable();
    table_two.Load(DR_two);

    DataRow row_two = table_two.NewRow();
    row_two["customer_number"] = "Select Customer Number";
    table_two.Rows.InsertAt(row_two, 0);

    comboBox2.DataSource = table_two;
    comboBox2.DisplayMember = "customer_number";
    comboBox2.ValueMember = "customer_number";
    comboBox2.Text = "Select Customer Number";
}

Please correct the SQL query command as you want, but don't forget to put a correct filter like my sample code above.


text:
Q: If $ \frac{1-z}{1+z} $ is purely imaginary, then what will be $ \vert z \vert $? Assuming $ z $ a non-zero complex number; the ratio $ \frac{1-z}{1+z} $ is purely imaginary. Then what will be $ \vert z \vert $ ?
I can't figure out a clear, simple way to figure out its real part. How to do it?

A: IMO problems like this should be solved without using imaginary/real parts.
You were given that something is pure imaginary. Therefore that something is negated under complex conjugation. IOW
$$
\frac{1-z}{1+z}=-\overline{\left(\frac{1-z}{1+z}\right)}=-\frac{1-\overline{z}}{1+\overline{z}}.
$$
Thus
$$
(1-z)(1+\overline{z})=-(1-\overline{z})(1+z).
$$
Expanding both sides you see that the terms $-z+\overline{z}$ cancel, and, recalling that $z\overline{z}=|z|^2$, you are left with the equation
$$1-|z|^2=-(1-|z|^2).$$
Leaving this to you.

A: Say $${1-z\over 1+z} =ib\;\;\;\Longrightarrow \;\;\;z = {1-bi \over 1+bi}$$
so $$|z| = {|1-bi|\over |1+bi|} = 1$$

A: Hint: set $z = a + ib$. You then have,
$$\frac{1-a-ib}{1+a+ib}$$
Start by multiplying by $$\frac{1-a-ib}{1-a-ib}$$.

A: Hint. One may observe that
$$
\frac{1-z}{1+z}=\frac{(1-z)(1+\bar{z})}{(1+z)(1+\bar{z})}=\frac{1-|z|^2+2i\text{Im}z}{\left|1+z\right|^2}.
$$

A: Just to give a different argument, any linear fractional transformation $f(z)={az+b\over cz+d}$ (with $ad-bc\not=0$) takes circles to circles, where straight lines qualify as circles (of zero curvature).  For $f(z)={1-z\over1+z}$, we have $f(1)=0$ and $f(\pm i)=\mp i$.  Thus the (unique) circle determined by the points $1$, $i$, and $-i$ maps to the (unique) circle determined by the points $0$, $-i$, and $i$.  The former is the unit circle, and the latter is the imaginary axis.  So $f(z)={1-z\over1+z}$ is imaginary if and only if $|z|=1$ (except for $z=-1$, unless you want to think of $f(-1)=i\infty$ as imaginary).
The algebra, of course, has simply been swept under the rug of the general theorem about linear fractional transformations taking circles to circles.

A: Hint. Write $z=x+yi$ and expand the fraction by $1-(x+yi)$

A: Hint
Let $z = a+bi$, then
$$\frac{1-a-bi}{1+a+bi} = \frac{(1-a-bi)(1+a-bi)}{(1+a+bi)(1+a-bi)} = \frac{1+a-bi-a-a^2+abi-bi-abi+b^2}{(1+a)^2-b^2}=\frac{1-2bi-a^2+b^2}{1+a+a^2-b^2}=ci$$
for some $c \in \mathbb R$. What requirements on $a,b$ must be true for the real part to equal 0?

A: If $(1-z)/(1+z)$ is purely imaginary, then we can write
$$\frac{1-z}{1+z} = ai \qquad \exists\,a\in\mathbb R$$
solving this equation for $z$ gives $$ z = \frac{1-ai}{1+ai} = \frac{1-a^2}{1+a^2} -\frac{2a}{1+a^2}i,$$
so $$|z| = \sqrt{\left(\frac{1-a^2}{1+a^2}\right)^2 + \left(\frac{2a}{1+a^2}\right)^2},$$
which after a bit of algebraic simplification gives $|z| = 1$.


text:
Q: Scala get output in order So this is a code output when I am doing some queries on my data :
Quartal    Cooperation    Sponsoring        Fees
2014/2    52.878.990,22    1.347.863,90    147.400.000,00
2013/1    41.915.908,42    18.867.625,26    153.753.810,00
2013/2    58.940.141,17    9.196.517,72    153.855.201,00
2014/1    39.257.778,34    17.836.682,47    147.269.362,00
Total:    192.992.818,15    47.248.689,35    602.278.373,00

You can see that the numbers are not printed in a nice way each one in the next line... So I want that these lines are always getting formatted when printed out like this:
Quarter     Cooperation      Sponsoring            Fees
2014/2    52.728.402,92    1.347.863,90  147.400.000,00
2014/3    37.136.924,43    8.270.494,07  147.800.000,00
2014/4    63.044.689,86    1.318.163,94  146.900.000,00
Total    152.910.017,21   10.936.521,91  442.100.000,00

See the difference? So I know that I have to take the length() of the previous one and something like this but I dont know how exactly?
Code snippet looks like this for the print statement:
    println("%s    %s    %s        %s".format("Quartal","Cooperation","Sponsoring","Fees"))
    println(s"Total:    %,.2f    %,.2f    %,.2f".format(totalMedKF2.sum,totalMedKF4.sum,totalMedKF31.sum))

A: Probably you want this:
println("%-10s %16s %16s %16s".format("Quartal","Cooperation","Sponsoring","Fees"))
println(s"Total:     %,16.2f %,16.2f %,16.2f".format(totalMedKF2.sum,totalMedKF4.sum,totalMedKF31.sum))

The numbers in there (-10, 16) are used to tell the formatter the minimum amount of space that should be given for that item.  Negative numbers mean "left-align"; positive numbers mean "right-align".
Lots more info can be found here: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html


text:
Q: A new car is selling for $5000$ down and $5000$/yr (at the end of) each of the next $5$ years. What is the fair price of the car in cash? A new car is selling for $5000$ down and $5000$/year (at the end of) each of the next $5$ years. If interest rates are $5$% compounded semi-annually, what is the fair price of the car in cash?
What I did was make a formula for the Future Value:
$$A(t) = 5000 + 5000 \, \left(1 + \frac{0.05}{2}\right)^{2t}.$$
I plugged in $t = 5$ into the equation and got
$$A(5) = 11400.42.$$
Is this right?

A: $i^{(2)}=5\%$ so the effective annual interest is $i=(1+5\%/2)^2-1\approx 5,06\%$.
The present value is
$$
A(0)=5000+5000v+\cdots+5000v^5=5000\;\ddot a_{\overline{6}|i}=18,258.93
$$
where $v=\frac{1}{1+i}\approx 0.952$.


text:
Q: Overfitting through model selection I'm asking this question as I found little explanation of this phenomenon otherwhere. I am wondering about how to best deal with overfitting that comes from the model selection itself. Say I want to run some regression on a set of observations. My choice of which model to use (linear, log, exponential) is already in some sense a parameterisation. Even more so if I run several regressions using different models and then choosing the best one. For example, if I am to compare a linear with an exponential model of some sort, am I not (implicitly) doing a regression of the sort:

where I is a binary variable that I still determine based on a fitting procedure. Is there a way to quantify (or qualify) to what extent a model may be overfitted because of freedom in model selection?

A: A good question. This is sometimes called "overfitting by investigator".
As long as you have plenty of data, separate it into three parts:
- training data, used to train each specific model
- validation data (also called the dev set) to choose which model to use
- test data, used only as the final step, to determine the performance of your chosen model
If you are data poor, this is more difficult.
Another good step is to write a project plan before looking at the data at all. If you can identify an approach at this stage, from prior knowledge, then it avoids the risk you point to.


text:
Q: using Maven overlay how to include shared jsp in <@ include> tag I have common resources war having common jsps which is included in main project pom.xml as below:
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>

                            <workDirectory>target/overlay-war-folder</workDirectory>
                            <overlays>
                                    <overlay>
                                            <groupId>com.sft</groupId>
                                            <artifactId>CommonResources</artifactId>
                                             <includes>
                                                <include>**/*.jsp</include>
                                            </includes>
                                            <targetPath>WEB-INF/views</targetPath>

                                    </overlay>
                            </overlays>
                    </configuration>
            </plugin>

I want to include jsp from commonresources war in tab as
<div class="tab-content">
                            <%@ include file="common.jsp"
                        </div>

common.jsp File not found error is popping..Do I need to include overlay folder path? How to solve this?

A: Problem was resolved after adding
 runtime   in
 <dependency>
            <groupId>com.sft</groupId>
            <artifactId>CommonResources</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <type>war</type>
            <scope>runtime</scope>
        </dependency>

and removing includes in overlays tag. Also my directory structure in main project under WEB-INF was different than common resources. The problem was resolved by this changes.


text:
Q: javascript in operator and events update:
for( i in window)if(i=='onhashchange')console.log(i, window[i]); //prints onchangechange undefined

on browser where onhashchange event is supported I have
'onhashchange' in window;  //returns true
window['onhashchange']; //returns false
window.onhashchange;  //returns false;

why does the former returns true and the rest returns false?

A: Could it be simply that the window object has a property called onhashchange, but the value of the property is currently null and therefore considered false?
var a = { 'foo': null }
console.log('foo' in a) // true
console.log(a.foo) // null
console.log(!!a.foo) // false

…where the !! is a double negation, a trick to convert value to true/false.

A: I think with help of the first operation you just check if such an event is in window object, so it returns true. Two other tell you if such a handler is implemented, and there is no implementation yet you get false.
Can you check the following:
window.onhashchange = function() {}
window['onhashchange'];

yea, anyway it will return true now, because we have defined that variable... So most probably
'onhashchange' in window;

just checks if browser supports it
window['onhashchange']; //returns false
window.onhashchange;  //returns false;

just checks if handler already implemented
PS. Also you can be interesting in Javascript IN operator compatibility, here @Andy E wrote:

You should err on the side of caution when using it to check event support. All implementations except Mozilla support "eventname" in element as a test for DOM events, Firefox will result in false here unless a handler is defined.

UPDATE: to see difference between "x in window" and "window.x" (which is equal to window['x']), take a look at the following script and its output:
var foo = {};
console.info( 'bar' in foo ); // false, because no such proeprty
console.info( foo.bar ); // undefined, because no such property
console.info( foo.bar ? 'true' : 'false' ); // 'false' because no such property

foo = { bar: false };
console.info( 'bar' in foo ); // true, because there is such property
console.info( foo.bar ); // false, because this is value of bar property
console.info( foo.bar ? 'true' : 'false' ); // 'false' because foo.bar is false

foo = { bar: 1 };
console.info( 'bar' in foo ); // true, because there is such a property
console.info( foo.bar ); // 1, because this is value of bar proeprty
console.info( foo.bar ? 'true' : 'false' ); // 'true', because foo.bar is 1 (which is not 0 which meant to be false)

foo = { bar: 0 };
console.info( 'bar' in foo ); // true, because there is such a property
console.info( foo.bar ); // 0, because this is value of bar proeprty
console.info( foo.bar ? 'true' : 'false' ); // 'false', because foo.bar is 0 (which meant to be false)

UPDATE2: Detecting event support without browser sniffing  - this article shows how to make event detection cross browser (because "event in window" does not work in Mozilla; this article also answers why it is so)


text:
Q: When form submission is done between 2 VM's in Application gateway it shows 502 error I have hosted a site in two VM's and added it in Application Gateway back end pool. We have a form submit which will do DB update and a confirmation page will be shown.
If both the server is up. The changes are updated properly on DB and confirmation page is shown even if the Form Filled from VM1 and submitted to VM2.
Consider the below case. The user comes into the page from VM1 and filling the details. After the VM1 is unavailable. Now when the user submites the code. The page loads and shows 502 proxy error. But the DB update are properly done through VM2. But the confirmation page is not shown.

A: The issue was due to the incorrect timeout value set on Health Probe. When your server is down, the requests will be sent to the backend unhealthy server for 4 minutes as the timeout value is too long. Once the timeout value is reduced, the issue is resolved.


text:
Q: Defining a new word within frequency analysis I would like to know how to define a new word which can include others. For example:
Word    Frequency
0   game    52055
1   laura   24953
2   luke    21133
3   story   20739
4   dog     17054
35  cat     4244

I would like to 'create' a new word, pet, which include dog and cat and their corresponding frequency. Something like this:
Word    Frequency
0   game    52055
1   Laura   24953
4   pet     21298
2   luke    21133
3   story   20739

I am thinking of using a dictionary to do it:
thisdict = {
  "dog": "pet",
  "cat": "pet"}

but I am not sure on how to apply it and if this can allow me to keep also their values (21298 in total)

A: replace first then do groupby
df.Word.replace(thisdict,inplace=True)
df
Out[104]:
     Word  Frequency
0    game      52055
1   laura      24953
2    luke      21133
3   story      20739
4     pet      17054
35    pet       4244
df = df.groupby(['Word'], as_index=False).sum()
df
Out[106]:
    Word  Frequency
0   game      52055
1  laura      24953
2   luke      21133
3    pet      21298
4  story      20739


text:
Q: Submit form by using Bootstrap twitter modal I'm trying to submit a form by using the bootstrap modal. I've managed to submit the data successfully at the code that follows. My issue is that I'm working my php by action tags, ie. if($_GET['action']=='add'){//do something} etc. and I'm sending the information by the url. So..at the time being I changed that I make the insertion after checking if the submit button has been submitted that's why the form is working, is there any way I can send the information by the URL and get it inside the modal?   ie. mypage.php?action=add#myModal)
Furthermore, do you know how to prevent the modal to close after submitting, as I want to give the user the ability to add information more than once.
Any help really appreciated.
Add

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add

            Name
            <input type="text" name="cname" value="" class="input-sm">

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <input type="submit" value="Save" id="save_add" name="save_add" class="btn btn-primary">

A:     <form action="mypage.php" method="get">

 Name	 <input type="text" name="cname" value="" class="input-sm">

 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <input type="submit" value="Save" id="save_add" name="save_add" class="btn btn-primary">
</form>


text:
Q: Dynamic list of variables in process in Azure Data Factory I have a lookup config table that stores the 1) source table and 2) list of variables to process, for example:
SQL Lookup Table:
tableA, variableX,variableY,variableZ   <-- tableA has more than these 3 variables, i.e it has other variables such as variableV, variable W but they do not need to be processed
tableB, variableA,variableB   <-- tableB has more than these 2 variables
Hence, I will need to dynamically connect to each table and process the specific variables in each table. The processing step is to convert the julian date (in integer format) to standard date (date format). Example of SQL query:
select dateadd(dd, (variableX - ((variableX/1000) * 1000)) - 1, dateadd(yy, variableX/1000, 0)) FROM [dbo].[tableA]
The problem is after setting up lookup and forEach in ADF, I am unsure how to loop through the variable array (or string, since SQL DB does not allow me to store array results) and convert all these variables into the standard time format.
The return result should be a processed dataset to be exported to a sink.
Hence would like to check what will be the best way to achieve this in ADF?
Thank you!

A: I have reproed in my local environment. Please see the below steps.

*

*Using lookup activity, first get all the tables list from control table.

*Pass the lookup output to ForEach activity.

*Inside ForEach activity, add lookup activity to get the variables list from control table where table name is current item from ForEach activity.
  @concat('select table_variables from control_tb where table_name = ''',item().table_name,'''')

*Convert lookup2 activity output value to an array using set variable activity.

@split(activity('Lookup2').output.firstRow.table_variables,',')

*create another pipeline (pipeline2) with 2 parameters (table name (string) and variables (array)) and add ForEach activity in pipeline2

*Pass the array parameter to ForEach activity in pipeline2 and Use the copy activity to copy data from source to sink

*Connect Execute pipeline activity to pipeline 1 inside ForEach activity.


text:
Q: How to create an SQL column that can have multiple values? I created a table in SQL using PostgreSQL called "tenants". Below is the code for the tenants:
create table tentants (
id bigserial not null primary key,
tenant_name varchar(1000) not null,
offices int not null,
number int not null,
email varchar(1000)

I want to include the ability to add multiple values to "office" in case a tenant rents more than one office. I don't want to use JSON for this. I tried creating a related table called "offices" but That could only allow me to add one office per tenant.
What is the best approach for this?

A: You can create an "tenant_offices" table (like you did before), having as structure :
id, tenant_id, office_id,... where id is the primary key of the "tenant_offices" table and tenant_id and office_id are foreign keys.
tenant_id which refers to your tenants table and office_id which refers to your offices table.
Here, the tenant can therefore rent several offices.
Hoping to have enlightened you, or helped !

A: You can use text, that works for me with ids separated by commas like this
4,3,67,2

Anyway the proper approach would be another table and name it tenant_offices
tenant_offices
  columns >
    tenant_id
    office_id (well ofcourse you should have atleast an office table)

A: I assume that the relationship is one-to-many tenant to office (that is, office can be rented only by one tenant)
Then you have to create table offices with a foreign key that points to the tenant:
CREATE TABLE offices (
id bigserial not null primary key,
tenant_id bigserial foreign key references tenants(id))
additional columns if needed

note that in this version you will not retain history of rents (you will have to run update on offices to change tenant_id)
EDIT: In case of a many-to-many relationship (that will also allow us to retain history of rents) we need to create a relationship table:
CREATE TABLE TenantsOffices (
id bigserial not null primary key
tenant_id bigserial foreign key references tenants(id),
office_id bigserial foreign key references offices(id),
start_date datetime,
end_date datetime)

Useful information: https://www.sqlshack.com/learn-sql-types-of-relations/


text:
Q: How can I run pytest in another folders in Python In folder [Root]/src/app, I have a file services_factory.py, for example:
class Describing:
  def __init__(self):
    pass

  def get_description(self):
    pass

class APIService(Describing):
  def __init__(self):
    pass

  def get_description(self):
    return 'Here provide services for APIs'

class DatabaseService(Describing):
  def __init__(self):
    pass

  def get_description(self):
    return 'Here provide services for Database'

class Injector:
  def __init__(self):
    pass

  def get_service(self, type='API'):
    services = {
      "API": APIService,
      "DB": DatabaseService
    }
    return services[type]()

At the end of file services_factory.py, I add an unittest, ex:
def test_services_injector():
  injector = Injector()
  api_service = injector.get_service('API')
  db_service = injector.get_service('DB')
  assert api_service.get_description() == 'Here provide services for APIs'
  assert db_service.get_description() == 'Here provide services for Database'

Then, cmd: $ pytest src/app/services_injector.py, it worked nicely.

But when I create a file test_services_factory.py in [Root]/tests/app, for example:
import unittest
from unittest.mock import patch

def test_services_injector():
  assert 'a' == 'a'

I can't import the classes in my services_factory.py.
So, how can I quickly fix this problem?


text:
Q: Use recurrence relation Fermat numbers to show that the set of prime numbers is infinite I'm working on some proofs on a recurrence relation with Fermat numbers.
a). Prove with Fermat numbers $f_n = 2^{2^n} + 1$ that:
$$ f_0 \cdot f_1 \cdot f_2 \cdot f_3 \cdots f_{n-1} = f_n - 2$$
b). Prove that $f_n$ is relatively prime with $f_0, f_1, f_2, ... , f_{n-1}$. In other words:
for any $n$, $f_n$ is not divisible with any factors of its previous Fermat number.
In my attempt on (a) I used the sum of the powers of $2$ :
$$2^0 + 2^1 + 2^2 + 2^3 + ... + 2^n = 2^{n+1} - 1$$
but I didn't come very far.
Some help would be very much appreciated.

A: a) If $f_0\times f_1\times\cdots\times f_{n-1}=f_n-2$, then\begin{align}f_0\times f_1\times\cdots\times f_{n-1}\times f_n&={f_n}^2-2f_n\\&=\left(2^{2^n}+1\right)^2-2\times\left(2^{2^n}+1\right)\\&=2^{2\times2^n}+2\times2^{2^n}+1-2\times2^{2^n}-2\\&=2^{2^{n+1}}+1-2\\&=f_{n+1}-2.\end{align}
b) If $p$ is a prime number which divides $f_n$ and $f_m$, with $n<m$, then, $p$ divides both $f_0\times f_1\times\cdots\times f_m$ and $f_m$. Therefore, $p$ divides their difference, which is $2$. Since $p$ is prime, $p=2$, but this is impossible, because the Fermat primes are odd. This proves that distinct Fermat numbers are relatively prime.
For each $n\in\mathbb N$, let $p_n$ be the smallest prime factor of $f_n$. Then $(p_n)_{n\in\mathbb N}$ is an injective sequence of prime numbers. Therefore, there are infinitely many prime numbers.


text:
Q: open() function returns directory error for no reason I was making a project that has you type what's on the screen, and I was trying to get it to generate random words from a file. but I got an error saying FileNotFoundError: [Errno 2] No such file or directory: 'words.txt'. I double-checked that the file was in the same directory and it was named right. Then I went back to my other program using this file, and it didn't work either (Even though it worked perfectly before). I tried using a shorter file to see if that was the problem, but it still gave me the same error.
Here is my (incomplete) code:
from Tkinter import Tk, Entry
import random

words = open('words.txt')
tab = Tk()

words = words.readlines()

totype = words[random.randint(1, len(words))]

print(totype)

How can I fix this?

A: Check that the directory you're running python from is the correct directory.
On python 3.4+, you can use the pathlib module to open files in the same directory as the script easily:
from pathlib import Path

p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
    words = f.read()

You can check this with:
import os
cwd = os.getcwd()

And use the relative directory from that.
Alternatively, use the full directory.
You can get the full path of the script using:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))

Then you can use dir_path + file_name to get your full file path.

A: You have to give directory path specifying where the file is located if the file is located in same directory as your script file you can do
from Tkinter import Tk, Entry
import random

words = open('./words.txt')
tab = Tk()

words = words.readlines()

totype = words[random.randint(1, len(words))]

print(totype)

if it is located in some other folder then you can do
file = open(r'C:\Users\Directory\sample.txt') #example

words = open(file)

tab = Tk()

words = words.readlines()

totype = words[random.randint(1, len(words))]

print(totype)


text:
Q: All rows are not getting imported to datatable using oledbconnection I am stucked up at this point. I searched alot on gooogle but didnot find anything.
My problem is:
I have an Excel file which i want to export to datatable and from datatable i want to save it to oracle DB.
Excel file contains multiple columns and each column consists of large data(approx 20000characters/numbers).
using oledbconnection,excel columns with such large data are not copied to datatble.(Small data columns gets copied).
Can anyone suggest workaround to my problem???
Thanks in advance.

A: *

*Check the dataypes and their length i.e nvarchar(3000)

*If that doesnt work, test with a small set of data maybe 5 rows, you should be able to see a trend there.

*Also check the data type of your application, sometimes for large number you may use long, or if they are large strings maybe use a stringbuilder to pass the data instead of just a string....


text:
Q: Bundler - bundle package takes forever for a specific gem Where I work, we develop several Ruby Gems for internal use. They all depend on various combinations of both our own internal gems as well as third-party gems from RubyGems.org.
We automatically build our gems when we make a change using a build server (ElectricCommander) that packages them as gems and stores them in an internal repository. As part of that process, we run bundle package --all. This has been working flawlessly for all our gems until last week.
Last week, one of our gems started taking over 1 hour to run the bundle package command. It runs successfully, but it just takes over an hour to finish, which is a bit absurd.
On our other gem builds, the bundle package command runs just fine in a more respectable minute or so. There's not a huge difference in the amount of dependencies each gem contains. They all build in the same environment.
We're pulling our hair out over this one. A Google search didn't reveal anyone with the same problem. Has anyone experienced this issue, or does anyone know what might be causing it?

A: I've had a similar issue before when the gem in question was dependent on another gem that both had many versions and had many other dependencies. In our gem we had the other gem (it was rails) as a dependency without depending on a specific version.
So we had:
s.add_runtime_dependency "rails"

When we added a version we saw a significant increase in bundling speed:
s.add_runtime_dependency "rails", "~>3.2"

With an absolutely rigid version it was even quicker:
s.add_runtime_dependency "rails", "3.2.14"

The reason for the slowness, I believe, is that it looks at all of the dependencies for all of the versions of the gem that match the dependency in your gemspec. As you can imagine with a gem that has been around for a while and which has many other dependencies itself this can get to be quite a significant amount of looking around.

A: Bundler tries very hard to find a set of gems that meets all of your bundle's requirements, but in some cases, this search can take a long time. Depending on the order of gems in your Gemfile, the constraints you provide, and the dependencies encountered in other gems, Bundler might need to backtrack on the resolution process and re-resolve some gems. In worst-case scenarios, this can take exponential time.
Pat Shaughnessy explains the process well in How does Bundler bundle?. As he mentions, running Bundler with DEBUG_RESOLVER=1 in the environment can help show you what's happening.
You can work around these problems by changing the order of the gems in your Gemfile or by using more specific version constraints as Shadwell suggests.


text:
Q: Any listener or event in android that give me update if contact add or edit in android os book? I am building one android app and now am stop at one place,
I am not sure if me add new contact or edit contact in android OS book it give me any type of listener or event so according this may do further procedure.
Please, someone know about this please answer.

A: You have to create Broadcast Receiver for achieve contact related functionality.

*

*ContactsContract

*this
This will helps you.

A: You should implement ContentObserver in order to manage contact related changes.
For more info check out the following link.


text:
Q: Using Simple Exponential Smoothing to Forecast Time Series Data I'm trying to forecast timeseries sales data with simple exponential smoothing in python but when i try using the predict function on the fit it just repeats the same value for each specified interval. Any suggestions on how to get a proper forecast?
Timeseries seasonal data:

Fit Code
fit4 = SimpleExpSmoothing(Holt_Data, initialization_method="heuristic").fit(
smoothing_level=0.8, optimized=False
)

fcast4 = fit4.forecast(3).rename(r"$\alpha=0.8$")

Fitted Plot:

fit4.predict(start='2022-01-01',end='2023-01-01')

Predicted Value Graph plot:


text:
Q: How callIndex works in react's useState under the hood? I'm currently learning how React works under the hood and built a custom useState from scratch following the tutorials on Youtube.
But I'm having trouble understanding how callIndex is incremented and why do I need to set currentIndex variables which basically take the callIndex value.
The code works like this -

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";

let callIndex = -1;
let stateValues = [];
const useState = (initValue) => {
  callIndex++;
  console.log("callIndex", callIndex);
  const currentIdx = Number(callIndex);
  if (stateValues[currentIdx] === undefined) {
    stateValues[currentIdx] = initValue;
  }
  const setState = (newValue) => {
    console.log("currentIdx in setState", currentIdx);
    stateValues[callIndex] = newValue;
    render();
  };

  return [stateValues[currentIdx], setState];
};

const App = () => {
  const [countA, setCountA] = useState(1);
  const [countB, setCountB] = useState(-1);
  const [countC, setCountC] = useState(0);
  return (

Count A: {countA}

        <button onClick={() => setCountA(countA - 1)}>Subtract</button>
        <button onClick={() => setCountA(countA + 1)}>Add</button>

Count B: {countB}

        <button onClick={() => setCountB(countB - 1)}>Subtract</button>
        <button onClick={() => setCountB(countB + 1)}>Add</button>

Count C: {countC}

        <button onClick={() => setCountC(countC - 1)}>Subtract</button>
        <button onClick={() => setCountC(countC + 1)}>Add</button>

  );
};
function render() {
  // callIndex = -1;
  ReactDOM.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
    document.getElementById("root")
  );
}
render();

Every time the useState function is called, the callIndex variables would be incremented by 1.
In this code, I called useState 3 times. So, the callIndex value would be 3.
The problem starts here -  when I called the setState function, it'll first assign the newValue to the stateValues but in which index will it be changed.
Are there any articles or tutorials explaining how this happening?

A: The biggest issue is, you need to be able to distinguish between useState calls for different components, and different renders of the same component. You need this
<Comp1 />

const Comp1 = () => {
  const [countA, setCountA] = useState(1);
  const [countB, setCountB] = useState(-1);

to perform different logic than
<Comp1 />
<Comp2 />

const Comp1 = () => {
  const [countA, setCountA] = useState(1);

const Comp2 = () => {
  const [countB, setCountB] = useState(-1);

But the information available to you exposed by React with functional components is very limited, and won't allow you to do this easily. There is much more information used by (and available to) React's internals, which can distinguish things like the start of a component call.
If you want to "replicate" useState, I think the easiest way to do so would be to go outside of React completely, so that when "updating" the state, you can just call a function that re-populates a section of the DOM. (In React, you don't want to call ReactDOM.render on an app many times, and especially not on every render - that results in it being rebuilt from the ground up every time.)
Also, a small issue - when mounting, you should check if the state property exists on the array before assigning, not just if the value on that property is undefined, otherwise you'll lose the desired logic when nothing is passed as an initial value. This
  if (stateValues[currentIdx] === undefined) {
    stateValues[currentIdx] = initValue;
  }

should be
  if (!([currentIdx in stateValues)) {
    stateValues[currentIdx] = initValue;
  }

In your state setter, you also need to change
stateValues[callIndex] = newValue;

to
stateValues[currentIdx] = newValue;

For a vanilla JS demo of your tweaked code:

let callIndex = -1;
let stateValues = [];
const useState = (initValue) => {
  callIndex++;
  const currentIdx = Number(callIndex);
  if (!(currentIdx in stateValues)) {
    stateValues[currentIdx] = initValue;
  }
  const setState = (newValue) => {
    stateValues[currentIdx] = newValue;
    renderApp();
  };

  return [stateValues[currentIdx], setState];
};

const root = document.querySelector('.root');
const renderApp = () => {
  callIndex = -1;
  root.textContent = '';
  root.appendChild(App());
};
const App = () => {
  const [countA, setCountA] = useState(1);
  const [countB, setCountB] = useState(-1);
  const [countC, setCountC] = useState(0);
  const div = document.createElement('div');
  div.innerHTML = `

Count A: ${countA}

        <button>Subtract</button>
        <button>Add</button>

Count B: ${countB}

        <button>Subtract</button>
        <button>Add</button>

Count C: ${countC}

        <button>Subtract</button>
        <button>Add</button>

`;
   // this could be made less repetitive, but this is just for demo purposes
   const buttons = div.querySelectorAll('button');
   buttons[0].onclick = () => setCountA(countA - 1);
   buttons[1].onclick = () => setCountA(countA + 1);
   buttons[2].onclick = () => setCountB(countB - 1);
   buttons[3].onclick = () => setCountB(countB + 1);
   buttons[4].onclick = () => setCountC(countC - 1);
   buttons[5].onclick = () => setCountC(countC + 1);
   return div;
};
renderApp();


text:
Q: cgo C struct field access from Go: underscore or no underscore? I'm running into a disconnect between the online documentation and the behavior I see in my programs accessing C structs within GO code. go version says I am using:
go version go1.4.2 linux/amd64

According to the GO CGO documentation:

Within the Go file, C's struct field names that are keywords in Go can be
  accessed by prefixing them with an underscore: if x points at a C struct with
  a field named "type", x._type accesses the field. C struct fields that cannot
  be expressed in Go, such as bit fields or misaligned data, are omitted in the
  Go struct, replaced by appropriate padding to reach the next field or the end
  of the struct.

I had troubles with this, so made a quick sample program to test it out:
package main
// struct rec
// {
//      int    i;
//      double d;
//      char*  s;
// };
import "C"
import "fmt"
func main() {
        s := "hello world"
        r := C.struct_rec{}
        r.i = 9
        r.d = 9.876
        r.s = C.CString(s)
        fmt.Printf("\n\tr.i: %d\n\tr.d: %f\n\tr.s: %s\n",
                r.i,
                r.d,
                C.GoString(r.s))
}

When I use underscores as the docs indicate (eg, substitute r._i for r.i above) I get the following compile error:

r._i undefined (type C.struct_rec has no field or method _i)

When I don't use underscores it works fine. I tried this with both pointers and non-pointers. The only other idea I can think of is that maybe it's because I allocated the instances in GO rather than C, is that the case??
Thanks for any help!

A: The answer is in the very quote you have in your question:

Within the Go file, C's struct field names that are keywords in Go can be accessed by prefixing them with an underscore(…)

i, d, and s are not keywords in Go.


text:
Q: How to remove duplicate phrases in Python? Suppose I have a string such as
'I hate *some* kinds of duplicate. This string has a duplicate phrase, duplicate phrase.'

I want to remove the second occurrence of duplicate phrase without removing other occurrences of its constituent parts, such as the other use of duplicate.
Moreover, I need to remove all potential duplicate phrases, not just the duplicates of some specific phrase that I know in advance.
I have found several posts on similar problems, but none that have helped me solve my particular issue:

*

*Removing duplicate words

*Removing duplicate lines

*Removing repeated words within a phrase
I had hoped to adapt the approach from the last link there (re.sub(r'\b(.+)(\s+\1\b)+', r'\1', s)) for my purposes, but could not figure out how to do so.
How do I remove all arbitrary duplicate phrases of two or more words from a string in Python?

A: Thanks everyone for your attempts and comments. I have finally found a solution:
s = 'I hate *some* kinds of duplicate. This string has a duplicate phrase, duplicate phrase.'
re.sub(r'((\b\w+\b.{1,2}\w+\b)+).+\1', r'\1', s, flags = re.I)
# 'I hate *some* kinds of duplicate. This string has a duplicate phrase.'

Explanation
The regular expression
r'((\b\w+\b.{1,2}\w+\b)+).+\1'

finds every occurrence of multiple runs of alphanumeric characters separated by one or two [any character] (to cover the case where words are separated not just by a space, but perhaps a period or comma and a space), and then repeated following some run of [any character] of indeterminate length. Then
re.sub(r'((\b\w+\b.{1,2}\w+\b)+).+\1', r'\1', s, flags = re.I)

replaces such occurrences with the first multiple run of alphanumeric characters separated by one or two [any character], being sure to ignore case (since the duplicate phrase could sometimes occur at the beginning of a sentence).


text:
Q: Force the auto import to use ".js" extension in TypeScript Visual Studio Code Editor The auto-import completion feature sometimes adds the .js extension, but not all the time. However, without the extension in the TypeScript source, the tsc compiler won't add the extension to the emitted JavaScript file which can create run-time issues such as module not found error.
For details of the problem please refer to: Appending .js extension on relative import statements during Typescript compilation (ES6 modules).
The question is: is there any way to configure the automatic import completion feature to force to append the.js extension in the import statements? Or are there any add-ons or VS Code extensions that can achieve this?
This minor thing has been extremely annoying at times!

A: I found that now the VSCode has it in the Preferences or Settings Ctrl + , under the entry:
"typescript.preferences.importModuleSpecifierEnding": "js",.

A: Sublime Text version
Install package "LSP-typescript". Click Preferences -> Package Settings -> LSP -> Servers -> LSP-typescript. Add following json
{
  "initializationOptions": {
    "preferences": {
      "importModuleSpecifierEnding": "js"
    }
  }
}

Or use this in tsconfig
{
  "compilerOptions": {
    "moduleResolution": "nodenext", // <- Necessary to get imports with .js
  },
  "exclude": ["node_modules"]
}


text:
Q: How to set the background color of the selected tab in PagerTiltleStrip I trying to change the color of the selected tab in PagerTitleStrip, I was able to change the color of the entire strip. But that is not what I wanted.
How to achieve this? Can any one help?

A: You can do it with PagerTitleStrip too.

*

*Implement ViewPager.OnPageChangeListener in your main activity

*Put setOnPageChangeListener for your ViewPager
MyViewPager.setOnPageChangeListener(this);

*Then overrride methods
onPageScrolled,
onPageSelected,
onPageScrollStateChanged
we just need to put our code in onPageSelected(int position) method
like if you have 5 pages, however beforthat you need
- Declare pagerTitleStrip in your main code.
    PagerTitleStrip pagerTitleStrip;

*

*And in onCreateMethod
PagerTitleStrip = (PagerTitleStrip) findViewById(R.id.title);

*R.id.title is the id  of pagerTitleStrip in main_layout
if(position==0){
    pagerTitleStrip.setBackgroundColor(0xFF3D0201);
}
if(position==1){
    pagerTitleStrip.setBackgroundColor(0xFF013E10);
}
if(position==2){
    pagerTitleStrip.setBackgroundColor(0xFF242F52);
}
if(position==3){
    pagerTitleStrip.setBackgroundColor(0xFF60611D);
}
if(position==4){
    pagerTitleStrip.setBackgroundColor(0xFF5E2E52);
}

A: Finally figured it out! Considered PagerTabStrip instead of PagerTitleStrip.
tabStrip = (MyPagerTabStrip) findViewById(R.id.pager_title_strip);
            tabStrip.setBackgroundColor(Color.rgb(240, 240, 240));
            tabStrip.getChildAt(1).setPadding(30, 15, 30, 15);
            tabStrip.getChildAt(1).setBackgroundResource(R.drawable.background_orange);
            tabStrip.setDrawFullUnderline(false);
            tabStrip.setTabIndicatorColor(Color.rgb(240,240,240));

Took one day to research on it!

A: If you still want to use PagerTitleStrip and not PagerTabStrip all you have to do is below.
tabStrip = (PagerTitleStrip) findViewById(R.id.pager_title_strip);
            tabStrip.setBackgroundColor(Color.rgb(240, 240, 240));
            tabStrip.getChildAt(1).setPadding(30, 15, 30, 15);
            tabStrip.getChildAt(1).setBackgroundResource(R.drawable.background_orange);

This will allow you to set the background color of the middle tab and will not show a tab indicator, like PagerTabStrip.


text:
Q: Extract number with special characters from a file using sed and grep command I am trying to extract the number surrounded by the square brackets after matching with the word that is placed after the number. for ex.
The file contains
xxxx [098] yyyy zzzz

I need to search for the yyyy and if it is matches in the line, i have to extract the 098 itself.
I am trying with
sed 's/.*\[\([^]]*\)\].*/\1/g' str.txt

for extracting the number without pattern matching.
and am using
sed -nr 's/.*( |^)([0-9]+) yyyy.*/\2/p' str.txt

for pattern match and get the number that is placed before that match. But i couldn't merge this two commands. I am confusing with the error

sed: -e expression #1, char 26: unknown option to `s'

I think this held because of using the / as the delimiter more.

A: You always need to use the conditional print logic for such cases where you you decide to print on a condition. With the -n and p predicates, you can control the command to print the matched group only if the match was successful.
So combining your attempts you need something like
sed -n 's/.*\[\([^]]*\)\][[:space:]]yyyy.*/\1/p'

which won't print for any other case other than yyyy after the [..] string.
But parsing a space de-limited file is quite easy if you decide to use awk in which your result could simply be written as
awk '$3 == "yyyy" { gsub(/[][]/,"",$2); print $2 }'

A: As you have tagged grep, another option if you can use gnu grep is to make use of the -P option Perl-compatible regular expression and use lookarounds:
grep -Po "(?<=\[)\d+(?=\] yyyy)" str.txt

That will give you 098

A: if data in 'd' tried on gnu sed
sed -E 's/.*xxxx\s*\[(098)\]\s*yyyy.*/\1/' d


text:
Q: Why does cudaMemGetInfo report a change in the total amount of device memory? When I run the following piece of code the reported total amount of memory on my GPU changes (according to cudaMemGetInfo anyway). This behavior is not mentioned in the documentation for cudaMemGetInfo, which says that total should contain the total amount of memory on my device that can be allocated (which cannot change without putting a different GPU in my system right?). Can somebody explain why this is happening? It does not seem to happen when I don't call cudaMallocManaged.
#include <iostream>

void printStats()
{
    size_t free, total;
    cudaMemGetInfo(&free, &total);
    std::cout << "free:  " << free << "\ntotal: " << total << std::endl;
}

int main(void)
{
    // Before memory allocation
    printStats();

    int N = 1;
    float *x, *y;
    cudaMallocManaged(&x, N*sizeof(float));
    cudaMallocManaged(&y, N*sizeof(float));

    // After memory allocation.
    printStats();

    cudaFree(x);
    cudaFree(y);

    // After freeing the memory.
    printStats();

    return 0;
}

result:
free:  94383273356630
total: 20
free:  5661994326
total: 4
free:  140729276827856
total: 94383273355680

A: It turns out that when your CUDA driver version is insufficient for CUDA runtime version this sort of undefined behavior happens. For anyone else running into this problem I recommend checking the output of cudaGetLastError() that's how I discovered what the problem was.
I fixed it by downgrading my CUDA version to 10.1 since that was the newest version my driver supports. (You can check your CUDA and driver version using the nvidia-smi tool).


text:
Q: search by county in here api without latitude and longitude i want to use here api for location search in specific country
but problem is that i have to pass the county latitude and longitude to the search api
is there any way so i can send only country code with latitude and longitude
to here search api
"addressFilter" parameter already search on city or state in country
but it work along with latitude and longitude
$url="https://places.cit.api.here.com/places/v1/discover/search?app_id=&app_code=&at=37.09024,-95.712891&q=pizza&addressFilter=Hawally

A: You can try to send country code in q parameter itself with latitude and longitude as below :
https://places.cit.api.here.com/places/v1/discover/search?app_id=XXXX&app_code=YYYY&at=29.330964,47.519325&q=KW

Hope this helps!


text:
Q: Draw Vectors to a Bitmap in EaselJS I'm working on an EaselJS program that continually draws thousands of vectors. Needless to say, after a short amount of time, performance drops. To solve this in Flash, I would have created a Bitmap behind the vectors and periodically draw the vectors to that Bitmap and remove them from the display list.
I'm having trouble doing this in EaselJS, even though it seems like all the pieces are in place. How can I create an empty Bitmap() and draw the contents of my Container() to it?

A: I think you can just put everything in a container and cache it.
var vectorContainer=new Container;
for (var i = 0;i<numVectors;i++){
  var vector=new Shape();
  //draw whatever vector you want to vector.graphics
  vectorContainer.addChild(vector);
}
vectorContainer.cache(someX,someY,someW,someH);

However get the newest untagged build as the current release has a bug and doesn't cache container properly.

A: I've also been adding the 'snapToPixel = true' to vectors because I've read it is supposed to help in some browsers. So, in your example code above, I would add the following line right before the last line where you do your caching.
vectorContainer.snapToPixel = true;

Check out this demo of cache and snap to pixel settings to see a live example.
In my particular browser set up, the snap to pixel does not actually change the performance, but in my reading of the docs it seems like it should.


text:
Q: I am trying to plot every mesh point of a model elephant so that the surface of the elephant wraps around the interior surface of the mirror I'm trying to find a way to turn the elephant inside out in a way. Imagine cutting an elephant in half from tail to trunk, stopping right before the trunk. You could flatten the elephant out and wrap it with the elephant's surface now being on the inside. I wonder if you can do this by reflecting the mesh points of the elephant circularly using shelled ellipse. Any suggestions and help are appreciated.
To clarify this is like reflecting each mesh point across the elliptical mirror but in an elliptical manner and not across a simple line or plane. So all the mesh points inside the mirror would now be outside.
Here is the link to all the files.
https://drive.google.com/drive/folders/1qB0PiJ6CA98JtgUw9DtszJVqLW_54saU?usp=sharing
CylindricalShell =
 ImplicitRegion[
  700 <= 128.026 x^2 + 93.42 z^2 <= 950 && -3 <= y <= 3, {x, y, z}]
mirror = Translate[
  Region[CylindricalShell, Axes -> True, FaceGrids -> All], {-0.4,
   0, -0.1}]

elephant =
  Import["C:\\Users\\Admin\\Downloads\\elefante.obj",
   "GraphicsComplex"];
grid = Graphics3D[elephant, Axes -> True, FaceGrids -> All]
elephantmeshpoints = MeshRegion[elephant]
(*Graphics3D[GeometricTransformation[elephantmeshpoints,]*)
vector = Graphics3D[{Arrow[{{0, 0, 0}, {1.5, 0, 0}}], Axes -> True,
    FaceGrids -> All}];
(*Working On the Part where: the elephant is turned "inside out" and \
the surface of the elephant is curved around the interior surface of \
the mirror*)

elephantinmirror =  Show[mirror, grid]
SetSystemOptions[
  "LibraryLinkOptions" -> "TestFloatingPointExceptions" -> False];


text:
Q: IIS 7/ASP.NET 4/MVC 3 Preview 1: random "Could not load file or assembly" errors I'm using the new Razor ViewEngine with ASP.NET 4/ASP.NET MVC 3.
In both Cassini on my local machine (Win7 x64/VS 2010), as well as IIS7 (Windows Web Server 2008), I'm randomly getting "Could not load file or assembly" errors.
With Cassini, rebuilding the solution generally fixes the problem.
In IIS7, recycling the application pool generally fixes the problem.
It is always the same assembly - a "Core" project of mine that is referenced by the ASP.NET MVC project. The solution hierarchy looks like this:

*

*"Core" project (this is the one identified in the "Could not load file or assembly" error)

*"Data" project (LINQ-to-SQL models)

*

*Core

*ASP.NET MVC Site

*

*Core

*Data

All these references are project references. The stack trace of the error starts in the "Data" project, which references the "Core" project. Any ideas?

A: Please refer the following blog posts;
http://www.tugberkugurlu.com/archive/deployment-of-asp-net-mvc-3-rc-2-application-on-a-shared-hosting-environment-without-begging-the-hosting-company
It might help...


text:
Q: Normalizing a table with different structures I have a normalized table (table a) and a non-normalized table (table b), like this:

I want to insert a new row into the normalized table for each parent in the non-normalized table. So if there is a record in table B with two parents for a studentID, I want to insert two records into table A with each different parent name from table B.
I've been struggling for with this for hours, any help would be appreciated on how to go about doing this.

A: Assuming parentID is an auto incremental column, you could do this:
INSERT INTO NormalizedFamily(studentID, parentName)
SELECT studentID, parentName1
FROM FlatFamily
UNION
SELECT studentID, parentName2
FROM FlatFamily
WHERE parentName2 IS NOT NULL
UNION
SELECT studentID, parentName3
FROM FlatFamily
WHERE parentName3 IS NOT NULL
UNION
SELECT studentID, parentName4
FROM FlatFamily
WHERE parentName4 IS NOT NULL

In any case, I don't really get why the column parentId is the key of your normalized table. As it is, the same parent can't have multiple students related to him?, shouldn't the key be a combination of parentID and studentID?.

A: This is what unpivot is meant for.  It's kind of weird and hard-ish to understand for beginners though.  Here's a totally hacky way to do the same thing that should be easy enough to understand:
 insert into NormalizedFamily (parentId, studentId, parentName)
 select p.parentName,
        p.parentId,
        f.studentId
   from Parent p
            inner join
        (select studentId, parentName1 as parentName from FlatFamily
         union all
         select studentId, parentName2 as parentName from FlatFamily
         union all
         select studentId, parentName3 as parentName from FlatFamily
         union all
         select studentId, parentName4 as parentName from FlatFamily
         union all
         select studentId, parentName5 as parentName from FlatFamily
        ) t                on t.parentName = p.parentName

Here is how unpivot would work.  It basically turns columns into rows.  So try out this select statement:
 SELECT studentId, parentColumnName, parentName
   FROM (SELECT studentId, parentName1, parentName2, parentName3, parentName4, parentName5
           FROM FlatFamily) f
UNPIVOT (parentName FOR parentColumnName IN (parentName1, parentName2, parentName3, parentName4, parentName5)) AS t


text:
Q: How do I get the normal photo? I'm using this library https://github.com/kirill3333/react-avatar
There is a method onBeforeFileLoad() in which the size of the image is checked. Later the selected photo will be saved in preview. My question is, how do I get the normal photo that the user has selected - that is, the photo that he has not yet cropped?
import React, { useState } from "react";
import ReactDOM from "react-dom";
import Avatar from "react-avatar-edit";

const App = () => {
  const [preview, setPreview] = useState(null);
  const [src, setSrc] = useState("./example/einshtein.jpg");

  const onClose = () => {
    setPreview(null);
  };

  const onCrop = (preview) => {
    setPreview(preview);
  };

  const onBeforeFileLoad = (elem) => {
    if (elem.target.files[0].size > 71680) {
      alert("File is too big!");
      elem.target.value = "";
    }
    else {
       // ToDo
       // get the normale photo
    }
  };
  return (

      <Avatar
        width={390}
        height={295}
        onCrop={onCrop}
        onClose={onClose}
        onBeforeFileLoad={onBeforeFileLoad}
        src={src}
      />

  );
};

ReactDOM.render(<App />, document.getElementById("root"));

A: Its in your "src" state.
According to documentation of the package you are using; onImageLoad(image) will return you the loaded image.
You can also use your onBeforeFileLoad function. And set it to a  element for example.
  const onBeforeFileLoad = (elem) => {
    ....
    else {
       setOriginal(elem.target.files[0])
    }