Q: Display external website page in asp .net mvc 5 I am building a website for a class project using ASP NET MVC 5, wherein I need a section of the website to display a page from a different website. The goal is to somehow embed that page in my view, so UI interactions are still possible with the embedded page, as if the page was visited directly in the browser (the end effect is that the page is rendered and allows interaction but my website theme always stays around it)
I know one way to do it is to just put it inside an iframe in my View. But I want to know if there is a different solution. My instructor suggested using partial views, but I can't figure out how to achieve the same result. Can anyone suggest a different way to achieve this ? Also, what would be the right way to do this in terms of security (I believe iframe is), but I want to know other's opinion ?
Thanks.

A: I suggest you use a sandboxed IFrame e.g.
http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
    src="https://blah.com/index.html"
    style="border: 0; width:130px; height:20px;">
</iframe>

You can tweak how much power the content in the Iframe has (i.e. can it run scripts).
I guess you could also look at using a partial view. My guess is you'd need to use a WebClient instance to download the HTML source of the target webpage, and then pass that HTML into a partial view. But I don't see how any script tags would render correctly for you, which means the page would not be interactive.


Q: In LibreOffice Calc, how do I change through LibreOffice Basic the value of a cell with an event listener set to it without crashing the program? I am trying to create two tables which mirror changes made to any of them to one another automatically.
To that end, I added event listeners which are triggered when the cells of these tables are edited by the user.
Unfortunately, editing one of the tables causes LibreOffice to crash, even though the changes are indeed reflected correctly, as seen upon reopening the file.
I thought the crash might be due to a never-ending circular reference, but it still crashes after it has been made non-circular (by commenting out the relevant parts of the code so that changes are reflected only one way rather than both ways).
I noticed the code worked fine when writing to a cell that didn't have an event listener set to it.
How can I write to one of the cells with event listeners set to them without causing LibreOffice to crash?
You may want to download the following file. Please run Main and then try editing the cell C3 of the Planning sheet. The arbitrary string "C" should be written in the cell C4 of the Services sheet.
Here is a simplified version of the code :
REM  *****  BASIC  *****

const SERVICESSHEET_NUMBER = 2
const SERVICESSHEET_SERVICES_COLUMN = 2

Type cellStruct
    columnNumber As Integer
    rowNumber As Integer
End Type

Sub UpdateServicesSheet(editedCell As cellStruct, newValue As String)

    Dim oSheets
    Dim servicesSheet

    oSheets = ThisComponent.getSheets()
    servicesSheet = oSheets.getByIndex(SERVICESSHEET_NUMBER)

    servicesSheet.getCellByPosition(SERVICESSHEET_SERVICES_COLUMN, 3).setString(newValue)

End Sub

Private oListener, cellRange as Object

Sub AddListener
    Dim sheet, cell as Object

    sheet = ThisComponent.Sheets.getByIndex(0)  'get leftmost sheet
    servicesSheet = ThisComponent.Sheets.getByIndex(2)

    cellRange = sheet.getCellrangeByName("C3")
    oListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener")  'create a listener
    cellRange.addModifyListener(oListener)  'register the listener

    cellRange = servicesSheet.getCellrangeByName("C4")
    oListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener")  'create a listener
    cellRange.addModifyListener(oListener)  'register the listener
End Sub

global CircularReferenceAllowed As boolean

Sub Modify_modified(oEv)

    Dim editedCell As cellStruct
    Dim newValue As String

    editedCell.columnNumber = 2
    editedCell.rowNumber = 2

    If CircularReferenceAllowed Then
        CircularReferenceAllowed = false
        UpdateServicesSheet(editedCell, "C")
    End If

End Sub

Sub Modify_disposing(oEv)
End Sub

Sub RmvListener
    cellRange.removeModifyListener(oListener)
End Sub

Sub Main

    CircularReferenceAllowed = true
    AddListener

End Sub

Crossposted to :

*

*OpenOffice forums

*LibreOffice discourse platform

A: It seems like the event trigger is within another event's function is causing the crash. In any case, the solution is to remove the listener, then add it back after modifying the other cell.
You do need to global the Listener and the Cell objects to make this work.
This code is simplified to work on C3 and C15 on the first sheet. It would also output some information on C14, which isn't really necessary for your purpose, but I use it to see what's happening. You need to adopt the according to what you need.
global goListener as Object
global goListener2 as Object
global goCellR as Object
global goCellR2 as Object
global goSheet as Object

global giRun as integer
global giUpd as Integer

Sub Modify_modified(oEv)
    Dim sCurStr$
    Dim sNewStr As String
    'xRay oEv

    giRun = giRun + 1
    sCurStr = oEv.source.string

    oCell = goSheet.getCellByPosition(2, 14)
    If (oCell.getString() <> sCurStr) Then
        ' only update if it's different.
        giUpd = giUpd + 1
        goCellR2.removeModifyListener(goListener2)
        oCell.setString(sCurStr)
        goCellR2.addModifyListener(goListener2)
    End If
    sNewStr =sCurStr & " M1 Run=" & giRun & " Upd=" & giUpd
    goSheet.getCellByPosition(2, 13).setString(sNewStr)
End Sub

Sub Modify2_modified(oEv)
    Dim sCurStr$
    Dim sNewStr As String
    Dim oCell as Object
    'xRay oEv

    giRun = giRun + 1
    sCurStr = oEv.source.string
    oCell = goSheet.getCellByPosition(2, 2)
    If (oCell.getString() <> sCurStr) Then
        ' only update if it's different.
        giUpd = giUpd + 1
        goCellR.removeModifyListener(goListener)
        oCell.setString(sCurStr)
        goCellR.addModifyListener(goListener)
    End If
    sNewStr =sCurStr & " M2 Run=" & giRun & " Upd=" & giUpd
    goSheet.getCellByPosition(2, 13).setString(sNewStr)
End Sub

Sub Modify_disposing(oEv)
    MsgBox "In Modify_disposing"
End Sub

Sub Modify2_disposing(oEv)
    MsgBox "In Modify2_disposing"
End Sub

Sub RmvListener
    MsgBox "In RmvListener"
    goCellR.removeModifyListener(goListener)
    goCellR2.removeModifyListener(goListener2)
End Sub

Sub AddListener

    goSheet = ThisComponent.Sheets.getByIndex(0)  'get leftmost goSheet
    'servicesSheet = ThisComponent.Sheets.getByIndex(2)

    goCellR = goSheet.getCellrangeByName("C3")
    goListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener")  'create a listener
    goCellR.addModifyListener(goListener)  'register the listener

    goCellR2 = goSheet.getCellrangeByName("C15")
    goListener2 = createUnoListener("Modify2_","com.sun.star.util.XModifyListener")  'create a listener
    goCellR2.addModifyListener(goListener2)  'register the listener
End Sub

Sub Main
    giRun = 0
    giUpd = 0
    AddListener

End Sub


Q: Why the swift compiler cannot use my subscript? I have code that resembles this
I created custom subscript to do the unwrapping for me to make things easier.
enum MyEnum {
   case one
   case two
   case three
}

struct MyStruct {
   static var empty: Self {
       return .init()
   }

   //Some Variables Here
}

class MyClass {
   var index = 0

   var data: [MyEnum: MyStruct] = [
       .two: .empty,
       .three: .empty,
       .one: .empty
   ]

   var allTypes: [MyEnum] {
       switch Bool.random() {
           case true:
               return [.two, .three]
           case false:
               return [.one]
       }
   }

   var currentSelectedType: MyEnum {
       return allTypes[index]
   }

   func myMethod(type: MyEnum) {
       let one: MyStruct = data[type]!
       let two: MyStruct = data[currentSelectedType]!
       let three: MyStruct = data[allTypes[index]]
       let four: MyStruct = data[.one]

   }
}

fileprivate extension Dictionary {
   subscript(_ key: Key) -> Value where Key == MyEnum, Value == MyStruct {
       get {
           return self[key]!
       }
       set {
           self[key] = newValue
       }
   }
}

in my MyClass myMethod why I have to forcely unwrapp one and two but not three and four otherwise I get a compile time error
       let one: MyStruct = data[type] // Error Value of optional type 'MyStruct?' must be unwrapped to a value of type 'MyStruct'
       let two: MyStruct = data[currentSelectedType] //Error Value of optional type 'MyStruct?' must be unwrapped to a value of type 'MyStruct'

Is there something I'm missing here?

A: I don't have an answer on why compiler isn't picking the expected overload in this situation.
I would recommend clarifying the overload you wish to use at call site, like following.
fileprivate extension Dictionary {
    subscript(safe key: Key, defaultValue: Value = .empty) -> Value where Key == MyEnum, Value == MyStruct {
        get { return self[key, default: defaultValue] }
        set { self[key] = newValue }
    }
}

With above, you can tell compiler explicitly to use your preferred overload.
func myMethod(type: MyEnum) {
    let one: MyStruct = data[safe: type]
    let two: MyStruct = data[safe: currentSelectedType]
    let three: MyStruct = data[safe: allTypes[index]]
    let four: MyStruct = data[safe: .one]
}


Q: How to populate my Django Model 'updated_by' field with logged in User automatically using a formset? I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.
models.py
class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

A: I think the problem lies in your views.py. Try getting request.user before saving the form.

A: i think you should have made form for Inventory if yes(let InvntoryForm) than in view.py file you have done something like this:-
    if request.method == 'POST':
      Inven_form=InventoryForm(data=request.POST)

       if Inven_form.is_valid():
           user=Inven_form.save()
           #in between add this
           Inven_form.updated_by=request.user.username
           user.save()

A: I would use the 'commit=False' argument which will create a new object and assign it without saving to your database.  You can then set the user attribute and call save() with no arguments.
For example, this is how I assigned the user attribute to my blog app.
in views.py
if form.is_valid():
            # Create a new entry and assign to new_article.
            new_article = form.save(commit=False)

            # Set the new article attribute to the current user.
            new_article.user = request.user

            # Save to database now the object has all the required data.
            new_article.save()

