Q: Extract jsonb in Postgresql - dictionary and array structure in same jsonb field I am using postgresql and I have this table on dataset, that some columns are jsonb.
SELECT
external_id as cod,
title as name,
objectives
FROM table

So, the result for "objectives" column is like that:
{"blocks":
    [
        {"key":"dek2k",
        "text":"Objetivo Geral",
        "type":"unstyled",
        "depth":0,
        "inlineStyleRanges":
            [
            {"offset":0,"length":14,"style":"fontsize-12pt"},
            {"offset":0,"length":14,"style":"fontfamily-Arial"},
            {"offset":0,"length":14,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{"text-align":"start"}},
        {"key":"ct1vn",
        "text":"Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design,",
        "type":"unstyled","depth":0,"inlineStyleRanges":
            [
            {"offset":0,"length":216,"style":"color-rgb(0,0,0)"},
            {"offset":0,"length":216,"style":"fontsize-12pt"},
            {"offset":0,"length":216,"style":"fontfamily-Arial"},
            {"offset":0,"length":216,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{}},
        {"key":"8jshq",
        "text":"","type":"unstyled","depth":0,
        "inlineStyleRanges":[],
        "entityRanges":[],"data":{}},
        {"key":"avq4h",
        "text":"tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.",
        "type":"unstyled",
        "depth":0,
        "inlineStyleRanges":
            [
            {"offset":0,"length":23,"style":"color-rgb(0,0,0)"},
            {"offset":0,"length":23,"style":"fontsize-12pt"},
            {"offset":0,"length":23,"style":"fontfamily-Arial"},
            {"offset":0,"length":23,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{}}
    ],
"entityMap":{}
}

I want to get in result only what is in "text". Sometimes it has just one "text" value, sometimes it has up to 15 or more.
What i need is a result like this for all rows in table:
 cod      |      name      | objectives
----------+-----------------+----------
 1        | A              | Objetivo Geral Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design, tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.

Any clue?

A: The json functions with string_agg() achieve what you want.
Using WITH ORDINALITY guarantees correct ordering of the text elements.
SELECT t.external_id as cod,
       t.title as name,
       string_agg(a.block->>'text', ' ' ORDER BY rn) as objectives
  FROM "table" t
       CROSS JOIN LATERAL jsonb_array_elements(t.objectives->'blocks')
                           WITH ORDINALITY as a(block, rn)
 GROUP BY t.external_id, t.title;


Q: How to display template parameter type name in natvis? I want to extend a natvis visualizer for a (C++) template class. Is there a way to display a type name of the first template parameter?
It would be great for boost::variant<int,bool> v; v=1; to display 1 (int) or something like that

A: In my opinion the best solution is to use the standard C++17 std::variant. MSVC comes with natvis for this type so that you have a pretty view of the value that is stored.
Here is some natvis code that I just wrote and tested:
  <Type Name="boost::variant<*>">
    <DisplayString Condition="which_==0">{*($T1*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==1" Optional="true">{*($T2*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==2" Optional="true">{*($T3*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==3" Optional="true">{*($T4*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==4" Optional="true">{*($T5*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==5" Optional="true">{*($T6*)storage_.data_.buf}</DisplayString>
    <DisplayString Condition="which_==6" Optional="true">{*($T7*)storage_.data_.buf}</DisplayString>
    <Expand>
      <Item Name="which">which_</Item>
      <Item Name="value0" Condition="which_==0">*($T1*)storage_.data_.buf</Item>
      <Item Name="value1" Condition="which_==1" Optional="true">*($T2*)storage_.data_.buf</Item>
      <Item Name="value2" Condition="which_==2" Optional="true">*($T3*)storage_.data_.buf</Item>
      <Item Name="value3" Condition="which_==3" Optional="true">*($T4*)storage_.data_.buf</Item>
      <Item Name="value4" Condition="which_==4" Optional="true">*($T5*)storage_.data_.buf</Item>
      <Item Name="value5" Condition="which_==5" Optional="true">*($T6*)storage_.data_.buf</Item>
      <Item Name="value6" Condition="which_==6" Optional="true">*($T7*)storage_.data_.buf</Item>
    </Expand>
  </Type>

It works for any boost::variant<type_or_types>.
It has a DisplayString that takes the variant's member storage_ and extracts the buffer buf. The address of the buffer is then cast to a pointer to the type that was provided to std::variant. As you can see in my code which_ is zero based, whereas the template parameters are 1 based. I am not interested in the address but in the value, so I am adding a * in front of the value.
I also added an Expand section so that you can expand a variant. This allows me to show which_ and to show the value again - this time the column Type will show the correct type as you can see in my screen capture (for the variant itself the type is displayed as boost::variant<…> and I do not know how to add the type name into the DisplayString).
Please note that the Optional="true" are required because otherwise we would get a parsing error in cases where less than 7 type parameters are passed (as in boost::variant<int,bool>and natvis does not have a $T7.
If you need more template parameters, you can easily extend the code.
If you want the DisplayString to also shows the index (as an explicit value or coded into the name value…), you can easily change it accordingly as in
<DisplayString Condition="which_==0">{{which={which_} value0={*($T1*)storage_.data_.buf}}}</DisplayString>

Last but not least please note that I did not test very much and that I did not look into boost::variant into detail. I saw that storage_ has members suggesting that there is some alignment in place. So it might not be sufficient to just use storage_.data_.buf. It might be necessary to adjust the pointer depending on the alignment being used.

A: If you want to show $T1 as a string, wrap it with ". For example, for
<DisplayString>{*($T1*)storage_.data_.buf} {"$T1"}</DisplayString>
in your case you will see 1 "int"


Q: What should I use in ANSI C to create linked lists? In Java I used LinkedList<T>.
Is there any standard, or maybe some other libraries, to create LinkedLists in C?

A: No, C doesn't have anything like that. If you can use C++, there's std::list.
You'll have to write the structure yourself in C.

A: As others have said, there is no standard library support for linked lists in C.  That means you either get to roll your own (like most people have done at one or more times in their C coding career), or you look at other libraries for support.
For most uses, you will find that an 'intrusive' implementation is appropriate.  You modify your existing structure to include a pointer to the next item in the list (and, if you're doing a doubly linked list, the previous item).
typedef struct TheStruct TheStruct;

struct TheStruct
{
    ...the real data...
    TheStruct *next;
  //TheStruct *prev;
};

Your list now consists of a simple pointer to the head item:
TheStruct *head = 0;

TheStruct *allocated_node = new_TheStruct(value1, value2, ...);

assert(allocated_node->next == 0);

// Insert new allocated node at head of list
allocated_node->next;
head = allocated_node;

You have to worry about threading issues if you've got threads access the same list, and so on and so forth.
Because this code is so simple, this is how it is most frequently handled.  Deleting a node from a list is trickier, but you can write a function to do it.
People have dressed up this basic scheme with macros of varying degrees of complexity so that the code manipulating different types of lists can use the same macros.  The Linux kernel uses a macro-based set of linked lists for managing its linked list data structures.
The alternative to the 'intrusive' implementation (which is so-called because it requires a change to the structure to include the list pointers) is to have some generic list mechanism:
typedef struct GenericList GenericList;
struct GenericList
{
    void        *data;
    GenericList *next;
  //GenericList *prev;
};

Now you have the ability to put (pointers to) unmodified structures into the list.  You lose some type safety; there is nothing to stop you adding random different structure types to a list that should be homogeneous.  You also have to allocate memory for the GenericList structures separately from the pointed at data.

*

*One advantage of this is that a single data item can be on multiple separate lists simultaneously. * One disadvantage of this is that a single data item can accidentally be on multiple lists, or multiple times in a single list, simultaneously.

You also have to make sure you understand the ownership properties for the data, so that the data is released properly (not leaked, not multiply-freed, not accessed after being freed).  Managing the memory for the list itself is child's play by comparison.
With the GenericList mechanism, you will likely have a library of functions that manage the list operations for you.  Again, searching should reveal implementations of such lists.

A: C does not (as yet) provide any standard container structures.  You'll have to roll your own.

A: It doesn't exist by default, but it can be made quite easily.
Basically a linked list is a header pointer that points to 1st element, and an ending file pointing to null.
The elements are actually nodes, containing the object and a pointer to the next node.
So making a basic one is quite easy, though in C it might be painful as no classes, only structs.

A: There are no Lists in the standard C library. A very good C library you can use is PBL - The Program Base Library here. Its interface is Java like. You can download it from here


Q: Domino Rest service API to get Tentative status in Ateendee's calendar Is there any way to find the Tentative status of my meetings as an Attendee from the response of "GET /{db}/api/calendar/events"  or  "GET /{db}/api/calendar/events/meetingId" ?
Some documents say x-lotus-noticetype property with "P" indicates a tentative acceptance. But I am getting a status "A" instead, after tentative accept meeting in both 8.5.3 and 9.0.1 versions of domino.
Use case: To show my(Attendee's) tentatively accepted meetings in Yellow color , in my Web App's calendar.

A: You should look at the JSON transparency property.  When an attendee tentatively accepts a meeting, the property will look like this:
  "transparency": "transparent"

On the other hand, when an attendee accepts a meeting, the property will look like this:
  "transparency": "opaque"

In other words, a transparent event doesn't block busy time; an opaque event does block busy time.  This terminology comes from the iCalendar specification.  See the TRANSP property in iCalendar.


Q: Exchange Information between two windows Im not sure how to explain my problem in short at the title, so forgive me for this. Lets say I opened my website in some random page, and I have a register button. Really simple, but in my case I require the registration form to appear in other tab(or window). Not "RederPartial", nor popup window of some kind, legit new tab. The problem is, I want to be able do detect, from that random page of mine, when the registration completed (ie a new user has been created). How can I pass this information? without reloading the first page

A: There are various ways to make two windows talk with each other (through server, with cookies, using FileSystem API  or Local Storage.
Locale Storage is by far the easiest way to talk between two windows who come from the same domain, but it is not supported in older browsers. Since you need to contact the server anyway to find out when someone has registered, I recommend using the server (Ajax//web sockets).
Here's a somewhat simple AJAX solution which you could use in your random page:
(function(){
    var formOpened = false;
    var registered = false;

    //Change to whatever interaction is needed to open the form
    $('#registerbutton').on('click', function(){
        if (!formOpened){
            formOpened = true;

            //Will try to poll the server every 3 seconds
            (function pollServer(){
                $.ajax({
                    url: "/ajax/pollregistered",
                    type: "GET",
                    success: function(data) {
                        if (data.registered){
                            registered = true;
                            //do other stuff here that is needed after registration
                        }
                    },
                    dataType: "json",
                    complete: setTimeout(function() {if (!registered) pollServer();}, 3000),
                    //will timeout if request takes longer than 2 seconds
                    timeout: 2000,
                })
            })();

            //opens the new tab
            var win = window.open('/registrationform', '_blank');
            win.focus();
        }
    });
})();

You can then use the session key of the visitor in  the  '/ajax/pollregistered' action to write your backend code to check if and when this visitor registered as user to your site.
If you don't mind using the local storage, you could poll the storage instead of the server and have the registration page write to local storage upon registration. This is less stressing for your server, but might not work for users with ancient browsers.
Also worth nothing that this method of opening a new tab is not completely reliable. Technically there is not a sure shot way of opening a new tab with javascript. It depends on browser and the preferences of the user. Opening a new tab might get blocked for users who are using anti popup plugins.
That being said, I strongly recommend revising your design and try finding a way to work with just one window instead. It's probably better for both yourself and your users.


Q: Adjust border to content I have a simple grid with 2 columns with border and two columns Fiddle
The problem is I want to adjust the border to the content and the content has left padding, so I want to remove that free space.
I tried to use box-sizing: border-box; but it causes no effect

HTML:

    Annual Test Test

    80

SCSS:
.totalContainer {
  display: grid;
  grid-template-columns: 2fr 1fr;
  margin-top: 30px;
  border: 1px solid rgba(72, 82, 93, 0.8);
  border-radius: 12px;
  box-sizing: border-box;

  &__row {
    background-color: #E5E5E5;
  }

  &__space {
    padding: 10px 0 10px 140px;
  }

  &__text {
    font-size: 13px;
  }

  &__result {
    text-align: right;
  }
}

A: Using margin-left instead of padding:
 &__space {
    padding: 10px 0 10px 10px;
    margin-left: 140px;
  }

A: I think you are missing the big picture here.

Making up a block box in CSS we have the:
Content box: The area where your content is displayed, which can be
sized using properties like width and height. Padding box: The padding
sits around the content as white space; its size can be controlled
using padding and related properties.
Border box: The border box wraps
the content and any padding. Its size and style can be controlled
using border and related properties.
Margin box: The margin is the
outermost layer, wrapping the content, padding, and border as
whitespace between this box and other elements. Its size can be
controlled using margin and related properties.

So in short the border includes the padding (it wraps the content as well as the padding), while the margin lays outside of it (pushing the content with border and padding included). I would recomand to check the box model docs.


Q: middleman Invalid byte sequence in UTF-8 I want to edit a webpage for someone who is using middleman.  Anytime I run middleman in the console I get this error:
Traceback (most recent call last):
    68: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `<main>'
    67: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `eval'
    66: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/middleman:23:in `<main>'
    65: from /Users/apple/.rvm/gems/ruby-2.6.0/bin/middleman:23:in `load'
    64: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-cli-4.3.3/bin/middleman:49:in `<top (required)>'
    63: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-cli-4.3.3/bin/middleman:49:in `new'
    62: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/application.rb:283:in `initialize'
    61: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:28:in `block in install_methods!'
    60: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    59: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    58: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    57: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `execute'
    56: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
    55: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
    54: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
    53: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `block in execute'
    52: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `instance_exec'
    51: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    50: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    49: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    48: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/file_watcher.rb:47:in `before_configuration'
    47: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    46: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    45: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    44: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `poll_once!'
    43: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `reduce'
    42: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `each'
    41: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:241:in `block in poll_once!'
    40: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    39: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    38: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    37: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources/source_watcher.rb:212:in `poll_once!'
    36: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    35: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    34: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    33: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources/source_watcher.rb:288:in `update'
    32: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:28:in `block in install_methods!'
    31: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    30: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    29: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    28: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `execute'
    27: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
    26: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
    25: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
    24: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `block in execute'
    23: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/callback_manager.rb:57:in `instance_exec'
    22: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    21: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    20: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    19: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:351:in `did_change'
    18: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
    17: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
    16: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
    15: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:361:in `run_callbacks'
    14: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:431:in `each'
    13: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `traverse_depth_first'
    12: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/hamster-3.0.0/lib/hamster/vector.rb:1316:in `each'
    11: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/sources.rb:368:in `block in run_callbacks'
    10: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
     9: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
     8: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
     7: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:89:in `update_files'
     6: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:89:in `each'
     5: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_handler.rb:138:in `block in redefine_method'
     4: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/call_with.rb:76:in `call_with'
     3: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/contracts-0.13.0/lib/contracts/method_reference.rb:43:in `send_to'
     2: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/core_extensions/data.rb:108:in `touch_file'
     1: from /Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/util/data.rb:60:in `parse'
/Users/apple/.rvm/gems/ruby-2.6.0/gems/middleman-core-4.3.3/lib/middleman-core/util/data.rb:60:in `match': invalid byte sequence in UTF-8 (ArgumentError)

Is there a way to find out what is causing this error?  I didn't build this website, I just cloned the repository but I don't know where to start.
I've looked this up earlier and found people with a similar problem that said that it had something to do with the font files.  Even when I removed those I still have this error. If anyone could help me out I would appreciate it.  Thanks in advance.


Q: Create Shape drawable with stroke color, corner and solid drawable I Want to create a shape: solid is a Bitmap (repeat tiles), and stroke is a color. I use LayerList:
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/additional_image"
        android:drawable="@drawable/bg_detail_loop"
        >
    </item>
    <item android:id="@+id/rounded_corners"
        android:drawable="@drawable/shape_box_dlg">
    </item>
</layer-list>

File bg_detail_loop.xml:
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:filter="true"
    android:gravity="center"
    android:tileMode="repeat"
    android:src="@drawable/tile_detail"
    />

File shape_box_dlg.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke
        android:width="2dip"
        android:color="#EE6A1F" />
    <gradient android:angle="270" />
    <corners android:radius="6dp" />
</shape>

But, in the corner, the background Bitmap not clip. I want rounded the corner. Anyone help me? Thanks


Q: zshell passing argument to function I put this in my zshrc:
function picofl() {
        openocd -f interface/picoprobe.cfg -f target/rp2040.cfg  -c 'program "$1" reset exit'
}

Then I run: picofl myblink.elf but it errors with unexpected argument. What am I doing wrong?


Q: Custom Sinatra route I'm looking to make a custom route for my Sinatra blog project which shows the user the last entered post in the database.
get "/most-recent-job" do
  Job.last

Can anyone help? I can't find info in my curriculum for such a request.

A: The Sinatra documentation on routes is pretty thorough. Assuming you're just trying to call a class method of Jobs::last, and that the method returns something stringifyable, then:
get '/most-recent-job' do
  Jobs.last
end

should get it done. If that's insufficient for your use case, you'll have to expand your question to include code and output showing what Jobs.last is supposed to return, whatever errors you're getting from the route currently, and what you think the route's output ought to look like if you're expecting a MIME type other than text/plain.


Q: Layers in Hexagonal Architecture I'm reading a lot about hexagonal architecture, but in all the examples that i'm looking, all folders and class ubication are different, and this looks a bit confusing to me.

I've done a simple spring boot application with below folder structure. Adapter folder contains implementation of repository interface and the rest controller.
In domain folder, I've model, which is a simple POJO, ports, that are interfaces of service class which contains all the business logic of Product, and the interface of repository which exposes the methods to be implemented in repository.
In another folder I've service implementation, and as i told before, with the business logic of product.
Is this a correct way to implement an hexagonal architecture for a simple use case? If not, why? Where i should put every class and why? This is what it's not clear...
Much appreciate!

A: You are totally free to organise your code however you wish. This is unrelated to hexagonal architecture.
With that being said, if you want to use hexagonal architecture efficiently, you should probably follow a domain-driven design, that is to say, you should organise your code based on domain/business logic, and not based on technical similarities.
For example, instead of having the following structure:
controller
    product
    cart
    customer
service
    product
    cart
    customer
repository
    product
    cart
    customer

DDD recommends the following structure:
product
    controller
    service
    repository
cart
    controller
    service
    repository
customer
    controller
    service
    repository

Once you've done this, if it helps, you could wrap these in three packages for the differents parts of the hexagonal architecture: user side, business logic and server side. This is something I've done in the past; it helps me keep the different layers clear.
userside
    product
        controller
    cart
        controller
    customer
        controller
businesslogic
    product
        service
    cart
        service
    customer
        service
serverside
    product
        service
    cart
        repository
    customer
        repository

Again, the structure of your packages is not the most important concept. The hexagonal architecture focuses on three principles:

*

*Explicitly separate user side, business logic, and server side layers. A clear package structure helps, but you can separate these layers in other ways.

*Dependencies go from user side and server side layers to the business logic. This is done by defining interfaces and adapters in the business logic (see below). The goal is that code in the user side and server side may be changed without impacting the business logic layer. For example, if you wish to change your repository from a MySQL implementation to a PostgreSQL implementation (in the server side layer), this change should not impact your business logic: the new implementation need only comply with the interface in the business logic.

*Dependency injection: the business logic defines interfaces (commonly called "ports") and transformers ("adapters") with which the user side and server side layers must comply for communication.

It's a very DDD oriented architecture; the idea is that the business logic remain as close to the domain as possible, and unadulterated by technical requirements.

A: Hexagonal architecture doesn't say snything about how to organize the hexagon code (business logic). You can implement however you want to.
Take a look at these articles:
https://jmgarridopaz.github.io/content/articles.html


Q: Tensorflow input pipeline for distributed training I am trying to figure out how to setup my input pipeline for tensorflow in distributed training. It's not clear whether the readers will read from a single process and send the data to all workers or each server will start it's own input pipeline? How do we ensure that every worker has a different input going to it?

A: I will give an example of how I do it:
import tensorflow as tf
batch_size = 50
task_index = 2
num_workers = 10
input_pattern = "gs://backet/dir/part-00*"

get all names of files in the bucket that correspond to input_pattern
files_names = tf.train.match_filenames_once(
                input_pattern, name = "myFiles")

select names for worker task_index. tf.strided_slice is like slice for lists: a[::,task_index] (select every task_indexth file for worker task_index)
to_process = tf.strided_slice(files_names, [task_index],
                 [999999999], strides=[num_workers])
filename_queue = tf.train.string_input_producer(to_process,
                     shuffle=True, #shufle files
                     num_epochs=num_epochs)

reader = tf.TextLineReader()
_ , value = reader.read(filename_queue)
col1,col2 = tf.decode_csv(value,
        record_defaults=[[1],[1]], field_delim="\t")

train_inputs, train_labels = tf.train.shuffle_batch([col1,[col2]],
        batch_size=batch_size,
        capacity=50*batch_size,
        num_threads=10,
        min_after_dequeue = 10*batch_size,
        allow_smaller_final_batch = True)

loss = f(...,train_inputs, train_labels)
optimizer = ...

with tf.train.MonitoredTrainingSession(...) as mon_sess:
    coord = tf.train.Coordinator()
    with coord.stop_on_exception():
        _ = tf.train.start_queue_runners(sess = mon_sess, coord=coord)
        while not coord.should_stop() and not mon_sess.should_stop():
            optimizer.run()

I'm not sure my method is the best way to implement input pipeline in case of distributed TensorFlow implementation because each worker reads names of all files in the bucket

Good lecture about input pipeline in TensorFlow: http://web.stanford.edu/class/cs20si/lectures/notes_09.pdf


Q: Django Design Pattern - request.user in Model I run into this pattern all the time and I'm wondering if there's a better way to handle it.  Lots of my models contemplate the idea of 'creator' - in other words, I want to make sure the user who created the object is saved as the creator.  As such, my models almost always include
creator = models.ForeignKey(User)

There doesn't seem to be a way of defaulting this user to the user who created it (request.user).  As such I find myself building model forms and adding creator as a HiddenInput()
class MyModelForm(ModelForm):
    class Meta:
        model = MyModelForm
        fields = ['name', 'creator']
        widgets = {
            'creator': HiddenInput()
        }

and then binding the form in the view with initial
form = MyModelForm(initial={'creator': request.user})

and checking on POST to make sure no one dickered with the form (full view):
def create(request):
    form = MyModelForm(initial={'creator': request.user})
    if request.method ==  'POST':
        if int(request.POST['creator']) != int(request.user.id):
            return render(request,'500.html', {'message':'form tampering detected'})
        form = FeedGroupForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('index'))
    return render(request, 'mymodelformpage.html',{'form':form})

I'm fine with this but it seems like an anti-pattern.  It strikes me that there ought to be a way to default the creator in the model.
creator = models.ForeignKey(User, default=request.user)

Or do it in a post_save perhaps?

A: No, this is not the right way. The correct way is to exclude the creator field from the form, then set it on save:
if form.is_valid:
    obj = form.save(commit=False)
    obj.creator = request.user
    obj.save()
    ... redirect ...


Q: Running Android Studio Volley in different API levels The app I made ran on different API levels but the volley library only works API level 26.
I was puzzled when I can't login in the app using my phone (android 9) but a later model works just fine. I found out that I can only login in Android 8 phones (API level 26). I tested multiple virtual devices with different API levels and API level 26 let's me login and the rest just doesn't work. I was wondering how can I make volley library work on API level 26 and higher.
Edit: It was a big mistake for me but I now enabled the log for errors and I found these.
(Using http://)

(Using https://)

plugins {
    id 'com.android.application'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.studentplanner"
        minSdk 26
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {

        viewBinding true

    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    namespace 'com.example.studentplanner'
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'com.github.xabaras:RecyclerViewSwipeDecorator:1.3'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.android.volley:volley:1.2.1'
    implementation 'com.google.code.gson:gson:2.9.1'

    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha04'
    implementation 'com.google.android.material:material:1.1.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

A: Add this line in your application tag
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>


Q: WooCommerce product categories are not displayed properly in menu I got this strange behavior in Wordpress, I have about 90 product categories/subcategories.
All the related functions are working fine, except when I go to Appearance -> Menu and try to add product categories to my menu.
The thing is that only two pages of product categories are viewed with many missing categories.
please see the attached screenshot.

I am using Woocommerce v3.3.4
Server info:

A: Go to the ‘Tools’ tab inside the WooCommerce > System Status of your WordPress administration panel. Here you first use the ‘Recount terms’ button and after that use the ‘Clear transients’ button. This will force the system to recount all the products the next time a category is loaded.

A: File Manager >> public_html >> wp-admin >> includes >> nav-menu.php
search for paginate there is two it will be the one in line 692 (it was for me).
// Paginate browsing for large numbers of objects.
    $per_page = 50;
Change 50 to your needs
Also add to child theme functions.php


Q: EJS not rendering on placing image url I am trying to add image using EJS, the page on the browser doesn't render as I want.
Here is the image of the browser
ejs code for this rendering page is
<% layout('layout/boilerplate') -%>
   <% for (let camps of allCamps){%>

                <img class="img-fluid" src="<%= camps.image[0].url %>">

<%= camps.title %>

<%= camps.description %>

                      <%= camps.location%>

                  <a class="btn btn-primary" href="/campgrounds/<%=camps._id%>">View <%=camps.title%>

 <% }%>


Q: Add SSH Connection with pem key to Apache Airflow connection Is there a way to add an ssh connection to Apache Airflow from the UI either via connections or vairables tab that allow connection using a pem key and not a username and password.

A: DISCLAIMER: Following answer is purely speculative

*

*I think key_file param of SSHHook is meant for this purpose

*And the idiomatic way to supply it is to pass it's name via extra args in Airflow Connection entry (web UI)

*

*Of course when neither key_file nor credentials are provided, then SSHHook falls back to identityfile to initialize paramiko client.

*Also have a look how SFTPHook is handling this


Q: Facing problem with material mat-select dropdown position issue Facing problem with material mat-select dropdown position issue. Dropdown position is keep on changing on select of item. How to keep position as fixed. Can you someone support please.


Q: Issue while using webservice to call some java application method which is using resource file Issue while using webservice to call some java application method which is using resource file
I have created one java application which contains following directory structure in my src folder of java..
Src/
  Transcriber.java
  config.xml
  digits.gram
  transcriber.manifest

I have successfully created web-service of this java application with .aar file and putting into axis2 service folder
I am packaging this whole in Transcriber.aar file with the following structure
Transcriber\edu\cmu\sphinx\demo\transcriber

and in that all 4 file above I listed.
I have two method in above Transcriber.java class.. 1st method is just processing without any of other file use like (e.g. config.xml,digits.gram and transcriber.manifest). and its working fine and I can call easily that method from android.
but my second method uses the other files also(e.g. config.xml,digits.gram and transcriber.manifest) to process some logic I want.
But some how I'm getting error when I call the second method and its give me error while I'm calling this 2nd method from android device .
My Error is as follows:
  at java.lang.Thread.run(Thread.java:662)
Caused by: Property exception component:'jsgfGrammar' property:'grammarLocation'
 - Can't locate resource:/edu/cmu/sphinx/demo/transcriber
edu.cmu.sphinx.util.props.InternalConfigurationException: Can't locate resource:
/edu/cmu/sphinx/demo/transcriber

its give me error that some how it cant locate the grammar file digits.gram which is i use to add via the config.xml file with this code in config.xml
<component name="jsgfGrammar" type="edu.cmu.sphinx.jsgf.JSGFGrammar">
        <property name="dictionary" value="dictionary"/>
        <property name="grammarLocation"
             value="resource:/edu/cmu/sphinx/demo/transcriber"/>
        <property name="grammarName" value="digits"/>
    <property name="logMath" value="logMath"/>
    </component>

Why I'm Having this kind of error?enter code here
My CODE WHERE I HAVE FIRST GET THE CONFIG.XML AND THEN CONFIG.XML GET ANOTHER RESOURCE FILE....its successfully finds the config.xml but then the code in config.xml cant locate other resource file
package edu.cmu.sphinx.demo.transcriber;

import edu.cmu.sphinx.frontend.util.AudioFileDataSource;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/** A simple example that shows how to transcribe a continuous audio file that has multiple utterances in it. */
public class TranscribeSimpleGrammar {

        private static final String PATH = "file:///D:\\Sound\\";

        @SuppressWarnings({ "null", "null" })
        public String recognize_wave(String wavePath) throws MalformedURLException{

              URL audioURL;

              //  if (args.length > 0) {
                //    audioURL = new File(args[0]).toURI().toURL();
              //  } else {
                    //audioURL = TranscribeSimpleGrammar.class.getResource("hello.wav");
                        //audioURL = new URL(PATH + "turn-on-light-kitchen-male.wav");
                        //audioURL = new URL(PATH + "turn-down-tv-volume-female.wav");
                       // audioURL = new URL(PATH + wavePath);
              audioURL = new URL(wavePath);
              //audioURL = new URL(PATH + "turn-down-dining-room-music-player-volume-male.wav");

               // }

                URL configURL = TranscribeSimpleGrammar.class.getResource("config.xml");

                ConfigurationManager cm = new ConfigurationManager(configURL);
                Recognizer recognizer = (Recognizer) cm.lookup("recognizer");

                /* allocate the resource necessary for the recognizer */
                recognizer.allocate();

                // configure the audio input for the recognizer
                AudioFileDataSource dataSource = (AudioFileDataSource) cm.lookup("audioFileDataSource");
                dataSource.setAudioFile(audioURL, null);

                // Loop until last utterance in the audio file has been decoded, in which case the recognizer will return null.
                Result result;
                while ((result = recognizer.recognize())!= null) {

                        String resultText = result.getBestResultNoFiller();
                        System.out.println(resultText);
                }

            return result.getBestResultNoFiller();
        }

        public String get_wav_byte(byte[] wavbite,String path){

            String result1="null";

            try
            {
                File dstFile = new File(path);
                FileOutputStream out = new FileOutputStream(dstFile);
                out.write(wavbite, 0, wavbite.length);

                out.close();

            }
            catch (IOException e)
            {
              System.out.println("IOException : " + e);
            }

            try {
                result1=recognize_wave(path);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         return result1;

     }

}

A: Have you ever tried to change
<property name="grammarLocation" value="resource:/edu/cmu/sphinx/demo/transcriber"/>

to
<property name="grammarLocation" value="resource:edu/cmu/sphinx/demo/transcriber"/>

(meaning just removing the leading slash before edu)?
Class.getResource() and ClassLoader.getResource() do interpret the provided name differently: while Class.getResource( "/edu/cmu/sphinx/demo/transcriber/transcriber.manifest" ) would find the resource, you have to use ClassLoader.getResource() with the argument "edu/cmu/sphinx/demo/transcriber/transcriber.manifest" to find the same resource. As you do not know which method is used by the library code you call to load the other resources, you should give it a try.


Q: menu accordion with first voice open i have this menu
I can not copy the code of the menu on the topic , so I put everything on jsfiddle , Practically What I would like the menu stays open without clicking on ParalleloR so I would like the open class is fixed on the first menu item

(function ($) {
    $(document).ready(function () {
        $('#cssmenu li.has-sub>a').on('click', function () {
            $(this).removeAttr('href');
            var element = $(this).parent('li');
            if (element.hasClass('open')) {
                element.removeClass('open'); element.find('li').removeClass('open');
                element.find('ul').slideUp();
            }
            else {
                element.addClass('open');
                element.children('ul').slideDown(); element.siblings('li').children('ul').slideUp(); element.siblings('li').removeClass('open'); element.siblings('li').find('li').removeClass('open'); element.siblings('li').find('ul').slideUp();
            }
        });
        $('#cssmenu>ul>li.has-sub>a').append('');
        (function getColor() {
            var r, g, b;
            var textColor = $('#cssmenu').css('color');
            textColor = textColor.slice(4);
            r = textColor.slice(0, textColor.indexOf(','));
            textColor = textColor.slice(textColor.indexOf(' ') + 1);
            g = textColor.slice(0, textColor.indexOf(','));
            textColor = textColor.slice(textColor.indexOf(' ') + 1);
            b = textColor.slice(0, textColor.indexOf(')'));
            var l = rgbToHsl(r, g, b);
            if (l > 0.7) {
                $('#cssmenu>ul>li>a').css('text-shadow', '0 0px 0px rgba(0, 0, 0, .0)');

            }
            else {
                $('#cssmenu>ul>li>a').css('text-shadow', '0 0px 0 rgba(255, 255, 255, .0)');

            }
        })();
        function rgbToHsl(r, g, b) {
            r /= 255, g /= 255, b /= 255;
            var max = Math.max(r, g, b), min = Math.min(r, g, b);
            var h, s, l = (max + min) / 2;
            if (max == min) {
                h = s = 0;
            }
            else {
                var d = max - min;
                s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
                switch (max) {
                    case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                    case g: h = (b - r) / d + 2; break;
                    case b: h = (r - g) / d + 4; break;
                }
                h /= 6;
            }
            return l;
        }
    });
})(jQuery);
.widget-area .widget {
    padding: 40px 10px 40px 0px;
}

#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
    margin: 0;
    padding: 0;
    border: 0;
    list-style: none;
    line-height: 1;
    display: block;
    position: relative;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

#cssmenu {
    width: 100%;
    font-family: Roboto;
    color: #ffffff;
}

    #cssmenu ul ul {
        display: none;
    }

.align-right {
    float: right;
}

#cssmenu > ul > li > a {
    padding: 15px 25px 16px 10px;
    border-top: 1px solid #CACACA;
    cursor: pointer;
    z-index: 2;
    font-size: 12px;
    font-weight: 300;
    text-decoration: none;
    color: #000000;
    /*background: #F9F9F9;*/
}

    #cssmenu > ul > li > a:hover,
    #cssmenu > ul > li.active > a,
    #cssmenu > ul > li.open > a {
        color: #000000;
    }

#cssmenu > ul > li.open > a {
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.15);
    border-bottom: 0px solid #1682ba;
}

#cssmenu > ul > li:last-child > a,
#cssmenu > ul > li.last > a {
    border-bottom: 0px solid #1682ba;
}

.holder {
    width: 0;
    height: 0;
    position: absolute;
    top: 0;
    right: -11px;
}

    .holder::after,
    .holder::before {
        display: block;
        position: absolute;
        content: "";
        width: 6px;
        height: 6px;
        right: 20px;
        z-index: 10;
        -webkit-transform: rotate(-135deg);
        -moz-transform: rotate(-135deg);
        -ms-transform: rotate(-135deg);
        -o-transform: rotate(-135deg);
        transform: rotate(-135deg);
    }

    .holder::after {
        top: 17px;
        border-top: 2px solid #000;
        border-left: 2px solid #000;
    }

#cssmenu > ul > li > a:hover > span::after,
#cssmenu > ul > li.active > a > span::after,
#cssmenu > ul > li.open > a > span::after {
    border-color: #eee;
}

.holder::before {
    top: 18px;
    border-top: 2px solid;
    border-left: 2px solid;
    border-top-color: inherit;
    border-left-color: inherit;
}

#cssmenu ul ul li a {
    cursor: pointer;
    border-bottom: 1px solid #F5F5F5;
    /* border-left: 1px solid #32373e; */
    /* border-right: 1px solid #32373e; */
    padding: 12px 42px 12px 16px;
    z-index: 1;
    text-decoration: none;
    font-size: 13px;
    color: #32373e;
    background: #FFFFFF;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

#cssmenu ul ul li:hover > a,
#cssmenu ul ul li.open > a,
#cssmenu ul ul li.active > a {
    background: rgb(255, 255, 255);
    color: #23282d;
}

#cssmenu ul ul li:first-child > a {
    box-shadow: none;
}

#cssmenu ul ul ul li:first-child > a {
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

#cssmenu ul ul ul li a {
    padding-left: 30px;
}

#cssmenu > ul > li > ul > li:last-child > a,
#cssmenu > ul > li > ul > li.last > a {
    border-bottom: 0;
}

#cssmenu > ul > li > ul > li.open:last-child > a,
#cssmenu > ul > li > ul > li.last.open > a {
    border-bottom: 0px solid #32373e;
}

#cssmenu > ul > li > ul > li.open:last-child > ul > li:last-child > a {
    border-bottom: 0;
}

#cssmenu ul ul li.has-sub > a::after {
    display: block;
    position: absolute;
    content: "";
    width: 5px;
    height: 5px;
    right: 20px;
    z-index: 10;
    top: 11.5px;
    border-top: 2px solid #000;
    border-left: 2px solid #000;
    -webkit-transform: rotate(-135deg);
    -moz-transform: rotate(-135deg);
    -ms-transform: rotate(-135deg);
    -o-transform: rotate(-135deg);
    transform: rotate(-135deg);
}

#cssmenu ul ul li.active > a::after,
#cssmenu ul ul li.open > a::after,
#cssmenu ul ul li > a:hover::after {
    border-color: #000;
}

.subsubm {
    padding-left: 44px !important;
    background-color: #FFFFFF !important;
    border: 1px !important;
    color: black !important;
}

ParalleloR

Consulenza legale in outsourcing per aziende

Modello contratto di outsourcing

Temporary management

Consulenza società estere

Consulenza crisi aziendale

Consulenza risanamento aziendale e rilancio

Cpnsulenza ristrutturazione del debito

https://jsfiddle.net/exolon82/vpfLf78s/3/
I can not copy the code of the menu on the topic , so I put everything on jsfiddle , Practically What I would like the menu stays open without clicking on ParalleloR so I would like the open class is fixed on the first menu item

A: Just add this style
#cssmenu > ul > li > ul{display: block!important;}

Here is the FIDDLE

A: if you need the first menu to open on page load and you still want it to work as an accordion, trigger click event, on first menu item in top accordion, onload.
$('#cssmenu li.has-sub>a').on('click', function(){
...
});
$('#cssmenu>ul>li.has-sub>a').click();

check the fiddle


Q: PHP getting expiring time of a cookie Can I get the expiring time of a cookie which is already set?
For example, I have set a cookie:
setcookie("test_cookie","some value", time()+3600*24*30);

Now can i get the time when the test_cookie is expiring?
One option could be that when i set the test_cookie, i can set the expiring time in another cookie, but i'm wondering if there's alternative, better way without setting other cookie?
Thanks.

A: Setting it in another cookie is the best method, that or simply appending it to the end of the data you're storing with a delimeter such as #.

A: There's no way to get the expiry time because the browser doesn't send it. So the olny way is to store the time somewhere in another cookie or in session maybe.

A: Check this link How to get cookie's expire time
cookie expiration date can be set in another cookie.This cookie can then be read later to get the expiration date


Q: Why using array in command cancels output redirection? I have this (simplified) code:
elems="${array[@]}"
do_cmd "xxx" "for_each \"$elems\" func" ">> $log_file" || return $?

which redirects output to $log_file (as expected).
However, if the code above is simplified as:
do_cmd "xxx" "for_each \"${array[@]}\" func" ">> $log_file" || return $?

then the output is no longer redirected to $log_file (instead it outputs to stdout).
Any ideas why?
Note: internally do_cmd uses eval. The for_each is:
for_each()
{
  local elems=$1
  local func_and_args=$2

  for elem in $elems
  do
    $func_and_args $elem
  done
}

A: Why The Original Code Broke
When you put ${array[@]} in a context that can only ever evaluate to a single string, it acts just like ${array[*]}. This is what your "working" code was doing (and why it wouldn't keep looking like it was working if your array values had spaces in their values or were otherwise at all interesting).
When you put ${array[@]} in a context that evaluates to multiple words (like a command), it generates breaks between words at every boundary between the individual array items.
Thus, your string starting with for_each was split up into several different arguments, rather than passing the entire array's contents at once; so the redirection was no longer present in do_cmd's $3 at all.

How To Do This Well
Starting with some general points:

*

*Array contents are data. Data is not parsed as syntax (unless you use eval, and that opens a can of worms that the whole purpose of using arrays in bash is to avoid).

*Flattening your array into a string (string=${array[@]}) defeats all the benefits that might lead you to use an array in the first place; it behaves exactly like string=${array[*]}, destroying the original item boundaries.

*To safely inject data into an evaled context, it needs to be escaped with bash 5.0's ${var@Q}, or older versions' printf %q; there's a lot of care that needs to be taken to do that correctly, and it's much easier to analyze code for correctness/safety if one doesn't even try. (To expand a full array of items into a single string with eval-safe escaping for all in bash 5.0+, one uses ${var[*]@Q}).

Don't do any of that; the primitives you're trying to build can be accomplished without eval, without squashing arrays to strings, without blurring the boundary between data and syntax. To provide a concrete example:
appending_output_to() {
  local appending_output_to__dest=$1; shift
  "$@" >>"$appending_output_to__dest"
}

for_each() {
  local -n for_each__source=$1; shift
  local for_each__elem
  for for_each__elem in "${for_each__source[@]}"; do
    "$@" "$for_each__elem"
  done
}

cmd=( redirecting_to "$log_file" func )
array=( item1 item2 item3 )
for_each array "${cmd[@]}"

(The long variable names are to prevent conflicting with names used by the functions being wrapped; even a local is not quite without side effects when a function called from the function declaring the local is trying to reuse the same name).


Q: Android Studio - Failed to refresh Gradle project - failed to find target 4.4w
I'm trying to move my project from eclipse into android studio so that I can start building an android wear app.  I exported the app from eclipse and imported it into android studio.  However, when I try and add the android wear app, I start getting the error message "failed to find target 4.4w" see screen shot.
When creating a brand new project, this error does not occur.  I noticed that i'm still running on android api 19 for external libraries, but I can't upgrade it since it can't find it.
The 4.4w is installed via sdk manager, why can't android studio see this?

A: For some reason, the wear project had '4.4w' as the build target, i updated this to 20 and the error went away.


Q: How do I Add PHP code in WordPress POST without using a plugin I am trying to add php code(2000 lines) to WordPress post manually without using any plugin or third party tool. But I have not been successful in this... If anybody knows how I can do this please feel free to post an answer. So far I have been able to add my php code to WP Page but not WP Post. I will be looking forward to you! Thanks!

A: I was able to do this by creating a separate .php file in my theme "twentytwentytwo" folder and then I pasted the following code in it...
"<?php
/*

*

*Template Name: new Theme

*Template Post Type: post
*/
?>"
""
""
By doing this I created a Separate theme for my post. Then simple pasted my php code under the get_header() line....
After this I logged in to my WP admin and clicked on the edit post and in the template dropdown section I found my theme name "new Theme" just selected that and published. Job done!

A: Use 'the_content' filter https://developer.wordpress.org/reference/hooks/the_content/
example :
function custom_content($content)
{
    global $post;

    if ($post && $post->post_type == 'post') {

        if ($post->ID == '145'()) { // target a specific post by ID
            // do something
        }
    }

    return $content;
}
add_filter('the_content', 'custom_content');


Q: Running two loops at the same time ? moving and traveling using loops I am a first year Computer Engineer so I am a little bit amatuer in coding C++, anyway I am creating a game where there are two spaceships shooting each other. I currently succeeded making the first spaceship move by using a while loop and the GetASyncKeyState function. but now I am making the bullets travel. I used  for loop, and I did succeed in making the bullet travel upward. But there's a problem, I can't move the spaceship until the for loop stop or the bullet reach the top of the console window (I am using console btw). is there a way to both run the for loop and while at the same time ? or to run two different function at the same time since GameMovement() is for the movement of spaceship and BulletTravel() is for the bullet. and I am calling BulletTravel() from GameMovement().
void GameMovements()
{
bool FirstInitialization = true;
int Player1XCoordinate = 55, Player2XCoordinate = 55;
int Player1YCoordinateU = 28, Player1YCoordinateD = 29;

while (true)
{
    BulletPattern(Player1XCoordinate);

    if (FirstInitialization == true)
    {
        GameBorderAndStatus();
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
        FirstInitialization = false;
    }

    //MOVEMENTS FOR PLAYER 1
    else if (GetAsyncKeyState(VK_LEFT) && Player1XCoordinate != 16)
    {
        system("cls");
        GameBorderAndStatus();

        Sleep(10);
        Player1XCoordinate -= 3;
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }
    else if (GetAsyncKeyState(VK_RIGHT) && Player1XCoordinate != 94)
    {
        system("cls");
        GameBorderAndStatus();
        Player1XCoordinate += 3;

        Sleep(10);
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }
    else if (GetAsyncKeyState(VK_UP) && Player1YCoordinateU != 24)
    {
        system("cls");
        GameBorderAndStatus();
        Player1YCoordinateU -= 2;
        Player1YCoordinateD -= 2;

        Sleep(10);
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }
    else if (GetAsyncKeyState(VK_DOWN) && Player1YCoordinateU != 28)
    {
        system("cls");
        GameBorderAndStatus();
        Player1YCoordinateU += 2;
        Player1YCoordinateD += 2;

        Sleep(10);
        SetCoordinate(Player1XCoordinate, Player1YCoordinateU);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinateD);
        cout << "^==|==^ \n";
    }

 }
}

void GameBorderAndStatus()
{
       //Draw game border
      for (int i = 0; i < 31; i++)
      {
         SetCoordinate(15, i);
         cout << "|";
         SetCoordinate(104, i);
         cout << "|";
      }

 }

void BulletPattern(int Player1MuzzleLocation)
{
    for (int i = 25; i != 3; i--)
    {
       Sleep(100);
       SetCoordinate(Player1MuzzleLocation + 3, i);

    }
}

 void SetCoordinate(int CoordinateX, int CoordinateY)
 {
     COORD Coordinate;
     Coordinate.X = CoordinateX;
     Coordinate.Y = CoordinateY;
     SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Coordinate);
 }

A: Rather than using two different functions and moving one object within each, you might find better results keeping track of where each object should be, and using one function to draw both.
It's a little hard to tell what's going on in your code since some functions and variable declarations are missing (I don't see you ever actually drawing a bullet, for example - might be a bug in your BulletPattern?), but something like this might do the trick:
void GameMovements()
{
    while (true)
    {
        //MOVEMENTS FOR PLAYER 1
        if (GetAsyncKeyState(VK_LEFT) && Player1XCoordinate != GAMEBOARD_LEFT)
        {
            Player1XCoordinate -= 3;
        }
        else if (GetAsyncKeyState(VK_RIGHT) && Player1XCoordinate != GAMEBOARD_RIGHT)
        {
            Player1XCoordinate += 3;
        }
        else if (GetAsyncKeyState(VK_UP) && Player1YCoordinate != SPACESHIP_TOP)
        {
            Player1YCoordinate -= 2;
        }
        else if (GetAsyncKeyState(VK_DOWN) && Player1YCoordinate != SPACESHIP_BOTTOM)
        {
            Player1YCoordinate += 2;
        }

        Sleep(10);

        UpdateBulletPosition();
        DrawObjects();
    }
}

void UpdateBulletPosition()
{
  //if the bullet hits the top of the screen, remove it
  if (bulletYCoordinate == GAMEBOARD_TOP)
  {
      bulletXCoordinate = 0;
      bulletYCoordinate = 0;
  }

  //I assume you're automatically generating bullets whenever possible; you'll have to adjust this conditional if that's not the case

  //no bullet? generate one
  if (bulletXCoordinate == 0)
  {
      bulletXCoordinate = Player1XCoordinate + 3;
      bulletYCoordinate = 25;
  }
  else
  {
      bulletYCoordinate--;

      Sleep(100);
  }
}

void DrawObjects()
{
        //wipe the screen and show status first
        system("cls");
        GameBorderAndStatus();

        SetCoordinate(Player1XCoordinate, Player1YCoordinate);
        cout << "   ^  \n";
        SetCoordinate(Player1XCoordinate, Player1YCoordinate + 1);
        cout << "^==|==^ \n";

        //only draw the bullet if there's a bullet there to draw
        if (bulletXCoordinate != 0)
        {
            SetCoordinate(bulletXCoordinate, bulletYCoordinate);
            cout << ".\n";
        }
}

const int GAMEBOARD_LEFT = 16;
const int GAMEBOARD_RIGHT = 94;
const int GAMEBOARD_TOP = 3;
const int SPACESHIP_TOP = 24;
const int SPACESHIP_BOTTOM = 28;

int Player1XCoordinate = 55, Player2XCoordinate = 55;
int Player1YCoordinate = 28;
int bulletXCoordinate = 0, bulletYCoordinate = 0;

I also made some tweaks to the rest of your code. Every case in your if-else block used the same basic drawing code, so I pulled that out of the if-else entirely. That also let me drop the entire initialization if-else.
I also dropped one of your vertical coordinates for the spaceship. You really don't need two; just keep track of the upper coordinate and draw the lower half of the ship at Player1YCoordinate + 1.
Finally, I replaced your hardcoded board edges with constants. Magic numbers are generally frowned upon; using named constants makes it easier to determine why you're using a given value in a given location, as well as making it easier to update the code in the future (perhaps you need to update for a different console size).


Q: LUIS not returning the correct entity values I am trying to learn how to use LUIS to train for an intent to search my data on my database using NLP. I created an Intent UIM.Search and added the following Utterance for which the token view is as below:

I mapped them to the entities so that I can get the actual user values for API based queries as shown below

Issue I am having is when I use the testing panel and enter texts like:
show customers in paris for chocolatemagic the entities it returns are as below

where as when I enter an exact phrase used for training I get the correct result like:
show me cakemagic customers from bangalore
returns

Can someone please help me understand what am I missing here to translate the user query to actual intent and then get the query parameters as entities to convert to SQL queries.
EDIT1:
Adding the Model details, but this time including the Phrases, which actually works. But this is not something i would like to do as then i'll have to add all possible combinations of words that can be used in the query
    {
  "luis_schema_version": "3.1.0",
  "versionId": "0.1",
  "name": "UIM",
  "desc": "",
  "culture": "en-us",
  "intents": [
    {
      "name": "None"
    },
    {
      "name": "UIM.Search"
    }
  ],
  "entities": [
    {
      "name": "address.city",
      "roles": []
    },
    {
      "name": "address.country",
      "roles": []
    },
    {
      "name": "count",
      "roles": []
    },
    {
      "name": "search.order",
      "roles": []
    },
    {
      "name": "search.type",
      "roles": []
    },
    {
      "name": "subsidiary",
      "roles": []
    }
  ],
  "composites": [
    {
      "name": "address",
      "children": [
        "address.city",
        "address.country"
      ],
      "roles": []
    }
  ],
  "closedLists": [],
  "patternAnyEntities": [],
  "regex_entities": [],
  "prebuiltEntities": [
    {
      "name": "number",
      "roles": []
    }
  ],
  "model_features": [
    {
      "name": "company Names",
      "mode": true,
      "words": "honeywell,chocolatemagic,boeing,jeppesen,cakemagic",
      "activated": true
    },
    {
      "name": "City Names",
      "mode": true,
      "words": "bangalore,paris,london,bellevue,berlin,amsterdam,rome,new york,madrid,moscow,sydney,tokyo,kirkland,redmond,frankfurt,barcelona,milan,vienna,prague,brussels,athens,lisbon,stockholm,munich,zurich,budapest,warsaw,copenhagen,dublin,hamburg,istanbul,oslo,bucharest,venice,helsinki,shanghai,geneva,beijing,zagreb,malaga,luxembourg,sofia,kiev,manchester,buenos aires,bangkok,singapore,tallinn,riga,seoul,melbourne,vilnius,toronto,cairo,dubai,los angeles,san francisco,montreal,vancouver,chicago,boston,mumbai,johannesburg,rio de janeiro,miami,seattle,new orleans,san diego,las vegas,houston,philadelphia,atlanta,dallas,denver,orlando,tampa,jacksonville,washington,detroit,phoenix,memphis,cleveland,pittsburgh,portland,baltimore,richmond,madison,nashville,san antonio,sacramento,charlotte,austin,indianapolis,minneapolis,columbus,buffalo,oakland,louisville,cincinnati,newark,milwaukee,san jose,birmingham,raleigh",
      "activated": true
    },
    {
      "name": "Country Names",
      "mode": true,
      "words": "india,usa,uk,france,australia,germany,u.s.a.,u.k.,ireland,austria,finland,denmark,spain,netherlands,sweden,italy,poland,norway,greece,cyprus,belgium,belfast,switzerland,russia,malta,romania,hungary,slovenia,croatia,portugal,european,iceland,slovakia,bulgaria,prague,serbia,estonia,lithuania,latvia,ukraine,albania,armenia,moldova,belarus,kazakhstan,ghana,uruguay,azerbaijan,moscow,paraguay,montenegro,eurovision,venezuela,algeria,burkina,cameroon,tunisia,guatemala,honduras,lesotho,angola,bolivia,nicaragua,grenada,liberia,tanzania,ecuador,cuba,tobago,zimbabwe,ethiopia,rwanda,trinidad,fiji,mozambique,guyana,namibia,belize,haiti,barbados,cambodia,mauritania,mauritius,uganda,maldives,nigeria,kenya,botswana,bahamas,vanuatu,seychelles,africa",
      "activated": true
    },
    {
      "name": "Entity Names",
      "mode": true,
      "words": "customers,suppliers,fleets,transactions,companies,services,employees,retailers,manufacturers,partners,fleet,products,transaction,events,contact,projects,clients,programs,facilities,client,consultant",
      "activated": true
    },
    {
      "name": "Services Names",
      "mode": true,
      "words": "parts,services,planes,applications,components,systems,subsystems,sensors,software,equipment,accessories,electronics,cakes",
      "activated": true
    }
  ],
  "regex_features": [],
  "patterns": [
    {
      "pattern": "show me {subsidiary} from {search.type} in {address.city}",
      "intent": "UIM.Search"
    },
    {
      "pattern": "show me {count} {search.type} from {address.city} in {address.country}",
      "intent": "UIM.Search"
    },
    {
      "pattern": "show me all {search.type} from {address.city}",
      "intent": "UIM.Search"
    }
  ],
  "utterances": [
    {
      "text": "show 4 customers who bought cakes",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 7,
          "endPos": 15
        },
        {
          "entity": "search.order",
          "startPos": 28,
          "endPos": 32
        }
      ]
    },
    {
      "text": "show 5 customers who bought cakes from bangalore",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 7,
          "endPos": 15
        },
        {
          "entity": "search.order",
          "startPos": 28,
          "endPos": 32
        },
        {
          "entity": "address.city",
          "startPos": 39,
          "endPos": 47
        }
      ]
    },
    {
      "text": "show all customers form bangalore",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 9,
          "endPos": 17
        },
        {
          "entity": "address.city",
          "startPos": 24,
          "endPos": 32
        }
      ]
    },
    {
      "text": "show customers in bangalore for cakemagic",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 5,
          "endPos": 13
        },
        {
          "entity": "address.city",
          "startPos": 18,
          "endPos": 26
        },
        {
          "entity": "subsidiary",
          "startPos": 32,
          "endPos": 40
        }
      ]
    },
    {
      "text": "show me all indian customers for cakemagic",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "address.country",
          "startPos": 12,
          "endPos": 17
        },
        {
          "entity": "search.type",
          "startPos": 19,
          "endPos": 27
        },
        {
          "entity": "search.order",
          "startPos": 33,
          "endPos": 41
        }
      ]
    },
    {
      "text": "show me cakemagic customers from bangalore",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "subsidiary",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "search.type",
          "startPos": 18,
          "endPos": 26
        },
        {
          "entity": "address.city",
          "startPos": 33,
          "endPos": 41
        }
      ]
    },
    {
      "text": "show me customers from bangalore who liked our cakes",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "address.city",
          "startPos": 23,
          "endPos": 31
        },
        {
          "entity": "search.order",
          "startPos": 47,
          "endPos": 51
        }
      ]
    },
    {
      "text": "show me customers from usa",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "address.country",
          "startPos": 23,
          "endPos": 25
        }
      ]
    },
    {
      "text": "show me customers who have ordered cake",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "search.order",
          "startPos": 35,
          "endPos": 38
        }
      ]
    },
    {
      "text": "show me customers who likes our cake",
      "intent": "None",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 8,
          "endPos": 16
        },
        {
          "entity": "search.order",
          "startPos": 32,
          "endPos": 35
        }
      ]
    },
    {
      "text": "show me top 3 customers from bangalore in india",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 14,
          "endPos": 22
        },
        {
          "entity": "address.city",
          "startPos": 29,
          "endPos": 37
        },
        {
          "entity": "address.country",
          "startPos": 42,
          "endPos": 46
        }
      ]
    },
    {
      "text": "show me top 3 customers from india",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 14,
          "endPos": 22
        },
        {
          "entity": "address.country",
          "startPos": 29,
          "endPos": 33
        }
      ]
    },
    {
      "text": "show top 3 customers form bangalore who have ordered cakes in last 3 months",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 11,
          "endPos": 19
        },
        {
          "entity": "address.city",
          "startPos": 26,
          "endPos": 34
        },
        {
          "entity": "search.order",
          "startPos": 53,
          "endPos": 57
        }
      ]
    },
    {
      "text": "which customers from usa bought cakes from me",
      "intent": "UIM.Search",
      "entities": [
        {
          "entity": "search.type",
          "startPos": 6,
          "endPos": 14
        },
        {
          "entity": "address.country",
          "startPos": 21,
          "endPos": 23
        },
        {
          "entity": "search.order",
          "startPos": 32,
          "endPos": 36
        }
      ]
    }
  ],
  "settings": []
}

