text:
Q: handling huge size of data using arraylist I have got an assignment question in java.
I have a text file in the size of GBs. Read it, and find the number of occurrence of each word in that file and display it like [<< word >> - <>].
Best case would be all the words are same. so i will display that word with no of occurrence
but consider the worst case like words present in the file are unique. so i need to display all the words with occurrence as 1.
How to handle this huge list of data ? Do we have any solution for this ?

A: Ideally, writing Map-Reduce program in java could be the best approach for this.
Here is an example for word count program using Map-Reduce paradigm : Word Count Example
Other approach could be perform this using recursive read/write operations.
Create a Map (one map per alphabet) so that you can have 26 maps with you. Put words in appropriate maps depending on the starting alphabets. When certain map size is reached, write all the words from that map along with its incremented count to a file with some identification to know which words it contains. Once you have read all the words from your file (size in GB's), read back the files from disk and calculate the word count. this will involve some IO, but I think will no cause any memory related issues.


text:
Q: Local DC/OS is unreachable I have a DC/OS local installation using vagrant. I have restarted my Mac machine and power up the virtual machines on which dc/os is installed. Still I not not able to open the GUI. When I give docs service command on CLI, I get the following error
URL [http://m1.dcos/mesos/master/state.json] is unreachable.

A: The response I got from mesosphere:
It would be good if you can login to your master node with:
vagrant
 ssh m1
And run the following command:
sudo
 systemctl status dcos-adminrouter.service
I have cleaned up the vagrant environment and set up again. I am not facing the problem yet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you set HTTP header before posting Pretty sure I know the answer to this one, but want to make sure I'm not missing something...
Running ASP.NET 4.0 and have a request where I need to send a user to a 3rd party app but set an HTTP header value before doing so. This would be a Request header. I can set the Response Header no problem but am unable to do so with Request headers as the collection is read-only. Essentially, the process is as follows:

*

*User clicks button to initiate transfer to 3rd party app

*Page posts back and we grab user info - at this point I need to set the header

*Issue a Response.Redirect and send them to the 3rd party app.

Note: I'm not stuck on a Response.Redirect; I could change the form to POST to the 3rd party app simply as a means of transferring the user, that's fine.
I believe I could setup an IIS rewrite rule to set the header (based on this article: http://learn.iis.net/page.aspx/686/setting-http-request-headers-and-iis-server-variables/) but I don't want to go that route as the header value will contain a UserID and I'd rather not expose that to the user at all - even for a brief moment. I certainly understand that even a header isn't invisible as someone could inspect the page, but I'm not concerned with that.
Any ideas would be a great help.
Thanks,
Ryan

A: How about:
using System.Net;

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
req.Headers.Add(new HttpRequestHeader(), "my header content");


text:
Q: Javascript + HTML - load image in the background (asynchronously?) I've found many topics describing javascript image loading but not exactly what I am searching for.
I am currently loading images in html the normal way, like

This results in a webpage where you have empty spaces that are filled with the loading image from top to bottom. In addition I always have to watch the filesize of the image.
What I want to achieve is that when the page loads, a downscaled version of every image (around 10kb) is shown. When the page is fully loaded, there should be a javascript function which loads the big images in the background and replaces them when they are loaded.
I already found a way to do this with javascript but until all images are replaced the browser shows that he is in "loading" state. Is it possible to do the loading task in the background by using asynchronous methods?

A: Have you tried this?
window.onload = function() {
    setTimeout(function() {
        // XHR to request a JS and a CSS
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://domain.tld/preload.js');
        xhr.send('');
        xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://domain.tld/preload.css');
        xhr.send('');
        // preload image
        new Image().src = "http://domain.tld/preload.png";
    }, 1000);
};

http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

A: Do you know what is really annoying? If you just miss to add the window.onload function to your own solution and it works as you wanted...
Thanks for you idea! :D


text:
Q: Prevent slick.js to open link onclick next I´m using slick.js slider in my angularJs web app. The plugin is working fine. I have the prev and next pagination buttons. All slick code is inside an anchor link to another page. When, I click in the prev or next button, the slick is sliding but the link is opened as well. So, I would like to prevent to open the link on buttons click that are styled over the link.
Please see simplified structure.

When the code is parsed, the buttons re created like: <button class="slick-next slick-arrow" aria-label="Next" type="button" style="display: inline-block;">Next</button>
As said, when I click in the button, the slider works but the link is opened as well.

A: You might want to listen for click events on the  element and check if event.target.classList.contains('slick-arrow') is true and, in that case, call event.preventDefault() to prevent the link from opening.
In your template:

In your component:
handleLinkClicked(e: ClickEvent) {
    if (e.target.classList.contains('slick-arrow')) e.preventDefault();
}

Otherwise, you could also try moving the  inside slick, maybe replacing the
 if that works for you:


text:
Q: Display message in WooCommerce email notifications when order has backorder items in it I am trying to display a specific message on the Order confirmation email IF one of several products of your order is/are on backorder.
I am struggling to get the right function to scan all the products and get my boolean working.
My current code:
add_action( 'woocommerce_email_after_order_table', 'backordered_items_checkout_notice_email', 20, 4 );
function backordered_items_checkout_notice_email( $order, $sent_to_admin, $plain_text, $email ) {
  $found2 = false;
  foreach ( $order->get_items() as $item ) {
            if( $item['data']->is_on_backorder( $item['quantity'] ) ) {
            $found2 = true;
            break;
        }
    }

    if( $found2 ) {
        if ( $email->id == 'customer_processing_order' ) {echo ' '.__('⌛ One or several products are Currently out of stock.
Please allow 2-3 weeks for delivery.', 'plugin-mve').'
';}

    }
}

With this code, when you click on "Order" the page just freezes and no email is sent. But I get the order in the backend.
Could anyone give me a hand to fix?

A: Your code contains a CRITICAL uncaught error, namely: Call to a member function is_on_backorder() on null
Following code will add the message for the customer_processing_order email notification. Also see: How to target other WooCommerce order emails
So you get:
function action_woocommerce_email_after_order_table( $order, $sent_to_admin, $plain_text, $email ) {
    // Initialize
    $flag = false;

    // Target certain email notification
    if ( $email->id == 'customer_processing_order' ) {
        // Iterating through each item in the order
        foreach ( $order->get_items() as $item ) {
            // Get a an instance of product object related to the order item
            $product = $item->get_product();

            // Check if the product is on backorder
            if ( $product->is_on_backorder() ) {
                $flag = true;

                // Stop the loop
                break;
            }
        }

        // True
        if ( $flag ) {
            echo '
' . __( 'My message', 'woocommerce' ) . '
';
        }
    }
}
add_action( 'woocommerce_email_after_order_table', 'action_woocommerce_email_after_order_table', 10, 4 );


text:
Q: Fresh Anaconda Navigator install, Jupyter notebook keeps showing connection error I'm brand new to coding and have downloaded Anaconda to use Jupyter Notebook. However, I keep getting an error, cannot connect to network. I have looked around and tried a bunch of different fixes, none of which have worked. I've reinstalled Anaconda several times, tried opening Jupyter at ip=127.0.0.1 port=9999, VPN on and off. It's been a couple days now so I'm really hoping someone can help. Below is what shows up in Anaconda Prompt when I try to open a notebook. Not sure if it's related but Jupyter Notebook also won't launch from Anaconda Navigator, I HAVE to use Anaconda Prompt to launch it. I'm completely new to coding so any help would be greatly appreciated.
To access the notebook, open this file in a browser:
      file:///C:/Users/Gerad%20Collingwood/AppData/Roaming/jupyter/runtime/nbserver-22504-open.html
  Or copy and paste one of these URLs:
       http://localhost:8888/?token=2ef67e00adc18a197a353c6807983fc62bd1e5423a3788af
    or http://127.0.0.1:8888/?token=2ef67e00adc18a197a353c6807983fc62bd1e5423a3788af`
`[I 11:22:50.281 NotebookApp] Creating new notebook in /Python Codes`
`Bad address (C:\ci\zeromq_1602704446950\work\src\epoll.cpp:100)`
[I 11:22:53.527 NotebookApp] Kernel started: cd50ffe9-3bae-48a6-a2a7-9fccfdf64f3d, name: python3
`Bad address (C:\ci\zeromq_1602704446950\work\src\epoll.cpp:100)`
`Exception in thread Thread-4:`
`Bad address (C:\ci\zeromq_1602704446950\work\src\epoll.cpp:100)`
`Traceback (most recent call last):`
`File "C:\Users\Gerad Collingwood\anaconda3\lib\threading.py", line 932, in _bootstrap_inner
   self.run()`
 `File "C:\Users\Gerad Collingwood\anaconda3\lib\threading.py", line 870, in run
   self._target(*self._args, **self._kwargs)`
 `File "C:\Users\Gerad Collingwood\anaconda3\lib\site-packages\ipykernel\iostream.py", line 78, in _thread_main
   self.io_loop.start()`
 `File "C:\Users\Gerad Collingwood\anaconda3\lib\site-packages\tornado\platform\asyncio.py", line 199, in start
   self.asyncio_loop.run_forever()`
`File "C:\Users\Gerad Collingwood\anaconda3\lib\asyncio\base_events.py", line 570, in run_forever
   self._run_once()`
 `File "C:\Users\Gerad Collingwood\anaconda3\lib\asyncio\base_events.py", line 1823, in _run_once
   event_list = self._selector.select(timeout)`
 `File "C:\Users\Gerad Collingwood\anaconda3\lib\selectors.py", line 323, in select
   r, w, _ = self._select(self._readers, self._writers, [], timeout)`
 `File "C:\Users\Gerad Collingwood\anaconda3\lib\selectors.py", line 314, in _select
   r, w, x = select.select(r, w, w, timeout)`
`OSError: [WinError 10038] An operation was attempted on something that is not a socket


text:
Q: What is the difference between "CPU samples" tab and "Thread CPU Time" tab of visualvm sampler? When I use visualvm, I get confused about "CPU samples" tab and "Thread CPU Time" tab of the sampler. The following screenshots show the same thread "Monitor Ctrl-Break" respectively in these two tabs:
CPU time in "CPU samples" tab is 1082903ms.
CPU time in "Thread CPU Time" tab is only 15.6ms!
My questions:

*

*Why the CPU time in these two tabs differ so much?

*What is the meaning of these two CPU time? In other words, which parts do these two CPU time consist of?
Looking forward for some replies. Thank you all.

A: The difference comes from the fact that the JVM does not know whether a native method blocks or not.
Consider a simple example:
public class Test {
    public static void main(String[] args) throws Exception {
        System.in.read();
    }
}

If the standard input is console, and a user have not typed anything, the method InputStream.read will block. If the standard input is a file on a disk, read will immediately return the first byte of the file. The JVM does not distinguish these two cases; it happens on the OS level. From the JVM perspective, a thread executing FileInputStream.read method is always in RUNNABLE state, even though the underlying I/O may block on the OS level.
CPU sampler in VisualVM treats RUNNABLE threads as if they consume CPU.
On the contrary, Thread CPU time tab gets statistics directly from the OS, and thus shows the real CPU usage.
So if a thread blocks inside a native method like read, it is considered runnable from the JVM perspective, but idle from the OS perspective. In fact, such method does not consume CPU time, but VisualVM sees that a thread is RUNNABLE and counts it as busy.
VisualVM is not the only profiler that suffers from this problem. This is actually a common fallacy of all sampling profilers based on the standard Java API to get thread stack traces. Find more details in my presentation.


text:
Q: Julia `mapslices` when output dimension exceeds input dimension I'm trying to apply a function f(x::Array{Float64, 1}) -> Array{Float64, 2} to each row in an m x n array in Julia (I'm using v1.1, if it's relevant).
Now, I was hoping that I could simply apply mapslices as follows:
# toy example of f
f = (x -> randn(length(x), length(x)))
A = randn(100, 50)

# intent: apply f to every row in A and collect the result into a 100 x 50 x 50 matrix.
result = mapslices(f, A, dims=2)

Unfortunately, mapslices fails with the following message:

ERROR: DimensionMismatch("tried to assign 2 elements to 1 destinations")

Is there a mapslices analogue for this situation? I know I can do this with a for loop but I was hoping for something easier.
Update: apparently one way to do this is to embed A into a 3-D array:
result = mapslices(f, reshape(A, (size(A)..., 1)), dims=[2, 3])

A: I tried only with Julia v1.6, but I think you can very literally "apply f to each row" with eachrow (which appeared in Julia v1.1):
julia> f(x) = randn(length(x), length(x))
f (generic function with 1 method)

julia> A = rand(3,2)
3×2 Matrix{Float64}:
 0.47239    0.179252
 0.542389   0.25828
 0.0513623  0.630193

julia> f.(eachrow(A))
3-element Vector{Matrix{Float64}}:
 [-2.183245554875081 -0.16762649791435957; 0.9124553173227186 0.9148972946316921]
 [-0.7322553194397725 -0.5844536492551982; 0.37738478201981623 -0.7056092457600269]
 [1.0091890849396576 1.6451194487283958; 0.674221636656597 1.0509408618443663]

A: mapslices isn't very flexible. Here's a variant of what you ask, done without it:
julia> f(x::AbstractVector) = x .* x';  # vector -> matrix

julia> A = randn(5, 7);

julia> f(A[1,:]) |> size
(7, 7)

julia> reduce(hcat, map(f, eachrow(A))) |> size
(7, 35)

julia> B = reshape(reduce(hcat, map(f, eachrow(A))), (7,7,5));

julia> B[:,:,3] ≈ f(A[3,:])
true

Here reduce(hcat, ...) is combining matrices from f along their 2nd direction; we need reshape to separate again the first index of A which has become the last index of B -- which of the 5 rows made this slice.
There are also many package solutions:
julia> using JuliennedArrays

julia> Slices(A,2) |> size  # like eachrow
(5,)

julia> C = Align(map(f, Slices(A,2)), 1,2);  # size (7, 7, 5)

julia> C ≈ B
true

julia> D = Align(map(f, Slices(A,2)), 2,3);  # size (5, 7, 7)

julia> D[3,:,:] ≈ f(A[3,:])
true

julia> using TensorCast

julia> @cast C2[i,j,k] := f(A[k,:])[i,j];  # := makes a new array

julia> C2 ≈ B
true

julia> @cast D2[k,i,j] := f(A[k,:])[i,j];

julia> D2 ≈ D
true


text:
Q: Collecting users who reacted to a message using discord.js I'm trying to collect all users that have reacted to certain message.
My code
client.on('messageReactionAdd', (reaction, user) => {
    if(reaction.emoji.name === "✅") {
    console.log(reaction.emoji.users);
}

But it returns undefined. If I use "reaction.emoji" it returns
ReactionEmoji {
  reaction:
   MessageReaction {
     message:
      Message {
        channel: [Object],
        id: '371695165498458115',
        type: 'DEFAULT',
        content: 'bb',
        author: [Object],
        member: [Object],
        pinned: false,
        tts: false,
        nonce: '371695172469129216',
        system: false,
        embeds: [],
        attachments: Collection {},
        createdTimestamp: 1508689433217,
        editedTimestamp: null,
        reactions: [Object],
        mentions: [Object],
        webhookID: null,
        hit: null,
        _edits: [] },
     me: true,
     count: 1,
     users: Collection { '370300235030986752' => [Object] },
     _emoji: [Circular] },
  name: '✅',

I'm trying to get the users: Collection { '370300235030986752' => [Object] }, part. Thanks in advance.

A: According to the docs it is just reaction.users:
client.on('messageReactionAdd', (reaction, user) => {
    if(reaction.emoji.name === "✅") {
        console.log(reaction.users);
    }
});


text:
Q: referencing and storing the strong name externally for reuse I have a lot of assemblies that have set the InternalsVisibleToAttribute pointing one specifc  assembly within the same solution. Unfortunately the assembly that is being pointed to has a stong name, so I always have to put the same public key token over and over again into the AssemblyInfo.cs files. Since  there is no precompiler in c#, how would I ideally eliminate this redundancy.

A: You have a couple of easy-ish options:

*

*Use a constant instead of a literal in your AssemblyInfo.cs files.

*Add this attribute to a shared file (e.g.: CommonFriendAssemblies.cs) that is linked rather than copied into your individual projects.

#1 is somewhat simpler to manage, but it has the unfortunate side-effect of removing IntelliSense support for the referenced internals in the referencing project.
#2 is somewhat more complex to manage, but it doesn't interfere with IntelliSense support.

A: maybe you could use t4
rename AssemblyInfo.cs to AssemblyInfo.tt
and add something like this
<#@ template language="C#v3.5" hostspecific="True" debug="True" #>
<#@ output extension="cs" #>

[assembly: InternalsVisibleTo("<# Write(System.Reflection.Assembly.GetExecutingAssembly().FullName); #>")]


text:
Q: Make jQuery Datatable fit content area I am trying to use jQuery Datatables for the first time. I am getting data back from a web service then massaging it in to  the format that Datatables expects(Javascript array of data and one for columns). My issue is I am trying to make this in to a widget to place on a dashboard so the container is small and I need the datatable to fit in to it both height and width.

Table

var createNewTable = function (data) {

var aoColumn = _.map(_.first(data), function (row) {
    return {
        'sTitle': row.Key
    };
});
var aaData = _.map(data, function (row) {
    return _.map(row, function (innerRow) {
        return innerRow.Value;
    });
});
$('.portlet-content').append('

');
$('#t_container').dataTable({
    "bAutoWidth": false,
        "aaData": aaData,
        "aoColumns": aoColumn
});

};
full code example can be seen in this fiddle:
http://jsfiddle.net/2ccgk/3/

A: I don't have enough rep to comment, but the bottom line is you are going to have to style your table to fit.  Reduce the font, padding, etc. and set the widths of each column until it fits in the container.  Its not going to be an easy task with so many columns in such a small container.


text:
Q: Data not being added to dynamodb even though response returned is 200 Below is my response from dynamodb transct_write_item. But data is not saved to my table.
{
   "ResponseMetadata":{
      "RequestId":"*******",
      "HTTPStatusCode":200,
      "HTTPHeaders":{
         "server":"Server",
         "date":"Fri, 11 Feb 2022 08:14:50 GMT",
         "content-type":"application/x-amz-json-1.0",
         "content-length":"2",
         "connection":"keep-alive",
         "x-amzn-requestid":"*******",
         "x-amz-crc32":"********"
      },
      "RetryAttempts":0
   }

Here is the data I am adding
[
   {
      "Put":{
         "TableName":"test_data",
         "Item":{
            "pk":"test",
            "order_id":"abc",
            "created_at":1644567288980,
            "updated_at":1644567288980
         }
      }
   }
]

Is there anything I am missing?


text:
Q: Why ternary operator doesn't replace if-else I've met a little problem and a knowledge gap
I found using If-Else style is too boilerplate sometimes and wanted to replace it with elvis-operator, for example:
Dictionary<string, List<List<int>> VarsWithInfo;

want to replace:
if (VarsWithInfo.ContainsKey(ruleVar))
    {
        VarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks };
    }
else
    {
        VarsWithInfo[ruleVar].Add(NestingBlocks);
    }

with that:
VarsWithInfo.ContainsKey(ruleVar) ?
    VarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks } :
    VarsWithInfo[ruleVar].Add(NestingBlocks);

I know that line with ternar operator is too long in this case, but I want to know the primary reason.
Thank you.

A:
The conditional operator ?:, commonly known as the ternary conditional operator, evaluates a Boolean expression, and returns the result of evaluating one of two expressions, depending on whether the Boolean expression evaluates to true or false

From MSDN
The ternary operator always returns a value. In the expression x = a ? b : c, if a is true then it will assign the value of b to x, otherwise it will assign the value of c to x.
Therefore both b and c need to be expressions which result in a value, and both of those values need to be of the same type.
Neither VarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks } nor VarsWithInfo[ruleVar].Add(NestingBlocks) are expressions, and they do not return a value. Therefore they cannot be used in a ternary.

I'm assuming your code was supposed to be:
if (!VarsWithInfo.ContainsKey(ruleVar))
{
    VarsWithInfo[ruleVar] = new List<List<int>> { NestingBlocks };
}
else
{
    VarsWithInfo[ruleVar].Add(NestingBlocks);
}

A common way of writing this is:
if (!VarsWithInfo.TryGetValue(ruleVar, out var list))
{
    list = new List<List<int>>();
    VarsWithInfo[ruleVar] = list;
}
list.Add(NestingBlocks);

This avoids the duplicate dictionary lookup (i.e. calling VarsWithInfo.ContainsKey(ruleVar) and then reading from VarsWithInfo[ruleVar]).


text:
Q: Create new data in registry key? I just create new registry key called MyTestApp, and want to add new data in it, but don't know how.  So I have following code.
bool CreateSectionDataRegistry(CString sectionData, CString sectionValue)
{
    HKEY hKey;      //registry key handle
    LONG lResult;   //result of registry operations
    DWORD dwType, dwSize=0;

    //try to open the key that we are currently pointing at with rootPath
    lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, rootPath + "\\" + "MyTestApp", NULL, KEY_ALL_ACCESS, &hKey);

    if (lResult == ERROR_SUCCESS || lResult == ERROR_MORE_DATA)
    {
        //we have successfully opened the registry key. Now try to access the data
        lResult = RegQueryValueEx(HKEY_LOCAL_MACHINE, sectionData, 0, &dwType, NULL, &dwSize);

        if(lResult == ERROR_SUCCESS || lResult == ERROR_MORE_DATA)
        {
                          //data already exists, so just return
            RegCloseKey(hKey);
            return true;
        }
        else//section data does not exist, so create new data
        {
            DWORD dwDisposition;
            lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE, sectionData, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisposition);
            RegCloseKey(hKey);
            return true;
        }
    }

    return false;
}

But when I trace down to the RegCreateKeyEx() call, it returns success but data is not created under the MyTestApp registry key or anywhere in the registry.  Am I using the correct function to create new data under MyTestApp.  Also from the argument above, I have CString sectionValue, so how do I check if I need to create data for REG_SZ or REG_DWORD?
Thanks!

A: It seems I just need to call RegSetValueEx() to create registry value under MyTestApp.  Probably just me but when I look at the RegSetValueEx() definition in Microsoft website, it says set the value, but it does not say if value does not exist, it will create the value.
LPTSTR lpszData = new TCHAR[sectionValue.GetLength() + 1];
_tcscpy(lpszData, sectionValue);
lResult = RegSetValueEx(hKey, sectionData, 0, REG_SZ, (LPBYTE)lpszData, sectionValue.GetLength());

So now it creates the registry value, however I cannot still tell if sectionValue is REG_SZ or REG_DWORD.


text:
Q: (OpenCV Stitching) How to get better performance using OpenCV Stitcher class? I have some problems when using Stitcher class.
First, I use ORB Feature Finder because it's faster than SURF.
but it's still slow.
Second, Stitcher class accuracy is too low.
Third, How can I get more performance by using Stitcher class?
Additional, How can I catch directions between two images?
This is my code.
Thank you.
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/stitching.hpp"
#include "opencv2/features2d.hpp"

using namespace cv;
using namespace std;

void overlayImage(const cv::Mat &background, const cv::Mat &foreground, cv::Mat &output, cv::Point2i location);

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

 Mat first;
 Mat second;
 Mat m_first;
 Mat m_second;
 vector<Mat> images;
// vector<Mat> re_images;
 Mat panorama;
 Mat result;
 unsigned long t;
 t = getTickCount();
 first = imread(argv[1], CV_LOAD_IMAGE_COLOR);
 second = imread(argv[2], CV_LOAD_IMAGE_COLOR);
 //Mat m_first = Mat::zeros( first.size(), first.type() );
 //Mat m_second = Mat::zeros( second.size(), second.type() );
 /*
for( int y = 0; y < first.rows; y++ ) {
    for( int x = 0; x < first.cols; x++ ) {
         for( int c = 0; c < 3; c++ ) {
          m_first.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( 1.2*( first.at<Vec3b>(y,x)[c] ) + 20 );
     }
    }
}

for( int y = 0; y < second.rows; y++ ){
 for( int x = 0; x < second.cols; x++ ) {
         for( int c = 0; c < 3; c++ )  {
      m_second.at<Vec3b>(y,x)[c] =
         saturate_cast<uchar>( 1.2*( second.at<Vec3b>(y,x)[c] ) + 20 );
    }
    }
}
*/
//imwrite("first.png", m_first);
//imwrite("second.png", m_second);
 resize(first, m_first, Size(640, 480));
 resize(second, m_second, Size(640, 480));
 images.push_back(m_first);
 images.push_back(m_second);

 Stitcher stitcher = Stitcher::createDefault(false);
 //Stitcher::Status status = stitcher.stitch(imgs, pano);
 //stitcher.setWarper(new PlaneWarper());
 stitcher.setWarper(new SphericalWarper());
// stitcher.setWarper(new CylindricalWarper());
 stitcher.setFeaturesFinder(new detail::OrbFeaturesFinder(Size(3,1),1500));
//        stitcher.setRegistrationResol(0.6);
//        stitcher.setSeamEstimationResol(0.1);
//        stitcher.setCompositingResol(0.5);
//stitcher.setPanoConfidenceThresh(1);
        stitcher.setWaveCorrection(true);
        stitcher.setWaveCorrectKind(detail::WAVE_CORRECT_HORIZ);
        stitcher.setFeaturesMatcher(new detail::BestOf2NearestMatcher(false,0.3));
        stitcher.setBundleAdjuster(new detail::BundleAdjusterRay());

        stitcher.setBlender(new detail::MultiBandBlender());
 stitcher.stitch(images, panorama);
 printf("%.2lf sec \n",  (getTickCount() - t) / getTickFrequency() );
 Rect rect(panorama.cols / 2 - 320, panorama.rows / 2 - 240, 640, 480);
 Mat subimage = panorama(rect);
 Mat car = imread("car.png");
 overlayImage(subimage, car, result, cv::Point(320 - (car.cols / 2), 240 - (car.rows / 2 )));
 imshow("panorama", result);
// resize(panorama, result, Size(640, 480));
 imwrite("result.jpg", result);
 waitKey(0);

 return 0;
}

void overlayImage(const cv::Mat &background, const cv::Mat &foreground, cv::Mat &output, cv::Point2i location)
{
  background.copyTo(output);

   // start at the row indicated by location, or at row 0 if location.y is negative.
  for(int y = std::max(location.y , 0); y < background.rows; ++y)
  {
    int fY = y - location.y; // because of the translation

     // we are done of we have processed all rows of the foreground image.
    if(fY >= foreground.rows)
      break;

     // start at the column indicated by location,

    // or at column 0 if location.x is negative.
    for(int x = std::max(location.x, 0); x < background.cols; ++x)
    {
      int fX = x - location.x; // because of the translation.

       // we are done with this row if the column is outside of the foreground image.
      if(fX >= foreground.cols)
        break;

       // determine the opacity of the foregrond pixel, using its fourth (alpha) channel.
      double opacity =
        ((double)foreground.data[fY * foreground.step + fX * foreground.channels() + 3])

        / 255.;

       // and now combine the background and foreground pixel, using the opacity,

      // but only if opacity > 0.
      for(int c = 0; opacity > 0 && c < output.channels(); ++c)
      {
        unsigned char foregroundPx =
          foreground.data[fY * foreground.step + fX * foreground.channels() + c];

        unsigned char backgroundPx =
          background.data[y * background.step + x * background.channels() + c];

        output.data[y*output.step + output.channels()*x + c] =
          backgroundPx * (1.-opacity) + foregroundPx * opacity;

      }
    }
  }
}

A: *

*FAST feature detector is faster than SURF and ORB.
Moreover, finding 1500 features in a 640*480 picture takes too much time. 300 features is ok. So you can use this code instead:
detail::OrbFeaturesFinder(Size(3,1),300));

*Stitcher Class is so slow. I suggest you try to implement stitcher class yourself. Try using feature detectors, descriptors, then matching and after that find homography then making mask and then warping.

*I don't understand your third question, "How can I catch directions between two images?". What do you mean exactly?


text:
Q: Jquery variable value doesn't work outside the function I'm pretty new to jquery and i'm finding difficulty on this issue.
I have a variable "veh_select_prev" defined. Depending upon the click a user makes between the first 2 inner functions it should pass the value to the third inner function. Here is my try:
<script>
    var jqOld = jQuery.noConflict();
    jqOld(document).ready(function() {
            var veh_select_prev;

            jqOld("#package_front_suv").click(function(){
            var veh_select_prev = ".cust_suv";
                if(!jqOld("input:checkbox[name='package_type[]']").is(":checked")){
                    alert('Please select at least 1 package');
                }
                else{
                    jqOld(veh_select_prev).hide( "slide",
                                 { direction: "left"  }, 500 );
                    jqOld(".cust_target4").show( "slide",
                                  {direction: "right" }, 500 );
                }
            });

            jqOld("#package_front_hatch").click(function(){
            var veh_select_prev = ".cust_hatchback";
                if(!jqOld("input:checkbox[name='package_type[]']").is(":checked")){
                    alert('Please select at least 1 package');
                }
                else{
                    jqOld(veh_select_prev).hide( "slide",
                                 { direction: "left"  }, 500 );
                    jqOld(".cust_target4").show( "slide",
                                  {direction: "right" }, 500 );
                }
            });

            jqOld("#order_back").click(function(){
                jqOld(".cust_target4").hide( "slide",
                             { direction: "right"  }, 500 );
                jqOld(veh_select_prev).show( "slide",
                              {direction: "left" }, 500 );
            });
    });
    </script>

A: In every click event change variable from:
var veh_select_prev = "value";

To
veh_select_prev = "value";

A: Because if u declare a variable inside function using var keyword so its mean its a locally declared and local variable u can access only inside function, but if u declare a variable inside function without using var keyword its mean its globally defined variable inside function and global variable you can access everywhere and you don`t need to re-declare again and again..
so use like that -- veh_select_prev = "value";


text:
Q: Python - Selenium - Cannot Find Element on Page I have been using Selenium for a while now and am trying to extract LinkedIn company ID's from their LinkedIn company page. Every tag in this section is dynamic or not unique. So I went for xpath.

<code style="display: none" id="bpr-guid-3744658">
  {"data":{"elements":["Ts9RZEZq7awx/7fUFM1C+A==,0"],"paging":{"count":10,"start":0,"links":[]}},"included":[{"$deletedFields":[],"width":800,"fileIdentifyingUrlPathSegment":"800_800/0?e=1536192000&v=beta&t=6ny2TVRT-FUOSV45OcAvzB5KWQlEJM0YmuPxexVNx0M","height":800,"$type":"com.linkedin.common.VectorArtifact","$id":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-3"},{"$deletedFields":[],"width":400,"fileIdentifyingUrlPathSegment":"400_400/0?e=1536192000&v=beta&t=-5gPpNm7Ro7cttZe-oKhpFK0cwbm11VMH9uHoptg1Mk","height":400,"$type":"com.linkedin.common.VectorArtifact","$id":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-2"},{"$deletedFields":[],"width":200,"fileIdentifyingUrlPathSegment":"200_200/0?e=1536192000&v=beta&t=4xw5nz_6JCFJpMCvqp3zYgpWu4vkjT88sgc7mmZBMiM","height":200,"$type":"com.linkedin.common.VectorArtifact","$id":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-1"},{"$deletedFields":[],"width":100,"fileIdentifyingUrlPathSegment":"100_100/0?e=1536192000&v=beta&t=FrXLV0ITY8qMu6Qm-C6domrXpRbUWbbhWCZpeWffJfI","height":100,"$type":"com.linkedin.common.VectorArtifact","$id":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-0"},{"$deletedFields":["attribution"],"artifacts":["urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-0","urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-1","urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-2","urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage,artifacts,80a83d1c-6000-4576-ac86-2403150cd7ab-3"],"rootUrl":"https://media.licdn.com/dms/image/C5603AQHWo0jcnWXI7A/profile-displayphoto-shrink_","$type":"com.linkedin.common.VectorImage","$id":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage"},{"profilePicture":{"com.linkedin.common.VectorImage":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo,profilePicture,com.linkedin.common.VectorImage"},"firstName":"Stephanie","lastName":"Goldberger","$deletedFields":[],"entityUrn":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo","$type":"com.linkedin.voyager.identity.normalizedprofile.Profile"},{"inNetworkPeopleSearchUrl":"https://www.linkedin.com/vsearch/p?f_N=F&f_CC=1288","$deletedFields":[],"totalNumberOfConnections":1,"topConnectionsResolutionResults":{"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo":"urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo"},"topConnections":["urn:li:fs_normalized_profile:ACoAAAI8JnMBdj5agxf-k-p3EhA5XpUNvhknDIo"],"$type":"com.linkedin.voyager.jobs.shared.InNetworkRelevanceReasonDetails","$id":"Ts9RZEZq7awx/7fUFM1C+A==,0,details,com.linkedin.voyager.jobs.shared.InNetworkRelevanceReasonDetails"},{"$deletedFields":[],"company":"urn:li:fs_normalized_company:1288","details":{"com.linkedin.voyager.jobs.shared.InNetworkRelevanceReasonDetails":"Ts9RZEZq7awx/7fUFM1C+A==,0,details,com.linkedin.voyager.jobs.shared.InNetworkRelevanceReasonDetails"},"$type":"com.linkedin.voyager.organization.relevance.CompanyRelevanceReason","$id":"Ts9RZEZq7awx/7fUFM1C+A==,0"}]}
</code>

In the inspect dev tools, this command returns the expected results:
e = $x('//*[contains(.,"bpr-guid-3744658")]')

However, because the id is dynamic, I tried this instead:
e = $x('//*[contains(.,"bpr-guid-")]')

This returns results, but the right node is not in the list. The node after the one I am looking for actually made it into the list.
My program is in Python, but I am using JavaScript as it is much faster to debug (so solutions in Python instead are much appreciated).
Datalet is in list

A: Try to use starts_with instead of contains, I would also recommend using id instead of ., like this:
 CompanyList = driver.find_elements_by_xpath('.//code[starts-with(@id, "bpr-guid")]')

If the elements do not always have tag <code or they do not start-with @id = bpr-guid, then we can come up with another more direct solution than what you were trying before to narrow down the list of elements.

A: //*[starts-with(@id, "bpr-guid")]


text:
Q: How to talk with ABP API from windows service This is what I would like to build. A hosted web/api project built on APB where tenants can use the web application to define "Scan Definitions" that run inside their network. A scan definition would just contain a target IP Address to be scanned with WMI. They would download and install a windows service that would run periodically in their network. The service would communicate with the APB web API to retrieve scan definitions, then run the scan and upload the resulting scan data into the APB web API. Then the users would be able to view that scan data within the web app.
My question is with the CORS access in place, how can I make it so that the windows service is allowed to talk with the API. Also what is the best way to authenticate the service with api such that the service would know which tenant it should be using so that it pulls down the correct scan definitions and uploads the data to the correct tenant as well.
Thanks in advance for any help or guidance.

A: I was able to get a service up and running by following the abp sample found here: https://github.com/aspnetboilerplate/aspnetboilerplate-samples/tree/master/ConsoleRemoteWebApiCall/CallApiFromConsole
I still have things to work through, but it's gotten me to a spot where I can access the api from a console application


text:
Q: Best way to handle this error? [AVCaptureFigVideoDevice setTorchModeOnWithLevel:error:]: unrecognized selector sent to instance I'm trying to turn off an image in my torch app if the device doesn't support LED dimming.
  NSError* outError;
        BOOL success = [device setTorchModeOnWithLevel:brightnessLevel error:&outError];
        if(!success){
            [self.lightDialIndicator setHidden: YES];
            self.lightDial.image = [UIImage imageNamed:@"light_dial_disabled.png"];
        }

but my app crashed with the following error
[AVCaptureFigVideoDevice setTorchModeOnWithLevel:error:]: unrecognized selector sent to instance 0x73ad460

Any idea of a better/working way of detecting when the device doesn't allow me to use setTorchModeOnWithLevel?

A: First off, setTorchModeOnWithLevel is a property on the AVCaptureDevice class.
Second, if you want to test if a class can respond to a certain selector that you're calling on it, you use this:
BOOL isSuccessful = NO;
if ([device respondsToSelector:@selector(setTorchModeOnWithLevel:error:)]) {
    NSError* outError;
    isSuccessful = [device setTorchModeOnWithLevel:brightnessLevel error:&outError];
}
if (!isSuccessful) {
    [self.lightDialIndicator setHidden: YES];
     self.lightDial.image = [UIImage imageNamed:@"light_dial_disabled.png"];
}

You didn't show how you instantiated device in your example, but this applies to any class where you're unsure of whether it has a certain method or not.


text:
Q: Underscore _.bind() issue with nested function calls After using _.bindAll('addOne'), the addOnemethod does get a correct this but it somehow breaks function calls on other objects inside this "bound" method :
/**
 * Add an element to the list
 */
addOne: function(tag) {

    // scope of this is correct
    var newClass = App.getViewClass('myClass')(someOptions) <-- scope inside App::getViewClass is wrong! overriden by current this

}

Any ideas on how i could somehow restore normal behavior?

A: Needed to wrap my getter :
var myObject = new (App.getModelClass(model))(data);

As i got incorrect scope with :
var myObject = new App.getModelClass(model)(data);


text:
Q: How to swap UIScrollViews? Let's imagine that I have 2 UIScrollViews with different UIImageViews inside. When I trigger an action I would like the contents, parameters etc (besides the location) of the 2nd UIScrollView to be passed onto the 1st UIScrollView.
So, here's the code that I've come up with:
-(void) someAction {
UIScrollView * scroll = [[UIScrollView alloc] init]; // create an intermediary scrollView
scroll = secondScroll; // here I intent to pass the content of secondScroll to scroll
scroll.frame = firstScroll.frame; // here I assign the frame of firstScroll to scroll
so that it doesn't take the frame of secondScroll;
firstScroll =scroll;  // and then pass all the contents of scroll to firstScroll;
}

But when I execute that and trigger the action, the firstScroll seems to take the content of secondScroll, but secondScroll seems to be deleted. I need it to stay as is.
Any help?
Thanks

A: -(void) someAction {
    UIScrollView * scroll = [[UIScrollView alloc] init]; // create an intermediary scrollView

That's WRONG. You'll be leaking memory with it, since you're losing the pointer to that scroll view after assigning it to a different object. You'd better simply declare UIScrollView *scroll; for that purpose.
    scroll = secondScroll; // here I intent to pass the content of secondScroll to scroll

But that's not what happens. The scroll views don't magically copy themselves; if you assign one to another, you only assign the pointer.
    scroll.frame = firstScroll.frame; // here I assign the frame of firstScroll to scroll
    // so that it doesn't take the frame of secondScroll;

So, from now on, if you operate on scroll, it will effect secondScroll.
    firstScroll = scroll;  // and then pass all the contents of scroll to firstScroll;

And with this, you assign firstScroll to SecondScroll. So firstScroll will now essentially be secondScroll, losing it (leaking memory again and again) and having done nothing useful.
}

What on Earth are you trying to do with this?
Assuming you want to exchange the two views, you should do something like this instead:
BOOL firstScrollVisible = NO; // in -init or whatever

- (void) someAction
{
    if (fistScrollVisible)
        [self.view bringSubviewToFront:secondScroll];
    else
        [self.view bringSubviewToFront:firstScroll];
    firstScrollVisible = !firstScrollVisible;
}

A: Try doing the following:
- (void)someAction {
    [firstScroll removeFromSuperview]; // So that we do not leave the old firstScroll as a subview
    firstScroll = [secondScroll copy]; // Makes a copy of secondScroll and stores it in firstScroll
    [self addSubview:firstScroll]; // Add the new firstScroll to the view
}

Important Note(s):
This code will leak memory, as -copy returns an object with a reference count of +1, but we do not release firstScroll. I highly suggest you make firstScroll and secondScroll into nonatomic, retain properties (@property (nonatomic, retain) UIScrollView *firstScroll). If you want more info on this, just ask. Furthermore, you will need to make sure that firstScroll and secondScroll are never garbage values when this code gets run (it will crash) - depending on when and how it is called you may be fine.

A: @jrtc27 Thanks for your answer. I think I've found a solution and it seems to accomplish what I'm looking for. But I'm not sure if it's the right way or not. Here's what I do:
- (void)someAction {
    [[firstScroll subviews] makeObjectsPerformSelector:@selector(removeFromSuperView:);//here I sort of blank out the content of the firstScroll
    NSArray * array = [secondScroll subviews];//place all subview of the secondScroll in array
    int i = 0;
    int nrOfSubviews = [array count];
    for (i=0;i<nrOfSubviews;i++) { //appoint them one by one to firstScroll
        [firstScroll addSubview:[array objectAtIndex:i]];
    }
}

A: If you want to clone a UI element, you use NSCoder (just like the nib file loader does).
NSData *scrollViewData = [NSKeyedArchiver archivedDataWithRootObject:self.firstScroll];
CGRect oldFrame = self.secondScroll.frame;
self.secondScroll = [NSKeyedUnarchiver unarchiveObjectWithData:scrollViewData];
self.secondScroll.frame = oldFrame;

This serializes the UIView and all its subviews into an NSData and then creates a complete copy of those from the NSData.


text:
Q: Extract Private Key from Certificate Store python I can get information from the certificate by extracting it through ".get_pem()", but I need the private key too, do you know any method that allows me to extract it?
 with wincertstore.CertSystemStore("MY") as store:
            data_atual = datetime.date.today()
            num_data_atual = str(data_atual).replace('-', '')
            list = []
            list.sort(reverse=True)
            for cert in store.itercerts(usage=wincertstore.CLIENT_AUTH):
                print(cert.get_name())
                print(cert.cert_type)
                print(cert.enhanced())
                print(cert.get_pem())
                #print(cert.get_key())
                pem = cert.get_pem()
                encodedDer = ''.join(pem.split("\n")[1:-2])
                cert_bytes = base64.b64decode(encodedDer)
                cert_pem = ssl.DER_cert_to_PEM_cert(cert_bytes)
                cert_details = x509.load_pem_x509_certificate(
                    cert_pem.encode('utf-8'), default_backend())

                nome_certificado = cert.get_name()


text:
Q: issue with subprocess.call Python 2.7.3 with ubuntu:
Trying to run a program, (youtube-dl in this example) with subprocess.call with some arguments, I encounter the following issue. consider the following script:

try.py:
#!/usr/bin/python

from subprocess import call

url = "https://www.youtube.com/watch?v=8SbUC-UaAxE"
myArray = ['./youtube-dl {}'.format(url),'-x','--audio-format mp3']
#print the array before executing:
for item in myArray:
    print item,
#execute:
call(myArray)

This script prints outputs:
oris@oris:~/Desktop/YouTube/backend$ ./try.py
./youtube-dl https://www.youtube.com/watch?v=8SbUC-UaAxE -x --audio-format mp3
Traceback (most recent call last):
File "./try.py", line 16, in <module>
call(myArray)
 File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

Strangly, On the first line of the output I see the script does output ./youtube-dl https://www.youtube.com/watch?v=8SbUC-UaAxE -x --audio-format mp3 This command runs perfectly from bash directly, but produces an OSError from python. I also thought maybe to try and supply the url as an argument like this:
myArray = ['./youtube-dl', url,'-x','--audio-format mp3']

but than youtube-dl has an error of incorrect usage:
 oris@oris:~/Desktop/YouTube/backend$ ./try.py
 Usage: youtube-dl [options] url [url...]

 youtube-dl: error: no such option: --audio-format mp3
 ./youtube-dl https://www.youtube.com/watch?v=8SbUC-UaAxE -x --audio-format mp3

I've read youtube-dl source to see how it handles the supplied arguments with optparse. I don't see the url as an argument there, so I'm guessing i'm passing the arguments to subprocess.call incorrectly.
Side note: another thing I find odd is the fact the print here takes effect after the subprocess call, as opposed to their order on my script. Is something happening here asynchronously?
What am I missing here? Many thanks

A: --audio-format and mp3 should be passed as separated arguments:
myArray = ['./youtube-dl', url, '-x', '--audio-format', 'mp3']


text:
Q: How to animate UITableViewCell using Swift? I have a UITableView and inside the  tableViewCell I have a UICollectionView.
My requirement is while tapping on a button of first tableView cell I have to animate  second tableViewCell.
Below is my code :-
 //Cell For Row at indexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if (0 == indexPath.section) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FirstRowCell") as! FirstRowCell
        cell.btnReview.addTarget(self, action: #selector(GotoReview), for: UIControlEvents.touchUpInside)
        cell.btnMyProduct.addTarget(self, action: #selector(AnimateCollectionView), for: UIControlEvents.touchUpInside)
        //cell.

        return cell
    } else if ( 1 == indexPath.section) {
        let identifier = "TableCollectionCell"
        var tableCollectionCell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TableCollectionCell

        if(tableCollectionCell == nil) {
            let nib:Array = Bundle.main.loadNibNamed("TableCollectionCell", owner: self, options: nil)!
            tableCollectionCell = nib[0] as? TableCollectionCell
            tableCollectionCell?.delegate = self
        }

        return tableCollectionCell!
    } else {
        let identifier = "BrandImagesTableCell"
        var brandImagesTableCell = tableView.dequeueReusableCell(withIdentifier: identifier)

        if(brandImagesTableCell == nil) {
            let nib:Array = Bundle.main.loadNibNamed("BrandImagesTableCell", owner: self, options: nil)!
            brandImagesTableCell = nib[0] as? BrandImagesTableCell
          }

        //brandImagesTableCell.
        return brandImagesTableCell!
    }
}

In my code you can see:
        if (0 == indexPath.section)

In that I have a button target  (#selector(AnimateCollectionView)).
I want to animate  tableCollectionCell which is at  (1 == indexPath.section).
See my  AnimateCollectionView method :-
func AnimateCollectionView() {
    let identifier = "TableCollectionCell"
    var tableCollectionCell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TableCollectionCell

    if(tableCollectionCell == nil) {
        let nib:Array = Bundle.main.loadNibNamed("TableCollectionCell", owner: self, options: nil)!
        tableCollectionCell = nib[0] as? TableCollectionCell
        tableCollectionCell?.delegate = self
    }

    tableCollectionCell?.alpha = 0

    UIView.animate(withDuration: 1.50, animations: {
        //self.view.layoutIfNeeded()
        tableCollectionCell?.alpha = 1
    })
}

A: If you want to animate its change, you can just change some state variables, call tableView.reloadRows(at:with:), and have your cellForRowAt then check those state variables to know what the final cell should look like (i.e. whether it is the "before" or "after" cell configuration).
For example, here is an example, with two cells, toggling the second cell from red to blue cells.
class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UINib(nibName: "RedCell", bundle: nil), forCellReuseIdentifier: "RedCell")
        tableView.register(UINib(nibName: "BlueCell", bundle: nil), forCellReuseIdentifier: "BlueCell")
    }

    @IBAction func didTapButton(_ sender: UIButton) {
        isRedCell = !isRedCell
        tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .fade)
    }

    var isRedCell = true

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCell", for: indexPath)
            return cell
        } else if indexPath.row == 1 {
            if isRedCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: "RedCell", for: indexPath)
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BlueCell", for: indexPath)
                return cell
            }
        }
        fatalError("There are only two rows in this demo")
    }

}

Now, assuming you really needed to use NIBs rather than cell prototypes, I would register the NIBs with the tableview like above, rather than having cellForRow have to manually instantiate them itself. Likewise, for my cell with the button, I just used a prototype cell in my storyboard and hooked the button directly to my @IBOutlet, avoiding a NIB for that cell entirely.
But all of that is unrelated to your main problem at hand: You can create your cells however you want. But hopefully this illustrates the basic idea, that on the tap of the button, I'm not trying to load any cells directly, but I just update some status variable that cellForRow will use to know which cell to load and then tell the tableView to animate the reloading of that IndexPath.
By the way, I assumed from your example that the two different potential cells for the second row required different NIBs. But if you didn't, it's even easier (use just one NIB and one cell identifier), but the idea is the same, just update your state variable and reload the second row with animation.


text:
Q: Работа с DOM , динамическое создание таблици , как правильно?

(function() {
  var options = {
    "url": "http://localhost:3000/users",
    beforeSend: function() {
      console.log("Checking database!");
    },
    complete: function() {
      console.log("Data from database loaded!");

    },
    success: function(data) {
      if (data.length !== 0) {
        var parsedData = toJsObject(data);
        createTableSchema(parsedData);
      }
    },
    error: function() {
      var error_block = $("

Can't load data from database , can't connect to database!

");
      error_block.appendTo("#error").addClass("error");
    },
    async: true,
    method: 'GET'
  };
  $.ajax(options);
})();

function toJsObject(object) {
  return JSON.parse(JSON.stringify(object));
}

function createTableSchema(data) {
  var currentTable = $("#loginTable");
  var row = $("

").addClass("table-bordered");
  var td = $("	").addClass("text-center");

  for (var index in data) {
    var objLength = Object.keys(data[index]).length; //4
    var obj = data[index]; //get each object
    while (objLength > 0) {
      td.appendTo(row);
      objLength--;
    }
    row.appendTo(currentTable);
  }
}

        NICKNAME
        EMAIL
        PASSWORD
        ID

        data
        data
        data
        data

При проверки в браузере в Elements : Я получаю  только одно присоединение ,
что не хватает в алгоритме в методе createTableSchema .. ?

A: Думаю тут проблема именно в том, что один раз создан объект и в него попытка записать постоянно.... а надо постоянно новые создавать.... то есть и $("

") и $("	") надо поместить в соответствущие циклы

var currentTable = $("#loginTable");

for (var i = 0; i < 5; ++i) { // for (var index in data) {
    var row = $("

").addClass("table-bordered");
    var objLength = 4; // var objLength = Object.keys(data[index]).length;
    //var obj = data[index]; //get each object
    while (objLength > 0) {
        var td = $("	").addClass("text-center");
        td.appendTo(row);
        objLength--;
    }

    row.appendTo(currentTable);
}
table tr td {
  border: 1px solid black;
  width: 20px;
  height: 20px;
}


text:
Q: How do I add minutes step to Bootstrap DateTimePicker? I tried with this and other methods, but it's still not working.
$(function () {
    $('#datetimepicker').datetimepicker({
        format: 'HH:mm',
        disabledTimeIntervals: [[moment({ h: 0 }), moment({ h: 6 })], [moment({ h: 17, m: 30 }), moment({ h: 24 })]],
        enabledHours: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
        minuteStepping: 15
    });
});

A: You have to use stepping option to achieve what you need:

$(function () {
    $('#datetimepicker').datetimepicker({
        format: 'HH:mm',
        disabledTimeIntervals: [[moment({ h: 0 }), moment({ h: 6 })], [moment({ h: 17, m: 30 }), moment({ h: 24 })]],
        enabledHours: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
        stepping: 15
    });
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

  <input type='text' class="form-control" />


text:
Q: RegEx - Match a number that has different beginnings I'm new to RegEx and I'm trying to match a specific number that has 8 digits, and has 3 start options:

*

*00

*15620450000

*VS

For Example:

*

*1562045000012345678

*VS12345678

*0012345678

*12345678

I don't want to match the 4th option.
Right now I have managed to match the first and third options, but I'm having problems with the second one, I wrote this expression, trying to match the 8 digits under 'Project':
156204500|VS|00(?<Project>\d{8})

What should I do?
Thanks

A: With your shown samples, please try following regex once.
^(?:00|15620450000|VS)(\d{8})$

OR to match it with Project try:
^(?:00|15620450000|VS)(?<Project>\d{8})$

Online demo for above regex
Explanation: Adding detailed explanation for above.
^(?:00|15620450000|VS)  ##Checking value from starting and in a non-capturing group matching 00/15620450000/VS here as per question.
(?<Project>\d{8}        ##Creating group named Project which is making sure value has only 8 digits till end of value.
)$                      ##Closing capturing group here.

A: Let's understand why your solution failed that will help you get around such kind of problems in the future. Your regex, 156204500|VS|00(\d{8}) is processed as follows:
156204500 OR VS OR 00(\d{8})
In arithmetic,
1 + 2 + 3 (4 + 5) <--- (4 + 5) is multiplied with only 3

is different from
(1 + 2 + 3) (4 + 5) <--- (4 + 5) is multiplied with (1 + 2 + 3)

This rule is applicable to RegEx as well. Obviously, you intended to use the second form.
By now, you must have already figured out the following solution:
(15620450000|VS|00)(\d{8})

Note that unless you want to capture a group, a capturing group does not make sense and this is where regex has another concept called non-capturing group which you obtain by putting ?: as the first thing in the parentheses. With a non-capturing group, the final solution becomes:
(?:15620450000|VS|00)\d{8}


text:
Q: /usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory I get this error:
(cv) jalal@klein:~/computer_vision/py-faster-rcnn/caffe-fast-rcnn$ make -j8 && make pycaffe
PROTOC src/caffe/proto/caffe.proto
CXX src/caffe/blob.cpp
CXX src/caffe/data_reader.cpp
CXX src/caffe/layer.cpp
CXX src/caffe/solvers/adadelta_solver.cpp
CXX src/caffe/solvers/rmsprop_solver.cpp
CXX src/caffe/solvers/adagrad_solver.cpp
CXX src/caffe/solvers/nesterov_solver.cpp
CXX src/caffe/solvers/sgd_solver.cpp
CXX src/caffe/solvers/adam_solver.cpp
CXX src/caffe/syncedmem.cpp
CXX src/caffe/common.cpp
CXX src/caffe/internal_thread.cpp
CXX src/caffe/layer_factory.cpp
In file included from /usr/include/boost/python/detail/prefix.hpp:13:0,
                 from /usr/include/boost/python/args.hpp:8,
                 from /usr/include/boost/python.hpp:11,
                 from src/caffe/layer_factory.cpp:4:
/usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory
compilation terminated.
Makefile:565: recipe for target '.build_release/src/caffe/layer_factory.o' failed
make: *** [.build_release/src/caffe/layer_factory.o] Error 1
make: *** Waiting for unfinished jobs....

In Makefile.config I have:
PYTHON_INCLUDE := /use/include/python3.4

And in Makefile I have:
#PYTHON_LIBRARIES ?= boost_python python2.7
PYTHON_LIBRARIES ?= boost_python python3.4

I am using virtual environment for running OpenCV3 with Python3.4.3+:
(cv) jalal@klein:~/computer_vision/py-faster-rcnn/caffe-fast-rcnn$ python --version
Python 3.4.3+

However in in the /usr/include I have these Pythons I was not sure which one is actually for Python3.4.3+:
$ ls /usr/include/python
python2.7/  python3.4/  python3.4m/ python3.5m/

$ ls /usr/include/python3.4m/
abstract.h         ceval.h                enumobject.h   Imaging.h       metagrammar.h      parsetok.h     pyerrors.h     pystrcmp.h      structseq.h
accu.h             classobject.h          errcode.h      ImDib.h         methodobject.h     patchlevel.h   pyexpat.h      pystrtod.h      symtable.h
asdl.h             codecs.h               eval.h         ImPlatform.h    modsupport.h       pgen.h         pyfpe.h        Python-ast.h    sysmodule.h
ast.h              code.h                 fileobject.h   import.h        moduleobject.h     pgenheaders.h  pygetopt.h     Python.h        token.h
bitset.h           compile.h              fileutils.h    intrcheck.h     namespaceobject.h  pyarena.h      pyhash.h       pythonrun.h     traceback.h
bltinmodule.h      complexobject.h        floatobject.h  iterobject.h    node.h             pyatomic.h     pymacconfig.h  pythread.h      tupleobject.h
boolobject.h       datetime.h             frameobject.h  listobject.h    numpy              pycapsule.h    pymacro.h      pytime.h        typeslots.h
bytearrayobject.h  descrobject.h          funcobject.h   longintrepr.h   object.h           pyconfig.h     pymath.h       rangeobject.h   ucnhash.h
bytes_methods.h    dictobject.h           genobject.h    longobject.h    objimpl.h          pyctype.h      pymem.h        setobject.h     unicodeobject.h
bytesobject.h      dtoa.h                 graminit.h     marshal.h       opcode.h           py_curses.h    pyport.h       sliceobject.h   warnings.h
cellobject.h       dynamic_annotations.h  grammar.h      memoryobject.h  osdefs.h           pydebug.h      pystate.h      structmember.h  weakrefobject.h
$ ls /usr/include/python3.4
abstract.h         ceval.h                enumobject.h   Imaging.h       metagrammar.h      parsetok.h     pyerrors.h     pystrcmp.h      structseq.h
accu.h             classobject.h          errcode.h      ImDib.h         methodobject.h     patchlevel.h   pyexpat.h      pystrtod.h      symtable.h
asdl.h             codecs.h               eval.h         ImPlatform.h    modsupport.h       pgen.h         pyfpe.h        Python-ast.h    sysmodule.h
ast.h              code.h                 fileobject.h   import.h        moduleobject.h     pgenheaders.h  pygetopt.h     Python.h        token.h
bitset.h           compile.h              fileutils.h    intrcheck.h     namespaceobject.h  pyarena.h      pyhash.h       pythonrun.h     traceback.h
bltinmodule.h      complexobject.h        floatobject.h  iterobject.h    node.h             pyatomic.h     pymacconfig.h  pythread.h      tupleobject.h
boolobject.h       datetime.h             frameobject.h  listobject.h    numpy              pycapsule.h    pymacro.h      pytime.h        typeslots.h
bytearrayobject.h  descrobject.h          funcobject.h   longintrepr.h   object.h           pyconfig.h     pymath.h       rangeobject.h   ucnhash.h
bytes_methods.h    dictobject.h           genobject.h    longobject.h    objimpl.h          pyctype.h      pymem.h        setobject.h     unicodeobject.h
bytesobject.h      dtoa.h                 graminit.h     marshal.h       opcode.h           py_curses.h    pyport.h       sliceobject.h   warnings.h
cellobject.h       dynamic_annotations.h  grammar.h      memoryobject.h  osdefs.h           pydebug.h      pystate.h      structmember.h  weakrefobject.h

I have this for my Virtual Environment in the bashrc:
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

Basically how can I setup Caffe to work with Python3.4.3+?
https://github.com/rbgirshick/py-faster-rcnn

A: Use this
sudo apt-get install python-dev python3-dev


text:
Q: Symfony3 error adding new bundle I've a bundle that I created and is working in another project. I copied the Bundle folder inside the src folder, copied some segurity parameters, imported the service resource inside config.yml and add the bundle inside AppKernel.php as

new LoginBundle\LoginBundle()

And when I made a $ php bin/console doctrine:schema:validate it return this error
PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "LoginBundle" from namespace "LoginBundle".
Did you forget a "use" statement for another namespace? in {project}\app\AppKernel.php:18
Stack trace:
#0 {project}\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php(450): AppKernel->registerBundles()
#1 {project}\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php(116): Symfony\Component\HttpKernel\Kernel->initializeBundles()
#2 {project}\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php(69): Symfony\Component\HttpKernel\Kernel->boot()
#3 {project}\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php(125): Symfony\Bundle\FrameworkBundle\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#4 {project}\bin\console(27): Symfo in {project}\app\AppKernel.php on line 18

EDIT
AppKernel.php content
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new LoginBundle\LoginBundle(),
            new AppBundle\AppBundle(),
        ];

        if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

            if ('dev' === $this->getEnvironment()) {
                $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
                $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
            }
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}

And here goes the bundle file structure

Also this is the LoginBundle.php
namespace LoginBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class LoginBundle extends Bundle
{
}

A: My solution was generating aoutoloaders again like
php composer.phar dump-autoload

Hope it helps someone

A: i think in routing.yml you must add
login:
    resource: "@LoginBundle/Controller/"
    type:     annotation
    prefix:   /


text:
Q: What does Jest's "const mock = jest.fn();" really do? I found this mocking example floating around on a tutorial page, but I find it confusing that this is used as an example so often.
test("mock return value", () => {
  const mock = jest.fn();
  mock.mockReturnValue("bar");

  expect(mock("foo")).toBe("bar");
  expect(mock).toHaveBeenCalledWith("foo");
});

Does const mock = jest.fn(); ever connect to a real function that needs to be mocked? If so, how does it know which function to mock? What is the use case for a new and random mock like this?

A: The example in this article only demonstrates the functionality of jest.fn().  The mock object is not used by the code to be tested.
As it says, the mock function provides the below features:

*

*Capture calls

*Set return values

*Change the implementation

There is a scenario in real code where a function takes an object and calls a method on that object. In this scenario, you can create a mock object and pass it to that function.
E.g.
// A real function need to be tested, it can be imported from a module
function getUserById(dbc, id) {
  return dbc.query('select * from users where id = $1;', [id]);
}

describe('70538368', () => {
  test('should pass', () => {
    const mDbc = {
      query: jest.fn().mockReturnValue({ name: 'teresa teng' }),
    };
    const actual = getUserById(mDbc, '1');
    expect(actual).toEqual({ name: 'teresa teng' });
    expect(mDbc.query).toBeCalledWith('select * from users where id = $1;', ['1']);
  });
});


text:
Q: Appending objects to JSON lists There is an exception occurring and I am not sure why because I am new to JS. As soon as I reach the line testData["beacons"].append(beacon); My code jumps to catch(e). I am assuming I cant append objects to other arrays?
JS:
$(document).ready(function() {
    // Data to describe what kind of test
    var testData = {
        "timestamp": "",
        "hive": 0,
        "hdfs": 0,
        // Contains a list of testData objects
        "beacons":[]
    };

    var testRun = document.getElementById("test-form");
    testRun.addEventListener('submit', function(event) {
        event.preventDefault();
        var selectedTest = document.querySelector('input[name=test-select]:checked');
        alert(selectedTest);
        var testType = selectedTest.id;
        if (testType == "hdfs-test") {
            testData["hdfs"] = 1;
            testData["hive"] = 0;
        } else if (testType == "hive-test") {
            testData["hdfs"] = 0;
            testData["hive"] = 1;
        } else if (testType == "hdfs-hive-test") {
            testData["hdfs"] = 1;
            testData["hive"] = 1;
        } else {
        //    null
        }

        var events = document.getElementById("event-textarea").value;
        // check in valid input
        var eventSource = events.replace("],[","],,,,[");
        // beaconLists allows users to submit --> [{beacon1}, {beacon2}, ...], [{beacon3}, {beacon4}, ...]
        var beaconLists = eventSource.split(",,,,");
        for (var i = 0; i < beaconLists.length; i++) {
            // inspect one list in beaconLists [{beacon1}, {beacon2}, ...]
            var beaconList = beaconLists[i];
            try {
                // list of JSON objects
                var beaconObjList = JSON.parse(beaconList);
                for (var j = 0; j < beaconObjList.length; j++) {
                    var beaconObj = beaconObjList[j];
                    if (beaconObj["data"] && beaconObj["application"]) {
                    //    successful parse to find events
                    //    describe beacon being tested
                        alert("yes");
                        var beacon = {
                            "app_name": beaconObj["application"]["app_name"],
                            "device": beaconObj["application"]["device"],
                            "device_id": beaconObj["application"]["device_id"],
                            "os": beaconObj["application"]["os"],
                            "os_version": beaconObj["application"]["os_version"],
                            "browser": beaconObj["application"]["browser"],
                            "beacon": beaconObj
                        };
                        // append to testData
                        testData["beacons"].append(beacon);
                        // reset beacon so we can append new beacon later
                        beacon = {};
                    } else {
                    //    notify event isn't in the correct format?
                        alert("no");
                    }
                }
            } catch (e) {
            //     notify bad JSON
                alert("failed");
            }
        }
        console.log(testData);
        //$.ajax({
        //    type: "POST",
        //    url: "/test/",
        //    data: testData,
        //    success: function () {
        //        alert("yay");
        //    },
        //    failure: function () {
        //        alert("boo");
        //    }
        //});

    });

});

A: There is nothing wrong with having an array of objects. JavaScript handles that just fine. The main issue is that append is a jQuery API method for adding elements (psuedo native appendChild). push is how you add to an array.
testData["beacons"].push(beacon);

Further, this part of your code is problematic.
// reset beacon so we can append new beacon later
beacon = {};

Both the variable beacon and the one added here testData["beacons"] are the same. In JavaScript, the value of testData["beacons"]'s recent beacon is the same as the variable beacon. When the value in the variable beacon is set to {}, so is the array's value. This line of code simply needs to be removed. Inside of the variable environment set up, the use of var will set up a new variable for beacon each iteration.

A: You should use the push method, like:
testData["beacons"].push(beacon);


text:
Q: AngularJS & Rails - Seperated apps/deployments or one app? Most of the resources/example about rails and angular on the internet just put them together. AngularJS goes inside of rails under app/assets. This feels reeeaaaly dirty to me. Is it a good idea? What if we decide at some time we won't be using rails and we move to, I don't know, sinatra? How hard would it be to port?
What would be pros/cons of everthing in a single rails app and what would be pros/cons for two seperated apps?
Thank you!

A: Even when placing Angular (or any other client-side MV* framework) inside your Rails app, you are pretty much keeping the separation of concerns intact. That is, you have a Rails API serving JSON (or similar) data, and a separate Javascript framework using that data to render appropriate views. If you ever wanted to use a different server-side API, you can do so, and still utilize your entire Javascript directory as is.
Placing the client side framework in Rails is simply a matter of convenience. It comes with an organized directory structure and the ability to serve your HTML, which is essentially all you're using it for when it comes to your views. But again, these views aren't really tied to Rails, as they're just HTML and Javascript, so you can easily move them to a different platform when necessary.


text:
Q: Подменю в Вордпресс, как поменять заголовок первого элемента В админке вордпресса хочу сделать подменю вида:
Email Campaigns

*

*Wait for approve

*Approved

*Sent

*Blacklist
add_menu_page( 'Email Campaigns', 'Email Campaigns', "manage_options", 'email_campaigns', array(__CLASS__,'showEmailCampaignsPage'),'dashicons-email-alt',4);
add_submenu_page( 'email_campaigns', 'Approved', 'Approved', "manage_options", 'email_campaigns_approved', array(__CLASS__,'showEmailCampaignsPage'));
add_submenu_page( 'email_campaigns', 'Sent', 'Sent', "manage_options", 'email_campaigns_sent', array(__CLASS__,'showEmailCampaignsPage'));
add_submenu_page( 'email_campaigns', 'Blacklist', 'Blacklist', "manage_options", 'email_campaigns_blacklist', array(__CLASS__,'showEmailCampaignsPage'));

Получается, что первый элемент подменю назван именем главного меню:

как изменить Email Campaigns в подменю на Wait for approve (в постах сделано значит можно!)

A: Нужно установить аргумент $function в null и добавить подменю с новым заголовком.
    add_menu_page( 'Email Campaigns', 'Email Campaigns', "manage_options", 'email_campaigns', null,'dashicons-email-alt',4);
    add_submenu_page( 'email_campaigns', 'Wait for Approve', 'Wait for Approve', "manage_options", 'email_campaigns', array(__CLASS__,'showEmailCampaignsPageWait'));
    add_submenu_page( 'email_campaigns', 'Approved', 'Approved', "manage_options", 'email_campaigns_approved', array(__CLASS__,'showEmailCampaignsPageApproved'));
    add_submenu_page( 'email_campaigns', 'Sent', 'Sent', "manage_options", 'email_campaigns_sent', array(__CLASS__,'showEmailCampaignsPageSent'));
    add_submenu_page( 'email_campaigns', 'Sent Error', 'Sent Error', "manage_options", 'email_campaigns_sent_error', array(__CLASS__,'showEmailCampaignsPageSentError'));
    add_submenu_page( 'email_campaigns', 'Blacklist', 'Blacklist', "manage_options", 'email_campaigns_blacklist', array(__CLASS__,'showEmailCampaignsPageBlacklist'));


text:
Q: Children routes are not working in feature module I have an big app where i don't want to have everything in the app-routing.module and app.module.ts file.
(for example the route paths )
I want to make organisation of my modules into featured modules ( FOR NOW I AM NOT USING LAZY LOADING ).
My problem is that when i include just normal route path without children routes then feature modules in the imports array in the app.module.ts are working.But when i include children routes in some feature modules then it is not working.CablecoModule in this case
Please help me
//app.module.ts
@NgModule({
  declarations: [
    AppComponent,
    PagenotfoundComponent,
    LoginComponent,
    HomeComponent,
    ContactUsComponent,
    ForgotPasswordComponent,
    CoffeeComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot(),
    Ng4LoadingSpinnerModule.forRoot(),
    ReactiveFormsModule,
    FormsModule,
    HttpClientModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    NgbModule.forRoot(),
    UsersModule,

    CablecoModule,

    UiModule,
    AppRoutingModule,
  ],
  providers: [
    {provide: HTTP_INTERCEPTORS, useClass: Interceptor, multi: true},
    MatDatepickerModule
  ],
  bootstrap: [AppComponent],
  exports: [
    // AppRoutingModule,
    // MatDatepickerModule,
    // MatFormFieldModule,
    // MatNativeDateModule,
    // MatInputModule,
    // BrowserAnimationsModule
  ]
})
export class AppModule { }

//app routing

const appRoutes: Routes = [
     { path: '', component: HomeComponent , canActivate: [AnonymousGuard]},
    { path: 'coffee', component: CoffeeComponent },
    { path: 'contact-us', component: ContactUsComponent },
    { path: 'login', component: LoginComponent},
    { path: 'forgot-password', component: ForgotPasswordComponent },
    { path: 'cpe20', component: Cpe20Component },
   {path:"**" , component:PagenotfoundComponent}
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes),
        // NgDatepickerModule
    ],
    exports: [
        RouterModule
    ]
})

export class AppRoutingModule {

}

//cablecomodule

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    AppRoutingModule,
    Ng2SmartTableModule,
    NgbModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatInputModule,
    MatSidenavModule,
    BrowserAnimationsModule,
    MatTooltipModule,
    CountUpModule,
    NgxDaterangepickerMd.forRoot(),
    CablecoRoutingModule
    //NgxPaginationModule
  ],

  declarations: [DashboardComponent, SurveyComponent, GoogleAutocompleteDirective, GoogleMapComponent, LitBuildingsListComponent, SearchResultsComponent, ListOfUsersComponent, ListOfOrganizationsComponent, ConfigurationComponent, OtherResultsComponent, OrganizationTypeComponent, MultiSiteSearchComponent, RequestServiceabilityComponent, SearchPreviewComponent, PricingComponent, TvCardComponent, UserProfileComponent, ChangePaswComponent, AllMultiSiteSearchesComponent, PromotionsComponent, ComcastContractComponent, ImportServicesComponent, ProvidersComponent, QuotesDashboardComponent, QuotesAdminDashboardComponent, SpectrumContractComponent, SearchHistoryComponent, PackagesComponent, ComcastPackagesComponent, RegularPricingComponent, PackagePricingComponent, FiberPricingComponent, FiberAndVoicePricingComponent, Cpe20Component, CoxContractComponent, ExportComponent, StatisticsComponent, ImportStatusesComponent , SignupComponent],
  providers:[DataService, MatDatepickerModule,DashboardComponent, SurveyComponent, GoogleAutocompleteDirective, GoogleMapComponent, LitBuildingsListComponent, SearchResultsComponent, ListOfUsersComponent, ListOfOrganizationsComponent, ConfigurationComponent, OtherResultsComponent, OrganizationTypeComponent, MultiSiteSearchComponent, RequestServiceabilityComponent, SearchPreviewComponent, PricingComponent, TvCardComponent, UserProfileComponent, ChangePaswComponent, AllMultiSiteSearchesComponent, PromotionsComponent, ComcastContractComponent, ImportServicesComponent, ProvidersComponent, QuotesDashboardComponent, QuotesAdminDashboardComponent, SpectrumContractComponent, SearchHistoryComponent, PackagesComponent, ComcastPackagesComponent, RegularPricingComponent, PackagePricingComponent, FiberPricingComponent, FiberAndVoicePricingComponent, Cpe20Component, CoxContractComponent, ExportComponent, StatisticsComponent, ImportStatusesComponent , SignupComponent],
})
export class CablecoModule { }