Here is the full code for the add_article view if this helps.
@login_required
def add_article(request):
    """ Add a new article. """
    if request.method != 'POST':
        # No data submitted, create a blank form.
        form = AddArticleForm()
    else:
        # POST data submitted, process data.
        form = AddArticleForm(request.POST, request.FILES)
        if form.is_valid():
            new_article = form.save(commit=False)
            new_article.author = request.user
            new_article.save()
            return back_to_blog_page()

    context = {'form': form}
    return render(request, 'add_article.html', context)


Q: Deploying with composer on fabric I am looking for the right way on doing a wordpress deployment using

*

*Fabric

*Composer

What I have:

*

*A nginx, php-fpm and mysql plataform running on Ubuntu 12.04 LTS

*A common sudoer user, as example, I will name "deployer"

*A web user name www-data with a group named www-data
What I am looking for:

*

*Deploy a wordpress site with composer using fabric

*Deployment would be done with the sudoer user named "deployer" but www-data directory owned

*Deploy must be done on /var/www/my_wordpress_site
Issues

*

*Composer couldn't write /home/deployer/.composer, I guess composer try to use it directory since teh user used for the deploy is deployer

*Composer couldn't install dependences

Question:

*

*Could be possible to install the wordpress site on a directory like /home/deployer/my_wordpress_site and make it nginx writable?

*What would be the right way for make deploys on web sites

Fabric Code
<pre>

STAGES = {
        'development' : {
            'hosts'       : ['deployer@deployment-server'],
            'code_dir'    : '/var/www/my_wordpress_site' ,
            'code_branch' : 'development'
            },
            ....
        }

def stage_set(stage_name='development'):
    env.stage = stage_name
    for option, value in STAGES[env.stage].items():
        setattr(env, option, value)
....

@task
def development():
    stage_set('development')

@task
def deploy():
    require('stage', provided_by=(production, staging, development))
    with settings(warn_only=True):
        if sudo("test -d %s" % env.code_dir, user='www-data', group='www-data').failed:
            sudo("git clone git@bitbucket.org:myuser/my_wordpress_site.git %s" % (env.code_dir), user='www-data', group='www-data')
            with cd(env.code_dir):
                sudo("php -r \"copy('https://getcomposer.org/installer', 'composer-setup.php');\"", user='www-data', group='www-data')
                sudo("php -r \"if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;\"", user='www-data', group='www-data')
                sudo("php composer-setup.php", user='www-data', group='www-data')
                sudo("php -r \"unlink('composer-setup.php');\"", user='www-data', group='www-data')
                sudo("php composer.phar install --no-dev", user='www-data', group='www-data')
    with cd(env.code_dir):
        sudo("git pull", user='www-data', group='www-data')
        sudo("php composer.phar update --no-dev", user='www-data', group='www-data')
        </pre>


Q: C Library checksum for binary file in windows and linux I'm using CRC library for checksum, for text file the result same in windows and linux, but for binary file the result different.
I'm using mingw for compiler my c program in windows, checksum result different. is there a way checksum result same between windows and linux using CRC library?
Adding code :
I using this code for checksum file, found it from some web googling. (forgot to save the link).
crc32.c
#include <sys/types.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

#define CRC(crc, ch)     (crc = (crc >> 8) ^ crctabb[(crc ^ (ch)) & 0xff])

static const uint32_t crctabb[256] = {
    0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
    0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
    0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
    0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
    0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
    0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
    0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
    0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
    0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
    0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
    0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
    0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
    0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
    0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
    0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
    0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
    0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
    0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
    0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
    0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
    0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
    0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
    0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
    0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
    0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
    0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
    0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
    0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
    0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
    0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
    0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
    0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
    0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
    0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
    0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
    0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
    0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
    0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
    0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
    0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
    0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
    0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
    0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
    0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
    0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
    0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
    0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
    0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
    0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
    0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
    0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
    0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
    0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
    0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
    0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
    0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
    0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
    0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
    0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
    0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
    0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
    0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
    0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
    0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};

uint32_t crc32_total = 0;

int crc32(int fd, uint32_t *cval, off_t *clen)
{
    uint32_t lcrc = ~0;
    int nr ;
    off_t len ;
    char buf[BUFSIZ], *p ;

    len = 0 ;
    crc32_total = ~crc32_total ;
    while ((nr = read(fd, buf, sizeof(buf))) > 0)
        for (len += nr, p = buf; nr--; ++p) {
        CRC(lcrc, *p) ;
        CRC(crc32_total, *p) ;
    }
    if (nr < 0)
        return 1 ;

    *clen = len ;
    *cval = ~lcrc ;
    crc32_total = ~crc32_total ;
    return 0 ;
}

checksum.c
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "crc32.c"

int main (int argc,char *argv[]){
        uint32_t val;
        int ch, fd;
        off_t len;
        int (*cfncn)(int, uint32_t *, off_t *);

        cfncn = crc32;
        fd = STDIN_FILENO;
        if ((fd = open(argv[1], O_RDONLY, 0)) < 0) {
        }
        if (cfncn(fd, &val, &len)) {
        }
        printf("%d\n",val);
}

I run this code checksum binary file
Windows result 10992
Linux result 1663

A: In Windows, you must open the file in binary mode by adding the _O_BINARY flag:
fd = open(argv[1], O_RDONLY | _O_BINARY, 0)

If you don't, the C++ runtime will perform translations on the contents of the file as it's read in. The most obvious result will be to remove all the \r characters from the input, but an even greater danger is that it will signal end-of-file when it reads \x1a and you'll stop prematurely. The first is an attempt to normalize the line-endings between text files on the *nix systems where C was first developed (which uses \n by itself), and text files on Windows (which uses the pair \r\n). The second is backwards compatibility run amok, retaining a convention that existed before DOS when file sizes couldn't be specified in blocks less than 128 characters.


Q: How to change onclick text's position? Hi guys so I'm new to all this html stuff.
Basically;
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick
When i do this the text shows up under the button. I want it next to the button (right)
How can i do that?

A: Add display:inline-block to p tag
Try this.
<button onclick="myFunction()">Click me</button>

Fiddle:https://jsfiddle.net/9yqs14p4/

A: I'm afraid you need to spend a bit more time learning about this. Realistically you'll need to use CSS to style the HTML that is output by your Javascript.
Both CodeSchool and Codecademy have great tutorials on learning the basics of HTML, CSS and Javascript. You'll need to learn these basics if you want to do this sort of thing yourself.
https://www.codeschool.com/
https://www.codecademy.com/
I've copied your example into a CodePen, which helps to show you the roles played by HTML, CSS and Javascript. As an example, the CSS could be;
http://codepen.io/tombeynon/pen/rVQvMO
button{
    float:left;
    margin-right:5px;
}

#demo{
    float:left;
}

A: First of all you have to know, that in HTML there are inline elements, e.g  and block elements, e.g
. That means, what the word says.
You can test the difference:
// block

div1

div2

// inline
span1span2

In the example is used the
 tag which is a block element. Therefore
you see the text below.
<button> is an inline element. If you simply use a span:

it works!


Q: Action Script 3 Errors 1061 and 1120 I'm new to this, not sure what I'm doing wrong, Thank you for help
Please see my code below:
protected function getXMLUrl(vid:String):String {

    //return 'http://v.iask.com/v_play.php?vid='+ vid;

    var rand:*   = Math.random();
    var f1:*     = function (param1:Number) : Number {

        var _loc_2:* = param1.toString(2);
        var _loc_3:* = _loc_2.substring(0, _loc_2.length - 6);
        return parseInt(_loc_3, 2);
    };

    var Str1:*   = "Z6prk18aWxP278cVAH";
    var Date1:*  = new Date();
    var Num:*    = this.f1(int(Date1.time / 1000));
    var str:*    = vid.toString() + str1 + Num + rand.toString();
    var hash:*   = MD5.hash(str);
    var encode:* = hash.substr(0, 16).toString() + Num.toString();

    return 'http://v.iask.com/v_play.php?vid='+ vid + "&ran=" + rand + "&p=i&k=" + encode;
}

And here are the Errors I'm getting
1061: Call to a possibly undefined method f1 through a reference with static type

1120: Access of undefined property MD5.

1120: Access of undefined property str1.

A: Never mind, I fixed it
add
import com.adobe.crypto.MD5;

also deleted all the " :* "


Q: How to draw a point beside a line? I have an arrow that can point at any direction. I need to draw a point alongside, at a specific distance. The point needs to remain on the correct side of the arrow. How do I do this? I know the angle of the arrow.
Illustration:
--->
o

A: If you have a vector representing the arrow, you could make a unit vector then times it by the length that you want and place the point at the end of the new shortened vector.

A: You already know the angle and location of the arrow, so what you should do is just draw the point based on the arrows end-point (the blunt end-point) and in the direction of the arrow + 90º.


Q: Simple Entity Framework 4 adding object We have an MVC application that creates entity models and stores them in a session.  Later on, we want to commit these to the database.  Just trying to do a
db.Attendees.AddObject(attendee);

throws the error
The EntityKey property can only be set when the current value of the property is null.

