text:
Q: SQL Constraint IGNORE_DUP_KEY on Update I have a Constraint on a table with IGNORE_DUP_KEY.  This allows bulk inserts to partially work where some records are dupes and some are not (only inserting the non-dupes).  However, it does not allow updates to partially work, where I only want those records updated where dupes will not be created.
Does anyone know how I can support IGNORE_DUP_KEY when applying updates?
I am using MS SQL 2005

A: I'm not sure what is really going on, but if you are inserting duplicates and updating Primary Keys as part of a bulk load process, then a staging table might be the solution for you.  You create a table that you make sure is empty prior to the bulk load, then load it with the 100% raw data from the file, then process that data into your real tables (set based is best).  You can do things like this to insert all rows that don't already exist:
INSERT INTO RealTable
        (pk, col1, col2, col3)
    SELECT
        pk, col1, col2, col3
        FROM StageTable s
        WHERE NOT EXISTS (SELECT
                              1
                              FROM RealTable r
                              WHERE s.pk=r.pk
                         )

Prevent the duplicates in the first place is best.  You could also do UPDATEs on your real table by joining in the staging table, etc.  This will avoid the need to "work around" the constraints.  When you work around the constraints, you usually create difficult to find bugs.

A: If I understand correctly, you want to do UPDATEs without specifying the necessary WHERE logic to avoid creating duplicates?
create table #t (col1 int not null, col2 int not null, primary key (col1, col2))

insert into #t
select 1, 1 union all
select 1, 2 union all
select 2, 3

-- you want to do just this...
update #t set col2 = 1

-- ... but you really need to do this
update #t set col2 = 1
where not exists (
    select * from #t t2
    where #t.col1 = t2.col1 and col2 = 1
    )

The main options that come to mind are:

*

*Use a complete UPDATE statement to avoid creating duplicates

*Use an INSTEAD OF UPDATE trigger to 'intercept' the UPDATE and only do UPDATEs that won't create a duplicate

*Use a row-by-row processing technique such as cursors and wrap each UPDATE in TRY...CATCH... or whatever the language's equivalent is

I don't think anyone can tell you which one is best, because it depends on what you're trying to do and what environment you're working in. But because row-by-row processing could potentially produce some false positives, I would try to stick with a set-based approach.

A: I have the feeling you should use the MERGE statement and then in the update part you should really not update the key you want to have unique. That also means that you have to define in your table that a key is unique (Setting a unique index or define as primary key). Then any update or insert with a duplicate key will fail.
Edit: I think this link will help on that:
http://msdn.microsoft.com/en-us/library/bb522522.aspx


text:
Q: USPS Rate API Working for Domestic Zip Codes Only My shipping quote api for USPS is working for USA zip codes only.  Canada, United Kingdom and other international zip codes result in this error:  Microsoft VBScript runtime error '800a01a8' Object required:  xmlRate.selectSingleNode(...)' /folder/subfolder/usps_plugin.asp, line 32.
Here is the code for that file:
<%

function GetUSPSRate(SourceZip, DestZip, Weight, Method)
    dim xml
    dim post

    post = "<RateV4Request USERID='MYUSPSUSERNAME'>" & _
        "<Revision/>" & _
        "<Package ID='1ST'>" & _
        "<Service>" & Method & "</Service>" & _
        "<ZipOrigination>" & SourceZip & "</ZipOrigination>" & _
        "<ZipDestination>" & DestZip & "</ZipDestination>" & _
        "<Pounds>" & Weight & "</Pounds>" & _
        "<Ounces>0</Ounces>" & _
        "<Container>RECTANGULAR</Container>" & _
        "<Size>LARGE</Size>" & _
        "<Width>12</Width>" & _
        "<Length>12</Length>" & _
        "<Height>12</Height>" & _
        "<Girth>12</Girth>" & _
        "</Package>" & _
        "</RateV4Request>"

    set xml = CreateObject("MSXML2.ServerXMLHTTP")
    xml.open "GET", "http://production.shippingapis.com/ShippingAPI.dll?API=RateV4&XML=" & post
    xml.send("")

    dim xmlRate
    set xmlRate = xml.responseXML

    GetUSPSRate = xmlRate.selectSingleNode("//Rate").text
end function

function GetUSPSRates(SourceZip, DestZip, Weight)
    dim rates
    set rates = CreateObject("Scripting.Dictionary")
    rates.add "USPS Express", GetUSPSRate(SourceZip, DestZip, Weight, "EXPRESS")
    rates.add "USPS Priority", GetUSPSRate(SourceZip, DestZip, Weight, "PRIORITY")
'   rates.add "USPS First Class", GetUSPSRate(SourceZip, DestZip, Weight, "FIRST CLASS")

    set GetUSPSRates = rates
end function
%>

Also, here is the code that calls for that request:
dim uspsRates
dim uspsKey
set uspsRates = GetUSPSRates("02196", receiverpostalcode, shipmentweight)

for each uspsKey in uspsRates
    dim uspsValue
    uspsValue = uspsRates.item(uspsKey)
    %>
    <input name="shipinfo" type="radio" value="<%= uspsValue %>|<%= uspsKey %>">$<%= uspsValue + stone_handlingfee %> <%= uspsKey %>
    <br>
<% next
%>

It works perfectly and flawlessly for domestic zip codes, however, international is when the issues occur.  Constructive input is greatly appreciated.

A: Not all the variables were accounted for to generate international quotes.  Country, City and Zip are the most important. Without these, the api could not return results.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to develop for different environments I am developing a JIRA plugin that should work under JIRA 6 and 7. Unfortunately there are major API changes between those versions and I have to build the project with different dependencies for each JIRA version.
The core of my plugin should not be changed between the versions, thus I thought about creating an abstraction layer for the JIRA API tht provides only methods that I need.
The main problem is, that I absolutely don't know how to structure the project. I considered to create a branch in git for each JIRA version, but then I would have to make the same changes on the core in each branch. I suspect that I will get forget this at some point.
Does anybody have an idea on how to solve this problem?

A:  Three different modules
Here is one of the proposed structure,
By implementing the maven version changes, there can be a module level version changes.
And again for the code base changes, there has to be git branch change where the backporting should happen.
Lets say version 6 is in a branch and the changes you want in the version 7,
As it is one of the common change, the file has to be core module and as well there should be a healthy merge between these branches.

A: Use submodules.
Your structure should like like this:
+ ROOT Project 1
| - Common (shared between your projects = submodule)
| - Project specific code

+ ROOT Project 2
| - Common (shared between your projects = submodule)
| - Project specific code

Read this full answer about it, how to use it and what can you gain from it.
How to use 2 GIT Repos in a Project? (git submodules, subtree)


text:
Q: ModuleNotFoundError: No module named 'mpl_toolkits.basemap' I have trouble importing the basemap module of mpl_toolkits in python.
I've got following error message when I try to run "from mpl_toolkits.basemap import Basemap":
ModuleNotFoundError: No module named 'mpl_toolkits.basemap'
I'm using python 3.6.5 in windows.
I've found relevant Q&A in
"Python basemap module impossible to import" and I already followed what's instructed there (i.e. source activate MyProfileName, conda install basemap) but it didn't work.
The clue might already be given in the Q&A above but as I'm quite new to python, I couldn't figure out the solution.

A: I would recommend installing Anaconda environment from scratch. Let Anaconda handle dependencies for you. Then you need to install mpl_toolkits separately in your conda environment with:
conda install -c conda-forge basemap-data-hires

See also here.
After doing this, executing
from mpl_toolkits.basemap import Basemap

from python console should work normally.

A: I recently faced this problem on Windows 10.  I had created a conda environment with python 3.7 and anaconda 5.2.0 and tried all retrieved solutions. But nothing worked for me and all my efforts worth many hours were in vain.
What I observed that currently Basemap is not compatible with python 3.0, so I remove the environment and creates a fresh with python 2.7 and anaconda 5.2.0. So, to help others who are juggling with same problem, here is the complete set of solution:
Getting the Basemap Toolkit (support the functionality of mapping data)

*

*create conda environment as:
conda create -n Basemap python=2.7 anaconda=5.2.0

*Activate the created conda environment:
activate Basemap

*Install the following packages:

*

*
conda install -c conda-forge basemap