//cableco-routing
const routess: Routes = [
{
        path: 'ibs', component: LayoutComponent, children: [
            {
                path: '',
                redirectTo: 'dashboard',
                pathMatch: 'full'
            },
            {
                path: 'dashboard',
                component: DashboardComponent
            },
            {
                path:"signup",
                component:SignupComponent
            }
        ]
    }
]

@NgModule({
  imports: [RouterModule.forChild(routess)],
  exports: [RouterModule]
})
export class CablecoRoutingModule { }

A: *

*Do you have an <router-outlet></router-outlet> in your LayoutComponent?

*What do you expect the route towards CablecoRoutingModule -> DashboardComponent to be?


text:
Q: FFT of a square wave I'm generating a square wave as PWM whose frequency is set to 25 Hz. On the oscilloscope, I've got:

The data referred to the image above was stored and maniputed, then I plot it using jupyter notebook, as shown below:

Applying the FFT to that signal,I've got:

The main question is: wasn't the main peak (the 2.7 V) supposed to be near 25 Hz?
UPDATE: I just did the corrections that you tell and
the visualization is better! I'm still obtaining the main peak in 0 Hz, but the second harmonic is in 25 Hz ( but the amplitude is low). I also didn't get the 13 V dc offset that Chris pointed out.

UPDATE 2: I subtracted the average dc level (1.35 V)  from the signal as most of you told me and I got the result I believe it's correct now:

A: I'd make this a comment, but I don't have enough points to do that yet.
You should plot your FFT data starting at 0 Hz and go up to, say, 500 Hz.  That will give you 10 or so harmonics.  You are probably zoomed too far out in the frequency domain(x-axis) to get much detail and realize what's going on here.
And yes, the fundamental should be at 25 Hz.

A: Your signal is a square wave with its base at 0V and its peak at 2.7V or so.  So it has an average voltage of 1.35V.  In the frequency domain, the overall average of a signal is its content at DC or 0Hz -- so that's why there's a peak at 0Hz.
The FFT of a square wave that is centered on 0V has energy at every odd harmonic, starting at 1.  So there's energy at 1f, 3f, 5f, etc.

A: A DC offset will create a big spike at 0 Hz.  Remove it to see the AC content (fundamental frequency and harmonics of your square wave).
You can remove the DC offset by subtracting the average level of the waveform before the DFT or FFT.

A: The fundamental will be at 0Hz because you have a DC offset. There is no negative component to your signal.


text:
Q: Convert Julian Dates to Gregorian dates in impala I have a table where the dates are in Julian dates, and I would like to convert these dates into Calendar dates.
Here is a sample of a Julian date I have: 2457395.
In calendar date it should be: 07012016 (DDMMYYYY).
I tried to convert the date into the number of days since (01/01/1900) but even if I don't know how to have a date with a number of days as an input.
Many thanks in advance!