The entity key is just a simple type of long and is an identity column in the database.  What are we missing?  This seems like such a simple thing to do?  In order to get things to work, we have had to create a copy of the object and then save the copy.  Can you not put entity framework models into session, bring them back out, and then save them?
Here's the Attendee description in the Entity Framework model...it is hitting a SQL Server 2008 DB
[EdmEntityTypeAttribute(NamespaceName="Model", Name="Attendee")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Attendee : EntityObject
{
    #region Factory Method

    /// <summary>
    /// Create a new Attendee object.
    /// </summary>
    /// <param name="attendeeID">Initial value of the AttendeeID property.</param>
    /// <param name="firstName">Initial value of the FirstName property.</param>
    /// <param name="lastName">Initial value of the LastName property.</param>
    /// <param name="email">Initial value of the Email property.</param>
    /// <param name="createdBy">Initial value of the CreatedBy property.</param>
    /// <param name="createdOn">Initial value of the CreatedOn property.</param>
    /// <param name="modifiedBy">Initial value of the ModifiedBy property.</param>
    /// <param name="modifiedOn">Initial value of the ModifiedOn property.</param>
    public static Attendee CreateAttendee(global::System.Int64 attendeeID, global::System.String firstName, global::System.String lastName, global::System.String email, global::System.String createdBy, global::System.DateTime createdOn, global::System.String modifiedBy, global::System.DateTime modifiedOn)
    {
        Attendee attendee = new Attendee();
        attendee.AttendeeID = attendeeID;
        attendee.FirstName = firstName;
        attendee.LastName = lastName;
        attendee.Email = email;
        attendee.CreatedBy = createdBy;
        attendee.CreatedOn = createdOn;
        attendee.ModifiedBy = modifiedBy;
        attendee.ModifiedOn = modifiedOn;
        return attendee;
    }

    #endregion
    #region Primitive Properties

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Int64 AttendeeID
    {
        get
        {
            return _AttendeeID;
        }
        set
        {
            if (_AttendeeID != value)
            {
                OnAttendeeIDChanging(value);
                ReportPropertyChanging("AttendeeID");
                _AttendeeID = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("AttendeeID");
                OnAttendeeIDChanged();
            }
        }
    }
    private global::System.Int64 _AttendeeID;
    partial void OnAttendeeIDChanging(global::System.Int64 value);
    partial void OnAttendeeIDChanged();

A: You should be adding, not attaching, the new objects.
Update If you get the same error when you AddObject, then you need to make sure the StoreGeneratedPattern in SSDL is set to Identity. The designer should do this for you if your DB is set up correctly and your provider supports it.

A: If the item does not exist in the database you do not need to call context.Attach, only context.AddObject or context.<collection>.Add.


Q: How to read excel from aem dam and make it available to download for user Please look into image for code reference . Query builder is giving me zero result .
I have uploaded excel file in dam/empexcelfile folder


Q: Apache Camel Hazelcast queue polling This is a first time I am using Hazelcast distributed cache (queue) via apache camel. I created a route builder where I configured a hazelcast-queue endpoint as described in apache camel documentation. Camel route is started but it wasn't connecting to hazelcast (client configuration) instance. it was always starting new hazelcast (in build /embedded) from library.
I tried passing Hazelcast instance (client config) in route setter using hazel constants host, port, HazelcastInstance name, etc.., but all tries were unsuccessful.

*

*Step 1: I created spring bean for HazelcastInstance (Client network configuration)

*Step 2: Add all apache-camel dependency for Hazelcast

*Step 3: Created RouteBuilder

*Step 4: Override configure method and implemented the following line

Sample code
fromF("hazelcast-%sfoo?queueConsumerMode=Poll", HazelcastConstants.QUEUE_PREFIX)
    .setHeader(HazelcastConstants.INSTANCE_HOST, constant("127.0.0.1"))
    .setHeader(HazelcastConstants.INSTANCE_PORT, constant(5701))
    .setHeader(HazelcastConstants.HAZELCAST_INSTANCE_NAME_PARAM, constant("hazelcastinstance"))
    .log("::>: Camel log " + body());

Camel started and listening [10.67.113.160]:5701 instead [127.0.0.1]:5701.

A: Assuming that you have a running Hazelcast cluster, what you want to achieve can be done with Spring Boot by following the next steps:
1. Add the dependency camel-hazelcast-starter to your project
With maven, you would add the next dependency
<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-hazelcast-starter</artifactId>
</dependency>

2. Create your specific HazelcastInstance
In the example below, it creates a bean called customHazelcastConfig of type HazelcastInstance built from the client configuration file custom-client-hazelcast-config.xml that has been added to the root of the classpath.
@Component
public class HazelcastConfigProvider {

    @Bean
    public HazelcastInstance customHazelcastConfig() {
        return HazelcastClient.newHazelcastClient(
            new ClientClasspathXmlConfig("custom-client-hazelcast-config.xml")
        );
    }
}

3. Specify your HazelcastInstance to your Camel endpoint
In the example below, we indicate camel-hazelcast to retrieve the HazelcastInstance from the registry using customHazelcastConfig as name corresponding to our specific instance created in step #2.
fromF(
 "hazelcast-%sfoo?queueConsumerMode=Poll&hazelcastInstance=#customHazelcastConfig",
  HazelcastConstants.QUEUE_PREFIX
).log("Receiving: ${body}");

4. Switch in client mode (Optional)
By default the component camel-hazelcast is in node mode or cluster mode. To switch in client mode simply add camel.component.hazelcast-queue.hazelcast-mode=client to your application.properties
This step is optional and could be skipped

More details can be found from https://camel.apache.org/components/next/hazelcast-queue-component.html


Q: How to validate the user has been scroll to top when he click on "back to top" button in selenium I came across one of the scenario where I need to validate the user is scroll to top of the page when clicked on the "back to top" button on the bottom of the screen.
I tried with the following way but that didn't work.
I tried to validate the element present on the top of the page using
isDisplayed method

I have attached the image for clear description.

A: Solved it using the javascript concept used pageYOffset method.
Complete code
JavascriptExecutor executor = (JavascriptExecutor) driver;
Long value = (Long) executor.executeScript("return window.pageYOffset;");

pageYOffset method will return the vertical pixels, so as soon I logged in got the vertical pixels and then scrolled to the back to top button and after performing the action on back to top button, again got the vertical pixels and validated it.

A: isDisplayed() checks if the element is actually present in the viewport so it should work. May be put some wait in between clicking and checking isDisplayed for debugging puropose .
if (element.isDisplayed()) {
doSomething();
}
else {
doSomethingElse();
}


Q: CMake build with gcc/g++ fails on Windows I've installed CMake 3.14.4 (from cmake-3.14.4-win64-x64.msi) and GCC 5.1.0 (from tdm64-gcc-5.1.0-2.exe) on Windows 7 Enterprise and 10 Home (64-bit).
I'm trying to build a .LIL from cpp/hpp source files github sources. The CMakeLists.txt refers to includes directory from the COTS install. A header file in the includes directory has this if-else and the CMake build always errors out by falling in the last else block below:
# if defined(_M_AMD64)
#  include <wchar.h>
#  if BIP_CXX11_SUPPORT
typedef char16_t CciChar;
#  else
typedef wchar_t CciChar;
#  endif
typedef __int64 CciInt;
typedef unsigned __int64 CciCount;
#  define __CCI_WINDOWS__
# else
#  error The C plugin interface for IBM Integration Bus is only available
for 64-bit Windows x86-64 systems
#endif

Steps:
1. c:\iib-swm\build>cmake -DIIB_INSTALL_DIR=C:\Progra~1\IBM\IIB\10.0.0.12
-G "MinGW Makefiles" ../source
-- The CXX compiler identification is GNU 5.1.0
-- Check for working CXX compiler: C:/software/C++Tools/tdm-
gcc/bin/g++.exe
-- Check for working CXX compiler: C:/software/C++Tools/tdm-
gcc/bin/g++.exe -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: C:/iib-swm/build

This is the content of CMakeSystem.cmake after this step:
set(CMAKE_HOST_SYSTEM "Windows-6.1.7601")
set(CMAKE_HOST_SYSTEM_NAME "Windows")
set(CMAKE_HOST_SYSTEM_VERSION "6.1.7601")
set(CMAKE_HOST_SYSTEM_PROCESSOR "AMD64")

set(CMAKE_SYSTEM "Windows-6.1.7601")
set(CMAKE_SYSTEM_NAME "Windows")
set(CMAKE_SYSTEM_VERSION "6.1.7601")
set(CMAKE_SYSTEM_PROCESSOR "AMD64")

set(CMAKE_CROSSCOMPILING "FALSE")

set(CMAKE_SYSTEM_LOADED 1)

2. c:\iib-swm\build>cmake --build .

   -- Configuring done
   -- Generating done
   -- Build files have been written to: C:/iib-swm/build
   [ 33%] Building CXX object
   CMakeFiles/statsdsw.dir/StatsdStatsWriter.cpp.obj
   In file included from
   C:/Progra~1/IBM/IIB/10.0.0.12/server/include/plugin/BipCci.h:14:0,
             from
   C:/Progra~1/IBM/IIB/10.0.0.12/server/include/plugin/BipCsi.h:14,
             from C:\iib-swm\source\StatsdStatsWriter.hpp:13,
             from C:\iib-swm\source\StatsdStatsWriter.cpp:10:
   C:/Progra~1/IBM/IIB/10.0.0.12/server/include/plugin/BipCos.h:170:4:
   error: #error The C plugin inter
   face for IBM Integration Bus is only available for 64-bit Windows x86-
   64 systems
   #  error The C plugin interface for IBM Integration Bus is only
   available for 64-bit Windows x86-64
   systems
      ^
   CMakeFiles\statsdsw.dir\build.make:62: recipe for target
   'CMakeFiles/statsdsw.dir/StatsdStatsWriter.
   cpp.obj' failed
   mingw32-make.exe[2]: ***
   [CMakeFiles/statsdsw.dir/StatsdStatsWriter.cpp.obj] Error 3
   CMakeFiles\Makefile2:71: recipe for target
   'CMakeFiles/statsdsw.dir/all' failed
   mingw32-make.exe[1]: *** [CMakeFiles/statsdsw.dir/all] Error 130
   Makefile:82: recipe for target 'all' failed
   mingw32-make.exe: *** [all] Error 130

I just can't understand that even when CMake recognizes the system processor as AMD64, it doesn't translate to _M_AMD64 in the includes .h file? I've trawled CMake and related resources on the net. Tried running CMake as admin, shortened the path in which git project was cloned to without luck.
PS: My only brush with cpp was at Uni 15 years ago, so please have mercy my lords (and ladies) if I've missed to C the obvious.

A: _M_AMD64 appears to be specific to Visual Studio compilers.  The question is confusing because it suggests that CMake is doing the pre-processing.  It doesn't.  You are using gcc. gcc doesn't appear to implement the Visual Studio specific pre-processor macros.
You'll either have to alter the code to work with gcc or define the missing macros yourself using a CMake command like target_compile_definitions.
Be aware that the README file says to use Visual Studio 2015 for building on Windows.


Q: How to Display Updated Array After Adding To It? Just trying to figure this out, can't really get there...
Basically, I have something in state called "arrayCodes" that is nothing but an array of strings. I want to type in something to add in the textbox, push it to the end of the "arrayCodes", then want the updated array to display on screen. Right now, I get 'A1A2' as the output, but I want 'A1A2(userinput)'. I've put some console logs, and it has confirmed that the user input is getting added to the state, but I can't figure out how to display it on screen. Any help is greatly appreciated.
Here is the component in question:
import React, { Component } from 'react';

class Testing extends Component {
    state = {
        arrayCodes: ['A1', 'A2'],
        currentCode: '',
    }

    addEditCode = (inputCode) => {
        //console.log("Add Edit Code")
        var arrayCode;
        arrayCode = this.state.arrayCodes
        console.log("array code before push", arrayCode)
        arrayCode.push(inputCode)
        console.log("array code after push", arrayCode)
        this.setState({ arrayCodes: arrayCode })
        console.log("Array of Codes is now: ", this.state.arrayCodes)
    }

    setCurrentCode = (input) => {
        this.setState({ currentCode: input })
    }

    render() {
        return (

                <input type="text"
                    name="enteredCode"
                    placeholder="Enter an edit code to add..."
                    onChange={(event) =>
                    this.setCurrentCode(event.target.value)} />

                <button onClick={() =>
                this.addEditCode(this.state.currentCode)}>Click to
                add</button>

Current array in state: {this.state.arrayCodes}

        );
     }
}

export default Testing;

A: It looks like you're updating the wrong property in state. Updating editCodes array, but never reading from it. In addEditCode method, shouldn't this line:
this.setState({ editCodes: arrayCode })
be this:
this.setState({ arrayCodes: arrayCode })
?

A: You want something like this:
class Testing extends React.Component {
  state = {
    arrayCodes: ["A1", "A2"],
    currentCode: ""
  };

  addEditCode = inputCode => {
    const { arrayCodes } = this.state;
    arrayCodes.push(inputCode);
    this.setState({ arrayCodes });
  };

  setCurrentCode = input => {
    this.setState({ currentCode: input });
  };

  render() {
    return (

        <input
          type="text"
          name="enteredCode"
          placeholder="Enter an edit code to add..."
          onChange={event => this.setCurrentCode(event.target.value)}
        />
        <button onClick={() => this.addEditCode(this.state.currentCode)}>
          Click to add
        </button>

          Current array in state:
          {this.state.arrayCodes.reduce((acc, c) => {
            return acc + c;
          }, "")}

    );
  }
}

Working example here.

A: Well the problem is in the states

*

*editCodes ==> the one getting updated but not in the render method

*arrayCodes ==>the one you are showing in the render method

*currentCode ==> saving the value temporarily for the new value

Just Change it to
addEditCode = inputCode => {
        let arrayCodes = this.state.arrayCodes;
        arrayCodes.push(inputCode);
        this.setState({
          arrayCodes
        });
     };

Happy Coding \m/
In addition to that Use map or reduce to render the updated array


Q: Copy data from one table and save it into another table in different database on different SQL Server I have two different databases in two different SQL Servers. The databases are identical in schema but contain different data in one of the tables.
I want to copy all the data from one table in one database to the same table in the other database so that I can get rid of the database from which I am copying the data.
The data is too large so I cannot create data scripts and run it onto other database.
How can I achieve this?

A: There are many ways like ssis transfer,select * into ,but i prefer below way if you are just transferring data
create a linked server on source server for destination server,then you could refer destination server with four part name
Assuming linked server of source is A and destination server is B,data moving is as simple as
insert into B.databasename.Schema.Table
select * from table---this is in source server and db

if data is huge and you may worry about time outs,you can write a simple script which can do in batches like
 While (1=1)
    begin
    insert into B.databasename.Schema.Table
    select  top 10000* from table---this is in source server and db
    if (@@rowcount=0)
    break
    end

Creating linked server ,you can follow this

A: You have the following options available to you.  Not all of these will work, depending on your exact requirements and the networking arrangements between the servers.

*

*SQL Server Management Studio - Import & Export Wizard: this is accessed from the right-click menu for a database > Tasks > Import Data (or Export Data).

*SQL query using a Linked Server: a Linked Server configured between the two servers allows you to reference databases on one from the other, in much the same way as if they were on the same server. Any valid SQL query approach for transferring data between two tables within one database will then work, provided you fully-qualify the table names as Server.Database.Schema.Table.

*SSIS: create an SSIS package with both servers as connections, and a simple workflow to move the data from one to the other. There is plenty of information available online on how to use SSIS.

*Export to flat-file format then import: this could be done using the Import/Export Wizard above or SSIS, but instead of piping the data directly between the two servers, you would output the data from the source table into a suitable flat-file format on the filesystem.  CSV is the most commonly used format for this. This file can then be moved to the destination server using any file transfer approach (compressed e.g. to a Zip file if desired), and imported into the destination table.

*Database backup and restore: Similar to (4), but instead of using a flat file, you could create a backup of the source database via Tasks > Back Up...  You then move that backup as a file (just like the CSV approach), and restore it onto the destination server. Now you have two databases on the destination server, and can move data from one to the other locally.

A: I hope, this query helps you!!!
INSERT INTO [dbo].[tablename] (Column1, Column2,Column3)
(select Column1, Column2,Column3, from [Database1].[dbo].[tablename]

Thanks!!!


Q: Iterate a File System and write results to CSV file I'm writing a program that iterates a file tree and now I need it to write the results to a csv file. It's required that the contents be sorted alphanumerically before being written to the csv file. So I have been saving the files to a List.
FileInfo fi = new FileInfo(file);
fileList.Add( new Record {
    fileName = fi.Name,
    fileSize = fi.Length
});

Where Record is a class:
public class Record
{
    public long fileSize { get; set; }
    public string fileName { get; set; }

}

Then I'm doing a plain old Sort(). Now how can I write this list to a csv?
I welcome any better ways to do the whole process.
Is there a way that I can write the results to the csv as I go and then sort the csv alphanumerically? Basically the program has to sort it and not the user.
The csv also needs headers if you could get me going on that as well.

A: As long as you can fit all of the data in memory you're better off holding onto it all and sorting it in memory rather than writing it to a file.  The concept of sorting data in a file is generally solved by "read it into memory, sort it, and write it back out again".
As for writing a CSV file, it's not really that hard.  I like to use a StringBuilder to add on each of the fields for each line, and then once I have a line I append that line to the file.  For the headers, you either hard code them if appropriate, or get them from whatever source you have if it's dynamic.  Do you not know how to write to a file?  My guess is the File.WriteAllText() and File.AppendText() methods will be all you should need for that.
Just a general tip, since you asked, is that rather than adding the items to the list, since you'll eventually sort them all, is to add them to a SortedList, so that they're sorted as you go.  Then when you're done, you just get them one at a time and they are already in order.

A: You can use LINQ for the sorting and a StreamWriter for the file creation.
using (var writer = new StreamWriter(@"C:\files.csv")) {
    writer.WriteLine("Name,Size"); // Header
    var query = fileList.OrderBy(r => r.fileName);
    foreach (Record record in query) {
        writer.WriteLine("\"{0}\",{1}", record.fileName, record.fileSize);
    }
}

Note that I enclosed the file name in double quotes ("), in the case that a comma (,) is part of the file name. The double quote itself is not a valid character for file names in Windows, so that it should not be a problem.


Q: Django: Image from static folder doesn't load I need help=)
Image from static folder doesn't load.
Version: Django  1.11.3
This is my code:
first_project/first_project/settings.py:
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

TEMPLATE_DIR=os.path.join(BASE_DIR,"templates")
STATIC_DIR=os.path.join(BASE_DIR,"static")

...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first_app',
]

...

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS=[
    STATIC_DIR,
    os.path.join(BASE_DIR,"first_app","static","first_app"),
]

first_project/templates/first_app/index.html:
<!DOCTYPE html>
{% load static %}

    <meta charset="UTF-8">
    <title>Yp</title>

This is yp picture!

first_project/static/first_app/yp.jpg - the path to the image.
Thank you!

A: you should to do several things but I think you don't
do that.
I create a simple project only for you and added to my GitHub
just click in this link: GitHub first Project templates
if it is helpful please, take a vote.

A: First of all, you wrote scr, not src and this should be corrected.

After that you may need to clear "first_app/" part from your code, because you are adressing your directory directly in settings file.


Q: How can I recycle controllers in UICollectionView's cellForItemAtIndexPath? I am displaying a number of cells, whose content is reasonably memory intensive. I have a custom controller that sets up a view to display the content, and updates the UI periodically. However, often UICollectionView asks for a particular cell several times. I want to know how to design (well) a system to re-use the controller + view if I have already created it for a given piece of data.  I thought about storing a controller reference in the data object, but don't know if storing UI elements in what is meant to be data is a good idea. Also, if I did this, I would need to monitor retainCount on cell unload, and when it gets to '1', remove it from the data object, which seems a bit hacky.  Similarly, a NSDictionary of data->controller pairs in the UICollectionView could also work, and would again require monitoring retainCount, or re-implementing a retain counting mechanism for my particular case.  It's doable, but seems clunky.
I'm very new to ios, so it may be I'm approaching this all wrong. Any suggestions are greatly appreciated!

A: First of all, think if displaying a controller view inside a cell is a good idea. I'm not sure, but since i'm not familiar with your project, it's something only you can tell.
Secondly, You can create your own pool of controllers. When you need a controller to put inside the cell (in cellforIndexPath method), take one from the pool. If the pool is empty, create a new one.  The cell shouldn't come with a controller of it's own, put it only in cellForItemMethod.


Q: REST - Canonical URI vs Relative URI (from a user point of view) I'm currently designing a service.
It is a multi-tier service, that stores data from several clients using a REST interface.
It's not clear to me how should I accept a resource id inside the URI.
Let's say the user 001 creates a resource, the first for him, but the 100th for the system.
What should I return when the user 001 makes a GET to /resource/1 (/resource/{id}). Should I display his record thus making the URI relative to the user performing the request? Or should I return the 1st for the system (denying it because it's missing the permissions to see it)?
I don't want to go deep inside the authorization stuff, but I'd like to know how should I handle this kind of situations. If I should prefer the latter then how can I make a user say "ok, give me the 1st resource I created" or "give me the 2nd ... ", "give me the last .. ", "give me the 100th resource I created"?

A: I dont claim to be an expert on REST but here is what I would probably do.
In your domain model, if a resource cannot exist without a user then its perfectly OK to model URL calls such as
GET /user/{userId}/resource  //Gets all resources of a user

On the other hand if resources can exist without users then this link on stackoverflow gives a nice way of modelling such calls.
RESTful Many-to-Many possible?
Another thing which we did for one of our projects was that, we had the linking table (UserResource table(id,userId,resourceId) ,and  we had a unique ID for that and had something like
GET /userResource/{userResourceId}

 GET /userResource               //Retrieve all the resources user has access to

If security is your concern , there are links on StackOverflow on how to integrate Security with Rest calls. Ideally such logic should be handled on the serverside. You typically do not want to put that logic into the REST url.
For example if you get a call for
GET /resource  //Get all resources

Depending on who the user is, you return only that subset of resources he has access to.
Bottom Line : Dont build your resources around permissions.
Again, I am not an expert. Just my humble views. :-)


Q: JSON to Python not working correcly I have the following json string
{
    "meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 3
    },
    "objects": [
        {
            "id": 1,
            "name": "Exercicios_EO_JorgeLoureiro-cópia-não.está.exactament.igual.pdf\n",
            "resource_uri": "/api/open/1/"
        },
        {
            "id": 2,
            "name": "api.py\n",
            "resource_uri": "/api/open/2/"
        },
        {
            "id": 3,
            "name": "models.py\n",
            "resource_uri": "/api/open/3/"
        }
    ]
}

which i get from doing a server call and reading the response
response = url2.urlopen("http://127.0.0.1:8000/api/open/?format=json")
data = response.read()

However, when i load it from json to python via
res = json.loads(data)

i get, from printing res:
{u'meta': {u'previous': None, u'total_count': 3, u'offset': 0, u'limit': 20, u'next': None}, u'objects': [{u'resource_uri': u'/api/open/1/', u'id': 1, u'name': u'Exercicios_EO_JorgeLoureiro-c\xf3pia-n\xe3o.est\xe1.exactament.igual.pdf\n'}, {u'resource_uri': u'/api/open/2/', u'id': 2, u'name': u'api.py\n'}, {u'resource_uri': u'/api/open/3/', u'id': 3, u'name': u'models.py\n'}]}
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 3}, "objects": [{"id": 1, "name": "Exercicios_EO_JorgeLoureiro-cópia-não.está.exactament.igual.pdf\n", "resource_uri": "/api/open/1/"}, {"id": 2, "name": "api.py\n", "resource_uri": "/api/open/2/"}, {"id": 3, "name": "models.py\n", "resource_uri": "/api/open/3/"}]}

{u'meta': {u'previous': None, u'total_count': 3, u'offset': 0, u'limit': 20, u'next': None}, u'objects': [{u'resource_uri': u'/api/open/1/', u'id': 1, u'name': u'Exercicios_EO_JorgeLoureiro-c\xf3pia-n\xe3o.est\xe1.exactament.igual.pdf\n'}, {u'resource_uri': u'/api/open/2/', u'id': 2, u'name': u'api.py\n'}, {u'resource_uri': u'/api/open/3/', u'id': 3, u'name': u'models.py\n'}]}
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 3}, "objects": [{"id": 1, "name": "Exercicios_EO_JorgeLoureiro-cópia-não.está.exactament.igual.pdf\n", "resource_uri": "/api/open/1/"}, {"id": 2, "name": "api.py\n", "resource_uri": "/api/open/2/"}, {"id": 3, "name": "models.py\n", "resource_uri": "/api/open/3/"}]}

