text:
Q: Single Click and Double Click in EditText using the click listener My requirement is, on single click on Edit Text, user can enter data, on double click go to an activity where all data will be present.
I used the logic for press again to exit, I am unable to achieve it.
        ETBarCode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            doublePress=doubleTap();
            if(doublePress) {
                ETBarCode.requestFocus();
                InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(ETBarCode.getWindowToken(), 0);
            }
            else
            {
                Toast.makeText(MoveActivity.this, "Enter Data", Toast.LENGTH_SHORT).show();
                ETBarCode.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(ETBarCode, 0);

            }
        }
    });
}

private boolean doubleTap()
{
    if (doubleBackToExitPressedOnce) {
        Toast.makeText(this, "Scanning", Toast.LENGTH_SHORT).show();
        return doubleBackToExitPressedOnce;
    }
    this.doubleBackToExitPressedOnce = true;
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);
    return doubleBackToExitPressedOnce;
}

Is there any way to sort it out?

A: Use GestureDetector to detect:
final GestureDetector gestureDetector = new GestureDetector(your_context,new GestureDetector.SimpleOnGestureListener() {
    public boolean onDoubleTap(MotionEvent e) {
        // start activity
        return true;
    }
});

EditText et = (EditText) findViewById(R.id.your_id);
et.setOnTouchListener(new View.OnClickListener() {
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }
});

A: You can manage with counter variable:
int count = 0;

ETBarCode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            count++;
            doublePress=doubleTap();
            if(count==1) {
              ShowData();
              count=0;

            }
            else if(count==2){
               StartNewActivity();
              count=0;
            }

        }
    });

}

Hope this will help you.

A: This should solve your problem. I tried changing as little as possible from your code, however some things are not clear (where exactly are you redirecting to the new activity?). Also, I would not recommend this double tap to proceed thing in terms of user experience, it is very unconventional. I would rather have it as clickable TextView (with design clearly suggesting the clickability) for the "view" action, and an image button (the good old android pencil) next to it for the "edit" action.
ETBarCode.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        if(isDoubleClick()) {
            ETBarCode.requestFocus();
            InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(ETBarCode.getWindowToken(), 0);
        }
        else {
            Toast.makeText(MoveActivity.this, "Enter Data", Toast.LENGTH_SHORT).show();
            ETBarCode.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(ETBarCode, 0);
        }
    }
});

private boolean isDoubleClick() {
    if (!userHasClickedOnce) {
        Toast.makeText(this, "Scanning", Toast.LENGTH_SHORT).show();
        return false;
    }

    new Handler().postDelayed(new Runnable() {
    @Override
        public void run() {
            userHasClickedOnce = false;
        }
    }, 2000);

    return true;
}


text:
Q: Azure B2C AD Redirect to Angular App I am trying to run this Angular 4 example that uses Azure B2C Active Directory and adal-angular 4.
To run the app, in Azure I created a tenant, registered a the app in AD B2C and added a reply Url of https://localhost:4200.  I then added the app id and tenant to my Angular App.
When I run the app, it correctly redirects to https://login.microsoftonline.com... on load for login. Logging in correctly redirects to https://localhost:4200.
When I log out, there is a problem. The app is redirected to this static logout page which doesn't redirect back to my app.
I tried registering an app in Azure Active Directory (not B2C), moving its config data into my Angular App, and when I run it and a log out it redirects temporarily to this "logging you out" page which redirects back to the app.
The the redirect urls after logout are identical other than the tenant name, only the B2C just dies. This happens in both Chrome and Edge.
I expect that this is not just a difference in functionality between B2C and regular AD. I checked my configurations, but maybe this is something in the Azure portal I missed?

A: The logout request should include both the "p" and "post_logout_redirect_uri" parameters such as:
GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/logout?p=b2c_1_sign_up_sign_in&post_logout_redirect_uri=https%3A%2F%2Flocalhost%3A4200%2F

If the "post_logout_redirect_uri" parameter isn't specified, then Azure AD B2C displays a generic message.

A: You should use MSAL.js w/ Azure AD B2C.

ADAL ... is designed to only work against Azure AD "classic" (e.g. - NOT B2C)

Reference: MSAL or ADAL library for use with Azure AD B2C and Xamarin

See this Angular 4 example that uses MSAL.js.

redpajama_set_name: RedPajamaStackExchange


text:
Q: determine bold font with Python xlrd I know I can create bold font in excel (.xlsx files) using Python xlsxwriter package.
I'm reading and processing excel files with Python xlrd package. Is that possible for me to determine if a cell is using bold font or not?
I did some search and some posts say font attributes is not yet implemented in Python xlrd package.


text:
Q: Do browsers always treat strings and numbers in Javascript as immutable? In Javscript, do browser runtime interpreters always treat strings and numbers as immutable?
Surely, in cases where it provably is harmless, they would optimize and treat them as mutable. And if not, why not?
For instance, consider the humble for loop.
for (let i = 0; i < 1000000000000; i++) {
 console.log(i)
}

Since the i variable is scoped to the loop, and no code in the loop ever needs the "old values" of the i variable, it would make sense for the browser to simply increment the number that the symbol i points to each iteration. Otherwise, a stream of new bytes of memory will be taken up by the new values of i, for no conceivable reason ("someone might need those old values of i!"). We will have an unnecessary race between the for loop (creating new values of i in memory) and the garbage collector (killing off all the old values of i), which the loop will generally win, and we will have a stack overflow.
Oh, that's what happens, isn't it. If so, why are browsers dumb this way when they are so intelligent in optimizing the code in other ways?
There is a similar situation for strings. Consider the following.
{
   let completeWorks = "This string dictates the complete works of William Shakespeare. To be or not to be that is the question whether it is nobler in the mind..."
   completeWorks += "The End."  // <-- what happens here?
}

The string completeWorks is block-scoped and provably only lives in this block. So surely when the browser encounters the instruction completeWorks += "The End" it will just mutate completeWorks. If not, why not? Probably there is a good reason they don't do this, and I would like to learn it.

