text:
Q: Timeouts and Freezing in EWS with Office 365 I have a service that watches 2 email inboxes. One thread is created for each inbox. The new messages are read and marked as Read on startup, then the NewMail event handler handles all new mail after that.
We have been using EWS version 14. We had no issues retrieving emails.
After we moved the emails to Office 365, the problems started.
On startup, the retrieval and handling of existing new messages is still working fine.
After startup, when the NewMail event handler is triggered, the bind/load method times out, regardless of what we set the Timeout property to.
We tried to switch to the newest EWS version (15.0).
With the new version, the startup handling still works fine.
However, trying to bind one email in the NewMail event handler makes no error, but makes the inbox thread quit.
When there is a new email message in both inboxes, the entire service freezes on the Bind line (i let it sit for 40 minutes before having to kill the service).
We tried both EWS versions with the following, with no success:
The below code is used in the NewEmail event handler AND the startup processing of existing new messages. Why would the same code have issues in one place and not the other? How do i fix this?
I have also tried to use EmailMessage.Bind using the NotificationEventArgs object, but i have the same issues.
We tried a SyncLock to get around the lock up and/or timeout, but that did not help.
Thanks!
 Private Sub HaveMail(ByVal sender As Object, ByVal e As Microsoft.Exchange.WebServices.Data.NotificationEventArgs)
    Dim error_occured As Boolean = False
    Try
        Try
            SyncLock lock
                Logger.LogDebug("Just entered the Locked state of the HaveMail event")
                Dim ir As FindItemsResults(Of Item) = service.FindItems(WellKnownFolderName.Inbox, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False), New ItemView(20))

                Do While ir.Items.Count > 0
                    For Each i As EmailMessage In ir
                        Try
                            Logger.LogDebug("About to load a newly received email message")
                            i.Load(PropertySet.FirstClassProperties)
                        Catch ex As Exception
                            Throw New Exception("Error while loading an email message: " & ex.Message)
                        End Try
                        Dim rm As New ReceivedMessage
                        rm.ReceivedDateTime = i.DateTimeReceived
                        rm.ToAddress = i.DisplayTo
                        rm.Subject = i.Subject
                        rm.Body = i.Body
                        rm.FromAddress = i.From.Address
                        Logger.LogDebug("Just loaded a newly received email message from " & rm.FromAddress)
                        Dim rme As New ReceivedMessageEvent
                        rme.msg = rm
                        RaiseEvent GotMail(Me, rme)
                        Logger.LogDebug("Just processed a newly received email message from " & rm.FromAddress)
                        i.IsRead = True
                        i.Update(ConflictResolutionMode.AlwaysOverwrite)
                    Next
                    ir = service.FindItems(WellKnownFolderName.Inbox, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False), New ItemView(20))
                Loop

            End SyncLock

A: Generally speaking, it's not a good practice to do much of anything from within the actual event handler.  So Update, FindItems, and Bind would all make a call back to EWS from within your handler, and that is not good.  The ExchangeService object is also not thread safe.  How did you get away with it before O365?  I have no answer other than just lucky.

A: Thanks to an answer on my posting on MSN, I was able to fix the problem.
I needed to raise the DefaultConnectionLimit to 100. Apparently, it defaults to 2, which was not enough.


text:
Q: is fortify software compatible with Visual Studio 2012? I am using fortify software v3.20 and it doesn't seem to be compatible with VS 2012.
Is the latest version working with VS 2012 if so which one?
Thanks.

A: 3.8 is now available and supports VS2012.

A: The next release of Fortify SCA (v3.7?) should have VS2012 support.

A: Fortify 3.7 doesn't support VS .Net Release 2012. It supports VS .Net Releases 2003/5/8/10.

A: SCA 3.7 with its auditing and scanning plugins supports the VS 2003, 2005, 2008 and 2010. No express editions!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python. Внедрение Scrollbar в Canvas Есть подобие Paint'а. Умеет рисовать, импортировать картинки, сохранять сделанное и тд. Беда в том, что если на холсте слишком большое изображение, то оно просто не помещается на экране и из-за отсутствия какого-либо средства прокрутки увидеть полностью всё невозможно. Поставил себе цель внедрить Scrollbar, чтобы он появлялся, если изображение на холсте выходит за рамки окна. Перечитал десятки постов на разных сайтах и stackoverflow в том числе, но никак не получается внедрить именно в свой проект. Понимаю, что это не сложно, но пробелы в ООП дают о себе знать. Прикрепляю ниже свой код. Надеюсь, что его количество не отпугнет людей, птмч на самом деле там много всего не относящегося к вопросу, а суть понятна благодаря моим комментам. Я закомментил там код, где я пытался добавить Scrollbar. На самом деле я буду рад даже если скинете какую-либо документацию, в которой можно почитать как правильно в такой ситуации нужно добавлять такие элементы, ибо на своём курсе программирования слегка упустил этот момент. Однако, искренне буду благодарен решению. Заранее спасибо за ответы.

from tkinter import *
from tkinter import messagebox
from tkinter.tix import *
#import os
#import matplotlib.pyplot as plt
from PIL import Image, ImageTk, ImageGrab
from tkinter.filedialog import askopenfilename, asksaveasfile

