text:
Q: Unable to install AWS CLI on a Mac I am unable to install AWS CLI on MacBook Yosemite.
I get an error with the sudo command from AWS Documentation.
I initially installed sudo using the default python2.7, and then tried to install with python3.7 but it doesn't work. I feel it's the folder path that is incorrect but I don't know what to check on it.
Can I get some guidance?
Here is the error output:
MacBks-MBP:~ MacBkyosemite$ sudo /usr/local/bin/python3.7 awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
Password:
Running cmd: /usr/local/bin/python3.7 virtualenv.py --no-download --python /usr/local/bin/python3.7 /usr/local/aws
Running cmd: /usr/local/aws/bin/pip install --no-cache-dir --no-index --find-links file:///Users/MacBkyosemite/awscli-bundle/packages/setup setuptools_scm-1.15.7.tar.gz
Traceback (most recent call last):
  File "awscli-bundle/install", line 162, in <module>
    main()
  File "awscli-bundle/install", line 151, in main
    pip_install_packages(opts.install_dir)
  File "awscli-bundle/install", line 114, in pip_install_packages
    pip_script, setup_requires_dir, package
  File "awscli-bundle/install", line 49, in run
    p.returncode, cmd, stdout + stderr))
__main__.BadRCError: Bad rc (1) for cmd '/usr/local/aws/bin/pip install --no-cache-dir --no-index --find-links file:///Users/MacBkyosemite/awscli-bundle/packages/setup setuptools_scm-1.15.7.tar.gz': b'Traceback (most recent call last):\n  File "/usr/local/aws/bin/pip", line 7, in <module>\n    from pip import main\nImportError: cannot import name \'main\' from \'pip\' (/Users/MacBkyosemite/Library/Python/3.7/lib/python/site-packages/pip/__init__.py)\n'

MacBks-MBP:~ MacBkyosemite$ python3 --version
Python 3.7.3

MacBks-MBP:~ MacBkyosemite$ pip3 --version
pip 19.1.1 from /Users/MacBkyosemite/Library/Python/3.7/lib/python/site-packages/pip (python 3.7)

MacBks-MBP:~ MacBkyosemite$ which python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3

A: To install the AWS Command Line Interface on a Mac, simply run:
sudo pip3 install awscli

Tip: It is normally a good idea to use virtual environments when installing Python libraries to avoid conflicts. In such cases, start a virtual environment, then run pip.


text:
Q: Django rest framework custom Response middleware I use Django Rest Framework with rest_auth (/login, /logout/, /register...)
I have a Middleware, normally triggered by user_logged_in or user_logged_out signals.
In my Middleware, I want to use Response object from Rest framework.
My middleware.py
from django.contrib.sessions.models import Session
from django.contrib.auth import logout
from django.contrib.auth.models import AnonymousUser
from rest_framework.response import Response
from rest_framework import status

class OneSessionPerUserMiddleware:
    def __init__(self, get_response):

        self.get_response = get_response

    def __call__(self, request):

        if request.user.is_authenticated:
            if request.user.session_key != Session.objects.filter(session_key__in = request.user.session_key):
                logout(request)
                return Response(request)
        return self.get_response(request)

I suppose that I pass my condition,  but I get this error :
 The response content must be rendered before it can be accessed

How to use correctly the API Response object in a middleware ?
And I don't understand really what is : self.get_response = get_response ?

