text:
Q: How to completely remove the canvas element with Jquery/JavaScript? I have a canvas object that loads on my page dynamically from a jQuery plugin. It has no wrapper, no id or class associated to it.  But I need to remove it after
$(window).resize(function)() {...}

takes place.  I have tried using jQuery's
...next().remove();

technique, so that the neighboring div element can remove it from the DOM, but I am getting issues. specifically, additional elements on my page are also getting removed.  Is there a healthy way to about this?
Thanks!

A: How many canvas elements do you have on the page?  If there is only one; and you don't plan to ever add any in the future it might be simplest just to do
var dynamic_canvas = $('canvas');
if(dynamic_canvas) dynamic_canvas.remove();

A: If you are not using multiple canvas elements, simply
$('canvas').remove();

Will remove all matched elements on the page. http://jsfiddle.net/vj6NP/
If you do have multiple canvas on the page and would like to remove only one, you could select which one to remove using nth-of-type.
For example to remove the first instance http://jsfiddle.net/vj6NP/3/: -
$('canvas:nth-of-type(1)').remove();

A: The easiest way is to keep a reference to the canvas element added to the document then remove it using JQuery:
this.canvas = document.createElement('canvas');
//later...
$(this.canvas).remove();


text:
Q: Split git repository in two? Nearly a year ago, I started writing a game. I was just messing around at the time, but now I'm pretty serious about it. As it's grown, it's taken on the responsibilities of a major game engine, as well as the game logic of an actual game.
At some point, I decided I should break the two out, and designate a game and a game engine. I kept this separation in mind as I programmed for about the last 8 months, but I never did actually separate them.
Now I intend to finally move forward with this. The project is all in one git repository right now. I'd like to have two repositories; one for the game engine and one for the game.
I have two concrete questions:
1) How should I split the repository? I'd like to maintain history, so I'm thinking I'll just cp the repository, prune the two, and then check in. Any better ideas?
2) Should I add my game assets (models, images, sounds..) to the game repository, or should I make a third for these? I have quite a few assets, and many are subject to change, so it could create an inconvenient amount of noise.

A: As for #1, git provides some tools to make that very easy to do. For #2, I'd suggest a 2nd repository to keep your history clean and useful. You can pull it into your main working tree easily with git submodules.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add a test runner to playwright in docker I am starting using playwright, I have pulled the docker image and I am wondering how should I run tests. I have followed some old messages in playwright slack and run this command :
 docker run -d -it --rm -v /C/Workspace/playwrite/src/test/java/org/example/TestExample.java:. --ipc host --shm-size 2gb mcr.microsoft.com/playwright/java:v1.14.0-focal

The container has started, the test has been moved in docker but I don't think it has been run. My question is does the docker playwright has already a test runner such as junit? If nor do I have to modify the docker image? I don't find any docs that explain that.

A: The way it works is to run the Playwright image, which then provides you with  an environment to setup and run Playwright
# run in the root of your Playwright project
docker run -v $PWD:/e2e -w /e2e --rm -it mcr.microsoft.com/playwright:v1.16.2-focal /bin/bash

# you are now inside the container (bash)
root@f4cfe077964d:/e2e# npm install
root@f4cfe077964d:/e2e# npx playwright install
root@f4cfe077964d:/e2e# npx playwright test

More details about using the Playwright Docker image here


text:
Q: PIV smartcard from browser how it works for authentication without applet Reading smartcard keystore from  browser for digital signature vs using it for authentication, why for digital signature keystore  we have to use applet (run some code on client machine to read the key)  vs for authentication browsers reads the keys without any  applet or plugin etc.How smartcard lists smart card keys without any javascript or applet code.

A: digital signature functionnality is not yet implemented in web browsers APIs. A standard API is under work: WebCrypto. See http://www.w3.org/TR/WebCryptoAPI for an overview and more specifically http://www.w3.org/TR/WebCryptoAPI/#document-signing.
By the way, the keys are never read from the smartcard. The operation on the private key must always be made by the smartcard itself to ensure the key privacy.

A: The authentication part is handled by the TLS/SSL implementation, which is an intrensic part of the browser. There is no need to perform digital signature generation by the browser, so that is not included.
Of course not all browsers implement smart card functionality, and the ones that do may do it differently (e.g. IE uses the latest Microsoft proprietary API available when that version of IE was developed, and Firefox uses PKCS#11 through NSS).


text:
Q: Query Field Boosting issue in solr when boosted term is present in more than 1 field I am having 4 fields in solr.
For ex. Field1, Field2, Field3 and Field4.
My boost sequence is like field1^10, field2^8, field3^7 field4^6.
Now if I search for a keyword marketing lets say q=(Field1:("marketing")^10 OR Field2:("marketing")^8 OR Field3:("marketing")^7 OR Field4:("marketing")^6).
Requirement:
Now according to requirement, marketing present in field1 should appear first and so on which is working fine.
Problem:
But there is one record where marketing is appearing in Field3 and Field4 and it is appearing 2nd in result while record containing marketing in Field2 is appearing 3rd in result which is probably because of scoring mechanism.
Solution I need:
I want to show records in the order of boost applied in that field no matter if it is found in multiple field i.e. the record having marketing in field2 should always appear 2nd in result.

A: Response given by @MatsLindh in the comments is the proper solution :

You can however try to increase your boosts to have a much larger
  difference between the different levels - field1^100000, field2^10000, field3^1000 field4^100 - that way, given the same
  content, two later fields will not add up to a larger boost than the
  ones before it.
Note: Be aware that the scores will be affected by more than just the boost (such as the number of occurences, etc.).

A: I can think on two way to solve this:

*

*Use qf query parameter - if you pass the fields and boots in the qf parameter instead of q so your query looks something like that: q=marketing&qf="field1^10 field2^8, field3^7 field4^6" then the parsed query will be something like: max(field1:marketing^10,field2:marketing^8,field3:marketing^7 OR , field4:marketing^6) so it doesn't matter in how many fields they appear it'll only take the max.

*Change the boosts so each boost value is higher than the sum of the boost before him. e.g: field4^1, field3^2, field2^4, field1^8, that way no combination of fields can affect the ordering.


text:
Q: How to copy/paste without conditional formatting? After switching from Excel 2007 to Excel 2010 I've started to receive duplicates of conditional formatting rules. For example, I have a rule which colors the cell when it detects that cell contains the word "hello". When I copy this cell to other cells (which also contain the same rule), sometimes I receive duplicates. Those duplicates really slow down Excel.
So my question is, is there any way to disable copy/paste of conditional formatting? I want to copy/paste all content except the conditional formatting, including all formulas, values, and so on.
I don't know how to reproduce that problem, it occurs only occasionally and I work with Excel a lot.

A: Excel has had problems with copying conditional formats correctly since Excel 2007. If you didn't notice any problems then you were lucky. :-)
The easiest way to not copy conditional formatting is to not copy any formatting at all. i.e. to use Paste Special and paste Formulas or Values. This is actually quite fast if you use the old keyboard menu shortcuts.

*

*To Copy:  <Ctrl> + c

*To Paste everything <Ctrl> + v

*To Paste Special Values:  <Alt>, e, s, v, <Enter>

*To Paste Special Formauls:  <Alt>, e, s, f, <Enter>
I remember the Paste Special shortcuts by way of the old Excel menu:  E dit -> Paste S pecial -> V alues and E dit -> Paste S pecial -> F ormulas

A: There's now a "Merge Conditional Formatting" option in the "Paste Special" menu and this pastes everything you want (Data Validation, formatting, all the awesomeness) without creating duplicate conditional formatting rules!

A: If you are able to define all necessary conditional formatting rules at Worksheet level then you may not need conditional formatting at cell level. This makes it possible to copy and paste cells and rows without any changes in conditional formatting rules. Look at these rules from one of my sheets:
ScreenShot of Excel Rules Dialog

As you see these are defined as rules for "This Worksheet", formulas are defined manually and areas to which they apply are also defined manually. In result  if you look at rules for "Current selection" you will not see anything else. This means that all your rules are at worksheet level, there are no rules at cell level, so no rules are affected by copy/paste operations made on cells. Rules stay the same unless you manually edit them, and they are working as expected.
If you are curious - these conditional formatting rules are from an IP address plan. Here is the effect from those rules on the sheet:
IP Address Plan sample worksheet

A: For the destination cells that have the same conditional format rules defined, first select these cells/cell range and clear all rules by by going to Home > Conditional Formatting > Clear Rules from selected cells

Then, copy/paste your entire cell range with conditional formatting as desired.
EDIT: Alternatively, you can record a macro that copies only values from your source cells to your (conditionally formatted) destination cells. That's the quickest way for you to mass copy/paste multiple cells without duplicating formatting.

A: The best answer I can find does not work with CUT, it must be Copy, then Paste Special, and use the third icon on the top row, which will paste "Formulas & Number Formatting". Then delete or clear the original info.

A: If you are able to make the file a macro enabled file, right click on your tab and select "VBA code" then copy the following code into each worksheet in the document you where you need to prevent your conditional formatting from "fragmenting".
'This code substitutes "paste while merging conditional formats" any time paste is selected (no matter which type of paste is selected) from a dropdown menu AND from ctrl+V

Private Sub Worksheet_change(ByVal Target As Range)
If Application.CutCopyMode = xlCopy Then
Application.EnableEvents = False
Application.Undo
Target.PasteSpecial Paste:=xlPasteAllMergingConditionalFormats
Application.EnableEvents = True
End If
End Sub

'script to turn off drag and drop in sheet
Private Sub Worksheet_Activate()
Application.CellDragAndDrop = False
End Sub

'script to turn back on drag and drop when leaving sheet
Private Sub Worksheet_Deactivate()
Application.CellDragAndDrop = True
End Sub


text:
Q: How to print the output in two separate lines? I've been trying to print the output in two separate lines, I used System.out.println() and also System.out.println("\n") but I only seem to be getting the last number I enter as the output. I'm guessing this must be easy to work around but would be grateful for a nudge in the right direction.
import java.util.Scanner;
import java.util.*;
public class StoreToArray
{
  Scanner input = new Scanner(System.in);
  ArrayList<Integer> al = new ArrayList<Integer>();
  public static void main(String args [])
  {
    //Access method using object reference

    StoreToArray t = new StoreToArray();
    t.readFromTerminal();
  }

  public void readFromTerminal() {
    System.out.println("Read lines, please enter some other character to stop.");
    String in = input.nextLine();
    int check=0;
    while(true){
            check = input.nextInt();
            if(check == 0){ break;}
            al.add(check);
    }

    for (int i : al) {
        System.out.print(i);
    }
  }
}

A: The line:
String in = input.nextLine();

is capturing your first number entered and it is never added to the list al.
So, if you enter:
45
40
67
0
the output is:
[40, 67] (using System.out.println(al))
or:
4067 (using your for loop).
Note, the loop is broken by entering 0, not non-numeric characters as the first output text line would suggest.

Read lines, please enter some other character to stop

should really read

Read lines, please enter 0 to stop

[EDIT]
To add/display numbers to the list correctly:
1) Remove the line:
String in = input.nextLine();