{u'meta': {u'previous': None, u'total_count': 3, u'offset': 0, u'limit': 20, u'next': None}, u'objects': [{u'resource_uri': u'/api/open/1/', u'id': 1, u'name': u'Exercicios_EO_JorgeLoureiro-c\xf3pia-n\xe3o.est\xe1.exactament.igual.pdf\n'}, {u'resource_uri': u'/api/open/2/', u'id': 2, u'name': u'api.py\n'}, {u'resource_uri': u'/api/open/3/', u'id': 3, u'name': u'models.py\n'}]}

which is like 3 copies of what I really wanted, which is just that json string to python.
Any clue of what might be going on?
Thanks in advance
Here is the full code
response = url2.urlopen("http://127.0.0.1:8000/api/open/?format=json")
data = response.read()
print data
print "\n"
res = json.loads(data)
print res


Q: Why does LinkedHashSet extend HashSet and implement Set Opened a LinkedHashSet source code today and found some interesting thing:
public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {

The question is: why do they need both "extends HashSet" and "implements Set" when HashSet already is the Set?

A: They didn't need to explicitly write implements Set<E>. They did it for readability.

A: There is another reason; consider the following java program:-
package example;

import java.io.Serializable;
import java.util.Arrays;

public class Test {

 public static interface MyInterface {
  void foo();
 }

 public static class BaseClass implements MyInterface, Cloneable, Serializable {

  @Override
  public void foo() {
   System.out.println("BaseClass.foo");
  }
 }

 public static class Class1 extends BaseClass {

  @Override
  public void foo() {
   super.foo();
   System.out.println("Class1.foo");
  }
 }

 static class Class2 extends BaseClass implements MyInterface, Cloneable,
   Serializable {

  @Override
  public void foo() {
   super.foo();
   System.out.println("Class2.foo");
  }
 }

 public static void main(String[] args) {

  showInterfacesFor(BaseClass.class);
  showInterfacesFor(Class1.class);
  showInterfacesFor(Class2.class);
 }

 private static void showInterfacesFor(Class<?> clazz) {
  System.out.printf("%s --> %s\n", clazz, Arrays.toString(clazz
    .getInterfaces()));
 }
}

Which outputs the following text (java 6u16):
class example.Test$BaseClass --> [interface example.Test$MyInterface, interface java.lang.Cloneable, interface java.io.Serializable]
class example.Test$Class1 --> []
class example.Test$Class2 --> [interface example.Test$MyInterface, interface java.lang.Cloneable, interface java.io.Serializable]

Notice how Class1 does not have explicit interfaces defined, so the Class#getInterfaces() does not include those interfaces, whereas Class2 does. The use of this only becomes clear in this program:-
package example;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import example.Test.BaseClass;
import example.Test.Class1;
import example.Test.Class2;

public class Test2 extends Test {

 public static void main(String[] args) {

  MyInterface c1 = new Class1();
  MyInterface c2 = new Class2();

  // Note the order...
  MyInterface proxy2 = createProxy(c2);
  proxy2.foo();

  // This fails with an unchecked exception
  MyInterface proxy1 = createProxy(c1);
  proxy1.foo();
 }

 private static <T> T createProxy(final T obj) {

  final InvocationHandler handler = new InvocationHandler() {

   @Override
   public Object invoke(Object proxy, Method method, Object[] args)
     throws Throwable {
    System.out.printf("About to call %s() on %s\n", method
      .getName(), obj);
    return method.invoke(obj, args);
   }
  };

  return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
    .getClass().getInterfaces(), handler);
 }
}