(do not use basemap=1.1.0, channel error comes "package basemap =1.1.0 is not
available from current channels")
"Only the 'crude' and 'low' resolution datasets are installed by default". You may
need to install the following for high resolution:

*
conda install -c conda-forge basemap-data-hires

PROJ is a generic coordinate transformation software that transforms geospatial
coordinates from one coordinate reference system (CRS) to another. This includes
cartographic projections as well as geodetic transformations.

*
conda install -c conda-forge proj4 </b>

(Better to avoid pro4=5.2.0 as specific packages generates error)
PROJ is a generic coordinate transformation software that transforms geospatial
coordinates from one coordinate reference system (CRS) to another. This includes
cartographic projections as well as geodetic transformations.
After installation of the Basemap toolkit, open the jupyter notebook a fresh, it should show the current environment in upper right corner.
To check the current environment in jupyter, type:
import sys
print(sys.executable)

If still the activated environment is not shown then:

*

*run the following command in anaconda prompt in activated environment Basemap:
python -m ipykernel install --user --name Basemap --display-name "Python (Basemap)"

*Now change the environment from Kernel-> change kernel -> Python (Basemap)

*Finally Python(Basemap) should be shown in upper right corner.
Following needs to be imported in your program then to use it:
from mpl_toolkits.basemap import Basemap

In case of error: "No module named 'mpl_toolkits.basemap" type the following in jupyter:
import os
os.environ['PROJ_LIB'] = r'C:\ProgramData\Anaconda3\pkgs\proj4-5.2.0-h6538335_1006\Library\share

After this you need to restart apps for them to pick up the change, including explorer.exe. Restarting the machine is reccomended (but not required).
All the best. I hope this will work for you as well.


text:
Q: Monitoring Unmanaged program using .net
I have a exe program written using c++,
I want to perform some actions when that exe is opened, closed or minimized
I wonder whether this kind of functionality is possible using c#.net?

A: you can send windows message.
you also control on the window by using pipe name
A simple message pump looks like this:
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct MSG
{
    public IntPtr hwnd;
    public int message;
    public IntPtr wParam;
    public IntPtr lParam;
    public int time;
    public int pt_x;
    public int pt_y;
}

[DllImport("user32.dll", CharSet = CharSet.Ansi)]
public static extern bool GetMessage([In, Out] ref MSG msg, IntPtr hWnd, int MsgFilterMin,  int uMsgFilterMax);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr DispatchMessage([In] ref MSG msg);

[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern uint RegisterWindowMessage(string lpString);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    // #1
    MSG msg = new MSG();
    while (GetMessage(ref msg, IntPtr.Zero, 0, 0))
    {
        DispatchMessage(ref msg);
    }

    // #2
    uint UWM_UART_CTRL_TRS = Win32Api.RegisterWindowMessage("BT_UARTCTRL_TRANSFER");
    Win32Api.SendMessage(HWND_BROADCAST, UWM_UART_CTRL_TRS, (IntPtr)0, (IntPtr)0);

    // #3
    uint UWM_UART_CTRL_TRS = Win32Api.RegisterWindowMessage("BT_UARTCTRL_TRANSFER");
    Win32Api.SendMessage(HWND_BROADCAST, UWM_UART_CTRL_TRS, (IntPtr)1, (IntPtr)0);

A: Native .NET Process class has a functionality for an event fired when a process is closed.
Also process monitoring in C# is partially discussed in this post.
Considering this, you'll have to use Windows Management Instrumentation to track wide range of specific process events.


text:
Q: IIS web.config setting turns url in to parameter I did this on another project and now I can't make it work.
I need to set up the virtual address's in the web.config so that the URL
http://my.webspace.com/thesite/animal/dog/puppy
actualy goes to the page /thesite/animal.html with dog and puppy in the parameters.

A: You're looking for an url rewriter.
There's an example implementation at MSDN; URL Rewriting in ASP.NET


text:
Q: How do you handle interdependent options with python-click? I have two options that are interdependent. That is, the value selected for one constrains the valid options for the other.
What is best way to enforce this with the click library? Is there a built-in mechanism for this?
I want to take advantage of the built-in parameter error checks if possible. At the moment I've fallen back to checking the variables once they have been passed into my code.


text:
Q: convert powerpoint and keynote file to set of images Is there a way in C or Objective-C to convert presentation files (.ppt/.key) into a set of images?
many thanks!

A: I doubt. ppt file is the fact XML style document. So if you want to parse it you have to write a XML parser who puts element in the exact position... So in fact you have to create your own powerpoint.
But, you might (both PowerPoint and Keynote) consider to export presentation to pdf, and then this will be a lot simpler.

A: For PowerPoint, you can get each slide, present it through UIWebView and capture the image from view
IOS library to convert powerpoint presentations into images

A: It would be more helpful to know why you want to do this, but on mac, it's possible to do this kind of thing with javascript  and it's possible to call javascript from within cocoa
I doubt you'll have any luck if you want to do it in iOS.

A: PowerPoint for Mac offers a Save as Pictures open in the File menu that sounds like what you are looking for.


text:
Q: Wrong outcome while summing big arrays
I keep getting wrong outcome, while I try to sum big arrays. I have isolated problem to the following code sample (its not an sum of a big array, but I believe this is The problem)
Compilable Sample:
template <typename T>
void cpu_sum(const unsigned int size, T & od_value) {
    od_value = 0;
    for (unsigned int i = 0; i < size; i++) {
        od_value += 1;
    }
}

int main() {
    typedef float Data;
    const unsigned int size = 800000000;
    Data sum;
    cpu_sum(size, sum);

    cout << setprecision(35) << sum << endl; // prints: 16777216 // ERROR !!!
    getchar();
}

Environment:
OS: Windows 8.1 x64 home
IDE: Microsoft Visual Studio 2015
Error Description:
While my outcome should obviously be sum == 800000000 I keep getting sum == 16777216.
That is very weird for me, because float max value is far above this one, and yet it looks like sum variable reach its limit.
What did I miss??

A: It is a well known problem. Gradually your sum becomes so big that next summand becomes comparable with an epsilon (about 10^-14) of it. At that moment you start loosing precision.
Standard solution is to change summation tactics: when array larger than, say, 100 elements, split it in halves and sum each half separately. It goes on recursively and tend to keep precision much better.

A: As pointed out by Michael Simbursky, this is a well-known problem when trying to sum a large number of limited-precision numbers.  The solution he provides works well, and is quite efficient.
For the curious reader, a slower method is to sort your array before computing the sum, assuring that the values are added in order of increasing absolute value.  This ensures that the least-significant values make their contributions to the overall sum before being overwhelmed by the other values.  This technique is used more as an example/illustration than in any serious programming ventures.
For serious scientific programming where the overall size of the data can vary a great deal, another algorithm to be aware of is the Kahan Summation Algorithm, and the referenced wikipedia page provides a nice description of it.


text:
Q: Python Asyncio queue get doesn't receive the message I post a new question related the old for a problem with the get from queue.
This is the code (thanks to Martijn Pieters)
import asyncio
import sys
import json
import os
import websockets

async def socket_consumer(socket, outgoing):
    # take messages from the web socket and push them into the queue
    async for message in socket:
        await outgoing.put(message)
        file = open(r"/home/host/Desktop/FromSocket.txt", "a")
        file.write("From socket: " + ascii(message) + "\n")
        file.close()

async def socket_producer(socket, incoming):
    # take messages from the queue and send them to the socket
    while True:
        message = await incoming.get()
        file = open(r"/home/host/Desktop/ToSocket.txt", "a")
        file.write("To socket: " + ascii(message) + "\n")
        file.close()
        await socket.send(message)

async def connect_socket(incoming, outgoing, loop=None):
    header = {"Authorization": r"Basic XXX="}
    uri = 'XXXXXX'
    async with websockets.connect(uri, extra_headers=header) as web_socket:
        # create tasks for the consumer and producer. The asyncio loop will
        # manage these independently
        consumer_task = asyncio.ensure_future(
            socket_consumer(web_socket, outgoing), loop=loop)
        producer_task = asyncio.ensure_future(
            socket_producer(web_socket, incoming), loop=loop)

        # start both tasks, but have the loop return to us when one of them
        # has ended. We can then cancel the remainder
        done, pending = await asyncio.wait(
            [consumer_task, producer_task], return_when=asyncio.FIRST_COMPLETED)
        for task in pending:
            task.cancel()

# pipe support
async def stdio(loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()

    reader = asyncio.StreamReader()
    await loop.connect_read_pipe(
        lambda: asyncio.StreamReaderProtocol(reader), sys.stdin)

    writer_transport, writer_protocol = await loop.connect_write_pipe(
        asyncio.streams.FlowControlMixin, os.fdopen(sys.stdout.fileno(), 'wb'))
    writer = asyncio.streams.StreamWriter(
        writer_transport, writer_protocol, None, loop)

    return reader, writer

async def pipe_consumer(pipe_reader, outgoing):
    # take messages from the pipe and push them into the queue
    while True:
        message = await pipe_reader.readline()
        if not message:
            break
        file = open(r"/home/host/Desktop/FromPipe.txt", "a")
        file.write("From pipe: " + ascii(message.decode('utf8')) + "\n")
        file.close()

        await outgoing.put(message.decode('utf8'))

async def pipe_producer(pipe_writer, incoming):
    # take messages from the queue and send them to the pipe
    while True:
        json_message = await incoming.get()
        file = open(r"/home/host/Desktop/ToPipe.txt", "a")
        file.write("Send to pipe message: " + ascii(json_message) + "\n")
        file.close()
        try:
            message = json.loads(json_message)
            message_type = int(message.get('header', {}).get('messageID', -1))

        except (ValueError, TypeError, AttributeError):
            # failed to decode the message, or the message was not
            # a dictionary, or the messageID was convertable to an integer
            message_type = None
            file = open(r"/home/host/Desktop/Error.txt", "a")
            file.write(" Error \n")
            file.close()
        # 1 is DENM message, 2 is CAM message
        file.write("Send to pipe type: " + type)
        if message_type in {1, 2}:
            file.write("Send to pipe: " + json_message)
            pipe_writer.write(json_message.encode('utf8') + b'\n')
            await pipe_writer.drain()

async def connect_pipe(incoming, outgoing, loop=None):
    reader, writer = await stdio()
    # create tasks for the consumer and producer. The asyncio loop will
    # manage these independently
    consumer_task = asyncio.ensure_future(
        pipe_consumer(reader, outgoing), loop=loop)
    producer_task = asyncio.ensure_future(
        pipe_producer(writer, incoming), loop=loop)

    # start both tasks, but have the loop return to us when one of them
    # has ended. We can then cancel the remainder
    done, pending = await asyncio.wait(
        [consumer_task, producer_task], return_when=asyncio.FIRST_COMPLETED)
    for task in pending:
        task.cancel()
    # force a result check; if there was an exception it'll be re-raised
    for task in done:
        task.result()

def main():
    loop = asyncio.get_event_loop()
    pipe_to_socket = asyncio.Queue(loop=loop)
    socket_to_pipe = asyncio.Queue(loop=loop)

    socket_coro = connect_socket(pipe_to_socket, socket_to_pipe, loop=loop)
    pipe_coro = connect_pipe(socket_to_pipe, pipe_to_socket, loop=loop)

    loop.run_until_complete(asyncio.gather(socket_coro, pipe_coro))

main()

This code is the child process called from the parent by
subprocess.Popen(["python3", test], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=2048)

The problem is the object is in the queue by socket_consumer (received from the socket) but the pipe_producer doesn't go ahead from incoming.get().
The file writing is only for testing purpose.
The parent at the moment is this (only for test)
test = r"/home/host/PycharmProjects/Tim/Tim.py"
process = subprocess.Popen(["python3", test],
                           stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=2048)

for i in range(5):
    message = '{"header":{"protocolVersion":1,"messageID":2,"stationID":400}, the rest of json...}}';
    jsonValueBytes = message.encode("utf-8")
    process.stdin.write(jsonValueBytes + b"\n")

process.stdin.close()
process.wait()

Instead to send to web socket I'm using this code:
#!/usr/bin/env python

import asyncio
import websockets

async def hello(uri):
    header = {"Authorization": r"Basic XXXX="}
    message = '{"header":{"protocolVersion":1,"messageID":2,"stationID":400},"cam":{"generationDeltaTime":1,"camParameters":{"basicContainer":{"stationType":5,"referencePosition":{"latitude":451114425,"longitude":76720957,"positionConfidenceEllipse":{"semiMajorConfidence":4095,"semiMinorConfidence":4095,"semiMajorOrientation":3601},...other fields}}';
    async with websockets.connect(uri, extra_headers=header) as websocket:
        await websocket.send(message)

asyncio.get_event_loop().run_until_complete(
    hello('XXX'))

It send through pipe and works because I receive on pipe and send to the socket (the files FromPipe.txt. and ToSocket.txt are right).
Then I have code to send to a server with an opened web socket and this server send the message to the child. When the child receive from the socket the file FromSocket.txt is created but the ToPipe.txt in not created until I put it before the awit incoming.get()
FromSocket.txt has this content:
From socket: '{"header":{"protocolVersion":1,"messageID":2,"stationID":400},"cam":{"generationDeltaTime":1, ... other field}}'

But if there was a problem on type retrieving than it would create the file since it is the first instruction after the json_message = await incoming.get()
I think is a problem with the queue.
For test I put the incoming.get() in socket_consumer after the await outgoing.put(message) and it works.
UPDATE: If I run only the child (so without pipe) the ToPipe.txt is right and the message transfert from socket to pipe is fine.
For my test I run the parent, it sends to pipe one message that the child sends to the socket, then I send a message to the socket and the child catchs this message but it doesn't send to the pipe and the ToPipe.txt is not created. Maybe there is a problem in the main method

A: You are writing double-encoded JSON to the child process:
message = '{"header":{"protocolVersion":1,"messageID":2,"stationID":400}, the rest of json...}}';
jsonValue = json.dumps(message)

message is already a JSON string, so jsonValue is a double-encoded JSON string.
The pipe consumer pushes this double-encoded string into the queue for the socket. Next, the websocket producer in socket_producer() encodes the message again:
while True:
    message = await incoming.get()
    # ...
    json_message = json.dumps(message)
    await socket.send(json_message)

So now json_message is a triple-encoded JSON value, a JSON document containing a JSON document containing a JSON document:
>>> import json
>>> message = '{"header":{"protocolVersion":1,"messageID":2,"stationID":400}}}'  # valid JSON
>>> json_message = json.dumps(message)
>>> print(json_message)  # double-encoded
"{\"header\":{\"protocolVersion\":1,\"messageID\":2,\"stationID\":400}}}"
>>> json_message = json.dumps(json_message)  # encode *again*
>>> print(json_message)  # triple-encoded
"\"{\\\"header\\\":{\\\"protocolVersion\\\":1,\\\"messageID\\\":2,\\\"stationID\\\":400}}}\""

I don't know exactly what your web socket does with this, but lets assume that it uses json.loads() once, then echoes the decoded message back. This means that socket_consumer() receives the a JSON document that's encoded just twice. Your FromSocket.txt log certainly implies that this is what happens, because it contains a double encoded JSON message:
You can see this in your FromSocket.txt log:
From socket: "{\"header\":{\"protocolVersion\":1,\"messageID\":2,\"stationID\":400},\"cam\":{\"generationDeltaTime\":1,...other fields}}"

Note those \" entries, and the whole document is wrapped in quotes, but there are no \\\ triple-backslashes in the value.
Still, this extra layering of JSON encoding breaks the pipe_producer() coroutine, which expects the message to decode to a dictionary, not another string (even if that string contains another JSON document):
message = json.loads(json_message)
type = int(message.get('header', {}).get('messageID', -1))

message will decode to a string instead, so message.get will fail with an AttributeError, causing the coroutine to exit:
>>> json_message = "{\"header\":{\"protocolVersion\":1,\"messageID\":2,\"stationID\":400}}}"  # double encoded
>>> message = json.loads(json_message)
>>> message  # Back one stop, single-encoded JSON
'{"header":{"protocolVersion":1,"messageID":2,"stationID":400}}}'
>>> type(message)  # it's a string with JSON, not a dictionary
<class 'str'>
>>> message.get('header')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'get'

You need to make sure you do not encode your data too many times! If your pipe receives JSON data, don't encode the data again when sending it to the socket. When sending data to the pipe from the parent process, don't double encode the data, if you already have a JSON string there is no value in passing it through json.dumps() once more.
It would also be prudent to add more fail-safes in the coroutines. I didn't make the JSON decoding robust enough, so lets remedy that part:
async def pipe_producer(pipe_writer, incoming):
    # take messages from the queue and send them to the pipe
    while True:
        json_message = await incoming.get()
        try:
            message = json.loads(json_message)
            type = int(message.get('header', {}).get('messageID', -1))
        except (ValueError, TypeError, AttributeError):
            # failed to decode the message, or the message was not
            # a dictionary, or the messageID was convertable to an integer
            type = None
        # 1 is DENM message, 2 is CAM message
        if type in {1, 2}:
            pipe_writer.write(json_message.encode('utf8') + b'\n')
            await pipe_writer.drain()

You probably want to record that the decoding failed somewhere (push messages to a log queue that a separate task picks up to write to a log).
Next, we can update the connect_* functions to not ignore exceptions in the tasks that complete:
done, pending = await asyncio.wait(
    [consumer_task, producer_task], return_when=asyncio.FIRST_COMPLETED)
for task in pending:
    task.cancel()
# force a result check; if there was an exception it'll be re-raised
for task in done:
    task.result()

The done.result() check can re-raise the exception thrown in a consumer or producer. Since the connect_* coroutines are run via asyncio.gather(), which in turn is run by loop.run_until_complete(), that exception is then propagated all the way to the main() function, so it'll exit Python and you get to see the traceback printed. I've updated my other answer to include the for task in done: task.result() loop as that's good practice anyway.
With just the task.result() loop in my original answer code, and a websocket that just echoes the message back, and entering a valid JSON document (not double-encoded), I can see the error immediately; the parent process here is my terminal, so I'm just copying in the JSON message into my terminal window to send data into the pipe:
$ python3.7 so52291218.py
{"header":{"protocolVersion":1,"messageID":2,"stationID":400}}
Traceback (most recent call last):
  File "so52291218.py", line 140, in <module>
    main()
  File "so52291218.py", line 137, in main
    loop.run_until_complete(asyncio.gather(socket_coro, pipe_coro))
  File "/.../lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete
    return future.result()
  File "so52291218.py", line 126, in connect_pipe
    task.result()
  File "so52291218.py", line 104, in pipe_producer
    type = int(message.get("header", {}).get("messageID", -1))
AttributeError: 'str' object has no attribute 'get'

When I remove the json.dumps() call from the socket_producer() or I change my websocket server to use json.loads() on the incoming message and sending that out as the result, then the code works and I get the same message echoed back to my terminal.
Note that you can't just use a loop to write to a subprocess.Popen() pipe when both stdin and stdout are pipes. You can trivially cause the childprocess to hang on I/O by only writing in a loop. You'd have to make sure to read from the stdout pipe too, but because the child process is going to read and write from those handles in effectively random order, your parent process would also have to handle the I/O for the Popen() pipes asynchronously.
Rather than write up how to do that (which is already covered elsewhere on Stack Overflow), I'm instead telling you to use the pexpect project, as it already has done all that work for you (by spawning a separate thread that continually reads from the stdout pipe); using pexpect.popen_spawn.PopenSpawn() to keep this close to your original setup would look like this:
import sys
import pexpect

test = '...'
process = pexpect.popen_spawn.PopenSpawn([sys.executable, test])

for i in range(5):
    message = '{"header":{"protocolVersion":1,"messageID":2,"stationID":400}}';
    jsonValueBytes = message.encode("utf-8")
    process.send(jsonValueBytes + b"\n")

    # echo anything coming back
    while True:
        index = process.expect([process.crlf, pexpect.EOF, pexpect.TIMEOUT], timeout=0.1)
        if not process.before:
            break
        print('>>>', process.before.decode('utf8', errors='replace'), flush=True)

# send EOF to close the pipe, then terminate the process
process.sendeof()
process.kill(1)
process.wait()

So every time we send a full line to the pipe, we also look for lines coming the other way, with a short timeout, and echo any such lines.
With all fixes in place (making sure to avoid multiple-encoding JSON messages), and a very simple echoing websocket server, the pexpect code above prints:
>>> {"header":{"protocolVersion":1,"messageID":2,"stationID":400}}
>>> {"header":{"protocolVersion":1,"messageID":2,"stationID":400}}
>>> {"header":{"protocolVersion":1,"messageID":2,"stationID":400}}
>>> {"header":{"protocolVersion":1,"messageID":2,"stationID":400}}
>>> {"header":{"protocolVersion":1,"messageID":2,"stationID":400}}

Showing that there is a full round-trip path from parent process to child process to websocket and back.


text:
Q: Sign of the wave function in orbital representation? I have some fog in my head and a rather simple question for you:
When the sign of the wave function is representated on orbitals, what is this sign? I mean is it the sign of the real part of the wave function only? Or is it the sign of the complex wave function?
Thanks if you have any clue/explanation/links about this ;)

A: Are you thinking of illustrations like this?

If so, the sign just means that (in this case) $\Psi(-x) = -\Psi(x)$. There is no absolute sense in which one half of the orbital is negative and the other positive.


text:
Q: Software only USB implementation for ARM-M0/M0+? Since I'm worried about the future of AVR, I've been looking into software USB for ARM cortex-M0/M0+ that is similar to V-USB.  All I've found is a port of LUFA, which is for MCUs with internal USB hardware.
Now I know there are Cortex-M0/M0+ controllers that do have USB hardware, although I'm looking at using the smallest lowest pin-count I possibly can which usually don't have USB hardware.  I know some of these tiny controllers will have USB hardware but they are typically in a WLCSP package which have small spacing between the pads which I cannot work with.  This is why I'm looking for a software implementation.
Is there a software only implementation of USB for ARM-M0/M0+?
note: by software, I mean firmware but it seems code-only implementations of hardware peripherals are usually referred to by software.
note 2: Please don't suggest any specific products.  The question isn't about an inability to find small controllers with USB, its about the lack of a software implementation of USB for ARM much like V-USB.

A: Here's a new M0+ implementation comparable to V-USB
https://github.com/xobs/grainuum
Interesting 33c3 video explaining as well: https://youtu.be/GFY_A3jcI28
Still pretty fresh and prob not as stable as V-USB but sounds promising.  Curious how vital the 2 stage pipeline of the M0+ really is as would be nice to implement this on M0.
Doesn't sound like he's so tight that he can't afford one more cycle with the 3 stage pipeline.  I think the biggest issue will be M0's lack of single cycle I/O ports which is an optional feature of the M0+.  But he makes it sound like the pipeline is the real benefit of M0+.

A: It is not really too feasible. Because today many microcontrollers are fabricated for 2.5V down to 1.8V operating ranges. The software implementation through simple I/O toggling will not handle the high speed differential operation without a dedicated PHY on silicon (with special tranceivers). V-USB was working on AVR because it used on microcontrollers operating on 5V. There are no many of them on modern designs.


text:
Q: Rails rake db:migration do not recognise new migrates strange problem with rails migration.
I have 2 migrations in my app

I run rake db:migrate

Only one migration executed. No matter how many time I tried, the second migration was ignored
I also tried to run the specific migration by specifying a version number, but no luck

Use rails 4.1
The first migration generated by
rails g scaffold User .......

The second migration generated by devise plugin
rails g devise user ........

A: The migration file generated is without extension .rb.
It was an issue that was already reported in Devise. It was resolved in Devise version 3.2.3. Read the issue Generated migration filename missing extension #2971

A: Second file needs the .rb extension?


text:
Q: Displaying datetime in view in datepicker In my mvc application I've got a datepicker control and this control doesn't read value from database.
Model:
 [DisplayFormat(DataFormatString = "{0:dd'.'MM'.'yyyy}", ApplyFormatInEditMode = true, ConvertEmptyStringToNull = false)]
    public DateTime? myDate { get; set; }

View:

                    @Html.LabelFor(model => model.myDate, htmlAttributes: new { @class = "control-label col-md-4" })

                        @Html.EditorFor(model => model.myDate, new { htmlAttributes = new { @class = "form-control datepicker", @type = "date" } })
                        @Html.ValidationMessageFor(model => model.myDate , "", new { @class = "text-danger" })

Value in model:
model.myDate.Date {14.02.2019 0:00:00}
On the view it's displaying
dd.mm.yyyy without any values.
Saving works fine though.

A: My co-worker solved the problem by editing View in this way:

                    @Html.LabelFor(model => model.myDate, htmlAttributes: new { @class = "control-label col-md-4" })

                        @Html.EditorFor(model => model.myDate, new { htmlAttributes = new { @Value = (@Model.myDate.HasValue ? @Model.myDate.Value.ToString("yyyy-MM-dd") : null), @class = "form-control datepicker", @type = "date" } })
                        @Html.ValidationMessageFor(model => model.myDate, "", new { @class = "text-danger" })

A: I think the problem might be in the DataFormatString.
Try replacing:
DataFormatString = "{0:dd'.'MM'.'yyyy}"

with this:
DataFormatString = "{0:dd.MM.yyyy}"


text:
Q: Launch multiple and parallel forms and update them in C# I am writing a software where I need to create N forms and update them in real time from an application console.
I post here an example:
//THE DIMENSION OF o IS VARIABLE, IT CAN RANGE FROM 0 TO 5
//o LENGTH DEFINE HOW MANY PARALLEL FROMS MUST BE LAUNCHED AND o CONTENT DEFINE THE FORM TITLE
//osc IS A List<Osci>

public void read()
{
    //Create N thread
    Thread[] oscThread = new Thread[o.Length];

    for(int i = 0;i<o.Length; i++)
    {
        oscThread[i] = new Thread(new ThreadStart(OsciThreadProc));
        oscThread[i].Start();
        osc[i].setTitle("form n. " + o[i]);
    }

    //loop until the thread must be alive
    while (!suspendThread)
    {
        //HERE I GET A NEW LINE OF MY RAW DATA
        rawData myTemporaryRaw = getRawData();
        //HERE I RETURN THE DATA ANALYZED
        int[] data = AnalyzeRaw(myTemporaryRaw);

        //UPDATE FORM CONTENT
        //O CONTENT MATCH WITH Data VALUE
         for(int j = 0; j < o.Length; j++)
         {
            osc[j].Draw(data[o[j]]);
         }
    }
}

private void OsciThreadProc()
{
    var myOsc = new Osci();
    osc.Add(myOsc);
    myOsc.ShowDialog();
}

It is a console application (here, for simplicity I posted only a couple of methods) that must launch n forms and update them with a flow of content.
The form code is:
//THIS FORM HAS ONLY A LABEL valueLabel
public partial class Oscilloscope : Form
{
    public Osci()
    {
        InitializeComponent();
    }

    public Osci(int c)
    {
        InitializeComponent();
    }

    private void Osci_Load(object sender, EventArgs e)
    {

    }

    internal void setTitle(string title)
    {
        Text = title;
    }

    internal void Draw(int v)
    {
        valueLabel.Text = v.ToString();
    }
}

When I start this program, it launch an Exception ('System.ArgumentOutOfRangeException') on osc[i].setTitle("form n. " + o[i]);. Probably it try to get the new value, that are performed in the second method, before then first method.
Anyway, I think also that my way is not the best way in order to launch parallel forms and update them with a flow of information.
Can you sudgest to me a better way?

A: Are you sure that osc and o have equal dimensions at the moment of the error? It seems to me that they do not. So the error is only in that.


text:
Q: How is a toolbar generate from this line? I have this line

 in a code I'm working on. It generates a toolbar with many button on it and display a map. My goal is to add a new button to this toolbar but how am I suppose to do it knowing that they are generated by this line ? I used grep to try to find a JS function who could use this id to generate buttons but nothing at the moment.

A: Your application is dynamically generating elements with JavaScript.
Your code only shows a
 element, this provides nothing to identify how the buttons are being generated.
Open your website on Chrome and click Inspect Element. Then go to sources and you should be able to view the JavaScript that is creating the page.
Alternatively you can search through your source code for the id embedded_map, and you should be able to see the JavaScript written to generate the buttons.


text:
Q: Aruba with Thor, the feature fails with weird issue Building a CLI app using Thor and Aruba as testing framework.
Posted this issue at the Aruba's issues at github https://github.com/cucumber/aruba/issues/76 but still no comments at all.
So I'm posting it here so that I can get some feedback.
Issue
There are 2 scenarios in the features/login.feature file
The difference between the scenarios is that one uses Then I debug step, other doesn't.
When I run bundle exec cucumber features/, the one without debugger step fails. Aruba cannot catch the output.
But the one with debugger step, halts and when I press c to continue, Aruba can catch the output and it passes.
Banging my head since past 2 days, googled the whole earth, but couldn't find whats the issue is.
I've uploaded the repo at https://github.com/millisami/aruba_thor so that someone can see the issue.
To run the feature, just run bundle exec cucumber features.

A: I found the workaround myself.
Thanks to those who read this issue.


text:
Q: WPF: Windows 7 vs Windows 10 Appearance I have annoying appearance differences between Windows 10 devices and Windows 7 devices.
I am using WindowStyle="None" and DockPanel directly inside my Window element.
What I don't get is why there is still a border? Why are the borders on buttons, textboxes, comboboxes, etc. rounded?
It seems this is related to Aero. Is there a way I can stop my application from using Aero? I'm assuming there is another presentation framework related to Windows 10 but do not know what it is called to force it.
Would a BorderBrush be the easiest way to resolve this?
<Window x:Class="CBD.Presentation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:CBD.Presentation"
        Title="CBD" Height="760" Width="944" WindowStartupLocation="CenterScreen"
        WindowStyle="None" SizeChanged="Window_SizeChanged" MinWidth="944" MinHeight="760"
        Icon="favicon.ico">
    <DockPanel x:Name="Root_Window" Background="Black">
        <!--Application stuff here -->
    </DockPanel>
</Window>

Windows 7 display:

Windows 10 display:

Everything still functions properly but the way some textboxes and buttons are setup, parts of letters are missing.

A: I think both these is something a lot of people are going to stumble upon when they really start customizing the style of their applications. There's some well established shortcuts to both problems, such as using existing style/libraries for WPF:
There's a few common Window and style libraries I see:

*

*MahApps.Metro is a great library I've used for a long time for getting clean windows and interfaces (especially with 'dark' themes some customers love).

*Modern UI. Little personal experience, but it's similar in that it has more modern window designs, as well as a big style set. I've seen it used frequently.

*Elysium. Again, not much experience, but seems active. I've not seen it used as much as the other two.

These, of course, include a lot of other Metro theming. There are other theme packs available, I've found the Material Design In XAML Toolkit great if a client want's a modern design (Also recognizable, being from Google).
It looks like you're making your style from scratch, but the above might still be useful for you to simply use for the windows. If you want to go at it yourself there's a lengthy discussion with lot's of answers here.
For the curved corners, as discussed in the comments, this is as a result of WPF's default behavior on different operating systems. It attempts to select a default style to blend in best with the current operating system. For most applications that just use the default theme, this doesn't often matter.
When you're styling everything yourself though, it really plays havoc with what you have manually configured, because some properties that work well with the theme you set things up on might be different - like the rounded corners.
There's two options.

*

*Explicitly set all the properties, so it looks exactly how you want it. Doing this means that even if the 'base' theme changes, it will still look good. This is how those libraries above do things - they define a style completely. Problem is you will have to test it on the different themes manually and it's a bit of work.

*Manually set the base theme. (Can also be used for testing in option 1!) You can override which theme your app uses manually rather than letting it use the default for the operating system in much the same way you apply other custom themes, or maybe your own:

<App.Resources>
  <ResourceDictionary Source="/PresentationFramework.Aero, Version=3.0.0.0,
      Culture=neutral, PublicKeyToken=31bf3856ad364e35,
      ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml"/>
</App.Resources>

For some reason the above would not appear as code unless encased in quotes...


text:
Q: Accessing parent-child attributes in Mongoid I have two classes, namely Person and Language. Each language has a creator and an updater both who are from the Person class. I want to query attributes of the parent through the child and vice versa.
Person class
class Person
  include Mongoid::Document
  field :first_name, type: String
  field :last_name, type: String

  has_many :created_languages, class_name: 'Language', inverse_of: :created_by, foreign_key: 'created_by_id', autosave: true
  accepts_nested_attributes_for :created_languages

  has_many :updated_languages, class_name: 'Language', inverse_of: :updated_by, foreign_key: 'updated_by_id', autosave: true
  accepts_nested_attributes_for :updated_languages
end

Language class
class Language
  include Mongoid::Document

  field :content, type: String

  belongs_to :created_by, class_name: 'Person', inverse_of: :created_languages, foreign_key: :created_by_id, autosave: true
  accepts_nested_attributes_for :created_by

  belongs_to :updated_by, class_name: 'Person', inverse_of: :updated_languages, foreign_key: :updated_by_id, autosave: true
  accepts_nested_attributes_for :updated_by
end

What I want to query in my Rails app is the following: i.e. in the Rails console:
ruby 2.0.0p451 > a = Person.create!(first_name: "Marco", last_name:"Reus")
ruby 2.0.0p451 > b = Language.create!(content: "German", created_by_id: a.id, updated_by_id: a.id)
ruby 2.0.0p451 > a.created_languages (now works)
ruby 2.0.0p451 > a.updated_languages (now works)
ruby 2.0.0p451 > b.created_by (now works)
ruby 2.0.0p451 > b.updated_by (now works)

I used to receive the below error. With the above code it was solved.
Mongoid::Errors::AmbiguousRelationship:
Problem: Ambiguous relations :created_languages, :updated_languages defined on Person.
Summary: When Mongoid attempts to set an inverse document of a relation in memory, it needs to know which relation it belongs to. When setting :updated_by, Mongoid looked on the class Language for a matching relation, but multiples were found that could potentially match: :created_languages, :updated_languages.
Resolution: On the :updated_by relation on Language you must add an :inverse_of option to specify the exact relationship on Person that is the opposite of :updated_by.

A: You should also include inverse_of for all of them as such:
has_many :created_languages, class_name: 'Language', :inverse_of => :created_by

belongs_to :created_by, class_name: 'Person', :inverse_of => :created_languages

Hope it helps.


text: Q: how to export an xhtml form to xls including p:outputText and p:dataTable? i am creating an online time sheet form which then can be exported when approved as excel to be printed. i used primefaces extension pe:exporter for the data table, but i do not know how to export the p:outputText so that it will also exported together with the data table.


text: Q: System Update from 16.04 to 17.10 I've done a big update on my PC. He asked me if I want to upgrade from 16.04 to 17.10 but I don't know if I can lose some data or something..can someone explain me this situation? Thanks in Advice!


text: Q: Force specific text formatting when inserting text in Microsoft Word I like to annotate sources in DOCX form by adding notes into the body of the text. In order to distinguish between source text and annotation, however, it is necessary to use different text-formatting from the original text for the annotations. Is there any way to force Word to use this different style when I insert text, instead of having to reformat every individual annotation?


text:
Q: How to display tab bar when navigates to out of tabview controller? I have four tab item (home, user, setting, tools) in my tabbed page.
from home , trying  to navigate some other view controller. But , it navigate as new page. I want to navigate inside tabview controller and  want to display the tab bar item when it goes to next page.  Please advise how to achieve this in tabview controller.
[1]: https://i.stack.imgur.com/vo95F.png [enter image description here][1]

A: Use the UI hierarchy as my comment described, then it will work as you want.
The hierarchy in the storyboard is like this:

Make sure the tab bar controller is the root. Your table view controller have to be embedded in a navigation controller. Let the navigation controller be the tab  of the tab bar controller.


text:
Q: Get kubectl credentials in Azure I have created a K8s service (cluster) on Azure Portal.
I can retreive my credentials with this command (works fine):
az aks get-credentials --resource-group myResourceGroup --name myAKSCluster

But i want to know how i can download credentials from azure portal web interface (UI). Is there a way to do that ?
Thanks

A: K8s credentials are not available from the portal UI. Ref: https://learn.microsoft.com/en-us/azure/aks/kubernetes-walkthrough-portal#connect-to-the-cluster
You can connect to the cluster via cloud CLI rather than your local terminal.


text:
Q: Run python script from bash into Terminal not running I'm trying to run the following bash script on my raspberry pi:
#!/bin/bash

python Testing.py

It gives me two options: "Execute" and "Execute in Terminal".  Execute works no problem, it produces a CSV that I'm testing.   When I use "Execute in Terminal" though, the script doesn't run (I also have some print statements in there that don't print).  The terminal window is titled "LXTerminal".
Am I missing something?  My goal is to launch the script in a terminal window so it can produce print statements etc.
Thanks!

A: This works for me:
xterm -e 'python /path/to/my/script.py'
or if xfce
xfce4-terminal -e '/path/to/my/script.py'
I just can't figure out how to keep terminal open when the scipt is complete.
Terminal is closed after script run.

A: Try chmod 755 "file path/filename. I think this should help as it is used to change the file permissions.

A: I ran into the same issue and the problem was that my python command was an alias to the executable. When I replaced it with python3, it worked.


text:
Q: How to give request to the admin by user created by admin I have created an admin site and along with two users. Now user needs to request the admin to create, update and delete the topics. In the meantime, every user has to give access to delete their own created topic.
How to process this using Django?
admin:
from django.contrib import admin
from .models import Question, Sub_Topic, SID,  Main_Topic, Subjects
admin.site.register(Question)
admin.site.register(SID)
admin.site.register(Subjects)
admin.site.register(Main_Topic)
admin.site.register(Sub_Topic)

models:
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase
from django.contrib.auth.models import User

class SID(models.Model):
    static_id = models.CharField(max_length=250)

    def __str__(self):
        return self.static_id

class Subjects(models.Model):
    subjects = models.CharField(max_length=250)

    def __str__(self):
       return self.subjects

class Question(models.Model):
    STATUS_CHOICES = (
    ('draft', 'Draft'),
    ('published', 'Published'),
)
    IMPORTANCE_SCORE = (
('LOW','Low'),
('NORMAL', 'Normal'),
('HIGH','High'),
)
    parentid = models.CharField(max_length=250)
    staticid = models.AutoField(primary_key=True)
    qid = models.CharField(max_length=250)
    question = models.TextField()
    a= models.CharField(max_length=250)
    b= models.CharField(max_length=250)
    c= models.CharField(max_length=250)
    d= models.CharField(max_length=250)
    answer = models.CharField(max_length=250)
    importance = models.CharField(max_length=6, choices= IMPORTANCE_SCORE,
      default='LOW')
    complexity = models.PositiveIntegerField(default=0)
    time = models.CharField(max_length=200)
    marks = models.CharField(max_length=200)
    foundation = models.CharField(max_length=250)
    subject = models.CharField(max_length=250)
    core = models.CharField(max_length=250)
    exam = models.CharField(max_length=250)
    fscore = models.CharField(max_length=250)
    sscore = models.CharField(max_length=250)
    cscore = models.CharField(max_length=250)
    escore = models.CharField(max_length=250)

    def __str__(self):
        return "{} - {}".format(self.qid, self.question)

class Main_Topic(models.Model):
    IMPORTANCE_SCORE = (
('LOW','Low'),
('NORMAL', 'Normal'),
('HIGH','High'),
)
    Main_Topic_Id = models.CharField(max_length=250)
    Main_Topic = models.CharField(max_length=250)
    Num_Of_Sub_Topics =  models.PositiveIntegerField(default=0)
    Num_Of_Questions = models.PositiveIntegerField(default=0)
    importance_score = models.CharField(max_length=6, choices= IMPORTANCE_SCORE, default='LOW')
    complexity_score = models.PositiveIntegerField(default=0)
    prerequisite = models.CharField(max_length=250)

    def __str__(self):
        return self.Main_Topic

def get_absolute_url(self):
    return reverse('topic_detail', args=[str(self.id)])

class Sub_Topic(models.Model):
    IMPORTANCE_SCORE = (
('LOW','Low'),
('NORMAL', 'Normal'),
('HIGH','High'),
)
    staticid = models.PositiveIntegerField(default=0)
    sub_topic = models.CharField(max_length=250)
    Num_Of_Sub_subTopics =  models.PositiveIntegerField(default=0)
    Num_Of_Questions = models.PositiveIntegerField(default=0)
    importance = models.CharField(max_length=6, choices= IMPORTANCE_SCORE,
    default='LOW')
    complexity = models.PositiveIntegerField(default=0)
    prerequisite = models.CharField(max_length=250)

    def __str__(self):
        return self.sub_topic

This is the model file I am using, I hope to need to modify the login in the admin panel. While first creating the admin using create superuser in the admin panel, admin can create the users and give permission.
If so user1 has some crud operations and user2 has some crud operations. But we need to keep those operations individual to them.

A: You may need to rewrite admin site if you want to do that. But it will be too many to talk about it here. You may need to find a tutorial and to learn how to customize admin site.
I will recommend that instead of allowing user login to admin site, you can create your user admin site. On this page, user only can watch, update or delete their topic.
To do it, you need to have a line under the model class which you allow user to modify it.
created_by = models.ForeignKey('User', unique=True)

And when you try to update or delete, you can check if created_by = request.user (which is the user who currently login).


text:
Q: SQLite + Searchbar + uitableview I want to use SQlite with uisearchbar and uitableview. There is any example for this.
I find many examples for Uisearchbar with uitableview and sqlite with uitableview but not see any example for Mixed up of three.
Please show me any link if there is possible.
OR sample code
Thanks

A: It's the same when we have data in table view and search it. We select data from database to show in table view after we search it.


text:
Q: Does limit exist for this function and how to plot it in wolfram alpha? Heyy,
Sorry about putting two questions in single thread, but felt it's easier this way :D
the function in question is
$$
f(x) = \begin{cases}
3x + 4,  & \text{if $x \in$ Q} \\
7x, & \text{if $x \notin$ Q}
\end{cases}
$$
And the question asks if the following limit exists
$$
lim_{x\to 1}f(x)
$$
since there can be irrational values of x when x reaches 1 from both sides, i decided that the limit would not exist.
(1) So my first question is whether the limit exists or not
(2) And second is how to plot this function in wolfram alpha so i can visualize the graph? I tried piecewise function plotting but i cannot define the conditions that x is an element of rational/irrational number sets
Thank You!

A: Both $3x+4$ and $7x$ are close to $7$ if $x$ is close to $1$. Hence the function is continuous at $1$.
You could try to visualize the graph by drawing two dotted lines representing the linear functions on $\mathbb Q$ and on its complement.


text:
Q: Update UserGroup management with Django We have a implementation problem with users, groups and organisations.
Our situation:

*

*We have organisations.

*In an organisation we have some users.

*Each user has permissions based on his group (admin, user, read-only).

Now, we need to manage users permissions through organisations.
User 1 can be admin in organisation1 and read-only into organisation2
How can we do ? Can we update the built-in user group management or do we have to create a new relation table ?


text:
Q: Show HTML in WebView using Prism.js I am having trouble showing HTML in JavaFX's WebVew using Prism.js. I am able to successfully show a Java example, but the HTML example seems to want to show the HTML as it appears when you visit a site instead of just showing the syntax string. What is the correct way to display HTML in JavaFX's WebView using Prism.js?
Java Example (Displaying correctly)
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication319 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        String javaString = "/* HelloWorld.java\n"
                + " */\n"
                + "\n"
                + "public class HelloWorld\n"
                + "{\n"
                + " public static void main(String[] args) {\n"
                + "     System.out.println(\"Hello World!\");\n"
                + " }\n"
                + "}";

        String htmlString = "<!DOCTYPE html>\n"
                + "\n"
                + ""
                + "<link href=\"" + getClass().getResource("prism.css") + "\"" + " rel=\"stylesheet\"" + " type=\"text/css\"" + " />\n"
                + "\n"
                + ""
                + "\n"
                + "\n"
                + "
My First Heading
\n"
                + "\n"
                + "
My first paragraph.
\n"
                + "\n"
                + "
"
                + " \n"
                + javaString
                + "\n"
                + "
\n"
                + "\n"
                + "";

        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();
        engine.setJavaScriptEnabled(true);
        engine.loadContent(htmlString);

        StackPane root = new StackPane(webView);

        Scene scene = new Scene(root, 500, 400);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}

HTML Example (Not displaying correctly)
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication319 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        String htmlStringPreCode = "<!DOCTYPE html>\n"
                + "\n"
                + "\n"
                + "\n"
                + "\n"
                + "This is a Test\n"
                + "\n"
                + "\n";

        String htmlString = "<!DOCTYPE html>\n"
                + "\n"
                + ""
                + "<link href=\"" + getClass().getResource("prism.css") + "\"" + " rel=\"stylesheet\"" + " type=\"text/css\"" + " />\n"
                + "\n"
                + ""
                + "\n"
                + "\n"
                + "
My First Heading
\n"
                + "\n"
                + "
My first paragraph.
\n"
                + "\n"
                + "
"
                + " \n"
                + htmlStringPreCode
                + "\n"
                + "
\n"
                + "\n"
                + "";

        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();
        engine.setJavaScriptEnabled(true);
        engine.loadContent(htmlString);

        StackPane root = new StackPane(webView);

        Scene scene = new Scene(root, 500, 400);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

}

Expected output

Java: 1.8.0_171
Prism.js Download in the picture has Java selected also

A: Html code needs to be escaped first (so it can be displayed as a plain text).
See this question, both solutions work:
htmlStringPreCode = htmlStringPreCode.replace("<", "<");

//or

htmlStringPreCode = "";


text:
Q: How can I redirect a user if they are not authenticated using router In Angular 2 how can I redirect a user if they are not authenticated using router version 2.0.0-rc.1
I'm looking to do this in my app.component where my routes are store.
I want to detect if the user is authenticated before it hits a pages component.
So I can then redirect them to the login.
I've tried canActivate which doesnt seem to work for my router version.
I'm looking for a solution for this version of the router:     "@angular/router": "2.0.0-rc.1"
OR
A solution for the latest version of the router. If one is provided can you show me how to update my router version using git bash with this solution.
This is my current code:
export class AppComponent implements CanActivate {
    authService: AuthService;
    userService: UserService;

    constructor(_authService: AuthService, _userService: UserService, private location: Location, private router: Router) {
        this.authService = _authService;
        this.userService = _userService;
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < boolean > | boolean {

        //This doesnt get hit
        console.log("here");

        return true;
    }
}

A: Use an Interceptor:
import {bootstrap} from '@angular/platform-browser-dynamic';
import {provide} from '@angular/core';
import {HTTP_PROVIDERS, Http, Request, RequestOptionsArgs, Response, XHRBackend, RequestOptions, ConnectionBackend, Headers} from '@angular/http';
import {ROUTER_PROVIDERS, Router} from '@angular/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash'

import {MyApp} from './app/my-app';

class HttpInterceptor extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options));
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.get(url,options));
    }

    post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.put(url, body, this.getRequestOptionArgs(options)));
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.delete(url, options));
    }

    getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers();
        }
        options.headers.append('Content-Type', 'application/json');
        return options;
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status  == 401 && !_.endsWith(err.url, 'api/auth/login')) {
                this._router.navigate(['/login']);
                return Observable.empty();
            } else {
                return Observable.throw(err);
            }
        });

    }
}