2) Remove the for loop at the end and replace it with:
System.out.println(al);

A: Maybe use a do while and use try and catch. Because when you enter a character instead of a number your program is going to crash.
public class StoreToArray
{
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> al = new ArrayList<Integer>();
    public static void main(String args [])
    {
        //Access method using object reference

        StoreToArray t = new StoreToArray();
        t.readFromTerminal();
    }

    public void readFromTerminal() {
        System.out.println("Read lines, please enter some other character to stop.");
        int check=0;
        do{
            try {
                check = input.nextInt();
                if(check != 0)
                  al.add(check);
            }
            catch(InputMismatchException e)
            {
                System.out.println("Failed to convert to int.");
                check = 0;
            }
        }while(check != 0);

        for (int i : al) {
            System.out.println(i);
        }
    }
}

A: If i understand your question correctly, may be this is what you need
public void readFromTerminal() {
    System.out
            .println("Read lines, please enter some other character to stop.");
    int check = 0;
    while (true) {
        check = input.nextInt();
        al.add(check);
        if (check == 0) {
            break;
        }

    }

    for (int i : al) {
        System.out.print(i+ "\n");
    }
}


text:
Q: Retornar data invertida em PHP Estou elaborando um relatório com base na data-inicial (start_date) e data-final (end_date).
Meu retorno de filter vem através do POST, se eu usar então print_r($_POST), noto que a data vem no padrão brasileiro, normal.
$start_date = ($filter['start_date']) ? date("Y-m-d", strtotime($filter['start_date'])) : null;
$end_date = ($filter['end_date']) ? date("Y-m-d", strtotime($filter['end_date'])) : null;

Ao usar strtotime() para inverter a data, somente a start_date dá certo.
`start_date` : 2019-01-12
`end_date` : 1970-01-01

Resultado o print_r($_POST);
Array
(
    [start_date] => 12/01/2019
    [end_date] => 26/01/2019
)

Obs.: Notei que se eu digitar 13/01/2019, o retorno será 1970-01-01. Então, isto acontece por conta da inversão, qual seria a maneira correta de fazer isso?

A: Segundo a documentação de strtotime, quando a string passada está usando / como separador, assume-se que ela está no formato m/d/y (mês/dia/ano).
No caso do start_date, o valor é 12/01/2019, e por isso é interpretado como "1 de dezembro de 2019" (e não 12 de janeiro). Tanto que, testando seu código com esta string, eu obtive "2019-12-01" (não sei como você obteve 2019-01-12, mas enfim).
Já no caso de end_date, o valor é 26/01/2019, e strtotime interpretará como "o dia 1 do mês 26", o que resulta em uma data inválida. Neste caso, strtotime retorna FALSE.
O problema é que, ao passar o FALSE para a função date, este valor é interpretado como o número zero (já que date espera um int como parâmetro).
E como este parâmetro é o valor do timestamp (ou seja, a quantidade de segundos desde 01/01/1970), o timestamp com valor zero acaba resultando em 1970-01-01.

Uma maneira de resolver é trocar strtotime por DateTime::createFromFormat, especificando em qual formato está a string (no caso, d/m/Y). Este método retorna um DateTime, que por sua vez possui o método format, que pode ser usado para obter uma string contendo a data em outro formato (substituindo date()):
// parsing da string, criando uma data
$date = DateTime::createFromFormat("d/m/Y", "26/01/2019");
// formatar a data (converter para outro formato)
echo ($date->format("Y-m-d")); // 2019-01-26

Veja este código funcionando no Ideone.com.


text:
Q: How we I achieve add(4)(10)(20)(3)(1).total using Java Function? I am learning usage of,
java.util.function.Function

I wrote a code which uses java Function to add 4 to itself,
the code is as follows,
public class Test01 {

    public static void main(String[] args) {
        Function<Integer,Integer> addFunction = new Function<Integer,Integer>() {
            private int total = 0;
            public Integer apply(Integer value) {
                this.total += value;
                return this.total;
            }
        };

        int finalTotal = addFunction.andThen(addFunction)
                                    .andThen(addFunction)
                                    .andThen(addFunction)
                                    .apply(4);

        System.out.println(finalTotal);
    }

}

When I run the above code the output which I get is
32

How can I achieve something which I did in javaScript which is as follows,
var fn19 = function(){

        var addNum = function(num){

            var fn = function(num2){
                fn.sum += num2;
                return fn;
            };

            fn.sum = num;
            return fn;
        };

        print("addNum(3)(4)(3)(10) ==>  "+addNum(3)(4)(3)(10).sum);
};

fn19();

The output of the above code is
addNum(3)(4)(3)(10) ==> 20

Can I have the same kind of java function call where I can pass as many number arguments and the addFunction will add those many numbers.

A: An example, as close as possible to your JavaScript code, would be
class QuestionableConstruct {
    int sum;
    QuestionableConstruct add(int num2) {
        sum += num2;
        return this;
    }
}
Runnable fn19 = () -> {
    IntFunction<QuestionableConstruct> addNum = num -> {
        QuestionableConstruct fn = new QuestionableConstruct();
        fn.sum = num;
        return fn;
    };
    System.out.println("addNum(3)(4)(3)(10)==> "+addNum.apply(3).add(4).add(3).add(10).sum);
};
fn19.run();

A more Java like solution would be
interface Add {
    int sum();
    default Add add(int num) {
        int sum = sum() + num;
        return () -> sum;
    }
    static Add num(int num) {
        return () -> num;
    }
}

usable as
System.out.println("addNum(3)(4)(3)(10) ==>  "+Add.num(3).add(4).add(3).add(10).sum());

Unlike the JavaScript construct, this uses real immutable functions. Consider
Add a = Add.num(1).add(2).add(3);
System.out.println("1+2+3+4+5 = "+a.add(4).add(5).sum());
System.out.println("1+2+3+10+20 = "+a.add(10).add(20).sum());

which works smoothly without interference.
But of course, if you just want to sum a variable number of items, use
System.out.println("addNum(3)(4)(3)(10) ==>  "+IntStream.of(3, 4, 3, 10).sum());

or if you want a mutable accumulator, use
System.out.println("addNum(3)(4)(3)(10) ==>  "+
    IntStream.builder().add(3).add(4).add(3).add(10).build().sum());

which allows to keep the builder and pass it around.

A: You can't exactly do that in Java, what you are looking for is reducing a stream of values.
In other words: the "real" functional solution here isn't to call one method with multiple arguments. You rather have the values in some list, and then you define the function that "accumulates" over the content of that list, by applying a function on the elements.
See here for some examples.

A: The technique you're describing in the JavaScript world is taking advantage of a closure.
This is a nice side-effect of functions in JavaScript being first-class citizens. It's a way of associating functions with data in the enclosing scope and then being able to pass this association around without losing inner context. The most common/simple use of which is caching(its formal name being memoisation).
You would need functions(methods) in Java to be first class, but doing so would be redundant as classes by design are an entity which associates data and methods, making the whole concept of a closure in this context redundant.


text:
Q: Is typeid the same on different computers? I am wondering if hash_code() of typeid is the same on different computers? For an example: if typeid(int).hash_code() is it will be the same on another computer?

A:
I am wondering if hash_code() of typeid is the same on different computers?

It may or may not be.  From cppreference the behavior is:

Returns an unspecified value such that for all type_info objects referring to the same type, their hash_code() is the same.
No other guarantees are given: type_info objects referring to different types may have the same hash_code (although the standard recommends that implementations avoid this as much as possible), and hash_code for the same type can change between invocations of the same program.

A: From cppreference :

hash_code for the same type can change between invocations of the same program

(cited from here).
So not only is it not guaranteed to be the same on different computers, it's not even guaranteed to be the same for the same program every time.


text:
Q: How to remove space of url %20 on Nginx System? I want to redirect URLs like domain.com/stack%20over%20flow to domain.com/stack-over-flow.
I use Nginx, thus, I can't use .htacess based solutions.
How can I achieve this with Nginx?


text:
Q: How do you find the smallest partial order? The thing I find the most difficult is the transitive part. The only way that I know of is to see if the relation is transitive, but I have to do check if it is transitive for every relation possible on a given matrices. It gets quite cumbersome when you have a matrix of 5 elements or more. So is there some sort of shortcut?

