text:
Q: print lines between patterns individual separate files I have a big file of 5000+ lines which has a repeated pattern like shown below:
ABC
111
222
333
XYZ

ABC
444
555
666
777
XYZ

..
..

ABC
777777777
888888888
999999999
222
333
111
XYZ

I would like to extract contents between each 'ABC' and 'XYZ' and write it to a separate file.
Ex: file1 should have
ABC
111
222
333
XYZ

File2 should have
ABC
444
555
666
777
XYZ

Filen should have
ABC
777777777
888888888
999999999
222
333
111
XYZ

and so on.
How could we achieve this ? I read these below threads but it writes only one single file. Didn't help for my case.
How to select lines between two marker patterns which may occur multiple times with awk/sed
Print lines between two patterns to new file

A: awk '/^ABC/{file="file"c++}{print >>file}' a

A: Perl to the rescue!
< bigfile perl -nwe 'print {$OUT} $_
                         if (/ABC/ && do { open $OUT, ">", "file" . ++$i or die $!}
                            ) ... /XYZ/'

*

*n reads the file line by line

*it only prints if between /ABC/ and /XYZ/

*when /ABC/ is true, i.e. we're starting a new section, a new file is opened and associated with the filehandle $OUT. $i is the number of the file.

A: awk '
  # setup our output file name file0, file1, file2, ...
  $0 == "ABC"{if (i) {close(f)};f="file"i++;};
  # use inclusive range match
  $0 == "ABC",$0 == "XYZ"{print > f}
'


text:
Q: bash/sed script to get output from a file using a regex I have a file which contains lines of the form object 0: data: 2, object 0: data: 232132 in between other lines in the file.I need to extract the data values from the file for all object i and store them space separate in a output file say output using bash or sed.It would great if someone can help me in achieving this.
Example input:
num objects: 3
object    0: name: 'x'
object    0: size: 4
object    0: data: 1
object    1: name: 'y'
object    1: size: 4
object    1: data: 3231
object    2: name: 'x'
object    2: size: 4
object    3: data: -32

Example output:
1 3231 -32

A: You could use something like this:
awk '$3=="data:"{print $4}' file

This outputs the 4th field when the 3rd field is equal to "data:".
Shorter still, you could just match the pattern /data:/:
awk '/data:/{print $4}' file

To output the numbers on the same line, use printf rather than print. To keep things cleaner, you can use an array and print the values in the END block:
awk '/data:/{a[++n]=$4}END{for(i=1;i<=n;++i)printf "%s%s",$4,(i<n?FS:RS)}' file

Using an array like this makes it easy to separate each value with a space FS and add a newline RS at the end.
Any of these commands can produce an output file using redirection > output.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add or Subtract minutes from "int" formatted time Is there any easy way (using datetime or etc...) to correctly subtract/add minutes to the int formatted time, like:
1630 - 45 //I want to subtract 45 minutes from 1630 (a.k.a. 16:30), that gives 1585
          //However, I want to get  15:45

any simple workarounds?

A: You can do it by converting to a DateTime via string (and then back again), for example:
var time = 1630;
var newTime = int.Parse(
    DateTime.ParseExact(time.ToString("0000"), "HHmm", null)
            .AddMinutes(-45)
    .ToString("HHmm"));

Wrapped in an extension method:
public static int AddMinutes(this int source, int minutes)
{
    return int.Parse(
        DateTime.ParseExact(source.ToString("0000"), "HHmm", null)
                .AddMinutes(-45)
        .ToString("HHmm"));
}

And used like this:
var time = 1630;
var newTime = time.AddMinutes(-45);


text:
Q: How can Solve HTTP to HTTPS issue on HTML Template I have a site http://template.helloxpart.com/picasso/picasso/home_default.html, how can i secure this from http:// to https:// ?

A: You need a SSL certificate. This can be provided by certain hosters or you can get one here: https://www.instantssl.com/ssl-certificate-products/https.html (paid) or here: https://letsencrypt.org/ (free).


text:
Q: Segmentation fault handling I have an application which I use to catch any segmentation fault or ctrl-c.
Using the below code, I am able to catch the segmentation fault but the handler is being called again and again. How can I stop them.
For your information, I don't want to exit my application. I just can take care to free all the corrupted buffers.
Is it possible?
void SignalInit(void )
{

struct sigaction sigIntHandler;

sigIntHandler.sa_handler = mysighandler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
sigaction(SIGSEGV, &sigIntHandler, NULL);

}

and handler goes like this.
void mysighandler()
{
MyfreeBuffers(); /*related to my applciation*/
}

Here for Segmentation fault signal, handler is being called multiple times and as obvious MyfreeBuffers() gives me errors for freeing already freed memory. I just want to free only once but still dont want to exit application.
Please help.

A: You shouldn't try to continue after SIG_SEGV.  It basically means that the environment of your application is corrupted in some way.  It could be that you have just dereferenced a null pointer, or it could be that some bug has caused your program to corrupt its stack or the heap or some pointer variable, you just don't know.  The only safe thing to do is terminate the program.
It's perfectly legitimate to handle control-C.  Lots of applications do it, but you have to be really careful exactly what you do in your signal handler.  You can't call any function that's not re-entrant.  So that means if your MyFreeBuffers() calls the stdlib free() function, you are probably screwed.  If the user hits control-C while the program is in the middle of malloc() or free() and thus half way through manipulating the data structures they use to track heap allocations, you will almost certainly corrupt the heap if you call malloc() or free() in the signal handler.
About the only safe thing you can do in a signal handler is set a flag to say you caught the signal.  Your app can then poll the flag at intervals to decide if it needs to perform some action.

A: The default action for things like SIGSEGV is to terminate your process but as you've installed a handler for it, it'll call your handler overriding the default behavior. But the problem is segfaulting instruction may be retried after your handler finishes and if you haven't taken measures to fix the first seg fault, the retried instruction will again fault and it goes on and on.
So first spot the instruction that resulted in SIGSEGV and try to fix it (you can call something like backtrace() in the handler and see for yourself what went wrong)
Also, the POSIX standard says that,

The behavior of a process is undefined after it returns normally from
  a signal-catching function for a [XSI]   SIGBUS,  SIGFPE, SIGILL, or
  SIGSEGV signal that was not generated by kill(), [RTS]  sigqueue(),
  or raise().

So, the ideal thing to do is to fix your segfault in the first place. Handler for segfault is not meant to bypass the underlying error condition
So the best suggestion would be- Don't catch the SIGSEGV. Let it dump core. Analyze the core. Fix the invalid memory reference and there you go!

A: I do not agree at all with the statement "Don't catch the SIGSEGV".
That's a pretty good pratice to deal with unexpected conditions. And that's much cleaner to cope with NULL pointers (as given by malloc failures) with signal mechanism associated to setjmp/longjmp, than to distribute error condition management all along your code.
Note however that if you use ''sigaction'' on SEGV, you must not forget to say SA_NODEFER in sa_flags - or find another way to deal with the fact SEGV will trigger your handler just once.
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>

static void do_segv()
{
  int *segv;

  segv = 0; /* malloc(a_huge_amount); */

  *segv = 1;
}

sigjmp_buf point;

static void handler(int sig, siginfo_t *dont_care, void *dont_care_either)
{
   longjmp(point, 1);
}

int main()
{
  struct sigaction sa;

  memset(&sa, 0, sizeof(sigaction));
  sigemptyset(&sa.sa_mask);

  sa.sa_flags     = SA_NODEFER;
  sa.sa_sigaction = handler;

  sigaction(SIGSEGV, &sa, NULL); /* ignore whether it works or not */

  if (setjmp(point) == 0)
   do_segv();

  else
    fprintf(stderr, "rather unexpected error\n");

  return 0;
}

