text:
Q: Dual slope converter vs. delta-sigma converter? I'm curious as to why dual-slope analog to digital converters are used in most digital voltmeters, like one of these when a delta-sigma converter like one of these easily exceeds the specifications of any of the other dual-slope converters sold by Microchip, and in fact many other suppliers, especially given the low price point of the chip (about $4 in low quantities.) Is there a reason I am missing?

A: With a dual-slope ADC you effectively get free averaging as the run-up integration phase will have this effect.  The output is also extremely simple, just a pulse that needs to be timed which can be done with even the simplest micro controllers.
$4 is a really big deal when your making 50,000 of something and trying to sell it for $50.  The dual-slope part you linked is $1.64 in a PDIP for 5000+.  The sigma-delta's cheapest package is $2.88 in its cheapest package.  Saving ~$1.20 on a single part AND being able to use a more basic microcontroller is a big cost win.
I think you'll find the more expensive multimeters do use higher end ADCs.

A: Incidentally, an approach I used once that seemed to work pretty well was to have a PIC output drive an RC circuit and feed that into one input of a comparator, while the other input of the comparator was the signal under test.  Every 100us, I would sample the state of the comparator, set the output high or low as appropriate, and (if I set the output low) bump a counter.  Every 4096 interrupts, I would copy the value of that counter and reset it.
The beautiful thing about this approach is that provided the input isn't changing, and provided the RC time constant is sufficiently high, and the input isn't too close to a rail, one can avoid any need for precision constant current sources or other such things.  The system will output a ratiometric measurement of the input voltage compared to the output rails feeding the RC (e.g. if the input voltage is 3/4 of VDD, and the output swings fully to VDD or ground given the currents involved, the reading will be 3072/4096).
The biggest problem I've observed with this approach is that if the input changes significantly, the readings will be pegged for a little while, and the first reading after that will be meaningless.  Still, it's a cheap approach and seems to work pretty well.

A: It's basically speed, resolution and cost, dual-slope converters are cheaper but a lot slower and offer lower resolution. Speed and high resolution don't matter for something like a DVM, but they are important for, say, sampling speech and music.


text:
Q: Difficulty with ExternalEvaluate I am trying to import a Python function or execute a Python script from inside Mathematica, but the ExternalEvaluate command drives me nuts.
I proceed cautiously with the following Python test module, named "test.py":
def test():
   print("Test")
print("Hello")

I checked that the module can be found and tried it successfully from the CMD command line:
python
from test import test

Using Import in Mathematica also works:
Import["!python g:\\p\\python37\\test.py", "String"]

But then with ExternalEvaluate I first made sure that the Python connection works as follows, which works OK:
ExternalEvaluate["Python", "2+3"]

However, the following gives Exception: Import Error. EvaluationFailure:
ExternalEvaluate["Python", "from test import test"]

The same happens if I use a session:
ses = StartExternalSession["Python"]
ExternalEvaluate[ses, "from test import test"]

I would be glad for a hint what I am doing wrong

A: By default when you start a session, Working directory in Windows, is Documents folder:
ExternalEvaluate["Python", "import os;os.getcwd()"]

(*Out: "C:\\Users\\USERNAME\\Documents" *)

Import a single file
If you want to import a single file that does not import other files (not dependent on others), this solution will work:
ss = StartExternalSession["Python"];

ExternalEvaluate[ss, File["C:\\foo.py"]]

DeleteObject[ss];

Now it's like you had executed from foo.py import * and have access to all of its functions and variables.
Import a file with its dependencies
If you have a file that imports other files, the above solution will raise an error:
File: C:\bar.py
===============

import foo

foo.test()

ss = StartExternalSession["Python"];

ExternalEvaluate[ss, File["C:\\bar.py"]]

DeleteObject[ss];

The solution is to make the file directory known to the python interpreter which have so many solutions (some discussed here):
One of the solutions is to add sys.path.append(...) to the beginning of that file:
File: C:\bar.py
===============

import sys
sys.path.append('C:\\')

import foo

foo.test()

Now you have access to all of the functions and variables + ability to import other files.
All the code tested on Mathematica 12.2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: three.js MeshLambertMaterial Dear all: My models with MeshLambertMaterial consume about 1.6GB memory, which is excess the capability of 32-bit Chrome browser. When using Basic Material instead, the memory consumption is almost at the same level around 456mb. Nevertheless, no 3D-like-feeling towards objects in scenes.  Is there any solution to this?

A: Looks like you have complex geometry/huge texture files.
What I suggest is to decrease geometry complexity, try smaller textures and re-use once instantiated objects which are not visible on the screen
A good read about performance tweaking
: http://www.html5rocks.com/en/tutorials/casestudies/hobbit/


text:
Q: How to check an argument type before __init__ gets called I need to check the argument type in __init__(). I did it this way:
class Matrix:

    def __init__(self, matrix):
        """
        if type(matrix) != list raise argument error
        """
        if type(matrix) != list:
            raise TypeError(f"Expected list got {type(matrix)}")
        self.matrix = matrix

a = 5
new_matrix = Matrix(a)

But when the TypeError gets raised the __init__() method is already called. I am wondering how to do this before it gets called. I reckon this could be done using metaclass to "intercept it" at some point and raise an error, but I do not know how.

A: First:
one usually do not make such runtime checks in Python - unless strictly necessary. The idea is that whatever gets passed to __init__ in this case will behave similarly enough to a list, to be used in its place. That is the idea of "duck typing".
Second:
if this check is really necessary, then an if statement inside the function or method body, just like you did, is the way to do it. It does not matter that the "method was run, and the error was raised inside it" - this is the way dynamic typing works in Python.
Third:
There actually is a way to prevent your program to ever call __init__ with an incorrect parameter type, and that is to use static type checking. Your program will error on the preparation steps, when you run the checker, like "mypy" - that is roughly the same moment in time some static languages would raise the error: when they are compiled in an explicit step prior to being run. Static type checking can add the safety you think you need - but it is a whole new world of boilerplate and bureaucracy to code in Python. A web search for "python static type checking" can list you some points were you can start to learn that - the second link I get seens rather interesting: https://realpython.com/python-type-checking/
Fourth:
If you opt for the if-based checking, you should check if the object you got is "enough of a list" for your purposes, not "type(a) != list". This will bar subclasses of lists. not isinstance(a, list) will accept list subclasses, but block several other object types that might just work. Depending on what you want, your code will work with any "sequence" type. In that case, you can import collections.abc.Sequence and check if your parameter is an instance of that instead - this will allow the users to your method to use any classes that have a length and can retrieve itens in order.
And, just repeating it again: there is absolutely no problem in making this check inside the method. It could be factored out, by creating a complicated decorator that could do type checking - actually there are Python packages that can use type annotations, just as they are used by static type checking tools, and do runtime checks.  But this won't gain you any execution time. Static type checking will do it before running, but the resources gained by that are negligible, nonetheless.
And finally, no, this has nothing to do with a metaclass. It would be possible to use a metaclass to add decorators to all your methods, and have these decorators performe the runtime checking - but you might just use the decorator explicitly anyway.


text:
Q: Would separate Entities help reduce the memory consumed? (Entity Framework) We have a big accounting project, containing 300+ tables.
Then, we have different modules - Finance, Checkroll, etc.
Currently, each module is loading a giant Edmx entity containing all those tables. It is so clunky that it loads a very long time just to add a column into that Edmx.
So, I suggest to separate the entities. Ideally, each Module should only contain the tables that belong to him. Hopefully with this, it could minimize memory usage at the server.
Then, as expected, some reject the ideas. They claim that it doesn't help much (reduce server load / reduce Memory consumed) by saying that the Linq works like lazyload - "if you don't use the table in your linq query, it won't consume the extra memory."
I would like to justify whether that statement is valid. How's your practice normally?

A: In order to minimize memory consumption use smaller DbContexts, and use gcServer setting (if you run a console app or Windows Servce) - there are also other things you can do, see the MSDN whitepaper, Performance Considerations for EF 4, 5, and 6.


text:
Q: Disable prompt on ionic cordova prepare? I am trying to automate in jenkins the build of my ionic cordova app.
The command I run in jenkins are:
yarn
ionic cordova prepare

On the ionic cordova prepare, it is prompting some questions if I want to update the version of some plugin

Local plugin @ionic/cli-plugin-cordova has an update available (1.2.1
  => 1.3.0 )! Would you like to install it? (Y/n)

Is there any flag or parameter to pass pass to the prepare to disable the prompt or say no to the update?
I didn't find any information in the documentation.

A: I found the solution from the documentation
The flag --no-interactive does the trick.
--interactive / --no-interactive: Switch between interactive (default) and non-interactive mode. In non-interactive mode, the spinner and all prompts are disabled (useful for CI/CD servers).
It will basically answer no to all the update questions, very convenient.

A: I you ever want to say YES instead of NO you can use:
--no-interactive --confirm


text:
Q: Unable to load font in Allegro I'm playing around with Allegro 5 in C++ and Visual Studio 2012, but for some reason I can't get a font to load using the sample code from the Allegro wiki:
    ALLEGRO_FONT *font = al_load_ttf_font("pirulen.ttf",72,0 );

   if (!font){
      fprintf(stderr, "Could not load 'pirulen.ttf'.\n");
      return false;
   }

   al_clear_to_color(al_map_rgb(50,10,70));
   al_draw_text(font, al_map_rgb(255,255,255), 640/2, (480/4),ALLEGRO_ALIGN_CENTRE, "It worked!");

I've tried placing the font file in about every feasible directory in my Visual Studio project, as well as in the directory the .exe is in (as is suggested by several other threads).  I also tried just dropping a copy of it on the C: drive and calling it with the fully qualified path: I tried C:\\pirulen.ttf and C:/pirulen.ttf neither of which worked.  I've also tried adding it to the "Resource Files" folder in my project, but that did not work either.
Any advice on what could be going on?
Thanks.

A: Everything that needs to be said is here:

*

*Loading Resources (Troubleshooting)

A: I know this is a yonks old question, but I've just found it and read the docs as suggested by Matthew (which everyone ought to do), so thought I'd add this here for any others looking for an easy answer.
You can handle creating a path for each resource if you wish but it is easier to use al_change_directory to set up your resources directory, then you can find you assets there.
al_init_font_addon(); // initialize the font addon
al_init_ttf_addon();// initialize the ttf (True Type Font) addon