A: (V8 developer here -- as such I know very little about other browsers/engines.)
There's no easy answer to this; implementations are complicated.
Strings, in V8, are always immutable (after creation). One reason is that with objects being allocated on the heap, there's typically no free space after an object, so we can't just append characters to an existing string. Another reason is that keeping track of which strings can safely be mutated would add an extraordinary amount of complexity (aside from a few easier-to-detect niche cases, but if only those are supported, then the mechanism would provide much less value).
V8 does have a few nifty tricks for string manipulations up its sleeve: when you take a substring of a larger string, then no characters are copied; the new string is simply a reference that says "I'm a slice of length X of that other string over there, starting at index Y". Similarly, when concatenating two strings like your completeWorks example, the new string is a reference that says "I'm the concatenation of those two other strings". (For completeness, I'll mention that there are minimum character counts below which these tricks are not applied because simply copying the characters is at least as efficient.)
Numbers are both more performance sensitive and easier to deal with than strings. In general, heap-allocated numbers are always immutable; but that's not the end of the story. V8 heavily uses a special representation for "Smis" ("small integers"), because many numbers in JavaScript programs fall into that bucket. Smis are not heap objects; creating a new one is as cheap as modifying one, and in fact indistinguishable (like an int in C++). For numbers out of Smi range, the optimizing compiler also performs "escape analysis" and can "unbox" non-escaping numbers, which means keeping them in a CPU register (as a plain 64-bit float) instead of allocating them on the heap in the first place, which again is even better than mutating otherwise-immutable heap objects. For the special case of numbers stored in object properties, V8 also (in some cases) uses mutable storage.
So, the answer to your question is both "yes" (e.g. when generating unoptimized code, V8 doesn't spend the time to perform analysis, so the code must conservatively assume that any old value is needed somewhere), and "no" (for the optimizing compiler, your intuition is correct that this should be avoidable; however that still doesn't mean that any numbers that were allocated on the heap will be mutated there).

Since the i variable is scoped to the loop

Scoping in JavaScript is complicated. First off, there is no int i. Now consider this:
for (var i = 0; i < 100; i++) {
  // Use i here, or don't.
}
console.log(i);  // Prints "100".

If you meant let i, then sure, you'd have a block-scoped variable. In this example, performance would be the same.

We will have an unnecessary race between the for loop (creating new values of i in memory) and the garbage collector (killing off all the old values of i), which the loop will generally win

No. The garbage collector is highly adaptive, in particular it does more work when more allocations happen. There is no way to "outrun" it. If needed, program execution is stopped while the garbage collector tries to find memory that can be freed.

and we will have a stack overflow.

No, stack overflows have nothing to do with object allocations, or garbage collection, or heap memory in general.


text:
Q: Check if T is a bitfield? Is it possible to check at compile time if T is a bitfield?
I'd like to use it in:
template <typename Allowed>
struct explicitly_constructible
{
   template <typename T, typename = std::enable_if_t<is_bitfield_v<T>>>
   constexpr operator T() const;
};

Example usage:
struct normal
{
   int foo;
};

struct with_bitfield
{
  int bar : 2;
};

normal n{explicitly_constructible<int>()}; // well-formed
with_bitfield m{explicitly_constructible<int>()}; // must be ill-formed

I am implementing a reflection library that provides for_each and get<Index> tuple-like functions for pod-like structs. Unfortunately, you can't use it on a struct with bitfields since it is UB to get an address of a bit-field. So I want to detect if a struct contains a bitfield to fire a compile-time error. Now I have some workaround - I compare struct size against evaluated, but I would like a simpler approach.


text:
Q: Error using custom Skipper body parser configuration I'm using sails version 0.10.5. I have the bodyParser set like so in http.js:
bodyParser: require('skipper')({
  limit: 52428800
})

And I keep getting this error when starting the server:
error: TypeError: Cannot read property 'toLowerCase' of undefined
    at _parseHTTPBody (/var/www/testapp-backend/node_modules/skipper/index.js:49:19)
    at /var/www/testapp-backend/node_modules/sails/lib/hooks/http/middleware/defaults.js:104:28
    at module.exports (/var/www/testapp-backend/node_modules/sails/lib/hooks/http/middleware/defaults.js:144:7)
    at loadExpress (/var/www/testapp-backend/node_modules/sails/lib/hooks/http/initialize.js:103:65)
    at /var/www/testapp-backend/node_modules/sails/lib/hooks/http/index.js:190:18
    at /var/www/testapp-backend/node_modules/sails/lib/app/private/after.js:91:14
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:232:13
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:119:25
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:24:16
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:229:17
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:516:34
    at handlerFn (/var/www/testapp-backend/node_modules/sails/lib/app/private/after.js:78:13)
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:511:21
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:227:13
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:111:13
    at Array.forEach (native)
    at _each (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:32:24)
    at async.each (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:110:9)
    at _asyncMap (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:226:9)
    at Object.map (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:204:23)
    at _parallel (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:509:20)
    at Object.async.parallel (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:539:9)
    at Sails.emitter.after (/var/www/testapp-backend/node_modules/sails/lib/app/private/after.js:89:11)
    at Hook.initialize (/var/www/testapp-backend/node_modules/sails/lib/hooks/http/index.js:189:15)
    at Hook.bound [as initialize] (/var/www/testapp-backend/node_modules/lodash/dist/lodash.js:729:21)
    at /var/www/testapp-backend/node_modules/sails/lib/hooks/index.js:132:16
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:425:17
    at /var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:419:17
    at Array.forEach (native)
    at _each (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:32:24)
    at Immediate.taskComplete (/var/www/testapp-backend/node_modules/sails/node_modules/async/lib/async.js:418:13)
    at processImmediate [as _immediateCallback] (timers.js:367:17) [TypeError: Cannot read property 'toLowerCase' of undefined]

error: Encountered an error when trying to use configured bodyParser.
error: Usually, this means that it was installed incorrectly.
error: A custom bodyParser can be configured without calling the wrapper function- e.g.:
```
bodyParser: require("connect-busboy")
```
error: Alternatively, if you need to provide options:
```
bodyParser: {
fn: require("connect-busboy"),
options: {/* ... */}
}
```

There are no errors there after. What am I doing wrong? I tried following the instructions of the error but with skipper I'm not able to upload files to S3 greater than just a few mb's. I tried this and it doesn't work:
bodyParser: {
fn: require("skipper"),
options: {limit: 52428800}
}

that is as per the message above.

A: Due to a bug in the default bodyParser setting in Sails < 0.12, the normal method of configuring the middleware won't work.  The easiest solution is to simply replace bodyParser in the middleware order with another, custom middleware name and configure that instead, e.g.:
module.exports.http = {

  middleware: {

    // The order in which middleware should be run for HTTP request.
    // (the Sails router is invoked by the "router" middleware below.)
    order: [
      'startRequestTimer',
      'cookieParser',
      'session',
      // 'bodyParser', // <-- don't add the "bodyParser" middleware to the stack
      'skipper',   // <-- instead use this "custom" middleware
      'handleBodyParserError',
      'compress',
      'methodOverride',
      'poweredBy',
      '$custom',
      'router',
      'www',
      'favicon',
      '404',
      '500'
    ],

    // Configure Skipper
    skipper: require('skipper')({
      limit: 52428800
    })

  }
}


text:
Q: Scraping only returns header not details I'm a newbie to python and am just teaching myself how to code and scrape data, hoping someone can explain what Im doing wrong or why from the following script do I only get the headers, but no data is inserted into the text file?
Is it because its returning none or empty data fields from the scrape? or am I missing something in my logic
Not getting any errors from the code it would seem see idle out image below

code
# import necessary libraries
import requests
from bs4 import BeautifulSoup
import csv
import datetime

# get the current date
date = datetime.datetime.now().strftime("%Y%m%d")

# create the output file
filename = 'C:/Users/AJS2/Documents/datafiles_test/' + date + '.txt'
with open(filename, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['url', 'name', 'address', 'phone', 'email'])

# define the base url
base_url = "http://www.wedding-planners.com/index.cfm"

# get the page
page = requests.get(base_url)

# create a beautifulsoup object
soup = BeautifulSoup(page.content, 'html.parser')

# get the next button
next_button = soup.find('a', class_='Next')

# set the counter
counter = 0

# loop through the pages
while next_button and counter < 50:
    # get the list of wedding planners
    wedding_planners = soup.find_all('div', class_='plannerName')

    # loop through the list of wedding planners
    for planner in wedding_planners:
        # get the url
        url = planner.a['href']

        # get the page
        page = requests.get(url)

        # create a beautifulsoup object
        soup = BeautifulSoup(page.content, 'html.parser')

        # get the name
        name = soup.find('h1', class_='head1').text

        # get the address
        address = soup.find('span', class_='address').text

        # get the phone
        phone = soup.find('span', class_='phone').text

        # get the email
        email = soup.find('span', class_='email').text

        # save the data
        with open(filename, 'a', newline='') as csvfile:
            writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
            writer.writerow([url, name, address, phone, email])

    # increment the counter
    counter += 1

    # get the next page
    page = requests.get(next_button['href'])

    # create a beautifulsoup object
    soup = BeautifulSoup(page.content, 'html.parser')

    # get the next button
    next_button = soup.find('a', class_='Next')

print('Finished scraping')


text:
Q: DraftJS. Wrap up custom HTML tag with a custom Component Trying to implement smth similar with pure Draft.js:

To be more precise, i want to have these hidden blocks of original message(s) that are editable and expandable by clicking three-dots icon
So, after some research i found out there are Custom Block Rendering and Custom Block Components, so i'm trying to extend the blockRenderMap with OriginalMessage component:
const OriginalMessage = ({ children }) => {
  const [expanded, setExpanded] = useState(false);

  const toggleExpanded = () => setExpanded(!expanded);

  return (

        ...

      {children}

  );
};

const blockRenderMap = Immutable.Map({
  original: {
    element: 'original',
    wrapper: <OriginalMessage />,
  },
});

const extendedBlockRenderMap = DefaultDraftBlockRenderMap.merge(blockRenderMap);

...

// rendering the Editor

<Editor
  ...
  blockRenderMap={extendedBlockRenderMap}
/>

so, these are probably working pieces of code, and idea is - i need to parse following HTML into respective and recognizable blocks:

For example, this is a template that every new email has

Here we have a signature

<original>A lot of HTML here that includes previous messages blockquotes etc</original>

i use html-to-draftjs to get parse this html into blocks:
const blocksFromHTML = htmlToDraft(content, nodeName => {
  if (nodeName === 'original') {
    return {
      type: 'original',
      mutability: 'MUTABLE',
      data: {},
    };
  }
});

// setting new State

const newEditorState = EditorState.createWithContent(
  ContentState.createFromBlockArray(
    blocksFromHTML.contentBlocks,
    blocksFromHTML.entityMap,
  ),
  decorator,
);

setEditorState(newEditorState);

But when i check the block that suppose to have original type, the type is unstyled.
The question is - how to make Editor recognise <original> tag as a block that needs to be customly rendered?
btw, not sure that it's the right approach to solve the issue - any help or advice appreciated.
Thanks!

A: use Document.execCommand() and write your own component from scratch.
Then you will be able to do whatever you wish. Have a look at this example solving your issue, https://codepen.io/Nagibaba/pen/oNBQXgp


text:
Q: FFMPEG exec exit code 126 here is my code for FFMPEG
$mp3path=realpath("1.mp3");
$cmd = "/usr/include/ffmpeg -i $mp3path -ab 128 /home/swiftfa1/public_html/output.mp3 2>&1";
exec($cmd, $output, $value);
echo '
'; print_r($output); echo '
';
echo '
'; print_r($value); echo '
';
exit;

and here is my result:
Array
(
    [0] => sh: /usr/include/ffmpeg: Is a directory
)
126

I used whereis for ffmpeg path and searched a lot but can't solve my issue. any command returns 126!


text:
Q: Employee Test Driver Data Structures What would I use to define these Variables outside the Public and Private? Enum?
The Instructions for this section are this:
A default constructor. Remember that the default constructor for Address has the following initial values: Address to "99999 Sunset Boulevard" , "Beverly Hills", "CA", "99999"
4 private string instance variables for :Street, City, State, Zip
A constructor with 4 parameters: one for street, one for city, one for state, one for zip.
A printAddress(): it prints the Street, City, State, and Zip
Here is what I got so far
class Address
{
  public:
    Address();
    Address(City defaultCity, State defaultState, Street defaultStreet, Zip, defaultZip);
    int getCity();
    int getState();
    int getStreet();
    int getZip();
    int printAddress();
  private:
    int Street, City, State, Zip;
};
 Address :: Address(City defaultCity, State defaultState, Street defaultStreet, Zip, defaultZip);
{
    defaultCity = City
    defaultState = State
    defaultStreet = Street
    defaultZip = Zip
}
 Address::Address()
{
   Street = "99999 Sunset Boulevard,";
   City = "Beverly Hills,";
   State = "CA,";
   Zip = "99999";
}
 int Address::getCity()
{
   return City;
}
 int Address::getState()
{
   return State;
}
 int Address::getStreet()
{
   return Street;
}
 int Address::getZip()
{
   return Zip;
}
 int Address::printAddress()
{
   return Street, City, State, Zip;
};

Also when he says "print" I assume he means display right?
Thank you

A: I would do it like this:
#include <iostream>
#include <string>

/********************
 *  File: Main.cpp  *
 ********************/

/*
 * For simplicity I put it all in one file.
 */

class Address
{
public:
    explicit Address();
    explicit Address(const std::string& city, const std::string& state,
        const std::string& street, const std::string& zip);
    const std::string& getCity() const;
    const std::string& getState() const;
    const std::string&  getStreet() const;
    const std::string&  getZip() const;
    void printAddress() const;
private:
    std::string street;
    std::string city;
    std::string state;
    std::string zip;
};

// Default Constructor
Address::Address() :
    city("Beverly Hills"),
    state("CA"),
    street("99999 Sunset Boulevard"),
    zip("99999")
{ }

Address::Address(const std::string& city, const std::string& state,
    const std::string& street, const std::string& zip) :
    city(city), state(state), street(street), zip(zip)
{ }

const std::string& Address::getCity() const
{
    return city;
}
const std::string& Address::getState() const
{
    return state;
}
const std::string& Address::getStreet() const
{
    return street;
}
const std::string& Address::getZip() const
{
    return zip;
}
void Address::printAddress() const
{
    std::cout << street << ", " << city << ", "
              << state << ", " << zip << std::endl;
};

int main(int argc, char* argv[]) {
    Address defaultAddress;
    defaultAddress.printAddress();

    Address customAddress("Cologne", "NRW", "Domplatz 1", "D-50668");
    customAddress.printAddress();

    return 0;
}

EDIT:
Explaining some changes.

*

*Look at the private section of the class declaration. You declared members as int although they should be strings. I corrected that.

*In the constructors you should use initialization lists to initialize members.

*In your constructor parameter list you used the words City, State, Street and Zip as if they were types. Which they are not. The type of these parameters is std::string. Or in my case I chose const std::string& because I prefer passing by reference over passing by value if both are viable.

*If methods do not change the object you may declare them const so they can be called also on const instances of the class or const references. I did so in this example when declaring the getters.

*I did not see a need to return anything to the caller after printing so I changed the return type to void.

*I added a main function to test the class.
There is probably a lot more to say about the differences, but I think this is enough for tonight.
Cheers!


text:
Q: Prove that a set is a subfield Let $F$ be a finite field and $\varphi:\mathbb{Z}\to F$ a homomorphism such that $\varphi(1)=1_F$. Is $Im\varphi=\{\varphi(x):x\in \mathbb{Z}\} $ a subfield of $F$?
I know that $1_F\in Im\varphi$, $0_F\in Im\varphi$ and $(Im\varphi ,+)$ is a group, but I couldn't prove that given $x\in Im\varphi\setminus\{0_F\}$, then $x^{-1}\in Im\varphi$ in which $x^{-1}$ is the multiplicative inverse of $x$.
Another thing I know but I couldn't use to answer the question is that since $F$ is finite, then $\ker\varphi\neq\{0\}$. And since $\mathbb{Z}$ is a principal ideal domain and $\ker\varphi$ is a ideal, then exists $p\in\mathbb{Z}\setminus\{0\}$ such that $\ker\varphi=p\cdot \mathbb{Z}$.
I saw a teacher stating in a video lesson that $Im\varphi$ is a subfield of $F$ to prove that $p$ is prime. But unfortunately I couldn't understand why $Im\varphi$ is a subfield of $F$.

A: The image of $\phi$ is a subring of the field $F$, hence is an integral domain. This implies that $\ker(\phi)$ is a prime ideal of $\mathbb{Z}$.
But as you noted, $\ker(\phi)\neq \{0\}$ since $F$ is finite, which implies that $\ker(\phi)=p\mathbb{Z}$ for some prime $p$. Hence $\mathrm{Im}(\phi)\simeq \mathbb{Z}/p\mathbb{Z}$
is a field.


text:
Q: Formatting Powershell CSV Output file with header filters I can't seem to find any information anywhere on how to add header filters to a CSV file exported from powershell. See script below which exports a report on specific AD group members:
$Date = (Get-Date).ToString("dd/MM/yyyy hh:mm:ss")
$DateSh = (Get-Date).ToString("yyyyMMdd")

$CSVfile = "C:\Documents\Group Membership Report\Reports\$DateSh-GroupAccountsReport.csv"

$groups = ("Group1","Group2")
$groups | ForEach-Object {
    $curgroup = $_; $_
    } | Get-ADGroupMember -Recursive | Get-ADUser -Properties * -ErrorAction SilentlyContinue | Select Name,ObjectClass,Enabled,SamAccountName,LastLogonDate, @{N='Group';E={$curgroup}} | Export-Csv -NoTypeInformation $CSVfile

The rest of the script sends an email with this CSV as an attachment.
I would like to be able to add filters to the headers in the CSV file to make it easier to sort, which I can do manually, but I need the script to do this itself, see image below:
CSV Headers on top of data
I'm not sure if how simple a task it is, if it's just a case of adding a few extra lines to my existing script or needing a whole new one. I think it would need to be converted to an xls doc and formatted as a table. Any help is appreciated,
Thanks


text:
Q: Leer código de verificación de un sms desde IOS Quiero hacer una pequeña app para registrar usuarios.
Una vez que se registre el usuario se le enviará un sms con un código de verificación.
¿Solo necesito saber si es posible acceder a la lista de sms y obtener el código sin que el usuario se mueva de la aplicación?
El lenguaje que utilizo es swift
Se que en Android se puede, pero IOS es distinto pone muchas pegas al obtener información del usuario, por eso mi pregunta

A: 1.- Si haces que el mensaje pueda visualizarse en el centro de notificaciones de ios, cuando el usuario lo reciba y lo vea allí, le bastaría con deslizar hacia abajo el centro de notificaciones y así no saldría de la app. Pues aunque es algo externo, no obliga a salir de la app. No es una respuesta a tu pregunta pero es una solución posible.
2.- Otro tema sería que al registrarse reciba el código en su area de usuario. (Dentro de la app)
3.- También puedes hacer que el código sea una combinación de 3 cifras/letras de manera que sea tan fácil de recordar de que cuando aparece en pantalla el código tan solo tenga que ponerlo sin salirse.
En esta opción puedes ponerle al usuario de la app algo del estilo:

"Si tienes habilitadas las notificaciones de ios en pantalla
  bloqueada" Espera 5 segundos y verás el código aparecer en pantalla.


text:
Q: Clear Earlier Dates in End date Calendar using ajaxControlToolkit:calendarExtender If from date is selected in calendar Extender, I need to clear previous dates than from date from To Date Calendar as shown in figure. Please provide your comments

A: Use this CSS property on your any .css class
.ajax__calendar_day_disabled
{
    background-color:#ccc !important;
    color:#eee !important;
}

use above css class in date textbox like CssClass="disable_past_dates"
and use script
function getElementsByClassName(a, b) { var c = []; var d = a.getElementsByTagName("*"); for (var e = 0; e < d.length; e++) { if (d[e].className.indexOf(b) != -1) { c.push(d[e]) } } return c } function DisableDates(a) { if (a._element.className.indexOf("disable_past_dates") != -1) { var b = getElementsByClassName(a._days, "ajax__calendar_day"); var c = (new Date).setHours(0, 0, 0, 0); for (var d = 0; d < b.length; d++) { try { if (b[d].date.setHours(0, 0, 0, 0) >= c) { b[d].className = "ajax__calendar_day" } else { b[d].className = "ajax__calendar_day ajax__calendar_day_disabled" } } catch (e) { } } } if (a._element.className.indexOf("disable_future_dates") != -1) { var b = getElementsByClassName(a._days, "ajax__calendar_day"); var c = (new Date).setHours(0, 0, 0, 0); for (var d = 0; d < b.length; d++) { try { if (b[d].date.setHours(0, 0, 0, 0) <= c) { b[d].className = "ajax__calendar_day" } else { b[d].className = "ajax__calendar_day ajax__calendar_day_disabled" } } catch (e) { } } } } AjaxControlToolkit.CalendarBehavior.prototype.show = function (a) { this._ensureCalendar(); if (!this._isOpen) { var b = new Sys.CancelEventArgs; this.raiseShowing(b); if (b.get_cancel()) { return } this._isOpen = true; this._popupBehavior.show(); if (this._firstPopUp) { this._switchMonth(null, true); switch (this._defaultView) { case AjaxControlToolkit.CalendarDefaultView.Months: this._switchMode("months", true); break; case AjaxControlToolkit.CalendarDefaultView.Years: this._switchMode("years", true); break } this._firstPopUp = false } this.raiseShown(); DisableDates(this) } }; AjaxControlToolkit.CalendarBehavior.prototype._cell_onclick = function (a) { a.stopPropagation(); a.preventDefault(); if (!this._enabled) return; var b = a.target; var c = this._getEffectiveVisibleDate(); Sys.UI.DomElement.removeCssClass(b.parentNode, "ajax__calendar_hover"); switch (b.mode) { case "prev": case "next": this._switchMonth(b.date); break; case "title": switch (this._mode) { case "days": this._switchMode("months"); break; case "months": this._switchMode("years"); break } break; case "month": if (b.month == c.getMonth()) { this._switchMode("days") } else { this._visibleDate = b.date; this._switchMode("days") } break; case "year": if (b.date.getFullYear() == c.getFullYear()) { this._switchMode("months") } else { this._visibleDate = b.date; this._switchMode("months") } break; case "day": if (this._element.className.indexOf("disable_past_dates") != -1) { if (b.date.setHours(0, 0, 0, 0) >= (new Date).setHours(0, 0, 0, 0)) { this.set_selectedDate(b.date); this._switchMonth(b.date); this._blur.post(true); this.raiseDateSelectionChanged() } } else if (this._element.className.indexOf("disable_future_dates") != -1) { if (b.date.setHours(0, 0, 0, 0) <= (new Date).setHours(0, 0, 0, 0)) { this.set_selectedDate(b.date); this._switchMonth(b.date); this._blur.post(true); this.raiseDateSelectionChanged() } } else { this.set_selectedDate(b.date); this._switchMonth(b.date); this._blur.post(true); this.raiseDateSelectionChanged() } break; case "today": this.set_selectedDate(b.date); this._switchMonth(b.date); this._blur.post(true); this.raiseDateSelectionChanged(); break } DisableDates(this) };
This will disabled all the past dates but not clears it.

A: try this one,
CntrlID.MinDate = DateTime.Now;

CntrlID.MaxDate = DateTime.Today.AddMonths(12);

CntrlID.MaxDate = DateTime.Today.AddYears(100);


text:
Q: How Does WordPress Handle Upgrades? Can anyone describe the pseudocode for how WordPress handles its upgrades? As in, you go into WordPress admin and choose to upgrade the version of WordPress.
I mean, does it use FTP APIs locally? Does it send credentials to another host which reconnects back with FTP APIs? Does it download files with Curl? Does it polyfill if a given API isn't there and go another route? Does it test file permissions to see which API to use?
I've got a client who wants something like this built into a web application unrelated to WordPress.

A: Have a look it wp-admin/includes/update.php and wp-admin/includes/class-wp-upgrader.php
And here for some explanation: http://tech.ipstenu.org/2011/how-the-wordpress-upgrade-works/


text:
Q: Pandas: count numbers based on date, user and group I have a table in below format:
df = pd.DataFrame({'Date':['20191101','20191101','20191101','20191101','20191102','20191102','20191102','20191102'
                         ,'20191103','20191103','20191103','20191103'],
                 'User':['James','Kevin','Kevin','Corrado','James','Kevin','Corrado','Corrado','James','Kevin','Corrado','Corrado'],
                 'Department':['A','B','B','C','A','B','C','C','A','B','C','C']})
df

And the table is in this result:
df1
Date        Department      User
20191101           A         James
20191101           B         Kevin
20191101           B         Kevin
20191101           C         Corrado
20191102           A         James
20191102           B         Kevin
20191102           C         Corrado
20191102           C         Corrado
20191103           A         James
20191103           B         Kevin
20191103           C         Corrado
20191103           C         Corrado

My desired result table using above one to count is:
df2
Date        Department      User       Count
20191101           A         James        1
20191101           B         Kevin        2
20191101           C         Corrado      1
20191102           A         James        1
20191102           B         Kevin        1
20191102           C         Corrado      2
20191103           A         James        1
20191103           B         Kevin        1
20191103           C         Corrado      2

And I would like to build this second table df2, which counts the frequency of a user in that specific department on that specific date in a data frame format which I could directly refer to and plot charts using matplotlib. This df2 should also maintain the date, department and user, and add just 1 more column as count.
Is there any way to do such operation? Highly appreciated.


text:
Q: Tiled and MonoGame.Extended - How to handle collisions? I use Tiled to edit my maps, and I would like to set-up a collision system with my game.
I tried to set properties on some tiles of the tilesets I use, but the problem is that I can't access them from MonoGame.Extended, actually the library doesn't seem to be designed for this purpose, and I don't understand why.
i.e. when I look in the TiledMapTile class there is no property at all, certainly there are TiledMapTilesetTile objects from the TiledMapTileset class that contains properties, but how can I get this object from a position? What I want is something like this:
bool isCollisionTile = tiledMap.GetTile(x, y).Properties["IsCollisionTile"];

I'm also open to other approaches to handle collisions, either by using another C# Tiled support library for MonoGame/XNA, or by changing my approach of this problem, and find a completely different solution.
Thanks in advance!

A: You can always export the tile map you use to JSON if you like. See JSON-map-format.

Tiled can export maps as JSON files. To do so, simply select "File >
  Export As" and select the JSON file type. You can export json from the
  command line with the --export-map option.

Load your JSON in monogame and access the properties from there.
You can get the tile that the player is on using the ff:
int playerPosX = 0;
int playerPosY = 0;
int tileWidth = 32;

// TiledMap map
TiledMapTileLayer layer = map.GetLayer<TiledMapTileLayer>("Collision");
TiledMapTile? tile = null;

ushort x = (ushort)(playerPosX / tileWidth);
ushort y = (ushort)(playerPosY / tileWidth);

// Get tile based on player position
layer.TryGetTile(x, y, out tile);

if (tile.HasValue)
{
    // collided!
    // you can also compute the tile's position using the X, Y and tileWidth if needed.
}


text:
Q: HTML5 Draggable setDragImage doesn't work with canvas on Chrome I'm trying to use canvas as my drag image in native HTML5 Drag And Drop API.
The problem is that it works on Firefox but not on Chrome (58) and I can't pinpoint the problem.
Code: https://jsfiddle.net/196urLwd/5/

DRAG ME

function onDragStart(event){

    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    canvas.width = 100;
    canvas.height = 20;

    context.fillStyle = '#333333';
    context.fillRect(0, 0, canvas.width, canvas.height);

    context.fillStyle = '#999999';
    context.font = 'bold 13px Arial';
    context.fillText('DRAGGING...', 5, 15);

    event.dataTransfer.setData('text', 'lorem ipsum');
    event.dataTransfer.effectAllowed = 'copy';
    event.dataTransfer.setDragImage(canvas, -15, 9);

};

var theThing = document.getElementById('thing');
theThing.addEventListener('dragstart', onDragStart, false);

What am I doing wrong?

A: Chrome seems to require the canvas to be in the dom
document.body.append(canvas);

and just hide it with some css
canvas{
  position:absolute;
  left:-100%;
}

https://jsfiddle.net/196urLwd/6/


text:
Q: After changing form to FormData in Ajax, codeigniter form validation didn't work I wrote some code in CodeIgniter3 framework. I wrote a code that shows form validations with Ajax right after input fields. However, I added "upload image" function, for this reason, changed my ajax file from:
$(document).ready(function() {
$("#continueregistrationform").unbind('submit').bind('submit', function() {
    var form = $(this);

$.ajax({
    url: form.attr('action'),
    type: form.attr('method'),
    data: form.serialize(),
    async : false,
    cache : false,
    processData : false,
    dataType: 'json',
    success:function(response) {
    console.log(response);
        if(response.success) {
            $("#messages").html(response.messages);
            $("#continueregistrationform")[0].reset();
            $(".text-danger").remove();
            $(".form-group").removeClass('has-error').removeClass('has-success');
            location.href = "http://localhost/edu-center/";

        }
        else {
            $("#messages").html(response.messages);
            $.each(response.messages, function(index, value) {
                var element = $("#"+index);
                $(element).parent('div').find('.text-danger').remove();
                $(element).after(value);

            });
        }
    } // /success
});  // /ajax

return false;
});
});

to :
$(document).ready(function() {
$("#continueregistrationform").unbind('submit').bind('submit', function() {
    var formData = new FormData($('#continueregistrationform')[0]);
$.ajax({
    url: formData.attr('action'),
    type: formData.attr('method'),
    data: formData,
    async : false,
    cache : false,
    contentType: false,
    processData : false,
    dataType: 'json',
    success:function(response) {
    console.log(response);
        if(response.success) {
            location.href = "http://localhost/edu-center/";
        }
        else {
            $("#messages").html(response.messages);
            $.each(response.messages, function(index, value) {
                var element = $("#"+index);
                $(element).parent('div').find('.text-danger').remove();
                $(element).after(value);

            });
        }
    } // /success
});  // /ajax

return false;
});
});

Now instead of showing errors like before under the input fields, it shows them in a new blank white page. Where can be the problem? Thanks in advance!

A: I would personally not use formData.attr to set the action and method. You may want to verify that the values of formData.attr('action') and formData.attr('method') are what you expect them to be.
From my own personal experience doing exactly what you're doing, this is how I added the image and post variables to the ajax request:
// Add file
var formData = new FormData();
var fileInput = $('#your_image_upload_field')[0];
var file = fileInput.files[0];
formData.append('userfile[]', file); // MUST HAVE [] OR PHP HAS NO $_FILES !!!
// Add post vars
formData.append('a', a);
formData.append('b', b);
formData.append('c', c);
// Do post
$.ajax({ //...


text:
Q: Reference request for category theory works which quickly prove the theorem which generalises the 1st isomorphism theorem for groups/rings/... One aspect of category theory that caught my eye is that it can give simultaneously prove the 1st isomorphism theorem for groups/rings/fields/vector spaces/... Yet whenever I look up works on category theory, it takes hundreds of pages to reach this theorem. Is it possible to prove this result using substantially less theory, and if so, is there any work which provides such a proof?

A: If you want a categorical proof that encompasses nonabelian groups and rings-without-identity, then you need to work with concepts such as "normal subobject" that are (I think) not really part of the category theory that most mathematicians routinely encounter.  You may also find that a proof is not particularly enlightening at this level of generality.  I think this might explain why a simultaneous generalization does not appear early in textbooks.
I'll consider the formulation of the first isomorphism theorem which states that for any homomorphism $f: A \to B$, $ker(f): K \to A$ is a normal subobject, and the image of $f$ in $B$ is isomorphic to the quotient of $A$ by $K$.  The formalism is roughly as follows: We work in a category in which every morphism has a kernel and a cokernel.  Then any morphism $f: A \to B$ factors into a composition of $coker(ker(f)): A \to A/K$, $m: A/K \to N$, and $ker(coker(f)): N \to B$, and the diagram is defined up to unique isomorphism by the universal properties of kernel and cokernel.  For the first part of the theorem, one typically defines normal subobject to be a kernel (although there are alternative definitions involving congruences), so we reduce to the question of the image.  Here we have a conflict of terminology, since the "image" is often defined in categories as the kernel of the cokernel, and the first isomorphism theorem interprets image set-theoretically.  Given this alternative interpretation, the theorem amounts to the assertion that $m$ and $ker(coker(f))$ are monomorphisms.  Here we encounter another problem, since as far as I know, $m$ does not need to be a monomorphism in general.
At this point, we need to check that the categories we like have kernels and cokernels.  The kernel of a group homomorphism $f:A \to B$ is (the inclusion of) the preimage of the identity, and the cokernel of $f$ is given by taking the normal hull $N$ of $f(A)$ in $B$, and taking the quotient group $B/N$.  We get our theorem because the maps of $f(A)$ into $N$ and $N$ into $B$ are inclusions, hence monomorphisms.  A similar argument works for rings-without-identity.  For abelian groups and vector spaces, the map $m: f(A) \to N$ is an isomorphism.  For fields, there are no kernels, so the first isomorphism theorem doesn't make sense.

A: On Abelian situation "Theory of categories" (BArry Mitchell) is easy and short.
In general algebras see: "Universal Algebra" by P. M. Cohn.
For a general categorical tractate about algebraic proprieties of algebraic categorical structures see:
F. Borceux and D. Bourn, Malcev, Protomodular, Homological and Semi-Abelian Categories.

A: Let $C$ be a finitary algebraic category. That is objects are sets with additional structure (given by some operations of certain arities, satisfying some equations) and morphisms are structure preserving maps.
Now the isomorphism theorem reads as follows: Let $f : A \to B$ a morphism and $\sim$ a congruence relation on $A$ such that $a \sim b \Rightarrow f(a)=f(b)$. Then $f$ factors uniquely through the projection $A \to A/\sim$ and a morphism $\overline{f} : A/\sim \to B$. The image of $f$ coincides with the image of $\overline{f}$. Besides, $\overline{f}$ is injective iff $a \sim b \Leftrightarrow f(a)=f(b)$.
The proof is straight forward and generalizes the isomorphism theorems for groups/rings/... by finding alternative descriptions of congruence relations.

A: Try "Introduction to the Theory of Categories and Functors" by Bucur and Deleanu. They have a treatment of the isomorphism theorems in abelian categories beginning on page 101. They start by noting that the first isomorphism theorem follows from the definition of abelian category. Then they go on to prove the second and third theorems. Their discussion of abelian categories only begins on page 87, and they finish the third isomorphism theorem on page 111. If you already know the preliminaries, you might be able to get right to the heart of the matter without too much trouble.
Edit: I just stumbled onto a paper by Barros and Pombo, "A direct proof of Noether's second isomorphism theorem for abelian categories". It's only 8 pages long. They reference Bucur & Deleanu, Freyd, and Grothendieck. You can find it at http://www.scielo.org.co/pdf/rcm/v43n1/v43n1a04.pdf.


text:
Q: Difference between two arrays of Mongo Document _ids Essentially, I have two arrays of _ids from Mongodb that I'm trying to compare/get the differences of.
Array 1 comes directly from a document.find() call.  Array 2 comes from an document.Aggregate call, of which I then _.pluck the _id from both of them.
Array 1 might look like [ 1 , 57, 58, 100 ] as an example.
Array 2 might look like [ 1 , 2, 3, 4, 55, 100 ] as an example.
I want to find the difference and return and [ 57, 58 ].
To do this I've been using lodash as the library.  And I've tried the following two methods:
_.difference(array1, array2)

and
_.filter(array1, function(obj){ return !_.findWhere(array2, obj); });

But both don't seem to work.  I'd love some help if possible.

A: Ignore.  Turns out the filter code worked.  It was my db with the error.
_.filter(array1, function(obj){ return !_.findWhere(array2, obj); });


text:
Q: Month wise data fetch from mysql database Month wise data Image
Month wise data fetch from date field in mysql.
I have a table name salary_details and my table data looks like attached Image. Please see the image to solve my problem.
i am using following code of php.
"select *, SUM(amount) as amt from salary_details
group by month,name"

A: You need to do pivot, check reference here
SELECT Name, ['July'],['August'],['September'] FROM
(SELECT Name, [Month] , Amount FROM salary_details )Tab1
PIVOT
(
SUM(amount) FOR [Month] IN (['July'],['August'],['September'])
) AS Tab2
ORDER BY Tab2.Name


text:
Q: Excel VBA script to add apostrophe slow I have a VBA script that I use to add apostrophe to cells, but I have currently 200000 rows to check and it seems to take considerably long. The code I'm using is the following:
    Sheets("Sheet1").Select
    myrange = "c21:c200000"
    For Each cell In ActiveSheet.Range(myrange)
    If cell.Value <> "" Then cell.Value = "'" & cell.Value
    Next

Any ideas on how to make the code run faster or do you know of any other code that could work better?

A: I don't understand what you want to achieve with the single quote, but generally, you can fill all empty cells by limiting the range and write to all of them at once:
Const DefaultString = "'"
Dim ws As Worksheet, r As Range
Set ws = ThisWorkbook.Sheets(1)

Set r = ws.Range("A1:A200000")
' Fill last cell to ensure that SpecialCells looks to complete range
If r.Cells(r.Rows.Count, 1) = "" Then r.Cells(r.Rows.Count, 1) = DefaultString
Set r = r.SpecialCells(xlCellTypeBlanks)
r.Value2 = DefaultString


text:
Q: Is there a way to determine which aws services are being used by a user? I need to update our service access policy for an account (IAM user) that has access to a dozen or so services, problem is, I'm not sure which services the account uses.
It's an account that is used by a lot of our services, and developers so it would be unfeasible to track all usages...
I tried getting events from CloudTrail's Event history, but it doesn't give me a full list (i.e can't see any calls to SQS queues made by said account).
So my question is: Is there a way to track all the services that are used with a specific API key that belongs to an IAM user?

A: CloudTrail is a comprehensive list of all API calls invoked by a user. If you don't see SQS calls in CloudTrail then i suggest you double check that the user is making SQS calls or whether they have setup something to hide their SQS calls because CloudTrail is enabled by default and will catch SQS calls.
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-logging-using-cloudtrail.html

A: As @jellycsc suggested, I can find all the information I needed by going through Refining permissions in AWS.
Thanks, everyone!


text:
Q: Simulation and Survival mode not equal? I created a script in Simulation mode which runs great. Then when I want to execute it in survival mode it doesn't work anymore. It seems to have problems with the Memory hash in survival mode.

A: I haven't tested this, since I've been too busy to fiddle with Screeps since before Survival launched, but you should be able to initialize your memory on the first tick.
As in, create a module that explicitly sets every memory object you use to blank, then in your main loop, call that module if Game.time == 1.


text:
Q: send code from vim to an external application for execution I am regularly using stata at work. My text editor of choice is (g)vim.
I have been using the scripts provided here or here to send code from vim to stata. This functionality is immensely practical and virtually the only thing the keeps me from switching to linux completely. The scripts are written in AutoIT, so I cannot use them in linux. They are also basically independent from the choice of text editor, the people who wrote them are using notepad++.
Essentially, these scripts together with a few lines in my vimrc allow me to send selections or the whole file to a running stata window (if none is open, stata is started first).
I am looking for a solution that does this in linux, but I have no idea where to start. In linux there are two different stata versions, stata for the command line and xstata is the gui version. I need to use the gui version as the functionality of the command line version is limited unfortunately, so screen/tmux are ruled out.
If this is trivial, I'm really sorry for missing it and would be immensely grateful for a solution. I also wasn't able to find an existing plugin for vim I could utilize. If not, I am willing to invest some time and figure out how to implement a solution. A pointer in the right direction would however be quite helpful. I am relatively new to linux and programming in general, but willing to learn.
Regarding tools: I don't know bash, but it is something I want to look into anyways at some point. I have dabbled a bit in python, so that would also be ok. In case there is anything else absolutely superior for this task, please let me know.
Any help is greatly appreciated. The AutoIT scripts are hosted on the website, but I can post my windows setup here if necessary.
EDIT
Ok, after some debate in the comments, here is the essential AutoIT script that I need to translate. (I would prefer a solution that doesn't overwrite the content of the system clipboard each time though.)
Edit2
I guess this is what the script does essentially: It checks for an open stata window, selects it (or executes one), pastes the contents that are to be executed into a temporary file, switches to the stata window, selects the command line with ctrl-1 (and anything that might already be written there with ctrl-a) and then pastes do "tempfile" into the commandline, which then executes the code that was sent. At least that is how I understand it.
FINAL COMMENT
I have worked up a solution in bash some time ago, it is posted here as an answer to a previous version of this question.
; Declare variables
Global $ini, $statapath, $statawin, $statacmd, $dofile, $clippause, $winpause, $keypause

; File locations
; Path to INI file
$ini = @ScriptDir & "\rundo.ini"
;; contents of ini file are the following
    ;[Stata]
    ;; Path to Stata executable
    ;statapath = "C:\Program Files\Stata11\StataSE.exe"
    ;; Title of Stata window
    ;statawin = "Stata/SE 11.2"
    ;; Keyboard shortcut for Stata command window
    ;statacmd = "^1"
    ;[Delays]
    ;; Pause after copying of Stata commands to clipboard, in milliseconds
    ;; Use higher number if script fails (default: 100, recommended range: 0 - 200)
    ;clippause = 100
    ;; Pause between window-related operations, in milliseconds
    ;; Use lower number to speed up script, higher number if script fails (default: 200)
    ;winpause = 200
    ;; Pause between key strokes sent to Stata, in milliseconds
    ;; Use lower number to speed up script, higher number if script fails (default: 1)
    ;keypause = 1

; Path to Stata executable
$statapath = IniRead($ini, "Stata", "statapath", "C:\Program Files\Stata11\StataSE.exe")
; Title of Stata window
$statawin = IniRead($ini, "Stata", "statawin", "Stata/SE 11.2")

; Keyboard shortcut for Stata command window
$statacmd = IniRead($ini, "Stata", "statacmd", "^1")

; Path to do-file that is passed to AutoIt
; Edit line to match editor used, if necessary
$dofile = $CmdLine[1]

; Delays
; Pause after copying of Stata commands to clipboard
$clippause = IniRead($ini, "Delays", "clippause", "100")
; Pause between window-related operations
$winpause = IniRead($ini, "Delays", "winpause", "200")
; Pause between keystrokes sent to Stata
$keypause = IniRead($ini, "Delays", "keypause", "1")

; Set WinWaitDelay and SendKeyDelay to speed up or slow down script
Opt("WinWaitDelay", $winpause)
Opt("SendKeyDelay", $keypause)

; If more than one Stata window is open, the window that was most recently active will be matched
Opt("WinTitleMatchMode", 2)

; Check if Stata is already open, start Stata if not
If WinExists($statawin) Then
  WinActivate($statawin)
  WinWaitActive($statawin)
  ; Activate Stata command window and select text (if any)
  Send($statacmd)
  Send("^a")
  ; Run saved do-file
  ; Double quotes around $dofile needed in case path contains blanks
  ClipPut("do " & '"' & $dofile & '"')
  ; Pause avoids problem with clipboard, may be AutoIt or Windows bug
  Sleep($clippause)
  Send("^v" & "{Enter}")
Else
  Run($statapath)
  WinWaitActive($statawin)
  ; Activate Stata command window
  Send($statacmd)
  ; Run saved do-file
  ; Double quotes around $dofile needed in case path contains blanks
  ClipPut("do " & '"' & $dofile & '"')
  ; Pause avoids problem with clipboard, may be AutoIt or Windows bug
  Sleep($clippause)
  Send("^v" & "{Enter}")
EndIf

A: IronAHK is a Linux/Mono rewrite of the AutoHotKey scripting language, which is similar to AutoIt (a GUI automation / keyboard remapping tool). I haven't used IronAHK, but AutoHotkey can run AutoIt v2 scripts.
You can also look @Project Sikuli: "Sikuli is a visual technology to automate and test graphical user interfaces (GUI) using images (screenshots). Sikuli includes Sikuli Script, a visual scripting API for Jython, and Sikuli IDE, an integrated development environment for writing visual scripts with screenshots easily" (from the sikuli front page)
Another good option is Linux Desktop Testing Project (LDTP), scriptable with Python:
example:
from ldtp import *
from ldtputils import *

try:
    launchapp("gedit")
    if waittillguiexist("*.gedit")==0:
        raise LdtpExecutionError("Gedit window does not exist")

    selectmenuitem("*-gedit", "mnuFile;mnuOpen")
    selectrow("dkgOpenFiles...", "tblFiles", fileName[0])
    ...

A: Maybe you could use a mechanism similar to used by this vim plugin, which perform a similar task:
http://www.vim.org/scripts/script.php?script_id=1048
This plugin sends R code to a R tool, under unix and windows (R programming language  is widely used for statistical software development and data analysis).
I don't know about Stata or R language, but it seems that you could control Stata using R, as stated in
http://www.r-bloggers.com/why-use-r/
:
You can easily use it anywhere.  It's  platform-independent, so you can use it
on any operating system.  And it's free, so you can use it at any employer
without having to persuade your boss to purchase a license.
:
:
R allows you to integrate with other languages (C/C++, Java, Python) and
enables you to interact with many data sources: ODBC-compliant databases
(Excel, Access) and other statistical packages (SAS, Stata,  SPSS,
Minitab).

Some Stata commands translated to R:
http://www.r-bloggers.com/stata-or-r/
If you could perform the desired task through R then probably you could use the vim plugin above unchanged.
Hope this help.

A: I've used the VI map function to define macros to send my file to a C compiler, and retrieve the results. It's not very robust (no if/then programming), but it's pretty simple to implement, and I have a lot of standard mappings I use. For example &T uppercases the line I'm on while &t lowercases it. I use &S to run my spell checker (gspell), etc. You don't need to begin your macros with an ampersand, but this way I know it's an unlikely combination of letters I'd be typing.
Setting up a Map is pretty easy. You use the :map ex command, space, a word used to invoke the map, a space, and then the keystrokes you want to execute. If you need to insert something like a return or escape, prefix it with a Ctrl-V.
You can use map! to map a macro that can be executed while in Insert or Replace mode.


text:
Q: Firebase Database workouts issues I created the Database in firebase and used for my hybrid application, Let you explain the application scenarios below.
I have a hybrid application in this app, We need to insert, update, delete, kind of operations using firebase.
As of now, I did the insert method kind of queries alone using code. So the thing is I want to create multiple tables in firebase is it possible ?
Because For example, I've userTable, adminTable and guestTable, So If I need to insert one userData before that I need to check already the user found or not in Admin table this kind of scenarios How can I do in firebase ?
How can I maintain multiple tables in the firebase Database dashboard?
I have the table name called "Inmate_Data" now I want to add one more Table called "Admin_Data" and How can I do a joint operation like connecting two table using Firebase.
And, I tried to add one more table using Import JSON option But while I inserting new JSON the old Table got deleted like the "Inmate_Data" deleted and new JSON got added.
Please guide me in this.
@FrankvanPuffelen - Please find the below coding part.
Actually, I created the form and saving the data into firebase using below code.
$scope.addInmateDataToFirebase = function() {

  alert('Firebase')

  var newPostKey = null;

  // Get a key for a new Post.
  newPostKey = firebase.database().ref().child('Tables/Inmate_Data').push().key;
  alert(newPostKey);

  var dateofjoin= $filter('date')($scope.IMDOJ, 'yyyy-MM-dd');
  var dateofbirth= $filter('date')($scope.IMDOB, 'yyyy-MM-dd');

  console.log("Result"+ newPostKey);
  var admissionId="KAS"+pad(newPostKey,5);
  console.log("Padded number"+ pad(newPostKey,5));
  alert(admissionId);

            // A post entry.
            var postInmateData = {

              Inmate_ID: admissionId,
              Inmate_Name: $scope.IMfirstnameText,
              Inmate_Perm_Address1: $scope.IMAddress1 ,
              Inmate_Perm_Address2: $scope.IMAddress2 ,
              Inmate_Perm_City: $scope.IMCity,
              Inmate_Perm_State: $scope.IMState,
              Inmate_Perm_Pincode: $scope.IMPincode,
              Inmate_ProfilePhotoPath: $scope.IMProfilePhotoPath,
              Inmate_Temp_Address1: $scope.IMLocAddress1,
              Inmate_Temp_Address2: $scope.IMLocalAddress2,
              Inmate_Temp_City:$scope.IMGcity,
              Inmate_Temp_State: $scope.IMGstate,
              Inmate_Temp_Pincode: $scope.IMGpincode,
              Inmate_Mobile: $scope.IMMobile,
              Inmate_DOB: dateofbirth,
              Inmate_EmpOrStudent: $scope.IMEmpStudent,
              Inmate_DOJ: dateofjoin,
              Inmate_ID_Type: $scope.IMIdcardType,
              Inmate_ID_No: $scope.IMIdcardno,
              Inmate_ProffPhotoPath: $scope.IMProofPhotoPath,
              Inmate_Status:$scope.IMStatus

            };

            // Write the new post's data simultaneously in the list.
            var updates = {};
            updates['/Tables/Inmate_Data/' + newPostKey] = postInmateData;

            return firebase.database().ref().update(updates).then(function() {

              //$scope.ClearInMateDetails();

              alert(admissionId);
              $scope.statusMessage =  "Welcome to Kasthuri Hostel. Your Admission ID  is" + admissionId +" . Enjoy your Stay.";
              //sendSMS('9488627377',$scope.statusMessage);
              alert('Inmate data stored in cloud!');

              $scope.ClearInMateDetails();

            }, function(error) {

              alert (error);

            });

          }

Now the Inmate_data got stored. and I need to save the Inmate_alloc_data into firebase but before that, I need to check whether the Inmate_Id available in the Inmate_Data table in firebase.
Please find the below snap :

My suggestions :
For example like above screenshot now I've multiple tables like "Inmate_Data", "Inmate_Alloc", and more Shall I get all the data and store it in a local SQLite Db like same as "Inmate_Alloc_tbl" and "Inmate_Data_tbl" and finally If I update any values finally I want to get all values in the local database and store it in the firebase. Is it possible to handle ?
If so I can manage lots of SQL queries, right ? Because via firebase we can't able to manage all queries right ?
Please suggest your ideas.


text:
Q: Can I create .las or .laz files from .hgt, .tiff, .gpx/kml or .asc files? I have got into a golf simulator game and want to recreate my home course. Problem here is that the only import way for height information is a LAZ or LAS file. So I am looking for a way to work around. The Austrian government provides HGT and TIFF files, I tried a few ways but not being able to get it done, I have tried txt2las but I didn't get it done. My last idea what I found googling was to export height information from Google Earth via a KML/KMZ file and then port it to LAS/LAZ.
Did someone already do this and made a tutorial about it? Or am I just thinking too complicated and there is a way easier way?
Files I got from the area I need is the HGT file of the whole region, TIFF files, ASCII (ASC) raster and KML/KMZ export from Google Earth.

A: If you are able/willing to code a little, you could create the LAZ file in Python using laspy.
Here is some example code:
import laspy
import numpy as np

# generate random xyz point data:
n_points = 100
xyz = np.random.uniform(0, 30, (3, n_points))  # xyz point geometry
rgb = np.random.randint(0, 255, size=(3, n_points))  # rgb colour
intensity = rgb.mean(axis=0).astype('uint8')  # backscatter amplitude or intensity
n_returns = np.ones_like(intensity, dtype='uint8')  # number of laser returns per pulse
clf = np.copy(n_returns) + 1  # point classification (e.g. 2 = ground, 5 = veg)

# create the las file:
las = laspy.file.File('test.las', mode='w', header=laspy.header.Header())
las.header.offset = xyz.min(axis=1)
las.header.scale = [1, 1, 1]

# set point attributes:
las.X = xyz[0]
las.Y = xyz[1]
las.Z = xyz[2]
las.intensity = intensity
las.r = rgb[0]
las.g = rgb[1]
las.b = rgb[2]
las.return_num = n_returns
las.num_returns = n_returns
las.raw_classification = clf

# close file:
las.close()

If the ASCII raster contains tabular XYZ coordinates, you should be able to easily read the XYZ coordinates directly in Python (see Pandas library). Once you have the XYZ data as numpy arrays, you can write them to the las file as shown above.
You probably don't need to bother with other parameters (rgb values, intensity, point classification), but I have included them here for illustrative purposes just in case you want to do something fancy like classify trees around the golf course!


text:
Q: modifications in legend are not saved by using saveas I just got some strange behaviour when saving a figure by using saveas. You should be able to reproduce this with this:
%just plot a line:
plot(1:10);
legend('line 1')
%find the line (not the best solution, but its working here):
temp=findall(legend,'type','line')
%modify the marker of the line within the legend:
set(temp(1),'Marker','o')
%save it:
saveas(gcf,'Test','fig')

if you now open the figure, the modifications within the legend seem to be gone.
The question is:
How can I save it the way it is displayed including the changes of the legend?
and perhaps, if someone knows:
what is the reason for this behaviour of saveas?
additional info: Matlab 2013a

A: The problem is that you are changing the legend but not the marker on the line.  When Matlab loads the saved figure, it automatically sets the legend to match the line/marker.  I doubt if you can change this behavior.


text:
Q: Pseudofunctors of 2-variables and Gray tensor product of bicategories Let $\mathcal{A}, \mathcal{B}, \mathcal{C}$ be bicategories. We say a 'pseudofunctors of 2-variables' consists of two families of pseufunctors

*

*Fix $A\in obj\mathcal{A}$, we have a pseudofunctor $f(A,-): \mathcal{B}\to \mathcal{C}$.

*Fix $B\in obj\mathcal{B}$, we have a psudofuncotr $f(-,B): \mathcal{A}\to \mathcal{C}$.

*$f(A,-)(B)=f(-,B)(A):=f(A,B)$ for all $A\in obj\mathcal{A}, B\in\mathcal{B}$.

*for all $\alpha: A\to A',\beta:B\to B'$, an invertible 2-cell $f(\alpha,\beta)$ between
$$
f(A,B)\xrightarrow{f(A, \beta)}f(A,B')\xrightarrow{f(\alpha,B')} f(A',B'),\\
f(F,B)\xrightarrow{f(\alpha, B)}f(A',B)\xrightarrow{f(A',\beta)}f(A',B').
$$
These two families and $f(\alpha,\beta)$ satisfy coherence conditions similar to that of quasi-functor of two variables introduced by Gray ("Adjointness for 2-Categories", page 56), but droping the first requirement on identities, which I shall not spell out here; see Gordon-Power-Street in "Coherence for tricategory", where it is called cubical functors (so remove the line "which is an identity when either $\alpha$ or $\beta$ is an identity).
Notice that if $\mathcal{A}=\mathcal{B}=*$, the trivial bicategory with one objects, one 1-cell, one 2-cell, then the above data should be equivalent to two monads in $\mathcal{C}$ on the same object satisfying a distributive law.
Question:
Does there exist a funny tensor product $\mathcal{A}\otimes \mathcal{B}$ such that the above data is the same as a single pseudofunctor $\mathcal{A}\otimes \mathcal{B}\to \mathcal{C}$? (Gray tensor product of bicategories?)


text:
Q: Integration of exponentials of quadratic forms (general Gaussian itegrals) over semi-finite domains Hi
I'm interested in evaluating the integral of $e^{-s^T A s + b s}$ over a semi-infinite domain. $A$ is $\binom{N}{2}$x$\binom{N}{2}$ and has $N-1$ eigenvalues equal to $N$, and the rest 0. In particular, how does one deal with the limits of integration under an orthogonal transformation of the variables?
Deepak


text:
Q: Iterate over a C++ container in C I am attempting to write a C wrapper for some C++ data structures. Right now I've got the following in foo.cpp
typedef std::map<unsigned int, void *> _Map;

extern "C"{
    void* map_create()
    {
        return reinterpret_cast<void*> (new _Map);
    }

    void map_put(void *map, unsigned int k, void *v)
    {
        Map *m = reinterpret_cast<_Map *> (map);
        m->insert(std::pair<unsigned int, void *>(k, v));
    }
}

In foo.h I've got
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void *Map;
EXTERNC void *map_create();
EXTERNC void map_put(void* map, unsigned int k, int v);

I include foo.h and I'm good to go.
Now, I wanted to iterate over a map and noticed C++ does that through iterators. I have no experience with C++ and don't know how iterators are implemented.
Can I iterate over a std::map using a C wrapper? How would these functions definitions look like and how would I use them in a for-loop in my C code?

A: You won't be able to use iterators directly. You can, of course, do something along the lines of creating/releasing objects and obtain the values somehow. It isn't going to be efficient, though. It would look something like this:
typedef std::map<unsigned int, void*> map_type;
typedef map_type::iterator            map_iterator;

void* map_iterator_create(void* map) {
    return new map_iterator(map.begin());
}
void  map_iterator_destroy(void* it) {
    delete static_cast<map_iterator*>(it);
}
int map_iterator_next(void* map, void* it, unsigned int* key, void** value) {
    map_iterator* mit = static_cast<map_iterator*>(it);
    if (static_cast<map_type*>(map)->end() == *mit) {
        return 0; // no more elements
    }

    *key   = mit->first;
    *value = mit->second;
    ++mit;
    return 1;
}

This particular approach does reduce the flexibility coming with iterators a bit (e.g., it doesn't support subranges) but these could be supported at different costs. You'd use this iterator approach like this:
void*        it = map_iterator_create(map);
unsigned int key;
void*        value;
while (map_iterator_next(map, it, &key, &value)) {
    printf("key=%d value=%p\n", key, value);
}
map_iterator_destory(it);

It is probably more reasonable to not expose the iterator interface but rather an interface iterating over the sequence, e.g.:
extern "C" { typedef void (*map_function)(unsigned int, void*, void*); }
void map_iterate(void* map, map_function fun, void* userdata) {
    map_type* m = static_cast<map_type*>(m);
    std::for_each(m->begin(), m->end(),
                  [=](map_type::value_type const& v) {
                      fun(v.first, v.second, userdata);
                  });
}

... which would be used as
void my_iterating_fun(unsigned int key, void* value, void* userdata) {
     printf("key=%d value=%p\n", key, value);
}
// ...
map_iterator(map, my_iterating_fun, 0);

I haven't tried to compile the code (i.e., it is probably riddled with small typos) but something along those lines should work.

A: Here's something that won't compile, but gives you an idea on how I'd do it
class MyIterator {
  public:
    MyIterator(Map map) {
      it = map.begin();
    }

    void advance() {
      ++it;
    }

    bool isValid() {
      return it != map.end();
    }
  private:
    Map::const_iterator it;
    const Map map;
};

extern "C" {
void* newIterator(void* map) {
  return new MyIterator(static_cast<Map>(map));
}
void freeIterator(void* it) {
  delete static_cast<Map>(map);
}
void advanceIterator(void* it) {
  static_cast<MyIterator>(it)->advance();
}
void isValid(void* it) {
  static_cast<MyIterator>(it)->isValid();
}

int getKey(void* iterator) {...}
void* getValue(void* iterator) {...}
}


text:
Q: Team Foundation Server / TEE Check-In To Folder I utilize Eclipse with Team Explorer Everywhere to connect to a Team Foundation Server, whose primary purpose is to serve as a repository for my PHP application.
Rather than running a build on check-in, I'd like to have TFS dump the latest copies of the files to a specified folder, without building.
Is this action possible?

A: You can modify the build template\script to just perform the copy operation.


text:
Q: Find the maximum and parent value in an array I searched many thread but i can't find this solution
I have this Array
Array
( [0] => [1] => Array ( [0] => 2019-01-11T23:30:00CET [1] => -12.6 ) [2] => [3] => Array ( [0] => 2019-01-11T23:20:00CET [1] => -12.5 ) [4] => [5] => Array ( [0] => 2019-01-11T23:10:00CET [1] => -12.6 ) [10] => [11] => Array ( [0] => 2019-01-11T22:40:00CET [1] => -12.4 )

I found the path to have the maximum or minimum value ( Column [1] ) from this Array but i need to find the relative Parent

(example the minimum -12.6 is in the [1][0] as 2019-01-11T22:20:00CET)
  of this two values that are show in the first column ( Column[0] )

Thanks

A: If you use array_column() to extract the second column of your data, then you can use min() or max() with that array to pick which one you want.  This code then extracts the ones that match using a foreach() and if to check if it matches (not exactly sure what you want as output, but this should help)...
$source = [["2019-01-11T23:30:00CET", -12.6],
    ["2019-01-11T23:20:00CET", -12.5],
    ["2019-01-11T23:10:00CET", -12.6]
];

$extract = min(array_column($source, 1));  // or use max()
$output = [];
foreach ($source as $key => $element) {
    if ( $element[1] == $extract )  {
        // Matches, so add to output
        $output[$key] = $element[0];
    }
}
print_r($output);

will give
Array
(
    [0] => 2019-01-11T23:30:00CET
    [2] => 2019-01-11T23:10:00CET
)

You could use array_filter() to extract the matching rows, but a foreach() is enough for a straightforward thing like this (IMHO).
If there is a possibility of blank values or strings in the value column, this may confuse the min() as it will consider the values and compare them as strings, to ensure they are all compared as numbers you can add...
$values = array_map("floatval", array_column($source, 1));
$extract = min($values);  // or use max()

The array_map("floatval",... goes through the list and converts them all to float values.

A: Also, here's a generalized algorithm-sketch for "finding the max in some array", expressed as pseudo-code:

*

*"Leave quietly" if the array is empty, or throw an exception.

*Otherwise, assume that the first element in the array is the biggest one.

*Now, loop through the remaining elements, testing if each one is, in fact, bigger than the "biggest one" that you have so far.  If so, select it as the "biggest."

*When the loop is finished, return your answer.

Now – this is what a geek would call "an O(n) algorithm," which is to say that its execution-time will be "on the order of" the number of elements in the array.  Well, if this is a "one-off" requirement, that's fine.  Whereas if what you actually want to do is to get "more than one" max-element, sorting the array (once, then holding on to the sorted result ...) becomes significantly better, because the sort is going to be O(log(n)) ... "on the order of some logarithm of the number of elements," ... and the subsequent cost of "popping off" elements from that sorted array becomes non-existent.
There are other ways to do it, of course – trees and such - but I've already blathered-on too long here.


text:
Q: How to setText and save it in EditText I have two EditText fields (suppose they are empty) and I will write the text there and it will be remembered there, in the sense that when I go out of the window and go back there will be text entered there. Thank you for your help :)
Button button1;
Button button2;
TextView devices;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.change_url);
    button1 = (Button) findViewById(R.id.button9);
    button2 = (Button) findViewById(R.id.button10);

    button2.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            TextView buildings = (TextView) findViewById(R.id.buildings);
            String a = buildings.getText().toString();
            buildings.setText(a);
        }
    });

}

A: As my point of view,
Store your value in shared preference and whenever you want this values get from shared preference and put in edit text.

A: When you go out of a activity and you want to recover data when you come back, you should override onSaveInstanceState(Bundle savedInstanceState). Inside this method you will need to save all the data you want to recover when you come back again in the Bundle.
As example for your case:
First:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is killed and restarted.
  savedInstanceState.putString("EditText1", mEditText1.getText().toString());
  savedInstanceState.putString("EditText2", mEditText2.getText().toString());
}