A: If the SIGSEGV fires again, the obvious conclusion is that the call to MyfreeBuffers(); has not fixed the underlying problem (and if that function really does only free() some allocated memory, I'm not sure why you would think it would).
Roughly, a SIGSEGV fires when an attempt is made to access an inaccessible memory address.  If you are not going to exit the application, you need to either make that memory address accessible, or change the execution path with longjmp().

A: Well you could set a state variable and only free memory if its not set.  The signal handler will be called everytime, you can't control that AFAIK.

A: I can see at case for recovering from a SIG_SEGV, if your handling events in a loop and one of these events causes a Segmentation Violation then you would only want to skip over this event, continue processing the remaining events. In my eyes SIG_SEGV is similar to the NullPointerException in Java. Yes the state will be inconsistent and unknown after either of these, however in some cases you would like to handle the situation and carry on. For instance in Algo trading you would pause the execution of an order and allow a trader to manually take over, with out crashing the entire system and ruining all other orders.

A: Looks like at least under Linux using the trick with -fnon-call-exceptions option can be the solution. It will give an ability to convert the signal to general C++ exception and handle it by general way.
Look the linux3/gcc46: "-fnon-call-exceptions", which signals are trapping instructions? for example.


text:
Q: EclipseLink JPA with N+1 @OneToMany and @OneToOne relationships with multilevel entities I have to fetch the details based on departmentId and below conditions. I am using eclipseLink JPA 2.4+
if IS_SUBJECT = 2 Teacher entity should join with Subject
if IS_SUBJECT = 1 Teacher entity should join with Lab

when I fetch with departmentId values should map into Department and Teacher entities. JPA query as below.
SELECT distinct f FROM Department f " +
    " join fetch f.teacherList fm" +
    " join fetch fm.subject fmi on (f.isSubject = 2 and fm.subjectId = fmi.subjectId) " +
    " join fetch fm.lab fmg on (f.isSubject = 1 and fm.labId = fmg.labId) " +
    " WHERE f.departmentId IN :departmentIdList".

Entities as below:
@Entity
public class Department{
    @Id
    @Column(name = "DEPARTMENT_ID")
    private Integer departmentId;

    @OneToMany(mappedBy = "department")
    private List<Teacher> teacherList;

    @Column(name="IS_SUBJECT")
    private isSubject;
}

@Entity
public class Teacher{
    @Id
    @Column(name = "TEACHER_ID")
    private Integer teacherId;

    @Column(name = "DEPARTMENT_ID")
    private Integer departmentId;

    @Column(name = "SUBJECT_ID")
    private Integer subjectId;

    @Column(name = "LAB_ID")
    private Integer labId;

    @ManyToOne
    @JoinColumn(name = "DEPARTMENT_ID", insertable = false, updatable = false)
    @BatchFetch(BatchFetchType.JOIN)
    private Department department;

    @JoinColumn(name = "SUBJECT_ID", insertable = false, updatable = false)
    @BatchFetch(BatchFetchType.JOIN)
    private Subject subject;

    @BatchFetch(BatchFetchType.JOIN)
    @JoinColumn(name = "LAB_ID", insertable = false, updatable = false)
    private Lab lab;

}

@Entity
public class Subject{
    @Id
    @Column(name = "SUBJECT_ID")
    private Integer subjectId;

    @Column(name = "SUBJECT_NAME")
    private Integer subjectName;

}

@Entity
public class Lab{
    @Id
    @Column(name = "LAB_ID")
    private Integer labId;

    @Column(name = "LAB_NAME")
    private Integer labName;

}

The generated query is taking long time to fetch from eclipse link JPA. Please help me on writing the query.


text:
Q: How can I exorcise ghost Model from project? I had a Model called Media; it was since renamed to "PetImage" and further revised. Now ack doesn't find the string "Media" in any of my Python source files, .pyc files, my templates, or my SQLite3 database. So far as I can tell from re-examining source (and restarting Gunicorn), the string "Media" shouldn't be anywhere to be found anywhere in my project apart from e.g. stuff under CKeditor's root. I've also made and executed migrations.
But I'm still getting http://dpaste.com/0FX74SJ - Django is erroring out on a reported failure to load "Media":
Exception Value: 'module' object has no attribute 'Media'

What can I do so that Django doesn't expect the 'module' object (my models.py, I think) to provide a Media?
The function that appears to be getting the complaint is the fourth line, with the for loop, in:
def one_pet(request, pet_id):
    pet = models.Pet.objects.get(id = pet_id)
    media = []
    for item in models.PetImage.objects.all():
        if item.url.startswith('https://youtu.be/'):
            media.append('')
        else:
            media.append('')
    return render(request, 'one_pet.html', {
        'pet': pet,
        'site_name': settings.SITE_NAME,
        })

Is there additional bookkeeping to do if a model is renamed? What should I be doing if I want my now PetImage to be treated as the successor to Media and all further activity directed to PetImage?
Thanks,

A:
ack doesn't find the string "Media" in any of my Python source files, .pyc files

I don't think it would fine them in the .pyc files. Have you tried deleting all pyc files in the directory? If this comes up a lot, you can either set  the PYTHONDONTWRITEBYTECODE environment variable or execute a recursive delete in a post-merge hook in your version control setup.


text:
Q: django defaulting to db.sqlite3 if your custom database isn't found Say I have this really rad database I'm using with Django, but for debugging purposes I want to use the default `db.sqlite3' database in setting.py if my rad database isn't found or users aren't able to easily set up the database.
How can I accomplish this task with Django?

A: The way I do this is as such:
In settings.py:
import dj_database_url # you'll need this in requirements.txt

DATABASES = {
    "default": dj_database_url.config(default='sqlite:///db.sqlite3'),
}

If the DATABASE_URL environment variable is set, as it will be in production (Heroku for me, but you can use a DATABASE_URL env variable anywhere) then use that. Otherwise, fall back to sqlite
Additionally, at the end of settings.py I have:
# Import optional local settings.  This must be at the END of this file.
try:
    from .local import *
except ImportError:
    pass

This way you can override the sqlite database in two ways: you can set the DATABASE_URL environment variable, or you can create a "local.py" file (exclude this from version control via .gitignore) that overrides it and other settings selectively.  Why two ways?  Primarily because most of the devs on my team are more comfortable managing a local settings file than environment variables.
I use this philosophy for all of my settings that might vary between dev and production, or that contain something I don't want in source control for any other reason.

A: You can set a database deppending of your debug var for example. In settings file:
if DEBUG:
//test database using sqlite
 DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'you_db_name.sqlite3'),
    }
 }
else:
   //here your prod database


text:
Q: How to display a video player in a loop I am using a JW video player and the way it is implemented for a single video is as below

Loading the player...

No what I want to do is that I want to do is loop through each existing video and to display a jw video player for each video. Only problem is that it is not quite working, it is only display the jsplayer for one video, the other videos do not show anything but blank. What am I doing wrong below:

<?php foreach ($arrVideoFile[$key] as $v) { ?>

Loading the player...

<?php } ?>

A: id tag should be unic so JWPlayer is confused when calling #myElement
Try incrementing a value and dynamically rename "myElement-" + i
I didn't get to test but that shoudl work:

<?php
$i = 0;
foreach ($arrVideoFile[$key] as $v) { ?>
<div id="myElement-<?php echo $i; ?>">Loading the player...

<?php } ?>


text:
Q: Using ptrace to read a block of memory from another proccess in c I've been working on this code for a few hours and am out of ideas. Might be the way I'm using the read() function or but the output of the program is always the same.

OUTPUT:
  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}

trailed by some garbage characters
Probably some silly mistake in my coding, haven't coded in c for almost 2 years before today...
Anyway if anyone can point out what I'm doing wrong it would be much appreciated.
int attach(int start, int pid)
{
    long ret;

    if ( start == 1 )
    {
        ret = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
    }else{
        ret = ptrace (PTRACE_DETACH, pid, NULL, NULL);
    }

    if ( ret < 0 )
    {
        printf("Could not attach to pid\n"); exit(-1);
    }

    waitpid(pid, NULL, WUNTRACED);

    return(ret);
}

int dump(int pid, unsigned long long addr, unsigned long long endaddr, char *outfile)
{
    int output;
    int mem_fd;
    char mem_file_name[2048];
    unsigned long long size = endaddr - addr;
void *buf=malloc(size);
memset(buf,0,size);

    // attach
    attach(1,pid);

    // open the memory
    sprintf(mem_file_name, "/proc/%d/mem", pid);
    mem_fd = open(mem_file_name,O_RDONLY);
    lseek(mem_fd,addr,SEEK_SET);
    read(mem_fd,buf,size);

    // Cleanup
    attach(0,pid);
    close(mem_fd);
    free(buf);
}

EDIT: also I'm passing the addresses from /proc/$pid/maps through a shell script... They seem to be calculating the right start and end addresses.
ptrace is attaching to the process and stopping it..
EDIT2: also check it is reading the correct number of bytes into the buffer, it is... And reports it is seeking to the correct address.... which does seem like a rather high number for a memory address....
EDIT3: That got me thinking that the hex addresses in /proc/$pid/maps are in reversed order or swapped at the 4 byte mark... system endianess...
EDIT4: Just realized the address are only 6 bytes long... still haven't gotten it working though
EDIT5: I have a python program from these forums which works, and I've repeated the steps in c, but my program fails.... checked the python program and it is reading the address exactly the same as my program.... Have my program run parallel calls to the python calls and still it fails to read the correct memory... Link to python example here

A: Thanks to  Severin Pappadeux for pointing out where i was going wrong, bellow is the final working code.
#define _LARGEFILE64_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <malloc.h>
#include <fcntl.h>

int dump(int pid, long long, long long, char *outfile);

int main(int argc, char *argv[])
{
    if ( argc < 5 )
        return(-1);

    int pid=strtol(argv[1],NULL,10);
    long long addr=strtoll(argv[2],NULL,16);
    long long endaddr=strtoll(argv[3],NULL,16);

#if DEBUG
    printf("Accessing pid memory %d from %llu to %llu\n",pid,addr,endaddr);
#endif

    dump(pid,addr,endaddr,argv[4]);

    return(0);
}

int attach(int start, int pid)
{
    long ret;

    if ( start == 1 )
    {
        ret = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
    }else{
        ret = ptrace (PTRACE_DETACH, pid, NULL, NULL);
    }

#if DEBUG
    if ( ret < 0 )
    {
        printf("Could not attach to pid\n"); exit(-1);
    }
#endif

    waitpid(pid, NULL, WUNTRACED);

    return(ret);
}

int dump(int pid, long long addr, long long endaddr, char *outfile)
{
    int output;
    int mem_fd;
    char mem_file_name[2048];
    long long size = endaddr - addr;
    void *buf=malloc(size);
    memset(buf,0,size);
    long long readErr,writeErr,seekErr;

    // attach
    attach(1,pid);

    // open the memory
    sprintf(mem_file_name, "/proc/%d/mem", pid);
    mem_fd = open64(mem_file_name,O_RDONLY);
    output = open64(outfile,O_WRONLY|O_CREAT);
    seekErr=lseek64(mem_fd,addr,SEEK_SET);
    readErr=read(mem_fd,buf,size);
    writeErr=write(output,buf,size);

#if DEBUG
    printf("Allocated %lu usable bytes\n",malloc_usable_size(buf));
    printf("File %s block size is %llu bytes\n",mem_file_name,size);
    printf("Memory file value %d\n",mem_fd);
    printf("Seeked %llu Bytes\n",seekErr);
    printf("Read %llu Bytes\n",readErr);
    printf("Wrote %llu Bytes\n",writeErr);
    printf("\n\n");
#endif

    // Cleanup
    attach(0,pid);
    close(mem_fd);
    close(output);
    free(buf);
}


text:
Q: Limit on text data size in clipboard? ** ADDENDUM: After some serious hours of research i found that i was barking up the wrong tree. The problem was not the clipboard itself but what happens if you feed it malformed unicode text which i apparently did. My editor had no problem handling it but when the clipboard got it it was truncated at the point where the error was in the text.
Reading 'damaged' file content will have the same effect when strings are handled in the application later and i therefore now use the Encoder/DecoderExceptionFallback() functionality to detect errors.
Quite an eye opener. **
I have a problem with the Clipboard in my winforms C# application. I'm trying to save a very long text to the clipboard (>1.4 million chars) and when using the DataFormats.UnicodeText i cannot get back the same amount of text. In a specific case i copy 1469785 characters but get back only 502228 chars. If i tag the data as DataFormats.WaveAudio and then force as string cast at the call to Clipboard.GetData() i actually get the correct number of characters back. There seems to be some special handling when using text only.
This doesn't work:
Clipboard.SetData( System.Windows.Forms.DataFormats.UnicodeText, _sb.ToString() );
StringBuilder _sb2 = new StringBuilder( Clipboard.GetData( DataFormats.UnicodeText ) );

While this does:
Clipboard.SetData( System.Windows.Forms.DataFormats.WaveAudio, _sb.ToString() );
StringBuilder _sb2 = new StringBuilder( ( string )Clipboard.GetData( DataFormats.WaveAudio ) );

Using DataFormat.Text didn't help either but added the mangling of the unicode characters (for obvious reasons :D).
All information i can find on the net says there is no limitation on clipboard size short of the available memory so how can this be explained? Is there really some special handling with the text data format? I'm sure i'm missing some cruical thing here but what?

A: There is no limit, at least when using the windows API.  However, unless you intend for some other app to be able to paste this, there's probably no point in using the clipboard in the first place.


text:
Q: A c# Generics question involving Controllers and Repositories I have a  base repository class which contains all the common repository methods (as generic):
public abstract class BaseRepository<T, IdType> : IBaseRepository<T, IdType>

My repositories from this base e.g.:
public class UserRepository : BaseRepository<User, int>, IUserRepository

I also have a base controller class containing common actions, and inherit from this in controllers.  The repository is injected into this by DI.  E.g.
public class UserController : BaseController<User>
{
        private readonly IUserRepository userRepository;

        public UserController (IUserRepository userRepository)
        {
            this.userRepository= userRepository;
        }

My question is this:  The base controller needs to be able to access the repository methods that are defined in the base repository.  However I'm passing in via DI a different repository type for each controller (even though they all inherrit from the base repository).  How can the base controller somehow access the repository that is passed in (regardless of what type it is), so that it can access the common base methods?

A: You can hold a reference for BaseReposiroty in BaseController
public class BaseController <T, IdType>
{
    ...
    ...
    protected BaseRepository<T, IdType> Reposirory
    {
        { get; set; }
    }
    ...
    ...
}

A: It all your repositories will be derived from IBaseRepository<T,IdType>, then have:
interface IUserRepository : IBaseRepository<User,int> {...}

Now any reference to a IUserRepository will know about the IBaseRepository<> members, without having to mention concrete types like the UserRepository class or BaseRepository<> class.

A: Here's one way to do it..
public abstract class BaseController<TEntity, TRepository, TIdType>
    where TEntity : class, new()
    where TRepository : IBaseRepository<TEntity, TIdType>
{
    protected TRepository Repository = RepositiryFactory.GetRepository<TEntity, TRepository>();

    public IList<TEntity> GetAll()
    {
        return Repository.GetAll().ToList();
    }
    public IList<TEntity> GetAll(string sortExpression)
    {
        return Repository.GetAll(sortExpression).ToList();
    }
    public int GetCount()
    {
        return Repository.GetAll().Count();
    }
    public IList<TEntity> GetAll(int startRowIndex, int maximumRows)
    {
        var results = Repository.GetAll().Skip(startRowIndex).Take(maximumRows);
        return results.ToList();
    }
    public IList<TEntity> GetAll(string sortExpression, int startRowIndex, int maximumRows)
    {
        var results = Repository.GetAll(sortExpression).Skip(startRowIndex).Take(maximumRows);
        return results.ToList();
    }
}


text:
Q: get value from shared pref to setmultichoiceitems in alertdialog I have alertdialog with multiple choice items. I am able to display alert and able to select the checkbox the store in the shared preferences. Now how can i retrieve from the shared preference and maintain the checkbox state. the value storing in shared pref in format of [1,3,4] these checkboxes are selected. Please help.
final CharSequence[] ratings = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
    final ArrayList selectedratings = new ArrayList();
    final boolean[] ratingschecked = {false, false, false, false, false, false, false, false, false, false};
    SharedPreferences sharedPreferences = getSharedPreferences("checkedrate", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPreferences.edit();

    final AlertDialog.Builder builder = new AlertDialog.Builder(this);

    int size = sharedPreferences.getInt("size", 0);
    for(int j=0;j<size;j++)
    {
        selectedratings.add(sharedPreferences.getString("selectedratings" + j, String.valueOf(selectedratings.get(j))));
    }

    for(int j=0;j<selectedratings.size();j++){
            int s = (int) selectedratings.get(j);
            ratingschecked[s-1]=true;
    }

    builder.setTitle("Select Ratings");
    builder.setMultiChoiceItems(ratings, ratingschecked, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            if (isChecked) {
                if(!selectedratings.contains((String)String.valueOf(which+1))){
                    selectedratings.add(String.valueOf(which+1));
                    ratingschecked[which+1]=true;
                }
            } else if (selectedratings.contains(which + 1)) {
                selectedratings.remove((String)String.valueOf(which));
                ratingschecked[which]=false;

            }
        }
    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            // editor.putString("checked", String.valueOf(selectedratings));
            for (int i = 0; i < selectedratings.size(); i++) {
                editor.putString("selectedratings" + i, String.valueOf(selectedratings.get(i)));
            }
            editor.putInt("size", selectedratings.size());
            editor.apply();
            Log.e("Shiva", String.valueOf(selectedratings));

        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    AlertDialog dialog = builder.create();
    builder.show();
}

A: public void saveToPreferences(String key, String value) {
    final SharedPreferences prefs = getSharedPreferences(PREF_FILE_CONFIG,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.apply();
}

Use above method to save to preference and below method to get it back
public String getFromPreferences(String key) {
    final SharedPreferences prefs = getSharedPreferences(PREF_FILE_CONFIG, Context.MODE_PRIVATE);
    String value = prefs.getString(key, "");
    if (!value.isEmpty()) {
        return value;
    }
    return "";
}


text:
Q: ContentEditable div - all HTML after the first 'x' characters I've been working on a condenteditable div, whereby I highlight text when it goes over a defined maximum length.
Codepen here:
http://codepen.io/doublesidedstickytape/pen/NqBMXR
It works out OK - unless a user press Return - then it breaks!
I'm thinking that I could could get all the HTML content after the first [x] amount of characters, then loop through each of the  elements (which act as new lines) - to wrap a highlight class around them in my hidden div.
I'm not sure how to achieve this though.
HTML

JS
$(document).on("keyup", "div.editable", function(event) {

  // GOOD TO STORE THIS IN A VAR
  // PREVENTS THE BROWSER HAVING TO
  // FIGURE OUT WHAT $(this) IS
  // EACH TIME YOU CALL IT
  var element = $(this);

  // KEYUP
  if (event.type == "keyup") {

    var maximumLength = element.attr("data-maxlength");
    var currentLength = element.text().length;
    var content = element.text();

    // CURRENT LENGTH IS GREATER THAN
    // THE SPECIFIED MAXIMUM LENGTH
    if (currentLength > maximumLength) {
      var over = element.html().substr(maximumLength);
      over = "" + over + "";
      content = element.html().substr(0, maximumLength) + over;
    }
    $("div.readonly").html(content);

  }

});

CSS
body {
  margin: 0 auto;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 1em;
  line-height: 1.4em;
  color: #444;
}

div.wrapper {
  position: relative;
  margin-top: 15px;
}

div.editable,
div.readonly {
  width: 300px;
  white-space: wrap;
  position: absolute;
  top: 0;
  left: 0;
}

div.editable {
  border-bottom: 1px solid #00aeed;
  outline: none;
}

div.readonly {
  z-index: -99;
  color: transparent;
  background: transparent;
}

span.highlight {
  background: #fcc !important;
}

$(document).on("keyup", "div.editable", function(event) {

  // GOOD TO STORE THIS IN A VAR
  // PREVENTS THE BROWSER HAVING TO
  // FIGURE OUT WHAT $(this) IS
  // EACH TIME YOU CALL IT
  var element = $(this);

  // KEYUP
  if (event.type == "keyup") {

    var maximumLength = element.attr("data-maxlength");
    var currentLength = element.text().length;
    var content = element.text();

    // CURRENT LENGTH IS GREATER THAN
    // THE SPECIFIED MAXIMUM LENGTH
    if (currentLength > maximumLength) {
      var over = element.html().substr(maximumLength);
      over = "" + over + "";
      content = element.html().substr(0, maximumLength) + over;
    }
    $("div.readonly").html(content);

  }

});
body {
  margin: 0 auto;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 1em;
  line-height: 1.4em;
  color: #444;
}
div.wrapper {
  position: relative;
  margin-top: 15px;
}
div.editable,
div.readonly {
  width: 300px;
  white-space: wrap;
  position: absolute;
  top: 0;
  left: 0;
}
div.editable {
  border-bottom: 1px solid #00aeed;
  outline: none;
}
div.readonly {
  z-index: -99;
  color: transparent;
  background: transparent;
}
span.highlight {
  background: #fcc !important;
}

A: I have worked out a solution, see: http://jsfiddle.net/alan0xd7/6o1sr5fg/

*

*If there are text that needs highlighting, first we just copy over the content HTML to div.readonly for further processing. If no highlighting is required, we just empty the div.

*The collectTextNodes() function iterates through all the DOM nodes in the content HTML, and collects all text nodes. The collected nodes would only contain text, and no child nodes.

*For all the text nodes we collected, we run them through the highlight() function to highlight the text.

*highlight() works by first skipping maximumLength number of characters, then wrap everything in .


text:
Q: How to add product attributes at admin dashboard bestsellers tab? I would like to know, how to add product attributes ie SKU, Color, Size at admin dashboard bestsellers tab?
app\code\core\Mage\Adminhtml\Block\Dashboard\Tab\Products\Ordered.php

Collection Code:
$collection = Mage::getResourceModel('sales/report_bestsellers_collection')
            ->setModel('catalog/product')
            ->addStoreFilter($storeId)
        ;

A: Just Add ->join('catalog/product', 'product_id = entity_id', '*') to Collection Code.
$collection = Mage::getResourceModel('sales/report_bestsellers_collection')
            ->setModel('catalog/product')
            ->join('catalog/product', 'product_id = entity_id', '*')
            ->addStoreFilter($storeId);

Then create SKU Column.
$this->addColumn('sku', array(
            'header'    => Mage::helper('sales')->__('SKU'),
            'index'     => 'sku',
            'type'      => 'string',
            'sortable'  => false
        ));


text:
Q: error code 1292 incorrect date value mysql I have a table
`CREATE  TABLE IF NOT EXISTS `PROGETTO`.`ALBERGO` (

`ID` INT(11) NOT NULL COMMENT 'identificativo dell\' albergo' ,
`nome` VARCHAR(45) NULL COMMENT 'Il nome dell\'albergo' ,
`viale` VARCHAR(45) NULL COMMENT 'Il viale in cui si trova  ' ,
`num_civico` VARCHAR(5) NULL COMMENT 'Il numero civico che gli appartiene' ,
`data_apertura` DATE NULL COMMENT 'Data di inizio apertura (inizio stagione)' ,
`data_chiusura` DATE NULL COMMENT 'Data di chiusura (fine stagione)' ,
`orario_apertura` TIME NULL COMMENT 'Orario di apertura' ,
`orario_chiusura` TIME NULL COMMENT 'Orario di chiusura' ,
`posti_liberi` INT(11) NULL COMMENT 'Disponiblità posti liberi ' ,
`costo_intero` FLOAT NULL COMMENT 'Costo del prezzo intero' ,
`costo_ridotto` FLOAT NULL COMMENT 'Costo del prezzo ridotto' ,
`stelle` INT(11) NULL COMMENT 'Classificazione in base al criterio delle stelle' ,
`telefono` VARCHAR(15) NULL COMMENT 'Recapito telefonico' ,
`mail` VARCHAR(100) NULL COMMENT 'Recapito e-mail' ,
`web` VARCHAR(100) NULL COMMENT 'Sito Web relativo all\'ente' ,
'Nome-paese` VARCHAR(45) NOT NULL COMMENT 'Identificativo del paese in cui si trova l\'albergo' ,
`Comune` CHAR(2) NOT NULL COMMENT 'Identificativo del comune in cui si trova l\'albergo' ,
PRIMARY KEY (`ID`) ,
INDEX `Nome-paese` (`Nome-paese` ASC) ,
INDEX `Comune` (`Comune` ASC) ,
CONSTRAINT `Nome-paese`
  FOREIGN KEY (`Nome-paese` )
  REFERENCES `PROGETTO`.`PAESE` (`Nome-paese` )
  ON DELETE NO ACTION
  ON UPDATE CASCADE,
CONSTRAINT `Comune`
  FOREIGN KEY (`Comune` )
  REFERENCES `PROGETTO`.`PAESE` (`Comune` )
  ON DELETE NO ACTION
  ON UPDATE CASCADE)
ENGINE = InnoDB

When i try to run this query:
INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`)
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '01-05-2012', '31-09-2012', '06:30', '24:00', 80, 50, 25, 3, '43968083', 'info@hcentrale.it', 'http://www.hcentrale.it/', 'Trento', 'TN')

*Error Code: 1292. Incorrect date value: '01-05-2012' for column 'data_apertura' at row 1*
What have i to  change? (i tried to change format's date from gg/mm/yyyy to gg-mm-yyyy, but nothing changed)

A: With mysql 5.7, date value like 0000-00-00 00:00:00 is not allowed.
If you want to allow it, you have to update your my.cnf like:
sudo nano /etc/mysql/my.cnf

find
[mysqld]

Add after:
sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Restart mysql service:
sudo service mysql restart

Done!

A: Insert date in the following format yyyy-MM-dd example,
INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`)
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', 'info@hcentrale.it', 'http://www.hcentrale.it/', 'Trento', 'TN')