bootstrap(MyApp, [
  HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    provide(LocationStrategy, { useClass: HashLocationStrategy }),
    provide(Http, {
        useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router) => new HttpInterceptor(xhrBackend, requestOptions, router),
        deps: [XHRBackend, RequestOptions, Router]
    })
])
.catch(err => console.error(err));

A: You can use this
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

  constructor(private router: Router) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(
        catchError(
          (err: HttpErrorResponse) => {
            if (this.router.url !== '/login' && err.status === 401) {
              this.router.navigate(['/login']);
            }
            return throwError(err);
          }
        )
      );
  }

}

And in app.module.ts
{
  provide: HTTP_INTERCEPTORS,
  useClass: ErrorInterceptor,
  multi: true,
},


text:
Q: Can't break out of do while loop gcc (GCC) 4.6.3
c89
Hello,
I have the following do..while loop
#define NUMBER_DX_CHANNELS 4

do {
/* some some processing here */
i++;
dx_channels++;
} while((dx_channels > CHANNELS_PER_BOARD) || (i < number_fx_resources));

For some reason the dx_channels should reach 4 first before the number_fx_resources is reached. However, it never breaks out of the dx_channels > CHANNEL_PER_BOARD.
I could use an if statement, but that would be added a extra line of code.
Am I doing something wrong here? Is it because I am testing for 2 conditions?
Many thanks for any suggestions,