ALLEGRO_PATH *path = al_get_standard_path(ALLEGRO_RESOURCES_PATH);
al_append_path_component(path, "resources");
al_change_directory(al_path_cstr(path, '/'));
al_destroy_path(path);

Then you can reference paths relative to the resource root.
ALLEGRO_FONT* font = al_load_ttf_font("LibreCaslonText-Bold.ttf", 72, 0);

// Check font is loaded
if (!font) {
    fprintf(stderr, "failed to load font!\n");
    al_destroy_font(font);
    return -1;
}

To clarify LibreCaslonText-Bold.ttf exists in project_dir/resources/LibreCaslonText-Bold.ttf
Side note
In my case, I also needed to copy the resources over to my build directory. So I added this to my CMakeLists.txt.
if (NOT ${PROJECT_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_BINARY_DIR})
    file(COPY "${PROJECT_SOURCE_DIR}/resources" DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
endif()


text:
Q: How to filter windows event log with wildcard? According to the document here, the asterisk wildcard is supported and hence it should work in eg.
*[EventData[Data[@Name='TargetUserName'] ='User1*']]
but I cannot get any wildcard filter to work - has anyone been able to do this?

A: The XPath selector must begin with *, however you cannot use * to filter fields as Xpath 1.0 has no contains operator.
https://blogs.technet.microsoft.com/askds/2011/09/26/advanced-xml-filtering-in-the-windows-event-viewer/

XPath 1.0 Limitations:
  Windows Event Log supports a subset of XPath 1.0. There are limitations to what functions work in the query. For instance, you can use the position, Band, and timediff functions within the query but other functions like starts-with and contains are not currently supported.

A: Use Powershell
Get-EventLog -LogName "System" | ?{$_.Message -like "*YourSearchString*"} | Out-GridView


text:
Q: could not find driver PDOException on aws ubuntu server I have deployed my laravel project on ubuntu ec2 instance . When I try to make query thourgh tinker it works fine and it return data . But when I try open page it give this error
could not find driver
/var/www/html/coldxlogistics/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php#70
PDOException

I tried many think like.
php-mysql
php8.1-mysql

are installed on ubuntu
I also tried laravel commands like
php artisan optimize
php artisan cache:clear
php artisan config:cache
php artisan view:clear

but nothing is working
my php version is php 8.1.2


text:
Q: Stack on Windows - where is it? I'm a bit confused on where an exe stack is located.. I know that the CRT before the program runs initializes the heap by allocating an amount of heap (which in turn is allocated by the OS that allocates pages), but where's the stack? Is it on a page too? Or is it shared by all programs in user mode (ring3) by using a ring3 descriptor on the GDT (I think not but I'm not sure) ?

A: Windows will reserve a contiguous area of virtual memory (1MB by default) per thread. It then commits a few top-most pages of that memory region and marks a couple below that as guard pages.  As the thread's stack grows downward, if a guard page is accessed an exception occurs and Windows commits the guard page and marks pages below that as guard.
You can explore this behavior with the excellent SysInternals utility VMMap.  Below is a snippet from that tool:

A: Each thread is given its own stack. It's just a chunk of memory allocated for that purpose.
All memory is allocated in pages, including the stack (On Windows, I believe the stack defaults to 1MB, so it would span a number of pages, given that most memory pages are 4KB.)
But it's really just a chunk of memory pointed to by the stack pointer register.

A: Each program in Windows is a process. Processes generally do not share their memories between one another.
Sharing and not sharing is the question of how each process's virtual address space maps onto the physical memory.
If two processes have portions of their address spaces mapped onto the same pages of the physical memory, that memory is effectively shared by them, and each process can read and possibly write it and observe writes of the other process.
There's very little sense in sharing the stack memory and so every process has got its own stack. Actually, processes are more like containers. The entities that execute code and use the stack are threads. There's at least one thread in every process. Threads have their own stacks, but since threads of a process are in the same virtual address space, they can access each others stacks. Sometimes it's useful to share on-stack data between threads, but it should be done carefully so as not to corrupt thread states and cause hangs or crashes.


text:
Q: Rails-customize confirm dialog <%= link_to image_tag("icon_delete.png", :border => 0), user, method: :delete ,data: { confirm: 'Are you sure delete ' + user.email } %>

When user clicks on this link, I want a custom confirm dialog instead of simply showing confirm('Are you are').
I've read many threads, for example http://lesseverything.com/blog/archives/2012/07/18/customizing-confirmation-dialog-in-rails/.  However, I hit on issue Sprockets::EncodingError.
Any better solution?
UPDATE
Everything ok before implemented customized confirmation dialog,After encoding successful, This time
<%= link_to image_tag("icon_delete.png", :border => 0), user, method: :delete ,data: { confirm: 'Are you sure delete ' + user.email } %>

Actually,When I click on delete icon,no popup show and this link didn't call destroy() in UserController.It called show() on UserController.What's going on here?
$.rails.allowAction = (link) ->
return true unless link.attr('data-confirm')
$.rails.showConfirmDialog(link) # look bellow for implementations
false # always stops the action since code runs asynchronously

$.rails.confirmed = (link) ->
link.removeAttr('data-confirm')
link.trigger('click.rails')

$.rails.showConfirmDialog = (link) ->
message = link.attr 'data-confirm'
html = """

         ×

Are you sure Mr. President?

#{message}

         Cancel
         OK

     """
$(html).modal()
$('#confirmationDialog .confirm').on 'click', -> $.rails.confirmed(link)

File route.rb
     root :to => "users#index"
 devise_for :users, :controllers => {:registrations => "users"}
 resources :users
 match '/admin',   to: 'users#admin',   via: 'get'

A: Sounds like it's the same issue you're looking at. It sounds like the solution is to open the .js file with a text editor and save it as UTF-8 encoding.
Go to "Save with Encoding" menu and choose "UTF-8".
In the Sublime Text 2 this is in File > Save with Encoding > UTF-8.


text:
Q: C#: Stop Git commit if NUnit test fails I have a VS Solution the structure of which you can see here:
Solution Explorer Screenshot
I'm using NUnit 3.2.0 to run my tests.
How can I stop commits to my local branch if the NUnit test fails and display a message on the Git bash?
I read something about pre-commit hooks. How do I implement that here?
I'm using the NUnit Console Runner to test my UnitTests.dll using the following command line argument:
nunit3-conosle.exe UnitTests.dll /wait

P.S. Please let me know in the comments if you require more information regarding this.


text:
Q: Container View in Storyboard isn't allowed make more than one segue
I try to add more children for Container view but prevent me and only make one segue.

A: Make the connections from the view controller instead from a subview.


text:
Q: how to convert hashmap data to bitmap is it impossible if I want to transform the hashmap data to bitmap?
my data is like this

02-01-2022 15:20:04.038=[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 16.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

from this program
Map<String,Object> rightDataDict = new HashMap<>();
rightDataDict.put(String.valueOf(formatter.format(date)), Arrays.toString(r_data_double_arr));

Update our 2D array data:

[[0.0, 28.0, 80.0, 61.0, 8.0, 9.0, 0.0, 0.0, 13.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 31.0, 37.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 46.0, 63.0, 8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 63.0, 44.0, 26.0, 9.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],[0.0, 30.0, 80.0, 59.0, 5.0, 6.0, 0.0, 0.0, 12.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 35.0, 39.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 52.0, 64.0, 7.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 65.0, 44.0, 24.0, 8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]....]

Our 2d array looks like this, the size will be 50*89

A: Found something relevant:
Convert String to Bitmap
Try to convert or change <String, Object into <Integer, String> or <String, String>.
And add this before the method in the link above:
String output="";
for(String s:rightDataDict.values()){
    output+=s;
}

But if you don't want that idea... Try this:
String output="";
for(Object o:rightDataDict.values()){
    output+=o; /*If you hit an iceberg, try this: output+=(o+"");*/
}

Now with your 2d array just replace the for-each loop with this:
String output="";
for(int i:intArray){
    output+=(i+"");
}


text:
Q: MySQL Partitioning a table with an auto incrementing BIGINT unique primary key I have a hypothetical table with a primary key that is a BIGINT. Let's say my table grows very large and I have to partition and create different partitions by date range. What happens with primary key? Does that mean I can exceed the capacity of the BIGINT since there are more tables now? How does MySQL keep from assigning duplicate primary keys assuming a BIGINT set to auto increment a unique value?
Thanks in advance...

A: Partitioning doesn't create a new table. There is still one table with many partitions. Auto increment unique value keeps it functionality. Data grouped in partitions by date field that you choose to create partitions with.
Take a look at this : http://dev.mysql.com/tech-resources/articles/mysql_55_partitioning.html


text:
Q: Store, sort, and filter for multiple values in same column I use an Excel table to manage a large database containing metadata of files along the following lines:
 Context     Activities         File         Folder
----------------------------------------------------------
 home        play, homework     filename1    folder/path/
 home        play, dinner       filename2    folder/path/
 school      test               filename3    folder/path/
 school      teaching           filename4    folder/path/
 playground  play, rest, talk   filename5    folder/path/
 fields      work, play, rest   filename6    folder/path/

Several columns ("Activity" in the example above) contain multiple values.  On the one hand, I'd like to be able to filter the database for specific values.
The sort/filter popup window displays all combinations of values in cells separately (such as "play, rest, talk", "work, play, rest", etc.).
Is there a way to treat them as separate values (comma-separated, or whatever-separated, I could change the comma to whatever character that would work)?
Eventually, I'd like to be able to filter them selecting all that contain "play", all that contain "play" AND "talk", all that contain "play" OR "talk", and things like "all that contain x, y, but not z," etc.
Does Excel have any way of doing this?

A: Highlight the Context:Activities:File:Folder cells, the goto > Data > filter.
Then click on the "Activities" filter button, > Text Filter.. > Custom Filter..
There you'll see the options set all the mentioned contain/deosNotContain/OR/AND case. (:
Hope it helps.


text:
Q: 3D rotation like credit card in Android I need to provide some 3D rotation of images, like credit card (please check the video in the link)
I want to know is it feasible or not, in the case of Android. If yes, how can I do that.
The card must have some thickness.

A: It definitely is feasible, but you will have to do some studying:-).
Start here: http://developer.android.com/guide/topics/graphics/opengl.html
But you may also achieve your goal by just using the video you have posted in your link.

A: Some context would be useful such as will this be a loading screen? Something in video? etc?
For instance, if you are trying to make a website style layout and have the card up at the top always spinning, I would advice against that on any mobile device as its a waste of performance.
If instead you are using it as a loading screen then again I would advice against it as you are going to spend a lot of time initializing open gl and loading the texture and mesh for the card as well as any lighting you need and then initiate animators and do the spinning etc.
As previously stated OpenGL would be a way of doing this; however, this is not a simple few lines of code. This would be quite the undertaking for someone unfamiliar with OpenGL and 3D modeling to accomplish in a short time frame.

A: Question: do you require a native Android app, or would it be alright to use Flash Player?  You can find tons of interactive 3d geometry demos on http://wonderfl.net - I forked one that had a plane, switched it to a cube, and you can download the results -
3d box on wonderfl
Not OpenGL - the example I found was Papervision3D (which is out of date a couple of years) - but software rendering is fine for 12 triangles.  You, of course, would have to import your card faces as texture images if you want to make it look like a credit card.


text:
Q: Copy a external css file into web-app css folder in grails I have an external css file which I need to read at the gsp page.
I have created a environment variable as "SAM_THEME".
In my bootstrap.groovy file I have read the external css file path.
 def init = { servletContext ->
  String SAM_THEME=System.getenv("SAM_THEME");
print "VCAP_SERVICES"+SAM_THEME;
    servletContext["customcss"] =SAM_THEME;

 }

How when I try to access the servlet context in the gsp page.I am able to get the external css file path, but it is not getting read by the grails application.
       <link rel="stylesheet"
href="${resource(dir: 'css', file: application.customcss)}"
type="text/css">

Since this method is not working,there is any other way of to copy the external css file directly into web-app/css folder while bootstrap so that i can access directly in my gsp page.

A: In your BootStrap you can get the path to the css folder:
class BootStrap {

  def init = { servletContext ->
    println new File(servletContext.getRealPath("/WEB-INF/css")).getAbsolutePath();
  }
}

Then just copy your file to that location.


text:
Q: Matrixcursor with non-db content provider I have a content provider that returns a MatrixCursor for the query() method.
Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
   MatrixCursor cursor = new MatrixCursor(new String[]{"a","b"});
   cursor.addRow(new Object[]{"a1","b1"});
   return cursor;
}

In the LoaderManager's onLoadFinished() callback method I use the cursor data to update a text view.
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    cursor.moveToFirst();
    String text = (String) textView.getText();
    while (!cursor.isAfterLast()) {
        text += cursor.getString(1);
        cursor.moveToNext();
    }
    textView.setText(text);

}