Regards
Kiran

A: Kiran, the issue is you only have two utterances in your app that contain the subsidiary entity. Additional to that, the word 'cakemagic' is not a real word and, thus, LUIS doesn't know how to handle that word. The option is to either include more utterances from which you can train LUIS with (i.e. more examples of context, where the entity can show up in the utterance, or different values the subsidiary can be), use real words LUIS would naturally recognize, or build out the phrase list to include all the words you are looking to have included.


Q: Using ODBC connection with Azure Data Studio In order to connect to an IBM DB2 database, I am using DBeaver with an ODBC type of connection. But since I found Azure Data Studio very lightweight and portable, I want to ask if there is a way to connect to such databases because all I get is Microsoft SQL Server as connection type.


Q: Implicitly redirect in Apache I have Apache and want to implicitly redirect http request to a file.
That is, when a user hits http://example.com/foo/bar, I wish a user to see a content on .xml file under /some/folder/file.xml and at the same time a user must see http://example.com/foo/bar in the address bar.
Redirect instruction in httpd.conf makes a URL being changed once it gets redirected, but I want to keep the URL same.

A: Try this.
RewriteEngine  on
RewriteRule    "/foo/bar$"  "/some/folder/file.xml" [PT]

you can even specify mime-type.
RewriteRule    "/foo/bar$"  "/some/folder/file.xml" [PT,H=application/xml]

