text:
Q: Nexus OSS Remote User Token (RUT) for SSO Hello I am using Nexus OSS, and wanted to simulate SSO, using Remote User Token. Currently the Nexus is configured to LDAP authentication, and is working fine.
As per the instructions found here https://books.sonatype.com/nexus-book/reference/rutauth.html
Basically enabled Remote User Token and added header field Name "REMOTE_USER". This user is ldap and has access.
This instance is behind apache, so from apache, To test this RUT, I can set the header value REMOTE_USER, whoever, I don't see passed in user getting logged nor I see cookie being generated. I even tried firefox rest api client and set header, but with the same results. I can see that HTTP header is being set right.
Am I missing something?
Is there a way to debug that? Appreciate any help.
Thanks
S

A: RUT handles authentication, but the authenticated user still needs to be authorized to access the web UI.  What this means is that you need an LDAP user or group mapping in Nexus which assigns the necessary roles and privileges to the user.

A: I had a similar issue with Nginx, the header was not set using the correct value.
This can be quite confusing, as the reverse proxy does not complain and simply sends a blank request header to Nexus.
Using Keycloak and Nginx (Lua), instead of a preferred_username field in the IdP response:
-- set headers with user info: this will overwrite any existing headers
-- but also scrub(!) them in case no value is provided in the token
ngx.req.set_header("X-Proxy-REMOTE-USER", res.preferred_username)

I had to use the preferred_username field returned in the response's id_token element:
-- set headers with user info: this will overwrite any existing headers
-- but also scrub(!) them in case no value is provided in the token
ngx.req.set_header("X-Proxy-REMOTE-USER", res.id_token.preferred_username)


text:
Q: DataSourceTransactionManager bean not created after Introducing Spring Batch @EnableBatchProcessing Annotation I am integrating Spring Batch in one of the existing applications where other beans are successfully using DataSourceTransactionManager. However, I am getting the following error when I introduce the @EnableBatchProcessing annotation :

Field transactionManager in AuthBeans required a bean of type 'org.springframework.jdbc.datasource.DataSourceTransactionManager' that could not be found.

I've tried to configure BatchConfigurer but it has not resolved the issue. Please see BatchConfigurer code below.
@Configuration
public class CustomBatchConfigurer implements BatchConfigurer {

    @Autowired
    private DataSource dataSource;

    @Override
    public JobRepository getJobRepository() throws Exception {
        JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
        factory.setDataSource(dataSource);
        factory.setTransactionManager(getTransactionManager());
        factory.afterPropertiesSet();
        return  (JobRepository) factory.getObject();
    }

    @Override
    public PlatformTransactionManager getTransactionManager() throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }

    @Override
    public JobLauncher getJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(getJobRepository());
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }

    @Override
    public JobExplorer getJobExplorer() throws Exception {
        JobExplorerFactoryBean factory = new JobExplorerFactoryBean();
        factory.setDataSource(dataSource);
        factory.afterPropertiesSet();
        return  (JobExplorer) factory.getObject();
    }

I am wondering am I missing something? Your help regarding this will be highly appreciated.

A: In which class , you kept @EnableBatchProcessing annotation.
@EnableBatchProcessing should be at the highest level.
@EnableBatchProcessing will create the DataSourceTransactionManager by default.
Go through this BatchConfigure and follow the example.
I hope this will resolve your issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: unable to watch a bool variable in riverpod i am trying to watch a boolean variable in riverpod so i have the bellow code sample.
final isPro = StateProvider<bool>((_) => false);

class Example extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    bool testPro = watch(isPro); //this line returns error
    var totgleBool = context.read(isPro.notifier);

    return InkWell(
        onTap: () {
          totgleBool.state = true;
        },
        child: Container(child: testPro ? Text("yes") : Text("no")));
  }
}

so i am getting the following error " The argument type 'StateProvider' can't be assigned to the parameter type 'ProviderBase<Object?, "
Thanks.

A: try this
class Example extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) { // changed here
    bool testPro = ref.watch(isPro);
    var totgleBool = context.read(isPro.notifier);

    return InkWell(
        onTap: () {
          totgleBool.state = true;
        },
        child: Container(child: testPro ? Text("yes") : Text("no")));
  }
}


text:
Q: CloneNotSupportedException for an enumeration I got a strange error from my Android application reported by ACRA. It seems that clone() was called on an enumeration. Here's the stack trace:
        java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
            at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
            ... 2 more
    Caused by: java.lang.CloneNotSupportedException: Class doesn't implement Cloneable
            at java.lang.Object.clone(Object.java:155)
            at org.digitalcure.ccnf.app.io.data.Glyx.org.digitalcure.ccnf.app.io.data.Glyx[] values()(SourceFile:17)
            at org.digitalcure.ccnf.app.io.data.Glyx.org.digitalcure.ccnf.app.io.data.Glyx getForDatabaseValue(int)(SourceFile:140)
    ...

And this is the code of the enumeration:
package org.digitalcure.ccnf.app.io.data;

import org.digitalcure.ccnf.app.R;
import android.content.Context;
import android.content.res.Resources;

public enum Glyx {
    HIGH(-1),

    MEDIUM(0),

    LOW(1);

    private final int value;

    private Glyx(final int value) {
        this.value = value;
    }

    public static Glyx getForNormedValue(final int value) {
        final Glyx[] array = Glyx.values();
        for (final Glyx candidate : array) {
            if (candidate.value == value) {
                return candidate;
            }
        }

        return null;
    }

    public static Glyx getForDatabaseValue(final int value) {
        return getForNormedValue(value + HIGH.value);
    }

    // more code follows...
}

I removed the documentation and other uninteresting code, so line 17 refers to "public enum Glyx {" and line 140 to "return getForNormedValue(value + HIGH.value);".
I already checked my ProGuard configuration. It contains the following rule for enums:
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

I'm confused about the call of "clone()" on an enumeration and I cannot explain what happens here. What can I do to avoid this exception? Is there any explanation of this issue? Any help is appreciated.
Environment: Android 4.0.4, ZTE Grand X In


text:
Q: I need to pass number of arguments to a function equivalent to that of the array count of a variable I have an array variable. If the array count of the variable is 1, then I need to call a function with one argument and pass the array variable of index 0 as it's argument. If it's two, then I have to call a function with two arguments and pass the array variable of index 0 and 1 as it's arguments and so on till max three arguments.
I have tried using guard statements but I'm not sure if they will work in my case.
    class DFile{
//These are the functions:
        public func addData(_ date: Date) { }
        public func addData(_ date: Date, ch: Double) {}
        public func addData(_ date: Date, ch1: Double, ch2: Double) {  }
        public func addData(_ date: Date, ch1: Double, ch2: Double, ch3:       Double) {  }
    }
    //The date is static
    let df = DFile()
    var ch = [Double]() // this is the variable
    ch.append(GetNumber()) //I append data to the variable
    df.addData(dt,ch1: ch[0], ch2: ch[1], ch3: ch[2])// I need this to be dynamic, it needs to be different according to the array count.

Expected output: if array.count = 2,
df.adddata(_ date: Date, ch1: Double, ch2: Double)

A: You can proceed with creating a separate method in DFile's extension that will handle the calling of respective addData methods, i.e.
extension DFile {
    func addData(_ date: Date, _ ch: [Double]) {
        switch ch.count {
        case 0:
            self.addData(date)
        case 1:
            self.addData(date, ch: ch[0])
        case 2:
            self.addData(date, ch1: ch[0], ch2: ch[1])
        case 3:
            self.addData(date, ch1: ch[0], ch2: ch[1], ch3: ch[3])
        default:
            break
        }
    }
}

Call addData(_:_:) in extension DFile like,
df.addData(dt,ch)


text:
Q: Adding a Hash in an Array I'm trying to create an array of hashes in perl and I'm having some trouble in printing it as the only thing that prints out is the last hash entered.
Is there something wrong in how I push the hashtables into the array? Also, how can I print the contents of the array (the hashtables) properly?
print "\n===========SUBJECTS===========\n";
my $exit = "n";
until ( $exit eq "y" ) {    #loops until user enters 'y'
    print "Course Number: ";
    my $cNum = <STDIN>;
    chomp($cNum);

    print "Course Credit: ";
    my $cCred = <STDIN>;

    print "Grade: ";
    my $cGrade = <STDIN>;

    %subHash = (
        "courseNumber" => $cNum,
        "courseCredit" => $cCred,
        "courseGrade"  => $cGrade,
    );
    push @subList, \%subHash;
    $subCount += 1;

    print "\nFinished adding subjects?\n[y/n]\nCHOICE: ";    #asks for subject input termination
    $exit = <STDIN>;
    chomp($exit);
    print "\n==============================\n";
}

A: You'll need to loop through the array of hash refs, dereferencing each one appropriately.
for my $hash_ref (@AoH)
{
    for my $key (keys %{$hash_ref})
    {
        print "$key => $hash_ref->{$key}\n"
    }
}

or
for my $hash_ref (@AoH)
{
    while (my ($key, $val) = each %{$hash_ref})
    {
        print "$key => $val\n";
    }
}

See perldoc perldsc for more about nested data structures, including printing them out.

A: The answer has already been given to you. Are you having trouble copy and pasting it into your homework?
use strict;
use warnings;

my @subList;
print "\n===========SUBJECTS===========\n";
my $exit = "n";
until ( $exit eq "y" ) {    #loops until user enters 'y'
    print "Course Number: ";
    my $cNum = <STDIN>;
    chomp($cNum);

    print "Course Credit: ";
    my $cCred = <STDIN>;
    chomp($cCred);

    print "Grade: ";
    my $cGrade = <STDIN>;
    chomp($cGrade);

    push @subList, {
        "courseNumber" => $cNum,
        "courseCredit" => $cCred,
        "courseGrade"  => $cGrade,
    };

    print "\nFinished adding subjects?\n[y/n]\nCHOICE: ";    #asks for subject input termination
    $exit = <STDIN>;
    chomp($exit);
    print "\n==============================\n";
}

foreach my $hashref ( @subList ) {
    while ( my ($key, $val) = each %{$hashref} ) {
        print "$key => $val\n";
    }
    print "-----\n";
}


text:
Q: Help center uncapitalized letter AND typo: "Note: deleted questions do not... so you if you..." Towards the bottom of the Deleted Questions page of the Help Center is the following sentence:

Note: deleted questions do not appear in search results, so you if you
  wish to later undelete a question that you've deleted you must have
  saved the URL somewhere.

The word "deleted" should be capitalized here, because of the following grammar "rule" (found here):

If the introductory phrase preceding the colon is very brief and the
  clause following the colon represents the real business of the
  sentence, begin the clause after the colon with a capital letter:
Remember: Many of the prominent families of this New England state
  were slaveholders prior to 1850.

The word "you" is also duplicated (thanks @animuson), so the corrected sentence would be:

