text:
Q: pyarrow==0.17.1 installation ends with fatal error: 'arrow/python/config.h' file not found (Apple M1 chip) I'm trying to install the pyarrow==0.17.1 package on my MacBook pro machine (Apple M1 chip) and I'm getting the following error
      -- Found PkgConfig: /opt/homebrew/bin/pkg-config (found version "0.29.2")
      -- Found Arrow: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/include (found version "7.0.0")
      -- Arrow version: 7.0.0 (HOME: /opt/homebrew/Cellar/apache-arrow/7.0.0_3)
      -- Arrow SO and ABI version: 700
      -- Arrow full SO version: 700.0.0
      -- Found the Arrow core shared library: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/lib/libarrow.dylib
      -- Found the Arrow core import library: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/lib/libarrow.dylib
      -- Found the Arrow core static library: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/lib/libarrow.a
      -- Found ArrowPython: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/include (found version "7.0.0")
      -- Found the Arrow Python by HOME: /opt/homebrew/Cellar/apache-arrow/7.0.0_3
      -- Found the Arrow Python shared library: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/lib/libarrow_python.dylib
      -- Found the Arrow Python import library: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/lib/libarrow_python.dylib
      -- Found the Arrow Python static library: /opt/homebrew/Cellar/apache-arrow/7.0.0_3/lib/libarrow_python.a
      -- Configuring done
      -- Generating done
      -- Build files have been written to: /private/var/folders/6m/ychzdp6s7l390zfm77myvxzr0000gn/T/pip-install-lv5qrivl/pyarrow_12e0171ed6fa433da71d5392c3e10c3a/build/temp.macosx-12.0-arm64-3.7
      -- Finished cmake for pyarrow
      -- Running cmake --build for pyarrow
      cmake --build . --config release --
      [  6%] Compiling Cython CXX source for lib...
      [  6%] Built target lib_pyx
      [ 13%] Building CXX object CMakeFiles/lib.dir/lib.cpp.o
      /private/var/folders/6m/ychzdp6s7l390zfm77myvxzr0000gn/T/pip-install-lv5qrivl/pyarrow_12e0171ed6fa433da71d5392c3e10c3a/build/temp.macosx-12.0-arm64-3.7/lib.cpp:774:10: fatal error: 'arrow/python/config.h' file not found
      #include "arrow/python/config.h"
               ^~~~~~~~~~~~~~~~~~~~~~~
      1 error generated.
      make[2]: *** [CMakeFiles/lib.dir/lib.cpp.o] Error 1
      make[1]: *** [CMakeFiles/lib.dir/all] Error 2
      make: *** [all] Error 2
      error: command 'cmake' failed with exit status 2
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

I couldn't find a proven solution for this problem, the only reference I did review is the following - https://github.com/apache/arrow/issues/2281, as mentioned, no proven solution there.
Versions I'm using are:
python 3.7.12
pip 22.0.4
On my machine, I have the following installed - apache-arrow, apache-arrow-glib, cmake.
I've also tried to install the package with the --no-use-pep517 flag as the following- pip install --no-use-pep517 pyarrow==0.17.1 - no success there.
I took a peek inside arrow/python/ and config.h is obviously missing, I also look inside arrow/ which does contains a config.h, however, it's not the config.h that was required.
Does anyone have an idea how to solve this issue?

A: pyarrow==0.17.1 predates M1 chips (May 2020 vs November 2020).
Any particular reason you wouldn't want to use pyarrow==7.0.0? Your brew installed arrow seems to be 7.0.0 too.


text:
Q: Display date and time like a digital clock in Bash The command date +'%a %b %e %Y%n%I:%M %p' displays the date and time in the format:
Thu Sep 22 2016
08:02 PM

I was trying to think of a way to have the date and time update as the time changes. The only thing I can think of would be to do something like this:
#!/bin/bash

while true
do
    date +'%a %b %e %Y%n%I:%M %p'
done | awk '!seen[$0]++'

This produces output like:
Thu Sep 22 2016
08:02 PM
08:03 PM
08:04 PM

Is there a way to display the time change by overwriting the old time so that 08:02 changes to 08:03 on the same line, essentially making the date and time display like a regular digital clock?

A: To update the first line only when the day changes, and the second line every second:
while :; do
  # store start date in variable
  printf -v start_day '%(%a %b %e %Y)T'
  day=$start_day

  clear
  echo "$day"
  while sleep 1 && [[ $start_day = $day ]]; do
      printf -v day '%(%a %b %e %Y)T'
      printf '\r%(%I:%M %p)T'
  done
done

Using printf %()T restricts compatibility to recent bash 4.x, but substantially improves performance (avoiding the need to start an external program every time we want to update the time).

A: You can use tput to move the cursor around:
date +'%a %b %e %Y%n%I:%M %p'
while sleep 1
do
    tput cuu 2
    date +'%a %b %e %Y%n%I:%M %p'
done

redpajama_set_name: RedPajamaStackExchange


text:
Q: AttributeError: 'Pipeline' object has no attribute 'fit_resample' Based on the documentation given on the following link pipeline and imbalanced
i have tried to implement  code  on  some dataset, here is code :
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from sklearn.pipeline import  Pipeline
from sklearn.naive_bayes import GaussianNB
data =pd.read_csv('aug_train.csv')
data.drop('id',axis=1,inplace=True)
print(data.info())
print(data.select_dtypes(include='object').columns.tolist())
data[data.select_dtypes(include='object').columns.tolist()]=data[data.select_dtypes(include='object').columns.tolist()].apply(LabelEncoder().fit_transform)
print(data.head())
#print(data['Response'].value_counts())
mymodel =GaussianNB()
y =data['Response'].values
print(Counter(y))
X =data.drop('Response',axis=1).values
#X,y =SMOTE().fit_resample(X,y)
#mymodel.fit(X,y)
#print(mymodel.score(X,y))
#print(Counter(y))
over = SMOTE(sampling_strategy=0.1)
under = RandomUnderSampler(sampling_strategy=0.5)
steps = [('o', over), ('u', under)]
pipeline = Pipeline(steps=steps)
# transform the dataset
X, y = pipeline.fit_sample(X, y)

the main problem in this code is with line :
X, y = pipeline.fit_sample(X, y)

error  says that  AttributeError: 'Pipeline' object has no attribute 'fit_resample' how can i fix this issue? thanks in advance

A: The tutorial employs imblearn.pipeline.Pipeline, while your code uses sklearn.pipeline.Pipeline (check import expressions).  These appear to be different kinds of pipelines.


text:
Q: Drupal content in Solr I am using Apache Solr Search module for my Drupal 7 website. I have Solr running on a different server, my Drupal website is successfully connected to it and it works great meaning when I search for some text that is part of the Drupal website content such as 'basic page' or 'article', it returns search results. All good!
However, I have some xml documents(external data) that I want to be part of this search in the Drupal website. I have indexed those xml documents directly in Solr and they are searchable through Solr Admin only. I want to make them searchable from the Drupal website as well which shares the same Solr instance. How can I achieve that?
Do I have to modify schema.xml in Solr that was replaced with the one packaged from Drupal -apache solr module? Please shed some light.

A: I don't know of a way to do what you're describing with the stock Apache Solr module alone. The closest contrib module I know of is the Apache Solr Attachments module, but my understanding is that the attachments would need to be associated with content rather than indexed externally.
That said, there is an Apache Solr Examples project that includes a submodule called Apache Solr external index that is described as, "An example of how to search an external index with Solr." There may be enough there to help you create a custom module to do what you're needing.


text:
Q: videojs-contrib-hls bugginess on mobile safari I have a videojs player and using videojs-contrib-hls
element:
<video class="video-js vjs-default-skin vjs-big-play-centered" controls playsinline)

javascript:
const player = videojs(element)
player.src({
  type: 'application/x-mpegURL',
  src: <hls-url>
})

player.on('error', (e) => {
  console.error(e)
})

player.on('loadeddata', () => {
  console.log('laodeddata')
})

On desktop safari this works smoothly and everything is good. On Mobile safari I'm seeing the following issues:

*

*The full screen icon is on the player, tapping the full screen icon makes the screen go full and then it immediately collapses back to be inline. I tried removing the playsinline attribute but when I did that the video was not able to play on mobile safari at all

*About 4 out of 5 times (almost always) after tapping the play button the video correctly starts playing, but it freezes on the first frame and gets stuck. No error callbacks are fired, it just gets stuck and refresh is required. After several refreshing it will actually play and stream successfully.

A: The issue here was the library fastclick: https://github.com/ftlabs/fastclick
When the user clicks the "play" button fastclick was getting in the way and the Mobile Safari engine thought the play() was not initiated by a user gesture so Safari auto-paused the video.
The same effect was happened for the full screen action.


text:
Q: JavaSound: Detect device change Folks,
I am working on an applet that captures audio from the local computer and streams it up to the server. I am using a Java applet that currently hooks onto the default device and performs the upstream. Things are running well.
I now want to extend the functionality to allow users to choose the audio input device and to also show a sound level indicator of the chosen device in the web page.
I wrote a multithreaded utility that would do AudioSystem.getMixerInfo(); periodically and look for changes. There is also a thread that reads from the chosen device and displays sound levels.
My problem is that when I run my code and plug in a USB headset, the new device is not detected. However, if I shut down my code, then plug in the USB, the device does show up.
Is this a known and documented limitation of JavaSound that it does not sample the device set once the process is running?
I am using OSX Lion.
Thanks for any insights.
-Raj


text:
Q: T4 Template Generator rebuilt for Net Core I am working on a T4 template generator for Visual Studio that supports the net core runtime. The following requirements are

*

*T4 templates using netstandard 2.0 or netstandard 2.1 function assemblies.

*Support the latest language compiler.

*Debug T4 Templates in visual studio.

*generate T4 templates in visual studio via custom tool

That being said, what VS 2019 provides out of the box:

*

*T4 Template engine running on the Framework runtime.

*Roslyn in process compiler is limited to C# 5.0.

*Visual studio uses remote services to execute the template generation in a T4 host process, to attach too and debug the template.

*netstandard 2.x function assemblies are not supported, at least I could never get them to work.

Some of the considerations I have to account for are:

*

*netcore and net 5, do not support AppDomain.

*The T4 text transformation compiled with rosyln can not process in the framework, will not load the System.Private.CoreLib. this requires that a host process exist not only to generate the code files but also to debug them as well.

*This also means that the T4HostProcess uses named pipes to communicate with Visual Studio. Is the Host Process the named pipe server or is it the client. I want to say the server, but I am not sure, that is why I am posting this on stack overflow.

*With the last statement, I am pretty sure that I have to find a way to facilitate cross domain communication using named pipes, between a .net core process and a framework process(visual studio). Remote services is not an option because it was built for framework and will not work for .net core.

Steps taken to arrive to a solution:

*

*using the Mono T4 template engine to compile the T4 Transform assembly, using the netcore runtime of Roslyn.

*I have been able to accomplish the following: custom tool, compile a T4 transformation assembly.

I would love to hear about any suggestions on how I can get this working. I am in the weeds with this and some of them look downright daunting.