A: Impala does not support dates, only timestamps; and it does not have many date/time formatting features; so you need to be creative, e.g.
select JULIAN_DATE,
  adddate('1900-01-01 00:00:00Z', JULIAN_DATE -2415021) as AS_TIMESTAMP,
  to_date(adddate('1900-01-01 00:00:00Z', JULIAN_DATE -2415021)) as AS_ISO_DATE_STRING,
  from_unixtime(unix_timestamp(adddate('1900-01-01 00:00:00Z', JULIAN_DATE -2415021)), "ddMMyyyy") as AS_DMY_DATE_STRING
from WHATEVER

Sample output:
julian_date as_timestamp        as_iso_date_string as_dmy_date_string
----------- ------------------- ------------------ ------------------
2457395     2016-01-07 00:00:00 2016-01-07         07012016

A: Well if it is a JDE Julian date for example 118163 for 12-06-2018 then below code can be used
    date_add(to_timestamp(concat(substr(cast(cast(118162 + 1900000 as int) as     string),1,4),'01','01'),'yyyyMMdd'),
    cast(substr(cast(cast(118162 + 1900000 as int) as string),5,3) as int)-1)


text:
Q: USB type C not working I connected an external Numpad with a USB type C plug into my laptop and it doesn't work. I've tried the Numpad on a system running Windows and it works just fine.
I tried a couple of solutions on the internet:
modprobe thunderbolt
modprobe intel-wmi-thunderbolt