A: Draw a picture.  Make a dot for each of the elements.  Whenever you know that $a\prec b$, draw an arrow from $b$ to $a$.
Except that if you know that $a\prec b$ and $b\prec c$, don't bother drawing an arrow for $a\prec c$, because you'll be able to see at a glance that $a\prec c$. Also don't bother to draw the arrow from $a$ to itself, because you'll know they are there anyway.
If you have $a\prec b$ and $b\prec a$ for some $a$ and $b$, this will be apparent, and to make the order into a partial order, you merge $a$ and $b$ into a single dot.  Similarly any cycle of arrows $a\prec b\prec c\prec\cdots\prec a$ collapses down to a single point in a partial order.
Then look at the picture.  Maximal and minimal elements will be obvious; elements that can't be compared will be obvious; relations implied by transitivity will be obvious.
After you absorb the picture, try drawing it again, and this time when $a\prec b$, instead of drawing an arrow from $b$ to $a$, just try drawing $b$ above $a$ on the paper.  For example, here's when we have $a\prec 1, 0\prec c, b\prec 1, c\prec a, 0\prec b$:

Clearly 1 is maximal, 0 is minimal, and $b$ is not comparable with $a$ or $c$.  Also it's obvious that $0\prec a$ by transitivity.


text:
Q: vim in mac c-f doesn't page down Using mac book pro, OSX 10.13.3, iterms, vim(installed with homebrew)
I want to default key c-f, c-b for page down and page up
but when I use c-f or c-b, It doesn't work but just shows controlP like below capture.

When using iterms, default mac terminal, macvim, same issue occur.
There is no map about c-f and c-b in .vimrc. And I reinstalled vim, but same.
How can I use default key map?

A: Looks like you've got it mapped from somewhere else. You can unmap it or remap it in your .vimrc file. Did you happen to copy someone else's configuration? I don't know what the .vim_runtime directory is.
A quick google shows this repo. Are you using that?
I've copied other people's vimrcs before but still wouldn't suggest it. It leads to problems like this BUT I could be totally wrong in what you're doing here.
Cheers!

A: As already said, it is the ctrl-p plugin which does that.
But you can't just remap the command in your vimrc because the plugin is sourced after your vimrc so your mapping will be overwritten.
It would be possible to remap it in an autocmd (see :h autocmd) or in an file in the after-directory (:h after-directory)
But since ctrl-p is written as recommended, there is a setting to control the mapping:
let g:ctrlp_map = '<c-p>'

This works in your vimrc
Have a look here: https://github.com/kien/ctrlp.vim


text:
Q: Can a data file be used as a field in a function? I am making a program that iterates through a data file and looks through for a target sequence. Right now I am only using 2 files as test cases, but I want to expand it to be able to use 15-20 files. I don't want to define this many repeats of the same function just to encapsulate each file, so is there any way where i can input which file that i read?

# looks for a target sequence within sequence
def targetSequence1(target):
    print("looking for target sequence in data set 1", target)
    counter= 0
    length = len(target)
    for element in data:
        if(data[counter:counter+length] == target):
            print(" match found at", counter, counter+length)
        counter+=1

# same as targetSequence1, but for the other document
def targetSequence2(target):
    print("looking for target sequence in data set 2", target)
    counter= 0
    length = len(target)
    for element in data1:
        if(data1[counter:counter+length] == target):
            print(" match found at", counter, counter+length)
        counter+=1

these functions both work- but i want to be able to merge both of these programs so that i can pick which data file i want to analyze


text:
Q: sbt: copy resources to classpath in multi project build I have a sbt project with following structure:
project
|
|-- file.json
|-- <serverProject>
|-- <clientProject>

project aggregates both serverProject and clientProject. Starting sbt and compiling works fine.
When running or packaging serverProject I want file.json to end up at the classpath of serverProject.
I added file.json to the unmanagedResources in (Compile) for serverProject but I get following error when trying to run / package:
[info] Done packaging.
java.lang.RuntimeException: Duplicate mappings:
    project/serverProject/target/scala-2.11/classes/file.json
from
    file.json
        project/serverProject/file.json
    at scala.sys.package$.error(package.scala:27)
    at sbt.Sync$.noDuplicateTargets(Sync.scala:67)
    ...

It looks like sbt finds both the project root directory and serverProject directory as candidates for file.json after which it fails.
How to get around this error?
Thanks for reading and helping out!

A: I was able to solve my issue! When adding following setting to serverProject it works as expected:
unmanagedResources in (Compile) ++= Seq(file(baseDirectory.value.getParentFile.getAbsolutePath + "/file.json"))


text:
Q: How to get default application name in cli? I want to create a framework that shows the application name on statup. Targeting command line interface applications.
Question: how can I get such an application name in a generic way?
Eg spring offers a property, but which is not set by default:
@Value("${spring.application.name}")
private String appname;

And I don't want to set that property explicit. Looking for some kind of "default application name".
In a Java EE container there is also the following option:
String myApplicationName = (String) initialContext.lookup("java:app/AppName");

But how about CLI apps? How can I get some kind of generic application name?

A: The closest you can get, if I interpreted correctly your question, is to:

*

*find which class is running public static void main(String [] args) method

*get its simpleName

*store aforementioned name into a system property

and in order to do so, you have two options:

*

*call Thread.currentThread().getStackTrace(), and inspect its tail element. But this has to be executed in the main thread as well, otherwise you wont retrieve the correct StackTraceElement;

*call Thread:getAllStackTraces(), and parse the entire map to identify the main Thread, get the corresponding value, and pick its last StackTraceElement
Once you have StackTraceElement, you can call StackTraceElement:getClassName() which will return something like

scala.tools.nsc.MainGenericRunner

Split the string, save it into a system property, and you're good to go.
Hope it will help you.


text:
Q: Adding a file to SQL table - never saves I am trying to update a column of datatype image with a local file
Update tblabc
set DOCBLOB =(Select * FROM OPENROWSET(BULK 'C:\TEMP\abc.doc', SINGLE_BLOB) AS img)
where ID= 62
GO

The query appears to execute correctly (no error) but the column remains as NULL. I run the query in MSMS and then immediately check the table. I originally was trying to update the blob column using C# but get the same result — I get no error but never see the update.
I have successfully updated a text column so assume permissions are OK.
(Select * FROM OPENROWSET(BULK 'C:\TEMP\abc.doc', SINGLE_BLOB) AS img)

returns a column Bulkcolumn successfully populated

A: First of all, I'd recommend to dump the image datatype and use varbinary(max) instead - image has been deprecated since SQL Server 2005 ....
Secondly, I'd slightly rewrite your UPDATE statement to be this:
UPDATE TblFiles
SET DOCBLOB = img.BulkColumn
FROM OPENROWSET(BULK 'C:\TEMP\abc.doc', SINGLE_BLOB) AS img
WHERE ID = 62

In my case, this works just fine - the binary column gets updated with the contents of the file specified in the OPENROWSET call

A: Turns out that there was a Trigger (code that executes) on the table I was trying to update.
So my update was being reversed each time.
Once I disabled the trigger my original query worked


text:
Q: Upgrading to Scala 2.13 giving scalaoptions error I just upgraded to Scala latest version 2.13.2, now I resolved all dependencies.
Inside IntelliJ sbt refresh is working fine, but when I build the project I am getting this error:
Error: scalac: 'by-name-right-associative' is not a valid choice for '-Xlint'
Error: scalac: 'nullary-override' is not a valid choice for '-Xlint'
Error: scalar: 'unsound-match' is not a valid choice for '-Xlint'
Error: scala: bad option: '-Yno-adapted-args'

Not, sure what to do about it, I tried checking everywhere, but I am not able to resolve it.
Can someone please help.

A: Your  build.sbt (or some plugin imported in it) is setting up these options for scalac. You can find there something like:
scalacOptions ++= Seq(
  ...
  "-Xlint:by-name-right-associative",
  ...
  "-Xlint:nullary-override",
  ...
  "-Xlint:unsound-match",
  ...
  "-Yno-adapted-args",
 ...
)

which adds options that aren't valid for Scala 2.13. Once you remove them things should be ok.
To find them you can use inspect scalacOptions to list all places where this settings where modified, and then look there to get rid of them. If this is in some plugin that you cannot edit you can always remove them "manually":
scalacOptions --= Seq(
  "-Xlint:by-name-right-associative",
  "-Xlint:nullary-override",
  "-Xlint:unsound-match",
  "-Yno-adapted-args"
)


text:
Q: Is the factory design pattern applicable in this situation
*

*taskA, taskB, taskC inherit from my class Task

*ContextA, ContextA2, ContextB, ContextC inherit from my class Context
Contexts have a corresponding Task as class property :
public abstract class Context
{
    public String CommonProperty { get; set; }

    public abstract void MethodToOverride();
}

public class ContextA : Context
{
    public TaskA Task { get; set; }

    public override void MethodToOverride()
    {
        //do stuff with this.Task and this.CommonProperty
    }
}

public class ContextA2 : Context
{
    public TaskA Task { get; set; }

    public override void MethodToOverride()
    {
        //do stuff with this.Task and this.CommonProperty
    }
}

public class ContextB : Context
{
    public TaskB Task { get; set; }

    public override void MethodToOverride()
    {
        //do stuff with this.Task and this.CommonProperty
    }
}