The question now is, how do I add a new row to the MatrixCursor that will notify the change to LoaderManager's callback methods promptly?
I hope, I have made the question clear. Thanks in advance.

A: I hope it's not too late or may be someone else could help.
The tricky thing here. It's you have to make a new cursor every time you query to the contentProvider for this reason I have my item list and every time I query content provider I build a new cursor with my backed item list that have new items.
Why I have to do tha? Otherwise you are going to get an exception becouse CursorLoader attempt to register an observer inside a cursor that already have one.
Notice that the way to build new rows in a CursorMatrix is permitted in api level 19 and above, but you have alternative ways but involve more borring code.
public class MyContentProvider extends ContentProvider {

List<Item> items = new ArrayList<Item>();

@Override
public boolean onCreate() {
    // initial list of items
    items.add(new Item("Coffe", 3f));
    items.add(new Item("Coffe Latte", 3.5f));
    items.add(new Item("Macchiato", 4f));
    items.add(new Item("Frapuccion", 4.25f));
    items.add(new Item("Te", 3f));

    return true;
}

 @Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {

    MatrixCursor cursor = new MatrixCursor(new String[] { "name", "price"});

    for (Item item : items) {
        RowBuilder builder = cursor.newRow();
        builder.add("name", item.name);
        builder.add("price", item.price);
    }

    cursor.setNotificationUri(getContext().getContentResolver(),uri);

    return cursor;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    items.add(new Item(values.getAsString("name"),values.getAsFloat("price")))

    //THE MAGIC COMES HERE !!!! when notify change and its observers registred make a requery so they are going to call query on the content provider and now we are going to get a new Cursor with the new item

    getContext().getContentResolver().notifyChange(uri, null);

    return uri;
}


text:
Q: How to serve a webpage on connection to WiFi network I would like to be able to serve a local webpage (on a LAN) when someone connects to a WiFi network. This happens quite often in libraries, cafes etc, so i'm sure it can be done, but I have no idea how and can't seem to find much through searching the web. That, and my very limited networking knowledge means I'm hoping you guys can point me in the right direction. Many thanks!

A: The term you want to search for is captive portal.

A: You can use m0n0wall to create a captive portal/walled garden.  It's free to download and has a good amount of documentation for setup. (http://m0n0.ch/wall)
If you need some more advanced routing (like redirecting outbound SMTP connections) you can use pfSense which is a fork of the m0n0wall project. (http://www.pfsense.com)
And of course if you want to drop some cash you could use a Nomadix appliance.  (http://www.nomadix.com)

A: This can be achieved via combination of the following:

*

*Deny/refuse/interrupt all connections to non-whitelisted IP's (your web server)

*Intercept and respond to all HTTP/HTTPS requests with a redirect to your web server

Your webserver should include some action to authorize the user, at which point the user is no longer subject to the above behavior.
There are several commercial products to achieve this behavior, but you can also roll your own. I'm not aware of any free, OTS solutions, but I bet you can find one.


text:
Q: CookieContainer memory leak I'm seeing a small memory leak coupled with gradual CPU usage increase over time in an app that is using static HttpClient to regularly hit distinct urls that return set-cookie headers. These issues are solved by setting UseCookies = false on HttpClientHandler. That led me to investigate CookieContainer and I found that it maintains a hashtable (m_domaintable) of domains and for each domain it maintains a sorted list of paths (m_list). So even though cookies are correctly removed based on Capacity and PerDomainCapacity, memory and cpu usage grow over time as these collections grow with each new domain/path that is hit. There are some examples below that show the memory leak.
First example: add a cookie for many distinct domains
var cookieContainer = new CookieContainer();
for (int i = 0; i < 10000; i++)
{
    cookieContainer.Add(new Cookie("name1", "value1", "/", $"test{i}.com"));
}

Second example: add a cookie for the same domain with different paths
var cookieContainer = new CookieContainer();
for (int i = 0; i < 10000; i++)
{
    cookieContainer.Add(new Cookie("name1", "value1", $"/{i}", "test.com"));
}

Is there something I'm missing here in my usage of HttpClient/HttpClientHandler/CookieContainer? The documentation states that HttpClient should re-used throughout the life of an application but that means that CookieContainer will also be re-used and these collections will continue to grow.

A: There is a CookieContainer bug that is causing this issue: https://github.com/dotnet/corefx/issues/33712


text:
Q: Execute vs. Invoke for resolving a Promise in Jint I'm new to Jint and have noticed that calling Invoke on JS code with a Promise does not resolve as expected but calling Execute does. So given this code:

            const string jscode = @"
                function _itest1() {
                    writeConsole('\nStart');
                    _itest2().then((res) => { writeConsole('Step 1, '+res);
                                              writeConsole('Finish');
                                            });
                }

                function _itest2() {
                    writeConsole('in _itest2');
                    return new Promise((resolve, reject) => {
                        resolve('Step 2');
                    });
                }
            ";

            engine.Execute(jscode);
            engine.Execute("_itest1()");  // resolves
            engine.Invoke("_itest1");     // does not resolve

I get the following output
in _itest2
Step 1, Step 2
Finish

Start
in _itest2

Is this the expected behavior for Invoke?  If so, are there other strategies to ensure that a Promise gets resolved when Invoke is used?


text:
Q: How to edit jasper file? I am editing .jasper file using report tool. I am changing the alignment for parameter left to centre then i save that file. it generates the "jrxml" file also. in my Java code I can pass the .jasper location to print some items. but my changes not affect and the old design remains same..
Help me , How can I edit and save .jasper???
public static JasperPrint createRefundPrint(Ticket ticket, HashMap map) throws Exception {
        final String FILE_RECEIPT_REPORT = "/com/floreantpos/report/template/RefundReceipt.jasper";
    TicketDataSource dataSource = new TicketDataSource(ticket);
    return createJasperPrint(FILE_RECEIPT_REPORT, map, new JRTableModelDataSource(dataSource));
}

A: if you use a IReport for editing your .jrxml reports, you should just press the "Preview" button. Then the .jasper report file will be generated automatically in folder that contains the .jrxml file

A: To edit jasper report, you make your changes in the JRXML file. Once you build or compile your report it will generate a .jasper file which is used in your java code.

A: you try make dynamic report.
You do not have a location problem when you generate your own report.
Example;
public JasperDesign createDesign() throws JRException {
    JasperDesign jasperDesign = new JasperDesign();
    jasperDesign.setName("sampleDynamicJasperDesign");
    jasperDesign.setPageWidth(595); // page width
    jasperDesign.setPageHeight(842); // page height
    jasperDesign.setColumnWidth(515);   // column width of page
    jasperDesign.setColumnSpacing(0);
    jasperDesign.setLeftMargin(40);
    jasperDesign.setRightMargin(40);
    jasperDesign.setTopMargin(20);
    jasperDesign.setBottomMargin(20);

    JRDesignExpression expression = new JRDesignExpression();

    //Set style of page.
    JRDesignStyle normalStyle = new JRDesignStyle();
    normalStyle.setName("Sans_Normal");
    normalStyle.setDefault(true);
    normalStyle.setFontName("DejaVu Sans");
    normalStyle.setFontSize(12);
    normalStyle.setPdfFontName("Helvetica");
    normalStyle.setPdfEncoding("Cp1252");
    normalStyle.setPdfEmbedded(false);
    jasperDesign.addStyle(normalStyle);

    /*
    * Generate field dynamically
    * */

    JRDesignField field = new JRDesignField();
    field.setName("firstName");
    field.setValueClass(String.class);
    jasperDesign.addField(field);

    field = new JRDesignField();
    field.setName("lastName");  // set name for field.
    field.setValueClass(String.class);  // set class for field. Its always depends upon data type which we want to get in this field.
    jasperDesign.addField(field);   // Added field in design.

    field = new JRDesignField();
    field.setName("age");
    field.setValueClass(Integer.class);
    jasperDesign.addField(field);

    JRDesignBand band = new JRDesignBand();

    //Title Band
    band = new JRDesignBand();
    band.setHeight(30);

    JRDesignStaticText staticText = new JRDesignStaticText();
    staticText.setText("Person's Specification");
    staticText.setX(0);
    staticText.setY(0);
    staticText.setHeight(20);
    staticText.setWidth(515);
    staticText.setHorizontalAlignment(HorizontalAlignEnum.CENTER);
    band.addElement(staticText);
    jasperDesign.setTitle(band);

    band = new JRDesignBand(); // New band
    band.setHeight(20); // Set band height

    /*Create text field dynamically*/
    JRDesignTextField textField = new JRDesignTextField();
    textField.setX(0);  // x position of text field.
    textField.setY(0);  // y position of text field.
    textField.setWidth(160);    // set width of text field.
    textField.setHeight(20);    // set height of text field.
    JRDesignExpression jrExpression = new JRDesignExpression(); // new instanse of expression. We need create new instance always when need to set expression.
    jrExpression.setText(""" + "First Name: " + """ + "+" + "$F{firstName}"); //  Added String before field in expression.
    textField.setExpression(jrExpression);  // set expression value in textfield.
    band.addElement(textField); // Added element in textfield.

    textField = new JRDesignTextField();
    textField.setX(160);
    textField.setY(0);
    textField.setWidth(160);
    textField.setHeight(20);
    jrExpression = new JRDesignExpression();
    jrExpression.setText("$F{lastName}" + "+" + """ + " :Last Name" + """); // Added string after field value
    textField.setExpression(jrExpression);
    band.addElement(textField);

    textField = new JRDesignTextField();
    textField.setX(320);
    textField.setY(0);
    textField.setWidth(160);
    textField.setHeight(20);
    jrExpression = new JRDesignExpression();
    String age = """ + "" + """ + "+" + """ + "Age is: " + """ + "+" + """ + "" + """ + "+" + "$F{age}" + "+" + """ + "" + """;  // added html in text field with different color.
    jrExpression.setText(age);
    textField.setExpression(jrExpression);
    textField.setMarkup("html"); // By Default markup is none, We need to set it as html if we set expression as html.
    band.addElement(textField);
    ((JRDesignSection) jasperDesign.getDetailSection()).addBand(band);

    return jasperDesign;
}

A: You can compile a .jrxml in Project Explorer window of Jaspersoft Studio. For that first find your .jrxml report and rightclick on it. In context menu choose 'Compile report'. Then you get compiled .jasper report.


text:
Q: MySql Query to retrieve a a set number from each group If I have the table:
------------------
| Provider | ID  |
------------------
| X        | 125 |
------------------
| X        | 133 |
------------------
| X        | 342 |
------------------
| X        | 327 |
------------------
| Y        | 123 |
------------------
| Y        | 853 |
------------------
| Y        | 123 |
------------------
| Z        | 853 |
------------------
| Z        | 533 |
------------------
| Z        | 174 |
------------------

I want to get 2 random entries from each of the providers X and Y (ignoring Z) to produce
X  id
X  id
Y  id
Y  id

I've tried several queries including
select id, provider from tableName a where (SELECT COUNT(*) FROM tableName b where b.provider =  a.provider) = 2;

Any ideas?

A: How about you try this query:
select provider, ID, Rank from
(
    select *, @row_num := IF(@prev_value=provider,@row_num+1,1) AS rank, @prev_value := provider from
    (
        select provider, ID, rand() as SortingField from yourTable
        order by provider, SortingField
    ) t1,
    (SELECT @rownum := 0) x, (SELECT @prev_value := '') y
) src
where Rank <= 2 and Provider <> 'Z'

Okay, so here's how it works. First thing first, you need random entries so you need to add a "random" sorting field which I did using mySql's rand() function. Since it gives a random number, your fields will always be sorted randomly.
This sets us up for the next bit of your requirement which is the two random entries. Since your field are sorted randomly, we'll just pick the first two records which are going to be different every time the query runs. To do that, we're going to need a line counter that resets every time the desired field changes value (in your case, it's 'provider'). So that's what we're doing using variable:
@rownum is your row counter and is incremented by 1 every time a new record shows up.
@prev_value is your value checker that you use to determine when the counter needs to be reset. Notice that it's set after the @row_num incrementation, which is critical because if you set it before, you'd be checking against the current value, which would be pointless.
And at last, all you have to do is select the desired fields (provider, ID, Rank) and grab ranks that are inferior to 2 and ignore the 'Z' provider which is what the last part of the query does.
If you have questions, don't hesitate to ask, but I hope my explanation was clear enough.

A: Order by rand() and limit to 2 with a where clause for x and y and union all the results.  Plainly obvious what you're trying to do and easy to maintain.
SELECT Provider, ID
FROM tableName
WHERE provider = 'X'
ORDER BY Rand()
LIMIT 2

UNION ALL

SELECT Provider, ID
FROM tableName
WHERE provider = 'Y'
ORDER BY Rand()
LIMIT 2


text:
Q: Can't change one specific registry value from Java process While I can create/change almost any key in HKEY_CURRENT_USER, it doesn't seem possible to invoke the following command via Runtime.getRuntime().exec(...):
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v "ProxyOverride" /d "<local>" /f

The result of this command is always 0 (success).
Adding different keys via Java works flawlessly. However this one specific key is not visible in regedit afterwards.
Has my Java process different privileges than cmd? Both run with the same user (verified by invoking whoami).

Edit: The solution proposed by David in read/write to Windows Registry using Java doesn't work either.

Edit 2: Turns out, it did actually work but was immediately revoked by a following invocation of a net use command.


text:
Q: TreeCell Line Bindings messing up at scroll I have two TreeViews in my JavaFX GUI, which I fill dynamically. They can have a lot of data, so most of the time, they will be scrollable.
Afterwards, I create connections (or rather edges) between the TreeCells of both TreeViews. I draw a Line from the source cell to the target cell and create Bindings. My code for that is the following:
line.startYProperty().bind(Bindings.createDoubleBinding(() -> {
    Bounds b = sourceCell.getBoundsInParent();
        return b.getMaxY() + b.getHeight() / 2;
    }, sourceCell.boundsInParentProperty()));

line.endYProperty().bind(Bindings.createDoubleBinding(() -> {
    Bounds b = targetCell.getBoundsInParent();
    return b.getMaxY() + b.getHeight() / 2;
}, targetCell.boundsInParentProperty()));

Now, that does work for me, until I start scrolling one of the TreeViews. When the connected cell is scrolled out of the visible area of the treeview, the line position resets and connects itself to a different cell.
I figured that is because the binding is to a TreeCell and they can dynamically change their value depending on the visible data, but what would be the alternative to make it work?
How would I keep the Line bound to the original TreeCell without it changing when scrolled out and back into the view?
My example code:
@Override
  public void start(Stage primaryStage) {
    try {
      AnchorPane root = new AnchorPane();
      Scene scene = new Scene(root, 700, 400);
      primaryStage.setScene(scene);
      primaryStage.show();

      TreeItem sourceRoot = new TreeItem("source");
      sourceRoot.setExpanded(true);
      TreeItem targetRoot = new TreeItem("target");
      targetRoot.setExpanded(true);
      TreeView<String> source = new TreeView<String>(sourceRoot);
      TreeView<String> target = new TreeView<String>(targetRoot);
      target.setLayoutX(400.0);

      root.getChildren().add(source);
      root.getChildren().add(target)

      // fill and randomly select two visible cells
      for (int i = 0; i < 100; i++) {
        sourceRoot.getChildren().add(new TreeItem("ItemS " + i));
        targetRoot.getChildren().add(new TreeItem("ItemT " + i));
      }
      TreeCell<String> sourceCell = (TreeCell<String>) source.lookupAll(".tree-cell").toArray()[2];
      TreeCell<String> targetCell = (TreeCell<String>) target.lookupAll(".tree-cell").toArray()[4];
      Line line = new Line();

      line.setStartX(source.getWidth());
      line.startYProperty().bind(Bindings.createDoubleBinding(() -> {
        Bounds b = sourceCell.getBoundsInParent();
        return b.getMinY() + b.getHeight() / 2;
      }, sourceCell.boundsInParentProperty()));
      line.setEndX(target.getLayoutX());
      line.endYProperty().bind(Bindings.createDoubleBinding(() -> {
        Bounds b = targetCell.getBoundsInParent();
        return b.getMinY() + b.getHeight() / 2;
      }, targetCell.boundsInParentProperty()));

      root.getChildren().add(line);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    launch(args);
  }


text:
Q: ambiguity check and liberal coverage condition failures for code working under GHC 7.6 I had a clever bit of type-level machinery that worked on GHC 7.6 but not later versions. Looking back I'm not totally sure why it ever worked, but regardless I would like to get back this functionality somehow:
{-# LANGUAGE
    PolyKinds
  , FunctionalDependencies , FlexibleInstances , FlexibleContexts
  , OverlappingInstances
  , ScopedTypeVariables
  , TypeFamilies
  , UndecidableInstances
 #-}
module M where

import Data.Proxy

-- | A relation between a (maybe-partially-applied) type and that type fully
-- applied.
class Applied t (tab :: *) | t -> tab where
    -- | Fully apply a type @t@ with polymorphic arguments, yielding @tab@.
    applied :: Proxy t -> Proxy tab

instance Applied (t a) tab=> Applied t tab where
    applied _ = applied (Proxy :: Proxy (t a))

instance t ~ tab=> Applied t tab where -- always matches when `t` is kind `*`
    applied _ = Proxy :: Proxy tab

This depends on the tagged library on GHC 7.6. We can use it like:
$ ghci-7.6.3
Prelude> :l M.hs
[1 of 1] Compiling M                ( M.hs, interpreted )
Ok, modules loaded: M.
*M>
*M> :t applied (Proxy :: Proxy Either)
applied (Proxy :: Proxy Either) :: Proxy (Either a a1)
*M> (return $ Right 'a') == applied (Proxy :: Proxy Either)
True

However this doesn't compile on at least GHC 7.8.3 or later:
$ ghci-7.8.3
GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :l M.hs
[1 of 1] Compiling M                ( M.hs, interpreted )

M.hs:19:10:
    Could not deduce (Applied (t a0) tab)
      arising from the ambiguity check for an instance declaration
    from the context (Applied (t a) tab)
      bound by an instance declaration:
                 Applied (t a) tab => Applied t tab
      at M.hs:19:10-42
    The type variable 'a0' is ambiguous
    In the ambiguity check for:
      forall (k :: BOX) (k1 :: BOX) (t :: k1 -> k) tab (a :: k1).
      Applied (t a) tab =>
      Applied t tab
    To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
    In the instance declaration for 'Applied t tab'

M.hs:19:10:
    Illegal instance declaration for 'Applied t tab'
      The liberal coverage condition fails in class 'Applied'
        for functional dependency: 't -> tab'
      Reason: lhs type 't' does not determine rhs type 'tab'
    In the instance declaration for 'Applied t tab'
Failed, modules load

I think the answer here is related, but I don't yet understand the suggestion.
It's possible I might be able to work around this. The only place I use this class is in a signature of the form:
instance (Foo tab, Applied t tab)=> Bar (Proxy t) where

Which might indicate I want to make Foo kind-polymorphic, but this is in a big complicated library and I don't know if that change would be possible.

A: Your ghci example works for me in ghc-7.8.3 if I get rid of the FD, and enable -XAllowAmbiguousTypes. That extension will require you to annotate (using ScopedTypeVariables) the type of that applied function when it is used in instance (Foo tab, Applied t tab)=> Bar (Proxy t).


text:
Q: How to access a site on Codero without a domain name and without appending the username to the end Yesterday i have created a new site on my Codero Dedicated Server. and i have not assigned any domain name yet to the ip address.
Currently i am able to access my site with http://MySiteIpAddress/~username but i want to access it with only http://MySiteIpAddress/. Is there any way to do it. I don't know if that's  possible by htaccess rules, so any hints are appreciated.

A: You want to setup a virtual host and point it to the folder you want.
See this other post for more details.

You need to do several steps in order to make this work.

1.) Update the hosts file. On Windows XP, you can find it under c:\WINDOWS\system32\drivers\etc\. You should already see the first
  line from below, it takes care of your mentioned other project. - add
  the additional ones to make any requests to the mentioned virtual
  hosts routed back to your own machine.
127.0.0.1       localhost
127.0.0.1       foo-bar.com
127.0.0.1       abcdef.com
127.0.0.1       qwerty.com

2.) Update the vhosts file in Apache configuration. Under your XAMPP folder, add the following to
  apache\conf\extra\httpd-vhosts.conf and if needed change the ports
  (i.e. if you use 8080 instead of port 80).
<VirtualHost *:80>
  DocumentRoot C:/xampplite/htdocs/foo-bar/
  ServerName www.foo-bar.com
</VirtualHost>
<VirtualHost *:80>
  DocumentRoot C:/xampplite/htdocs/abcdef/
  ServerName www.abcdef.com
</VirtualHost>
<VirtualHost *:80>
  DocumentRoot C:/xampplite/htdocs/qwerty/web/
  ServerName www.qwerty.com
</VirtualHost>

3.) Do a quick configuration check. Open {XAMPP-folder}\apache\conf\httpd.conf your file and make sure that
  the following part is not commented out by a preceeding # character:
Include conf/extra/httpd-vhosts.conf

4.) Restart XAMPP.
 ... and you should be all setup now. Your other project should
  be accessible at the URI you mentioned if you just put it under
  C:/xampplite/htdocs/my-project/.


text:
Q: "Back to search results" problem I have a form with many inputs, but not all inputs must be filled in.
Form action is set to a php file, which checks which inputs are set and builds a query to query MySQL.
Then I display the results on the main page, and the users may click on an ad to show.
When clicked an ad, a new page opens with several options for the user (change ad, delete ad, save ad etc).
On this page, I am currently struggling with a 'back to search results' button/link. I don't know how to do this. I thought firstly about the 'history.go' to just make a 'back' button, but if the users would use one of the options on the page then the 'back' wouldn't work!
Another way would be to somehow save the query in a hidden input and pass it to the 'show ad' page or something... But this seems unsafe as the query is visible to users!
Do you have any ideas or suggestions?
Thanks

A: Save the data you need to build the query in the page. This could be a copy of the original form with all the input types converted to hidden.


text:
Q: Как при помощи JS удалить последний символ из слова в html документе? Допустим слово Домик, последняя буква К должна удалиться в html документе, то есть в html должно остаться только "Доми" ну или хотя бы, чтобы на экране было "Доми"
Желательно использовать метод replace.
Набросал код, но я не понимаю, что еще написать, дабы достичь результата.

let word = document.querySelector('.Slovo');
alert(word.innerHTML.replace(/.$/, '')); // по идее /.$/ должна удалить последний символ, но она не удаляет.
// Что еще написать, дабы получить желаемый результат?

  ДОМИК

A: В вашем случае мешают пробелы после слова. Если от них избавиться, то replace отработает как надо.

Мой вариант с slice

let word = document.querySelector('.Slovo');

alert(word.textContent.trim().slice(0, -1));

  ДОМИК

*

*trim - для очистки пробелов

*slice - для взятия всей строки без последнего символа


text:
Q: SQL Server - standard pattern for doing row by row operations on a table/view I want to iterate through a table/view and then kick off some process (e.g. run a job, send an email) based on some criteria.
My arbitrary constraint here is that I want to do this inside the database itself, using T-SQL on a stored proc, trigger, etc.
Does this scenario require cursors, or is there some other native T-SQL row-based operation I can take advantage of?

A: Your best bet is a cursor. SQL being declarative and set based, any 'workaround you may find that tries to force SQL to do imperative row oriented operations is unreliable and may break. Eg. the optimizer may cut out your 'operation' from the execution, or do it in strange order or for an unexpected number of times.
The general bad name cursors get is when they are deployed instead of set based operations (like do a computation and update, or return a report) because the developer did not found a set oriented way of doing the same functionality. But for non-SQL operations (ie. launch a process) they are appropriate.
You may also use some variations on the cursor theme, like client side iterating through a result set. That is very similar in spirit to a cursor, although not using explicit cursors.

A: The standard way to do this would be SSIS. Just use an Execute SQL task to get the rows, and a For Each task container to iterate once per row. Inside the container, run whatever tasks you like, and they'll have access to the columns of each row.

A: If you are planning on sending an email to each record with an email address (or a similar row-based operation) then you would indeed plan on using a cursor.
There is no other "row-based" operation that you'd do within SQL itself (although I like John's suggestion to investigate SSIS - as long as you have SQL Server Standard or Enterprise).  However, if you are summing, searching or any other kind of operation and then kicking off an event once done the entire selection set, then you would certainly not use a cursor.  Just so you know - cursors are generally considered a "last resort" approach to problems in SQL Server.

A: The first thought which comes to my mind when I need to iterate over the result set of a query is to use cursors. Yes, it is a quick and dirty way of programming. But cursors have their setbacks as well - They incur overheads and can be performance bottle necks.
There are alternatives to using cursors. You can try using a temp table with an identity column. Copy you table to the temp table and using a while loop to iterate over the rows. Then based on a condition call your stored procedure.
Here, check this link for alternatives to cursors - http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1339242,00.html
cheers


text:
Q: Google Maps geocoder to find nearby places from MySQL database I have a website where I store locations in a MySQL database and GeoCode using the address provided by the database.
Now I want to add a feature which will find the closest places to the specified point e.g. the location they are standing now or typing. I'm coding the geocoder and google maps in JavaScript and jQuery and I get the results using PHP to fetch from the database.
I read about the viewport but I can't figure out how it would work in my situation where I need to show my own database locations and not Google's.
Can anybody help? And it would be awesome if you have some kind of example.

A: radius search:
select *,
    acos(cos(centerLat * (PI()/180)) *
     cos(centerLon * (PI()/180)) *
     cos(lat * (PI()/180)) *
     cos(lon * (PI()/180))
     +
     cos(centerLat * (PI()/180)) *
     sin(centerLon * (PI()/180)) *
     cos(lat * (PI()/180)) *
     sin(lon * (PI()/180))
     +
     sin(centerLat * (PI()/180)) *
     sin(lat * (PI()/180))
    ) * 3959 as Dist
from TABLE_NAME
having Dist < radius
order by Dist

3959 is the Earth radius in Miles. Replace this value with
radius in KM, or any unit, to get results on the same unit.
centerLat and centerLon are the center of the search (your
input), while lat and lon are fields in the table.

A: Here's what I would do:

*

*Since you use a database anyway, convert and save the human-readable address to a LatLng (once) every time you add a place to your DB

*Query user for his/her location

*geocode the user location to a LatLng

*use a SQL query to find places matching desired distance. (see here https://developers.google.com/maps/articles/phpsqlsearch_v3)
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

*

*display SQL results back to Javascript map

A: Sounds like the classic store locator.  See this article in the Google Maps API v3 documentation for an example using PHP and MySQL.


text:
Q: Quotients of $\mathbb Z[X]$ by irreducible polynomials
Suppose we have an irreducible polynomial $f\in \mathbb Z[X]$ and say $r$ is a root of $f$ in $\mathbb C$. Is it true that $\mathbb Z[X]/(f(X))$ is isomorphic to $\mathbb Z[r]$ ?

I ask since it seems to work for cyclotomic polynomials but I do not understand why.

Can we generalize it to an integral domain $R$ (instead of $\mathbb Z$) and an algebraic closure of $\mathrm{Frac}(R)$ (instead of $\mathbb C$) ?

A: This adds details to DonAntonio's answer and generalizes it to the case in which $R$ is a UFD. The main point that requires clarification is why the kernel of the morphism he defines consists of the principal ideal generated by $f$.
There is a theorem that says that if $R$ is a UFD and $K$ its field of fractions, then $R[X]$ is also a UFD, and the prime factorization of a polynomial  $f$ in $R[X]$ is $f = ap_1 \cdots p_n$, where the $p_i$'s are irreducible in $K[X]$ and $a \in R$ is a constant. (Technically, I should also write $a = uq_1 \dots q_n$ for the factorization of $a$ in $R$.) Also, if $p \in R[X]$ is nonconstant, then it is irreducible in $R[X]$ if and only if it is irreducible in $K[X]$ and its coefficients have no common factors (Gauss's Lemma). So, except for constant factors, the decomposition of any polynomial is the same in $R[X]$ or in $K[X]$.
In your situation, you have a polynomial $f$ that is assumed irreducible in $R[X]$, and $f(r) = 0$. Of course, $f$ cannot be constant. From the above, $f$ is also irreducible in $K[X]$. Now if $g \in R[X]$ and $g(r) = 0$, then certainly $f$ divides $g$ in $K[X]$. If we write the decomposition $g = a p_1 \dots p_n$ in $R[X]$, this is also a valid decomposition in $K[X]$, hence $f$ must be, except for a constant factor, one of the $p_i$'s. But $f$ and $p_i$ are both irreducible in $R[X]$, so they differ by a factor which is a unit of $R$. Therefore $f$ divides $g$ in $R[X]$.
This proves that the morphism in DonAntonio's answer induces an isomorphism between $Z[x]/(f)$ and $Z[r]$.

A: Just apply the first isomorphism theorem for ring homomorphisms:
$$\phi:
\Bbb Z[x]\to\Bbb Z[r]\;,\;\;\phi(q(x)):=q(r)$$


text:
Q: How to refresh main activity after deleting a list item in another activity? I have 3 Activities in application, namely ExpenseSummary, AddExpense, ExpenseList.
I am using cursor adapter to populate the Expense List.
Here is code snippet from ExpenseCursorAdapter
        Button deleteItem=(Button)view.findViewById(R.id.deleteItem);
        deleteItem.setTag(cursor.getString(cursor.getColumnIndex(ExpenseEntry.COLUMN_NAME_ID)));
        final ExpenseTrackerDBHelper db_helper = new  ExpenseTrackerDBHelper(context);