Note: Deleted questions do not appear in search results, so if you
  wish to later undelete a question that you've deleted you must have
  saved the URL somewhere.

A: Huh. This is the first time I heard of that rule and I think it is weird, so I opted to avoid it completely and modified the beginning of that sentence (and threw the extra "you" out):

Please note that deleted questions do not appear in search results, so if you wish to later undelete a question that you've deleted you must have saved the URL somewhere.


text:
Q: Recommended maintenance plan for Windows PCs I'm helping someone out with their PC and wanted to point them to to a Windows PC periodic maintenance plan.
I was thinking they should:

*

*Run Disk cleanup (cleanmgr)

*Defragment their HD (maybe using Smart Defrag)

*Scan the HD for errors.

*Use the SysInternals Autorun

I found a page (posted below as an answer) that lets you schedule some of this but it would be great to have an option to just choose "Run maintenance and then shutdown my pc"

A: I would suggest the following replacements:

*

*run ccleaner.  Removes a lot of temp files generated by pesky applications.

*run JkDefrag.  Seems to work much better then the built in one.

3/4. Same.
EDIT: 5. run Malwarebytes periodically.

A: Configure your paging file to a fixed size. Install and configure pagedfrg to run at every boot.
Instead of disk cleanup I have my own utility called CleanAllTemp, which does exactly what the name suggests.
Always check for disk errors before defragmenting, as defrag, and perhaps also its alternatives, can sometimes miss errors and thereby screw both your file system and your day.
Apart from pagedfrg I no longer run automated cleanups, not since losing important files because disk cleanup deleted things that should not have been deleted and could not be restored because defrag had overwritten the space occupied by the files. Of course that could have been avoided by what is perhaps the most important item: Take a backup before starting the maintenance procedures.

A: Here's a link to a Microsoft page explaining how to automate all of the above:
Automate Disk Cleanup on Windows Vista-7

A: If you are technically inclined, you could create a BART (Windows PE) CD that they could just put in and boot off of. Then create a batch file that downloaded updated virus/spyware definitions to a USB drive. So the idea was that they would run the batch file to update the key, then reboot with the CD in the drive.
BART is a nice option because it can actually remove rootkits, spyware, viruses, etc as the computer's Windows installation isn't running. Ultimate Boot CD for Windows (UBCD) also has a number of tools including a defragger that works quite well.

A: I use:

*

*ccleaner on every boot up and set
the computer to power up on a
certain time in the morning before
people come in.

*I use spybot once
    every.. months

But can I just say, that I think windows XP has become FAR more stable and bug free ever since Microsoft stopped updating it. I mean, they still do security patches.. but ever since they stopped updating features on it, it works pretty well.

A: If you configure the paging file to be of a fixed size you don't need to run pagedefrag at all, since the pagefile won't fragment.
For my personal desktop with 4 x 500GB drives, XP Pro SP3:
(1) Disk cleanup with the built-in Windows utility, once a day.
(2) I run Diskeeper 2009 Pro in automatic defrag mode. Easy and highly effective solution since it defrags files, free space, metadata -the MFT etc automatically as required; the pagefile can be set to be defragged during boot (but I use a static PF). Some folders are in the defrag exclusion list (browser cache etc).
(3) My page file has it's own small partition on a secondary physical disk. Drives are unpartitioned otherwise.
(4) Chkdsk maybe once every couple of months...don't see a need to run it more frequently.
(5) Same with HDtune...once every couple of months just to see if the drive is running okay.
The above works perfectly for me.
Anti-malware/virus scans with Antivir, MBAM and Super Antispyware once every weekend..but that doesn't really fall under drive maintenance....


text:
Q: Is it possible to detect when Google Maps has rejected the API key? I am trying to debug an intermittent alert that is opened by the Google Maps API. The alert contains the following message:

Google has disabled use of the Maps API for this application. The provided key is not a valid Google API Key, or it is not authorized for the Google Maps Javascript API v3 on this site. If you are the owner of this application, you can learn about obtaining a valid key here: https://developers.google.com/maps/documentation/javascript/tutorial#api_key

I can't reproduce it, but I want to log it from JavaScript if it happens again. How can I do that?

A: You can check using the Google Maps API console https://code.google.com/apis/console/?pli=1
Update
I found this thread on Google's dev forum which might help https://groups.google.com/forum/#!topic/google-maps-api/YgYdJ04hcZI


text:
Q: ReplyError: ERR max number of clients reached - Redis I'm running this function from a NodeJS script:
const redis = require('redis')
const redisOptions = {
    url: '*****',
    password: '******'
}

const checkMessageStatus = (cachedMessageId, callback = () => {}) => {
    const client = redis.createClient(redisOptions)
    client.get('*', (err, cachedMessage) => {
        // returns error if it exists
        // figure out why this gets called twice
        if(err) return console.log('redis err',err)
        // returns true if message is cached
        if(cachedMessage) return
        // sets message as ID in database if the message hasn't been sent already
        client.set(cachedMessageId, JSON.stringify(cachedMessageId), 'EX', 120 * 60, (redisSetError, redisSetResponse) => {
            // console.error(redisSetError)
            // console.log(redisSetResponse)
            client.quit(callback)
        })
    })
}

I received this error:
ReplyError: ERR max number of clients reached

The DB is hosted through Redis labs and I can have 30 connections.
I ran:
CLIENT KILL TYPE normal
CLIENT KILL TYPE slave
CLIENT KILL TYPE pubsub

When I run info clients:
# Clients
connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

ISSUE: I still get this error even though there is only one connected client:
ReplyError: ERR max number of clients reached


text:
Q: Firebase data message to specific android app versions i have an android app and i want to send a firebase data message to inform the users of a new app version available in the play store. I am sending a data message in order to reach devices in which the app is in background.
I want send the message to specific versions, or if it's possible to all versions except the last version.
What is the best way to do it? Can I specify a version number in a fcm data message?
Below is the data message i am sending.
Thanks in advance.
{
  "to": "/topics/all",
  "data": {
    "title": "new version",
    "body": "a new version is available in play store"
  }
}

A: I don't have answer for your question but I can suggest another way to achieve your case.
Take a look at Firebase Remote Config.
You can define variable for your client to get anytime it start.
So for your case, we have 3 variable:
destinationVersion for your specific version
title
message
In the app, just put the logic like if app's version equal to destinationVersion , create a notification with title and message to tell user update the app
. Hope it helpful to you.

A: You can force users to update with Google now: https://developer.android.com/guide/playcore/in-app-updates#immediate


text:
Q: Topological Field Theory for Physicists I was wondering if anyone knows good resources for Topological Field Theories aimed at physicists. In particular, I am looking for references which are full of examples, starting with simple toy models and building up to more complicated TFTs. I am also looking for references aimed at explaining the subject at someone with a physics background and motivation. For example, a reference with explicit examples building from a Lagrangian that help motivate the more mathematical definitions of TFT. Also, seeing explicitly how one can build explicit examples of these more mathematical definitions from an explicit description of the fields of the theory and an action would be great!
A good example of what I am looking for is this lecture https://www.youtube.com/watch?v=pqgNrVTQ4yM&t=1498s, which treats free TFTs. Everything can be done explicitely and a lot of important ideas are already present! Having something like this in written form (which would allow to discuss the details) would be great!


text:
Q: Why main thread gets hanged when background worker is executing I have simple winforms application where i have button. on button click i am doing something like this
    private void Button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw_Convert = new BackgroundWorker();
        bw_Convert.WorkerReportsProgress = true;
        bw_Convert.DoWork += bw_Convert_DoWork;
        bw_Convert.RunWorkerCompleted += bw_Convert_RunWorkerCompleted;
        bw_Convert.ProgressChanged += bw_Convert_ProgressChanged;
        bw_Convert.WorkerReportsProgress = true;
        bw_Convert.RunWorkerAsync();
    }

I have following code for background worker
   public void bw_Convert_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; i <= 1000000; i++)
        {
            bw_Convert.ReportProgress((100 * (i) / 1000));
        }
    }
    public void bw_Convert_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

        progressBarControl1.EditValue = e.ProgressPercentage.ToString();
    }

By doing this. Why my Main Thread gets hanged as i m processing the things in Background Worker.

A: Because ReportProgress event handler is executed on main thread:

The call to the ReportProgress method is asynchronous and returns
  immediately. The ProgressChanged event handler executes on the thread
  that created the BackgroundWorker.

Thus you are constantly calling ReportProgress from background thread, it makes your main thread constantly busy handling this event.
If you have a lot of quick work to do in background, then try to report only each n-th iteration instead of raising event on each iteration:
public void bw_Convert_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i <= 1000000; i++)
    {
        if (i % 10000 == 0)
           bw_Convert.ReportProgress(i);
        // do something
    }
}

A: The ProgressChanged event is executed on the UI thread so you can access the controls.
The code inside your background worker is executing in a very short amount of time, leading to many events being raised in a short period of time, making the code react as if it would execute completely on the UI thread.
In fact, most of the work is being done in the UI thread, because updating a control on the screen is much more work than the loop iterations.


text:
Q: String not containing whitespace followed by digit I am trying to come up with a regex that returns a certain jpeg filename in a folder not containing a whitespace followed by digit at the end of the filename, e.g., 002504_GDG_EN_160902.jpeg would be fine, 002504_GDG_EN_160902 5.jpeg not.
My best guess so far is, with $file being the filename without the suffix and any number (e.g., 002504_GDG_EN_160902):
test=$(ls *.jpeg | sort | grep $file | grep -v '.*\s\d\.jpeg')

This works fine for the the above mentioned example, but somehow not for cases where $file is 2016_MUC-Werk_[B_DGF_LA_LZ_R]_FG-8_all_160926. Probably because of the brackets and/or minuses.

A: No need to use ls and grep.
Using extglob:
shopt -s nullglob
shopt -s extglob

printf "%s\n" +([^[:blank:]]).jpeg
002504_GDG_EN_160902.jpeg

Or to store matching filenames in an array:
files=(+([^[:blank:]]).jpeg)

+([^[:blank:]]).jpeg will match filenames with 1 or more non-space characters followed by .jpeg

A: Sample data:
ls -1
002504_GDG_EN_16090 2.jpeg
002504_GDG_EN_160901 32.jpeg
002504_GDG_EN_1609012.jpeg
002504_GDG_EN_1609013.jpeg
2016_MUC-Werk_[B_DGF_LA_LZ_R]_FG-8_all_160926

solution using array:
array=(*)
printf "%s\n" "${array[@]}" |grep -Pv  '\d\s\d.*(.jpeg|$)'
002504_GDG_EN_1609012.jpeg
002504_GDG_EN_1609013.jpeg
2016_MUC-Werk_[B_DGF_LA_LZ_R]_FG-8_all_160926

to store it in any variable:
var=$(printf "%s\n" "${array[@]}" |grep -Pv  '\d\s\d.*(.jpeg|$)')