A: return Response(request) is not something django can handle. Ps you are passing request object to Response what does that mean?
Actually Request and Response classes from rest framework are not compatible with django. rest framework wraps WSGIRequest (django's builtin) with Request object in APIView and after getting Response object from view, it creates HttpResponse object by unwrapping it. So Response object can only be used in rest framework views. You can use JsonResponse from django.http in middleware like this
from django.http import JsonResponse

if request.user.is_authenticated:
    if request.user.session_key != Session.objects.filter(session_key__in = request.user.session_key):
        logout(request)
        return JsonResponse({'logout': True}) # or whatever data you want to return
return self.get_response(request)

A: First of all: if you are using something other than rest_framework.authentication.SessionAuthentication as an authentication_class, then request.user is set outside of middlewares (somewhere during View.dispatch)
If you are sure that request.user is always corresponding to request.user inside rest_framework views and just want to return a response:
A. Look at the APIView.finalize_response: it's relatively "complex" because it can use different renderers (depending on accept-content request header), it may change headers. If you can access instance of your view in the middleware, then you can call view.finalize_response(request, response), if you don't have it then you can try doing rest_framework.views.APIView().finalize_response(...)
B. You can use django.http.HttpResponse: manually generate string for body, and specify appropriate content_type. And django.http.JsonResponse may be handy too.
C. I assumed that instead of return Response(request) you really are doing something else (like Response(data=...)). If you just need to return results from view, then remove return Response(request), so that return self.get_response(request) kicks in. But you are making a logout, so maybe you should return some instance of django.http.HttpResponseRedirect

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write this MySQL Query? Suppose I have a table that has three integer fields and one string field (just data).
For example it looks like:
Id      Category    Value   Data
1       1           3       ...
2       1           4       ...
3       2           2       ...
4       2           4       ...
5       3           5       ...
6       3           6       ...
7       3           2       ...
8       4           1       ...

What I want to do is for each Category, include the row with the minimum Value field in the result set. In this case, it would return:
Id      Category    Value   Data
1       1           3       ...
3       2           2       ...
7       3           2       ...
8       4           1       ...

How to write such a query?
Thanks!

A: select T1.Id,
       T1.Category,
       T1.Value,
       T1.Data
from YourTable as T1
  inner join (
               select Category,
                      min(Value) as Value
               from YourTable
               group by Category
             ) as T2
    on T1.Category = T2.Category and
       T1.Value = T2.Value

A: select *
from mytable t
join (select category, min(value) as value from mytable group by 1) x
    on t.value = x.value and t.category = x.category

The inner select gets the categories and values needed for the final result, then you join back to the main table to get all the columns.

A: SELECT category, MIN(value) as Value
FROM table
GROUP BY category

Use the MIN function and GROUP BY the results on the Category column.


text:
Q: Javascript function call with )( In JavaScript I have a function, for example:
function foo() {}

I can call it like this:
foo()

Or like this:
foo)(

Why does thesecond approach work? I don't get any errors. Is this a node.js bug? I tested on ubuntu terminal - node v0.10.37. In Chrome console second approach doesn't work.


text:
Q: How to stabilize adc output display on 7 segment I am designing a simple voltmeter. I am using 8 bit ADC of PIC16F72 and Mikro C compiler with a multiplexed 7 segment display. I am getting ADC value on 7 segment display but its continuously fluctuating (for example 1670mV fluctuates in between 1660 & 1680mV). I have tried everything in hardware, adding a cap on ADC and ground etc.
Here is my code:
void StabilizeVoltage()
{
     unsigned int ADS;
     if (flgAC)
      {
      ADS = ADC_Get_Sample(0);
      Voltage_FLOAT =(float)ADS *19.6078431372549;
      a= Voltage_FLOAT;
      Voltage_INT=a;
      //if(63<Voltage_INT && Voltage_INT<78 )
       if(Voltage_INT <=1050 )
      {
      Relay1=0;
      Relay2=0;
      Relay3=0;
      Relay4=0;
      }
      else if (1050<Voltage_INT && Voltage_INT<=1150)
      {
      Relay1=1;
      Relay2=0;
      Relay3=0;
      Relay4=0;
      }
      else if (1150<Voltage_INT && Voltage_INT<=1350)
      {
      Relay1=1;
      Relay3=1;
      Relay2=0;
      Relay4=0;
      }
      else if (1350<Voltage_INT && Voltage_INT<=1450)
      {
      Relay1=1;
      Relay3=1;
      Relay2=1;
      Relay4=0;
      }
      else if (1450<Voltage_INT )
      {
      Relay1=1;
      Relay3=1;
      Relay2=1;
      Relay4=1;
      }
      }
      flgAC = 1;
}
void main()
{
      InitIO();
      ADC_Init();
      InitTimer2();
      InitDisplay();
     while(1)
     {
         UpdateDisplay();
         StabilizeVoltage();
     }
}

Do I need any software filter ??

A: One possible software solution is the very simple to implement exponential moving average (http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average). It only requires one global variable and a few lines of code. It is a little more work to accomplish but this can also be done with fixed point code (ie. int) for much greater efficiency (I wouldn't worry about it if all your doing is reading an ADC and displaying it).
For example:
//K is the filter coefficient and must be smaller than 1 and greater than zero (0<K<1)
//The smaller the K is, the more the filter will smooth, but it will also take longer
//to reach its value when the input changes.
#define K 0.01f

float filter( float aData )
{
    static float memory;
    memory = memory*(1-K) + aData*K;
    return memory;
}

A: You're seeing dithering of that least-significant bit as it tries to decide whether to be a 1 or a 0; it's something you'll need to deal with by scaling the input to the ADC, unless you can ignore the display fluctuation.
That last bit will always dither a little unless it's measuring voltages that're VERY stable and it's not picking up ANY noise from outside sources. You may get it a bit quieter if you can lower your input impedance, if the dithering is the result of outside noise. Any time the voltage you measure isn't stable within 1.2%, you'll see that sort of dithering in the least-significant bit, though.
At 1670mv, your ADC is giving you data=85 +- 1. Multiplied by your ~19.6, data of 84 = 1646.4 (1646), data of 85 = 1666, and data of 86 = 1685.6 (1686), so you'll see anything from 1646 to 1686 depending upon whether your least-significant bit chooses 1 or 0.
Scale the input to the ADC with an opamp with a gain of 19.6, and you can do away with your software multiplication & read direct voltages... AND your dithering should be alleviated.


text:
Q: MySQL data recovery (innoDB) - missing .frm files but intact ibdata A recent server fiasco left me with a by-all-appearances intact ibdata file but only half of my .frm-containing directories. I've copied all of this to a fresh mysql install, and have successfully recovered the databases which I still had .frm files for. My question is - is it possible to regenerate the .frm files from the ibdata file somehow? Or somehow modify the .frm files from the development version of the same database such that they can be used for recovery?
Restoring from backup, sadly, is not a viable option.
Edited to clarify: I've tried to recover the databases using locally generated .frm files containing the same schema - no dice, even at innodb_force_recovery = 1.

A: I've never actually done this but your question relates to the tools I use so I was curious!  It looks like this is actually possible, here is an example:
http://www.chriscalender.com/?p=28

Sometime you may need to recover a table when all you have is the .ibd
file. In this case, if you try to load it into a new instance, your
likely to encounter some errors about the table id not matching. And
there is not really a way around this.
However, I've found two work-arounds for this:
Note: You will need the .ibd file and the CREATE TABLE statement for
each table you want to recover using these methods.

*

*Simulate the
internal InnoDB table counter. That is, create work tables (with
innodb_file_per_table enabled) until you have the internal pointer of
table id equal to (1 – id_of_ibd_table_you_need_to_restore). (See
Method #1)

*Manually hex edit the .ibd file, changing the table id.
(See Method #2)

The steps themselves are several pages long so I haven't pasted them here.
Another related post: http://www.mysqlperformanceblog.com/2011/05/13/connecting-orphaned-ibd-files/
I'll be curious to hear if that works, it looks like multiple people have used it successfully.


text:
Q: How to make row of images resize and fit one row on mobile? Kind of a dumb question but I can figure it out. I'm working on my portfolio site and I have icons of software languages that I excel in (bootstrap is supposed to be one of them).
I just want these images to display in a single row, and resize based on the screen size.
Here's some code that I've been trying:

Here's how it looks on mobile:

A: img {
  display: inline-block !important;
  max-width: 12% !important;
}

Border-box includes the padding and borders in the width and the 14.28% * 7 images = 99.96% of the width. You could also use:

*

*14.285% * 7 images = 99.995%

*14.2857%* 7 images = 99.9999%

*14.285714285714285714285714285714% * 7 images = 99.999999999999...%

A: With Bootstrap, you need to use multiple col-*-* classes on your div in order to achieve such result.
The purpose of those classes are to provide you different presentations based on the size of your screen (and furthermore, the presentation on each device - following the responsive design principle).
You can find more information on this interesting article, and this one too.
As Chris Happy pointed out, this can be achieved using percentages in CSS. But this is what also Bootstrap does in behind, so you don't have to reinvent the wheel.

A: By looking at your code, you wrapped the whole page in one div container. It is really important when using bootstrap that you use div container to every different section of your page. So for example before 'row' use another container (try the fluid one if the normal one doesn't work). And don't forget to close the divs in the right place to differentiate your sections properly!
Bootstrap is a grid system so you have to structure your page in sections.


text:
Q: How would I use a JButton to change a JLabel with every click of a button? I need to start off with a JLabel, for example a JLabel that reads,"Old Text". With a button click, I want to update that JLabel to, "Updated Text". I am able to do this with the code I posted below, but my issue is I want to be able to click the button again to go back to "Old Text" and so on. Basically, I need the button to allow me to alternate between those two texts but I can't get that to work.
// this doesn't switch back to "Old Code"

public void actionPerformed(ActionEvent event) {
    if(event.getSource() == jbutton)
        jlabel.setText("Updated Text");

    if(event.getSource() == jbutton)
        jlabel.setText("Old Text");

}

This works but isn't what I fully need because it only changes the JLabel once.
public void actionPerformed(ActionEvent event) {
    if(event.getSource() == jbutton)
        jlabel.setText("Updated Text");
}

A: The reason your code isn't work is, both if statements evaluate to true, so both get executed
There are several ways you might do this, probably the simplest is just to inspect the state of the text of the label and make some decision about what to do, for example...
public void actionPerformed(ActionEvent event) { if(event.getSource() == jbutton) jlabel.setText("Updated Text");

    if(event.getSource() == jbutton) {
        if (!jlabel.getText().equals("Old Text")) {
            jlabel.setText("Old Text");
        } else {
            jlabel.setText("Updated text");
        }
    }

}

Now, if you wanted to be "really" fancy, you could use a little bit of modular maths...
private int trigger = 0;
@Override
public void actionPerformed(ActionEvent e) {
    trigger++;
    if ((trigger % 2) == 0) {
        label.setText("Old text");
    } else {
        label.setText("Updated text");
    }
}


text:
Q: cakephp pagination sort descending first By default when you click on the sort field in pagination it will sort ascending first, is there a way to set it to descending first?
<?php echo $this->Paginator->sort('Views', 'views'); ?>

I want my users to see most viewed first after clicking on view sort not least viewed.

A: To set the default sort direction to be descending, change your code above to this:
<?php echo $this->Paginator->sort('Views', 'views, array('direction' => 'desc')); ?>

Once activated, the sort direction will toggle between descending and ascending as usual.


text:
Q: Get Vimeo Upload Progress in AJAX / PHP I'm trying to combine the Vimeo PHP library (http://github.com/vimeo/vimeo-php-lib/blob/master/vimeo.php) with the BlueImp's jQuery File Uploader (https://github.com/blueimp/jQuery-File-Upload). My problem is getting a progress event during the upload process, is this possible? here's the temporary page i'm uploading from (video upload is temporarily hard coded)
<?php if($_SESSION['ticket']){
  //check upload status
}
?>
<button id="btn">Upload to vimeo</button>

the Vimeo Upload API (https://developer.vimeo.com/apis/advanced/upload) states that I can check the status of an upload either via streaming (https://developer.vimeo.com/apis/advanced/upload#streaming-step4) or post (https://developer.vimeo.com/apis/advanced/upload#post-step4)
i can see that the vimeo api uses the post method, but my problem is when/where to return the progress to the browser. if i use the method above (setInterval) then I don't know how to get the ticket id and/or the endpoint from the initial ajax call into the checkUpload javascript function. I thought I could do this via session variables in PHP but I can't get the page to reload (to display the session variables set in the remote file) until the upload has completed
i modified 'vimeo.php' around line 413 with the following:
//store ticket id to session variable so we can check upload status, or resume progress indicator if page is reloaded (doesn't work if browser is closed)
session_start();
$_SESSION['ticket']=$ticket;
$_SESSION['endpoint']=$endpoint;

and around line 500 with the following:
// Confirmation successful, return video id
if ($complete->stat == 'ok') {
//upload was successful, we do not need to store this variable to check progress anymore
unset($_SESSION['ticket']);
unset($_SESSION['endpoint']);
$_SESSION['last_upload'] = 'http://vimeo.com/'.$complete->ticket->video_id;
return $complete->ticket->video_id;
}

any ideas?


text:
Q: Cannot Destroy Dynamically created Menu Item in Delphi Firstly, yes I have looked all over the net and still cannot seem to destroy dynamically created menu items.  Using Delphi XE. I create the items thus (for the purposes of the exercise SubMenuName is 'Test1':
MenuItemCreated := TMenuItem.Create(PopupMenu1);
MenuItemCreated.Caption:= SubMenuCaption
MenuItemCreated.Hint := SubMenuHint;
MenuItemCreated.Name := SubMenuName;
MenuItemCreated.OnClick :=  SubMenuClick;
MenuItemCreated.AutoHotkeys := maManual;
MySubMenu.Add(MenuItemCreated);

There is no issue using the sub-menu(s) created. The procedure SubMenuClick works as it should, and I identify the correct subMenu item so no issues there. What I then do is an application logout which is supposed to free the dynamically created sub-menus using this code (although I have tried many variations):
  // Get rid of the menu items created
  While MySubMenu.Count > 0 do
  begin
    Itemtodelete := MySubMenu.Items[0];
    FreeandNil(ItemtoDelete);
  end;

I have put in showmessage() debug lines that show the component names of the menu items being freeandnil'd and they are what I'd expect, ie. 'Test1' and any others I've created. I then log back in to my application (which was still running, but with me logged out).  The software then tries to recreate the same sub menus with the same names (as nothing has changed as far as my application is concerned and they were previously disposed of (supposedly)).  I immediately get the exception raised:
Error: A component Named Test1 already exists
I am at a complete loss as to how to dispose of the submenu items so that I can recreate them later with the same names.
Any help greatly appreciated.
Thanks,
KB

A: You did not say it, so I have to assume that MySubMenu is a MenuItem of PopupMenu1. If not please clarify.
To delete items from MySubMenu in order to recreate them again later, it's easyest to call the Clear method:
procedure TForm5.Button2Click(Sender: TObject);
begin
  MySubMenu.Clear;
end;

which deletes all menu items of MySubMenu and frees their memory.
In order to recreate the items later, you can not use Delete() or Remove(), without also freeing the memory because they do not free the memory of the items. This is documented in help:
http://docwiki.embarcadero.com/Libraries/XE7/en/Vcl.Menus.TMenuItem.Delete
http://docwiki.embarcadero.com/Libraries/XE7/en/Vcl.Menus.TMenuItem.Remove
With these methods you must free the memory yourself, before you recreate the menu items. But then, it's not necessary to even call Delete or Remove, you can just simply Free the items:
procedure TForm5.Button2Click(Sender: TObject);
var
  mi: TMenuItem;
begin
  while MySubMenu.Count > 0 do
  begin
    mi := MySubMenu.Items[0];
    mi.Free;
  end;
end;

There's no need to call FreeAndNil.
This last option looks very much as yours, with which you had problems when recreating the menu items. I can't reproduce the error except when using Delete() or Remove() without freeing.

A: Since the Popup menu owns the items, you do not Free it. Instead of FreeAndNil use MySubMenu.Delete(0) OR more appropriately MySubMenu.Items.Clear instead of the entire While routine.
On App shutdown the popup menu will clear it, there's no need to do it manually unless you're rebuilding the menu.


text:
Q: C# FileSystemWatcher Copy folder complete I am using FileSystemWatcher to monitor a folder that will be used to do some file renaming.
The only thing that will be copied will be folders containing files.  There will not be single files put into the monitored folder.  This is the code for setting up the FileSystemWatcher
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName;
watcher.IncludeSubdirectories = true;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
watcher.EnableRaisingEvents = true;

There doesn't seem to be any issues with this setup..
The folders being copied can be between 50-200mb big.  Is there a way to check/make sure that all the files have completed copying before starting the renaming process.
I tried this thinking that i would get an IOException if the copying was still happening when the GetFiles() was called.
bool finishedCopying = false;
while (!finishedCopying)
{
    try
    {
        List<FileInfo> fileList = directoryInfo.GetFiles().ToList();
        AlbumSearch newAlbum = new AlbumSearch(directoryInfo);
        return newAlbum;
    }
    catch (IOException)
    {
        finishedCopying = false;
    }
}

If anymore information is required, just ask an i can provide.
Ta.

A: I gave this a go using a timer.  It may not be the prettiest solution out there but at first testing it seems to be working so far.  Essentially what this does is when a folder is copied to the monitored folder it will add the folder path to the AlbumList.  The files in that folder will trigger the Created event.  This waits for the file to finish copying.  Once finished it starts a timer.  If a new Created event gets triggered the timer will reset itself.
When the timer.elapsed event is triggered it assumes (and I know assumption is the mother of all f*&k ups) that there are no more files to be copied and can start to process the fully copied folder..
System.Timers.Timer eventTimer = new System.Timers.Timer();
List<string> AlbumList = new List<string>();

private void watcher_Created(object sender, FileSystemEventArgs e)
{
    if (Directory.Exists(e.FullPath))
    {
        AlbumList.Add(e.FullPath);
    }

    if (File.Exists(e.FullPath))
    {
        eventTimer.Stop();
        FileInfo newTrack = new FileInfo(e.FullPath);
        while (IsFileLocked(newTrack))
        {
            // File is locked. Do Nothing..
        }
        eventTimer.Start();
    }
}

private void eventTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    List<string> ItemToRemove = new List<string>();
    foreach (var item in AlbumList)
    {
        DirectoryInfo di = new DirectoryInfo(item);
        AlbumSearch newAlbum = new AlbumSearch(di);

        if (DoSomethingMethod(newAlbum))
        {
            ItemToRemove.Add(item);
        }
        else
        {
            // why did it fail
        }
    }

    foreach (var path in ItemToRemove)
    {
        AlbumList.Remove(path);
    }
}

private bool DoSomethingMethod(AlbumSearch as)
{
    // Do stuff here
    return true;
}

A: This is a small demo app that check files at the beginning, and then uses two hashsets to track copied files. This will only work if the source directory is known. There is no way to know if a file was created from a file copy or from a direct creation, so you can only compare two known directories with Directory.GetFiles. And, as already said in comments, you will still have to check if during the copy process, other files were added / removed /  renamed in the old directory
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static HashSet<string> oldDirFiles = new HashSet<string>();
        static HashSet<string> newDirFiles = new HashSet<string>();

        static string oldDir = "C:\\New Folder";
        static string newDir = "C:\\New Folder 2";

        static System.Threading.ManualResetEvent resetEvent = new System.Threading.ManualResetEvent(false);

        static void Main(string[] args)
        {
            System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher();
            watcher.Path = newDir;
            watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName;
            watcher.IncludeSubdirectories = true;
            watcher.Filter = "*.*";
            watcher.Created += watcher_Created;
            watcher.Changed += watcher_Changed;
            watcher.Renamed += watcher_Renamed;
            watcher.EnableRaisingEvents = true;

            //get all files in old directory
            var oldFiles = Directory.GetFiles(oldDir, "*.*", SearchOption.AllDirectories);
            foreach (var file in oldFiles)
                oldDirFiles.Add(file);

            resetEvent.WaitOne();

            //now launch the directory copy

            //then you have to check if in the meaning time, new files were added or renamed
            //that could be done also with a watcher in the old directory
        }

        static void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            throw new NotImplementedException();
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            throw new NotImplementedException();
        }

        static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            //check if the copied file was in the old directory before starting
            if (oldDirFiles.Contains(e.FullPath.Replace(newDir, oldDir)))
            {
                newDirFiles.Add(e.FullPath);
                //if all the files have been copied, the file count will be the same in the two hashsets
                //the resetevent.Set() signal the waiting thread and the program can proceed
                if (newDirFiles.Count == oldDirFiles.Count)
                    resetEvent.Set();
            }
        }
    }
}


text:
Q: Sort BuddyPress Activity Stream by Profile Field (Location)? I have a Nationwide BuddyPress website, so the activity stream can become confusing since people from all over are posting updates/content. I'd like to give members the ability to sort the activity based on their chosen location in their profile (drop down).
If a person wants to view a BuddyPress stream from members in New York, then they should be able to... Not based on GeoLocation but on the state selected in their profile.
How can I filter activity based on the users location, which is chosen via drop down menu in Users > Profile Fields > State ?
Someone had mentioned - "Another approach is filtering on sql query which may be a little bit more efficient." but I'm not sure where to start with that one :(


text:
Q: Microsoft Access does not like a table field name in a SQL Query I have the following SQL query that I am trying to run inside Microsoft Access 2010 and I get an error( Syntax error in INSERT INTO statement) then it highlights the field "Level" if I rename the field to "Level1" it works. The problem is that I can't rename the field because I have several SQL queries in PHP that I rely on the field name "Level" Any ideas of why it would throw an error.
The reason I am running the query is to copy data from an external ODBC sqlite database using linked tables. I do have several other INSERT INTO queries working this way. If there is another way please let me know. I have the query in some VB code that I use DoCmd.RunSQL
INSERT INTO MinorStats1 ( PlayerID,YearNumber,TeamID,Level,B_PA,B_AB,B_Hits,B_Doubles,B_Triples,B_HR,B_RBI,B_BB,B_K,B_TB,B_AVG,B_SLG,B_OPS,B_OBP,B_FPCT,B_SB,B_CS,P_Wins,P_Losses,P_Saves,P_GS,P_OutsPitched,P_BF,P_Hits,P_HR,P_BB,P_K,P_ER,P_ERA)SELECT PlayerID,YearNumber,TeamID,Level,B_PA,B_AB,B_Hits,B_Doubles,B_Triples,B_HR,B_RBI,B_BB,B_K,B_TB,B_AVG,B_SLG,B_OPS,B_OBP,B_FPCT,B_SB,B_CS,P_Wins,P_Losses,P_Saves,P_GS,P_OutsPitched,P_BF,P_Hits,P_HR,P_BB,P_K,P_ER,P_ERA FROM MinorStats

A: Enclose level in square brackets as follows:
INSERT INTO MinorStats1 ( PlayerID,YearNumber,TeamID,[Level],B_PA,B_AB,B_Hits,B_Doubles,B_Triples,B_HR,B_RBI,B_BB,B_K,B_TB,B_AVG,B_SLG,B_OPS,B_OBP,B_FPCT,B_SB,B_CS,P_Wins,P_Losses,P_Saves,P_GS,P_OutsPitched,P_BF,P_Hits,P_HR,P_BB,P_K,P_ER,P_ERA)SELECT PlayerID,YearNumber,TeamID,[Level],B_PA,B_AB,B_Hits,B_Doubles,B_Triples,B_HR,B_RBI,B_BB,B_K,B_TB,B_AVG,B_SLG,B_OPS,B_OBP,B_FPCT,B_SB,B_CS,P_Wins,P_Losses,P_Saves,P_GS,P_OutsPitched,P_BF,P_Hits,P_HR,P_BB,P_K,P_ER,P_ERA FROM MinorStats
You need to do this because level is a reserved word in Access.  For a complete list of reserved words, see http://support.microsoft.com/kb/286335.

A: You just need to surround [Level] (which is a reserved word evidently)  with brackets.


text:
Q: How to create a file in Android? How to create a file, write data into it and read data from it on Android? If possible provide a code snippet.

A: I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;

public class AndroidFileFunctions {

    public static String getFileValue(String fileName, Context context) {
        try {
            StringBuffer outStringBuf = new StringBuffer();
            String inputLine = "";
            /*
             * We have to use the openFileInput()-method the ActivityContext
             * provides. Again for security reasons with openFileInput(...)
             */
            FileInputStream fIn = context.openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader inBuff = new BufferedReader(isr);
            while ((inputLine = inBuff.readLine()) != null) {
                outStringBuf.append(inputLine);
                outStringBuf.append("\n");
            }
            inBuff.close();
            return outStringBuf.toString();
        } catch (IOException e) {
            return null;
        }
    }

    public static boolean appendFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context, Context.MODE_APPEND);
    }

    public static boolean setFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context,
                Context.MODE_WORLD_READABLE);
    }

    public static boolean writeToFile(String fileName, String value,
            Context context, int writeOrAppendMode) {
        // just make sure it's one of the modes we support
        if (writeOrAppendMode != Context.MODE_WORLD_READABLE
                && writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
                && writeOrAppendMode != Context.MODE_APPEND) {
            return false;
        }
        try {
            /*
             * We have to use the openFileOutput()-method the ActivityContext
             * provides, to protect your file from others and This is done for
             * security-reasons. We chose MODE_WORLD_READABLE, because we have
             * nothing to hide in our file
             */
            FileOutputStream fOut = context.openFileOutput(fileName,
                    writeOrAppendMode);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            // Write the string to the file
            osw.write(value);
            // save and close
            osw.flush();
            osw.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void deleteFile(String fileName, Context context) {
        context.deleteFile(fileName);
    }
}

A: I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
     OutputStream fo = new FileOutputStream(file);
     fo.write(data1);
     fo.close();
     System.out.println("file created: "+file);
}

//deleting the file
file.delete();
System.out.println("file deleted");

A: From here: http://www.anddev.org/working_with_files-t115.html
//Writing a file...

try {
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */
       FileOutputStream fOut = openFileOutput("samplefile.txt",
                                                            MODE_PRIVATE);
       OutputStreamWriter osw = new OutputStreamWriter(fOut);

       // Write the string to the file
       osw.write(TESTSTRING);

       /* ensure that everything is
        * really written out and close */
       osw.flush();
       osw.close();

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file
        isr.read(inputBuffer);

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe)
      {ioe.printStackTrace();}

A: Write to a file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
        fos = new FileOutputStream(filepath);
        byte[] buffer = "This will be writtent in test.txt".getBytes();
        fos.write(buffer, 0, buffer.length);
        fos.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fos != null)
            fos.close();
    }