        deleteItem.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                deleteRecordWithId(itemId);
                cursor.requery();
                notifyDataSetChanged();
            }

            private void deleteRecordWithId(String itemId) {
                String selection = ExpenseEntry.COLUMN_NAME_ID + " = ?";
                // Specify arguments in placeholder order.
                String[] selectionArgs = { String.valueOf(itemId) };
                // Issue SQL statement.

                SQLiteDatabase db = db_helper.getWritableDatabase();
                db.delete(ExpenseEntry.TABLE_NAME, selection, selectionArgs);
            }
        });

When I try to delete an item it is removed from the list. Though I am not sure if it is getting deleted from database.
Now if click back button which show the EspenseSummary Activity which shows total of all the expenses using following code in on_create method.
public void showExpenseTotal(){
  ExpenseTrackerDBHelper mDbHelper = new ExpenseTrackerDBHelper(this);
  SQLiteDatabase db = mDbHelper.getReadableDatabase();

  long total_expense = 0;
  Cursor cursor;
  cursor = db.rawQuery("SELECT SUM(amount) FROM Expenses;", null);
  cursor.moveToFirst();
  total_expense = cursor.getLong(0);
  String total = Long.toString(total_expense);

  expenseTotal.setText(total.toString());
}

Update:
protected void onResume(Bundle savedInstanceState) {
    showExpenseTotal();
}

