text:
Q: How to scroll overflow table content while structure using flex css? Here i set content using display-flex css in parent main-wrapper, but i want to overflow content of table in scroll.
This can be solve using float:left css but i don't want to set structure using float:left.
So want just right side content on scroll not whole page scrolling.

* {
            margin: 0px;
            padding: 0px;
        }
        table, td, th {
          border: 1px solid black;
        }

        table {
          width: 100%;
          border-collapse: collapse;
          white-space: nowrap;
        }

        th,td {
            padding: 5px 10px;
        }

        .main-wrapper {
            display: flex;
        }

        .sidebar {
            width: 300px;
            height: 175px;
            display: block;
            min-width: 300px;
            background-color: #eeeeee;
            margin-right: 15px;
        }
        .table-wrapper {
            overflow: auto;
        }

                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading
                        Title Heading

                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text

                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text
                        Table content text

A: Can you please check the below code? Hope it will work for you. You need to give width to .main-content and max-width to .table-wrapper.
Please refer to this link: https://jsfiddle.net/yudizsolutions/9jbqudo1/1/

* {
  margin: 0px;
  padding: 0px;
}

table,
td,
th {
  border: 1px solid black;
}

table {
  width: 100%;
  border-collapse: collapse;
  white-space: nowrap;
}

th,
td {
  padding: 5px 10px;
}

.main-wrapper {
  display: flex;
}

.sidebar {
  width: 300px;
  height: 175px;
  display: block;
  min-width: 300px;
  background-color: #eeeeee;
  margin-right: 15px;
}

.table-wrapper {
  overflow: auto;
  max-width: 100%;
}

.main-content {
  width: calc(100% - 300px);
}

          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading
          Title Heading

          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text

          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text
          Table content text


text:
Q: Как разобрать строку методом parse() класса SimpleDateFormat, чтобы получить разные форматы при чтении ячеек Excel c помощью библиотеки POI? Пробую прочитать столбец в документе Excel и добавить прочитанное в список. Чтение формата даты пробую реализовать классом SimpleDateFormat, но требуется прочесть колонку с датой определенного формата и временем определенного формата, только не получается добиться данного результата, не понятно почему выкидывает
java.text.ParseException: Unparseable date: "dd.MM.yyyy"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at ru.app.doc.ReadExcelData.extractExcelContentByColumnIndex(ReadExcelData.java:73)
    at ru.app.doc.ReadExcelData.main(ReadExcelData.java:43)

Может кто нибудь подсказать в чем дело и как это реализовать?
switch (cell.getCellType()) {
    case Cell.CELL_TYPE_NUMERIC:
        String date = "dd.MM.yyyy";
        String time = "HH:mm";
        if (DateUtil.isCellDateFormatted(cell)) {
            // получение формата даты
            SimpleDateFormat sdfDate = new SimpleDateFormat(date);
            sdfDate.parse(date);
            columndata.add(sdfDate.format(cell.getDateCellValue()));
            // получение формата времени
            SimpleDateFormat sdfTime = new SimpleDateFormat(time, Locale.UK);
            sdfTime.parse(time);
            columndata.add(sdfTime.format(cell.getDateCellValue()));
        } else {
            columndata.add((int) cell.getNumericCellValue() + "");
        }
        break;
    case Cell.CELL_TYPE_STRING:
        columndata.add(cell.getStringCellValue());
        break;
}

A: В метод SingleDateFormat.parse нужно передавать строку, представляющую дату, например 25.10.2020. Тогда он вернёт объект типа java.util.Date
Но, мне кажется, что Вам его вызывать вовсе не нужно. Ведь задача в том, чтобы получить строку из объекта типа Date. А она решается вызовом метода SingleDateFormat.format.
Просто удалите строчки с вызовом метода SingleDateFormat.parse
Если хочется формировать только время для ячеек, в которых нет даты, нужно понять, какую строку возвращает sdfDate.format() для таких ячеек. После этого сравнивать результат sdfDate.format() с этой строкой.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What to do before the return in directives of AngularJS? I was asking myself, what things can you put in before the return statement, when defining directives in AngularJS?
angular.module('app').directive('myDir', function() {
    // What can you do here?
    return {
        restrict: 'E',
        link: function(scope, element) {
            // do things
        }
    };
});

So some general questions are:
1. What can you do there?
2. What can only happen there?
3. What shouldn't be done in there?

One thing I found useful, is that you can store variables or functions in there which you can then use in the definition of the directive, but I would like to hear some other suggestions.

A: Well, since no one else has answered yet... as I mentioned in the comments, the Understanding Directives wiki page has some useful information.
The first time the directive is encountered, Angular will run the directive function once.  So whatever you put here will only be executed one time (or maybe zero times if the directive is not used anywhere in your app.)  So, if something can be shared between all directive instances, you can put that here:  functions, directive-global variables, one-time initialization, etc.
Note that any functions that you put here will be rather limited.  They won't have access to the scope or element or attributes – unless you pass them in as arguments.  For that reason, functions that are used by the compile or link functions are often put inside the compile or link functions because then they'll have access to the scope, element, and attributes due to JavaScript closures.  The two example directives on the Directives page do this.


text:
Q: How to create the video from images located in SD card in Android using JavaCV/OpenCV Sorry for bad English...:(
I want to create video from images  located on SD Card and also each frame/image stay on  screen min 1 sec or any value(like 2,3,4 sec).
I am using the javacv/opencv library for that.
I have use the below code but not work for me i get error given below.
I have put my method and error log also, please help me as soon as possible.
Thanks in advance
public void createVideo()
    {
          String path ="/mnt/sdcard/images/";
          File folder = new File(path);
              File[]  listOfFiles = folder.listFiles();
              IplImage[]  iplimage = (IplImage[]) new IplImage[listOfFiles.length];
              if(listOfFiles.length>0)
              {
                 for (int j = 0; j < listOfFiles.length; j++)
                 {
                     String files="";
                     if (listOfFiles[j].isFile())
                     {
                         files = listOfFiles[j].getName();
                     }
                      String[] tokens = files.split("\\.(?=[^\\.]+$)");
                      String name=tokens[0];
                      System.out.println(" j " + name);
                      iplimage[j]=cvLoadImage("/mnt/sdcard/images/"+name+".jpg");
                 }

              }

              File videopath = new File(path);
              videopath.mkdirs();
              FFmpegFrameRecorder recorder = new  FFmpegFrameRecorder(path+"video"+System.currentTimeMillis()+".mp4",320,480);

               try {
                   recorder.setVideoCodec(13); //CODEC_ID_MPEG4
                   //CODEC_ID_MPEG1VIDEO
                   recorder.setVideoBitrate(50);
                   recorder.setFrameRate(10);
                   recorder.setPixelFormat(2); //PIX_FMT_YUV420P
                   recorder.start();
                   int x = 0;
                   int y = 0;
                  for (int i=0;i< 300 && x<listOfFiles.length;i++)
                     {
                       recorder.record(iplimage[x]);
                      if (i>(y+10)) {
                          y=y+1;
                          x++;
                      }
                     }
                   recorder.stop();
                  }
               catch (Exception e){
                   e.printStackTrace();
                 }
    }

But i get this one error please
04-09 12:36:26.130: W/System.err(10201): com.googlecode.javacv.FrameRecorder$Exception: avcodec_open2() error -22: Could not open video codec.
04-09 12:36:26.131: W/System.err(10201):     at com.googlecode.javacv.FFmpegFrameRecorder.startUnsafe(FFmpegFrameRecorder.java:492)
04-09 12:36:26.131: W/System.err(10201):     at com.googlecode.javacv.FFmpegFrameRecorder.start(FFmpegFrameRecorder.java:267)
04-09 12:36:26.131: W/System.err(10201):     at com.example.imagetovideo.MainActivity.createVideo(MainActivity.java:107)
04-09 12:36:26.131: W/System.err(10201):     at com.example.imagetovideo.MainActivity$1.doInBackground(MainActivity.java:57)
04-09 12:36:26.131: W/System.err(10201):     at com.example.imagetovideo.MainActivity$1.doInBackground(MainActivity.java:1)
04-09 12:36:26.131: W/System.err(10201):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-09 12:36:26.131: W/System.err(10201):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-09 12:36:26.131: W/System.err(10201):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-09 12:36:26.131: W/System.err(10201):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-09 12:36:26.131: W/System.err(10201):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-09 12:36:26.131: W/System.err(10201):     at java.lang.Thread.run(Thread.java:841)

please help me!!!!:)
Thank in advance

A: // mp4 video
This is working code. I am using this code to make video from images which are located in sdcard.
private class VideoCreate extends AsyncTask<Void, Void, Void> {

    String Videopath;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("VideoCreate onPreExecute call ");
        dismissProgressDialog();
        showProgressDialog();
    }

    @Override
    protected Void doInBackground(Void... params) {

        // try {

        temp_video_file_name_last = System.currentTimeMillis()
                + FileUtils.VIDEO_TYPE_MP4;
        // Vidopah = FileUtils.getScreenShotDirectory(getActivity(),
        // FileUtils.ATTACHMENT_TYPE_VIDEO)
        // + File.separator
        // + video_file_name_last;
        Videopath = getTempVideoDirectory() + File.separator
                + temp_video_file_name_last;

        File pF = new File(tempVideoShotDirecotry);
        if (!pF.exists()) {
            System.out.println("pF not exist");
            pF.mkdirs();
        }
        if (pF.exists()) {
            System.out.println("pF  exist");
        }
        int imgCounter = 0;

        File folder = new File(tempVideoShotDirecotry);

        File[] listOfFiles = folder.listFiles();
        System.out.println("listOfFiles size::" + listOfFiles.length);
        if (listOfFiles.length > 0) {

            for (int j = 0; j < listOfFiles.length; j++) {

                if (listOfFiles[j].getAbsolutePath().endsWith(".JPEG")
                        || listOfFiles[j].getAbsolutePath().endsWith(
                                ".jpeg")
                        || listOfFiles[j].getAbsolutePath()
                                .endsWith(".JPG")
                        || listOfFiles[j].getAbsolutePath()
                                .endsWith(".jpg")
                        || listOfFiles[j].getAbsolutePath()
                                .endsWith(".png")) {
                    System.out.println(j + " position listOfFiles::"
                            + listOfFiles[j].getAbsolutePath());
                    Bitmap bmp = BitmapFactory.decodeFile(listOfFiles[j]
                            .getAbsolutePath());
                    if (bmp != null) {
                        System.out.println("bmp is not null");
                        ++imgCounter;
                    }

                }

            }

        }

        Log.e("", "Intial Execute");

        FFmpegFrameRecorder recorder = null;
        recorder = new FFmpegFrameRecorder(Videopath, ScreenShotWidth,
                ScreenShotHeight);
        Log.d("Display",
                (new StringBuilder(String.valueOf(ScreenShotWidth)))
                        .append(":").append(ScreenShotHeight).toString());

        // working
        recorder.setVideoCodec(13);
        recorder.setFormat("mp4");
        recorder.setFrameRate(1.0D);
        recorder.setVideoQuality(1.0D);
        recorder.setVideoBitrate(40000);

        long l = System.currentTimeMillis();
        try {
            recorder.start();
        } catch (org.bytedeco.javacv.FrameRecorder.Exception e1) {
            e1.printStackTrace();
        }
        System.out.println("imgCounter size::" + imgCounter);

        for (int i = 0; i < imgCounter; i++) {
            org.bytedeco.javacpp.opencv_core.IplImage iplimageTemp = opencv_highgui
                    .cvLoadImage(listOfFiles[i].getAbsolutePath());
            long l1 = 1000L * (System.currentTimeMillis() - l);
            if (l1 < recorder.getTimestamp()) {
                l1 = 1000L + recorder.getTimestamp();
            }
            System.out.println(i + " timestamp:::" + l1);
            recorder.setTimestamp(l1);
            try {
                recorder.record(iplimageTemp);
            } catch (org.bytedeco.javacv.FrameRecorder.Exception e) {
                e.printStackTrace();
            }
        }

        Log.e("", "End Execute");
        try {
            recorder.stop();
        } catch (org.bytedeco.javacv.FrameRecorder.Exception e) {
            e.printStackTrace();
        }

        // } catch (Exception e) {
        // e.printStackTrace();
        // }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        dismissProgressDialog();
        alert.setCustomToast("Video is Generated");

        if (isTempVideoAvailableInStorage()) {

            new MergeAudioAndVideo().execute();
        }
    }
}