echo "$var"
002504_GDG_EN_1609012.jpeg
002504_GDG_EN_1609013.jpeg
2016_MUC-Werk_[B_DGF_LA_LZ_R]_FG-8_all_160926


text:
Q: JPA query: what is a proper way to select by a large set of possible values? What I have is a large (like hundreds of thousands) list of IDs. I want to get some values from the objects with this IDs with a JPA query.
Option 1 - using IN clause
List<Long> ids = /* ... */
entityManager.createQuery(
        "SELECT v.lat, v.lon FROM Vehicle v WHERE v.id IN (:ids)",
        Long[].class)
    .setParameter("ids", ids)
    .getResultList();

I'm afraid there might be a limit on IN clause contents.
Option 2 - query each ID separately
List<Long> ids = /* ... */
for (Long id : ids) {
    entityManager.createQuery(
            "SELECT v.lat, v.lon FROM Vehicle v WHERE v.id = :id",
            Long[].class)
        .setParameter("id", id)
        .getSingleResult();
}

That looks too slow as seems to be doing ids.size() requests.
What is a proper way to do this type of thing?

A: Neither of your methods have much merit.  As mentioned in Grzegorz's comment, all databases have a limit on how many list items you can use.  Also, there are limits on how many characters your query can contain.  So lists are out.
Hundreds of thousands of individual queries seems (remember the posting guidelines Dan, be courteous) unwise.
If this were my problem, I'd look at how that list of id's got generated in the first place.  It was probably a database query.  If so, I would make a new version of that query to get the lats and lons.  It might be a table join or it might be a subquery.  Without knowing your database structure, I can't give you any detailed suggestions.

A: First thing that comes to mind:

*

*Cut the id list in parts of say 1000 ids. A manageable size.

*Run an IN query for each part.

*Aggregate the result into a list.

For big data sets, the performance can be improved dramatically by doing (2) in parallel.


text:
Q: In Heroku Dataclips, how to hide the Query Is there a way to hide the Query shown at the top of the DataClip on Heroku?
I would like to give access to view the data but not the SQL.

A: Maybe not exactly what you want, but you don't get the query included when you just download the data as .csv


text:
Q: How does the mysqli execute function work internally? I have a DB where I have some tables, most of them irrelevant for this question:
Content_handler:
+-------------+-------------------+---------------------------+
| app_data_id | app_menu_entry_id | content_item_container_id |
+-------------+-------------------+---------------------------+
| 0           | 0                 | NULL                      |
| 0           | 1                 | bm9zb3Ryb3MtMC0w          |
+-------------+-------------------+---------------------------+

App_menu_entry:
+-------------------+----------+---------+--------------+
| app_menu_entry_id | position | name    | icon_id      |
+-------------------+----------+---------+--------------+
| 0                 | 0        | Nombre  | asd          |
| 1                 | 1        | Precios | icontest.png |
+-------------------+----------+---------+--------------+

Content_item_container:
+---------------------------+--------------+
| content_item_container_id | content_name |
+---------------------------+--------------+
| bm9zb3Ryb3MtMC0w          | Nosotros     |
+---------------------------+--------------+

content_handler.app_menu_entry_id REFERENCES TO app_menu_entry.app_menu_entry_id
content_handler.content_item_container_id REFERENCES TO content_item_container.content_item_container_id
Now, when I want to update app_menu_entry I DELETE all records from this table (with cascade, so also deletes content from content_handler) and then I insert data with PHP from an array so I use a foreach with prepared statements like this:
$menuQuery = $connection->prepare("INSERT INTO app_menu_entry(app_menu_entry_id,position,name,icon_id) VALUES(?,?,?,?)");
$handlerQuery = $connection->prepare("INSERT INTO content_handler(app_data_id, app_menu_entry_id, content_item_container_id) VALUES(?,?,?)");
$id = 0;

if (!$menuQuery || !$handlerQuery) {
    ErrorHandler::setError(ErrorHandler::DB_QUERY_ERROR, true);
    throw new \Exception('Error al realizar la consulta');
}

foreach ($menu['menu_items'] as $menuItem) {
    $name = $menuItem['name'];
    $position = $menuItem['position'];
    $icon = $menuItem['icon_id'];
    $contentId = ($menuItem['content'] != null) ? base64_encode($menuItem['content'] . '-' . $userId . '-' . $appId) : null;

    $menuQuery->bind_param('ssss', $id, $position, $name, $icon);
    $menuQuery->execute();

    $handlerQuery->bind_param('sss', $appId, $id, $contentId);
    $handlerQuery->execute();

    $id++;
}

The problem is that this loop insert data in app_menu_entry but not in content_handler. This can be solved adding sleep(1000); between execute() function and that make me think how can I prevent using sleep() and how this execute function works? Does it uses a thread, makes a async queue...?


text:
Q: 1.15.2 - How do I test for if a player's inventory is open? I'm trying to do something that gives you mining fatigue while your inventory is not open, but stops whenever it is opened. I would appreciate some help with this. Is there an NBT tag for this?

A: If they're never meant to mine any blocks, just put them in Adventure mode.
If they're meant to be able to mine a certain type of block, tools have NBT tags that allow them to mine one type of block only (they still need to be in Adventure mode):
1.12-: /give @p minecraft:diamond_pickaxe 1 0 {CanDestroy:["BLOCK_HERE"]}
1.13+: /give @p minecraft:diamond_pickaxe{CanDestroy:["minecraft:BLOCK_HERE"]} 1

If they're only not meant to be able to mine blocks in a certain area, put pressure plates activating Adventure mode at the entrance to it, and activating Survival Mode at the exit to it.


text:
Q: How to dynamically add stops in a Gradient I have the following gradient:
    Item {
        id: base
        width: 200
        height: 100
        start: Qt.point(0,0)
        end: Qt.point(width, 0)
        gradient: Gradient {
            GradientStop { position: 0.0; color: "white"}
            GradientStop { position: 0.5; color: "black" }
            GradientStop { position: 1.0; color: "white"}
        }

The stops property of Gradient doesn't have any member functions to append new stops and neither does LinearGradient.
How could I add stops to dynamically change the gradient?
The alternative is to create a new LinearGradient each time it is to be changed.

A: The Gradient is defined as a list property which, as stated in the linked documentation, cannot be modified by directly appending/removing elements
The only way to append new stops to the Gradient is by reassigning the stops property list. Here is a sample code:
import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 200
    height: 100

    Rectangle {
        id: base
        anchors.fill: parent
        gradient: Gradient {
            id:gradient

            GradientStop { position: 0.0; color: "white"}
            GradientStop { position: 0.1; color: "black" }
            GradientStop { position: 0.3; color: "white"}
        }

        Component
        {
            id:stopComponent
            GradientStop {}
        }

        Component.onCompleted:
        {
            // Type 1: Aassign a all new stop list
            var s1 = stopComponent.createObject(base, {"position":0.2,"color":"red"});
            var s2 = stopComponent.createObject(base, {"position":0.4,"color":"yellow"});
            var s3 = stopComponent.createObject(base, {"position":0.6,"color":"blue"});
            gradient.stops = [s1,s2,s3];

            // Type 2:Append to the original stop list
            var newStops = [];
            for (var idx = 0; idx < gradient.stops.length;idx++)
            {
                newStops.push(gradient.stops[idx]);
            }
            newStops.push(s3);
            gradient.stops = newStops;
        }
    }
}


text:
Q: How to export to Excel with a SharePoint List I want to create a SharePoint List where a user uses the People picker to select someone but the information on the list should be
Name, Title, Department and Phone.

I can't figure out how to accomplish this.
I have Excel 2016 and InfoPath 2013 installed if I need to use it

A: If you want to be able, in Excel, to edit a SharePoint list, including columns of type "Person or Group", this is not possible out of the box. Communication between Excel and SharePoint lists OOTB is limited to import an Excel spreasheet as a new SharePoint list, or export a SharePoint list to a new Excel file. No "roundtrip" / bidirectional sync.
It is only possible to do two-way data synchronization between Excel and a SharePoint list with third party products, such as the one my company has developed: SharePoint list Synchronizer.


text:
Q: How to add Strings to a TextView / ScrollView? I am quiet new to android developing sorry!
I want to add doctor values as Strings (first name, last name, and some others later) as one entry (I was trying to do so with Objects) to my Scroll View via a button. I know that I need a Layout and a Text View to do so but my Virtual Machine crushes.
As far as I understand I have to put my Text View (with the Strings) in the Layout and the Layout in the Scroll View (am I wrong?).
I was trying several things from different websites which all provide similar solutions but nothing worked so far. I am using Android 6.0 with android studio and designed my UI with the Design View and adapted some code in the XML files.
public void addDoctor(View view) {

    setContentView(R.layout.activity_main);
    // standard java class Doctor
    Doctor doc = new Doctor("Foo", "Boo");

    // this is the ScrollView I generated with the design
    ScrollView sv = (ScrollView) this.findViewById(R.id.ScrollViewDoctor);
    TextView tv = new TextView(this);
    // trying to fix the parent problem here
    if(tv.getParent() != null) {
        ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
    }
    //this should be "Foo"
    tv.setText(doc.getDocName());

    // this is the layout I generated with the design "linlay"
    LinearLayout ll = (LinearLayout) this.findViewById(R.id.linlay);
    sv.addView(ll);

    //only one child object! -> in the error log
    ll.addView(tv);
    setContentView(view);
}

I expected the Strings of the object to appear in the Scroll View but the error log says that "ScrollView can host only one direct child" which I was trying to fix with the if statement but it does not seem to affect my code.
Can you please help me with this. Do I miss something?
Thank you!

A: remove setContentView(view); on the end, you have already set this layout in first line
setContentView in most cases should be called once, inside onCreate method. if you are calling setContentView multiple times you are basically overrriding previous one
also this
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}

is unnecessary, you are creating new TextView line above, it wont have parent for shure

A: Why don't you use a RecyclerView? And then you don't need a ScrollView. And don't call setContentView(view); multiples times. You have to do only 1 time.

A: you need to create Multiline TextView
<ScrollView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_weight="1"
       android:layout_marginLeft="15dp"
       android:layout_marginRight="15dp"
       android:layout_marginTop="20dp"
       android:fillViewport="true">

       <TextView
           android:id="@+id/txtquestion"
           android:layout_width="fill_parent"
           android:layout_height="match_parent"
           android:background="@drawable/abs__dialog_full_holo_light"
           android:lines="20"
           android:scrollHorizontally="false"
           android:scrollbars="vertical"
           android:textSize="15sp" />

   </ScrollView>

A:
As far as I understand I have to put my Text View (with the Strings) in the Layout and the Layout in the Scroll View (am I wrong?).

You've right.
<ScrollView>
   <LinearLayout>
     <TextView></TextView>
   </LinearLayout>
</ScrollView>

How to Add a doctor in the right way

error log says that "ScrollView can host only one direct child"