And so on...
When iterating over a list of tasks, I want to create the corresponding Context :
foreach (Task t in tasks)
{
    Context context;

    if (t is TaskA)
    {
        if (condition)
        {
            context = new ContextA() { Task = t as TaskA};
        }
        else
        {
            context = new ContextA2() { Task = t as TaskA };
        }
    }
    else if (t is TaskB)
    {
        context = new ContextB() { Task = t as TaskB };
    }
    else if (t is TaskC)
    {
        context = new ContextC(){ Task = t as TaskC };
    }
    else
    {
        throw new Exception("Unkown Task");
    }

    context.CommonProperty = "value";
    context.MethodToOverride();//Do different things based on the context type
}

I feel there should be a cleaner way to achieve this but I can't figure out how to manage the creation of the context object, especially the case of contextA and contextA2 that depend on a condition.

A: foreach (Task t in tasks)
{
    Context  context = t.ConstructContext(condition);

    context.CommonProperty = "value";
    context.MethodToOverride();//Do different things based on the context type
}

public asbtract class Task
{
    //whatever might be in here
    public abstract Context ConstructContext();
}

public class TaskA : Task
{
    //NOTE: In my opinion condition should be internal to TaskA and no one else should know about and you should remove the parameter from the method
    // but I don't know where you get it from so I'm leaving it here
    public override Context ConstructContext(bool condition)
    {
        if (condition)
        {
            return new ContextA() { Task = this};
        }
        else
        {
            return new ContextA2() { Task = thid };
        }
    }
}

public class TaskB : Task
{
    public override Context ConstructContext(bool condition)
    {
        //ignore condition which implies it shouldn't really be passed

        return new ContextB() {Task = this};
    }
}

//etc...

I really don't like passing that condition about, its a code smell in my opinion, but from what you have said, it needs to be something external to the tasks. Anyway this should meet your needs

A: Yes, Factory Pattern is suitable.
class ContextFactory {
    public create(TaskA t, bool condition) {
        return condition ? new ContextA() { Task = t } : new ContextA2() { Task = t };
    }
    public create(TaskB t) {
        return new ContextB() { Task = t };
    }
    public create(TaskC t) {
        return new ContextC() { Task = t };
    }
}
...
ContextFactory factory = //... new or passed from somewhere
foreach (Task t in tasks) {
    Context context;
    if (t is TaskA) {
        context = factory.create(t as TaskA, condition);
    } else if (t is TaskB) {
        context = factory.create(t as TaskB);
    } else if (t is TaskC)
        context = factory.create(t as TaskC);
    } else {
        throw new Exception("Unkown Task");
    }
    context.CommonProperty = "value";
    context.MethodToOverride();//Do different things based on the context type
}


text:
Q: Data type somehow gets converted when appended to a list I am trying to convert text to binary using ASCII encoding, and then decode the binary back to text as proof of concept for a larger project. The following code works well and does what it is supposed to do:
bytes = []

input_data = "Hello"

for b in input_data:
    new_byte = bin(int.from_bytes(b.encode('ascii'), 'big'))
    bytes.append(new_byte)

for x in bytes:
    print(x)

for byte in bytes:
    byte_int = int(byte, 2)
    output_data = str(byte_int.to_bytes(byte_int, 'big').decode('ascii'))
    print(output_data)

However, as soon as I try to append the given value of output_data to a list within the for loop, the strings become converted to HEX for some odd reason.
bytes = []
output_list = []

input_data = "Hello"

for b in input_data:
    new_byte = bin(int.from_bytes(b.encode('ascii'), 'big'))
    bytes.append(new_byte)

for x in bytes:
    print(x)

for byte in bytes:
    byte_int = int(byte, 2)
    output_data = str(byte_int.to_bytes(byte_int, 'big').decode('ascii'))
    print(output_data)
    output_list.append(output_data)

print(output_list)

With the output:
0b1001000
0b1100101
0b1101100
0b1101100
0b1101111
H
e
l
l
o
['\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00H', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00e', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00l', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00l', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00o']

I have no idea why this happens, is there any explanation?

A: You misused the int.to_bytes method. As the doc states,

int.to_bytes(length, byteorder, *, signed=False)
Return an array of
bytes representing an integer. [...]
The integer is represented using
length bytes.

You used byte_int.to_bytes(byte_int, 'big'), so you convert for example the integer 72 into a byte string of length 72, which gives you 71 null bytes before the one representing your value.
You want a single byte, so use
output_data = str(byte_int.to_bytes(1, 'big').decode('ascii'))

A: When you are printing the list object itself and not its content, the actual content doesn't get printed in a representation way. That is why you see HEX values.
To achieve what you want, simply unpack the list:
print(*output_data)

Or this way:
for item in output_list:
    print(item, end=' ')


text:
Q: 2D Binary Search that accept random array sets public static int search(int[][] arr, int x){
  int row= arr.length, colum= arr[0].length-1;
  int lo=0, hi=row*colum;

    while(lo <= hi){
       int mid= lo+(hi-lo)/2;
         int mid_index= arr (mid/colum);
        if(mid_index == x){
               return mid;
        }else if (x < mid_index) {
            hi= mid-1;
        }else if (x > mid_index){
            lo= mid+2;
        }
    }
              return -1;
}
   public static void main(String args []){
    int [][] arr = {{1,2,3,4},
                    {5,6,7,8}
                    {1, 7, 7, 95},
                    {9, 9, 80, 33}};
    int x = 95;
    int result = search(arr , x);
    if (result == -1)
        System.out.print("Element is not present in array");
    else
        System.out.print("Element is present inside the index:" +""+ result);}

*** Still learning this topic but need help. I don't know how i can make it search for the index position and accept random set of arrays.***
// Return -1 if target is not found
// supposed to print  11 as the target in this given is in index 12.
// Can perfectly run if the given array is empty.
// Can run even with the random set of arrays.


text: Q: How to execute spring boot application from within a separate maven module using spring boot test I added the modules that I want to test as dependency, I try to create a @SpringBootTest but it can't find my @SpringBootApplication class thats inside a dependency. What's the best approach here?


text:
Q: Simple class failing nosetests3 I'm learning python and I'm having some trouble with some simple unit tests I'm trying to run. I'm using nosetests to run some manually written tests, and I've got my github repository set up with Travis Continuous Integration for a bit of CI practice. I noticed that it was failing all builds for python 3.x, but passing anything for 2.x.
First, here are my two files.
fib.py
#! /usr/bin/python3
#fib.py

import sys

def fib(n):
    if (n == 0):
        return 0
    if (n == 1):
        return 1
    return fib(n -1) + fib(n - 2)

def main():
   if (len(sys.argv) == 2):
       print(fib(sys.argv[1]))
   else:
       print("Usage: ", sys.argv[0], " [number]")

if __name__ == "__main__":
        main()

test_fib.py
#! /usr/bin/python3
#testfib.py

import unittest
from fib import fib

class TestFib(unittest.TestCase):
    def test_fib_0(self):
        self.assertEqual(fib(0), 0)

    def test_fib_1(self):
        self.assertEqual(fib(1), 1)

    def test_fib_2(self):
        self.assertEqual(fib(2), 1)

    def test_fib_range(self):
        for x in range(2,13):
            self.assertEqual(fib(x), fib(x - 1) + fib(x - 2))

if __name__ == "__main__":
       unittest.main()

running  python test_fib.py :
....
----------------------------------------------------------------------
Ran 4 tests in 0.018s

OK

running nosetests
....
----------------------------------------------------------------------
Ran 4 tests in 0.053s

OK
pi@kepler:~/dev/Projects/Numbers/fib$

However, when I deploy to Travis CI and it runs nosetests with python3.x, or I run nosetests3 on my machine, I see this:
EEEE
======================================================================
ERROR: test_fib_0 (fib.test_fib.TestFib)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/pi/dev/Projects/Numbers/fib/test_fib.py", line 9, in test_fib_0
    self.assertEqual(fib(0), 0)
TypeError: 'module' object is not callable

======================================================================
ERROR: test_fib_1 (fib.test_fib.TestFib)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/pi/dev/Projects/Numbers/fib/test_fib.py", line 12, in test_fib_1
    self.assertEqual(fib(1), 1)
TypeError: 'module' object is not callable

======================================================================
ERROR: test_fib_2 (fib.test_fib.TestFib)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/pi/dev/Projects/Numbers/fib/test_fib.py", line 15, in test_fib_2
    self.assertEqual(fib(2), 1)
TypeError: 'module' object is not callable

======================================================================
ERROR: test_fib_range (fib.test_fib.TestFib)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/pi/dev/Projects/Numbers/fib/test_fib.py", line 19, in test_fib_range
    self.assertEqual(fib(x), fib(x - 1) + fib(x - 2))
TypeError: 'module' object is not callable

----------------------------------------------------------------------
Ran 4 tests in 0.034s

FAILED (errors=4)