text:
Q: Assigning e-mails to accounts using nginx smtp proxy I want to use nginx as SMTP proxy for SMTP authentication. However, is it possible to pair somehow smtp login with email which was sent using this login? Like adding additional header containing login which goes through the proxy etc, so the SMTP server knows which account was used.

A: I am not sure I completely understand your use case.
In theory, nginx would just be passing the connection through to a backend server, in which case, I would assume the FROM field would contain the information you need.
If not, then there is some info in the mail headers that usually provides what you are looking for, e.g.:
Received: from some.node.tld (unknown [xx.xx.xx.xx])
    (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits))
    (Client did not present a certificate)
    (Authenticated sender: USER.NAME@DOMAIN.TLD)
    by MAIL.DOMAIN.TLD (Postfix) with ESMTPSA id 8828AC0FA5
    for <DESTINATION.USER@DOMAIN.TLD>; Fri,  1 May 201x 17:44:46 +0200 (CEST)

I am also not complete sure why you have nginx in the path - is there something specific you were trying to achieve?


text:
Q: How to Cross Build Latest Stable Qemu with x86_64-w64-mingw32 Installed the mingw and cloned the "latest stable" branch of QEMU with
sudo apt-get install -y mingw-w64
cd ~/
git clone -b stable-2.2 git://git.qemu.org/qemu.git
cd ~/qemu

Then from @http://wiki.qemu.org/Hosts/W32#Building_QEMU_for_W64 I tried:
./configure --cross-prefix=amd64-mingw32msvc-

and now I'm getting:
ERROR: "amd64-mingw32msvc-gcc" either does not exist or does not work

Update:
~/Scripts/qemu$ ./configure --cross-prefix=x86_64-w64-mingw32-
ERROR: pkg-config binary 'x86_64-w64-mingw32-pkg-config' not found

2nd Update:
Fixed previous issue with
sudo link /usr/bin/pkg-config /usr/bin/x86_64-w64-mingw32-pkg-config
sudo apt-get --no-install-recommends -y build-dep qemu

but now I'm getting:
owner@K53TA:~/qemu$ ./configure --cross-prefix=x86_64-w64-mingw32-

ERROR: zlib check failed
       Make sure to have the zlib libs and headers installed.

but zlib1g-dev IS INSTALLED

A: Warning: This answer is a Work In Progress
Even though I asked the OP to consider using WinQemu, I'm officially writing an answer for those that choose to "do it from scratch."  Assuming your build host is 64-bit and your Windows is 32-bit:

*

*We need to remove the OP's failed install of the cross-compile tools, using:
sudo apt-get --purge remove mingw-w64
rm -vR ~/qemu

*Now we must decide on our Architecture.  If your Build host is 64-bit, and your Windows is 32-bit, use:
sudo apt-get install gcc-mingw32 mingw32-binutils mingw32-runtime

*If your Build host is 64-bit, and your Windows is 64-bit, use:
sudo apt-get install gcc-mingw32 mingw32-binutils mingw-w64

*Optional: Add SDL Support by:
wget http://www.libsdl.org/release/SDL-devel-1.2.15-mingw32.tar.gz

*Now we download the Source Tarball, and untar it.  You can also use the Git Clone as the OP did, but you only need to choose one option:
sudo apt-get install wget && wget http://wiki.qemu-project.org/download/qemu-2.2.0.tar.bz2 && tar -xvjpf qemu-2.2.0.tar.bz2 && cd qemu-2.2.0

*Now we configure the build. If your Build host is 64-bit, and your Windows is 32-bit, use:
configure --cross-prefix=i586-mingw32msvc- [--extra-cflags=-mthreads]

*If your Build host is 64-bit, and your Windows is 64-bit, use:
configure --cross-prefix=amd64-mingw32msvc-
Note: If the Configure Phase fails, you must fix the configure errors, as the OP alluded to.  At this point, a configure failure is most likely caused by missing libraries


text:
Q: How to plot ranges of two variables with ggplot2 in R I have a data frame with four variables as follows:
my_matrix <- matrix (c("D1",5,25, 100,200,
           "D2",6,30,150,250,
           "D3",7,32,180,300), nrow =3, byrow = T)
my_matrix <- as.data.frame(my_matrix)
names(my_matrix) <- c("Layer","Tmin", "Tmax", "Pmin", "Pmax")
my_matrix$Tmin <- as.numeric(as.character(my_matrix$Tmin))
my_matrix$Tmax <- as.numeric(as.character(my_matrix$Tmax))
my_matrix$Pmin <- as.numeric(as.character(my_matrix$Pmin))
my_matrix$Pmax <- as.numeric(as.character(my_matrix$Pmax))

I plotted the ranges of Pmin and Pmax for Layer variable as follow:
ggplot(my_matrix, aes(Layer))+
 geom_linerange(aes(ymin= Pmin,ymax= Pmax),linetype=1,color="red")+
 geom_point(aes(y=Pmin),size=3,color="blue")+
 geom_point(aes(y=Pmax),size=3,color="blue")

I also plotted ranges for Tmin and Tmax for Layer variable:
ggplot(my_matrix, aes(y= Layer))+
 geom_linerange(aes(xmin = Tmin, xmax = Tmax),linetype=1,color="red" )+
 geom_point(aes(x=Tmin),size=3,color="blue")+
 geom_point(aes(x=Tmax),size=3,color="blue")

I want to combine these two plots into one plot where x-axis shows the ranges of Tmin and Tmax, while y-axis shows the ranges of Pmin and Pmax for Layer variable. There should be 3 plus sign on the plot for D1,D2,and D3 at the end. How can I plot this?


text:
Q: Need a way to change email address link depending on sender profile marketing cloud I have an email link icon in the footer of my email template. I want to be able to change the link of the email address in the footer dynamically depending on the 'from email' of the sender profile in marketing cloud email studio. How would I go about doing this? Thanks

A: I don't think this is possible without some workaround. The build process for an email handles email content and job configuration in separate steps and from what I understood by now the pairing of sender profile with the message itself happens after the message and contained AMPScript is evaluated.
You can check the order of operation in the documentation. The point of script evaluation is when the message is matched with subscribers. This step is also what you simulate when you click "Preview and Test" in the email editor. At this time the Sender profile is not yet assigned to the message.
The thread mentioned by fromero explains how a single sender profile can be made dynamic. This is something that you could possible use to solve your issue. Dynamic sender profiles do not need this FROM NAME attribute and data extension field name stuff by the way. You just need to start any lookup based on the subscriber key value.

*

*Create a lookup data extension that associates sender email addresses with a subscriber attribute or subscriber data extension field value (region, language, SF record owner, ...)

*Create a code snippet in Content Builder with AMPScript which first gives you the subscriber attribute (or data extension field) value based on the subscriber key and then looks up the appropriate email address in the lookup data extension. Set a variable @SenderEmail for the final result (or any other name. I will use this for further reference). Make sure to set a default sender address as fallback in your AMPScript. The following is an example of a dynamic sender profile script I deployed for a client based on the local branch ('Filiale') a contact is associated with ('Bevorzugte Filiale')

%%[var @Filiale, @Filialmail
Set @Filiale = Lookup('Contact_Salesforce', 'Bevorzugte_Filiale__c', 'Id', _subscriberkey)
if not empty (@Filiale) then
Set @Senderemail = Lookup('Filialen', 'MC_FilialEmail__c', 'Filialnummer__c', @Filiale)
else
Set @Senderemail = "youremail@example.com"
endif
]%%

*

*Use the following code to call the script in the dynamic sender profile. 123 stands for the Id of the content element you created.

%%=TreatAsContent(ContentBlockById('123'))=%%%%=v(@SenderEmail)=%%

*

*Use the same process logic for your sender profile FROM NAME if required (you would also have to add a corresponding field in your lookup data extension)

*In the Email itself insert the %%=TreatAsContent(ContentBlockById('123'))=%% call anywhere above the footer element where you need to personalize the address

*Use %%=v(@SenderEmail)=%% for the email address tag
Why the external content block?
The advantage of the approach with an "external" content block is that you only have to edit one element when you have to adjust the logic somehow. Also, most errors that might break your sender profile can already be found in the email preview with one major exception: Always make sure beforehand that any email addresses used in this process are validated/verified. This is something the email preview doesn't check.
Please comment if you need some context on the AMPScript functions


text:
Q: We infer from MCT that $v$ is a measure (Radon-Nikodym)
This is from Royden text. He say that "We infer from the linearity of integration and the MCT that $v$ is a measure .." I understand the linearity of integration $\implies$ $v$ is measure. But, I am not sure how MCT is used in this case. Could you give some hint?