A: You need: while((dx_channels < CHANNELS_PER_BOARD) && (i < number_fx_resources));
Note: && instead of ||


text:
Q: How to add  or  tags to  with HtmlAgilityPack? The link to download documentation from http://htmlagilitypack.codeplex.com is returning an error and I can't figure this out by trying the code.
I'm trying to insert various tags into the <head> section of a HtmlDocument that I've loaded from a HTML string. The original issue I'm having is described here.
Can somebody give me an idea of how to achieve this? Thanks

A: Maybe a bit late :-) Suppose I have this test.htm Html file:
<html>
<head>
    <title>Hello World!</title>
</head>
<body>
    Hello World
</body>
</html>

Here is how to add a LINK element underneath the HEAD element. You will not the semantics is very close to the System.Xml one, on purpose:
HtmlDocument doc = new HtmlDocument();
doc.Load("test.htm");

HtmlNode head = doc.DocumentNode.SelectSingleNode("/html/head");

HtmlNode link = doc.CreateElement("link");
head.AppendChild(link);
link.SetAttributeValue("rel", "shortcut icon");
link.SetAttributeValue("href", "http://www.mysite.com/favicon.ico");

The result will be:
<html>
<head>
    <title>Hello World!</title>
<link rel="shortcut icon" href="http://www.mysite.com/favicon.ico"></head>
<body>
    Hello World