This total is not updated. Item deletion is not reflecting in summary page.
Though if I add a new expense the total shown becomes correct.
Please help me here. I am new with Android.

A: You should use onResume() to update your changes since ExpenseSummary is already created , going back will not call onCreate() again.. it will be resumed.
You should learn more about Activity's LifeCycle
http://developer.android.com/training/basics/activity-lifecycle/index.html

A: You have to call
adapter.notifydatasetchanged()

This notifies all the observers that your data set has changed. Do this in onResume() of your activity.


text:
Q: JS function call won't work in Chrome and Opera (JS + jQuery) I can't seem to get the following functionality to work under Chrome and Opera (latest versions on Windows XP).
The code is:
$.getScript('/js/modules/'+module+'.js', function() {
    setTimeout('window.'+module+'_init()', 800);
});

Everything seems to work fine, the script loads, init function exists (a few debug alerts within that setTimeout statement verified that type of "window.module_init" really is a function) but the function just won't run.
I tried putting a simple alert at the beginning of that init function, leave ONLY an alert there - nothing helped.
I must say I'm quite puzzled by this, as this works just fine under Firefox and MSIE.
FYI, the init function in that external js file simply looks like this:
function notifications_init() {
    alert('test');
}

"notifications" is the value of my "module" variable above
Any advice is greatly appreciated :-)