A: If $\{E_n\}$ is a disjoint sequence in the sigma algebra with union $E$ then  $fI_E=\sum_{n=1}^{\infty} fI_{E_n}$. Let $f_k =\sum_{n=1}^{k} fI_{E_n}$ and apply MCT to this sequence.


text:
Q: What are the new rules for variable scoping in Emacs 24? Emacs 24 now has lexically-scoped variables. It also still has dynamically-scoped variables, of course. Now that it has both, I'm quite confused about when a variable will have which kind of scope. There's a lexical-binding variable that controls when lexical binding is enabled, and I think I read something about defvar now declaring a dynamically-scoped variable, but in general I'm pretty lost. Is there a good explanation somewhere of Emacs 24's new scoping rules? Or put another way, when I look at a variable in Emacs Lisp code written for Emacs 24, how do I tell what scope that variable is using?

A: Let's say that some code is being evaluated step by step in Emacs (either because you just did C-x C-e or because an Emacs Lisp file is being loaded or because a function from a hook is being run, etc), and that Emacs is about to evaluate my-abc within that code. Maybe my-abc is a local variable in that code or maybe it is not declared or maybe it has some global value, etc. Anyway, the current step is evaluation of my-abc. At that point, Emacs checks just two things to decide whether to evaluate my-abc using lexical scope or not.
First thing Emacs checks is "is my-abc a special variable?". The answer to that question is yes if (defvar my-abc ...) or (defcustom my-abc ..) or etc was run at any point in the past. Maybe (defcustom my-abc ..) was run while loading some other Emacs Lisp file, or maybe you evaluated some code containing (defvar my-abc ...) on the scratch buffer, or maybe not. If the answer is yes for any reason, Emacs at this point will evaluate my-abc using dynamic scope.
If the answer is no, then Emacs checks the second thing, which is (A) "where is this code (containing use of my-abc) that I (Emacs) am stepping through?". This is not (B) "what is the current buffer now?". If you just pressed C-x C-e on a buffer, say foo.el, and if the expression you pressed C-x c-e on contained a call to a function named mah-hello which is defined in mah-stuff.el, and if mah-hello function body contained a call to a function named my-hello which is defined in my-stuff.el, and if the function body of my-hello contained use of a variable named my-abc, then when Emacs eventually get to executing my-hello and then is about to evaluate my-abc in there, at that point when Emacs asks Question A, it answers my-stuff.el to itself. Not the buffer foo.el that contains the starting expression.
Then Emacs asks "is my-stuff.el a lexically scoped buffer, in other words, is lexical-binding true on that buffer?". If yes, Emacs evaluates my-abc using lexical scope, otherwise using dynamic scope.
Some update: Also, when the code is quoted as data and then passed to the eval function, the answer to (A) will not be a buffer. Still, it's as if eval makes up an imaginary buffer to place the code, and set the buffer-local value of lexical-binding for that buffer to the second argument passed to eval. The answer to (A) is not the buffer containing the `eval' call. It is the imaginary buffer.
For Lisp macros, when some macroexpanded code is being run, it's as if the expanded code is written to the buffer that contains the code that invoked the macro. Therefore the answer to (A) in this case is not the buffer that defined the macro, but the buffer where code that called the macro resides.

A: The manual is the definitive source. Start here:
C-hig (elisp) Variable Scoping RET
I had originally quoted the manual in this answer, but that information (dating back to Emacs 24.0.90.1) was slightly out of date. Better to read the manual from inside Emacs so that the information will be correct for the version you're using.
If you particularly want to read it on a web page, the current version is:
http://www.gnu.org/software/emacs/manual/html_node/elisp/Variable-Scoping.html


text:
Q: csproj and n-tier application In my application have at least 3 layers/tiers; like Data, Business, Web.
As the project was created in xproj format, I'm seeing the "Data" references in the "Web" tier.
This was not happening in csproj. How do I isolate better?


text:
Q: How to save JSON data to new JSON file through iterating using AJAX and PHP? I have simple movies editor with the sidebar in which user just drag and drop the element to the right side user can edit this element as they wish and save data to JSON, I want when the user clicks to save it should create a new file and save to it new data.
so far here is what I have
HTML

            <button type="button" class="btn btn-success btn-save">Save</button>

here is  js to save the file
var moviesblocks =null;

$(document).ready(function(){

$.getJSON('moviesblocks.json', function (data) {

    moviesblocks = data.moviesblocks;
    console.log(moviesblocks);

});

$("#main-btn-save").on("click", function () {

    var moviesparams = JSON.stringify({
        moviesblocks: moviesblocks
    });

    $.ajax({
            type: 'POST',
            data: {
                moviesparams: moviesparams
            },
            url: 'save_movies_block.php',
            success: function (data) {
                    $('#msg').html(data).fadeIn('slow');
                    $('#msg').delay(2000).fadeOut('slow');
            },
            error: function () {
                    $('#error-msg').html(data).fadeIn('slow');
                    $('#error-msg').delay(2000).fadeOut('slow');
            }
    });

    console.log(moviesparams);
});

})

Here is php file to handle the process
<?php
if(isset($_POST['moviesparams'])){
    $moviesparams = json_decode($_POST['moviesparams']);
    // do whatever checks you need on $moviesparams to verify valid data
    $success = file_put_contents("moviesblocks.json", json_encode($moviesparams));
    if($success === false){
        echo "sorry , something is wrong";
        die();
    }else{
        echo "Data successfully saved";
        die();
    }
} else {
    echo "nic";
}

$data=file_get_contents("data.json");
$result=json_decode($data);
?>

As you can see now after user clicks save it save to this file
moviesblocks.json

Now I want when a user clicks save, it should save to new file
something like moviesblocks1.json instead of moviesblocks.json
Here is a live demo live demo
How can I achieve what I want?

A: If you dont wanna use database, you need to create one more file to maintain file version numbers. Each time you wanna create new file, get the latest version number from this version.txt file and append it to filename. Eg : moviesblocks1.json, moviesblocks2.json.
After creating new file,  update the version from version.txt. This will help you to create new version number next time.


text:
Q: Classisthesis section numbers not showing I am using classicthesis with the MWE below.
When I compile locally, section numbers are not showing, but are included in the Table of Contents.
However, compiling with Overleaf does show the section numbers, both in the ToC and in the document.
So I think this is an issue with the version/compiler I am using to compile locally (pdflatex on Ubuntu-16.04).
How can I check which version of classicthesis is being called locally by pdflatex? And if it is out of date, how can I update it?
\documentclass{scrbook}
\usepackage[parts,pdfspacing]{classicthesis}

\begin{document}
    \tableofcontents
    \chapter{First chapter}
    \section{First section}
        Hello, world

    \section{Second section}

\end{document}

Here is an image of how it looks when compiled locally:

Thanks.


text:
Q: Error in UseMethod("invoke"): no applicable method for 'invoke' applied to an object of class "character" I'm trying to run a sample of the data. It is a Large tbl_spark (2 elemets, 1.4mb), and the class is "tbl_spark" "tbl_sql" "tbl_lazy" "tbl"
my code is as follows
temp <- sdf_sample(table, fraction = 0.01) %>% collect()

Then I got this error:
Error in UseMethod("invoke"): no applicable method for 'invoke' applied to an object of class "character"
Then I run the same thing again and got:
Error in as.vector(x, "character") : cannot coerce type 'environment' to vector of type 'character'
Please help


text:
Q: If $\omega$ is closed on $\mathbb R ^2 - 0$ and $\text d \omega =0$, then $\omega = \text d g+ \lambda \text d \theta$. I'm trying to solve problem 4-30 from "Calculus on manifolds", which is the one in the title, where $$\text d \theta = -\dfrac{y}{x^2+y^2}\text d x+\dfrac{x}{x^2+y^2}\text d y.$$ I think I'm on the right track, but I need some help concluding.
The problem is preceded by this simpler one:

If $\omega=f\text d x$ is a one form on $[0,1]$, there exists $g\colon [0,1]\to \mathbb R$ with $g(1)=g(0)$ and $\lambda\in \mathbb R$ such that $\omega = \text d g+ \lambda \text d x$.

and gives this hint:

Hint: if $C_R^*\omega = \lambda _R\text d t+ \text d (g_R),$
  show that all numbers $\lambda _R $ are equal.