You need internal remapping.


Q: Unable to extract JSON fields in Splunk I'm trying to extract JSON fields from syslog inputs.
In ./etc/system/default/props.conf I've added the following lines:
[mylogtype]
SEDCMD-StripHeader = s/^[^{]+//
INDEXED_EXTRACTIONS = json
KV_MODE = none
pulldown_type = true

The SEDCMD works; the syslogs headers are removed.

But the JSON fields are not parsed.
Any ideas?

A: Resolved. Use the following configuration in props.conf
[yourlogtype]
SEDCMD-StripHeader = s/^[^{]+//
KV_MODE = json
pulldown_type = true


Q: Storing class files in dll and using the dll for multiple websites in asp.net I want to create a class file in VS2005 and be able to use it in other websites on my computer / production server. How do I create this dll and store it in a common place where I can reference it while developing and also on the production server ?

A: Avoid the GAC unless you have full administration rights on the host server.
What you could do is create a project containing the source for your shared DLL. You can then add this project into each of your web site solutions, and add a reference in your site solutions to the project. This has the added advantage of enabling you to step into your shared source during debugging.

A: First add a class library project to your solution. Add this class into this library. And deploy this class to Global Assembly Cache (GAC). You can follow these steps to install your assembly to GAC.


Q: Convert time string in XSLT How do I convert a time string like
20101115083000 +0200

to
2010-11-15 08:30:00 +0200

using XSLT?

A: If you have XSLT 2.0, you can use date parsing and formatting functions.
If you have XSLT 1.0, but can use EXSLT, it provides similar functions.
These would be less transparent to use than @Peter's explicit code, but maybe more robust if your input format can vary.

A: Here is a most generic formatDateTime processing. Input and output format are completely configyrable and passed as parameters:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:call-template name="convertDateTime">
   <xsl:with-param name="pDateTime" select="."/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat">
    <year offset="0" length="4"/>
    <month offset="4" length="2"/>
    <day offset="6" length="2"/>
    <hour offset="8" length="2"/>
    <minutes offset="10" length="2"/>
    <seconds offset="12" length="2"/>
    <zone offset="15" length="5"/>
  </xsl:param>

  <xsl:param name="pOutFormat">
   <y/>-<mo/>-<d/> <h/>:<m/>:<s/> <z/>
  </xsl:param>

  <xsl:variable name="vInFormat" select=
   "document('')/*/xsl:template[@name='convertDateTime']
                       /xsl:param[@name='pInFormat']"/>
  <xsl:variable name="vOutFormat" select=
   "document('')/*/xsl:template[@name='convertDateTime']
                       /xsl:param[@name='pOutFormat']"/>
  <xsl:apply-templates select="$vOutFormat/node()"
       mode="_convertDateTime">
    <xsl:with-param name="pDateTime" select="$pDateTime"/>
    <xsl:with-param name="pInFormat" select="$vInFormat"/>
   </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="y" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/year/@offset,
                $pInFormat/year/@length)"/>
 </xsl:template>

 <xsl:template match="mo" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/month/@offset,
                $pInFormat/month/@length)"/>
 </xsl:template>

 <xsl:template match="d" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/day/@offset,
                $pInFormat/day/@length)"/>
 </xsl:template>

 <xsl:template match="h" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/hour/@offset,
                $pInFormat/hour/@length)"/>
 </xsl:template>

 <xsl:template match="m" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/minutes/@offset,
                $pInFormat/minutes/@length)"/>
 </xsl:template>

 <xsl:template match="s" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/seconds/@offset,
                $pInFormat/seconds/@length)"/>
 </xsl:template>

 <xsl:template match="z" mode="_convertDateTime">
  <xsl:param name="pDateTime"/>
  <xsl:param name="pInFormat"/>

  <xsl:value-of select=
     "substring($pDateTime,
                1+$pInFormat/zone/@offset,
                $pInFormat/zone/@length)"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied to the following XML document:
<dateTime>20101115083000 +0200</dateTime>

the wanted, correct result is produced:
   2010-11-15 08:30:00 +0200

A: We use templates:
<xsl:template name="format-date-time">
    <xsl:param name="date" select="'%Y-%m-%dT%H:%M:%S%z'"/>
    <xsl:value-of select="substring($date, 9, 2)"/>
    <xsl:text>/</xsl:text>
    <xsl:value-of select="substring($date, 6, 2)"/>
    <xsl:text>/</xsl:text>
    <xsl:value-of select="substring($date, 1, 4)"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="substring($date, 12, 2)"/>
    <xsl:text>:</xsl:text>
    <xsl:value-of select="substring($date, 15, 2)"/>
    <xsl:text>:</xsl:text>
    <xsl:value-of select="substring($date, 18, 2)"/>
</xsl:template>

We call these templates like this:
<xsl:call-template name="format-date-time">
    <xsl:with-param name="date" select="./Startdate"/>
</xsl:call-template>

./Startdate is an XML date, but with the substring technique, I think you could solve your problem too.


Q: What is dynamic DAO? This blog talked about using dynamic DAO instead of activerecord. What exactly is meant by "dynamic" DAO in the context of statically typed languages? Does this apply only to statically typed languages on a VM or also to compiled languages?