Which outputs:-
About to call foo() on example.Test$Class2@578ceb
BaseClass.foo
Class2.foo
Exception in thread "main" java.lang.ClassCastException: $Proxy1 cannot be cast to example.Test$MyInterface
 at example.Test2.main(Test2.java:23)

While Class1 does implicitly implement MyInterface, but the created proxy does not.
Hence if we wanted to create a dynamic proxy which implements all interfaces for an object which has implicit interface inheritance then the only way to do it generically would be to walk the superclasses all the way back to java.lang.Object, as well as walking all the implemented interfaces and their superclasses (remember Java supports multiple interface inheritance), which doesn't sound very efficient, while it is much easier (and faster) to explicitly name interfaces as I suppose they are set in at compile time.
So what uses reflection & proxies? RMI for one...
Therefore, yes it is a convenience, but no it is certainly not redundant: remember that these classes were carefully designed and implemented by Josh Bloch, so I suspect that they were explicitly programmed this way so that proxied network stubs and skeletons work as they do.

A: I've asked Josh Bloch, and he informs me that it was a mistake. He used to think, long ago, that there was some value in it, but he since "saw the light". Clearly JDK maintainers haven't considered this to be worth backing out later.

A: Good catch, they did not need to put java.io.Serializable either.

A: It's redundant. You could do without the implements Set<E>.

A: Perhaps it has something to do with the way javadoc gets generated. You know how Java API tells you all concrete classes that impement an interface or inherit from other classes? While I agree that at runtime its redundant, I can see how this might ease the automatic generation of javadoc. This is just a wild guess of course.


Q: MongoDB: invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [{"type":"Buffer","data":[]}] I am currently struggling to find a document with mongodb. I tried several things but can't understand the root issue or find any helpful information. I want to search for the following document:
{"_id":{"$oid":"5f97f73270f9d39dc29c7a6f"},"name":"XXX","surname":"XXX","position":"XXX"}

I currently have the id as a string, but obviously have an ObjectId in the mongodb collection. I googled around and found calls like
collection.find({ _id: new ObjectId("5f97f73270f9d39dc29c7a6f")})

multiple times, however this just seems to not work as I receive the following error upon execution
Unhandled Rejection (Error): invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [{"type":"Buffer","data":[]}]

I tried ObjectId from mongoose and mongodb. However, with { _id: { $oid: "5f97f73270f9d39dc29c7a6f" }} the query works just fine. Also it would work with the ObjectId object directly returned from a find query. I hope someone got any explanation why it would not work with the mongodb/mongoose ObjectIds.