Here $C_R(t)=Re^{i2\pi t}$.
Ok, so by problem 4-29 follows that $C_R ^*\omega$ is of the form given in the hint, and using closeness of $\omega$ I've been able to prove that all $\lambda$'s are equal. Since $C_R ^* \text d \theta = 2\pi \text d t$, it follows that, if we redefine $\lambda \mapsto 2\pi \lambda$: $$C_R ^* (\omega -\lambda \text d \theta ) =g'_R(t)\text d t$$
for all $R$ and for some function $g_R\colon [0,1]\to \mathbb R$.
I'm stuck here. I thought, for example, that $$g'_R\text d t=C_R ^*[ (g'_R\circ C_R ^{-1})\text d \theta ],$$
but I don't know if this fact can help (I'm not even sure that it can make sense,  since $C_R ^{-1}$ is discontinuous on the $x$ axis).
Any help or hint is much appreciated.

A: You're 90% done. You've shown that $\omega - \lambda d \theta$, pulled back by $C_R$, gives you $dg_R$. All you really need to do is build the function "g" on the punctured plane. And your individual $g_R$ functions are what you need to do that.
Basically, you'd like to say "my function $g$, at a point $P$ of the punctured plane, is just...well, if the polar coordinates of $P$ are $(R, \theta)$, then $g(P) = g_R(\dfrac{\theta}{2\pi})$, or something like that."
The problems have have left are
(1) cleaning up that statement a bit, and
(2) worrying about the $x$-axis and continuity and well-defined-ness there. As you observe, if your point $P$ is on the $x$-axis, then you could use either $g_R(0)$ or $g_R(1)$ to define $g(P)$. How can you be sure that they're the same? [Hint: does problem 4-30 have an additional conclusion about $g$? I seem to recall, from the last time I did this problem, about 40 years ago, that it does...]

A: To complete my proof above.
Let $g(r,\theta)=g_r(\frac{\theta}{2\pi})$, $r>0$, $\theta \in [0,2\pi]$. Denote with $p=(r,\theta)$ the polar coordinates on $\mathbb R ^2-{0}$ and let $G=g\circ p$ (by construction of $g$ in problem 4-29 it can be shown that $g^{(k)}(0)=g^{(k)}(1)$ if $f^{(k-1)}(0)=f^{(k-1)}(1)$, so $G$ is differentiable on the $x$ axis).
Now: $$C_R^*\text d G=C_R^*[(\dfrac{\partial g}{\partial r }\circ p)\text d r+(\dfrac{\partial g}{\partial \theta }\circ p)\text d \theta]=g_r'(t)\text d t,$$
so:$$C_R ^* (\omega -\lambda \text d \theta -\text d G)=0,$$
or$$\omega =\lambda \text d \theta + \text d G+H\, \text d r$$
for some function $H=h\circ p$ ($\text d r$ is the differential of $\sqrt{x^2+y^2}$).
Since $\omega$ is closed, we have $$\dfrac{\partial h}{\partial \theta}=0,$$
so $$h(r,\theta)=k(r).$$
Let $g_1=g+\intop _1 ^r k$, $G_1=g_1\circ p$, and we are done.


text:
Q: Braintree iOS SDK 4.0 - Reuse Add New Payment View Controller Is it possible to re-use the Braintree DropIn UI's Add New Payment View Controller? Or do we have to create a view controller manually from scratch and tokenize the new payment?
Any assistance will be greatly appreciated.
The screen that I am referring to:

A: I work at Braintree.
Either approach should work, but I think the best practice is to create it when it's necessary and deallocate it when you're done (i.e. do not keep a reference to it). Drop-in view controller instantiation is fairly lightweight, so instantiating it each time should not have much of an impact on CPU performance.
One small advantage of retaining the Drop-in view controller could be if you allow your customers to save payment methods to the Vault (e.g. your Braintree client token has a customer ID). In that case, the view controller loads saved payment methods from the Vault, which fires off a network call to load that data (see BTDropInViewController -fetchPaymentMethodsOnCompletion). Retaining the view controller in memory would allow you to cache the payment methods so that this doesn't have to be loaded.
The disadvantage to this approach is that you'd be keeping the view controller around in memory, which increases the memory footprint of your app. Also, the state of the Drop-in view controller will not be reset, so if your user partially fills out the card form, goes back, then returns at a later time, they'll still see the partially filled form.


text:
Q: Subtract Vertical Offset to Document Fragment scroll I have a page with a fixed header and I want a url like http://example.com#foo to scroll to the element with id=foo and subtract the height of the header so that the element is visible.
I've tried the following, but in at least Chrome, this code is run before the default document fragment scrolling occurs so the scroll position is overwritten:
$(function() {
  var offset;
  if (window.location.hash !== "") {
     offset = $(window.location.hash).offset().top;
     return $("body").scrollTop(offset - headerHeight);
  }
});

Here's a jsfiddle of the problem http://jsfiddle.net/rk8y7/1/

A: I was able to get this to work by changing the id of the DOM element to be the current id + _section and then listening for a hashchange event to set the scroll position of the page.
I also had to trigger hashchange on pageload to get it to the work on the first page load.
$(function() {
  $(window).on('hashchange', function() {
    var elemId, headerHeight, offset;
    elemId = window.location.hash + "_section";
    if (window.location.hash !== "" && $(elemId).length) {
      headerHeight = $('header').height();
      offset = $(elemId).offset().top;
      return $("html, body").scrollTop(offset - headerHeight);
    }
  });
  $(window).trigger('hashchange');
});

Here's my fiddle http://jsfiddle.net/sguha095/rk8y7/4/


text:
Q: Find value of XPath in different object in array I'm currently building a document in XSL-FO to build a table based on a list of items.  The issue is that the items have relationships between them, and I need to be able to reference a value from the other item based on the relationship.
Say I had an input object like:
    <Products>
      <Product>
        <ID>A</ID>
        <Name>Cat</Name>
        <Relationship>
          <ID>B</ID>
        </Relationship>
      </Product>
      <Product>
        <ID>B</ID>
        <Name>Hat</Name>
      </Product>
    </Products>

I need to be able to put together a table that has the format of:
    Name
    ----
    Cat
     - Hat
    ----
    Hat

To build the table rows, I've already done
    <fo:table>
      <xsl:apply-templates select='Product' />
    </fo:table>

and then 'within' each Product, putting a block based on the name:
    <fo:block>
      <xsl:value-of select="Name" />
    </fo:block>
    <fo:block>
      <xsl:apply-template select="..." />
    </fo:block>

My issue is the ... select option to get the name. I was hoping to be able to build an xpath along the lines of ../Product[ID=./Relationship/ID]/Name
but it doesn't work because the ./ now refers to any of the products, not just the "starting" object.
Is there a way to accomplish this referencing using xpath?

A: XSLT has a built-in key mechanism to resolve cross-references. Start by defining a key at the top level of your stylesheet as:
<xsl:key name="product" match="Product" use="ID" />

Then, from the context of Product, you can do:
<xsl:apply-templates select="key('product, Relationship/ID)/Name"/>

Alternatively, you could do:
<xsl:apply-templates select="../Product[ID=current()/Relationship/ID]/Name"/>

But using a key is both more elegant and more efficient.


text:
Q: Can't insert data I can't find mistake why my data didn't inserted in data base. I use sql server. DB is 3 field: 1) id (int) 2) test1(varchar(50)) 3) test2(varchar(50)). I try insert data from textbox and date.
private void SaveToDB()
    {
        string strSql = "";
        string[] tos = txtTo.Text.Split(';');
        for (int i = 0; i < tos.Length; i++)
        {
            strSql += "INSERT INTO test (test1, test2) VALUES ('" + txtContent.Text.Trim() + "','" + DateTime.Now.ToString() + "');";
        }
        using (SqlConnection connection = new SqlConnection(Common.ConnetionString))
        {
            connection.Open();
            SqlTransaction tran = connection.BeginTransaction();
            try
            {
                SqlCommand cmd = new SqlCommand(strSql, connection, tran);
                cmd.ExecuteNonQuery();
                tran.Commit();
            }
            catch (Exception e)
            {
                tran.Rollback();
            }
            finally
            {
                connection.Close();
                Response.Redirect("messagelist.aspx?flag=2");
            }
        }
    }

But how I should change code, that parameter work in loop

A: Your loop should probably encompass the entire block. Also, parameterize your query so you aren't left wide open to injection. Just a suggestion, but I would also use BEGIN TRANSACTION in your sql statement opposed to SqlTransaction tran, it will handle the rollback for you and clean up your code a bit.
string[] tos = txtTo.Text.Split(';');
for (int i = 0; i < tos.Length; i++)
{
    string strSql = "INSERT INTO test (test1, test2) VALUES (@Content, @DateTime);";
    using (SqlConnection connection = new SqlConnection(Common.ConnetionString))
    {
        connection.Open();
        SqlTransaction tran = connection.BeginTransaction();
        try
        {
            using (SqlCommand cmd = new SqlCommand(strSql, connection, tran))
            {
                cmd.Parameters.AddWithValue("@Content", txtContent.Text.Trim());
                cmd.Parameters.AddWithValue("@DateTime", DateTime.Now.ToString());
                cmd.ExecuteNonQuery();
                tran.Commit();
            }
        }
        catch (Exception e)
        {
            tran.Rollback();
        }
        finally
        {
            connection.Close();
            Response.Redirect("messagelist.aspx?flag=2");
        }
    }
}


text:
Q: different Database library with same methods in different flavours Best Practice? I have two different falvours in my Androdi app that should use different SQL implementations. One use:
android.database.sqlite.SQLiteDatabase

and second:
net.sqlcipher.database.SQLiteDatabase

I have methods like that:
getAll(SQLiteDatabase conn)

How should I solve this situation to avoid copy&paste? What is the best pratcice?
I have few ideas:
first one (the worst with a lot of copypaste) is to provide different methods :
 getAll(android.database.sqlite.SQLiteDatabase conn)
 getAll(net.sqlcipher.database.SQLiteDatabase conn)

second is to wrap this class with some other in every flavour importing proper database(aggregation, composition as SQLiteDatabase is final):
import android.database.sqlite.SQLiteDatabase;
public class SQLliteDatabaseFlavoured   {
     SQLiteDatabase sqLiteDatabase;
}

With usage:
getAll(SQLliteDatabaseFlavoured.SQLiteDatabase conn)

A: You can use the gradle buildVariant if you are using Android Studio
flavor1 -> packagename: com.example.flavor1
flavor2 -> packagename: com.example.flavor2

using this in your gradle script:
filter{
    String line -> line.replaceAll("<complete line of regular expression>",
                                   "<complete line of modified expression>")
}

How to replace a string for a buildvariant with gradle in android studio?
If not and you are worried about your app footprint or you want to ensure that the cipher library is only included when needed, then you should go with your Option #2 so that the compiler will remove the unused libraries. Option 1 will always include both libraries, which is unnecessary. Also, Option #2 gives you more flexibility if you ever change implementations (another SQLite product comes along).
From a "best practices" standpoint, you should consider maintenance and debug. Your first option guarantees that you will know exactly which library caused a problem. Otherwise, it must be very clear which flavor is being used or you are always provided a full stack trace when you receive a bug report. If you assume that both libraries are implemented in exactly the same way, then you have a testing nightmare doing either of the above if all you get is an error with a line number or less information. Even with a full stack trace, it may be difficult to debug issues and certainly not obvious to new people on the project. Also, from a best practices standpoint, ideally, you would not change out this type of dependency at all. But I understand that may not be possible.

A: ok I finally found solution based on @Jim's answer. Big Thanks!
It's not the cleanest but it wokrs.
I create two tasks to copy files
task copyNoEncryption << {
//copy to temp folder
copy {
    from("src/com/sql")
    into("src/temp/sql")
}
//copy back to correct folder and replace string's
copy {
    from("src/temp/sql")
    into("src/com/sql")

    filter {
 //you have to remember that first argument is REGEX and second is normal String
        String line ->
            line.replaceAll("before REGEX",
                    "after STRING")
    }
}
//delete temp folder
delete("src/temp")
}

and second task working analogously
task copyEncryption << {
//same body but reverse string swap
//REMEMBER in replaceAll 1st arg is REGEX and second is String
}

now I'm adding execution this task before respectively flavor
android.buildTypes.all{ theBuildType ->
tasks.whenTaskAdded{ theTask ->
    if(theTask.name == "generateFlavorWithoutEncryptionr${theBuildType.name.capitalize()}Sources"){
        theTask.dependsOn "copyNoEncryption"
    }
    else if(theTask.name == "generateFlavourWithEncryption${theBuildType.name.capitalize()}Sources"){
        theTask.dependsOn "copyEncryption"
    }
}
}

Now every time when I'm building flavor I have correct libraries.
Hope that someday this will help someone.


text:
Q: Count overall time between two timestamps per user Currently I'm stuck with some MySQL queries.
I have a table like this:
ID|USERID|USERNAME|STARTTIME|ENDTIME|COMMITTYPE

The users click buttons in a frontend -> Start <- and -> Stop <-.
This creates a db entry with their respective duties, starttime and endtime. So, each click on start creates a new row/entry in the db and will get finished by the click on the stop button.
My problem, is there a chance to count the overall time between the start time and the end time per user and commit type?

A: This probably work
SELECT USERID, COMMITTYPE, MIN(STARTTIME), MAX(ENDTIME),
SUM(TIME_TO_SEC(TIME_DIFF(ENDTIME - STARTTIME))/3600) hours FROM tablename
GROUP BY USERID, COMMITTYPE

A: Do you refer to something like this?
SELECT COMMITTYPE, USER, (ENDTIME - STARTTIME) AS ELLAPSED_TIME
FROM YOUR_TABLE GROUP BY COMMITTYPE, USERID;

A: SELECT DATEDIFF('new_date', 'old_date');

// eg

SELECT DATEDIFF('2006-04-01','2006-04-01');

IG GETTING USE LINUX
<?php

  // Set timezone
  date_default_timezone_set("UTC");

  // Time format is UNIX timestamp or
  // PHP strtotime compatible strings
  function dateDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Create temp time from time1 and interval
      $ttime = strtotime('+1 ' . $interval, $time1);
      // Set initial values
      $add = 1;
      $looped = 0;
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
        // Create new temp time from time1 and interval
        $add++;
        $ttime = strtotime("+" . $add . " " . $interval, $time1);
        $looped++;
      }

      $time1 = strtotime("+" . $looped . " " . $interval, $time1);
      $diffs[$interval] = $looped;
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
 break;
      }
      // Add value and interval
      // if value is bigger than 0
      if ($value > 0) {
 // Add s if value is not 1
 if ($value != 1) {
   $interval .= "s";
 }
 // Add value and interval to times array
 $times[] = $value . " " . $interval;
 $count++;
      }
    }

    // Return string with times
    return implode(", ", $times);
  }