A: Both DAO and ActiveRecord are patterns to access data in a Database. DAO stands for "Data Acess Object". Following are the links to the relevant Wikipedia pages to read more about the individual patterns.

*

*ActiveRecord: http://en.wikipedia.org/wiki/Active_record_pattern

*DAO: http://en.wikipedia.org/wiki/Data_access_object
Note that the ruby gem activerecord is an implementation of the "Active Record" patterns, which happens to have the same name as the pattern.


Q: How to ignore empty cell in google script function I'm trying to create a function that highlights any cells when they are changed ignoring any changes to empty cells, the function below does highlight changes but to ALL cells including empty ones, any help would be greatly appreciated.
function onEdit() {

var sheetsToWatch = ['IC', 'FTE'];

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var val = cell.getValue();

var sheetName = sheet.getName();
var matchFound = false;
for (var i = 0; i < sheetsToWatch.length; i++) {
if (sheetName.match(sheetsToWatch[i])) matchFound = true;
  }

if (val && matchFound){

var rowColLabel =
sheet.getRange(cell.getRow(),cell.getColumn()).setBackground('#faec15');

I tried a bunch of different if statements to try filter empty cells but nothing changes the result

A: Take advantage of the event object e, like this:
function onEdit(e) {
  if (!e) {
    throw new Error('Do not run this code in the script editor.');
  }
  if (!e.oldValue
    || !e.range.getSheet().getName().match(/^(IC|FTE)$/i)) {
    return;
  }
  e.range.setBackground('#faec15');
}

See Apps Script at Stack Overflow, Clean Code JavaScript, and these onEdit(e) optimization tips.

A: some ways to ignore empty data in apps-script:

// 1. assume you have one column of data:

  // if your data may contains 0 or false:
function test1() {
  const values = [
    ['value_1'],
    [0],
    ['value_2'],
    [false],
    ['value_3'],
    [''],
    ['value_4']
  ]

  for(const row of values) {
    if(row[0]==undefined || row[0]=='') continue;
    console.log(row);
  }
}

function test2() {
  // if your data do not contains 0 or false:
  const values = [
    ['value_1'],
    [''],
    ['value_2'],
    [''],
    ['value_3'],
    [''],
    ['value_4']
  ]

  for(const row of values) {
    if(!row[0]) continue;
    console.log(row);
  }
}

test1()
/** output:
["value_1"]
["value_2"]
["value_3"]
["value_4"]
*/

test2()
/** output:
["value_1"]
["value_2"]
["value_3"]
["value_4"]
*/

// 2. Assume you have a set rows and columns as data:
  // Assume all the test samples below does not contains 0 or false:
function test3(arg) {
  const values = [
    ['value_1-1','value_1-2','value_1-3'],
    ['','value_2-2','value_2-3'],
    ['value_3-1','','value_3-3'],
    ['value_4-1','value_4-2',''],
    ['','',''],
    ['value_5-1','value_5-2','value_5-3']
  ];

  switch(arg) {
    case 1: // 2-1. if you only want to check one column:
      {
        for(row of values) {
          if(!row[1]) continue; // check only column B of each row.
          console.log(row);
        }
      }
      break;
    case 2: // 2-2. if you need to check the whole row and skip only if the entire row is empty:
    {
      for(row of values) {
       if(row.every(col => !col)) continue; // check every columns of each row.
       console.log(row);
      }
    }
    break;
    case 3: // 2-3. if you need to check the whole row and skip if that row contains 1 or more empty cell:
    {
      for(row of values) {
       if(row.some(col => !col)) continue; // check every columns of each row.
       console.log(row);
      }
    }
    break;
  }
}

test3(1)
/** output:
["value_1-1","value_1-2","value_1-3"]
["","value_2-2","value_2-3"]
["value_4-1","value_4-2",""]
["value_5-1","value_5-2","value_5-3"]
*/

test3(2)
/** output:
["value_1-1","value_1-2","value_1-3"]
["","value_2-2","value_2-3"]
["value_3-1","","value_3-3"]
["value_4-1","value_4-2",""]
["value_5-1","value_5-2","value_5-3"]
*/

test3(3)
/** output:
["value_1-1","value_1-2","value_1-3"]
["value_5-1","value_5-2","value_5-3"]
*/


Q: Can you use TFS API with only query strings? Trying to queue build from Slack Using On-Premise TFS 2017 and Slack.  Just trying to find a way for people to manually queue builds.  Slack Slash Commands will almost work, but can't seem to send JSON bodies, so I'm trying to find out how to send credentials and definition IDs using only query strings...
Some background:

*

*Our people cannot run unsigned Powershell Scripts because of Group Policy overrides for ExecutionPolicy.

*Don't want to give people access to queue builds through web interface.

*We are using CI/CD, but need to manually queue for QA/Demo builds.

*Wanted to avoid using another app as a go-between if possible, since new environments for hosting are hard to come by here.

Is there a way to hit the TFS API through Slack Slash Commands?


Q: Django Model Foreign Key Casting Integer to Char Edited
I have two tables Table1 and Table2. Table1 has a field x of type int and Table2 has primary key y of type char. I am trying to do x = models.ForeignKey(Table2, ...) but it tries to cast y to an int first. In doing so, this overflows the int. I am wondering if it is possible to first cast x to a char and then do the foreign key relationship.


Q: What is the purpose of & in (a & 1) I am trying to solve a problem in codefights, after browsing the net, i found this solution.But i am not clear how it works.
    a * (a & 1) ^ b * !(b & 1) ^ !!(((a ^ b) + 1) & 2)

A: A single & is a bitwise AND, which means that the result is the bits that are set on BOTH left and right side of the operator.
As an example 15 & 7 or as they are represented in binary:
1111
&
0111

The bitwise AND will result in the a number with the common bits set:
1111 & 0111 = 0111

When you make the (a & 1) you are testing whether the least significant bit (lsb) is set, since you are performing a test like this:
a
&
00000001

If a had the bitwise value: 00000110 then the result would be 0, since there are no common bits set, if a had the bitwise value: 00000111 then the result would be 1 since the lsb is set on a.
This is used for different situations, if the lsb is set you know that the number is odd, so this test is really whether the number is odd or not (1, 3, 5, 7, ...).
Looking at the first part of your solution: a * (a & 1) you are multiplying a with the value of (0 or 1 remember), 1 if a is odd, and 0 if it is even.

A: Here & is a Bitwise Operator(works on bits and perform bit-by-bit operation).For more details see this and this


Q: Search Using IN Condition in MySql I am writing Web services for IOS In cakePhp and stuck in IN condition.
I have a table dog_temperaments and it has values "happy,dependent,shy".
Now if IOS send me array (happy,shy) Then I search Like this
Select dog_temperaments.* where temperaments IN(happy,shy)
Its work fine but if IOS send me array 0 or any(means search by any temperament) Then How I will Search........
Any means Search by all temperaments

A: If it is 0 or any any then no need for that condition as it ishould return all of them.
So aassuming $type will contain the temperaments as an array and 0/any will be single element for that case.
if(count($type) == 1 && in_array(($type[0], array('0', 'any'))) {
    $condition = "";
} else {
    $condition = "WHERE temperaments IN ('" . implode("','", $type) . "')";
}

And the query will be like -
"Select dog_temperaments.* from dog_temperaments ".$condition

A: Either you can check that the array is empty or not like
if(is_array($array)) {
    Use
    Select dog_temperaments.* where temperaments IN('happy','shy');
} else {
    notify Enter proper search key
}

Else you anyways get the empty results by using the same query if the array is empty like
Select dog_temperaments.* where temperaments IN(0);


Q: Python copying multiple files simultaneously (Multithreading) I have some python code that I use to copy files from one directly to another, however it is a very slow process and is sequential. I would like to find a way to do multithreading, copying more that one by one file, but rather have 10 or 100 processes running doing this. Here is my current core that process one by one file:
import os
import shutil

directory = "All_files"

with open('files.txt','w') as f:
    for filename in os.listdir(directory):
        src = directory+"/"+filename+"/02-Partners.pdf"
        file_exists = os.path.exists(src)
        if file_exists == True:
            dst="part/"+filename+"_"+"02-Partners.pdf"
            shutil.copyfile(src,dst)
            f.write('%s \n' % (filename))

Any assistance in getting multiple files copying at the same time will be appreciated.

A: Take a look at python's threading basic package and see if it fits you.
https://docs.python.org/3/library/threading.html


Q: Python Module issues Im pretty new to python, and have been having a rough time learning it. I have a main file
import Tests
from Tests import CashAMDSale

CashAMDSale.AMDSale()

and CashAMDSale
import pyodbc
import DataFunctions
import automa
from DataFunctions import *
from automa.api import *

def AMDSale():
    AMDInstance = DataFunctions.GetValidAMD()

And here is GetValidAMD
import pyodbc

def ValidAMD(GetValidAMD):
     (short method talking to a database)

My error comes up on the line that has AMDInstance = DataFunctions.GetValidAMD()
I get the error AttributeError: 'module' object has no attribute 'GetValidAMD'
I have looked and looked for an answer, and nothing has worked. Any ideas? Thanks!

A: When you create the file foo.py, you create a python module. When you do import foo, Python evaluates that file and places any variables, functions and classes it defines into a module object, which it assigns to the name foo.
# foo.py
x = 1
def foo():
    print 'foo'

>>> import foo
>>> type(foo)
<type 'module'>
>>> foo.x
1
>>> foo.foo()
foo

When you create the directory bar with an __init__.py file, you create a python package. When you do import bar, Python evaluates the __init__.py file and places any variables, functions and classes it defines into a module object, which it assigns to the name bar.
# bar/__init__.py
y = 2
def bar():
    print 'bar'

>>> import bar
>>> type(bar)
<type 'module'>
>>> bar.y
2
>>> bar.bar()
bar

When you create python modules inside a python package (that is, files ending with .py inside directory containing __init__.py), you must import these modules via this package:
>>> # place foo.py in bar/
>>> import foo
Traceback (most recent call last):
    ...
ImportError: No module named foo
>>> import bar.foo
>>> bar.foo.x
1
>>> bar.foo.foo()
foo

Now, assuming your project structure is:
main.py
DataFunctions/
    __init__.py
    CashAMDSale.py
        def AMDSale(): ...
    GetValidAMD.py
        def ValidAMD(GetValidAMD): ...

your main script can import DataFunctions.CashAMDSale and use DataFunctions.CashAMDSale.AMDSale(), and import DataFunctions.GetValidAMD and use DataFunctions.GetValidAMD.ValidAMD().

A: DataFunctions is a folder, which means it is a package and must contain an __init__.py file for python to recognise it as such.
when you import * from a package, you do not automatically import all it's modules. This is documented in the docs
so for your code to work, you either need to explicitly import the modules you need:
import DataFunctions.GetValidAMD

or you need to add the following to the __init__.py of DataFunctions:
__all__ = ["GetValidAMD"]

then you can import * from the package and everything listen in __all__ will be imported

A: Check out this.
It's the same problem. You are importing DataFunctions which is a module. I expct there to be a class called DataFunctions in that module which needs to be imported with
from DataFunctions import DataFunctions
...
AMDInstance = DataFunctions.GetValidAMD()


Q: how to insert an array into database in python? I have a database called my_python and I have a table called my_transport. There are 3 columns in the table: id, transport, and fee. for the first columns "id", I make it auto increment so that I don't have to insert any value into it. My question is how to insert the value of  my_trans and my_fee into the database table?
    import mysql.connector

    my_trans=['car','train','ship','train']
    my_fee=[200,300,150,200]

    try:
        connection = mysql.connector.connect(host='localhost',
                                 database='my-python',
                                 user='root',
                                 password='')
        sql_insert_query = """INSERT INTO my_transport
                               (`transport`, `fee`) VALUES (my_trans, my_fee)"""
        cursor = connection.cursor()
        result = cursor.execute(sql_insert_query)
        connection.commit()
        print ("Record inserted successfully into table")  except mysql.connector.Error as error :
        connection.rollback() #rollback if any exception occured
        print("Failed inserting record into table {}".format(error))  finally:
         #closing database connection.
        if(connection.is_connected()):
            cursor.close()
            connection.close()
            print("MySQL connection is closed")

I have try below code but it said:
"Failed inserting record into table 1054 (42S22): Unknown column 'my_trans' in 'field list'"

A: use .executemany to insert array of records as mentioned here
my_trans = []
my_trans.append('car', 200)
my_trans.append('train', 300)
my_trans.append('ship', 150)
my_trans.append('train', 200)

sql_insert_query = 'INSERT INTO my_transport
                               (transport, fee) VALUES (%s, %s)'
cursor = connection.cursor()
result = cursor.executemany(sql_insert_query, my_trans)