Read from file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
       fis = new FileInputStream(filepath);
       int length = (int) new File(filepath).length();
       byte[] buffer = new byte[length];
       fis.read(buffer, 0, length);
       fis.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fis != null)
            fis.close();
   }

Note: don't forget to add these two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


text:
Q: Opencart 2.2.0.0 Translation Issue I am trying to translate opencart version 2.2.0.0
I have translated the file and put them in following 2 directory
catalog/language/bangla
admin/language/bangla
it is working for category, product description etc from admin backend but not working for any of the parameters given in .php file like '
$_['text_checkout'] $_['text_wishlist'] etc. etc
I am testing it in localhost. Am I doing anything wrong?
thanks

A: To install a language package, you have to transfer all your files on your server (keeping the same structure) on the roots of a previously installed OpenCart.
After that, open your OpenCart backend and follow these steps:

*

*Navigate to System -> Localisation -> Languages

*Click the Add New button

*Fill in the following values :

*

*Language Name : name of the language, for example French

*Code : code of your language, for example fr

*Locale : localization of your language, for example fr,fr-FR,fr_FR.UTF-8,french

*Image : flag image for the language, for example fr.png

*Directory : directory of your language pack, for example fr-FR

*Status : Enabled

*Sort Order: 1

*Save these changes

*Navigate to System -> Settings

