text:
Q: What is a suitable replacement for the SQL Like operator to increase performance? I'm working on an application that runs on Windows Mobile 6 that needs to be able to retrieve all items from an item table that contain a given string (provided by the end user) within the item's description field. The problem is that there are approximately 170,000 items in the table. Since I need to return all items that contain the string anywhere within the description I'm forced to use a LIKE %string%, which eliminates any chance to use the index. The data and table structure are originally based on a Progress database, which has a wonderful contains operator on any word-indexed fields. This is not the case on our mobile application, since it uses SQL Server Compact 3.5.
Basically, my DAL runs the query and retrieves an SqlCeDataReader and then uses an ItemFactory to create a List object that contains only the matched items. This obviously lets us keep our domain/business objects separate from the data access layer.
Fine and dandy, except for the 8m and 42s that it takes to retrieve items when I search for all items that contain something like "golf" in the description. Obviously this is not an acceptable time frame for the end user.
My first attempt was to instead retrieve all items back from the database using SELECT * FROM Item" (with an order by clause on one of the main indexed fields). At this point I ran an IndexOf check as I ran through the SqlCeDataReader and had the ItemFactory only add items to the List object if they contained the requested description text. This improved the speed down to 1m 46s. Not too shabby, but still too slow.
I then tried another approach that showed promise... almost... While the application starts up, I tried creating a List that contained all item objects within the database (takes about 2 minutes to run the query and populate the entire list, but at least it's only once as the app is initializing... still... ugh). Once the list is complete, I can easily run queries on that list doing things such as the following (I hope my syntax is right... I'm not at work right now and I don't have Visual Studio on the pc I'm sitting at):
List<Item> specificItems =
    AllItems.FindAll(i => i.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0);