You're getting the error because you added already the linear layout inside the <ScrollView>, so you don't have to call, sv.addView(ll); because it's already inside (And you cannot add multiple layout in standard ScrollView)
So you're reference to ScrollView it's useless.
if you're xml is like this:
<ScrollView>
    <LinearLayout>

    </LinearLayout>
</ScrollView>

You can achieve your result with this:
public class MyActivityDoctors extends Activity {

    ScrollView sv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sv =  (ScrollView) this.findViewById(R.id.ScrollViewDoctor);
    }

    public void addDoctor(Doctor doctor)
    {
        //Linear Layout inside your ScrollView
        LinearLayout ll = (LinearLayout) this.findViewById(R.id.linlay);

        //Create a new TextView with doctor data
        TextView tv = new TextView(this);
        tv.setText(doctor.getDocName());

        //Adding textView to LinearLayout
        ll.addView(tv);
    }

}


text:
Q: Highlight all words containing a letter in a richtextbox How do i highlight all words containing a letter in a richtextbox. If i want to highlight the words that contain the letter "a" ,like the words hat or candle then highlight both words.
I'm using c# using winform.
 private void button208_Click(object sender, EventArgs e)
{
   HighlightPhrase(richTextBox1, "a", Color.Yellow);
}

This highlights all words with a letter "a" but i'm not sure how to length to spaces then highlight.
Thanks.

A: You can use the Find method to find the occurrences of the substring you're looking for. Then, use the SelectionBackColor property to change the back color to the highlight color for each occurrence.
int len = richTextBox.TextLength;
int index = 0;
string textToFind = "a";

// this will highlight the text you're looking for
while ( index < len )
{
   richTextBox.Find(textToFind, index, len, RichTextBoxFinds.None);
   richTextBox.SelectionBackColor = Color.Yellow;
   index = richTextBox.Text.IndexOf(textToFind, index) + textToFind.Length;
}

If you want to highlight the whole words that contain a certain letter, then whenever you find an occurrence of the letter, you'll need to search for word boundaries (left and right of the index of the letter) and once you've identified them select the whole word using the Select method of the RichTextBox control.
richTextBox.Select(wordBoundaryStart, wordBoundaryEnd - wordBoundaryStart);


text:
Q: How to draw boxes around table elements being displayed on the webpage using Django I'm trying out Django for the first time as a web framework.
My views.py function looks as follow:
def display(request):
    find_duplicate()
    return render_to_response('index.html', {'obj': my_model.objects.order_by('id')})

def get_dict():
    d={}
    for e in my_model.objects.all():
        col2 = e.col2
        col3 = e.col3
        col2 = unicode(col2).encode('UTF8')
        col3 = unicode(col3).encode('UTF8')
        d.setdefault(col2, [])
        d[col2].append(col3)
    del d['']
    return d

def find_duplicate():
    #print(d)
    d = get_dict()
    for k,v in d.items():
        if len(v) > 1:
            name=[]
            id=[]
            #print(k)
            for i in v:
                #print(i)
                reg1 = i.split("(")[0]
                name.append(reg1)
                reg2 = re.search(r'[A-Z0-9]*', i.split("_")[1])
                id.append(reg2.group())
            #print(name)
            #print(id)

And my index.html is as follows:

            Col1
            Col2
            Col3
            Col4
            Col5

       {% for b in obj %}

            {{ b.col1 }}
            {{ b.col2 }}
            {{ b.col3 }}
            {{ b.col4 }}
            {{ b.col5 }}

    {% endfor %}

My urls.py:
urlpatterns = patterns(
    '',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'myapp.views.display'),
)

So, right now the index.html displays the database from mysql ordered by col2 like this:
Col2   | Col3                   | Col4
1      | Name1(something_1234)  | Some_date
1      | Name1(something_3456)  | Some_date
2      | Name3(something_7890)  | Some_date
2      | Name4(something_0988)  | Some_date

Now, the get_dict() function in views.py returns the dictionary d which looks as follows:
{'1': ['Name1(something_1234)', 'Name1(something_3456)'], '2': 'Name3(something_7890)', 'Name4(something_0988)']}

And the find_duplicate() function parses the name and the id part from each element of Col3. So print(name) in that function will give names and ids for each key (num) i.e., ['Name1', 'Name1'] & ['1234', '3456'] for key 1.
Now, based on this I want to display red boxes on the table elements as follows:

So, for all values in Col2, if any 2 value is same then a box should be displayed around them, and then for that Col2 value check the name part and the id part and then display boxes around them accordingly.
Right now I'm just able to display the table but how do I display the table along with the boxes around the table elements?


text: Q: How can I find the chipset of my Arduino board? I've recently purchased an Arduino Pro Micro, which I am using as a BadUSB for experimental purposes. On Hak5, they spoofed the MAC Address of a USB Rubber Ducky to look like an Apple device (Hak5 Video). That is what I'm trying to do. Should I use lsusb? How would I find the chipset so I can spoof/change the device's MAC Address?


text:
Q: CommandHandler decorators dependency I have an issue where I would like my handler to use data generated from the handlers:

*

*UpdateUserProfileImageCommandHandlerAuthorizeDecorator

*UpdateUserProfileImageCommandHandlerUploadDecorator

*UpdateUserProfileImageCommandHandler

My problem is both architectural and performance.
UpdateUserCommandHandlerAuthorizeDecorator makes a call to the repository (entityframework) to authorize the user. I have other decorators similar to this that should use and modify entities and send it up the chain.
UpdateUserCommandHandler should just save the user to the database. I currently have to make another repository call and update the entity while I could have worked on the entity from the previous decorator.
My issue is that the command only accepts the user Id and some properties to update. In the case where I get the user entity from the Authorize decorator, how can I still work on that entity up the chain? Is it Ok to add that User property to the command and work on that?
Code:
public class UpdateUserProfileImageCommand : Command
{
    public UpdateUserProfileImageCommand(Guid id, Stream image)
    {
        this.Id = id;
        this.Image = image;
    }

    public Stream Image { get; set; }

    public Uri ImageUri { get; set; }
}

public class UpdateUserProfileImageCommandHandlerAuthorizeDecorator : ICommandHandler<UpdateUserProfileImageCommand>
{
    public void Handle(UpdateUserProfileImageCommand command)
    {
         // I would like to use this entity in `UpdateUserProfileImageCommandHandlerUploadDecorator`
         var user = userRespository.Find(u => u.UserId == command.Id);

         if(userCanModify(user, currentPrincipal))
         {
             decoratedHandler(command);
         }

    }
}

public class UpdateUserProfileImageCommandHandlerUploadDecorator : ICommandHandler<UpdateUserProfileImageCommand>
{
    public void Handle(UpdateUserProfileImageCommand command)
    {
         // Instead of asking for this from the repository again, I'd like to reuse the entity from the previous decorator
         var user = userRespository.Find(u => u.UserId == command.Id);

         fileService.DeleteFile(user.ProfileImageUri);

         var command.ImageUri = fileService.Upload(generatedUri, command.Image);

         decoratedHandler(command);

    }
}

public class UpdateUserProfileImageCommandHandler : ICommandHandler<UpdateUserProfileImageCommand>
{
    public void Handle(UpdateUserProfileImageCommand command)
    {
         // Again I'm asking for the user...
         var user = userRespository.Find(u => u.UserId == command.Id);

         user.ProfileImageUri = command.ImageUri;

         // I actually have this in a PostCommit Decorator.
         unitOfWork.Save();
    }
}

A: You should not try to pass on any extra data just for the sake of performance. Besides, usng decorators, you can't change the contract. Instead you should allow that user entity to be cached and this should typically be the responsibility of the repository implementation. With Entity Framework this is actually rather straightforward. You can call DbSet.Find(id) and EF will first look up the entity in the cache. This prevents unneeded round trips to the database. I do this all the time.
So the only thing you have to do is add a Find(key) or GetById method to your repository that maps to EF's Find(key) method and you're done.
Furthermore, I agree with Pete. Decorators should be primarily for cross-cutting concerns. Adding other things in decorators can be okay sometimes, but you seem to split up the core business logic over both the handler and its decorators. Writing the file to disk be longs to the core logic. You might be conserned about adhering to the Single Responsibility, but it seems to me that your splitting a single responsibility out over multiple classes. That doesn't mean that your command handlers should be big. As Pete said, you probably want to extract this to a service and inject this service into the handler.
Validating the authorization is a cross-cutting concern, so having this in a decorator seems okay, but there are a few problems with your current implementation. First of all, doing it like this will cause you to have many non-generic decorators, which leads to a lot of maintenance. Besides, you silently skip the execution if the user is unauthorized which is typically not what you want.
Instead of silently skipping, consider throwing an exception and prevent the user from being able to call this functionality under normal circumstances. This means that if an exception is thrown, there's either a bug in your code, or the user is hacking your system. Silently skipping without throwing an exception can make it much harder to find bugs.
Another thing is that you might want to consider is trying to implement this authorization logic as generic decorator. For instance have a generc authorization decorator or validation decorator. This might not always be possible, but you might be able to mark commands with an attribute. For instance, in the system I'm currently working on we mark our commands like this:
[PermittedRole(Role.LabManagement)]

We have a AuthorizationVerifierCommandHandlerDecorator<TCommand> that checks the attributes of the command being executed and verifies whether the current user is allowed to execute that command.
UPDATE
Here's an example of what I think your UpdateUserProfileImageCommandHandler could look like:
public class UpdateUserProfileImageCommandHandler
    : ICommandHandler<UpdateUserProfileImageCommand>
{
    private readonly IFileService fileService;

    public UpdateUserProfileImageCommandHandler(IFileService fileService)
    {
        this.fileService = fileService;
    }

    public void Handle(UpdateUserProfileImageCommand command)
    {
         var user = userRespository.GetById(command.Id);

         this.fileService.DeleteFile(user.ProfileImageUri);

         command.ImageUri = this.fileService.Upload(generatedUri, command.Image);

         user.ProfileImageUri = command.ImageUri;
    }
}