A: setTimeout(window[module+'_init'], 800);

A: How about setTimeout('window.'+module+'_init', 800);, without the braces?

A: I've just tested what you are explaining here and it worked great here. I am guessing that the external js file that you are loading using $.getScript contains errors.
Could you comment everything inside that file except for the notifications_init() you have in your question?
This is what I did:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        alert('start');
        var module = 'test';
        $.getScript('/Scripts/' + module + '.js', function () {
            alert('script was loaded and executed');
            setTimeout('window.' + module + '_init()', 800);
        });
        alert('finish');
    });
</script>

And test.js contains only this:
function test_init() {
    alert('test function');
}


text:
Q: Creating a mobile version of Wordpress site How can I create a mobile version of an existing Wordpress site?
I understand that I can use mobile specific style sheets but how can I adjust the actual template files so there's two versions, one for desktop and one for mobile?
It's not a case of making the site responsive because it's using only parts of the same information. Also, the site is more complicated than just using the various Wordpress mobile plugins.
Is there a way to load a different part of the template depending if it's mobile or desktop? So it'll be using the same template.

A: a little outdated, but this explains how tis was done using WPtouch
https://wordpress.stackexchange.com/questions/3875/how-to-detect-mobile-devices-and-present-them-a-specific-theme
than you can load stylesheet/ theme based on mobile browser (although this would use different templates or CSS files etc)
if ( strpos( $_SERVER['REQUEST_URI'], '/wp-admin' ) === false ) {
    add_filter( 'stylesheet', array(&$this, 'get_stylesheet') );
    add_filter( 'theme_root', array(&$this, 'theme_root') );
    add_filter( 'theme_root_uri', array(&$this, 'theme_root_uri') );
    add_filter( 'template', array(&$this, 'get_template') );
}


