text:
Q: Why does my desktop lock up when I copy lots of files to a USB drive? My desktop is usually very responsive, even under heavy load. But when I copy files to a USB drive, it always locks up after some time. By "lock up", I mean:

*

*Moving focus from one window to another can take 10-20s

*Switching desktops can take 10-20s

*Videos don't update anymore (in YouTube, the audio continues to play, only the video freezes)

The system load isn't exceptionally high when this happens. Sometimes, I see a lot of white on xosview indicating that the kernel is busy somewhere.
At first glance, it looks as if copying files to the USB drive would interfere somehow with compiz but I can't imagine what the connection could be.
Here is the output of htop:

Here is the output of iostat -c -z -t -x -d 1 during a 2 minute hang:
19.07.2012 20:38:22
avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           1,27    0,00    0,38   37,52    0,00   60,84

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
sdg               0,00     2,00    0,00  216,00     0,00 109248,00  1011,56   247,75  677,69    0,00  677,69   4,63 100,00

As you can see, only the external harddisk is active. Here is the complete log: http://pastebin.com/YNWTAkh4
The hang started at 20:38:01 and ended at 20:40:19.
Software information:

*

*openSUSE 12.1

*KDE 4.7.x

*Filesystems: reiserfs and btrfs on my internal harddisk, btrfs on the USB drive

A: My first guess was btrfs since the I/O processes of this file system sometimes take over. But it wouldn't explain why X locks up.
Looking at the interrupts, I see this:
# cat /proc/interrupts
           CPU0       CPU1       CPU2       CPU3       CPU4       CPU5       CPU6       CPU7
  0:        179          0          0          0          0          0          0          0  IR-IO-APIC-edge      timer
  1:          6          0          0          0          0          0          0          0  IR-IO-APIC-edge      i8042
  8:          1          0          0          0          0          0          0          0  IR-IO-APIC-edge      rtc0
  9:          0          0          0          0          0          0          0          0  IR-IO-APIC-fasteoi   acpi
 12:         10          0          0          0          0          0          0          0  IR-IO-APIC-edge      i8042
 16:    3306384          0          0          0          0          0          0          0  IR-IO-APIC-fasteoi   ehci_hcd:usb1, nvidia, mei, eth1

Well, duh. The USB driver uses the same IRQ as the graphics card and it is first in the chain. If it locks up (because the file system does something expensive), the graphics card starves (and the network, too).

A: I had seen similar problems with openSUSE 12.1's linux-3.1 kernel and found that disabling transparent huge pages helped:
echo never > /sys/kernel/mm/transparent_hugepage/enabled

The underlying problem is that if an application allocates 4MB or more, the kernel will try to give it a huge page, for which it needs a whole contiguous 4MB RAM. Now, if there are many dirty pages around, that still need to be written to a slow USB device, it waits for that IO to finish before continuing with the memory allocation.

A: As mentioned, this probably has to do with the kernel hugepages setup.
I know several people with this problem. You can find several documentation about it in the web, e.g.

*

*https://bbs.archlinux.org/viewtopic.php?id=112846&p=1

*http://lwn.net/Articles/467328/

*http://forum.manjaro.org/index.php?topic=2062.0

*Slow performance when copying files to and from USB devices
I have completely fixed the problem on my setup by doing the following. Notice YMMV, not all the fixes below may be necessary, and maybe they'll not be sufficient.
I may have forgotten something to be honest. Anyhow that's my setup and it works.

*

*Use linux-ck kernel

*echo madvise > /sys/kernel/mm/transparent_hugepage/enabled

*echo never > /sys/kernel/mm/transparent_hugepage/defrag

A: Change the cable. Remove oxid from usb port/cables.


text:
Q: Trying to INSERT a trim'd value in SQL 2012 but it is ignoring the trim I basically created the inserts in excel because it was the fastest way, copying and pasting it then resulted in this:
INSERT INTO MyCatFantasies values       (RTRIM(LTRIM('  boots   ')),RTRIM(LTRIM('   fluff mcgruff                                                                                ')))

The weird spacing is because of the way I copied it from excel. I figured whacking a couple of trims around the values would insert them into the database without spaces before or after, however after doing the insert, I found that it ignored the TRIM commands and the values were padded with the original whitespace.
Is there an explanation for this behaviour / what I am doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Launching Leap Motion Home App is not working in macOS I installed Leap Motion controller on macOS Catalina. The installation set up run successfully. However, when I try opening the Home APP it does not appear.
I later upgraded mac from macOS Catalina to macOS Big Sur, but Leap Motion Home APP is still not appearing/opening.
Any help?

A: The reason the Home App does not appear is that it is deprecated and no longer being supported on any platforms.
Reply from Developer on the Forum
Leap Motion Blogpost about the Home App

That said, you can still develop apps for the Leap Motion on Big Sur using the V2 SDK. If you want to explore pre-built apps, you can take a look at the Apps Gallery and use the Advanced Search to find apps that run on the V2 SDK.
Leap Motion Gallery of Apps
Using the Advance Search for V2 Apps

A: Leap Motion not working with MacOS Monterey or M1 MacOS Ventura
Download the latest Leap_Motion_SDK_Mac_2.3.1 version here or download it directly here.
Once the software is installed you should see it in your top status menu showing like this:

Using terminal run the following commands:
Check if UVCAssistant is running:
> ps -aex | grep UVCAssistant

Stop the UVCAssistant process:
> killall -9 UVCAssistant

You might have to execute the command multiple times until the Leap Motion Sensor connects and the light turns green or orange

If the terminal command doesn't work (M1 macOS Ventura) you can use the following: Open Activity Monitor App > Select Network Tab > Search for UVCAssistant > Select Stop (Keep stopping until the Leap Motion Sensor connects)
Bonus: If you would like to use it with the BetterTouchTool you can download the btt1.921b.zip version that supports Leap Motion for MacOSX here (Direct link to my personal Google Drive)
The solution is reference here


text:
Q: changing inner array object value with outer array value with map I'm new to full-stack development, specifically to java-script and functional programming.
Using high-order function (like map, filter and so) I need to change inner object array values into the outer array given value:
let arr = [
[ [
  {name: "Alice", age: 22},
  {name: "Charlie", age: 35}
 ], "Bob" ],
 [ [
  {name: "John" , age: 42}
  ], "Ben"]
]

and I need output array of:
output = [
 [
  {name: "Bob", age: 22},
  {name: "Bob", age: 35}
 ],
 [
  {name: "Ben", age: 42}
 ]
]

Thank you.

A: You already knew to use map, so here it is:
arr.map(x => x[0].map(y => {return {...y, name: x[1]}}))

For each item of the main list, we map it to a list of objects with the name replaced.

A: Slightly modified Simon's answer. Added a little bit of destructuring sugar

let arr = [
[ [
  {name: "Alice", age: 22},
  {name: "Charlie", age: 35}
 ], "Bob" ],
 [ [
  {name: "John" , age: 42}
  ], "Ben"]
]

const result = arr.map(([data, name]) => data.map(({age}) => ({name, age})))

console.log(result)


text:
Q: Python lxml finding element by id-tag I am working on a python program for keeping an inventory of a storage room. In a XML-document the amount of toners will be kept and I want my python program to be able to add, remove and display the amount of toners for different printers and different colors.
My XML looks like this:
<?xml version="1.0"?>
<printer>
    <t id="095205615111"> <!-- 7545 Magenta -->
        <toner>7545 Magenta Toner</toner>
        <amount>3</amount>
    </t>
    <t id="095205615104"> <!-- 7545 Yellow -->
        <toner>7545 Yellow Toner</toner>
        <amount>7</amount>
    </t>
</printer>

The id is the number from the barcode that we use for inventory.
So far I have these steps that I would like my program to use:

*

*Check if the id exist (the id-value is a variable in my python program piped from the content in a txt-file)

*Change the value of amount in the xml-document to +1 or -1
Whatever I try it never works fully. Do you have any suggestions of what I could use?

A:
Check if the id exist

You can solve this by constructing an XPath expression checking the @id attribute value.

Change the value of amount in the xml-document to +1 or -1

Once you locate the t node by a specific id, you can use find() to locate the inner amount node. Then, you can get the .text, convert it into an integer, change it, convert back to string and set the .text property.
The working example:
from lxml import etree

data = """<?xml version="1.0"?>
<printer>
    <t id="095205615111"> <!-- 7545 Magenta -->
        <toner>7545 Magenta Toner</toner>
        <amount>3</amount>
    </t>
    <t id="095205615104"> <!-- 7545 Yellow -->
        <toner>7545 Yellow Toner</toner>
        <amount>7</amount>
    </t>
</printer>"""

root = etree.fromstring(data)

toner_id = "095205615111"

# find a toner
results = root.xpath("//t[@id = '%s']" % toner_id)
if not results:
    raise Exception("Toner does not exist")

toner = results[0]

# change the amount
amount = toner.find("amount")
amount.text = str(int(amount.text) + 1)

print(etree.tostring(root))

A: You can also approach it with lxml.objectify which would make handling the data types easier:
from lxml import objectify, etree

data = """<?xml version="1.0"?>
<printer>
    <t id="095205615111"> <!-- 7545 Magenta -->
        <toner>7545 Magenta Toner</toner>
        <amount>3</amount>
    </t>
    <t id="095205615104"> <!-- 7545 Yellow -->
        <toner>7545 Yellow Toner</toner>
        <amount>7</amount>
    </t>
</printer>"""

root = objectify.fromstring(data)

toner_id = "095205615111"

# find a toner
results = root.xpath("//t[@id = '%s']" % toner_id)
if not results:
    raise Exception("Toner does not exist")

toner = results[0]

# change the amount
toner.amount += 1

# dump the tree object back to XML string
objectify.deannotate(root)
etree.cleanup_namespaces(root)
print(etree.tostring(root))

Note, how the amount change is implemented:
toner.amount += 1


text:
Q: How to write this formula in Python? I have this formula that I am struggling to write its Python equivalent:

Where I(x,y) is an image in the form of a numpy array, with the intensity value accessible using a row-column index. xbar is the centroid x coordinate, which is known.
My attempt at code is below:
# centroid is a tuple of (x,y) of the coordinate position. image is a 2d array of the image.
import scipy.integrate as integrate

height, width = image.shape[0:2]

intensity_func = lambda x,y: image[y,x]
denom = int.dblquad(intensity_func, 0, height, lambda x: 0, lambda x: width)
x_f = lambda x,y: (x-centroid[0])**2 * intensity_func(x,y)
x_num = int.nquad(x_f, [[0, width],[0, height]])
sig_x = np.sqrt(x_num[0]/denom[0])

print 4*sig_x


text:
Q: Erro na configuração de MapRoute O seguinte erro é retornado pra mim:

The parameters dictionary contains a null entry for parameter 'numerodeserie' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Equipamento(System.String, System.String, Int32, Int32)' in 'SCO.Controllers.EquipamentosController'

A configuração do meu MapRoute, faço dessa maneira:
routes.MapRoute(
 name: "EquipamentosTrafego",
 url: "Equipamentos/{cidadecod}/{contratocod}/Trafego/{filtro}",
 defaults: new
 {
    controller = "Equipamentos",
    action = "EquipamentosTrafego"
 }
 );

E na minha View tento acessar dessa maneira:

           @item.totaleqpson

O que está errado ?

A: Resolvido. Eu tinha um outro MapRoute configurado que estava sendo referenciado. Coloquei esse MapRoute depois do novo MapRoute:
routes.MapRoute(
       name: "EquipamentosTrafego",
       url: "Equipamentos/{cidadecod}/{contratocod}/Trafego/{filtro}",
       defaults: new
       {
           controller = "Equipamentos",
           action = "EquipamentosTrafego"
       }
       );

MapRoute que dava conflito, colocado depois:
routes.MapRoute(
      name: "Equipamento",
      url: "Equipamentos/{cidadecod}/{contratocod}/{numerodeserie}/{faixa}",
      defaults: new
      {
          controller = "Equipamentos",
          action = "Equipamento"
      }
      );


text:
Q: Hide or removing a menubar of tkinter in python I can set my menu with the following instruction:
my_tk.config(menu=my_menu_bar)

But, How do I remove it or hide it completely?
my_tk.config(menu=None)

doesn't work :-(

A: Just FYI, I know this question is old and has an accepted answer but this worked for me on tkinter version 8.6 Python 3
my_tk.config(menu="")

For some reason an empty string works but not None

A: Is this what you're looking for:
from tkinter import *
root = Tk()

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

submenu = Menu(menubar)
menubar.add_cascade(label="Submenu", menu=submenu)
submenu.add_command(label="Option 1")
submenu.add_command(label="Option 2")
submenu.add_command(label="Option 3")

def remove_func():
    menubar.delete(0, END)

remove_button = Button(root, text="Remove", command=remove_func)
remove_button.pack()

?

A: Another way is:
from tkinter import *
root = Tk()

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

submenu = Menu(menubar)
menubar.add_cascade(label="Submenu", menu=submenu)
submenu.add_command(label="Option 1")
submenu.add_command(label="Option 2")
submenu.add_command(label="Option 3")

def remove_func():
    emptyMenu = Menu(root)
    root.config(menu=emptyMenu)

remove_button = Button(root, text="Remove", command=remove_func)
remove_button.pack()

What's different:
in
def remove_func():

created an empty menu
emptyMenu = Menu(root)

and replaced it with the current menu (menubar)
root.config(menu=emptyMenu)


text:
Q: Remove image caption from post excerpt I am currently using a wordpress plugin called "limit-posts" to better customize my post excerpts. The only issue I have is the excerpt is including the caption text from the image that is within the post.
I can see in the code that all captions are enclosed in  tags
Is there a way I can strip out the any content within em tags from the post excerpt?
Here is a link to the current plugin in use - http://labitacora.net/comunBlog/limit-post.phps
Thank you very much

A: From what I understand the caption is a shortcode, so wrap get_the_content(...) inside strip_shortcodes() and it should remove it...

A: You can always simply hide it with CSS.
It's not a perfect solution but may be sufficient for your case.
CSS class of the caption paragraph is .wp-caption-text

A: I'd not use something like this at all. There are plenty of hooks for content and excerpt retrieval to use, I see absolutely no need to drop native functions in favor of something else.
You can use excerpt_length filter to change excerpt length (in words) or the_excerpt to make changes to excerpt's text before output.
If I may ask - what is your technical level with WordPress? Do you want some code examples for this? If so please write out how exactly you want excerpt modified.


text:
Q: Git: reset to a too old commit, and git log , only show from the commit I have now Today I use git, commit , the info is: 2016-11-25.
and after I do something wrong, I reset back to a old commit which info is:2016-10-18 careless.
and now I want to go to the 2016-11-25, but when I git log, not show my commit:

A: You can use Git's reflog feature, which is a sort of audit trail of all the things which happen as you use Git, including commits.
git reflog --date=iso

Try to find an entry looking something like the following:
b28ae3b HEAD@{2016-11-25 15:54:53 +0800}: commit: message for the commit which you
made earlier today

If you can find the commit, record the SHA-1 hash (b23ae3b in this example) because you will need it to restore your branch at that commit.  Now restore your branch via the following:
git checkout yourBranch
git reset --hard b28ae3b


text:
Q: how to use load cursor in db2 to insert null entries for newly created definition of existing table i have a requirement where i had to modify the definition of the existing table (my_Table) by adding new columns in mid of the table.
I have taken backup of the table, dropped the existing one and created it with new definition.
Now i wanted to load all the old data from backup file to my newly modified table using cursor load so that all the other columns get populated with data from backup file and newly added columns have ' ' (blank ) in the table
How to achieve this in DB2


text:
Q: How do I show Blogger comment form on mobile? The comment form of my Blogger blog is invisible in mobile devices. It only shows up whenever a first comment is posted using desktop. If comment is zero, the comment form is not shown in mobile.
I've tried the following css, to no avail
CSS
@media screen and (max-width:480px) {
#comments-block {display: block;}
.comment-footer {display: block;}
.comment-form {display: block;}
}

HTML

Thanks for your help.

A: Try to use
.blogger-iframe-colorize {
display: block !important;
}

See here:https://www.gurubest.com/2014/11/how-i-fixed-blogger-comment-form-for.html


text:
Q: Embedding quicktime player in Cocoa app I'm wondering if it's possible for me to embed the quicktime player in a cocoa app. The default QTMovieView is kind of ugly, and the quicktime player window has all the features I need in it, such as full screen, and the maintain aspect ratio button.
I'd like it to operate transparently to the user though. I'd rather avoid making them launch the quicktime app. I'd also like to be able to position the window on the screen. Also, I need to be able to access the current playhead position, and capture when they stop the movie. Any ideas on how I might go about doing this? Or would I have to build out my own custom video player?
A third party component would be fine as well if any exist. I'm just looking for that same quicktime player appearance with the black control bar that appears when hovering over the screen.

A:
Or would I have to build out my own custom video player?

Yes. There is no (reliable) way of getting QuickTime player to integrate into your application.
You should make a subclass of QTMovieView, and maybe use some subviews for the controls.

A: You can hide the controls if the QTMovieView if you do not like them. In IB switch off Show Controller property.
Alternatively, you can use QTMovieLayer.
Also, it is easy to create your own set of controls that will work directly with the properties and methods of the QTMovie.


text:
Q: How to write datatable rows to multiple files N number of records at a time? I have a query that pulls an unknown number of rows in to a datatable. I need to write the datatable to multiple tabbed delimited text files with only 55 rows per file. Desired results Ex. 176 records from query. File1 - 55 records, File2 - 55 records, File3 - 55 records, File6 - 11 records. I am not sure the best way to do this. Any help would be greatly appreciated.
Current Code:
DataTable results = sql results;

if (results.Rows.Count > 0)
{
    int counter = 0;
    int maxRows = 55;
    string fileName = path + "File_" + today.ToString("yyyyMMdd") + ".txt";

    if (File.Exists(fileName))
    {
        File.Delete(fileName);
    }

    for (int i = 0; i < results.Rows.Count; i++)
    {
        var currentRow = results.Rows[i];

        _writer.WriteDataToFile(results, fileName, delimiter); //This method writes a datatable to a file

        counter = counter + i;
    }
}

A: Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication190
{
    class Program
    {
        const string PATH = @"Enter Path Here";
        const int NUMBER_ROWS = 55;
        static void Main(string[] args)
        {

            DataTable results = new DataTable();
            DateTime today = DateTime.Now.Date;
            if (results.Rows.Count > 0)
            {
                int filenumber = 0;
                int rowCount = 0;
                StreamWriter writer = null;
                foreach (DataRow row in results.AsEnumerable())
                {
                    if (rowCount % NUMBER_ROWS == 0)
                    {
                        if (writer != null)
                        {
                            writer.Flush();
                            writer.Close();
                        }
                        string fileName = PATH + "File_" + ++filenumber + "_" + today.ToString("yyyyMMdd") + ".txt";
                        writer = new StreamWriter(fileName);
                    }
                    writer.WriteLine(string.Join("\t", row.ItemArray));
                    rowCount++;
                }
                writer.Flush();
                writer.Close()
            }
        }
    }
}


text:
Q: Expanding var names of __VA_ARGS__ in C++ preprocessor macro I'm trying to implement a proper enum to str macro which would automatise the association between enum values and their name in the code.
For example I'd like to define a new macro called "Test" like this:
ENUM_STR_DECLARE(Test, 1, test1, test2, test3)

This way, by calling TestEnumToString(test2) I could get access to a string "test2". At the moment, my current implementation of this ENUM_STR_DECLARE is done as follows:
#define ENUM_STR_DECLARE(enumName, intOffset, v1, ...)\
  enum enumName { v1 =  intOffset, __VA_ARGS__};\
  const char *enumName##EnumStringArray[] = { #v1 ,#__VA_ARGS__};\
  const char *enumName##EnumToString(value) { return enumName##EnumStringArray[ value - offset ]; }

Although when I do that, the enums handled by __VA_ARGS__ doesn't get a proper name separation:
enum Test {
    test1 = 1, test2, test3
};
const char *TestEnumStringArray[] = {"test1", "test2, test3"};
const char *TestEnumToString(value) { return TestEnumStringArray[ value - offset]; }

as I'd like to have "test2", "test3" instead of "test2, test3".
Is there any way to expand #__VA_ARGS__ names with a comma separation?
Cheers!
Edit: A workaround proposal
It seems there is no easy/elegant solution for this problem. The best implementation so far was proposed by @h-walters which provided a pretty detailled break down of the implemntation (thanks for your time!). Here is the link he shared for those who are interested:
H. Walters example.
However it seems even this implementation have to limit the number of enums you define (9 in his case). So a workaround has been the definitive answer for me.
Instead of struggling to get way of slicing __VA_ARGS__, one can simply stringify the whole __VA_ARGS__ as I did, and slice the obtained string each time we want to get the name of a specific enum. Obviously, this is a slower approach since it requires to parse the whole string each time instead of fetching directly with the enum index.
This speed issue is not relevant for me since the enum to string conversion is intended to be used for display purposes, otherwise the enum are directly used for time consuming routines. If you still wanna be fast while getting the string translation tho, you can take advantage of a cache (like a std::vector<std::string> for example) which could be built the first time you call the toString() method. Or you can go for @h-walters solution, which is the fastest, knowing its limitations.
Enough talking, here is the solution I finally end up with:
#define VA_TO_STR(...) #__VA_ARGS__