Q: Draw small circle images over triangle in ios I have a Triangle ,On which I am going to put hollow circles to create a Garland(we can call it rosary).
Each circle is an image which I need to put on triangle on specific place.
Guys, Let me know How would I make it possible?If you need more clarity on this, let me know.
Thanks in advance!

A: like this:
Objective-C:
UIBezierPath* polygonPath = UIBezierPath.bezierPath;
[polygonPath moveToPoint: CGPointMake(80.5, 33)];
[polygonPath addLineToPoint: CGPointMake(119.9, 101.25)];
[polygonPath addLineToPoint: CGPointMake(41.1, 101.25)];
[polygonPath closePath];
[UIColor.grayColor setFill];
[polygonPath fill];

UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(58, 56, 45, 45)];
[UIColor.redColor setFill];
[ovalPath fill];

Swift:
var polygonPath = UIBezierPath()
polygonPath.moveToPoint(CGPointMake(80.5, 33))
polygonPath.addLineToPoint(CGPointMake(119.9, 101.25))
polygonPath.addLineToPoint(CGPointMake(41.1, 101.25))
polygonPath.closePath()
UIColor.grayColor().setFill()
polygonPath.fill()

var ovalPath = UIBezierPath(ovalInRect: CGRectMake(58, 56, 45, 45))
UIColor.redColor().setFill()
ovalPath.fill()

Both produce this:

or this:
Objective-C:
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(40, 18, 91, 91)];
[UIColor.redColor setFill];
[ovalPath fill];

UIBezierPath* polygonPath = UIBezierPath.bezierPath;
[polygonPath moveToPoint: CGPointMake(85.5, 18)];
[polygonPath addLineToPoint: CGPointMake(124.9, 86.25)];
[polygonPath addLineToPoint: CGPointMake(46.1, 86.25)];
[polygonPath closePath];
[UIColor.grayColor setFill];
[polygonPath fill];

Swift:
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(40, 18, 91, 91))
UIColor.redColor().setFill()
ovalPath.fill()

var polygonPath = UIBezierPath()
polygonPath.moveToPoint(CGPointMake(85.5, 18))
polygonPath.addLineToPoint(CGPointMake(124.9, 86.25))
polygonPath.addLineToPoint(CGPointMake(46.1, 86.25))
polygonPath.closePath()
UIColor.grayColor().setFill()
polygonPath.fill()

For this:

And with a frame:
Objective-C:
CGContextRef context = UIGraphicsGetCurrentContext();

CGRect frame = CGRectMake(75, 28, 76, 66);
CGContextSaveGState(context);
CGContextBeginTransparencyLayer(context, NULL);
CGContextClipToRect(context, frame);

UIBezierPath* polygonPath = UIBezierPath.bezierPath;
[polygonPath moveToPoint: CGPointMake(CGRectGetMinX(frame) + 1.48684 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.42424 * CGRectGetHeight(frame))];
[polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 1.98823 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))];
[polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 0.98546 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))];
[polygonPath closePath];
[UIColor.grayColor setFill];
[polygonPath fill];

UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + floor((CGRectGetWidth(frame) - 44) * 0.50000 + 0.5), CGRectGetMinY(frame) + floor((CGRectGetHeight(frame) - 44) * 1.00000 + 0.5), 44, 44)];
[UIColor.redColor setFill];
[ovalPath fill];

CGContextEndTransparencyLayer(context);
CGContextRestoreGState(context);

Swift:
let context = UIGraphicsGetCurrentContext()
let frame = CGRectMake(75, 28, 76, 66)

CGContextSaveGState(context)
CGContextBeginTransparencyLayer(context, nil)

CGContextClipToRect(context, frame)

var polygonPath = UIBezierPath()
polygonPath.moveToPoint(CGPointMake(frame.minX + 1.48684 * frame.width, frame.minY + 0.42424 * frame.height))
polygonPath.addLineToPoint(CGPointMake(frame.minX + 1.98823 * frame.width, frame.minY + 1.42424 * frame.height))
polygonPath.addLineToPoint(CGPointMake(frame.minX + 0.98546 * frame.width, frame.minY + 1.42424 * frame.height))
polygonPath.closePath()
UIColor.grayColor().setFill()
polygonPath.fill()

var ovalPath = UIBezierPath(ovalInRect: CGRectMake(frame.minX + floor((frame.width - 44) * 0.50000 + 0.5), frame.minY + floor((frame.height - 44) * 1.00000 + 0.5), 44, 44))
UIColor.redColor().setFill()
ovalPath.fill()

CGContextEndTransparencyLayer(context)
CGContextRestoreGState(context)

This obviously isn't going to draw a bunch of small circles in the triangle, but you've not specified how many circles need to be drawn and so it's impossible to help you further without this very important information, but this will give you a start.
And for reference, here's where you'll need to visit, the following information is dealing with packing problems and math, specifically packing problems with fitting circls inside of triangles:
https://en.wikipedia.org/wiki/Malfatti_circles
http://hydra.nat.uni-magdeburg.de/packing/crt/crt.html#Download
https://en.wikipedia.org/wiki/Circle_packing_in_an_equilateral_triangle
and then this:

Dense Packings of Equal Disks in an Equilateral Triangle R. L. Graham,
  B. D. Lubachevsky
Previously published packings of equal disks in an equilateral
  triangle have dealt with up to 21 disks. We use a new discrete-event
  simulation algorithm to produce packings for up to 34 disks. For each
  n in the range 22≤n≤34 we present what we believe to be the densest
  possible packing of n equal disks in an equilateral triangle. For
  these n we also list the second, often the third and sometimes the
  fourth best packings among those that we found. In each case, the
  structure of the packing implies that the minimum distance d(n)
  between disk centers is the root of polynomial Pn with integer
  coefficients. In most cases we do not explicitly compute Pn but in all
  cases we do compute and report d(n) to 15 significant decimal digits.
Disk packings in equilateral triangles differ from those in squares or
  circles in that for triangles there are an infinite number of values
  of n for which the exact value of d(n) is known, namely, when n is of
  the form Δ(k):=k(k+1)2. It has also been conjectured that d(n−1)=d(n)
  in this case. Based on our computations, we present conjectured
  optimal packings for seven other infinite classes of n, namely
n=Δ(2k)+1,Δ(2k+1)+1,Δ(k+2)−2,Δ(2k+3)−3,Δ(3k+1)+2,4Δ(k), and 2Δ(k+1)+2Δ(k)−1.

We also report the best packings we found for other values of n in
  these forms which are larger than 34, namely, n=37, 40, 42, 43, 46,
  49, 56, 57, 60, 63, 67, 71, 79, 84, 92, 93, 106, 112, 121, and 254,
  and also for n=58, 95, 108, 175, 255, 256, 258, and 260. We say that
  an infinite class of packings of n disks, n=n(1),n(2),...n(k),..., is
  tight , if [1/d(n(k)+1)−1/d(n(k))] is bounded away from zero as k goes
  to infinity. We conjecture that some of our infinite classes are
  tight, others are not tight, and that there are infinitely many tight
  classes.

http://www.combinatorics.org/ojs/index.php/eljc/article/view/v2i1a1
and this as well:

Abstract
This paper presents a computational method to find good, conjecturally
  optimal coverings of an equilateral triangle with up to 36 equal
  circles. The algorithm consists of two nested levels: on the inner
  level the uncovered area of the triangle is minimized by a local
  optimization routine while the radius of the circles is kept constant.
  The radius is adapted on the outer level to find a locally optimal
  covering. Good coverings are obtained by applying the algorithm
  repeatedly to random initial configurations.
The structures of the coverings are determined and the coordinates of
  each circle are calculated with high precision using a mathematical
  model for an idealized physical structure consisting of tensioned bars
  and frictionless pin joints. Best found coverings of an equilateral
  triangle with up to 36 circles are displayed, 19 of which are either
  new or improve on earlier published coverings.

http://projecteuclid.org/euclid.em/1045952348
and then finally, this:
https://en.wikipedia.org/wiki/Malfatti_circles

A: Thanks Larcerax.
I need to draw 53 circles on the boundary of Triangle Like a Rosary. Each circle will be drawn at specific distance.
Out of 53 circles , 5 would be bigger than others(3 on corners(vertices) and other 2 on middle of 2 sides).
Triangle would stand like Cone.


Q: Possibilities to move file one folder to another on remte FTP server using python Trying to move files one folder to another on remote server using python?
                      shutil.move(src,dest)

but did not work for me any other suggestion?
now trying with ftplib but could not find correct function.


Q: How to prevent reloading the entire component on updating some firestore documents? I am trying to build a drag and drop to do list...After every drag and drop position of each element is updated in firebase...This is the function doing so
unfinishedTodos.forEach((each, index) => {
 firebaseApp.firestore().collection("todos").doc(each.id).update({
   index: index})
});

But after the update function is run the entire component is reloading..The problem is that since there are lots of items in the list I have to again scroll to find the item i was working with...I want to make sure that the firestore documents get updated but the page should not reload...How can I can prevent this reload?
Update:
I found out what went wrong...Actually I was using the onSnapshot function of firebase...So on every change it got triggered and reloaded the data...

A: React updates a component whenever any state or props variable changes.
So, to prevent a re-render conditionally, you can use this lifecycle function (returning false means avoiding a re-render):
class component
shouldComponentUpdate(prevState, prevProps) {
    if (this.state.someVariable !== prevState.someVariable ||
        this.props.someVariable !== prevProps.someVariable) {
        return false;
    }

    return true;
}

functional component
React.memo(MyComponent, (props, nextProps)=> {
    if(this.state.someVariable !== prevState.someVariable) {
        // if don't re-render/update
        return true
    }

    //...
})