*Click on the tab Local and define your standard languages for frontend and backend (backend language will not change before this step)

*Save these changes

*Installation is complete


text:
Q: No response returned from fetch I am trying to get data from the API and it doesnot return any value. I have tried to put the apiUrl in the browser directly it works there. Even a get request via postman returns request.
fetch(apiUrl)
    .then((response) => {
        let data = JSON.parse(response)
        console.log(data)
        return data;
    })

Also in Chrome debugger, there is no request in the network tab as well. I have used the same code earlier to get the response.

A: Calling the API with Fetch gives a promise, and converting it to JSON will return yet another promise, which you need to "await" for again. This is how it should look like
fetch(URL)
  .then(response => response.json())
  .then(json => console.log(json))

A: fetch(apiUrl)
  .then((response) => {
     return response.json().then( res => {
        let data = res;
        console.log(data)
        return data;
     })
})

try this


text:
Q: Тест Spring MockMvc: No mapping found for HTTP request with URI Есть простейший контроллер:
@GetMapping(value = "/ping", produces = "text/plain")
@ResponseBody
public String getPong(HttpServletRequest httpServletRequest) {
    return "pong";
}

С ним все в порядке, он исправно работает. Для него написан не менее простой юнит-тест:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:configuration/test-healthcheck-context.xml"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class PingTest {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void before() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}

@Test
public void pingTest () throws Exception {
    MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/ping").accept(MediaType.ALL)).andReturn();
    String response = mvcResult.getResponse().getContentAsString();
    Assert.assertEquals(response, "pong");
}

}
Контекст поднимается без ошибок, но тест не проходит, а в консоли выводится следующее:
2020-04-15 12:02:04.189 [INFO ] [o.s.t.web.servlet.TestDispatcherServlet ] [T:main                ] - FrameworkServlet '': initialization completed in 671 ms
2020-04-15 12:02:04.189 [DEBUG] [o.s.t.web.servlet.TestDispatcherServlet ] [T:main                ] - Servlet '' configured successfully
2020-04-15 12:02:04.230 [DEBUG] [o.s.t.web.servlet.TestDispatcherServlet ] [T:main                ] - DispatcherServlet with name '' processing GET request for [/ping]
2020-04-15 12:02:04.232 [DEBUG] [s.w.s.m.m.a.RequestMappingHandlerMapping] [T:main                ] - Looking up handler method for path /ping
2020-04-15 12:02:04.233 [DEBUG] [s.w.s.m.m.a.RequestMappingHandlerMapping] [T:main                ] - Did not find handler method for [/ping]
2020-04-15 12:02:04.233 [WARN ] [o.s.web.servlet.PageNotFound            ] [T:main                ] - No mapping found for HTTP request with URI [/ping] in DispatcherServlet with name ''

Очевидно, что закралась ошибка в конфигурации тестового окружения (так как сам контроллер, как я уже писал, работает). Подскажите, пожалуйста, где может быть ошибка? Спасибо!

A: Причина ошибки в том, что в xml-контексте теста не был указан бин контроллера.


text:
Q: How can you compile multiple typescript files with shared dependencies into a single javascript file? I have just started learning typescript, and I'd love to be able to write my code across dozens of files, modules or classes. But, I'd like to have all that compiled into a single .js file. which can be embedded in the html. This would mean I would not have to embed individual .js files in the HTML everytime I create a new one. I am trying to figure out header files, but I can't find find any clear explanation (or code samples) of how that works.
This is a NodeJS project in Webstorm. I am also using JQuery and I'd love to have JQuery imported and compiled into the .js file instead of being retrieved separately from the CDN each time - assuming that would make the site run faster!

A: You need to compile with the --out compiler flag. I have a demo up on youtube: http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1


text:
Q: Optimizing a regex expression I'm having issues where it's taking very long to run a match against this query. I'm trying to match up content that looks like the following:
One or more content paragraph of any length
Here is an optional paragraph

A single line or list item
A single line or list item

Here is my pattern. While it works for short expressions, it fails for longer ones.
^((.+[\r\n]?)+)\r\n\r\n([* -]*(.+)[\r\n]?)+$

My goal really is to separate out the first piece of content into a paragraph, and collect the last items into a list object using the matching pattern. I'm assuming two line breaks separate the paragraph(s) and a set of single-line items (only one line break).
Hope this isn't confusing. How can I optimize this regex? Thanks.

A: Time-consuming, inefficient backtracking can often be avoided by adding the ? modifier to the * and + quantifiers to make them match lazily or reluctantly, i.e. as few times as possible.
This can be particularly important when the quantifiers follow the . wildcard meta-character.
Try
(.+?)\r\n\r\n(?:[* -]*(.+?)(?:\r\n|$))+

with RegexOptions.Singleline so . matches any character including newlines.
(Alternatively use [\s\S] in place of the first .).
The first capture group will capture all that comes before the consecutive newlines, and then the next capture groups will capture each single line that follows. As in your regex, any leading *, - or space characters in the single lines will not be captured.
The paragraph/s will be match.Groups[1].Value, the first captured single line will be match.Groups[2].Captures[0].Value and the second match.Groups[2].Captures[1].Value) etc.
If the line-endings may be simply \n, change \r\n to \r?\n.

A: I'm not that good at regex but your one seems quite optimized to me. But to make it faster, use split instead to seperate the paragraph from the list
res = yourstring.Split('\r\n\r\n');
paragraph = res[0];
list=res[1];

then you can use regex or again split to seperate the list items from each other


text:
Q: Confused about docker build to keep running docker container forever So, I was playing around with Docker for the first time. What I did was to have an Open SSH server running on the container, so that I can logon to it from anywhere. It works fine when I used the following for docker build. Open SSH server was already installed in the base image.
#Download base image
FROM BaseImage
RUN mkdir /var/run/sshd
CMD ["/usr/sbin/sshd", "-D"]

If I run the container with the following
docker run -p 52022:22 -dit <MyContainerID>

And Logon to it from outside, like this,
ssh -p 52022 <userName>@<IPAddress>

I can login fine.
But then I changed my docker file to something more general purpose, by replacing the last command with what is shown below, because I read from the internet that CMD tail -f /dev/null is a way to keep the docker container running.
CMD service ssh start
CMD tail -f /dev/null

However, now If I try to login from outside, I get the following error.
ssh_exchange_identification: Connection closed by remote host

What is the reason? How come this is not working. The command service ssh start should had started the SSH server in the background, no?

A: I thought I would just clarify the situation here a little. With regard to how to use the CMD instruction and also with respect to ENTRYPOINT, that I think you should consider using here.
The CMD and ENTRYPOINT instructions in a Dockerfile, help us specify what command should be run when the image is started, and what arguments it should receive.
Generally what you want to do is to have the ENTRYPOINT specify an executable or script that should be invoked. Common practice is to have an entrypoint.sh or docker-entrypoint.sh script here.
The CMD command is then used to specify parameters to the entrypoint script.
So with ENTRYPOINT ["ping"] and CMD ["localhost"], the container would start with the command ping localhost.
From the docker documentation:

The main purpose of a CMD is to provide defaults for an executing
  container

So for your instance, I would use: CMD ["/usr/sbin/sshd", "-D"] - if you need to send anything else to the container on startup, make an entrypoint script that takes those parametes, set the script as the ENTYPOINT and at the end of it start the process /usr/sbin/sshd -D.
I believe that you may be trying to tail your sshd log here, in order to have it piped to the stdout and stderr. With the -D flag to sshd, your process will not become a daemon, but stay in the foreground of the session that it was executed in. And with docker, this is exactly what you want. Docker is aready logging everything sent to stdout and stderr, and you want to make use of this. If your sshd process is not already logging to stdout and stderr, then you could configure it to do so in your Dockerfile.
I would recommend that you read this article, for what you are doing: Dockerize an SSH service

A: OK, I solved the problem. In docker, you can use CMD just once. So, instead of
CMD service ssh start
CMD tail -f /dev/null

It should be,
CMD service ssh start && \
    tail -f /dev/null

A: The issue is only last CMD is considered by Docker build instructions
so you need to combine your both CMDs into one single command.