A: Why do this via decorators in the first place?
Validation
The normal approach is to have clients do any and all validation required before submitting the command. Any command that is created/published/executed should have all (reasonable) validation performed before submitting. I include 'reasonable' because there are some things, like uniqueness, that can't be 100% validated beforehand. Certainly, authorization to perform a command can be done before submitting it.
Split Command Handlers
Having a decorator that handles just a portion of the command handling logic, and then enriches the command object seems like over-engineering to me. IMHO, decorators should be use to extend a given operation with additional functionality, e.g. logging, transactions, or authentication (although like I said, I don't think that applies for decorating command handlers).
It seems that uploading the image, and then assigning the new image URL in the database are the responsibility of one command handler. If you want the details of those two different operations to be abstracted, then inject your handlers with classes that do so, like IUserimageUploader.
Generally
Normally, commands are considered immutable, and should not be changed once created. This is to help enforce that commands should contain up front all the necessary information to complete the operation.

A: I'm a little late here, but what I do is define a IUserContext class that you can IoC inject. That way you can load the important user data once and then cache it and all other dependencies can use the same instance. You can then have that data expire after so long and it'll take care of itself.


text:
Q: Proof of X is not Banach Set $X = \lbrace u\in\mathcal{C}^2 [0,\pi]: u(0)=u(\pi)=0\rbrace$ equipped with the norm $$\Vert u \Vert = \left(\int_0^\pi (u'(x))^2\ dx + \int_0^\pi u(x)^2\ dx\right)^{1/2}$$
I want to prove that $(X,\Vert \cdot \Vert)$ is not complete. Can anyone give me a hint or some ideas to find a Cauchy sequence in $X$ that is not convergent in $\Vert \cdot \Vert$-norm to any element of $X$?. I spent a lot of time thinking but I couldn't find one.
Thanks in advance.


text:
Q: Adding event listener onMount I'm trying to add an Event Listener to an dDOM Element on mount like:
        var isScrolling = null;
        console.log(document.getElementById("the-container"));
        document.getElementById("the-container").addEventListener('wheel', e => {
            window.clearTimeout(isScrolling);

            // Set a timeout to run after scrolling ends
            isScrolling = setTimeout(() => {
                // Run the callback
                scale.value = (Math.round(parseFloat(Math.min(Math.max(minScale, (scale.value + (e.wheelDelta / elWidth))), maxScale)) * 1e2) / 1e2);
                rerender();
            }, 150);
        }, false);

When adding in on the body element it's working as expected. When using the container element it's not. The element exists and there is no error message. When adding it manually in the console it also works. Using Vue3 composition api.


text:
Q: Unbound Field in Standalone Projection I have a Rich Text field attached to the PMQuote and CRQuote DACs. On the CRQuote, the user field is on the standalone class and the regular class, and that is working as desired. However, Acumatica's reporting does not show the HTML formatting so I am creating an unbound Plain Text field to put on the reports and in GI's. This field works fine on the PMQuote, but not on the CRQuote. On the CRQuote, the field is there, but it is always blank. I'm sure it is something to do with the projection, but I'm not sure how it should be created.
Here is the PMQuote field (working properly)
    [PXString(IsUnicode = true)]
    [PXUIField(Visible = false, DisplayName = "Scope Text")]
    public virtual String UsrScopePlainText
    {
        get
        {
            return PX.Data.Search.SearchService.Html2PlainText(UsrScope);

        }
    }
    public abstract class usrScopePlainText : PX.Data.BQL.BqlString.Field<usrScopePlainText> { }

And here is what I have on the CRQuote (not working):
public class CRQuoteExt : PXCacheExtension<CRQuote>
{
    #region UsrScope
    [PXDBText(IsUnicode = true, BqlField = typeof(CRQuoteStandaloneExt.usrScope))]
    [PXUIField(DisplayName = "Scope")]

    public virtual string UsrScope { get; set; }
    public abstract class usrScope : IBqlField { }
    #endregion

    #region UsrScopePlainText
    [PXString(IsUnicode = true)]
    [PXUIField(Visible = false, DisplayName = "Scope Text")]
    public virtual String UsrScopePlainText
    {
        get
        {
            return PX.Data.Search.SearchService.Html2PlainText(UsrScope);

        }
    }
    public abstract class usrScopePlainText : IBqlField { }
    #endregion
}

public class CRQuoteStandaloneExt : PXCacheExtension<PX.Objects.CR.Standalone.CRQuote>
{
    #region UsrScope
    [PXDBText(IsUnicode = true)]
    [PXUIField(DisplayName = "Scope")]
    public virtual string UsrScope { get; set; }
    public abstract class usrScope : IBqlField { }
    #endregion

    #region UsrScopePlainText
    [PXString(IsUnicode = true)]
    [PXUIField(Visible = false, DisplayName = "Scope Text")]
    public virtual String UsrScopePlainText
    {
        get
        {
            return PX.Data.Search.SearchService.Html2PlainText(UsrScope);

        }
    }
    public abstract class usrScopePlainText : IBqlField { }
    #endregion
}

Thanks!

A: An alternative solution could be to have a reusable attribute that you can attach to any field. I think this is cleaner than adding logic directly in the Data Access class...
using PX.Objects.IN;
using PX.Data;
using System;

namespace PX.Objects.IN
{
  public class InventoryItemPlainTextBodyExt : InventoryItem
  {
    [HtmlToText(typeof(InventoryItem.body))]
    [PXDependsOnFields(typeof(InventoryItem.body))]
    [PXUIField(DisplayName="Body (Plain Text)")]
    public virtual string BodyPlainText { get; set; }
    public abstract class bodyPlainText : PX.Data.BQL.BqlString.Field<bodyPlainText> { }
  }

  [PXString]
  public class HtmlToTextAttribute : PXEventSubscriberAttribute, IPXFieldSelectingSubscriber
  {
    protected Type _htmlField;

    public HtmlToTextAttribute(Type htmlField) :base()
    {
      _htmlField = htmlField;
    }

    public void FieldSelecting(PXCache sender, PXFieldSelectingEventArgs e)
    {
      e.ReturnValue = PX.Data.Search.SearchService.Html2PlainText(sender.GetValue(e.Row, _htmlField.Name) as string);
    }
  }
}

A: I'm not sure what happened, but I put the original code I posted above back into the customization project and it started working as expected.


text:
Q: Error Code: 1111. Invalid use of group function when trying to use Max function with IF condition I have a table category_model with columns- category_id, start_range, end_range and percentile.
category_id is of type varchar e.g. C1, C2, C3
start_range and end_range are float values e.g. -0.25 to 4.65
I am trying to check for scores that fall within a certain range and return the corresponding percentile.
The following query returns an error code 1111-invalid use of group function-
SELECT max(IF(spm.start_range <= 1.19 AND spm.end_range >= 1.19, spm.percentile, IF(max(spm.end_range) < 1.19, 99, 0))) AS percentile
FROM category_model spm
WHERE spm.category_id = 'C1'

If I replace it with the query below, it works fine, but then I cannot check the boundary conditions(e.g. a score falls outside the min start_range or max end_range).
SELECT max(IF(spm.start_range <= 1.19 AND spm.end_range >= 1.19, spm.percentile, 0)) AS percentile
FROM category_model spm
WHERE spm.category_id='C1'

Is there a way around this? I am using MySql version 5.2

A: Multiple aggregate function combination is not allowed.
Try this one by using subquery:
SELECT max(IF(spm.start_range <= 1.19 AND spm.end_range >= 1.19, spm.percentile, IF((SELECT MAX(end_range) FROM category_model) < 1.19, 99, 0))) AS percentile
FROM category_model spm
WHERE spm.category_id = 'C1'

A: Use a sub-query;
SELECT
    max(
        IF(
            spm.start_range <= 1.19 AND spm.end_range >= 1.19,
            spm.percentile,
            IF(x.max_end_range < 1.19, 99, 0)
        )
    ) AS percentile
FROM category_model spm
cross join (
    select max(end_range) max_end_range
    FROM category_model
    WHERE spm.category_id = 'C1'
) x
WHERE spm.category_id = 'C1'

Note:- Here spm.category_id = 'C1' condition is applied to calculate max_end_rangeIf that is not what you want then remove the condition.


text:
Q: Accesing external Javascript (Chart.js) with Thymeleaf i am trying some time now, to get the Chart.js in external file working with Thymeleaf. I was checking in countless external forums but couldnt find an answer. The closes to what i could find is the following
Thymeleaf external javascript file shares the module attributes with html file
but i still didn't manage to do it.
Here is my Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ChartController {

    @RequestMapping("/ExternalChart")

    public String hello(Model model) {

        String label[] = {"a","b","c","d","e","f","g","adasda","adasda2"};

        int point[] = {5,3,7,1,8,3,4,50};

        model.addAttribute("label",label);
        model.addAttribute("point",point);

        return "ExternalChart";
    }

}

html file is located in src/main/resources/templates/
<!DOCTYPE html>

<meta charset="UTF-8">
<link href="../static/css/Layout.css" th:href="@{/css/test.css}"
    rel="stylesheet" />
    <link href="../static/js/drawChart.js" th:href="@{/js/drawChart.js}"
    rel="javascript" />

Donkey

punch

    <canvas id="ChartDemo"></canvas>

My javascript. it is located in src/main/resources/static/js
function drawchart(xAxisData, yAxisData) {

    var ctx = document.getElementById("ChartDemo").getContext('2d');
    var ChartDemo = new Chart(ctx, {
        type : 'line',
        data : {

            labels : xAxisData,
            datasets : [ {
                label : "Chart-1",
                borderColor : 'rgb(255, 0, 0)',
                lineTension : 0,
                fill : false,
                data : yAxisData,
            }, ]
        },
        options : {
            responsive : true,
        }
    });
}

What i have noticed is that the attributes xAxisData and yAxisData get the values, but it seams that the drawChart(xAxisData,yAxisData) doesn't not get executed in browser.
I assume that i am making some silly mistake, and prospects of me finding it alone is close to zero. Thanks to anybody even trying to help me out
BR HK
p.s. i am really new with JS

A: I kind of have an answer. In this youtube video
https://www.youtube.com/watch?v=AEy7Hlz58bw? it is explained how to "externalize" JavaScript files. However, it is not really intuitive.
Javascript had to be written without function() part (which is something that i dont really understand)
//function done(xAxisData, yAxisData) {
    var ctx = document.getElementById("ChartDemo").getContext('2d');
    var ChartDemo = new Chart(ctx, {
        type : 'line',
        data : {

            labels : xAxisData,
            datasets : [ {
                label : "Chart-1",
                borderColor : 'rgb(10, 0, 0)',
                lineTension : 0,
                fill : false,
                data : yAxisData,
            }, ]
        },
        options : {
            responsive : true,
        }
    });
//}

and respective HTML needs to look like this
<!DOCTYPE html>

<meta charset="UTF-8">
<link href="../static/css/Layout.css" th:href="@{/css/test.css}"
    rel="stylesheet" />
<link href="../static/js/drawChart.js" th:href="@{/js/drawChart.js}"
    rel="javascript" />

Donkey

punch

    <canvas id="ChartDemo"></canvas>

basically part where attributes xAxisData and yAxisData are initialized, could not contain the external script file.
If i manage to find more suitable solution, i will be glad to post it as an update to this answer as i have noticed that a lot of people get stuck in similar problems
BR DK


text:
Q: What are the performance penalties, if any, of KEYS_ONLY versus ALL when projecting attributes in a DynamoDB GlobalSecondaryIndex? If you don't project all the attributes then if you query by that index by definition you can only get the hash of that value from the result and then perform another query using the hash key to get all the other data.
This would be 2 queries just to get 1 item. Naturally that doesn't make a lot of sense so there must be some reasons why it's advantageous to project only KEY attributes.
Does it speed up replication across the GSI since there are less values to copy thereby increasing chance of a fully consistent read taking place?
Does it lower read / write costs to the table overall as a whole?


text:
Q: Use later frame for video thumbnail in Windows 7 I've got a collection of videos and most of the thumbnails generated are useless as they are of a frame very early on, in most cases the title sequence.
Is there any registry setting or something to change the minimum length into a file to take a thumbnail shot?

A: You can use Thumbnailer Lite to specify a relative or fixed offset to use for video thumbnails. It can also alter a few other aspects of the thumbnail including adding a glossy shine on it. It can also be used to choose whether an embedded thumbnail is used (if available) or force a dynamic one to be generated.

A: Use Icaros.

Icaros is a collection of lightweight, high-quality, Windows Shell Extensions, which is capable of providing Windows Explorer thumbnails for essentially any video media file type. Icaros can provide Windows Explorer thumbnails, for essentially any video media format supported by FFmpeg which includes popular file types such as: MKV, FLV, AVI, MP4, MOV, RMVB, M2TS, OGM, etc. It is capable of thumbnailing just about any file by adding its extension(s) to the optional filetypes box and re-activating Icaros.

To set an offset to use for video thumbnails, after installing, open Icaros → Thumbnailing → Activate → SETTINGS → Set the "Thumbnail Offset." By default, it is set to 25% progress of the video. You can change this percentage, or you can also opt to set a specific preferred timestamp.
Screenshot:


text:
Q: how to program something like discord game activity So I have been trying to create something like discord game activity: When you open an app, discord displays it as the game you are currently playing. Now I don't want to query all open applications every second, so I was wondering whether there were alternatives like a callback when an application starts(I don't own the program, so I can not modify it). At first, I would like it to work on windows, but if you have solutions for other platforms I won't mind. I'm also using electron.js

A: You will get a loads more callbacks than you might expect from anything in win32 land that notifies you that a process has started. There used to be such an api a long way back [http://www.rohitab.com/discuss/topic/40418-process-notification-on-81/?p=10093378] . So... The only way I suspect you can do it now is through DDL hooking - which as far I recall requires admin privilege to install the hook. It's pretty low level thing to want to do here, so you will need to be writing some IPC code to talk between your hook and your Electron app. Probably a decent place that lays out your options is here https://www.apriorit.com/dev-blog/679-windows-dll-injection-for-api-hooks Note: Most AV will want to flag your app as malicious depending on which route you do follow.


text:
Q: Valid/invalid bit associated with memory segments From "Operating System Concepts":
Segmentation (without virtual memory)

With each entry in segment table associate:

*

*validation bit = 0 -> illegal segment

I understood that the valid/invalid bit is useful dealing with pages (a process doesn't use all the pages provided by the hardware architecture, so only the process' pages have to be marked as valid), but why is a valid/invalid bit associated with every entry in a segment table? Isn't the number of segments known at compile time? Every process' segment should be marked as valid, or not?


text:
Q: How to find the largest value for a function. What should I do with the natural number if x is not a natural number! Find the largest value of $^{1/} $  if  is a natural number.
My attempt solution is to find the derivative, equate to 0 and solve for that.
However, I get that x is e. Of course e is not a natural number. Hence why I am confused. How should I continue from here?
Should I state that since x is not a natural number the question can't be answered?

A: Let $f(x) =x^{\frac{1}{x}}$.
If you study the sign of $f'$ you'll see that $f$ is decreasing for $x \geq e$ and increasing for $x \leq e$ .
So if you take $2<e<3$ you have that $f(1)<f(2)$ and $f(n)<f(3)\ \forall n\geq 3$ this means that the maximum is either $2$ or $3$.
But $f(3)=\sqrt[3]{3}>\sqrt{2}=f(2)$ since $9>8$
So the maximum in the naturals must be 3.

A: Alternative approach:
As discussed,
$$\frac{d ~~\text{exp}\left[\frac{\log(x)}{x}\right]}{dx} ~: ~x \geq 3$$
is always negative, specifically because
$$\frac{d \left[\frac{\log(x)}{x}\right]}{dx} = \frac{1 - \log(x)}{x^2} ~: ~x \geq 3$$
is always negative.
Therefore, the problem reduces to manually examining $~\displaystyle n^{(1/n)},~$ for each $~n \in \{1,2,3\}.$
Per the answer of iZxCV, a reasonable shortcut is to realize that for $~1 \leq x \leq e,~$ the pertinent derivative is positive.  Therefore, you can immediately exclude $n=1$ from consideration and simply manually consider $n=2, n=3.$
Further, since $3$ is closer to $e = 2.71828...$ than $(2)$, you might blindly guess that $~\displaystyle 2^{(1/2)} < 3^{(1/3)}.$
Such a blind guess might be confirmed in one of two ways:
You know from the derivative that $~\displaystyle 3^{(1/3)} > 4^{(1/4)} = 2^{(1/2)}.$
Alternatively, you can reason that
$$2^{(1/2)} = 2^{(3/6)} = 8^{(1/6)} < 9^{(1/6)} = 3^{(2/6)} = 3^{(1/3)}.$$


text:
Q: Indexing pandas dataframe by passing a list I am trying to select multiple values from a DataFrame object that looks like this:
Int64Index: 100 entries, 0 to 99
Data columns (total 6 columns):
Cell                  68  non-null values
Sequence Protocol     68  non-null values
dtypes: float64(2), object(4)

I would like to select multiple values based on the value in the Cell column. I know how to do this by running a for loop over the data but I find that clunky.
Ideally, I would like to pass a list of "cells" that would give me another DataFrame object back.
An example output would be following:
idx = cell_info.Cell == ['1','3','5']

Would give the following for idx:
0    True
1   False
2    True
3   False
4    True
5   False
6   False
...

With np.sum(idx) would equal to 3
I have tried reindexing by Cell:
cell_info.reindex(index=cell_info.Cell)

Which results in empty DataFrame.
I tried passing the following to get the indexes where data.keys() is a list of cells I want to index by:
idx = cell_info.Cell == data.keys()

Which results in all values False i.e np.sum(idx) will yield 0 (but doesn't if I call each of them on its own).
If I do the following:
np.where(cell_info.Cell == data.keys())

It returns empty array, however, if I do the following:
np.where(cell_info.Cell == list(data.keys()))

It gives an error:
ValueError: Arrays were different lengths: 100 vs 19

It would be great if you could explain what is the appropriate way of passing a list to index and why there is a difference in the last two calls.


text:
Q: async/await "List<> does not contain a definition for 'GetAwaiter'" I apologize for sounding dense, but I swear I have read up on async/await and played with examples, but I am still stumped at simple things like why the following code is giving me error:
        [HttpGet("{includeInactive}")]
        public async Task<List<Torrent>> GetTorrentsAll(bool includeInactive)
        {
            List<Torrent> torrentsAll = await _cacheStore.GetCachedTorrentsAll();

            //...potentially filter torrentsAll here

            return torrentsAll;
        }

So _cacheStore.GetCachedTorrentsAll() is not an async function. It's just a function that potentially might be taking a while in the database, so I was trying to ensure that it's not blocking. I thought that awaiting it within the async web API was the way to go about that. But I get confusing error under the await _cacheStore.GetCachedTorrentsAll() line that says 'List does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'List' could be found (are you missing a using directive or an assembly reference?).
I am very confused by this.

A:
So _cacheStore.GetCachedTorrentsAll() is not an async function. It's just a function that potentially might be taking a while in the database, so I was trying to ensure that it's not blocking.

It is reasonable to make it asynchronous, then.

I guess maybe since _cacheStore.GetCachedTorrentsAll() is not async, it will still block the thread regardless (?)

This is correct. Synchronous methods - by definition - block the calling thread until they complete.

In which case async/await seems like a rabbit hole to me,

It can be. In this case, you have correctly identified an operation that should be asynchronous (i.e., I/O-bound). But just sticking an async on the controller method isn't going to help; that's actually the last step in making this asynchronous.
The first step is to identify the lowest-level API that should be asynchronous. E.g., the database query. Make that call use the asynchronous database API first, use await, and make that method async. Then let async/await grow from that method up through your app. It will eventually end up at the controller method, and then you can make that async.

A: You can rewrite your code to look like this:
[HttpGet("{includeInactive}")]
public async Task<List<Torrent>> GetTorrentsAll(bool includeInactive, CancellationToken token)
{
    return await Task.Run(() => {
        List<Torrent> torrentsAll = _cacheStore.GetCachedTorrentsAll();

    return torrentsAll;
    }, token);
}


text:
Q: Run Emacs batch scripts on OSX I'm a long time GNU/Linux user. Even though OSX is much like GNU/Linux is many ways, it differs in some. For example, when I install Firefox I expect to be able to run firefox in a shell to start it. But not in OSX.
That gives me some trouble when running Emacs batch scripts. Lets say I have this script:
#!/usr/bin/env emacs --script

(message "Hello world!")

I can run it without any problems. But I'll be using the emacs builtin to OSX. And most of the times that's not possible since the Emacs version is pretty old.
Installing Emacs from scratch made it possible to create a Bash-script, which called some emacs binary file.
But installing Emacs from http://emacsformacosx.com/ I can not make this work. Can anyone think of a solution for this?

A: (1) Launch Emacs.
(2) Open Activity Monitor. (Applications > Utilities > Activity Monitor)
(3) Find Emacs in the list of running processes, under "Process Name".
(4) Select it.
(5) Choose "Inspect" from the Toolbar.
(6) In the window that opens, choose the "Open Files and Ports" tab.
(7) The name of the Emacs executable currently running should be the second line in the list. (The first line should be /Users/yourusername.) In my case it's /Applications/Emacs.app/Contents/MacOS/Emacs, which is pretty standard.

A: Yes, you dig out the path to the Emacs app emacs.
I've got X EMACS on my machine (not an emacs app), but the path will be something like
/Applications/Emacs.app/Contents/bin/emacs

You can find the exact path with ls from the command line.


text:
Q: Excel - How do I use a cell value in one sheet to go to another value on a separate sheet in same workbook Right now I have a spot where the person will enter in their date they want to find and I want them to be able to push 'GO', this part is easy. I want it to look in another data sheet and go to and select the cell that corresponds with the value they put in the first sheet.
For reference in my code below 'HomeSheet' is the user page where they enter the data. 'DataSheet' is the page I want them to be directed to when they push the button.
Current code is giving me an error on the 3rd to last row where it's trying to select the cell it found that corresponded with the input date on the HomeSheet.
Any help is greatly appreciated!
Private Sub CommandButton4_Click()

    Dim xlRange As Range
    Dim xlCell As Range
    Dim xlSheet As Worksheet
    Dim valueToFind

    valueToFind = ThisWorkbook.Sheets("Homesheet").Range("I8")
    Set xlSheet = ActiveWorkbook.Worksheets("DataSheet")
    Set xlRange = xlSheet.Range("A1:ZZ1")

    For Each xlCell In xlRange
        If xlCell.Value = valueToFind Then
        Sheets("DataSheet").Range(xlCell).Select
        End If
    Next xlCell

End Sub


text:
Q: How I solve the error "sql: converting argument $1 type: unsupported type []interface {}, a slice of interface" How I solve the error "sql: converting argument $1 type: unsupported type []interface {}, a slice of interface"
I want to create Delete function in golang.
I think that
ids_interface := []interface{}{}
    for id := range ids{
        ids_interface = append(ids_interface, id)
    }

this code is mistake.
func String(ids []int64) string {
    ans := strings.Builder{}
    for i := 0; i < len(ids); i++ {
        ans.WriteString(strconv.FormatInt(ids[i], 10))
        if i != len(ids)-1 {
            ans.WriteRune(',')
        }
    }
    return ans.String()
}
// DeleteTODO deletes TODOs on DB by ids.
func (s *TODOService) DeleteTODO(ctx context.Context, ids []int64) error {
    const deleteFmt = `DELETE FROM todos WHERE id IN (?%s)`
    str_ids := String(ids)
    deleteFmt_str := fmt.Sprintf(deleteFmt, str_ids)
    ids_interface := []interface{}{}
    for id := range ids{
        ids_interface = append(ids_interface, id)
    }
    stmt,err := s.db.PrepareContext(ctx,deleteFmt_str)
    if err != nil{
        log.Fatal("server/todo.go update prepareContext ",err)
    }
    defer stmt.Close()
    res, err := stmt.ExecContext(ctx,ids_interface)
    if err != nil {
        return err
    }
    rows,err := res.RowsAffected()
    if err != nil {
        log.Fatal("server/todo.go stmt.RowsAffected()",err)
    }
    if rows != 1 {
        errors := model.ErrNotFound{ErrorWhen:time.Now(),ErrorWhat: "it didn't work"}
        return &errors
    }

    return nil
}


text:
Q: Different data.table r results with or without quotations / How to count unique values with uniqueN I'm trying to select all claims (ICN) with the value of 7015061009422. I use the following code:
  dt[ICN==7015061009422]

And I get back
> dt[ICN==7015061009422]
    UniversalID           ICN
 1:           2 7015061009422
 2:           3 7015061009417
 3:           2 7015061009411
 4:           2 7015061009428
 5:           2 7015061009437
 6:           4 7015061009417
 7:           5 7015061009411
 8:           6 7015061009417
 9:           6 7015061009422
10:           7 7015061009422

I finally figured out that if I put quotations around the value, what I want to happen, which is to select all the lines that actually have the ICN number equal to 7015061009422, that is what I get:
    > dt[ICN=="7015061009422"]
   UniversalID           ICN
1:           2 7015061009422
2:           6 7015061009422
3:           7 7015061009422

Why is it that using quotations around my data values makes such a big difference?
Sample dataset:
    ICN<-c(7015061009422,7015061009417,7015061009411,7015061009428,7015061009437,7,7015061009417,7015061009411,7015061009417,7015061009422,7015061009422,1)
  UniversalID<-c(2,3,2,2,2,1,4,5,6,6,7,8)
  dt<-cbind(UniversalID,ICN)
  dt<-as.data.table(dt)
  dt[ICN==7015061009422]
  dt[ICN=="7015061009422"]

I'm hoping that this can also help me figure out why my unique count isn't working:
> > dt[,uniqueN(ICN)]
[1] 3

Very clearly, there are more than three different ICN values, so why this happening?

A: When you compare very large numbers using ==, R does not check for exact equality. Rather, it checks whether the numbers are "close" to each other. If so, it returns TRUE. R does the same thing with floating point numbers.
When you put quotations around your number, you are implicitly casting it into a string. Thus, calling == will cause R to do a string comparison, and you get the answer you want.
Instead of a == b, use abs(a-b) < 0.001, or some other arbitrary small number.
EDIT: Are you doing any actual arithmetic with these numbers? If not, you should probably just convert them to factors.


text:
Q: how angular2 app can call jsp page I am trying to integrate my Angular2 + Java web app with another one which consists of many JSPs (and doesn't have any Web Services).
What is a right way of calling non visual JSP page from Angular?   I assume the call passes JS object (or JSON) and returns another object or JSON (which might have some status, error code, maybe include input object with some modifications).
Should response be processed as observable?
Any code samples?
TIA,
Oleg

A: JSP run on server side in addition to html, css and js. it would be most appropriate to say that your angular web app calls a servlet. For instance, you may have an angular web login page whereby the servlet will do the authentication procedures and return a json string denoting a successful or unsuccessful authentication which can be parsed in your angular web app. For any remote calls in angular use angular http api, please refer to these two links
https://angular.io/guide/http
https://angular.io/api/http/Http
An example to get you going is as per below
If your servlet url is annotated as follows
@WebServlet("/login")

//in your servlet you can use java libraries like json writer or google gson to build your json object and then send it using for instance response.getWriter().
in your angular web app, you can call the servlet as follows:
return this.http.get('http://localhost:8080/testapp/login')
            .map((res: Response) => {
                //this.result will contain the results of the authentication process
                this.result = res.json();
            })
            .catch(this.handleError);

hope its enough to get you going. the angular link will help you understand more.
Ashley


text:
Q: How to set the FlagStatus on the "Sent" copy of a message? Essentially I want to run the following code.
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    If InStr(Item.Body, "XYZ") > 0 Then
        mailItem.FlagStatus = olFlagComplete
        mailItem.Save
    End If
End Sub

This gives me two problems. Firstly Outlook won't let me set the FlagStatus in this event, so I have to set FlagRequest to "Complete".
Maybe I can live with this. Secondly, and more importantly, this flag is set in the copy of the message that goes to the recipients but is not set in the copy of the message that I keep.
I need this flag set for me, not the recipient of the message. Thanks for suggestions.

A: Switch to the ItemAdd event on the Sent Items folder.
In the ThisOutlookSession module.
Private WithEvents sentFolItms As Items

Private Sub Application_Startup()
    Set sentFolItms = Session.GetDefaultFolder(olFolderSentMail).Items
End Sub

Private Sub sentFolItms_ItemAdd(ByVal sMail As Object)
    If InStr(sMail.Body, "XYZ") > 0 Then
        sMail.FlagStatus = olFlagComplete
        sMail.Save
    End If
End Sub


text:
Q: How can I have list of all users logged in my web application I use spring-mvc and each use who logged in my web app i create a session variable user which is a object containing his id, name and some others info.
session.setAttribute("user", user);

What I want is to have a list of all users who are logged in my program.
i want this list to check simultaneous log in because is must be just one access by account.
ps : don't tell me to use spring-security because i want to work just with MVC Interceptor and preHandle()

A: 1) use below code to auto-wire ServletContext object in spring MVC
@Autowired
ServletContext context;

2) You need to collect all logged in users Set in the context.
...
    public void login(User user) {
        logins.add(user);
    }
...
    public void logout(User user) {
        logins.remove(user);
    }

If you're storing the logged-in users in the session already
public void sessionDestroyed(HttpSessionEvent event) {
    User user = (User) event.getSession().getAttribute("user");
    if (user != null) {
        Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
        logins.remove(user);
    }
}

A: You can use the implementation of HttpSessionListener and ServletContextListener.
HttpSessionListener gets invoked whenever a Session is created or destroyed ,Where as ServletContextListener is invoked when Context is created or destroyed.
EDIT:
The HttpSessionBindingListener can be used on the class whose instances may be stored in the session, such as in your case User.
When an instance of this User get set as a session attribute by HttpSession.setAttribute(), then the valueBound() will be invoked. When it get removed by either HttpSession.removeAttribute(), or an invalidate of the session, or get replaced by another HttpSession.setAttribute(), then the valueUnbound() will be invoked.
Example :
public class User implements HttpSessionBindingListener {

@Override
public void valueBound(HttpSessionBindingEvent event) {
    addLoginUser(event);
}

@Override
public void valueUnbound(HttpSessionBindingEvent event) {
    removeLoginUser(event);
}

private void removeLoginUser(HttpSessionBindingEvent event){
if (user != null) {
            ServletContext context = event.getSession().getServletContext();
            Set<User> logins = context.getAttribute("loginUsers");
            logins.remove(this);
    }
 }
   private void addLoginUser(HttpSessionBindingEvent event){

   if (user != null) {
      ServletContext context = event.getSession().getServletContext();
      Set<User> logins = context.getAttribute("loginUsers");
      logins.add(this);
   }
}

}
 //Use this listner for adding loginUsers when ServletContext is initialized.
 public class MyServletContextListener implements ServletContextListener{
   public void contextInitialized(ServletContextEvent event){
       Set<User> logins = new HashSet<User>();

       //add Initial login to ServletContext
       event.getServletContext().setAttribute("loginUsers", logins);
   }

 public void contextDestroyed(ServletContextEvent event){}

 }

Add the following configuration in your web.xml file.
<listener>
    <listener-class>
        package.name.MySessionAttributeListener
    </listener-class>
</listener>

 <listener>
    <listener-class>
        package.name.MyServletContextListener
    </listener-class>
</listener>

Hope this helps,Thanks.


text:
Q: How can I make two windows on jetpack compose desktop and going from window to another? How can I make two windows on jetpack compose desktop and going from window to another when I click button for example?
fun main() = application {
    Window(
        onCloseRequest = ::exitApplication,
        title = "Products Manager",
        state = rememberWindowState(width = 700.dp, height = 600.dp)
    ) {
        val count = remember { mutableStateOf(0) }
        MaterialTheme {
            Column(Modifier.fillMaxSize(), Arrangement.spacedBy(5.dp)) {
                Button(modifier = Modifier.align(Alignment.CenterHorizontally),
                    onClick = {
                        count.value++
                    }) {
                    Text(if (count.value == 0) "Hello World" else "Clicked ${count.value}!")
                }
                Button(modifier = Modifier.align(Alignment.CenterHorizontally),
                    onClick = {
                        count.value = 0
                    }) {
                    Text("Reset")
                }
            }
        }
    }
}

A: To create multiple windows, you simply need to have multiple Window composables. Check out Open and close multiple windows documentation section for example.
To switch between windows programmatically, you can use window.toFront() on the window that should become topmost: window is property available in FrameWindowScope inside Window.content.
Here's an example how it can be done with two window "types". You can replace type with any other identifier.
enum class WindowTypes {
    First,
    Second,
}

fun main() = application {
    val windowFocusRequestSharedFlow = remember { MutableSharedFlow<WindowTypes>() }

    WindowTypes.values().forEach { windowType ->
        key(windowType) {
            Window(
                title = windowType.toString(),
                onCloseRequest = ::exitApplication,
            ) {
                LaunchedEffect(Unit) {
                    windowFocusRequestSharedFlow
                        .filter { it == windowType }
                        .collect {
                            window.toFront()
                        }
                }
                val scope = rememberCoroutineScope()
                Button({
                    scope.launch {
                        val windowTypeToFocus = WindowTypes.values().run {
                            get((indexOf(windowType) + 1) % count())
                        }
                        windowFocusRequestSharedFlow.emit(windowTypeToFocus)
                    }
                }) {
                    Text("next window")
                }
            }
        }
    }
}


text:
Q: Placing Google Analytics in a separate file I have a bunch of static webpages that used to have GA code placed before </body> tag. I was tasked to place them before the </head> tag (as recommended by Google). (Personally, I think this is a silly request but you have to make the client happy.)
Now, my question is not about the benefit of having GA code in the <body> opposed to the <head> but about whether placing the GA code in a script file (that is in the <head> tag) would be the same as placing it inline right before </head> tag?
For example,
index.html
 <head>
     <!-- some stylesheet files -->
     <!-- some script files -->
     <script>
         // Google Analytics code
     </script>
 </head>

versus
index.html
 <head>
     <!-- some stylesheet files -->
     <!-- some script files -->
     <script src="main.js"></script>
     <!-- some more script files -->
 </head>

main.js
 // random JS code followed by Google Analytics code

A: You can place the GA code inside your main.js then you'll not have to explicitly place the GA code on all pages.


text:
Q: How Do I Properly Update AppWidget? I'm a noob to android and I'm having issues updating an appwidget.  It's a news widget that displays different text every 20 secs.  I have no problem getting the text to switch & display  properly when the widget is initialized.  However, after every 30 min update of the widget my widgetID int array retains the int that existed prior to the update.  So after each update the widget shows old data and new data.  Is there a to clear the widget ID int array of old data during the update process.  Any help is greatly appreciated.
My Code:
allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);

Method for switching text in widget.  This works fine initially, but after update shows old data along with new data...
   public void updateStory() {

    tickerheadline = RssReader.rssheadline.get(storyCounter);
    tickerstory = RssReader.rssstory.get(storyCounter);
    remoteViews.setTextViewText(R.id.headline, tickerheadline );
    remoteViews.setTextViewText(R.id.story, tickerstory );
    if (storyCounter==RssReader.rssheadline.size()-1){
        storyCounter = 0;
        storyCounter++;
    }else{
        storyCounter++;
    }
    appWidgetManager.updateAppWidget(allWidgetIds, remoteViews);
    //Log.e("Widget", allWidgetIds.toString());
    mHandler.postDelayed(new Runnable() {
         public void run() {
           updateStory();
         } } ,20000);  }

}

EDIT
public void updateStory() {
    //Added
    appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
    ComponentName thisWidget = new ComponentName(getApplicationContext(),MyWidgetProvider.class);
    remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(),R.layout.widget1);

    tickerheadline = RssReader.rssheadline.get(storyCounter);
    tickerstory = RssReader.rssstory.get(storyCounter);
    remoteViews.setTextViewText(R.id.headline, tickerheadline );
    remoteViews.setTextViewText(R.id.story, tickerstory );
    if (storyCounter==RssReader.rssheadline.size()-1){
        storyCounter = 0;
        storyCounter++;
    }else{
        storyCounter++;
    }

    appWidgetManager.updateAppWidget(thisWidget, remoteViews);

    //appWidgetManager.updateAppWidget(allWidgetIds, remoteViews);
    //Log.e("Widget", allWidgetIds.toString());
    mHandler.postDelayed(new Runnable() {
         public void run() {
           updateStory();
         } } ,20000);  }

}