A: I was having the same issue in Workbench plus insert query from C# application.
In my case using ISO format solve the issue
string value = date.ToString("yyyy-MM-dd HH:mm:ss");

A: I happened to be working in localhost , in windows 10, using WAMP, as it turns out, Wamp has a really accessible configuration interface to change the MySQL configuration. You just need to go to the Wamp panel, then to MySQL, then to settings and change the mode to sql-mode: none.(essentially disabling the strict mode) The following picture illustrates this.

A: An update. Dates of the form '2019-08-00' will trigger the same error. Adding the lines:
[mysqld]

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

to mysql.cnf fixes this too. Inserting malformed dates now generates warnings for values out of range but does insert the data.

A: Just an update of @Sinan Eldem's answer:
Since MySQL 8.0 the sql_mode='NO_AUTO_CREATE_USER' is deprecated (source) and should be removed from the line, otherwise it will result in error reading sql_mode and failure starting mysqld.
If using MySQL 8.0+ add the following line instead:
[mysqld]

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"


text:
Q: How to hide/remove particular data from the Network tab in developer tools
I am working on React project and want to display the scores of an assessment, but the score should be anonymous (that is we should not be able to see the score of individual member. We should just see the overall scores of all members without the score being traced to their name).
I want to hide the score response from the network tab so that it is not accessible on the frontend. Is there a way I can do it?