text:
Q: C++ template lambda wrapper Can anyone figure out how to make this compile ?
I'm trying to wrap a lambda in another function that does something (here printing "you know what") + calling the lambda.
Best would be to have automatic template parameters deduction.
#include <iostream>
#include <functional>
#include <utility>

void youKnowWhat(const std::function<void()>&& fun)
{
    std::cout << "You know what ?" << std::endl;
    fun();
}

template <typename... Args>
auto youKnowWhatSomething(const std::function<void(Args...)>&& fun)
{
    return [fun{std::move(fun)}](Args... args)
        {
            youKnowWhat(std::bind(fun, std::forward<Args>(args)...));
        };
}

int main()
{
    const auto imHavingSomething([](const std::string& s){
        std::cout << "Im having " << s << std::endl;
    });

    const auto youKnowWhatImHavingSomething(youKnowWhatSomething(std::move(imHavingSomething)));
    youKnowWhatImHavingSomething("fun with templates");
    youKnowWhatImHavingSomething("headaches");
}

A: Will this work for you? I've (basically) removed the const from const ... &&, and added a template parameter to the function youKnowWhatSomething. The lambda is no longer declared as const in main.
#include <iostream>
#include <functional>
#include <utility>

void youKnowWhat(const std::function<void()>& fun)
{
    std::cout << "You know what ?" << std::endl;
    fun();
}

template<typename function_t, typename... Args>
auto youKnowWhatSomething(function_t&& fun)
{
    return [fun{std::move(fun)}](Args... args)
        {
            youKnowWhat(std::bind(fun, std::forward<Args>(args)...));
        };
}

int main() {
    auto imHavingSomething = [](std::string s) {
        std::cout << "Im having " << s << std::endl;
    };

    const auto youKnowWhatImHavingSomething =
        youKnowWhatSomething<decltype(imHavingSomething), std::string>
        (std::move(imHavingSomething));

    youKnowWhatImHavingSomething("fun with templates");
    youKnowWhatImHavingSomething("headaches");
}

A: How about
#include <iostream>
#include <functional>
#include <utility>

template <typename F>
void youKnowWhat(F&& fun)
{
    std::cout << "You know what ?" << std::endl;
    fun();
}

template <typename F>
auto youKnowWhatSomething(F&& fun)
{
    return [fun{std::move(fun)}](auto&&... args) -> decltype(fun(std::forward<decltype(args)>(args)...), void())
        {
            youKnowWhat([&](){fun(std::forward<decltype(args)>(args)...); });
        };
}

int main()
{
    const auto imHavingSomething([](std::string s){
        std::cout << "Im having " << s << std::endl;
    });

    const auto youKnowWhatImHavingSomething(youKnowWhatSomething(imHavingSomething));
    youKnowWhatImHavingSomething("fun with templates");
    youKnowWhatImHavingSomething("headaches");
}

Demo


text:
Q: Supporting custom hooks in existing cpp class I am designing support for custom hooks in existing C++ class.
class NotMyClass {
  public:
    void DoSomething() {
      // Needs custom logic here.
      hook_.DoSomethingCustom();
    }

  protected:
    Hook hook_;
    int not_my_class_inner_variable_1_;
    Node not_my_class_inner_variable_2_;
    ...... More Class vars.....
}

class Hook {
  public:
    void DoSomethingCustom() {
    // Some custom logic that needs to access not_my_class_inner_variable_1_, not_my_class_inner_variable_2 etc. .
    }
}

Adding some more context here after initial comments: NotMyClass class is autogenerated and no custom logic can be added to this class. We want to be able to add custom hooks inside the autogenerated classes. So the plan was to instead pass/ingect in a Hook class that will be able to provide some custom processing. The autogenerated NotMyClass class will have hook_. DoSomethingCustom().
What's the best way to access NotMyClass  member variables inside Hook ?
I don't want to change the class structure(that is use inheritence) of NotMyClass due to additional constraints.
Is making Hook a friend of NotMyClass a good option and then passing NotMyClass as this to Hook functions ?
Thanks in advance!

A: The problem cannot be solved as stated, i.e., without breaking the Open-Closed-Principle (OCP), which says that "classes (and other things) should be open for extension but closed for modification." In this case, this means that you shouldn't try to both (a) leave MyClass unchanged and (b) access its private or protected members from outside. Private (or protected) signal things that are not accessed from the outside, that's literally what private (or protected) are designed for. You can circumvent this (old ways, new ways) but you shouldn't.
The answer by sanitizedUser modifies MyClass, which is undesirable as per the question. A hacky but straight-forward suggestion to your problem might be to pass the fields to be modified explicitly to the method by reference:
class MyClass {
  public:
    void DoSomething() {
      // Pass references to the fields you want to modify.
      hook_.DoSomethingCustom(my_class_inner_variable_1_, my_class_inner_variable_2_);
    }

  protected:
    Hook hook_;
    int my_class_inner_variable_1_;
    Node my_class_inner_variable_2_;
}

class Hook {
  public:
    void DoSomethingCustom(int &inner_variable_1, Node& inner_variable_2_) {
      // Use the data members.
    }
}

To signal that your Hook class explicitly is allowed to access members of MyClass, you could declare it as a friend. Example:
#include <iostream>

class Node {};

class MyClass;

class Hook {
  public:
    void DoSomethingCustom(MyClass &m);
};

class MyClass {
    friend Hook;  // Allows the Hook class to access our members!

  public:
    MyClass(Hook h): hook_(h) {}

    void DoSomething() {
      // Pass references to the fields you want to modify.
      hook_.DoSomethingCustom(*this);
    }

    void print_my_class_inner_variable_1_() {
        std::cout << my_class_inner_variable_1_ << std::endl;
    }

  protected:
    Hook hook_;
    int my_class_inner_variable_1_;
    Node my_class_inner_variable_2_;
};

void Hook::DoSomethingCustom(MyClass &m) {
      // Allowed to access private member because we are a friend!
      m.my_class_inner_variable_1_ = 42;
}

int main() {
    MyClass c{Hook{}};
    c.print_my_class_inner_variable_1_();
    c.DoSomething();
    c.print_my_class_inner_variable_1_();
}

Note: your whole design with this "Hook" looks very weird to me. How do you "add hooks" to this thing (which imho is one of the defining requirements for calling something a "hook")? I'm sure if you posted a lot more context, people here would suggest a very different larger-scale design.

A: It's not an ideal solution but if you are allowed to declare the Hook class a friend of NotMyClass then the following code somewhat works.
#include <iostream>

class NotMyClass;

class Hook {
  public:
    void DoSomethingCustom(const NotMyClass& c);
};

class NotMyClass {
  friend Hook;

  public:
    void DoSomething() {
      hook_.DoSomethingCustom(*this);
    }

  protected:
    Hook hook_;
    int not_my_class_inner_variable_1_;
    // Commenting Node member out because the definition of it is missing.
    // Node not_my_class_inner_variable_2_;
};

void Hook::DoSomethingCustom(const NotMyClass& c) {
    std::cout << c.not_my_class_inner_variable_1_ << '\n';
}

int main() {
    NotMyClass{}.DoSomething();
    return 0;
}

Output.
0

If you can modify NotMyClass entirely then I advice you to use polymorphism and declare Hook as an abstract class. This way its behaviour can be swapped more easily.
#include <iostream>
#include <string>

template<class State>
struct Hook {
    virtual State run(const State& s) const = 0;
};

struct ExampleState {
    int number;
    std::string text;
};

std::ostream& operator<<(std::ostream& stream, const ExampleState& state) {
    stream << state.number << ", " << state.text << '\n';
    return stream;
}

struct ExampleHook : public Hook<ExampleState> {
    ExampleState run(const ExampleState& s) const override;
};

class Receiver {
    public:
        void DoSomething();
        Receiver(const Hook<ExampleState>* const hook);

    private:
        const Hook<ExampleState>* const hook;
        ExampleState state;
};

ExampleState ExampleHook::run(const ExampleState& s) const {
    // Returning a modified state.
    return {
        s.number + 1,
        "Modified " + s.text
    };
}

void Receiver::DoSomething() {
    std::cout << "Original state:\n" << this->state;
    this->state = this->hook->run(this->state);
    std::cout << "Modified state:\n" << this->state;
}

Receiver::Receiver(const Hook<ExampleState>* const hook)
    : hook(hook), state{0, "hello"} {}

int main() {
    ExampleHook hook;
    Receiver receiver(&hook);
    receiver.DoSomething();
    return 0;
}

Output.
Original state:
0, hello
Modified state:
1, Modified hello

A: One way of doing this is declaring data members of class MyClass public and then passing a reference to an instance of MyClass to an instance of Hook.
class MyClass {
  public:
    void DoSomething() {
      // Pass a reference to this.
      hook_.DoSomethingCustom(*this);
    }

  public:
    Hook hook_;
    int my_class_inner_variable_1_;
    Node my_class_inner_variable_2_;
}

class Hook {
  public:
    void DoSomethingCustom(const MyClass& c) {
      // Use the data members.
      auto& ref1 = c.my_class_inner_variable_1_;
      auto& ref2 = c.my_class_inner_variable_2_;
    }
}

If you cannot declare the members public because this is a legacy code, then there is always the evil option.
#define protected public

// Your code.

#undef protected

However, if this code is already compiled as a dynamic library then you are out of luck.


text:
Q: pagination-error in Codeigniter I can't see what I'm doing wrong in my code.
I want to get the pagination-links to work but the result I get is the 404-error, The page not found...
This is my model:
class Clientlist extends CI_Model{
public function __construct()
{
        // Call the CI_Model constructor
        parent::__construct();
}

//Get full clients
public function full_list($limit) {
    $sql = $this->db->get('clients', $limit);

    return $sql;
}
public function count_list() {
    return $this->db->count_all('clients');
}

}
This is my view:
foreach ($client_list->result() as $cl) {
    echo $cl->fName . ' ' . $cl->lName . ' ' . $cl->cName . ' ' . $cl->cNumber . ' ' . $cl->phone . ' ' . $cl->mail .'<br />';
}
    echo $this->pagination->create_links();

This is my controller:
$this->load->library('pagination');
                    $this->load->model('customers/clientlist');

                    $config['base_url'] = base_url('index.php/customers/cList');
                    $config['total_rows'] = $this->clientlist->count_list();
                    $config['per_page'] = 10;
                    $config['uri_segment'] = 3;

                    $this->pagination->initialize($config);
                    $results = $this->clientlist->full_list($config["per_page"]);

                    //Load the template.
                    $user_details = $this->login->user_details($id);
                    $view_info = array('username' => $user, 'details' => $user_details);
                    $header_info = array( 'title' => 'Registrera ny kund');
                    $this->load->view('template', array(
                        'view'          => 'customers/clist',
                        'view_info'     => $view_info,
                        'header_info'   => $header_info,
                        'footer_info'   => '',
                        'client_list'   => $results,
                        ));

Can you help me out and find what I have done wrong?
Thanks!