</body>
</html>


text:
Q: Query - Pivoting 2 columns into 2 rows I am familiar with PIVOTS but have done only simple ones of one column into a row.
I have this query:
DECLARE @EndDate DATE
SET @EndDate ='20160728' --{?EndDate}

SELECT T1.ItemCode,SUM(T0.IssuedQty) [Litres],SUM(T1.CmpltQty) [Tons]
FROM    WOR1 T0 INNER JOIN
        OWOR T1 ON T0.DocEntry = T1.DocEntry INNER JOIN
        OITM T2 ON T1.ItemCode = T2.ItemCode
WHERE   T0.ItemCode ='FURNACE OIL/0001' AND T1.Type ='S' AND
        (T1.PostDate BETWEEN (SELECT Dateadd(month, Datediff(month, 0, @EndDate), 0)) AND @EndDate)
GROUP BY T1.ItemCode

This returns the results:

What do I need to do is to get the following results but I'm unsure how.

How do I achieve this?
EDIT: The one highlighted as duplicate is different. It is joining 2 queries for additional columns. I just need 1 query transposed to take 2 columns into rows.

A: You could do something like this I suppose:
DECLARE @EndDate DATE
SET @EndDate ='20160728' --{?EndDate}

SELECT
    A.LineType,
    CASE B.ItemCode WHEN 'FG/RM/001' THEN CASE A.LineType WHEN 'Litres' THEN SUM(B.IssuedQty) WHEN 'Tons' THEN SUM(B.CmpltQty) ELSE Null END END AS [FG/RM/001],
    CASE B.ItemCode WHEN 'FG/RM/002' THEN CASE A.LineType WHEN 'Litres' THEN SUM(B.IssuedQty) WHEN 'Tons' THEN SUM(B.CmpltQty) ELSE Null END END AS [FG/RM/002],
    CASE B.ItemCode WHEN 'FG/RM/003' THEN CASE A.LineType WHEN 'Litres' THEN SUM(B.IssuedQty) WHEN 'Tons' THEN SUM(B.CmpltQty) ELSE Null END END AS [FG/RM/003],
    CASE B.ItemCode WHEN 'FG/RM/004' THEN CASE A.LineType WHEN 'Litres' THEN SUM(B.IssuedQty) WHEN 'Tons' THEN SUM(B.CmpltQty) ELSE Null END END AS [FG/RM/004],
    CASE B.ItemCode WHEN 'FG/RM/005' THEN CASE A.LineType WHEN 'Litres' THEN SUM(B.IssuedQty) WHEN 'Tons' THEN SUM(B.CmpltQty) ELSE Null END END AS [FG/RM/005],
    CASE B.ItemCode WHEN 'FG/RM/006' THEN CASE A.LineType WHEN 'Litres' THEN SUM(B.IssuedQty) WHEN 'Tons' THEN SUM(B.CmpltQty) ELSE Null END END AS [FG/RM/006],
    CASE B.ItemCode WHEN 'FG/RM/007' THEN CASE A.LineType WHEN 'Litres' THEN SUM(B.IssuedQty) WHEN 'Tons' THEN SUM(B.CmpltQty) ELSE Null END END AS [FG/RM/007]