A: there is no way to hide the Network API calls from a browser.

A: You should manage it from backend API response by managing what is the final data result you need and only send it.


text:
Q: API POST request - Python example to Google Script - 'Unexpected end of JSON input' I'm trying to connect a Google spreadsheet to snov.io service using an API POST request, they have provided a Python code as example and I have tried to run the google script below based on it, but without success. Any ideas? Thank you :)
Python (provided by the company)
def get_access_token():
params = {
    'grant_type':'client_credentials',
    'client_id':'c57a0459f6t141659ea75cccb393c111',
    'client_secret': '77cbf92b71553e85ce3bfd505214f40b'
}

res = requests.post('https://api.snov.io/v1/oauth/access_token', data=params)
resText = res.text.encode('ascii','ignore')

return json.loads(resText)['access_token']

Google Script (Error:SyntaxError:'Unexpected end of JSON input')
var params = {
    'grant_type':'client_credentials',
    'client_id':'c57a0459f6t141659ea75cccb393c111',
    'client_secret': '77cbf92b71553e85ce3bfd505214f40b',
    'method':'post'
}
var url = 'https://api.snov.io/v1/oauth/access_token';

var response = UrlFetchApp.fetch(url,params)
var json = response.getContentText();
    obj = JSON.parse(json);
    token = obj.result.access_token;
    return token

A: In order to achieve the same request with your python script, how about modifying your Google Apps Script as follows?
Modified script:
From:
var params = {
    'grant_type':'client_credentials',
    'client_id':'c57a0459f6t141659ea75cccb393c111',
    'client_secret': '77cbf92b71553e85ce3bfd505214f40b',
    'method':'post'
}
var url = 'https://api.snov.io/v1/oauth/access_token';

var response = UrlFetchApp.fetch(url,params)

To:
var params = {
  'grant_type': 'client_credentials',
  'client_id': 'c57a0459f6t141659ea75cccb393c111',
  'client_secret': '77cbf92b71553e85ce3bfd505214f40b',
}
var url = 'https://api.snov.io/v1/oauth/access_token';
var response = UrlFetchApp.fetch(url, {method: "post", payload: params});

*

*In this case, even when method: "post" is removed, the same request is achieved.

Reference:

*

*fetch(url, params)