Then, to recover it you need to override onRestoreInstanceState(Bundle savedInstanceState) :
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  String text1 = savedInstanceState.getString("EditText1");
  String text2 = savedInstanceState.getString("EditText2");
  //At this point you recovered your data, so you can put in the EditText
  mEditText1.setText(text1);
  mEditText2.setText(text2);
}

More references at : https://developer.android.com/guide/components/activities/activity-lifecycle.html


text:
Q: Proof that parallelogram equals 2x2 determinant

I do not understand one sentence: "Figure 5.3b shows that the solid parallelogram areas add to the dotted parallelogram area (because the two triangles completed by the dotted lines are the same)."
Can someone help me understand this? I do not see that A + A' = area of the dotted parallelogram.

A: You can cut out the almost flat triangle at the bottom and paste it back at the top, it doesn't change the area to cut/paste and what you get is the dotted parallelogram.
Great picture by the way, very enlightening regarding the properties of the determinant.

A: The dotted parallelogram's area is the sum of areas of solid ones plus the area of the upper triangle minus the area of the lower triangle. Since the areas of the two triangles are the same, you get the result.


text:
Q: D3 Reactangle Bar with color gradient depending on value I am trying to build something as attached below but not able to figure out how to get it done using d3. I tried using x-axis for scale band and placing a rectangle on it but that doesn't seems to work as the axis and rectangle do not sync with the values. Can someone help me with the approach on how to get this done or some relevant examples maybe can be of good help.
The graph shows the revenue and the more good the numbers are the gradient of colors increases accordingly.