?>

///
echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";

OUTPUT

6 years
  18 years, 11 months, 30 days, 23 hours, 59 minutes, 59 seconds 2
  months 6 years, 2 months, 10 days 4 years, 11 months, 30 days, 8
  hours, 21 minutes, 49 seconds


text:
Q: Octopus Deploy and VPN Does anyone know if its possible to deploy to a server in a VPN using Octopus Deploy?
If the tentacle is on the server in the VPN is there a way Octopus Deploy to connect/disconnect  to a VPN?
Cheers
UPDATE
We think we've found a work around by:

*

*Installing a tentacle on the same server as our Octopus is running on, then adding a first step that executes a Powershell script to create the VPN connection.

*The next step is then deploying the NuGet package to the tentacle server within the VPN.

*The final step is another Powershell script executed on the same tentacle server as the first step to close the connection

Early tests seem to show this works!
Kudos to my colleague Rachel for coming up with it!

A: There's no way to do this at the moment short of establishing the VPN connection yourself and then triggering the Octopus deployment using Octo.exe, followed by disconnecting.
In future it would be nice to have support for opening a VPN connection within Octopus. Is your VPN session established using the Windows remote access server components (i.e., would a toolkit like http://dotras.codeplex.com/ be able to open the connection?) or is it through some custom software?

A: You could use Hamachi for VPN - I decided to place any servers which are targets for deployment into a Hamachi group.
It's really simple to use and probably only useful for those who are not governed by strict IT policies etc.
But probably good for most.
See https://secure.logmein.com/products/hamachi/download.aspx


text:
Q: FileZilla public key not working (Successfully loaded 0 key pairs from file) I currently have troubles logging in with a public key using FileZilla.
Neither the root user, not an other user accept the key.
Now the strange thing is when using putty it is working without any troubles.
I do not have the slightest idea what the problem might be.
Things I checked:

*

*Connection to the server:
The server does receive the authentication attempt

*The key is located in ~/.ssh/authorized_keys

*The file permissions are correct (700 for ~/.ssh and 600 for ~/.ssh/authorized_keys)

*Using the same key with PuTTY. This is working!

*Password login over SFTP is working as well

*Trying a new key: Not working as well (PuTTY is accepting it without problems)
Logs:
PuTTY:
Event Log: Writing new session log (SSH packets mode) to file: PuTTY.log
Event Log: Looking up host "x.x.x.x"
Event Log: Connecting to x.x.x.x port 22
Event Log: Server version: SSH-2.0-OpenSSH_6.0p1 Debian-4+deb7u2
Event Log: Using SSH protocol version 2
Event Log: We claim version: SSH-2.0-PuTTY_Release_0.63_(file_config_0.6.1)
Event Log: Doing Diffie-Hellman group exchange
Event Log: Doing Diffie-Hellman key exchange with hash SHA-256
Event Log: Host key fingerprint is:
Event Log: ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx
Event Log: Initialised AES-256 SDCTR client->server encryption
Event Log: Initialised HMAC-SHA-256 client->server MAC algorithm
Event Log: Initialised AES-256 SDCTR server->client encryption
Event Log: Initialised HMAC-SHA-256 server->client MAC algorithm
Event Log: Reading private key file "C:\Program Files (x86)\Putty\PBS - Verknüpfungen\root.key.ppk"
Event Log: Offered public key
Event Log: Offer of public key accepted
Event Log: Sent public key signature
Event Log: Access granted
Event Log: Opening session as main channel
Event Log: Opened main channel
Event Log: Requesting X11 forwarding
Event Log: X11 forwarding enabled
Event Log: Allocated pty (ospeed 38400bps, ispeed 38400bps)
Event Log: Started a shell/command

FileZilla:
Status: Connecting to x.x.x.x...
Response:   fzSftp started, protocol_version=2
Command:    keyfile "C:\Program Files (x86)\Putty\PBS - Verknüpfungen\root.key.ppk"
Command:    open "root@x.x.x.x" 22
Trace:  Looking up host "x.x.x.x"
Trace:  Connecting to x.x.x.x port 22
Trace:  We claim version: SSH-2.0-PuTTY_Local:_Mar_29_2015_12:25:15
Trace:  Server version: SSH-2.0-OpenSSH_6.0p1 Debian-4+deb7u2
Trace:  We believe remote version has SSH-2 channel request bug
Trace:  Using SSH protocol version 2
Trace:  Doing ECDH key exchange with hash SHA-256
Trace:  Host key fingerprint is:
Trace:  ecdsa-sha2-nistp256 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx
Trace:  Initialised AES-256 SDCTR client->server encryption
Trace:  Initialised HMAC-SHA-256 client->server MAC algorithm
Trace:  Initialised AES-256 SDCTR server->client encryption
Trace:  Initialised HMAC-SHA-256 server->client MAC algorithm
Trace:  Successfully loaded 0 key pairs from file
Error:  Connection attempt interrupted by user

(The last message is caused by me pressing cancel after being asked for the password)

A: It's probably the umlaut in the path. The interface between FileZilla and the internal psftp process is not Unicode-enabled.
When I tried a path with diacritics, psftp didn't load the key either:
Trace:  Successfully loaded 0 key pairs from file

When I removed the diacritics, it worked:
Trace:  Successfully loaded 1 key pair from file
Trace:  Offered public key from "C:\path\key.ppk"


text:
Q: React validate input field using errors array I'd like to apply a few validation rules to an HTML input field, and add the error message to the errors state array each time the check doesn't go through.
<input
  name="email"
  type="email"
  value={ email }
  placeholder="Type your email address here..."
  onChange={ handleChange }
/>
<button
  className="Form_Submit"
  onClick={ handleSubmit }
>
  <i className="fas fa-arrow-right" />
</button>

handleSubmit() {
  const {
    values: {
    email = '',
    errors = []
  } = {}
} = this.state;

if (!validateEmailAddress(email)) {
  errors.push('Please provide a valid e-mail address');
}

if (isEmpty(email)) {
  errors.push('Email address is required');
  }
}

Updated:
if (!validateEmailAddress(email)) {
  this.setState({
    errors: [...errors, 'Please provide a valid e-mail address']
  });
}

if (isEmpty(email)) {
  this.setState({
    errors: [...errors, 'Email address is required']
  });
}

The following syntax doesn't take the number of component update times, therefore I end up with 4-8 messages each time I click the submit button. Are there ways to handle the input field validation in the errors array (to display all messages in the end) to push just a single value to an array, and then remove it?

A: I think you are missing setting state.
handleSubmit() {
  const {
    values: {
      email = '',
      errors = ''
    } = {}
  } = this.state;

  if (!validateEmailAddress(email) && !errors.contains('Please provide a valid e-mail address')) {
    errors.push('Please provide a valid e-mail address')
  }

  if (!!email && !errors.contains('Email address is required')) {
    errors.push('Email address is required');
  }

  setValues({...rest, errors});
  if (!errors.length) {
    doFunc(); //your expected function
  }
}

A: You can refer to this code https://www.codegrepper.com/code-examples/javascript/push+unique+values+in+array+javascript
const myArray = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(myArray)]; // ['a', 1, 2, '1']

Set in javascript stores unique values so it will be helpful. You can apply the below code
const errorSet = new Set([...this.state.errors]);
if (!validateEmailAddress(email)) {
  errorSet.add('Please provide a valid e-mail address');
}

if (isEmpty(email)) {
  errorSet.add('Email address is required');
}
this.setState({
   errors: [...errorSet]
});


text:
Q: WPF creating multiple groups of controls Let's say I have five textboxes and five checkboxes next to them.
Now I want to create x groups of controls like that, then bind it with a list of objects that will contain text from textboxes and data on if checkboxes were checked.
What's the common approach for things like that?
I started with writing a function that would loop x times creating new RowDefinition inside an existing Grid, then inside that Row, make another Grid, inside that Grid create five rows and two columns, and add all those controls, set their rows, columns, add binding etc but I think it can't be the right way to do this, it's too much of a hassle writing all of that. There must be a better way.

A: You can achieve this functionality using a ItemsControl and Defining Datatemplate for the Items. Refer the below code. I taken an example of 3 TextBoxes and Checkboxes.
<StackPanel>
    <ItemsControl x:Name="itms">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBox Width="50" Text="{Binding Text1}" Grid.Row="0" Grid.Column="0"/>
                    <CheckBox IsChecked="{Binding Check1}" Content="Check1" Grid.Row="0" Grid.Column="1"/>
                    <TextBox Width="50" Text="{Binding Text2}" Grid.Row="1" Grid.Column="0"/>
                    <CheckBox IsChecked="{Binding Check2}" Content="Check2" Grid.Row="1" Grid.Column="1"/>
                    <TextBox Width="50" Text="{Binding Text3}" Grid.Row="2" Grid.Column="0"/>
                    <CheckBox IsChecked="{Binding Check3}" Content="Check3" Grid.Row="2" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    <Button Click="Button_Click" Content="Add Items"></Button>