text:
Q: mybatis return id for inserted fields without object I know this question is asked several times but most of the answers are for the scenario when we are passing an object as parameter.
I am trying to insert a row into sql server using mybatis and I want the id of the inserted row.
I am not passing an object but raw variables like Integer, Long, Double
<insert id="insertUserSummary"  useGeneratedKeys="true" >
       INSERT INTO BRS_USER_SUMMARY
 (BRS_BRM_ID, BRS_USR_ID)
 VALUES
 (#{masterid}, #{userid} )
</insert>

I am just passing masterid and userid in the calling function and it does an insert but I do not get id in return. Note- I am not passing an object as parameter but two variables.
Thank you.

A: One way to get the generated id from an insert query is to pass a map which will be used to hold the id of the generated row:
<insert id="insertUserSummary" useGeneratedKeys="true" keyColumn="id" keyProperty="idMap.id">
    INSERT INTO BRS_USER_SUMMARY (BRS_BRM_ID, BRS_USR_ID)
    VALUES (#{masterid}, #{userid})
</insert>

Mapper:
int insertUserSummary(@Param("masterid") int masterId, @Param("userid") int userId, @Param("idMap") Map<String, Integer> idMap);

Usage:
Map<String, Long> idMap = new HashMap<>();
int affectedRows = mapper.insertUserSummary(42, 31415, idMap);
int insertedRowId = idMap.get("id");


text:
Q: How do I make a jumping animation in Unity2D? So I'm making this Unity2D game and I'm trying to implement a jumping animation, it has 5 states(launching, rising, apex, falling, landing).
How should I set up the transitions between these states?
Thanks.

A: Go onto Youtube and search "How to make an animation in Unity2D". This place is for help and advice, not for us to do your work for you :) Good luck! If something goes wrong and you've tried to fix it, then come here and we can try and help you!

A: You can use a Blend tree. There's also plenty of tutorials on youtube/unity to show exactly how to use.


text:
Q: Custom error code with Spring ConstrainValidation I have actually a solution to validate fields with costum boilerplate of code.
I would like to create annotations to simplify that, but I can't find how to manage custom Error code for my validation.
Does anyone know a solution ?


text:
Q: 3rd party React component not updating I have a component that calls a 3rd party component called ReactCollapsingTable which looks like this:
export class MyComponent extends Component <DataTableProps, {rows: any, columns: any} > {

    constructor(props: DataTableProps) {
        super(props);
        this.state = {rows: this.getRows(), columns: this.getColumns() };
    }

    getRows() {
        ...
        return rows;
    }

    getColumns() {
        ...
        return columns;
    }

    componentDidUpdate(prevProps: Readonly<DataTableProps>): void {
        if (!_.isEqual(this.props, prevProps)) {
            this.setState({rows: this.getRows(), columns: this.getColumns() });
        }
    }

    render() {
        return <ReactCollapsingTable
            rows={this.state.rows}
            columns={this.state.columns}
        />;
    }
}

When my component updates it changes the values of this.state.rows and this.state.columns with this.setState. In my render function I am logging the values of this.state.rows and this.state.columns to the console and they are changed as expected. However the ReactCollapsingTable does not change. Am I doing something wrong or is it that component? If that's the 3rd party's component fault, is there a work around? Maybe unmount it and put back again, or something along these lines. Thank you.

A: Apparently, this is caused by the 3rd party component. Trying a different version of that library, fixed my problem. Also, using a different library I am not getting this issue either.


text:
Q: Are $\text{SO}(3)$ and $S^2 \times S^1$ homotopy equivalent? There is a natural projection $\text{SO}(3) \to S^2$ which is the projection to the coset space of a subgroup $\text{Stab}(p)$ for any $p \in S^2$ under the standard action of the group. The preimage of any point in $S^2$ is a circle.
Is $\text{SO}(3)$ homotopy equivalent to $S^2 \times S^1$?

A: The answer is NO!!
A different topological presentation of $SO(3)$ as $\mathbb RP^3$ would be helpful to complete this proof. So how to prove that this two spaces are homeomorphic? Observe that any matrix $A\in SO(3)$ is a orientation preservoing rotational matrix acts on $\mathbb R^3$. Since it is a $3\times 3$ matrix, so it has a real eigenvalue, and corresponding to this eigenvalue, the matrix fixes the eigen-vector in particular the line generated by the eigenvector. So we can think of any element of $SO(3)$ as a rotation of closed unit 3-disc with a fix axis. Now define a map $\phi :D^3\to SO(3)$ sends a non-zero vector $x$ to the rotation through angle of $|x|\pi$ about the axis joining origin and $x$.  Ans observe that antipodal points on the boundary are represent the same element, and in the interioi it is a $1-1$-map. So now if we consider the quotient map which quotient out the antipodal points of the boundary of the unit-disc, we get a homeomorphism $\bar{\phi}: \mathbb RP^3\to SO(3)$.
Now from here you can easily see that $SO(3)$ and $S^2\times S^1$ are not homotopically equivalent, since their fundamental groups are different.


text:
Q: httplistener and http connect method I am using the HTTP Proxy setting on my ipad to redirect traffic to my .net httplistener.
If i send http traffic using the ipad proxy sends the traffic to my httplistener, and
my code does its thing. If i send https traffic using the ipad and its http proxy I see the packets show up at my machine (sniff using wireshark) on port 8443, but my listener doesn't get kicked off. I have the prefixes and certificates correct. I proved this out by instructing a browser to go directly to my machine w/o the http proxy using port 8443.
I noticed from my sniffs of the https connection attempt that the HTTP CONNECT method
is contained in the packet. Its probably trying to tunnel the SSL traffic. Does http.sys or httpListener recognize/handle the CONNECT method ? I am curious why my httplistener isn't firing off ??
thoughts on how I can further troubleshoot this ?

A: It's not stated in your question, so have you actually setup your HttpListener to support SSL with a site certificate as documented in this question?
How do I add SSL to a .net application that uses httplistener - it will *not* be running on IIS


text:
Q: Best API/code library to build a timeline/chart I'm reaching out for some advice on the best API/code library to use to build an interactive timeline/chart. I have included an example image below. The idea would be that you have a key, and clickable elements along a path/line that pop up/out when interacted with.
I have a lot of experience with Google Maps API, but this is quite clearly something a little different. Would you suggest ChartJS? Or something else? Just trying to get some background/research.
Do let me know if posting this on SO was the wrong thing to do.

A: Take a look at D3J or Dojo. They are both JavaScript libraries for data-driven and data-centric front-end applications.


text:
Q: How can I fetch the latest log file to scrape every time I run my python script? There is a list of json logs in my Downloads folder.
Every time I run this script I want the latest one to be fetched.
import json

json_file = '/home/Downloads/log12-41-12.json'
json_data = open(json_file)
logs = json.load(json_data)

for index in logs:
    print(index)

file.close()
json_data.close()

A: Code Snippet
 import os
 logdir='/home/Downloads/' # path to your log directory
 logfiles = sorted([ f for f in os.listdir(logdir) if.startswith('log')])
 print "Most recent file = %s" % (logfiles[-1],)


text:
Q: zfs rename/move root filesystem into child Similar question exists but the solution (using mv) is awful because in this case it works as "copy, then remove" rather than pure "move".
So, I created a pool:
zpool create tank /dev/loop0

and rsynced my data from another storage in there directly so that my data is now in /tank.
zfs list
NAME      USED  AVAIL  REFER  MOUNTPOINT
tank      591G  2.10T   591G  /tank

Now I've realized that I need my data to be in a child filesystem, not in /tank filesystem directly.
So how do I move or rename the existing root filesystem so that it becomes a child within the pool?
Simple rename won't work:
zfs rename tank tank/mydata
cannot rename to 'tank/mydata': datasets must be within same pool

(Btw, why does it complain the datasets are not within same pool when if fact I only have one pool?)
I know there are solutions that involve copying all the data (mv, or sending the whole dataset to another device and back), but shouldn't there be a simple elegant way?
Just noting that I do not care of snapshots at this stage (there are none yet to care of).

A: Given the problem documented by @USDMatt, ZFS send/receive is probably the best way to go.
zfs snapshot tank@snap
zfs send tank@snap | zfs receive tank/anotherfs
zfs set mountpoint=/beep/boop tank/anotherfs
rm -rf /tank/*
zfs destroy tank@snap

Watch out when running the rm -rf if you don't change the mount point of if you have other filesystems in your tank zpool. You don't want to recursively remove the contents of the new filesystem (/tank/newname) or any other child filesystems (/tank/*) accidentally.

A: (see notes in comments, this works, but you'll never be able to delete initial the snapshot, so it's not a good solution)
With ZFS this is surprisingly straightforward: just snapshot, clone and then rm. No extra space or copy time required.
zfs snapshot tank@mydata
zfs clone tank@mydata tank/newname
zfs set mountpoint=/beep/boop tank/newname
rm -rf /tank/*

Watch out when running the rm -rf if you don't change the mount point of if you have other filesystems in your zpool.  You don't want to recursively remove the contents of the new filesystem (/tank/newname) or any other child filesystems (tank/*) accidentally.  Once you've confirmed your files are not in the root fs (/tank/) and only in your new filesystem, you can also delete that initial snapshot.
zfs delete tank@mydata

A: I don't think there's a simple elegant way... although you could just change your mountpoint...
mkdir /tank
zfs set mountpoint=/tank/mydata <possibly renamed tank set>

Or maybe rename tank and then mount it where you need it...
Either that, or create a filesystem in the right place and cp, mv, or zfs send/receive...

A: was copying whole disk to a new dataset, then found out it was a root folder:/
zfs clone tank tank/mynewdataset && rm -rf /mnt/tank/ && zfs promote tank/mynewdataset

this made my root data appear in the 'child' dataset, and fixed 2 issues with other solutions: sizes are correct, copy didn't execute.


text:
Q: How to prevent space trimming when importing HTML with ImportString? I am importing a HTML-formatted string with
ImportString[string, "HTML"]

to properly parse all HTML-escaped characters like > and  .
However, Mathematica seems to trim all repeated spaces in the process:
ImportString["a   b", "HTML"]
ImportString["a   b", "HTML"]
ImportString["a    b", "HTML"]

a b
a b
a b

Can I disable this unwanted trimming of spaces while parsing a HTML-formatted string?


text:
Q: How to extract only a paritcular datetime from the webresponse and match it with the given date time? I am using following regular expression to extract date from a html page:
(((0?[1-9]|[1-2][1-9]|[123]0|31)(/|.|'|:|,|\s|-)(0?[13578]|1[02])(/|.|'|:|,|\s|-)\d{4})|((0?[2-9]|[0?1]1|[1-2][1-9]|[123]0)(/|.|'|:|,|\s|-)(0?[13456789]|1[0-2])(/|.|'|:|,|\s|-)(\d{4}))|((0?[1-8]|[1-2][0-8]|[0?1]9)(/|.|'|:|,|\s|-)(0?2)(/|.|'|:|,|\s|-)(\d{4}))|(29(/|.|'|:|,|\s|-)0?2(/|.|'|:|,|\s|-)((19(0[048]|[2468][048]|[13579][26]))|([2-9]\d{1}([2468][048]|[13579][26]|00)))))(.*|\w*|\s*)([01]?\d)|(2[0-3])(:|\.|-|'|\/|\s)[0-5]?\d{2}"); //dd-mm-yyyy hhh:mm:ss

above regular expression extracts date that is in dd mm yyyy h mm ss format with different separators.
what i get as output from match.value is something like below:
11/09/2013 at 09:48	 that is it matches everything from the response that follows the match.

but i only want that the result of match.value should be only like this:
11/09/2013 09:48

so what my expression basically does is that it matches everything that follows the date which is not my requirement i need that it should only match date and time mentioned in the text box.
kindly help me how can i change my regex to meet my requirement.

A: Try adding these to your logic (<[^<]+?>)+ to remove the HTML tags and (&[^;]+?;)+ for &nbsp.
EDIT:
text = Regex.Replace(text, "<[^<]+?>" ,"");
text = Regex.Replace(text, "(&[^;]+?;)+", "");
text = text.Trim();
text = text.Remove(17);


text:
Q: Conditional expectation formula for $Y\leq y$ According to wikipedia the conditional expected formula for $X$ and $Y$ continuous random variables with join density $f_{X,Y}(x,y)$, $Y$'s density $f_Y(y)$, and conditional density $f_{X|Y}(x|y)=\dfrac{f_{X,Y}(x,y)}{f_Y(y)}$ of $X$ given $Y=y$ is
$E(X|Y=y)=\int_{-\infty}^\infty xf_{X|Y}(x|y)dx$
My question is, how does this formula change when $Y\leq y$ instead of $Y=y$?

A: You want something like $f_{X|Y\leq}(x|y)=\frac{\int_{-\infty}^y f_{X,Y}(x,a)~da}{\int_{-\infty}^y f_{Y}(a)~da}$, and then $\mathbb E[X|Y\leq y]=\int_{-\infty}^\infty xf_{X|Y\leq}(x|y)~dx$.

A: Provided $P(Y\le y)>0$, one has $$E[X\mid Y\le y]=\frac{E[XI(Y\le y)]}{P(Y\le y)}\,,$$ where $I(Y\le y)=1$ if $Y\le y$ and $I(Y\le y)=0$ if $Y>y$.
In your case when marginal, conditional and joint pdfs exist, this can be written as
\begin{align}
E\left[X\mid Y\le y\right]&=\frac1{P(Y\le y)}\iint_{\mathbb R^2} x I(v\le y)f_{X,Y}(x,v)\,\mathrm{d}x\,\mathrm{d}v
\\&=\frac1{P(Y\le y)}\int_{-\infty}^y\int_{-\infty}^{\infty} xf_{X,Y}(x,v)\,\mathrm{d}x\,\mathrm{d}v
\\&=\frac{1}{P(Y\le y)}\int_{-\infty}^y \left\{\int_{-\infty}^{\infty} xf_{X\mid Y}(x\mid v)\,\mathrm{d}x \right\}f_Y(v)\,\mathrm{d}v
\end{align}
In other words,
$$E\left[X\mid Y\le y\right]=\frac{\int\limits_{-\infty}^y E\left[X\mid Y=v\right]f_Y(v)\,\mathrm{d}v}{\int\limits_{-\infty}^y  f_Y(v)\,\mathrm{d}v}$$


text:
Q: Why is VBA creating a folder on ActiveWorkbook.SaveAs I have this VBA:
ActiveWorkbook.SaveAs Filename:=Path & Filename & ".xls"
ActiveWorkbook.Close

This is supposed to save the currently active workbook or worksheet to a path and file name provided. The extension ".xls" is used so that the exported file is a Excel 97-2003 Workbook.
It saves the Workbook or Worksheet but has a folder included in them. Let's say the file name was "Master.xls", ActiveWorkbook.SaveAs works but the VBA seem to include a folder named "Master_files" next to it as if it were saved as a web file. How can I disable this?
Note that the sheet came from an online database, when I click the link to export the records into an Excel sheet it doesn't download it but instead opens it straight from web to my Excel application which is why I created this SaveAs code.

A: I believe you need to expressly specify the format:
ActiveWorkbook.SaveAs Filename:=Path & Filename & ".xls", FileFormat:=xlExcel8

Otherwise, it is saving as HTML, along with the _files, because you got it from the Web (I think).  MSDN says:

For an existing file, the default format is the last file format specified

which I am guessing is HTML for your situation.
xlExcel8 is the constant to use for .xls files per Ron de Bruin's reference.


text:
Q: XMLSignature defaults to RSA, how to also verify DSA curves for SSL signatures? I am writing java code to take a canonicalised XML file which is signed by an SSL key of an approved party.
I am able to get the content and signature out of the file and even verify the signature if the signer uses an RSA key.
However, if an SSL signature was created with a DSA key, the XMLSignature object will fail with the following error:

javax.xml.crypto.dsig.XMLSignatureException: java.security.InvalidKeyException: No installed provider supports this key: sun.security.rsa.RSAPublicKeyImpl

My code is as follows:
    SignatureCheck result = new SignatureCheck();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document xml = dBuilder.parse(fileStream);
    xml.getDocumentElement().normalize();

    // Find Signature element
    NodeList nl = xml.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) return result;

    // Create a DOM XMLSignatureFactory that will be used to unmarshal the
    // document containing the XMLSignature
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    // Create a DOMValidateContext and specify a KeyValue KeySelector
    // and document context
    DOMValidateContext valContext = new DOMValidateContext(new CertKeySelector(), nl.item(0));

    // unmarshal the XMLSignature
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);

    // Validate the XMLSignature (generated above)
    result.isValid = signature.validate(valContext);

A: It turns out that actually XML signature does accept this curve, I was just comparing the wrong certificate (an ecdsa one against an RSA one).


text:
Q: Cannot log in (nothing happens after entering password) after pressing a key combination at restart The plasma desktop can no longer be started. What could be the reason?
Immediately after a restart command (via GUI) I pressed a key combination: CTRL + ALT + another key, I think F1, 1, 2 or F2. I'm not sure about the third button.
The next time I booted up, the Kubuntu 16 login screen appeared as usual. After the correct password has been entered, nothing happens at all.

A: When you pressed a key combination CTRL+ALT+(F1, 1, 2, F2). It's only show nothing.
You just needs type,

*

*CTRL+F12 for Show Desktop KDE.

*ALT+D or ALT+S for show Desktop Settings.

*ALT+F3 for Open the Window Operations Menu.

*CTRL+ESC for show System Activity.

*ALT+SPACE or ALT+F2 for show Run Command Interface.

See more for another Description a key combination of KDE Desktop please see this.
Hope this helps.


text:
Q: Searching a folder directory for a file and retrieving file path's in a web application Note: I have never used PHP in my life.
I have come to the point in my mobile web application that I need to find out of a file exists in a structure like:
-Folder
    -SubFolder
        -file.html
    -SubFolder
        -file.html
    ...
-Folder
    -Subfolder
        -file.html
...

I care to see if this html file exists for a certain subfolder so that if it does I can display its html contents.
I have written the rest of my mobile web application using solely html and javascript but from what I've read it seems this is not doable with javascript alone. ( :( )
So I have a few questions as I sit here looking up everything I need to implement this in PHP (since this is the most common thing I am seeing when looking up how to do this).

*

*Currently all I have been using in this application (simple application) is
index.html
style.css
code.js
any image files I use or text files I read from using javascript

Would the PHP code go in the HTML file? Currently the way I have it set up is my index.html file calls a initialization() function that is called when the page loads, and the rest of the application is run from the code.js file that just updates the  elements of the html file. How can I add this PHP to the HTML file to be run when I need it to? Can PHP go into a javascript file? Pretty much after a bunch of logic in the JS file I get to a point where I decide if I need to or not need to search the file structure for a file.
So now on the actual code on how to do it in PHP, from what I've found..
 <?php
 $filename = '/path/to/foo.txt';

 if (file_exists($filename)) {
     echo "The file $filename exists";
 } else {
     echo "The file $filename does not exist";
 }
 ?>

I pulled that from php.net. One thing about my folder structure is I will know the paths of the files ahead of time. So I feel like it may be easy to follow that format and see if file_exists($filename). My question is instead of echoing a string like in the example can I echo the actual path to the html file? Where does "echo" return the value?
Again this is all new to me, and if this is doable in any easier way (jquery?) I would love to know. My main concern is where to put this php code or how to call it when I want to and have it return something that I can use in my javascript code.
Thanks


text:
Q: How can I achieve traceability in a git server-repository? I need to set up a centralized git repository for a large team of in-house developers.
I need some convincing mechanism that allows me to trace a given commit back to a user. As I understand from this question, this will probably not be the actual git-authors. I do not expect to be using this information for anything (other than satisfying in-house requirements for traceability). Relating a commit to the client's IP adress is considered reliable enough, so it's not really strict. Grepping log-files would be acceptable, but I am expecting fairly concurrent commits.
Any suggestions how I can achieve this ? I am deliberately trying to be open-ended as to solution type (ssh, git-server, apache) here
(And yes, if "joe" pushes changes he fetched from "osama", then joe will read this code before commiting)

A: You could achieve this through a post-receive hook. This example hook just echos back possible details that could be logged to the pushing user, but the details could be logged via syslog or a dedicated loggin mechanism of some kind.
# sample logging post-receive hook

echo This hook logs back to the pusher, but could append to syslog or something.
echo push from user $LOGNAME at $(date), ssh client details: $SSH_CLIENT

echo refs updated:
echo -------------
cat
echo -------------

For the SSH_CLIENT details to be accurate, you probably want to ensure that users don't have direct shell access as otherwise they could get a shell via ssh, then spoof their LOGNAME and SSH_CLIENT info, although such fudging would be malicious and giving malicious users push access to a git repository is inherently dangerous. There are more reliable ways to determine the users identity but if the user has control over there login scripts then, as the hook is run as the logged in user, there is always the possibility that they can manipulate it in a way to subvert how the hook works.
This way you get the from and to commit SHA1 for each branch changed. In order to ensure that you can always easily examine the history you probably also want to make sure that the config variables receive.denyDeletes and received.denyNonFastForwards are set to true. Again, to deny fiddling with these configs, you want to avoid users having shell access to the repository.
If you don't mind about non-fast forwards or branch deletes, you can still access old commits that haven't been pruned through the reflogs, so long as these are enabled via the core.logAllRefUpdates.

A: Set an update hook. You will have the old and new commit IDs and the ref name. Relating this to the IP of the committer will probably require tracing back your parent PIDs until you reach sshd, or you could just record the current user's username.


text:
Q: java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to Specific class I want to have common method for inserting and getting objects from MongoDB collection. For all mongo db operations I am using Jongo library. Here's my code:
 public UserModel getUserByEmailId(String emailId) {
    String query = "{emailId:'"+emailId+"'}";
    Object obj = storage.get(query);

    UserModel user = (UserModel) obj;
    //getting exception on above line. I am sure that I have UserModel
    //type of data in obj
    // Exception is: java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to UserModel
    return user;
}

Here is "storage.get(String query)" method. My intention is to have common method to read data from mongo db. That's why I want it to return Object. (Feel free comment if I'm wrong)
public Object get(String query) {
    Object obj = collection.findOne(query).as(Object.class);
    return obj;
}

//Here: collection is my "org.Jongo.MongoCollection" type object.

What is the right way to get UserModel type of object from "Object"? Let me know if you need more information

A: The Jongo library is returning a map, specifically a LinkedHashMap. You are trying to cast that to an instance of your UserModel class, which Java does not know how to do.
You seem to be expecting the Jongo library to return a UserModel. Assuming that's your custom designed class, there is no way that the library would know how to map the data from MongoDB to this object. Unless of course you could somehow specifically instruct it to do so (I'm not familiar with Jongo).
You could however use Jackson to map the map to UserModel (or other objects).

A: If you only need to map documents to UserModel objects
collection.findOne("{name:'John'}").as(UserModel.class);

If you are looking for a generic approach :
public <T> T get(String query, Class<T> clazz) {
  return collection.findOne(query).as(clazz);
}
...
UserModel user = this.get("{name:'John'}", UserModel.class);


text:
Q: SQL update in ranking order Using Oracle 11g, and the data below:
create  table ds_tmp
(col1 varchar2(5) ,date1 DATE, col3 varchar2(3));

insert into ds_tmp
values('pat1','01-JAN-2018','PND');

insert into ds_tmp
values('pat1','02-JAN-2018','MIS');

insert into ds_tmp
values('pat1','03-JAN-2018','DUP');

insert into ds_tmp
values('pat2','01-JAN-2017','MIS');

insert into ds_tmp
values('pat2','02-JAN-2017','DUP');

insert into ds_tmp
values('pat2','03-JAN-2017','DUP');

insert into ds_tmp
values('pat2','04-JAN-2017','INV');

What I need to do is:
1) group by col1
2) update col3 in the following order:
if any col3=PND then set all col3 to PND
else if any col3=MIS set all col3 to MIS
else if any col3=DUP set all col3 to DUP
else set all col3 to INV

So, using the data above we would end up with all col3 values for pat1=PND and all col3 values for pat2=MIS.
I could use CASE to mimic if then else but it only selects on 1 column. I think I may need an an analytic rank function but I can't think how to code it, any suggestions appreciated.

A: You can get the adjusted value with:
select col1, date1, col3,
  case
    when count(case when col3 = 'PND' then col3 end)
           over (partition by col1) > 0 then 'PND'
    when count(case when col3 = 'MIS' then col3 end)
           over (partition by col1) > 0 then 'MIS'
    when count(case when col3 = 'DUP' then col3 end)
           over (partition by col1) > 0 then 'DUP'
  end as adj_col3
from ds_tmp;

COL1  DATE1       COL ADJ
----- ----------- --- ---
pat1  03-JAN-2018 DUP PND
pat1  02-JAN-2018 MIS PND
pat1  01-JAN-2018 PND PND
pat2  03-JAN-2017 DUP MIS
pat2  02-JAN-2017 DUP MIS
pat2  04-JAN-2017 INV MIS
pat2  01-JAN-2017 MIS MIS

Then either replace col3 with that expression in your query, or use it for an update if you actually want to change the values in the table.
The over (partition by col1) does the 'grouping' part, and the three values are evaluated in the order you wanted, so PND takes priority over MIS etc.


text:
Q: Using forwardRef in other component got type error I got this error:

Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLDivElement>'

import React from "react";

const Other = React.forwardRef((props, ref) => {
  return (

Other

  );
});

export default Other;

Is this the right usage?
Demo: https://codesandbox.io/s/summer-shadow-5ul13e?file=/src/Other.tsx:0-172

A: Simply make sure to provide type arguments to forwardRef, as shown for example here:
import React from "react";

const Other = React.forwardRef<HTMLDivElement, unknown>((props, ref) => {
  return (

{/* Okay */}

