text:
Q: Pandas Dataframe Enlargement I have a dataframe with the following format
Name    Entries Price
John      2       10
Mary      3       12

And I want to transform it to a dataframe where every row has entry value 1
Name    Entries Price
John      1       10
John      1       10
Mary      1       12
Mary      1       12
Mary      1       12

My solution to it was to iterate throughout every row in the original frame, get the total entries for that row, N, and then I append new rows N times to a new dataframe. However this is pretty in inefficient. Do you guys have any idea how to make it faster?

A: Use -
op = df.reindex(df.index.repeat(df['Entries'])).reset_index(drop=True)
op['Entries'] = 1

Output
    Name    Entries Price
0   John    1   10
1   John    1   10
2   Mary    1   12
3   Mary    1   12
4   Mary    1   12


text:
Q: Эффект как у LIDAR в Unity 3D Я пытаюсь придумать, как можно реализовать идею с LIDAR в Unity. Я хотел что бы игрок при нажатии на кнопку запускал сканер, который будто светом проходится по окружению, и оставляет там точки. Такое уже есть в одном из режимов Garry's mod, он так же называется LIDAR:
https://youtu.be/C_bGNtgUV-M
Но я не могу никак понять как это можно сделать. Если использовать Raycast, тогда лучей будет слишком много, и это плохо будет для производительности. А в интернете ничего об этом нету. Можете подсказать как это можно сделать?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jupyter Note pandas scatter_matrix Hi the problem is that the Jupyter note tells me pandas does not have the attribute 'scatter_matrix'.
import pandas as pd
from pandas.plotting import scatter_matrix
iris_dataframe = pd.DataFrame(X_train, columns =iris_dataset.feature_names)
grr=pd.scatter_matrix(iris_dataframe, c=y_train, figsize=(15,15), marker='o',
                  hist_kwds={'bins':20}, s=60, alpha=.8, cmap=mglearn.cm3)

A: This error shows up because scatter_matrix is an attribute of pandas.plotting and not pandas. See you have pandas and scatter_matrix imported. You can either use:
grr=pd.plotting.scatter_matrix(iris_dataframe,c=y_train,figsize(15,15),marker='o',hist_kwds={'bins':20}, s=60, alpha=.8, cmap=mglearn.cm3)

or
grr=scatter_matrix(iris_dataframe,c=y_train,figsize(15,15),marker='o',hist_kwds={'bins':20}, s=60, alpha=.8, cmap=mglearn.cm3)


text:
Q: Achieving Isolation for Specific Rows in Database C# I have an application which issues letters to users in sequential order. This is the database structure
-------------------
UserID  LastIssued
-------------------
User1   2
User2   3
User3   0
User4   3
--------------------

Admin users are able to issue letters (increment the number) to user. There are multiple admins who are able to login parallelly in the system.
This is the function which is used to issue letters
private void issueNewLetterToUser(String userid)
{
    int lastIssued;
    lastIssued = getLastIssuedForUserID(userid);
    //CHECKPPOINT1
    lastIssued++;
    updateLastIssuedForUserID(userid);
}