</StackPanel>

public partial class Window2 : Window
{
    ObservableCollection<MyClass> lst = new ObservableCollection<MyClass>();
    public Window2()
    {
        InitializeComponent();
        itms.ItemsSource = lst;

    }
    int i = 0;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        i++;
        lst.Add(new MyClass() { Text1 = i.ToString(), Text2 =i.ToString()+1,Text3=i.ToString()+2,Check1=true,Check2=true,Check3=false});
    }
}

class MyClass
{
    public string Text1 { get; set; }
    public string Text2 { get; set; }
    public string Text3 { get; set; }
    public bool Check1 { get; set; }
    public bool Check2 { get; set; }
    public bool Check3 { get; set; }
}


text:
Q: SQLAlchemy subqueries ,do they apply in this scenario I have been reading a lot about SQLAlchemy subqueries and somehow i think somehow it applies to my problem .
I have the following 2 queries
Query 1=>isp_ratings_per_service = db.session.query(func.count(Ratings.ratings_value).label('count_of_users'),
                                               func.sum(Ratings.ratings_value).label('sum_of_ratings'),
                                               func.avg(Ratings.ratings_value).label('avg_of_ratings'),
                                               Isps.isp_name, Service_metric.metric_name, Services.service_name) \
        .filter(Service_metric_ratings.isp_id == Isps.isp_id) \
        .filter(Service_metric_ratings.ratings_value == Ratings.ratings_value) \
        .filter(Service_metric_ratings.metric_id == Service_metric.metric_id) \
        .filter(Service_metric_ratings.user_id == User.user_id) \
        .filter(Service_metric_ratings.service_id == Services.service_id) \
        .filter(Service_metric.metric_name == metric_name) \
        .filter(Services.service_name == service_name) \
        .group_by(Isps.isp_name)

Query 2 => ratings_table_values = db.session.query(Ratings.rating_value, Ratings.rating_comment)

I want to use the values stored in this line
func.avg(Service_metric_ratings.ratings_id).label('avg_of_ratings'),

to select data in another table based on this value like this
for i in isp_ratings_per_service:
    (round(i.avg_of_ratings)))
    ratings_table_values = Ratings.query.filter_by(rating_value=(round(i.avg_of_ratings)))

is it possible to put them in one query using a subquery ,the problem at the moment is that it creates 2 iterations in the flask template which is not giving me the results i want as below
 {% for i in ratings_table_values %}

  {{ i.rating_value}}
  {{ i.rating_comment}}
 {% endfor %}

{% for i in isp_ratings_per_service %}
blah blah blah
{% endfor %}

I would prefer if one query would give me the results i want ,

A: I managed to fix my own question like this , the queries are seperate with no need for Joins and its working perfectly. I have developed my logic in Jinja
{% for i in isp_ratings_per_service %}
  {{ i.isp_name }}
  {{ i.metric_name }}
  {{ i.service_name }}
  {{ i.count_of_users }}
  {{ i.sum_of_ratings }}
  {{ i.avg_of_ratings|round|int }}
         {% for m in ratings_table_values %}
            {% if (m.ratings_value) ==(i.avg_of_ratings|round|int)%}
                 {{ m.ratings_comment}}
            {% endif %}
         {% endfor %}

  {% else %}

No entries here so far

  {% endfor %}


text:
Q: If $f'(x)\geq c$ then $f$ is both one one and onto. If  $f:\mathbb{R}\rightarrow \mathbb{R}$ be a  continuously differentiable function with the property that there is some positive number $c$ such that for every $x\in\mathbb{R}$ $$f'(x)\geq c$$ then $f$ is both one one and onto. Strictly increasing condition gives that $f$ is one one function. How to prove onto? Please help. Thanks a lot.

A: By mean-value theorem, $a<b$
$$\displaystyle f(b)-f(a)=(b-a)f'(d)$$
$$\displaystyle \geq c(b-a) >0$$
Therefore f(x) is increasing and continuous, one one and onto.

A: You have $f(y) = \int_x^y f'(t) dt \ge c(y-x)$ hence $\lim_{y \to \infty} f(y) = \infty$.
If $y < x$ then $f(y) = - \int_y^x f'(t) dt \le -c(x-y)$ and
hence $\lim_{y \to -\infty} f(y) = -\infty$.


text:
Q: objectContext life scope Today I came across in an issue that I can't explain exactly the reason, so I think the better is to share it via stackoverflow.
Well, I have an mvc 3 application with .net entities and I tried to insert in db a huge string and this produced a sqlExeepton "string or binary data would be truncated". Ok up to here, I will fix it later :).
After this issue, I tried to update the same entity by a single value (in fact I increased a counter) and got again the same exception. That socked be a bit.
If I dispose the objectContext at the end of each method or I if create a new objectContext at the start of each method the problem will be solved.
What I can not understand is how does the objectContext reacts if it get initialized in the class instead of a method
public class MyController : BaseController {

    private static EFUnitOfWork efUnitOfWork = new EFUnitOfWork();
    Products_Repository productsRepos = new Products_Repository(new EFRepository<Products>(), efUnitOfWork);
..
//methods
..
}

Thanks in advance

A:
how does the objectContext reacts if it get initialized in the class?

You will have one instance which lives as long as your controller class lives. And that will match the lifetime of one http request and thats the recommended lifetime when coding web apps.
So you get a fresh context for every single request and have not to bother with some old state  stored in an old context object.


text:
Q: Why does calling a method via a pointer end up with a different result than calling via the method directly? In the example following, I'm calling an instance method of a View using the method directly (saveTitle), and via a pointer to that method (saveAction).
When calling the method, I am passing in the current value of the title variable.
When I call it directly, the current value matches the value inside the method.
When I call it via a pointer to the method, the value inside is the value it was when the struct was first instantiated.
It is almost like there is a new instance of the Struct being created, but without the init method being called a second time.
I suspect this has something to do with how SwiftUI handles @State modifiers, but I'm hoping someone out there will have a better understanding, and be able to enlighten me a bit.
Thanks much for your consideration :)
import SwiftUI

struct EditContentView: View {
  @Binding var isPresented: Bool
  @State var title: String
  var saveAction: ((String) -> Void)?

  var body: some View {
    TextField("new title", text: $title)
      Button("save") {
          print("calling saveText")
          // this call works as expected, the title inside the saveTitle method is the same as here
          saveTitle(title)
          print("now calling saveAction, a pointer to saveTitle")
          // with this call the title inside the method is different than the passed in title here
          // even though they are theoretically the same member of the same instance
          saveAction!(title)
          isPresented = false
      }
  }

    init(isPresented: Binding<Bool>, title: String) {
        print("this method only gets called once")
        self._isPresented = isPresented
        self._title = State(initialValue: title)
        saveAction = saveTitle
    }

    func saveTitle(_ expected: String) {
        if (expected == title) {
            print("the title inside this method is the same as before the call")
        }
        else {
            print("expected: \(expected), but got: \(title)")
        }
    }
}

struct ContentView: View {
  @State var title = "Change me"
  @State var showingEdit = false
  var body: some View {
    Text(title)
      .onTapGesture { showingEdit.toggle() }
      .sheet(isPresented: $showingEdit) {
          EditContentView(isPresented: $showingEdit, title: title)
      }
  }
}

A: I don't think this is related to @State. It is just a natural consequence of structs having value semantics, i.e.
struct Foo {
    init() {
        print("This is run only once!")
    }

    var foo = 1
}

var x = Foo() // Prints: This is run only once!
let y = x // x and y are now two copies of the same *value*
x.foo = 2 // changing one of the copies doesn't affect the other
print(y.foo) // Prints: 1

Your example is essentially just a little more complicated version of the above. If you understand the above, then you can easily understand your SwiftUI case, We can actually simplify your example to one without all the SwiftUI distractions:
struct Foo {
    var foo = 1
    var checkFooAction: ((Int) -> Void)?

    func run() {
        checkFoo(expectedFoo: foo)
        checkFooAction!(foo)
    }

    init() {
        print("This is run only once!")
        checkFooAction = checkFoo
    }

    func checkFoo(expectedFoo: Int) {
        if expectedFoo == foo {
            print("foo is expected")
        } else {
            print("expected: \(expectedFoo), actual: \(foo)")
        }
    }
}

var x = Foo()
x.foo = 2 // simulate changing the text in the text field
x.run()

/*
Output:
This is run only once!
foo is expected
expected: 2, actual: 1
*/

What happens is that when you do checkFooAction = checkFoo (or in your case, saveAction = saveTitle), the closure captures self. This is like the line let y = x in the first simple example.
Since this is value semantics, it captures a copy. Then the line x.foo = 2 (or in your case, the SwiftUI framework) changes the other copy that the closure didn't capture.
And finally, when you inspect what foo (or title) by calling the closure, you see the unchanged copy, analogous to inspecting y.foo in the first simple example.
If you change Foo to a class, which has reference semantics, you can see the behaviour change. Because this time, the reference to self is captured.
See also: Value and Reference Types

Now you might be wondering, why does saveAction = saveTitle capture self? Well, notice that saveTitle is an instance method, so it requires an instance of EditContentView to call, but in your function type, (String) -> Void, there is no EditContentView at all! This is why it "captures" (a copy of) the current value of self, and says "I'll just always use that".
You can make it not capture self by including EditContentView as one of the parameters:
// this doesn't actually need to be optional
var saveAction: (EditContentView, String) -> Void

assign it like this:
saveAction = { this, title in this.saveTitle(title) }

then provide self when calling it:
saveAction(self, title)

Now you won't get different copies of self flying around.


text:
Q: QOOXDOO extend - Не наследуются static свойства Доброго времени суток. Возник вопрос интересный.
Есть флеймворк qooxdoo. При создании дочернего класса не наследуются statics свойства родителя. Что может быть не так ?
пример:
qx.Class.define('sdf.items.BaseItem', {
   extend: qx.core.Object,
   statics: {
      TEST: 1
   }
});

qx.Class.define('sdf.items.ChildItem', {
   extend: sdf.items.BaseItem
});

sdf.items.ChildItem.TEST //undefined

Может быть, кто-нибудь сталкивался ?
P.S. Пробовал юзать Mixins и т.д. - проблема остается.
A: http://manual.qooxdoo.org/1.4/pages/core/oo_feature_summary.html