And even though the modules loaded successfully the USB type C port is still not working.
I'm running:
uname -a

Linux 6.0.0-kali6-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.0.12-1kali1 (2022-12-19) x86_64 GNU/Linux

Running tail -f /var/log/kern.log while plugging in the numpad doesn't show anything in the output.
How can I fix this?
Thanks in advance.
Sorry for not giving out more information, I don't exactly know where to look so if you need more information please tell me what to run and I will update the question.
UPDATE:
lsusb                                                                                21:18:47
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 005: ID 05c8:03a0 Cheng Uei Precision Industry Co., Ltd (Foxlink) HP HD Camera
Bus 001 Device 004: ID 8087:0a2b Intel Corp. Bluetooth wireless interface
Bus 001 Device 003: ID 258a:0049 BY Tech Gaming Keyboard
Bus 001 Device 002: ID 046d:c534 Logitech, Inc. Unifying Receiver
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

---

lsusb -t                                                                                21:18:52
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/6p, 5000M
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/12p, 480M
    |__ Port 1: Dev 2, If 1, Class=Human Interface Device, Driver=usbhid, 12M
    |__ Port 1: Dev 2, If 0, Class=Human Interface Device, Driver=usbhid, 12M
    |__ Port 2: Dev 3, If 0, Class=Human Interface Device, Driver=usbhid, 12M
    |__ Port 2: Dev 3, If 1, Class=Human Interface Device, Driver=usbhid, 12M
    |__ Port 7: Dev 4, If 0, Class=Wireless, Driver=btusb, 12M
    |__ Port 7: Dev 4, If 1, Class=Wireless, Driver=btusb, 12M
    |__ Port 9: Dev 5, If 0, Class=Video, Driver=uvcvideo, 480M
    |__ Port 9: Dev 5, If 1, Class=Video, Driver=uvcvideo, 480M