text:
Q: Adding a counter on html file in Angular I'm showing the restaurants that are filtered by the name and the address. (if no name or address is given then all restaurants are shown). The problem is that I need to add a counter to count the remaining restaurants after each filter or the count of all restaurants if no filtering is done.
The code I used (works perfectly):
(app-res-tabs is a component that shows the restaurant)

        <app-res-tabs [res]="res"></app-res-tabs>

How to add a counter for the restaurants in this code ?

A: You can add index to the *ngFor:

 It is index of restaurants {{ i }}

 It is counter of restaurants {{ i + 1 }}

UPDATE:
You can create a variable counter:
counter = this.restaurants.length;

this.searchForm.controls['str'].valueChanges.subscribe((value) => {
  this.searchString = value;
  this.counter = this.restaurants.filter(f =>
       f.Name.toLowerCase().includes(value.toLowerCase()
       || this.searchLength == false)
       && (f.Address == this.printedOption || this.checked == false)).length;
  if (this.searchString.length > 0) {
    this.searchLength = true;
  }
  else { this.searchLength = false }

});

HTML:

counter: {{ counter }}

{{res.Name}}

A work example at stackblitz.com

A: You can check this StackBlitz Link
You have to check remaining length of autocomplete results and actual data of length. You can use reactive forms here...
this.remainingResults = this.booksName.length -  data.length;

Go stackblitz link for complete example

A: You can try to create a function that will return the filtered values.
getData(data){
   return data.filter(item => item.includes(yourSearchString));
}

Update filter function as per your requirement.

<li
    {{i}}


text:
Q: Find the angle θ, such that... a) sinθ=0.8
b) cos2θ=-0.24
c) tanθ/2=2.1
We are allowed to use calculators to solve these kinds of questions, but I have problems of showing them with a general solution. That's what I've done:
a) sinθ=0.8
θ=53.13° +360° =k
θ=-53.13° +360° =k
b) COSθ= -0.24
θ=51.94°+360 °=k
θ=-51.94°+360°=k
c) tanθ/2=2.1
tanθ=4.2
θ=76.60 °
θ=76.60 °+360 °=k
Just not sure if I am doing the right things :/

A: a) Look at the unit circle where the line $y=0.8$ intersects the circle. Or consider that $\sin(-θ)=-\sin(θ)$.
b) the sign of $\cosθ$ is positive for $θ$ between $-90°$ and $90°$.
c) check if it is $\tan(θ)/2$ or $\tan(θ/2)$.


text:
Q: Getting ' object is not iterable Error in my code I'm getting "Type object is not iterable" error while running this code of my project in EucledianScore's for loop ->j in train_user..This code is for user-user collaborative filtering using the dataset from MovieLens.I've seen many "Type object is not iterable" problem's solution but those are not working for my code.
def user_collabo():
def EucledianScore(train_user, test_user):
    sum = 0
    count = 0
    for i in test_user:
        score = 0
        for j in train_user:
            if(int(i[1]) == int(j[1])):
                score= ((float(i[2])-float(j[2]))*(float(i[2])-float(j[2])))
                count= count + 1
            sum = sum + score
    if(count<4):
        sum = 1000000
    return(math.sqrt(sum))
data_cols=['user id','movie id','rating','timestamp']
item_cols=['movie id','movie title','release date',
'video release date','IMDb URL','unknown','Action',
'Adventure','Animation','Childrens','Comedy','Crime',
'Documentary','Drama','Fantasy','Film-Noir','Horror',
'Musical','Mystery','Romance ','Sci-Fi','Thriller',
'War' ,'Western']
user_cols = ['user id','age','gender','occupation',
'zip code']
users = pd.read_csv('u.user', sep='|', names=user_cols, encoding='latin-1')
item = pd.read_csv('u.item', sep='|', names=item_cols, encoding='latin-1')
data = pd.read_csv('u.data', sep='\t', names=data_cols, encoding='latin-1')
utrain = (data.sort_values('user id'))[:99832]
print(utrain.tail())
utest = (data.sort_values('user id'))[99833:]
print(utest.head())
utrain = utrain.as_matrix(columns = ['user id', 'movie id', 'rating'])
utest = utest.as_matrix(columns = ['user id', 'movie id', 'rating'])
users_list = []
for i in range(1,943):
    list1 = []
    for j in range(0,len(utrain)):
        if utrain[j][0] == i:
            list1.append(utrain[j])
        else:
            break
    utrain = utrain[j:]
    users_list.append(list1)
score_list = []
for i in range(0,942):
    score_list.append([i+1,EucledianScore(users_list[i], utest)])

score = pd.DataFrame(score_list, columns = ['user id','Eucledian Score'])
score = score.sort_values(by = 'Eucledian Score')
#print(score)
score_matrix = score.as_matrix()
user= int(score_matrix[0][0])
common_list = []
full_list = []
for i in utest:
    for j in users_list[user-1]:
        if(int(i[1])== int(j[1])):
            common_list.append(int(j[1]))
        full_list.append(j[1])

common_list = set(common_list)
full_list = set(full_list)
recommendation = full_list.difference(common_list)
item_list = (((pd.merge(item,data).sort_values(by = 'movie id')).groupby('movie title')))['movie id', 'movie title', 'rating']
item_list = item_list.mean()
item_list['movie title'] = item_list.index
item_list = item_list.as_matrix()
recommendation_list = []
for i in recommendation:
    recommendation_list.append(item_list[i-1])

recommendation = (pd.DataFrame(recommendation_list,columns = ['movie id','mean rating' ,'movie title'])).sort_values(by = 'mean rating', ascending = False)
print(recommendation[['mean rating','movie title']])

user_collabo()
Output:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-24f9c9703462> in <module>
     71         recommendation = (pd.DataFrame(recommendation_list,columns = ['movie id','mean rating' ,'movie title'])).sort_values(by = 'mean rating', ascending = False)
     72         print(recommendation[['mean rating','movie title']])
---> 73 user_collabo()

<ipython-input-20-24f9c9703462> in user_collabo()
     43         score_list = []
     44         for i in range(0,942):
---> 45                 score_list.append([i+1,EucledianScore(users_list[i], utest)])
     46
     47         score = pd.DataFrame(score_list, columns = ['user id','Eucledian Score'])

<ipython-input-20-24f9c9703462> in EucledianScore(train_users, test_user)
      5                 for i in test_user:
      6                         score = 0
----> 7                         for j in train_users:
      8                                 if(int(i[1]) == int(j[1])):
      9                                         score= ((float(i[2])-float(j[2]))*(float(i[2])-float(j[2])))

TypeError: 'type' object is not iterable

A: The error comes from this line:
users_list.append(list)

This appends the python builtin type list. I think you meant users_list.append(list1). This will build up users_list into a list of lists.


text:
Q: Git with Blink1 feedback I just bought a Blink1 lately and I'm trying to integrate it with Git.
alias git='function __git() {
    OUTPUT="$(blink1-tool --list)"
    EXPECTED="no blink(1) devices found"

    git "$@"

    if ! [ "$OUTPUT" = "$EXPECTED" ]
    then
        if [ $? = 0 ]
        then
            blink1-tool --green --blink 1
        else
            blink1-tool --red
        fi
    fi
}; __git'

However, when I make a new in my iTerm, it blinks before any git commands. And if I execute a command like git status, it blinks 4 times, but I only see 1 log of the blink:
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
blink 1 times rgb:0,ff,0:
set dev:0:0 to rgb:0x00,0xff,0x00 over 300 msec
set dev:0:0 to rgb:0x00,0x00,0x00 over 300 msec


text:
Q: How to run a function before jQuery validate plugin does the validation? I'm using the jQuery validation plugin. I need to remove some design elements from the form before validation occurs (long story). Anyway I can't find any methods that will allow me to do this. The closest I found is the submitHandler option:
http://jqueryvalidation.org/validate/#submithandler
But this fires after validation right before the form is submitted by the plugin if the validation is successful. I need to do some things before the validation even occurs that need to fire whether the  form validated successfully or not. Is there an option for this plugin that allows for that?

A: Not entirely sure what you're asking, but if by "validation", you mean when the messages are displayed, you can use these callback functions to get out in front of those.
The highlight and unhighlight callback functions toggle the error/valid classes on the input elements and labels.  You can over-ride these to do whatever you want.
The errorPlacement callback function is what places the message for each element.  Again, you can override this to do whatever you want.  (You could prevent the placement of messages until your "other things" are done.)

The invalidHandler callback function is the opposite of the submitHandler and it fires upon submit when the form is invalid.
Refer to documentation for all callback functions:  http://jqueryvalidation.org/validate/


text:
Q: How to replace all whitespace between quotes that start with specific string with underscore in VSCode? I have the following string:
this is a sample id="aaa bbb ccc" name="abc abc"

I want to match only the whitespace between quotes that start with the string "id=" and replace all occurrences with underscore. The result string should look like:
this is a sample id="aaa_bbb_ccc" name="abc abc"