I'm pretty new to python, so I'm not sure if my problem is with my code or with how I'm using nose. Any ideas on what I'm doing wrong?
Here are the versions of everything I'm running:
$ python -V
Python 2.7.3
$ python3 -V
Python 3.2.3
$ nosetests -V
nosetests version 1.3.0
$ nosetests3 -V
nosetests3 version 1.1.2
$ cat /etc/*-release
PRETTY_NAME="Debian GNU/Linux 7 (wheezy)"
NAME="Debian GNU/Linux"
VERSION_ID="7"
VERSION="7 (wheezy)"
ID=debian
ANSI_COLOR="1;31"
HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support/"
BUG_REPORT_URL="http://bugs.debian.org/"

A: Make sure you don't have some old files laying around, such as a fib/fib.pyc or something under __pycache__ perhaps, because for me, everything works correctly under Python 3.3.2 with nosetests as well as without:
(python3.3.2)~/code/python/stackoverflow$ nosetests test_fib.py
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

for example, run python (or ipython) in that directory and execute:
>>> from fib import fib
>>> fib
???

and see what it reports: if fib is reported to be a <function ...>, everything should be correct; if <module ...>, you have to investigate why it is so. For example, this is what I get:
>>> from fib import fib
>>> fib
<function fib at 0x10cb7d9e0>

You can also try adding from __future__ import absolute_import and see how Python 2.x behaves then; if the same problem starts occurring, it's an indication that you have a top-level package fib somewhere which Python 3.x imports by default but in Python 2.x gets overrided with the sibling package (i.e. a package in the same folder as test_fib), which is changed to Python 3.x behavior with the __future__ import. For more information about future imports, see Future statement definitions; about absolute_import, see PEP 328 -- Imports: Multi-Line and Absolute/Relative.


text:
Q: Trying to render a square with vaos and vbos i am trying to learn how to use vaos and vbos. Right now i am trying to render a square but nothing is rendering on the screen. I am using android studios and OpenGL ES 3.
This is my MainActivity:
package com.example.karno.androidgameprojectv3;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import renderEngine.DisplayManager;
import renderEngine.MainRenderer;

public class MainActivity extends Activity {

    DisplayManager gameView;
    MainRenderer renderer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        renderer = new MainRenderer();
        gameView = new DisplayManager(this);

        gameView.setEGLContextClientVersion(3);

        gameView.setRenderer(renderer);
        this.setContentView(gameView);
    }

    @Override
    protected void onDestroy(){

//        Log.d("------test", "in on destroy");
        renderer.loader.cleanUp();
        super.onDestroy();
    }

}

This is the Loader class where i bind the vaos and vbos:
package renderEngine;

import android.opengl.GLES11;
import android.opengl.GLES20;
import android.opengl.GLES30;
import android.util.Log;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;

public class Loader {

    private int [] vaos;
    private int [] vbos;
    private int countVbos = -1;
    private int countVaos = -1;

    public Loader( int neededVAOs, int neededVBOs){
        vaos = new int[neededVAOs];
        vbos = new int[neededVBOs];

    }

    public RawModel loadToVAO(float[] position) {

        int vaoID = createVAO();
        storeDataInAttributeList(0, 3, position);

        unbindVAO();
        Log.d("looking for null---", "position = " + position);
        return new RawModel(vaoID, position.length/3);
    }

    private int createVAO() {

        countVaos++;
        GLES30.glGenVertexArrays(1, vaos, 0);
        GLES30.glBindVertexArray(vaos[countVaos]);
        return vaos[countVaos];
    }

    private void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) {

        countVbos++;
//        GLES30.glGenBuffers(1, vbos);
        GLES20.glGenBuffers(1, vbos,0);
//        Log.d("------vbo", "vbo id = " + vbos.get(countVbos));
        GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vbos[countVbos]);
        FloatBuffer buffer = storeDataInFloatBuffer(data);
//        Log.d("looking for null arg", "arg2 = " + vbos.get(countVbos) + ", arg3 = " + buffer);
        GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, vbos[0], buffer, GLES30.GL_STATIC_DRAW);
        GLES30.glVertexAttribPointer(attributeNumber, coordinateSize, GLES30.GL_FLOAT, false, 0, 0);
        GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0);
    }

    private FloatBuffer storeDataInFloatBuffer(float[] data) {

        FloatBuffer buffer = FloatBuffer.allocate(data.length);
        buffer.put(data);
        buffer.flip();
        return buffer;
    }

    private void unbindVAO() {
        // this will unbind the VAO
        GLES30.glBindVertexArray(0);
    }

    public void cleanUp() {
        Log.d("--------", "in clean up");
        for (int vao : vaos) {
            GLES30.glDeleteBuffers(vao, vaos, 0);
        }
        countVaos = -1;
        for (int vbo : vbos) {
            GLES20.glDeleteBuffers(vbo, vbos,0);
        }
        countVbos = -1;
        Log.d("--------", "cleaned up.");
    }
}

The MainRenderer:
package renderEngine;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.util.Log;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MainRenderer implements GLSurfaceView.Renderer {

    public Loader loader;
    Renderer renderer;
    RawModel model;

    private static final int NEEDED_VAOS = 1;
    private static final int NEEDED_VBOS = 1;

    //square
    float[] vertecies = {
            -0.5f, 0.5f, 0f,
            -0.5f, -0.5f, 0f,
            0.5f, -0.5f, 0f,

            0.5f, -0.5f, 0f,
            0.5f, 0.5f, 0f,
            -0.5f, 0.5f, 0f,
    };

    @Override
    public void onDrawFrame(GL10 arg0){

//        GLES20.glClearColor(0,1,0,1);
//        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        renderer.prepare();
        renderer.render(model);
    }

    @Override
    public void onSurfaceChanged(GL10 arg0, int height, int width){

    }

    @Override
    public void onSurfaceCreated(GL10 arg0, EGLConfig config){

//        Log.d("check------", "in on surface created.");
        loader = new Loader(NEEDED_VAOS, NEEDED_VBOS);
        renderer = new Renderer();
        model = loader.loadToVAO(vertecies);
    }
}

The View:
package renderEngine;

import android.content.Context;
import android.opengl.GLSurfaceView;

public class DisplayManager extends GLSurfaceView {

    public DisplayManager(Context context){
        super(context);
    }
}

The Render class:
package renderEngine;

import android.opengl.GLES11;
import android.opengl.GLES20;
import android.opengl.GLES30;
import android.util.Log;

public class Renderer {

    public void prepare(){

        GLES11.glClearColor(0,1,0,1);
        GLES11.glClear(GLES11.GL_COLOR_BUFFER_BIT);
    }

    public void render(RawModel model) {

//        Log.d("------render","model.getVaoID() = "+ model.getVaoID());
        GLES30.glBindVertexArray(model.getVaoID());
        GLES30.glEnableVertexAttribArray(0);
        GLES11.glDrawArrays(GLES11.GL_TRIANGLES, 0, model.getVertexCount());
        GLES20.glDisableVertexAttribArray(0);
        GLES30.glBindVertexArray(0);
    }
}

The 3d model.
package renderEngine;

public class RawModel
{
    private int vaoID;
    private int vertexCount;

    public RawModel(int vaoID, int vertexCount)
    {
        this.vaoID = vaoID;
        this.vertexCount = vertexCount;
    }

    /**
     * @return the vaoID
     */
    public int getVaoID() {
        return vaoID;
    }

    /**
     * @return the vertexCount
     */
    public int getVertexCount() {
        return vertexCount;
    }
}

In logcat i am getting:

2019-01-06 20:33:43.667 4618-4657/com.example.karno.androidgameprojectv3 E/emuglGLESv2_enc: a vertex attribute index out of boundary is detected. Skipping corresponding vertex attribute. buf=0x7c2911e22a00
  2019-01-06 20:33:43.667 4618-4657/com.example.karno.androidgameprojectv3 E/emuglGLESv2_enc: Out of bounds vertex attribute info: clientArray? 0 attribute 0 vbo 1 allocedBufferSize 1 bufferDataSpecified? 1 wantedStart 0 wantedEnd 72

Any help will be appreciated.

A: The 2nd parameter of GLES30.glBufferData has to be the size of the buffer in bytes, rather then the named buffer object.
See also Java Code Examples for android.opengl.GLES20.glBufferData() and glBufferData:
GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER,
     buffer.capacity() * BYTES_PER_FLOAT, buffer, GLES30.GL_STATIC_DRAW);

Note glBufferData creates and initializes the buffer object's data store, for the buffer object which is currently bound by glBindBuffer.


text:
Q: Angular 9 ng-if and ng-show - element is always displayed In Angular 9 I have code in that I want to hide html element. In typescript I have public property:
export class UserPageComponent implements OnInit {
  public postModel: any = {};

And in Html component I want to check if I should display html element:
<mat-video ng-if="postModel.moviePath != ''" src="{{ postModel.moviePath }}"></mat-video>

But element mat-video is always displayed.
When I wanted to use ng-show the result is the same.

A: You are using angularjs syntax, with angular it should be ngIf directive
<mat-video *ngIf="postModel.moviePath != ''" src="{{ postModel.moviePath }}"></mat-video>

Also there is NO ng-show with angular.


text:
Q: Will RewriteRules In .htaccess Affect Site's Speed? I am planing to add at most 10 .htaccess rewrite url codes in home directory will it affect execution ( loading time of site ) of my website ?
my current .htaccess file is
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9]+)/([0-9]+)/([^.]+).html index.php?perma=$3
RewriteRule ^movies/([^.]+).html gallery.php?movie=$1
RewriteRule ^album/([^.]+).html gallery.php?album=$1
RewriteRule ^img/([^.]+)/([^.]+).html gallery.php?img=$2
RewriteRule ^movies.html gallery.php

A: You might need to see performance impact of order of rewrite rules when using apache mod_rewrite and, like @diolemo commented, for 20 rewrite rules it's not noticeable.

A: Yes it will affect the load time. The more rules/exceptions you have, the longer it takes to render. But: we are talking about micro/milliseconds that won't be even noticed by the human eye.

A: 10 rules are not a problem, but for future reference: The usual approach is to redirect everything to a single entry point and let the application do the routing. A simple example:
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L,QSA]

index.php
$query = $_SERVER['REQUEST_URI'];
$queryParts = explode('/', $query);
switch($queryParts[0]) {
    case 'movies':
        // ...
        break;
    case 'album':
        // ...
        break;
    case 'img':
        // ...
        break;
    // ...
    default:
        // 404 not found
}

The RewriteCond conditions assure that requests to existing files are not rewritten. QSA is optional, it means "query string appended", so that for example movies.html?sort=title gets rewritten to index.php?sort=title. The original request URI is available in $_SERVER['REQUEST_URI'].
If your application is object oriented, the Front Controller pattern will be of interest to you. All major PHP frameworks use it in some way, it might help to look at their implementations.
If not, a micro-framework like Silex could do the job for you. In Silex your routing could look as follows:
index.php
require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