A: Here is a D3 example with x-axis and linear gradients:

const data = [2.3, 2.5, 3.4, 8.7, 7.8, 2.8, 2.2, 1.7];

// Create scale
const scale = d3.scaleLinear().domain([17, 20.5]).range([0, 400]);

const tickFormat = val => {
  const year = Math.floor(val);
  const quarter = val - year  === 0.5 ? 4 : 2;
  return `${quarter}Q ${year}`;
}

// Add scales to axis
const x_axis = d3.axisBottom().scale(scale).tickFormat(tickFormat);

const svg = d3.select('svg');

//Insert axis
svg.append("g").attr('transform', 'translate(50,100)').call(x_axis);

const step = 400 / (data.length - 1);

const valuesContainer = svg.append('g').attr('transform', 'translate(50,50)')

valuesContainer.selectAll('text.value')
  .data(data, (d, i) => i)
  .enter()
  .append('text')
  .classed('value', true)
  .text(d => `${d}%`)
  .attr('x', (d, i) => i * step)
  .attr('text-anchor', 'middle')
  .style('font-family', 'sans-serif')
  .style('font-size', '12px');

const ranges = data.slice(0, data.length - 1)
  .map((v, i) => ({from: v, to: data[i + 1]}));

const rangesContainer = svg.append('g')
  .attr('transform', 'translate(50,60)')