Note Static members aren't inherited. For calling a superclass static method, use this.superclass, like in this example:

qx.Class.define('A', {
  statics: {
     f: function() {}
  }
});

qx.Class.define('B'), {
  extend: A,
  members: {
     e: function() {
        this.superclass.self(arguments).f();
     }
  }
});

Static functions can access other static functions directly through the this keyword.

Говоря по русски static не наследуется (остается в базовом классе), чтобы получить доступ к static надо использовать доступ до родительского класса через свойство superclass
qx.Class.define('sdf.items.BaseItem', {
   extend: qx.core.Object,
   statics: {
      TEST: 1
   }
});

qx.Class.define('sdf.items.ChildItem', {
   extend: sdf.items.BaseItem
});

console.log(sdf.items.ChildItem.superclass.TEST); //1


text:
Q: popup problem : not showing proper corresponding content iterating over an array, am printing some div content for each iteration.
Whenever the user clicks on any div content, a popup should appear and should show the corresponding content in the popup from the array.
below is my code,
foreach ($email as $client)
{

                echo "
 Show more.......
";
                echo "
";
                echo $client['Email']['body'];
                echo "
";

}

javascript code below
jQuery(document).ready(function(){

jQuery('.t').click(function(e)
{
  var height = jQuery('.popup_msg').height();
  var width = jQuery('.popup_msg').width();
  leftVal=e.pageX-(width/1.5)+"px";
  topVal=e.pageY-(height/13)+"px";

  jQuery('.popup_msg').css({left:leftVal,top:topVal}).show();
});

jQuery('.popup_msg').click(function(e)
{
jQuery('.popup_msg').fadeOut('fast');
});

});

in the above codes, what i want to achieve is, whenever the user clicks on the div with class t, the corresponding $client['Email']['body'] should appear in the popup

A: The problem is that your selector matches all .popup_msg, not only the one you need. Use the find() method to get the correct popup in the $('.t').click function:
jQuery('.t').click(function(e)
{
      var popup_msg = jQuery(this).find('.popup_msg');
      var height = popup_msg.height();
      var width = popup_msg.width();

      leftVal=e.pageX-(width/1.5)+"px";
      topVal=e.pageY-(height/13)+"px";

      popup_msg.css({left:leftVal,top:topVal}).show();
});

Note: I haven't tested this code, it might not be 100% correct but hopefully you get what I mean.


text:
Q: Eclipse Android error when building dx.jar and traceview.bat I know there are a multitude of questions across various forums that touch on this issue but nothing has helped thus far.
I use Eclipse Photon for my IDE.
I installed the Android SDK via Android Studio.
I recently moved to a new machine and since then I get these errors when trying to build the project. Actually, the first image occurs when I first open Eclipse. The second image is what I see when building (I cleaned beforehand).

Many solutions suggest reinstalling platform tools/build tools/the entire SDK etc.
So, I did this:
1) Closed down Eclipse
2) Opened Android Studio and went to SDK Manager
3) Unchecked and uninstalled all the options highlighted in the images below.
4) Once uninstalled I restart Android Studio and reinstalled all of them.
5) The errors noted at the start of this post persist.

Any ideas what I can try next? It seems every machine move/upgrade causes build issues. It's the main reason I dislike coding for phones, it's not the coding, it's the dev environments!


text:
Q: Finding matching suggestions with multiple records from different "users" I'm not even entirely sure how to phrase my question because it is rather complicated. I am trying to implement a feature that will help crowd source information for one of our systems, and the system should validate these "suggestions" automatically. There are certain criteria that determine a "valid" suggestion:

*

*3 suggestions

*3 different "users"

*Same combination of "adaptors"

For example, Tom works for Acme Co. and suggests using Adaptor A + Adaptor B for this particular scenario. Likewise, Jon works for Acme Inc. and suggests the same Adaptor A + Adaptor B for this particular scenario. Finally, Bob works for Acme Enterprises, and he too suggests the same Adaptor A + Adaptor B for this particular scenario.
Upon Bob submitting his suggestion, the system would be able to determine that there are 2 matching suggestions from 2 different companies, constituting a valid suggestion, and would then perform some action (this action is outside of the scope of this issue).
What I have done so far is create a table to store suggestions:
id
user_id
vehicle_id
service_id
Each suggestion may have one or more "adaptors" so I am using a pivot table:
suggestion_id
adaptor_id
Finally, because we are really concerned about the "company" the user works for (remember suggestions are only considered valid if they come from 3 different companies), so I have composed a view to join this information:
suggestion_id
user_id
company_id
vehicle_id
service_id
adaptor_id
Here is an example of what some of this data would look like:

The highlighted rows a potentially valid suggestion, with the exception that the suggestions from company 58 should only be counted as 1 suggestion because they come from the same company. Furthermore, suggestion 87 only contains 1 of the adaptors found in the other 2 matching suggestions. If suggestion 87 included both adaptor id 669 and 936, these suggestions would be considered valid.
My question is how to query this information? I currently am trying something like this:
select distinct
`company_id`,
`vehicle_id`,
`service_id`,
`adaptor_id`
from `service_guide_suggestions`
where `user_id` != 2
and `company_id` != 1
and `vehicle_id` = 30149
and `service_id` = 3
and `adaptor_id` in (669,936)

I need to be able to answer some question as "Do we have at least 3 suggestions for the same vehicle and service, from 3 different companies, with matching adaptors?"
My apologies if my question is not clear or is lacking enough information. I'm happy to provide as many details as possible for any feedback. Many thanks!
UPDATE
Trying danblack's suggestion yields these results:


text:
Q: What could be the cause of a limit in the voltage supplied to a capacitor? Recently I built a very basic 2-stage coil gun for a school project. Each coil was powered by an electrolytic capacitor. In order to charge the capacitor, the coil connected to an IGBT (insulated-gate bipolar transistor). I controlled that would block the current during charging. When I wished to shoot the coil I would use an Arduino to open the IGBT and then discharge the capacitor through the coil. There was also a diode to help protect the IGBT but I don't believe this was the source of the problem I faced. I also later learned that my diode didn't properly protect my IGBT, I am aware of my mistake in that regard and am only including it incase this is somehow the source of my problem. My capacitor was rated for 80 volts and had 0.1 farads of capacitance. I charged it to 70 volts to be safe but after the first discharge I was unable to charge it past 36 volts. After a decent amount of analysis I could not find a reason why this happened so I tried charging and discharging more times to see if I could find a pattern but it would simply plateau at arbitrarily low voltages without any clear pattern. I also noticed that when taken off the charger it would very slowly but noticeably leak voltage. After speaking to my professor about it, he theorized that I damaged the capacitor due to the fast discharge but I was wondering if there is another possible reason I hit certain voltage plateaus or how to avoid this problem in the future if this is the reason. Below is a picture of my circuit of one coil(the two coils are isolated but follows the same set up).

A: I think that it is $\text{rapidly changing current} \Rightarrow \text {large emf in opposition to change}$.
So what you need is a reverse biased diode across the coil.
How to make an Electromagnetic Coil Gun explains what to do with the circuit as below

In the video at about 0:30 the statement "here with a diode to release the reverse current" is made.


text:
Q: Error in Skeletonization and Skeleton Pruning I was trying to run the skeletonization and skeleton pruning software from
skeletonization and skeleton pruning
and getting the following errors. I used matlab 2015a .Authors claimed that it runs on matlab 7.0. Please help me to correct it.i just want to see the output. Anyone can suggest a pseudocode for Skeletonization and Skeleton Pruning in simple way?
Error in SkeletonGrow1 (line 42)
                skltn(i,j) = CheckSkeleton1(bw,dist,lab,i,j,ro,mark);

Error in div_skeleton_new (line 51)
bw=SkeletonGrow1(I0,ro,mark);

Error in Test (line 6)
[bw,I0,x,y,x1,y1,aa,bb]=div_skeleton_new(4,1,bw,15);

A: first two errors are due to same function (CheckSkeleton1). The number of arguments are different in both calls. Tweek it, do check readme file or contact author.


text:
Q: AuthLogic one time password (persistence_token) - what config is required to use this? Can anyone confirm what config exactly is required to make the one time password (persistence_token) work?
From what I can work out so far it is the following, however this isn't working for me so I must be wrong:

*

*pass an additional URL parameter of "user_credentials=xxxxpersistence_tokenxxxx"

*question - are there any other URL parameters required beyond this?  any user id or username?

*have the persistence_token field in my database table (which it is and I can see it populated)

*have "acts _as _authentic " in my user model per normal

*question: is "acts _as _authentic " required in each of my own models?

When I enter a URL in the browser directly to one of my own model resources following the above I see in the logs:
(a) initial request - Redirected to http://localhost:3000/user_session/new
(b) and then for this redirect:
Processing UserSessionsController#new (for 127.0.0.1 at 2009-12-03
06:14:24) [GET]
  Parameters: {"action"=>"new", "controller"=>"user_sessions"}
  User Columns (3.4ms)   SHOW FIELDS FROM `users`
  User Indexes (0.9ms)   SHOW KEYS FROM `users`
Rendering template within layouts/application
Rendering user_sessions/new
  SQL (0.6ms)   SELECT count(*) AS count_all FROM `users` WHERE
(last_request_at > '2009-12-02 20:04:24')
Completed in 182ms (View: 151, DB: 5) | 200 OK [http://localhost/
user_session/new]

(c) But then the web-page ends up on the login page, and not
automatically on the page I was after - i.e. I was expecting that the
one-time password would allow AuthLogic to automatically do the
session and then authentication?
Thanks
PS. Wonder if it related to this authlogic code I found in params.rb
def single_access_allowed_request_types(value = nil)
  rw_config(:single_access_allowed_request_types, value, ["application/rss+xml", "application/atom+xml"])
end

A: I think I have have it now. I did:

*

*Pass the parameter (not header) of user_credentials=<>

*Have the single_access_token column in your users table

*Put the following method in the users_controller:

private
  def single_access_allowed?
    true
  end

*

*For other controllers (i.e. besides application, user, user_sessions)
I put: "before_filter :require_user"  (not sure if there's a way to do this in the
controller that would handle it automatically?)

thanks


text:
Q: Dynamic array creation in perl I have read this post and saw that there are various ways to create a dynamic naming of arrays in perl.
http://en.allexperts.com/q/Perl-CGI-1045/dynamic-naming-array-1.htm
as per the link, the code will create dynamic arrays like these:
@yearsSoFar2004,
@yearsSoFar2005,
@yearsSoFar2006 etc.

My requirement is as follows. I want to create a dynamic array like this:
my @a0=();
my @a1=();
my @a2=();
my @a3=();