A: Although you can be very clever with AppWidgets in android in terms of updating and so in, the easiest way to get going is simply to rebuild the widget contents every time you refresh. As you're only refreshing every 30 minutes, there's not much reason to worry about cpu usage.
So, I would suggest doing a standard rebuild each time you trigger an update using the standard approach. The code you have above, whilst it looks correct, doesn't actually force an update, much cleaner to start from scratch. Once that's working, then if you can make it more lightweight, do tell me how!
// You need to provide:
// myContext - the Context it is being run in.
// R.layout.widget - the xml layout of the widget
// All the content to put in it (duh!)
// Widget.class - the class for the widget

RemoteViews rv= new RemoteViews(myContext.getPackageName(), R.layout.widget);
rv.setXXXXXXX // as per normal using most recent data set.
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(myContext);
// If you know the App Widget Id use this:
appWidgetManager.updateAppWidget(appWidgetId, rv);
// Or to update all your widgets with the same contents:
ComponentName projectWidget = new ComponentName(myContext, Widget.class);
appWidgetManager.updateAppWidget(projectWidget, rv);

Often the easiest approach (in my view) is to wrap this up in a WidgetUpdater.class which you either call from a service or directly using a time alarm call. Using onUpdate is generally a bad idea because it force the phone into full power mode and isn't very controllable. I've never managed to make it work. Much better to do something like:
    Intent myIntent = // As per your onUpdate Code
    alarmPendingIntent = PendingIntent.getService(context, 0, myIntent, PendingIntent.FLAG_ONE_SHOT);

    // ... using the alarm manager mechanism.
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, alarmPendingIntent);


