text:
Q: How can I scan NFC-Tags with iOS / Xamarin from viewmodel I have a Cross-Platform Xamarin.Forms .net standard app for android / iOS and wanted to add the nfc-scan functionality.
For my first test, I've put all into my AppDelegate class.
This code works:
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, INFCNdefReaderSessionDelegate
{
    public NFCNdefReaderSession Session { get; set; }

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();

        if (Session == null)
        {
            Session = new NFCNdefReaderSession(this, null, true);
        }
        Session = new NFCNdefReaderSession(this, null, true);
        Session?.BeginSession();

        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }

    public void DidInvalidate(NFCNdefReaderSession session, NSError error)
    {
        Console.WriteLine("ServiceToolStandard DidInvalidate: " + error.ToString());
    }

    public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
    {
        var bytes = messages[0].Records[0].Payload.Skip(3).ToArray();
        var message = Encoding.UTF8.GetString(bytes);
        Console.WriteLine("ServiceToolStandard DidDetect: " + message);
    }
}

My Problem:
After that I've put all into a new NfcScanner class and wanted to call the ScanAsync function from my ViewModel. If I run this code, everything looks fine. The scan starts when I press the button on my phone, it shows the blue tick symbol but then it never gets into one of the implemented methods DidDetect, DidInvalidate. Do you know what the reason could be?
public class NfcScanner : INfcScanner, INFCNdefReaderSessionDelegate
{
    public string ErrorText { get; private set; }

    private NFCNdefReaderSession _session;
    private TaskCompletionSource<string> _tcs;

    public Task<string> ScanAsync()
    {
        if (!NFCNdefReaderSession.ReadingAvailable)
        {
            throw new InvalidOperationException("Reading NDEF is not available");
        }

        _tcs = new TaskCompletionSource<string>();
        _session = new NFCNdefReaderSession(this, null, true);
        _session.BeginSession();

        return _tcs.Task;
    }

    public void DidInvalidate(NFCNdefReaderSession session, NSError error)
    {
        Console.WriteLine("ServiceToolStandard DidInvalidate: " + error.ToString());
        _tcs.TrySetException(new Exception(error?.LocalizedFailureReason));
    }

    public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
    {
        Console.WriteLine("ServiceToolStandard DidDetect msgs " + messages.Length);
        var bytes = messages[0].Records[0].Payload.Skip(3).ToArray();
        var message = Encoding.UTF8.GetString(bytes);
        Console.WriteLine("ServiceToolStandard DidDetect msg " + message);
        _tcs.SetResult(message);
    }

    public IntPtr Handle { get; }

    public void Dispose()
    {
        Console.WriteLine("ServiceToolStandard Dispose");
    }
}

I tried also to make a void Scan() Method and call it directly from AppDelegate. The result is the same. The scan window opens and it shows the blue tick symbol, but it never reaches the methods diddetect, didinvalidate.

Edit 07.02.2018 16:56:
I saw in the example code, that their class derives from UITableViewController.
This was the only real difference between my code and the example code. After I derived in my NfcScanner class from ViewController it worked. But I'm not sure why and if it's the right way?
public class NfcScanner : UIViewController, INfcScanner, INFCNdefReaderSessionDelegate
{
 ...
}

Thanks a lot for your help!

A: I tried to find an answer, why it works after i derived from UIViewController. I think I found it, in this tutorial: Core NFC Tutorial

Creating a session, we can specify a delegate in our
  NFCNDEFReaderSession class. I would like to use the NFCHelper class as
  the delegate, so we must first adhere to the delegate protocol,
  NFCNDEFReaderSessionDelegate. This delegate is based on an Objective-C
  object, so we must first also adhere to NSObject.
  NFCNDEFReaderSessionDelegate has two delegate methods we must
  implement:

UIViewController inherits from NSObject. Now it also works after I changed my code to:
public class NfcScanner : NSObject, INfcScanner, INFCNdefReaderSessionDelegate
{
 ...
}

A: The question is a bit old and still comes up on top of the search results so I just wanted to share a new answer for any one looking for it. In order to access any of the NFC Functionality, you can use the Plugin.NFC nuget package. It supports writing to NFC Tags using iOS too, and also provides a great sample in the GitHub repository. You should be able to use that straight from your View
Model if you really need to, though I would recommend calling it from your view instead, based on MVVM principles.
I recently used it and documented my journey on How to get started with NFC and Xamarin in 5 minutes.