This approach knocked it down to 21s. Very nice (still slow though in the grand scheme of things). However, the problem is that the memory usage is way too great if I load all the items from the database. I had to actually cut off the last 20,000 items (so the 21s time frame probably would have been more like 25s) during the initial load, because an OutOfMemoryException was being thrown. According to the memory manager on the emulator, I still had about 20 MB of free RAM, but I've heard that a process can only have 32 MB or RAM associated to it (not sure if that's true for WM 6, but it appears so).
To make sure it wasn't because I was using a List object to hold all the items (which I was instantiating with the needed capacity in its constructor to avoid dynamic resizing), which I've also read may cause extra memory usage when it implicity calls EnsureCapacity, I tried using an Item[] array (sized ahead of time). This still had the memory issue and the size difference was negligible.
Ok enough rambling. I know I'm likely going to have to some how limit the records returned from the database by the datareader (through some indexed search on a different type of field) and then will likely use indexOf on that smaller subset of items to get maximum performance (thus skipping the Like operator all together). This will cause the end user to have to enter more than just a description search though (perhaps item hierarchy information to limit which type of items to search within).
Any ideas? Am I going about this the wrong way?
Thanks for listening (sorry this post is long, I'm kind of thinking out loud).
Oh I should add (just in summary) what I'm using:

*

*Windows Mobile 6

*Sql Server Compact Edition 3.5

*C# 3.5

UPDATE: While the Bloom Filter approach mentioned below seemed interesting, I could not fulfill one requirement (which I didn't really specify above). I can't really match words that are contained inside other words (e.g. "club" would not return "clubs"). Due to this, I was forced to use a different approach altogether (Kent Fredric... thanks for pointing this out). I've marked Kent's answer as the correct one, since his approach was the one that filled the most requirements (Mitch, your's had a similar issue as the Bloom filter suggested by Jaunder). However, I have gone a different approach (for now...) than his way as well.
What I've done is pulled all item objects into memory, with only item numbers and descriptions (which keeps it under the memory limitations, however it still does cause a longer initialization than I like... multithreading and loading that information behind the scenes while the application is running can take care of that I guess). To perform the searches I've written my own contains routine. The routine is written in unmanaged c# code that uses two pointers and a couple of loops to run through the description and the required matching text. If it finds a match anywhere in the description, it adds the item number to an array. Once all items have been searched, a new query goes back to the database and grabs only the matching item numbers (which is very fast due to the index on an integer field). Then those items are created in a List with all information (not just the item number and description). The whole operation takes approximately 5 - 10 seconds (depending on the description), which is good enough for now.
I'll still look into further optimizing this (might be able to track how many characters the search term is... if there are less characters remaining on the item description than the required text, the loop could continue straight to the next item).
Any suggestions are still welcome. For now I have marked Kent's answer as "the most correct" for my question.
Props to Dolch for helping me write the contains routine.

A: How about pre-processing (once) the items table (and each new entry added to it would need to be processed), to create a word occurrance table having
CREATE TABLE WordItemOccurance
(
    [Word] varchar(50) not null,

    ItemId int not null
        constraint FK_Items references ItemTable(ID)
)

Iterate over all your items, break into separate words and add entries to the occurance table as they are found.
Creating a clustered index on [Word] and joining to the Item table on ItemId should be fast.

A: I voted for Mitch Wheat's answer, but there are a few tricks I would also test for effectiveness.
My big worry about having a table full of  [char],[int]  is you may still find yourself executing large volumes of pointless string comparisons, especially if you use %word% on this new table. ( Duplicated but not-matching-our-search entries ).
I would probably opt for experimeting with
Words
-----
chars  | word_id

WordsToEntry
------------
word_id | entry_id

and see if the database overhead is a worthy mitigation of this possible problem ( I cant  test, sorry )

A: You could try using a bloom filter.

*

*wikipedia

*using bloom
filters


text:
Q: three.js animation above image - javascript http://ignite.la/advance1/
on the above URL, you can see the stars animation and the sphere reflecting the animation.
what i want to achieve, is
, meaning that the reflecting sphere, is shown on the astronauts helmet. i cant seem to find any workaround to do it...
any tips or guidance would be great.
the astronaut is missing the webpage, find it here.
https://i.imgur.com/2BtPgXh.png
thanks in advance.

A: You don't need to render it above the image if you make the shade of the helmet in the image transparent. At least that sounds like the easiest way to go here.
So you would replace the black color of the helmet with transparency (keep the rteflections of the arms and shoulders in there, partly transparent) and render the reflections along with the rest of the three.js-scene behind that.
Otherwise you'd need to very accurately fit the reflection onto the helmet (maybe using the stencil-buffer or something like that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel 4 - routing - repeating segments in URL I have this URL:
example.org.ch/c123-Category-One

Where '123' is category ID which I need to pass to controller. Routing rule is:
Route::get('/c{id}-{slug}', [
  'as' => 'category.index',
  'uses' => 'Company\Package\CategoryController@view',
])->where('id', '[0-9]+');

But I can have subcategories:
example.org.ch/c123-Category-One/c234-Category-Two
example.org.ch/c123-Category-One/c234-Category-Two/c567-Category-Three
..
example.org.ch/..X-LEVELS../c2846-Category-X

For these I tried this routing rule:
Route::get('{path}/c{id}-{slug}', [
  'as' => 'category.index',
  'uses' => 'Company\Package\CategoryController@view',
])->where(['path' => '.*', 'id' =>'[0-9]+']);

It works for 2nd level category and more but not for: example.org.ch/c123-Category-One
Is possible to have one rule for all cases?


text:
Q: how to join two lists with their respective values So I have two lists
a_List = [24.6781, 23.4512, 26.4623, 16.9619, 17.7685]
a_List2 = [3000.0, 500.0, 900.0, 900.0, 3000.0]

where I want the values of a_List2 to be connected to a_List to get a desired output of
1-3000 2-900 3-3000 4-500 5-900

Where position 3 has the largest values of a_List2 and position 4 has the smallest value of a_List2
basically connecting the two lists with their respective values while maintaining the correct indexes of a_List, keep in mind that the position of the values could differ.
the value 26.4623 is the highest value in a_List so it should be connected to the highest value in a_List2 which is 3000
the value 24.6781 is the second-highest so it should be connected to the second-highest value in a_List2 which is 3000
the value 23.4512 is the third-highest so it should be connected to the third-highest value in a_List2 which is 900
and so on.
then I need to print out the connected values from a_List2 in the correct order of indexes of a_List
        for i in range(routers):
            a_dict.update({max(a_list) : max(a_list2)})
            router_list.remove(max(a_list2))
            a_list.remove(max(a_list))
        for x in a_dict.values():
            other_count+=1
            print(str(other_count)+"-"+str(int(x)), end= " ")
a_dict = {}
routers = 5 since we have 5 routers in this particular case

which will give me the semi correct output of
1-3000 2-3000 3-900 4-900 5-500

but it doesn't keep the structure if a_List which is what I need

Also not allowed to use any built in python sort() function.

A: What I think you're asking
Given two lists of the same length, how can I sort one using the values of the other?  For example:
to_show = ['a', 'b', 'c', 'd']
to_sort = [100, 200, -50, 700]
assert MAGIC() == ['c', 'a', 'b', 'd']

How to go about this
Indeed, you can get a sorted version of one list using the other very simply.  Let's use sorted since it doesn't modify anything in place, which is friendly.  There are many possible approaches, one might look like the below:
>>> [b for a, b in sorted(zip(to_sort, to_show))]

a "clever" version of this might look like:
>>> zip(*sorted(zip(to_sort, to_show)))[1]
('c', 'a', 'b', 'd')

How this works
This does a couple of things, it first groups your two lists together using zip
>>> zip(to_sort, to_show)
[(100, 'a'), (200, 'b'), (-50, 'c'), (700, 'd')]

it next sorts those values.  Python sorts tuples based on the first, then the second, then the third, etc.  This means we sort first by to_sort, and would break ties based on to_show (no ties with our data).
>>> sorted(zip(to_sort, to_show))
[(-50, 'c'), (100, 'a'), (200, 'b'), (700, 'd')]

In our clever version we call zip(* ...) to "unzip" that data back into two lists:
>>> zip(*sorted(zip(to_sort, to_show)))
[(-50, 100, 200, 700), ('c', 'a', 'b', 'd')]

and grab the second list, to_show (now sorted) using a list index:
>>> zip(*sorted(zip(to_sort, to_show)))[1]
('c', 'a', 'b', 'd')

Alternative approach using key=
>>> [v for i, v in sorted(enumerate(to_show), key=lambda i_v: to_sort[i_v[0]])]
['c', 'a', 'b', 'd']

You may prefer is to use the key keyword argument to sort or sorted.  The goal will be to say "when you sort item 1 of to_show, just look at to_sort instead".  To do this we will include the index, and then strip it out afterwards.
We use enumerate to give us the index with the value
>>> sorted(enumerate(to_show), key=lambda i_v: to_sort[i_v[0]])
[(2, 'c'), (0, 'a'), (1, 'b'), (3, 'd')]

and can then follow the same processing as above (zip or comprehension) to extract the value (this time the 0 index instead of the 1).
Note that there is no function of the form below (i.e. ignoring indexes)
>>> sorted(to_show, key=magic(to_sort))

that can exist, a lookup from values in to_show to to_sort will have trouble with duplicate values in to_show.


text:
Q: Cannot set width and height of cloned element I cloned an image element using JS. I can move it around by setting the left and top attributes of the clone. However I cannot change the size.
var sprite_org = "WEs1";
var sprites = new Array(7);

var org = document.getElementById(sprite_org);
sprites[0] = org;

for (var i=1; i<7; i++) {
    let clone = org.cloneNode(true);
    clone.setAttribute( 'id', "Sprite" + i );
    org.parentNode.appendChild(clone);
    sprites[i] = document.getElementById("Sprite"+i);
    sprites[i].style.top = "0px";
    sprites[i].style.width = "500px";
}

A: Try cleaning this up a bit.
for (var i=1; i<7; i++) {
    let clone = org.cloneNode(true);
    clone.setAttribute( 'id', "Sprite" + i );
    clone.style.top = "0px";
    clone.style.width = "500px";
    sprites[i] = clone;
    org.parentNode.appendChild(clone);
}

Also images have width and height "attributes" not just the css styling of them:
clone.width = 500;
clone.height = 300;

A: Got it working with
for (var i=1; i<7; i++) {
    sprites[i] = org.cloneNode(true);
    sprites[i].style.left = i*200+"px";;
    document.getElementById("WEbggroup").appendChild(sprites[i]);
}


text:
Q: superset cannot query the kylin's data? I link to kylin datasource and kylin's data can preview in sqllab,when enter the sql in sqllab,click the run query button,query status always pending and http reponse like
{"query": {"changedOn": 1574996199515.888, "changed_on": "2019-11-29T02:56:39.515888", "dbId": 4, "db": "Kylin", "endDttm": null, "errorMessage": null, "executedSql": null, "id": "5H-DGzWuw", "limit": 1000, "progress": 0, "rows": null, "schema": "DEFAULT", "ctas": false, "serverId": 59, "sql": "select a.country,a.name from DEFAULT.KYLIN_COUNTRY ", "sqlEditorId": "k7GQtMhzk", "startDttm": 1574996199504.259033, "state": "pending", "tab": "Untitled Query", "tempTable": "", "userId": 1, "user": "admin user", "resultsKey": null, "trackingUrl": null, "extra": {}}}

how do I resolve it?

A: Resovled,the datasource choosed asynchronous query.


text:
Q: Heap size that mono develop uses I am using macOS x64 and I got OutOfMemoryException while my computations. I need 1.8GB.
Hpw can I increase the heap size in Xamarin Studio (mono develop)?
I tried
export MONO_GC_PARAMS=max-heap-size=2g

but it's now working


text:
Q: onclick() fails after changing javascript version I accidentally changed Javascript version on Webstorm from ECMAScript 6 to flow.
All onclick() functions like the following defined in html and in javascript stopped working.
<div class="just-me" onclick="helloworld();">

Gives the following error,

Uncaught ReferenceError: helloWorld is not defined

I tried to use following approaches,
javascript:
document.getElementbyId('test').addEventListener('click', helloWorld);

jquery:
$("#test").on('click', helloWorld);

I tried to use console.log() but nothing is printed in console.
Problem isn't solving even after reverting back to ECMA 6.
Edit: helloWorld() is defined and in the scope. This issue happened after javascript version was changed to flow everything worked fine before that.

A: The function helloWorld should be defined before using it in addEventListener() or on().

A: Call your function like this.
$("#test").click(function() { helloWorld() });

You have to call it inside click wrapper.


text:
Q: Get timeZone information from date with date with offset value we have the below date having offset -07, which belong to "US/Pacific" time zone.
String startTime = "2020-06-12T09:30:00.000-07:00";

I want to retrieve timezone info ("US/Pacific") from above date object.

A: You can get a list of zones that have a -7h offset at that particular moment in time, but it will not be unique. For example you could use this code:
String bookingStartTime = "2020-06-12T09:30:00.000-07:00";
OffsetDateTime odt = OffsetDateTime.parse(bookingStartTime);
Set<String> allZones = new HashSet<>();
for (String z : ZoneId.getAvailableZoneIds()) {
  ZoneId id = ZoneId.of(z);
  ZonedDateTime zdt = odt.atZoneSameInstant(id);
  if (zdt.getOffset().equals(odt.getOffset())) allZones.add(z);
}

for (String z : allZones) System.out.println(z);

And the output is:

US/Pacific-New
  America/Tijuana
  SystemV/PST8PDT
  US/Arizona
  America/Santa_Isabel
  Canada/Yukon
  Canada/Pacific
  America/Creston
  America/Phoenix
  America/Dawson_Creek
  America/Los_Angeles
  America/Whitehorse
  America/Ensenada
  America/Dawson
  PST8PDT
  America/Hermosillo
  America/Vancouver
  SystemV/MST7
  Etc/GMT+7
  America/Fort_Nelson
  US/Pacific
  Mexico/BajaNorte

A: You can parse the String to an OffsetDateTime (knows offset only), extract the ZoneOffset from it, use it to compare a ZonedDateTime (knows zone and offset) for every available ZoneId with this offset and store the ones with equal offsets.
The following method gives you a list of possible ZoneIds for an OffsetDateTime parsed from the String you have:
private static SortedSet<String> getAllZoneIdsFor(OffsetDateTime offsetDateTime) {
    // initialize a data structure for the result
    SortedSet<String> result = new TreeSet<>();
    // extract the zone offset from the given OffsetDateTime
    ZoneOffset zoneOffset = offsetDateTime.getOffset();

    // then check all available zone ids for a matching offset
    for (String zone : ZoneId.getAvailableZoneIds()) {
        // create a ZoneId object from the string
        ZoneId zoneId = ZoneId.of(zone);
        // create a ZonedDateTime from the given LocalDateTime adding the zone
        ZonedDateTime zonedDateTime = offsetDateTime.atZoneSameInstant(zoneId);
        // and check if the extracted offset equals the one of the current zone
        if (zonedDateTime.getOffset().equals(zoneOffset)) {
            // and add the zone id to the result if it does
            result.add(zoneId.toString());
        }
    }

    return result;
}

You would use it in a main() like this
public static void main(String[] args) {
    // take the offset dateime string
    String bookingStartTime = "2020-06-12T09:30:00.000-07:00";
    // parse it to an OffsetDateTime
    OffsetDateTime offsetDateTime = OffsetDateTime.parse(bookingStartTime);

    // get the zones with the offset of the given OffsetDateTime
    SortedSet<String> matchingZones = getAllZoneIdsFor(offsetDateTime);
    // and print them all
    matchingZones.forEach(System.out::println);
}

and see the output
America/Creston
America/Dawson
America/Dawson_Creek
America/Ensenada
America/Fort_Nelson
America/Hermosillo
America/Los_Angeles
America/Phoenix
America/Santa_Isabel
America/Tijuana
America/Vancouver
America/Whitehorse
Canada/Pacific
Canada/Yukon
Etc/GMT+7
Mexico/BajaNorte
PST8PDT
SystemV/MST7
SystemV/PST8PDT
US/Arizona
US/Pacific
US/Pacific-New

Please note you won't be able to find a particular ZoneId just providing an offset. You would need more information (e.g. the system locale) in order to determine a specific zone for a given offset.


text:
Q: Pandas ignore many rows when reading csv I have a dataset with more than 1,000,000 rows.
However, read_csv cannot read them all.
products = pd.read_csv("PAD_NEW.csv", encoding = "ISO-8859-1", error_bad_lines=False)
products.shape
(859971, 137)

But in r using fread, i can get 1048575
> dim(products)
[1] 1048575     137

I tried to read using R first then write a new file for Python. But it did not work.
UPDATE: I manually check those rows being ignored, there is a column named description and there are sentences like "new product, next week" I think python take the "," in this column as a separate. Because after I delete this column it works.


text:
Q: Mono addin doesn't load if initialized from autocad I've a quite complex application, this application is structured like so:
Main.exe (is a standalone application)
Main.exe uses Project1.dll (which contains a form)
the form contained inside the Project1.dll is extended by another dll (Project2.dll) using mono.addins
In Main.exe I can see the form extended in the correct way.
I've also implemented an autocad connector (say Project3.dll) which is loaded via netload inside autocad, this connector uses the form of Project1.dll and that form has to be extended also in autocad.
The result is that inside autocad my form appears not extended, and if I debug the code:
        AddinManager.Initialize();
        AddinManager.Registry.Update(null);

        foreach (IMyPlugin Addin in AddinManager.GetExtensionObjects(typeof(IMyPlugin)))
        {
            if (Addin.IsPluginLicensed)
                EmbedPlugin(Addin);
        }

the foreach doesn't yield any addin.
Notice that each of those .dll are stored in the same directory.
I suppose that the problem resides in the different location of the autocad exe file but I've tried some tweaks and none works..
I've tried:

*

*create an .addins file that contains the .dlls path.

*create a subfolder \addins\ with a copy of all the .dlls

*initialize the AddinManager giving the .dll path

*update the AddinManager.Registry giving the .dll path

the code structure is quite complex (involves many files and projects) so is not so easy to paste or give some working code.

A: I've solved the problem. Mono.Addins was loaded from LoadFrom context and this has led to a DllHell problem. Manually loading Mono.Addins like described here solved the problem.


text:
Q: How can I see the id (and "name") of a CKAN entity (to be used in API update calls)? When looking at the API for updating Packages, Groups, Organizations, or Users, I see that one of the input args is

id (string) – the name or id of the user to update

(https://docs.ckan.org/en/2.9/api/index.html#ckan.logic.action.update.package_update). What are the different ways that I can see the "id" of a CKAN user/org/package? The "name"?
Are the IDs just the URL component of the CKAN object that I see when I am, say, updating an Organization? Eg...

Just from looking at the API docs here (https://docs.ckan.org/en/2.9/api/index.html#ckan.logic.action.update.resource_update) and older examples here (https://docs.ckan.org/en/ckan-1.7.2/api-tutorial.html), the IDs appear to be UUIDs, but I don't know how I would know these values from the CKAN web UI. And is the "name" the name as shown when I, say, view the dataset/Package in the web UI or is it as shown in the URL when looking at the Package (as in the image shown above)?
Could anyone provide more clarity on this? Is this explained somewhere in the docs?

A: It depends on what Id/Name you looking, you can query or list them I use rest api like this on ckan 2.8+:
organizations:
ckan-server:5000/api/action/organization_list

groups:
ckan-server:5000/api/action/group_list

packge:
ckan-server:5000/api/action/package_search

you need to set header with api_key (will be deprecated soon).
also some api calls supports name instead of id, so if you willing to update any it will address by name if pressent on request.
the best is first search by name or partial name, then extract id from response.


text:
Q: recursion c# how it works? I wanted to get the summary of all array elements by using recursion
Here is the code.
   static int SummaryOfArray(int[]myArray, int i = 0, int result = 0)
    {

        result += myArray[i];
        i++;
        if (i >= myArray.Length)
        {
            return result;
        }
        else
        {
          SummaryOfArray(myArray, i,result);     //<---if I put the "result =" on the top here
            return result;
        }

    }

    static void Main(string[] args)
    {

        int[] arr = { 3, 2, 5};

        Console.WriteLine(SummaryOfArray(arr));
    }

If I put the "result =" on the front of the code my program works well and gives
the correct summary of the array elements,
but if I delete it gives me "3" as the result.
But why??? I don't understand at all, I watched lots of materials and videos
about the recursion, but I still do not understand why.
I understand the "last in last out" but why does the "result" changes from 10 to 3
at the end?

A:    static int SummaryOfArray(int[] myArray, int i = 0, int result = 0)
{
    if(myArray.Length == i) return result;
    else  return  SummaryOfArray(myArray,i+1,result+myArray[i] );
}

Try it.


text:
Q: How do I loop an array in imacros? I would like to loop "pin_board" and replace the "boardarray" every time it loops.. here is the code below..`
var boardarray = ['board1', 'board2', 'board3', 'board4', 'board5'];

var text = 'pin_board';

for(var i in boardarray) {

pin_board = "CODE:";
pin_board += "VERSION BUILD=8300326 RECORDER=FX" + "\n";
pin_board += "TAB T=1" + "\n";
pin_board += "TAG POS=1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
pin_board += "WAIT SECONDS=3" + "\n";
pin_board += "TAG POS=1 TYPE=LI ATTR=TXT:" + boardarray + "\n";
pin_board += "WAIT SECONDS=3" + "\n";
pin_board += "TAG POS=R1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
pin_board += "WAIT SECONDS=5" + "\n";

}
iimPlay(pin_board);

Thanks for the reply @karaxuna.. I modify my script and tried it on imacros.. unfortunately, it only loop once and instead of starting with board1 it started and ends in baord5. So it only run once. I don't know if I miss something.
Here is the edited code..
var boardarray = ['board1', 'board2', 'board3', 'board4', 'board5'];

var text = 'pin_board';

for(var i = 0; i < boardarray.length; i++)
{
pin_board = "CODE:";
pin_board += "VERSION BUILD=8300326 RECORDER=FX" + "\n";
pin_board += "TAB T=1" + "\n";
pin_board += "TAG POS=1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
pin_board += "WAIT SECONDS=3" + "\n";
pin_board += "TAG POS=1 TYPE=LI ATTR=TXT:" + boardarray[i] + "\n";
pin_board += "WAIT SECONDS=3" + "\n";
pin_board += "TAG POS=R1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
pin_board += "WAIT SECONDS=5" + "\n";

}
iimPlay(pin_board);

thanks,

A: for(var i = 0; i < boardarray.length; i++)
{
    //...
    pin_board += "TAG POS=1 TYPE=LI ATTR=TXT:" + boardarray[i] + "\n";
}

Don't use for in for arrays, use it for objects to list it's properties
EDIT
var boardarray = ['board1', 'board2', 'board3', 'board4', 'board5'];

var pin_board = '';

for(var i = 0; i < boardarray.length; i++)
{
    pin_board += "CODE:";
    pin_board += "VERSION BUILD=8300326 RECORDER=FX" + "\n";
    pin_board += "TAB T=1" + "\n";
    pin_board += "TAG POS=1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
    pin_board += "WAIT SECONDS=3" + "\n";
    pin_board += "TAG POS=1 TYPE=LI ATTR=TXT:" + boardarray[i] + "\n";
    pin_board += "WAIT SECONDS=3" + "\n";
    pin_board += "TAG POS=R1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
    pin_board += "WAIT SECONDS=5" + "\n";
}

A: "...unfortunately, it only loop once and instead of starting with board1 it started and ends in baord5. So it only run once. I don't know if I miss something."
of course, cuz for do the work and then run iimPlay(pin_board);
if you want to run every time - just put iimPlay(pin_board); in the for
for(var i = 0; i < boardarray.length; i++)
{
    pin_board += "CODE:";
    pin_board += "VERSION BUILD=8300326 RECORDER=FX" + "\n";
    pin_board += "TAB T=1" + "\n";
    pin_board += "TAG POS=1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
    pin_board += "WAIT SECONDS=3" + "\n";
    pin_board += "TAG POS=1 TYPE=LI ATTR=TXT:" + boardarray[i] + "\n";
    pin_board += "WAIT SECONDS=3" + "\n";
    pin_board += "TAG POS=R1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
    pin_board += "WAIT SECONDS=5" + "\n";
    iimPlay(pin_board);
}

A: Do you guys read wiki.imacros.net ?
var boardarray = ['board1', 'board2', 'board3', 'board4', 'board5'];

var pin_board = '';

for(var i = 0; i < boardarray.length; i++)
{
    pin_board += "CODE:";
    pin_board += "VERSION BUILD=8300326 RECORDER=FX" + "\n";
    pin_board += "TAB T=1" + "\n";
    pin_board += "TAG POS=1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
    pin_board += "WAIT SECONDS=3" + "\n";
    pin_board += "TAG POS=1 TYPE=LI ATTR=TXT:{{board}}" + + "\n";
    pin_board += "WAIT SECONDS=3" + "\n";
    pin_board += "TAG POS=R1 TYPE=BUTTON ATTR=TXT:Pin<SP>it" + "\n";
    pin_board += "WAIT SECONDS=5" + "\n";

iimSet("board", boardarray[i])
iimPlay(pin_board);
}

http://wiki.imacros.net/iimSet


text:
Q: What could restrict dataflow pipeline to only using a single worker? I've been trying to debug a pipeline which takes a input parameter that drives subsequent ParDo operations. For reasons that I cannot fathom, the pipeline will not scale beyond a single worker even though I've disabled autoscaling and set the number of workers. Sadly the abysmal dataflow interface on GCP does little to illuminate the inability to scale. Can anyone advise as to what might be the issue or how to debug effectively?
with beam.Pipeline(options=opts) as p:
  result = (
      p | "Initialize Pipeline" >> beam.Create(
          [(f'gs://data/']) |
      "Scan for extraction tasks" >> beam.ParDo(scanner.ScanForTasks()) |
      "Extract data" >> beam.ParDo(worker.TaskToData()))

A: The problem turned out to be related to an optimization in dataflow called 'fusion' in which adjacent operations are fused together, presumably so that they can run seamlessly on the same worker. The problem is that if a pipeline is seeded by a single item which generates a large number of downstream tasks, all these tasks will then be processed on the same worker that handled the initial seeding task.
The solution is to seed the pipeline directly with the tasks to prevent this 'optimization' from killing performance
def scan_for_tasks():
  tasks = []
  # Build your task list here
  return tasks

with beam.Pipeline(options=opts) as p:
  result = (
    p | "Initialize Pipeline" >> beam.Create(scan_for_tasks()) |
    "Extract data" >> beam.ParDo(worker.TaskToData()))


text:
Q: Svelte: doesn't work inline css animation Doesn't work inline css animation like this:

Hello {name}!

https://svelte.dev/repl/e32b72cb98cb4b78a47b1bcb1ecab9e9?version=3.53.1
But if delete style attribute

Hello {name}!

and add
.test
    background: yellow;
    animation: bg 2s linear infinite;
}

It works!
But I want to add animation as inline style.

A: Everything within a component style is scoped to the component by default and the inline style apparently is not recognized as referring to the defined @keyframes.
Regular selectors can be made global using :global() around the selector but for @keyframes you would have to prefix the name with -global- (which is removed again on compilation).
@keyframes -global-bg { ... }

REPL
Note that this really is defined as global then and any other component that defines global keyframes with the name bg will cause interference.


text:
Q: @rollup/plugin-node-resolve throws error: Cannot read property 'length' of undefined I got this error and it comes from @rollup/plugin-node-resolve
[!] TypeError: Cannot read property 'length' of undefined
TypeError: Cannot read property 'length' of undefined
//...
at async Promise.all (index 0)
at async Promise.all (index 2)
at async Promise.all (index 0)
at async Promise.all (index 0)
at async Promise.all (index 0)

This is my config. I can confirm the error is coming from @rollup/plugin-node-resolve
const config = {
  input: './build/sw.js',
  //Other configs
  }],
  plugins: [
    nodeResolve(),
    commonjs({
      include: ['./src/**', 'node_modules/**']
    })
  ]
}

I am importing the following workbox dependency in my sw.js
workbox-core
workbox-precaching
workbox-routing
workbox-strategies
workbox-expiration
workbox-background-sync
How can I tackle this error?

A: Not 100% sure about the cause of this issue, but I found out that if I dont explicitly install Rollup in my packages, the version of Rollup you would get with npx rollup -v is 1.x.x. Upgrading it to 2.x.x would fix this error.


text:
Q: Docusign - using two different email body/blurb contents Hello I have setup our app using the dev/demo account and almost ready to get a paid account. I want to get a starter API account, which doesn't have Branding.

*

*Can I remove the Resource File from the email body without having access to branding? Any other way?

*I would like to setup one email body/blurb for the signing email and a different for the completed email. Again without branding would I be able to do that?

I have been able to add customize/add html into the signing email body but would like to add a new condition somehow for the completed
something like envDef.EmailBlurbCompleted =
thank you

A: There's only one emailBlurb field in DocuSign right now. That field is used in both the original as well as the final email that are sent out. You can customize it per recipient, which is not exactly what you're asking for.
You can change it after the envelope is created, but only if it's still in draft status.
Changing this field when an envelope is in sent status requires a correct operation. Which is also not exactly what you are asking to do.
At the moment what you're asking is not a feature that exist, you can build something to mimic this, but I'm not sure that is a good idea either.


text:
Q: How can I find all records where $type of field not equal 'date'? I want get all records from collection, there deleted is not true, and $type of 'startDate' or 'endDate' is not 'date'. I am trying to use this find query:
{
        '$and' :
            {
                {'deleted' : {'$ne' : true}},
                {
                    '$or' :
                        {
                            {'startDate' : {'$type' : {'$ne' : 'date'}}},
                            {'endDate' : {'$type' : {'$ne' : 'date'}}},
                        }
                }
            }
    }

But I get error: "argument to $type is not a number or a string". How can I get desired result?

A: Your $type and $ne are the wrong way round. Try something like this:
{
  $and: [
    { deleted: { $ne: true } },
    {
      $or: [
        { startDate: { $not: { $type: "date" } } },
        { endDate: { $not: { $type: "date" } } }
      ]
    }
  ];
}

I've changed the order of $type and $ne and changed $ne to $not. I've also swapped out the objects for arrays in your $and and $or queries.


text:
Q: How to insert array variable from Python to Javascript I have this issue passing the data from an array variable to the python javascript function. Below is the entire script
 array1 =[['X-val', 'Y-val'], [4, 5], [8, 12], [11, 14]];

self.response.out.write('<script type="text/javascript">'+
                        'google.load("visualization", "1", {packages:["corechart"]});'+
                        'google.setOnLoadCallback(drawChart);'+
                        'function drawChart() { '+
                        'var data = google.visualization.arrayToDataTable({0});' +
                        'var chart = new google.visualization.LineChart(document.getElementById("casestrend"));chart.draw(data);} '+
                        '</script> '.json.dumps(array1))

This is the javascript code which i want to convert to the python format wherein the array required for arrayToDataTable() will be fetched through queries. Currently static version of it (array1 above) doesn't work
<script type="text/javascript">
 google.load("visualization", "1", {packages:["corechart"]});
 google.setOnLoadCallback(drawChart);
 function drawChart() {
 var data = google.visualization.arrayToDataTable([['X-val', 'Y-val'], [4, 5], [8, 12], [11, 14]]);
 var chart = new google.visualization.LineChart(document.getElementById('chart'));
 chart.draw(data);
 }
 </script>

Please let me know how to pass the data (array) from the python to the javascript so that the chart gets loaded.

A: Your current solution doesn't work because format (you missed it, right?) calls before strings concatenated.
In current case I would prefer concatenation over format to prevent braces escaping:
js_code = '''
          <script type="text/javascript">
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
          function drawChart() {
          var data = google.visualization.arrayToDataTable(''' + json.dumps(array1) + ''');
          var chart = new google.visualization.LineChart(document.getElementById("casestrend"));chart.draw(data);}
          </script>
          '''

A: This will work.
array1 =[['X-val', 'Y-val'], [4, 5], [8, 12], [11, 14]];

self.response.out.write("""<script type="text/javascript">
    google.load("visualization", "1", {{packages:["corechart"]}});
    google.setOnLoadCallback(drawChart);
    function drawChart() {{
    var data = google.visualization.arrayToDataTable({0});
    var chart = new google.visualization.LineChart(document.getElementById("casestrend"));chart.draw(data);}}
    </script> """.format(json.dumps(array1)))


text:
Q: Two Buttons with equal width in Constraint Layout How can I get two buttons side by side in ConstraintLayout with fixed and equal length?
Something like this:

A: Try this code..
<?xml version="1.0" encoding="utf-8"?>
<androidx.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/button1"
    android:text="Button 1"
    app:layout_constraintLeft_toLeftOf="parent"
    android:textAllCaps="false"
    app:layout_constraintRight_toLeftOf="@+id/guideline"
    />

<androidx.support.constraint.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5" />

<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/button2"
    android:text="Button 2"
    android:textAllCaps="false"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/guideline"
    />
 </androidx.support.constraint.ConstraintLayout>


text:
Q: How to see computer activity I am very very new to Ubuntu. I wish to know how to see user logs in Ubuntu. I realized that our son has been using his computer on days he's not supposed to. Apparently, he configured the computer that user logs are deleted so I don't see user logs except on the day the computer is turned on. Is there a way to see computer activity and which dates and time? I will really appreciate your responses.

A: Try this:
sudo nautilus

Inside of the window that opened click "computer" with the hard drive icon to the left of it. Open the folder named var, than open log, than double click auth.log, you will see a lot of information that you can ignore but focus on the date and times showing on the left hand side as you scroll down.


text:
Q: nextgen gallery - filenames' character encoding issue I am building a website using wordpress and i am planning to use Nextgen Gallery in order to show some pictures on a page.
My issue is, when i upload an image which has a filename containing greek characters, it doesn't show properly. Actually it doesn't show at all.
The filename on the server is saved as %ce%bf%cf%81%cf%84%ce%b1%ce%bd%cf%83%ce%b9%ce%b1
The img src on the page appears to be ok, as %ce%bf%cf%81%cf%84%ce%b1%ce%bd%cf%83%ce%b9%ce%b1.jpg
But the image doesn't show at all (is broken) and when i click "Open in a new tab", it returns the path of the image, but with the greek characters this time, like http://localhost/wordpress/wp-content/gallery/test/ορτανσια.jpg
How should i fix this issue?
Kind regards.

A: I would check the encoding on the database. Make sure it's set to utf-8 unicode
Edit:
Here is an article for more indepth reading:
http://www.informit.com/articles/article.aspx?p=328641
Also taken from here
The reason why I suggest you check the encoding is because if you insert something into a database with encoding set to ISO 8859-7 Greek, then it is going to interpret the characters as greek.


text:
Q: How to reverse bars on log scale in geom_col? library(tidyverse)

data <- structure(list(periodo = c("2T", "2T", "3T", "3T", "1T", "1T",
"3T", "3T", "4T", "4T", "1T", "1T", "2T", "2T", "3T", "3T", "4T",
"4T", "1T", "1T", "2T", "2T", "3T", "3T", "4T", "4T", "1T", "1T",
"2T", "2T", "3T", "3T", "4T", "4T", "1T", "1T", "1S", "2S", "1S",
"2S", "1S", "2S", "2S", "2S", "1S", "1S"), valor = c(0.005248075,
0.005128614, 0.0027195, 0.0151865, 0.002138615, 0.0154045, 0.00258683684210526,
0.010892, 0.02037825, 0.0232392666666667, 0.026491725, 0.0232410291666667,
0.026384125, 0.0232420416666667, 0.00438416666666667, 0.00122625,
0.0125198083333333, 0.00935866250000001, 0.00981484583333334,
0.0072391375, 0.0214400530654592, 0.0214486897415176, 0.0597089068767695,
0.0116124859053284, 0.00311100760334978, 0.00369158618252611,
0.02056125, 0.00690491666666667, 0.00277258333333333, 0.00211695833333333,
0.00235166666666667, 0.00235791666666667, 0.0176666666666667,
0.025125, 0.0236666666666667, 0.0212916666666667, 0.000170841666666667,
0.000172070833333333, 0.0005342625, 0.00141873333333333, 0.00107964166666667,
0.00191949166666667, 0.000509783333333334, 0.0013974, 0.002087,
0.000502616666666667), nombre = structure(c(4L, 2L, 4L, 2L, 4L,
2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L,
2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 3L,
3L, 3L, 3L, 4L, 1L, 2L, 4L, 1L, 2L), .Label = c("P-2", "R-5",
"E-3", "R-4"), class = c("ordered", "factor"))), row.names = c(NA,
-46L), class = c("tbl_df", "tbl", "data.frame")

chart
data %>%
ggplot(aes(periodo, valor, fill = nombre)) +
  geom_col(position = position_dodge2(width = 0.3, preserve = "single")) +
  scale_y_continuous(
    label_y,
    trans = "log10",
    limits = 10^c(-5, 0),
    breaks = 10^c(-5:0)
  )

Be default the bars are upside down, which is confusing because I read the column valor from bottom to top.

Expected output: I need the bars to be upside down like "normal".

A: Here's a hack where we shift the plotted values to be >1, then shift the labels the same amount:
(Btw I would second the comment that bar charts will be unavoidably misleading on a log scale, since we are taught to interpret length as proportional to value. geom_point might be a simpler choice here, avoiding the need for any adjustments.)
data %>%
  ggplot(aes(periodo, valor*1e5, fill = nombre)) +
  geom_col(position = position_dodge2(width = 0.3, preserve = "single")) +
  scale_y_continuous(name = "valor",
    trans = "log10",
    limits = 10^c(0, 5),
    breaks = 10^c(0:5),
    labels = scales::scientific(10^c(-5:0))
  )


text:
Q: add the value of a cell to another cell and then clear it I have been unable to find a way to create a kind a score tracker.
I want to have 2 cells... one to capture a value and one to keep a running total.
This is the scenario:
Cell B1 will contain a running total of points scored.
Cell A1 will allow the user to input a score.
I need The value entered in A1 to be added to the current total in B1.
Once B1 has been updated with the added value, cell A1 should be cleared to be ready for then next score.
Can this be done?
Thanks to all for any ideas you can offer.

A: Try this in the one of the worksheet modules ...
Private bIgnoreEvent As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
    If bIgnoreEvent Then Exit Sub
    bIgnoreEvent = True
    Cells(1, 2) = Cells(1, 2) + Cells(1, 1)
    Cells(1, 1) = ""
    bIgnoreEvent = False
End Sub

By all means try it without the bIgnoreEvent bit as follows so you can see why it is necessary. I recommend you do this after you have saved your current work ...
Private Sub Worksheet_Change(ByVal Target As Range)
    Cells(1, 2) = Cells(1, 2) + Cells(1, 1)
    Cells(1, 1) = ""
End Sub

... because it WILL CRASH EXCEL ... you have been warned!


text:
Q: getting values from Iframe to Spring MVC I have an requirement like we will show an Iframe in product details page. Then user will do some configuration and he clicks on Addtocart in the Iframe, I need to add the product to the our cart(spring MVC).
How this can be achievable? Even Though if they send a rest call to our Spring MVC machine we cannot able to add this item to the session cart and how we can refresh the storefront page to show the cart update?
The Iframe is an cross domain Iframe.


text:
Q: What's the best way to get selected rows from Telerik Grid back to controller I have a Telerik Grid from which I select rows.  I click a button which runs JavaScript to extract the grids selected rows (utilizing grid.selectedKeyNames()).
How can I now run a Post back to my controller?
The onSelectClick() javascript runs and I have the id's of the rows selected in the Telerik grid.
I have tried doing an Ajax call but no luck.
Controller:
public ActionResult Index()
    {

        return View(materialsListVM);
    }

    [HttpPost]
    public ActionResult Index(string selectedMatType, string selectedMaterials, string projectMaterialsList)
    {
        if (projectMaterialsList != null)
        {
            materialsListVM.LoadProjectMaterialsList(projectMaterialsList);
            //materialsListVM.projectMaterialsListVM.ProjectMaterialsList = JsonConvert.DeserializeObject<List<ProjectMaterialsListVM.ProjectMaterial>>(projectMaterialsList);
        }

        if (selectedMatType != null)
        {
            selectedMatType = selectedMatType.Trim();
            materialsListVM.SelectMaterialType(selectedMatType);
            ViewBag.SelectedMatType = selectedMatType;
        }
        materialsListVM.GetMaterials();

        if (selectedMaterials != null)
        {
            string[] materialIds = selectedMaterials.Split(',');
            foreach (string id in materialIds)
            {
                MoveToProjectMaterialsList(id, selectedMatType);
            }
        }
        ViewBag.ProjectMaterialsList = materialsListVM.projectMaterialsListVM.ProjectMaterialsList;

        return View(materialsListVM);
    }

View + JavaScript:
  @model MyProject.ViewModel.MaterialsListVM

<div id="CapWeld" style="display:block">
    @(Html.Kendo().Grid(Model.CapWeld_Materials)
                    .Name("gridCapWeld")
                    .Columns(columns =>
                    {
                        columns.Select().HeaderTemplate(" ").Width(40);
                        columns.Bound(c => c.MaterialId).Hidden();
            //columns.Bound(c => c.MaterialTypeName);
            columns.Bound(c => c.PcsPartNum);
                        columns.Bound(c => c.ClientPartNum);
                        columns.Bound(c => c.Type).Filterable(ftb => ftb.Multi(true));
                        columns.Bound(c => c.OuterDiameter).Filterable(ftb => ftb.Multi(true));
                        columns.Bound(c => c.WallThickness).Filterable(ftb => ftb.Multi(true));
                        columns.Bound(c => c.Specification).Filterable(ftb => ftb.Multi(true));
                        columns.Bound(c => c.Grade).Filterable(ftb => ftb.Multi(true));
                    })
                    //     .Events(ev => ev.Change("onChange"))
                    .Pageable()
                    .Sortable()
                    .Scrollable()
                    .TableHtmlAttributes(new { width = "90%" })
                    //.HtmlAttributes(new { style="height:500px"})
                    .PersistSelection(true)
                    .Filterable()
                    .DataSource(datasource => datasource
                    .Ajax()
                    .ServerOperation(false)
                    .Model(m => m.Id(d => d.MaterialId))
                    )
    )
</div>

<script>

    function onSelectClick() {
        var selected = $(':radio[name="MatType"]:checked').val();
        selected = selected.replace("{ Name = ", "");
        selected = selected.replace(" }", "");
        selected = selectedMatType.replace(" ", "");

        var grid = $('#grid' + selected).data('kendoGrid');
        var selectedMaterials = grid.selectedKeyNames().join(", ");

        alert(selectedMaterials);

       // window.location = '@Url.Action("Index", "MaterialsList")' + '?selectedMatType=' + selectedMatType + '&selectedMaterials=' + selectedMaterials;

    }
</script>

A: Here's what I did:
I removed the onclick event from the button and added jquery as follows:
<script type="text/javascript">
$(function () {
    $('#btnSelect').click(function () {
        var selected = $(':radio[name="MatType"]:checked').val();
        selected = selected.replace("{ Name = ", "");
        selected = selected.replace(" }", "");
        selected = selectedMatType.replace(" ", "");

        var grid = $('#grid' + selected).data('kendoGrid');
        var selectedMaterials = grid.selectedKeyNames().join(", ");

        $.ajax({
            type: "POST",
            data: { selectedMatType: selectedMatType, selectedMaterials: selectedMaterials },
            dataType: "json",
            url: '@Url.Action("Index", "MaterialsList")',
            success: function (result) {
                console.log(result);
            }
        })
    })
})

What's not shown is the partialview with the radiobuttons which also has javascript to set variable 'selectedMatType.  It was left out for simplicity.
Hope this helps someone.


text:
Q: C and Python integration: name of callback function I am working on a project which requires  Python with C integration. I have got it mostly working except for one issue below:
How do I get the string representation of the callback function object in the C code.  (See my comment in the code)
import mymodule
c=0

def double_it():
   c = c * 2
   return

def multiply(a, b):
   global c
   c = a*b
   mymodule.print_result(c, double_it)
   return

Where mymodule.print_result is defined as:
static PyObject*
print_result(PyObject* self, PyObject* args)
{
    PyObject *pCallBackFunc, *pArgs;
    int restult;
    char *func_name = NULL; // I want to fill this

    if (!PyArg_ParseTuple(args, "iO", &result, &pCallBackFunc))
    {
         printf ("ERRPR\n");
         return NULL;
     }

 if (PyCallable_Check(pCallBackFunc)) {
    Py_XINCREF(pCallBackFunc);

     // func_name = .... How to get the of the call back function that is "double_it" ???

   PyObject_CallObject(pCallBackFunc, pArgs);
   Py_XDECREF(pCallBackFunc);
   return Py_None;
}

Any help is greatly appreciated.

A: Same way you would do it in Python, but in C instead.
PyObject_GetAttrString(pCallBackFunc, "__name__")

A: You could look at how the func_get_name function is implemented.
So to access the name of a function simply use:
PyObject *
get_function_name(PyFunctionObject *fun) {
    Py_INCREF(fun->func_name);
    return fun->func_name;
}

To be used as:
if (!PyArg_ParseTuple(args, "iO", &result, &pCallBackFunc))
{
     printf ("ERRPR\n");
     return NULL;
}

if (PyFunction_Check(pCallBackFunc)) {

   func_name = get_function_name((PyFunctionObject *)pCallBackFunc);

   PyObject_CallObject(pCallBackFunc, pArgs);
   Py_RETURN_NONE;
}

However func_name is a PyObject *. So you'd have to also convert it into a char *.

Note: you do not want to use PyCallable_Check because only functions have a name. Other callables need not have it. If you want to be able to handle generic callables and obtain the name only in the case of functions you still have to explicitly check for PyFunctions and then for generic callables.

The above solution avoids the attribute lookup and thus it should be quite more efficient than calling PyObject_GetAttr*.


text:
Q: Изменить имя пользователя во время предпросмотра в TicketComments Здравствуйте, друзья!
Прикручиваю Tickets (TicketComments) на сайт под Modx Revo для комментариев и возникла вот какая сложность.
В форме для отправки комментария есть поле для ввода имени автора комментария
<input type="text" class="text form-control" name="name" id="comment-name" value="[[+name]]" placeholder="Ваше имя"/>

Когда пользователь не авторизован, то во время предпросмотра указывается значение из поля name выше. Когда же пользователь авторизован — указывается его полное имя из профиля.
Мой вопрос: где найти шаблон для вывода текста превью, чтобы поменять там имя на то, которое пользователь вводит в форме и если нельзя, то каким это сделать плагином? onBeforeCommentPublish?

A: Победил. Создал копию файла default.js у Tickets,поменял в системных настройках путь на путь до копии.
внутри файла нашел
comment: {
        preview: function(form,button) {

            //Сохраняю имя из формы коммента

            var trueName = $(form).find("#comment-name").val();

            $(form).ajaxSubmit({
                data: {action: 'comment/preview'}
                ,url: TicketsConfig.actionUrl
                ,form: form
                ,button: button
                ,dataType: 'json'
                ,beforeSubmit: function(formData, form, options) {
                    Tickets.comment.addAttachmentsToText(form, formData);
                    $(button).attr('disabled','disabled');
                    return true;
                }
                ,success: function(response) {
                    $(button).removeAttr('disabled');
                    if (response.success) {
                        $('#comment-preview-placeholder').html(response.data.preview).show();

                       //Меняю имя в тексте плейсхолдера

                        $('#comment-preview-placeholder').find('.ticket-comment-author').text(trueName);
                        prettyPrint();
                    }
                    else {
                        Tickets.Message.error(response.message);
                    }
                }
            });
            return false;
        }


text:
Q: importing Twilio on google app engine I've seen other similar questions but none of the solutions are working for me. I am trying to get Twilio working with Google App Engine. I am using the python API and can't seem to get it to work. I tried a few tactics:

*

*used pip install twilio

*downloaded the twilio file directly into my root directory

*sym linked the required files according to a few tutorials

nothing seems to work. When I write the line "import twilio.twiml" it makes the google app engine crash and say "error: server error:
What is the best way to import Twilio and load into the google app engine server?

A: From the docs

..you will need to add Twilio's Python library to your application.
  This involves installing some package management tools and the latest
  version of the Twilio Python module, then symlinking the library and
  its dependencies into your Google App Engine application:

*

*cd to the directory where your application is stored, this will be the helloworld directory you created if you followed the Getting
  Started guide.

*Install setuptools (installation instructions).

*Use setuptools to install pip:
$ sudo easy_install pip

*Use pip to install Twilio's Python library and dependencies:
$ pip install twilio

*Locate your site-packages directory. This is where pip installed the Twilio helper library:
$ python -c "import site; print(site.getsitepackages()[0])"

*Use the output of that command as the value of {SITE_PACKAGES} below to symlink the Twilio Python module to your application directory.
  First, link the Twilio library:
$ ln -s {SITE_PACKAGES}/twilio .

*Then link the Twilio Python module's dependencies:
$ ln -s {SITE_PACKAGES}/httplib2 .
$ ln -s {SITE_PACKAGES}/six.py .

You have now installed the Twilio library into your Google App Engine
  project.

You can then import twilio with for example
from twilio import twiml

A: You should use vendoring. The official documentation for Google App Engine with python also recommends using a virtualenv and installing third party libs into a subdirectory of the project root:
To install virtualenv:
$ sudo pip install virtualenv

Create a virtual environment somewhere outside your application directory. (These files should not be uploaded with your app code. Or you can create it in your project directory but will have to add a rule in your app.yaml to skip it.)
To create a virtual environment:
$ virtualenv <env_name>

$ source /path/to/<env_name>/bin/activate
$ cd <your_appengine_project_directory>
$ ln -s {virtualenv}/lib/python2.7/site-packages lib

This way a pip install in the virtualenv automatically goes to the lib directory as well.
$ pip install twilio

The docs then say to make an appengine_config.py file in the project root with the following content:
from google.appengine.ext import vendor
# Add any libraries installed in the "lib" folder.
vendor.add('lib')

This way a pip install in the virtualenv automatically goes to the lib directory as well.
You should thus be able to import twilio.twiml and take it on from there.

A: Thanks for the input. I had already tried all of these things. When I ran the app on a local host I saw in the console that the error I was facing was with 'pytz'
Turns out that Twilio requires the Pytz dependency to be in the root directory of Google App Engine. They have not updated the documentation yet.
Hope that helps anyone in the future.


text:
Q: How to override default Content-type I have a minimal-API ( Project Sdk="Microsoft.NET.Sdk.Web" ) app that has a GET endpoint that I would like to return an image/png.
The endpoint is:
app.MapGet("/text2img/{inputText}", (string inputText) => {
  var fileBytes = new ByteArrayContent(text2img(inputText).ToByteArray());
  var mimeType="image/png";
  var fileBytesArray = fileBytes.ReadAsByteArrayAsync().Result;
  return Results.File(new Microsoft.AspNetCore.Mvc.FileContentResult(fileBytesArray, mimeType).FileContents);
});

And it returns the correct bytes for a png-image, but the content-type is octet-stream:
HTTP/1.1 200 OK
Content-Length: 24975
Content-Type: application/octet-stream
Date: Fri, 22 Oct 2021 16:29:49 GMT
Server: Kestrel

How do I return the correct Content-type?

A: Results.File (at least in the latest version) has parameter for contentType you can just pass byte array and content type to it:
app.MapGet("/img", () =>
{
    var mimeType = "image/png";
    var bytes = ...
    return Results.File(bytes, contentType: mimeType);
});


text:
Q: JSON expected EOF, got ',' I was converting my JSON file into .csv and while converting there was such mistake as "expected EOF, got ','"
{
  "id": 22970,
  "type": "message",
  "date": "2018-11-24T21:08:21",
  "edited": "1970-01-01T03:00:00",
  "from": "lox",
  "from_id": 731504644,
  "text": "no"
 },
{
  "id": 22971,
  "type": "message",
  "date": "2018-11-24T21:08:32",
  "edited": "1970-01-01T03:00:00",
  "from": "Gox",
  "from_id": 417024817,
  "text": "ok"
 }

It shows that the comma after first block must be deleted,but when i delete it next { glows red. How could i format this so it will be normally converted?

A: Your JSON is incorrect with or without a comma.
I believe you are trying to have an array of objects with JSON. If so, the syntax should look like this
[ // Array of objects
    { // Object 1
      "id": 22970,
      "type": "message",
      "date": "2018-11-24T21:08:21",
      "edited": "1970-01-01T03:00:00",
      "from": "lox",
      "from_id": 731504644,
      "text": "no"
    }, // Comma separating array items
    { // Object 2
      "id": 22971,
      "type": "message",
      "date": "2018-11-24T21:08:32",
      "edited": "1970-01-01T03:00:00",
      "from": "Gox",
      "from_id": 417024817,
      "text": "ok"
    }
]

I recommend using any online JSON parser to check for syntax erros in the future.


text:
Q: CMake: how to use INTERFACE_INCLUDE_DIRECTORIES with ExternalProject? I'm trying to add external project as a library to my project using ExternalProject_Add:
ExternalProject_Add(
        xgboost
        GIT_REPOSITORY https://github.com/dmlc/xgboost.git
        GIT_TAG v0.60
        PREFIX ${CMAKE_CURRENT_BINARY_DIR}
        INSTALL_COMMAND ""
)

Also, I'm defining library target and adding external project as a dependency:
set(XGBOOST_PREFIX_PATH "${CMAKE_CURRENT_BINARY_DIR}/src")
set(XGBOOST_BINARY_PATH "${XGBOOST_PREFIX_PATH}/xgboost-build")
set(XGBOOST_BINARY_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/include;${XGBOOST_PREFIX_PATH}/xgboost/dmlc-core/include;${XGBOOST_PREFIX_PATH}/xgboost/rabit/include")
add_library(libxgboost IMPORTED STATIC GLOBAL)
add_dependencies(libxgboost xgboost)

set_target_properties(libxgboost PROPERTIES
        "IMPORTED_LOCATION" "${XGBOOST_BINARY_PATH}/liblibxgboost.dylib"
        "IMPORTED_LINK_INTERFACE_LIBRARIES" "${CMAKE_THREAD_LIBS_INIT}"
        "INTERFACE_INCLUDE_DIRECTORIES" "${XGBOOST_BINARY_INCLUDE}"
        )

in another CMakeLists.txt:
add_library(somelib STATIC SomeLib.cpp)
target_include_directories(somelib PUBLIC libxgboost)
target_link_libraries(somelib libxgboost)

The problem is that cmake INTERFACE_INCLUDE_DIRECTORIES doesn't allow to export include dir which does not exist.
Is there any other way to make header files being included automatically for all targets which depend on libxgboost ?
UPDATE:
Error message:
CMake Error in somelib/CMakeLists.txt:
  Imported target "libxgboost" includes non-existent path

    "build/xgboost/src/xgboost/include"

  in its INTERFACE_INCLUDE_DIRECTORIES.  Possible reasons include:

  * The path was deleted, renamed, or moved to another location.

  * An install or uninstall procedure did not complete successfully.

  * The installation package was faulty and references files it does not
  provide.

A: I'll post the final CMakeLists.txt to include xgboost into your project, it might be useful for someone, the solution to the problem above is to create directories during cmake configure phase (NOTE: I'm using OSX to build that, so you would need to use liblibxgboost.so for GNU/Linux instead of liblibxgboost.dylib):
include(ExternalProject)

ExternalProject_Add(
        xgboost
        GIT_REPOSITORY https://github.com/dmlc/xgboost.git
        GIT_TAG v0.60
        PREFIX ${CMAKE_CURRENT_BINARY_DIR}
        INSTALL_COMMAND ""
)

set(XGBOOST_PREFIX_PATH "${CMAKE_CURRENT_BINARY_DIR}/src")
set(XGBOOST_BINARY_PATH "${XGBOOST_PREFIX_PATH}/xgboost-build")

set(XGBOOST_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/include")
set(DMLC_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/dmlc-core/include")
set(RABIT_LIB_INCLUDE "${XGBOOST_PREFIX_PATH}/xgboost/rabit/include")
set(XGBOOST_BINARY_INCLUDE "${XGBOOST_LIB_INCLUDE};${DMLC_LIB_INCLUDE};${RABIT_LIB_INCLUDE}")

# Hack to make it work, otherwise INTERFACE_INCLUDE_DIRECTORIES will not be propagated
file(MAKE_DIRECTORY ${XGBOOST_LIB_INCLUDE})
file(MAKE_DIRECTORY ${DMLC_LIB_INCLUDE})
file(MAKE_DIRECTORY ${RABIT_LIB_INCLUDE})

add_library(libxgboost IMPORTED STATIC GLOBAL)
add_dependencies(libxgboost xgboost)

set_target_properties(libxgboost PROPERTIES
        "IMPORTED_LOCATION" "${XGBOOST_BINARY_PATH}/liblibxgboost.dylib"
        "INTERFACE_INCLUDE_DIRECTORIES" "${XGBOOST_BINARY_INCLUDE}"
)

A: Note that it is possible to combine FetchContent and ExternalProject_Add to achieve the following:

*

*FetchContent will make the source available at configure time, thereby bypassing the issue that the INTERFACE_INCLUDE_DIRECTORIES doesn't exist.

*ExternalProject_Add will use the source downloaded by FetchContent to build at build time
Here is an example building libpqxx:
include(FetchContent)
include(ExternalProject)

find_package(PostgreSQL)

# Using FetchContent means we will download libpqxx at configure-time

FetchContent_Declare(libpqxx_ext
    GIT_REPOSITORY
        https://github.com/jtv/libpqxx
    GIT_TAG
        tags/7.4.1
    )

FetchContent_GetProperties(libpqxx_ext)

if(NOT libpqxx_ext_POPULATED)
  FetchContent_Populate(libpqxx_ext)
endif()

set(LIB_PQXX_SRC_DIR ${CMAKE_BINARY_DIR}/_deps/libpqxx_ext-src)

# Build libpqxx

ExternalProject_Add(libpqxx_ext
    SOURCE_DIR
        ${libpqxx_ext_SOURCE_DIR}
    PREFIX
        ext
    BINARY_DIR
        build
    CMAKE_ARGS
        -DSKIP_BUILD_TEST=on
    INSTALL_COMMAND
        ""
    BUILD_ALWAYS
        OFF
    )

set(LIB_PQXX_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/build/src)

# Make the libpxqq artifacts available to our project

add_library(libpqxx STATIC IMPORTED GLOBAL)

set_target_properties(libpqxx
    PROPERTIES

    INTERFACE_INCLUDE_DIRECTORIES
        ${LIB_PQXX_SRC_DIR}/include
    IMPORTED_LOCATION
        ${LIB_PQXX_BUILD_DIR}/libpqxx.a
    INTERFACE_LINK_LIBRARIES
        ${PostgreSQL_LIBRARIES})

add_dependencies(libpqxx libpqxx_ext)


text:
Q: Splitting data into an array public class ImportDoctorFile  {

    public ImportDoctorFile() {
              System.out.println("Starting Cons");

     List<Doctor> doctorList = new ArrayList<>();
            Scanner scanner;
      try
        {
             scanner= new Scanner(new File("Doctors.csv"));
              scanner.useDelimiter("\n");
             while (scanner.hasNextLine())
            {
                String temp = scanner.nextLine();
                String [] tempDetails = temp.split(",");

                Doctor myDoctor;
                Surgeon mySurgeon;

                if(tempDetails.length == 5)
                {
                    myDoctor =new Doctor (tempDetails[0],tempDetails[1],tempDetails[2],tempDetails[3],tempDetails[4]);
                    doctorList.add(myDoctor);
                    System.out.println(myDoctor);
                }
                else if(tempDetails.length ==6)
                {
                    mySurgeon =new Surgeon (tempDetails[0],tempDetails[1],tempDetails[2],tempDetails[3],tempDetails[4],tempDetails[5]);
                    doctorList.add(mySurgeon);
                    System.out.println(mySurgeon);
                }
            }
        }
      catch(FileNotFoundException e)
        {
            System.out.print("Error, unable to locate the CSV File!");

        }
    }
}

I am having a problem when trying to load the data from my .csv file into an array and split it up. When outputting the details it skips some of the doctors and miss places the 6th index when creating a surgeon. I have pasted the csv file above.
Conor Murphy    12 Front Road Leeds Telephone   conor@hotmail.com   Surgery      12/05/2016
Carol McKee 79 The Green Birmingham Skype   Cmckee-25   Neurology
Robert Jones    165 Main Street Glasgow Facetime    R.jones@gmail.com    Orthopedics
Mary Shelley    297 Peartree Grove Guildford     Skype  m-shelly1   Cardiology
John Smith  13 Value Avenue Bristol Telephone    +44(0)7987545352    Surgery     12/05/2016
Laura Penny 87 Primrose Way Ipswich Facetime    l.penny234@btinternet.com    Pulmonology
Mark Matthews   2 The Strand Dublin Skype   Matthews-m15     Int.Care Medicine
Ciaran Bell 58 Windy Ridge Folkstone    Telephone   +44(0)8452126984     Infectious Disease
Nicola Johnson  128 Ash Park Coleraine  Skype   Nicky-j123  Surgery     24/11/2015

A: You can use StringBuilder class
StringBuilder class has the property of converting its content into tokens.
Simply add ',' as the delimiter and you will get the tokens.


text:
Q: jenkins java plugin field gives Bad Message 414 reason: URI Too Long When field in my plugin is filled with about 5000 characters it gives error:
Bad Message 414
reason: URI Too Long

When I make it less a bit, it gives:
Bad Message 431
reason: Request Header Fields Too Large

config.jelly:
<f:entry field="field" title="Example">
   <f:textarea value="${it.getField()}"/>
</f:entry>

java:
private String field;
...
public FormValidation doCheckField(@QueryParameter String value)
            throws IOException, ServletException {
    if (value.length() == 0) {
        return FormValidation.error("Please set an input");
    } else {
        return FormValidation.ok();
    }
}

A: It was fixed by adding to Jenkins config

*

*/etc/sysconfig/jenkins for default SLES installation

*C:\Program Files (x86)\Jenkins\jenkins.xml in Windows

JENKINS_ARGS="--requestHeaderSize=32768"


text:
Q: How to create a subquery how can i combine 2 mysql statement into one statement.
These are my statements
MYSQL 1
SELECT et.imei as IMEI, MAX(FROM_UNIXTIME(et.timestamp)) as TID
FROM exp_terminal_log as et
group by et.imei
order by TID desc;

MYSQL 1 OUTPUT
IMEI              LATEST DATE
351895053434419   2013-04-28 11:12:28
354851057203265   2013-04-28 11:10:44
354851057234989   2013-04-28 11:10:32

MYSQL 2
SELECT ct.title AS TITLE, t.phoneid as IMEI
FROM transactions AS t
inner JOIN exp_channel_titles AS ct ON (ct.entry_id = t.restaurant_id)
WHERE t.cardid != '88888888' AND t.cardid > 0
AND ct.status= 'open'
GROUP by ct.entry_id

MYSQL 2 OUTPUT
TITLE       IMEI
Café Katz   351895053434419
Restaurant1 354851057203265
Restaurant2 354851057234989

Desired output
TITLE       IMEI               LATEST DATE
Café Katz   351895053434419    2013-04-28 11:12:28
Restaurant1 354851057203265    2013-04-28 11:10:44
Restaurant2 354851057234989    2013-04-28 11:10:32

this is how tried, but this does not work, because of my subquery is returning more than one row.
SELECT et.imei as IMEI, MAX(FROM_UNIXTIME(et.timestamp)) as TID
FROM exp_terminal_log as et
group by et.imei
having et.imei = (

SELECT t.phoneid as IMEI
FROM transactions AS t
inner JOIN exp_channel_titles AS ct ON (ct.entry_id = t.restaurant_id)
WHERE t.cardid != '88888888' AND t.cardid > 0
AND ct.status= 'open'
GROUP by ct.entry_id )

A: Try this:
SELECT
  ct.title AS TITLE,
  t.phoneid as IMEI,
  t2.TID
FROM transactions AS t
inner JOIN exp_channel_titles AS ct ON ct.entry_id = t.restaurant_id
INNER JOIN
(
  SELECT et.imei as IMEI, MAX(FROM_UNIXTIME(et.timestamp)) as TID
  FROM exp_terminal_log as et
  group by et.imei
) AS t2 ON t.phoneid = t2.IMEI
WHERE t.cardid != '88888888'
  AND t.cardid > 0
  AND ct.status= 'open'
GROUP by ct.entry_id;

A: You can do a join of the two subqueries:
SELECT titles.TITLE, titles.IMEI, dates.TID  FROM
   (SELECT et.imei as IMEI, MAX(FROM_UNIXTIME(et.timestamp)) as TID
       FROM exp_terminal_log as et
       group by et.imei
       order by TID desc) dates
  INNER JOIN
   (SELECT ct.title AS TITLE, t.phoneid as IMEI
       FROM transactions AS t
       inner JOIN exp_channel_titles AS ct ON (ct.entry_id = t.restaurant_id)
       WHERE t.cardid != '88888888' AND t.cardid > 0
       AND ct.status= 'open'
       GROUP by ct.entry_id ) titles
  ON titles.IMEI=dates.IMEI


text:
Q: Having trouble getting startup scripts to work in Server 2003 Thanks for taking the time to read this.
I am having trouble getting my startup scripts to run correctly on the domain I am administering. Before anyone gets upset and says "go read xxx article from microsoft",... I have. I am simply missing something or not understanding it properly. I understand how to assign the script, what I am curious about is where exactly it should be placed in the Windows folder structure. I have been able to get them to work by creating a share folder called "scripts" and pointing to that exact unc pathname IE \servername\scripts\xxx.bat. However, I would like to do it properly, would someone please tell me where they should be placed in Win2003 server, and what the path name should be when assigning a group policy to do something that applies to computer specific properties? Your assistance is very much appreciated by a junior admin trying to learn some new tricks!

A: The script gets placed in "domain\sysvol\domain\policies\policy guid\machine\scripts\startup" folder. The easiest and recommended way to add a script is to edit the GPO that applies to the computer(s) in question using GPMC, expand Computer Configuration, Expand Windows Settings, select the Scripts item in the left pane, double-click the Startup item in the right pane, click the Show Files button, and paste your script into the windows explorer window that opens, close the explorer window, click the Add button, type the name of the script in the "Script Name" field, click OK, click OK again, and close the GPMC.

A: For the best results I think your startup and login script should be stored and referenced from a path somewhere under sysvol so the can be replicated out to all the domain controllers.
When you create a policy you and click the 'Browse button' you will find that the default path where the scripts would be created would be a folder like this.  Putting things here in this location is fine and not uncommon.
\\domain.tld\SysVol\domain.tld\Policies\{6380CAEE-DF69-4AF2-A3BB-F0EEB4DC8801}\Machine\Scripts\Startup

Another common location where people place their scripts in the netlogon folder.  I tend to prefer this because you can use better folder and script names.
\\domain.tld\SYSVOL\domain.tld\scripts (aka \\domain.tld\netlogon)

A: Just re-read your question.  I think what you want to do is assign login scripts via Group Policy if I understand your question correctly.
This article will help:
http://www.computerperformance.co.uk/Logon/logon_script_assign.htm
If it's not working on the workstations, try running the following on the workstation:
gpupdate /force /sync /boot

Also make sure that the Group Policy is being applied to your workstations as well.  You can run the gpresult command from the workstations(s) to see/make sure it's applying correctly.


text:
Q: How to set 'spring.datasource.url' inside a Docker Container I created a Spring Boot application which uses a MySQL database. I use a docker-compose to launch the database.

services:
  adminer:
    image: adminer
    restart: always
    ports:
      - 8888:8080
  db:
    image: mysql:latest
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 'example' # TODO: Change this
    volumes:
      - "./config/my.conf:/etc/mysql/conf.d/config-file.cnf"
      - "./data:/var/lib/mysql:rw"

The Spring Boot Application (Backend) currently does not use Docker, I run it inside Eclipse. Before launching the Backend I have to grep the Docker Container for IPAddress:
docker inspect mysql_ex_db_1 | grep 'IPAddress'

which results something like this (this exact address changes time-to time)
                "IPAddress": "",
                    "IPAddress": "172.21.0.2",

Then I take this value and I set spring.datasource.url inside Eclipse in the file Application.properties with it.
spring.datasource.url=jdbc:mysql://172.21.0.2:3306/employee_management_system?allowPublicKeyRetrieval=true&useSSL=false&createDatabaseIfNotExist=true

After this I can launch the Backend in Eclipse the Connection to database is there, everything works.
Now I want to move the launching of Backend from Eclipse to the same docker-compose file I use to launch the database. Therefore I built an image, and appended the docker-compose file:
version: '3.1'

services:
  adminer:
    image: adminer
    restart: always
    ports:
      - 8888:8080
  db:
    image: mysql:latest
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 'example' # TODO: Change this
    volumes:
      - "./config/my.conf:/etc/mysql/conf.d/config-file.cnf"
      - "./data:/var/lib/mysql:rw"
  backend:
    image: backend:latest
    restart: always
    ports:
      - 8090:8080

In this case how can I configure the IPAddress in spring.datasource.url?
The exact IPAddress changes whenever I re-launch the mysql containers.
spring.datasource.url=jdbc:mysql://172.21.0.2:3306/employee_management_system?allowPublicKeyRetrieval=true&useSSL=false&createDatabaseIfNotExist=true

So what should I write instead of '172.21.0.2' ?
I tried localhost here but it
does not seem to work.

A: First of all, you can set environment variables like spring.datasource.url outside of your docker image. This allows you to dynamically set these variables according to your deployment needs (like connecting to a dev or prod database).
All docker containers running from your docker-compose file run in the same virtual network and their service names correspond to their hostnames within this network. When you want to access your database from your dockerized spring backend the hostname and port will be db:3306. You can overwrite spring.datasource.url in your docker-compose file by introducing an environment variable like:
version: '3.1'

services:
  adminer:
    image: adminer
    restart: always
    ports:
      - 8888:8080
  db:
    image: mysql:latest
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 'example' # TODO: Change this
    volumes:
      - "./config/my.conf:/etc/mysql/conf.d/config-file.cnf"
      - "./data:/var/lib/mysql:rw"
  backend:
    image: backend:latest
    restart: always
    ports:
      - 8090:8080
    environment:
      spring.datasource.url: "jdbc:mysql://db:3306/employee_management_system?allowPublicKeyRetrieval=true&useSSL=false&createDatabaseIfNotExist=true"

A: In your Spring Boot app, your spring.datasource.url must be like this:
spring.datasource.url=jdbc:postgresql://${DATABASE_HOST}:5432/my_db

(here I am connecting to a postgres db). Then you set the variable in your docker compose:
...
environment:
  DATABASE_HOST:container_name

you can also test outside a docker-compose, by command line like this:
docker run -it -p 8080:8080 -e "JAVA_OPTS=-Xmx128m" --network=my_network -e DATABASE_HOST=postgres_container_name --name myapp myregistry/myimage:version

A: Add this env variable to your backend in docker-compose:
backend:
  ...
  environment:
    - SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/employee_management_system?allowPublicKeyRetrieval=true&useSSL=false&createDatabaseIfNotExist=true


text:
Q: Issue with router.php and send parameters via URL in joomla3 component I designed a joomla3 component...
I want to send some parameters to component via URL.
I linked a menu for this component..So I access to this component by this address:
http://examle.com/tag
I have 3 parameters:
years
month
day
example:
http://examle.com/tag/2014/12/19
This is my router.php
<?php
defined('_JEXEC') or die ;
function BahaediniBuildRoute(&$query)
{
       $segments = array();
       $app     = JFactory::getApplication();
       $menu        = $app->getMenu();
       $params      = JComponentHelper::getParams('com_bahaedini');
       $advanced    = $params->get('sef_advanced_link', 0);

       if(isset($query['year']))
       {
                $segments[] = $query['year'];
                unset( $query['year'] );
       }
       if(isset($query['month']))
       {
                $segments[] = $query['month'];
                unset( $query['month'] );
       }
       if(isset($query['day']))
       {
                $segments[] = $query['day'];
                unset( $query['day'] );
       }

       return $segments;
}

function BahaediniParseRoute($segments)
{
       $vars = array();

       $segments[0]='items';
       switch($segments[0])
       {

               case 'items':
                       $vars['view'] = 'items';
                       if(isset($segments[0]))
                       {
                       $year = explode( '/', $segments[0] );
                       $vars['year'] =  (int)$year[0];
                       }

                       if(isset($segments[1]))
                       {
                       $month = explode( '/', $segments[1] );
                       $vars['month'] = (int)$month[0];
                       }

                       if(isset($segments[2]))
                       {
                       $day = explode( '/', $segments[2] );
                       $vars['day'] = (int)$day[0];
                       }

                       break;
       }
       return $vars;
}?>

So I wana test it. I put some code in a php file in models folder (items.php):
echo "
y:".$_date          = urldecode($app->input->getString('year'));
echo "
m:".$_date          = urldecode($app->input->getString('month'));
echo "
d:".$_date          = urldecode($app->input->getString('day'));

The result are:
y:0
m:12
d:19

You can sea...value of 'y' must be '2014' but it is '0'!
How can I solved this problem? what is my wrong?

A: Reading your code, BahaediniParseRoute() function, first you assign $segments[0] to 'items', then you try to explode it and read $year from it... it's returning '0' because you're casting $year as int, but it contains 'items'.
Try removing the casts and var_dump($segments) before you assign it 'items' (which makes little sense anyways, why set it and then test it in a conditional loop? you know $segments[0]='items' so what's the point of switch ... case 'items'?


text:
Q: CREATE DATABASE permission denied in database 'master'. A database with the same name exists I was running my application in Visual Studio 2010 Application Server, but now I have changed it to use IIS Local Server, then everything crushed. I am getting following error:

System.Data.SqlClient.SqlException: CREATE DATABASE permission denied in database 'master'.
  An attempt to attach an auto-named database for file D:\Code\EMSApplication\EMSApplication.Web\App_Data\ASPNETDB.mdf
  failed. A database with the same name exists, or specified file cannot
  be opened, or it is located on UNC share.

I have changed the setting of Application Pool of the Default Web Site of IIS to Classic .NET AppPool.

Also changed the Identity of the Classic .NET AppPool to LocalSystem.

I also set the permission of the NETWORK SERVICE to the Full

The connection string is:
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.mdf;Integrated Security=True

But none of them worked. I am still getting that error. Any suggestion will be very helpful to me.
Thanks.

I am using SQL Server 2008 Express which comes with the installation of Visual Studio 2010.

A: The problem is, pretty clearly, that you already have a database named ASPNETDB attached to that SQL Server instance.  My assumption is that the VS development web server is still running, and that is what has the database attached.  If so, just shut it down and try an IIS restart, and you should be good.  If that doesn't do it, go and download SSMS Express, connect to your local SQLExpress instance, and try to detach the existing database from there.


text:
Q: Does the Casimir effect give the correct value for Dark Energy? My understanding is that the Casimir Effect is caused by vacuum energy. Quantum mechanics (QED) predicts vacuum energy, but gets the value grossly wrong, by a factor of $10^{120}$. On the other hand, from what I have read, Dark Energy is understood to be caused by vacuum energy.
Has anyone checked whether the measured value for the Casimir Effect fits the value required for Dark Energy to make up 70% of the energy in the universe? If it did, that would be an excellent validation of Dark Energy.

A: Fill your imaginary box with lots of parralell plates and calculate the energy then scale by the age of the universe and you will have your answer.


text:
Q: Undownvote a question or answer If I accidentally downvoted an answer or question, it became -1. When I undownvote it, it becomes 1, not 0. Why?

A: By default when you downvote and undownvote to the answer/question, the count will be same as the previous count only.
May be on the same time, some other user may upvote the answer/question, so when you undo or updownvote to the answer/question, its looks like the vote count is as 1. But the 1 is display due to the other user's upvote.


text:
Q: How can I elegantly construct a form for a model that has a polymorphic association? Here are my models:
class Lesson < ActiveRecord::Base
  belongs_to :topic, :polymorphic => true
  validates_presence_of :topic_type, :topic_id
end

class Subject < ActiveRecord::Base
   has_many :lessons, :as => :topic
end

class Category < ActiveRecord::Base
  has_many :lessons, :as => :topic
end

Now, what I need is a form that will allow the user to create or update Lessons. The questions is, how can I provide a select menu that offers a mix of Subjects and Categories? (To the user, on this particular form, Subjects and Categories are interchangeable, but that's not the case elsewhere.)
Ideally, this would look something like this:
views/lessons/_form.html.haml
= simple_form_for(@lesson) do |f|
  = f.input :title
  = f.association :topic, :collection => (@subjects + @categories)

That won't work because we'd only be specifying the topic_id, and we need the topic_types as well. But how can we specify those values?
I guess the crux of the problem is that I really want a single select menu that specifies two values corresponding to two different attributes (topic_id and topic_type). Is there any elegant railsy way to do this?
A few notes:
a) Single table inheritance would make this issue go away, but I'd like to avoid this, as Categories and Subjects have their own relationship… I'll spare you the details.
b) I might could pull some javascript shenanigans, yes? But that sounds messy, and if there's a cleaner way to do it, some magic form helper or something, then that's certainly preferable.
c) Though I'm using simple_form, I'm not wedded to it, in case that's complicating matters.
Thanks

A: If you don't wish to use STI, you can do something similar: create a new model Topic(name:string) which will polymorphically reference Subject or Category.
class Lesson < ActiveRecord::Base
  belongs_to :topic
  validates_presence_of :topic_id
end

class Topic < ActiveRecord::Base
  belongs_to :topicable, :polymorphic => true
end

class Subject < ActiveRecord::Base
   has_one :topic, :as => :topicable
   has_many :lessons, :through => :topic
   accepts_nested_attributes_for :topic
end

class Category < ActiveRecord::Base
   has_one :topic, :as => :topicable
   has_many :lessons, :through => :topic
   accepts_nested_attributes_for :topic
end

In the view where you create a new Subject/Category:
<%= form_for @subject do |subject_form| %>
  <%= subject_form.fields_for :topic do |topic_fields| %>
    <%= topic_fields.text_field :name %>
  <% end %>
<% end %>

A: After thinking this through, the less dirty implementation IMO would be to hire the JS shenanigans (b):
= f.input_field :topic_type, as: :hidden, class: 'topic_type'
- (@subjects + @categories).each do |topic|
  = f.radio_button :topic_id, topic.id, {:'data-type' => topic.class.name, class: 'topic_id'}

With a sprinkle of JS (your needs may vary):
$('input:radio.topic_id').change(function() {
  $('input:hidden.topic_type').val($(this).attr('data-type'));
});

Notes:

*

*I use a radio button to select a topic (category or subject) in a list

*The class name of each of possible topic is stored in an attribute 'data-type'

*When a radio button is selected, the class name is copied to the hidden input via JS

*Using: HTML5, jQuery, haml, simple_form


text:
Q: programmatically bottom margin to ImageView not working marginBottom not working. It works but the margin is only a few space regardless of how much margin is applied. Why?
Java-code :
LinearLayout onepage= (LinearLayout) findViewById(R.id.onepage);

RelativeLayout bluegreen = new RelativeLayout(this);
p_ll = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
bluegreen.setLayoutParams(p_ll);

//some other views that make up the whole page

//bottom most image
ImageButton migs = new ImageButton(this);
p_rl = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
p_rl.addRule(RelativeLayout.CENTER_HORIZONTAL);
p_rl.setMargins(0, 0, 0, 20);
register.setLayoutParams(p_rl);
register.setImageResource(R.drawable.migs);
register.setPadding(0, 0, 0, 0);

bluegreen.addView(migs);

onepage.addView(bluegreen);

XML:
<LinearLayout
    android:id="@+id/onepage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".PageActivity" >
</LinearLayout>

A: Have you notice that in setMargins method parameters are in pixel and not in dp? take a look at android doc page
So depending of your device screen size but 20 px can be very small.
Don't forget to call requestLayout() to take in account margin changes.


text:
Q: Open a CRM Entity from a Web Resource I have a Web Resource that is working fine, except for one major headache.
I need to be able to click on a link and open an existing entity record. These two methods both almost get me there, but are blocked by different reasons:
1. Calling it directly with a link like this:
window.open('http://OurCRM/main.aspx?etc=10088&id=%7bc1d0db62-aa9e-e911-80e0-0a94ef08472f%7d&pagetype=entityrecord', '_self');

The problem with this one is that it doesn't work due to CRM saying
"Sys.InvalidOperationException: Sys.InvalidOperationException: Service Xrm.Interfaces.Services.IMostRecentlyViewedService already has an implementation"
note : If I take out the '_self' it works but then that defeats the purpose of what we're trying to do (need to keep it in the same tab).
2. using the Client API:
parent.Xrm.Utility.openEntityForm('ourentity', guid, '', '');

This one is blocked due to Cross Origin Frames being blocked by browsers.
Does anyone know how to do this?

A: Below snippet should work: (this will be onclick of button or link)
onclick="window.location.href='http://OurCRM/main.aspx?etc=10088&id=%7bc1d0db62-aa9e-e911-80e0-0a94ef08472f%7d&pagetype=entityrecord';"

A: To help others out, this was resolved in another, similar question
accessing the logged in CRM user from custom page
Basically we were looking at two different ways to handle the same problem of working with webforms inside CRM.


text:
Q: cheerioJS not grabbing element from page I'm having issues grabbing an element with cheerio js.
I opened the following website -> https://www.voobly.com/ladder/view/Age-of-Mythology-The-Titans/1v1-Supremacy
and when I do view page source I can see the id -> pagebrowser1, but when I try to grab it using cheerio, it returns null.

const axios = require('axios');
const cheerio = require('cheerio');

axios.get('https://www.voobly.com/ladder/view/Age-of-Mythology-The-Titans/1v1-Supremacy').then((res) => {
    const $ = cheerio.load(res.data)

    console.log($("#pagebrowser1").html());
});