Q: Can print function catch None return value and not print it? I am new and learning Python. What is the best way to avoid printing None in the code below? I commented out raising an error.
I know why None is being printed. I would have liked to have 2 return types for the function but apparently that is bad practice for maintainability of the code according to S.Lott's response on Why should functions always return the same type?. Moreover, unutbu's answer on the same post where errors will pop up when you call the function within a function expecting a certain type - fun1(fun2(arg)). I don't want to raise a runtime error as S.Lott suggested. Is there a way of print catching the None value and not printing it?
def smaller_root(a,b,c):
    """
    akes an input the numbers a,b and c returns the smaller solution to this
    equation if one exists. If the equation has no real solution, print
    the message, "Error: No Real Solution " and simply return.
    """
    discriminant = b**2-4*a*c

    if discriminant == 0:
        return  -b/(2*a)
    elif discriminant > 0:
        return (-b-discriminant**0.5)/(2*a) #just need smaller solution
    else:
        print("Error: No Real Solution")
        #raise Exception("Error: No Real Solution")
        #no return statement as there is no use for it.
        #Python will implicitly return None

A: Your function do one, and only one, thing. So, in your case, it should find the smaller_root according to some variables.
The return value of your function should be the root. In your case, it is possible that it returns None, which would indicate that there is no root for the solution.
However, you are trying to make the function do more than one thing, that is, you are trying to make the function return a value (the root) AND print out a message if no root is found.
You should choose one functionality only for you function: It will EITHER print out the result (that is, print a root or a message) OR return the result.
Every other logic beyond that of the functionality would be out of the function's scope, e.g.:
def smaller_root(a,b,c):
    """
    akes an input the numbers a,b and c returns the smaller solution to this
    equation if one exists. If the equation has no real solution, print
    the message, "Error: No Real Solution " and simply return.
    """
    discriminant = b**2-4*a*c

    if discriminant == 0:
        return  -b/(2*a)
    elif discriminant > 0:
        return (-b-discriminant**0.5)/(2*a) #just need smaller solution
    else:
        return None

result = smaller_root(some_a, some_b, some_c)
if (result is None):
    print("Error: No Real Solution")


Q: How do you support swiping to delete a row in a UICollectionView list with compositional layout? Previously with table views this was done in the UITableViewDataSource delegate callback tableView(_:commit:forRowAt:). Is there equivalent functionality in the APIs associated with the new collection views, or a recommended way of implementing it?

A: The UICollectionLayoutListConfiguration, which you used to create the layout, has leadingSwipeActionsConfigurationProvider and trailingSwipeActionsConfigurationProvider properties that are functions taking an index path. Your function can return different swipe actions, or nil, for different rows of the list:
var config = UICollectionLayoutListConfiguration(appearance: .plain)
config.trailingSwipeActionsConfigurationProvider = { indexPath in
    let del = UIContextualAction(style: .destructive, title: "Delete") {
        [weak self] action, view, completion in
        self?.delete(at: indexPath)
        completion(true)
    }
    return UISwipeActionsConfiguration(actions: [del])
}

Writing delete(at:) is left as an exercise for the reader; basically you just do the very same thing you would have done in any collection view.


Q: I override api_date of themplates in DHTMLX but it is not used? In dhtmlx gantt, you can format input date (from string or any type) into javascript date. This date is used to draw chart. Base on the dhtmlx document, you can replace converter (api_date) by custom function:
I override the function as follow:
 gantt.templates.api_date = function(date){
    throw "It is called";
 };

but, it never is called.

A: I don`t know why this function is not called. I also confuse for this, because official documents of DHMTLX Gantt (as you mentioned, api_date) say it should works.
However I found that if you override xml_date it will work as you want. Although it is named xml_date but it works for json data also.
So could use following snippet:
gantt.templates.xml_date = function(date){
    // Your customized code.
    // return a Date object.
};

A: api_date template and config are no longer used. We will update the information in the documentation. Please use xml_date as hadi.mansouri suggested.


Q: Angular 6: You need to import the HttpClientModule in your AppModule Before minusing, please note that no other issues reported helped me. Looked through the whole stackoverflow regarding this issue.
This is in app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { LalaComponent } from './lala/lala.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { ApiModule } from 'atlas-client';

@NgModule({
  declarations: [
    AppComponent,
    LalaComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    ApiModule
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule { }

This is in lala.component.ts:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-lala',
  templateUrl: './lala.component.html',
  styleUrls: ['./lala.component.css']
})
export class LalaComponent implements OnInit {

  constructor(private http: HttpClient) {
    console.log('test');
  }

  ngOnInit() {

  }
}

package.json:
{
  "name": "lala-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.0.3",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "core-js": "^2.5.4",
    "rxjs": "^6.0.0",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^6.0.3",
    "@angular-devkit/build-angular": "~0.6.6",
    "typescript": "~2.7.2",
    "@angular/cli": "~6.0.7",
    "@angular/language-service": "^6.0.3",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1"
  }
}

I get this error:

Error: You need to import the HttpClientModule in your AppModule!  See
  also https://github.com/angular/angular/issues/20575
at new ApiModule (atlas-client.js:216)
at _createClass (core.js:9264)
at _createProviderInstance$1 (core.js:9234)
at initNgModule (core.js:9170)
at new NgModuleRef_ (core.js:9899)
at createNgModuleRef (core.js:9888)
at Object.debugCreateNgModuleRef [as createNgModuleRef] (core.js:11719)
at NgModuleFactory_.push../node_modules/@angular/core/fesm5/core.js.NgModuleFactory_.create

(core.js:12421)
      at core.js:4720
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke
  (zone.js:388)

Please note, that the issue still there when I remove import { HttpClientModule } from '@angular/common/http'; line with respective import.

A: There is a bug in angular-cli when the swagger-codegen package is either linked using  npm link or installed directly using: npm install PATH_TO_GENERATED_PACKAGE/dist --save (see: https://github.com/angular/angular-cli/issues/8284).
The issue seems to be with ng serve only, not with ng build --prod --base-href=..., but I did not test an 'ng build' yet.
The "You need to import the HttpClientModule in your AppModule!" message is not valid, but an error is thrown anyhow.
An (ugly) workaround described in this ticket is to generate the code using swagger-codegen-cli (or openapi-generator-cli), search for, and comment out the error message:
// if (!http) {
//     throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
//     'See also https://github.com/angular/angular/issues/20575');
// }

Next: run npm install && npm run build and install the package in the consuming project.
A cleaner solution would be to use a (private) npm registry.

UPDATE 14/7/2018
Further investigation showed that the workaround described above does not solve all problems.
Instead, I am now using a private npm registry Verdaccio and have no issues anymore.
-Arjen


Q: Inner working of Integer('string') call? If I want to see if a string is a valid integer, I can do:
puts Integer('1') #=> 1

as any non-integer would raise an error:
puts Integer('a') #=> invalid value for Integer(): "a" (ArgumentError)

If I want to make sure my variable is both a Float and an Integer, I do not want to repeat myself so I try to put the classes in a list:
x = '1'
[Integer, Float].each{|c| puts c(x) } #=> undefined method `c' for main:Object (NoMethodError)

Will someone explain why this does not work, and if there is some way to achieve what I am looking for? What kind of method call is Integer(var)?
Note, I have no real world problem I'm trying to solve here, I'm just curious.

A: When you do:
Integer('10')

you are essentially calling the Integer class method defined in Kernel, passing it the argument 10.
To achieve what you want you can do:
[:Integer, :Float].each { |c| puts method(c).call(x) }


Q: How to detect JavaScript events on third party sites Is there any way (implemented or just in theory) that one could detect JavaScript events and actions assigned on a third party site?
If I am injecting JavaScript into a foreign site and want to avoid overwriting onsubmit, onclick, onfocus and other such events, is there any way to detect and extend such callbacks rather than overwrite them?
Ideas I've had:

*

*run the site in a headless browser or JavaScript engine before hand to capture all executed JavaScript

*parse the JavaScript on the fly and hope the third party JavaScript conforms to my parser's expectations

A: If you just want to add new event handlers without overwriting the existing event handlers, you can use addEventListener() or attachEvent() (for older versions of IE) instead of setting .onclick, .onsubmit, etc... to add a new event handler without affecting the previous event handlers.
Here's a simple cross browser function to add an event:
// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));
        });
    }
}

There is no cross browser way that I'm aware of from regular javascript to interrogate existing DOM objects to see which ones have regular javascript event handlers installed via addEventListener or attachEvent.  If the event handlers are installed with jQuery, they can be interrogated via this technique.
There is some future spec work that has been done to add a property that would list all the event handlers, but I am not sure it is implemented yet.  You can read more about that here.
For event handlers installed with onclick, onsubmit, onfocus, etc..., you can check all existing DOM elements to see which ones have handlers assigned for those events and you can then hook them if you want to.
// add other events here you are interested in
var events = ["onclick", "onsubmit", "onfocus", "onblur"];
var elems = document.getElementsByTagName("*"), item;
for (var i = 0; i < elems.length; i++) {
    item = elems[i];
    for (var j = 0; j < events.length; j++) {
        if (item[events[j]]) {
            console.log("event handler for " + events[j]);
        }
    }
}

A: You can actually get what you want by changing the prototype of addEventListener and attachEvent:
// intercept events cross browser
var method;
if (HTMLElement.prototype.addEventListener) {
  method = 'addEventListener';
} else {
  method = 'attachEvent';
}
HTMLElement.prototype.realAddEventListener = HTMLElement.prototype[method];
HTMLElement.prototype[method] = function(a,b,c) {
  console.log('here are all the events being added:', arguments);
  this.realAddEventListener(a,b,c);
};

Of course, it's important that this is added into the page before any other page scripts, but it can come after or before libraries like jQuery, but might have conflicts on the prototype with prototype.js, not sure.
You'll also want to check for onclicks and the whole set of events, which you can find by running console.dir(document.createElement('a')) in a javascript console.


Q: Any class in C# that can tell me clock tick, seconds consumed by a function Is there a class in C# that can give me clock ticks, seconds consumed by a method? I guess I have two wrap that functionality around function to time the ticks and seconds taken up.

A: Use:
using System.Diagnostics;

...