Other

  );
});

Playground Link

A: Initialise useRef with null initially and type <HTMLDivElement>. Also, apply type <HTMLDivElement> to forwardRef as well. Check on mount if ref is assigned correctly.
Here is the Sandbox Link


text:
Q: Whats the most effective way to use Jastor to create object and managedobject to store in iOS? given objective c doesn't do multiple inheritance, what would be the best way to implement class(es) using Jastor to convert and json data source into object and also use managedobject (core data) as storage?
The whole reason for choosing Jastor was that I want to avoid laboriously code each property/field and then to have to copy the whole lot property by property into a managedobject seems dire.
But whats the most elegant way of achieving this?
Thanks

A: Any NSObject subclass including NSManagedObject does just what you want out of box by means of NSKeyValueCoding protocol. See example here.


text:
Q: Android Databinding : package does not exist I'm trying to use data-binding with Android.
I can not anymore build my project. I got this error :

"Error:(13, 46) error: package ch.company.project.databinding does not
  exist"

Here my gradle :
http://pastebin.com/dkXd1Mxr
and
http://pastebin.com/n9hkFWGQ
And here the gradle output :
https://pastebin.com/w93Rausg

A: I am not satisfied with accepted answer, that tell you to stack trace without hints.
Here are some possible causes that lead to this problem. Check if you are not doing any of the following.
Basically Android DataBinding is not that mature still. It will fail without appropriate errors many times.
So if you have an issue like package ch.company.project.databinding does not exist".
Possible causes of fail:

*

*First of all check your recently edited layouts xml one by one for errors (for wrong imports & variables). I don't get proper error in this case usually.

*Check your data binding syntax in binding block ({...}) in layout element for errors. Always Rebuild (not Build) project after working in one layout.

*Check your @BindingAdapter method having correct parameters. For example imageUrl binding adapter would accept ImageView or View as first parameter.

*You should always Rebuild project after doing work in one layout.

*If you are not able to find errors by above steps, then try --debug and --stacktrace in compile option of
File> Settings> Build, Execution, Deployment> Compiler> Command-line Options

A: Make sure your package name start with lowercase letter.
in my case issue solved after two hours of struggle

A: Thanks to Yigit!
The issue was not directly link to Android Databinding.
There were a bug in the project (some variables not correctly setted)
I would recommend to use gradle with "--debug and --stacktrace" for more informations, it's helping a lot.

A: earlier my package name was "com.xyz.abc.Models"
changing the package name to all small letters "Models" -> "models"
solved the issue.

A:
Package name should start with small letter.
for example Activities is wrong it'll give an error instead refactor->rename to activities

A: I got the error:

Error:(9, 46) error: package com.company.www.bar.databinding does not
  exist.

i just remove "=" sign . it worked for me
From this :
 <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@={()->activity.onButtonClick()}"/>

to :
<Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{()->activity.onButtonClick()}"/>

A: I had similar problems with my project
You could try:

*

*check xml files for errors that cause a build failure

*clean project

*File -- invalidate caches / restart

A: On my particular case, I was using Dagger 2. This package error appears in a lot of classes without any relation with the original error: a dependency injection error.
Happy reminder: Scroll more on your stacktrace to know what is the real problem.

A: I was stuck with same error for hours. After trying several solution from stackoverflow, I updated my project with stable gradle dependencies.
Still it was not solved, however with the same gradle dependency DataBinding was working fine in another project of mine.
So, I went project folder using explorer and Deleted 2 things.

*

*build folder

*all files from .idea/libraries

After that i synced the project and it continued to work just fine.

A: Package names have to START with Small Letters. Otherwise, Binding library cannot understand that is it class or package. Moreover, you do NOT need to do all of it with small letters.
Example, wrong usage:
package com.thecompany.activity.ContactInfo; //Problem is ContactInfo, 'C'.

Example, TRUE usage:
package com.thecompany.activity.contactInfo; //Solution is contactInfo, 'c'.

A: The bug is not the DataBinding Package, it's a syntactic or logical error. For example, you have the attribute "lastName" in your POJO, but in the layout it's android:text="@{user.lastname}".
Check your "layout" and do Rebuild Project.

A: Make sure your model's fields you reference in layout have public access modifiers

A: Change
{ databinding = true}

to
buildFeatures{
     dataBinding = true

}

A: If you're coming to this question because you switched to JDK11 in Android Studio Artic Fox and your view binding broke in the UI but not during execution then be aware that this is a known issue and should be resolved in Bumble Bee:
https://issuetracker.google.com/issues/180946610
The current fix is to switch back to JDK8 (or install the Bumble Bee canary release).

A: To get rid of this error just enclose your complete layout design inside a plain layout tag in the activity_main.xml file.
After wasting many hours in finding solution this worked for me. Give it a try.

A: if you tried this steps

*