text:
Q: Issue with z-index and transform I am trying to create a dropdown menu with secondary and tertiary sub menus. The sub menus are supposed to slide out from underneath the parent menus.  The actual code has several divs nested in multiple levels.
I have added a transform of translateY(700px) to the secondary-menu element to make it slide from underneath the primary-menu. However that causes the tertiary-menu to slide over the secondary-menu and not underneath it.
If the transform is removed the tertiary-menu works fine. A z-index of -1 was provided on tertiary-menu but that does not help. I have tried other combination of z-index on secondary and tertiary menus but it does not work.
There are quite a few related questions on this site but they don't help in my case. Here is the stripped down version of code to recreate the issue:

.primary-menu {
  position: relative;
  margin-left: 50px;
  z-index: 100;
  background-color: grey;
  height: 50px;
  padding: 20px;
}

.primary-menu:hover~.secondary-menu {
  transform: translateY(0);
  visibility: visible;
  height: 500px;
}

.secondary-menu:hover {
  transform: translateY(0);
  visibility: visible;
  height: 500px;
  /* actually height is not known in advance, this value is put here just for this example */
}

.secondary-menu {
  position: absolute;
  width: 150px;
  top: 50px;
  left: 50px;
  background-color: red;
  transform: translateY(-700px);
  transition: transform 1s;
  visibility: hidden;
}