var sw = Stopwatch.StartNew();
DoYaThing();
Console.WriteLine("{0} Elapsed", sw.Elapsed);

A: You could use the System.Diagnostics.Stopwatch class.
Stopwatch sw = new Stopwatch();
sw.Start();

// Your method call here...

sw.Stop();

// Get the elapsed time
TimeSpan elapsed = sw.Elapsed;

From here, you can use the TimeSpan.Ticks or the TimeSpan.TotalSeconds properties to determine the elapsed ticks or elapsed seconds, respectively.
If you wanted to, you could use a method along the following lines to "wrap" that functionality around a function, as you mentioned (just an idea, you'd probably want to tweak this code to suit your specific purposes -- passing in arguments, etc.):
public static T ExecuteWithElapsedTime<T>(Func<T> function, out TimeSpan elapsedTime)
{
   T rval;

   Stopwatch sw = new Stopwatch();
   sw.Start();
   rval = function();
   sw.Stop();
   elapsedTime = sw.Elapsed;

   return rval;
}

And you could call it like this (where myFunc is a function that returns an int):
TimeSpan elapsed;
int result = ExecuteWithElapsedTime(myFunc, out elapsed);

Might be simpler though to not even bother with a method like this, and just put the Stopwatch code inline with your method call.

A: There's the high resolution timer ...
Also, iirc a TimeSpan can give you a measurement in ticks back.

A: You can check out the [System.TimeSpan] class and wrap that around your method.


Q: SQL window function is grouped, but still get "must be an aggregate expression or appear in GROUP BY clause" I have a SQL (presto) query, let's say it's this:
select
      id
    , product_name
    , product_type
    , sum(sales) as total_sales
    , sum(sales) over (partition by type) as sales_by_type

from some_table

group by 1,2,3

When I run this, I get an error telling me that the window function needs to appear in the GROUP BY clause. Is the best solution to break this out with a subquery? Or is there some syntax changes I need to make for this to work?

A: If you want the total sales for the type, then you need to nest the sum()s:
select id, product_name, product_type,
       sum(sales) as total_sales,
       sum(sum(sales)) over (partition by type) as sales_by_type
from some_table
group by 1,2,3;

If you also want the total of all sales, then:
select id, product_name, product_type,
       sum(sales) as total_sales,
       sum(sum(sales)) over (partition by type) as sales_by_type,
       sum(sum(sales)) over () as total_total_sales
from some_table
group by 1,2,3;

A: What you need is something like below
select
      id
    , product_name
    , product_type
    , sum(sales) over () as total_sales
    , sum(sales) over (partition by type) as sales_by_type
    from some_table

or
select
      id
    , product_name
    , product_type
    , sum(sales) over (partition by (select 1)) as total_sales
    , sum(sales) over (partition by type) as sales_by_type
    from some_table

Both of these works in sql server. Not sure what/if it will work for presto though.
I have seen below variation as well.
over (partition by null)


Q: .on('click') event for a single JSON layer, how to? I'm stuck with a problem that I can't find anywhere else on the internet. Or atleast not what I mean.
In my part of code I have made a popup with an map.on('click') event, however I would like the event to be only possible with one layer and only when that layer is active. As you can see in my code I also want my sidebar to open a tab when the layer is clicked, however now when you click the map anywhere the sidebar will still open.
The layer that I want the sidebar to react to is called: "bottlenecklayer"
The next code is what I currently have, the code at the bottom shows what I've tried as well but did not work.
 map.on('click', function(evt){

     var feature = map.forEachFeatureAtPixel(evt.pixel,
       function(feature) {

         return feature;

      });

      document.getElementById("sidebar").classList.toggle("collapsed");
      document.getElementById("pop-up-message").classList.toggle("active");

     if (feature) {
         var geometry = feature.getGeometry();
         var coord = geometry.getCoordinates();
         var imagebottleneckbefore = feature.get('Image_before');
         var imagebottleneckafter = feature.get('Image_after');

     /* if (imagebottleneckbefore === null)
         {imagebottleneckbefore = "hidden"};*/

     if (imagebottleneckafter === null)
         {imagebottleneckafter =  "otterplaceholde.jpg"};

     if (imagebottleneckafter === "nopic")
         {imagebottleneckafter =  "otterplaceholde.jpg"};

     if (feature.get('Description') === null)
         {return "Er is geen beschrijving bij dit knelpunt."};

         var contentjson = '
' + "Knelpunt:" + ' ' + feature.get('Name') + '
';
        /* contentjson += "";*/
         contentjson += '&nbsp'
         contentjson += "";
         contentjson += '
' +  feature.get('Description') + '
';
        // contentjson += '
' + feature.get('Descriptionholder') + '
';
         content_elementjson.innerHTML = contentjson;

     }

    });

This is the part of code that does not work either:
bottlenecklayer.on('click',function(evt){
  document.getElementById("sidebar").classList.toggle("collapsed");
  document.getElementById("pop-up-message").classList.toggle("active")
});

A: You need to specify a layerFilter function in the forEachFeatureAtPixel request:
 var feature = map.forEachFeatureAtPixel(evt.pixel,
   function(feature) {

     return feature;

  }, {

     layerFilter: function(layer) {
        return layer === bottlenecklayer;
     }

  });

Layers do not have click events.


Q: How to give fixed length into chosen.jquery.js plugin? Have a day I used chosen.jquery.js plugin for my dropdownlist but it get width size automatically please somebody know how to choose a fixed length to my all dropdowlists.
Thanks.!

A: I have experienced the same problem with you before. I solve this problem with set the width and max-width for the drop down.
<select class="chzn-select" name="chznName" >
...
</select>

<style>
    select, option {
        width: 500px;
        max-width: 500px;
    }
</style>

Chosen will create the chosen dropdown with width from the actual dropdown that you create.


Q: Import error when deploying Flask application to Kubernetes (GCP) I'm new to Kubernetes, so assume i don't know anything about deploying applications in it.
I have a Flask application and i'm trying to deploy from Azure Pipelines to GCP Kubernetes Cluster. I've already set up all the environment but, when i launch a new Release (from Azure Pipelines), i receive import errors at the GCP Kubernetes Logs screen, regarding the libraries i am using in my application. The main one that appears is:
ImportError: cannot import name 'anonymous_user_required' from 'flask_security'
Which is strange, since i have set up a Virtual Environment, with all the packages at requirements.txt on my local machine and everything runs smoothly.
Below is my Dockerfile:
FROM python:3.7

ENV APP_HOME /app
ENV PORT 5000

WORKDIR $APP_HOME

COPY . $APP_HOME

RUN pip3 install -r requirements.txt
CMD ["python", "app.py"]

And my deployment.yaml:
apiVersion: v1
kind: Service
metadata:
  name: app
spec:
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP
    name: http
  selector:
    app: app
  type: NodePort

---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: app
spec:
  backend:
    serviceName: app
    servicePort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  selector:
    matchLabels:
      app: app
  replicas: 1
  template:
    metadata:
      labels:
        app: app
    spec:
      containers:
      - name: app
        image: APP_IMAGE
        ports:
          - containerPort: 8080
        livenessProbe:      # Used by deployment controller
          httpGet:
            path: /
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
        readinessProbe:     # Used by Ingress/GCLB
          httpGet:
            path: /
            port: 8080
          initialDelaySeconds: 3
          periodSeconds: 5
        resources:
          limits:
            memory: 1024Mi
          requests:
            memory: 768Mi

The APP_IMAGE is being set on my azure-pipelines.yml:
steps:
- task: CmdLine@1
  displayName: 'Lock image version in deployment.yaml'
  inputs:
    filename: /bin/bash
    arguments: '-c "awk ''{gsub(\"APP_IMAGE\", \"gcr.io/$(DockerImageName):$(Build.BuildId)\", $0); print}'' deployment.yaml > $(build.artifactstagingdirectory)/deployment.yaml"'

I followed Google Tutorial to deploy the application to a Kubernetes Cluster. The pipeline is working fine, it's publishing the Docker Image in the Google Container Registry and the Release from Azure is generating logs at the GCP Kubernetes screen.
Am i missing something at the deployment.yaml file? There is some extra configuration i have to do in GCP Kubernetes to make it work?


Q: Finding date/time intervals from multiple rows T-SQL I have an audit table that stores a master table's "status" values in multiple rows, each row has a date/time stamp. Let's call the master table "Project" and it moves through different status changes: Open, Pending, Closed. However sometimes the Project can move back to Open after it's been closed. Data would be something like this:
ProjectId    Date          Status
1234         07-01-2015    Open
1234         07-03-2015    Pending
1234         07-05-2015    Closed
1234         07-06-2015    Open

I need to take a date parameter value, and determine what status the Project "1234" was in on that given date.
ex: Date=07-02-2015 would give me "Open"
Date=07-07-2015 would also give me "Open"
Date=07-03-2015 would give me "Pending"
The problem I'm having is that the SQL needs to look at the surrounding rows (if any)

A: 1) Limit the rows to only rows with date inside the window.
2) Sort the result by date descending (putting the most recent at the top)
3) Select the first row
DECLARE @CheckDate DATETIME = '07-07-2015',
        @ProjectId INT = 1234

-- To ignore time, set the check date to the first millisecond of the
-- next day and use a less than operator
SET @CheckDate = DATEADD(dd, DATEDIFF(dd, 0, @CheckDate) + 1, 0)

SELECT TOP 1
         [Status]
FROM     [Project]
WHERE    [ProjectId] = @ProjectId
AND      [Date] < @CheckDate
ORDER BY [Date] DESC

A: If you have 2012 or later, you can do this with Lead as follows:
declare @date datetime = '7-2-15' --or whatever

select ProjectID, Status from (
    select *
        , lead(date) over (partition by projectID order by date) as NextEvent
    from MyTable) a
where @date between [date] and isnull(NextEvent, @date + 1)

Otherwise, you can approximate lead using row_number and a self-join.
Note, depending on how precise your dates are, you may want to use something like where @date >= date and @date < isnull(NextEvent, @date + 1) instead of between.