#define ENUM_STR_DECLARE(enumName_, intOffset_, v1_, ...)\
  enum enumName_ { v1_ =  intOffset_, __VA_ARGS__, enumName_##_OVERFLOW };\
  namespace enumName_##EnumNamespace{\
    const char *enumNamesAgregate = VA_TO_STR(v1_, __VA_ARGS__); \
    int enumOffSet = intOffset_; \
    std::string toString(int enumValue_) {\
      int commaCounter = 0; std::string outStr;\
      for( unsigned long iChar = 0 ; iChar < strlen(enumNamesAgregate) ; iChar++ ){ \
        if( enumNamesAgregate[iChar] == ',' ){\
          if( not outStr.empty() ){ return outStr; } /* found! return */\
          else{ commaCounter++; iChar += 2; } /* not yet found, next */ \
        }\
        if( commaCounter == enumValue_ ){ outStr += enumNamesAgregate[iChar]; }\
      }\
      return outStr;\
    }\
    std::string toString(enumName_ enumValue_){ return enumName_##EnumNamespace::toString(static_cast<int>(enumValue_)); }\
    int toEnumInt(const std::string& enumStr_){\
      for( int enumIndex = intOffset_ ; enumIndex < enumName_::enumName_##_OVERFLOW ; enumIndex++ ){ \
        if( enumName_##EnumNamespace::toString(enumIndex) == enumStr_ ){ return enumIndex; } \
      }\
      return intOffset_ - 1; /* returns invalid value */\
    }\
    enumName_ toEnum(const std::string& enumStr_){ return static_cast<enumName_>(enumName_##EnumNamespace::toEnumInt(enumStr_)); }\
  }

Thus, the simple example I presented above would unfold as:
enum Test {
  test1 = 1, test2, test3, Test_OVERFLOW
};
namespace TestEnumNamespace {
  const char *enumNamesAgregate = "test1, test2, test3";
  int enumOffSet = 1;
  std::string toString(int enumValue_) {
    int commaCounter = 0;
    std::string outStr;
    for (unsigned long iChar = 0; iChar < strlen(enumNamesAgregate); iChar++) {
      if (enumNamesAgregate[iChar] == ',') {
        if (notoutStr.empty()) { return outStr; }
        else {
          commaCounter++;
          iChar += 2;
        }
      }
      if (commaCounter == enumValue_) { outStr += enumNamesAgregate[iChar]; }
    }
    return outStr;
  }
  std::string toString(Test enumValue_) { return TestEnumNamespace::toString(static_cast<int>(enumValue_)); }
  int toEnumInt(const std::string &enumStr_) {
    for (int enumIndex = 1; enumIndex < Test::Test_OVERFLOW; enumIndex++) {
      if (TestEnumNamespace::toString(enumIndex) == enumStr_) { return enumIndex; }
    }
    return 1 - 1;
  }
  Test toEnum(const std::string &enumStr_) { return static_cast<Test>(TestEnumNamespace::toEnumInt(enumStr_)); }
}

So let's say, if you want to get the string of the enum "test1":
TestEnumNamespace::toString(Test::test1);
TestEnumNamespace::toEnum("test1");

Hope it will help other dev :).
Cheers again!

A: Using boost preprocessor:
#include <boost/preprocessor/tuple.hpp>
#include <boost/preprocessor/seq.hpp>
#include <boost/preprocessor/stringize.hpp>

#define MACRO_DELIM(r, data, elem) BOOST_PP_STRINGIZE(elem) ,

#define DELIMITED_STRINGIZE(...) \
    BOOST_PP_SEQ_FOR_EACH(MACRO_DELIM, _, \
        BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)))

#define ENUM_STR_DECLARE(enumName, intOffset, v1, ...)\
  enum enumName { v1 =  intOffset, __VA_ARGS__};\
  const char *enumName##EnumStringArray[] = { DELIMITED_STRINGIZE(v1, __VA_ARGS__)};\
  const char *enumName##EnumToString(value) { return enumName##EnumStringArray[ value - offset ]; }

ENUM_STR_DECLARE(Test, 1, test1, test2, test3)

Demo:
http://coliru.stacked-crooked.com/a/3f3376f2d4abe266

A: Not exactly solution, but workaround, downside is you have to free each enum:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char** explode(const char* src, size_t & out_size);

#define CAT(...) #__VA_ARGS__
#define ENUM_STR_DECLARE(enumName, intOffset, v1, ...)\
    enum enumName { v1 =  intOffset, __VA_ARGS__};\
    const char *enumName##EnumString = CAT(v1, __VA_ARGS__);\
    size_t enumName##EnumStringArraySize = 0;\
    const char **enumName##EnumStringArray = explode(enumName##EnumString, enumName##EnumStringArraySize);\
    const char *enumName##EnumToString(size_t value) { return enumName##EnumStringArray[ value - intOffset ]; }\
    void free##enumName() {\
        for (size_t i = 0; i < enumName##EnumStringArraySize; ++i) {\
            free((char *)enumName##EnumStringArray[i]);\
        }\
        free(enumName##EnumStringArray);\
    }

ENUM_STR_DECLARE(Test, 3, test1, test2, test3, test4, test5, test6)

int main() {
    printf("test1: %s, test3: %s, test6: %s", TestEnumToString(test1), TestEnumToString(test3), TestEnumToString(test6));

    freeTest();
    return 0;
}

const char** explode(const char* src, size_t & out_size)
{
    size_t size = strlen(src);
    if (!size) return NULL;

    int i = 0;
    char* psrc = (char*)src;
    for (; psrc[i]; (psrc[i] == ',' ? i++ : *psrc++));

    char** dest = (char**)malloc(sizeof(char*) * ++i);
    out_size = i;

    char* srcCopy = (char*)malloc(size + 1);
    memcpy(srcCopy, src, size);
    srcCopy[size] = '\0';

    const char * d = ", \0";
    char* tok = strtok(srcCopy, d);
    if (tok == NULL) {
        // only one item
        dest[0] = (char*)malloc(size + 1);
        memcpy(dest[0], src, size);
        dest[0][size] = '\0';
    }
    else {
        // first item
        size = strlen(tok);
        dest[0] = (char*)malloc(size + 1);
        memcpy(dest[0], tok, size);
        dest[0][size] = '\0';

        // rest
        i = 1;
        while ((tok = strtok(NULL, d)) != NULL) {
            size = strlen(tok);
            dest[i] = (char*)malloc(size + 1);
            memcpy(dest[i], tok, size);
            dest[i][size] = '\0';
            ++i;
        }
    }

    free(srcCopy);

    return (const char**)dest;
}


text:
Q: How to use .animate() in jquery Hope you could check my code. Just want to animate. Toggle the top position of div tag with 'accordionHeader' class.
<script type="text/javascript">
  $(document).ready(function() {
    $(".accordionHeader").toggle(function() {
      $(".accordionHeader").animate({"top": "0 144px"}, 500);
      function(){
        $(".accordionHeader").animate({"top": "144px 0"}, 500);
      );
  });
</script>

Thank you so much.

A: you mean:
$(document).ready(function(){
   $(".accordionHeader").toggle(
     function(){
        $(".accordionHeader").animate({"top": "144px"}, 500);
     },
     function() {
        $(".accordionHeader").animate({"top": "-144px"}, 500);
     });
});

As an alternative, since jQuery.toggle() is deprecated, you could also do:
$(".accordionHeader").on("click", function() {
    var clicked = $(this).data('clicked');
    if (clicked) {
        $(".accordionHeader").animate({"top": "144px"}, 500);
    }
    else {
        $(".accordionHeader").animate({"top": "-144px"}, 500);
    }
    $(this).data("clicked", !clicked);
});

A: you can try this on click event
 $('.accordionHeader').animate({ position: 'relative', top: '144px' }, 500);


text:
Q: Establish Concurrent Websocket Connections to server Using Python Twisted Websocket Client I'm trying to open concurrent websocket connections from client end(which has 60k ports limit per machine) using Python Twisted Authobhan Websocket Client.But I'm unable to open not more than 20k connections using below code:
from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory

class WebSocketClient(WebSocketClientProtocol):

    def _handshake_request(self):
        pass

    def onOpen(self):
        self._handshake_request()

    def onConnect(self, response):
        pass
    def onMessage(self,data):
        pass

class WebSocketFactory(WebSocketClientFactory):

    """WebSocketClient Factory"""

    protocol = WebSocketClient

if __name__ == '__main__':

    factory = WebSocketFactory()

    ##### Note here. ######
    for _ in range(num_connections):
        reactor.connectTCP(ws_url, ws_port, factory)
    #####

    reactor.run()

I have used "reactor.connectTCP" in a loop, Does it the correct way to open the concurrent websocket connections using Twisted?
Let me know.

A: You need to perform fewer concurrent connection attempts.  You may be able to sustain 20k or more connections but you won't be able to establish them all simultaneously.
Limit yourself to a few dozen or a hundred at a time.  You may want to use twisted.internet.task.cooperate for this.


text:
Q: How to update controller variable with 'ng-model' AngularJS? I am trying to get user input through a text box using ng-model, and append to a base URL for a http.get call as follow;
index.html:

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Search Video</title>
        <link rel="stylesheet" href="app/css/custom/main.css">
        <link rel="stylesheet" href="app/css/custom/responsive.css">

                <input type="text" id="searchTxt" ng-model="append">
                Search Video

searchcontroller.js
'use strict';

var vidcontrol = angular.module("vidcontrol", []);

vidcontrol.controller("vidcontroller", ['$scope', '$http', function($scope, $http) {
    $http.get('http://api.themoviedb.org/3/tv/airing_today?api_key=d5e87524383e2872a9555990b268dc5b').success(function(response) {
        $scope.results = response.results;
    });
}]);

vidcontrol.controller('searchController', ['$scope', '$http',
    function ($scope, $http) {
        var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
        // var searchTxt = $('#searchTxt').val();// this works fine when used
        var searchUrl = url + append; //$scope.append also logs 'undefined' on the console
        $http.get(searchUrl).success(function (response) {
            $scope.searchResults = response.results;
        });
    }]);

but I'm not getting any response. when I log searchUrl on console, I could see that append was not updated according to value from text box. I'm quite new to Angular and I can't figure out what I'm doing wrong. What should I do to fix this?

A: Now, I see the issue. When controller loaded, it executes controller code. That mean REST query runs before view is built. That is reason you see undefined problem. Solution is to define a method in controller which will be invoked when you click "Search Video".
Update view
 Search Video //Look at ng-click

Update Controller:
vidcontrol.controller('searchController', ['$scope', '$http',function($scope, $http) {
            var url = "http://api.themoviedb.org/3/search/movie?api_key=d5e87524383e2872a9555990b268dc5b&query=";
            $scope.search = function(){ // Look at here, Defined a method to invoke on "Search Video" link click
                var searchUrl = url + $scope.append;
                $http.get(searchUrl).success(function(response) {
                    $scope.searchResults = response.results;
                });
            };
        } ]);


text:
Q: Deleted Scheduled Messages still sending I am building a slack application that will schedule a message when someone posts a specific type of workflow in a channel.
It will schedule a message, and if someone from a specific group of users replies before it has sent, it will delete the scheduled message.
Unfortuantely these messages are still sending, even though the list of scheduled messages is empty and the response when deleting the message is a successful one. I am also deleting the message within the 60 second limit that is noted on the API.
Scheduling the message gives me a success response, and if I use the list scheduled messages I get:
[
  {
    id: 'MESSAGE_ID',
    channel_id: 'CHANNEL_ID',
    post_at: 1620428096, // 2 minutes in the future for testing
    date_created: 1620428026,
    text: 'thread_ts: 1620428024.001300'
  }
]

Canceling the message:
async function cancelScheduledMessage(scheduled_message_id) {
  const response = await slackApi.post("/chat.deleteScheduledMessage", {
    channel: SLACK_CHANNEL,
    scheduled_message_id
  })

  return response.data
}

response.data returns { "ok": true }
If I use the list scheduled message API to retrieve what is scheduled I get an empty array []
However, the message will still send to the thread.
Is there something I am missing? I have the proper scopes set up and the API calls appear to be working.
If it helps, I am using AWS Lambda, and DynamoDB to store/retrieve the thread_ts and message IDs.
Thanks all.

A: For messages due in 5 minutes or less, chat.deleteScheduleMessage has a bug (as of November 2021)  [1]. Although this API call may return OK, the actual message will still be delivered due to the bug.
Note that for messages within 60 seconds, this API does return an proper error code, as described in the documentation [2]. For the range (60 seconds, ~5 minutes), the API call returns OK but fails behind the scenes.
Before this bug is fixed, the only thing one can do is to only delete messages scheduled 5 minutes (the exact threshold may vary, according to Slack) or more (yes not very ideal and may not be feasible for some applications).
[1] Private communication with Slack support.
[2] https://api.slack.com/methods/chat.deleteScheduledMessage


text:
Q: Setting the taskbar overlay icon with programmatically created I'm in the process of programmatically recreating an overlay icon so to present text on the taskbar icon. I did this:
    GlyphRunDrawing gDrawing = new GlyphRunDrawing(Brushes.Black,
                                           iconOverlayText.ToGlyphRun());

    Window.TaskbarItemInfo =
        new System.Windows.Shell.TaskbarItemInfo();
    DrawingImage image = new DrawingImage();
    image.Drawing = gDrawing;

    Window.TaskbarItemInfo.Overlay = image;

The image source seems fine, if I set "image" as the source of a test wpf image, the text displays just fine. But for some reason, it doesn't display on the taskbar icon. Do you know why?
So I tried a few other options, like the official taskbar support libraries. It's a little confusing, because there are two of them seemingly, but neither worked to show an icon overlay for me:
It doesnt work on this official sample application sample MainDemo and IMClient demo:

http://code.msdn.microsoft.com/Windows7Taskbar

And I can't start the other samples collection called Win7API Codepack sample, because of this cryptic error:

TaskDialog feature needs to load version 6 of comctl32.dll but a different version is current loaded in memory.

Any suggestion what might be wrong?

A: From the Remarks section of TaskbarItemInfo.Overlay:

The overlay is not displayed if the
  user sets the taskbar to show small
  icons


text:
Q: passing char array as argument to fopen I am trying to open a file (on ubuntu) who's path is in a variable path. But when I try to pass path to fopen() it fails to find the file.
Here is piece of code
char path="./client.c";
FILE *fp;
if((fp=fopen(path,"r"))==NULL)
printf("file could not be opened\n");

Nevertheless, if I directly pass the path it works fine. Following code works fine.
FILE *fp;
if((fp=fopen("./client.c","r"))==NULL)
printf("file could not be opened\n");

What am I doing wrong? How can i fix it?

A: You are not declaring the array size in
char path="./client.c";

Change it to:
char path[]="./client.c";

Now your code should run as desired.
And if you are interested in using pointers use
const char* path="./client.c";

to point directly to the string

A: Replace
char path="./client.c";

with
const char* path="./client.c";
//^no array, just point to the string literal

if you don't need to modify the path.
If you do, then:
char path[]="./client.c";
//^create a modifiable array from the string literal

char path="./client.c";

compiles because a string literal autoconverts to the adress of the string literal
(they're placed in a static, usually read-only, segment of your executable) which is an integer that can be, with a loss, assigned to a char.
However, you should absolutely get a warning about this from the compiler.
Aim for compilation without any warnings.

A: Just replace the line
char path="./client.c";

with
char path[]="./client.c";


text:
Q: PHP on a site with dynamic content SO FAR I have made a website which is connected to a MYSQL database. On the website I have many buttons, each button corresponds to a table in my database. When I click the button, a javascript function opens my php file in this form

xmlhttp.open("GET", "addPoint.php?q=" + name, true);  Where name is the name of the table

Back to the html. I have a div with an ID that will update with whatever the PHP echos.
The div is now populated with table, reflecting the table in mysql. This all works fine.
Here is the problem: I am trying to implement a voting system, where you vote by clicking on one of the elements of the newly created table. AFAIK the MYSQL updating which will need to happen for the vote to work, will need to be done in PHP, which means that I need to tell the PHP file

*

*The name of the table

*The name of the element

I am reluctant to use forms because I would like to just be able to click some text, NOT have to fill in a form or click a radio button.
So how do I get these 2 bits of info to a PHP file? Is the structure which I am doing this any good or should I step back and redesign?
Thanks for reading please let me know if I have been ambiguous.

A: Familiarize yourself with JQuery. It's great for projects like these.
http://www.w3schools.com/jquery/default.asp

A: As Norse already alluded to, use javascript to submit a "form" request for you. The javascript can populate the table and element values for you based on the button which was clicked. It is up to you whether this is a GET/POST.
JQuery would be a great way to help make this easier, but you don't need it if you don't want it.


text:
Q: SharePoint 2010: Site Content and Structure copy/move is disabled I want to copy (or move) a list (or a library) from one website to another:
From: https ://sp.mydomain.de/Website1
To:   https ://sp.mydomain.de/Website2
When calling Site Content and Structure (https: //sp.mydomain.de/_layouts/sitemanager.aspx) and navigatin to Website1 I can select the list which I want to move.
In the menu action I only can select "delete" - not "copy" or "move" (grayed out).
I am doing this as the site admin (and tried site collection manager etc.)
http://imageshack.com/a/img823/258/oqlj.png
Why are these menu elements not available?
Best regards,
Stefan

A: This forumpost on Social Technet is about the same problem you are facing and in the answers are several options you can try out. One answer that got my attention stated following:

The move action is available only for individual items you can't perform  move action for document library or for folder instead of move you can perform that using extension from gary lapointe  http://stsadm.blogspot.com/2007/08/stsadm-commands_09.html gl-exportlist command.

This is the last answer on the page. I hope this is of any help!


text:
Q: Uploading files to Google Cloud Storage with Flask I'm trying to upload some images to GCS via an App Engine instance using Flask, but every time the file it's uploaded, when I download it I get a corrupt file. What am I doing wrong ?
I've downloaded and used the Google Cloud Storage client the way is in the docs.
@app.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        extension = secure_filename(file.filename).rsplit('.', 1)[1]
        options = {}
        options['retry_params'] = gcs.RetryParams(backoff_factor=1.1)
        options['content_type'] = 'image/' + extension
        bucket_name = "gcs-tester-app"
        path = '/' + bucket_name + '/' + str(secure_filename(file.filename))
        if file and allowed_file(file.filename):
            try:
                with gcs.open(path, 'w', **options) as f:
                    f.write(str(file))
                    print jsonify({"success": True})
                return jsonify({"success": True})
            except Exception as e:
                logging.exception(e)
                return jsonify({"success": False})

Thanks for your help !!

A: You're uploading (writing to the gcs stream) the str representation of the file object, not the file contents.
try this:
@app.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        extension = secure_filename(file.filename).rsplit('.', 1)[1]
        options = {}
        options['retry_params'] = gcs.RetryParams(backoff_factor=1.1)
        options['content_type'] = 'image/' + extension
        bucket_name = "gcs-tester-app"
        path = '/' + bucket_name + '/' + str(secure_filename(file.filename))
        if file and allowed_file(file.filename):
            try:
                with gcs.open(path, 'w', **options) as f:
                    f.write(file.stream.read())# instead of f.write(str(file))
                    print jsonify({"success": True})
                return jsonify({"success": True})
            except Exception as e:
                logging.exception(e)
                return jsonify({"success": False})

But this is not the most efficient way to do this, also, there is a 32mb cap on file uploads straight from app engine, the way to avoid this is by signing an upload url with GCS and upload the file directly from the front-end to GCS, or you can create a file upload url with blobstore and a handler to do the post-upload processing, as specified here: https://cloud.google.com/appengine/docs/python/blobstore/


text:
Q: Unable to clear interval when element is outside viewport in Intersection Observer API I'm trying out Intersection Observer API but I have come to a dead end when I use setInverval with it.
So I have this div which have width and height of 500px. If the div is in viewport I want to trigger setInterval which will log something every 3 seconds. But if I scroll and the div is outside the viewport I want to clear that interval. That is, stop the interval and stop the logging altogether.
Right now when I scroll and the div is in viewport, the setInterval and the logging starts  but if I scroll again and the div is not in the viewport the setInterval and the logging doesn't stop.
What am I doing wrong here?
Here's the snippet:

const mainContainer = document.querySelector('#main-container');

const callback = (entries, observer) => {

  entries.forEach(item => {

    let intervalVar;

    if (item.isIntersecting) {

      intervalVar = setInterval(() => {

        console.log('div is in viewport');

      }, 3000);

    } else {

      console.log('div is not in viewport');

      clearInterval(intervalVar);

    }

  })
};

const options = {
  threshold: 0.1
};

const observer = new IntersectionObserver(callback, options);
observer.observe(mainContainer);

A: So, here's one way of tackling the problem.
I've created a Map between an entry from the intersection observer callback's entries argument and the interval id (intersections).
I've created a function (intersectionChanged) that gets called for each entry in the intersection observer callback's entries argument. It checks to see if the entry is intersecting, and whether we have an interval id yet. If both are true, it clears the existing interval and adds a new one. If it's newly intersecting, it adds a new interval. If it's not intersecting, and there's an interval id, it clears that interval. Otherwise, it does nothing. In other words, if it's not intersecting, and no interval id exists, it doesn't do anything.
Putting them together was easy with the code you already had built.

const mainContainer = document.querySelector('#main-container');
const intersections = new Map();
const intersectionChanged = function (entry) {
  if (entry.isIntersecting && intersections.get(entry.target) != null) {
    clearInterval(intersections.get(entry.target));
    intersections.set(entry.target, setInterval(() => {
        console.log('div is in viewport');
      }, 3000));
  } else if (entry.isIntersecting) {
    intersections.set(entry.target, setInterval(() => {
        console.log('div is in viewport');
      }, 3000));
  } else if (!entry.isIntersecting && intersections.get(entry.target) != null) {
    console.log('div is not in viewport');
    clearInterval(intersections.get(entry.target));
  }
};
const callback = (entries, observer) => {
  entries.forEach(intersectionChanged);
};

const options = {
  threshold: 0.1
};

const observer = new IntersectionObserver(callback, options);
observer.observe(mainContainer);


text:
Q: configuring rds without having a domain How to configure  Active Directory Domain Services Configuration if i dont have a domain.
problem statement
I have a server and i want to install RDS inorder to have session based virtualisation so that 5-6 users can access this server .
so i wanted to install RDS from adding roles and features. when i start this process i get an
error saying local server must be joined to the domain to complete the RDS installation
please help me out

A: RDS requires the server to be a domain member for this scenario. If I recall correctly, it won't behave properly on a domain controller either, so it needs to specifically be a domain member server.
Therefore, what I would suggest if this is a physical server, is installing a DC and the RDS server as two different virtualised servers on top of a HyperV host. If that doesn't work for you then you may need to completely re-think what you're trying to accomplish.


text:
Q: How to get recently used and closed apps in android Lollipop version? The following code is working for  before Lollipop versions, but after Lollipop, it's not working. Any suggestion?
Log.e(TAG,"-----RECENT APPS-----\n");
for (ActivityManager.RecentTaskInfo task : recentTasks) {
    Intent baseIntent = task.baseIntent;
    if (baseIntent != null) {
        String text = baseIntent.getComponent().getPackageName();
        String appName = "";
        try {
            appName = (String) pack.getApplicationLabel(
                    pack.getApplicationInfo(text, PackageManager.GET_META_DATA));
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
        Log.i(TAG, "Recent Apps : " + text + " :" + appName);
        recent_task_map.put(text, (String) appName);
    } else {
        Log.i(TAG, "RecentTask :" + " No Recent task");
    }
}

A: getRecentTasks() is deprecated and will only work for devices having API level < 21
If you wish to do so for devices having API level > 21, you can use getAppTasks() to get the list of tasks related to the calling application.
For more information, check out the below links :
https://developer.android.com/reference/android/app/ActivityManager.html#getRecentTasks(int%2C%20int)
https://developer.android.com/reference/android/app/ActivityManager.html#getAppTasks()


text:
Q: Cucumber test results always return 0 if run from Maven EDIT (2018-01-24):
Since none of the comments are working, I have updated the post to include the present state and include more details. If anyone can have a fresh look, please go ahead.

When running mvn clean test, the test results for Cucumber are always 0. When a step fails, the result is always BUILD SUCCESS.
Maven Results:

Directory Structure:

pom.xml:
<project>
  [...]
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!-- Core Dependencies -->
        <java.version>1.8</java.version>
        <cucumber.version>1.2.5</cucumber.version>
        <ngwebdriver.version>1.0</ngwebdriver.version>
        <selenium.version>3.8.1</selenium.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-picocontainer</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.12</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.paulhammant/ngwebdriver -->
        <dependency>
            <groupId>com.paulhammant</groupId>
            <artifactId>ngwebdriver</artifactId>
            <version>${ngwebdriver.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>${selenium.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20.1</version>
                <configuration>
                    <includes>
                        <include>**/*Runner.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Runner:
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/features", tags = { "~@ignore" }, glue = "stepdefs", plugin = {
        "pretty", "html:target/cucumber-reports/test-report", "json:target/cucumber-reports/test-report.json",
        "junit:target/cucumber-reports/test-report.xml" }, snippets = SnippetType.UNDERSCORE, monochrome = true, dryRun = false)

public class MainRunner {

}

A: I found the solution.
Problems are caused by TestNG Assert. Looks like Maven reads only JUnit Asserts.
When I switched my JUnit Asserts to TestNG I was able to recreate your issue.


text:
Q: show and hide div from bottom to top I have this example with a div which show / hide from the top, but I need it from the bottom to the top, I was trying to change some code, but I couldn't, and I didn't find any example.

titulo

contenido

Ocultar

A: Use $("#top-panel").slideUp();  instead of slideToggle()


text:
Q: Sort array from days Laravel 5.8 I want to sort an array according to the days name order. here is my array comes from query result.

        $data = DB::table('jobs')
                ->select('day', DB::raw('count(*) as count'))
                ->groupBy('day')
                ->get()->toArray();

Output is:

I send this data to draw a bar chart with chart.js , so I want to sort this array from Monday to Friday.
I'm new to laravel. please help me to solve this. thank you in advance.

A: You could sort them based on the carbon day constants.
Carbon\Carbon::SUNDAY evaluates to 0, Carbon\Carbon::MONDAY evaluates to 1 all the way to Carbon\Carbon::SATURDAY evaluating to 6.
To programatically get a constant, you can use the constant($string) method.
$data = DB::table('jobs')
    ->select('day', DB::raw('count(*) as count'))
    ->groupBy('day')
    ->get()
    ->sortBy(function ($job) {
        return constant('\Carbon\Carbon::'.strtoupper($job->day));
    })
    ->values()
    ->toArray();

or using php > 7.4
$data = DB::table('jobs')
    ->select('day', DB::raw('count(*) as count'))
    ->groupBy('day')
    ->get()
    ->sortBy(fn($job) => constant('\Carbon\Carbon::'.strtoupper($job->day)))
    ->values()
    ->toArray();

This should return them in a Sunday to Saturday order.
If you want them ordered Monday to Sunday, you're going to need to tweak it a little.
Instead of
return constant('\Carbon\Carbon::'.strtoupper($job->day))

return (6 + constant('\Carbon\Carbon::'.strtoupper($job->day))) % 7;

A: In most cases, you probably want to store date data, not a string with the name of the day. That way you can use order by on your date column.
In your case, you can do something like:
$days = array_flip(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]);

usort($data, function($a, $b) use ($days) {
  return $days[$a->day] <=> $days[$b->day];
});

A: You can try simply this :
$outputArray  = array[$data[1],$data[3],...];


text:
Q: Call twice timeupdate have problem to call twice timeupdate.
My code is:
$("video").on(
    "timeupdate",
    function(event){
        alert('work');
    }
);

it work but if I do this:
$('#video').html( $('#newVideo').html());

previous code dont work.
I try next way also not work:

*

*<video id="video">

*`$(document).on( "timeupdate", 'video',
$(document).delegate('video',
$("video").bind(,
$( "video" ).live(`

A: Call .on() on an element higher up the heirarchy to ensure the event binding works for any element under it matching the selector - whether that element is currently existing or not.
// this will work for all <video> elements within the document object
$(document).on("timeupdate", 'video', function(event){
    alert('work');
});
// if possible change 'document' to something that is
// closer up in the hierarchy to the video elements

A: My solution is:
function initPlayer () {
    var player = $(document).find('video')[0];
    if (player) {
        player.addEventListener('timeupdate', function () {
            alert('work');
        }, false)
    }
}

must .find video tag again after changes and before call function for ex. in this way:
$( "#button" ).click(function() {
    $('#video').html( $('#newVideo').html());
    initPlayer();
});


text:
Q: Magento2: How to translate language In header.phtml I add new banner:

 x
  BLACK WEEK!: TYLKO TERAZ NAWET DO -63%* NA +150 MAREK PREMIUM!

But now this banner is displayed in Polish language on all stores website. How can I translate this banner for others websites stores?

A: As I said in comment, You need to Add text like:
<?php echo __('your-context'); ?>

After that you need to put translation in CSV file.
For more information about How to add translation You can refer Link


text:
Q: Unable to rotate the labels on x-axis in DevExtreme We are build a SPFx webpart in SharePoint 2016. We are using DevExtreme for displaying bar charts with React. The labels on x-axis are a bit long so not all the labels are displayed. When we try to rotate the labels on x-axis using the below code it throws an error.
<ArgumentAxis>
    <Label overlappingBehavior={'rotate'} rotationAngle={90} ></Label>
</ArgumentAxis>

The error in browser console is as below.
Uncaught (in promise) Error: Minified React error #130; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=130&args[]=undefined&args[]=%20Check%20the%20render%20method%20of%20%60ArgumentAxis%60. for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at r (sp-webpart-workbench-assembly_en-us.js:188)
    at p.i [as _instantiateReactComponent] (sp-webpart-workbench-assembly_en-us.js:174)
    at performInitialMount (sp-webpart-workbench-assembly_en-us.js:174)
    at p.mountComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at Object.mountComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at h.mountChildren (sp-webpart-workbench-assembly_en-us.js:174)
    at h._createInitialChildren (sp-webpart-workbench-assembly_en-us.js:174)
    at h.mountComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at Object.mountComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at performInitialMount (sp-webpart-workbench-assembly_en-us.js:174)
sp-webpart-workbench-assembly_en-us.js:174 Uncaught TypeError: Cannot read property '__reactInternalInstance$9s1g0il1o7' of null
    at Object.u [as getClosestInstanceFromNode] (sp-webpart-workbench-assembly_en-us.js:174)
    at r (sp-webpart-workbench-assembly_en-us.js:174)
    at i (sp-webpart-workbench-assembly_en-us.js:174)
    at r.perform (sp-webpart-workbench-assembly_en-us.js:174)
    at Object.batchedUpdates (sp-webpart-workbench-assembly_en-us.js:174)
    at Object.i [as batchedUpdates] (sp-webpart-workbench-assembly_en-us.js:174)
    at dispatchEvent (sp-webpart-workbench-assembly_en-us.js:174)
localhost:4321/dist/pfizer-sp-tap-web-part.js:96555 Array(4)
localhost:4321/dist/pfizer-sp-tap-web-part.js:96562 Array(18)
localhost:4321/dist/pfizer-sp-tap-web-part.js:96548 Array(36)
sp-webpart-workbench-assembly_en-us.js:174 Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null
    at p._updateRenderedComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at p._performComponentUpdate (sp-webpart-workbench-assembly_en-us.js:174)
    at p.updateComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at p.receiveComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at Object.receiveComponent (sp-webpart-workbench-assembly_en-us.js:174)
    at Object.updateChildren (sp-webpart-workbench-assembly_en-us.js:174)
    at h._reconcilerUpdateChildren (sp-webpart-workbench-assembly_en-us.js:174)
    at h._updateChildren (sp-webpart-workbench-assembly_en-us.js:174)
    at h.updateChildren (sp-webpart-workbench-assembly_en-us.js:174)
    at h._updateDOMChildren (sp-webpart-workbench-assembly_en-us.js:174)
/_layouts/15/WsaUpload.ashx:1 Failed to load resource: the server responded with a status of 403 (Forbidden)
2sp-webpart-workbench-assembly_en-us.js?version=1:174 Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null
    at p._updateRenderedComponent (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at p._performComponentUpdate (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at p.updateComponent (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at p.receiveComponent (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at Object.receiveComponent (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at Object.updateChildren (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at h._reconcilerUpdateChildren (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at h._updateChildren (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at h.updateChildren (sp-webpart-workbench-assembly_en-us.js?version=1:174)
    at h._updateDOMChildren (sp-webpart-workbench-assembly_en-us.js?version=1:174)

The link in the error message shows the below description.

Element type is invalid: expected a string (for built-in components)
  or a class/function (for composite components) but got: undefined.
  Check the render method of ArgumentAxis

What am I doing wrong here?

A: for overlappingBehavior, Accepted Values: 'rotate' | 'stagger' | 'none' | 'hide', in string.


text:
Q: Auto adjust container height to fit content I know that this question has been answered already, however, I tried the solutions I found but it didn't solve my problem. I'm trying to set the container to auto-adjust its height according to the content available.
At the moment, the container doesn't adjust when content is shorter, such as in picture 2:
Picture 1
Picture 2
If I remove height: 100% and replace it with height: auto, the container height will fill all the space available and I won't be able to see scrollbar and submit button:
result with height: auto
How can I dynamically adjust the container?
Here's my code:
<apex:page sidebar="false" showHeader="false" applyHtmlTag="false">
  <html>

  <head>
    <apex:includeLightning />
  </head>

  <body class="slds-scope">
    <style type="text/css">
      body {
        font-family: EF Circular, Helvetica, Open Sans, Arial, sans-serif;
        font-size: 15px !important;
        font-weight: normal;
      }

      .flow {
        width: 700px;
        height: 100%;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0.9;
        overflow: auto;
        -webkit-box-shadow: 5px 5px 16px -6px rgba(0, 0, 0, 0.77);
        box-shadow: 5px 5px 16px -6px rgba(0, 0, 0, 0.77);
      }

      input {
        /*height: 9px !important;*/
        padding: 6px 6px !important;
        margin-bottom: 5px;
        /*display: block !important; */
        font-size: 12px !important;
        line-height: 16px !important;
        color: #191919 !important;
        background-color: #efefef !important;
        border: 1px solid #009ee8 !important;
        border-radius: 4px !important;
        width: 9cm;
      }

      .slds-scope .slds-input {
        background-color: rgb(255, 255, 255);
        border: 1px solid rgb(217, 219, 221);
        border-radius: .25rem;
        width: 4.4cm;
        transition: border .1s linear, background-color .1s linear;
        display: inline-block;
        padding: 0 1rem 0 .75rem;
        line-height: 1.875rem;
        min-height: calc(1.875rem + (1px * 2));
      }

      .slds-scope .slds-input-has-icon_right .slds-input__icon,
      .slds-scope .slds-input-has-icon--right .slds-input__icon {
        right: auto;
      }

      select {
        color: #000;
        height: 0.8cm;
        width: 9cm;
      }
    </style>
    <div id="flowContainer" class="flow" />
    <script>
      var statusChange = function(event) {
        if (event.getParam("status") === "FINISHED") {
          var outputVariables = event.getParam("outputVariables");
          var key;
          for (key in outputVariables) {
            if (outputVariables[key].name === "myOutput") {}
          }
        }
      };
      $Lightning.use("c:DLAflow", function() {
        $Lightning.createComponent("lightning:flow", {
            "onstatuschange": statusChange
          },
          "flowContainer",
          function(component) {
            component.startFlow("DLA_Application_Page");
          }
        );
      }, );
    </script>
  </body>

  </html>
</apex:page>

A: You should use height: fit-content;.

A: Use max-height along with height:auto;:
height: auto;
max-height: 100%;


text:
Q: PHP str_replace to include function/file as part of a Templating system Overview: I'm making a tempting system for my sites, which at the moment is going quite well and it is working how I would expect it to, the only problems arise when I would like something like {PAGE_SIDEBAR} to show the file template/sidebar.php or something similar.
I am using
//loads of other str_replace here
$body = str_replace("{PAGE_SIDEBAR}, include("template/sidebar.php"), $body);
echo $body;

this works, however it includes the file at the start of body, NOT where {PAGE_SIDEBAR} is. Where the tag is, it shows the number 1.
See screenshots for better explanation:
How the rendered template looks before
Using the insert code above
Also, for point of interest, How it looks using file_get_contents() instead of include():  http:// www.jamesmoorhouse.co.uk/stack_overflow/str_replace/file_get_contents_method.png
Ideally  I Am hoping for it to work as it would with the include method, but show up where the file_get_contents method puts it.

A: You have to capture everything that the include spits out using output buffering to be able to use it as a string:
ob_start();
include("template/sidebar.php");
$str_sidebar = ob_get_clean();
$body = str_replace("{PAGE_SIDEBAR}", $str_sidebar, $body);
echo $body;

If there are lots of placeholders that you want to replace, you might want to use a regular-expression based solution with a callback so that you don't have to repeat this code for each. See my answer here for a primer.


text:
Q: Using THREE.js with aurelia-cli, exporting as global Install THREE.js: npm install three
Configuring aurelia.json:
"dependencies": [
      {
        "name": "three",
        "path": "../node_modules/three/build",
        "main": "three.min"
      }

importing in view: import * as THREE from 'three';
Ok so this works and I am able to use three.js, however, I would also like to use some of the plugins. Specifically GPUParticleSystem. Now this plugin depends on a Global THREE object. In a first attempt I added this to aurelia.json
"dependencies": [
          {
            "name": "three",
            "path": "../node_modules/three/build",
            "main": "three.min",
             "exports": "THREE" //this should make the library a global object?
          }

But it doesn't seem to be working? I cannot see the global variable from devTools.

A: One possible way of solving this is to use prepend in aurelia.json:
...
"prepend": [
    "node_modules/three/build/three.min.js",
    "node_modules/three/examples/js/GPUParticleSystem.js"
 ]
...


text:
Q: cannot boot after update I am a beginner user of Ubuntu. I updated it and the following problem occurred while booting.
[328.626105] type=1400 audit(1428046501.300:67): apparmor="STATUS" operation="profile_replace" profile="unconfined" name="/usr/sbin/cupsd" pid=1435 comm=" apparmor_parser"

What should I do? What did I do wrong?

A:
cupsd is the scheduler for the Common UNIX Printing System. It implements a printing system based upon the Internet Printing Protocol, version 1.1. If no options are specified on the command-line then the default configuration file (usually /etc/cups/cupsd.conf) will be used.

It propably has nothing to do with Your hung.
Try to load older kernel (hit and hold Shift - as far as i remember) while system boots. When GRUB menu load, select older kernel and let us know what happens.
If You can load into linux, copy and paste 'older kernel log' - dmesg's from /var/log.


text:
Q: Is there example of scala abstract type usage which is impossible to achieve with generics? There are two possible way to express abstraction over types.
abstract class Buffer {
  type T
  val element: T
}

rather that generics, e.g.
abstract class Buffer[T] {
  val element: T
}

I understand benefits in usability of using different approaches in different contexts.
But I'm interest in examples where it is absolutely impossible to convert Abstract Type version to Generic version.
PS Code snippets are welcome.

A: Another difference: only type parameters can be used as self-types,
abstract class Buffer[T] { self: T =>
  val element: T
}

A: // This is possible
trait M { type TM }
trait P[TP] extends M { type TM = TP }

// This is not
trait P[TP]
trait M extends P[TM] { type TM }

A: Abstract types can be bound to path dependent types which is not possible with type parameters. Thus you can e.g. implement an abstract type with a concrete inner class:
trait A { type T }
class B extends A { class T }

or explicitly bind it to a path dependent type inside the classes scope:
class C { type T = this.type }
class D { object Q; type T = Q.type }


text:
Q: How do I create a guild in Guild Wars 2? I was just wondering how you create a guild in Guild Wars 2?
Beta weekend starts tomorrow and I am going to need to create our guild, but I have not seen anything about how to create one in GW2.
What are the requirements?
Where do I go?
Do I need currency?
Do I need people to sign a charter?
Any other details would be great.

A: Additionally, there was a specific NPC Guild Registrar (He was near the Auction House in Divinty's Reach, not sure about the location in the other cities) that would allow you to create a guild as well. It may be that you need to go talk to him in later versions, but for now, he simply forced you into the same interface as above.

A: You do not need a charter or to go to a special area, though you can create a guild by speaking to a Guild Registrar in a city.
You will need to have 1 silver in order to create a guild. Then all you need to do is open the Guild window (G by default), choose a name (31 character limit) and guild tag (an abbreviation that will show up next to your character name, up to 4 characters), and that's it.
Note that guild members don't even have to have be on the same Home World (server) as you, though you do need to be on the same Home World if you wish to play World vs. World together.
The default maximize size for a guild is 50 members. In order to increase this size, you will need to speak to a Guild Registrar. The following table from the official wiki lists the costs and upgrades as follows:
Tier   Membership Cap    Cost
 1          50         1 Silver
 2          100        1 Silver
 3          200       10 Silver
 4          300        1 Gold
 5          400        1 Gold
 6          500        2 Gold


text:
Q: Ubuntu Network configuration setting and Windows Suppose I have connected to a Network having Static IP after that connected to a Network having DHCP, When I go back to previos network having static one I find lost my setting (IPV4). Probably Windows has one place to set Network configuration.But in ubunto/Linux there are different static IP configuration corresponding to different Networks.How can we do this fow windows?or is there any setting availble for windows

A: If you are asking how to change the static IP of your windows computer:
Go to the Network and Sharing Center in the Control panel
Click change adapter settings
Right-Click on Local Area Connection and select properties
Click Internet Protocol Version 4 (TCP/IPv4) then properties
Select the radio button for Use the following IP address
Enter your IP address
Click OK
If this fails then return to Obtain IP automatically


text:
Q: How can I search for user_name and password in table contains MILLIONS OF records as fast as possible? Hi there
There is a question I was not lucky to find a solution till now, What technique Facebook use to match username and password in millions of record in few seconds or less, I need a simple example for this case. In my work users less than 300,000 records so using LINEAR search not a big problem but what I have to do if users become millions???


text:
Q: Function returns only one column when return type is record type postgres I have a function that has the return type of record.
Below is the function am using, basically what the function does is , it takes in input paramter and queries the database to return the columns:
drop function if exists test_proc(sr_number1 bigint);
create or replace function test_proc(sr_number1 bigint) RETURNS record /*SETOF tbl*/ AS $$

declare
i integer default 0;
record_type record;
begin
select sr_num,product_number,phone,addr into record_type from my_table where sr_num=sr_number1;
return record_type;
end
$$ LANGUAGE plpgsql;

Unfortunately, when I execute the function as
select test_proc(12345);  I get the result as a comma separated list in just one column like (sr_num,product_number,phone,addr). But what I was hoping to have it return was a table row with the column values and their respective column names.
I also tried executing the function as
select * from test_proc(12345); but get the following error

ERROR:  a column definition list is required for functions returning "record"

A: When querying a function that returns a record you must specify the type of record you want to get in the result
 select * from test_proc(12345) f(b bigint, t text);

This should work.
A better solution is to declare the type of record in the function
 CREATE OR REPLACE FUNCTION test_proc(sr_number1 bigint)
 RETURNS TABLE(b bigint, t text) AS $$  $$


text:
Q: Autodesk-forge's "Visual Cluster" extension on NWD files I'm trying the "Visual Cluster" extension in a forge-based app. It seems to be working fine with RVT files but it's not clustering at all for NWC/NWD files.
Do Autodesk-Forge support visual clusters on NWC/NWD files?
You can try uploading NWC/NWD files here https://forge-extensions.autodesk.io/ and enable VisualClusters extension.

A: The Autodesk.VisualClusters extension uses attributeName of the object properties for cataloging, and its default value is Revit Category.
If you want to change the default value, you need to pass an option called attribName to change it. For example, we changed it to use Material for cataloging.
Note. By default, it will search leaf nodes' properties. If you want to group by parent nodes, you need to set the option searchAncestors to true.
viewer.loadExtension('Autodesk.VisualClusters', { attribName: 'Material', searchAncestors: true });

Here is an example for NWD/NWC files (tests with v7.58):
viewer.loadExtension('Autodesk.VisualClusters', { attribName: 'LcRevitMaterialProperties:LcOaSceneBaseUserName' });

A: Thank you this is just what I needed.
But it needs to be clarified that 'attribName' is NOT available via postman...It is only available via code:

var selection = viewer.getSelection();
if (selection.length == 0) { return;
}

viewer.getProperties(selection[0], function (result) {
  const props = result.properties;

  var attribNameArray = [];

  for (let i = 0; i < props.length; i++) {
    const property = props[i];
    attribNameArray.push(property.attributeName);
  }
  //turn array into string with new lines
  var attribNameString = attribNameArray.join('\n');
  alert(attribNameString);
});


text:
Q: Salvar o total de linhas de um SELECT com WHERE em uma variável Preciso desenvolver um código onde o total de linha de um SELECT seja armazenado em uma variável. Escrevi o código abaixo, mas quando utilizo o WHERE retorna um erro "Notice: Trying to get property of non-object in".
É possível fazer um SELECT utilizando um WHERE e salvar o total de registros localizados em uma váriável com o formato "0000"?
include "conecta_mysql.inc";

$escritorio = $_POST["n_escritorio"];

$resultado = $mysqli->query("SELECT * FROM registros WHERE escritorio=$escritorio");
$linhas = $resultado->num_rows;

$mysqli->close();

A: Obrigado a todos pela a ajuda. Uma pessoa me ajudou com a seguinte solução:
$escritorio = $_POST["n_escritorio"];

echo "$escritorio<br>";

$resultado = $mysqli->prepare("SELECT * FROM registros WHERE escritorio = '".utf8_decode($escritorio)."'");
$resultado->execute();
$resultado->store_result();

$linhas = $resultado->num_rows;
echo "total: $linhas";

$mysqli->close();


text:
Q: Error: Unclosed quotation mark after WHILE (@7DaysEarlierPartitionIntegerId <= @CurrentPartitionIntegerId)
    BEGIN
        Set @7DaysEarlierPartitionId
            = CAST(@7DaysEarlierPartitionIntegerId AS char)
        set @sqlCommand
            = 'Select * from '
              + quotename(@RequestUsage_Partition + @7DaysEarlierPartitionId)
              + 'where UserLogin like''r2\rohit.kharade'
        exec(@sqlCommand)
        set @7DaysEarlierPartitionIntegerId
            = @7DaysEarlierPartitionIntegerId + 1
    END

I get the error:

Unclosed quotation mark after the character string 'r2\rohit.kh'.

How to execute the exec command with UserLogin =%r2\rohit.kharade%

A: You're missing the end quote, this should get you there.
WHILE (@7DaysEarlierPartitionIntegerId <= @CurrentPartitionIntegerId)
    BEGIN
        Set @7DaysEarlierPartitionId
            = CAST(@7DaysEarlierPartitionIntegerId AS char)
        set @sqlCommand
            = 'Select * from '
              + quotename(@RequestUsage_Partition + @7DaysEarlierPartitionId)
              + 'where UserLogin like ''r2\rohit.kharade'''
        exec(@sqlCommand)
        set @7DaysEarlierPartitionIntegerId
            = @7DaysEarlierPartitionIntegerId + 1
    END

I generally like to use CHAR(39) in place of multiple quotes, just to make code more readable
WHILE (@7DaysEarlierPartitionIntegerId <= @CurrentPartitionIntegerId)
    BEGIN
        Set @7DaysEarlierPartitionId
            = CAST(@7DaysEarlierPartitionIntegerId AS char)
        set @sqlCommand
            = 'Select * from '
              + quotename(@RequestUsage_Partition + @7DaysEarlierPartitionId)
              + 'where UserLogin like ' + CHAR(39) + 'r2\rohit.kharade' + CHAR(39)
        exec(@sqlCommand)
        set @7DaysEarlierPartitionIntegerId
            = @7DaysEarlierPartitionIntegerId + 1
    END

Bonus thought, just as another, more readable version, you could also QUOTENAME
WHILE (@7DaysEarlierPartitionIntegerId <= @CurrentPartitionIntegerId)
    BEGIN
        Set @7DaysEarlierPartitionId
            = CAST(@7DaysEarlierPartitionIntegerId AS char)
        set @sqlCommand
            = 'Select * from '
              + quotename(@RequestUsage_Partition + @7DaysEarlierPartitionId)
              + ' where UserLogin like ' + QUOTENAME('r2\rohit.kharade', CHAR(39))
        exec(@sqlCommand)
        set @7DaysEarlierPartitionIntegerId
            = @7DaysEarlierPartitionIntegerId + 1
    END

A: As an alternative, you could parameterize the argument so that you don't have to deal with quotes at all.
DECLARE @likeArg varchar(255) = 'r2\rohit.kharade';

WHILE (@7DaysEarlierPartitionIntegerId <= @CurrentPartitionIntegerId)
BEGIN
    Set @7DaysEarlierPartitionId
        = CAST(@7DaysEarlierPartitionIntegerId AS varchar(11)) --*
    set @sqlCommand = N'Select <output columns> from '
          + quotename(@RequestUsage_Partition + @7DaysEarlierPartitionId)
          + N' where UserLogin like @likeArg ORDER BY <sort columns>;'
    exec sys.sp_executesql @sqlCommand, N'@likeArg varchar(255)', @likeArg;
    set @7DaysEarlierPartitionIntegerId += 1;
END

* Also, don't use char/varchar etc. without length.


text:
Q: Getting charts to start at the beginning of the window I am trying to plot the top 20 coins on one chart each with their own line. I have them showing but via their prices, they are all over the place and impossible to see. How can I get all of their charts to start on the left of my chart?
//@version=3
study("Top20Plotted", precision=1, overlay=true)

coinPrice = security(coin, period, close);

ethusdt  = security("COINBASE:ETHUSD", period, close)
xrpusdt  = security("Poloniex:XRPUSDT", period, close)
ltcusdt  = security("COINBASE:LTCUSD", period, close)
bchusd   = security("COINBASE:BCHUSD", period, close)
eosusdt  = security("Bitfinex:EOSUSD", period, close)
bnbusdt  = security("BINANCE:BNBUSDT", period, close)
xlmusdt  = security("BINANCE:BNBUSDT", period, close)
trxusdt  = security("BINANCE:TRXUSDT", period, close)
adausdt  = security("BINANCE:ADAUSDT", period, close)
xmrusdt  = security("BINANCE:XMRUSDT", period, close)
dashusdt = security("BITFINEX:DASHUSD", period, close)
atomusdt = security("BINANCE:ATOMUSDT", period, close)
linkusdt = security("BINANCE:LINKUSDT", period, close)
iotausdt = security("BINANCE:IOTAUSDT", period, close)
neousdt  = security("BINANCE:NEOUSDT", period, close)
etcusdt  = security("BINANCE:ETCUSDT", period, close)
xtzusdt  = security("BINANCE:XTZUSDT", period, close)

plot(ethusdt, color=aqua, style=line, title="ETH")
plot(xrpusdt, color=blue, style=line, title="XRP")
plot(ltcusdt, color=fuchsia, style=line, title="LTC")
plot(bchusd, color=gray, style=line, title="BCH")
plot(eosusdt, color=green, style=line, title="EOS")
plot(bnbusdt, color=lime, style=line, ttitle="BNB")
plot(xlmusdt, color=maroon, style=line, ttitle="xlm")
plot(trxusdt, color=navy, style=line, title="TRX")
plot(adausdt, color=olive, style=line, title="ADA")
plot(linkusdt, color=orange, style=line, title="LINK")
plot(iotausdt, color=purple, style=line, title="IOTA")
plot(neousdt, color=red, style=line, ttitle="NEO")
plot(etcusdt, color=silver, style=line, title="ETC")
plot(xtzusdt, color=teal, style=line, title="XTZ")


text:
Q: Apex chart stretch full size Having a problem with apex-charts where it wont stretch full size. How can I make the graph only fit into its parent container.
Here is a inspect of the gap issues, as you can see the inner chart element isn't correctly spaced to its corresponding parents:

Here is the current code:
import Chart from "react-apexcharts";

const SimpleChart = () => {
    const data = {
        series: [{
          name: 'series1',
          data: [31, 40, 28, 51, 42, 109, 100]
        }],
        options: {
          chart: {
            type: 'area',
            toolbar: { show: false },
          },
          dataLabels: {
            enabled: false
          },
          legend: {
            show: false
          },
          stroke: {
            curve: 'smooth'
          },
          grid: { show: false },
          xaxis: {
            labels: { show: false },
            axisBorder: { show: false },
            axisTicks: { show: false },
            type: 'datetime',
            categories: ["2018-09-19T00:00:00.000Z", "2018-09-19T01:30:00.000Z", "2018-09-19T02:30:00.000Z", "2018-09-19T03:30:00.000Z", "2018-09-19T04:30:00.000Z", "2018-09-19T05:30:00.000Z", "2018-09-19T06:30:00.000Z"]
          },
          yaxis: {
            labels: { show: false },
          },
          tooltip: {
            enabled: false
          },
        },
    };

    return (
        <Chart
            options={data.options}
            series={data.series}
            width="150"
            type="area"
        />
    )
}

export default SimpleChart```

A: Enable the sparkline option
chart: {
  sparkline: {
    enabled: true
  }
},


text:
Q: AVDs created with avdmanager no longer launch due to missing setting After running sdkmanager --update, I can no longer successfully launch AVDs created using avdmanager with the following images:

*

*system-images;android-27;google_apis;x86

*system-images;android-26;google_apis;x86
I can, however, use the system-images;android-25;google_apis;x86 image. Alternatively, if created using Android Studio, an emulator created with the aforementioned images will work - every time.
When creating using avdmanager, I am running: avdmanager create avd -n TEST_1234 -k 'system-images;android-27;google_apis;x86' -d 'Nexus One' -f
I have tried to run it without specifying a device, and also with the -c option to specify an initial sdcard size, but no combination is working past the issue.
When trying to launch one of these AVDs with the emulator, it seems to get stuck in a loop, repeatedly outputting the below:
emulator: onGuestSendCommand: [0x7f0b315d2730] Adb connected, start proxing data
emulator: onGuestClose: [0x7f0b315d2730] Adb closed by guest
emulator: onGuestClose: [0x7f0b317a33e0] Adb closed by guest
emulator: onGuestSendCommand: [0x7f0b29741ac0] Adb connected, start proxing data
emulator: onGuestClose: [0x7f0b29741ac0] Adb closed by guest
emulator: onGuestClose: [0x7f0b2b8a3780] Adb closed by guest
emulator: onGuestSendCommand: [0x7f0b301518a0] Adb connected, start proxing data
emulator: onGuestClose: [0x7f0b301518a0] Adb closed by guest
emulator: onGuestClose: [0x7f0b3121f540] Adb closed by guest
emulator: onGuestSendCommand: [0x7f0b30d3a700] Adb connected, start proxing data
emulator: onGuestClose: [0x7f0b30d3a700] Adb closed by guest
emulator: onGuestClose: [0x7f0b3052cbc0] Adb closed by guest

Likewise, if I launch the AVD manager in Android Studio after creating an AVD using the terminal avdmanager, it will not allow me to launch them (no error messages, just does not respond when pressing the play button).
Should I choose to open the "Edit Device" window, within Android Studio, making no changes to it and clicking the save button will then allow me to launch it.
Doing this makes changes to the AVD's configuration file, which I believe is responsible for the launch working.
When creating using avdmanager, the config.ini file looks like this:
PlayStore.enabled=false
abi.type=x86
avd.ini.encoding=UTF-8
hw.accelerometer=yes
hw.audioInput=yes
hw.battery=yes
hw.cpu.arch=x86
hw.dPad=no
hw.device.hash2=MD5:0250c2773d1dd25bb2b12d9502c789f7
hw.device.manufacturer=Google
hw.device.name=Nexus One
hw.gps=yes
hw.lcd.density=240
hw.lcd.height=800
hw.lcd.width=480
hw.mainKeys=yes
hw.sdCard=yes
hw.sensors.orientation=no
hw.sensors.proximity=yes
hw.trackBall=yes
image.sysdir.1=system-images/android-27/google_apis/x86/
tag.display=Google APIs
tag.id=google_apis

After editing in Android Studio, or when creating via Android Studio, it will look like this:
AvdId=TEST_1234
PlayStore.enabled=false
abi.type=x86
avd.ini.displayname=TEST 1234
avd.ini.encoding=UTF-8
disk.dataPartition.size=800M
fastboot.forceColdBoot=no
hw.accelerometer=yes
hw.arc=false
hw.audioInput=yes
hw.battery=yes
hw.camera.back=none
hw.camera.front=none
hw.cpu.arch=x86
hw.dPad=no
hw.device.hash2=MD5:0250c2773d1dd25bb2b12d9502c789f7
hw.device.manufacturer=Google
hw.device.name=Nexus One
hw.gps=yes
hw.gpu.enabled=yes
hw.gpu.mode=guest
hw.initialOrientation=Portrait
hw.keyboard=no
hw.lcd.density=240
hw.lcd.height=800
hw.lcd.width=480
hw.mainKeys=yes
hw.ramSize=512
hw.sdCard=yes
hw.sensors.orientation=no
hw.sensors.proximity=yes
hw.trackBall=yes
image.sysdir.1=system-images/android-27/google_apis/x86/
runtime.network.latency=none
runtime.network.speed=full
sdcard.size=100M
showDeviceFrame=no
skin.dynamic=yes
skin.name=480x800
skin.path=_no_skin
skin.path.backup=_no_skin
tag.display=Google APIs
tag.id=google_apis
vm.heapSize=16

After working my way through the differences in these settings, I found that if I create a new AVD using avdmanager, but then add the following line to the newly created config file, it will successfully launch:
disk.dataPartition.size=800M

So, it seems as if this is the core setting that Android Studio is adding which makes the AVDs usable from Android Studio, but not avdmanager.
Does anyone know how one can force avdmanager to set this? I see no option for it, but without setting this, it's not possible to create AVDs using avdmanager on its own.

A: Problem solved - having discovered the troublesome setting, I've managed to find an argument that can be used when launching emulator, which allows this to be specified: -partition-size
Launching an emulator using emulator -avd TEST_1234 -partition-size 800 -verbose will work around the problem and will successfully launch emulators created using the newer images.


text:
Q: scroll event not firing on div element in IE I have tried everything I can think of to get this event to trigger when scrolling on the div tag. I made sure that it was actually reaching this code and it does. It never triggers when scrolling though. I also tried using .scroll(...) and .bind('scroll'...) Any thoughts on what the issue is?
$('.ScrollIEContainer').scroll(function ()
{
   var scrollPos = $(this).scrollTop();
   if (scrollPos != null && scrollPos != undefined)
   {
      $(this).contents('table.GridView').children('thead').children('tr').css({ 'top': scrollPos + 'px' });
   }
});

The goal here is to update the top position of the header in my grid view to implement fixed header scrolling.
UPDATE:
I have been unable to debug any of this code with the exception of alert statements for some inexplicable reason but I was able to debug and use the watch window to check on my selector elements by inserting a a line of code right before it that would result in a Null Reference exception (WTF). Anyways, I looked at the dom inside my element and the onscroll event is null event after  the code above is executed.

A: jQuery's live doesn't support scroll
Is your element dynamically added?
Edited:
Change $(this).topScroll() to $(this).scrollTop()

A: Here is a working example with a div.  Notice that the headers position is relative to its parent.  Your problem may simply lie with the thead not responding to this positioning though.

Header

0

1

2

3

4

5

6


text:
Q: How to make a large list in R without using a loop I have around 500 dataframes with two columns and a varying number of rows (from 10 till 30) in R. I also have a character vector containing the names for the dataframes. I now wish to bundle all these dataframes into a single list so I can refer to these list elements using the dataframe names.
I was thinking to use a loop to loop through the dataframes and add them to the list in each step but I couldn't pull it of.

A: The following works:
df_list = mget(df_names)

However, the real solution is to not have 500 data.frames in your workspace to begin with: either load/create them immediately inside a list, or have your data in such a format that it's collated into one big data.frame.
Think of variables as things you have to keep in your head at the same time: if there are too many to remember, you have too many. Because how else can you reason about the state of your program, i.e. about its semantics and correctness?

A: Check this:
df_names <- c(    ) # yours dataframes names character vector
lst <- list()

for (i in df_names) {
  lst[i] <- list(get(i))
}


text:
Q: How does HTTP POST method transfer data ? I know what is the HTTP header and how the HTTP data format , I also know how to make a HTTP post from Java ,
like
StringBuffer result = new StringBuffer();
PrintWriter out = null;
BufferedReader in = null;
StringBuffer result = new StringBuffer();
try {
    URL realUrl = new URL("http://somesite/somepage.htm");
    URLConnection conn = realUrl.openConnection();
    conn.setRequestProperty("accept", "*/*");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
           "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    out = new PrintWriter(conn.getOutputStream());
    out.print(param);
    out.flush();
    in = new BufferedReader(
              new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
         result.append(line);
    }
} catch (Exception e) {
    e.printStackTrace();
}

I can use some code like this write stream to web server , and read stream also .
Here is my question .
What is the HTTP POST method really do , I mean how does the client communicate to web server ?
What will happen if the web server only read the HTTP POST header and don't read the stream from client ?
Does the stream will stuck in somewhere ?
Thanks .


text:
Q: How can I count the rows with data in an Excel sheet? I am trying to count the number of rows in a spreadsheet which contain at least one non-blank value over a few columns: i.e.
row 1 has a text value in column A
row 2 has a text value in column B
row 3 has a text value in column C
row 4 has no values in A, B or C

The formula would equate to 3, because rows 1, 2, & 3 have a text value in at least one column. Similarly if row 1 had a text value in each column (A, B, & C) this would be counted as 1.

A: With formulas, what you can do is:

*

*in a new column (say col D - cell D2), add =COUNTA(A2:C2)

*drag this formula till the end of your data (say cell D4 in our example)

*add a last formula to sum it up (e.g in cell D5): =SUM(D2:D4)

A: If you want a simple one liner that will do it all for you (assuming by no value you mean a blank cell):
=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, "")

If by no value you mean the cell contains a 0
=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, 0)

The formula works by first summing up all the rows that are in columns A, B, and C (if you need to count more rows, just increase the columns in the range. E.g. ROWS(A:A) + ROWS(B:B) + ROWS(C:C) + ROWS(D:D) + ... + ROWS(Z:Z)).
Then the formula counts the number of values in the same range that are blank (or 0 in the second example).
Last, the formula subtracts the total number of cells with no value from the total number of rows. This leaves you with the number of cells in each row that contain a value

A: If you don't mind VBA, here is a function that will do it for you. Your call would be something like:
=CountRows(1:10)

Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.

A: Try this scenario:
Array = A1:C7. A1-A3 have values, B2-B6 have value and C1, C3 and C6 have values.
To get a count of the number of rows add a column D (you can hide it after formulas are set up) and in D1 put formula =If(Sum(A1:C1)>0,1,0). Copy the formula from D1 through D7 (for others searching who are not excel literate, the numbers in the sum formula will change to the row you are on and this is fine).
Now in C8 make a sum formula that adds up the D column and the answer should be 6. For visually pleasing purposes hide column D.

A: You should use the sumif function in Excel:
=SUMIF(A5:C10;"Text_to_find";C5:C10)
This function takes a range like this square A5:C10 then you have some text to find this text can be in A or B then it will add the number from the C-row.

A: This is what I finally came up with, which works great!
{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}
Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.