FROM
    (
        SELECT 'Litres' AS LineType
    UNION ALL
        SELECT 'Tons' AS LineType
    ) A
CROSS JOIN
    (
        SELECT T1.ItemCode,SUM(T0.IssuedQty) [Litres],SUM(T1.CmpltQty) [Tons]
        FROM    WOR1 T0 INNER JOIN
                OWOR T1 ON T0.DocEntry = T1.DocEntry INNER JOIN
                OITM T2 ON T1.ItemCode = T2.ItemCode
        WHERE   T0.ItemCode ='FURNACE OIL/0001' AND T1.Type ='S' AND
                (T1.PostDate BETWEEN (SELECT Dateadd(month, Datediff(month, 0, @EndDate), 0)) AND @EndDate)
        GROUP BY T1.ItemCode
    ) B
GROUP BY
    A.LineType


text:
Q: How can I ignore a TAP result in perl with Test::more? I want to make use of this library to pretty print the differences of my test Test::Differences; but I do not want to count this in my plan, as this is just used for debugging in my use case.
So I created a minimal example of this issue to reproduce this, I know is not "right" to do the oks like this, but is a good ilustration of the problem.
use strict;
use warnings;
use utf8::all;
use open ':std', ':encoding(UTF-8)';

use Test::Differences;
use Test::Deep::NoTest qw(cmp_details deep_diag);
use Test::More tests => 2;
use JSON;