cat /boot/config-6.0.0-kali6-amd64 | grep CONFIG_TYPEC                                                               21:25:56
CONFIG_TYPEC=m
CONFIG_TYPEC_TCPM=m
# CONFIG_TYPEC_TCPCI is not set
CONFIG_TYPEC_FUSB302=m
# CONFIG_TYPEC_WCOVE is not set
CONFIG_TYPEC_UCSI=m
CONFIG_TYPEC_TPS6598X=m
# CONFIG_TYPEC_ANX7411 is not set
# CONFIG_TYPEC_RT1719 is not set
# CONFIG_TYPEC_HD3SS3220 is not set
# CONFIG_TYPEC_STUSB160X is not set
# CONFIG_TYPEC_WUSB3801 is not set
# CONFIG_TYPEC_MUX_FSA4480 is not set
CONFIG_TYPEC_MUX_PI3USB30532=m
# CONFIG_TYPEC_MUX_INTEL_PMC is not set
CONFIG_TYPEC_DP_ALTMODE=m
CONFIG_TYPEC_NVIDIA_ALTMODE=m

UPDATE2: the output of lsusb doesn't differ before and after plugging in the Numpad.
Also tried flipping the plug, no luck.


text:
Q: What is /Users/me/Applications? I am on Mavericks (1.9.2) and I just noticed a folder called Applications in my home folder, i.e. I have a folder /Users/me/Applications.  This folder is empty:
cd Applications
pwd
/Users/me/Applications
ls -a
./          ../         .localized
cat .localized
[nothing]
cd
ls -lh
drwx------   3 me  staff   102B 19 Apr 21:08 Applications/