.category {
  padding: 20px;
  position: relative;
}

.tertiary-menu {
  position: absolute;
  left: 100%;
  visibility: hidden;
  padding: 20px;
  top: 0;
  left: 0;
  transition: left 1s;
  z-index: -1;
  background-color: hotpink;
}

.category:hover .tertiary-menu {
  visibility: visible;
  left: 100%;
}

Menu

Mobiles

Smartphones

Mobile Cases, Covers

Power Banks

Feature Phones

Samsung

The sandbox link is here

A: The 'z-index' you put in the '.tertiary-menu' is working.
The reason it doesn't seem to work is because '.tertiary-menu' is a children of '.category'.
The background of '.category' is transparent, so the '.tertiary-menu' below is visible.
Simply add the background color and height to '.category' and it will look like this.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.primary-menu {
    position: relative;
    margin-left: 50px;
    z-index: 100;
    background-color: grey;
    height: 50px;
    padding: 20px;
}

.primary-menu:hover~.secondary-menu {
    transform: translateY(0);
    visibility: visible;
    height: 500px;
}

.secondary-menu:hover {
    transform: translateY(0);
    visibility: visible;
    height: 500px;
    /* actually height is not known in advance, this value is put here just for this example */
}

.secondary-menu {
    position: absolute;
    width: 150px;
    top: 50px;
    left: 50px;
    background-color: red;
    transform: translateY(-700px);
    transition: transform 1s;
    visibility: hidden;
}

.category {
    padding: 20px;
    position: relative;
    height: 100%;
    background-color: blue;
}

.tertiary-menu {
    position: absolute;
    left: 100%;
    visibility: hidden;
    padding: 20px;
    top: 0;
    left: 0;
    transition: left 1s;
    z-index: -1;
    background-color: hotpink;
}

.category:hover .tertiary-menu {
    visibility: visible;
    left: 100%;
}

Menu

Mobiles

Smartphones

Mobile Cases, Covers

Power Banks

Feature Phones

Samsung


text:
Q: Visual Studio 2008 header path problem I'm having windows 7 and visual studio 2008 on my PC. Also having two windows SDKs of v6.0 and v7.1. I'm trying to create one small application using Microsoft Media Foundation but finding one problem. All header files which i included in my project are taking from the following path
c:\program files\microsoft sdks\windows\v6.0a\include\
instead of taking it from
c:\program files\microsoft sdks\windows\v7.1\include\
Could you please tel me how to change this path??
Thanks in advance,
Sri

A: Click Start->All Programs->Microsoft Windows SDK v7.1->Tools->Visual Studio Registration->Windows SDK Configuration Tool, select v7.1 from the dropdown menu and click Make Current


text:
Q: Bind Telerik Grid I am binding Gird like below with the Model named "Employee"
<%= Html.Telerik().Grid<Employee>()
             .Name( "EmployeeGrid" )
    .Columns(colums => colums.Bound(E => E.EmployeeID)) %>

But I am getting the below error in this line Grid<Employee>()

The type or namespace name 'Employee' could not be found
I have three grids in one view so I cannot refer any particular model name using @model in first line of view.

A: The error tells you that the View does not know the Type 'Employee' .
You have to write in the first line:
<%@ Import namespace="MyProgram.FolderOfEmployeeClass" %>

info of the using statement in aspx files:
Is it possible to use the 'using' statement in my aspx views? (ASP.NET MVC)
piece of advice: user the Razor engine instead of aspx. This is much more easier to use!


text:
Q: Regex to search inside contents of file I am using software to search inside txt files with Regex, For example

So I want to find files which Contain "Black" under "color" under "clothes", So the regex should highlight "Black" which located in line 7 only.
My aim here is to follow the order no mater how many lines between terms.
I will be more than thankful if you explain "regex" so I know what I have missed.
Thanks in advance

A: You can use the following regex for matching the given 'Black':
/.+?Clothes.+?Colour.+?(Black)/s

Description

Demo
http://regex101.com/r/gD9iD3
Discussion
The regex here may not fit all your needs. It uses .+? for navigating between the searched elements. This is really imprecise: the "Red" case that you have outputted in your comments is a guenine POC.
The next step here is to determine how elements (Clothes, Colour etc) are structured. Armed with this knowledge, the regex can be strengthened. .+? will be replaced then by more specific elements.
If the regex is used in a Javascript context, the s modifier is not available.
To work around this limitation, the following structure: .+? can be replaced with [\s\S]+?.