The following regex matches all whitespace between quotes, but it doesn't take into account the fact that the quotes must be preceded by "id="
\s(?=[^"]*"[^"]*(?:"[^"]*"[^"]*)*$)

Quotes inside quotes are not possible.

A: Since starting with VS Code 1.31, infinite-width lookbehinds are supported,  you may use
(?<=\bid="[^"]*?)\s

Or, to make sure there actually is a " after the whitespace,
(?<=\bid="[^"]*?)\s(?=[^"]*")

Replace with _.
See the regex demo online. Details:

*

*(?<=\bid="[^"]*?) - a positive lookbehind that matches a location that is immediately preceded with

*

*\b - word boundary

*id=" - a literal id=" string

*[^"]*? - any 0 or more chars other than ", as few as possible (due to *? non-greedy quantifier)

*\s - a whitespace

*(?=[^"]*") - a positive lookahead that matches a location immediately followed with any 0+ chars other than " (with [^"]* pattern) and then a ".

See the proof it works in VSCode:


text:
Q: Adjustments needed in a Rails app to use Datamapper instead of ActiveRecord I am trying to use Datamapper in a Rails app as an alternative to ActiveRecord.
I've followed the various setup instructions and have Datamapper working in my app.
But one of the first things I noticed that no longer works is this:
  <%= f.error_messages %>

I believe this is tied to an ActiveRecord helper - is there an alternative way of reporting validation failures in the View for Datamapper?
Am I likely to encounter many more examples of functionality like this that will require adjustments in my app?
Is this project doable or is it likely to involve a lot of complicated hackery?
Has anyone documented all of the required application adjustments?
I suspect Datamapper is not used widely because I'm finding it hard to find these kinds of simple instructions on Google.

A: Today Rails plays well with ActiveRecord; changing ORM will surely give you some troubles. Rails 3.0 will be ORM agnostic so I expect a switch like the one you are describing to be easier in the future.
Unless you are craving to understand Rails inside-out and you are going to have the time to fix the glitches that your application will expose, stick with ActiveRecord.

Am I likely to encounter many more examples of functionality like this that will require adjustments in my app?

It depends on the code you have already wrote. For what you have reported in your question I'd say yes.

Is this project doable or is it likely to involve a lot of complicated hackery?

It is doable and will involve a lot of complicated hackery. The downside is that most of what you are going to learn from this hackery will be likely outdated by Rails 3.0.


text:
Q: File with input/output error on SSD My laptop generally works fine. However I have, as far as I can tell, a single file that gives me an input/output error when I try to copy it:
$ cp badfile badfile.copy
cp: error reading 'badfile': Input/output error

In /var/log/syslog I see this:

blk_update_request: critical medium error, dev nvme0n1, sector
468307904 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 0

My SSD is less than a year old, so if it's failing I can get a replacement. The thing is, I bought the laptop without an operating system, so I need to be able to prove that it's a hardware problem. How can I do that?
I've tried doing a filesystem check on the disk from a bootable USB, and it couldn't find anything wrong with it. smartctl doesn't look wrong, but my eye is untrained: what should I be looking for?


text:
Q: JavaFX -- ChangeLisener Issues and Opening Scene From Within a Scene I'm writing to get some information regarding JavaFX. I have designed an application using SceneBuilder that has a primary scene consisting of a few text fields and buttons used to browse for files. There is also a text area used for output once the program has been run. I have added change listeners within the initialize method of the Controller so that when the output text area is updated a log file gets modified.
Initially I tested this using the output text area to display the log file. I was able to get everything working correctly with it logging and displaying the log in this output text area once I select a 'view log' menu item from the main File menu. I ran into an issue that didn't seem very cleanly solved where when I displayed the Log it wanted to also log that display. I couldn't think of a clean work around for this and decided I would rather have the log open in its own secondary popup scene.
One of my issues is that if I place a change listener on the output text area inside the Controller's initialize method, when I try to 'view log' it throws a null pointer exception and points me to the line where the change listener is added. But please note that although it throws this exception trying to open the log window the change listeners and output text area still work appropriately.
If I remove the change listener the window opens fine - but nothing is updated within the logFileOutputTextArea.
Controller File:
public class AppController implements Initializable
{
    @FXML
    private TextArea logFileOutputTextArea;

    @Override
    public void initialize(URL url, ResourceBundle rb)
    {

        verifierOutputTextArea.textProperty().addListener(new ChangeListener<String>()
        {
            @Override
            public void changed(ObservableValue<? extends String> ov, String t, String t1)
            {
                // IF we have a valid file
                if (verifierOutputTextArea.textProperty().getValue().equals("Valid"))
                {
                  openOutputFolderButton.visibleProperty().setValue(!openOutputFolderButton.visibleProperty()
                        .getValue());
                }

            }
        });

        verifierOutputTextArea.textProperty().addListener(new ChangeListener<String>()
        {
            @Override
            public void changed(ObservableValue<? extends String> ov, String t, String t1)
            {
                appendLog(verifierOutputTextArea.textProperty().getValue());    // append the output to the log

            }
        });

        // Check for a preset input file location
        checkDefaultInputDirectory();

    } // END INITIALIZE

    @FXML
    private void openLog()
    {

        try
        {
            Stage dialogStage = new Stage();

            Parent root = FXMLLoader.load(getClass().getResource("fxml/logwindow.fxml"));

            Scene scene = new Scene(root);

            dialogStage.setScene(scene);
            dialogStage.setTitle("Log");
            dialogStage.show();
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }

        Path logFilePath = Paths.get(StaticTools.LOG_FILE_LOCATION);

        // IF the file doesn't exist
        if (!Files.exists(logFilePath))
        {
            this.logFileOutputTextArea.textProperty().setValue("Log has not been created yet!");
        }
        else
        {
            try
            {
                byte[] fileByteArray = Files.readAllBytes(logFilePath);

                this.logFileOutputTextArea.setText(StaticTools.cryptTool(new String(fileByteArray), Cipher.DECRYPT_MODE));

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

    } // END OPENLOG

} // END CONTROLLER

Log Window .fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.*?>
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" minHeight="-Infinity" minWidth="-Infinity" prefHeight="304.0"
        prefWidth="478.0" xmlns="http://javafx.com/javafx/8"
      fx:controller="application.javafx.AppController">
    <children>
        <GridPane layoutX="14.0" layoutY="22.0" prefHeight="269.0" prefWidth="446.0">
            <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0"/>
            </columnConstraints>
            <rowConstraints>
                <RowConstraints maxHeight="-Infinity" minHeight="-Infinity" prefHeight="20.0" vgrow="SOMETIMES"/>
                <RowConstraints vgrow="SOMETIMES"/>
            </rowConstraints>
            <children>
                <Label text="Log File">
                    <padding>
                        <Insets bottom="5.0"/>
                    </padding>
                </Label>
                <TextArea fx:id="logFileOutputTextArea" editable="false" prefHeight="200.0" prefWidth="200.0"
                          wrapText="true" GridPane.rowIndex="1"/>
            </children>
        </GridPane>
    </children>
</AnchorPane>

Do I need a separate controller for each fxml file? Why does placing initialize statements and change listeners into the initialize method cause issues? Why after the output text area in the main scene has been modified, either by clearing the text or setting the text, does alt-tabbing to a different window throw java.lang.IllegalArgumentException: argument type mismatch exceptions every time?
Thank you for your time!

A: You seem to be trying to use one controller class for two different fxml files: LogWindow.fxml and some other fxml file which invokes showLog() by means of an event handler on a menu item.
If this is the case, you are going to end up with two instances of the controller: one created by the FXMLLoader that loads the "main" fxml, and one created by the FXMLLoader that loads LogWindow.fxml. The showLog() method is being invoked on the instance created by the "main" fxml, so it will populate the text area defined in the "main" fxml (if there is one, else you will likely get a null pointer exception). This of course is not the text area in LogWindow.fxml, so the text will not be displayed there.
You probably want to create a separate controller class for LogWindow.fxml, and populate the text area in its initialize() method.


text:
Q: JavaScript Closures - Using the ECMA Spec, please explain how the closure is created and maintained I'm reading about JavaScript closures.  I'm familiar with Execution Contexts, how the Lexical Environment is maintained, and very familiar with Lexical Scoping.
I want to know how closures in JavaScript are created and maintained. Sometimes it's hard for me to grasp such important concepts without knowing how it is actually doing it.  I know that, according to Wikipedia, a closure is

is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function.

But my question is, I want to know how, according to the ECMA Specification, that a closure is created and maintained.  I'm not looking for a high-level explanation of closure theory, please reference the ECMA Specification in your answer.
Note:  Please do not consider this a duplicate, unless the answer explains a closure using the ECMA Specification.  Again, I'm not interested in someone quoting wikipedia and giving an example, I want to fully understand how JavaScript does this.  (I'm familiar with this question on SO).

A: According to the Wikipedia definition, as mentioned in the question, a closure is a

is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function.

The understanding of how execution contexts and lexical environments are maintained is known and the goal here is to understand when a function is returned, how is that referencing environment maintained/referenced?
Let's begin.
In section 8.6.2 on the ECMA 262 v 5 specification, it lists the internal properties of ECMAScript objects.  The one to point out here is in table 9, the [[Scope]] property.  According to the description of this property, it is described as

A lexical environment that defines the environment in which a Function object is executed. Of the standard built-in ECMAScript objects, only Function objects implement [[Scope]].

As we will see, the [[Scope]] property of a function object will always be set to the parent's lexical environment.  We see this mentioned in section 13.2 which talks about the process of creating a function object.  (Please note: function object in this context is referring to a native ECMAScript object, and not the accessible function object through code).
When a function is created, it sets the internal [[Scope]] property to the VariableEnvironment, LexicalEnvironment or Global Environment of the running execution context, depending on if the function is a function declaration, function expression or created through the Function constructor.
When control is given over to the global code, as well as when control enters function code, declaration binding instantiation occurs as part of initializing the execution context.  Part of the declaration binding instantiation is to bind the function declarations within the scope of the current context by creating the function objects as mentioned in section 13.2.  The below example shows this:
For example
  // The global execution context has already been initialized at this stage.
  // Declaration binding instantiation has occurred and the function
  // foo is created as a new native object with a [[Scope]] property
  // having the value of the global execution context's VariableEnvironment
  function foo() {
    // When foo is invoked, a new execution context will be created for
    // this function scope.  When declaration binding instantiation occurs,
    // bar will be created as a new native object with a [[Scope]] property
    // having the value of the foo execution context's VariableEnvironment
    function bar() {
      }
    bar(); // Call bar
  }
  foo();

Another thing to look is the process that occurs upon entering/creating the execution context when entering a function. Below is a summary of what happens.

*

*Create a new Lexical Environment type by internally calling  NewDeclarativeEnvironment.  The [[Scope]] property of the function will be set as the outer reference in order for the "Lexical Environment" chain to be maintained.  (Remember that the [[Scope]] property was set and will always be the parent's lexical scope.  Also, Lexical Environment chain is a phrase I made up, the concept referring to resolving identifiers by traversing the Lexical Environments through outer references until the identifier can be resolved.)

*Set the LexicalEnvironment and VariableEnvironment to the newly created Lexical Environment in step 1.

*Perform declaration binding instantiation.
With the knowledge that a function maintains a reference to it's parent Lexical Environment through the internal [[Scope]] property, we can now see how closures work.
<script>
// foo.[[Scope]] was set to the global environment during the global execution context initialization
  function foo() {
    var x = 1;
    // bar.[[Scope]] was set to foo's lexical environment during foo's execution context initialization
    function bar() {
      var y = 2;
      alert(x + y);
    }
    return bar;
  }

   var dummy = foo(); // Assign variable binding "dummy" to a reference of the "bar" function.
   dummy(); // Calls the "bar" function code.  The reference still has it's [[Scope]] property set, thus the identifier look-ups work as expected when resolving the identifiers.
   alert(dummy.name); // Alerts "bar";

</script>

So to answer the question, a functions parent LexicalEnvironment is persisted through the internal [[Scope]] property of the function.  Note that local variables within the function can be resolved when the function is run, only "free variables" need to be tracked and are done so by the [[Scope]] property.
Note:  Please, if my information is incorrect, comment below.


text:
Q: Change platform in OpenCL sample I am trying to run an OpenCL sample on a platform that is different than the one in sample program. The sample is for PowerVR and I want to run on Adreno gpu.So I have added the appropriate libOpencl.so file.But i m getting error while running::
What other changes i should make?
    02-18 08:59:04.207: I/Debug(19668): OpenCL lib Loaded
    02-18 08:59:04.216: E/art(19668): dlopen("/data/app/com.example.inversefilter-1/lib/arm/libInverseFilter.so", RTLD_LAZY) failed: dlopen failed: could not load library "jni/../external/libPVROCL.so" needed by "libInverseFilter.so"; caused by library "jni/../external/libPVROCL.so" not found
02-18 08:59:04.338: I/art(19668): Background sticky concurrent mark sweep GC freed 1703(98KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 11MB/11MB, paused 5.199ms total 38.674ms
02-18 08:59:04.496: I/Debug(19668): 853
02-18 08:59:04.496: I/DEBUG(19668): BEFORE runOpencl
02-18 08:59:04.498: E/art(19668): No implementation found for void com.example.inversefilter.MainActivity.initOpenCL(java.lang.String) (tried Java_com_example_inversefilter_MainActivity_initOpenCL and Java_com_example_inversefilter_MainActivity_initOpenCL__Ljava_lang_String_2)
02-18 08:59:04.498: D/AndroidRuntime(19668): Shutting down VM
02-18 08:59:04.509: E/AndroidRuntime(19668): FATAL EXCEPTION: main
02-18 08:59:04.509: E/AndroidRuntime(19668): Process: com.example.inversefilter, PID: 19668
02-18 08:59:04.509: E/AndroidRuntime(19668): java.lang.UnsatisfiedLinkError: No implementation found for void com.example.inversefilter.MainActivity.initOpenCL(java.lang.String) (tried Java_com_example_inversefilter_MainActivity_initOpenCL and Java_com_example_inversefilter_MainActivity_initOpenCL__Ljava_lang_String_2)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at com.example.inversefilter.MainActivity.initOpenCL(Native Method)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at com.example.inversefilter.MainActivity.onCreate(MainActivity.java:91)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.app.Activity.performCreate(Activity.java:5953)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.app.ActivityThread.access$800(ActivityThread.java:148)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.os.Handler.dispatchMessage(Handler.java:102)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.os.Looper.loop(Looper.java:135)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at android.app.ActivityThread.main(ActivityThread.java:5312)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at java.lang.reflect.Method.invoke(Native Method)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at java.lang.reflect.Method.invoke(Method.java:372)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
02-18 08:59:04.509: E/AndroidRuntime(19668):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
02-18 08:59:07.510: I/Process(19668): Sending signal. PID: 19668 SIG: 9

My cpp file is given below:
#include <jni.h>
#include <android/bitmap.h>
#include <android/log.h>

#include <string>
#include <cstring>
#include <sstream>
#include <vector>

/*
 * needed for loadProgram function
 */
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>

#include <sys/time.h>

#include <CL/cl.h>

// Commonly-defined shortcuts for LogCat output from native C applications.
#define  LOG_TAG    "AndroidBasic"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)

/* Container for all OpenCL-specific objects used in the sample.
 *
 * The container consists of the following parts:
 *   - Regular OpenCL objects, used in almost each
 *     OpenCL application.
 *   - Specific OpenCL objects - buffers, used in this
 *     particular sample.
 *
 * For convenience, collect all objects in one structure.
 * Avoid global variables and make easier the process of passing
 * all arguments in functions.
 */
struct OpenCLObjects
{
    // Regular OpenCL objects:
    cl_platform_id platform;
    cl_device_id device;
    cl_context context;
    cl_command_queue queue;
    cl_program program;
    cl_kernel kernel;

    // Objects that are specific for this sample.
    bool isInputBufferInitialized;
    cl_mem inputBuffer;
    cl_mem outputBuffer;
};

// Hold all OpenCL objects.
OpenCLObjects openCLObjects;

/*
 * Load the program out of the file in to a string for opencl compiling.
 */
inline std::string loadProgram(std::string input)
{
    std::ifstream stream(input.c_str());
    if (!stream.is_open()) {
        LOGE("Cannot open input file\n");
        exit(1);
    }
    return std::string( std::istreambuf_iterator<char>(stream),
                        (std::istreambuf_iterator<char>()));
}

/* This function helps to create informative messages in
 * case when OpenCL errors occur. The function returns a string
 * representation for an OpenCL error code.
 * For example, "CL_DEVICE_NOT_FOUND" instead of "-1".
 */
const char* opencl_error_to_str (cl_int error)
{
#define CASE_CL_CONSTANT(NAME) case NAME: return #NAME;

    // Suppose that no combinations are possible.
    switch(error)
    {
        CASE_CL_CONSTANT(CL_SUCCESS)
        CASE_CL_CONSTANT(CL_DEVICE_NOT_FOUND)
        CASE_CL_CONSTANT(CL_DEVICE_NOT_AVAILABLE)
        CASE_CL_CONSTANT(CL_COMPILER_NOT_AVAILABLE)
        CASE_CL_CONSTANT(CL_MEM_OBJECT_ALLOCATION_FAILURE)
        CASE_CL_CONSTANT(CL_OUT_OF_RESOURCES)
        CASE_CL_CONSTANT(CL_OUT_OF_HOST_MEMORY)
        CASE_CL_CONSTANT(CL_PROFILING_INFO_NOT_AVAILABLE)
        CASE_CL_CONSTANT(CL_MEM_COPY_OVERLAP)
        CASE_CL_CONSTANT(CL_IMAGE_FORMAT_MISMATCH)
        CASE_CL_CONSTANT(CL_IMAGE_FORMAT_NOT_SUPPORTED)
        CASE_CL_CONSTANT(CL_BUILD_PROGRAM_FAILURE)
        CASE_CL_CONSTANT(CL_MAP_FAILURE)
        CASE_CL_CONSTANT(CL_MISALIGNED_SUB_BUFFER_OFFSET)
        CASE_CL_CONSTANT(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST)
        CASE_CL_CONSTANT(CL_INVALID_VALUE)
        CASE_CL_CONSTANT(CL_INVALID_DEVICE_TYPE)
        CASE_CL_CONSTANT(CL_INVALID_PLATFORM)
        CASE_CL_CONSTANT(CL_INVALID_DEVICE)
        CASE_CL_CONSTANT(CL_INVALID_CONTEXT)
        CASE_CL_CONSTANT(CL_INVALID_QUEUE_PROPERTIES)
        CASE_CL_CONSTANT(CL_INVALID_COMMAND_QUEUE)
        CASE_CL_CONSTANT(CL_INVALID_HOST_PTR)
        CASE_CL_CONSTANT(CL_INVALID_MEM_OBJECT)
        CASE_CL_CONSTANT(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR)
        CASE_CL_CONSTANT(CL_INVALID_IMAGE_SIZE)
        CASE_CL_CONSTANT(CL_INVALID_SAMPLER)
        CASE_CL_CONSTANT(CL_INVALID_BINARY)
        CASE_CL_CONSTANT(CL_INVALID_BUILD_OPTIONS)
        CASE_CL_CONSTANT(CL_INVALID_PROGRAM)
        CASE_CL_CONSTANT(CL_INVALID_PROGRAM_EXECUTABLE)
        CASE_CL_CONSTANT(CL_INVALID_KERNEL_NAME)
        CASE_CL_CONSTANT(CL_INVALID_KERNEL_DEFINITION)
        CASE_CL_CONSTANT(CL_INVALID_KERNEL)
        CASE_CL_CONSTANT(CL_INVALID_ARG_INDEX)
        CASE_CL_CONSTANT(CL_INVALID_ARG_VALUE)
        CASE_CL_CONSTANT(CL_INVALID_ARG_SIZE)
        CASE_CL_CONSTANT(CL_INVALID_KERNEL_ARGS)
        CASE_CL_CONSTANT(CL_INVALID_WORK_DIMENSION)
        CASE_CL_CONSTANT(CL_INVALID_WORK_GROUP_SIZE)
        CASE_CL_CONSTANT(CL_INVALID_WORK_ITEM_SIZE)
        CASE_CL_CONSTANT(CL_INVALID_GLOBAL_OFFSET)
        CASE_CL_CONSTANT(CL_INVALID_EVENT_WAIT_LIST)
        CASE_CL_CONSTANT(CL_INVALID_EVENT)
        CASE_CL_CONSTANT(CL_INVALID_OPERATION)
        CASE_CL_CONSTANT(CL_INVALID_GL_OBJECT)
        CASE_CL_CONSTANT(CL_INVALID_BUFFER_SIZE)
        CASE_CL_CONSTANT(CL_INVALID_MIP_LEVEL)
        CASE_CL_CONSTANT(CL_INVALID_GLOBAL_WORK_SIZE)
        CASE_CL_CONSTANT(CL_INVALID_PROPERTY)

    default:
        return "UNKNOWN ERROR CODE";
    }

#undef CASE_CL_CONSTANT
}

/* The following macro is used after each OpenCL call
 * to check if OpenCL error occurs. In the case when ERR != CL_SUCCESS
 * the macro forms an error message with OpenCL error code mnemonic,
 * puts it to LogCat, and returns from a caller function.
 *
 * The approach helps to implement consistent error handling tactics
 * because it is important to catch OpenCL errors as soon as
 * possible to avoid missing the origin of the problem.
 *
 * You may chose a different way to do that. The macro is
 * simple and context-specific as it assumes you use it in a function
 * that doesn't have a return value, so it just returns in the end.
 */
#define SAMPLE_CHECK_ERRORS(ERR)                                                      \
    if(ERR != CL_SUCCESS)                                                             \
    {                                                                                \
        LOGE                                                                          \
        (                                                                             \
            "OpenCL error with code %s happened in file %s at line %d. Exiting.\n",   \
            opencl_error_to_str(ERR), __FILE__, __LINE__                              \
        );                                                                            \
                                                                                \
        return;                                                                       \
    }

void initOpenCL
(
    JNIEnv* env,
    jobject thisObject,
    jstring kernelName,
    cl_device_type required_device_type,
    OpenCLObjects& openCLObjects
)
{
    /*
     * This function picks and creates all necessary OpenCL objects
     * to be used at each filter iteration. The objects are:
     * OpenCL platform, device, context, command queue, program,
     * and kernel.
     *
     * Almost all of these steps need to be performed in all
     * OpenCL applications before the actual compute kernel calls
     * are performed.
     *
     * For convenience, in this application all basic OpenCL objects
     * are stored in the OpenCLObjects structure,
     * so, this function populates fields of this structure,
     * which is passed as parameter openCLObjects.
     * Consider reviewing the fields before going further.
     * The structure definition is in the beginning of this file.
     */

    using namespace std;

    // Will be used at each effect iteration,
    // and means that you haven't yet initialized
    // the inputBuffer object.
    openCLObjects.isInputBufferInitialized = false;

    // Search for the Intel OpenCL platform.
    // Platform name includes "Intel" as a substring, consider this
    // method to be a recommendation for Intel OpenCL platform search.
    const char* required_platform_subname = "PowerVR";

    // The following variable stores return codes for all OpenCL calls.
    // In the code it is used with the SAMPLE_CHECK_ERRORS macro defined
    // before this function.
    cl_int err = CL_SUCCESS;

    /* -----------------------------------------------------------------------
     * Step 1: Query for all available OpenCL platforms on the system.
     * Enumerate all platforms and pick one which name has
     * required_platform_subname as a sub-string.
     */

    cl_uint num_of_platforms = 0;
    // Get total number of the available platforms.
    err = clGetPlatformIDs(0, 0, &num_of_platforms);
    SAMPLE_CHECK_ERRORS(err);
    LOGD("Number of available platforms: %u", num_of_platforms);

    vector<cl_platform_id> platforms(num_of_platforms);
    // Get IDs for all platforms.
    err = clGetPlatformIDs(num_of_platforms, &platforms[0], 0);
    SAMPLE_CHECK_ERRORS(err);

    //cl_uint selected_platform_index = num_of_platforms;

    LOGD("Platform names:");

    cl_uint i = 0;
        // Get the length for the i-th platform name.
        size_t platform_name_length = 0;
        err = clGetPlatformInfo(
            platforms[i],
            CL_PLATFORM_NAME,
            0,
            0,
            &platform_name_length
        );
        SAMPLE_CHECK_ERRORS(err);

        // Get the name itself for the i-th platform.
        vector<char> platform_name(platform_name_length);
        err = clGetPlatformInfo(
            platforms[i],
            CL_PLATFORM_NAME,
            platform_name_length,
            &platform_name[0],
            0
        );
        SAMPLE_CHECK_ERRORS(err);

    //selected_platform_index = 0;
    openCLObjects.platform = platforms[0];

    /* -----------------------------------------------------------------------
     * Step 2: Create context with a device of the specified type.
     * Required device type is passed as function argument required_device_type.
     * Use this function to create context for any CPU or GPU OpenCL device.
     */

    cl_context_properties context_props[] = {
        CL_CONTEXT_PLATFORM,
        cl_context_properties(openCLObjects.platform),
        0
    };

    openCLObjects.context =
        clCreateContextFromType
        (
            context_props,
            required_device_type,
            0,
            0,
            &err
        );
    SAMPLE_CHECK_ERRORS(err);

    /* -----------------------------------------------------------------------
     * Step 3: Query for OpenCL device that was used for context creation.
     */

    err = clGetContextInfo
    (
        openCLObjects.context,
        CL_CONTEXT_DEVICES,
        sizeof(openCLObjects.device),
        &openCLObjects.device,
        0
    );
    SAMPLE_CHECK_ERRORS(err);

    /* -----------------------------------------------------------------------
     * Step 4: Create OpenCL program from its source code.
     * The file name is passed bij java.
     * Convert the jstring to const char* and append the needed directory path.
     */
    const char* fileName = env->GetStringUTFChars(kernelName, 0);
    std::string fileDir;
    fileDir.append("/data/data/com.example.inversefilter/app_execdir/");
    fileDir.append(fileName);
    fileDir.append(".cl");
    std::string kernelSource = loadProgram(fileDir);
    //std::string to const char* needed for the clCreateProgramWithSource function
    const char* kernelSourceChar = kernelSource.c_str();

    openCLObjects.program =
        clCreateProgramWithSource
        (
            openCLObjects.context,
            1,
            &kernelSourceChar,
            0,
            &err
        );

    SAMPLE_CHECK_ERRORS(err);

    /* -----------------------------------------------------------------------
     * Step 5: Build the program.
     * During creation a program is not built. Call the build function explicitly.
     * This example utilizes the create-build sequence, still other options are applicable,
     * for example, when a program consists of several parts, some of which are libraries.
     * Consider using clCompileProgram and clLinkProgram as alternatives.
     * Also consider looking into a dedicated chapter in the OpenCL specification
     * for more information on applicable alternatives and options.
     */

    err = clBuildProgram(openCLObjects.program, 0, 0, 0, 0, 0);

    if(err == CL_BUILD_PROGRAM_FAILURE)
    {
        size_t log_length = 0;
        err = clGetProgramBuildInfo(
            openCLObjects.program,
            openCLObjects.device,
            CL_PROGRAM_BUILD_LOG,
            0,
            0,
            &log_length
        );
        SAMPLE_CHECK_ERRORS(err);

        vector<char> log(log_length);

        err = clGetProgramBuildInfo(
            openCLObjects.program,
            openCLObjects.device,
            CL_PROGRAM_BUILD_LOG,
            log_length,
            &log[0],
            0
        );
        SAMPLE_CHECK_ERRORS(err);

        LOGE
        (
            "Error happened during the build of OpenCL program.\nBuild log:%s",
            &log[0]
        );

        return;
    }

    /* -----------------------------------------------------------------------
     * Step 6: Extract kernel from the built program.
     * An OpenCL program consists of kernels. Each kernel can be called (enqueued) from
     * the host part of an application.
     * First create a kernel to call it from the existing program.
     * Creating a kernel via clCreateKernel is similar to obtaining an entry point of a specific function
     * in an OpenCL program.
     */

    openCLObjects.kernel = clCreateKernel(openCLObjects.program, "inverseKernel", &err);
    SAMPLE_CHECK_ERRORS(err);

    /* -----------------------------------------------------------------------
     * Step 7: Create command queue.
     * OpenCL kernels are enqueued for execution to a particular device through
     * special objects called command queues. Command queue provides ordering
     * of calls and other OpenCL commands.
     * This sample uses a simple in-order OpenCL command queue that doesn't
     * enable execution of two kernels in parallel on a target device.
     */

    openCLObjects.queue =
        clCreateCommandQueue
        (
            openCLObjects.context,
            openCLObjects.device,
            0,    // Creating queue properties, refer to the OpenCL specification for details.
            &err
        );
    SAMPLE_CHECK_ERRORS(err);

    // -----------------------------------------------------------------------

    LOGD("initOpenCL finished successfully");
}

extern "C" void Java_com_example_inversefilter_MainActivity_initOpenCL
(
    JNIEnv* env,
    jobject thisObject,
    jstring kernelName
)
{
    initOpenCL
    (
        env,
        thisObject,
        kernelName,
        CL_DEVICE_TYPE_GPU,
        openCLObjects
    );
}

void shutdownOpenCL (OpenCLObjects& openCLObjects)
{

    cl_int err = CL_SUCCESS;

    if(openCLObjects.isInputBufferInitialized)
    {
        err = clReleaseMemObject(openCLObjects.inputBuffer);
        SAMPLE_CHECK_ERRORS(err);
    }

    err = clReleaseKernel(openCLObjects.kernel);
    SAMPLE_CHECK_ERRORS(err);

    err = clReleaseProgram(openCLObjects.program);
    SAMPLE_CHECK_ERRORS(err);

    err = clReleaseCommandQueue(openCLObjects.queue);
    SAMPLE_CHECK_ERRORS(err);

    err = clReleaseContext(openCLObjects.context);
    SAMPLE_CHECK_ERRORS(err);

}

extern "C" void Java_com_example_inversefilter_MainActivity_shutdownOpenCL
(
    JNIEnv* env,
    jobject thisObject
)
{
    shutdownOpenCL(openCLObjects);
    LOGD("shutdownOpenCL(openCLObjects) was called");
}

/*
 * Effect step.
 * This function is called each time you need to process the image.
 *
 * The function consists of the following parts:
 *   - reading input image content if changed
 *   - running OpenCL kernel on the input image
 *   - reading results of image processing
 */
void nativeInverseOpenCL
(
    JNIEnv* env,
    jobject thisObject,
    OpenCLObjects& openCLObjects,
    jobject inputBitmap,
    jobject outputBitmap
)
{
    using namespace std;

    AndroidBitmapInfo bitmapInfo;
    AndroidBitmap_getInfo(env, inputBitmap, &bitmapInfo);

    size_t bufferSize = bitmapInfo.height * bitmapInfo.stride;

    cl_uint rowPitch = bitmapInfo.stride / 4;
        cl_int err = CL_SUCCESS;

    // In this application the input buffer is allocated and initialized on demand
    // with the first call or when the Java side requests an update of the input image.

        if(openCLObjects.isInputBufferInitialized)
        {

            err = clReleaseMemObject(openCLObjects.inputBuffer);
            SAMPLE_CHECK_ERRORS(err);
        }

        LOGD("Creating input buffer in OpenCL");

        void* inputPixels = 0;
        AndroidBitmap_lockPixels(env, inputBitmap, &inputPixels);

        openCLObjects.inputBuffer =
            clCreateBuffer
            (
                openCLObjects.context,
                CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
                bufferSize,   // Buffer size in bytes.
                inputPixels,  // Bytes for initialization.
                &err
            );
        SAMPLE_CHECK_ERRORS(err);

        openCLObjects.isInputBufferInitialized = true;

        // Do not forget to unlock pixels in the bitmap object.
        AndroidBitmap_unlockPixels(env, inputBitmap);

    void* outputPixels = 0;
    AndroidBitmap_lockPixels(env, outputBitmap, &outputPixels);

    cl_mem outputBuffer =
        clCreateBuffer
        (
            openCLObjects.context,
            CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
            bufferSize,    // Buffer size in bytes, same as the input buffer.
            outputPixels,  // Area, above which the buffer is created.
            &err
        );
    SAMPLE_CHECK_ERRORS(err);

    err = clSetKernelArg(openCLObjects.kernel, 0, sizeof(openCLObjects.inputBuffer), &openCLObjects.inputBuffer);
    SAMPLE_CHECK_ERRORS(err);

    err = clSetKernelArg(openCLObjects.kernel, 1, sizeof(outputBuffer), &outputBuffer);
    SAMPLE_CHECK_ERRORS(err);

    err = clSetKernelArg(openCLObjects.kernel, 2, sizeof(cl_uint), &rowPitch);
    SAMPLE_CHECK_ERRORS(err);

    /* Define the global iteration space for clEnqueueNDRangeKernel.
     * Every work-item running a kernel processes a single pixel
     * in the image. The global iteration space (globalSize)
     * is two-dimensional and exactly matches the image dimensions.
     *
     * To learn more about the OpenCL NDRange and find details on how
     * kernels are executed on OpenCL devices, refer to the
     * OpenCL specification, chapter 3.2 Execution Model.
     */
    size_t globalSize[2] = { bitmapInfo.width, bitmapInfo.height };

    timeval start;
    timeval end;

    gettimeofday(&start, NULL);

    err =
        clEnqueueNDRangeKernel
        (
            openCLObjects.queue,
            openCLObjects.kernel,
            2,
            0,
            globalSize,
            0,
            0, 0, 0
        );
    SAMPLE_CHECK_ERRORS(err);

    err = clFinish(openCLObjects.queue);
    SAMPLE_CHECK_ERRORS(err);

    gettimeofday(&end, NULL);

    float ndrangeDuration =
        (end.tv_sec + end.tv_usec * 1e-6) - (start.tv_sec + start.tv_usec * 1e-6);

    LOGD("NDRangeKernel time: %f", ndrangeDuration);
    err = clEnqueueReadBuffer (openCLObjects.queue,
            outputBuffer,
            true,
            0,
            bufferSize,
            outputPixels,
            0,
            0,
            0);
    SAMPLE_CHECK_ERRORS(err);

    // Call clFinish to guarantee that the output region is updated.
    err = clFinish(openCLObjects.queue);
    SAMPLE_CHECK_ERRORS(err);

    err = clReleaseMemObject(outputBuffer);
    SAMPLE_CHECK_ERRORS(err);

    AndroidBitmap_unlockPixels(env, outputBitmap);

    LOGD("nativeInverseOpenCL ends successfully");
}

extern "C" void Java_com_example_inversefilter_MainActivity_nativeInverseOpenCL
(
    JNIEnv* env,
    jobject thisObject,
    jobject inputBitmap,
    jobject outputBitmap
)
{
    nativeInverseOpenCL
    (
        env,
        thisObject,
        openCLObjects,
        inputBitmap,
        outputBitmap
    );
}

Can anyone help?


text:
Q: video capture software for iPhone Simulator HI All,
I m looking for a software/tool, which can lead me to capture my application in simulator..
I saw so many videos of application, which performs their functionality of application and capture it in video.
Please suggest me some video capturing tool for my app promotion.
Suggestions are always appreciated.
regards

A: As I could not find any tool fitting my needs, I made my own tool : WhazzerFinger.
You can download it (sources or binary) here: https://github.com/zippy1978/WhazzerFinger.
The application adds an overlay on top of the actual simulator window to give it a more realistic look. At the moment only iPhone is supported in portrait or landscape mode. iPad should come in the next releases.
Screenshots and videos are stored on the desktop. Videos are encoded using H.264 codec.
Here is a resulting video (WhazzerFinger + iMovie with Ken Burns effect): http://youtu.be/Z3W-qU5EP4A.

A: The perfect tool is iPhone-Simulator-Capture SIMBL plugin

*

*Install SIMBL

*Download the code

*Modify Info.plist key "SIMBLTargetApplications/MaxBundleVersion" (and/or "SIMBLTargetApplications/MinBundleVersion") value plist to the actual version of your simulator (240 worked for me) (latest version: 272)

*Build

*Place bundle in "~/Library/Application Support/SIMBL/Plugins"

*Relaunch simulator, now you should have "Recording" in the menu.

A: Now the easiest way is using QuickTime with File > New screen recording and select the part of your screen you want to capture.
iMovie is doing the rest well :-)
Hope this helps.

A: Any Mac OS screen capture tool will work, such as QuickTime Player or Snapz Pro X from Ambrosia Software, Inc.
The QuickTime Player screen recordings are of your entire screen, so you should be prepared to crop the video.  If you don't have sufficient video editing software, Snapz Pro would be the better choice.

A: I've used Screenflow for some times now and I'm satisfied with the performance. It captures the whole screen but you can crop the video afterwards in Screenflow.
One big advantage is the possibility to exchange the cursor with a custom image (like a white circle) so it looks more like a touch.

A: I installed iPhone Simulator Capture today. With SIMBL installation it works. But it displayed an alert window on every simulator first run. My version is 272. I downloaded latest source from the Github. Build the code and replaced the bundle file that xcode created with the file under Library/Application Support/SIMBL. So it is working now. No version test alert window.


text:
Q: How to use tagger file and exe file as library in eclipse? I am working in eclipse luna and am not able to resolve how to use wordnet-2.1.exe and left3words-wsj-0-18.tagger (tagger file)as libraries. I have currently added these two files as Java Build Path->Libraries->Add JARs... .
These were the errors displayed:

*

*Archive for required library: '../lib/left3words-wsj-0-18.tagger' in project 'x' cannot be read or is not a valid ZIP file

*Archive for required library: '../lib/WordNet-2.1.exe' in project 'x' cannot be read or is not a valid ZIP file.

It is important to add these two libraries for the code to run. Does anybody have any idea how to remove this error?

A: You can use  jna wrapper library that used to load any Native library .you can get it from this  link

A: Are you trying to run the Stanford tagger and Wordnet from Java?
If so, you should not include the *.tagger file as a "library". This is a model file, which will be read in by the tagger program. The easiest thing to do is to include the *.jar model file included with the tagger distribution as a library. Otherwise, you can point your code to the particular *.tagger model file with the property (or command line flag) pos.model. See the tagger documentation for details: http://nlp.stanford.edu/software/tagger.shtml or use the tagger through CoreNLP: http://nlp.stanford.edu/software/corenlp.shtml#Usage.
For WordNet, you almost certainly don't want to be using an *.exe file at all. There are plenty of Java wrappers for WordNet out there; e.g., JAWS or JWI.


text:
Q: QGroupBox sizing with my QT5 custom widget I am trying to make a custom widget: for displaying a processor register which has a name, a value and can be displayed in octal/decimal hexa. The code is shown at the bottom. I receive better result when I use the code as shown (i.e I insert QRadioButtons):

If I use
mainLayout->addWidget(DisplayMode);

instead (I guess this is the correct method) then the resulting picture is

Do I misunderstand something? What is wrong?
RegisterWidget::RegisterWidget(QWidget *parent)
:QFrame (parent)
{
  mValue = 0;
  mName = "";
  setFrameStyle(QFrame::Panel | QFrame::Sunken);
  QHBoxLayout *mainLayout = new QHBoxLayout(this);
  label = new QLabel(tr("mName"),this);
  label->setText(mName);
  label->setLineWidth(2);
  QGroupBox *DisplayMode = new QGroupBox("");
  QRadioButton *OctalR = new QRadioButton(this);
  QRadioButton *DecimalR = new QRadioButton(this);
  DecimalR->setChecked(true);    DecimalR->setDown(true);
  QRadioButton *HexaR = new QRadioButton(this);
  QHBoxLayout *hbox = new QHBoxLayout;
  hbox->addWidget(OctalR);
  hbox->addWidget(DecimalR);
  hbox->addWidget(HexaR);
  hbox->addStretch(1);
  DisplayMode->setLayout(hbox);
  mainLayout->addWidget(label);
  Value = new QLCDNumber(this);
  Value->setDigitCount(8);
  Value->setSegmentStyle(QLCDNumber::Flat);
  Value->display(mValue);
  mainLayout->addWidget(Value);
 /* mainLayout->addWidget(DisplayMode);*/
  mainLayout->addWidget(OctalR);
  mainLayout->addWidget(DecimalR);
  mainLayout->addWidget(HexaR);
  setLineWidth(3);
  setLayout(mainLayout);
    connect(OctalR, SIGNAL(clicked()), this, SLOT(setOctal()));
    connect(DecimalR, SIGNAL(clicked()), this, SLOT(setDecimal()));
    connect(HexaR, SIGNAL(clicked()), this, SLOT(setHexa()));
}

A: Call QLayout::setContentsMargins() for both mainLayout and hbox. Try (3, 3, 3, 3) as parameters for a starting point and tweak. Layouts have default margins of 11 pixels on most platforms, according to the docs.


text:
Q: jQuery.maskedInput - Switching input masks dynamically I have a text field that requires a mask.  As per the suggestions on other SO threads I am using this jQuery plugin to do this: http://digitalbush.com/projects/masked-input-plugin/.
I am having a problem with it however.  There 2 different masks that can be applied to my input field.  The decision of which one to use can only be determined after the first 4 characters have been inputed.  So here's what I have:
$('#user-input').keyup(function () {
     current_val = $(this).val();
     if (current_val.replace(/\s*$/, "").length == 4){
         mask = determineMask(current_val);
         $(this).unmask();
         $(this).mask(mask);
     }
});

When the line "$(this).mask(mask)" fires, all existing input is removed.  Does anyone know how to prevent this package from doing that?  Is there another plugin, library, code snippet, etc that would be better at dong what i am trying to do here?


text:
Q: What is the benefit of importing process in node? I am used to simply using process.cwd() directly inside of node applications, however, I have recently read the node docs and saw that it recommends importing it from node:process.
So what is the difference from just calling it directly?
process.cwd()

vs importing it and calling it:
import {cwd} from 'node:process'

cwd()

I am currently building a CLI application in case that makes a difference.

*

*Is there a difference?

*Which one should I be using?

A: importing it from node:process guarentees that you get the built-in process module, not some global that some other code in the project has configured or overridden.
This may be done for safety reasons or just for robustness reasons so other modules in the project can't hack on a global process object before you get to use it.
It also may not normally be needed, but is considered good project hygiene as it deters certain types of hacking.


text:
Q: Stomp and Temporary queues I have a script that sends a message to a subscriber on a well known queue.  It then waits for a reply on a temporary queue.  If no reply comes within 10 seconds, the script errors out and terminates.  I understand that this will destroy the temporary queue, however the messages (if for example the subscriber is not up at the time the message was sent) will remain on the well known queue, and when the subscriber comes up it will read the old messages and reply to the temporary queue.  This is all in python using stompy.  I'm assuming that the temporary queue will be re-instantiated when the reply is made.  So the question is how can I check if the temp queue still exists in the broker before doing the reply.  I'm using Apollo as the message broker.

A: Did a bit of experimentation,  if the message is sent back on the temp queue, it shows up in the apollo broker for a short period and then gets dropped.  So i guess i answered my own question


text:
Q: parsing packet to get application layer protocols such as http and tls using the dpdk packet framework without being computationally expensive I have the following packet inspection function that parses transport layer protocols such as TCP and UDP. I need to get deeper into the packet and get application layer protocols such as HTTP and TLS. My current theory is to implement a pattern matching function on the payload but that would be computationally expensive. Any leads on how to proceed?
void inspect_packet(struct rte_mbuf *pkt, unsigned port_id, int i)
{
    uint8_t *data = (uint8_t *)(pkt->buf_addr + pkt->data_off);
    unsigned int offset = 0;
    struct rte_ether_hdr *eth = (struct rte_ether_hdr *)data;
    offset += sizeof(struct rte_ether_hdr);

    a_counter[i].pkts_counter++;
    a_counter[i].bits_counter += pkt->pkt_len;

    if (eth->ether_type != htons(RTE_ETHER_TYPE_IPV4) && eth->ether_type != htons(RTE_ETHER_TYPE_IPV6)
        && eth->ether_type != htons(RTE_ETHER_TYPE_ARP))
    {
        return;
    }

    if (eth->ether_type == RTE_ETHER_TYPE_ARP)
    {
        a_counter[i].arp_counter++;
        return;
    }

    struct rte_ipv4_hdr *iph = (struct rte_ipv4_hdr *)(data + offset);
    struct rte_ipv6_hdr *iph6 = (struct rte_ipv6_hdr *)(data + offset);

    struct rte_tcp_hdr *tcph = NULL;
    struct rte_udp_hdr *udph = NULL;

    if(eth->ether_type == htons(RTE_ETHER_TYPE_IPV4))
    {
        offset += 20; //header length
        switch (iph->next_proto_id)
        {
            case PROTOCOL_TCP:
                a_counter[i].tcp_counter++;
                tcph = (struct rte_tcp_hdr *)(data + offset);
                break;

            case PROTOCOL_UDP:
                a_counter[i].udp_counter++;
                udph = (struct rte_udp_hdr *)(data + offset);
                break;

            default:
                break;
        }
    }
    else if (eth->ether_type ==  htons(RTE_ETHER_TYPE_IPV6))
    {
        offset += 40; //header length
        switch (iph6->proto)
        {
            case PROTOCOL_TCP:
                tcph = (struct rte_tcp_hdr *)(data + offset);
                break;

            case PROTOCOL_UDP:
                udph = (struct rte_udp_hdr *)(data + offset);
                break;
        }
    }

    data = nullptr;
}

A: [based on the live discussion]
Question: My current theory is to implement a pattern-matching function on the payload but that would be computationally expensive. Any leads on how to proceed?
Answer: The application logic to identify the protocols and application would be fixed cost. So the first goal is to ensure pre-processing and post-processing stages lead to minimal loss. These get varied from physical NIC to virtual NIC too.
So let me explain a few pointers I follow for the best result.

*

*In virtual NIC, I use memif or vhost for the best performance.

*if I know specific IP, VLAN, MPLS, VXLAN which get filtered I prefer to use AF_XDP PMD on the virtual NIC that bifurcates the traffic.

*In the case of physical NIC, use the NIC that supports PTYPES, RSS, QUEUE redirection.

(Physical NIC offload)

*

*Using RSS, one can program RSS to spread traffic on all queues.

*Combining queue redirection with RSS, one can specifically send the desired traffic like IPv4, IPv6, VxLAN, GRE, Geneve, GTPu to be RSS on selective queues. This allows all ARP, ND, lldp and other packets to fall onto default queue.

*Using DPDK APi rte_eth_dev_set_ptypes enable rte_mbuf to carry ptype information from descriptor.

*ensure to use vector mode (AVX2 and|or AV512) with smaller descriptor size if possible for certain NIC.

So well-tuned (BIOS and Kernel Command Line) lcores will now be able to get RX packets DMA with enough metadata. This will allow the extra overhead to parse each packet to reduce since selected traffic is sent to a specific queue and the PTYPE on the RSS queue helps to do an early filter.
Then divide the development into multiple stages

*

*stage-1: rx packets and increments protocol counters then use rte_mbuf_free without drops

*stage-2: increment ref_cnt for the interested packet, and do tx_burst. then perform stage-2

*stage-3: run single instance of optimized application-parser and how much cycles overhead comes in and is there packet drops

if packet drops are present, it means single queue traffic needs either spread to multiple queues (more RX queues) in case of the run to completion model. Else explore the option of using eventdev or flow distributor with multiple lcore threads as application parsers.
Note:

*

*as pointed out, one can use HW FPGA lookaside or SW regex like (hyperscan) to achieve optimized application parsing.

*this will work with clear text, in case of TLS, for connection which doesn't have keys to be terminated can be bypassed by using rte_flow to carry 32bit marker.

Above logic is true for IDS mode. In case of IPS mode, sometimes requirements will be come to ensure packet ordering. So use atomic eventdev for all the 3 stages.


text:
Q: Email Mocking is failing Im trying to mock the send email functionality which sends out email when a particular job/task is completed. When i try to unit test it getting below error. Is this the right way to test it or something wrong or missing anything.
@Mock
private MailServiceImpl mailService;

@Mock
private JavaMailSenderImpl javaMailSender;

@Before
public  void setUp() {
    MockitoAnnotations.initMocks(this);
    mailService=new MailServiceImpl(javaMailSender);

}

@Test
public void testSendEmail() {

    try {
        doNothing().when(mailService).sendMail(getEmailProperties());
        mailService.sendMail(getEmailProperties());
        verify(mailService,times(1)).sendMail(getEmailProperties());
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

}

public EmailProperties getEmailProperties() {

    EmailProperties emailProperties = new EmailProperties();

    emailProperties.setFromAddress("from@Test.com");
    emailProperties.setToAddress("To@Test.com");
    emailProperties.setEmailBody("Test");
    emailProperties.setSubject("Test email");
    emailProperties.setAttachment((File) null);
    emailProperties.setMessageType(1);

    return emailProperties;
  }

Below is the error message is thrown from testSendEmail method. Any suggestions or any other ways to test it. google search didn't help much.
java.lang.AssertionError:
    Argument passed to when() is not a mock!
    Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();
    at org.junit.Assert.fail(Assert.java:88)
    at com.xx.xx.xx.mail.MailServiceTest.testSendEmail(MailServiceTest.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

A: The error message is trying to say that Mockito.when() method accepts only mocked/spied objects.
You are using mailService in when method which is wrong as its neither mocked nor spied object.
mailService=new MailServiceImpl(javaMailSender);

I cannot go into too much details as the code under test is not provided.
But you can try replacing
mailService=new MailServiceImpl(javaMailSender);
with
  mailService=Mockito.spy(new MailServiceImpl(javaMailSender));
This should make your mailService as something mockito will accept.

A: removal of doNothing().when(mailService).sendMail(getEmailProperties()); fixed the issue. Not sure what was causing this issue


text:
Q: Solve primary key violation in SSMS While trying to insert some items into a table I get the following error:

Msg 2627, Level 14, State 1, Procedure dba_create_fake_orders, Line 95 [Batch Start Line 2]
  Violation of PRIMARY KEY constraint 'PK_OrderItem_1'. Cannot insert duplicate key in object 'dbo.OrderItem'. The duplicate key value is (10000, 100009).

Here's how my tables are set up and the following code is just a segment of the code used to insert those items to the table:
Table Set UP
INSERT INTO Orders(order_id, customer_id, sub_total, tax_total,
                   grand_total, date_created)
    SELECT
        @order_id, @customer_id, 0, 0,
        0, @date_created

INSERT INTO OrderItem (order_id, quantity, game_id, price_id)
    SELECT
        @order_id, @quantity, game_id, price_id
    FROM
        GameVersion
    WHERE
        game_id = @game_id

@order and @customer_id are taken from a flat customer table and are chosen at random. The OrderItem table is empty always so I'm not sure why it's saying that there's a duplication error. The only tables that are populate is Orders and GameVersion.
GameVersion is populated way before and Orders is done just before OrderItem. I'm assuming the issue is that since I have to keys then it might be complaining since they might be the same number but I'm still not sure.

A: If the following query returns more than one row then it means your dataset has duplicate value in the column set you are using as PK in OrderItem.
select count(*), game_id from GameVersion GROUP BY game_id having count(*)>1


text:
Q: What is the reduction formula for $\int x\cos^nx\,dx$ such that $n \in \mathbb{Z}^+ $? I am pretty bad at deducing reduction formulas but I tried and I reached
$$\frac{1}{2}I_{n-2} + \frac{1}{2}(x\sin x\cos^{n-1}x+\sin^{n-1}x+\frac{1}{n} \cos^nx)$$
Which I tried testing for $n = 2$ and comparing my answer to the integral-calculator's, the calculator's answer was: $$\frac{2x(\sin(2x)+x)+\cos(2x)}{8} + C$$
And mine was: $$\frac{16x^2 + 16x\sin2x + 8\cos2x + 32\sin x}{64}$$
I can tell that I got a couple of things right, like the existence of a $\sin2x$ multiplied by a $x^1$, the existence of an $x^2$ free of any trigonometric functions, and a $\cos2x$ free of any $x$ all three with matching coefficients to the actual answer.
And then I have that annoying extra $sinx$ which I can't really trace.
I know that comparing answers the way I am doing is kinda wrong, but I just couldn't help myself but see the similarities and feel close to the correct answer.
EDIT: here's the process as requested, I'll be skipping some parts because I need to sleep for uni.
$$\int x cos^nx\ dx = \int x\cos^{n-2}x\cos^2x\ dx = \int x\cos^{n-2}(1-\sin^2x)dx$$
then solving that using the fact that $\sin^2x = \frac{1}{2}(1-\cos2x)$ I reached, $$\frac{1}{2} I_{n-2} + \frac{1}{2}\int x\cos^{n-2}\cos2x\ dx$$
Then, solving $\int x\cos^{n-2}\cos2x\ dx$ by parts, $u = x\cos^{n-2}x$ and $dv = \cos2x\ dx$
$$\int x\cos^{n-2}\cos2x\ dx = \frac{x\cos^{n-2}x\sin2x}{2}-\frac{1}{2}\int (-(n-1)x\sin^{n-3}x+\cos^{n-2}x)\sin2x\ dx$$
then, solving that last integral I got: $-2\sin^{n-1}x-\frac{2\cos^nx}{n}$
plugging in and simplifying the $\sin2x$ using $\sin2x = 2\sin x\cos x$ I got
$$I_n = \frac{1}{2}I_{n-2} + \frac{1}{2}(x\sin x\cos^{n-1}x+\sin^{n-1}x+\frac{1}{n}\cos^nx)$$

A: The first step is correct. You made a mistake during integration by parts
$$ v = \frac{\sin 2x}{2} = \sin x\cos x, \quad du = \big( \cos^{n-2}x - x(n-2)\cos^{n-3}x\sin x \big)\ dx $$
Then
$$ \begin{align} \int x\cos^{n-2}x\sin 2x\ dx &= x\cos^{n-1}x\sin x - \int \cos^{n-1}x\sin x\ dx \\ &\quad + (n-2)\int x \cos^{n-2}x \sin^2 x\ dx \\
&= x\cos^{n-1}x\sin x + \frac{\cos^n x}{n} + (n-2)I_{n-2}  - (n-2)I_n  \end{align} $$
Altogether
$$ \begin{align}
I_n &= \frac{1}{2}I_{n-2} + \frac{1}{2}\int x\cos^{n-2}x \sin 2x \ dx \\
&= \frac{n-1}{2}I_{n-2} - \frac{n-2}{2}I_n + \frac{1}{2}x\cos^{n-1}x\sin x + \frac{\cos^n x}{2n}
\end{align} $$
which gives
$$ I_n = \frac{n-1}{n}I_{n-2} + \frac{1}{n}x\cos^{n-1}x\sin x + \frac{\cos^n x}{n^2} $$


text:
Q: Do newly added Couchbase servers need to be added to client configurations to be leveraged? I'm working with Couchbase, specifically using the .NET client. We're unsure whether we need to add a load balancer for Couchbase. I know we don't need one to actually balance the nodes, but I'm unsure if we need one to allow for adding servers on the fly.
Consider the following .NET Couchbase configuration:
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="couchbase" type="Couchbase.Configuration.CouchbaseClientSection, Couchbase"/>
  </configSections>
  <couchbase>
    <servers bucket="default" bucketPassword="">
      <add uri="http://192.168.0.2:8091/pools"/>
      <add uri="http://192.168.0.3:8091/pools"/>
    </servers>
  </couchbase>
</configuration>

Now say we add another server to the cluster, located at:
192.168.0.4:8091

If an application is already deployed with the configuration with two servers, will it be able to leverage the newly added server? Or do all client configurations need to have an element added like:
<add uri="http://192.168.0.4:8091/pools"/>

Our thought is that if all configurations would need to be updated that we could just point all clients to a load balancer instead, and add the new servers to the load balancer.

A: If you look at this architectural white paper (pdf) on Couchbase it says:

To talk to Couchbase Server, applications use memcached compatible smart-client SDKs in a variety of languages
  including Java, .NET, PHP, Python, Ruby, C, and C++. These clients are cluster topology aware and get updates on
  the cluster map. They automatically send request from the application to the appropriate server.

http://info.couchbase.com/couchbase-server-architecture-review.html
It is also mentioned here in the documentation if you don't want to download the pdf.  http://docs.couchbase.com/couchbase-manual-2.2/#rebalancing

A: it's recommended by Couchbase to have all cluster nodes in the connection configuration of the application. Nevertheless, it is not really required - cluster map will be updated from servers that are in the application configuration.
Daniel