While the execution is at checkpoint 1 in the code, suppose another admin calls the same function for the same user, next letter will be issued by two admins. I want to prevent this. Also, if the function call is for some other user, the execution should be allowed because the database rows are independent.
How can I achieve this?
(The question is specific to C# syntax, but still applicable to all languages)

A: This is a great case scenario for the transaction pattern.
Here is a good read about it: https://blog.matthewskelton.net/2005/08/22/better-transactions-with-delegates-in-csharp/
As a possible solution you might want to have the data update inside a transaction that can be accessed only by one admin at the time.


text:
Q: Using decltype with member function pointers I have some trouble using decltype for member function pointers:
#include <iostream>
#include <type_traits>

struct A
{
    void func1() {}
    typedef decltype(&A::func1) type;
};

int wmain(int argc, wchar_t* argv[])
{
    typedef decltype(&A::func1) type;

    //Case 1
    std::wcout
        << std::boolalpha
        << std::is_member_function_pointer<type>::value
        << std::endl;

    //Case 2
    std::wcout
        << std::boolalpha
        << std::is_member_function_pointer<A::type>::value
        << std::endl;

    system("pause");
    return 0;
}

Case 1 prints true as expected, but Case 2 prints false.
Is decltype stripping away the "member" property of a type? If so, why?
Also, is there a way to prevent this behavior? I need to get the type of a member function regardless of where I use decltype.
Please help.
EDIT:
Reported to Microsoft

A: For the sake of formality (having an answer to the question), this appears to be a bug in VC2010's compiler. File a bug report so that Microsoft can fix it in the next version.


text:
Q: JavaScript condition block vs blank return for control flow I have always written my JavaScript blocks
var functionName = function() {
  if (someCondition) {
      // stuff
  } else {
      // stuff
  }
};

but today I saw
var functionName = function() {
  if (someCondition) {
     // stuff
     return;
  }
  // stuff
};

I like that the first example is more explicit in the logic. What are some reasons why you would or wouldn't want to do it the second way demonstrated?

A: Many coding standards mandate that you shouldn't "early exit" from functions.  It's a trade-off between readability, and "correctness" [*]
The early exit avoids the need for the subsequent code to be indented in an extra level.  For example, IMHO it makes sense to have some error detection checks grouped together at the top of functions with an early exit on failure, with the meat of the function written as normal.
On the other hand, when reading code for debugging purposes it's easy to miss the early exit, and end up trying to find a bug in the wrong part of your code.
[*] those same code standards often eschew usage of break and continue.  FWIW I think it's a symptom of over application of Djikstra's "GOTO considered harmful" mantra.

A: Less indentation in case you got more then one someCondition.
Imagine:
var functionName = function() {
    if (someCondition) {
        // stuff
    } else {
        // stuff
        if (someConditionB) {
            // stuff

        } else {
            // stuff

            if (someConditionC) {
                // stuff

            } else {
                // stuff

                if (someConditionD) {
                    // stuff
                } else {
                    // stuff
                }
            }
        }
    }
};

Which would be a lot more readable without all the elses:
var functionName = function() {
    if (someCondition) {
        // stuff
        return;
    }

    if (someConditionB) {
        // stuff
        return;
    }

    if (someConditionC) {
        // stuff
        return;
    }
    if (someConditionD) {
        // stuff
        return;
    }

    // stuff
};

A: You may want to use method 2 in 2 cases:
Case 1: You have more stuff after your logic that you do not want run.  The code executed does all you need and you don't need the extra stuff.
Case 2: Depending on what the function is attached to, you want to return a false to prevent an action.  Once such instance would be an onSubmit for a form, and validate the input.  If it is bad, immediately return false and prevent the form from submitting.


text:
Q: Solution for data conversion today I trying to design a timestamping for a message that i send and the code that i use in the function is below:
void MainWindow::buttonClickHandler()
{
    QString qs;
    qs=ui->lineEdit->text();
    std::string m_text=qs.toStdString();
    //std::string m_text = ui->lineEdit->text();
        // Customized message
    long long startTime = System::currentTimeMillis();
    try{
            std::auto_ptr<TextMessage> message(m_IfacomMessageBroker->getSession()->createTextMessage(m_text));
            //message->setCMSTimestamp(System::currentTimeMillis());

            //m_IfacomMessageBroker->sendMessage(message);
             m_IfacomMessageBroker->sendMessage("test");
            long long ltest = m_IfacomAmqProducer->getSenderTimestamp(message);
            QDateTime *dt = new QDateTime();
            dt->setMSecsSinceEpoch(ltest);
            QString qtstring1 = dt->toString("dd.MM.yyyy hh:mm:ss.zzz");
        } catch (CMSException& e) {
            e.printStackTrace();

    }

        long long endTime = System::currentTimeMillis();
        double totalTime = (double)(endTime - startTime) / 1000.0;
}
void MainWindow::on_pushButton_3_clicked()
{
   m_IfacomMessageBroker->close();
}

When I try to build the solution, I have this error:
Error   12  error C2664: 'IfacomAmqSender::getSenderTimestamp' : cannot convert   parameter 1 from 'std::auto_ptr<_Ty>' to 'const cms::Message *'   C:\Users\Marco\Desktop\Activemq\ReleaseVersions\GUI-CMS-SENDER\mainwindow.cpp   105 1   GUI-CMS-SENDER

but the strange thing is that I use this function without problem in another .cpp file!!!

A: Say m_IfacomAmqProducer->getSenderTimestamp(message.get()).


text:
Q: Rails, handle two sites with different url and design but with the same db I'm looking for the best way to solve a problem.
At this moment I have a site for a customer, example.domain.com
My customer ask to create another website with some changes in design, but the contents are the same of the first website. I don't want to duplicate the website, because every feature I add to the site A must be deployed also to site B, and I'm looking a smart way to handle the situation.
I need to keep two different domains and I need also custom mailers and other small tweaks in the controllers (and maybe in some models).
My idea is to put in application controller a before filter like this
before_action :detect_domain
private
def detect_domain
  case request.env['HTTP_HOST']
  when "example.domain.com"
    request.variant = :host1
  when "example1.domain.com"
    request.variant = :host2
  end
end

Then I use the variant with some conditional to choose the mailer, to customize the views and to apply some code changes.
Any other idea?

A: Using a before filter and a per-request variable like your proposal will work, with a couple caveats that I'll mention below. I'd recommend a tool like the request_store gem to actually store the per-request value of which "skin" is selected.
Now, for the caveats. First, the main problem with per-request variables is that your Rails app does not always exist in the context of a request. Background jobs and console sessions operate outside of the usual request/response flow of your app. You will need to think about what happens when your models or other non-controller/view code is executed when that variable isn't set. I would suggest simply not having your models depend on RequestStore at all -- have the controllers pass any request-specific information down into the models, if needed.
Secondly, it's not clear from your description if you want any data or logical separation between the two domains, or if you just want different look-and-feels. If the former, you might consider the apartment gem, which aims to make database multi-tenancy easier.
EDIT: I also want to mention that, as an alternative to the multi-tenant solution above, you also have the option of a multi-instance solution. Wherein, you use an environment variable to indicate which version of the site should be displayed, and spin up multiple instances of your app (either on the same server with a reverse proxy, or on separate servers with separate DNS entries or a reverse proxy). The downside is increased infrastructure costs, but the context problem I mentioned above no longer exists (everything always has access to environment variables).


text:
Q: Switching source control contexts in Visual Studio Team Explorer When I connect to a local Git repository in Visual Studio (2015), Team Explorer shows a Git-specific interface (Changes, Branches, Sync, etc.). When I then connect to a non-Git TFS project, it refuses to acknowledge this switch and continues to show this Git interface (as opposed to the desired TFS interface with My Work, Pending Changes, Source Control Explorer, etc). Whenever I click one of the Git menu options, I get a message saying

The current page is inactive because you are not connected to a Git team project

which is information of which I am fully aware, but rather than allowing to switch to "TFS mode", it suggests I connect to a Git project.
The only remedy I have found is to close and reopen VS, quite annoying. Is there a way to force this switch?

A: I was having the same issues. It appears as though you have to switch back to the Microsoft Git Plugin and then switch back though Tools -> Options -> Source Control. I think while you can double click on a TFS project, the Team Explorer window doesn't reset unless its done from the options menu.


text:
Q: Is there a way to make the scrollbar longer in tkinter? I have a tkinter listbox inside a frame which is inside a canvas. The scrollbar works very well through this code:
messagesList.config(yscrollcommand = scrollbar.set)
        scrollbar.config(command=messagesList.yview)

However, I wanted the scrollbar to be longer so that I can actually scroll. I tried things such as making the frame bigger or make it take more space with padx and pady. Is there any way to make the scrollbar longer?
The image of how it currently is:

Complete code:
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont

root = tk.Tk()
root.title("Messager")
root.geometry("1300x700")
root.resizable(height = 0, width = 0)
#makes window not resizable

class Elements:

    def __init__(self, main):

        def sendMessage():
            user = userName.get()
            message = userMessage.get()
            print(user+ " username")
            print(message + " message")

        theCan = tk.Canvas(main)
        titleFrame = tk.LabelFrame(main)
        mainFrame = tk.LabelFrame(theCan)
        greeting = tk.Label(titleFrame, text="Messager", bg = "#74a5f2", font = (None, 35))
        userName = tk.Entry(titleFrame, font = (None, 15))
        userName.insert(0, "An Unnamed Scrub")
        userMessage = tk.Entry(titleFrame, font = (None, 15))
        userMessage.insert(0,"Your Message")
        sendButton = tk.Button(titleFrame, command = sendMessage, text = "Send!", bg = "#74a5f2", font = (None, 22))
        titleMessage = tk.Label(mainFrame, text = "MESSAGER", bg = "#74a5f2", font = (None, 50))
        messagesList = tk.Listbox(mainFrame)
        scrollbar = tk.Scrollbar(mainFrame, orient=tk.VERTICAL, relief = 'flat')

        messagesList.config(yscrollcommand = scrollbar.set)
        scrollbar.config(command=messagesList.yview)

        testList = ["apple", "orange","apple", "orange","apple", "orange","apple", "orange","apple", "orange","apple", "orange","apple", "orange"]

        for item in testList:
            messagesList.insert(tk.END, item)

        placeholder = tk.Label(main, text = "    ")
        placeholder1 = tk.Label(main, text = "    ")
        placeholder2 = tk.Label(main, text = "    ")
        placeholder3 = tk.Label(main, text = "    ")
        placeholder4 = tk.Label(main, text = "    ")
        placeholder5 = tk.Label(main, text = "    ")
        placeholder6 = tk.Label(main, text = "    ")
        placeholder7 = tk.Label(main, text = "    ")
        placeholder8 = tk.Label(main, text = "    ")
        placeholder9 = tk.Label(main, text = "    ")
        placeholder10 = tk.Label(main, text = "    ")
        placeholder11 = tk.Label(main, text = "    ")
        placeholder12 = tk.Label(main, text = "    ")
        placeholder13 = tk.Label(main, text = "    ")

        placeholder.grid(row = 1, column = 1)
        placeholder1.grid(row = 2, column = 2)
        placeholder2.grid(row = 3, column = 3)
        placeholder3.grid(row = 4, column = 4)
        placeholder4.grid(row = 5, column = 5)
        placeholder5.grid(row = 6, column = 6)
        placeholder6.grid(row = 7, column = 7)
        placeholder7.grid(row = 8, column = 8)
        placeholder8.grid(row = 1, column = 9)
        placeholder9.grid(row = 1, column = 10)
        placeholder10.grid(row = 1, column = 11)
        placeholder11.grid(row = 1, column = 12)
        placeholder12.grid(row = 1, column = 13)
        placeholder13.grid(row = 1, column = 14)

        #placeholders to move the mainframe frame to the center

        titleFrame.grid(row = 1, padx = 20, pady = 20)

        greeting.grid(pady = 20)
        userName.grid()
        userMessage.grid(pady = 20)
        sendButton.grid()

        mainFrame.grid()
        titleMessage.grid(pady = 20)
        messagesList.grid()
        theCan.grid(row = 1, column = 15, pady = 20)

        scrollbar.grid(sticky = "ne", rowspan = 5)

postEverything = Elements(root)
root.mainloop()

A: As has been said already, you need to place the box and the scroll bar on the same row using grid
    messagesList = tk.Listbox(mainFrame)
    scrollbar = tk.Scrollbar(mainFrame, orient=tk.VERTICAL, relief = 'flat')

    messagesList.config(yscrollcommand = scrollbar.set)
    scrollbar.config(command=messagesList.yview)

    messagesList.grid(row=0,column=0)
    scrollbar.grid(row=0,column=1,sticky = "ns")

Also note that I've changed the sticky attribute to be "ns" which means the scroll bar will stretch to fit the row and match the height of the messagesList widget.


text:
Q: How to inherit permissions in SharePoint 2013 through Rest Api? In Sharepoint 2013, there is a rest API to break permissions and add permissions to the object, but is there an rest Api to inherit permissions on the object again?
Thanks

A: Use this endpoint url to reset the permission, this will reset the permissions which means it will inherit the parent permission.
url : <site URL>/_api/Web/Lists/GetByTitle('<list name>')/items('<item id>')/resetroleinheritance

The above URL will reset the permission at the item level, you may implement the same for list or site level.

A: Similar to breakroleinheritance you can use resetroleinheritance endpoint
https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.resetroleinheritance.aspx


text:
Q: how to extract timezone from localtime() I'm using the following code to print the current time.
use Getopt::Long;
use Time::Local;
sub gettime
{
        my $t = time();
        my ($sec,$mn,$hr,$mday,$mon,$yr,@left, $dstr);

        ($sec,$mn,$hr,$mday,$mon,$yr,@left) = localtime($t);
        $yr  = $yr-100+2000;
        $mon += 1;
        $dstr = sprintf "%02d:%02d:%02d (%02d-%02d-%04d)", $hr, $mn, $sec, $mon,
 $mday, $yr;
        print $dstr;
}

gettime();

I can set the timezone using -
local $ENV{TZ} = ":/usr/share/lib/zoneinfo/America/Los_Angeles";
How can I extract the timezone from localtime() ?

A: You could use strftime():
use POSIX;
$tz = strftime("%Z", localtime());

Or, calculate the difference between localtime() and gmtime().

A: You can have the timezone as well as the offset from UTC:
perl -MPOSIX -e 'print strftime "%Z (%z)\n",localtime'

A: $ perl -MPOSIX -le 'tzset; print for tzname'
CST
CDT

tzset() and tzname() functions from POSIX module can be a easily remembered answer.


text:
Q: Set value of C++ extern variable from Cython In my project I am wrapping some C++ code (that I have full control over) with Cython to be able to call the C++ functionality from Python.
In one of the C++ header files I want to use the "extern" keyword to define (but not initialize) a variable, which is then used in the corresponding cpp implementation file. I want to set the value for that variable from within the Cython wrapper.
In the following you can find a minimal version of my code.
Edit: As pointed out by @ead, my original code sample was not suited to reproduce the problem. Here is a minimal working example that is better suited to point out the problem.
test.h
extern int testVariable;

void function1();

void function2();

test.cpp
#include "test.h"
#include <iostream>

int testVariable;

void function1() {
    std::cout << "function1 called, testVariable = " << testVariable << "\n";
}

void function2() {
    std::cout << "function2 called, testVariable = " << testVariable << "\n";
}

wrapper1.pyx
cdef extern from "test.h":

    int testVariable

    void function1()

testVariable = 42

cpdef wrapper_function1():
    function1()

wrapper2.pyx
cdef extern from "test.h":

    void function2()

cpdef wrapper_function2():
    function2()

main.py
from wrapper1 import wrapper_function1
from wrapper2 import wrapper_function2

if __name__ == '__main__':
    wrapper_function1()
    wrapper_function2()

setup.py
from Cython.Build import cythonize
from setuptools import setup, Extension

sources = [
    '*.pyx',
    'test.cpp'
]

extensions = [
    Extension(name='*', sources=sources, language='c++')
]

setup(name='test',
      packages=['test'],
      install_requires=["Cython>=0.29.0"],
      python_requires='>=3.7',
      ext_modules=cythonize(extensions, language_level='3'))

The code is compiled via the command python3.7 setup.py build_ext --inplace.
When executing the main.py, the output is as follows:
function1 called, testVariable = 42
function2 called, testVariable = 0

When calling function1 everything works as expected, i.e. testVariable is set to 42. When calling function2, which is wrapped in a separate Cython file, testVariable seems to be uninitialized, which is surprising to me as testVariable is supposed to be a global variable.
I split the wrapper across two pyx-files, because I do not actually want to call function2 from Python, but from C++ (the code is not shown here for brevity). When calling the function from C++, the problem persists, i.e., testVariable is 0.
Thanks for your answers!
PS: My code was inspired by https://stackoverflow.com/a/52925796

A: I would solve this problem using a class, like:
header
extern int m_nfoo;

class   __declspec(dllexport)  MyCppClass
{
public:
    MyCppClass();
    ~MyCppClass(void);

    int GetFoo();
    void SetFoo(int Foo);
....

c++:
int m_nFoo=0;

int MyCppClass::GetFoo()
{
    return m_nFoo;
}

void MyCppClass::SetFoo(int Foo)
{
    m_nFoo=Foo;
}

pxd:
cdef extern from "MyCppClass.h":

    cdef cppclass MyCppClass:
        MyCppClass()
        int GetFoo()
        void SetFoo(int Foo)

pyx:
cdef class myClass:
    """
    wrapper of MyCppClass
    """

    def __cinit__(self):
        self.thisptr = new MyCppClass()

    def setFoo(self,foo):
        self.thisptr.SetFoo(foo)

    def getFoo(self):
        return self.thisptr.GetFoo()

and in some py:
    I=myClass()

    I.setFoo(42)
    print ('foo=',I.getFoo())

and that works fine


text:
Q: How do you check if your wifi is connected to 802.11ac vs n in linux? I dual-booted Linux mint on MacBook pro running macOS Catalina. I am getting 240 Mb/s down on macOS but only 30-40 down on Linux mint. I am connected to 802.11ac on macOS. How would I check if my connection in Linux is 802.11ac or not? and/fix the problem?

A: Try sudo iw wlan0 station dump, where wlan0 is your WLAN device. This will give you both the current transmission and receive rate and the channel width.
If your channel width is 80 MHz or 160 Mhz, you are using 802.11ac. If your channel width is 20 MHz or 40 MHz, you are using 802.11n.
Note that 802.11ac includes 802.11n as a fallback option, and depending on send/receive conditions, 802.11ac will scale back to 40 MHz or 20 MHz wide channels and lower bit rates. Then you are still "using 802.11ac".
If you want to see what your driver/hardware combination is capable of ("does it support 802.11ac in the first place?"), use iw phy. If you see VHT (very high througput), you have 802.11ac.
Also note that hardware support on the MacBook may be suboptimal for Apple specific hardware like the WLAN. So if iw phy doesn't show VHT, there's nothing you can do about it, unless you can get Apple to make their hardware documentation public so people can write Linux drivers for it.


text:
Q: VBA used save range as input for diagramm after a match operation in VBA - I get a range variable
 Set rngSel = ActiveSheet.Range(Cells(3, 28).Offset(0, startIdx - 1), Cells(3, 28).Offset(0, endIdx - 1))

It tells me that the data that I want to visualise in a bar chart are between A3 and Z3 (always in a single row) , fo r instance. I can also print this
 MsgBox ("rngSel=" & rngSel.Cells.Address)

However, now I would like to use rngSel to feed the input for my diagramm. I tried
ActiveChart.SetSourceData Source:=Sheets("Diagramm 1").rngSel

That does not work however. rngSel only provides the x coordinates range (A3 to Z3, for instance. The y values are in A4 to Z4. How can I - based on the rngSel object tell my Diagramm 1 to only take the data from
A3:Z4? Without manually specifying but dynamically using rngSel?
whole macro
Sub Aku()
    Dim startIdx As Integer, endIdx As Integer
    Set valRng = ActiveSheet.Range("AB3:LS3")

    startIdx = Application.Match(CLng(Cells(2, 18).Value), valRng, 0)
    endIdx = Application.Match(CLng(Cells(2, 22).Value), valRng, 0)

    Set rngSel = ActiveSheet.Range(Cells(3, 28).Offset(0, startIdx - 1), Cells(3, 28).Offset(0, endIdx - 1))

    MsgBox ("rngSel=" & rngSel.Cells.Address)
    ActiveChart.SetSourceData Source:=rngSel.Resize(2), PlotBy:=xlRows

End Sub

A: edited after further OP's clarifications
try this:
Sub Aku()
    Dim startIdx As Integer, endIdx As Integer
    Dim rngSel As Range, valRng As Range

    With ActiveSheet
        Set valRng = .Range("AB3:LS3")

        startIdx = Application.Match(CLng(Cells(2, 18).Value), valRng, 0)
        endIdx = Application.Match(CLng(Cells(2, 22).Value), valRng, 0)

        Set rngSel = .Range(Cells(3, 28).Offset(0, startIdx - 1), Cells(3, 28).Offset(0, endIdx - 1))
    End With
    Worksheets("Sheet 1").ChartObjects("Diagramm 1").Chart.SetSourceData Source:=rngSel.Resize(2), PlotBy:=xlRows
End Sub

it assumes you're running this macro when the Active sheet is the one where to read values from


text:
Q: How to loop through two separate files with one for loop and two variables in bash?         for e in $(find .  -type f -name "*.sh")
        do

        done
        cat code.log | while read k
        do
            chmod $k $e
        done

how do I combine the two loops
one loop is finding all files with .sh extension and the other loop is looping through a file which has all the file permission octaves
I want to combine the output of both the loops in a sequential order
for eg : file1.sh,file2.sh..
code.log =  777,666,665,556
I want the to chmod the file as per the permission


text:
Q: Euler's method for Python I want to approximate the solutions of dy/dx = -x +1, with eulers method on the interval from 0 to 2. I'm using this code
def f(x):
    return -x+1  # insert any function here

x0 = 1  # Initial slope #
dt = 0.1  # time step
T = 2  # ...from...to T
t = np.linspace(0, T, int(T/dt) + 1)  # divide the interval from 0 to 2 by dt
x = np.zeros(len(t))
x[0] = x0 # value at 1 is the initial slope
for i in range(1, len(t)):  # apply euler method
    x[i] = x[i-1] + f(x[i-1])*dt

plt.figure()  # plot the result
plt.plot(t,x,color='blue')
plt.xlabel('t')
plt.ylabel('y(t)')

plt.show()

Can I use this code to approximate the solutions of any function on any interval? It's hard to see whether this actually works, because I don't know how to plot the actual solution ( -1/2x^2 + x ) along side the approximation.

A: It would probably help if you consistently used the same variable names for the same role. Per your output, the solution is y(t). Thus your differential equation should be dy(t)/dt = f(t,y(t)). This would then give an implementation for the slope function and its exact solution
def f(t,y): return 1-t

def exact_y(t,t0,y0): return y0+0.5*(1-t0)**2-0.5*(1-t)**2

Then implement the Euler loop also as a separate function, keeping out problem specific details as much as possible
def Eulerint(f,t0,y0,te,dt):
    t = np.arange(t0,te+dt,dt)
    y = np.zeros(len(t))
    y[0] = y0
    for i in range(1, len(t)):  # apply euler method
        y[i] = y[i-1] + f(t[i-1],y[i-1])*dt
    return t,y

Then plot the solutions as
y0,T,dt = 1,2,0.1
t,y = Eulerint(f,0,y0,T,dt)
plt.plot(t,y,color='blue')
plt.plot(t,exact_y(t,0,y0),color='orange')

A: You can just plot the actual solution by using:
def F(x):
   return -0.5*x+x

# some code lines

plt.plot(t,x,color='blue')
plt.plot(t,F(t),color='orange')

But please note that the actual solution (-1/2x+x = 1/2x) does not correspond to your slope f(x) and will show a different solution.
The *real slope f(x) of the actual solution (-1/2x+x = 1/2x) is just simply f(x)=1/2


text:
Q: How to bulk update database if the new values are in array? php I am trying to do an UPDATE statement for multiple records for the edit function. The page has multiple rows that requires to be updated. I am not sure how to construct the statement if the parameter passed is an array.
arr_items[[arr_items2]] </br>
arr_items[[value1, value2, value3, value4], [value1, value2, value3, value4]]

I tried different bind_param also but it won't work.
edit-view.php
$dao5->modify($arr_items)

DAO.php
public function modify($arr_items) {
        $sql = 'update table set
                column3=:???(supposedly value3)
                column4=:???(supposedly value4)
                where column1=:???(supposedly value1) and column2=:???(supposedly value2);

        $values = $arr_items;

        for ($i=0; $i < count($values); $i++){
            $stmt = $conn->prepare($sql);
        }

        $connMgr = new ConnectionManager();
        $conn = $connMgr->getConnection();

       call_user_func_array(array($stmt, 'bind_param'), $values);

        $stmt->execute();
    }

Error Message:  ``` Uncaught Error: Call to a member function
  prepare() on null in C:

A: after experimenting the sql should be as per below and loop inside the statement to modify each record.
       $sql = 'update table set column3=:value3, column4=:value4 where column1=:value1 and column2=:value2 ';

        $values = $arr_items;

        for ($i=0; $i<count($values); $i++){
            $query_p = array(':value3'=> $arr_items[$i][2], ':value4' => $arr_items[$i][3], ':value1' => $arr_items[$i][0], ':value2' => $arr_items[$i][1]);

            $stmt->execute($query_p);
        }


text:
Q: The destination phone number has been blocked by Verify Geo-Permissions. NZ is blocked for key xxx currently, I am facing an issue with Verify Geo Permissions. I have checked the related docs and reached my admin, and he can confirm that all Verify Geo-Permissions for New Zealand have been checked to be available on the panel (SMS and Voice Channel). Can anyone let me know what can be the other reasons for this error message to be given?

A: There are now separate geo permissions specifically for Verify, more details here:
Verify Geo Permissions available in console now.
https://www.twilio.com/changelog/verify-geopermissions-available-in-console-now
Did you use these?


text:
Q: Multiple selection by clicking and dragging [I want to create the option to select a few days by dragging and clicking together.
I did try by dragging, but it doesn't suit me, I want them to also click the mouse
What is the way to set a click and drag action together, I made an attempt to set a click and drag event like this:
// $ ("body"). on ('click mouseover', ". button", (event) => {

  But in actuality it refers to the event when either pressing or dragging, I don't want to be able to drag alone without clicking
Thank you
Link to code in codepen
I want to create the option to select a few days by dragging and clicking together.
I did try by dragging, but it doesn't suit me, I want them to also click the mouse
What is the way to set a click and drag action together, I made an attempt to set a click and drag event like this:
$ ("body"). on ('click mouseover', ". button", (event) => {});

  But in actuality it refers to the event when either pressing or dragging, I don't want to be able to drag alone without clicking
Thank you

 "use strict";

 $(document).ready( () => {

    //
    $("body").on('click',".all_buttons" , (event) => {

      if( $( ".all_buttons" ).hasClass( "point" )){
         $( ".button" ).each(function( index ) {
              $(this).prev('input').prop( "checked", false );
          });
          $( ".all_buttons" ).removeClass('point');
       } else {
           $( ".button" ).each(function( index ) {
                $(this).prev('input').prop( "checked", true );
            });
          $( ".all_buttons" ).addClass('point');
       }

    });
//
  // $("body").on('click mouseover',".button" , (event) => {
    $("body").on('click mousedown',".button" , (event) => {

     $(event.currentTarget).prev('input').prop("checked", !$(event.currentTarget).prev('input').prop("checked") );

   });

 });
body{
  text-align: center
}
$selected-color: orange;

.button-group input{
  display: none;
}

.button-group input:checked + label,
.button-group input:checked + label:active {
  background-color: $selected-color;
}

.checked {
  background-color: $selected-color;
}

form{
  direction: rtl;
}
label{
  margin:1px !important;
}

  <form>

Checkbox Button Group with Foundation 6 for sites

You can select multiple items at once

      <input id="checkbox1" type="checkbox">
      all

      <input id="checkbox2" type="checkbox">
      Sunday

      <input id="checkbox3" type="checkbox">
      Monday

      <input id="checkbox4" type="checkbox">
      Tuesday

      <input id="checkbox5" type="checkbox">
      Wednesday

      <input id="checkbox6" type="checkbox">
      Thursday

      <input id="checkbox7" type="checkbox">
      Friday

  </form>


text:
Q: Dynamic outputfilename in Data Flows in Azure Data Factory results in folders instead of files I am setting up a Data Flow in ADF that takes an Azure Table Dataset as Source, adds a Derived Column that adds a column with the name "filename" and a dynamic value, based on a data field from the source schema.
Then the output is sent to a sink that is linked to a DataSet that is attached to Blob Storage (tried ADLS Gen2 and standard Blob storage).
However, after executing the pipeline, instead of finding multiple files in my container, I see there are folders created with the name filename=ABC123.csv that on its own contains other files (it makes me think of parquet files):
- filename=ABC123.csv
  + _started_UNIQUEID
  + part-00000-tid-UNIQUEID-guids.c000.csv

So, I'm clearly missing something, as I would need to have single files listed in the dataset container with the name I have specified in the pipeline.
This is how the pipeline looks like:

The Optimize tab of the Sink shape looks like this:

Here you can see the settings of the Sink shape:

And this is the code of the pipeline (however some parts are edited out):
source(output(
        PartitionKey as string,
        RowKey as string,
        Timestamp as string,
        DeviceId as string,
        SensorValue as double
    ),
    allowSchemaDrift: true,
    validateSchema: false,
    inferDriftedColumnTypes: true) ~> devicetable
devicetable derive(filename = Isin + '.csv') ~> setoutputfilename
setoutputfilename sink(allowSchemaDrift: true,
    validateSchema: false,
    rowUrlColumn:'filename',
    mapColumn(
        RowKey,
        Timestamp,
        DeviceId,
        SensorValue
    ),
    skipDuplicateMapInputs: true,
    skipDuplicateMapOutputs: true) ~> distributetofiles

Any suggestions or tips?  (I'm rather new to ADF, so bear with me)

A: I recently struggled through something similar to your scenario (but not exactly the same). There are a lot of options and moving parts here, so this post is not meant to be exhaustive. Hopefully something in it will steer you towards the solution you are after.
Step 1: Source Partitioning
In Data Flow, you can group like rows together via Set Partitioning. One of the many options is by Key (a column in the source):

In this example, we have 51 US States (50 states + DC), and so will end up with 51 partitions.
Step 2: Sink Settings
As you found out, the "As data in column" option results in a structured folder name like {columnName}={columnValue}. I've been told this is because it is a standard in Hadoop/Spark type environments. Inside that folder will be a set of files, typically with non-human-friendly GUID based names.
"Default" will give much the same result you currently have, without the column based folder name. Output to Single File" is pretty self-explanatory, and the farthest thing from the solution you are after. If you want control over the final file names, the best option I have found is the "Pattern" option. This will generate file(s) with the specified name and a variable number [n]. I honestly don't know what Per partition would generate, but it may get close to you the results you are after, 1 file per column value.

Some caveats:

*

*The folder name is defined in the Sink Dataset, NOT in the Data Flow. Dataset parameters is really probably "Step 0". For Blob type output, you could probably hard code the folder name like "myfolder/fileName-[n]". YMMV.

*Unfortunately, none of these options will permit you to use a derived column to generate the file name. [If you open the expression
editor, you'll find that "Incoming schema" is not populated.]

Step 3: Sink Optimize
The last piece you may experiment with is Sink Partitioning under the Optimize tab:

"Use current partitioning" will group the results based on the partition set in the Source configuration. "Single partition" will group all the results into a single output group (almost certainly NOT what you want). "Set partitioning" will allow you to re-group the Sink data based on a Key column. Unlike the Sink settings, this WILL permit you to access the derived column name, but my guess is that you will end up with the same folder naming problem you have now.
At the moment, this is all I know. I believe that there is a combination of these options that will produce what you want, or something close to it. You may need to approach this in multiple steps, such as have this flow output to incorrectly named folders to a staging location, then have another pipeline/flow that processes each folder and collapses the results the desired name.

A: You're seeing the ghost files left behind by the Spark process in your dataset folder path. When you use 'As data in column', ADF will write the file using your field value starting at the container root.
You'll see this noted on the 'Column with file name' property:

So, if you navigate to your storage container root, you should see the ABC123.csv file.
Now, if you want to put that file in a folder, just prepend that folder name in your Derived Column transformation formula something like this:
"output/folder1/{Isin}.csv"
The double-quotes activate ADF's string interpolation. You can combine literal text with formulas that way.


text:
Q: How to split data into clusters based on fitting to function I have data which looks somewhat like this:

On the picture, you can see that the data can be described by 2 linear functions - if you manage to split it into 2 groups, each can easily be fitted with a x + b
However, when I run FindClusters on that data, I get this:

It seems, I need to adjust it somehow
Can anyone show me how to properly use FindClusters to split this data?
UPDATE
The functions are all known and the same.
To play with, the data can be emulated with:
dd = Join[Table[ {x, .3 x + 2 + RandomReal[{-1, 1}]}, {x, 0, 100}],
 Table[ {x, .6 x - 20 + RandomReal[{-1, 1}]}, {x, 0,
100}]]; ListPlot[dd]; cc = FindClusters[dd]; ListPlot[cc]

A: Another approach to this problem is to use the image processing capabilities. This code creates a binary image from the data, then uses ImageLines, which implements the Radon transform to locate the most prominent lines. These are then highlighted in orange.
dd = Join[Table[{x, .3 x + 2 + RandomReal[{-1, 1}]}, {x, 0, 100}],
  Table[{x, .6 x - 20 + RandomReal[{-1, 1}]}, {x, 0, 100}]];
img = ListPlot[dd, Axes -> False] // Image;
binImg = Binarize[ColorNegate@img];
lines = ImageLines[binImg, 0.2];
HighlightImage[binImg, {Orange, Line /@ lines}]

In the event of more lines, you can change the second argument to ImageLines.

A: This does the same as the other answer (fit two lines to the data, cluster data points based on whether they are closer to one line or the other), but with a bit different coding style:
dd = Join[Table[ {x, .3 x + 2 + RandomReal[{-1, 1}]}, {x, 0, 100}],
  Table[ {x, .6 x - 20 + RandomReal[{-1, 1}]}, {x, 0, 100}]];

cost1[a1_, b1_, a2_, b2_, {x_, y_}] :=
  Min[(a1 + b1 x - y)^2, (a2 + b2 x - y)^2]
cost[a1_, b1_, a2_, b2_] :=
  Total[Map[cost1[a1, b1, a2, b2, #]&, dd]]

sol = Minimize[cost[a1, b1, a2, b2], {a1, b1, a2, b2}][[2]]

set1q[{x_, y_}] := (a1 + b1 x - y)^2 < (a2 + b2 x - y)^2 /. sol
set1 = Select[dd, set1q];
set2 = Complement[dd, set1];

ListPlot[{set1, set2}]

A: If we can assume we know more or less the functions for the two groups, in this case two linear functions (two parameters each) we can just NMinimize for the Min distance of the two functions.
{w, sol} = NMinimize[
  Total[
   Map[
    Min[Abs[#[[2]] - (n1 + m1 #[[1]])],
      Abs[#[[2]] - (n2 + m2 #[[1]])]] &
    , dd
    ]
   ], {n1, n2, m1, m2}]

{95.3241, {n1 -> 1.84575, n2 -> -19.8623, m1 -> 0.300732,  m2 -> 0.598053}}

Once we have extracted the parameters for the two functions, then we just GatherBy each point, based on  which function is closer.
ListPlot@Module[{n1, n2, m1, m2},
  {n1, n2, m1, m2} = Values[sol];
  GatherBy[dd,
   LessEqual[Abs[#[[2]] - (n1 + m1 #[[1]])],
     Abs[#[[2]] - (n2 + m2 #[[1]])]] &]
  ]

More general
Define your function with arbitrary number of parameters
func[parms_List][x_] := parms[[1]] + parms[[2]]  x

A distance function
dist[f_][{x_, y_}] := Abs[y - f[x]]

Or (after comment by @SampoSmolander)
dist[f_][{x_, y_}] := (y - f[x])^2

Fake data
dd = Table[
   With[
    {
     a = RandomChoice[{1, 4}],
     b = RandomChoice[{1/2, 2}]
     }, {x, func[{a, b}][x] + RandomReal[{-1, 1}]}], {x, 0, 10,
    0.01}];

Minimisation, The i index goes through the number of parameters of each function (here 2), the index j over the number of functions to fit (in this case 4).
sol2 = Last@With[{n = 2, m = 4},
   NMinimize[
    Total@Map[Function[{L}, Min @@ Table[
         dist[func[Array[c[#, k] &, n]]][L]
         , {k, m}]], dd]
    , Flatten[Table[c[i, j], {i, n}, {j, m}]]]
   ]

Plot
Show[
 ListPlot@GatherBy[
   dd
   , Position[#, Min[#]] &[
     Table[dist[func[{c[1, k], c[2, k]} /. sol2]][#], {k, 4}]] &
   ],
 Plot[
  Evaluate[
   Table[
     func[{c[1, k], c[2, k]}][x]
     , {k, 4}] /. sol2
   ]
  , {x, 0, 10}
  ]]

Obviously there is no way to be sure this will converge to reasonable clusters if the lines are too mixed or the functions too complicated.
Fitting different number of functions
Let's see how does this perform when there are four groups of points and we ask for m different number of clusters, from 1 to 6.
plots = Table[
  sol2 = Last@With[{n = 2},
     NMinimize[
      Total@Map[Function[{L}, Min @@ Table[
           dist[func[Array[c[#, k] &, n]]][L]
           , {k, m}]], dd]
      , Flatten[Table[c[i, j], {i, n}, {j, m}]]]
     ];
  ListPlot[
   GatherBy[
    dd
    , Position[#, Min[#]] &[
      Table[dist[func[{c[1, k], c[2, k]} /. sol2]][#], {k, m}]] &
    ], PlotLabel -> m], {m, 6}];

Grid@Partition[plots, 2]

A: If there are no crossing points, Method->"Agglomerate"option and specifying the number of clusters at 2nd argument works great.
dd = Join[Table[{x, .3 x + 2 + RandomReal[{-1, 1}]}, {x, 0, 100}],
   Table[{x, .6 x - 20 + RandomReal[{-1, 1}]}, {x, 0, 100}]];
ListPlot[dd]
cc = FindClusters[Select[dd, #[[1]] < 60 &], 2,
   Method -> "Agglomerate"];
cc2 = FindClusters[Select[dd, #[[1]] > 85 &], 2,
   Method -> "Agglomerate"];
ListPlot[Join[cc, cc2, 2]]


text:
Q: "I couldn't find XXX" and "I didn't find XXX" which is better? We communicate via email. He told me to get something under an address. But I can't find it under that location.
How would I say?

I didn't find it.

-

I couldn't find it.

A: "I couldn't find it" is more appropriate for your case, I think.
"I didn't find it" implies that you chose not to find it. "I couldn't find it" tells the listener that you tried, but failed.


text:
Q: Which groups allow selecting the properties allowExternalSenders or autoSubscribeNewMembers? When I select the properties allowExternalSenders or autoSubscribeNewMembers for a group synced from an on-premise Active Directory, I get the following error via Graph API SDK:
403 Forbidden
Graph service exception Error code: AppOnlyAccessNotEnabledForTarget
Error message: App Only access is not allowed for target resource: 'a1d0c98e-fb7e-40c4-a7b5-ccf6d96cba57@34f0717f-f1a0-4894-b310-d379993504b9'.

The Graph Explorer displays the following 404 error, even though it is not a mailbox:
{
  "error": {
    "code": "MailboxNotEnabledForRESTAPI",
    "message": "REST API is not yet supported for this mailbox.",
    "innerError": {
      "request-id": "5beae8eb-4a59-404f-bd42-0c6aa2a25abd",
      "date": "2020-03-31T13:02:11"
    }
  }
}

An example request looks like this:
https://graph.microsoft.com/v1.0/groups/{id}?$select=id,deletedDateTime,assignedLicenses,description,displayName,groupTypes,licenseProcessingState,mail,mailEnabled,mailNickname,onPremisesLastSyncDateTime,onPremisesSecurityIdentifier,onPremisesSyncEnabled,onPremisesDomainName,onPremisesSamAccountName,preferredDataLocation,securityEnabled,securityIdentifier,visibility,resourceProvisioningOptions,allowExternalSenders,autoSubscribeNewMembers

Which property should I use to decide if I should try to select these properties or not? I want to avoid missing the properties for groups which actually do expose these properties, so I do not simply want to guess.

A: Slightly different take on this answer, Microsoft even thought only providing one API for groups, there are effectively two different objects returned, SecurityEnabled = True or False. If Security = True then you can not ask for the follow attributes

(allowExternalSenders,autoSubscribeNewMembers,hideFromAddressLists,hideFromOutlookClients)

Is this ok, NO its not ok, Microsoft needs to return null instead of providing THE WRONG ERROR MESSAGE and sending people like us into multi hour head scratchers.
In my code, I now check if securityEnabled is true or false and have a different set of attributes depending.

A: The mailbox is on a dedicated (on premise) Microsoft Exchange Server or is not a valid (configured) Office 365 mailbox. Contact your Exchange or Office admin to apply any of these recommended solutions.
To filter Office 365 groups you can do this:
https://graph.microsoft.com/v1.0/groups?$filter=groupTypes/any(c:c eq 'Unified')


text:
Q: How to get the last item from a Laravel database query array Say I am querying the user table like this in Laravel:
routes.php
Route::get('/users', function()
{
    $users = DB::table('users')->get();
}

users.blade.php

@foreach ($users as $user)

{{ $user->id }}

@endforeach

But I wanted the following with the last users id from the original query in the row below then how could I get that information?
users.blade.php

@foreach ($users as $user)

{{ $user->id }}

@endforeach

lastUserId }}">

A: You may use last to get the last item:
$last = $users->last();


text:
Q: Freeradius showing incorrect number of online users vs NAS Scenario:
Freeradius server 2.2.8 as billing system on Ubuntu Server,
NAS is Mikrotik Router ccr1036 v 6.42.4
Problem:
on NAS i can see 900 active/online users, where as on freeradius I see 500 sessions (where acctstop time is NULL)
I use following query to calculate online number of users in FR.
mysql -uroot -s -e "use radius; select * from radacct  WHERE acctstoptime IS NULL;" |wc -l

I tried to disconnect all users on NAS, clear all sessions from freeradius, users reconnect fine, but still number of users on NAS vs freeradius doesnt matches. What should I check?

A: This is a fundamental issue with the fact that RADIUS is a lossy protocol.  If a user goes offline, and for some reason, the RADIUS server doesn't receive the Acct-Status-Type=Stop packet, then the session will be permanently marked as open.
If you use the SQL queries from FreeRADIUS v3, you'll see they have an AcctUpdateTime field.  This AcctUpdateTime field is set to NOW() every time a session is changed.
https://github.com/FreeRADIUS/freeradius-server/blob/v3.0.x/raddb/mods-config/sql/main/mysql/queries.conf#L332
The purpose of this field is to make it easy for external scripts to go in and correct sessions which are obviously stale, by looking at when the session was last updated.
If you want to fix this, I'd either updated to FreeRADIUS v3.0.x (2.2.8 hasn't been supported for a while now), or use the v3.0.x schema and queries (they should mostly work).
Then just run a query every 10 minutes to updates rows with a NULL AcctStopTime, where the difference between NOW() and AcctUpdateTime is > <NAS Interim Interval> * 2, setting AcctStopTime to NOW().
For this to work, Interim-Updates will need to be enabled on your NAS.  These are Accounting-Requests sent periodically from the NAS to update things like traffic counters, but in this case, they can also be used as useful heartbeat messages.
If you can't figure out where the static config option for this is on your NAS, it can sometimes be enabled by returning the Acct-Interim-Interval attribute in  your Access-Accept, which'll specify the interim interval in seconds.


text:
Q: Setting up ECSlidingViewController Basic Menu Example I am new to IOS development. I am trying run ECSlidingViewController (2.0.3) Basic Menu Example. However, the build fails and I get the following error:
ld: library not found for -lECSlidingViewController
linker command failed with exit code 1 (use -v to see invocation)

I have tried pod install and it installed some dependencies, including ECSlidingViewController, but it still returns the error above.

A: You need to do this: Click on your project (targets) Click on Build Settings Under Library Search Paths, delete the paths. Remove framework from your project and serach path. And after that add it again
May be this will help you


text:
Q: UIView subviews don't responde to delegates I have following code in viewDidLoad
myViewController = [[UIViewController alloc] initWithNibName:@"myView" bundle:nil] ;
self.myView = myViewController.view;
[self.view addSubview:myView];

This code loads view from myView.nib (I have corresponding view controller m and h files of course). myView view has UITextField and other controls. So far so good - I can see all my controls on the screen.
The problem however is that even though I set a delegate for UITextField to be File's Owner (which is myView) and I implement UITextFieldDelegate in myView.m, delegate methods are never fired!
This does NOT happen if I add UITextField to the original view (created by the XCode as default template). Why is this happening?
The reason I need to useSubview because in actual code will layer view to the UIScrollView so I can pan and zoom.
THanks!

A: My first question to your question is, "is there a reason to use UIViewController to load your NIB file?".
It appears that you're "throwing away" the UIViewController and merely using it for its ability to load a NIB file.  I'd stop that first, as that may help you debug this issue.  Use:
self.myView = (UIView*)[NSBundle loadNibNamed:@"myView"];

The second part I'd question is that you say "File's Owner" -- because you're using a separate UIViewController, you may have it set to call back to your UIViewController, not the code that you mean to callback to.  Maybe you could tell us a little about the setup of the XIB file?


text:
Q: Error while calling sqlite database query I get the following exception when running from code. Which argument is the message talking about?
Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.
at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1284)
at su.joel.punchintime.ShowRawDB.displayDatabaseInfo(ShowRawDB.java:53)
at su.joel.punchintime.ShowRawDB.onCreate(ShowRawDB.java:19)

at this line: Cursor cursor = db.rawQuery(queryString, whereArgs);
The activity:
package su.joel.punchintime;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class ShowRawDB extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_raw_db);
        displayDatabaseInfo();
    }
    private void displayDatabaseInfo() {
        DatabaseHelper DBHelper = new DatabaseHelper(this);
        SQLiteDatabase db = DBHelper.getReadableDatabase();
        String[] projection = {
                DBHelper.COL_ID,
                DBHelper.COL_DATE,
                DBHelper.COL_PUNCHIN
        };
        String selection = "null";
        String[] selectionArgs = { "null" };
        String sortOrder =
                DBHelper.COL_DATE + " DESC";
        String queryString =
                "SELECT * FROM punchlog";
        String[] whereArgs = new String[] {""};
        Cursor cursor = db.rawQuery(queryString, whereArgs);
        List itemIds = new ArrayList<>();
        while(cursor.moveToNext()) {
            long itemId = cursor.getLong(
                    cursor.getColumnIndexOrThrow(DBHelper.COL_ID));
            itemIds.add(itemId);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, itemIds);
        ListView lst = (ListView) findViewById(R.id.listDB);
        lst.setAdapter(adapter);
        cursor.close();
    }
}

And the database helper:
package su.joel.punchintime;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public final class DatabaseHelper extends SQLiteOpenHelper {
        public static final String TABLE_NAME = "punchlog";
        public static final String COL_ID = "_id";
        public static final String COL_DATE = "date";
        public static final String COL_PUNCHIN = "punchin";
        public static final String COL_PUNCHOUT = "punchout";
        public static final String COL_ONDUTY = "onduty";
        public static final String COL_FORGOTIN = "forgotin";
        public static final String COL_FORGOTOUT = "forgotout";
        public static final String COL_LATEIN = "latein";
        public static final String COL_LATEOUT = "lateout";
    String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COL_ID + " INTEGER PRIMARY KEY," +
                    COL_DATE + " TEXT," +
                    COL_PUNCHIN + " TEXT," +
                    COL_PUNCHOUT + " TEXT," +
                    COL_ONDUTY + " INTEGER," +
                    COL_FORGOTIN + " INTEGER," +
                    COL_FORGOTOUT + " INTEGER," +
                    COL_LATEIN + " INTEGER," +
                    COL_LATEOUT + " INTEGER);";
    String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + TABLE_NAME;
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "PunchInTime.db";
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        System.out.println(SQL_CREATE_ENTRIES);
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}

A: Seems to me that you are passing a single whereArg when the SQL string expects none...
try
String[] whereArgs = new String[] {};
instead.

A: Cursor cursor = db.rawQuery(queryString, whereArgs);

Instead of the above code, replace with
Cursor cursor = db.rawQuery(queryString, null);

This is because your whereArgs is empty.


text:
Q: Swift, Core Data, Optional Integer16 and keyPath I have an entity in CoreData which has an optional property of type Integer 16.  It can genuinely be nil and in my application I want to refer to it as an Int? type.  As Int? (or for that matter Int16?) isn't a recognised Objective-C type, the compiler throws a bit of a wobbly. I want to avoid using code like NSNumber?.intValue throughout so I've actually set up my ManagedObject type with custom accessors for this property.  My question relates to identifying the property through #keyPath rather than a static string.  In Core Data the field is named 'pin' on entity 'User'.  Here's the code I have:
class User: NSManagedObject {
// MARK: - Properties
static let pinKey = "pin"

@NSManaged internal(set) var name: String
@NSManaged fileprivate var primitivePin: NSNumber?

internal(set) var pin: Int? {
    get {
        willAccessValue(forKey: #keyPath(pin))  // THIS LINE ERRORS
        let value: Int? = primitivePin.map { $0.intValue }
        didAccessValue(forKey: User.pinKey)
        return value
    }
    set {
        willChangeValue(forKey: User.pinKey)
        primitivePin = newValue.map { NSNumber(value: Int16($0)) }
        didChangeValue(forKey: User.pinKey)
    }
}

}
The line in error is what I 'want' to achieve but of course the var pin isn't an obj-c type and the compiler complains, so I have defined the static constant pinKey as you can see.  #keyPath feels like the right way to go about it, and the entity does have a field called pin, but in this scenario is the only option open to me to use a static value?

A: In #keyPath you have to specify property name. If you don't have defined property called pin, you will receive an error. In your case you have to use #keyPath(User.primitivePin). I believe this should work.
Also, i guess, calling map is redundant here. You can write directly let value = primitivePin?.intValue and so on.

A: The answer is....with custom properties/accessors #keyPath can't used as there is no defined @NSManaged property for it - as Maksym points out.  However, you can't use the defined primitive for it either, instead using the property name as a String as also shown in the code above (User.pinKey)


text:
Q: Should I even check for a default value when calling IEnumerable.FirstOrDefault where T: struct I have a sequence of structs like so:
struct Foo { }

...

// somewhere else
var foos = GetListOfFoos();

...

// somewhere else
var foo = foos.FirstOrDefault();

Now, should I just go ahead and use the foo I just retrieved without worrying about nullability, of course because structs are not nullable since they're value types.
It just feels a bit worrying.
I know this is a stupid question and the answer is, "Yes, just use it without any checks for null." But I don't know why I am asking this even or what the question here is.
I am not missing anything by not checking for nullability here, right? There cannot be an invalid state for structs put inside that IEnumerable<T>, right?
Of course, I understand that if Foo had uninitialized members because it declared a parameterized ctor that did not initialize each and every member, one or more members of the instance of Foo will be in an unsable state. But as such each instance of Foo in that list will amount to something and there's no need to check for nulls or anything as there is no such thing as default(Foo), right? Of course, just confirming.

A: Even if value types are not null you should worry about this value being the default value if that was exceptional or not expected.

there is no such thing as default(Foo)

Sure, It will return an instance of this type where all members are nitialized to their default alues.
If you take f.e. struct Guid then default(Guid) returns an instance which is equal to Guid.Empty or new Guid().
So my advice is, don't compare with default(yourStruct) because that could lead to nasty bugs if the default struct could be a valid instance. Instead you could use Any:
bool containsAny = foos.Any();
if(containsAny)
{
    Foo firstFoo = foos.First();
}

MSDN: default

*

*returns null for reference types(class types and interface types)

*zero for numeric value types

*for user-defined structs, it returns the struct initialized to the zero bit pattern, which produces 0 or null for each member depending on whether that member is a value or reference type. For nullable value types, default returns a System.Nullable<T>, which is initialized like any struct.

A: If T is a struct, you can't check for null: it will never be null, and a real "zero" (equivalent) in the list/sequence will be indistinguishable from "no there weren't any values in the list/sequence".
No, you don't need to check for null here.


text:
Q: Проблема с removeClass Требуется сделать так чтобы непрочитанные сообщения становились прочитанными. Есть скрипт, но он почему-то не срабатывает, консоль ошибок не выдает. Требуется чтобы у скрипта если он увидел сообщение через определенный интервал удалялся класс text-sender-unread и оставался только text-sender-read. Вот пример кода:

$(document).ready(function() {
  var timeout;
  $('.message-block').scroll(function() {
    var me = this;
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(function() { //чтобы не искать одно и то же несколько раз
      $(me).find('.text-sender-unread').each(function() {
        var scrollTop = $(me).scrollTop(),
          posTop = $(this).position().top,
          message = this;
        setTimeout(function() {
          if (posTop >= scrollTop && posTop <= scrollTop + $(me).height()) {
            $(message).removeClass('.text-sender-unread');
          }
        }, 1500);
      });
    }, 100);

  }).scrollTop(50);
});
.message-block {
  position: sticky;
  background-color: #eef2f4;
  height: 400px;
  overflow-y: scroll;
  padding-top: 10px;
  border-radius: 10px;
}

.text-sender-read {
  background-color: #8bda84;
  width: 60%;
  padding: 5%;
  border-radius: 30px;
}

.text-sender-unread {
  box-shadow: 0px 0px 14px 2px #3675d8;
}

.sender {
  position: relative;
}

.sender:before {
  content: '';
  position: absolute;
  top: 23px;
  right: 96%;
  border-right: 30px solid rgb(139, 218, 132);
  border-top: 1px solid transparent;
  border-bottom: 41px solid transparent;
}

.incoming {
  position: relative;
}

.incoming:after {
  content: '';
  position: absolute;
  top: 23px;
  left: 96%;
  border-left: 30px solid rgb(219, 218, 222);
  border-top: 1px solid transparent;
  border-bottom: 41px solid transparent;
}

.text-incoming {
  background-color: rgba(173, 164, 172, 0.31);
  width: 60%;
  padding: 5%;
  border-radius: 30px;
  float: right;
}

.page_square_photo {
  position: relative;
  display: inline-block;
  height: 82%;
  border-radius: 50%;
  border: 3px solid #b6cada;
  width: 70px;
  /* margin-left: 6px; */
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;
}

.page_photos_module {
  padding: 5px 0px 20px;
  height: 110px;
}

.inline-message {
  display: table-row-group;
}

4trew1 yht4rewq 4trew1 yht4rewq 4trew1 yht4rewq 4trew1 yht4rewq

 4trew1 yht4rewq 4trew1 yht4rewq 4trew1 yht4rewq 4trew1 yht4rewq

ythrgf4ew

A: Моя проблема была в синтаксисе, то есть
$(message).removeClass('text-sender-unread');

.removeClass() уже обозначает класс, незачем ставить точку перед text-sender-unread, точка обозначает класс, # решетка — ид.


text:
Q: Why won't `tail -f` follow my syslog when running live? I want to monitor /var/log/syslog for any changes in realtime (or within-a-few-seconds-of-time), but tail -f won't update with any new changes.
I'm running Ubuntu-based Linux Mint 17 XFCE live now, but this hasn't worked on live iso's of Ubuntu, Xubuntu, or Linux Mint Mate either.
I've tried these:
$ tail -f /var/log/syslog
$ tail -f --retry -s 1 /var/log/syslog
$ tail --follow=name  /var/log/syslog
$ tail --follow=name --retry  /var/log/syslog
$ tail --follow=name --retry -s 1 /var/log/syslog
But it only initially outputs the last few lines of the file, then no updates when the file grows (when, for example, trying to mount an empty file gives about 15 lines of errors).
Actually, even trying to follow a test file in my home folder doesn't seem to work, running tail -f testfile and then (in another terminal):
$ echo "new stuff" >> testfile
$ echo "new stuff2" >> testfile
$ echo "3" >> testfile
doesn't result in any updates to tail either...
But if I put testfile in /tmp(mounted on a tmpfs) then it does follow the file's changes.
Why won't tail follow?
Is there something weird about running live, or overlayfs that cripples tail -f? And any suggestions how to follow the log? (xwatch works ok, anything better or in terminal?)

I've tried running strace tail -f  -s 1 testfile and here are the last couple lines of output, after it write(1,'s the existing couple lines of testfile:
write(1, "new1\n", 5new1
)                   = 5
fstat64(3, {st_mode=S_IFREG|0644, st_size=22, ...}) = 0
fstatfs64(3, 84, {f_type=0x1021994, f_bsize=4096, f_blocks=968776, f_bfree=461437, f_bavail=461437, f_files=203469, f_ffree=190635, f_fsid={0, 0}, f_namelen=255, f_frsize=4096, f_flags=1056}) = 0
inotify_init()                          = 4
inotify_add_watch(4, "testfile", IN_MODIFY|IN_ATTRIB|IN_DELETE_SELF|IN_MOVE_SELF) = 1
fstat64(3, {st_mode=S_IFREG|0644, st_size=22, ...}) = 0
read(4,

A: tail uses inotify which does not work with overlayfs See this bug report and this discussion. @Xen2050 pointed out the ---disable-inotify switch to tail See this workaround
You could use apt-src to install the coreutils source, and recompile tail with -UHAVE_INOTIFY


text:
Q: Enable the query cache in postgreSQL to improve performance My application is very database intensive so I'm trying to reduce the load on the database. I am using PostgreSQL as rdbms and python is the programming language.
To reduce the load I am already using a caching mechanism in the application. The caching type I used is a server cache, browser cache.
Currently I'm tuning the PostgreSQL query cache to get it in line with the characteristics of queries being run on the server.
Questions:

*

*Is it possible to fine tune query cache on a per database level?

*Is it possible to fine tune query cache on a per table basis?

*please provide tutorial to learn query cache in PostgreSQL.

A: Tuning PostgreSQL is far more than just tuning caches. In fact, the primary high level things are "shared buffers" (think of this as the main data and index cache), and the work_mem.
The shared buffers help with reading and writing. You want to give it a decent size, but it's for the entire cluster.. and you can't really tune it on a per table or especially query basis. Importantly, it's not really storing query results.. it's storing tables, indexes and other data. In an ACID compliant database, it's not very efficient or useful to cache query results.
The "work_mem" is used to sort query results in memory and not have to resort to writing to disk.. depending on your query, this area could be as important as the buffer cache, and easier to tune. Before running a query that needs to do a larger sort, you can issue the set command like "SET work_mem = '256MB';"
As others have suggested you can figure out WHY a query is running slowly using "explain". I'd personally suggest learning the "access path" postgresql is taking to get to your data. That's far more involved and honestly a better use of resources than simply thinking of "caching results".
You can honestly improve things a lot with data design as well and using features such as partitioning, functional indexes, and other techniques.
One other thing is that you can get better performance by writing better queries.. things like "with" clauses can prevent postgres' optimizer from optimizing queries fully.
The optimizer itself also has parameters that can be adjusted-- so that the DB will spend more (or less) time optimizing a query prior to executing it.. which can make a difference.
You can also use certain techniques to write queries to help the optimizer. One such technique is to use bind variables (colon variables)--- this will result in the optimizer getting the same query over and over with different data passed in. This way, the structure doesn't have to be evaluated over and over.. query plans can be cached in this way.
Without seeing some of your queries, your table and index designs, and an explain plan, it's hard to make specific recommendation.
In general, you need to find queries that aren't as performant as you feel they should be and figure out where the contention is. Likely it's disk access, however,the cause is ultimately the most important part.. is it having to go to disk to hold the sort? Is it internally choosing a bad path to get to the data, such that it's reading data that could easily be eliminated earlier in the query process...  I've been an oracle certified DBA for over 20 years, and PostgreSQL is definitely different, however, many of the same techniques are used when it comes to diagnosing a query's performance issues. Although you can't really provide hints, you can still rewrite queries or tune certain parameters to get better performace.. in general, I've found postgresql to be easier to tune in the long run. If you can provide some specifics, perhaps a query and explain info, I'd be happy to give you specific recommendations. Sadly, though, "cache tuning" is likely to provide you the speed you're wanting all on its own.

A: I developed a system for caching results, to speed-up results queried from a web-based solution. I reproduced below in essence what it did:
The following are the generic caching handling tables and functions.
CREATE TABLE cached_results_headers (
  cache_id serial NOT NULL PRIMARY KEY,
  date timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_access timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
  relid regclass NOT NULL,
  query text NOT NULL,
  rows int NOT NULL DEFAULT 0
  );
CREATE INDEX ON cached_results_headers (relid, md5(query));

CREATE TABLE cached_results (
  cache_id int NOT NULL,
  row_no int NOT NULL
  );

CREATE OR REPLACE FUNCTION f_get_cached_results_header (p_cache_table text, p_source_relation regclass, p_query text, p_max_lifetime interval, p_clear_old_data interval) RETURNS cached_results_headers AS $BODY$
DECLARE
  _cache_id int;
  _rows int;
BEGIN
  IF p_clear_old_data IS NOT NULL THEN
    DELETE FROM cached_results_headers WHERE date < CURRENT_TIMESTAMP - p_clear_old_data;
  END IF;

  _cache_id := cache_id FROM cached_results_headers WHERE relid = p_source_relation AND md5(query) = md5(p_query) AND query = p_query AND date > CURRENT_TIMESTAMP - p_max_lifetime;
  IF _cache_id IS NULL THEN
    INSERT INTO cached_results_headers (relid, query) VALUES (p_source_relation, p_query) RETURNING cache_id INTO _cache_id;
    EXECUTE $$ INSERT INTO $$||p_cache_table||$$ SELECT $1, row_number() OVER (), r.r FROM ($$||p_query||$$) r $$ USING _cache_id;
    GET DIAGNOSTICS _rows = ROW_COUNT;
    UPDATE cached_results_headers SET rows = _rows WHERE cache_id = _cache_id;
  ELSE
    UPDATE cached_results_headers SET last_access = CURRENT_TIMESTAMP;
  END IF;
  RETURN (SELECT h FROM cached_results_headers h WHERE cache_id = _cache_id);
END;
$BODY$ LANGUAGE PLPGSQL SECURITY DEFINER;

The following is an example of how to use the tables and functions above, for a given view named my_view with a field key to be selected within a range of integer values. You would replace all the following with your particular needs, and replace my_view with either a table, a view, or a function. Also replace the filtering parameters as required.
CREATE VIEW my_view AS SELECT ...; -- create a query with your data, with one of the integer columns in the result as "key" to filter by

CREATE TABLE cached_results_my_view (
  row my_view NOT NULL,
  PRIMARY KEY (cache_id, row_no),
  FOREIGN KEY (cache_id) REFERENCES cached_results_headers ON DELETE CASCADE
  ) INHERITS (cached_results);

CREATE OR REPLACE FUNCTION f_get_my_view_cached_rows (p_filter1 int, p_filter2 int, p_row_from int, p_row_to int) RETURNS SETOF my_view AS $BODY$
DECLARE
  _cache_id int;
BEGIN
  _cache_id := cache_id
    FROM f_get_cached_results_header('cached_results_my_view', 'my_view'::regclass,
                                     'SELECT r FROM my_view r WHERE key BETWEEN '||p_filter1::text||' AND '||p_filter2::text||' ORDER BY key',
                                     '15 minutes'::interval, '1 day'::interval); -- cache for 15 minutes max since creation time; delete all cached data older than 1 day old

  RETURN QUERY
    SELECT (row).*
    FROM cached_results_my_view
    WHERE cache_id = _cache_id AND row_no BETWEEN p_row_from AND p_row_to
    ORDER BY row_no;
END;
$BODY$ LANGUAGE PLPGSQL;

Example: Retrieve rows from 1 to 2000 from cached my_view results filtered by key BETWEEN 30044 AND 10610679. Run a first time and the results of the query will be cached into table cached_results_my_view, and the first 2000 records will be returned. Run it again shortly after and the results will be retrieved from the table cached_results_my_view directly without executing the query.
SELECT * FROM f_get_my_view_cached_rows(30044, 10610679, 1, 2000);


text:
Q: PHP Separate comma array into variable / values I have a string in a table field that looks like this:
part1=1,part2=S,part3=Y,part4=200000

To call it from the table I do this:
 while($row = mysqli_fetch_array($result)) {

        $row['mystring'];

}

My problem is that I need to separate the parts into variables for example:
From this:
part1=1,part2=S,part3=Y,someothername=200000

To This:
$part1 = '1';
$part2 = 'S';
$part3 = 'Y';
$someothername = '200000';

How can I do this?

A: Use like this
parse_str( str_replace(",", "&", "part1=1,part2=S,part3=Y,someothername=200000") );

Use with there name like:
$part1 // return 1
$part2 // return S
$part3 // return Y

works like you want, see the demo

A: First split string:
$s = "part1=1,part2=S,part3=Y,part4=200000";
$a = explode(",",$s);

then foreach part of string ("part1=1"...) create an array and explode as variable:
foreach($a as $k=>$v)
{
 $tmp = explode("=",$v);
 $tmp = array($tmp[0]=>$tmp[1]);
 extract($tmp);
}
echo $part1;

A: Double explode your string to get the wanted field :
$string ="part1=1,part2=S,part3=Y,someothername=200000";

foreach (explode(',', $string) as $parts) {
  $part = explode('=', $parts);
  $array[$part[0]] = $part[1];
}

var_dump($array);

Output :
 array(4) {
  ["part1"]=>
  string(1) "1"
  ["part2"]=>
  string(1) "S"
  ["part3"]=>
  string(1) "Y"
  ["someothername"]=>
  string(6) "200000"
}

I wouldn't suggest the use of variable variables to get the output as :
$part1 = ...
$part2 = ...

Using an array is probably the easier and safest way to do here. As suggested in my comment, it avoid potential conflicts with variable names.

A: If you use PHP 5.3+ you can use array_map
<?php

$string = 'part1=1,part2=S,part3=Y,part4=200000';

array_map(function($a){
    $tmp = explode('=', $a, 2);
    global ${$tmp[0]}; //make vars available outside of this function scope
    ${$tmp[0]} = $tmp[1];
}, explode(',', $string));

//Variables available outside of array_map scope
echo $part1 . '
';
echo $part2 . '
';
echo $part3 . '
';
echo $part4 . '
';

?>

A: You can use something called 'Variable variables'. You can declare the content of a variable as a variable, if you use double dollar sign, instead of a single one. For example:
$fruit = "apple";
$$fruit = "this is the apple variable";
echo $apple;

It would output the following:

this is the apple variable

You have to be a bit more tricky with defining variables from an array, as you'd have to enclode the original variable in curly brackets. (for example: ${$fruit[0]})
So the answer to your question is:
$parts = "part1=1,part2=S,part3=Y,someothername=200000";
$parts_array = explode(",", $parts);
foreach ($parts_array as $value) {
    $temp = explode("=", $value);
    ${$temp[0]} = $temp[1];
}
echo "$part1, $part2, $part3, $someothername";

PHPFiddle link: http://phpfiddle.org/main/code/adyb-ug5n


text:
Q: Python data.table row filter by regex What is the data.table for python equivalent of %like%?
Short example:
dt_foo_bar = dt.Frame({"n": [1, 3], "s": ["foo", "bar"]})
dt_foo_bar[re.match("foo",f.s),:] #works to filter by "foo"

I had expected something like this to work:
dt_foo_bar[re.match("fo",f.s),:]

But it returns "expected string or bytes-like object".
I'd love to start using the new data.tables package in Python the way I use it in R but I work a lot more with text data than numeric.
Thanks in advance.

A: Since version 0.9.0, datatable contains function .re_match() which performs regular expression filtering. For example:
>>> import datatable as dt
>>> dt_foo_bar = dt.Frame(N=[1, 3, 5], S=["foo", "bar", "fox"])
>>> dt_foo_bar[dt.f.S.re_match("fo."), :]
     N  S
--  --  ---
 0   1  foo
 1   5  fox

[2 rows x 2 columns]

In general, .re_match() applies to a column expression and produces a new boolean column indicating whether each value matches the given regular expression or not.


text:
Q: Footprint to accomodate chips with different pin count I am working on a PCB that (among other things) accomodates an MCU which is available either in a SOIC-14 or SOIC-16 package. Both packages are pin-compatible, the SOIC-14 is simply shorter to one side. This allows me to use the same PCB with a SOIC-16 footprint on it but populate it with either chip, depending on which one is available.
So far so good. Problem: the coordinates in the pick-and-place file always refer to the middle of the chip. That means I cannot use the same pick-and-place file - instead I have to offset the coordinates by half a pin.
I wonder if there is any best-practice to handle such a situation. Of course I can manually edit the pick-and-place file easily, but it would be quite nice to somehow handle it within the CAD tool and generate the correct file automatically. I cannot think of a smart way to achieve that... I guess the right way would be to have both chips in the BOM but assign a part only to one of them. But if I were to put two overlaying footprints on the PCB, I'd get errors because the courtyards overlap (although the pads are connected to the same nets).
(my CAD tool is Altium CircuitStudio)
How can I accommodate chips with a different pin count?

A: The way to do this is commonly done with variants, but you have to produce two design files, you can use the same schematics and output two different designs (boms or PCB's). This also helps with manufacturing because you only send one set of files to the manufacturer and this creates less confusion.
For example:
I have boards with parts that use the same PCB, but have different parts loaded for the same component, I use variants to keep track of the parts and create two different BOMS's. I then keep all the files in the same zip folder and create two zip folders for each variant. When I want to order I send the correct zip file to the assembler and they build that design.
The different pin count might be tricky with a variant but doable.


text:
Q: cudaMemcpy invalid argument My program runs 2 threads - Thread A (for input) and B (for processing). I also have a pair of pointers to 2 buffers, so that when Thread A has finished copying data into Buffer 1, Thread B starts processing Buffer 1 and Thread A starts copying data into Buffer 2. Then when Buffer 2 is full, Thread A copies data into Buffer 1 and Thread B processes Buffer 2, and so on.
My problem comes when I try to cudaMemcpy Buffer[] into d_Buffer (which was previously cudaMalloc'd by the main thread, i.e. before thread creation. Buffer[] were also malloc'd by the main thread). I get a "invalid argument" error, but have no idea which is the invalid argument.
I've reduced my program to a single-threaded program, but still using 2 buffers. That is, the copying and processing takes place one after another, instead of simultaneously. The cudaMemcpy line is exactly the same as the double-threaded one. The single-threaded program works fine.
I'm not sure where the error lies.
Thank you.
Regards,
Rayne

A: If you are doing this with CUDA 3.2 or earlier, the reason is that GPU contexts are tied to a specific thread. If a multi-threaded program allocated memory on the same GPU from different host threads, the allocations wind up establishing different contexts, and pointers from one context are not portable to another context. Each context has its own "virtualised" memory space to work with.
The solution is to either use the context migration API to transfer a single context from thread to thread as they do work, or try the new public CUDA 4.0rc2 release, which should support what you are trying to do without the use of context migration. The downside is that 4.0rc2 is a testing release, and it requires a particular beta release driver. That driver won't work will all hardware (laptops for example).


text:
Q: Browse and select document library files through a Modal Dialog I have a page which should link documents from a document library as hyperlinks in the page, so that a user can click on the hyperlink and view it. For this purpose,I need to add functionality to add documents from the Document library.
So, I need to select a document in the Document library through a window(maybe a modal popup), and set the selected document's path as a hyperlink. How would be the best way to achieve this?
The functionalities required are
1) Need to browse the document library,
2) search for a document and when it's selected by user ... include/capture it's path as a hyperlink.


text:
Q: Location Services will not activate on iPad I am developing an iOS app which uses Location Services. The app works fine on iPhones (3GS and 4), but does not request locations services when run on the iPad. That is, the user is never asked to enable location services, nor does the app appear in Location Services section of the Settings app.
I have seen a few forum posts describing similar issues, but all of these were resolved by installing the app on the iPad through iTunes (via ad-hoc distribution) rather than running it through Xcode, or by resetting location warnings. I tried both of these solutions on an iPad, an iPad 2, and the iPad simulator, both to no avail.
We use the following code to enable Location Services updates. We have verified both by on-device debugging and placement of NSLogs that our code is getting run.
- (id)init {
    [super init];

    if (clManager == nil) {
        clManager = [[CLLocationManager alloc] init];
    }
    clManager.delegate = self;

    [self startLocationMonitoring];

    return self;
}

- (BOOL)isLocationAvailable {
    return [CLLocationManager significantLocationChangeMonitoringAvailable];
}

- (void)startLocationMonitoring {
    if ([self isLocationAvailable]) {
        [clManager startMonitoringSignificantLocationChanges];
    } else {
        // handle lack of Location Services
    }
}

A: This probably does not answer your question, but might help somebody. The WiFi iPad models don't support significant location changes (the significantLocationChangeMonitoringAvailable method returns NO) and the startMonitoringSignificantLocationChanges seems to do nothing when running on these – it does not trigger the error delegate method nor it brings forward the blue bubble dialog asking for location services permission.

A: iPad comes in 2 models (wifi and wifi+3G). http://www.apple.com/ipad/specs/
The wifi model does not have A-GPS support.
If yo go through the specification you will see that A-GPS is only available on wifi+3G model and perhaps you are using the wifi(only) model.
However, through WIFI, iPad can detect locations if router is providing the same which does not seems to be in your case.
You can try your app on iPad2 wifi+3G version and you will see that it runs just fine..!!


text:
Q: SearchBar doesnt have 'X' button on right hand side As you can see my SearchBar doesn't have an 'X' button, which is normally at the right hand side of the SearchBar.
I only have the issue using Android, iOS has an X and a cancel button.
Do I need to add a tag in or what am I doing wrong?

 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="BottleShop.Views.Products">
        <NavigationPage.TitleView>
            <StackLayout BackgroundColor="Red" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand" Orientation="Horizontal">
                <SearchBar x:Name="Search" TextColor="Black" BackgroundColor="Purple" TextChanged="Searc_TextChanged" HorizontalOptions="FillAndExpand" Placeholder="Search..." PlaceholderColor="Gray" VerticalOptions="StartAndExpand"/>
            </StackLayout>
        </NavigationPage.TitleView>
        <ContentPage.ToolbarItems>
            <ToolbarItem Name="CartImage" Icon="ShoppingCart.png" Priority="0" Order="Primary" Activated="Clicked"/>
            <ToolbarItem Text="{Binding NoItemsInShoppingCart}" Priority="0" Activated="Clicked" Order="Primary"/>
        </ContentPage.ToolbarItems>

        <ContentPage.Content>

Xamarin.Forms v5.0.0.2012

A: Remove

NavigationPage.TitleView

Or

StackLayout BackgroundColor="Red" HorizontalOptions="FillAndExpand"
VerticalOptions="StartAndExpand" Orientation="Horizontal"

If the SearchBar surrounded by NavigationPage.TitleView and StackLayout, the 'X' button will disappear. Remove anyone of them can solve the problem.


text:
Q: AccessViolationException? I'm getting this weird AccessViolationException in my C# program that uses a MySQL database connection. I use values from the database to generate an autocorrect facility for a textbox. Here's the code snippet:
private void textBoxName_TextChanged(object sender, EventArgs e)
    {

            AutoCompleteStringCollection asc = Database.getSuggestedNames(textBoxName.Text);
            if (asc != null)
                textBoxName.AutoCompleteCustomSource = asc;
    }

The getSuggestedNames(string) method is implemented in Database.cs as follows:
public static AutoCompleteStringCollection getSuggestedNames(string namepart)
    {
        string query = "SELECT name FROM worker WHERE name LIKE '%"+namepart+"%';";
        string[] namecolumn = { "name" };
        List<string>[] names = getValues(query,namecolumn);
        AutoCompleteStringCollection namec = new AutoCompleteStringCollection();
        for (int i = 0; i < names[0].Count; i++)
            namec.Add(names[0][i]);
        return namec;
    }

The actual query is done with a separate method in the same file called getValues:
private static List<string>[] getValues(string query,string[] columnNames)
    {
        if (connection == null)
            initialize();

        if (connection.State == ConnectionState.Closed)
            connection.Open();

        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataReader dataReader = cmd.ExecuteReader();
        List<string>[] list = new List<string>[columnNames.Length];

        for (int i = 0; i < columnNames.Length; i++)
            list[i] = new List<string>();

        while (dataReader.Read())
        {
            for(int i=0;i<columnNames.Length;i++)
                list[i].Add(dataReader[columnNames[i]] + "");
        }

        dataReader.Close();
        connection.Close();
        return list;
    }

The exception always occurs when the user enters data into the textbox textBoxName. The error is not very frequent and the call stack shows its the external code that causes the problem. So I assume it should be MySQL that causes the problem.
Can somebody please help me to overcome this problem since there is nothing I can do.
The exact line the error occurs on is line 17 in the following code,which is not much use for me for debugging. Visual Studio does not show any other place. The stack trace shows [external code]. But here it is anyway:
1    using System;
2    using System.Collections.Generic;
3    using System.Windows.Forms;
4
5    namespace LabourManagement
6    {
7        static class ManagementProgram
8        {
9            /// <summary>
10            /// The main entry point for the application.
11            /// </summary>
12            [STAThread]
13            static void Main()
14            {
15                Application.EnableVisualStyles();
16                Application.SetCompatibleTextRenderingDefault(false);
17                Application.Run(new General());
18
19            }
20        }
21    }

A: I had a similar problem when i was working on a DataGridView auto-complete feature. at last, i discovered that the strange problem 'Access violation reading location 0x00000000' is due to a small semi-bug in .net which cause this exception if you add a null string to a AutoCompleteStringCollection!
So, the important thing when you are loading auto complete data from a source like as a database is to ensure avoid/skip null items when adding data to the collection.
Edit your code as following (note the if condition: if (names[0][i]!=null) ...):
public static AutoCompleteStringCollection getSuggestedNames(string namepart)
{
    string query = "SELECT name FROM worker WHERE name LIKE '%"+namepart+"%';";
    string[] namecolumn = { "name" };
    List<string>[] names = getValues(query,namecolumn);
    AutoCompleteStringCollection namec = new AutoCompleteStringCollection();
    for (int i = 0; i < names[0].Count; i++)
        if (names[0][i]!=null) namec.Add(names[0][i]);
    return namec;
}

A: I had the same issue with a ComboBox where i edited the item collect during a SelectedIndexChanged event. The stack trace will be unmanaged code, but editing the ComboBox.items collection was definitely the culprit. Maybe editing the AutocompleteSource items is causing your issue (since "Suggest" mode works like a ComboBox).


text:
Q: Printing numbers in python I have a script that generates some numbers (specifically times in epoch form).
Everytime it generates a number, I append the number to an array (called VALUES) and print both the array and that number. However, the number does not contain as many places after the decimal as the number in the array.
For example, a sample output will look like this (after 3 iterations):
VALUES = [733948.45278935181, 733948.45280092594, 733948.45280092594]
Number = 733948.452801

The third number in the array corresponds to the value in Number.
How come they contain different number of positions after the decimal?
Off-topic: What are the numbers after the decimal called? I thought there was some mathematical term for them I just can't remember what it is.
Note: Code was in python.

A: When you print the list, it prints repr(x) for each x in the list.
When you print the number, it prints str(x).
For example:
>>> print 123456789.987654321
123456789.988

>>> print [123456789.987654321]
[123456789.98765433]

>>> print str(123456789.987654321)
123456789.988

>>> print repr(123456789.987654321)
123456789.98765433

A: When python prints out a number, it sometimes prints out more decimal places based on whether the internal method is calling repr or str (which both convert the number to a string). repr will return more decimal places, while str does not.
print calls str, so when you do print Number, it will trim it a tad. However, when you  convert a list of numbers to a string when you do print VALUES, the list will internally use repr, giving it more decimal places.
In summary, depending on how it is being printed out, you will see different amounts of decimal places. However, internally, it is still the same number.
If you want to force it to use a specific number of decimal places, you can do this:
print "%.3f" % 3.1415   # prints 3.142

A: To get the precision you want, you need something like:
VALUES = [733948.45278935181, 733948.45280092594, 733948.45280092594]
for v in VALUES:
    print '%18.11f' % (v)

And the term I've always used for those digits after the decimal point is "those digits after the decimal point".  :-)

A: The part of the number to the right of the decimal point (or more generally, the radix point) is called the fractional part of the number (as opposed to integer part). For the decimal system it can be called the decimal part. In binary I've seen that part of the number referred to as the fractional bits.
From time to time an author will use the term mantissa when referring to that part of a number, but I believe that usage is considered wrong by many, as mantissa -- in my experience -- is most often often used as a synonym to significand.


text:
Q: Spring Pageable implementation on SQL Server 2008 - Offset clause I am trying implement a paging and sorting repository with a @Query annotation.  The query is simple enough:
SELECT DISTINCT(B.batch), B.scanDate, COUNT(B.batchReferenceNumber) as TransactionCount FROM Batch B

My database is SQL Server.  The query that is getting generated is:
    select
    distinct batch0_.BatchNumber as col_0_0_,
    count(batch0_.BatchNumber) as col_8_0_
from
    BATCH batch0_
order by
    batch0_.BatchNumber asc offset ? rows fetch next ? rows only

I get an error:  Incorrect syntax near 'offset'.
The reason is "Offset" was not introduced until SQL Server 2012.
Is there any way around this?  Or do I need to implement my own repository versus using the interface?

A: The SQL for the offset/limit clause is generated by your JPA provider.
You might be able to fix this by configuring the correct SqlDialect or if no such dialect is available you may raise an issue with that project.


text:
Q: Visual Studio 2015 Stuck Initializing Templates I am running Visual Studio 2015 Professional.  Every time I open my solution and either click/open on the Unit Test project within the solution or any of the files within the Unit Test project, I get a popup window that states "Initializing Templates...".
Visual Studio then becomes unresponsive and the mouse cursor turns into a spinner.  Sometimes it finishes (after several LONG minutes) or I just get frustrated and kill devenv.exe and try to avoid clicking on the project.  I then use VS2013 if I need to make changes within that project.
I have tried repairing Visual Studio 2015.  I have uninstalled it (and all 3rd party add-ons) and reinstalled it.  Nothing seems to work.  I would really like to use VS2015 but this is kind of a deal breaker.
Does anyone have any ideas?
EDIT
I tried opening another solution and when I went to the Unit Test project within it, I got the same popup/freezing.
Also, I just opened Visual Studio and tried to create a new project.  Same popup and now its frozen.
EDIT 2
Seems running the program as Administrator is causing the issue.  If I run Visual Studio 2015 normally, it eventually "initializes the templates" (after about 15 seconds).  Run VS2015 as administrator, and it just gets stuck "initializing templates".  Seems counter-intuitive.
I would still like to have this problem resolved.  I do have to run VS2015 occasionally as an administrator.

A: Running devenv.exe /installvstemplates fixed the issue for me. It took about 7 minutes to run, though, so be patient.

A: I had the same problem, I even tried the solution given above by Collin, but it showed me the error message "The operation could not be completed. Access is denied"

Following the steps below solved my issue-
Go to Control Panel -> Programs -> Uninstall a program -> Search for Microsoft Visual Studio (Mine was Microsoft Visual Studio Professional 2013) -> double click and select Repair button. This will solve the issue.

A: A temporary solution
1. Open existing project from .sln file
2. Close the internet connection
3. Right click on main solution and click add new project

Follow above step it will work.


text:
Q: unknown keyword project_id in Google Cloud Dns for ruby I'm trying to call DNS from Google Cloud Ruby
dns = Google::Cloud::Dns.new project_id: "my-id", credentials: "my_credentials"

but I receive this error:
 unknown keywords: project_id, credentials

how can i configure google cloud ruby DNS from code (not environment vars)

A: I was running into this error message when using Google::Cloud::Storage. For some reason, the google-cloud-storage github page did not have the correct syntax. The google docs have the answer:
storage = Google::Cloud::Storage.new(
  project: "project-123",
  keyfile: "keyfile.json
)

So perhaps it's a similar change for DNS.


text:
Q: Differentiating between standing waves (stationary waves) and progressive waves The question is ''Differentiate between standing waves (stationary waves) and progressive waves?"
I do not understand what exactly they would like to hear.
Should we talk about the frequency, properties, etc?
How can I incorporate their definitions into the answer? How do I pinpoint exactly what is different, beween standing waves and progressive waves?
Thank you in advance.

A: First advice: never seek answers to please what you believe your teachers want to hear. Doing so really limits your understanding and what you ultimately learn.
Waves are fundamentally the means by which nature expresses the movement of energy through time and space. Traveling waves are those that begin at some source of energy and can be observed a distance away from that source through what we classify as wave properties: frequency, speed and amplitude. When two waves of the same properties cross one another they can interfere resulting in what's called a 'standing' wave. Although the standing wave appears to be stationary in space it's actually the result of traveling waves interfering with one another. Standing waves and the interfering waves that create them normally occur when energy is trapped within a cavity that allows reflection of the traveling waves, such as within the length of a tube, for example. The standing wave within the cavity is essentially a resonance of the cavity. Musically instruments such as the flute are one example of such a cavity in which standing waves exist.