text:
Q: Hierarchical single select tree-view radio group display using Vue I'm wondering if there is an easy way to accomplish this using Vue. Essentially I want to display a dynamic navigational hierarchy using radio elements.
So essentially if I had the top level with Color, Shape, Standalone and select Color it would show a new radio group from an array of child objects ("Blue", "Yelllow, etc.) but if a selection does not have a child array it doesn't expand.
The easiest way to describe this is as a sort of hierarchical folder structure which typically uses something like a tree view but I've yet to find anything using radio input.


text:
Q: Минимальное время выполнения цикла на Python Есть цикл
i = 0
while i <= 25:
    do_something()
    i += 1

Нужно сделать так, чтобы 1 проход по циклу выполнялся ровно 1 секунду

A: (сорри, не могу пока ещё оставлять комментарии).

есть задача: камера должна совершать 25 кадров в секунду и сохранять их, после чего они должны обновляться каждую секунду

Если я правильно понял твою задачу, то в opencv ты можешь итерироваться по фреймам.
Пример есть тут: https://stackoverflow.com/questions/18954889/how-to-process-images-of-a-video-frame-by-frame-in-video-streaming-using-opencv

A: импортируйте модуль time и перед 4 строкой напишите sleep(1)


text:
Q: Overlapping images in HTML table Can someone explain why the images are overlapping?

Nymphomaniac: Vol. II

(2013)

Nymphomaniac: Vol. II

(2013)

Example Image:

A: The problem is that
 tags which contain  tags don't have width and height attributes at the same time  has width and height.
so if you add next css code:

and then you are going to add class="photodiv"to
 elements which contain  inside it.
here are all the code :
<!doctype html>

Nymphomaniac: Vol. II

(2013)

Nymphomaniac: Vol. II

(2013)

A: You are going to need to add some css to the code so add

Then you are going to add id="poster" to the first
, making it


text:
Q: Mysql is taking 63 GB from the server I have a centos 6.9 in AWS which has mysql server Ver 5.6.36
I am facing really big slowness problem with exporting reports and most time it gives time out. the database side around 80G the server has 64G RAM and the mysql is using it all.
I am not a mysql specialist, so please if you need any statistic just ask me.
I do not know what I have to share.
but in the logs there is two errors. I do not know if these log related to the same problem.
2017-08-02 18:22:31 11629 [ERROR] InnoDB: Unable to lock ./ibdata1, error: 11
2017-08-02 18:22:31 11629 [Note] InnoDB: Check that you do not already have another mysqld process using the same InnoDB data or log files.

A: We do need  SHOW GLOBAL STATUS  and  SHOW GLOBAL VARIABLES  added to your question to quickly analyze key statistics and configuration information for your instance.  Thanks for offering the information.
The visual clues in the errors indicate second attempt to start another instance of MySQL.
TOP and MYTOP from your Centos server may be useful.

A: *

*The error messages say that two copies of mysqld are running.  That is a no-no.

*Without the configuration, we cannot explain the "using it all".

*It is quite OK for a database to be bigger than RAM.  RAM is used to cache parts of the dataset.


text:
Q: Homeomorphism from square to unit circle Can we find a homeomorphism from the square $Q_2$ of side length $2$ centered on the origin and the unit circle $S^1$?
We can easily define a map $r:Q \longrightarrow S^1$ by
$$(x,y) \mapsto  \bigg(\frac{x}{\sqrt{x^2+y^2}},\frac{y}{\sqrt{x^2+y^2}} \bigg)$$ which is a radial projection onto the unit circle, but how can we define $r^{-1}$ and show that it is continuous?
Thoughts
I think we may define the inverse map as
$$(x,y) \mapsto \bigg(\frac{x}{\sqrt2\max{│x│, │y│}} , \frac{y}{\sqrt2\max {│x│, │y│}}\bigg)$$At least intuitively this maps to a square, and the $\frac{1}{\sqrt2}$ term scales appropriately. However, how can we demonstrate these are continuous maps, thus demonstrating that $Q_2$ and $S^1$ are homeomorphic?
Any help would be appreciated. Regards, MM.

A: I'm not sure why you need algebraic formulas. Define each map $f$ to be radial projection onto the appropriate curve (from the origin) and find continuity by the property "$\forall$ neighborhood $U$ of $f(x)$ $\exists$ a neighborhood of $x$ whose image is contained in $U$", which is easy to check by eye.

A: It seems off to me. For example, in your second map, the point $(1,0)$, which is on the unit circle, gets mapped to $(\frac1{\sqrt2},0)$, which is not on the square.
If I were you, I would write out the four different maps for each side of the square - I think it simplifies the process, especially since once you remove the max terms, the function is easier to work with.

A: Let me outline a proof; I shall leave the details of this proof as exercises.
Exercise 1: Prove that the unit circle $S^1$ is homeomorphic to the space obtained from the unit interval $[0,1]$ by identifying the endpoints $0$ and $1$. (Hint: the exponential mapping $\theta\to e^{i\theta}$ can be composed with a linear mapping to give a homeomorphism.)
Let $C$ be the image of a simple closed curve in the plane, that is, let $C$ be the image of a continuous function $f:[0,1]\to \mathbb{R}^2$ such that $f:(0,1)\to\mathbb{R}^2$ is injective and $f(0)=f(1)$.
Exercise 2: Prove that $C$ is homeomorphic to the unit circle $S^1$. (Hint: show that $f:[0,1]\to C$ induces a continuous bijection $\tilde{f}:S^1\to C$ using Exercise 1 and then show that $f$ is an open mapping using the compactness of $S^1$ and the fact that the plane is Hausdorff.)
We now need an elementary lemma of point-set topology:
Exercise 3: Let $X$ be a topological space and let $X=A\cup B$ where $A$ and $B$ are closed subspaces of $X$. Prove that if $g:A\to Y$ and $h:B\to Y$ are continuous functions into a topological space $Y$ such that $g(x)=h(x)$ for all $x\in A\cap B$, then there is a unique continuous function $f:X\to Y$ such that $f(a)=g(a)$ and $f(b)=h(b)$ for all $a\in A$ and $b\in B$.
Finally, we can prove the result of your question:
Exercise 4: Prove that the unit square is the image of a simple closed curve in the plane and conclude that it is homeomorphic to the unit circle. (Hint: you can use Exercise 3 to "glue" continuous mappings together.)
Exercise 5: Give examples of images of simple closed curves in the plane (using Exercise 3) and conclude (using Exercise 2) that they are homeomorphic to the unit circle $S^1$.
I hope this helps!

A: If you choose to go about it in a computational manner, you can prove that both of the maps are continuous by noting that they are compositions of continuous functions.

A: Following in line with @Amitesh Datta's answer above, rather than proving the homeomorphism directly there are simpler ways that one can arrive at the desired result.
This following technique uses a fairly high-powered result (in the sense that once you know it, you can prove a lot of things are homeomorphic quite easily), but I think it's a very useful result that anyone doing topology should be aware of.

Definition: An open $n$-cell is any topological space that is homeomorphic to the open unit ball $\mathbb{B}^n$. A closed $n$-cell is any topological space homeomorphic to $\overline{\mathbb{B}^n}$

This is the high-powered result that I mentioned earlier.

Theorem: If $D \subseteq \mathbb{R}^n$ is a compact convex subset with nonempty interior, then $D$ is a closed $n$-cell and it's interior is an open $n$-cell. In fact given any point $p \in \operatorname{Int}(D)$, there exists a homeomorphism $F: \overline{\mathbb{B}^n} \to D$ that sends $0$ to $p$, $\mathbb{B}^n$ to $\operatorname{Int}(D)$ and $\mathbb{S}^{n-1}$ to $\operatorname{Bd} D$.

Now note that if we let $A \subseteq \mathbb{R}^2$ be the (solid) square of side length $2$, then $A$ is easily seen to be a convex subset, and is thus a closed $2$-cell by the theorem above. Moreover the square $Q_2$ is the topological boundary of the solid square $A$ and the theorem above then immediately shows that $\operatorname{Bd}(A) = Q_2 \cong S^1$ as desired.


text:
Q: 14.04 Wireless constanly disconnects I've followed the solution from here
ubuntu 14.04 wireless constantly disconnects
and here
How do I keep my Wifi from dropping out?
and niether have worked.  I've been using ubuntu for nearly 10 years now and it's never been as unstable as it is now.  I also have an ubuntu certified laptop (BS).  What do I have to do to get this to work?
Edit
Relevant output from lspci -knn
07:00.0 Network controller [0280]: Ralink corp. RT3290 Wireless 802.11n 1T/1R PCIe [1814:3290]
    Subsystem: Hewlett-Packard Company Ralink RT3290LE 802.11bgn 1x1 Wi-Fi and Bluetooth 4.0 Combo Adapter [103c:18ec]
    Kernel driver in use: rt2860

07:00.1 Bluetooth [0d11]: Ralink corp. RT3290 Bluetooth [1814:3298]
    Subsystem: Hewlett-Packard Company Ralink RT3290LE 802.11bgn 1x1 Wi-Fi and Bluetooth 4.0 Combo Adapter [103c:18ec]


text:
Q: How do I explain Identifer Expected Good Day,
I have a question on theory
public class ExamQ1a {
    double a, b, c, s, area;
    a = 3;
    b = 4;
    c = 5;
    area = Math.sqrt(s (s-a) (s-b) (s-c));
    s = (a + b + c) / 2;
    System.out.println("area = " + area);
}

I have a question based on past exam paper; During compilation, statement [a = 3;] is highlighted and an error message (identifier expected) is shown.  Explain what the problem is and how to fix it?
I know that it should be inside a method but how do i properly explain it?
Thanks.

A: My understanding is that the class definition is evaluated at compile-time, so initializers like double a = 3; are permitted by some compilers, but statements like a = 3; that are not contained within a method or constructor would never be executed, and so are not permitted.


text:
Q: Kivy content sizes adjustment I have been started to work in kivy recently. The thing what I am doing now is, i have a blank page with a button, when I click that button it navigates to an user input screen. It works fine, but the content comes in a very small input boxes and text as in the picture.

My question is that I want it bigger and centred.
Here is my code:
In python:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.widget import Widget
from kivy.lang import Builder

class LoginScreen(GridLayout):
    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.cols = 2
        self.add_widget(Label(text="Username:"))
        self.username = TextInput(multiline=False)
        self.add_widget(self.username)

        self.add_widget(Label(text="Password:"))
        self.password = TextInput(multiline=False, password=True)
        self.add_widget(self.password)

        self.add_widget(Label(text="Two Factor Auth:"))
        self.tfa = TextInput(multiline=False)
        self.add_widget(self.tfa)

class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("screen.kv")

class SimpleKivy(App):
    def build(self):
        return presentation

if __name__ == "__main__":
    SimpleKivy().run()

In kv:
 #: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: "main"
    Button:
        color: 0,1,0,1
        font_size: 25
        size_hint: 0.3,0.2
        text: "Click"
        on_release: app.root.current = "other"
        pos_hint: {"right":1, "top":1}

<AnotherScreen>:
    name: "other"

    GridLayout:
        LoginScreen

A: In your screen.kv,  you have the LoginScreen inside a GridLayout. Since the LoginSCreen is a GridLayout, you do not need that extra GridLayout.
Just change:
<AnotherScreen>:
    name: "other"

    GridLayout:
        LoginScreen

to:
<AnotherScreen>:
    name: "other"

    LoginScreen:


text:
Q: How to use Django streaming download a file when writting data to it? How to use Django to streaming download a file when writing data to it?
That means I don't know the file size when I start downloading it.


text:
Q: Circuit to detect amperage? Is there a circuit which can detect how much amps are flowing through it, and if the amperage falls below a certain level to output some signal?  (e.g. to direct the voltage to a different output)
Due to getting only vague answers on the question How to attain a topping charge for a lead-acid battery?, I decided to rephrase what I need in a different manner.  I am very new at these things, so I apologize in advance if there is some way I am not explaining myself well; or maybe this is completely trivial to look up somewhere, and that's the reason I have not gotten any answers other than those of the type "Yes, this can be done".

A: Here is a circuit that should do what you want.   It uses the LT6100 is that it has variable gain and 0.5% accuracy.  I have used this chip in a commercial product.

If you use it with a 100 mΩ resistor, a 1A load with drop 100 mV across the resistor. Using a gain of 20, this will give a 2v output. By adjusting the voltage divider feeding the + lead of the comparator, you can set the threshold you need.
If you combine the LT6100 with a 100 mΩ 0.5% resistor, you will have 1% accuracy for the combination.
The LT6100 is available from Digi-Key for $2.36.


text:
Q: Weird couldn't match type error I have simple one line function:
revRange :: (Char,Char) -> [Char]
revRange t = unfoldr (\b -> if b == (pred (fst t)) then Nothing else Just (b, pred b)) (snd t)

It works well:
*Main Data.List> revRange ('a', 'f')
"fedcba"

Then I want to extract unfoldr lambda as unique function:
revRange :: (Char,Char) -> [Char]
revRange t = unfoldr fun t
fun t = (\b -> if b == (pred (fst t)) then Nothing else Just (b, pred b)) (snd t)

Now, I have a weird error:
Couldn't match type `Char' with `(Char, Char)'
Expected type: (Char, Char) -> Maybe (Char, (Char, Char))
  Actual type: (Char, Char) -> Maybe (Char, Char)
In the first argument of `unfoldr', namely `fun'
In the expression: unfoldr fun t

A: First, format your code:
revRange :: (Char,Char) -> [Char]
revRange t = unfoldr fun t
fun t = (\b -> if b == (pred (fst t))
               then Nothing
               else Just (b, pred b)) (snd t)

Next, double check the type of unfoldr using Hoogle:
unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

Next, add a type signature to fun so that GHC will tell you what the problem is. According to the type of unfoldr, fun should have the type:
b ~ Char
a ~ Char

fun :: Char -> Maybe (Char, Char)

since you are unfoldr in the original example with snd t.
I usually like to verify small pieces, so we can remove the definition of foo and just use the type signature:
revRange :: (Char,Char) -> [Char]
revRange t = unfoldr fun t

fun:: Char -> Maybe (Char, Char)
fun b = error ""

GHC complains that t has type (Char, Char) but fun expects type Char. You've called unfoldr fun t instead of unfoldr fun (snd t) as in the original example. Move that bit from fun into revRange:
revRange :: (Char,Char) -> [Char]
revRange t = unfoldr fun (snd t)

fun:: Char -> Maybe (Char, Char)
fun b = error ""

Next, add in the definition of fun again. We can remove the lambda and put b as a normal argument to fun:
fun:: Char -> Maybe (Char, Char)
fun t b = if b == (pred (fst t))
          then Nothing
          else Just (b, pred b)

Immediately we see another glaring problems: fun takes two arguments but the signature says it should only take one!
Since t is a constant in the original lambda, we can solve this problem by partially applying fun in revRange, so the final answer is:
revRange :: (Char,Char) -> [Char]
revRange t = unfoldr (fun t) (snd t)

fun:: (Char, Char) -> Char -> Maybe (Char, Char)
fun t b = if b == (pred (fst t))
          then Nothing
          else Just (b, pred b)

To address your comment, you'd like to write
revRange :: (Char,Char) -> [Char]
revRange = unfoldr fun2

Using the same approach as above, in the signature of unfoldr we need b ~ (Char,Char) and a ~ Char. So we'd like fun2 to have the type
fun2 :: ((Char,Char) -> Maybe (Char, (Char, Char)))

I'll leave the definition of fun2 as an exercise. As a hint, I suggest adopting the convention that the first part of the pair is constant and holds fst t.


text:
Q: How do I merge two lists within the cycle? I have to create a list within a cycle which includes a Gauss function for z range(0,200)
def GetDepth():

    return float(a * 2.7 - (z - mu)**2 / (2 * sig**2))

for z in range(-1,200):

    k =[]
    z=z+1;
    for i in range(1):
        k.append(z);
        Gauss_list.append([z]);
        Gauss_list.append([GetDepth()]);
print(Gauss_list)

It returns something like:
[[0], [-1.0535849715692442], [1], [-0.8792864705363532], [2], [-0.7109879179039058], [3], [-0.5486893136719024], [4], [-0.39239065784034244]....

But what I need is:
 [[0, -1.0535849715692442], [1,-0.8792864705363532], [2,-0.7109879179039058], [3,-0.5486893136719024]....

That is for a Gauss plot. Maybe there is another option to make a plot without making 2-binary list?

A: Instead of:
    Gauss_list.append([z]);
    Gauss_list.append([GetDepth()]);

Use append at once:
    Gauss_list.append([z, GetDepth()])


text:
Q: Internet Explorer AutoComplete Form Data I am looking to load, display and have the user remove stored AutoComplete data from Internet Explorer using c#. I am looking specifically for form data and not stored credentials.
Not sure if IE version matters, but I do believe Windows version makes a difference.
The settings can be found in Internet Options: under the Content tab by clicking the Settings button in the AutoComplete section.

A: The autocomplete entries and saved passwords are stored in the registry, specifically:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage1
This answer shows exactly where, and this page confirms it. I've also tested it on IE11 and can confirm that entries get created in this area of the registry when saving passwords and autocomplete. So, using standard Windows API calls or PowerShell can get that information for you, and also delete it (simply by deleting the directories under IntelliForms).
Note that the data is stored in binary or hex, so you would need to reverse-engineer that if you want to present it in a readable format.


text:
Q: How to force Remap Current Pending Sector Count My Laptop Hard Drive Crystal Disk Info - Caution then I found out that there is a Current Pending Sector Count is this drive ok? Can I force remap it? on Windows or Linux?
I tried WDC Data Lifeguard or even windows chkdsk /r but no luck.
           Model : WDC WD5000LPVT-22G33T0
        Firmware : 01.01A01
       Disk Size : 500.1 GB (8.4/137.4/500.1/500.1)
     Buffer Size : 8192 KB
     Queue Depth : 32
    # of Sectors : 976773168
   Rotation Rate : 5400 RPM
       Interface : Serial ATA
   Major Version : ATA8-ACS
   Minor Version : ----
   Transfer Mode : SATA/300 | SATA/300
  Power On Hours : 8531 hours
  Power On Count : 5986 count
     Temperature : 40 C (104 F)
   Health Status : Caution
        Features : S.M.A.R.T., APM, 48bit LBA, NCQ
       APM Level : 0060h [ON]
       AAM Level : ----
    Drive Letter : C:

-- S.M.A.R.T. --------------------------------------------------------------
ID Cur Wor Thr RawValues(6) Attribute Name
01 200 200 _51 000000000245 Read Error Rate
03 155 152 _21 0000000004E2 Spin-Up Time
04 _87 _87 __0 00000000368F Start/Stop Count
05 200 200 140 000000000000 Reallocated Sectors Count
07 200 200 __0 000000000000 Seek Error Rate
09 _89 _89 __0 000000002153 Power-On Hours
0A 100 100 __0 000000000000 Spin Retry Count
0B 100 100 __0 000000000000 Recalibration Retries
0C _95 _95 __0 000000001762 Power Cycle Count
BF __1 __1 __0 00000000065E G-Sense Error Rate
C0 200 200 __0 00000000006F Power-off Retract Count
C1 184 184 __0 00000000BDB6 Load/Unload Cycle Count
C2 103 _91 __0 000000000028 Temperature
C4 200 200 __0 000000000000 Reallocation Event Count
C5 200 200 __0 000000000001 Current Pending Sector Count
C6 100 253 __0 000000000000 Uncorrectable Sector Count
C7 200 200 __0 000000000000 UltraDMA CRC Error Count
C8 100 253 __0 000000000000 Write Error Rate

A: I could be done but you probably wouldn't want to.
When an error occurs when a sector is written the drive replaces the bad sector with a spare and then rewrites the data and there is no data loss. The "Reallocated Sectors Count" is a count of these sectors. But things aren't so simple when an error occurs when a sector is read. Remapping the sector would not be a good idea because this would prevent recovery of it's data if a later read operation were to succeed. Instead the drive makes a note of the bad sector and waits for one of 2 events to occur. The "Current Pending Sector Count" is a count of such sectors.

*

*If the sector is later successfully read it can be remapped with no data loss. Unfortunately you have no way of knowing when this will occur or even if it is possible. The read operation may succeed at the next attempt or it may fail after 1000 tries.

*If the sector is later written to it can be remapped with no data loss. Unfortunately there is no way of knowing when or if this will occur. If the sector contains frequently modified data the wait may not be long. But if the sector contains a system or application executable file it may be long time before it is updated, or it may not happen at all.
Note that all of this occurs entirely within the drive with the OS having no involvement or knowledge of the operation. The drive provides no means of identifying which sectors are involved, just their number. It could probably be determined with drive specific software designed for the use of data recovery professionals. Such software is designed for professional use and priced accordingly.
With no way of knowing which sectors are involved there isn't much that software can do with them. Doing a clone backup of the drive and then restoring it would force the pending sectors to be written and allow then to be remapped. With an image backup you have no assurance that the sectors involved would be written. And the data in the bad sectors would be forever lost. And with a large drive this would take considerable time.
There really is nothing to be gained by forcing the reallocation. There is no advantage in successfully reading a remapped sector with the wrong data over failing to reading the original sector with the original data. And there is a chance it may eventually succeed if not remapped. If the sector is later written it will be remapped with no data loss.


text:
Q: File Access Denied despite being administrator, owning the files, and having full permissions I'm trying to copy data from my old laptops hard drive to my new desktop's. But on a certain folder, I can't copy any of the actual files - just the subfolders. I am informed that I require permission from myself, the only user and administrator on the computer, to change the file. I have taken ownership of all of the folders and files on the hard drive, which can be verified by viewing the properties of any of the files. Also, I have full permissions on ALL of the files and folders on the disk. So, why am I getting this error? And how do I fix it?
I have changed the owner and permissions on ALL child objects of the container. Here is a screenshot:

I recognize that the files in question on drive G are encrypted, but I'm not allowed to decrypt them either...
In desperation, I've even tried rebooting after making all the ownership and permissions changes to the WHOLE drive. No luck.
I've searched for hours on Google for a solution, to no avail. These files are essential to completing my work project, so, I must resolve this issue.
UPDATE: Using the command line move/copy tools also returns an "Access Denied" error. takeown /f <folder> /r works just fine though, further proving that I do indeed have full ownership of the files.

A: The problem is that your user (on the new computer) doesn't have access to the encryption keys (from the old computer) that were used to encrypt the files.
Windows, confusingly, gives an "access denied" error message when trying to read an EFS-encrypted file that you lack the encryption key for (e.g. files that were created on a different computer). This is independent of ownership/permissions.
If you can still boot the old computer, decrypt the files from the OS install that they were encrypted from.
If you can't boot the old computer, see these questions:

*

*How decrypt a file that encypted in other windows xp os

*EFS recovery from backed up registry files?
Edit: It probably isn't possible to boot the laptop HDD on a different computer (Windows is finicky about hardware). But don't panic; the certificate is in principle what you need to decrypt. The problem is getting the software to use it. Try Microsoft's EFS certificate migration for Windows 7.

A: Try booting off of some form of Live CD (or even boot into the Windows 7 Recovery Console), and copying them while Windows hasn't started. This may get around any issues related to encryption (though there are no guaranty that the encrypted files will work after they have been moved.)


text:
Q: How to scrape data from web site that is made with Java Applet I want to scrape data from web site.
I can scrape data from normal html web site by using selenium-webdriver and phantomjs.
But it is impossible get data from Java Applet.
How can I get data from Java Applet application?


text:
Q: SOAP API RetrieveRequest for specific Business Unit I am trying to pull information about various sends from the API in an automated fashion into a Ruby on Rails app.
I can successfully run the call and parse the results for the entire account (including all business units) using this hash as my soap body:
{
  'tns:RetrieveRequest' => {
    'ObjectType' => 'Send',
    'Properties' => ['Additional', 'Duplicates', 'ExistingUndeliverables', 'ExistingUnsubscribes', 'ForwardedEmails', 'HardBounces', 'InvalidAddresses', 'MissingAddresses', 'NumberDelivered', 'NumberErrored', 'NumberExcluded', 'NumberSent', 'NumberTargeted', 'OtherBounces', 'SendDate', 'SendLimit', 'SentDate', 'SoftBounces', 'UniqueClicks', 'UniqueOpens', 'Unsubscribes','EmailName', 'Additional', 'ID','PartnerKey', 'PreviewURL'],
    'QueryAllAccounts' => true,
    :attributes! =>
    {
      'Filter' => {"xsi:type" => "tns:SimpleFilterPart"}
    },
    'Filter' =>
    {
      'Property' => 'SendDate',
      'SimpleOperator' => 'between',
      'DateValue' => ['2014-02-05', '2014-02-13']
    }
  }
}

However, this doesn't give me a good way to tie any of the sends back to specific business units (which correspond to our own internal customers). I'm looking for a way to either pull back business unit information as part of this call, or to run this call for only one business unit at a time.
I've been trying things like this for my soap body but to no avail:
{
  'tns:RetrieveRequest' => {
    'ObjectType' => 'Send',
    'Properties' => ['Additional', 'Duplicates', 'ExistingUndeliverables', 'ExistingUnsubscribes', 'ForwardedEmails', 'HardBounces', 'InvalidAddresses', 'MissingAddresses', 'NumberDelivered', 'NumberErrored', 'NumberExcluded', 'NumberSent', 'NumberTargeted', 'OtherBounces', 'SendDate', 'SendLimit', 'SentDate', 'SoftBounces', 'UniqueClicks', 'UniqueOpens', 'Unsubscribes','EmailName', 'Additional', 'ID','PartnerKey', 'PreviewURL'],
    'QueryAllAccounts' => true,
    'PartnerProperties' =>
    {
      'Name' => 'ClientID',
      'Value' => '0123456'
    },
    :attributes! =>
    {
      'Filter' => {"xsi:type" => "tns:SimpleFilterPart"}
    },
    'Filter' =>
    {
      'Property' => 'SendDate',
      'SimpleOperator' => 'between',
      'DateValue' => ['2014-02-05', '2014-02-13']
    }
  }
}

Can you provide me with the appropriate formatting of a call that can meet my needs?

A: It is possible to have the request return the ID for the Business Unit that the Send is related to by including Client.ID in the Properties array being passed.
It is also possible to specify a specific business unit for the retrieve by specifying the RetrieveRequest > ClientIDs > ID property and setting QueryAllAccounts to True.  Example SOAP would look like:
<RetrieveRequestMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
    <RetrieveRequest>
        <ClientIDs>
            <ID>100000</ID>
        </ClientIDs>
        <ObjectType>Send</ObjectType>
        <Properties>Client.ID</Properties>
        <Properties>ID</Properties>
        <Properties>SendDate</Properties>
        <QueryAllAccounts>true</QueryAllAccounts>
    </RetrieveRequest>
</RetrieveRequestMsg>


text:
Q: GPS Location is being saved automatically without approval Okay my problem is this:
I have two Activities, A and B.
In Activity A I have a webview which presents a google map with coordinates that are taken from a SharedPreferences DB file. if the DB file is empty then the google map query gets default values.
Now when I go to Activity B, the GPS Location starts working and it lets me decide if I want to save my current location (I can either click on the "save" button which saves the current location to the DB file or just click on the "get back without saving" button which takes me back to Activity A without saving the location.
The thing is, when I click on the "get back without saving" the location in Activity A changes!! it has been updated even though I didn't click on the "save" button!
how can this be?
Does anybody have a clue? please help

A: Okay, it seems that onStop() method caused this issue.
onStop() worked everytime I switched between A and B Activites and saved the last location.
The whole purpose of implementing onStop() was just in case the app crashes and not when switching between Activities.
Does anybody have an idea on how to set it correctly?


text:
Q: How can I make if-statements recurring until the user types 'quit'? I am coding in Python.
Let us say when the program starts, the user is prompted with the following:
Press 1) to check what the temperature is outside.
Press 2) to find out how many miles are on your car.
Press 3) to see how full your gas tank is.
Press 4) to find out how much money you made last week.