I was wondering how did this folder came into being... this is admittedly a purely academic curiosity before I get rid of it.

A: Anything can create ~/Applications.
It's usually used to store apps that you don't want to (or can't because you're not admin) install globally on the system. The folder doesn't exist by default, but if created it will be given a custom icon like /Applications. Any app on the system can create this folder and since no record of what app created it exists you probably won't know.

A: /Users/<username>/Applications or ~/Applications is your user's Applications folder.  Much like your Desktop, Documents, et al., this folder is local to the user and can be changed by (natively) only that same user.  Very nice if you want to install an application for only yourself and no one else.
/Applications is your system-level Applications folder, visible and accessible by all users on the system.  To make changes on the system-level, you must authenticate as an admin.
grgarside is right: the folder isn't there by default.  You can add it yourself or an installer (e.g. Spotify's installer) can create it for you.

A: Just to add a little more context to the answers above... The only time I've ever seen any apps appear in here was when I installed older Adobe Air apps. I think the new Air subsystem properly places apps in the primary Applications folder. If you want an application only available to you (your user account) and not to other users you'd want to put the Application ~/Applications instead of the globally accessible /Applications folder. On OS X you can run an application from anywhere, so these aren't really super special folders as much as they're default folder locations with the purposes listed by "thankyour" already.