text:
Q: Finite State Machine Simulation Implementation in ISL+ (Racket) I'm a newbie working through HTDP2 (Felleisen et al.) on my own but have gotten stuck on question #380 of chapter IV -Intertwined Data. The problem is within the context of creating a DSL but I am first reacquainted with a general FSM Simulator and provided with the following code:
; An FSM is a [List-of 1Transition]
; A 1Transition is a list of two items:
;   (cons FSM-State (cons FSM-State '()))
; An FSM-State is a String that specifies a color

; data examples
(define fsm-traffic
  '(("red" "green") ("green" "yellow") ("yellow" "red")))

; FSM FSM-State -> FSM-State
; matches the keys pressed by a player with the given FSM
(define (simulate state0 transitions)
  (big-bang state0 ; FSM-State
    [to-draw
     (lambda (current)
      (overlay (text current 12 "black")
               (square 100 "solid" current)))]
[on-key
  (lambda (current key-event)
    (find transitions current))]))

; [X Y] [List-of [List X Y]] X -> Y
; finds the matching Y for the given X in alist
(define (find alist x)
  (local ((define fm (assoc x alist)))
    (if (cons? fm) (second fm) (error "not found"))))

The problem is then stated as follows:
Reformulate the data definition for 1Transition so that it is possible to restrict transitions to certain keystrokes. Try to formulate the change so that find continues to work without change. What else do you need to change to get the complete program to work? Which part of the design recipe provides the answer(s)? See exercise 229 for the original exercise statement.
Exercise 229 introduces a structure type definition to keep track of the states and the transitions but since the problem statement asks me to stay within the provided find function I am hard pressed to come up with a similar structure type of definition. Instead I came up with the following Data Definition:
; An FSM is a [List-of Transition]
; A Transition is a two-item list of the following form:
; (cons FSM-State (cons (cons KeyEvent (cons FSM-State '()))'()))

; data example
(define fsm-traffic (list (list "red" (list "r" "green"))
                          (list "green" (list "g" "yellow"))
                          (list "yellow" (list "y" "red"))))

Hence calling (find fsm-traffic "green") I get (list "g" "yellow") I have thus modified the on-key clause as follows:
(lambda (current key-event)
  (if (string=? key-event (first (first (rest (first transitions)))))
      (second (find transitions current))
      (error "invalid input")))

Now if I start the program with (simulate "red" fsm-traffic) State0 is rendered and if I press "r" it goes to "green" FSM-State but then it won't accept "g" to go to the following state and so on.
If I begin the world-program with (simulate "yellow" fsm-traffic) then FSM-State "yellow" is rendered but it will not transition to any other state (the error clause is activated); similarly with "green" as the starting state.
My hunch is that since I defined fsm-traffic with the "red" state first it accepts its input to transition to "green" but since the same is not happening with the other states big-bang is not "juggling" the transitions parameter right. But I just don't know how to fix that. I also don't know if I've gone wrong since the start with my data definition.
Thank you in advance for helping me out.
P.D. please let me know if I have followed the rules on posting on stackoverflow (this is my first post :).

A: You identified the source of the problem is correctly. You defined fsm-traffic with the "red" state and the "r" transition first, and the on-key handler only looks at the first. It does this in the if question:
(string=? key-event (first (first (rest (first transitions)))))
;                    ^                   ^
;                    |                   this makes it only look at `"red"`
;                    this makes it only look at `"r"` within that

This if question seems complicated. Just like we would do if it was a function with a signature and purpose, we can design the inputs, output, and purpose of this expression.
Inputs: What should it depend on?
Which keys are valid depends on the transitions table, but it also depends on the current state. This is the reason why only "r" is valid on the "red" state, but "g" is valid on the "green" state. So its inputs are:
current : FSM-State
key-event : KeyEvent
transitions : FSM

Your existing expression ignores current.
Output and purpose
It is an if question, so it should output a Boolean. The purpose of this boolean is to determine whether the key is valid on the current state.
It should be true when there is any transition in the table for both the current state and the key-event.
This purpose statement with "any" and "both" sounds complicated enough that it deserves to be its own function. Using the inputs, output, and purpose we just made:
;; FSM-State KeyEvent FSM -> Boolean
;; Determines whether there is any transition in the FSM table for both the current
;; state and the key event.
(define (transition-for-state-and-key? state key table)
  ....)

Your current expression for the body this doesn't include the state,
(string=? key (first (first (rest (first table)))))

But the actual body should depend on both state and key.
Just like this depends on both, the find function should also depend on both state and key.
;; FSM-State KeyEvent FSM -> FSM-State
;; Finds the matching transition-state from the given state with the given key in the table.
(define (find-transition-state state key table)
  ....)

And note the relationship between transition-for-state-and-key? and find-transition-state. The transition-for-state-and-key? function should return true exactly when find-transition-state won't error.
This should be enough for you to continue.


text:
Q: merging multiple Strings in java I have a task where I'm asked to create a method that merges multiple Strings so that the first character in the first string is followed by the first character in the 2nd String followed by the first character in the 3rd string and so on.
public static String merge(String... s)

if I would merge("AH", "HI", "U") the result would be AHUHI. I'm just not quite sure how to deal with this problem when the amount of Strings are unknown, someone has any idea how this could be executed?¨
This is what I tried:
public static String merge(String... s)
    {
        StringBuilder b = new StringBuilder();

         for(int i = 0; i < s.length ; i++)
         {
             for(int y = 0; y < s.length ; y++)
             {
             b.append(s[y].charAt(i));
             }
         }
         return b.toString();
    }

and this is the exception I got:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

A: *

*Find maxLength (the length of the longest String in your arguments) and change the outerloop to iterate maxLength times

*Before you access a char of a String via charAt() check if the String is long enough, so you wont get the StringIndexOutOfBoundsException
Since you are already dealing with multiple input Strings, the code should work fine after these changes.
public static String merge(String... strings)
{
    int maxLength = 0;
    StringBuilder sb = new StringBuilder();

    // find the longest
    for (String s : strings)
        if (s.length() > maxLength)
            maxLength = s.length();

    // build the output string
    for (int i = 0; i < maxLength; i++)
        for (String s : strings)
            if (s.length() > i)
                sb.append(s.charAt(i));

    return sb.toString();
}

A: You're on the right lines, but you need to check that each string you're referencing is big enough not to throw the StringIndexOutOfBoundsException.  So first, try getting the max string length:
public static String merge(String... s)
{

    int maxLen = 0;
    for (String str : s) // this loops through each string in the array s
    {
        maxLen = Math.max(maxLen, str.length());
    }

    // maxLen is now the length of the longest string;

    StringBuilder b = new StringBuilder();

    for (int i = 0; i < maxLen; ++i) // for each character position up to the max...
    {
         for (String str : s) // loop through each string:
         {
             if (str.length() > i) // check whether current string has any characters left
             {
                 b.append(str.charAt(i));
             }
         }
     }
     return b.toString();
}

A: Thats how I would do it:
Basically, you loop though every String and always take the 1st, 2nd, 3rd, ... character of the String and append it to the StringBuilder.
private static String merge(String... strings) {
    StringBuilder sb = new StringBuilder();
    int adv;
    boolean edited;

    adv = 0;
    edited = true;
    while (edited) {
        edited = false;
        for (String s : strings) {
            if (adv < s.length()) {
                sb.append(s.charAt(adv));
                edited = true;
            }
        }
        adv++;
    }
    return sb.toString();
}

A: This is how I would do it:
public static String merge(String... s)
{
    // Here we create a StringBuilder, this will store our result string
    StringBuilder b = new StringBuilder();

    // This boolean will control when we stop appending
    boolean appended = true;

    // The outer loop will loop over the indices of the available characters
    // until we have no more characters to append
    for (int i = 0; appended; ++i) {
        // We have to default this to false to start our loop so that we don't
        // exit early
        appended = false;
        // Loop over the individual strings that we were passed
        for (String item : s) {
            // If the string we are looking at has a character at the current
            // position, we append it to our StringBuilder, otherwise we skip
            // it
            if (i < item.length()) {
                b.append(item.charAt(i));
                // Because we appeneded a character, we might have additional
                // characters, so set this so that our loop continues
                appended = true;
            }
        }
    }
    // Now we call the toString() method of StringBuilder to get a String
    // result, which we return to our caller.
    return b.toString();
}

A: Split each String into a array.  Similar to this: Split string into array of character strings
Then go through the array and take out index 0 and assign it to a new string, and do that for index 1, and so on.


text:
Q: Xamarin.Forms Xaml background Image I just started a Xamarin.Forms application and I want to add a background image to my XAML.
I added the attribute but it does not appear when I run it!!
Here is the images.
APP
public class App : Application
{
    public App()
    {
        // The root page of your application
        MainPage = new Page();
    }

XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App1.Page"
         BackgroundImage="bg.png">

SO, how do I fix it?

A: Add your bg.png file in each of your native projects, since you are currently using a Android emulator start with your Xamarin.Android project:

Android - Place images in the Resources/drawable directory with Build Action: AndroidResource

ref: https://developer.xamarin.com/guides/xamarin-forms/working-with/images/
Example: In your Xamarin.Android project, add bg.png as shown:

Check the Build Action of that image and ensure that it is assigned AndroidResource. Rebuild and re-test.

A: In Xamarin.forms

*

*The images should be placed in the following folders
   iOS, Android  - Resources folder

   Windows/UWP, Windows Phone  - Assets folder

*Then the build action(rt click img->properties) of the images should be changed as follows
iOS - BundleResource             Windows Phone - Content

Android - AndroidResource        Windows/UWP - Content

If Still the image is not displayed, try changing the Copy to Output Directory to Copy if newer in image Properties

A: If you want to add background image in XAML file for the entire page in Xamarin project, then use the BackgroundImage property and add your image to the Android project under Resources -> drawable folder and for iOS Resources folder.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:PhoneDailerDemo"
             x:Class="PhoneDailerDemo.MainPage"
             BackgroundImage="image3.jpg">

    <Label Text="Welcome to Xamarin Forms!"
           VerticalOptions="Center"
           HorizontalOptions="Center" />
    <StackLayout Padding="100">
       //..........
    </StackLayout>
</ContentPage>

A: Reducing the size of the image worked for me.

A: Another way (source) you can achieve this, is by setting the image's build action (in file properties) as Embedded Resource.
Then, using a converter markup-extension you will be able to use it directly in XAML and won't have to copy or link the files in each platform specific project.
Here's the converter you should add to you portable project:
[ContentProperty(nameof(Source))]
public class ImageResourceExtension : IMarkupExtension
{
  static readonly Assembly CurrentAssembly =
    typeof(ImageResourceExtension).GetType().Assembly;

  public const string Assets = nameof(Assets);

  public string Source { get; set; }

  public object ProvideValue(IServiceProvider serviceProvider)
  {
    if (string.IsNullOrWhiteSpace(Source))
      return null;

    // Do your translation lookup here, using whatever method you require
    var source = $"{CurrentAssembly.GetName().Name}.{Assets}.{Source}";

    var imageSource = ImageSource.FromResource(source, CurrentAssembly);

    return imageSource;
  }
}

Then in your XAML:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:local="clr-namespace:WorkingWithImages;assembly=WorkingWithImages"
   x:Class="WorkingWithImages.EmbeddedImagesXaml">
  <Image Source="{local:ImageResource Background.jpg}"}
</ContentPage>

A: Image files can be added to each application project and referenced from Xamarin.Forms shared code. To use a single image across all apps, the same filename must be used on every platform, and it should be a valid Android resource name (ie. only lowercase letters, numerals, the underscore, and the period are allowed).

*

*iOS - Place images in the Resources folder with Build Action: BundleResource . Retina versions of the image should also be supplied - two and three times the resolution with a @2x or @3x suffixes on the filename before the file extension (eg. myimage@2x.png).

*Android - Place images in the Resources/drawable directory with Build Action: AndroidResource. High- and low-DPI versions of an image can also be supplied (in appropriately named Resources subdirectories such as drawable-ldpi , drawable-hdpi , and drawable-xhdpi ).

*Windows Phone - Place images in the application's root directory with Build Action: Content .

*Windows/UWP - Place images in the application's root directory with Build Action: Content .

You can read more at Working with Images
Loading and displaying images in Xamarin.Forms


text:
Q: Google Analytics - GTag.js: Some non-custom not reported in Analytics reports I set up Google Analytics on my site to track events. However, some default events, i.e. purchase, and exception events do not appear in my Analytics reports. All my custom events appear in the reports as expected. The begin_checkout default event also appears. This inconsistent behavior has me confused.
I can work around this problem by exclusively using custom events, but I don't think I should have to as I'm simply following the documentation. See below for my exception event.
  gtag('event', 'exception', {
    'description': errorStringDefinedEarlier,
    'fatal': false
  });


text:
Q: Send an image with hyperlink via email Java Is there a possibility to send an image with hyperlink via email in Java?

A: You can do this through the library javamail.
Then you'll have to use html (a markup language) which supports hyperlinks.
Here's an example to use html & javamail


text:
Q: MognoDB Compass search key by value I am using MongoDb compass, and I have documents with a lot of keys, and I want to find the key of the document by the value.
For example something like where value = "123" and it will return the Key1, is there a way to do it?
{
    "_id": "57a443c74d854d192afcc451",
    "Key1": "123",
    "Key2": "aaa"
}


text:
Q: Spring + Vue любой запрос HTTP ERROR 404 В ходе некоторых изменений в коде контроллеров полностью перестало работать приложение, на любой запрос возвращается HTTP ERROR 404, причем откат на версию до изменений так же не работает,  как и на любые другие версии, в которых все работало. В настройках WebMvcConfig все настроено и прекрасно работало, никаких изменений не вносил, на попытки изменить конфигурацию в WebSecurityConfig никакой реакции, уже пробовал все, вплоть до полного удаления Spring Security из проекта. Даже пытался собрать новый проект из кода с версии где все работало, результат тот же самый, причем даже полностью без всего бекенда и вообще без Security, результат тот же самый: HTTP ERROR 404

По видимому проблема с файлом index.html, так как он приходит пустым, отднако попытки изменить его расположение на любой другой внутри src/recoursesтак же безрезультатны, либо проблема с webpack так как при запросе нет никаких других запросов в браузере, кроме /
Cамое интересное то, что НИКАКИХ ИЗМЕНЕНИЙ В КОДЕ ФРОНТЕНДА И ВЕБПАКА НЕ БЫЛО, оно просто перестало работать на ровном месте, после изменения когда, совершненно не связанного в загрузкой страниц, до этого все работало отлично очень долгое время
Я надеюсь кто нибудь может помочь с этой ситуаций, у кого была схожая проблема или же хотя бы определить причину или направление, в котором нужно копать, вот код ключевых элементов проекта:
структура проекта

main.js
import Vue          from 'vue'
import VueResource  from 'vue-resource'
import router       from "./router";
import App          from "pages/App.vue"
import Vuetify      from "vuetify";
import BootstrapVue from 'bootstrap-vue'
import Vuesax       from 'vuesax'
import VueMask      from 'v-mask'
import store from 'store'

Vue.use(VueResource);
Vue.use(Vuetify);
Vue.use(BootstrapVue);
Vue.use(Vuesax);
Vue.use(VueMask);
new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    router,
    store,
    render: a => a(App)
});

router.js
import Vue          from 'vue';
import VueRouter    from "vue-router";
import Home         from "pages/Catalog.vue";
import Admin        from "pages/Admin.vue";
import Order        from "pages/Order.vue";
Vue.use(VueRouter);
const routes = [
    {path: '/', component: Home},
    {path: '/order', component: Order},
    {path: '/admin', component: Admin},
];
export default new VueRouter({
    mode: 'history',
    routes
})

index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>PleaseDo</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@3.x/css/materialdesignicons.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

webpack.config.js
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
    mode: 'development',
    devtool: 'source-map',
    entry: path.join(__dirname, 'src', 'main', 'resources', 'static', 'js', 'main.js'),
    devServer: {
        contentBase: './dist',
        disableHostCheck: true,
        compress: true,
        port: 8000,
        allowedHosts: ['localhost:9000']
    },
    module: {
        rules: [
            {test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {test: /\.vue$/,
                loader: 'vue-loader'
            },
            {test: /\.css$/,
                use: ['vue-style-loader', 'css-loader']
            },
            { test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                loader: 'file-loader'
            },
            {test: /\.(png|jpe?g|gif)$/i,
                use: [{loader: 'file-loader',},],
            }
        ]
    },
    plugins: [new VueLoaderPlugin()],
    resolve: {
        modules: [
            path.join(__dirname, 'src', 'main', 'resources', 'static', 'js'),
            path.join(__dirname, 'node_modules'),
        ],
    }
}

WebMvcConfig.java
@Configuration
public class WebMvcConfig {
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerCustomizer() {
        return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/"));
    }
}

WebSecurityConfig.java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**")
                    .authorizeRequests()
                    .antMatchers("/", "/login**", "/js/**", "/error**").permitAll()
                .and()
                    .authorizeRequests()
                    .antMatchers("/api/admin/**").permitAll()//!!!hasAuthority("ADMIN")
                    .mvcMatchers("/api/user/**").authenticated()
                    .anyRequest().permitAll()
                .and()
                    .formLogin()
                    .loginPage("/user/login")
                    .loginProcessingUrl("/user/login")
                    .defaultSuccessUrl("/", true)
                    .permitAll()
                .and()
                    .logout().permitAll()
                    .logoutUrl("/user/logout")
                    .logoutSuccessUrl("/")
                .and().csrf().disable();
    }
}


text:
Q: Incorrect hostname on logstash/kibana issue There are the steps i have taken so far:-
1)created a image template from a vm
2) spin new vms from that image
3) each vm (and the image) had logstash forwarder running on it
Now the issue is when i check in logstash all messages are coming under the same hostname of the image-vm.
Say i created the image from vm whose hostname is  "test"
All new vms (even though they have a different hostname) are sending messages with host="test"