Whatever the user types in, the if statement is executed. I want this program to keep going until the user types quit. Nonetheless, as a user, I want to be able to keep hitting 1) or 2) as many times as I want.
Here is my code thus far:
x = raw_input("Enter number here: ")

if x == '1':
    weather = 46
    print "%s degrees" % (weather)

if x == '2':
    milesoncar = '30,000'
    print "%s miles" % (milesoncar)

if x == '3':
    gasintank = 247.65
    print "%s miles left in gas tank" % (gasintank)

if x == '4':
    money = '$439'
    print "You made %s last week." % (money)

if x == 'quit':
    print 'Goodbye

The only thing that I want to make this program stop is if the user types "quit."
How would I go about doing this? Do I need a while loop comprised of if statements? If so, how would I go about doing that?

A: Just put everything in a while True loop, then use break when the user entered quit:
while True:
    x = raw_input("Enter number here (or 'quit' to end): ")
    if x == 'quit':
        break

    # ...


text:
Q: Why are these variables getting cleared/reset? I am attempting to write a small library for scrolling events in JavaScript, but I must be missing something easy, because it seems that my vars are getting reset at some point inside of this method.
Here is the code:
var scrollEvents = {
  change: window.onscroll = function (selector, property, initialValue, changedValue) {
    // grab the selectors and convert them into an array so we can use forEach()
    var items = document.getElementsByClassName(selector);
    var itemArray = [].slice.call(items);
    // window.pageYOffset has better compatibility than document.body.scrollTop
    var scrollPos = window.pageYOffset;
    var breakPoint = 10;
    if (scrollPos > breakPoint) {
      console.log('if');
      console.log(items);
      console.log(itemArray);
      itemArray.forEach(function (i) {
        i.setAttribute("style", property + ": " + changedValue + ";");
        console.log("style", property + ": " + changedValue + ";")
      });
    } else {
      console.log('else');
      console.log(itemArray);
      itemArray.forEach(function (i) {
        i.setAttribute("style", property + ": " + initialValue + ";");
      });
    }
  }
};