const gradients = svg.selectAll('linearGradient')
  .data(ranges, (d, i) => i)
  .enter()
  .append('linearGradient')
  .attr('id', (d, i) => `grad-${i}`)
  .attr('x1', '0%')
  .attr('x2', '100%')

gradients.append('stop')
  .attr('offset', '0%')
  .attr('stop-color', '#008')
  .attr('stop-opacity', d => d.from / 10);

gradients.append('stop')
  .attr('offset', '100%')
  .attr('stop-color', '#008')
  .attr('stop-opacity', d => d.to / 10);

rangesContainer.selectAll('rect.range')
  .data(ranges, (d, i) => i)
  .enter()
  .append('rect')
  .classed('range', true)
  .style('fill',(d, i) => `url(#grad-${i})`)
  .attr('x', (d, i) => i * step)
  .attr('width', step)
  .attr('height', 30)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="150">

</svg>


text:
Q: How to register a servlet in Spring Boot XML file? I wrote a servlet for a Spring Boot application. It worked when I used
contextHandler.addServlet(MyClass.class, "/v1/route");

Now I'm trying to register the servlet in beans.xml file as a bean. This one
<bean id="myId" class="com.abc.MyClass"/>

doesn't contain route. MyClass extends HttpServlet and overrides doGet method.
How to register a servlet which is also a bean?