my $context = 1;
my $extracted_ref = {
    a => '1',
    b => '2',
    c => '3',
    d => '4',
};
my $reference_ref = {
    a => '1',
    b => '3',
    c => '3',
    d => '4',
};

my ($is_compare_ok, $stack) = cmp_details($extracted_ref,$reference_ref);
my $json_reference = JSON->new->canonical->encode($reference_ref);
my $json_extracted = JSON->new->canonical->encode($extracted_ref);

ok(1);
if ($is_compare_ok){
    ok(1);
    return 1;
}else{
    ok(0);
    eq_or_diff($reference_ref, $extracted_ref, "Error in '$0'", {context=>$context}); # <- I don't want to count this
    return 0;
}

I would expect to get to tests executed at the end of the script, the two ok which are done during the process. But the function eq_or_diff adds a new test to the TAP session so the script ends with an exection of 3 tests and therefore done_testing() expects 2 but gets 3.
This is a minimal example, but usually I have a main script:
main.t
use Test::More tests => 2;
...
ok(some_function_in_other_file_or_library(), "name_of_the_test");
...

lib.pm
...
sub some_function_in_other_file_or_library{
...
   eq_or_diff(...)
   return $bool;
}
...

I mention this because I tried with substest and I was not able to make it work neither, and I main does not have to now what happens in the lib because otherwise I think I could just use done_testing($planned_tests+1):
lib.pm
use Test::More tests qw/subtest/;
subtest 'An example subtest' => sub {
    plan tests => 1;

    eq_or_diff(...)
};

Summary: How can I make something similar to:
do_not_add_to_tap(eq_or_diff(...))
# or
increased during runtime the planned tests
plan() = plan()+1...

A: Test::Differences and friends are really doing two things for you, then complicating it by tightly coupling it to the test framework. That's not a big bother because it's really just wrapping things from other modules that you can use directly.
First, it uses Data::Dumper to output a predictable serialization by setting various parameters, such as SortKeys. Second, it uses Text::Diff to compare the lines of those dumps.
So, just do that yourself. Here's the first part, which just returns the single string that represents the dump, suitable for string comparisons to see if they are equal:
sub dump_it {
    my( $arg ) = @_;
    local $Data::Dumper::Deparse   = 1;
    local $Data::Dumper::Indent    = 1;
    local $Data::Dumper::Purity    = 0;
    local $Data::Dumper::Terse     = 1;
    local $Data::Dumper::Deepcopy  = 1;
    local $Data::Dumper::Quotekeys = 0;
    local $Data::Dumper::Useperl   = 1;
    local $Data::Dumper::Sortkeys  = 1;
    Data::Dumper::Dumper($arg);
    }

The second part does a similar thing with Text::Diff. It sets various parameters, which you can season to taste. I made this to pass it two strings, which I turn into lines inside an array reference (since this is all in memory):
sub my_diff {
    state $rc = require Text::Diff;
    my( $got, $expected, $context ) = @_;

    $context //= 3;  # lines around the diff to show

    my $diff = Text::Diff::diff
        [ split /^/m, dump_it( $got ) ],
        [ split /^/m, dump_it( $expected ) ],
      { CONTEXT     => $context,
        STYLE       => 'Table',
        FILENAME_A  => 'got',
        FILENAME_B  => 'expected',
        OFFSET_A    => 1,
        OFFSET_B    => 1,
        INDEX_LABEL => "Ln",
      };
    chomp $diff;
    $diff .= "\n";

    $diff;
    }

So now the meat of your program is something like this:
my $is_same = dump_it( $reference_ref ) eq dump_it( $extracted_ref );

pass();
if ($is_same){
    pass();
}else{
    fail();
    note( my_diff( $reference_ref, $extracted_ref, 1 ) );
}


text:
Q: Data binding 15,000 items in a combobox is too slow So as the title suggests, I have about 15,000 items and I'm trying to bind them to a ComboBox. well I have a data grid and I tried using a DataGridComboBoxColumn which was slow so I switched to a DataGridTemplateColumn using DataTemplates but it's not any faster. I've been searching online for a long time and I profiled my code and the majority of the time isn't being spent in my code. So my question is how would I speed that up? I'm pretty new to WPF and C#. My collection is a static ObservableCollection that I'm binding to the ItemsSource.

A: The default ItemsPanel of a ComboBox might be a StackPanel, which lacks virtualization, you could try to replace it with a VirtualizingStackPanel to see if that is the issue.
However this is still kind of a bad idea unless you use the ComboBox's keyboard input capabilities.


text:
Q: getElementById with variable into backticks I want to modify an element according to the id that returns my server, out after several hours of research I can not operate my code.
var doc = document.getElementById(`"itvf-ticket-${data.idIntervention}"`);
console.log(doc); --> null
doc.style.display = "block"; --> can't work cause it's null

Yet if I enter my id directly, the "display block" is made.
document.getElementById("itvf-ticket-36").style.display = "block";

Thank's!

A: If you're using backticks then the quotation marks aren't necessary and can be removed.
var doc = document.getElementById(`itvf-ticket-${data.idIntervention}`);