I currently have it static in my code but i want to make it dynamic. Here is the static code below. Please help me guys. I am a newbie to PERL
my @a=();
my @b=();
my @c=();
my @d=();

A: Three problems with your request:

*

*my declares a lexical variable at compile-time, so asking to pass a name to my at run-time makes no sense.

*Symbolic references can't be used to access lexical variables.

*It's a stupid thing to do.

A:
My requirement is as follows. I want to create a dynamic array like this:
my @a0=();
my @a1=();
my @a2=();
my @a3=();

As I have said before, "When you find yourself adding an integer suffix to variable names, think I should have used an array."
So, instead, use
my @data = (
    [ ... ],
    [ ... ],
    [ ... ],
);

If you wanted index each year's data array by the year (instead of integers 0, 1, 2, ..., n), then use a hash:
my %data = (
    2005 => [ ... ],
    2006 => [ ... ],
    2007 => [ ... ],
);

What you have now is compounded stupidity. Don't do that.


text:
Q: Error when trying to chain class method in controller in Ruby on Rails I am trying to chain a few class methods from my User model to perform a faceted search. When the code runs it returns the following error
undefined method `has_skill_categories' for #<Array:0x000001026d3de8>

Can you show me how to call these methods from the model in the controller by chaining them together?
Here is my code:
experts_controller.erb
class ExpertsController < ApplicationController
  layout 'experts'

  def index

    @users = User.text_search(params[:query])
              .has_marketing_assets(params[:marketing_platforms])
              .has_skill_categories(params[:skills])
              .search_for_user_country(params[:user][:country])
  end

  def show
    @user = User.find(params[:id])
  end
end

user.erb
class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :marketing_assets
  has_many :marketing_platforms, through: :marketing_assets
  has_many :my_skills
  has_many :skills, through: :my_skills
  has_many :past_works
  has_many :past_work_types, through: :past_works

  validates :first_name, :last_name, presence: true

  include PgSearch
  pg_search_scope :search, against: [:first_name, :last_name, :company, :description, :job_title, :website, :email, :country, :city, :state],
                  using: {tsearch: {dictionary: 'english'}},
                  associated_against: {:skills => :name, :past_works => [:description, :title, :url], :marketing_assets => [:platform, :description, :url], :past_work_types => :name,
                                       :marketing_platforms => :name}

  def self.text_search(query)
    if query.present?
      search(query)
    else
      User.all
    end
  end

  def self.has_marketing_assets(platforms)
    if platforms.present?
      @platforms = MarketingPlatform.all
      platforms_count = platforms.count
      where_clause_platforms = 'SELECT *
                                FROM Users
                                WHERE Users.id IN
                                (SELECT Users.id
                                FROM users
                                INNER JOIN marketing_assets ON users.id = marketing_assets.user_id
                                WHERE marketing_assets.marketing_platform_id= '
      n = 0

      if platforms.count > 0

        platforms.each do |platform|
          n += 1
          where_clause_platforms = where_clause_platforms + platform
          if n < platforms_count
            where_clause_platforms = where_clause_platforms + ' OR marketing_assets.marketing_platform_id= '
          end
        end

        where_clause_platforms = where_clause_platforms + " GROUP BY users.id
                                                          HAVING COUNT(DISTINCT marketing_assets.marketing_platform_id) = #{platforms.count})"
        find_by_sql(where_clause_platforms)

      else
        return
      end
    end
  end

  def self.has_skill_categories(skills)
    if skills.present?

      skills_count = skills.count
      where_clause_skills = 'SELECT *
                                      FROM Users
                                      WHERE Users.id IN
                                      (SELECT Users.id
                                      FROM users
                                      INNER JOIN my_skills ON users.id = my_skills.user_id
                                      WHERE my_skills.skill_id= '
      n = 0

      if skills_count > 0

        skills.each do |skill|
          n += 1
          where_clause_skills = where_clause_skills + skill
          if n < skills_count
            where_clause_skills = where_clause_skills + ' OR my_skills.skill_id= '
          end
        end

        where_clause_skills = where_clause_skills + "GROUP BY users.id
                                                        HAVING COUNT(DISTINCT my_skills.skill_id) = #{skills.count})"
        find_by_sql(where_clause_skills)

      else
        return
      end
    end
  end

  def self.search_for_user_country(country)
    if country.present?
      where('country = ?', "#{country}")
    else
      return
    end
  end

end

A: First off, in order to chain your methods, you should be returning an ActiveRecord query object. Calling return without an argument will return nil, which is not chainable. You should instead return where(), which would return the current collection with no modifications.
The reason you are getting the error above is because find_by_sql returns results as an array, not a scoped query like where does. So, as you are doing it now, I don't think there's a way to chain them. But that's probably a good thing because it will force you to rewrite your queries and scopes without raw sql statements.
I would highly recommend reviewing the Rails Guides on Active Record Querying, and avoid writing raw SQL statements if at all possible in a Rails project. This could greatly simplify your methodology. You should never put raw user input into SQL queries, which it looks like you are doing in multiple places in your code. Rails provides an advanced query interface to protect you and your data, and the SQL statement you are building above is extremely vulnerable to injection attacks.
With the correct combination of scope and association calls (which can use scopes defined on the associated model), you could probably clean a lot of that code up and greatly improve the security of your application.
Update
It looks to me like your queries could greatly be simplified using scopes and #merge.
def self.has_skill_categories(skill_ids)
  joins(:my_skills).merge Skill.where(id: skill_ids)
end

def self.has_marketing_assets(platform_ids)
  joins(:marketing_assets).merge MarketingAsset.where(marketing_platform_id: platform_ids)
end

Those may not get you exactly what you're going for, but from what I can tell, it should be close, and show you how you can use the built-in ActiveRecord query interface to build complex queries without ever writing any raw SQL.


text:
Q: Changing DefaultTask (Entry Point) in Windows Phone App According to Microsoft template the entry point of Windows Phone app is MainPage.xaml. I manage to change it to *.xaml page, but how to get rid of those .xaml pages and write only C#. In windows Forms it was quite easy, but what about Windows Phone ? If I just change the default task to be .cs file, it doesn't run.

A: Unlike in WinForms there is no concept of an application's main entry point not corresponding to a visual page represented by XAML (in this case, as you pointed out, the default is MainPage.xaml). The idea being that this wouldn't make sense since there always has to be a visual portion to a Phone application. While you could potentially write the same thing purely in code it's not something that is directly supported.
An application has the ability to run in the background via Background Agents (see http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx), but it still needs the visual portion of the application to install the Agent and to be accepted onto the Store.


text:
Q: InputStreamReader vs FileReader I can't seem to determine any difference between InputStreamReader and FileReader besides the way the two are initialized. Is there any benefit to using one or the other? Most other articles cover FileInputStream vs InputStreamReader, but I am contrasting with FileReader instead. Seems to me they both have the same purpose.

A: FileReader reads character from a file in the file system. InputStreamReader reads characters from any kind of input stream. The stream could be a FileInputStream, but could also be a stream obtained from a socket, an HTTP connection, a database blob, whatever.
I usually prefer using an InputStreamReader wrapping a FileInputStream to read from a file because it allows specifying a specific character encoding.

A: First, InputStreamReader can handle all input streams, not just files. Other examples are network connections, classpath resources and ZIP files.
Second, FileReader until Java 11 did not allow you to specify an encoding and instead only used the plaform default encoding, which made it pretty much useless as using it would result in corrupted data when the code is run on systems with different platform default encodings.
Since Java 11, FileReader is a useful shortcut for wrapping an InputStreamReader around a FileInputStream.

A: FileReader extends InputStreamReader.  The only differences is that FileReader has constructors which assume you are reading from a file such as String filename, File file and FileDescriptor fd
I suggest you have a look at the source for FileReader to know more.


text:
Q: running selenium junit4 test suite tests multiple times I have a test suite.  I'd like to execute this entire test suite 1000 times.  I have googled and looked everywhere and I can't seem to figure this out.  Any help would be greatly appreciated!!  If it would be easier to switch to testng, I will.
package com.bpms.tests;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
                InitiateBuyPlan.class,
                AddItemsToBuyPlan.class,
                ReviewBuyPlan.class,
                ApproveBuyPlan.class,
                ManageQuoteSolicitation.class,
                StartQuote.class,
                ReviewQuote.class,
                RecordInterestInQuotes.class,
                ReviewCountryBuyIn.class,
                CompleteItemInfo.class,
                ReviewItemInformation.class,
            })
public class SuiteAllTests
{

}

A: You will have to build the test case programatically than via annotations
import org.junit.runners.AllTests;
import junit.framework.TestSuite;
import junit.framework.Test;

@RunWith(AllTests.class)
public final class SuiteAllTests {

  public static TestSuite suite() {
    TestSuite suite = new TestSuite();
    for (int i= 0; i<1000; i++) {
      suite.addTest(new JUnit4TestAdapter(XXX.class));
      suite.addTest(new JUnit4TestAdapter(YYY.class));
    }
    return suite;
  }
}

Just replace XXX and YYY with the classes you have in your annotations.


text:
Q: Relatively Positioned Anchor (IE Woes) I am positioning an anchor like so:
#test-link {
    position: relative;
    bottom: 100px
}

As I need it so that when I visit #test-link the page jumps down to that particular section, but 100px higher. Otherwise the page scrolls too far down for what I need.
This works fine in decent browsers, however in IE7, 8 and 9 the relative positioning gets completely ignored.
I've tried different ways to fix it such as adding text to the anchor as well as various CSS properties (e.g. display: block) however nothing makes any difference.

A: Sure enough, IE7 through IE10 don't go to the relatively-positioned element (but rather to its natural location). There is one exception, IE8 worked just as I had expected. Nearly every browser I checked other than IE worked as expected as well.
This appears to be an issue with relative positioning, as attempting this with absolute positioning works just fine in IE6 through IE10. This of course doesn't help your situation since you're trying with relative positioning.
The only solution I have found after playing around with this for a while is to replicate relative positioning using margins:
#movedElement {
    display: block;
    margin: -100px 0 100px;
}

This gave smiliar results to those we see in other browsers, in all versions of IE. This isn't ideal, I understand, but it may suffice until better information is found.
I'll continue to research this, and return when I learn more.
You Could Use padding for Padding
In the meantime, another common approach to adding some whitespace before your target-area is to add margins to expand the space above that element. This is what I've done in the example viewable online at http://jsfiddle.net/Px6r9/1/show/#foo.

#paddedContent {
    padding-top: 50px; /* Adds whitespace above content */
}