A: This approach worked for me. It's a mix of declaration in XML and a fully programmatic registration.
In beans.xml file I've specified a constructor parameter which passed ServletContextHandler, like this:
<bean id="myId" class="com.abc.MyClass">
    <constructor-arg ref="servletContextHandler"/>
</bean>

In MyClass constructor I'm adding the servlet - together with route - to the servlet holder, thus registering it as servlet:
public MyClass(ServletContextHandler h) {
    h.addServlet(new ServletHolder(this), "/v1/route");
}

Surely this can interfere with other requirements, like the constructor may need other parameters, other initializations may be needed. But here I'm registering a bean in XML and registering servlet programmatically. May be the servlet registration can also be done without explicit Java code, I don't know how to do that.
xerx593, I've seen that page but those examples didn't look good enough for what I wanted. Thank you anyway.


text:
Q: Localhost Not Responding I Just Install Wamp Server and All are Ok. But when i Write localhost on my Browser it open but when i Click my Folder like Wordpress or Joomla it Give this Error

Internal Server Error
The server encountered an internal error or misconfiguration and was
  unable to complete your request.
Please contact the server administrator at admin@example.com to inform
  them of the time this error occurred, and the actions you performed
  just before this error.
More information about this error may be available in the server error
  log.

I really dont know What to Do now and i have too Much Problem