*invalidate/restart`

*keeping this properties in gradel.properties

android.databinding.enableV2=false
android.enableExperimentalFeatureDatabinding=true

and checking all xml  files looks good.
then you should go with this solution, add below code in project level build.gradle
    allprojects {
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xmaxerrs" << "1000"
        }
    }
}

this will give you exact error where you have actual error
explanation: above code will increase the size of the compile error

A: in my case, i follow the android documentation :
buildFeatures {
    viewBinding true
}

use "=" instead of space
buildFeatures {
    viewBinding = true
}

A: Try following Refactor -> migrate to androidx
and in the build.grade(:app)
implementation 'androidx.appcompat:appcompat:1.0.0'

or  use new version is released
implementation 'androidx.databinding:databinding-runtime:4.1.0'

A: Make sure that if your layout filename is named in the following format: <name>_activity.xml that your binding class name complies the following format as well: <name>ActivityBinding
For me, changing my layout filename from activity_login.xml to login_activity.xml resolved this issue because my binding class name was LoginActivityBinding.
Here's an except from the Android Layouts and binding expressions page mentioning this:

A binding class is generated for each layout file. By default, the name of the class is based on the name of the layout file, converting it to Pascal case and adding the Binding suffix to it. The above layout filename is activity_main.xml so the corresponding generated class is ActivityMainBinding

A: if you use a model in your layout, make sure you dont have the model and the package named same and also the paackage name should start with small letter.
i changed mine from Model>Model.class to modelPac>Model.class

A: In my case the problem appeared when I was creating productFlavors and set sourceSets.
Changing
sourceSets {
    develop {
        res.srcDirs = ['myApp/src/develop/res']
    }

to
sourceSets {
    develop {
        res.srcDirs = ['src/develop/res']
    }
}

solved my issue.


text:
Q: cascading dropdown in primefaces 3.2 not working i wish to use cascading dropdown in primefaces 3.2 but its not working. below is my xhtml code:
<p:selectOneMenu style="width: 150px" value="#{watchBean.exchange}">
                    <f:selectItem itemLabel="NSE" itemValue="nse"/>
                    <f:selectItem itemLabel="BSE" itemValue="bse"/>
                    <p:ajax event="change" update="sym" listener="#{watchBean.wow}" />
                </p:selectOneMenu>
            <p:selectOneMenu style="width: 150px" id="sym" value="#{watchBean.sl}" var="scrip">
                <f:selectItems  itemLabel="#{scrip.scripSymbol}" itemValue="#{scrip.scripSymbol}"/>
            </p:selectOneMenu>

bean code:
import java.util.List;
import javax.annotation.ManagedBean;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;
import service.MasterScrip;
import service.StatelessWebService_Service;

/**
 *
 * @author root
 */
@javax.faces.bean.ManagedBean
@javax.faces.bean.RequestScoped
public class watchBean {
    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/StatelessWebService/StatelessWebService.wsdl")
    private StatelessWebService_Service service;

    /** Creates a new instance of watchBean */
    public watchBean() {
    }
    String uname,scripSym,exchange;
    Integer scripID;
    List<UserTrack> ut;
List<MasterScrip> sl;
    public List<MasterScrip> getSl() {
        return sl;
    }

    public void setSl(List<MasterScrip> sl) {
        this.sl = sl;
    }

    public String getExchange() {

        return exchange;
    }

    public void setExchange(String exchange) {
        sl=getAllScripByExchange(exchange);
        setSl(sl);
        this.exchange = exchange;
    }
public void wow(ValueChangeEvent e)
{
    sl=getAllScripByExchange((String)e.getNewValue());
   // setSl(sl);
    //FacesContext.getCurrentInstance().renderResponse();

    // sl=getAllScripByExchange(exchange);
} ....

i get the following error:
javax.el.MethodNotFoundException: Method not found: beans.watchBean@2e1b13.wow(javax.faces.event.AjaxBehaviorEvent)

i referred to How do I get PrimeFaces <p:selectOneMenu> to call valueChangeListener? and removed the listener from my code, kept only the value attribute for 1st dropdown,still it doesnt work, then it gives no error and the 2nd dropdown isnt filled dynamically.
i am stuck in this, what is the cause of this error and how can it be solved?

A: 1) Remove parameter from method wow(). the ajax listener takes no parameter; when the method is executed, the attribute "exchange" contains the new value.
2) the selectOneMenus should be surrounded by h:form
3) The second selectOneMenu is wrong. the value attribute of the selectOneMenu should reference the selected item of the combo; not the list of items. the var attribute goes in the f:selectItems tag. the f:selectItems tag is missing the value attribute, which references the list of items. it should look like this:
<p:selectOneMenu style="width: 150px" id="sym" value="#{watchBean.selectedItem}" >
          <f:selectItems value="#{watchBean.sl}" var="scrip"
                         itemLabel="#{scrip.scripSymbol}"
                         itemValue="#{scrip.scripSymbol}"/>
</p:selectOneMenu>


text:
Q: How to Input Data Into a Trained Neural Network Algorithm - MATLAB This is very basic, but I can't seem to find an answer online...
I have developed a neural network for classification using MATLAB. However, I would like to feed to trained algorithm a new dataset for prediction in a prospective manner. I can't seem to figure out the formatting for the function myNeuralNetworkFunction(X,~,~). What goes into X, ~, and ~? If I put random number values in those three spots ie. myNeuralNetworkFunction(1,2,3) it will output
ans =
0.4793
0.3524
0.1683

Is this interpreted as the probability that sample fits into Class I, Class II, and Class III respectively?
Thank you for the help, I know these are newbie questions.
Below is the code for the neural network:
function [Y,Xf,Af] = myNeuralNetworkFunction(X,~,~)
%MYNEURALNETWORKFUNCTION neural network simulation function.
%
% Generated by Neural Network Toolbox function genFunction, 25-Sep-2014 13:48:20.
%
% [Y] = myNeuralNetworkFunction(X,~,~) takes these arguments:
%
%   X = 1xTS cell, 1 inputs over TS timsteps
%   Each X{1,ts} = 24xQ matrix, input #1 at timestep ts.
%
% and returns:
%   Y = 1xTS cell of 1 outputs over TS timesteps.
%   Each Y{1,ts} = 3xQ matrix, output #1 at timestep ts.
%
% where Q is number of samples (or series) and TS is the number of timesteps.

%#ok<*RPMT0>

  % ===== NEURAL NETWORK CONSTANTS =====

  % Input 1
  x1_step1_xoffset = [14.8911704312115;15.2767639519654;0.51064;1.90413;33.60375;15.43632;24.71805;0.01846;4.981;0.00033;0.22159;39.32377;19.36387;9.81086;0.22033;4.6786;14.9629;8.8028;4.74512;0.55702;660.25663;8.59155;0.37416;17.83039];
  x1_step1_gain = [0.027354428009736;0.0612618147797722;0.53764452556903;0.108070429498904;0.00273415535440648;0.0167784432574442;0.00143874231937304;0.483828047511914;0.499625281039221;0.652986597450087;1.59790355054169;0.00545387219881284;0.018425510635389;0.00896113957019686;0.837910418997105;0.00686875293360145;0.00614397382765453;0.0196487182502502;0.10665671204021;1.48306341579166;0.000773677797796089;0.0480697241735192;0.314333448065042;0.00523034792222075];
  x1_step1_ymin = -1;

  % Layer 1
  b1 = [1.55987050956456;1.3844896446184087;1.1858356678234501;-1.0437094397090567;-0.7695743943051927;0.7727728185085837;-0.49850097623420581;0.3360196027312633;-0.5052450230407648;0.12573629438984127;-0.36142377450191465;-0.26512162787695787;0.43422049198818885;-0.59484996326687367;-0.74347840297622803;-1.1241254208475855;1.0621269773342072;-1.1217914200306649;1.4625923192101142;-1.5876844882508814];
  IW1_1 = [-0.055982436209679104 -0.28944502014743512 0.38896483763687473 -0.17520091781902516 -0.36788963119290879 0.58680010891648471 0.38941048594029137 0.010330200046712359 -0.049196997026008424 -0.25965095783883646 -0.02330444839336468 0.48471956663410432 0.35540617499483801 -0.34500146111020641 -0.0306422432801076 -0.20558648541285637 -0.48852403830931596 0.58018036801883965 -0.21778584198672668 -0.17639473933123317 -0.12894993242501401 -0.32191664913965018 0.36502076112253562 -0.35423424394067804;-0.44842057227554855 0.39700388069390274 0.18239852514402061 0.33330369404033905 -0.33083266709586073 -0.42109550142439961 -0.37936412673907055 0.14092987565726023 0.27498893910037497 -0.037696461239827603 0.42058106837803533 -0.35405721057928519 -0.31200898537356103 0.3266151312604435 0.24758020461158411 -0.00028318649770493406 0.48622068190587153 -0.050159207180306711 0.038521280211102946 -0.43752851101801921 -0.40917699558077231 -0.31417436789272912 -0.30924992912408938 0.38587651437275444;-0.23169755933546252 -0.033754347614425945 -0.43966963319617031 -0.10362737153323315 -0.23869583433068692 -0.018842535943556636 -0.27934947951447109 -0.43974815194076045 -0.33977835068587897 0.17162613017120945 -0.36065553178060761 -0.39840592499124527 -0.10812891657493709 -0.39993101606248699 0.19264396978343784 -0.56134807445038559 -0.3646549207685566 0.03693663630665505 0.28992344266856157 -0.24197846571776097 -0.28421945026123852 0.2238898665802749 0.57957009993848951 0.52865696060643663;0.46775595437716078 -0.49759398923140102 -0.25543635820865557 0.18011414654693347 0.22839857302768798 -0.39817052105690232 0.42124548524474159 -0.38302040274848675 -0.45018774604344564 0.30776271594062077 -0.053687146243323117 0.21008425591895208 -0.25086014236085991 0.46442044353123357 0.37013016450855851 -0.35562597240295934 0.48246075163860352 -0.22143337282043704 -0.15354622986226024 -0.19520148498923329 0.28175659072346265 -0.19991745788738577 -0.265495614539076 -0.32998007941199758;0.53314385759977978 -0.084288099570861252 -0.087904814731226133 0.13997887906328665 0.078583762374498448 0.22089986106370055 0.11937406236219919 0.17931986738852818 -0.45555526826525045 0.10273619071622088 0.15437971971424042 0.19671926437767534 -0.30373240551984354 0.32987810978703014 0.33946655924729924 -0.33172198600185432 0.15007897699613323 0.44305909871884158 -0.45965277545665773 -0.5445260477144781 0.53690386149310154 0.32071960639735619 0.3346706317427332 -0.60044551394561885;-0.21895079613669227 0.30360131864707257 -0.48254331869669026 0.5426234966667407 0.53175788259274104 0.43438569989221498 0.25674366269228105 -0.20235539069140043 0.05522085113210641 -0.35628856718433854 0.1805462722036959 -0.20232926059522438 -0.56741148515447382 -0.24436414572936965 0.27639712244441805 0.35074056368620099 -0.33877374004680966 -0.38162031513538591 0.061523677180970113 -0.20635757815991357 0.17478209045151902 0.14373440637723872 0.4140189252683093 0.086756882167071767;0.20194393498084873 0.33601377745253913 -0.10774209305964288 -0.29722624992594709 0.30223692004740155 -0.41190860275852431 0.32459858890469206 -0.4103664016524477 0.1718744178031123 0.36646047872493631 0.24021043279112594 -0.47527338312608136 0.45522056842903807 0.4663571072074067 -0.15619524330182147 0.17042159594600717 -0.0094643117123553756 0.34972229572902347 -0.35841045332376159 0.44184179501847487 0.50657491877032257 -0.27251535338974842 0.053976124783220322 -0.45817262113177243;-0.48112733765313997 -0.15382945548644572 0.59568206101452548 0.071917432620535626 0.14546994145938053 -0.029054476752923268 -0.44239514130279495 -0.49288663170035307 0.61976876211435661 -0.35515864087981674 -0.26095866399195611 -0.49938787137002588 0.041803130505081311 0.35681709414517526 -0.24095955980424952 0.26090619437256735 0.27496224831511668 -0.10807493710234177 0.11792476953631001 0.12084195942242892 0.13552026682635013 0.26233519005540168 0.48436137135289897 0.41261415007384206;0.21895780734810372 -0.1511323910665277 -0.30822548003275396 -0.33710575421358474 0.034674652442276827 0.15101859650020807 -0.011485449807831588 -0.25985968754425742 -0.43197950537600155 0.43497607287821932 -0.064820281951947667 -0.073022254701932118 0.015714438133674614 -0.023776065260460819 0.34997606652439067 0.37469844465000585 -0.25689851488533372 0.51569778564256707 -0.44838098074602389 0.31305831108437643 0.51306142767010743 -0.40214657636097817 -0.41763716358690595 0.45699543228831752;-0.53017416936845407 0.42831417232332336 0.11786784798380144 0.039227806546526515 -0.29763012137133199 0.24637901223770131 0.29762857397361714 -0.013347397012488965 -0.4627281529891169 0.24554434668388281 0.39129352061411959 0.379553553064787 0.04415707626655066 -0.11971558212994232 -0.15276429992136409 0.45228689028401242 -0.50322528984760739 0.046552169551343309 -0.37788000442556102 -0.29612757986196442 0.33798412345818085 0.069089800822850531 -0.49046720164829072 0.26511335230057065;0.20196677020567266 0.095488430461431573 0.16399244062844004 0.52716962232017073 0.4348012802986464 0.018067285639911158 -0.26705074363994968 0.48825114495670008 0.14127835124956273 0.24629868830206755 0.54017198057440774 0.06480510843471024 -0.022685160228366745 -0.15438176399914305 -0.43132627576811389 -0.13129532598575516 0.096451476137207587 0.5926396743011304 0.091208771991736159 0.42720517218438908 -0.29783725969092761 0.65683408878263738 0.36153177278145338 -0.22919208447591802;-0.50452115900815619 0.0030003517081181488 0.46134789637779744 -0.60227711400545947 -0.48214549250915872 0.013063050810550585 0.15135559839444082 0.39143093064769241 -0.14086525474058859 -0.21731704108556071 -0.054170772583192923 -0.49764000322426905 -0.30456997680804121 0.18375313948369021 0.41927012683947518 0.19128196902407038 -0.37761853390034739 -0.26576194181536378 0.07726206216389829 -0.38520339916841162 0.025887458179402578 -0.11906795914922447 -0.56692586761027453 0.13538403175109057;0.35891662644586675 -0.37425630339293836 -0.13087333241744242 -0.16492608364523814 -0.47868126798293337 -0.29135042798915084 -0.32892700173155859 -0.41341689342409382 -0.47684656050809077 -0.40828991848978646 -0.22424380129271532 0.29329791200577621 0.52835706198039978 -0.24064601775448177 -0.078866115462040517 0.29104242992340346 -0.24155428609588137 -0.12412108758956597 -0.12661134901318469 0.53644335880766647 0.12353437383200713 0.044443354598736433 0.21915106707248028 0.45738952754175133;-0.4006229555345403 -0.38491870113799098 0.12684216755732858 0.23789761071382912 0.25780049722498549 0.12128670064482043 0.35455194739691609 -0.4402274458485313 0.26906181992343847 0.57958726634921054 -0.025706324845669152 0.16140130401483566 -0.060519286269974548 -0.49816799130907657 -0.32786559565987894 0.16032470166880464 0.47671706759696875 0.12126382162524643 0.11497301319122195 -0.060984633499597526 0.46572964627020685 0.53029114632588248 0.34913629799983792 0.3783603854876138;-0.23751836785709313 0.48943920219833192 -0.29803103360979344 0.51154553661021629 -0.10243898977969999 0.1738700091501662 0.40995996639230364 0.39877231971176491 0.019918105182817482 0.15560102498926082 -0.098114106905600795 -0.15612390887354927 0.17301979172967061 0.567425194056702 -0.53484903500060321 0.17128726452515966 -0.34133214953438257 0.36482792066829411 0.40500232676302061 -0.3046651610223628 0.14649536078138331 -0.23949813135658626 -0.36393981963734012 0.22581701137418828;-0.40046957858520676 0.6034617628482869 -0.48336085729216799 0.086551313937414401 0.11485328389518146 0.069661771564103803 0.047510680842533633 -0.14211127107043481 0.22762855836704607 -0.21910785086188639 -0.29622202947083798 0.010467063845525388 0.23958478560501784 0.47212874176804626 0.1021228950976064 -0.36988758340717282 0.43616237795047241 -0.34513066977461881 0.14396012746107209 0.17986038875407201 0.48818701767399414 0.28917556942311645 -0.10086763238985247 0.33793394200564547;0.46284253016065918 -0.13727771516669529 0.13577149568213143 0.58818192843346606 -0.20148925476427895 -0.46029269863375366 -0.11294539393881832 0.024584643894249029 0.096542815957358211 -0.47936958224293125 -0.38391418257758381 -0.0060708736228519012 0.31378810959162057 0.29455211667194553 -0.14010352441871604 -0.33539638866126609 -0.15418382335315545 -0.53468970341166444 -0.14260673859838446 -0.1588041819874888 -0.38130427331586136 -0.3152783892401666 -0.13797679272406654 0.41318952672339815;-0.0037580606519731774 0.25559446638500755 0.20805798628313835 -0.1197347663038016 0.25029241343311948 -0.19266109493430622 0.52557544297059011 -0.1619733303821082 -0.59587716408971514 -0.37733940188634407 -0.36931374243099563 0.035618524883801912 -0.36574413766651082 0.62552801072201847 -0.15345989677803071 -0.26277675374506049 -0.69325217331710443 -0.19889757010483353 0.080406773105486662 0.075152499178945523 -0.2528234547543543 0.47888754226850988 0.44361594565071144 0.13773610213966411;0.20986694884019669 0.5838069905096277 -0.24368635959982227 -0.31599013988815555 -0.18540921192951351 0.10603309773028717 -0.67295724327081385 -0.24897469750728726 0.19173947449901921 0.51005578175094068 -0.015723561815696684 0.1587217224633255 -0.29884049261948881 -0.0039568545329125258 -0.1061339521622824 0.16201250459705921 -0.28062245454944174 0.10496187687903319 -0.34786621560772413 0.32270413963798411 -0.054666413518356639 -0.31614441259179926 -0.25305596431344596 -0.62685043098789994;-0.44657252161722044 0.40823814755654514 0.064212018038187074 0.0066019305589507665 0.25098026347930169 -0.18569199430015434 -0.11776683585309426 0.46833540687344827 -0.19916527198638995 -0.2905264441725523 -0.45266095490372243 -0.34687790231020543 0.2229130626291119 -0.38366535966479787 0.017187383060134738 -0.29935260697370364 -0.38314823395341346 0.44303063064199694 0.2368545199511122 0.35728303698551611 -0.42103390461422724 0.37014001452647027 0.38735250852526876 -0.23260623539266509];

  % Layer 2
  b2 = [0.25980539367757699;0.58647489488472682;-1.065941024916949];
  LW2_1 = [0.070686644098666221 -0.62704849467284407 -0.26668403380813344 -0.60847661573672651 0.49634405645024138 0.96115472226825938 0.70161314683215703 -0.16244831393351064 -0.38778721201635435 -0.82737438162882337 -0.24871150318794885 0.33797064247996977 0.53933794530594548 -0.37673777430541439 0.66603786612798555 -0.86058356658893731 -0.1846439763729246 0.25597795984504707 0.88301766928111958 0.70154602431628132;-0.27224631592661641 -0.46534028660614779 0.31748339396483055 -0.77568458059698819 -0.19985189513930471 0.058899860449242475 -0.10649552828923813 0.59251644442143325 0.54884630250946731 -0.74722920996123465 0.78936347266716889 0.68795991441040816 -0.11649640733421024 0.88899475748526757 -0.27752223550178284 0.12836172010559904 0.34304188529668661 -0.3303334581681488 0.26083195268179116 0.28358224497140561;0.67722868060993668 -0.73839160801059034 -0.52668020024017737 -0.42037687153952519 0.42608979733760222 -0.085145700117314219 0.40224829869858036 -0.4380368280033714 0.22960637835244566 -0.61906073689858399 0.55422321506755923 -0.15626454164673309 0.58835836575191547 -0.89973441932108511 -0.77901845165683903 0.77329875011083038 -0.68252063535418506 -0.80613188132936098 0.85129342660612917 0.86638907626986761];

  % ===== SIMULATION ========

  % Format Input Arguments
  isCellX = iscell(X);
  if ~isCellX, X = {X}; end;

  % Dimensions
  TS = size(X,2); % timesteps
  if ~isempty(X)
    Q = size(X{1},2); % samples/series
  else
    Q = 0;
  end

  % Allocate Outputs
  Y = cell(1,TS);

  % Time loop
  for ts=1:TS

    % Input 1
    Xp1 = mapminmax_apply(X{1,ts},x1_step1_gain,x1_step1_xoffset,x1_step1_ymin);

    % Layer 1
    a1 = tansig_apply(repmat(b1,1,Q) + IW1_1*Xp1);

    % Layer 2
    a2 = softmax_apply(repmat(b2,1,Q) + LW2_1*a1);

    % Output 1
   Y{1,ts} = a2;
  end

  % Final Delay States
  Xf = cell(1,0);
  Af = cell(2,0);

  % Format Output Arguments
  if ~isCellX, Y = cell2mat(Y); end
end

% ===== MODULE FUNCTIONS ========

% Map Minimum and Maximum Input Processing Function
function y = mapminmax_apply(x,settings_gain,settings_xoffset,settings_ymin)
  y = bsxfun(@minus,x,settings_xoffset);
  y = bsxfun(@times,y,settings_gain);
  y = bsxfun(@plus,y,settings_ymin);
end

% Competitive Soft Transfer Function
function a = softmax_apply(n)
  nmax = max(n,[],1);
  n = bsxfun(@minus,n,nmax);
  numer = exp(n);
  denom = sum(numer,1);
  denom(denom == 0) = 1;
  a = bsxfun(@rdivide,numer,denom);
end

% Sigmoid Symmetric Transfer Function
function a = tansig_apply(n)
  a = 2 ./ (1 + exp(-2*n)) - 1;
end

A: Regarding the neural network: I didn't fully read your code but usually you can think about the training step as first making a prediction and then correct it based on the learning paradigm. so to classify basically you just perform the first part (until you get the estimated output) with your trained weights.
Note that the output of a sigmoidal node (which is one of the most used transfer functions at the output of a classification network) is not a probability but can at some extent be thought as one. if you have 3 outputs, each with a value between 0 and 1, and knowing that the closest an output node is to 1 the more probable it is that the input match that class, then you can simply do: Pn(i)=On(i)./sum(On), where Pn(i) is the probability of node(or class) i, On(i) is the output of the node i.
Summing up: Learning_step=predict+Learning_paradigm, Probabilistic_Classification_Step=predict/sum(predict)


text:
Q: Google Sheets (or maybe Zapier) CHANGES my formulas after I close the file and run my Zap: Google Sheets CHANGES my formulas after I close the file and run my Zap:  Three formulas, fairly simple.
All the row references are changing after I close the file (I double-and triple-check the entries before I close it) and run the Zap.
The first formula is: =IF(AND('Quiz One'!C29>0,'Quiz One'!C29<26), 'Quiz One'!A29, " ") it's copied down to Row 1000 (where the row is now 1000 in the formula).  I close the file.
I come back after running my Zapier, which adds a row of data to the worksheet "Quiz One".  That data is supposed to show up on the worksheet where this formula is, but it's not there. Instead, the formula in Row 29 now references Row 30, and all the way down to the bottom, where Row 1000 now references Row 1001.
This was supposed to trigger another Zap which sends the quiz respondent their results report.  But they never get it, because the formulas keep changing...

A: You are probably better off emailing Zapier support at contact@zapier.com!


text:
Q: Java - Case insensitive split WITH VARIABLE splitting string program test
so I have a program that will be given two strings as arguments: base and remove. It has to take out remove from base. I am using the split method to remove the second string from the first. However, the case on the chars of the second string should not matter, while the case of the first string must be preserved. I found a lot of ways to do this when you define the remove string in the program as a String literal: I can use ?i for example, but because remove is coming in as an argument and not a literal that I am defining in the program, this isn't working. Please check my attached picture so that you can see exactly where this is failing. Appreciate the help.
public String withoutString(String base, String remove) {

      String array[] = base.split(remove);
      String result = "";
        for(int i = 0; i<array.length;i++)
          result+= array[i];

      return result;
    }

A: Use a regex pattern with CASE_INSENSITIVE and LITERAL flags:
return Pattern.compile(remove, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
        .matcher(base).replaceAll("");

A: String.replaceAll() method accepts regex you can use directly like:
return base.replaceAll("(?i)(" + remove +")[\s]*", "")