And I would like to call it like so:
scrollEvents.change("foo", "height", "400px", "800px");

I have quite a few extra console.log() calls inside there because I have been trying to diagnose the issue, but I have rewritten the code several times and seem to have hit a dead end.
The behavior I would like is that I can call scrollEvents.change() passing those parameters to change style attributes at certain scroll points.
Here is the code without all the extra console.log()'s:
var scrollEvents = {
  change: window.onscroll = function (selector, property, initialValue, changedValue) {
    // grab the selectors and convert them into an array so we can use forEach()
    var items = document.getElementsByClassName(selector);
    var itemArray = [].slice.call(items);
    // window.pageYOffset has better compatibility than document.body.scrollTop
    var scrollPos = window.pageYOffset;
    var breakPoint = 10;
    if (scrollPos > breakPoint) {
      itemArray.forEach(function (i) {
        i.setAttribute("style", property + ": " + changedValue + ";");
      });
    } else {
      itemArray.forEach(function (i) {
        i.setAttribute("style", property + ": " + initialValue + ";");
      });
    }
  }
};

UPDATE:
Thanks to @pointy this library now works: https://github.com/ryanpcmcquen/scrollEvents

A: You've set up an object with a property called "change", and you've assigned a function to that property. The assignment also assigned the function to the "onscroll" property of the window object.
When the browser detects a user scroll operation, it will invoke that function, and regardless of your formal parameter list in the declaration it'll pass either nothing (Internet Explorer) or an event object.
Making a call to scrollEvents.change will invoke the event handler function, but that will have no effect on how the browser invokes the event handler when the user messes with the scrollbar or mouse wheel (or whatever).
I'm not sure exactly how you intend for this API to work, so it's hard to say how to fix it. If you want to attach just one event handler at a time, then the simplest thing to do would be to wrap your current code in another function:
var scrollEvents = {
  change: function (selector, property, initialValue, changedValue) {
    window.onscroll = function(event) {
      // grab the selectors and convert them into an array so we can use forEach()
      var items = document.getElementsByClassName(selector);
      var itemArray = [].slice.call(items);
      // window.pageYOffset has better compatibility than document.body.scrollTop
      var scrollPos = window.pageYOffset;
      var breakPoint = 10;
      if (scrollPos > breakPoint) {
        itemArray.forEach(function (i) {
          i.setAttribute("style", property + ": " + changedValue + ";");
        });
      } else {
        itemArray.forEach(function (i) {
          i.setAttribute("style", property + ": " + initialValue + ";");
        });
      }
    };
  }
};