class Paint(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        print(parent)
        self.parent = parent
        self.color = "black"
        self.brush_size = 2

        self.setUI()

    def set_color(self, new_color):
        self.color = new_color

    def set_brush_size(self, new_size):
        self.brush_size = new_size

    def draw(self, event):
        self.canv.create_oval(event.x - self.brush_size,
                                event.y - self.brush_size,
                                event.x + self.brush_size,
                                event.y + self.brush_size,
                                fill=self.color, outline=self.color)
        # Непосредственно функция, которая будет отвечать за
        # появление "линии" на холсте

    def setScroll(self):
        sw = ScrolledWindow(self, scrollbar=Y)
        sw.pack(fill=BOTH, expand=1)

    def setUI(self):
        self.pack(fill=BOTH, expand=1)
        # Размещаем активные элементы на родительском окне

        self.columnconfigure(6, weight=1)
        # Даем седьмому столбцу возможность растягиваться, благодаря
        # чему кнопки не будут разъезжаться при ресайзе

        self.rowconfigure(2, weight=1)
        # То же самое для третьего ряда

        # sw = ScrolledWindow(self, scrollbar=Y)
        # sw.pack(fill=BOTH, expand=1)
        # Здесь я как раз и пытался внедрить скролбар, но получал ошибку, связанную
        # с тем, что не могу спаковать то, что спаковано (как я понял)

        self.canv = Canvas(self, bg='white')
        # Создаем поле для рисования, устанавливаем белый фон

        self.canv.grid(row=2, column=0, columnspan=7, padx=5, pady=5, sticky=E + W + S + N)
        # Прикрепляем канвас методом grid. Он будет находится в 3м ряду, первой колонке,
        # и будет занимать 7 колонок, задаем отступы по X и Y в 5 пикселей, и заставляем
        # растягиваться при растягивании всего окна

        self.canv.bind("<B1-Motion>", self.draw)
        # Привязываем обработчик к канвасу. <B1-Motion> означает "при движении
        # зажатой левой кнопки мыши" вызывать функцию draw

        color_lab = Label(self, text="Цвет кисти: ")
        # Создаем метку для кнопок изменения цвета кисти

        color_lab.grid(row=0, column=0, padx=6)
        # Устанавливаем созданную метку в первый ряд и
        # первую колонку, задаем горизонтальный отступ в 6 пикселей

        red_btn = Button(self, text="Красный", width=8,command=lambda: self.set_color("red"))
        # Создание кнопки:  Установка текста кнопки, задание ширины
        # кнопки (10 символов), функция вызываемая при нажатии кнопки.

        red_btn.grid(row=0, column=1)
        # Устанавливаем кнопку

        # Создание остальных кнопок повторяет ту же логику, что и создание
        # кнопки установки красного цвета, отличаются лишь аргументы.

        green_btn = Button(self, text="Зеленый", width=8, command=lambda: self.set_color("green"))
        green_btn.grid(row=0, column=2)

        blue_btn = Button(self, text="Синий", width=8, command=lambda: self.set_color("blue"))
        blue_btn.grid(row=0, column=3)

        black_btn = Button(self, text="Чёрный", width=8, command=lambda: self.set_color("black"))
        black_btn.grid(row=0, column=4)

        white_btn = Button(self, text="Белый", width=8, command=lambda: self.set_color("white"))
        white_btn.grid(row=0, column=5)

        #clear_btn = Button(self, text="Очистить", width=8, command=lambda: self.canv.delete("all"))
        #clear_btn.grid(row=0, column=6, sticky=W)

        size_lab = Label(self, text="Размер кисти: ")
        size_lab.grid(row=1, column=0, padx=5)

        one_btn = Button(self, text="2", width=8, command=lambda: self.set_brush_size(2))
        one_btn.grid(row=1, column=1)

        two_btn = Button(self, text="5", width=8, command=lambda: self.set_brush_size(5))
        two_btn.grid(row=1, column=2)

        five_btn = Button(self, text="7", width=8, command=lambda: self.set_brush_size(7))
        five_btn.grid(row=1, column=3)

        seven_btn = Button(self, text="10", width=8, command=lambda: self.set_brush_size(10))
        seven_btn.grid(row=1, column=4)

        ten_btn = Button(self, text="20", width=8, command=lambda: self.set_brush_size(20))
        ten_btn.grid(row=1, column=5)

def importImage():

    global paint
    fname = askopenfilename(filetypes=[("Изображения", "*.jpeg;*.jpg;*.png;*.gif")])

    if fname is not None:
        try:
           img = ImageTk.PhotoImage(Image.open(fname))
           paint.canv.background = img
           paint.canv.create_image(0, 0, anchor=NW, image=img)
        except Exception as err:
            messagebox.showerror("Ошибка загрузки файла", err)
    # Функция импорта изображения на холст

def saveImg():
    global paint

    fname = asksaveasfile(mode='w', defaultextension=".jpg", filetypes=[("JPEG", ".jpg")])
    if fname is None:
        return

    x = paint.canv.winfo_rootx() + 2
    y = paint.canv.winfo_rooty() + 2
    xx = x + paint.canv.winfo_width() - 4
    yy = y + paint.canv.winfo_height() - 4
    ImageGrab.grab(bbox=(x, y, xx, yy)).save(fname)
    # Функция сохранения нарисованного на холсте

def main():

    global paint
    root = Tk()
    root.title('Analoque ImageEditor')
    root.geometry("850x650+250+50")
    # Создание окна, смена его названия, размера и положения

    mainmenu = Menu(root)
    root.config(menu=mainmenu)

    filemenu = Menu(mainmenu, tearoff=0)
    filemenu.add_command(label="Очистить холст", command=lambda: paint.canv.delete("all"))
    filemenu.add_command(label="Импорт", command=importImage)
    filemenu.add_command(label="Сохранить нарисованное", command=saveImg)
    filemenu.add_command(label="Выход", command=root.quit)

    helpmenu = Menu(mainmenu, tearoff=0)
    helpmenu.add_command(label="Помощь")
    helpmenu.add_command(label="О программе")

    mainmenu.add_cascade(label="Файл", menu=filemenu)
    mainmenu.add_cascade(label="Справка", menu=helpmenu)
    # Добавление меню и его дальнейшее наполнение с подменю

    paint = Paint(root)
    # Функция, открывающая возможность рисовать

    root.mainloop()

if __name__ == '__main__':
    main()

    # Основа, которая запускает main(), если данный файл является
    # главным в запуске

A: Вот пример
frame=Frame(r,width=300,height=300)
frame.pack(expand=True, fill=BOTH) #.grid(row=0,column=0)

c=Canvas(frame,bg=cbg,width=600,height=400,scrollregion=(-10000,-10000,10000,10000))
c.pack()
hbar=Scrollbar(frame,orient=HORIZONTAL)
hbar.pack(side=BOTTOM,fill=X)
hbar.config(command=c.xview)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
vbar.config(command=c.yview)
c.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
c.pack(side=LEFT,expand=True,fill=BOTH)


text:
Q: Changing random Javascript to rotation sequential so I am trying to rotate some text snippets sequentially with javascript.  The below code does it randomly, and my javascript is zilch.  Can someone direct me in how to make this rotation sequential?  Thanks!
Site is built in Concrete5.  http://www.travelus.com.au/about-us/trial

There is supposed to be some content in this box, but you need Javascript to see it...

A: Try this, variable i maintains index of current element to be displayed. And after it reaches end of messages, it resets back to 0.
var i=0;
function newMessage()
{
  if(i===messages.length)
  {
    i=0;
  }
 var elem =document.getElementById("msg");
 elem.innerHTML = messages[i];
 i=i+1;
}

A: Right now your message is selected at random with the randno variable which randomly selects one of your messages by generating a random number. To make it sequential (and rotating, as I assume you would like it), you need to make a variable that is scoped higher than the newMessage function--basically outside of the function call.
To do this, you'd want to do something like this:
var index = 0;
function newMessage()
{
    index = (index + 1) % messages.length
    var elem =document.getElementById("msg");
    elem.innerHTML = messages[index];
}

The % symbol is a modulus and gives you the remainder of the new value of index divided by the number of messages you have so your number will never be higher than the number of messages you have. This is called modular arithmetic or clock arithmetic.

A: elem.innerHTML = messages[0];
messages.push(messages.shift());


text:
Q: Can a service be split into two microservices using common libraries? I am thinking of splitting a service serving multiple endpoints into microservices that can serve a set of endpoints but the problem is that the two services have certain logic in common. can the two services use libraries to address this? is it even a good idea to split it up?
to give a hypothetical analogy,
lets say the given service has two endpoints,

*

*GET /animals, which returns a list,
["dog", "cat"]

*POST /walk, that accepts the animal
// request body
{
    animal: "dog"
}

// handler
handle(request, response) {
    animalFood{{"dog": biscuits}, {"cat" : milk}}
    goForAWalk({
                   animal: request.Animal,
                   food: animalFood[request.Animal]
              })
}

Is it a good idea to split the two API's and keep the processing logic in libraries? Feels like the services are still coupled and belong to the same domain?

A: One of the driving ideas behind microservices, is to have independently deployable components: if team A makes a change on microservice a, they should be able to deploy it whenever they want, and team B should be able to deploy their change on service b  at their own pace.
Sharing a common library is on one side a good thing, because you reuse proven code.  On the other side, it might create a hidden coupling that may hamper independence if for example one of the team needs the common library to evolve:

*

*If the common library is about basic technical services needed for the APIs, change will probably be relatively well controlled: components using the old and the new release should most often be able to coexist, if it's related to the implementation of interoperable standards.

*If the common library is about domain objects, there are high risk of a more significant coupling, unless great care is taken to ensure backward compatibility. And this might create some technical liabilities over the time.

Therefore, you should assess carefully your design before deciding to split your microservices. Each microservice should be in principle as self-contained as possible. Very closely related features should therefore best stay together. Some strategies facilitate the cohesion: decompose by business capability, by subdomain, or by responsible team.
Ultimately it's up to you to see if it makes sense in your real life context.  But for your simplfied example of animal care, I would honestly hesitate to separate the services as some kind of care (go for a walk, feed, ...) seems highly co-related to the relevant animal).

A: I am not sure it solves anything in your particular case, but it can be done.
An example:
Let's say you are using C#, with Entity Framework Core for database access. In this case all your microservices (the ones made in C# at least) will use Entity Framework Core. In other words, they are all sharing the same library.
"But this is not a library I build myself" you might say. Well, no. But is it really any different? You can build your own general purpose libraries (which might be somewhat less general that i.e. EF Core) and use them like you would with any other library. If you are using Visual Studio, you can even make your own NuGet package and NuGet server.
In fact, many of the most popular general purpose libraries started out as a library solving a specific problem for someone. Try to find some YouTube videos of Jimmy Bogard talking about AutoMapper for instance.
So to summarize, you are not breaking the microservice pattern, by using the same library in multiple services. But you always need to ask yourself, what you gain by splitting a service. And perhaps start by "splitting it internally", so to speak. That is, to prepare the code for a split, but don't actually do so.


text:
Q: Can adiabatic heat exchange between different temperatures ever be reversible? I've been told, A volume 2X of Temperature 0.5*(T1+T2) is always at higher entropy than thermally insulated volumes, 'X' at T1, 'X' at T2 put together.
Let's take Sys1 (A volume 2X of Temperature 0.5*(T1+T2)) with entropy S1.
Let's take Sys2 (thermally insulated volumes, 'X' at T1, 'X' at T2 put together) with entropy S2.
We know S2>S1. It means that in any reversible pathway I go from Sys1 to Sys2, I have the weighted average of Q's flowing into the system to be positive. It says heat must flow into the system. I understand we can't give heat to surroundings because that'd result in equilibrium temperature being less than 0.5*(T1+T2). But Why is zero heat not OK?
Let's take an adiabatic two-chambered vessel with an infinitesimal transmittive layer separating two chambers. Why is this not reversible?

A: Entropy flows during heat transfer, but entropy is not conserved; it is also generated from nothing whenever energy flows down a gradient in an intensive property (such as pressure, temperature, chemical potential, electric field, stress, surface tension...). That's why your two-chambered vessel coming to thermal equilibrium isn't reversible.
During (real) heat transfer, entropy flows and is generated simultaneously.
The increase in entropy of a system coming to an equilibrium does not require heating from an external force, and surrounding the system with adiabatic walls will not suppress this entropy increase.
For two identical bodies (with temperature-independent material properties) at temperatures $T_1$ and $T_2>T_1$ brought into contact, the final temperature is $\frac{T_1+T_2}{2}$, as you note. In addition, $2C\ln\frac{T_2}{T_1}$ entropy is generated, where $C$ is the heat capacity of each body.
There is only one way to conceptualize reversible heat transfer between bodies at different temperatures: use them to run a reversible heat engine, which will provide us with work. One example is the Carnot cycle, which has the distinction of being the only reversible heat engine that requires only two reservoirs (the hot and cold reservoirs).
After this reversible heat transfer is completed, the two bodies are at the shared temperature $\sqrt{T_1T_2}$, and the entropy increase in the rest of the universe is zero. We obtain energy of $2C\left(\frac{T_1+T_2}{2}-\sqrt{T_1T_2}\right)$ in the form of work.
If we wish to bring the system to the same state as if the bodies were simply pushed together, we could dissipate that work into thermal energy (by running an electrical current through a resistor, for instance). This would raise the temperature to $\frac{T_1+T_2}{2}$ and generate $2C\ln\frac{T_2}{T_1}$ in entropy.


text:
Q: multi expression ternary operator? I'm trying to make multiexpression for ternary operator in Javascript like this :
condition ?
exp1 ; ... ; expN
:
alternative1 ; ... ; alternativeN

Here my code :
  validateEmail && validatePassword ?
        this.setState({validateForm: true})
        this.setState({nameSubmit:"onSubmit"})
        : null

My console returns me an error :

Declaration or statement expected

The javascript documentation talks about :

Syntax :
condition ? expr1 : expr2

But maybe someone has achieved the multi expression ternary operator ?
Thanks

A: const exp = () => { exp1; ... ; expN }
const alt = () => { alternative1; ... ; alternativeN }

condition ? exp() : alt();

It's not very readable you could use an IIFE to create the function and execute it in the same line.
condition ? (() => { exp1; ... ; expN })() : (() => { alternative1; ... ; alternativeN })();

Edit: I think you just added your code. In your code, I would recommend simply merging your setState calls into one command:
this.setState({
  validateForm: true,
  nameSubmit:"onSubmit"
});

A: You can use the comma operator.

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

let a = 0,
    b = 1,
    c = 2,
    d = a === 0 ? (b++, c++) : -1;

console.log(b, c, d); // prints 2 3 and 2(because this will be the last expression to be evaluated).

A: To execute multiple statements in one branch there is the if statement:
if(validateEmail && validatePassword) {
   this.setState({validateForm: true});
   this.setState({nameSubmit:"onSubmit"});
}


text:
Q: 404 - Category not found joomla Joomla 3 return 404 when try open url, etc
site.com/index.php/en/rolaplus-en-gb
Article with alias rolaplus-en-gb exist.
Other url work fine!
Or how open article over id?

A: Have You setup simple addresses in Global Configuration?
To open articje over id use
index.php?option=com_content&view=article&id=20


text:
Q: changing char by subtracting its ASCII code in c language I am doing some string workshop for my c learning. There is a problem, where you ask for a user input let say "bob" and the code is to lower its ASCII code so it becomes "ana". I am at loss on how I go about doing this. Would it be something like
int main() {
    char str[10];
    char test[10];
    int i;

    printf("Enter a string: ");
    scanf("%s", str);

    while(str[i]!='\0') {
       test[i]=str[i]; i++;
    }
}

If I were to print this it only gives me the ASCII code and not the letters associated with it. How would I take the ASCII code and turn it into letters? Or is there a better method for it

A: You want:
test[i] = orig[i] - 1;

If I were to print this it only gives me the ASCII code

That just means you are not printing it correctly. This should work:
printf("orig: %s, transformed: %s\n", orig, test);

A: In C, char is an integer type. There's no need to convert between a code and a letter: the letter is the code. For example, on ASCII systems 'a' == 97.
In other words, you can simply do str[i]--; directly (assuming your platform uses ASCII).


text:
Q: UIButton in UICollectionViewHeader doesn't work EDIT: The code works in the body of the cell, but not in the header!
I have added a button programmatically to my view. Everything is properly displayed. When I press the button it is highlighted.
The problem is that the function is not called. Does anybody has an idea to solve the problem?
let addPerson : UIButton = {
    let btn = UIButton(type: .system)
    btn.setTitle("Test button", for: .normal)
    btn.setTitleColor(.white, for: .normal)
    btn.backgroundColor = .darkGray
    btn.layer.masksToBounds = true
    btn.addTarget(self, action: #selector(handleAddPerson), for: .touchUpInside)
    btn.translatesAutoresizingMaskIntoConstraints = false
    return btn
}()

@objc func handleAddPerson() {
    print("test")
}

//Following is inside the init
let stackView = UIStackView(arrangedSubviews: [addPerson,addGroup])
    stackView.distribution = .fillEqually
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.spacing = 10
    addSubview(stackView)

    NSLayoutConstraint.activate([
        stackView.topAnchor.constraint(equalTo: topAnchor, constant: 8),
        stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8),
        stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
        stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
        ])

A: Try to changes the selector to this mate:
@objc func handleAddPerson(_ sender: UIButton?) {
    print("test")
}


text:
Q: How do I get the serving URL for Google Cloud Storage file objects on App Engine dev server? I have a python App Engine app and save files using the Google Cloud Storage API. However I need to get the serving URL for each file.
On production it is easy to figure out what the serving URL is as I prepend http://commondatastorage.googleapis.com to /bucket/path/to/file.txt as I already have the bucket name and path to my file.
How do I figure out what the serving URL is on the dev server?
It seems straight forward enough to do this with images using images.get_serving_url which can now take either blobstore or Cloud Storage references.
How can I figure out the serving URL for all files, not just images in a way that is compatible with both the development and production App Engine environments?

A: You can use GCS via the blobstore API. See this section for how to set up a serving handler for a GCS key:
https://developers.google.com/appengine/docs/python/blobstore/#Python_Using_the_Blobstore_API_with_Google_Cloud_Storage


text:
Q: fit glm with known coefficients and unknown intercept I am trying to fit a logistic regression model using glm, where I am only interested in the intercept - but I still want the model to be fitted with known coefficients.
Example:

or
beta <- c(24.5,3.6,2.87,7.32)

So I want to use
model <- glm(y~x_1+x_2+x_3+x_4, family=binomial(link="logit"), data=dt)

and in some way incorporate the known betas, so the glm function only fits the alpha. How can I do that?

A: With offsets, which add a known term to the linear predictor (RHS of the formula, on the logit scale) of a GLM.
beta <- c(24.5, 3.6, 2.87, 7.32)
dt <- transform(dt,
         pred=beta[1]*x_1+beta[2]*x_2+beta[3]*x_3+beta[4]*x_4)
model <- glm(y~1+offset(pred), family=binomial(link="logit"), data=dt)


text:
Q: SELECT Average Count of IIS method calls per second I'm trying to find out the average count of IIS calls per second (GET, POST, PUT, etc) in a time span of one week
Here's an example of a SELECT I'd use to get total counts in a week:
  SELECT Method, COUNT(*)
      AS TotalCalls
    FROM IISLog
   WHERE dDate
 BETWEEN '2018-05-10'
     AND '2018-05-17'
GROUP BY Method

How can I granularise this SELECT to get an average count of Method calls per second in this date range?
Expected output for calls per second:
Method    CallsPerSecond
Get       15
Put       10
Post      14
Delete    12

The number counts are just example estimates

A: Just divide by the amount of seconds that compose your filter ranges.
DECLARE @StartDate DATETIME = '2018-05-10'
DECLARE @EndDate DATETIME = '2018-05-17'

SELECT
    Method,
    CallsPerSecond = COUNT(*) / NULLIF(DATEDIFF(SECOND, @StartDate, @EndDate), 0),
    TotalCalls = COUNT(*)
FROM
    IISLog AS I
WHERE
    I.dDate BETWEEN @StartDate AND @EndDate
GROUP BY
    I.Method


text:
Q: What is the best practice to calculate a hash on a BufferedImage? I am working on a program that processes images, and can flip them if the underlying OCR detects that they are upside down.
However the OCR output is not 100% reliable in terms of bounding boxes, so sometimes it is wrongly detected that an invoice is upside down... forever.
I need to prevent this: The files have no unique identifiers anymore after they've been flipped, I can not see anymore that they are the same file after it has been flipped two times.
So what would be the best, or an acceptable, practice to create a hash from BufferedImages. I assume that every time the same file has been read, it will generate also the same RGB values for every pixel in the BufferedImage.
I can implement some naive algorithm myself, taking the RGB of every pixel, and then computing a hash/checksum. However I do not believe this is a correct method, how would it be best to do it?


text:
Q: How can I get parents' parents' child's value using jQuery? I'm a student who is studying Python alone these days.
Below is part of my HTML page's JavaScript code.
let temp_html_0 = `

        ${title}

REASON : ${comment}

        <button type="button" class="btn btn-success" onclick="confirm()">Confirm</button>
        <button type="button" class="btn btn-danger" onclick="reject()">Reject</button>

`

javascript function :
function confirm(){
    alert('confirmed')
    let test = $(this).parent().parent().find(".card-img-top").attr("src");
    alert(test)
    window.location.reload()
}

What I want to do is:
When user clicks btn-success button,
call confirm() function,
and get img src (${image} in my code)
to call AJAX.
I tried code above but it didn't work.
How can I get img src value?

A: From your comment I see that temp_html_0 will be repeated, then why not just use a subclass with a unique identifier like the iteration index for example and add it to your image class as the following

And then you can pass that index to your function and get that element by using your logic.

A: You can pass the button reference in HTML event binding confirm(this) reject(this), then you may access the parent and image src in both of the methods as shown in be below snippet.

function confirm(btn) {
  var $btn = $(btn);
  var imgSrc = $btn.closest('.card').find('.card-img-top').attr('src');
  console.log(`confirmed - ${imgSrc}`);
}

function reject(btn) {
  var $btn = $(btn);
  var imgSrc = $btn.closest('.card').find('.card-img-top').attr('src');
  console.log(`rejected - ${imgSrc}`);
}

        ${title}

REASON : ${comment}

        <button type="button" class="btn btn-success" onclick="confirm(this)">Confirm</button>
        <button type="button" class="btn btn-danger" onclick="reject(this)">Reject</button>

A: The core of the problem is that you use the onclick attribute. The value of it is confirm(), so when activated it will call the function but not set the context in any way. So this will be window (if you're not in strict mode).
A quick fix would be to modify the function definition to function confirm(el){  and the HTML to onclick="confirm(this)" in order to have access to the element that's clicked as a parameter. This leads to this code:

function confirm(el){
    console.log('confirmed')
    let test = $(el).parent().parent().find(".card-img-top").attr("src");
    console.log(test)
    //window.location.reload()
}

//////////////////////////////

const image = "foo";
const url = "bar";
const title = "baz";
const comment = "quux";

let temp_html_0 = `

        ${title}

REASON : ${comment}

        <button type="button" class="btn btn-success" onclick="confirm(this)">Confirm</button>
        <button type="button" class="btn btn-danger" onclick="reject()">Reject</button>

`

$("#main").append(temp_html_0);

However, a better technique is to use event binding on dynamically created elements using event delegation. It will execute the function with the correct context and further allows you to still have a single event handler but you do not mix the HTML with logic that JavaScript would use.:

function confirm(){
    console.log('confirmed')
    let test = $(this).parent().parent().find(".card-img-top").attr("src");
    console.log(test)
    //window.location.reload()
}

$("#main") // --> common ancestor for all your dynamic elements
  .on("click", ".btn-success", confirm);
//             ^^^^^^^^^^^^^^  ^^^^^^^ --> event handler to execute
//              ↳ element to monitor for clicks

function reject(){
    console.log('rejected');
}

$("#main").on("click", ".btn-danger", reject);

//////////////////////////////

const image = "foo";
const url = "bar";
const title = "baz";
const comment = "quux";

let temp_html_0 = `

        ${title}

REASON : ${comment}

        <button type="button" class="btn btn-success">Confirm</button>
        <button type="button" class="btn btn-danger">Reject</button>

`

$("#main").append(temp_html_0);

A: You can directly pass image src as parameter into confirm function call like this:
<button type="button" class="btn btn-success" onnclick="confirm(${image})">Confirm</button>
and you can get this parameter value inside confirm function.


text:
Q: FancyTree DnD how to allow only drop into valid folders and not outside of parent I have a fancytree table which has A Main Folder A Child and a child of a child.
below is what I would like to achieve
 Static(Folder) -> Not Droppable
   |
   Cycles(Folder) -> Not Droppable
    |
    [0] -> (folder) -> Able to drop into
    ----------------------- Cannot Drop Nodes Here
    [1] -> (folder) -> Able to drop into
    ----------------------- Cannot Drop Nodes Here
    [2] -> (folder) -> Able to drop into

My current code sorta works, but I had to set a custom flag for the nodes called "droppable" and if its false then don't allow dragging into it. You can't drop into the folder itself, but if its expanded you're still able to drag into the folder at any position. I only want to allow the node to go into the folders that are valid.

dragEnter: function(node, data) {

     if (node.data.droppable == false) {
         return false;
      }

      return true;
 },


text:
Q: Allow typing of non English Characters in text box In VB.NET, I want to allow typing of non English Characters (For example, Russian, Turkish) in text box. How can I achieve this? Please let me know.

A: I believe richtextbox allows for that.  You're talking about accents and umlauts right?
If so, I'm pretty sure if you just resize your richtextbox down to the size of your textbox then you'll be alright.
If that doesn't work try importing a language pack resource.  Use MSDN for specific ones.
Hope that helped


text:
Q: GROUP BY statement throwing errors tutorial isn't Hello im going through a tutorial on SQL joins and this statement below is throwing "sql_mode=only_full_group_by" error. I copied this directly from the tutorial and its working for him. Do I just need to disable this mode in the terminal?
    SELECT *
    FROM customers
    JOIN orders
            ON customers.id = orders.customer_id
    GROUP BY orders.customer_id;

A: If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. [1]
You can disable this, but it really makes sense to leave it enabled. Think about the following case:
id | type
---|-----
1  | foo
2  | foo
3  | bar

If you used a similar query to yours, select * from table group by type, what would you expect the output to be? Perhaps you expect two rows, foo and bar,  but what do you expect to be in the id column, namely for the foo record? Should we just choose the earliest record? The latest record? A random record? This is what the error is telling you - instead of having the database engine choose for you, you must be explicit.
So, in your example, you need to think about what the resulting data should look like. Maybe instead of select * you want select customers.name, count(*) ..., etc.
The reason this works for the tutorial you're following is either they don't have only_full_group_by enabled or they're using a MySql version older than 5.7.5 where this was introduced. In this case, the server is free to choose any value from each group, which is probably not what you want.
Finally, if you want your console to behave in the same way your tutorial is behaving, you can disable ONLY_FULL_GROUP_BY in the console by:
mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
[1] https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html


text:
Q: Error while compiling the package in PL/SQL. Error(7,1): PLS-00103: Encountered the symbol "CREATE"
Error(7,1): PLS-00103: Encountered the symbol "CREATE". I tried to put
  / before create but then error was Error(6,1): PLS-00103: Encountered
  the symbol "/" .

I am new to PL/SQL programming, could you please help on this.
CREATE OR REPLACE PACKAGE EMP_BULK_INSERT AS

     PROCEDURE Bulk_Insert;

    END EMP_BULK_INSERT;
    /* package body */
    CREATE OR REPLACE PACKAGE BODY EMP_BULK_INSERT AS

      PROCEDURE Bulk_Insert
      AS
         /* select all records from source table */
          CURSOR kt_test_cur IS
            SELECT empid
            ,      empband
            ,      empname
            ,      workexp
            ,      salary
            from   kt_test;

            /* create nested table type and variable that will hold BIG_TABLE's records */
            TYPE kt_test_ntt IS TABLE OF kt_test_cur%ROWTYPE;
            l_kt_test kt_test_ntt;
       BEGIN
            /* open pointer to SELECT statement */
            OPEN kt_test_cur;
            /* collect data in the collection */
            FETCH kt_test_cur BULK COLLECT INTO l_kt_test;
            /* close the pointer */
            CLOSE kt_test_cur;

           /* print size of the collection */
           DBMS_OUTPUT.PUT_LINE('Nested table holds: ' || TO_CHAR(l_kt_test.COUNT) || ' records.');

            /* write data down to target table */
            FORALL indx IN l_kt_test.FIRST..l_kt_test.LAST
                INSERT INTO kt1_test(empid,empband,empname,workexp,salary)
                VALUES (l_kt_test(indx).empid,l_kt_test(indx).empband,l_kt_test(indx).empname,l_kt_test(indx).workexp,l_kt_test(indx).salary);

             DBMS_OUTPUT.PUT_LINE('Number of rows inserted ' || SQL%ROWCOUNT || ' rows');

             COMMIT;

        END Bulk_Insert;

    END EMP_BULK_INSERT;

A: The "/" needs to be on a blank line, all by itself.
Like this:
CREATE OR REPLACE PACKAGE abc AS
...
END;
/
CREATE OR REPLACE PACKAGE BODY abc AS
...
END;
/

The meaning of the "/" is to execute the command buffer. In this case it executes the previous PL/SQL block.
For a more in depth discussion on this topic, see here on
stack overflow

A: If you want to manipulate the package vie the dedicated object viewa of SQL Developer you have to separate package def and body and use the "/" in neither:
First compile the package spec (without "/"). Then open the body in a separate tab page with the small package icon (left from the compile icon). Edit your body code and compile there (again, without the "/").


text:
Q: How to arrange feature matrix? I'm trying to arrange a feature matrix of size (1425 x 15) where each column represents the natural frequency of each sensor and each row represents a single data file. However, I keep on getting the same values in each column and the next value is printed to the next row. How would I be able to rearrange the feature matrix?
I tried to form a code which can be found below, but, I don't know what my mistake in the code. I formed different codes but the results were still the same. Please find below the codes formed:
Code 1:
# Matrix array:
DataSizerow=0
DataSizecolumn=0
Data = np.zeros((1425,15))

# Forming a feature matrix from frequency, PSD and AutoCorrelation values:
        # Dataset.shape[1] represesnt the acceleration dataset column
        # List_Of_DataFrame_Feature = []
        # List_Of_DataFrame_Label = []
        Length_PSD_mean = len(x_axis_list_psd_filtered)
        print('Length of PSD values: ', Length_PSD_mean)
        if Length_PSD_mean > 1:
            for PSD_Mean in range(Length_PSD_mean):
                X_axis_values_psd_mean = mean(x_axis_list_psd_filtered)
        else:
            X_axis_values_psd_mean = x_axis_list_psd_filtered
        DataFrame_Feature = np.array(X_axis_values_psd_mean)
        DataFrame_Feature1 = np.array(x_axis_list_filtered)
        DataSizecolumn = DataSizecolumn + 1
        print('Data Size column: ',DataSizecolumn)
        Data[DataSizecolumn - 1] = DataFrame_Feature
        if DataSizecolumn in range(1, dataset.shape[1]):
            DataSizerow = DataSizerow + 1
            print('Data Size row: ', DataSizerow)
            Data[DataSizerow - 1] = DataFrame_Feature
        print('Sensor {0}'.format(k))
        print('Data Frame: ', Data)

Code 2:
        # Dataset.shape[0] represesnt the acceleration dataset row
        # Dataset.shape[1] represesnt the acceleration dataset column
        DataSizecolumn1 = 0
        DataSizerow1 = 0
        DataFrame1 = np.zeros((1426, 16))
        for DataSizecolumn1 in range(1, dataset.shape[1]):
            print('Data Size column: ', DataSizecolumn1)
            for DataSizerow1 in range(1, dataset.shape[0]):
                print('Data Size row: ', DataSizerow1)
                DataFrame1[DataSizerow1][DataSizecolumn1] = DataFrame_Feature
        print('Sensor {0}'.format(k))
        print('DataFrame: ', DataFrame1)

Code 3:
        # Dataset.shape[0] represesnt the acceleration dataset row
        # Dataset.shape[1] represesnt the acceleration dataset column
        DataSizecolumn2 = 0
        DataSizerow2 = 0
        DataFrame2 = np.zeros((1426, 16))
        for DataSizecolumn2 in range(1, dataset.shape[1]):
            print('Data Size column: ', DataSizecolumn2)
            DataFrame2[DataSizecolumn2] = DataFrame_Feature
            if DataSizecolumn2 == dataset.shape[1]:
                DataSizerow2 = DataSizerow2 + 1
                print('Data Size row: ', DataSizerow2)
                DataFrame2[DataSizerow2] = DataFrame_Feature
                if DataSizerow2 == dataset.shape[0]:
                    break
        print('Sensor {0}'.format(k))
        print('DataFrame: ', DataFrame2)

The expected result should be like the matrix below of single row:
          Sensor 1 | Sensor 2 | Sensor 3 | Sensor 4 | Sensor 5 | Sensor 6 |
Data file     13   |   51.5   |    13    |   13     |    13    |    13    |
          Sensor 7 | Sensor 8 | Sensor 9 | Sensor 10 | Sensor 11 | Sensor 12 |
Data file     8.5  |    14    |    20    |   18.6    |   9.5     |   39    |
          Sensor 13 | Sensor 14 | Sensor 15 |
Data file     8.5   |    8.5    |    8.5    |

But the actual result is below:
          Sensor 1 | Sensor 2 | Sensor 3 | Sensor 4 | Sensor 5 | Sensor 6 |
Data file     13   |   13     |    13    |   13     |    13    |    13    |
          Sensor 7 | Sensor 8 | Sensor 9 | Sensor 10 | Sensor 11 | Sensor 12 |
Data file     13   |    13    |    13    |    13     |    13     |    13     |
          Sensor 13 | Sensor 14 | Sensor 15 |
Data file     13    |    13     |    13     |

Actual Feature matirx text file
Please find below the whole code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import fft
from scipy.signal import welch
import glob
import sys
from numpy import NaN, Inf, arange, isscalar, asarray, array
from statistics import mean
np.set_printoptions(threshold=sys.maxsize)

def peakdet(v, delta, x=None):
    """
    Converted from MATLAB script at http://billauer.co.il/peakdet.html

    Returns two arrays

    function [maxtab, mintab]=peakdet(v, delta, x)
    %PEAKDET Detect peaks in a vector
    %        [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local
    %        maxima and minima ("peaks") in the vector V.
    %        MAXTAB and MINTAB consists of two columns. Column 1
    %        contains indices in V, and column 2 the found values.
    %
    %        With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices
    %        in MAXTAB and MINTAB are replaced with the corresponding
    %        X-values.
    %
    %        A point is considered a maximum peak if it has the maximal
    %        value, and was preceded (to the left) by a value lower by
    %        DELTA.

    % Eli Billauer, 3.4.05 (Explicitly not copyrighted).
    % This function is released to the public domain; Any use is allowed.

    """
    maxtab = []
    mintab = []

    if x is None:
        x = arange(len(v))

    v = asarray(v)

    if len(v) != len(x):
        sys.exit('Input vectors v and x must have same length')

    if not isscalar(delta):
        sys.exit('Input argument delta must be a scalar')

    if delta <= 0:
        sys.exit('Input argument delta must be positive')

    mn, mx = Inf, -Inf
    mnpos, mxpos = NaN, NaN

    lookformax = True

    for i in arange(len(v)):
        this = v[i]
        if this > mx:
            mx = this
            mxpos = x[i]
        if this < mn:
            mn = this
            mnpos = x[i]

        if lookformax:
            if this < mx - delta:
                maxtab.append((mxpos, mx))
                mn = this
                mnpos = x[i]
                lookformax = False
        else:
            if this > mn + delta:
                mintab.append((mnpos, mn))
                mx = this
                mxpos = x[i]
                lookformax = True
    return array(maxtab), array(mintab)

# Definition to get values needed for the FFT plot:
def get_fft_values(y_values, T, N, f_s):
    f_values = np.linspace(0.0, 1.0/(2.0*T), N//2)
    fft_values_ = fft(y_values)
    fft_values = 2.0/N * np.abs(fft_values_[0:N//2])
    return f_values, fft_values

# Definition to find the values of axis:
def findyaxis(y_axis_input, x, y):
    x = np.array(x)
    order = y.argsort()
    y = y[order]
    x = x[order]
    input = np.array(y_axis_input)
    return x[y.searchsorted(input, 'left')]

def merge(list1, list2):
    merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))]
    return merged_list

def autocorr(x):
    result = np.correlate(x, x, mode='full')
    return result[len(result) // 2:]

def get_autocorr_values(y_values, T, N, f_s):
    autocorr_values = autocorr(y_values)
    x_values = np.array([T * jj for jj in range(0, N)])
    return x_values, autocorr_values

def signaltonoise(a, axis=0, ddof=0):
    """
    The signal - to - noise ratio of the input data. Returns the signal - to - noise ratio of `a`, here defined as the
    mean divided by the standard deviation.
    Parameters
    ----------
    a: array_like An array_like object containing the sample data.

    axis: int or None, optional.
    If axis is equal to None, the array is first ravel 'd. If axis is an
    integer, this is the axis over which to operate.Default is 0.

    ddof: int, optional.
    Degrees of freedom correction for standard deviation.Default is 0.

    Returns
    -------
    s2n: ndarray.
    The mean to standard deviation ratio(s) along `axis`, or 0 where the standard deviation is 0.
    """
    a = np.asanyarray(a)
    m = a.mean(axis)
    sd = a.std(axis=axis, ddof=ddof)
    return np.where(sd == 0, 0, m/sd)

def get_psd_values(y_values, T, N, f_s):
    f_values, psd_values = welch(y_values, fs=f_s)
    return f_values, psd_values

def smooth(y, box_pts):
    box = np.ones(box_pts)/box_pts
    y_smooth = np.convolve(y, box, mode='same')
    return y_smooth

# Assign folder to `folder`:
DataPathList = sorted(glob.glob('DataPath*.txt'), key = lambda z: (len(z)))
# DataSizerow = 0
# DataSizecolumn = 0
MaxDataSizerow = 1425
MaxDataSizecolumn = 15
Data = np.zeros((1426,15))
for fp in DataPathList:
    # Load spreadsheet:
    print('Opened file number: {}'.format(fp))
    dataset = np.loadtxt(fname=fp)
    print('The size matrix of Sensors Undamaged Scenario:', dataset.shape)
    print('The column size matrix of Sensors Undamaged Scenario:',dataset.shape[1])
    for k in range(1, dataset.shape[1]):
        # Create some time data to use for the plot:
        dt = 1

        # Getting the time period and frequency:
        t_n = 2
        N = 2192
        T_s = 0.00390625
        f_s = 256

        # Obtaining data in order to plot the graph:
        y = dataset[:,k]
        x = np.arange(0, len(y), dt)
        x1 = np.linspace(0, t_n, N)

        SNR = signaltonoise(y)
        print('Signal-to-Noise Ratio (SNR): ', SNR, 'dB')

        SR = 1/t_n
        SR1 = 1/T_s
        Nf = (SR)/2
        Nf1 = (SR1)/2

        # Plotting the acceleration-time graph:
        # plt.plot(x1, y)
        # plt.xlabel('Time (s)')
        # plt.ylabel('Acceleration (ms^-2)')
        # plt.title('Plot of Sensor {0}'.format(k))
        # # plt.show()
        # plt.show(block = False)
        # print('Plot of Sensor {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

        ## Fast Fourier Transform (FFT)
        # Obtaining the Sampling frequency and time period:
        print('Period:', T_s, 's')
        print('Sampling Frequency: ', f_s, 'Hz')
        f_values, fft_values = get_fft_values(y, T_s, N, f_s)

        # Setting plot limits:
        ax = plt.gca()
        ax.set_ylim([min(fft_values), max(fft_values)])
        ax.set_xlim([min(f_values), max(f_values)])
        amp_index = np.array(fft_values)
        amp_index_max = max(amp_index)
        amp_index_min = min(amp_index)
        delta = (amp_index_max + amp_index_min)/2

        # Obtaining the amplitude values:
        maxtab, mintab = np.array(peakdet(amp_index, delta))
        amplitudes3 = maxtab
        y_axis_list = []
        for e in range(len(amplitudes3)):
            amplitude3 = amplitudes3[e]
            amplitude3final = amplitudes3[e][1]
            y_values = amplitude3final
            y_axis_list.append(y_values)
        x_axis = np.abs(f_values)
        x_axis_list = []
        for o in range(len(y_axis_list)):
            x_axis_values = findyaxis(y_axis_list[o], x_axis, fft_values)
            x_axis_list.append(x_axis_values)
        peaks = merge(x_axis_list, y_axis_list)
        print('Number of Peaks Coordinates: ', len(peaks))
        print('Peaks Coordinates: ', peaks)

        # Plotting the amplitude-frequency graph:
        # plt.plot(f_values, fft_values, linestyle='-', color='blue')
        # plt.scatter(x_axis_list, y_axis_list, marker='*', color='red', label='Peaks: {0}'.format(len(peaks)))
        # plt.xlabel('Frequency [Hz]', fontsize=16)
        # plt.ylabel('Amplitude', fontsize=16)
        # plt.title("Frequency domain of the signal {0}".format(k), fontsize=16)
        # plt.legend()
        # # plt.show()
        # plt.show(block = False)
        # print('Frequency domain with peaks of the signal {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

        # Obtaining the PSD values:
        f_values, psd_values = get_psd_values(y, T_s, N, f_s)
        amp_psd_index = np.array(psd_values)
        amp_psd_index_max = max(amp_psd_index)
        amp_psd_index_min = min(amp_psd_index)
        psd_delta = (amp_psd_index_max + amp_psd_index_min) / 2
        maxtab, mintab = np.array(peakdet(amp_psd_index, psd_delta))
        amplitudes_psd = maxtab
        y_axis_list_psd = []
        for e in range(len(amplitudes_psd)):
            amplitude_psd = amplitudes_psd[e]
            amplitude_psd_final = amplitudes_psd[e][1]
            y_values_psd = amplitude_psd_final
            y_axis_list_psd.append(y_values_psd)
        x_axis_psd = np.abs(f_values)
        x_axis_list_psd = []
        for o in range(len(y_axis_list_psd)):
            x_axis_values_psd = findyaxis(y_axis_list_psd[o], x_axis_psd, psd_values)
            x_axis_list_psd.append(x_axis_values_psd)
        psd_peaks = merge(x_axis_list_psd, y_axis_list_psd)
        print('Number of PSD Peaks Coordinates: ', len(psd_peaks))
        print('PSD Peaks Coordinates: ', psd_peaks)

        # Plotting PSD-Frequency graph:
        # plt.plot(f_values, psd_values, linestyle='-', color='blue')
        # plt.scatter(x_axis_list_psd, y_axis_list_psd, marker='*', color='red', label='Peaks: {0}'.format(len(psd_peaks)))
        # plt.xlabel('Frequency [Hz]')
        # plt.ylabel('PSD [V**2 / Hz]')
        # plt.title("PSD of the signal {0}".format(k), fontsize=16)
        # plt.legend()
        # # plt.show()
        # plt.show(block = False)
        # print('PSD with peaks of the signal {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

        # Obtaining AutoCorrelation values:
        t_values, autocorr_values = get_autocorr_values(y, T_s, N, f_s)
        amp_auto_corr_index = np.array(autocorr_values)
        amp_auto_corr_index_max = max(amp_auto_corr_index)
        amp_auto_corr_index_min = min(amp_auto_corr_index)
        auto_corr_delta = (amp_auto_corr_index_max + amp_auto_corr_index_min) / 2
        maxtab, mintab = np.array(peakdet(amp_auto_corr_index, auto_corr_delta))
        amplitudes_auto_corr = maxtab
        y_axis_list_auto_corr = []
        for e in range(len(amplitudes_auto_corr)):
            amplitude_auto_corr = amplitudes_auto_corr[e]
            amplitude_auto_corr_final = amplitudes_auto_corr[e][1]
            y_values_auto_corr = amplitude_auto_corr_final
            y_axis_list_auto_corr.append(y_values_auto_corr)
        x_axis_auto_corr = np.abs(t_values)
        x_axis_list_auto_corr = []
        for o in range(len(y_axis_list_auto_corr)):
            x_axis_values_auto_corr = findyaxis(y_axis_list_auto_corr[o], x_axis_auto_corr, autocorr_values)
            x_axis_list_auto_corr.append(x_axis_values_auto_corr)
        auto_corr_peaks = merge(x_axis_list_auto_corr, y_axis_list_auto_corr)
        print('Number of AutoCorrelation Peaks Coordinates: ', len(auto_corr_peaks))
        print('AutoCorrelation Peaks Coordinates: ', auto_corr_peaks)

        # Plotting Autocorrelation-Time delay graph
        # plt.plot(t_values, autocorr_values, linestyle='-', color='blue')
        # plt.scatter(x_axis_list_auto_corr, y_axis_list_auto_corr, marker='*', color='red', label='Peaks: {0}'.format(len(auto_corr_peaks)))
        # plt.xlabel('time delay [s]')
        # plt.ylabel('Autocorrelation amplitude')
        # plt.title("AutoCorrelation of the signal {0}".format(k), fontsize=16)
        # plt.legend()
        # # plt.show()
        # plt.show(block = False)
        # print('AutoCorrelation with peaks of the signal {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

        print('Completed file {}'.format(fp), ', Now going into filtering the signal')

########################################################################################################################
############################################## Filtered Section ########################################################
########################################################################################################################

        # Plotting the smoothed filtered signal acceleration-time graph:
        y_filter = smooth(y, 10)
        # plt.plot(x1, y_filter)
        # plt.xlabel('Time (s)')
        # plt.ylabel('Acceleration (ms^-2)')
        # plt.title('Plot of Smoothed Sensor {0}'.format(k))
        # # plt.show()
        # plt.show(block = False)
        # print('Plot of Smoothed Sensor {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

        ## Filtered Fast Fourier Transform (FFT)
        # Obtaining the Sampling frequency and time period:
        print('Period:', T_s, 's')
        print('Sampling Frequency: ', f_s, 'Hz')
        f_values_filtered, fft_values_filtered = get_fft_values(y_filter, T_s, N, f_s)

        # Setting plot limits:
        ax = plt.gca()
        ax.set_ylim([min(fft_values_filtered), max(fft_values_filtered)])
        ax.set_xlim([min(f_values_filtered), max(f_values_filtered)])
        amp_index_filtered = np.array(fft_values_filtered)
        amp_index_filtered_max = max(amp_index_filtered)
        amp_index_filtered_min = min(amp_index_filtered)
        amp_index_filtered_delta = (amp_index_filtered_max + abs(amp_index_filtered_min)) / 2

        # Obtaining the amplitude values:
        maxtab, mintab = np.array(peakdet(amp_index_filtered, amp_index_filtered_delta))
        amplitudes3 = maxtab
        y_axis_list_filtered = []
        for e in range(len(amplitudes3)):
            amplitude3 = amplitudes3[e]
            amplitude3final = amplitudes3[e][1]
            y_values_filtered = amplitude3final
            y_axis_list_filtered.append(y_values_filtered)
        x_axis_filtered = np.abs(f_values_filtered)
        x_axis_list_filtered = []
        for o in range(len(y_axis_list_filtered)):
            x_axis_values_filtered = findyaxis(y_axis_list_filtered[o], x_axis_filtered, fft_values_filtered)
            x_axis_list_filtered.append(x_axis_values_filtered)
        peaks_filtered = merge(x_axis_list_filtered, y_axis_list_filtered)
        print('Number of Filtered Peaks Coordinates: ', len(peaks_filtered))
        print('Filtered Peaks Coordinates: ', peaks_filtered)

        # Plotting the amplitude-frequency graph:
        # plt.plot(f_values_filtered, fft_values_filtered, linestyle='-', color='blue')
        # plt.scatter(x_axis_list_filtered, y_axis_list_filtered, marker='*', color='red', label='Peaks: {0}'.format(len(peaks_filtered)))
        # plt.xlabel('Frequency [Hz]', fontsize=16)
        # plt.ylabel('Amplitude', fontsize=16)
        # plt.title("Filtered Frequency domain of the signal {0}".format(k), fontsize=16)
        # plt.legend()
        # # plt.show()
        # plt.show(block = False)
        # print('Filtered Frequency domain with peaks of the signal {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

        # Obtaining PSD Filtered values:
        f_values_filtered, psd_values_filtered = get_psd_values(y_filter, T_s, N, f_s)
        amp_psd_index_filtered = np.array(psd_values_filtered)
        amp_psd_index_filtered_max = max(amp_psd_index_filtered)
        amp_psd_index_filtered_min = min(amp_psd_index_filtered)
        amp_psd_index_filtered_delta = (amp_psd_index_filtered_max + abs(amp_psd_index_filtered_min)) / 2
        maxtab, mintab = np.array(peakdet(amp_psd_index_filtered, amp_psd_index_filtered_delta))
        amplitudes_psd_filtered = maxtab
        y_axis_list_psd_filtered = []
        for e in range(len(amplitudes_psd_filtered)):
            amplitude_psd_filtered = amplitudes_psd_filtered[e]
            amplitude_psd_final_filtered = amplitudes_psd_filtered[e][1]
            y_values_psd_filtered = amplitude_psd_final_filtered
            y_axis_list_psd_filtered.append(y_values_psd_filtered)
        x_axis_psd_filtered = np.abs(f_values_filtered)
        x_axis_list_psd_filtered = []
        for o in range(len(y_axis_list_psd_filtered)):
            x_axis_values_psd_filtered = findyaxis(y_axis_list_psd_filtered[o], x_axis_psd_filtered, psd_values_filtered)
            x_axis_list_psd_filtered.append(x_axis_values_psd_filtered)
        psd_peaks_filtered = merge(x_axis_list_psd_filtered, y_axis_list_psd_filtered)
        print('Number of Filtered PSD Peaks Coordinates: ', len(psd_peaks_filtered))
        print('Filtered PSD Peaks Coordinates: ', psd_peaks_filtered)
        print('X-Axis Filtered PSD Amplitudes: ', amplitudes_psd_filtered[:, [0]])
        length_amplitudes_psd_filtered = len(amplitudes_psd_filtered[:, [0]])
        print('Amplitudes PSD filtered length: ', length_amplitudes_psd_filtered)
        if length_amplitudes_psd_filtered > 1:
            # for PSD_Mean in range(length_amplitudes_psd_filtered):
            X_axis_values_psd_mean = mean(x_axis_list_psd_filtered)
            print('Mean Amplitudes PSD filtered: ', X_axis_values_psd_mean)
        else:
            X_axis_values_psd_mean = x_axis_list_psd_filtered

        # Plotting PSD-Frequency filtered graph:
        # plt.plot(f_values_filtered, psd_values_filtered, linestyle='-', color='blue')
        # plt.scatter(x_axis_list_psd_filtered, y_axis_list_psd_filtered, marker='*', color='red', label='Peaks: {0}'.format(len(psd_peaks_filtered)))
        # plt.xlabel('Frequency [Hz]')
        # plt.ylabel('PSD [V**2 / Hz]')
        # plt.title("Filtered PSD of the signal {0}".format(k), fontsize=16)
        # plt.legend()
        # # plt.show()
        # plt.show(block = False)
        # print('Filtered PSD with peaks of the signal {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

        # Obtaining Filtered AutoCorrelation values:
        t_values_filtered, autocorr_values_filtered = get_autocorr_values(y_filter, T_s, N, f_s)
        amp_auto_corr_index_filtered = np.array(autocorr_values_filtered)
        amp_auto_corr_index_filtered_max = max(amp_auto_corr_index_filtered)
        amp_auto_corr_index_filtered_min = min(amp_auto_corr_index_filtered)
        amp_auto_corr_index_filtered_delta = (amp_auto_corr_index_filtered_max + abs(amp_auto_corr_index_filtered_min)) / 2
        maxtab, mintab = np.array(peakdet(amp_auto_corr_index_filtered, amp_auto_corr_index_filtered_delta))
        amplitudes_auto_corr_filtered = maxtab
        y_axis_list_auto_corr_filtered = []
        for e in range(len(amplitudes_auto_corr_filtered)):
            amplitude_auto_corr_filtered = amplitudes_auto_corr_filtered[e]
            amplitude_auto_corr_final_filtered = amplitudes_auto_corr_filtered[e][1]
            y_values_auto_corr_filtered = amplitude_auto_corr_final_filtered
            y_axis_list_auto_corr_filtered.append(y_values_auto_corr_filtered)
        x_axis_auto_corr_filtered = np.abs(t_values_filtered)
        x_axis_list_auto_corr_filtered = []
        for o in range(len(y_axis_list_auto_corr_filtered)):
            x_axis_values_auto_corr_filtered = findyaxis(y_axis_list_auto_corr_filtered[o], x_axis_auto_corr_filtered, autocorr_values_filtered)
            x_axis_list_auto_corr_filtered.append(x_axis_values_auto_corr_filtered)
        auto_corr_peaks_filtered = merge(x_axis_list_auto_corr_filtered, y_axis_list_auto_corr_filtered)
        print('Number of Filtered AutoCorrelation Peaks Coordinates: ', len(auto_corr_peaks_filtered))
        print('Filtered AutoCorrelation Peaks Coordinates: ', auto_corr_peaks_filtered)

        # Plotting AutoCorrelation-Time delay filtered graph:
        # plt.plot(t_values_filtered, autocorr_values_filtered, linestyle='-', color='blue')
        # plt.scatter(x_axis_list_auto_corr_filtered, y_axis_list_auto_corr_filtered, marker='*', color='red', label='Peaks: {0}'.format(len(auto_corr_peaks_filtered)))
        # plt.xlabel('time delay [s]')
        # plt.ylabel('Autocorrelation amplitude')
        # plt.title("Filtered AutoCorrelation of the signal {0}".format(k), fontsize=16)
        # plt.legend()
        # # plt.show()
        # plt.show(block = False)
        # print('Filtered AutoCorrelation with peaks of the signal {0}'.format(k))
        # plt.pause(5)  # Pauses the program for 10 seconds
        # plt.close('all')

########################################################################################################################
############################################## Feature Matrix ##########################################################
########################################################################################################################
        # Forming a feature matrix from frequency, PSD and AutoCorrelation values:
        for DataSizeRow in range(MaxDataSizerow):
            for DataSizeColumn in range(MaxDataSizecolumn):
                DataFrame_Feature = np.array(X_axis_values_psd_mean)
                Data[DataSizeColumn - 1] = DataFrame_Feature
                Data[DataSizeColumn + 1]
                break
        print('Data Frame: ', Data)
    # np.savetxt('DataFrameTestfinal1.txt', Data, delimiter = ' , ')
    # # np.savetxt('DataFrame3.txt', DataFrame, delimiter=' , ')
    # np.savetxt('DataFrameTestfinal2.txt', DataFrame1, delimiter=' , ')
    # np.savetxt('DataFrameTestfinal3.txt', DataFrame2, delimiter=' , ')
    print('Completed both original and filtered signals of file {}'.format(fp))

The dataset is from the website link.
Link:  http://users.metropolia.fi/~kullj/JrkwXyZGkhF/wooden_bridge_time_histories/
Thank you for your help.


text:
Q: Kendo Checkbox is not passing notmapped value to controller I am having a problem with the kendo checkbox.  It is not setting the value i check on it and sending to the controller.  It is showing in the javascript model (in a custom save event) that the field is null.  It also hits the model in the controller as null.
How i declare the field:
[NotMapped]
    public bool? ValueBool { get; set; }

the control is in a partial view and is called like this:
@Html.Kendo().CheckBoxFor(m=> m.ValueBool).Checked(Convert.ToBoolean(Model?.Value ?? "false"))

This shows the control with the correct value.
However it's not passing the value when i click "save".  Any ideas?

A: ValueBool is nullable, so, if you are going for a 'tri-state' checkbox, meaning if the user doesn't touch the field, it stays null, but if they check it, it's true, uncheck it, it's false, you'll need to look at something like this: https://stackoverflow.com/a/17822452/493557
However, since you're converting the nullable bool to an either True or False value, perhaps you aren't looking for that tri-state option and you can either change your ValueBool to not be nullable, or do something like the following:
In your model add a boolean property that returns a non-nullable representation of your underlying nullable boolean:
public bool ValueBoolNotNullable //Obviously rename this :)
{
    get
    {
        return ValueBool.HasValue ? ValueBool.Value : false;
    }
    set
    {
        ValueBoolNotNullable = value
    }
}

And update your view CheckBoxFor to use that new property:
@Html.Kendo().CheckBoxFor(m=> m.ValueBoolNotNullable)


text:
Q: How to store PHP constants in a MySQL db I need to create a bunch of feeds in a fixed width format, they're all relatively the same in layout, but they can all have different formats.
For example:

Field 1 can be 30 bytes wide, left justified and padded with 0s
Field 2 can be 20 bytes wide, right justified padded with spaces

I'd like to store parameters for php's str_pad in the DB, but don't know the best way to store the pad_type parameter, since it's a constant, I can't read it back like:
$field = str_pad($input, $width, $pad_string, $pad_type)

I suppose I could wrap an eval() around $pad_type, but that seems sketchy.
Is there a better way to do this?
I'm stuck with, PHP 5.0, MySQL 4

A: Use constant():
$value = constant('NAME_OF_THE_CONSTANT_AS_STORED_IN_DB');


text:
Q: Crypted passwords in PHP-apis? Twitter? I'm creating a small service using api-libraries, such as Twitter. Is it possible to input users password to Twitter-api crypted. I would not like to store peoples passwords uncrypted on my server, but writing them every time is annoying.
Does someone know?
Martti Laine

A: You should consider using OAuth.
Here are some examples.

A: If you're using PHP you can use the GnuPG extension to easily encrypt any credentials on your side, and decrypting them before making the API calls.
Here's a check list of things you need:

*

*make sure gpg is installed on your system;

*create a gpg key pair and store the files on a safe location;

*optionally password protect the generated private key;

*use PHP's GnuPG extension to encrypt and decrypt data using those keys.

Here's a small PHP example, taken from the gnupg_encrypt() manual:
<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?>

This technique should also be applied even if you're using OAuth or other password-less authentication method. A common mistake is to use OAuth and not encrypt locally saved tokens as access to those tokens might give anyone the power to act on behalf of the user.


text:
Q: Measuring high voltage DC using an Arduino I want to measure a high voltage DC (electric vehiclr battery pack) source with isolation. The 4 ways I identified were using

*

*Linear optocoupler

*Isolated amplifier

*ADC on the HV side and sending the voltage digitally to LV side with optical isolation

*Using a voltage to frequency/pwm convertor

The first two options are too expensive/complicated for me so that only leaves me with the latter two.
For the third option I was thinking of stepping down the HV DC (~400 V) to 5 V using an SMPS to power the Arduino. I wanted to know if I were to use a voltage divider with the HV DC to measure the voltage using the Arduino ADC would I run into problems with ground reference? i.e the SMPS ground is different from the HV DC ground and as such the Arduino ADC has a different reference ground?L.
The fourth option seems the easiest to me but I was having the same confusion as above. Will the V to F IC be powered by the HV side? Can I use a voltage divider to step down the voltage to 5 V and use a voltage regulator IC such as an LM7805 and power it using that? V to F ICs have very low power requirements (50 - 10 mW) so the power loss in the potential divider resistor will be very low.
I would also like to know if there are any easier methods to measure HV DC with isolation.

A:
Can I use a voltage divider to step down the voltage to 5 V and use a voltage regulator IC such as an LM7805 and power it using that. […] V to F ics have very low power requirements (50 - 10 mW) so the power loss in the potential divider resistor will be very low.

No. Please. This was already answered in your previous question: the fact that your load "only" uses little power at 5V means that you still need to supply all its current through your voltage divider and your linear regulator. In the comments I calculated that for you – 4W get continuously dropped over your resistor. Such resistors exist, but you will have to pay for that power resistor (effectively, a small incandescent light bulb's equivalent of power, only that you don't want the resistor to glow in white light) and you will have to cool it actively.  Nothing about this is "easy".
If you actually want to build a voltage divider out of two resistors to then feed your 5V regulator and keep the voltage within that regulator's input range, you will need to spend more than 10 times power on the voltage divider. Honestly, we shouldn't even have to discuss this if you're measuring voltages: This is basics, P = U·I.

I was thinking of stepping down the hv DC (~400 V) to 5 V using an smps

An appropriate approach!

I wanted to know if I were to use a voltage divider with the HV DC to measure the voltage using the Arduino ADC would I run into problems with ground reference

No, if you're doing this all on the side that referenced to your high-voltage ground, that seems the way to go.

*

*linear optocoupler

*isolated amplifier

*having an ADC at the hv side and sending the voltage digitally to LV side with optical isolation

*Using a voltage to frequency/pwm convertor

Linear Optocoupler
… or any optocoupler, really, that comes with a sufficiently specified input/output-current curve, since applying a corrective curve is trivial in a microcontroller:
Would be an easy, low-complexity solution. Problem: These things are extremely temperature dependent, so you would need to find a way to stabilize its temperature, or to accurately measure its temperature. I bet there's measurement-grade optoisolators that have temperature control or correction built in, but these will cost more...
Isolated amplifier

*

*Needs supply on HV side

*costly

Measure on HV side, send optically to isolated side
That's how I'd do it. Still needs a HV-side supply, but that can be cheaply built using SMPS.
There's dedicated isolated ADCs for exactly such measurement problems; e.g. https://www.digikey.com/short/dr0tf0ww . Of course, these cost like 7€, but they save you a HV-side microcontroller and thus reduce complexity of your overall system.
Voltage-to-Frequency converter
If you want, just "half an ADC" (this is especially true if you think about how Delta-Sigma ADCs work). Sure, that works. I guess the idea was to then transport the AC through a transformer to achieve isolation, or at least through class Y capacitors.
Will work, depends on the accuracy of your conversion. Many V-to-F converters are not so good, and the ones that don't look like fake or counterfeit chips on ebay are currently pretty expensive (3,50€ for the cheapest one you can actually buy from digikey, AD7740, but that's also actually a pretty good V-to-F converter, so that's an upside). So that you'd be better off doing the conversion with the ADC of some MCU and letting the MCU then generate a square wave of desired frequency (or some PWM of desired length); might just as well let the MCU then send the data using UART across an optical isolator. (If you can keep the output zero-mean, can also use capacitors or transformers instead an optical isolator). Or, might directly go for the isolated ADC.

A: There is really little to fear by using a differential amplifier with sufficiently high value resistors, such as 500k, which will limit any possible current to a safe level that will not even be perceptible. The threshold of perception is generally on the order of one mA, and 5 mA is considered a "safe" level, which is about where most GFCI devices trip.
It is best to use two or three resistors in series, to provide fail-safe redundancy as well as providing good margin for voltage rating of the resistors. So three 150k resistors will limit current to less than 1 mA, and a differential amplifier using a precision op-amp will have good accuracy and common mode rejection. This method can also be used to read phase-to-phase voltages on a motor.
(edit) Aother device to consider is IL300 (Linear Optocoupler).
And you could use a high voltage optoisolator like TLP240GA (400 V) to turn on an isolation amplifier like HCPL-7520 (16 mA) long enough to take a measurement. If the device can start up to take a measurement in 5 ms and a measurement every 100 ms is sufficient, the average current draw would be less than 1 mA. You might be able to assure no more than the rated 400 V by using zener diodes and voltage dividers.


text:
Q: How can you know when a file has been modified within a running Python? I have a Python/PyQt application that loads many file references into memory and informs the user of information (text) within each file.   It even allow the user to open an editor (vim in my case) using Popen.   I would like the program, which lists all the files it opened in a QTreeView, to mark a checkbox in a column with the mtime if newer then the start of the application.  I know how to get the mtime of a file.  What I want to do is know if the file has been updated (modified - Windows OS) and change the checkbox state to reflect the fact that the file is now modified (dirty).  It seems to me that I could do this by running a separate Thread (or QDialog with nothing displayed?)  But this would require a process to continually be doing a getmtime on a list of files and communicating with the MainWindow.   It could be that the polling loop has some sleep in it so as to not take up too many cycles, but this presents other issues.  I would really like it for the OS to emit a file_change, but I do not think that is a likely solution.  Any thoughts?

A: There's watchdog, which monitors for filesystem changes on a few platforms, including windows.
If you want to do it yourself, the mechanism in use here, for the non-polling monitoring on windows, is the ReadDirectoryChangesW API function
Alternatively, there's the FindFirstChangeNotification API call, which is a bit less complicated for some use cases.
Here is a good write up about using all of these routines on windows, in python.

A: The suggestion to use FindFirstChange from otherchirps sent me in the direction I was looking for.   My end answer was to use QFileSystemWatcher from PyQt4. This provided the features I wanted and closer integration with Qt.  The following is an example of how to watch files, and directories using QFileSystemWatcher.  Now I can extend the paths/files to check and ask which ones are being monitored.  This lacks a lot of error checking, but it is a stub to start work from.
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from os import curdir

class MainWindow(QtGui.QMainWindow):
    path_Sig = QtCore.SIGNAL('pathsAdd()')
    def __init__(self):
        super(MainWindow, self).__init__()
        self.path = ['./test.dat', 'local1.bdf', 'Sub/sub1.bdf']
        button = QtGui.QPushButton('Paths')
        self.label = QtGui.QLabel(curdir)
        widget = QtGui.QWidget()
        layout = QtGui.QVBoxLayout(widget)
        layout.addWidget(button)
        layout.addWidget(self.label)
        self.setCentralWidget(widget)
        self.connect(button, QtCore.SIGNAL('clicked()'), self.setPaths)

    @QtCore.pyqtSlot(list)
    def setPaths(self):
        self.emit(QtCore.SIGNAL('path_Sig'), self.path)
        self.myPaths(self.path)
    @QtCore.pyqtSlot(list)
    def myPaths(self, path_list):
        self.label.setText(str().join(path_list))
    @QtCore.pyqtSlot("QString")
    def dirChanged(self, results):
        self.label.setText("Dir  {} changed".format(results))
    @QtCore.pyqtSlot("QString")
    def fileChanged(self, results):
        self.label.setText("File {} changed".format(results))

class FileWatcher(QtCore.QFileSystemWatcher):
    these_Sig = QtCore.SIGNAL('myPaths()')
    def __init__(self, paths=None):
        super(FileWatcher, self).__init__()
        try:
            self.addPaths(paths)
        except:
            self.addPath(curdir)

    @QtCore.pyqtSlot()
    def filesReport(self):
        self.emit(QtCore.SIGNAL('these_Sig'), self.files())
    @QtCore.pyqtSlot(list)
    def pathsAdd(self, path_list):
        self.addPaths(path_list)
        self.filesReport()

 if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('FileWatcherDemo')
    window = MainWindow()
    window.show()
    filewatcher = FileWatcher()
    QtCore.QObject.connect(filewatcher, QtCore.SIGNAL('directoryChanged(QString)'), window, QtCore.SLOT('dirChanged(QString)'))
    QtCore.QObject.connect(filewatcher, QtCore.SIGNAL('fileChanged(QString)'), window, QtCore.SLOT('fileChanged(QString)'))
    QtCore.QObject.connect(filewatcher, QtCore.SIGNAL('these_Sig'), window.myPaths)
    QtCore.QObject.connect(window, QtCore.SIGNAL('path_Sig'), filewatcher.pathsAdd)
    sys.exit(app.exec_())


text:
Q: UnPack NuGet package that gets created on build I am trying to unpack the nuget package that gets created during the build.
My Directory.Build.props file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Project>
    <PropertyGroup>
        <RestorePackagesPath>C:\packages</RestorePackagesPath>
    </PropertyGroup>
    <PropertyGroup>
        <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
        <PackageOutputPath>C:\LocalNuGetPackages</PackageOutputPath>
    </PropertyGroup>
    <PropertyGroup>
        <Version>1.0.0.1</Version>
    </PropertyGroup>
    <Target Name="UnPack" AfterTargets="Pack">
        <Exec Command="nuget install $(PackageId) -Version $(PackageVersion) -Source C:\LocalNuGetPackages -OutputDirectory C:\packages" />
    </Target>
</Project>

But this gives a different directory structure as Visual Studio is doing it.
Visual Studio produces the following directories
C:\packages\$(PackageId)\$(PackageVersion)\

But the used command (nuget install) produces
C:\packages\$(PackageId).$(PackageVersion)\

Is there a way to call the Visual Studio "internal" nuget to get the same directory structure, or am I missing an argument that enables this structure?
Currently I am using the nuget.exe from here https://www.nuget.org/downloads which I have added to PATH in my system variables.
Side note, I am not trying to install the NuGet package to any project, I am just looking to unpack it like Visual Studio does.

A: That is designed by that. global nuget caches always make the nuget path like package_id/version/xxx. That's the way VS IDE unpacks NuGet packages into the global cache mechanism.
And when you use nuget install or packages folder under the solution folder by packages.config, it actually likes package_id.version/xxx.
This difference is not what we can handle and can belong to the design itself. So I have reported the issue to the Team.
You could vote it and add any comments if I did not describe it in detail. Hope it could solve your confusion as soon as possible.

A: As was pointed out in the github issue created by @Perry the command I was actually looking for was
nuget add "C:\LocalNuGetPackages\castle.core.4.4.0.nupkg" -Source C:\packages -expand

Instead of
nuget install castle.core -Version 4.4.0 -Source C:\LocalNuGetPackages -OutputDirectory C:\packages

The add command lacks the ability to fetch the nuget package from a "source" (eg. NuGet.org or C:\LocalNuGetPackages) and you already need the *.nupkg downloaded and ready to unpack.
But this lack of ability is irrelevant in my situation, since upon build I am creating the *.nupkg and they are ther for me to unpack.
Don't get confused with the argument being called -Source in the add it is actually the equivalent of -OutputDirectory for the install command.
So for other users/cases it would be desirable to have the install command do the different directory structure, but for me add was what I wanted.


text:
Q: Priority queue of pairs in reverse order I'm wanting to do something like this:
priority_queue< pair<int, int>, vector<int>, greater<int> > Q;

This works fine if the type I'm comparing is int, i.e.:
priority_queue< int, vector<int>, greater<int> > Q;

however, obviously with the pair<int, int>, there is no way of comparing the pairs in the queue with the standard >. I was wondering what I should do? How would I implement an overloaded > or is there another way I can create a priority queue of pairs with the smallest pair.second being at the top of the queue?

A: Have you tried this?
typedef pair<int, int> P;
priority_queue< P, vector<P>, greater<P> > Q;

This will give the reverse ordering of the normal operator< for pair<int, int>, which will start with the smallest first tie-broken with smallest second.
If you want to sort by smallest second first and first second (!) then you'll need a new sorting functor:
struct Order
{
    bool operator()(P const& a, P const& b) const
    {
        return a.second < b.second || a.second == b.second && a.first < b.first;
    }
}

Then use:
priority_queue< P, vector<P>, Order > Q;

A: You should create your own domain class rather than using pair<int, int> here, as far as I can see. Then  you can overload > as you like.


text:
Q: Dotted underline TEXT I have a element (e.g. a label) with a fixed width and  I want that only the text to be dotted-underlined. If a do the "trick" with border-bottom the whole box will be underlined
I think this explains my problem

A: You should wrap it into a span and add that border-bottom style to that span: http://jsfiddle.net/mrg9a/2/

A: You could wrap the text in <span> tags and then apply the style to the spans.
See the second element in this jsFiddle example.

A: Since label elements are inline by default, the problem is caused by making them inline blocks. This in turn is presumably an attempt to avoid using the most natural and most effective way of structuring a form, namely an HTML table. Just switch to table markup and use label inside td with no fancy settings, and the label elements will take the border you set on them, in their natural width.


text:
Q: Feed reader - blog subscriptions Lot of times you will find a team writing good set of blogs, and if you are not interested in the content from one or more blogger in that group, is there any feed reader that allows me to unsubscribe to a particular blog in the group?

A: Yep, (coincidentally named) Feed Reader can do this with what they call a "smartfeed". You will want to filter by Author.
Here's an example I used to filter questions to only yours:


text:
Q: Place Image in PyQt QTableWidget Header I am trying to create a QTableWidget that has a thumbnail image in it's vertical header (and eventually some text under it). My current attempt is to subclass the QTableWidgetItem...
class ShotHeader(qt.QTableWidgetItem):
    imagePath = os.path.join(r'T:\path\to\image.jpg')
    shotThumbnailPixMap = QPixmap(imagePath).scaledToWidth(60)

    def __init__(self):
        super(ShotHeader, self).__init__()
        self.setData(QtCore.Qt.DecorationRole, self.shotThumbnailPixMap)

And later on this is set via
shotInterface = QTableWidget(rows, cols)
for row in range(rows):
    shotInterface.setVerticalHeaderItem(row, ShotHeader())

Which does show the image, but it seems to be an icon which I cannot change the size of, as can be seen in the following image...

Obviously, I'm looking for a way to make the images a decent size,
I have searched quite extensively for a solution to this problem, but have so far come up with nothing. No amount of scaling the QPixmap has any effect.
I'd really appreciate some help on this.
NB: I'm running PyQt in Houdini if that makes any difference.


text:
Q: Can't mount automatically TrueCrypt volume I have script for guessing the password of TrueCrypt volume. It should work but TrueCrypt or VeraCrypt says that it is invoked with incorrect command line parameters. Can anyone help with this?
#!/bin/bash
working="working.txt"
tc=veracrypt
prefix="--text --keyfiles= --protect-hidden=no --non-interactive -p "
sufix="gentle.tc /mnt"
count=0

echo archive=gentle.tc

while read -r p; do

    echo -en "\033[2K\r$p"

    if $tc "$prefix\"$p\" $sufix"; then echo "$p" >>$working ; exit ; fi

    if $tc "$prefix\"$p\n\" $sufix"; then echo "$p" >>$working ; exit ; fi

    if $tc "$prefix\"$p\r\" $sufix"; then echo "$p" >>$working ; exit ; fi

    if $tc "$prefix\"$p\r\n\" $sufix"; then echo "$p" >>$working ; exit ; fi

    b64=$(echo -n "$p" | base64)
    md5=$(echo -n "$p" | md5sum | gawk '{print $1}')
    sha1=$(echo -n "$p" | sha1sum | gawk '{print $1}')
    sha256=$(echo -n "$p" | sha256sum | gawk '{print $1}')

    if $tc "$prefix\"$b64\" $sufix"; then echo "$p" >>$working ; exit ; fi

    if $tc "$prefix\"$md5\" $sufix"; then echo "$p" >>$working ; exit ; fi

    if $tc "$prefix\"$sha1\" $sufix"; then echo "$p" >>$working ; exit ; fi

    if $tc "$prefix\"$sha256\" $sufix"; then echo "$p" >>$working ; exit ; fi

    count=$((count+1))

done < list.txt
echo COUNT=$count

A: Ok, so I've changed the script to have no variables, now it works ok:
#!/bin/bash
working="working.txt"
count=0

echo archive=gentle.tc

while read -r p; do

    echo -en "\033[2K\r$p"
    echo "$p" >> tested.txt

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$p" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$p\n" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$p\r" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$p\r\n" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    b64=$(echo -n "$p" | base64)
    md5=$(echo -n "$p" | md5sum | gawk '{print $1}')
    sha1=$(echo -n "$p" | sha1sum | gawk '{print $1}')
    sha256=$(echo -n "$p" | sha256sum | gawk '{print $1}')

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$b64" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$md5" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$sha1" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    if truecrypt --text --keyfiles= --protect-hidden=no --non-interactive -p "$sha256" gentle.tc /mnt 2>>errors.txt; then echo "$p" >>$working ; exit ; fi

    count=$((count+1))

done < list.txt
echo COUNT=$count


text:
Q: How to print a specific re.Match object Is it possible to print out a certain re.match object from the results?
Python
sentence = '''
Tue, 20 August 2019
17:30 - 21:00 CEST
'''

pattern = re.compile(r'\d\d[:]\d\d')
matches = pattern.finditer(sentence)

for match in matches:
    print(match)
    print(match.group(0))

Output --> print(match)
<re.Match object; span=(20, 25), match='17:30'>
<re.Match object; span=(28, 33), match='21:00'>

Output --> print(match.group(0))
17:30
21:00

Is it possible to only print a certain match?
print(first re.Match object in list) = 17:30

print(second re.Match object in list) = 21:00

Attempts --> my attempts to solve this
for match in matches:
    print(matches[0].group(0))
    print(match.group(0))
    print(match[0])
    print(match)
    print(match.__getitem__(0))
    print(match.group(0))
    print(match.groupdict(0))
    print(match.start(0))
    print(match.groups)
    print(match.group(1))
    print(re.match(r'<img.*?>', matches))
    print(re.match(r'<img.*?>', match).group(0))

A: for match in matches == you do the printing for all your matches.
Do this:
sentence = '''
Tue, 20 August 2019
17:30 - 21:00 CEST
'''

pattern = re.compile(r'\d\d[:]\d\d')
matches = pattern.findall(sentence) # returns a list
print(matches[0].group(0)) # get first element from the list (0-indexed) and get its first group

A: You may add a counter if you wish, increment it in the for cycle and check if it is the number of match you need to print.
See the Python demo online:
import re

sentence = '''
Tue, 20 August 2019
17:30 - 21:00 CEST
'''
pattern = re.compile(r'\d\d:\d\d')
cnt = 0          # Initialize the counter
wanted = [1,2]   # Defines the 1-based IDs of the matches you want to display

for match in pattern.finditer(sentence):
    cnt += 1                  # Increment the counter
    if cnt in wanted:         # If the ID is in wanted IDs
        print(match.group())  # Print it


text:
Q: Using JSON to store entity stats within a game I'm planning to create a game, either Turn Based Strategy or a Fantasy RPG and an idea I thought of was to use jsonto store the stats of the player and any computer entities within. I've never used jsonbefore but it looks pretty simple, So i'm wondering if this would good idea to use it or to use database to hold the information?

A: It's best to think ahead.
You should build a database to store game information.
And you could use JSON to exchange game data on a network.
You would have many possibilities under this concept. For instance:
You would display the information of your game, which is stored in your database in a Web page, using JSON format.
I hope this helps you.


text:
Q: Keep getting the gradle error "...APK was either not signed" with org.swinglabs:pdf-renderer I keep getting the error:
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.unacademy.debug"
        pkg: /data/local/tmp/com.unacademy.debug
        Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES]

        Installation failed since the APK was either not signed, or signed incorrectly.
        If this is a Gradle-based project, then make sure the signing configuration is specified in the Gradle build script.

It happens on all devices on all build variants (they use the same config though). Running "Generate Signed APK" from android studio works fine as I use another key.
EDIT:
I did in fact add a library compile 'org.swinglabs:pdf-renderer:1.0.5'. Removing this, and rebuilding solves the problem.
Part of the build.gradle:
signingConfigs {
    debug {
        keyPassword 'hello123'
        storeFile file('debug_new.jks')
        storePassword 'hello123'
        keyAlias 'debug'
    }

A: Did you edit the AndroidManifest.xml directly in the .apk file? If so, that won't work.
Every Android .apk needs to be signed if it is going to be installed on a phone, even if you're not installing through the Market. The development tools work round this by signing with a development certificate but the .apk is still signed.
One use of this is so a device can tell if an .apk is a valid upgrade for an installed application, since if it is the Certificates will be the same.
So if you make any changes to your app at all you'll need to rebuild the .apk so it gets signed properly.


text:
Q: run Java Web Start applications in non admin user accounts I have a java web start applications that perfectly works on my pc. The problem is that this app needs to be run on machines where the user does not have admin rights. For linux everything works fine even without sudo rights, but on windows I keep getting errors like this:
JNLPException[category: System Configuration : Exception: null : LaunchDesc: null ]

Moreover while I tested and make everything work on the 3 test PCs, every time I use another PC I get a new error like
JARSigningException

or
InvocationTargetException - Can't load library: \\Ubz01fst\Profs\User\xxx\swt-win32-3738.dll

The documentation is not that much, the debug is difficult on JNLPs. Do you think that it is my problem or as I guess the library is not stable and well defined for all the platforms and the architectures?


text:
Q: Groovy How to find key value in list of maps I want to find a better solution than iterating through a list of maps, which looks like this:
[[name:"Gromit", likes:"cheese", id:1234],[name:"john", likes:"fries", id:1234],...]

I have a list of names like ["lisa","carl","bob"...]. so I want to search the list of maps for the 'likes' and 'id' associated with my names list, but I don't want to iterate through the list for every single name using some boolean code.
For a regular map, I think I can do this:
if(regularMap.containsKey(key)) {
    println regularmap[key]
}

How can I do something similar for a list of maps within a Jenkins declarative pipeline?

A: It isn't clear what form you want the results in but the following is a starting point:
    def inputData = [[name: "Gromit", likes: "cheese", id: 1234], [name: "john", likes: "fries", id: 1234]]
    def names = ["lisa", "Gromit", "carl", "bob", "john",]

    def results = []
    names.each { name ->
        def matchingMap = inputData.find { it.name == name }
        if (matchingMap) {
            results << [matchingMap.id, matchingMap.likes]
        }
    }

results will be [[1234, cheese], [1234, fries]].

A: listOfMaps.findAll{ it.name in names }


text:
Q: Visual Studio Project Settings Location I Have Researched this question on Google and i cant seem to fine a good answer, or perhaps i am just searching the wrong thing
I Know by default any project settings are stored in the User/AppData directory
Is there anyway to make these setting be read from the same directory that the program runs from?

A: If you want the configuration settings to be read from the application directory, you should use the Application Configuration file. This is the myprogram.exe.config file. But note that these are not specific to a user. And you might have issues if the user doesn't have privileges to write to the file in the application's directory.


text:
Q: How to SSH gate forwarding git user to gitserver? Im trying to set up ssh/git access through a ssh gate but googleing has come up empty.
Basically I want any connection to my ssh gate from the user git to be forwarded to my ssh server so that pushes and pulls can me made remotely. However if any other user connects I want them to be logged in as usual.
internet--(git)-->gate--(git)--> git-server

internet--(user)-->gate

Any help or advice would be much appreciated.
One way to do this on the client side is to add the following to your .ssh/config:
Host git.life-hack.org
    HostName          git.life-hack.org
    ProxyCommand      ssh darkclown@www.life-hack.org nc %h %p
    User              git

But I was hoping that there would be a way to do this server side.

A: I assume you're talking about Linux and OpenSSH. Please advise if this is not the case.
I understand that the git-server isn't directly reachable from the internet. I don't think you can do what you're proposing automatically just using SSH.
Let's assume gate is on 2.2.2.2 (public IP) and git-server is at 10.10.10.10 (RFC1918)
Depending on what exacly you're trying to achieve and what the constraints are, you could:
1) have the user connecting to the git-server forward a port first:
ssh -N -L2222:10.10.10.10:22 user@2.2.2.2

and then they could log in as:
ssh -p2222 git@localhost

2) on the gate, you could forward connections made to 2.2.2.2:2222 to 10.10.10.10:22
so your user would log in as:
ssh -p2222 git@2.2.2.2
This would require a few commands executed on the gate:
# enable forwarding
echo -n 1 > /proc/sys/net/ipv4/ip_forward
# DNAT packets destined for 2.2.2.2:2222 to 10.10.10.10:22
iptables -A PREROUTING -d 2.2.2.2 -p tcp --dport 2222 -j DNAT --to-destination 10.10.10.10:22
# allow responses from 10.10.10.10 to get through
iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
# allow forwarding connections to 10.10.10.10:22
iptables -A FORWARD -p tcp --dport 22 -d 10.10.10.10 -j ACCEPT

There's nothing specific to do on the git-server.


text:
Q: .CER & .PFX file formats Since not all the UWP environments support the Windows CAPI and Win32 APIs necessary to create .CER and .PFX files. I was wondering if anyone in the community knew of a library or open source project that does this programmatically and without the use of any Windows, Unix or iOS native APIs.

A: I worked with .cer and .pfx certificates with uwp and there is not a third party library or open source project to create these kind of files. There is only support for reading


text:
Q: how to put filter on structure of attributes of xml files with spark I have a large number of xml files with large number of attributes. I want to apply a filter on the list of these files so that I can find files which contains attribute named "A" as StructType. How can I achieve this ?
|-- A: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- B: string (nullable = true)
|    |    |-- C: string (nullable = true)

Data is like -
A
[[1,X]]