text:
Q: Approval History (sObject 'ProcessInstance') - Overall Status field, queryable?
*

*Is it possible to declaratively capture the current 'Overall Status'
from the Approval History object on the related master record? I
assume that this is not possible.

*Is it possible to SOQL on the the 'Overall Status' field from the
Approval History? I am not able to find this field via the API
(workbench). Looking at the documentation, there is no field
for 'Overall Status'.

*If it is not possible to SOQL on the 'Overall Status' field, is the
best approach to use a custom Visualforce page to override the
standard page and use JavaScript to capture the first index in the
'Overall Status' column? This answer looks like it would point
me in the right direction. Or would another approach be to query all the ProcessInstanceSteps that belong to a single ProcessInstance record and query the StepStatus?

A: It's just the Status field. You can also get the individual step statuses from ProcessInstanceStep.
SELECT Status, TargetObjectId, (Select StepStatus FROM Steps)
FROM ProcessInstance WHERE TargetObjectId = '<id_here>'


text:
Q: Create word pairs from list and assign value for each word pair I have a list:
s = ['apple','orange','banana'.'strawberry','mango']

I would like to create pairs for  first word and other words:
s = [('apple','orange'),('apple','banana'),('apple','strawberry'),('apple','mango')]

And then, I would like  to assign values for each word pair:
 s = [('apple','orange',4),('apple','banana',3),('apple','strawberry',2),('apple','mango',1)]

A: This may do what you want, though I'm not sure you've explained the problem thoroughly enough to know what the "value" (third element of each tuple) is supposed to be:
s = ['apple', 'orange', 'banana', 'strawberry', 'mango']

print [(s[0], s[i], len(s) - i) for i in range(1, len(s))]

# [('apple', 'orange', 4), ('apple', 'banana', 3), ('apple', 'strawberry', 2), ('apple', 'mango', 1)]


text:
Q: Is it recommended to use DocBlock even if I'm not using phpDocumentor? I'm developing a simple website for a client.
I have read about phpDocumentor and DocBlocks, and I thought that documenting my classes and functions will be very useful.
I'm almost sure I will not generate any documentation for the site, since it's a pretty simple website, and guess what? It doesn't have an API...
But is it still recommended to write DocBlocks in my code? From what I know many programmers even don't write simple comments, but DocBlocks.
I'm not going to generate any readable documentation by the client/ next programmer but I still think that making some comments that are more than just simple text will be better.
edit - If you think that DocBlocks are redundant in my case, are there any other "standards" for writing comments / documentation?
The last time everything that doesn't have a standard makes me feel stupid, that I'm not sure if it's better to write if(){ or if () {, /* */ or //, etc.
I'm new to the documentor and DockBlocks, and I'm still not sure if I have to write this question here or in StackOverflow. Thank you very much anyway!

A: It is useful to document similar stuff in a similar way. This makes it easy to read the code as you can grasp the important things easily. Using an established standard as a foundation is useful as new team members will quickly get used to the scheme. phpdocumentor format is based on JavaDoc. The same form is sometimes used in other languages, too. Therefore even developers not familiar with PHP are more like to understand and use it quickly.
Additionally tools like IDEs support the format. And can derive information for some help from it.
If you should be strict in using it is a different question. You might use just little parts of it and modify others to your needs. Just like with any other tool ;-)

A: At my previous jobs we didn't use DocBlocks for PHP if the code was not an API and was not going to be used to generate documentation. Here was our philosophy on comments:
Use /**/ only for formal documentation at the top of the script that includes the author, date, brief description, etc. Use // for all other comments.
We noticed that comments can get out-dated and turn into lies about the code. We instead would try to write "self-illuminating" code by choosing function/class names that better reflect their purpose/function. We would also re-factor complex functions into simpler functions that "do one thing" instead of writing large functions that had a short novel comment above it to try and describe what it did.
The only benefit I can see that we were missing is labeling the function arguments on what data type they expecting and what data type the return value is. But then again, PHP is a loosely typed language where the DocBlocks could betray you (best to just use === and !== and is_*() functions if you really need to look at data types).


text:
Q: One loop over multiple Ansible tasks I've created an Ansible playbook that creates a cloud instance and then installs some programs on the instance. I want to run this playbook multiple times (without using a bash script). Is it possible to use a loop to loop over those two tasks together (I.E. One loop for two tasks?). All I've been able to find so far is one loop for each individual task

A: I managed to do this by recursively including the same yaml file based on a condition. Here is the gist: https://gist.github.com/ParagDoke/5ddfc3d5647ce9b0110d1b9790090092. Effectively, in your playbook, include a file with some vars:
  - name: Invoke poller
    vars:
      some_condition: '"failed" not in response.content and response.json.status=="running"'
    include_tasks: status-poller.yml

Then in status-poller.yml, include itself:
- include_tasks: includes/status-poller.yml
  when: some_condition

A: An update:

In 2.0 you are able to use with_ loops and task includes (but not playbook includes), this adds the ability to loop over the set of tasks in one shot. There are a couple of things that you need to keep in mind, a included task that has it's own with_ loop will overwrite the value of the special item variable. So if you want access to both the include's item and the current task's item you should use set_fact to create a alias to the outer one.:

- include_tasks: test.yml

  with_items:
    - 1
    - 2
    - 3

in test.yml:

- set_fact: outer_loop="{{item}}"
- debug: msg="outer item={{outer_loop}} inner item={{item}}"

  with_items:
    - a
    - b
    - c

Source: Ansible Docs

A: No that's currently not possible. with_items used to work with the include statement in previous versions of Ansible but was unfortunately dropped.
Though it will be brought back in Ansible 2.0, see slide 14/15 of What's New in v2 - AnsibleFest London 2015

You could try to work with the v2 branch from github, the feature should be available in there.
What you can do with 1.9.1 is to move your tasks into a role and reference this role multiple times in your playbook.


text:
Q: Microsoft Graph, enumerate sharepoint list I'm learning Microsoft Graph API.  And am looking for assistance in using the  SharePoint Enumerate items in a list feature.
I've completed the Microsoft learn tutorial and want to take it a step further.
I had the idea of using a SharePoint list to update a website dynamically.  So, just show the list on the website with the items in a ul tag.
I think I will need to do the following:

*

*Register the app in Azure with "Redirect URI" set to "Web".  And accounts in any organizational unit.

*Use the tutorial template as my website template:  template

*Find the site ID and the list ID.

That last one is where I am confused.  I've used the sharepoint graph to run some HTTP requests but those used a function called "GetByTitle('the list name')".  And in this case they are wanting the site and list ID.  Does this mean the site name, and list name, or the internal IDs of each?
I haven't found a good tutorial on using the SharePoint graph stuff.
If anyone has done this before, please share some tips with me.

A: As far as I know, GetByTitle means getting items by SharePoint list name.
You can refer to this document to work with SharePoint sites in Microsoft Graph