See the MDN docs for template literals for further reference.

A: If you're using backticks because you're trying to use a template literal, the problem is the quotes ("); remove them:
var doc = document.getElementById(`itvf-ticket-${data.idIntervention}`);
doc.style.display = "block";

An untagged template literal results in a string.
Live Example:

var data = {
  idIntervention: "123"
};
var doc = document.getElementById(`itvf-ticket-${data.idIntervention}`);
doc.style.display = "block";

This is the initially-hidden div

A: Look at the string you are generating. Compare it to the working string.

const manual = "itvf-ticket-36";
const data = {
  idIntervention: 36
};
const generated = `"itvf-ticket-${data.idIntervention}"`;
console.log(manual);
console.log(generated);
console.log(manual === generated);

" delimit a string literal. ` delimit a template literal which creates a string.
You are adding quote marks to the ID you are trying to search for. Don't put the quote marks inside your string:
const generated = `itvf-ticket-${data.idIntervention}`;


text:
Q: mysql_server won't start: after downgrading from 8.0 to 5.7 I recently downgraded mysql from 8.0 to 5.7. The downgrade worked fine but somehow today after server shutdown, mysql wont start and below are the errors from : /var/log/mysql/error.log:
[ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.columns_priv'
doesn't exist
2021-01-06T13:28:45.064432Z 0 [ERROR] Fatal: can't initialize grant subsystem - 'Table
'mysql.columns_priv' doesn't exist'
2021-01-06T13:28:45.064442Z 0 [ERROR] Fatal error: Failed to initialize ACL/grant/time zones
structures or failed to remove temporary table files.
2021-01-06T13:28:45.064498Z 0 [ERROR] Aborting

2021-01-06T13:28:45.065865Z 0 [Note] Binlog end

Working in ubuntu server 18.04


text:
Q: Materialized view bigger than table it is based on? I have a database that's ~130 GB and one table makes up for most of this (85 GB). Because this table holds a lot of duplicates, we have a materialized view which basically uses a window function to only select the newest rows.
The original table holds 85 mio. records and the materialized view is expected to have approximately 15 mio. records. So I would expect about 15 GB of disk usage. There are no additional attributes in the view, that are not already in the table.
However, when I invoke REFRESH MATERIALIZED VIEW it fails with "not enough disk space", even though there are 160 GB free. I checked and it really writes that much (and then rolls back).
Why would I need that much space? 160 GB is almost twice of the original table, although it should contain only 1/5 of the data.
I am running Postgresql 10.6.


text:
Q: dropdownlistfor to a string to use in jquery in my script code, i would like to get the html content of the droplistfor and put it to a variable, but when i try it, it gives me an error:
Uncaught SyntaxError: Unexpected token <
var select_doc_types = @Html.DropDownListFor(m => m.DocumentTypes, Model.DocumentTypes, Resources.Select, new { @class = "form-control" });

Why is it according to you ?
is there a way to do it without calling a partial view to get the string values.
Thanks

A: Try below:
var select_doc_types = = (Html.DropDownListFor(m => m.DocumentTypes, Model.DocumentTypes, Resources.Select, new { @class = "form-control" })).ToString();

Basically DropDownListFor returns MvcHtmlString you need to convert to string. Hope it helps

A: I end up doing that, it works just fine:
var select_doc_types = "<select class='form-control'><option selected='selected' disable>Please Choose...</option>"+
                    foreach (var item in Model.DocumentTypes)
                    {
                        <text>"<option> @item.Text </option>" + </text>
                    }
                    "</select>";


text:
Q: Velocity and acceleration measurement in a video I am trying to find a method to calculate the velocity and acceleration of a tracked object, lets say a ball falling. I am using Processing 2 to make this program, and I know the distance from the camera to the object and it can calculate its position in every frame during the motion.
To calculate the velocity, I used this formula (all calculated in pixels): VelocityX=(PositionX - LastPositionX)/delta time
And something similar with acceleration: AccelerationX=(VelocityX - LastVelocityX)/delta time
Then, I changed delta time with frames. So now I have velocity and acceleration in Pixels per frame, but my question is how can I transform this Pixels per frame unit to mm/s for example? to more intuitive units like that.
I calculate the position in  pixels too, but I make a conversion to mm after that, but I'm a little confused about how to do that for velocity and acceleration.
// Get the current time
currTime = frameCount;
deltaTime = (currTime - prevTime);

// Remember current time for the next frame
prevTime = currTime;

// Calculate velocity in X and Y directions (pixels / frame)
if (lastMovingX != Float.MAX_VALUE) {
    velX = (PX - lastMovingX) / deltaTime;
    velY = (PY - lastMovingY) / deltaTime;
}

// Save the current frame position for the next calculation
lastMovingX = PX;
lastMovingY = PY;
if (lastVelX != Float.MAX_VALUE) {
    accelX = (velX - lastVelX) / deltaTime;
    accelY = (velY - lastVelY) / deltaTime;
}

lastVelX = velX;
lastVelY = velY;

A: If you know the size of the object, you can extract the ratio of pixels/mm. If you know your frame rate, you can convert frames to seconds.
To find pixels/mm = Object size in pixels / object size in mm
(pixels/frame) / (pixels/mm) = mm/frame
mm/frame * frames/second  = mm / second
Is this what you are looking for?


text:
Q: Mysterious Vertical Gap Between Divs There is a mysterious gap appearing between my header and footer. I took out the main content divs while investigating so I know it is not those to blame. Here is my website:
http://classweb2.mccombs.utexas.edu/mis333k/msbcf555/TestSite/Default.aspx
I will share the stylesheet if requested, but it is long and I feel like the solution is something obvious that I have not thought of.
What I have tried:

*

*Resetting the margins and padding

*Making sure no line breaks or other divs are hiding between the real divs

A: Your #header element has display:inline-block applied to it. Inline-block adds visible space between elements if there is any whitespace at all - even a single space character.  I'm not why you've made it an inline-block, as it seems like a standard block level element.  Remove that and the space should disappear.
There are other options as well, though I think this is the simplest.  For more information on the "mysterious" spaces that inline-blocks creates, see here: http://css-tricks.com/fighting-the-space-between-inline-block-elements/


text:
Q: How can I use a customized build of the AWS sdk in ReactJS? I make a customized build here of the AWS SDK:
https://sdk.amazonaws.com/builder/js/
I can't find any examples of how to use this in ReactJS.  Can anyone please point me in the right direction?
I have tried putting this in my index.html

And in my ReactJS code replaced imoprt with var:
//import AWS from 'aws-sdk'
var AWS = require('aws-sdk')

But now my application does not even load - shows only the background image and does not load - absolutely zero shows in the Chrome console - no messages at all.

I can see in the Chrome network console that the custom sdk build is being loaded OK with a status 200 so that seems to be OK.
Can anyone suggest what I need to do please?
thanks

A: You cannot import a customized build of AWS SDK as a module. You'll need to link it as an external js file in /public/index.html:
<script src="PATH/TO/YOUR/CUSTOM/aws-sdk-{SDK_VERSION}.min.js"></script>

Then, you can access the global variable AWS via window object:
const AWS = window.AWS;

AWS.config.region = "YOUR_BUCKET_REGION";
const bucket = new AWS.S3({
  params: {
    Bucket: "YOUR_BUCKET_NAME"
  }
});

Alternatively, instead of linking to customized SDK builds, you can always npm install aws-sdk and then import individual AWS services as:
const S3 = require("aws-sdk/clients/s3");


text:
Q: Is there a possibility that spring cloud config clients can load properties from their local as well? I am integrating spring cloud config in one of the products, where spring cloud clients are configured to load properties from spring cloud config server, and spring cloud config server operates in two profiles namely native & vault.
Is there a way/possibility that the spring cloud config clients do NOT reach out to server when their "spring.active.profiles" is set to let's "local" And for any other profiles apart from "local" they reach out to server.
In short, clients pick properties from their local and not server's local when "spring.active.profiles" is "local" and for any other profile they reach out to server to load properties?
The reason is for local development, we won't require to have spring cloud config server up and running.
Cloud config server application.yml:
server:
  port: 9111

spring:
  profiles:
    active: native
  cloud:
    config:
      server:
        # git:
        # uri:
        native:
          searchLocations: classpath:/common
        vault:
          port: 8200
          host: 127.0.0.1
          kvVersion: 1
          backend: kv
          profileSeparator: /

management:
  endpoints:
    web:
      exposure:
        include: '*'

Cloud config client bootstrap.properties:
spring.application.name=config-client
spring.cloud.config.uri=http://localhost:9111
spring.cloud.config.token=<Token>
spring.profiles.active=local

A: You can disable config server for a specific profile and refer to local property file. See below stackoverflow link for details:
Spring cloud config in local dev mode


text:
Q: Django Basics myapp mapping in myproject "myapp" is not defined I am learning django, and have ran python manage.py startapp myapp which created the following folder structure:
myapp/
   __init__.py
   admin.py
   models.py
   tests.py
   views.py

I also added myapp to INSTALLED_APPS in settings,
INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp',
)

then I ran python manage.py migrate and python manage.py createsuperuser to create super user
I have also created views of myapp :
"from django.http import HttpResponse

def hello(request):
   text = """
welcome to my app !
"""
   return HttpResponse(text)
"

Finally, here's the URL mapping:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
   url(r'^admin', include(admin.site.urls)),
   url(r'^hello/', 'myapp.views.hello', name = 'hello'),
)

When ran, it throws an error stating that "myapp" is not defined. And I am not able to access admin page at http://127.0.0.1:8000/admin
How can I solve this error and get my application to work?

A: Possibly myapp is not included in INSTALLED_APPS in setting.py. I suppose you are following this tutorial.

A: add this in your url mapping:
from myapp import views