A: Installation of joomla (doc of 2.5) : your site will be accessed at yoursite.com/Joomla instead of yoursite.com.
With wordpress
1 - Delete .htaccess and keep htaccess.txt.
2 - Global Configuration/SEO Settings, value of  Search Engine Friend URLs => No


text:
Q: Extract text before third - "Dash" in SQL Can you please help to get this code for SQL?
I have column name INFO_01 which contain info like:
D10-52247-479-245 HALL SO
and I would like to extract only
D10-52247-479
I want the part of the text before the third "-" dash.

A: You'll need to get the position of the third dash (using instr) and then use substr to get the necessary part of the string.
with temp as (
    select 'D10-52247-479-245 HALL SO' test_string from dual)
select test_string,
       instr(test_string,1,3) third_dash,
       substr(test_string,1,instr(test_string,1,3)-1) result
  from temp
);

A: Here is a simple statement that should work:
SELECT SUBSTR(column, 1, INSTR(column,'-',1,3) ) FROM table;

A: I'm assuming MySQL, let me know if I'm wrong here. But using SUBSTRING_INDEX you could do the following:
SELECT SUBSTRING_INDEX(column, '-', 3)

EDIT
Appears to be oracle. Looks like we may have to resort to REGEXP_SUBSTR
SELECT REGEXP_SUBSTR(column, '^((?.*\-){2}[^\-]*)')

Can't test, so not sure what kind of result that will have...

A: Using a combination of SUBSTR and INSTR will return what you want:
SELECT SUBSTR('D10-52247-479-245', 0, INSTR('D10-52247-479-245', '-', -1, 1)-1) AS output
  FROM DUAL

Result:
output
-------------
D10-52247-479

Use:
SELECT SUBSTR(t.column, 0, INSTR(t.column, '-', -1, 1)-1) AS output
  FROM YOUR_TABLE t

Reference:

*

*SUBSTR