text:
Q: De-Interlacing with Mediafoundation My problem is that I get interlaced uncompressed UYVY Frames and I need to deinterlace them.
My first guess was to do this with directshow and Dscaler, but I cant find a 64bit version of it (did I mention that the app is 64 bit?). I am also not able to compile it in 64 bit.
The next try would be media foundation. The EVR somehow deinterlace the frames. I would like to use this mechanism outside a renderer.
Has someone an idea?
(If there is any other idea how to deinterlace frames in another way, I would like to hear ;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What should be the approach for react js based site's performance testing-Jmeter I have an application which is in react js. Here I am giving demo site  https://webix.com/demos/bank-app/#!/top/customers?user=1/information .Suppose I have to do performance test of statistics page tab how can I do this. As all the resources downloaded from the start when I hit the ttps://webix.com/demos/bank-app/ page. Now when I go to chrome developer tool and click on customer->statistics it shows me only static file.my client wants me to check the performance of those chart load time.
can anybody help.
Also do I have to load test google API's for charts that loaded on the page. There is so many SVG files and woff2 file. do I have to load test these things.
Thanks,
Bibek

A: client wants me to check the performance of those chart load time - if you mean chart rendering time - JMeter won't give this to you, as per JMeter project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

So if you want to include this rendering time into your report the only option I can think of is going for WebDriver Sampler which provides JMeter integration with Selenium browser automation framework
There is so many SVG files and woff2 file. do I have to load test these things. - yes, but wisely, there is a special setting at "Avanced" tab of the HTTP Request sampler responsible for retrieval of these images, scripts, styles, fonts, etc.

the idea is to enable downloading for the domain you're testing (and exclude external assets if any). Also don't forget to add HTTP Cache Manager to your test plan because real browsers do download these "embedded resources" but they do it only once. See Web Testing with JMeter: How To Properly Handle Embedded Resources in HTML Responses article for more details.

A: Try Google lighthouse once. It will give brief idea about basic improvement. By this you can achieve good amount performance improvement. then you can go with JMeter.


text:
Q: Rspec, capybara getting started issues I have have started with simple example of Rspec,Capybara. I have come across few issues. This issues are probably because I have experience with cucumber and page_object gem, but here I am using capybara and Site_prism gem.
I have tried:
my_example_spec.rb
    require_relative 'Support/spec_helper'
    require_relative 'pages/login_page'
describe 'My behaviour'  do

  it 'should do something'do
    @login_page = LoginPage.new
    @login_page.load
    @login_page.login('autouser','password')
  end
end

and login_page.rb
class LoginPage < SitePrism::Page

 set_url "/login"

  element :username, "input[id='username']"
  element :password, "input[id='password']"
  element :submit, "input[id='submit']"

  def login(username,password)
   @login_page.username.set username
   @login_page.password.set password
   @login_page.submit.click

  end

end

Issues are:

*

*When I run my_example_spec.rb it gives error
Testing started at ...
Run options: include {:full_description=>/My\ behaviour\ should\ do\ something/}

NoMethodError: undefined method `username' for nil:NilClass
./pages/login_page.rb:10:in `login'
./my_example_spec.rb:11:in `block (2 levels) in <top (required)>'
-e:1:in `load'
-e:1:in `<main>'

*Shouldn't it be on(LoginPage).login (autouser, password). It should navigate to the page and run login method. It is how it works in page_object gem whats the equivalent of site_prism gem

A: The login method in your LoginPage class should be
def login(username,password)
  username.set username
  password.set password
  submit.click
end

@login_page is not an instance variable of the LoginPage class so it is not accessible inside the class.  It's also not necessary inside the class since you're already inside the class.


text:
Q: Expanding Accordion Panel in PrimeFaces with a RadioButton click Below is the snapshot of the layout I'm trying to achieve.
I have two questions/problems here:

*

*Right now,the page loads with all the accordian panels open. I want it initially to be in the closed state (like in option 1).

*On click of the Radio button near the tab, the tab should expand. If I click on another radio button, the new tab associated with the radio button should expand, and the other one should close.

How do we accomplish this ?
I don't see any toggle function or anything associated with PrimeFaces accordian. There is only widgetVar.show() function, but it's not helping me.

A: To begin with your accordion panel tabs closed try setting activeIndex to -1 (or any value that does not correspond to an existing panel). I have not tested this with multiple tabs in an accordion panel, but it should work:
<p:accordionPanel activeIndex="-1">


text:
Q: WordPress category gives 404 after moving to a different domain I just moved a site from one domain to another and now category links are all 404. I have flushed the rewrite rules, recreated the .htaccess file but still it throws up 404.
Weird thing is that if I delete .htaccess file, then the posts are still accessible by domain.com/postname/ and when I save permalinks, then it is created there. So can it be the case it is using some other .htaccess file? Possibly some fallback that I am not aware of?
Re-Edit: Tag pages don't work fine. Its all weird. Tags generally give 404, one of them opened a non 404 page but not what it should be (i.e. posts listing under that tag). And a category redirects itself to one of the posts. This all led me to conclude that tags were working but they are not. Also everything works, when I turn off the permalinks.
I am using a custom slug for category "cat" and not the default "category" but reverting to the default doesn't solve anything. Any clues?
Edit: I saw Ipstenu's sticky on WP forums and found that Advanced Permalinks are known to have a problem with WP 3.1, so I disabled it and recreated by permalinks but still no joy. What did I miss?
So far, I have tried recreating permalinks, flushing rewrite rules by calling global $wp_rewrite; $wp_rewrite->flush_rules(); in functions.php, deleting rewrite_rules in options table & even deleting .htaccess file. So I am clueless and would appreciate if someone can give me a clue how it can be fixed.
Further Edit: If I delete the .htaccess file, the site behaves if it was there and I can browse pretty permalinks without any issue (.htaccess file is not there in the WP root) but when I resave permalinks, it is created there. So can there be some kind of fallback for .htaccess because this shouldn't be possible without rules in .htaccess?
EDIT: I am still stuck at the issue. Can anyone please help me out?
Final Edit: Is there anything left in the wild that I can do to troubleshoot this issue? I have lost hope on this one.

A: Setup 301: Moved Permanently redirects! This post should be helpful

A: Check to make sure that your .htaccess file is active - ie in your apache virtual host settings make sure you've got something like AllowOverride All in the  section

A: After trying everything out, nothing worked but then all of a sudden, deleting .htaccess file and re-saving permalinks did the job.


text:
Q: Converting iOS9 coalesced touches drawing code for iOS8 and iOS7 compatibility I have the below code from a project available at: https://github.com/FlexMonkey/SmoothScribble/tree/master/SmoothScribble
Currently this project only runs on iOS9 as the project uses UIStackView and coalescedTouchesForTouch which are only available for iOS9. However I wish to convert the project to make it available for iOS7 and iOS8 as well. How do I go about doing that?
I think I might have a handle on how I might go about replacing UIStackView with a UIView. However, how do I handle sections that refer to coalescedTouches?
For instance, how do I convert the below code snippet so that it conforms to a traditional touchesMoved that works on iOS8 and iOS9?
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
guard let
    touch = touches.first,
    coalescedTouches = event?.coalescedTouchesForTouch(touch),
    touchOrigin = touchOrigin
    else
{
    return
}

coalescedTouches.forEach
    {
        hermiteScribbleView.appendScribble($0.locationInView(touchOrigin))
        simpleScribbleView.appendScribble($0.locationInView(touchOrigin))
}
}

import UIKit

class ViewController: UIViewController
{
let stackView = UIStackView()

let hermiteScribbleView = HermiteScribbleView(title: "Hermite")
let simpleScribbleView = SimpleScribbleView(title: "Simple")

var touchOrigin: ScribbleView?

override func viewDidLoad()
{
    super.viewDidLoad()

    view.addSubview(stackView)

    stackView.addArrangedSubview(hermiteScribbleView)
    stackView.addArrangedSubview(simpleScribbleView)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    guard let
        location = touches.first?.locationInView(self.view) else
    {
        return
    }

    if(hermiteScribbleView.frame.contains(location))
    {
        touchOrigin = hermiteScribbleView
    }
    else if (simpleScribbleView.frame.contains(location))
    {
        touchOrigin = simpleScribbleView
    }
    else
    {
        touchOrigin = nil
        return
    }

    if let adjustedLocationInView = touches.first?.locationInView(touchOrigin)
    {
        hermiteScribbleView.beginScribble(adjustedLocationInView)
        simpleScribbleView.beginScribble(adjustedLocationInView)
    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    guard let
        touch = touches.first,
        coalescedTouches = event?.coalescedTouchesForTouch(touch),
        touchOrigin = touchOrigin
        else
    {
        return
    }

    coalescedTouches.forEach
        {
            hermiteScribbleView.appendScribble($0.locationInView(touchOrigin))
            simpleScribbleView.appendScribble($0.locationInView(touchOrigin))
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    hermiteScribbleView.endScribble()
    simpleScribbleView.endScribble()
}

override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?)
{
    if motion == UIEventSubtype.MotionShake
    {
        hermiteScribbleView.clearScribble()
        simpleScribbleView.clearScribble()
    }
}

override func viewDidLayoutSubviews()
{
    stackView.frame = CGRect(x: 0,
        y: topLayoutGuide.length,
        width: view.frame.width,
        height: view.frame.height - topLayoutGuide.length).insetBy(dx: 10, dy: 10)

    stackView.axis = view.frame.width > view.frame.height
        ? UILayoutConstraintAxis.Horizontal
        : UILayoutConstraintAxis.Vertical

    stackView.spacing = 10

    stackView.distribution = UIStackViewDistribution.FillEqually
}
}

Full project code available at: project available at: https://github.com/FlexMonkey/SmoothScribble/tree/master/SmoothScribble

A: Yesterday I also had a question on compatibility and it turned out that it could be solved easily by Availability Condition, like this:
if #available(iOS 9.0, *) {
  let store = CNContactStore()
} else {
  // Fallback on earlier versions
}

You can read this article to know more about it.
http://useyourloaf.com/blog/checking-api-availability-with-swift.html
I do not know if we have the same problem. But, in my view, I could have two snippets of code comforming to iOS 9 and iOS 8 respectively, and use Availability Condition or @available Attribute to resolve compatibility problem.


text:
Q: Select Rows with Maximum Column Value group by Another Column This should be a simple question, but I can't get it to work :(
How to select rows that have the maximum column value,as group by another column?
For example,
I have the following table definition:
ID
Del_Index
docgroupviewid

The issue now is that I want to group by results by docgroupviewid first, and then choose one row from each docgroupviewid group, depending on which one has the highest del_index.
I tried
SELECT docgroupviewid, max(del_index),id FROM table
group by docgroupviewid

But instead of return me with the correct id, it returns me with the earliest id from the group with the same docgroupviewid.
Any ideas?

A: You will have to complicate your query a little bit:
select a.docgroupviewid, a.del_index, a.id from table a
    where a.del_index = (select max(b.del_index) from table
        where b.docgroupviewid = a.docgroupviewid)

A: I've struggled with this many times myself and the solution is to think about your query differently.
I want each DocGroupViewID row where the Del_Index is the highest(max) for all rows with that DocGroupViewID:
SELECT
    T.DocGroupViewID,
    T.Del_Index,
    T.ID
FROM MyTable T
WHERE T.Del_Index = (
    SELECT MAX( T1.Del_Index ) FROM MyTable T1
    WHERE T1.DocGroupViewID = T.DocGroupViewID
)

It gets more complex when more than one row can have the same Del_Index, since then you need some way to choose which one to show.

EDIT: wanted to follow up with another option
You can use the RANK() or ROW_NUMBER() functions with a CTE to get more control over the results, as follows:
-- fake a source table
DECLARE @t TABLE (
    ID int IDENTITY(1,1) PRIMARY KEY,
    Del_Index int,
    DocGroupViewID int
)

INSERT INTO @t
SELECT 1, 1 UNION ALL
SELECT 2, 1 UNION ALL
SELECT 3, 1 UNION ALL
SELECT 1, 2 UNION ALL
SELECT 2, 2 UNION ALL
SELECT 2, 2 UNION ALL
SELECT 1, 3 UNION ALL
SELECT 2, 3 UNION ALL
SELECT 3, 3 UNION ALL
SELECT 4, 3

-- show our source
SELECT * FROM @t

-- select using RANK (can have duplicates)
;WITH cteRank AS
(
    SELECT
        DocGroupViewID,
        Del_Index,
        ID,
        RANK() OVER
            (PARTITION BY DocGroupViewID ORDER BY Del_Index DESC)
        AS RowRank,
        ROW_NUMBER() OVER
            (PARTITION BY DocGroupViewID ORDER BY Del_Index DESC)
        AS RowNumber
    FROM @t
)
SELECT *
FROM cteRank
WHERE RowRank = 1

-- select using ROW_NUMBER
;WITH cteRowNumber AS
(
    SELECT
        DocGroupViewID,
        Del_Index,
        ID,
        RANK() OVER
            (PARTITION BY DocGroupViewID ORDER BY Del_Index DESC)
        AS RowRank,
        ROW_NUMBER() OVER
            (PARTITION BY DocGroupViewID ORDER BY Del_Index DESC)
        AS RowNumber
    FROM @t
)
SELECT *
FROM cteRowNumber
WHERE RowNumber = 1

If you have ways to sort out ties, just add it to the ORDER BY.


text:
Q: pdo query not running i can't seem to figure out why this query isn't running
if ( $productName && $productDescription && $productPrice ) {
// SQL
// UPDATE `prostud_tristurion`.`products` SET `product_title` = 'ajax test', `product_description` = 'Was certainty remaining engrossed applauded sir how discovery.', `product_price` = '524' WHERE `products`.`product_id` = 10;
try {

    $query = "update products set product_title = :pName, product_description = :pDescription, product_price = :pPrice, where product_id = :pid";
    //prepare query for excecution
    $stmt = $con->prepare($query);

    //bind the parameters
    $stmt->bindParam(':pid', $id);
    $stmt->bindParam(':pName', $productName);
    $stmt->bindParam(':pDescription', $productDescription);
    $stmt->bindParam(':pPrice', $productPrice);
    // echo "$productPrice / $productDescription / $productName / $id\n $stmt";
    var_dump($_POST);
    // Execute the query
    if ($stmt->execute() ) {
        echo "Record was updated.";
    } else {
        die('Unable to update record.');
    }

}catch(PDOException $exception){ //to handle error
    echo "Error: " . $exception->getMessage();
}
}

all i get is Unable to update record.
var_dump($_POST);

is looking good

A: You have an errant comma at product_price = :pPrice, where
If your code reaches the die statement then you have exceptions turned off (not recommended) but you can get the error message from the database (to log or echo) with $stmt->errorInfo()


text:
Q: Cardinality of set of strict total orders on the reals I'm revising for an exam - two questions:
i) What's the cardinality of the set of strict total orders on $R$?
This is a subset of the power set of $R$ (because $|R|=|R.R|$), so I know its cardinality is less than this - but I can't find a way to show its cardinality is equal to this, i.e. an injection from the power set into the set of strict total orders.
ii) What is the cardinality of the set of countable subsets of F, where F is the set of functions from $R$ to $R$?
Cardinality of F is same as cardinality of power set of $R$ (one way given by reasoning above, and the other way by the fact that $|P(R)|=|2^R|=|R^R|$. The set of countable subsets of this I am not sure how to calculate though.


text:
Q: C++ array of pairs copy constructor and assignment operator I'm struggling with my copy constructor and assignment operator in my C++ program.  I get a segmentation fault (core dump) when testing either of them, individually.  I'm building a hash table that is constructed through an array with a pair inside each index.  The indexes are chosen based on a hash function, the first part of the pair is a key, the second part of the pair is a value. There's obviously more to the class, but nothing that affects the copy and assignment operator, so I kept them out there.  I have no memory leaks and I test the op= and copy constructor with a good number of values already in it.
In UnorderedMap.h
template <typename K, typename V>
class MyUnorderedMap: public Dictionary<K, V>
{
    private:
        MyPair<K, V> *m_data = nullptr; // hash table, array of pairs

        int data_size = 0; // current number of elements inside the array
        int reserved_size = 0; // max elements inside the array

    public:
        // Start data_size and reserved_size at 0, m_data to nullptr
        MyUnorderedMap();

        ~MyUnorderedMap();

        MyUnorderedMap(const MyUnorderedMap<K, V> &source);

        MyUnorderedMap<K, V> & operator=(const MyUnorderedMap<K, V> &source);
}

In UnorderedMap.hpp
// Copy Constructor
template <typename K, typename V>
MyUnorderedMap<K, V>::MyUnorderedMap(const MyUnorderedMap<K, V> &source)
{
  data_size = source.data_size;
  reserved_size = source.reserved_size;
  m_data = new MyPair<K, V>[reserved_size];
  for(int i = 0; i < reserved_size; i++)
  {
    m_data[i].first = source.m_data[i].first;
    m_data[i].second = source.m_data[i].second;
  }
}

// Assignment Operator
template <typename K, typename V>
MyUnorderedMap<K, V> & MyUnorderedMap<K, V>::operator=(const MyUnorderedMap<K, V> &source)
{
  if(this!=&source)
  {
    delete[] m_data;
    reserved_size = source.reserved_size;
    data_size = source.data_size;
    m_data = new  MyPair<K, V>[reserved_size];
    for(int i=0; i<reserved_size; i++)
    {
      m_data[i].first = source.m_data[i].first;
      m_data[i].second = source.m_data[i].second;
    }
  }
  return *this;
}

In MyPair.h
template <typename K, typename V>
struct MyPair
{
    K first;
    V second;

    MyPair(){}
    MyPair(const K &key): first(key) {}
    MyPair(const K &key, const V &value): first(key), second(value) {}
};

Does anyone see a problem with why it would be behaving like this?
I'm a lot more confident in my copy constructor than the operator=.
Edit x3: I have an insert function not shown that properly inserts into the hash table.  So I solved the copy constructor but the op= is still not working.. I fixed the copy constructor above so now it shows a working copy constructor, for anyone else who wants to use it as an effectively working basis. Fixed the assignment operator as well and provided the correct version.

A: m_data is defined as a pointer in UnorderedMap.h, initialised as nullptr but in the implementation it gets used without being assigned to some actual storage.

A: I noticed in your copy constructor that you delete [] m_data, but then a few lines later you start assigning values into it; this is a big no-no. After you delete [] it, you have to allocate a new array using m_data = new MyPair<K,V>[data_size]; or something like that.
I also noticed that you initialize your class just in the class declaration, with
private:
    MyPair<K,V>* m_data = nullptr;
    data_size = 0;

and so on. This is generally not how initialization works in C++; you have to put that in the actual constructor, and it doesn't look like you implemented one in your code.

A: I am assuming that Dictionary has correct copy semantics.
If you take what has been stated from the comments, here is what your code should look like:
First, the copy constructor:
template <typename K, typename V>
MyUnorderedMap<K, V>::MyUnorderedMap(const MyUnorderedMap<K, V> &source)
        : m_data(new MyPair<K, V>[source.reserved_size]),  // <-- You are missing this
          data_size(source.data_size),
          reserved_size(source.reserved_size)
{
   for(int i = 0; i < reserved_size; i++)
   {
      m_data[i].first = source.m_data[i].first;
      m_data[i].second = source.m_data[i].second;
   }
}

The copy constructor uses the member-initialization list.  Note that the memory is allocated in the member-initialization list.  This is the operation you did not have in your version of the copy constructor, and the major issue with your code.
However, there are other issues, which can be addressed with your implementation of the assignment operator.
The next function you should implement after the copy constructor is the destructor, and not the assignment operator.  There is a strategic reason why you want to implement the destructor next, to be explained later.
template <typename K, typename V>
MyUnorderedMap<K, V>::~MyUnorderedMap()
{
   delete [] m_data;
}

Now that you have those two function, the assignment operator becomes trivial.  However, let's go over your flawed version:
template <typename K, typename V>
MyUnorderedMap<K, V> & MyUnorderedMap<K, V>::operator=(const MyUnorderedMap<K, V>
                                                       &source)
{
     if(this!=&source)
     {
         delete[] m_data;
         data_size = source.data_size;

Let's stop right here.  You have potentially corrupted your object with those last two lines of code.
The reason is that you've changed the members of your object, and you have yet to allocate memory.  What if the call to new[] in the next line throws an exception?  You now have an object that is in an invalid state.
If you write the assignment operator this way, the way it should be written is to make sure all the memory is allocated first, and then start to adjust the object's member variables.
But there is a simpler way to avoid all of this:
#include <algorithm>
//...
template <typename K, typename V>
MyUnorderedMap<K, V> & MyUnorderedMap<K, V>::operator=(const MyUnorderedMap<K, V>
                                                       &source)
{
     if(this!=&source)
     {
         // create a temporary
         MyUnorderedMap<K,V> temp(source);

         // swap out the temp's contents with the current object
         std::swap(temp.data, data);
         std::swap(temp.data_size, data_size);
         std::swap(temp.reserved_size, reserved_size);

         // temp will be destroyed when the if() goes out of scope
      }
      return *this;
  }

So why does this work?  It's simple, and the code basically documents what is done.
You're creating a copy of the passed-in object.  Then you're swapping out the contents of the current object's with the copy's contents.  Then the copy dies of (after the if block) with the old contents.  There is no issue of exceptions being thrown and creating invalid objects, there is no redundant code between the copy constructor and assignment operator, etc.
This technique of writing the assignment operator is called the copy / swap idiom.  The only way it works is if you have a correct copy constructor and a correct destructor.  That's why we wrote those two functions first, so as to take advantage of simply swap-ping the members in the assignment operator.


text:
Q: No space left on device on CentOS7 My machine which OS is CentOS7 have to backup 50G data into MySQL. But, there is no space left on the device. But there are many spaces on /home. How can I make user that there are enough space for MySQL to store data. I think there is no space in /dev/mapper/centos-root, how can I move space to from /home to /.
$ df -h
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root   50G   50G   20K 100% /
devtmpfs                 7.8G     0  7.8G   0% /dev
tmpfs                    7.8G   84K  7.8G   1% /dev/shm
tmpfs                    7.8G  2.6G  5.2G  34% /run
tmpfs                    7.8G     0  7.8G   0% /sys/fs/cgroup
/dev/mapper/centos-home  500G   20G  480G   4% /home
/dev/sda1                497M  241M  257M  49% /boot
tmpfs                    1.6G   16K  1.6G   1% /run/user/42
tmpfs                    1.6G     0  1.6G   0% /run/user/0
tmpfs                    1.6G  4.0K  1.6G   1% /run/user/1000

And g++ compile code failed.
$ g++ test.cpp
Cannot create temporary file in /tmp/: No space left on device
[1]    6642 abort (core dumped)  g++ test.cpp

A: You first need to get your root partition ("/") down from being full or many bad things will happen in your system. It needs /tmp to be writeable for many system and user tasks.
Your root partition is only 50GB so you're never going to get the space you need there with current partition structure.
Your options would be to repartition to get a separate /var (out of space in /home) to give yourself space for MySQL data files. the utility parted will do that. If it's a hosted machine that may not be easy or possible to do, and I don't recommend playing around with that utility if you're not sure what you're doing.
Failing that, it's a bit of a hack but you could get around it with symlinks. Again not normally recommended and you'd probably need to take your machine down to single-user mode as running daemons will have file locks stopping you moving. The essence would be:
mv /var /home
ln -s /home/var /var

And if you do that you'll probably need to reboot the machine to bring it up cleanly:
shutdown -r now

Please research what you want to do, playing around with disk partitions can get very messy if you don't have a clear plan.

A: If you store only backups of MySQL on your / partition then it's easy to move the data.
Assume you're storing your data in /opt/backup/ you can:

*

*Stop the backup from writing to that directory ( if you're using some backup program )

*Move backup folder in / to /home/ ( or any folder in /home as you want)
# mv /opt/backup/ /home/

*Create a symbolic link to old directory:
# ln -s /home/backup/ /opt/backup

*Give proper permission to make sure your backup program have write permission to /home/backup with chmod.

*Start your backup program back

A: Clone operating system using professional tools like acronis to larger disk with bigger partitions as hard links may cause trobule at later stage. Use boot rescue to rebuild grub as after moving to new disk layout centos may not boot.

A: Using CentOs 7, I tried two IDE's but had the same problem handling a project with approx 16000 files.
"no space left on device" was logged by the IDE.
Both IDE's were hanging, or became unresponsive, or debugging actions stop or pause would crash the whole system or terminate the desktop session.
And in the message log it said:
Oct  2 10:44:08 localhost gnome-session: inotify_add_watch("/home/tools/trunk/ext/boost/libs/hana/example/functional") failed: "No space left on device"

Turns out the Centos Kernel has a buffer for folder watches etc..
i found the solution by sfuser0000 on this site.. This is a copy of the solution:

Common problem, temporary solution, increase the watches limit (to,
  say, 512K):
sudo sysctl fs.inotify.max_user_watches = 524288
(worked for me, but I'll probably go permanent and maybe larger, info
  below)
To make the change permanent, edit the file /etc/sysctl.conf and add
  this line to the end of the file:
fs.inotify.max_user_watches = 524288
Size info below:
"Can you increase the watches? By how much? Any tradeoffs? Short
  answer: Sure, no sweat. Go to straight to a half-million (524288) if
  you want...the additional memory used should be negligible on a modern
  system with 4GB+ of memory.
Each used inotify watch takes up 540 bytes (32-bit system), or 1 kB
  (double - on 64-bit) This comes out of kernel memory, which is
  unswappable. So, assuming you set the max at 524288, and all were used
  (improbable), you'd be using approx. 256MB/512MB of 32-bit/64-bit
  kernel memory
Note that your application will also use additional memory to keep
  track of the inotify handles, file/directory paths, etc. -- how much
  depends on its design."

A: Permanent solution:
fs.inotify.max_user_watches=1048576   #just add to this line
to
/etc/sysctl.conf
fixed the limit value permanently
then do
sysctl -p


text:
Q: Connect RDS Aurora Postgres SQL from one account to another account using AWS Privatelink(VPC Endpoint) with IAM Authentication in AWS I want to connect RDS Aurora Postgres SQL from one account to another account using AWS Privatelink(VPC Endpoint) with IAM Authentication. I have below setup.
Account A:
I have VPC Endpoint service which is pointing to NLB and NLB is redirect request to RDS Aurora Postgres SQL.The VPC Endpoint service has allowed principal for 'Account B'.
Account B:
I have created VPC Endpoint which has pointed to 'Account A' VPC Endpoint service. I have application which is connect my RDS DB using VPC Endpoint dns name as host name in psql command(Instead of RDS Endpoint).
I can able to connect RDS from 'Account B' via VPC Endpoint with above setup using credentials mode(username and password of DB).
But I am unable connect RDS with IAM Authentication. How to connect RDS from different account using VPC Endpoint with IAM Authentication.
Could anyone give me details steps?


text:
Q: FlutterViewController setInitialRoute for windows I am trying to Navigate to a specific route from Native flutter Pugin.
I was able to do that in swift for iOS:
            let extVC = FlutterViewController()
            extVC.setInitialRoute(routerName)
            window?.rootViewController = extVC

What is the equivelent to setInitialRoute in flutter native(c++) plugin for Windows?
bool FlutterWindow::OnCreate() {
  if (!Win32Window::OnCreate()) {
    return false;
  }

  RECT frame = GetClientArea();

  // The size here must match the window dimensions to avoid unnecessary surface
  // creation / destruction in the startup path.
  flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
      frame.right - frame.left, frame.bottom - frame.top, project_);
  // Ensure that basic setup of the controller was successful.
  if (!flutter_controller_->engine() || !flutter_controller_->view()) {
    return false;
  }
  run_loop_->RegisterFlutterInstance(flutter_controller_->engine());
  SetChildContent(flutter_controller_->view()->GetNativeWindow());
  return true;

A: There is currently no equivalent in the Windows embedding API. You should file an issue requesting the functionality you need.


text:
Q: How to execute shell command with arguments in C I'm unable to execute the command alone, with arguments is working. How can I make it work both ways.
char command[256];
char args[10][256];
char buffer[256] __attribute__((aligned(4096)));

Funcion is handling command and arguments and I'm sure they are correct, however I can't find a way to execute it.
pid = fork();
    if (pid == -1)
    {
      printf("Failed forming fork\n");
      return;
    }
    else if (pid == 0)
    {
      strcpy( cmd , "/usr/bin/");
      strcat( cmd, command);
      execl(cmd, command, args, NULL);

    }else{
      wait(NULL);
       }

And in general how can I stop fork bombs, how to check for them and avoid them?


text:
Q: Get string length function (strlen) of a constant char array is not a constant expression Let's see the simplified code directly (compiled by: GCC 6.3.0)
#include<iostream>
#include<cstring>

using namespace std;

int main(int arga, char* argv[]) {

    const char cs[] = "Hello";//define a constant c-style string
    constexpr size_t newSize = strlen(cs) + strlen(" ");//Error

    return 0;
}

Compiler yielded an error:  strlen(((const char*)(& cs))) is not a constant expression
However, when I move the c-string definition to the global scope, then the problem is off.
....
const char cs[] = "Hello";

int main(int arga, char* argv[]) {
    constexpr size_t newSize = strlen(cs) + strlen(" ")//No Error
 ....
}

Can someone explain what happened? Why strlen() sees a globally defined constant c-string as a constant expression, but not the one in the stack?

A: Standard strlen is not constepxr, therefore, it cannot be used in constexpr context. However, GCC knows about strlen, therefore it is able to compute the length of the string, in some circumstances - even if it is not mandated/permitted by the standard.
If you are concerned only by arrays, you can use std::size to get their size:
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
    return N;
}


text:
Q: Keep real numbers in Ruby language How are real numbers kept in Ruby language? How can I keep 7.125 as real number in the memory? In this code:
myNumber = 7.125
puts("The number is #{myNumber}")

I do not understand how the number is kept in memory.

A: In Ruby 1.8 & 1.9, floats are never immediates, so all floats require a new memory allocation.
In Ruby 2.0.0, on 64 bit systems, many floats are now immediate. This means that the typical floats don't require memory allocation & deallocation anymore, so much faster operations.
Ruby stores its values in a pointer (32 or 64 bits, depending on the platform). It actually uses a trick to store immediates in that pointer. This is the reason why Fixnum can only hold 31 / 63 bits.
On 32 bit platforms, there's no clever way to store floats, but on 64 bits platforms, it's possible to use the first ones to flag this value as an immediate float and the remaining 60 or so to hold the data. The floats that do require the full 64 bits can not be immediates, though, so these are stored like before using an actual pointer.
More info on this optimization can be found in the https://bugs.ruby-lang.org/issues/6763

A: There is no way to keep real numbers in Ruby. The closest things are Float or Rational, both of which cannot express real numbers fully.

A: How about the Bigdecimal class (arbitrary precision arithmetics)? See the API, which follows standards on the topic.


text:
Q: built-in isight camera on early 2008 macbook air 1,1 Does the (camera + internal microphone) system use a single internal 2.0 USB interface that connects to logic board?
This seems to be the case according to Wikipedia, and ifixit, even though I cant get 100% sure. Also, is LVDS cable involved here?
Edit: looking at ifixit pictures, from step 19 it seems the internal microphone cable is connected to logic board, while all other input from display (ie. also the USB part from isight) goes through display data cable in step 23

A: The camera, Bluetooth module, keyboard and trackpad all connect internally via USB. No LVDS cable is required or used by the camera. The internal microphone is connected directly to the audio controller.
Take a look at About This Mac from the Apple menu, go to More Info > System Report, and look at the devices listed in the USB category to see the various device connections.


text:
Q: How do I vertically align a div inside of another div? I've looked at other posts but they aren't working for me. My website (http://www.jacksewell.uk/) has a modal that fades in when you click the "Hire Me" button. Currently its not centred vertically but it is centred horizontally. I would like the modal to be centred both horizontally and vertically. Any help?
Thanks :D
Here the markup and CSS (Sass) for the modal:
HTML:

            ×

Ready to start your next project?

            <form action="form_submit.php">
                Name:
<input type="text" name="client-name">

                Company :
<input type="text" name="company-name">

                Service:
<select name="Service">
                <option value="Website">Website Devlelopemnt</option>
                <option value="Design">Design related tasks</option>
                <option value="SEO">SEO Related tasks</option>
                <option value="All">Full Package (Website designed & developed with SEO)</option>
              </select>

                Extra Detail :

                <textarea rows="4" cols="50">Please add more detail about what you are looking for.
                </textarea>

              <input type="submit">
            </form>

CSS (Sass):
.modal
  display: none
  position: fixed
  z-index: 1
  left: 0
  top: 0
  width: 100%
  height: 100%
  overflow: hidden
  background-color: black
  background-color: rgba(0, 0, 0, 0.5)

.modal-header
  text-align: center

.modal-content
  background-color: #fefefe
  margin: 2vh auto
  padding: 20px
  border: 1px solid #888
  width: 80%
  -webkit-animation-name: modal
  -webkit-animation-duration: 450ms
  animation-name: modal
  animation-duration: 450ms

.modal-body
  display: flex
  flex-direction: column
  align-items: center
  margin: 24px
  span
    color: #212121
    font-weight: 600
  input, select, textarea
    border-radius: 5px
    padding: 6px 12px 6px 12px
    margin: 10px
    width: 220px
    border: solid 2px #d1d1d1
    outline: none
  select
    width: 250px

input[type=submit]
  border-radius: 5px
  border: 0
  width: 260px
  height: 35px
  color: #fff
  background: #3498db
  -webkit-appearance: none

.close
  color: rgba(0, 0, 0, 0.5)
  float: right
  font-size: 28px
  font-weight: bold
  transition: all ease-in-out 0.25s
  &:hover, &:focus
    color: #000
    text-decoration: none
    cursor: pointer

A: This will do the trick, hope this helps!
.modal-content {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

A: You can use flexbox. Flexbox is currently not working on IE 9 and 8, but it is fine on every other browser as you can see here.
You just have to add this css to your .modal class ( the parent of your .modal-content):
.modal {
  display: flex;
  flex-direction: column;
  justify-content: center;
  // Your css goes here, without the display:block;
}

For further information on centering things with css, you can check this guide: https://css-tricks.com/centering-css-complete-guide/


text:
Q: Redux Saga: Testing plain javascript function inside my saga with redux-saga-test-plan and jest I am trying to figure out how it is that I can test my saga that contains a regular ol' javascript function in it.
Here is my saga:
export function* watchGetActivities() {
    yield takeLatest(actionTypes.GET_ACTIVITIES, getActivitiesSaga);
}

function* getActivitiesSaga() {
    try {
        const activities = yield call(api.getActivities);
        const timezone= yield call(getTimezone);
        const activityWithTimezone=attachTimeZoneToActivities(activities.data,timezone.data);
        yield put(getActivitesSuccess(activityWithTimezone));
    } catch (e) {
        yield put(getActivitiesFailure());
        yield put(showModal(modalTypes.ERROR, 'Could not retrieve activities.'));
    }
}

The function that the third const calls (this essentially loops through the activities retrieved from the apis and combines them):
export const attachTimeZoneToActivities= (activities,timezones)=>{
    activities.forEach(function (activity) {
        activity['timezone']=getActivityTimeZone(timezones,activity.start_epoch_ms)
    })
return activities;
}

And finally, my test using redux-saga-test-plan:
it('fetches activities from the activities API', () => {
    const fakeActivity = { data: {foo: 'bar' } };
    const fakeTimezone= { data: {timezone: 'denver' } };
    const fakeAttachTimeZoneToActivities={foo:'bar',timezone: 'denver'};
    return expectSaga(watchGetActivities, api)
        .provide([
            [call(api.getActivities), fakeActivity],
            [call(getTimezone),fakeTimezone],
            [matchers.call.fn(attachTimeZoneToActivities), fakeAttachTimeZoneToActivities]
            [matchers.call.fn(getActivityTimeZone), 'denver']
        ])

        .put(activity.getActivitesSuccess({ foo: 'bar',timezone:'denver'}))
        .dispatch(activity.getActivities())
        .silentRun()
});

for whatever reason, the saga immediately goes to failing the api call, I could get it to pass before I added in all the timezone nonsense just fine.  Anyone have any tips?  Thank you in advanced!

A: The issue was that I forgot that functions in sagas need to be called using saga effects so for the third const it needed to be called like so:
const activityWithTimezone= yield call(attachTimeZoneToActivities, activities.data,timezone.data);

Everything else works correctly!


text: Q: Does changing character varying length have an impact on Postgresql query performance? Does it make a query faster when a Postgresql column is set as character varying (50) instead of character varying (255) ?


text:
Q: Change encoding from T1 I want to change encoding from T1 to UTF-8 in Java.
I read and parse pdf to String using Tika. Then I change the ecoding using decode and encode methods in Charset class. There is no problem with common encodings like windows-1252 or UTF-8, but I cannot find class with T1 encoding.
Text sample:
Przykªady zastosowa«

I can properly decode this text on this page:
http://kanjidict.stc.cx/recode.php


text:
Q: Find the Error of a linearization by integration Let's say $E(x)$ is the error between a function $f(x)$ and its first order linearization $L(x)$, so:
$$E(x)=f(x)-L(x)=f(x)-f(a)-f'(a)(x-a)$$
Then by the Mean-Value Theorem for $u\in(a,x)$:
$$\frac{E'(x)}{x-a}=\frac{f'(x)-f'(a)}{x-a}=f''(u)$$
$$E'(x)=f''(u)(x-a)$$
Question:
How can I show by integration from here that: $$E(x)=\frac{f''(s)}{2}(x-a)^2$$
My attempt:
Integrating $E'(x)=f''(u)(x-a)$ I get $E(x)=\frac{f''(u)}{2}(x-a)^2+C$
How do I get from $E(x)=\frac{f''(u)}{2}(x-a)^2+C$ to $E(x)=\frac{f''(s)}{2}(x-a)^2$?

A: Use the fact that $E(a) = 0$ to get $C = 0$. I assume that $s$ is just some number between $x$ and $a$, i.e., $u = s$.


text:
Q: How to make KDE Spectacle automatically save a picture? The "PrtScr" key in KDE in Ubuntu 18.04 invokes "spectacle", which pops up as a separate window.  You can click "save and exit" to save a screenshot.  The hotkeys that launch Spectacle appear to be defined in /usr/share/khotkeys/spectacle.khotkeys .
Is there a way of changing the settings so that it "just saves the screenshot" (i.e. there's no clumsy sequence of "press PrtScn, go to where spectacle has launched, press Save and Exit" each time)?

A: You can use shortcut keys.
Meta+Print will take a screenshot of the active window.
Shift+Print will take a screenshot of your entire desktop, i.e. all monitors.
Meta+Shift+Print will take a rectangular region screenshot.
https://docs.kde.org/trunk5/en/kdegraphics/spectacle/starting.html

A: *

*Enter Settings > Shortcuts > Custom Shortcuts

*Create new custom group ie "Spectacle": Edit > New Group

*And create new custom shortcut(s): Edit > New > Global Shortcut > Command/URL

*fill the name, e.g. "Region Capture"

*Trigger: Print

*And in Action Tab put the following in Command/URL

spectacle -brc -o "$HOME/pictures/screenshots/Screenshot_$(date +'%Y%m%d_%H%M%S').png"

*

*Save the config

*Press PrintScreen button or the one that you configured before

*Click twice and voilà :)


text:
Q: CSS3 radial-gradient not working on fire fox? This radial gradient is not working on firefox:
background-image: -moz-radial-gradient(bottom center, 900px 900px, #7dd134 0%, #137f1e 90%, #137f1e 100%);

A: It is Mozilla`s bug they do not support defined size radial gradient.
Here  is the bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=627885


text:
Q: how to dynamically insert datediff into webpage to keep updated in real time (now) I can do a request in phpmyadmin to show the number of days between todays date and a date selected by a user:
SELECT DATEDIFF(CURDATE(), date_instructed) AS DAYS FROM date_tester
.. but i think this wont update all the table and will only update when a new record is created in the table.
So can anyone suggest the best way  to dynamically update/count  the days in a column by using a date entered by a user .
Should it even be put in a column? or should i use php to echo the result for each row on the webpage.
If I should be manipulating the 'date_instructed' with a script and then entering it in the html table seperatly is their a link to show me how to do this?
Many thanks
<?php
include 'dbh.php';
?>

      First Name
      Last
      Date Instructed
      Days On Market

    <?php

    $query  = "SELECT  first_name, last_name, date_instructed , days_onmarket
                FROM date_tester";
    $result = mysqli_query($conn, $query);
    while ($date_tester = mysqli_fetch_assoc($result)) {
        echo "
";
        echo "" . $date_tester['first_name'] . "	";
        echo "" . $date_tester['last_name'] . "	";
        echo "" . $date_tester['date_instructed'] . "	";
    }
    ?>

A: From what i understand this is what you need:
 $query  = "SELECT  first_name, last_name, date_instructed ,    days_onmarket, DATEDIFF(CURDATE(), 'date_instructed') AS DAYS FROM date_tester";
   $result = mysqli_query($conn, $query);
while ($date_tester = mysqli_fetch_assoc($result)) {
    echo "
";
    echo "" . $date_tester['first_name'] . "	";
    echo "" . $date_tester['last_name'] . "	";
    echo "" . $date_tester['date_instructed'] . "	";
    echo "" . $date_tester['DAYS'] . "	";
}


text:
Q: SQL check if date value has 5 days straight I have a date column contains date value, I want to see if all the date values contains 5 day straight for example

2019-03-15
...
2021-06-01
2021-06-02
2021-06-03
2021-06-04
2021-06-05
....
2021-07-01

In this case returns true
The only catch is that the syntax must work with SQL Server 2008 R2 version

A: You can subtract an enumerated value and that is constant for adjacent dates.  Then aggregate and count.
So, to get all sequences of 5 or greater:
select min(date), max(date), count(*)
from (select t.*, row_number() over (order by date) as seqnum
      from t
     ) t
group by dateadd(day, - seqnum, date)
having count(*) >= 5;

If you want to return a 'true'/'false' value:
select (case when exists (select min(date), max(date), count(*)
                          from (select t.*, row_number() over (order by date) as seqnum
                                from t
                               ) t
                          group by dateadd(day, - seqnum, date)
                          having count(*) >= 5
                         )
              then 'true' else 'false'
        end) as flag


text:
Q: Show the manufacturers that sold cellphone in 2010 but didn't in 2009. (USING MYSQL) SELECT Manufacturer_Name
FROM DIM_MANUFACTURER
     INNER JOIN DIM_MODEL ON DIM_MANUFACTURER.IDManufacturer = DIM_MODEL.IDManufacturer
    WHERE DIM_MANUFACTURER.IDManufacturer IN
          (
          SELECT DIM_MODEL.IDManufacturer
            FROM DIM_MODEL
            INNER JOIN FACT_TRANSACTIONS ON DIM_MODEL.IDModel = FACT_TRANSACTIONS.IDModel
             WHERE DIM_MODEL.IDMODEL IN
             (
             SELECT FACT_TRANSACTIONS.IDModel
              FROM FACT_TRANSACTIONS
             WHERE IDModel NOT IN (YEAR(STR_TO_DATE(Date_d,'%m/%d/%Y')) = 2009) AND
                IDModel In (YEAR(STR_TO_DATE(Date_d,'%m/%d/%Y')) = 2010)));

A: Hmmm . . . I am thinking exists and not exists:
select m.*
from dim_manufacturer m
where exists (select 1
              from transactions t join
                   dim_models mo
                   using (idmodel)
              where m.IDManufacturer = mo.IDManufacturer and
                    t.date_d >= '2010-01-01' and t.date_d < '2011-01-01'
             ) and
      not exists (select 1
                  from transactions t join
                       dim_models mo
                       using (idmodel)
                  where m.IDManufacturer = mo.IDManufacturer and
                        t.date_d >= '2009-01-01' and t.date_d < '2010-01-01'
                 ) ;


text:
Q: changing state inside map return causes a 'Too many re-renders' error white trying to add values to the array in the setPositions call, that line causes Too many re-renders error

export default function () {
  const colors: string[] = ['#b22828', '#42853a', '#bbb', '#378e91', '#bb32b3'];
  const [positions, setPositions] = useState<Position[]>([]);

  return (
      <ChakraProvider>
          {[1, 2, 3].map((element, index) => {
              let top: number = RandomPicker(10, 800);
              let left: number = RandomPicker(15, 1500);
              //the next line causes the error
              setPositions([new Position(top, left), ...positions]);
              console.log(positions);
              let color: string = colors[RandomPicker(0, colors.length)].toString();
              return (
                  <Clickable
                      key={index}
                      top={top.toString() + 'px'}
                      left={left.toString() + 'px'}
                      color={color}
                  />
              );
          })}
      </ChakraProvider>
  );
}

A: You are enqueueing state updates in the render function return. In the case of function components the entire component function body is the render function. These enqueued state updates are an unintentional/unexpected side-effect in what should be considered a pure function, the render looping issue is created.
Use an useEffect hook to issue side-effects.
From what I can tell you are wanting to generate 3 random positions and then map them to Clickable components.
export default function () {
  const colors: string[] = ['#b22828', '#42853a', '#bbb', '#378e91', '#bb32b3'];
  const [positions, setPositions] = useState<Position[]>([]);

  useEffect(() => {
    setPositions([1, 2, 3].map(() =>
      new Position(RandomPicker(10, 800), RandomPicker(15, 1500))
    );
  }, []);

  return (
    <ChakraProvider>
      {positions.map((element, index) => {
        const color: string = colors[RandomPicker(0, colors.length)];
        return (
          <Clickable
            key={index}
            top={top.toString() + 'px'}
            left={left.toString() + 'px'}
            color={color}
          />
        );
      })}
    </ChakraProvider>
  );
}

Or just map the initial state directly.
export default function () {
  const colors: string[] = ['#b22828', '#42853a', '#bbb', '#378e91', '#bb32b3'];
  const [positions, setPositions] = useState<Position[]>([1, 2, 3].map(
    () => new Position(RandomPicker(10, 800), RandomPicker(15, 1500))
  );

  return (
    <ChakraProvider>
      {positions.map((element, index) => {
        const color: string = colors[RandomPicker(0, colors.length)];
        return (
          <Clickable
            key={index}
            top={top.toString() + 'px'}
            left={left.toString() + 'px'}
            color={color}
          />
        );
      })}
    </ChakraProvider>
  );
}


text:
Q: How to add space in GridLayout in JPanel? I am new to Java and learning GUI now a days. I want to add space on top of may FirstPlayer name I am using JPanel with GridLayout but when I add invisible box as the first element to set my elements in the center but I got nothing as my desire. Please help me.
Here is my code:
JPanel    main   =   new  JPanel();

GridLayout  layout  =   new GridLayout(6,1);
layout.setVgap(10);
JPanel  parentPanel =   new JPanel(layout);
parentPanel.setOpaque(false);
parentPanel.add(Box.createRigidArea(new Dimension(80,0)));
parentPanel.add(main.getFirstName());
parentPanel.add(main.getFirstField());
parentPanel.add(Box.createRigidArea(new Dimension(20,0 )));

parentPanel.add(main.getSecondName());
parentPanel.add(main.getSecondField());

main.add(parentPanel,BorderLayout.CENTER);

JFrame frame    =   new JFrame("Player Menu");

frame.add(main,BorderLayout.CENTER);
frame.add(Box.createRigidArea(new Dimension(100,0 )),BorderLayout.NORTH);
frame.setVisible(true);
frame.pack();
frame.setSize(900,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


text:
Q: Lua Pattern Matching - force optional parameters to be filled before it moves on? I need a pattern that will grab values for two or more parameters of varying length.
I need to convert a scanf format %i to a lua pattern and it is proving very difficult. I don't need to worry about the type of storage that can be passed in with scanf. Just the %i for integer and if they specify a specific link.
Documentation for scanf, if needed, can be found here.
This is what I have so far:
if(scanfLetter == "i" or scanfLetter == "d" or scanfLetter == "u") then
   if(specifiedNum == 0)then
     newPattern = "([%+%-]?%d+)"
   elseif(specifiedNum >= 2)then
     newPattern = "([%+%-%d]?%d^".. string.rep("%d?", specifiedNum-2)..")$"
   else
     newPattern = "(%d)"
   end

which basically just checks to see if they passed in a specific number or not (specifiedNum). If it is 0 that means they didn't.
It all works until there are two length specified %is in a row. For example:
%5i%6i

If they enter in 6 or more characters it works fine because match will return two values: the first one consisting of the first 5 numbers and the 6th goes the next value.
The trouble is if there are fewer than 5. In scanf or printf it will not match %5i%6i if there are 5 or fewer numbers, but in my pattern it will still match under string.match and it returns all the values but the last in the first return and the second value get the last number entered.
More specific example so you don't have to type it all out and see it the pattern ends up looking like.
Given:
([%.%+%-%d]?%d[%.%d]?[%.%d]?[%.%d]?)([%.%+%-%d]?%d[%.%d]?[%.%d]?[%.%d]?[%.%d]?)

If 123456789 is passed to it, the match returns 2 values:
`12345` and `6789`

However, if 1234 is passed in, the match returns 2 values:
`123` and `4`

which is incorrect (it should not be a match).
Is what I seek possible?
(Maybe somebody has already written a scanf format to lua patterns converter?)


text:
Q: How do I view an embedded RavenDB database? RavenDB server comes with a web UI Studio letting to look what's inside. But what's the way to take a look in an embedded RavenDB?

A: If you are running a test you can use the WaitForUserToContinueTheTest method. Otherwise I guess you'll need to start the http server yourself.


text:
Q: How to decrease the width and height of angular gauge fusion widget Hi i am using the following example to construct the angular gauge fusion widget, but i am not finding a option to decrease the height and width of the widget.Can i know is their any option to resize the angular widget.
http://www.fusioncharts.com/widgets/Gallery/Angular15.html

A: The gauge is built using various elements which are placed using pixel values based on the width of 300 and height of 300. You can make these elements scale automatically using the Auto Scale feature of the gauge.
Please use origW='300' origH='300' autoScale='1' in <chart> and <annotations> element before you try to decrease the width and height of the gauge.
NOTE: You should always increase or decrease the size of the gauge using the original ratio of width and height (which is 300:300 i.e., 1:1 in this case)
So, using the auto scale you can safely use 200x200px or 400x400px.
<chart origW='300' origH='300' autoScale='1' bgColor='FFFFFF' upperLimit='100' lowerLimit='0' baseFontColor='FFFFFF' majorTMNumber='11' majorTMColor='FFFFFF'  majorTMHeight='8' minorTMNumber='5' minorTMColor='FFFFFF' minorTMHeight='3' toolTipBorderColor='FFFFFF' toolTipBgColor='333333' gaugeOuterRadius='100' gaugeOriginX='150' gaugeOriginY='150' gaugeScaleAngle='270' placeValuesInside='1' gaugeInnerRadius='80%25' annRenderDelay='0' gaugeFillMix='' pivotRadius='10' showPivotBorder='0' pivotFillMix='{CCCCCC},{333333}' pivotFillRatio='50,50' showShadow='0' >
<colorRange>

    <color minValue='0' maxValue='50' code='C1E1C1' alpha='40'/>

    <color minValue='50' maxValue='85' code='F6F164' alpha='40'/>

    <color minValue='85' maxValue='120' code='F70118' alpha='40'/>

</colorRange>

<dials>

    <dial value='65' borderColor='FFFFFF' bgColor='000000,CCCCCC,000000' borderAlpha='0' baseWidth='10'/>

</dials>

<annotations origW='300' origH='300' autoScale='1'>

    <annotationGroup xPos='150' yPos='150' showBelow='1'>

        <annotation type='circle' xPos='0' yPos='0' radius='145' startAngle='0' endAngle='360' fillColor='CCCCCC,111111'  fillPattern='linear' fillAlpha='100,100'  fillRatio='50,50' fillAngle='-45'/>

        <annotation type='circle' xPos='0' yPos='0' radius='120' startAngle='0' endAngle='360' fillColor='111111,cccccc'  fillPattern='linear' fillAlpha='100,100'  fillRatio='50,50' fillAngle='-45'/>

        <annotation type='circle' xPos='0' yPos='0' radius='110' startAngle='0' endAngle='360' color='666666'/>

    </annotationGroup>

</annotations>
</chart>

For more information on Auto Scale please read : http://www.fusioncharts.com/widgets/docs/Contents/Ang_Origins.html


text:
Q: ArcGIS JSAPI Query Related Records/Relationship Table I am using this example https://developers.arcgis.com/javascript/3/jssamples/fl_query_related.html
to develop an application which queries related features.  I have two feature classes and have created a N-M relationship class.  The objective is to click on an electric feeder and query the related customers.  There are 26 electrical feeders  and over 400 customers.  My relationship class was based on the OBJECTIDs being the primary keys and the foreign keys being the "feederID" that the structures have and the that the customers are assigned to.
Ideally, I'd expect to see several customers per feeder, but based on my logic in this code sample, I am only returning the matching ObjectIDs per feeder.
What should be changed to return each customer which shares the same feeder?
 function findRelatedRecords(evt) {
        var features = evt.features;
        var relatedTopsQuery = new RelationshipQuery();
        relatedTopsQuery.outFields = ["*"];
        relatedTopsQuery.relationshipId = 0;
        relatedTopsQuery.objectIds = [features[0].attributes.OBJECTID];
        wellFeatureLayer.queryRelatedFeatures(relatedTopsQuery, function(relatedRecords) {
          console.log("related recs: ", relatedRecords);
          if ( ! relatedRecords.hasOwnProperty(features[0].attributes.OBJECTID) ) {
            console.log("No related records for ObjectID: ", features[0].attributes.OBJECTID);
            return;
          }
          var fset = relatedRecords[features[0].attributes.OBJECTID ];
          var items = array.map(fset.features, function(feature) {
            return feature.attributes;
          });
          //Create data object to be used in store
          var data = {
            identifier: "OBJECTID",  //This field needs to have unique values
            label: "OBJECTID", //Name field for display. Not pertinent to a grid but may be used elsewhere.
            items: items
          };

          //Create data store and bind to grid.
          store = new ItemFileReadStore({ data:data });
          grid.setStore(store);
          grid.setQuery({ OBJECTID: "*" });
        });
    }


text:
Q: echo PHP variable if iframe content is empty I have this JS / PHP Code:

I want to be able to echo the $ContactsDisplay variable if the iframe is empty
I added the alert in to test, but the alert does not show and neither does the PHP variable.
What could be going wrong?

A: Your nearly there try this.
 if($( "#frameDemo" ).contents().length == 0){
   alert('success loaded');
 } else {
   alert('fail not loaded');
 }

success

fail


text:
Q: Most efficient way to re-use jQuery-selected elements I can imagine the correct answer to this based on theory, but I'm just looking for some confirmation. I'm wondering what the most efficient way to re-use a jQuery-selected element is. For example:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');

vs.
myDiv = $('#my_div');
myDiv.css('background','red');
//some other code
myDiv.attr('name','Red Div');

I assume the second example is more efficient because the element #my_div doesn't have to get found more than once. Is that correct?
Similarly, is it more efficient to first save $(this) in a varaible, such as 'obj', and then reuse 'obj' rather than using $(this) over and over? In this case, jQuery isn't being forced to find an element over and over again, but it IS being forced to convert this to a jQuery object [$(this)]. So as a general rule of thumb, should a jQuery object ALWAYS be stored in a variable if it will be used more than once?

A: if you're using jQuery selector (like $('#element')), then yes, you should always store your results.
if you're using object and wrapping it in jQuery (like $(this)), it's not necessary, because jQuery doesn't need to search for that element again.

A: One thing that I find is generally overlooked is just how powerful jQuery chains are. It may not be so noticeable, but since jQuery caches your wrapped elements within a chain, you can modify elements, go into a more specific subset, modify, then go back up into a a general superset without much overhead.
I expect something like (pardon the example)
$('#myDiv')
    .addClass('processing')
    .find('#myInput')
    .hide('slow')
    .end()
    .removeClass('processing')
    ;

to be better performance-wise than even
var $myDiv = $('#myDiv').addClass('processing');
var $myInput = $('#myDiv #myInput').hide('slow');
    $myDiv.removeClass('processing');

A: You should write your code such that you limit the number of DOM traversals.
When you write something like this:
$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');

You are finding #my_div twice, which is inefficient.
You can improve this either by assigning the result of a selector (i.e. var x = $('.something')) and manipulate the variable x, or you can chain your method calls like this:
$('#my_div').css('background','red').attr('name','Red Div');

You'll see the above code used a lot, because you're finding the element once. The css() method will apply a CSS style and return the actual result of $('#my_div'), so you can invoke another method, in this case attr().
My preferred way of handling the re-use of selectors is to store them as a variable, and wrap my stuff in a closure.

A: This also holds for applying the jQuery function to elements returned in an event handler. Try to avoid applying $(...) too many times, because this is slow. Instead create a variable that contains the result of $(...). Good practice is to start the variable with a $, which gives a hint about the jQuery object inside the variable.
$('a').click(function(){
  var $this = $(this);
  $this.addClass("clicked");
  $this.attr("clicked", true);
});


text:
Q: Django - Trying to order get_object_or_404 by latest I have a collection of blog post with a category defined for each. The single category page displays all post under the specified category, but I would like these to be sorted by the date written.
Here is what I have:
def single_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    categories = Category.objects.all()
    context = {
        'category': category,
        'categories': categories
    }
    return render(request, 'Blog/single-category.html', context)

This doesn't work, but here is what I want:
def single_category(request, slug):
    category = get_object_or_404(Category.objects.order_by('-written_on'), slug=slug)
    categories = Category.objects.all()
    context = {
        'category': category,
        'categories': categories
    }
    return render(request, 'Blog/single-category.html', context)

Here are my Category and Post models
class Category(models.Model):
    name = models.CharField(max_length=120)
    slug = models.SlugField(max_length=120)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return '/%s/' % self.slug

class Post(models.Model):
    name = models.CharField(max_length=120)
    slug = models.SlugField(max_length=120)
    post_category = models.ForeignKey(Category, related_name='post',
    on_delete=models.CASCADE)
    post_summary = models.TextField(max_length=120)
    post_content = models.TextField()
    written_on = models.DateField()
    preview_image = models.ImageField()
    homepage_carousel_status = models.IntegerField(choices=STATUS,
    default=0)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return '/%s/%s/' % (self.post_category.slug, self.slug)

A: You can fetch the related Posts and order these in descending written_on order:
def single_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    posts = Post.objects.filter(post_category=category).order_by('-written_on')
    categories = Category.objects.all()
    context = {
        'category': category,
        'categories': categories,
        'posts': posts
    }
    return render(request, 'Blog/single-category.html', context)
In the template you thus then enumerate over posts, instead of category.post:
{% for post in posts %}
    …
{% endfor %}


text:
Q: How to POST the screenshot in base64 encoding in python I would like to make a POST call in python to post a image(image is a base64 string). I'm new to making a POST call with boundary. POST call is expected to be made in below mentioned format.Any ideas on how it could be done is appreciated
POST .../api/URL_PATH
Content-Type: multipart/form-data; boundary=someboundary
Accept: application/json

--someboundary
Content-Disposition: form-data; name="entity"
Content-Type: application/json; charset=UTF-8
{
                "item": {
                                "id": 1002345,
                                "type": "type"
                },
                "name": "screenshot.png",
                "description": "This is screenshot"
}
--someboundary
Content-Disposition: form-data; name="content"; filename="screenshot.png"
Content-Type: image/png
Content-Transfer-Encoding: base64

iVBORw0KGgoAAAANSUhEUgAAALAAAAAzCAIAAAC48RV/AAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAALRSURBVHhe7ZjhUewwDITph3roh3qoh36OOLYc
rSRHd445YNjv17Msr2R5J9y8lxshChqCADQEAWgIAtAQBKAhCEBDEICGIAANQQAaggA0BAFoCALQ
EASgIQhAQxCAhiDAXzTE5/vrS+H1/bNFyDJoCAJ8gyE+3oLnCoOT/FZDrLzjj0FDrOM/G0LepNFn
0GaiefsIgzV/pCPAvuwqQ6h9fbZWLBFVuyX4iAJblS4LrVKsObh43UKUTtx8Uqiijh6YnDkmDBE2
07oJ5zIY1plOIdivm/HBjf4EQcUB6tXCQ72dpOjgjp6hjlTKbzfKOEZ3gVlDHLeVUfR2WgDbC4KJ
TqRb/60GUo/3gKjJWZewkRzp5SSjJeRFRULf0eN0jmaN7qgQlpHd3sVFFvyGsHMI53LHsDClraKL
ygyUmJF31fwREwn6w1HnRSMNT6CDoaxQ2+/bdn2RSUO0FjW9o3Aug2ENdYKxdLKRRdVcBEVkFYEZ
J5q+akCg04vv1ksL4UrSf/AL0ftH+gXCuQTBU51gLJ10ZEE1F0GRQS87T/tC3GmIsNlVfpgwROvu
aOGuufjguQ4OCclHNqx2RIyIP2HIi+YahbFOC6WFJL1zXvBBLhtC+j/aMgkVH0x0vG6J7MnpyOxy
w0WMiC+3sQdNfyea5kY77lgvJHm2claoLXSRlUz8yZB7G44LYELr3AcznWh/F8vfxiw3XOTspYDW
f17Udrwf7KEmMyzjEkaFYgE5fZm5H5X65vL/DOoCej8clwQzHby87ORvY5YbLhKI+GGrMedFCy1U
qGF3TAVU8iOFbJOCOnCBOUOQaYL3fgg5rywkxlrylaAhnsxVQ/jPUv9i0BB/kVVfCMeavxg0xLO5
aoiC+vFRWfJtqNAQBKAhCEBDEICGIAANQQAaggA0BAFoCALQEASgIQhAQxCAhiAADUEAGoIANAQB
aAgC0BBEcbt9ATZhuQV8mjteAAAAAElFTkSuQmCC
--a1b2c3d4--

Below is the code I tried
url = 'URL'
files = {'file': ('screenshot.png', 'base64 string')}

response = requests.post(url, auth=('*****', '******'), data={"item" : { "id": 1002345, "type": "type"
                },
                "name": "screenshot.png",
                "description": "This is screenshot"
}, files=files)

A: I believe this is what you want. Painful request to assemble! I included logging so you could see exactly what is coming out. They only way to get your content-type set on the json data was to add it as a file and manually set it with "None" filename.
import requests
import base64
import logging
import json

# Setup logging of raw requests
try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

# Setup your file
subheaders = dict()
subheaders["Content-Transfer-Encoding"] = "base64"
encodedImage = base64.b64encode(open("screenshot.png", "rb").read())

# Setup separate json data
payload = {"item" : { "id": 1002345, "type": "type" },
           "name": "screenshot.png",
           "description": "This is screenshot"}

# Build Files
files = { 'entity': (None, json.dumps(payload), 'application/json; charset=UTF-8'),
          'content': ("screenshot.png", encodedImage, "image/png", subheaders) }

# POST!
url = "http://localhost:5000"
response = requests.post(url, files=files)


text:
Q: Как сравнить даты Есть заранее известная дата.  Например, есть некий документ от 01.03.2018, действителен до 01.05.2018. И есть текущая дата. Как можно проверить осталось ли меньше месяца до 01.05.2018 или больше месяца? Никак не соображу как это можно проверить.

A: Добавьте к сегодняшней дате один месяц и сравните получившийся результат с нужной датой. Добавить месяц можно с помощью метода AddMonth:
var date = new DateTime(2018, 5, 1);
if (DateTime.Today.AddMonths(1) > date)
    Console.WriteLine("Меньше месяца");
else
    Console.WriteLine("Больше месяца");

Это же условие можно переписать по другому, если вам это более понятно (если дата окончания минус 1 месяц уже прошла, то осталось меньше месяца):
if (DateTime.Today > date.AddMonths(-1)) ...

Ну и имейте ввиду, что обычно юристы устанавливают всевозможные сроки в сутках, т. к. месяцы в году имеют разную продолжительность, поэтому, возможно, правильнее будет использовать метод AddDays, например:
if (DateTime.Today.AddDays(30) > date) ...

или, то же самое:
if ((date - DateTime.Today).TotalDays < 30) ...


text:
Q: Calculate the average from several columns and group by group_id I'm trying to calculate the averages from one table and put it in a new table that is grouped by group name in MySQL.
In the first table (called answers) I have survey answers from many groups. The answers are numerical values (INT, 1-7) and questions are grouped into question groups (culture, performance, etc.). All answers have a respondent name and they all belong to a group with a *group_id*. I'd like to aggregate the answers and calculate averages for all question groups and group by group_id.
For example. We can assume the data in answers looks like this:
||respondent | group_id | question_1 | question_2 | question_3| question_4 | question_5 | question_6||
||Joe        |1         |4           |3           |5          |4           |2           |2          ||
||Jane       |1         |3           |6           |6          |2           |1           |6          ||
||Jones      |1         |7           |3           |4          |1           |6           |4          ||
||Harry      |2         |2           |2           |3          |7           |5           |3          ||
||Pete       |2         |3           |5           |1          |4           |4           |5          ||
||Frank      |2         |1           |1           |2          |2           |7           |6          ||
||Sam        |3         |6           |7           |4          |6           |2           |2          ||
||Kim        |3         |3           |3           |6          |5           |1           |1          ||
||Todd       |3         |1           |4           |7          |4           |5           |7          ||

I'd now like to get the average for questions 1-3 into average_a and the averages from questions 4-6 into average_b into a different table (results) with all groups and grouped by group_id
Right now table answers looks like this:
 ||group_id|average_a|average_b||

    ||   1    | null  | null   ||

    ||   2    |  null | null  ||

    ||   3    |  null | null  ||

I'd like to UPDATE the results table to look like this:
||group_id|average_a|average_b||
||   1    |  4,5556 |  3,1111 ||
||   2    |  2,2222 |  4,7778 ||
||   3    |  4,5556 |  3,6667 ||

EDIT:
Adding some details on the original answers table:
+------------------------+------------------+------+-----+---------+----------------+

| Field                  | Type             | Null | Key | Default | Extra          |

+------------------------+------------------+------+-----+---------+----------------+

| id                     | int(10) unsigned | NO   | PRI | NULL    | auto_increment |

| Respondent             | varchar(20)      | YES  |     | NULL    |                |

| Email                  | varchar(39)      | YES  |     | NULL    |                |

| Website                | varchar(60)      | YES  |     | NULL    |                |

| Bransch                | varchar(60)      | YES  |     | NULL    |                |

| Koncern                | varchar(60)      | YES  |     | NULL    |                |

| Company                | varchar(60)      | YES  |     | NULL    |                |

| typ_av_enhet           | varchar(60)      | YES  |     | NULL    |                |

| avdelning              | varchar(60)      | YES  |     | NULL    |                |

| typ_av_avdelning       | varchar(30)      | YES  |     | NULL    |                |

| gruppid                | varchar(5)       | YES  |     | NULL    |                |

| survey_no              | varchar(5)       | YES  |     | NULL    |                |

| Grupp                  | varchar(28)      | YES  |     | NULL    |                |

| group_type             | varchar(60)      | YES  |     | NULL    |                |

| Kön                    | varchar(1)       | YES  |     | NULL    |                |

| Ålder                  | varchar(5)       | YES  |     | NULL    |                |

| Samarbetsträning       | varchar(1)       | YES  |     | NULL    |                |

| Samarbetserfarenhet    | varchar(1)       | YES  |     | NULL    |                |

| TaskClarity1           | varchar(1)       | YES  |     | NULL    |                |

| TaskClarity2           | varchar(1)       | YES  |     | NULL    |                |

| TaskClarity3           | varchar(1)       | YES  |     | NULL    |                |

Also here is the script that I tried using @stefan's instructions:
    <?php
$username = "root";
$password = "root";
$hostname = ":/Applications/MAMP/tmp/mysql/mysql.sock";

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
 or die("Unable to connect to MySQL");
echo "Connected to MySQL
";

//select a database to work with
$selected = mysql_select_db("ca",$dbhandle)
  or die("Could not select ca");

//delete old table
$delete_sql="Drop Table results";
// Execute query
if (mysql_query($delete_sql))
  {
  echo "Table deleted successfully";
  }
else
  {
  echo "Error deleting table: " . mysql_error();
  }

//create table
$sql="CREATE TABLE results(Group_id INT PRIMARY KEY, TaskClarity FLOAT)";

// Execute query
if (mysql_query($sql))
  {
  echo "Table results created successfully";
  }
else
  {
  echo "Error creating table: " . mysql_error();
  }

//Calculate task clarity
$task_clarity = "
INSERT INTO results (
    Group_id,
    TaskClarity
)
(
   SELECT
     gruppid ,
     AVG((TaskClarity1 + TaskClarity2 + TaskClarity3)/3) as average_task_clarity
   FROM
     answers
   GROUP BY
     gruppid
) ON DUPLICATE KEY UPDATE TaskClarity = VALUES(TaskClarity)"
;
$resource_retrive_task_clarity = mysql_query($task_clarity);    //execute the query
if (! $resource_retrive_task_clarity = mysql_query($task_clarity) ){
    echo "Error reading from table";
    die;
}

if (! mysql_num_rows($resource_retrive_task_clarity ) ){
    echo "No records found in table";
}
else {
echo "funkar";

}

//close the connection
mysql_close($dbhandle);
?>

A: Try this:
EDIT to update the results table (assuming that group_id column has UQ or PK index)
INSERT INTO results (
    group_id,
    average_a,
    average_b
)
(
   SELECT
     group_id ,
     AVG((question_1 + question_2 + question_3)/3) as za_average_a,
     AVG((question_4 + question_5 + question_6)/3) as za_average_b
   FROM
     answers
   GROUP BY
     group_id
) ON DUPLICATE KEY UPDATE
     average_a = VALUES(average_a),
     average_b = VALUES(average_b)

UPDATE The example is made here and it works

A: You can do like following:
 INSERT INTO new_table(`group_id`,`average_a`,`average_b`)
    SELECT group_id,(AVG(question_1 ) + AVG(question_2 )  + AVG(question_3 ))/3,
    (AVG(question_4 ) + AVG(question_5 )  + AVG(question_6 ))/3  FROM old_table
    GROUP BY group_id

A: You can use this:
SELECT GROUP_ID
,(SUM(question_1)+SUM(question_2)+SUM(question_3))/(3*COUNT(GROUP_ID)) AS Avg1
,(SUM(question_4)+SUM(question_5)+SUM(question_6))/(3*COUNT(GROUP_ID)) AS Avg2
FROM answers
GROUP BY Group_Id;

Here in /(3*COUNT(GROUP_ID) 3 is number of columns (q1,q2,q3) while COUNT(GROUP_ID) is number of rows for each GROUP_ID
See this SQLFiddle


text:
Q: How I can display Image on mouseover event on asp:linkButton I am using asp.net framework 3.5 and c# 2.0. I am able to bind data in to gridview.
Actually I want to display Image on mouseover event on asp:linkButton, which is used in grid view
<asp:GridView ID="gvTemplate" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" Width="100%"
    OnRowCommand="gvTemplate_RowCommand" OnRowDataBound="RowDataBound" OnPageIndexChanging="gvTemplate_PageIndexChanging">
                                                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <Columns>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Sr. No">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Left" />
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Template Name" ItemStyle-HorizontalAlign="Left">
            <ItemTemplate>
                <asp:LinkButton ID="lBtTempID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"tempName") %>'
                    CommandName='<%# DataBinder.Eval(Container.DataItem,"tempID") %>' CommandArgument="tempID" onmouseover="javascript:showImage(this.id)"/>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Template Type">
            <ItemTemplate>
                <asp:Label ID="lbltempType" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"tempType") %>' />
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Left" />
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <EditRowStyle BackColor="#999999" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>

A: If you can use jquery it would be like this
    $('.lBtTempClass').mouseover(function() {
///  Do your code
    });

you should add a css class to link button
<asp:LinkButton ID="lBtTempID" CssClass="lBtTempClass" runat="server" >


text:
Q: Pressing tab takes me from subject to under the signature I'm not sure if this is a bug or a configuration issue in Thunderbird 45.2.0 (latest).
When writing a message from an email account that comes with an html signature (external file), pressing the tab key on the keyboard to navigate from address to subject to email-body, moves the cursor from the subject line to under the signature.
Is there anything I can do, i.e. change a setting or change the html-signature, so that the cursor goes where it should?


text:
Q: How to check if modal view controller failed to display? I have an app that uses modal view controllers for various purposes. Most importantly for this question, we use a modal controller to display the login screen when a user is logged out.
The issue I ran into is that it appears that presentModalViewController:animated: will fail silently if another modal controller is being animated on or off screen when the call is made. It will print to the debug console with a warning, but the method itself doesn't return a BOOL or throw an exception, so I can't seem to check in code whether it failed so I can retry it in a second.
Is there some way to detect that the controller failed to display immediately after calling this method?

A: So as I was typing this question, I realized I could check presentingViewController (or parentViewController) to see if it was displayed, and if nil, try again.
Tested and it works. Figured I'd post and answer the question anyway for others to find that may run into a similar issue.

Aa few more things I noticed in testing:

*

*It looks like if the modal view is not displayed with an animation, it will be successful even if another modal view is animating when you make the call.

*Calling dismissModalViewControllerAnimated:NO on the controller you are displaying off of, before presenting the modal controller with animation, will also allow it to complete successfully even if another controller is animating.


text:
Q: Large 2D array in C - Stack OverFlow error I haven't used C in long time, and I'm having an issue filling a 2D array from a CSV. The file format is like this:
Node, In, Out
1,200,10393
...
This is essentially an array representation of a linked list. There are 150000 elements and whenever I try to fill the array I get an error saying
     "Unhandled exception at 0x000000013facb957 in main.exe: 0xC00000FD: Stack overflow."
I'm on a 64-bit machine with 16GB of RAM and I'm using VS C++ 2010 Express with an x64 build configuration.
int main(int argc, char *argv[])
{

int counter = 0;
char line [ 1024 ];
int map[150000][2] = {0};
char *comma = ",";
char *token;
int index;
int in, out;
char* end;
int nodeID;
FILE *fp;

fp = fopen("mapsorted.txt","r"); // read mode

if( fp == NULL )
{
  perror("Error while opening the file.\n");
  exit(EXIT_FAILURE);
}

//Skip header line
fgets ( line, sizeof line, fp );

while ( fgets ( line, sizeof line, fp ) != NULL) /* read a line */
{
    //first part - the index for storage
    token = strtok(line,comma);
    index = strtol(token,&end,10);

    //second part
    token = strtok(NULL,comma);
    in = atoi(token);

    //third part
    token = strtok(NULL,comma);
    out = atoi(token);

    //store in array
    map[index][0] = in;
    map[index][1] = out;
}
fclose ( fp );
}

The code seems to work when I allocate a smaller array, but fails when it is this large. I think I should have enough memory to be able to handle an array of this size.

A: int map[150000][2];

seems at least 2 * 4 * 150000 bytes (assuming a modern 32-bit architecture), which is roughly 1.2MB. Knowing that modern OSes typically set up a stack size of a few megabytes, this could actually be the problem. Your computer having several gigabytes of RAM doesn't mean all of it can be consumed by your process, especially not on the stack. For large arrays, try malloc()ating some memory on the heap:
int (*map)[2] = malloc(sizeof(*map) * 150000);

or
int *map = malloc(150000 * 2 * sizeof(*map));

(pay attention to the dimensions in the second case!), or declare it as static to move it out of stack space:
static int map[150000][2];

Or simply make it a global variable to achieve a similar behavior:
int map[150000][2];

void foo()
{
    ...
}

A: The array is too big to fit in the stack. Try moving it outside of the function:
static int map[150000][2] = {0};
int main(int argc, char *argv[])
{

and so on.


text:
Q: how to use searchController with two arrays I have two arrays (first names, Last names) in my TableView (cell.textLabel and cell.detailTextLabel)
I want to make a search bar in this TableView.
I have created class with two string.
@interface clientContent : NSObject { }
@property (nonatomic, strong) NSString *clName;
@property (nonatomic, strong) NSString *clLast;
@end

then I have created array in main class (which have Table view) and added my information
like this
    for (int i = 0; i < PQntuples(clientQuery); i++)
{
    clientContent *cc = [[clientContent alloc] init];
    cc.clName = [[NSString alloc] initWithUTF8String:PQgetvalue(clientQuery, i, 0)];
    cc.clLast = [[NSString alloc] initWithUTF8String:PQgetvalue(clientQuery, i, 1)];
    [allClients addObject:cc];
}

after this I load it into tableView;
clientContent *cc = [allClients objectAtIndex:indexPath.row];
    cell.textLabel.text = cc.clName;
    cell.detailTextLabel.text = cc.clLast;
}

Then I use
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

How to make it right? I can't understand..

A: You should override searchDisplayController:shouldReloadTableForSearchString: delegate method of UISearchDisplayController and filter datasource array for searchResultsTableView as you want.
You can apply predicate on your array(array of clientContent object) and change dataSource array. Using predicate you can filter your array on both fields(clName & clLast).
You can get help related to predicates from https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/Reference/NSPredicate.html


text:
Q: Calculate Overtime based on a sum of columns I would like to calculate hours worked that are over 40 per week.
table = shift_log_data
database = shift_logs

Field           Type            Null    Key     Default     Extra
id              int(100)        NO      PRI     NULL    auto_increment
admin_hrs       decimal(20,2)   NO              0.00
shop_hrs        decimal(20,2)   NO              0.00
fab_hrs         decimal(20,2)   NO              0.00
paint_hrs       decimal(20,2)   NO              0.00
vacation_hrs    decimal(50,2)   NO              0.00
control_hrs     decimal(20,2)   NO              0.00
test_hrs        decimal(20,2)   NO              0.00
engine_hrs      decimal(20,2)   NO              0.00
hydraulic_hrs   decimal(20,2)   NO              0.00
699_paint       varchar(100)    NO              0.00
699_shop        varchar(100)    NO              0.00
maint_hrs       varchar(100)    NO              0.00
date            date            NO              NULL
name            varchar(50)     NO              NULL
job             varchar(50)     NO              NULL

Need the columns admin_hrs through maint_hrs total per week using the date field.
If hours are greater than 40 hours per week, make an alias called overtime showing the rest of the hours greater than forty.
I have tried.
SELECT SUM(overtime)
  FROM
  (
    SELECT name,
           IF(SUM(test_hrs+fab_hrs+control_hrs+shop_hrs+paint_hrs+engine_hrs+hydraulic_hrs)>40,
             SUM(test_hrs+fab_hrs+control_hrs+shop_hrs+paint_hrs+engine_hrs+hydraulic_hrs))-40,
              0) AS overtime
      FROM shift_log_data
     GROUP BY name
  ) TOTAL_OVERTIME

A: Try this:
SELECT s.Name, YEAR(s.Date), WEEKOFYEAR(s.date),
      IF(SUM(test_hrs+fab_hrs+control_hrs+shop_hrs+paint_hrs+engine_hrs+hydraulic_hrs)>40,
          SUM(test_hrs+fab_hrs+control_hrs+shop_hrs+paint_hrs+engine_hrs+hydraulic_hrs))-40,
          0
         ) AS overtime
FROM shift_log_data s
GROUP BY s.Name, YEAR(s.Date), WEEKOFYEAR(s.date);


text:
Q: Stop the row selection change of datagridview in C# I'm making a program in which we can edit or insert record through data grid view by just pressing the enter key. The problem is that whenever I write a value in any cell and press enter, the row selection changes to the next row.
When I press enter key, i want it to not change the selected row. It should just get out of cell editing or move to the next cell.
I had the same problem on enter press when the row was just selected. I solved it by subtracting one from row index, but how do I solve this with the cell issue?

A: You would think that there would be a property in the grid to change how the selection moves when the enter key is pressed. Unfortunately, the DataGridView does not have this property. I am guessing a third-party library may have a grid with this feature.
Below is a possible solution taken from an answer by @Cody Gray. DataGridView keydown event not working in C#... His answer touches on the problem when trying to wire-up the grids KeyDown or other "Key" events that are for the "GRID." Meaning that when the user is "editing" in a cell, those events will not fire. In most cases, you should use the grids EditingControlShowing event to capture the individual cell key events. This appears simple enough; however, it is unclear "when" this should be done.
Example, using either solution below will work as described by moving the selection horizontally and not vertically when the user presses the enter key… HOWEVER…. this ONLY works IF the user is "editing" a cell when the "Enter" key is pressed. If the user simply "clicks" on a different cell then presses the "Enter" key the selection will move down.
I am confident that you could get this to work for the cases when the cell is NOT being edited. The question I would ask… Is it worth the effort to turn the "Enter" key into a "Tab" key? If you were to implement this beyond the cell being edited, I am confident that you will realize after you implement this that the functionality you just implemented is already available in the "Tab" key. Just a thought on reinventing the wheel.
As Cody's answer alludes to, it is not straight forward to do what you are describing using the "DataGridView" base events. This solution basically creates a Class that inherits from the DataGridView and overrides the grids ProcessCmdKey event. Here you can implement the behavior described, however, as stated above, the horizontal movement will only happen if the cell is being edited.
class MyDataGridView : DataGridView {

  protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) {
    if ((keyData == (Keys.Enter))) {
      if (this.CurrentCell.IsInEditMode) {
        Point lastPosition = new Point(this.CurrentCell.ColumnIndex, this.CurrentCell.RowIndex);
        if (lastPosition.X == this.ColumnCount - 1) {
          lastPosition.X = 0;
          lastPosition.Y++;
        }
        else {
          lastPosition.X++;
        }
        this.CurrentCell = this.Rows[lastPosition.Y].Cells[lastPosition.X];
      }
    }
    return base.ProcessCmdKey(ref msg, keyData);
  }
}

@Asaf 's answer in the same link above, supplied an example using the grids base events. A full example is below using both approaches. Drop a DataGridView and a myDataGridView onto a form for the code to work properly. Hope this helps.
DataTable GridTable;
DataTable GridTable2;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  GridTable = GetTable();
  FillTable(GridTable);
  dataGridView1.DataSource = GridTable;
  GridTable2 = GetTable();
  FillTable(GridTable2);
  myDataGridView1.DataSource = GridTable2;
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Col1", typeof(string));
  dt.Columns.Add("Col2", typeof(string));
  dt.Columns.Add("Col3", typeof(string));
  dt.Columns.Add("Col4", typeof(string));
  return dt;
}

private void FillTable(DataTable dt) {
  for (int i = 0; i < 15; i++) {
    dt.Rows.Add("C1R" + i, "C2R" + i, "C3R" + i, "C4R" + i);
  }
}

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
  if (e.Control is DataGridViewTextBoxEditingControl) {
    DataGridViewTextBoxEditingControl tb = e.Control as DataGridViewTextBoxEditingControl;
    tb.PreviewKeyDown -= dataGridView1_PreviewKeyDown;
    tb.PreviewKeyDown += dataGridView1_PreviewKeyDown;
  }
}

private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
  if (e.KeyData == Keys.Enter) {
    //if (dataGridView1.CurrentCell.IsInEditMode) {
      Point lastPosition = new Point(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex);
      if (lastPosition.X == dataGridView1.ColumnCount - 1) {
        lastPosition.X = 0;
        lastPosition.Y++;
      }
      else {
        lastPosition.X++;
      }
      dataGridView1.CurrentCell = dataGridView1.Rows[lastPosition.Y].Cells[lastPosition.X];
    //}
    //else {
      // good luck here
    //}
  }
}