text:
Q: imacros select from popup dropdown Could you please help me :)
I have a TEXTBOX field which filling from a dropdown popup list.
enter image description here
It's not a drop-down list where I could use TYPE=SELECT
It doesn't take it as just a text, it needs to be picking from the list.
If I record a macro, it gives me:
   TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:management_main    ATTR=ID:order_release/attribute1 CONTENT=201500
   TAG POS=2 TYPE=TR ATTR=TXT:201500

If I record a macro in Experimental event recording mode:
EVENT TYPE=CLICK SELECTOR="HTML>BODY>FORM>DIV:nth-of-type(3)>DIV>TABLE>TBODY>TR:nth-of-type(6)>TD:nth-of-type(3)>DIV>TABLE>TBODY>TR>TD>INPUT" BUTTON=0
EVENTS TYPE=KEYPRESS SELECTOR="HTML>BODY>FORM>DIV:nth-of-type(3)>DIV>TABLE>TBODY>TR:nth-of-type(6)>TD:nth-of-type(3)>DIV>TABLE>TBODY>TR>TD>INPUT" CHARS="201500"
EVENT TYPE=KEYPRESS SELECTOR="HTML>BODY>FORM>DIV:nth-of-type(3)>DIV>TABLE>TBODY>TR:nth-of-type(6)>TD:nth-of-type(3)>DIV>TABLE>TBODY>TR>TD>INPUT" KEY=13
EVENT TYPE=CLICK SELECTOR="HTML>BODY>FORM>DIV:nth-of-type(4)>DIV>DIV>TABLE>TBODY>TR>TD>DIV>DIV>TABLE>TBODY>TR>TD" BUTTON=0

I've tried:
EVENT TYPE=CLICK SELECTOR="#order_release/attribute1" BUTTON=0
EVENTS TYPE=KEYPRESS SELECTOR="#order_release/attribute1" CHARS="201500"

it doesn't work also...
Inspection of elements:
enter image description here
So still can't catch this event to fill that field...
Have you any idea for me?
I would be veeeeeery thankful)
Thank you in advance!

A: I have found a solution and it works:
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:management_main ATTR=NAME:order_release/attribute1 CONTENT={{!COL7}}
TAG POS=1 TYPE=INPUT:HIDDEN FORM=NAME:management_main ATTR=ID:order_release/attribute1@ID CONTENT={{!COL7}}


text:
Q: Better understanding of magento interfaces In magento, in every step of project you can find instances of interfaces, just like for example in this function below:
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
        //Upgrade schema logic
}

How is it possible to create instance of interface, If I understand interfaces well, it's not possible to have interface object
SchemaSetupInterface $setup,
ModuleContextInterface $context

A: That is kind of good programming and in Magento it has something to do with its dependency injection (DI) pattern.
General Interface Usage
Interfaces defines a minimum of funkctions, a class has to implement. So if a function accepts an interface of type SchemaSetupInterface, it just wants a class which implements the functions defined in SchemaSetupInterface.
In this special case, where the interface is defined as follows, the upgrade function wants a class which implements getIdxName($tableName, $fields, $indexType = ''); and getFkName($priTableName, $priColumnName, $refTableName, $refColumnName);.
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Framework\Setup;

/**
 * DB schema resource interface
 * @api
 * @since 100.0.2
 */
interface SchemaSetupInterface extends SetupInterface
{
    /**
     * Retrieves 32bit UNIQUE HASH for a Table index
     *
     * @param string $tableName
     * @param array|string $fields
     * @param string $indexType
     * @return string
     */
    public function getIdxName($tableName, $fields, $indexType = '');

    /**
     * Retrieves 32bit UNIQUE HASH for a Table foreign key
     *
     * @param string $priTableName  the target table name
     * @param string $priColumnName the target table column name
     * @param string $refTableName  the reference table name
     * @param string $refColumnName the reference table column name
     * @return string
     */
    public function getFkName($priTableName, $priColumnName, $refTableName, $refColumnName);
}

Magento DI.xml
Magento supports di.xml definition files and a global ObjectManager which resolves classes based on the preference configuration in the di.xmls. Instances of classes which implement special interfaces are then automatically injected into constructors of your classes.
Example: vendor/magento/magento2-base/app/etc/di.xml:
<config>
    <!-- ... more -->
    <preference for="\Magento\Framework\Setup\SchemaSetupInterface" type="\Magento\Setup\Module\Setup" />
    <!-- ... more -->
</config>

With this configuration, Magento passes an instance of \Magento\Setup\Module\Setup, which is defines as follows to your upgrade function.
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Setup\Module;

use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\App\ResourceConnection;

/**
 * @api
 */
class Setup extends \Magento\Framework\Module\Setup implements SchemaSetupInterface
{
    /**
     * Retrieve 32bit UNIQUE HASH for a Table index
     *
     * @param string $tableName
     * @param array|string $fields
     * @param string $indexType
     * @param string $connectionName
     * @return string
     */
    public function getIdxName(
        $tableName,
        $fields,
        $indexType = '',
        $connectionName = ResourceConnection::DEFAULT_CONNECTION
    ) {
        return $this->getConnection($connectionName)->getIndexName($this->getTable($tableName), $fields, $indexType);
    }

    /**
     * Retrieve 32bit UNIQUE HASH for a Table foreign key
     *
     * @param string $priTableName  the target table name
     * @param string $priColumnName the target table column name
     * @param string $refTableName  the reference table name
     * @param string $refColumnName the reference table column name
     * @param string $connectionName
     * @return string
     */
    public function getFkName(
        $priTableName,
        $priColumnName,
        $refTableName,
        $refColumnName,
        $connectionName = ResourceConnection::DEFAULT_CONNECTION
    ) {
        return $this->getConnection($connectionName)->getForeignKeyName(
            $this->getTable($priTableName),
            $priColumnName,
            $refTableName,
            $refColumnName
        );
    }
}

You can find more information about dependency injection in Magento in the Docs.


text:
Q: elFinder file manager preventing image popup on double click I have a question about elfinder file manager. When I double click on an image, I want to prevent opening it on Windows.
Can someone help me please
I do not know what to do.

A: In order to avoid opening image or any kind of file on mouse double click, you must add getFileCallback() - callback to the elFinder options object. Inside you can get file url as it shown inside the example below.
 $('#elfinder').elfinder({
    getFileCallback: (file, fm) => {
       let fileURL = file.url;

       $('#elfinder').remove();
    },
 })