$app->get('/{year}/{month}/{slug}', function ($year, $month, $slug) use ($app) {
    return include 'article.php';
});
$app->get('/movies/{movie}.html', function ($movie) use ($app) {
    return include 'gallery.php';
});
$app->get('/album/{album}.html', function ($album) use ($app) {
    return include 'gallery.php';
});
$app->get('/img/{parent}/{img}.html', function ($parent, $img) use ($app) {
    return include 'gallery.php';
});
$app->get('/movies.html', function () use ($app) {
    return include 'gallery.php';
});

$app->run();

gallery.php and article.php would have to return their output. You probably can reuse your existing scripts with this index.php if you replace $_GET['var'] with $var and add output buffering:
gallery.php
ob_start();
// ...
return ob_get_clean();

A: Most of the time needed to download a webpage comes from retrieving the HTML, CSS, JavaScript, and images. The time to rewrite the URL is negligible.
Usually, the images are the biggest cause of slow load times. A tool like Pingdom can help you put the load times of various components in perspective.
http://tools.pingdom.com/fpt/
HTH.


text:
Q: Compute a magnitude using a function that depends on the type of a data.table row I want to compute a magnitude that depends on the type of a data.table row:
library (data.table)

n1 <- c(1,2,3)
n2 <- c(10,20,30,40)
num <- list(n1,n2)
type <- c("price", "volume")
dt1 <- data.table (num, type)
dt1 [, cons.fun := "sum"]
dt1[type=="price", cons.fun := "mean"]

> dt1
           num   type cons.fun
1:       1,2,3  price     mean
2: 10,20,30,40 volume      sum

Thus, I need to create a new column magnitude based on the cons.fun value. I tried:
dt1 [, magnitude:=match.fun(cons.fun)(num)], and got the error:
Error in match.fun(cons.fun) :
  'c("mean", "sum")' is not a function, character or symbol

Instead of the expected:
> dt1
           num   type cons.fun magnitude
1:       1,2,3  price     mean         2
2: 10,20,30,40 volume      sum       100

How can I get it right? Thank you!

A: Here is one approach.  Loop through the rows, get the value of the string and apply the function on the 'num' column
dt1[, magnitude := get(cons.fun)(num[[1]]), 1:nrow(dt1)]
dt1
#          num   type cons.fun magnitude
#1:       1,2,3  price     mean         2
#2: 10,20,30,40 volume      sum       100

Or as the OP was using match.fun, 'cons.fun' can be looped with mapply to extract the function object and to apply the function  on the corresponding list column 'num'
dt1[, magnitude := mapply(function(x, y) match.fun(x)(y), cons.fun, num)]


text:
Q: Python script boot - Debian I'm a trying to start a program at boot but without success.
The program starts well but doesn't stay alive (it is supposed to be a infinite script).
But when I start the program normally I don't have any problem! I don't get why when I run at reboot it doesn't work.
I use a cron tab like this:
@reboot sudo python /bin/gestion.py &

I can show you my code:
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
import time
import socket
import threading
import sys

from os.path import expanduser
import datetime

print("DEBUT")

vitesse = 4
etat_moteur_droit = 0
etat_moteur_gauche = 0
data_thr = "Starting"
etat_thr = 1
HOST = '192.168.1.50'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

file = open('/home/log.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()

print("MID")

def main():
    global data_thr
    global etat_thr
    global etat_moteur_droit
    global etat_moteur_gauche
    global vitesse

    print("START")
    etat_moteur_droit=0
    setup_io()
    # gestion_bonus(0)
    # gestion_moteur_droit(4,0)
    # gestion_moteur_gauche(4,0)
    # avancer()
    # time.sleep(3)
    # tourner_a_gauche()
    # time.sleep(3)
    # tourner_a_droite()
    # time.sleep(3)
    # arreter()
    x = threading.Thread(target=thread_serveur)
    x.start()
    while True:
        try:
            data_thr = data_thr.partition('\n')[0]
            if(data_thr == ""):
                etat_thr = 0
            if(data_thr == "Fin thread"):
                x = threading.Thread(target=thread_serveur)
                x.start()
                data_thr = "Fin thread step 2"
            if(data_thr == "avance"):
                avancer()
            if(data_thr == "stop"):
                arreter()
            if(data_thr == "gauche"):
                tourner_a_gauche()
            if(data_thr == "droite"):
                tourner_a_droite()
            if(data_thr[:7] == "vitesse"):
                vitesse  = int(data_thr[8:10])
                if(etat_moteur_droit == 1):
                    PWM.set_duty_cycle("P9_14", vitesse)
                if(etat_moteur_gauche == 1):
                    PWM.set_duty_cycle("P8_19", vitesse)
        except:
            print("Erreur lors de reception message")
    print("FIN")
    file = open('/home/log.txt', 'w')
    file.write("FIN!\n" + str(datetime.datetime.now()))
    file.close()

def thread_serveur():
    global data_thr
    global etat_thr
    connected = 0
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
    while connected == 0:
        try :
            s.bind((HOST, PORT))
        except socket.error:
            pass
        finally:
            connected = 1
    s.listen(1)
    conn, addr = s.accept()
    print('Connected by', addr)
    timing = 0
    start = time.time()
    while etat_thr == 1:
        try:
            data_thr = conn.recv(1024)
            if not data_thr:
                break
            if data_thr != "":
                print(data_thr)
            conn.sendall("Bien recu")
        except:
            print("Erreur lecture thread")
    s.shutdown(socket.SHUT_RDWR)
    s.close()
    data_thr = "Fin thread"

def setup_io():
    GPIO.setup("P9_17", GPIO.OUT)
    GPIO.setup("P9_24", GPIO.OUT)
    GPIO.setup("P9_23", GPIO.OUT)
    PWM.start("P9_14", 0)
    PWM.stop("P9_14")
    PWM.start("P8_19", 0)
    PWM.stop("P8_19")
    PWM.cleanup()

def gestion_bonus(etat):
    if(etat == 1):
        GPIO.output("P9_17", GPIO.HIGH)
    else:
        GPIO.output("P9_17", GPIO.LOW)
    GPIO.cleanup()

def gestion_moteur_droit(vitesse,enable):
    global etat_moteur_droit

    if(enable == 1 and etat_moteur_droit == 0):
        PWM.start("P9_14", vitesse)
        GPIO.output("P9_24",GPIO.HIGH)
        etat_moteur_droit = 1
    elif(enable == 1 and etat_moteur_droit == 1):
        PWM.set_duty_cycle("P9_14", vitesse)
        GPIO.output("P9_24",GPIO.HIGH)
    elif(enable == 0):
        PWM.stop("P9_14")
        GPIO.output("P9_24",GPIO.LOW)
        etat_moteur_droit =0
    GPIO.cleanup()

def gestion_moteur_gauche(vitesse,enable):
    global etat_moteur_gauche

    if(enable == 1 and etat_moteur_gauche == 0):
        PWM.start("P8_19", vitesse)
        GPIO.output("P9_23",GPIO.HIGH)
        etat_moteur_gauche = 1
    elif(enable == 1 and etat_moteur_gauche == 1):
        PWM.set_duty_cycle("P8_19", vitesse)
        GPIO.output("P9_23",GPIO.HIGH)
    elif(enable == 0):
        PWM.stop("P8_19")
        GPIO.output("P9_23",GPIO.LOW)
        etat_moteur_gauche =0
    GPIO.cleanup()

def avancer():
    global vitesse
    gestion_moteur_droit(vitesse,1)
    gestion_moteur_gauche(vitesse,1)

def tourner_a_gauche():
    global vitesse
    gestion_moteur_droit(vitesse,1)
    gestion_moteur_gauche(vitesse,0)

def tourner_a_droite():
    global vitesse
    gestion_moteur_droit(vitesse,0)
    gestion_moteur_gauche(vitesse,1)

def arreter():
    global vitesse
    gestion_moteur_droit(vitesse,0)
    gestion_moteur_gauche(vitesse,0)
if __name__ == "__main__":
    main()

Can you help me please?

A: As I can see you are using some network service. Maybe when the cron run at @reboot, the network is not ready yet. It may worth a try to implement as service and run command on that way.
Example implementation
Create a file where the system daemon services can be found, e.g.: /lib/systemd/system/TestStartup.service. Example for content of member:
[Unit]
Description=Test service for startup
After=network.target

[Service]
User=root
ExecStart=/usr/bin/python /bin/gestion.py
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target

/usr/bin/pythn can be different as which version you are using and where it is installed on your machine, but you can check by whereis python command output:
ati@atihome:/lib/systemd/system$ whereis python
python: /usr/bin/python2.7 /usr/bin/python /usr/bin/python3.7 /usr/bin/python3.7m /usr/lib/python2.7 /usr/lib/python3.7 /etc/python2.7 /etc/python /etc/python3.7 /usr/local/lib/python2.7 /usr/local/lib/python3.7 /usr/share/python /usr/share/man/man1/python.1.gz

Then you need to reload system daemon and enable this service to allow to run after system startup. This service will start after Network is up. You can do by these commands:
systemctl daemon-reload
systemctl enable TestStartup (or how you named your member)

You can test, that start command is proper by this command:
systemctl start TestStartup

And check its status by this command:
systemctl status TestStartup

Then you can reboot the computer and check that it worked. I don't say that is is your solution for 100% but it may worth a try.


text:
Q: How can I call a CGI function within a javascript function? How can I call a CGI function within a javascript function? Such like this:
function jsFun()
{
    //something that can call a CGI function
}

A: Try jQuery.
function jsFun() {
    $.post(YOUR_CGI_URL, YOUR_PARAMS);
}


text:
Q:  not returning seconds in .value in Chromium Consider the following input field

document.getElementById("inp").addEventListener(
  "change",
  function(e) {
    document.getElementById("div").textContent = e.target.value;
  }
);
<input type="time" step="1" value="00:00:00" id="inp" />

00:00:00

When tested in Firefox, the value is what I expect when the input is changed -- the format is hh:mm:ss. But when tested in Chromium (67.0.3396.99), when the input is changed to anything that has 0 seconds, e.g. 01:00:00, the value attribute only returns hh:mm.
Is this correct / intended behaviour as per the specs? (Edit: It is.) And the main question: Is there a standard way that I'm unaware of, that is more preferable than .value, to get its value in hh:mm:ss, or do I have to resort to some JavaScript string parsing?

A: The outputs of Firefox and Chromium are actually both consistent with the specs.
The HTML Living Standard (Last Updated 24 July 2018) states:

The value attribute, if specified and not empty, must have a value that is a valid time string.

And "valid time string" is defined as follows:

A string is a valid time string representing an hour hour, a minute
  minute, and a second second if it consists of the following components
  in the given order:

*

*Two ASCII digits, representing hour, in the range 0 ≤ hour ≤ 23

*A U+003A COLON character (:)

*Two ASCII digits, representing minute, in the range 0 ≤ minute ≤ 59

*If second is nonzero, or optionally if second is zero:

*

*A U+003A COLON character (:)

*Two ASCII digits, representing the integer part of second, in the range 0 ≤ s ≤ 59

*If second is not an integer, or optionally if second is an integer:

*

*A U+002E FULL STOP character (.)

*One, two, or three ASCII digits, representing the fractional part of second

Credits to user @int32_t for linking me to the current standard.

A: For what it's worth the JavaScript string parsing is very simple and straight-forward to implement:

document.getElementById("inp").addEventListener(
  "change",
  function(e) {
    let time = e.target.value;
    if (time.length < 6) { // missing :ss on chrome
      time += ':00'; // add it ourselves
    }
    document.getElementById("div").textContent = time;
  }
);
<input type="time" step="1" value="00:00:00" id="inp" />

00:00:00


text:
Q: Convert object in JSON to map in Java Been trying to convert an object in JSON to java using Gson but many things do not match up.
Before the object was an int, now it's converted into an object.
This is part of the JSON (I need only damage to get converted):
I've tried most of the guides online but still not helpful at all.
[
  {
    "username": "lol",
    "value": [
      "one","two"
    ],
    "Power": [
      {
        "type": "Damage",
        "damage": {"first":2, "second":0,"third":0}
}]}]

A: The JSON you are trying to parse seems not a valid Json structure. Use this https://jsonformatter.curiousconcept.com/ to validate the JSON structure and try parsing.

A: To convert your Text into an Hashmap, use this.
String yourJson = "insert your JSON here";
Type type = new TypeToken<List<Map<String, Object>>>() {}.getType();
List<Map<String, Object>> parsedJson = new Gson().fromJson(yourJson, type);

now you can access it via:
Map<String, Object> user = (Map<String, Object>) parsedJson.get(0);
List<Map<String, Object>> userPowers = (List<Map<String, Object>>) user.get("Power");
Map<String, Object> usersFirstPower = userPowers.get(0);
Map<String, Object> firstPowerDamage = (Map<String, Object>) usersFirstPower.get("damage");
System.out.println(firstPowerDamage.get("first").toString());

Edit
This is another way to use Gson:
String yourJson = "...";
JsonArray map = (JsonArray) new JsonParser().parse(yourJson);
System.out.println(map.get(0).getAsJsonObject().get("Power").getAsJsonArray().get(0).getAsJsonObject().get("damage"));


text:
Q: Software keyboard move editTexts for android I'm trying to get the editTexts, and sign in button to move up when the software keyboard is out however I want the background to not be compressed(I'm going to add an image soon). I have the TextView(Login), two EditTexts(email and password) and signin button in a ScrollView because I thought that might help however I have not be able to figure anything out.
http://i.imgur.com/vlYifc6.png
http://i.imgur.com/vlYifc6.png
This is the xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" >

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:id="@+id/textLayout">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Login"
                android:id="@+id/loginView"
                android:textSize="22dp"
                android:layout_above="@+id/textLayout"
                android:layout_centerHorizontal="true" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/emailTextfield"
                android:inputType="textEmailAddress"
                android:background="@android:drawable/edit_text"
                android:textColor="@android:color/primary_text_light"
                android:text="andresc1305@yahoo.com"
                android:hint="Email" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Password"
                android:text="Andres123"
                android:background="@android:drawable/edit_text"
                android:textColor="@android:color/primary_text_light"
                android:ems="10"
                android:id="@+id/passwordTextfield" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="SIGN IN"
                android:background="@android:color/transparent"
                android:textSize="24dp"
                android:id="@+id/signinButton"
                android:layout_below="@+id/textLayout"
                android:layout_centerHorizontal="true"
                android:onClick="onSigninClick"/>
        </LinearLayout>
    </ScrollView>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Forgot your password?"
        android:background="@android:color/transparent"
        android:textSize="14dp"
        android:id="@+id/forgotButton"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="onPasswordRecoverClick"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register"
        android:background="@android:color/transparent"
        android:textSize="14dp"
        android:id="@+id/registerButton"
        android:layout_alignTop="@+id/forgotButton"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="onRegisterClick"/>