*INSTR
Addendum
If using Oracle10g+, you can use regex via REGEXP_SUBSTR.


text:
Q: Register value not getting updated properly I have written the following assembly language program to determine if the value in al is a digit
INCLUDE Irvine32.inc
.data
randVal DWORD ?
.code

main PROC

IsDigit PROC
cmp al,'0'
jb ID1
cmp al,'9'
ja ID1
test ax,0
ID1: ret
IsDigit ENDP

mov al, 'x'
call IsDigit
mov bl , 'y'
main ENDP
END main

Here is what I see in debugging mode in registers. As I have put x into al. x = 120 in ASCII = 78.
I expected to see 78 in AL. But that's not the case :
enter image description here
I have defined a proc called IsDigit and then call it using call IsDigit. Is that a correct
way to call an assembly language function. Also I see only the main registers in the registers window
Is there a way to see all flags too in visual studio


text:
Q: Force induced in a coil by a moving magnet So a magnet moves towards one end of a coil. A pole is induced in this end of the coil that opposes the pole of the magnet moving towards it (e.g. south pole induced to oppose the north pole of the moving magnet).
Now my question is, which direction would the coil move (if it were to)?
North-South should result in attraction, right?

A: First of all, if the north pole of the magnet is brought closer to the coil, anticlockwise current will develop in the coil as seen from the magnet side. This corresponds to North pole on the coil and not South pole. So essentially there will be repulsion.


text:
Q: SequelizeDatabaseError after deplying nodejs app to heroku I have an ecommerce app written in nodejs. I recently deploy my app to heroku..Here are the configurations:

Development mode:

database: mysql

Production Mode

database: postgresql add-on

Deploy done successfully and I've run heroku run bash command followed by sequelize -m commmand..After that I've done db:migrate and all the migrations were successfully done.but when I try to search the routes, I am getting an error on many routes.but there is a similarity on every routes.
for example: Here is the response I am getting on creating user routes.
  "name": "SequelizeDatabaseError",
  "parent": {
    "name": "error",
    "length": 105,
    "severity": "ERROR",
    "code": "42703",
    "position": "47",
    "file": "parse_relation.c",
    "line": "3294",
    "routine": "errorMissingColumn",
    "sql": "SELECT \"id\", \"username\", \"email\", \"password\", \"image\", \"createdAt\", \"updatedAt\" FROM \"Users\" AS \"User\" WHERE \"User\".\"email\" = 'developerstackbase@gmail.com' LIMIT 1;"
  },
  "original": {
    "name": "error",
    "length": 105,
    "severity": "ERROR",
    "code": "42703",
    "position": "47",
    "file": "parse_relation.c",
    "line": "3294",
    "routine": "errorMissingColumn",
    "sql": "SELECT \"id\", \"username\", \"email\", \"password\", \"image\", \"createdAt\", \"updatedAt\" FROM \"Users\" AS \"User\" WHERE \"User\".\"email\" = 'developerstackbase@gmail.com' LIMIT 1;"
  },
  "sql": "SELECT \"id\", \"username\", \"email\", \"password\", \"image\", \"createdAt\", \"updatedAt\" FROM \"Users\" AS \"User\" WHERE \"User\".\"email\" = 'developerstackbase@gmail.com' LIMIT 1;"
}

A: Can you please use same database for both environments and update if it is working on your local.


text:
Q: Excetpion handling in c++/cli Actually i am working on c++/CLI dll which is using C# dll and c++/cli dll will use from native c.
c++/cli code is like:-
public ref class Class1
{
    // TODO: Add your methods for this class here.
public:
     static Managed_EMV_DLL::Managed_EMV ^obj = gcnew Managed_EMV(); // object of c#   class
     bool INIT_READER(unsigned int *);
     bool READ_KEY(unsigned int *ERROR_CODE,unsigned char *RETURN_ARRAY, unsigned int *Array_LENGTH);

};

-i want to handle the exception in c++/CLI code,
-handle exception when c# dll not found.
how i can make it.

A: What is the exact problem you're facing .... See the below example format.
try
 {
 }
catch(FormatException ^) // display an appropriate message
 {
   Console::WriteLine(L"You must enter a valid number "
                               L"and no other character!");
 }

Just sort out what exception could be thrown from C# dll and then put appropriate handles in your C++/CLI code.

A: I want to handle any kind of exception not only FormatException or TypeInitializationException.
Here i write code like:-
try
{

}
catch (Exception^ ex)
{
Console::WriteLine("Error in C++/CLI INIT function: {0}", ex->ToString());
}
catch (...)
{
      Console::WriteLine("Error in INIT");
}

and it works good.... i hope it will catch any kind of exception...


text:
Q: how to create a drag and drop function in html 5? hi im stuck with making a drag and drop function in html5.i tested the code on chrome and when i try to drop it in the area where i made it for dropping the code
it shows a stop sign as arrow. i actually made a bordered section box in which i have some text that i want to be changed when i  drop my image  in it.
this is my js code:
function doFirst(){
pic = document.getElementById('pic1');
pic.addEventListener("dragstart", startDrag , false);
left = document.getElementById('left1');
left.addEventListener("dragenter", function(e){e.preventDefault();}, false);
left.addEventListener("dragover", function(e){e.preventDefault();} , false);
left.addEventListener("drop", dropped , false);
}

function startDrag(e){
   var code = '';
   e.dataTransfer.setData('hello', code);
}

function dropped(e) {
    e.preventDefault();
    left.innerHTML = e.dataTransfer.getData('hello');
}

window.addEventListener("load", doFirst , false);

A: First, a piece of advice: learn how to debug and use the developer's tools (specially the console) provided by the modern browsers (or use Firebug/Web development extensions if you prefer).
Had you checked the console, then you'd have seen that the code throws a JS error ("Syntax error: Unexpected token") and you'd know where in the code that error was. In particular, on this line:
var code = '';

If you search online, you'll see that "javascript strings must be terminated before the next newline character" (from Andrew Dunn's answer to this question). And once that error is fixed:
var code = '';

the rest of your code works fine, as you can see on this JSFiddle (I added real URLs to the pictures so you could see the effect working).

A: try with this code:
<!DOCTYPE HTML>

Font: http://www.w3schools.com/html/html5_draganddrop.asp


text:
Q: What is a single word/phrase that can be used in place of 'mistaken assumption' or 'incorrect belief'? What is a suitable word that can be used in the below story scenario?
I've considered the following words; Delusion, Conjecture, Fallacy, Belief, Erroneous assumption. Is there a better word anyone can suggest?

In a small village there was a girl afflicted with a mortal disease. The medicine to which was expensive and could only be obtained from a doctor who lived seven days journey away.
Her family had the money, but no one to make the perilous journey.
A man, her lover volunteered, and promised to return with the medicine. He got the medicine, but on the way back was mauled by a bear and succumbed to his injuries.
His absence caused the village folk to gossip that he had taken the money and ran away.
The girl's condition worsened, and at soon she passed away under the (mistaken assumption/incorrect belief) that the man had tricked her and ran off.


text:
Q: Use WebClient, DownloadData method and Custom Header to Post to a web page ** Update I have a solution below, but it's rather manual... if there is an easier way, I'd prefer that answer.
I want to record execution and download time of a webpage, and I am trying to use the WebClient.DownloadDataAsync method to post data to a page and get a result.
I know there are numerous ways to post using WebClient or WebRequest objects, but none of them dispatch the DownloadProgressChanged event. This event is key, as I want to track progress of the download, which is in the area of 30 megs+.
I figure the best way to do this would be to construct the header manually, but I'm hitting a dead-ends. Mainly, I cannot add the data to the request.
WebClient client = new WebClient();
//!!!!*****no idea how to add the following data to the request
string data = "test1=value";
client.Headers.Add( "POST", "/About.aspx HTTP/1.1" );
client.Headers.Add( "Host", "http://localhost:12065" );
client.Headers.Add( "Content-Type", "application/x-www-form-urlencoded" );
client.Headers.Add( "Content-length", data.Length.ToString() );

client.DownloadProgressChanged += OnDownloadProgressChanged;
client.DownloadDataCompleted += OnDownloadDataCompleted;
client.DownloadDataAsync( new Uri( "http://localhost:12065/About.aspx" ) );

I am open to other solutions, or getting the header in this example to work as if the client is sending a POST.

A: OK... well I figured out a way to do this using WebRequest. It's a little more complicated, but it does the trick. I am surprised that WebClient doesn't do this already, but it seems as though WebClient has a number of unexpected issues.
//Using System.Diagnostics, set up a Stopwatch to time the execution
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

//convert your post data into a byte array... we're dealing with streams here
byte[] postData = Encoding.ASCII.GetBytes( postData );

//We're using the WebRequest object found in System.Net to do our work for us
WebRequest request = WebRequest.Create( url );

//Set all your headers
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.ContentLength = postData.Length;

//set up your request stream and write out your post data
Stream stream = request.GetRequestStream();
stream.Write( postData, 0, postData.Length );
stream.Close();

//Send the data and wait for a response. [blocking operation]
WebResponse response = request.GetResponse();

//Once you reach this line, the server has finished doing it's work,
//and downloading has commenced
Console.WriteLine( "First Response: {0}", stopWatch.Elapsed );

//Start timing the download, wouldn't it be nice is there was a restart method? (.Net 4.0)
stopWatch.Reset();
stopWatch.Start();

//We want to receive the data. so ask for the response stream
Stream reponseStream = response.GetResponseStream();

//In my case, there are megabytes of information, so the console is no good,
//I'll store it in a file.
FileStream fileStream = File.Open( "result.txt", FileMode.OpenOrCreate );

//create a buffer to collect data as it is downloaded
byte[] buffer = new byte[1024];

//This loop will run as long as the responseStream can read data. (i.e. downloading data)
//Once it reads 0... the downloading has completed
int resultLength;
while( ( resultLength = reponseStream.Read( buffer, 0, buffer.Length ) ) != 0 )
{
    //You could further measure progress here... but I don't care.
    fileStream.Write( buffer, 0, resultLength );
}

//Everything is done... how long did it take to download?
Console.WriteLine( "Download Complete: {0}", stopWatch.Elapsed );

//housekeeping
fileStream.Flush();
fileStream.Close();
stopWatch.Stop();


text:
Q: Prove the following property of a measure: $\mu ((0,x]) = cx.$ Let $\mu :\mathcal{B}(\mathbb{R}) \to [0,\infty]$ be a measure such that for all $h\in \mathbb{R}$ and $A\in \mathcal{B}(\mathbb{R})$, $\mu(A+h) = \mu(A)$. Let $c= \mu((0,1])$.
I want to prove the property that $\mu((0,x]) = cx$ for any $x\geq 0$.
I have already proven that $\forall x\geq 0, \forall q\in\mathbb{N}: \mu((0,qx]) = q\mu((0,x])$.
As well as $\forall p,q\in \mathbb{N}: \mu((0,\frac{p}{q}]) = c\frac{p}{q}$.
However now I'm stuck. I know that $\mu$ is a measure and therefore $\sigma$-additive, however I am not quite sure how to use this because $x$ is now a real number instead of an integer or a fraction.