Now when you call
scrollEvents.change("foo", "height", "400px", "800px");

then that function call will establish the event handler.


text:
Q: C++ Get all variables by object type Is it possible to get all variables in memory by type?
Example:
string container[]; //Array that will contain the objects
GetAllObjects(string, &container); //Get all the objects by specified object type

A: No, not generally.
If the objects itself maintain a list of them, ie. the constructor adds it´s own object to some global array/list and the destructor removes it, then yes. But without changes to the class, it isn´t possible.
If you plan to implement such a list thing, pay attention to multi-thread locking.


text:
Q: Can I get image from canvas element and use it in img src tag? Is there possibility to convert the image present in a canvas element into an image representing by img src?
I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader() or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.
This is my html:

        <canvas id="transform_image"></canvas>

image from canvas

In JavaScript it should look something like this:
$(document).ready(function() {
    img = document.getElementById('picture');
    canvas = document.getElementById('transform_image');

    if(!canvas || !canvas.getContext){
        canvas.parentNode.removeChild(canvas);
    } else {
        img.style.position = 'absolute';
    }
    transformImg(90);
    ShowImg(imgFile);
}

function transformImg(degree) {
    if (document.getElementById('transform_image')) {
        var Context = canvas.getContext('2d');
        var cx = 0, cy = 0;
        var picture = $('#picture');
        var displayedImg = {
            width: picture.width(),
            height: picture.height()
        };
        var cw = displayedImg.width, ch = displayedImg.height
        Context.rotate(degree * Math.PI / 180);
        Context.drawImage(img, cx, cy, cw, ch);
    }
}

function showImg(imgFile) {
    if (!imgFile.type.match(/image.*/))
    return;

    var img = document.createElement("img"); // creat img object
    img.id = "pic"; //I need set some id
    img.src = imgFile; // my picture representing by src
    document.getElementById('image_for_crop').appendChild(img); //my image for crop
}

How can I change the canvas element into an img src image in this script? (There may be some bugs in this script.)

A: Do this.  Add this to the bottom of your doc just before you close the body tag.

Of course somewhere in your doc you need the canvas tag that it will grab.
<canvas id="yourCanvasID" />

A: I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!

A: canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.

A: canvas.toDataURL() will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);

Complete example
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a , filled with the <canvas>'s data url.

// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");

// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");

ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
  ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();

// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();

document.getElementById('result').appendChild(target);
canvas { border: 1px solid black; }
img    { border: 1px solid blue;  }
body   { display: flex; }
div + div {margin-left: 1ex; }

Original:

  <canvas id="canvas" width=200 height=100></canvas>

Result via <img>:

See also:

*

*MDN: canvas.toDataURL() documentation

A: Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/

here the image should apear

<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>

Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server ---  ASP.net C# (.aspx web form page)  Any advice would be cool....


text:
Q: xslt1.0 replace is not working I have URLs with some special characters and i would like to replace them and I am using xslt 1.0 so I am writing the code as below.
<xsl:template name="string-replace-all">
        <xsl:param name="text"/>
        <xsl:param name="replace"/>
        <xsl:param name="by"/>
        <xsl:choose>
            <xsl:when test="contains($text,$replace)">
                <xsl:value-of select="substring-before($text,$replace)"/>
                <xsl:value-of select="$by"/>
                <xsl:call-template name="string-replace-all">
                    <xsl:with-param name="text" select="substring-after($text,$replace)"/>
                    <xsl:with-param name="replace" select="$replace"/>
                    <xsl:with-param name="by" select="$by"/>
                </xsl:call-template>
            </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$text"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

and calling like this:

            <xsl:variable name="link">
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="@FileRef"/>
                <xsl:with-param name="replace" select="'''"/>
                <xsl:with-param name="by" select="'%27'"/>
            </xsl:call-template>
            </xsl:variable>-->
                <xsl:value-of select="@New_x0020_Doc_x0020_Title" disable-output-escaping="yes" />

I am getting the error "webpart cannot be displayed". Can anyone please suggest what am i doing wrong here?

A: The provided "replace" template is working.
To confirm this use the following transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="/*">
        <xsl:variable name="link">
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="@FileRef"/>
                <xsl:with-param name="replace">'</xsl:with-param>
                <xsl:with-param name="by" select="'%27'"/>
            </xsl:call-template>
        </xsl:variable>

        "<xsl:value-of select="$link"/>"
    </xsl:template>

    <xsl:template name="string-replace-all">
        <xsl:param name="text"/>
        <xsl:param name="replace"/>
        <xsl:param name="by"/>
        <xsl:choose>
            <xsl:when test="contains($text,$replace)">
                <xsl:value-of select="substring-before($text,$replace)"/>
                <xsl:value-of select="$by"/>
                <xsl:call-template name="string-replace-all">
                    <xsl:with-param name="text" select="substring-after($text,$replace)"/>
                    <xsl:with-param name="replace" select="$replace"/>
                    <xsl:with-param name="by" select="$by"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$text"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

when the transformation is applied on this XML document:
<t FileRef="Abc'Xyz'Tuv"/>

the wanted, correct result is produced:
"Abc%27Xyz%27Tuv"

The problem may be in the way you specify the replace parameter (uneven number of apostrophes in the expression):
Instead of:
<xsl:with-param name="replace" select="'''"/>

Use:
<xsl:with-param name="replace">'</xsl:with-param>


text:
Q: How to fix command prompt cutting of start of output? For a long time inside of Visual Studio 2019, and also pretty much everywhere else in windows, my command prompt has cut out the first few lines/characters when opening it.
Meaning something like this:

Ends up looking like this:

I've tried playing around with the cmd prompt preferences for window and buffer size but it changes nothing.
Does anyone know how to fix this?


text:
Q: If $A$ is a rank one linear transformation, show there is a unique scalar $\alpha$ such that $A^2 = \alpha A$
If $A$ is a rank one linear transformation, show there is a unique scalar $\alpha$ such that $A^2 = \alpha A$. Then, if $\alpha \neq 1$, show that $1-A$ is invertible.

This is problem 9, section 52 of Halmos, Finite Dimensional Vector Spaces. I have been thinking about this for a while, but my attempts have not produced any worthwhile results/progress.

A: Hint:
Let $R_t$ be a non-zero row of $A$. Then, for each $R_i$, $\exists \ \alpha_i$, such that $R_i = \alpha_i R_t$. Then, how may we represent $A$?


text:
Q: Returning only the last value Returning only the last value
The code works only if the last item of for each loop, help me
this is my view code
<?php if($value->lnkCod == $link_id){echo'exemple';}?>

Model
public function AddClass($user_id)
    {
        $this->db->select('lnkCod');
        $this->db->where('user_id', $user_id);

        $query = $this->db->get('site_votos');

        return $query->result_array();

    }

Controller
$user_id = $this->session->userdata('user_id');
$id_post_addclass = $this->user->AddClass($user_id);

        foreach ($id_post_addclass as $valor) {

            $lnkCod = $valor['lnkCod'];
        }

        $this->data['link_id'] = $lnkCod;

$this->load->view('site/home/index', $this->data);

A: You are not placing the data in array.I wonder what you want to achieve but if you want to put all your data in $lnkCod then you should first declare it as array like this
$lnkCod = array();

then in your foreach loop use like this
 foreach ($id_post_addclass as $valor) {

            $lnkCod[] = $valor['lnkCod'];
        }

data['link_id'] = $lnkCod;
$this->load->view('your_view',$data);

Feel free to let me know if you have any question.
--Update--
In your view you have can access like this
foreach($link_id as $id)
{
echo $id;
}


text:
Q: Get the key of the clicked fluent ui button menu Once again I have the confirmation the Microsoft documentation, is really poorly auto-generated with a useless content.
I have a Fluent UI, Splitbutton. Here are the poorly generated docs. And there are two options "Email message" and "Calendar event"... is not clear at all how to get the click on these items and understand what item was clicked... I tried the following codepen
const menuProps: IContextualMenuProps = {
  items: [
    {
      key: 'emailMessage',
      text: 'Email message',
      iconProps: { iconName: 'Mail' },
    },
    {
      key: 'calendarEvent',
      text: 'Calendar event',
      iconProps: { iconName: 'Calendar' },
    },
  ],
  onItemClick: onItemClick,
};

function onItemClick(event){
  console.log(event.currentTarget);
}

First of all the onClick in example is on the button itself, not on the menu items without any suggestion how to get them. Finally, after some researches, I found in another doc that it needs probably to have a onItemClick in the Props... undocumented, but then, also what is the type of this event and how to get the item key?

A: Completely by chance found an example on a non-ms related site, cause that is completely missing from the docs:
function onItemClick(event, item){
  console.log(item.key);
}

A: For the sake of completeness. There is even a whole documentation page just for the ContextualMenu, where the complete IContextualMenuProps interface is described along with some examples.
There you can see the type of onItemClick:
(ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => boolean | void

If you take a closer look at the Button documentation you mentioned before, there is also a link to the said documentation under Implementation -> IButtonProps interface -> menuProps