</RelativeLayout>

A: Look at this answer. In short, your problem can most likely be solved by setting the following in your AndroidManifest.xml inside the relevant activity or application element:
android:windowSoftInputMode="adjustResize"

A: @PPartisan
This is without:
android:windowSoftInputMode="adjustResize"

http://i.imgur.com/tbNioU2.png
This is with:
http://i.imgur.com/7ZePHjS.png
Beside the compression you can see my "Forgot your password" and "Register" buttons but I have those outside my ScrollView in the XML. Is there a way to scroll the LinearLayout (which contains the Login(TextView, email(EditText), password(EditText), and Signin(button) up when the software keyboard comes up?
The answer by zmilojko seems like what I want to do but he only says to add the ScrollView and not what to do after that has been added. Is there something I can place in the  to make it move up when the software keyboard comes up?

A: see this thread, i think it can help you
layout of the screen moves up when keyboard is displayed
or just try to put this in your xml:
android:windowSoftInputMode="adjustPan"

or this
android:windowSoftInputMode="adjustNothing"

Seems like it works different in each case.


text:
Q: Owl carousel is breaking the page Hi I used this Codepen for a client site (Squarespace). I tinkered a lot via CSS only.>

*

*Please check a specific client page; password is mmmm1234

*Scroll down and check "Discover Online Experiences" section where I implemented the slider

*For example, if viewed in a smaller screen size, like 1280px width, page breaks

*It breaks most especially in iPad versions

*Usually, if we put 4 or 5 cards only, it won't break the page

*But eventually we should be able to put more

*A contributor / developer from Squarespace couldn't help me about this and mentioend that maybe the owlcarousel itself had the problem

*Can anyone help me?

Below is the css and js of the one I used for client's

<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.40/css/uikit.min.css" rel="stylesheet">

A: UPDATED
When the Owl carousel has a lot of elements, its owl-stage block becomes very wide and the carousel takes the full width of the screen from the parent boxes, which they are ready to yield to it.
And among its parent blocks there is a block with the .content-wrapper class, which has the ability to become wider than the visible area of the screen.
Class .page-section:not(.full-bleed-section)>.content-wrapper has CSS properties:
   box-sizing: content-box;
   padding-left: 30px;
   padding-right: 30px;

Class .page-section>.content-wrapper has properties:
   box-sizing: content-box;
   max-width: 1363px;
   width: 100%;

As a result we have 100% + 60px for the potential width of this block:
https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen.
content-box gives you the default CSS box-sizing behavior.

This is not noticeable on desktop while the max-width property is in effect. But on a narrow screen it ceases to constrain the width of the block and it goes beyond the border of the visible area. And then we see a horizontal scroll bar and an extra white area on the right side of the page layout.
Solution 1: Define box-sizing: border-box; for this block. In this case, padding will be counted within 100% of the width, not added to them.

Solution 2: If you need to use exactly box-sizing: content-box; here, you can take advantage of the fact that this block already has the display: flex; property and let it figure out on its own how much space it can provide for its content.
  flex-basis: 100%;
  width: 0;

Both solutions work well when editing the site with the developer tools. They give reliable results for any screen width, as far as I could see.
On the web page, you also need to pay attention to the CSS specificity in order for the new properties to work.


text:
Q: LinkedIn REST API Cant Send Message; Couldt parse mailbox-item document: error: Unexpected end of file after null Im using Linkedin Rest Api on a site im building, in general works great  the only problem is that i cant send messages to my connections.
({'status': '400',
  'content-length': '302',
  'transfer-encoding': 'chunked',
  'vary': '*',
  'server': 'Apache-Coyote/1.1',
  '-content-encoding': 'gzip',
  'date': 'Wed, 28 Mar 2012 22:52:35 GMT',
  'x-li-request-id': 'QU0G42N6TV',
  'nncoection': 'close',
  'x-li-format': 'xml',
  'content-type': 'text/xml;charset=UTF-8'},
  '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  \n<error>\n <status>400</status>
  <timestamp>1332975155652</timestamp>
  <request-id>QU0G42N6TV</request-id>
  <error-code>0</error-code>
  <message>Couldn\'t parse mailbox-item document: error: Unexpected end of file after null</message>\n</error>\n'

this how i call the api:
client.request(url,'POST','text/xml',param)
where:
url = 'http://api.linkedin.com/v1/people/~/mailbox'

param:
<?xml version='1.0' encoding='UTF-8'?><mailbox-item>
<recipients>
<recipient>
<person path='/people/TquMAMeCCD' />
</recipient>
</recipients>
<subject>Congratulations on your new position.</subject>
<body>Youre certainly the best person for the job!</body> </mailbox-item>

Thanks!

A: My Problem was finally on the header, i wasn't setting the right content-type. That fixed it.


text:
Q: Shell script with SFTP and mget finishing before downloads are complete Here is my script:
#!/usr/bin/expect
spawn /usr/bin/sftp user@place
expect "password:"
send "mysecret\n"
expect "sftp>"
send "mget dir/*.csv\n";
expect "sftp>"
send "quit\n"

It starts to download but after a few seconds, it sends the quit command and exits the program before the downloads are complete.
The only way I've successfully made it stop is to throw in an "interact" command but because I want to run this as a cron job, I don't want to just spawn processes that end up sitting.
Is there a way to accomplish this?
edit:
Someone will ask why I don't have a key setup... this is the only method allowed to me by the vendor.

A: Adding the line set timeout -1 appears to have fixed this problem
The whole script should look as such:
#!/usr/bin/expect
set timeout -1
spawn /usr/bin/sftp user@place
expect "password:"
send "mysecret\n"
expect "sftp>"
send "mget dir/*.csv\n";
expect "sftp>"
send "quit\n"

A: Well, if you can use Perl:
use Net::SFTP::Foreign;

my $sftp = Net::SFTP::Foreign->new('user@place', password => 'mysecret');
$sftp->mget("dir/*.csv", '.',
             on_error => sub {
               warn "unable to copy '$_[1]{filename}':".$sftp->error."\n";
             });

You will have to install Net::SFTP::Foreign and IO::Pty (also available as packages in several linux distributions).


text:
Q: jquery Chosen and mCustomScrollbar not working properly together I use jquery Chosen together with malihu's plugin mCustomScrollbar and
I found it not compatible.
I want to apply the scrollbar on chosen result and its not working. Here is my working fiddle to see my work.
HTML:

$(function() {
  $('select.select').chosen({
    disable_search_threshold: 10,
    width: "50%"
  });

  //$('.chosen-results').mouseenter(function() {
    $('.chosen-results').mCustomScrollbar({
      theme: "dark-3"
    });
  //});
});
.select {
  max-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.jquery.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.css" rel="stylesheet"/>

<select id="name" class="select">
  <option value="">Select</option>
  <option value="aaa">aaa</option>
  <option value="bbb">bbb</option>
  <option value="ccc">ccc</option>
  <option value="ddd">ddd</option>
  <option value="eee">eee</option>
  <option value="fff">fff</option>
</select>

jsFiddle: https://jsfiddle.net/bbwfvcj0/

A: You have to initialize the mCustomScrollbar when it is visible.

$(function() {
  $('select.select').chosen({
    disable_search_threshold: 5,
    width: '50%'
  });
  $('select.select').on('chosen:showing_dropdown', function() {
    $('.chosen-results:visible').mCustomScrollbar({
      theme: 'minimal-dark'
    });
  });
  $('select.select').on('chosen:hiding_dropdown', function() {
   if($(".chosen-results").length) {
    $('.chosen-results').mCustomScrollbar('destroy');
    }
  });
});
.chosen-drop .chosen-results {
  max-height: 100px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.jquery.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.css" rel="stylesheet" />

<select id="name" class="select">
  <option value="">Select</option>
  <option value="aaa">aaa</option>
  <option value="bbb">bbb</option>
  <option value="ccc">ccc</option>
  <option value="ddd">ddd</option>
  <option value="eee">eee</option>
  <option value="fff">fff</option>
  <option value="ggg">ggg</option>
  <option value="hhh">hhh</option>
</select>


text:
Q: how to make setTimeout refer to context of object? var myObj = {
    name:"mike",
    go:function(){
        console.log(this.name);
    }

}

myObj.go()   //logs out mike
setTimeout(this.myObj.go,200)  //logs out (emptyString)

A: Try this:
setTimeout(function(){
  myObj.go();
},200);

A: Define a variable reffering to the object before:
var _this = this;
setTimeout(function() {_this.myObj.go();}, 200);

A: Several ways:
setTimeout(this.myObj.go.bind(this.myObj), 200);

or
var that = this;
setTimeout(function () {
    that.myObj.go();
}, 200);

Note that .bind isn't supported in older browsers, so a polyfill may be required in order to support it. Here's some information about the method: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

A: var myObj = {
    name:"mike",
    go:function(){
        console.log(this.name);
    }

}

setTimeout(function(){myObj.go()},200)

A: Try this
var myObj = {
    name:"mike",
    go:function(){
        console.log(this.name);
    }

}

myObj.go();   //logs out mike
setTimeout(function(){
    myObj.go(); //logs out mike too
},200);

A: Your code is right minus a few things.
setTimeout(this.myObj.go,200)

Should be
setTimeout(function() {myObj.go()},200)

It was undefined because this.myObj was not in the scope of setTimeout, nor was it wrapped in an anonymous function, or a variable function. You were on the right track though!


text:
Q: Java null arguments when chaining Constructors Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object):
public class Rectangle {

    int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle source) {
        this(source.width, source.height);
    }
}

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

A: Yes, you can use a helper method which will throw the exception if necessary, and return the original value otherwise... you can call that within your constructor invocation, as you're allow method calls as part of argument evaluation.
// In a helper class
public static <T> T checkNotNull(T value) {
    if (value == null) {
        throw new IllegalArgumentException();
    }
    return value;
}

Then use it as:
public Rectangle(Rectangle source) {
    this(Helper.checkNotNull(source).width, source.height);
}

However... I believe that NullPointerException is the recommended exception to throw here anyway (in Effective Java 2nd edition, for example), which your existing code will throw already. So you quite possibly don't want to make any change to your existing code.
If you want a helper method for checks like this but are happy for it to throw NullPointerException, I'd recommend using Guava and its Preconditions class, which has this and a lot of other helpful checking methods.
Also note that Java 1.7 introduced java.util.Objects which has requireNonNull, so you don't even need a third party library.

A: One text-book trick is move the initialization out of the constructor to a method. Then, you can have whatever code you want before it:
public class Rectangle {

    int width, height;

    public Rectangle(int width, int height) {
        init(width, height);
    }

    public Rectangle(Rectangle source) {
        if (source == null) {
            throw new IllegalArgumentException("source can't be null!");
        }
        init(source.width, source.height);
    }

    private void init(int width, int height) {
        this.width = width;
        this.height = height;
    }
}

A: If you really do want to throw an IllegalArgumentException, I think the cleanest solution is to use a static method instead of a constructor:
public static Rectangle from(Rectangle source) {
    if (source == null) {
        throw new IllegalArgumentException("source can't be null!");
    }
    return new Rectangle(source.width, source.height);
}

Or you could just add a copy method:
public Rectangle copy() {
    return new Rectangle(this.width, this.height);
}

I'd prefer the latter, since it removes the need to concern yourself with the Rectangle possibly being null. Note that this will cause a NPE if you use this with a null Object, which is possibly a further indication that an NPE is fine.

A: You can do this:
public Rectangle(Rectangle source) {
     this(checkNotNull(source, "Source cannot be null").width, source.height);
}

private static <T> T checkNotNull(T t, String msg) {
    if (t == null) throw new IllegalArgumentException(msg);
    return t;
}

I also agree with Jon Skeet that a NullPointerException is not a bad bevahiour in this case. The only thing is that in long lines when you get an NPE it can be a bit hard to identify which object is null, which is why a more specific message can be useful.
You can also not reinvent the wheel and use standard java.util.Objects methods if you don't bother throwing a NullPointerException instead:
public Rectangle(Rectangle source) {
     this(Objects.requireNonNull(source, "Source cannot be null").width, source.height);
}

if your error message is expensive to build, you can provide a Supplier<String> instead, to pay the cost of the construction of the message only when it's actually needed:
 public Rectangle(Rectangle source) {
     this(Objects.requireNonNull(source, () -> explainError(source)).width, source.height);
}

A: You can do like this
int width, height;

public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
}

public Rectangle(Rectangle source) {
   if(source != null) {
      width = source.width;
      height = source.height;
   }
}


text:
Q: PHP MySQL Query insert Function Is there any possibilty to add a function-call in a SQL-Query?
At the moment i'm doing this:
§sql = "SELECT * FROM TABLE";

But I want, that I'm using a field from my table and call with this a function, which return me true or false.
Maybe a example could explain it better:
"$sql = SELECT * FROM TABLE WHERE functionCall(TABLE.FIELD)=true";

Then I just get all entrys from TABLE, where my function returns true.
Is there any possibility to do that?

A: you could use If condition before  like that :
 $sql = "SELECT * FROM TABLE";

 fetch your query here

 If(functionCall($row['FIELD'])==true) {
    your wished code here
    .......
  }


text:
Q: How to Reset a Boundary Timer Time Cicle and/or Time Duration in Activiti 5.22.0? Does anyone know how can I programmatically reset a Boundary
Timer Time Cicle and/or Time Duration from a Java TaskListener using Activiti 5.22.0?

A: Can you please try this?

processInstanceId => process Instance ID
jobs = processEngine.getManagementService().createTimerJobQuery().processInstanceId(processInstanceId).list();
TimerJobEntity tJobEntity = (TimerJobEntity) job;
tJobEntity.setDuedate(date);

where date is new date that we want to set.