Q: Parsing modified MNIST in the form of CSV for Conv Neural Network I'm planning on using this modified version of MNIST for benchmarking research, but they are currently in .mat format. So, I've read on StackOverflow that MatlabRecordReader actually isn't that robust, and that it's far smarter to change the data into CSV format.
I've downloaded Matlab and changed the .mat file to a .csv file that has 60000 (for the test data) lines, the first 784 values of each line being the pixel values of the image itself and the last 10 values being the label (though I believe I can easily condense the label into one value at the end of the first 784 values).
Now that I have this data, I'm not exactly sure how I should pass it through an Iterator properly for my Conv Neural Network. I've looked up the documentation, but this isn't exactly what I need, and looking up the examples in the the docs for the RecordReaderDatasetIterator was also a near-miss because it treats lines of the CSV files as either a 1 dimensional vector (as apposed to a matrix) or formats the data for linear regression.
I hope this has been clear enough. Could someone please assist me?

A: Use CSVRecordReader with the label appended to the end of each row as an integer with 0 to 9.
Use convolutionalFlat as the setInputType at the bottom.
Example snippet:

       .setInputType(InputType.convolutionalFlat(28,28,1))
                .backprop(true).pretrain(false).build();

Whole code example for the neural net config:
https://github.com/deeplearning4j/dl4j-examples/blob/master/dl4j-examples/src/main/java/org/deeplearning4j/examples/convolution/LenetMnistExample.java


Q: Bootstrap select plugin is not working I am trying to use this Bootstrap-Select Plugin. I have created a fiddle also according to the demo,
http://jsbin.com/anepet/1/edit
But i am totally blank and not understand why this is not working, the appearance of select list is not changing, can anybody please help me out?

A: Perhaps add the invocation to make all .selectpicker elements a selectpicker? You will pretty much hit your head after seeing this. In the source of the Select plugin page you will see countless times where the demo uses a css selector to invoke .selectpicker() on the elements.
<script type="text/javascript">
    $('.selectpicker').selectpicker();
</script>

Please see. http://jsbin.com/anepet/3/edit

A: You are including the js twice and not invoking the selectpicker()..
remove this line:
    <script src="http://silviomoreto.github.com/bootstrap-select/javascripts/bootstrap-select.js"></script>
and add this:
<script type="text/javascript">
    $(document).ready(function(){
        $('.selectpicker').selectpicker();
    });
</script>

in the <header> and it will work


Q: Como obtengo los datos de un Task para mostrarlos en una vista de MVC? Tengo un método en mi api de net core que me devuelve un ActionResult envuelto en un Task :
public async Task<ActionResult> GetMobileAplicacion(){
   ....
   return Ok(aplicaciones);
}

Ese api NO esta hecho con Entity Framework sino con métodos propios. Ahora lo que quiero es hacer una parte visual para el backend por decirlo de alguna forma sin embargo cuando trato de hacer lo siguiente en mi controlador MVC :
       public ActionResult Index()
        {
            var lista =new MobileAplicacionController();

            var result = lista.GetMobileAplicacion();

            ViewBag.aplicaciones = result;

            return View(ViewBag.aplicaciones);
        }

Me tira el siguiente error:
RuntimeBinderException: Cannot implicitly convert type 'System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.ActionResult>' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)

Como puedo convertir el actionresult en un ienumerable o en un viebag que pueda mostrar en una vista razor?

A: Primero te paso al enlace en stackoverflow en inglés donde yo obtuve la respuesta, de la cual participé.
Aquí te muestro con un test unitario cómo obtener el valor dentro de:
Task<IActionResult>

Si bien no es exactamente el mismo escenario que lo que tu dices, si es el mismo objetivo, obtener el valor.
[TestMethod]
public async Task Get_ReturnsAnArea()
{
    // Arrange
    string areaId = "SomeArea";
    Area expectedArea = new Area() { ObjectId = areaId, AreaNameEn = "TestArea" };

    var restClient = new Mock<IRestClient>();
    restClient.Setup(client => client.GetAsync<Area>(It.IsAny<string>(), false)).ReturnsAsync(expectedArea);

    var controller = new AreasController(restClient.Object);

    //// Act

    // We now await the call
    IActionResult actionResult = await controller.Get(areaId);

    // We cast it to the expected response type
    OkObjectResult okResult = actionResult as OkObjectResult;

    // Assert

    Assert.IsNotNull(okResult);
    Assert.AreEqual(200, okResult.StatusCode);

    Assert.AreEqual(expectedArea, okResult.Value);

   // We cast Value to the expected type
    Area actualArea = okResult.Value as Area;
    Assert.IsTrue(expectedArea.AreaNameEn.Equals(actualArea.AreaNameEn));
}

Lo principal aquí es obtener el valor (value) que te devuelve el ActionResult.
En mi caso eso lo puedes ver en:
OkObjectResult okResult = actionResult as OkObjectResult;
var valor = okResult.Value; // esto te lo he puesto a modo ilustrativo.

Entiendo que View tiene que recibir una 'System.Collections.IEnumerable' pero le estás pasando un Task< Microsoft.AspNetCore.Mvc.ActionResult >
Por tanto, primero hay que hacer el await del metodo en tu caso GetMobileAplicacion ya que es asíncrono para luego obtener el valor del ActionResult.
Retomando tu ejemplo y modificándolo un poco creo que podría funcionar así:
public ActionResult Index()
        {

            var lista =new MobileAplicacionController();

            var result = await lista.GetMobileAplicacion(); //ya que es async

            ViewBag.aplicaciones = result.value;

            return View(ViewBag.aplicaciones);
        }

Editado:
En relación a tu método de tu API de .NET Core no te es necesario modificar el controlador en el api y decirle el tipo de datos que devuelve ya que  OkObjectResult recibe un object y una des su propiedad (heredada) Value es de tipo object como puedes ver aquí
namespace Microsoft.AspNetCore.Mvc
{
    public class ObjectResult : ActionResult, IStatusCodeActionResult, IActionResult
    {
        public ObjectResult(object value);

        [ActionResultObjectValueAttribute]
        public object Value { get; set; }

Por tanto tu Controlador podría ser así sin necesidad de especificar el tipo:
[Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public async Task<IActionResult> GetStringArray()
        {
            return Ok(new string[] { "value1", "value2" });  //Devuelve un string Array
        }

        [HttpGet("{id}", Name = "Get")]
        public async Task<IActionResult> GetInt(int id)
        {
            return Ok(5); //Devuelve un int
        }
    }

Es por eso que en el Unit Test que te puse de ejemplo al principio te puse otra Clase (Area) ya que de esa forma da igual el tipo devuelto porque queda envuelto dentro del Value del ActionResult.
Espero que te sea de ayuda.

A: Te en cuenta que estás llamando a un Web Api que funciona de manera asíncrona public async Task<ActionResult> GetMobileAplicacion().
Para poder obtener correctamente el resultado, tienes dos opciones:
1 - De forma asíncrona - async / await
Debes transformar la Acción Index() de tu Controlador MVC en asíncrona:
    public async Task<ActionResult> Index()
    {
        var lista = new MobileAplicacionController();
        var result = await lista.GetMobileAplicacion();
        ViewBag.aplicaciones = result;
        return View(ViewBag.aplicaciones);
    }

2 - De forma síncrona - Result
Si no importa que el proceso sea síncrono, puedes utilizar Result para obtener directamente el resultado:
    public ActionResult Index()
    {
        var lista = new MobileAplicacionController();
        var result = lista.GetMobileAplicacion().Result;
        ViewBag.aplicaciones = result;
        return View(ViewBag.aplicaciones);
    }

A: Necesitas devolver una collecion de ActionResult de la siguiente manera
Para un objeto simple
 public async Task<ActionResult<MiTipo>> GetMobileAplicacion()

Para una coleccion
 public async Task<ActionResult<MiTipoDeColeccion<MiTipo>>> GetMobileAplicacion()

Y luego sacar el resultado de la tarea con Wait() / Result / o async y await como otros ya lo han indicado.

A: Aunque no entiendo muy bien porqué quieres llamar un ActionResult desde otro ActionResult, puede que esto te funcione:
 public ActionResult Index()
        {
            var lista =new MobileAplicacionController();
            var result = lista.GetMobileAplicacion().Result;
            ViewBag.aplicaciones = result;
            return View(ViewBag.aplicaciones);
        }

básicamente, al ser un Task, invocado desde un método no asincrono, debes acceder a Result para que se evalue el Task y obtengas el resultado de la misma.
Ahora, creo que la forma correcta para ejecutar un action desde otro Action es como se describe aqui: ControllerBase.RedirectToAction

A: La respuesta de @Sebastian Inones fue la que más me ayudo:
Primero tuve que modificar el controlador en el api  y decirle el tipo de datos que devuelve:
public async Task<ActionResult<MobileAplicacion>> GetMobileAplicacion()

y segundo en el controlador MVC tuve que pegar este código:
 public async Task<ActionResult> Index()
        {

            var controller = new MobileAplicacionController();

            var action =await controller.GetMobileAplicacion();

            OkObjectResult okResult =  action.Result as OkObjectResult;

            ViewBag.aplicaciones = okResult.Value;

            return View();
        }


Q: Passive Link in Angular 2 -  equivalent In Angular 1.x I can do the following to create a link which does basically nothing:
My Link

But the same tag navigates to the app base in Angular 2. What is the equivalent of that in Angular 2?
Edit: It looks like a bug in the Angular 2 Router and now there is an open issue on github about that.
I am looking for an out of the box solution or a confirmation that there won't be any.

A: Here are some ways to do it:

*

*Click Me

*Click Me

*Click Me

A: You have prevent the default browser behaviour. But you don’t need to create a directive to accomplish that.
It’s easy as the following example:
my.component.html
Link

my.component.ts
goToPage(pageIndex, event) {
  event.preventDefault();
  console.log(pageIndex);
}

A: I have 4 solutions for dummy anchor tag.
    1.
    2.
    3.

4.If you are using bootstrap:
<button class="btn btn-link p-0" type="button" style="cursor: pointer"(click)="doSomething()">MY Link</button>

A: Here is a simple way

capture the bubbling event and shoot it down

A: Updated for Angular 5
import { Directive, HostListener, Input } from '@angular/core';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector : '[href]'
})
export class HrefDirective {
  @Input() public href: string | undefined;

  @HostListener('click', ['$event']) public onClick(event: Event): void {
    if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) {
      event.preventDefault();
    }
  }
}

A: Not sure why people suggest using routerLink="", for me in Angular 11 it triggers navigation.
This is what works for me:

No data yet, ready to create?

A: In my case deleting href attribute solve problem as long there is a click function assign to a.

A: If you have Angular 5 or above, just change
Click me

into
Click me

A link will be displayed with a hand icon when hovering over it and clicking it won't trigger any route.
Note: If you want to keep the query parameters, you should set queryParamsHandling option to preserve:
Click me

A: There are ways of doing it with angular2, but I strongly disagree this is a bug. I'm not familiarized with angular1, but this seems like a really wrong behavior even though as you claim is useful in some cases, but clearly this should not be the default behavior of any framework.
Disagreements aside you can write a simple directive that grabs all your links and check for href's content and if the length of it it's 0 you execute preventDefault(), here's a little example.
@Directive({
  selector : '[href]',
  host : {
    '(click)' : 'preventDefault($event)'
  }
})
class MyInhertLink {
  @Input() href;
  preventDefault(event) {
    if(this.href.length == 0) event.preventDefault();
  }
}

You can make it to work across your application by adding this directive in PLATFORM_DIRECTIVES
bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: MyInhertLink, multi: true})]);

Here's a plnkr with an example working.

A: A really simple solution is not to use an A tag - use a span instead:
Click here

span.link {
  color: blue;
  cursor: pointer;
  text-decoration: underline;
}

A: An achor should navigate to something, so I guess the behaviour is correct when it routes. If you need it to toggle something on the page it's more like a button? I use bootstrap so I can use this:
<button type="button" class="btn btn-link" (click)="doSomething()">My Link</button>

A: I am using this workaround with css:
/*** Angular 2 link without href ***/
a:not([href]){
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    user-select: none
}

html
My link

Hope this helps

A: simeyla solution:

A: That will be same, it doesn't have anything related to angular2. It is simple html tag.
Basically a(anchor) tag will be rendered by HTML parser.
Edit
You can disable that href by having javascript:void(0) on it so nothing will happen on it. (But its hack). I know Angular 1 provided this functionality out of the box which isn't seems correct to me now.
Test

Plunkr

Other way around could be using, routerLink directive with passing "" value which will eventually generate blank href=""
Click me

A: you need to prevent event's default behaviour as follows.
In html
view

In ts file
view(event:Event){
 event.preventDefault();
 //remaining code goes here..
}

A: I wonder why no one is suggesting routerLink and routerLinkActive (Angular 7)

I removed the href and now using this. When using href, it was going to the base url or reloading the same route again.

A: Updated for Angular2 RC4:
import {HostListener, Directive, Input} from '@angular/core';

@Directive({
    selector: '[href]'
})
export class PreventDefaultLinkDirective {

    @Input() href;
    @HostListener('click', ['$event']) onClick(event) {this.preventDefault(event);}

    private preventDefault(event) {
        if (this.href.length === 0 || this.href === '#') {
            event.preventDefault();
        }
    }
}

Using
bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: PreventDefaultLinkDirective, multi: true})]);


Q: How can I compare two lists of means in a dataframe, by row I am trying to compare with t-test, two list of gene expressions mean values.
My matrix is built like this
col1 <- c(6.7 , 8.4, 3.1)
col2 <- c(7.7, 8.8, 3.6)
matrix <- cbind(col1, col2)
rownames(matrix) <- c("gene1", "gene2", "gene3")

I want to get the p value for each genes.
all that I know is that col1 correspond to means calculated on 22 sample and col2 30 samples.
I tried to apply a t-test per row, but it is not working.
apply(t.test, matrix$col1, matrix$col2, 1)

A: I think you need to do a better job of defining what, exactly it is that you want to compare.  There's no such thing as a p value of a mean.  What are you comparing, base pair variance between a gene in column 1 and one in column 2?  Or is col. 1 the full sequence of one gene and col2 the full sequence of a second gene?  Your question doesn't make it clear what you're analyzing, and without that you may have good math that means nothing.
Here's a good definition of t test, assuming that that test is, in fact, what you ought to be using.  Note that this test requires not only the difference between the means (which you could calculate from what you showed us), the standard deviation of each mean (which you didn't), and the number of items (which you did).  This means we only have 2 out of 3 of the necessary inputs.  To get the 3rd, either you need to supply it, or you need to supply the raw data which produced it.


Q: Variable scoping in Manipulate Here is my attempt to manipulate the value of q for the PDF function. Whenever I use the manipulate function, nothing happens to the output. Can anyone explain why?

A: You have many code errors, such as the error in defining a function G[x_]= instead of G[x_]:=, the fact that sigma cannot have a value (because q is not assigned), missing semicolons, and much more.
I presume you're lifting my code from here.
Anyway, here is your answer:
Manipulate[
 Integrate[
  PDF[
      NormalDistribution[0, -q Log[2, q] - (1 - q) Log[2, 1 - q]], x],
  {x, 0, 1}],
  {q, .1, .3}]

A: You have a variable scoping problem. The global q that appears in your definition of sigma is not the same as the local q that appears in your Manipulate expression. One way to fix it is:
sigma[q_] := -q Log2[q] - (1 - q) Log2[1 - q]
g[q_][x_] := PDF[NormalDistribution[0, sigma[q]], x]
Manipulate[g[q][x], {q, .0001, 1}]

A: Manipulate doesn't "see" the q term in the argument.
To fix this use
Manipulate[PDF[NormalDistribution[0, sigma], x] /. q -> Q, {Q, 0, 1}]

Or make sigma a function of q as
sigma[q_] := -q Log[2, q] - (1 - q) Log[2, 1 - q]
Manipulate[PDF[NormalDistribution[0, sigma[q]], x], {q, 0, 1}]


Q: How to implement pinch to zoom and flick with momentum for a drawing (graph) Core Graphics app? In my app, I drew a graph using Core Graphics (inside a view, inside a view). Not a graphing calc app though, it graphs patient data and marks it every six months, and it is larger than the screen, so the user needs to have some way to move around. I was wondering if there is an easy way to implement pinch to zoom, or to flick with momentum. I was planning on just using UITouch to get notified when these actions were performed, but it doesnt really give you a lot of information. For example, all you get with the pinch to zoom is the ratio that they have zoomed, and all you get with the flick is the direction that they have flicked. So, I was just going to implement basic flicks without momentum, and simple pinch to zoom without being able to move around too.
But I figured I would ask here first, to see if anyone has a better idea about how to do this (easily).
EDIT: I found lots of places that tell you how to do this with photos, but none with core graphics or something like that, thanks.

A: I ended up using a UIScrollView, which implements pinch to zoom, and flick automatically (well, almost).


Q: CodeBlocks - How to add an icon to a C program? I have a small C console program and I want to add an .ico file to it, so that the executable looks nice.
How can I do this in CodeBlocks with MinGW/gcc?

A: I could not find relevant help via google that a total beginner (like me for C) could follow, so I will Q&A this topic.

*

*First of all you need an .ico file. Put it in the folder with your main.c file.

*In CodeBlocks go to File -> New -> Empty File and name it icon.rc. It has to be visible in the Workspace/Project otherwise CodeBlocks will not be aware of this file. It will show up there in a project folder called Resources .

*Put the following line in it: MAINICON ICON "filename.ico". MAINICON is just an identifier, you can choose something different. More info 1 & More info 2.

*Save the files and compile - CodeBlocks will do everything else for you

What will happen now, is windres.exe (the Resource Compiler) compiling the resource script icon.rc and the icon to an object binary file to obj\Release\icon.res. And the linker will add it to the executable.
It's so easy yet it took me quite a while to find it out - I hope I can save someone else having the same problem some time.


Q: Array.pop - last two elements - JavaScript I have a question using Array.pop function in JavaScript. Array.pop removes and returns the last element of an Array. My question is then: is it possible to remove and return the last TWO elements of array and return them instead of the last?
I am using this function to return the last element of URL, like this:

URL: www.example.com/products/cream/handcreamproduct1

'url'.splice("/").pop(); -----> "handcreamproduct1"

what i want is:
'url'.splice("/").pop(); -----> "cream/handcreamproduct1"

I want to take the last two parameters in the url and return them, with .pop i only get the last one. Remember that the URL is dynamic length.  The url can look like this:

URL: www.example.com/products/cream/handcreamproduct1
OR

  URL: www.example.com/products/handcream/cream/handcreamproduct1

A: Split the array, use Array#slice to get the last two elements, and then Array#join with slashes:

var url = 'www.example.com/products/cream/handcreamproduct1';

var lastTWo = url
  .split("/") // split to an array
  .slice(-2) // take the two last elements
  .join('/') // join back to a string;

console.log(lastTWo);

A: There is no built in array function to do that.
Instead use
const urlParts = 'url'.split('/');
return urlParts[urlParts.length - 2] + "/" + urlParts[urlParts.length - 1];

A: I love the new array methods like filter so there is a demo with using this
let o = 'www.example.com/products/cream/handcreamproduct1'.split('/').filter(function(elm, i, arr){
    if(i>arr.length-3){
  return elm;
  }
});
console.log(o);

A: You can use String.prototype.match() with RegExp /[^/]+\/[^/]+$/ to match one or more characters that are followed by "/" followed by one or more characters that are followed by end of string

let url = "https://www.example.com/products/handcream/cream/handcreamproduct1";

let [res] = url.match(/[^/]+\/[^/]+$/);

console.log(res);

A: Note that if the URL string has a trailing / then the answers here would only return the last part of the URL:

var url = 'www.example.com/products/cream/handcreamproduct1/';

var lastTWo = url
  .split("/") // split to an array
  .slice(-2) // take the two last elements
  .join('/') // join back to a string;

console.log(lastTWo);

To fix this, we simply remove the trailing /:

const urlRaw = 'www.example.com/products/cream/handcreamproduct1/';
const url = urlRaw.endsWith("/") ? urlRaw.slice(0, -1) : urlRaw
const lastTWo = url
  .split("/") // split to an array
  .slice(-2) // take the two last elements
  .join('/') // join back to a string;

console.log(lastTWo);


Q: adding typings to a imported json file import { CharacterDataStructure } from "../../Typings/Interfaces"

declare module "../../Data/Characters/Raw_Characters.json" {
    export = CharacterDataStructure
}

import RawCharacters from "../../Data/Characters/Raw_Characters.json"

As you can see, I want to add a type to my JSON file but it recognises it as a non module. The reason why I want to do this is because of my interface,
Here is an example of my data in my json file and my interface:
JSON file:
{ id: "character_1", type: "item" }

my interface:
interface CharacterDataStructure {
 id: `character_${number}`
 type: "item"|"power up"
}

When I import my JSON file, it recognises id and type as string(s) and does not check their value to see if they match the interface. And thus this will give me an error


Q: Can I use non-constant array size for class members? in the code below, uint16_t sine[ANGULAR_RESO] throws an error
non static member reference must be relative to specific object struct
class BLDCControl  {
    public:
        uint16_t ANGULAR_RESO;
        uint16_t sine[ANGULAR_RESO];
        uint16_t pwm_resolution = 16;

}

What am I doing wrong?

A: To use the class as it is written ANGULAR_RESO must be a compile time constant and in this way it is no longer a specific member for every object. It must be static. If you need a varying array size, use  std::vector , as follows
class BLDCControl  {
    public:

        uint16_t ANGULAR_RESO;
        std::vector<uint16_t> sine;
        uint16_t pwm_resolution = 16;

}

And if ANGULAR_RESO is the size of your array (as @ aschepler suggested ), you can go without it because your std::vector has this size as a private member and you can get its value by std::vector<unit16_t>::size() method
#include <cstdint>
#include <vector>
struct BLDCControl  {
    BLDCControl(uint16_t ANGULAR_RESO, uint16_t pwm_resolution_v = 16) :
            pwm_resolution {pwm_resolution_v},
            sine {std::vector<uint16_t>(ANGULAR_RESO)}{}

    std::vector<uint16_t> sine;
    uint16_t pwm_resolution;

};
int main(){

    BLDCControl u(4, 16);
    std::cout << "ANGULAR_RESO is:\t"  << u.sine.size();

}


Q: Visual Studio call stack always off by a line I've been noticing that the call stack in VS always seems to be off by a line. Once I step into a function the line number for the stack frame I just left gets incremented and points to the next non-empty line. Then if I double click that frame in the Call Stack window it indeed takes me to some line after the function call that I'm actually in. I've repo'd this in empty projects in both VS2015 and VS2017 (debug builds).
In the pic below you'll notice the second stack frame indicates line 17, which is the return several lines below the Log() call where the debugger is actually stopped.
This is a trivial repro, but I'm seeing this constantly in real projects and I don't recall having this problem outside of the last few days.
Anyone have any idea what might be causing this?


Q: Android Camera preview has 'laces' or 'Mosaic' on the border use SurfaceTexture,Why the picture cannot full fill up the screen? I want to make camera preview only, but some reason causes the problem like the picture shows below:

I use a subclass of GLSurfaceView to preview. From the picture we can see the picture can't fully fill up the screen, but if I preview use mCamera.setPreviewDisplay(mHolder); then the result is correct.
Is SurfaceTexture display different on different device? Is SurfaceTexture or GLES11Ext.GL_TEXTURE_EXTERNAL_OES memory alignment?
Should SurfaceTexture make some configuration to fully fill up the screen?
Thanks.
The code I use almost like this:
activity content layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.camera.PreviewSurfaceView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

PreviewSurfaceView.java:
public class PreviewSurfaceView extends GLSurfaceView {
    private PreviewRenderer mRender;
    public PreviewSurfaceView(Context context) {
        this(context,null);
    }
    public PreviewSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setEGLContextClientVersion(2);

        mRender = new PreviewRenderer(context,this);

        setRenderer(mRender);

        setRenderMode(RENDERMODE_WHEN_DIRTY);
    }
}

PreviewRenderer.java:
public class PreviewRenderer implements GLSurfaceView.Renderer {
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        initShaders();
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        Camera.Parameters parameters = mCamera.getParameters();
        mCamera.setParameters(parameters);

        mTextureId = mGlesHelper.createTextureOESID();

        mSurfaceTexture = new SurfaceTexture(mTextureId);

        mSurfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
            @Override
            public void onFrameAvailable(SurfaceTexture surfaceTexture) {
                Log.d(TAG, "onFrameAvailable: tid = " + Thread.currentThread().getId());
            }
        });
        try {
            mCamera.setPreviewTexture(mSurfaceTexture);
            mCamera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        mSurfaceWidth = width;
        mSurfaceHeight = height;
    }
    @Override
    public void onDrawFrame(GL10 gl) {
        if (mSurfaceTexture != null){
            mSurfaceTexture.updateTexImage();
        }
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
        GLES20.glClearColor(0.6f, 0.5f, 0.3f, 1.0f);
        GLES20.glViewport(0,0,mSurfaceWidth,mSurfaceHeight);
        GLES20.glUseProgram(mRenderProgram);

        GLES20.glVertexAttribPointer(mVertexCoorLocation,3,GLES20.GL_FLOAT,false,0,mScreenVertexBuffer);
        GLES20.glEnableVertexAttribArray(mVertexCoorLocation);

        GLES20.glVertexAttribPointer(mTextureCoorLocation,2,GLES20.GL_FLOAT,false,0,mTextureBuffer);
        GLES20.glEnableVertexAttribArray(mTextureCoorLocation);

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
        GLES20.glUniform1i(mOesTextureLocation, 0);

        GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP,mIndics.length,GLES20.GL_UNSIGNED_SHORT,mIndicsBuffer);

        GLES20.glDisableVertexAttribArray(mVertexCoorLocation);
        GLES20.glDisableVertexAttribArray(mTextureCoorLocation);

        mSurfaceView.requestRender();
    }
}

vertex.glsl:
attribute vec4 a_vertexCoor;
attribute vec2 a_textureCoor;

varying vec2 v_textureCoor;

void main() {
    v_textureCoor = vec2(1.0 - a_textureCoor.y,1.0 - a_textureCoor.x);
    gl_Position = a_vertexCoor;
}

fragement.glsl:
#extension GL_OES_EGL_image_external : require

precision highp float;

uniform samplerExternalOES u_OEStexture;

varying vec2 v_textureCoor;

void main() {
    gl_FragColor = texture2D(u_OEStexture,v_textureCoor);
}

additional：

A: Through a day's study,I find the reason finally.The step of change as follow:
1.Change vertex.glsl and add some sentences:
uniform mat4 uVertexMatrix;
uniform mat4 uTextureMatrix;

void main() {
    gl_Position = uVertexMatrix*a_vertexCoor;
    vec2 textureCoor = (uTextureMatrix*vec4(a_textureCoor,0,1)).xy;

    v_textureCoor = vec2(textureCoor.x,textureCoor.y);
}

2.Change onDrawFrame() method and add some sentences:
....
//important code
mSurfaceTexture.getTransformMatrix(mTextureMatrix);
...
GLES20.glUniformMatrix4fv(mVertexMatrixLocation,1,false,mVertexMatrix,0);
GLES20.glUniformMatrix4fv(mTextureMatrixLocation,1,false, mTextureMatrix,0);
...

Then you can get the correct result through two steps descript above.
In the previous vertex.glsl,the code v_textureCoor = vec2(1.0 - textureCoor.x,1.0-textureCoor.y); can transform the texture to get correct view based on https://learnopengl.com/Getting-started/Textures ,but it not works always on various devices.
In many open source projects,such as google/grafika and aiyaapp/AAVT,matrix-transform has been used to handle texture.They inspire me,and handle the problem finally.


Q: When does $n-2$ divide $n-5$? We got asked this question today in a national exam:
$n$ is a positive integer; find the values of $n$ for which $n-2$ divides $n-5$.

A: $$\frac{n-5}{n-2}=1-\frac{3}{n-2}.$$
So we want the quantity $\frac{3}{n-2}$ to be an integer. Now ask yourself for what values of $n \in \{1,2,3,4, \ldots \}$ will $n-2$ divide $3$?

A: Hint: $$n-5=n-2-3$$ so we get $$\frac{n-5}{n-2}=1-\frac{3}{n-2}$$


Q: How to access slider menu from another activity? Hi I am working with android applications.I have a slider menu in my library project.I had integrated it with another project and I need to access the same slider menu in my new project.I tried with calling intent, but it calls the full activity.I need only slider menu from the library. How can I access this, please help me.Thanks in advance :)


Q: embed hyperlinks in a subliime text file One cool thing about Google Docs is that you can highlight a word, hit command-K (on a mac) and, hey presto, turn that word into a hyperlink.
One cool thing about Sublime Text is that it is better than Google Docs in every other way. My humble opinion.
Question: are there any plugins for ST that let you embed clickable hyperlinks into words? Specifically I want to do this for markdown files.


Q: how can pass this regular expression in C# ?about"[]" mean I have the following regular expression:
^[A-Z&&[^EIOSTUYZ]][X|0-9&&[^4-6]][A-F[NWX]].?.?$

I don't how can pass this regular expression. I trid AW0AW,AXFX,3D0E, but all can't pass it.


Q: Auto-start my program in administrative mode when system starts up without the UAC prompt My problem :
I made a program and i have this program for example now under this directory : "C:\Program Files (x86)\AppName", now in the program i'm saving some images in my program directory, but since this is in the C drive, it's giving me a access denied error, now i made the program to always run in administrative mode and that worked just fine, but also there is in my program a feature to auto-start my program when the system starts up using a registry key, but when the "always run in administrative mode" is ON, the program will not start even though there is a start-up key in the registry, and when the "always run in administrative mode" is OFF, it will start.

What I have tried so far :
I tried making an another executable file that will start when the system starts up and then it will run my main program and close it self and i knew that will work but now every time i start my computer, the User Access Control prompt  ask me if i trust this program even and that is not very user-friendly.
So i searched and i found that i can create scheduled task but i didn't find a lot of examples and but i tried creating one manually and it did work as wanted!
But here is a code which didn't work :
Imports Microsoft.Win32.TaskScheduler

 Using ts As New TaskService("\\RemoteServer")
    'Create a new task definition and assign properties
    Dim td As TaskDefinition = ts.NewTask()
    td.RegistrationInfo.Description = "Does something"

    'Create a trigger that will fire the task at this time every other day
    td.Triggers.Add(New DailyTrigger() With {
        Key.DaysInterval = 2
    })

    'Create an action that will launch Notepad whenever the trigger fires
    td.Actions.Add(New ExecAction("notepad.exe", "c:\test.log", Nothing))

    'Register the task in the root folder
    ts.RootFolder.RegisterTaskDefinition("Test", td)
End Using

And the problem with the code is :
It couldn't find the TaskService and it has no use of the TaskScheduler library!

Hope someone have some previous experience with that who can help me!

A: To answer your question:
To use that code you've got to download the Managed Task Scheduler Wrapper first. Then to make it run with administrative privileges you've got to set the RunLevel to TaskRunLevel.Highest on your TaskDefinition:
td.Principal.RunLevel = TaskRunLevel.Highest

However like Plutonix says you shouldn't be writing files to the directory of your program (as that's usually located in the restricted %ProgramFiles% folder).
Instead, use the %ProgramData% directory. You can get the path to it from your code via Environment.GetFolderPath():
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)

'Example:
Dim ConfigPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "AppName")
Dim ImagePath As String = Path.Combine(ConfigPath, "MyImage.png")

If Directory.Exists(ConfigPath) = False Then Directory.CreateDirectory(ConfigPath)


Q: Change state without overriding other values in react I am trying to change the state of my app without overriding the values that haven't changed. I am doing so using the spread operator, but something is going wrong.
Here is my base state : useState({data : [{name : undefined , project : []}] });
With setState i want to just add names but keep the project array empty since it didn't change.
setManager(prevState => ({...prevState , data : res.data}))

After performing setState the new state looks like this :
[
    {name: "John doe"},
    {name: "Jane Doe"}
]

as you can see the default state is completely overridden.
res.data looks like this by the way :
[
  {name: "john doe"},
  {name: "jane doe"}
]

A: By setManager(prevState => ({...prevState , data : res.data})) you're simply overriding your earier 'main' data property.
data is an array, new values are in array ... simply concat them
setManager(prevState => ({...prevState ,
  data : prevState.data.concat( res.data )
}))

After that you should have
[
  {name: undefined , project : []},
  {name: "john doe"},
  {name: "jane doe"}
]

... but probably you wanted to manage names and project separately:
const [manager, setManager] = useState({
  data: {
    name: undefined,
    project: []
  }
});

... or even
const [manager, setManager] = useState({
  name: undefined,
  project: []
});

This way you don't need to 'address' this data with 'intermediatory' .data
<Component names={manager.name} />

... not by {manager.data.name}.
Of course updating only name needs different code
setManager(prevState => ({
  ...prevState,
  name : prevState.name.concat( res.data )
}))

*

*...prevState prevents deleting project property

*name should be initialized with [], not undefined

*conditional rendering can be done with `{!manager.name.lenght && ... }

If you have separate states 'slices' then no need to use one common state, use many useState declarations.

A: Probably what you need is:
const [manager, setManager] = useState({
  data: [{ name: undefined, project: [] }]
});

setManager(prevState => ({
  data: prevState.data.map((item, index) => ({ ...item, ...res.data[index] }))
}));

However, if you're just storing an array of "items", then your state should look more like:
const [manager, setManager] = useState([{ name: undefined, project: [] }]);

setManager(prevState =>
  prevState.data.map((item, index) => ({ ...item, ...res.data[index] }))
);

Also, the way how you're gonna merge prev and incoming data depends on many things and maybe you need some more sophisticated way of storing state.

A: You inited your state with an Array, not an Object, that's the reason for the behavior.
Change this from
useState({data : [{name : undefined , project : []}] });

to
useState({data : {name : undefined , project : []} });


Q: postgres ERROR: relation "routine_privileges" does not exist I am trying to put together a query to find unused indexes in a postgres database:
SELECT indexrelname, pg_relation_size(quote_ident(indexrelname)), idx_scan
FROM pg_stat_all_indexes
WHERE idx_scan=0
    AND indexrelname NOT LIKE 'pg_toast_%';

The above seems to work all right, but I want to concentrate on the big indexes, so I added an extra condition:
SELECT indexrelname, pg_relation_size(quote_ident(indexrelname)), idx_scan
FROM pg_stat_all_indexes
WHERE idx_scan=0
    AND indexrelname NOT LIKE 'pg_toast_%'
    AND pg_relation_size(quote_ident(indexrelname)) > 1000000 ;

Which resulted in
ERROR:  relation "routine_privileges" does not exist

Could someone tell me why the second query is wrong and how to fix it?


Q: *ngIf is adding elements instead of replaceing them My Code

Type of isFollowing is Boolean
Whenever I'm changing it to true or false it's showing the new element according to the expression but it is not removing the previous element but adding a new element to the DOM.
As a result, multiple icons are visible like in the image.
Multiple Icons being Added
I believe change detection is detecting the change and adding a new DOM element but it's not updating the previous DOM Element.

A: Try this

A: Try with

<ng-template #follow></ng-template>

A: Why not you doing this with ngClass?

A: I ran into this exact same issue, each of the suggested answers did not work. I haven't figured out why this was happening, but I solved it by wrapping the i tags in span tags and moving the *ngIf to the span tags like so:


Q: Is it possible to nest the all function? I have a list of objects named items. Each object has a property state and a property children, which is another list of objects. And each child object has also a property named state. What I want to know is if every item and their children are in the states happy or cheerful.
I did this with all (only analysing the states of the items):
if all(item.state in ['happy', 'cheerful'] for item in items):
   pass

I would like to know which is the best way to do the same with not only items but children too.

A: You are seeking for some recursion here:
def is_happy(items):
   return all(item.state in ['happy', 'cheerful'] for item in items) and all(is_happy(item.childs) for item in items)

As @tobias_k pointed out this should be quicker since it iterates only once on items:
def is_happy(items):
   return all(item.state in ['happy', 'cheerful'] and is_happy(item.childs) for item in items)

It is at least more readable.
In the case you only have two layers of objects a simple for might do the trick too.
def is_happy(items):
    happy_children = True
    for item in items:
        if any(child.state not in ['happy', 'cheerful'] for child in item):
            happy_children = False
            break
    return all(item.state in ['happy', 'cheerful'] for item in items) and happy_children

A: I guess this would be the right way:
if all(item.state in ['happy', 'cheerful'] and all(c.state in ['happy', 'cheerful'] for c in item.childs) for item in items):
   pass

A: First step: flatten the list of items:
def flatten(items):
    for item in items:
        yield item
        for child in getattr(item, 'children', ()):
            yield child

Or using Python 3.4+:
def flatten(items):
    for item in items:
        yield item
        yield from getattr(item, 'children', ())

And now you can iterate through flattened items using all(..) or some other way:
is_happy = lambda item: getattr(item, 'state') in ('happy', 'cheerful')
are_happy = lambda items: all(map(is_happy, flatten(items)))

A: Recursion is your friend here
def happy(x):
    return (x.state in ('happy', 'cheerful') and
            all(happy(xc) for xc in x.children))

A: This is probably best done manually.
def valid(item):
    return item.state in ['happy', 'cheerful']

for item in items:
    if not (valid(item) and all(valid(child) for child in item)):
        break
else:
    # success

Changing the generator expression to work with this is possible but makes it a bit hacky.
if all(child.state in ['happy', 'cheerful'] for item in items for child in item+[item]):
   pass

So to answer your question, yes its possible to nest the all function and thats how you could do it if you really wanted.


Q: Why is the white box appearing? The first box the loop outputs is a white box with a black outline. I don't understand where it's coming from...
https://editor.p5js.org/matranson/present/6fNelJM8_

function setup() {
    colorMode(HSB,360,100,100);
    createCanvas(400, 400);
    var boxh = height / 10;
    var boxw = width;
    for(var i = 0; i < 10; i++) {
    var h = lerp(64, 22, i / 9);
    var s = lerp(86, 90, i / 9);
    var l = lerp(96, 56, i / 9);
    rect(0, i * boxh, boxw, boxh);
    fill(h,s,l);
    stroke(0,0,100);
    }

}

function draw() {
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>

A: stroke() sets the color used to draw lines and borders. fill() sets the color used to fill shapes. rect() draws a rectangle.
The stroke and the fill color has to be set before the rectangle is drawn:
fill(h,s,l);
stroke(0,0,100);
rect(0, i * boxh, boxw, boxh);

function setup() {
    colorMode(HSB,360,100,100);
    createCanvas(400, 400);
    var boxh = height / 10;
    var boxw = width;
    for(var i = 0; i < 10; i++) {
      var h = lerp(64, 22, i / 9);
      var s = lerp(86, 90, i / 9);
      var l = lerp(96, 56, i / 9);

      fill(h,s,l);
      stroke(0,0,100);
      rect(0, i * boxh, boxw, boxh);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>


Q: give labels as a numpy array with shape(m,1) or shape(m,) to a model simply i trying to test a simple Dense neural network without hidden layer.first 50th columns of my data is features and last one is label.
X = data[:, :50]
y = data[:, -1]
input = keras.Input(shape=(50,))
output = keras.layers.Dense(1)(input)
model = keras.Model(inputs=input, outputs=output)
model.compile(loss='mse')
model.fit(X, y, epochs=20)

is there difference between giving data[:, -1] or data[:, 50:] as labels to model? why? (seems the results is equal)
>>> data[:, 50:].shape
result: (1000, 1)

>>> data[:, -1].shape
result: (1000,)

>>> data[:, :50].shape
result: (1000, 50)

A: data[:, -1] returns the value of the last column for every row
but data[:, 50:] will return the values of the all columns starting from column no 50. Since in your case there are only 50 columns it is same as data[:, -1] but with 1 in the second dimension indicating that only 1 column was picked
Assume that the data is of size (1000, 60), then data[:, -1] would still return a array of shape (1000,) but data[:, 50:] would return an array of shape (1000, 10)


Q: Not able to access imported class using * wildcard but able to use same class when imported with full qualified name
*

*I am new to java please help me

*I am having trouble using the * wild card in my import statements

*I compiled the javatesting1 class using javac -d . javatesting1.java and also got the .class file in test1 package

*here is my folder structure click on this image

*When i compile javatesting2 while using import statement with * I am getting the following error

    javac javatesting2.java
    javatesting2.java:2: error: cannot access javatesting1
    class testingclass extends javatesting1
                               ^
    bad source file: .\javatesting1.java
    file does not contain class javatesting1
    Please remove or make sure it appears in the correct subdirectory of the sourcepath.

    javatesting2.java:6: error: cannot find symbol
        System.out.println(a);
                           ^
    symbol:   variable a
    location: class testingclass

    2 errors

Here is my code
    package test1;
    public class javatesting1
    {
         protected int a=45;
         int b=78;
    }

    //I am not able to use the javatesting1 class when i use test1.* instead of test1.javatesting1

    // the below code is on another file in the same directory
    import test1.javatesting1;
    class testingclass extends javatesting1
    {
        public void meth1()
        {
            System.out.println(a);
           // System.out.println(b);
        }
    }
    public class javatesting2
    {
        public static void main(String [] args)
        {
                  testingclass obj=new testingclass();
                  obj.meth1();
        }
    }

A: Hello and welcome to Stack Overflow!
Since you are declaring class javatesting1 to be in a package test1, Java expects to find that class in a folder named like the package in order to scan it (using the wildcard).
I have tested your code, importing using wildcard *, with a folder structure like this

folder

*

*javatesting2.java

*test1

*

*javatesting1.java

Try editing your folder structure.
Also please try do adhere to coding conventions: class names should be named using CamelCase, e.g. JavaTesting1


Q: Highchart x-axis show label after specific days no matter what is in the x-axis categories This is my code for highchart:
Highcharts.setOptions({
    time: {
        useUTC: false
    }
});

$('#container-chart').highcharts({
    chart: {
        type: 'line',
        alignTicks: false,
    },
    title: {
        text: "Title 1",
    },
    tooltip: {
        formatter: function() {
            return Highcharts.dateFormat('%b %e, %Y',new Date(this.x))+ '
' + this.y;
        }
    },
    xAxis: {
        categories: [1391122800000,1393542000000,1396216800000,1398808800000,1401487200000,1404079200000,1406757600000,1409436000000,1412028000000,1414710000000,1417302000000,1419980400000,1422658800000,1425078000000,1427752800000,1430344800000,1433023200000,1435615200000,1438293600000,1440972000000,1443564000000,1446246000000,1448838000000,1451516400000,1454194800000,1456700400000,1459375200000,1461967200000,1464645600000,1467237600000,1469916000000,1472594400000,1475186400000,1477868400000,1480460400000,1483138800000,1485817200000,1488236400000,1490911200000,1493503200000,1496181600000,1498773600000,1501452000000,1504130400000,1506722400000,1509404400000,1511996400000,1514674800000,1517353200000,1519772400000,1522447200000,1525039200000,1527717600000,1530309600000,1532988000000,1535666400000,1538258400000,1540940400000],
        // tickInterval: (24 * 3600 * 1000 * 173),
        labels: {
            formatter: function () {
                return Highcharts.dateFormat("%b %y", this.value);
            },
        }
    },
    yAxis: {
        title: { text: ''
        },
    },
    legend: {
        enable: true,
    },
        plotOptions: {
            series: {
                marker: {
                    enabled: false
                },
                dataLabels: {
                    enabled: false,
                    allowOverlap: true,
                },
                lineWidth: 2,
                states: {
                    hover: {
                        lineWidth: 3
                    }
                },
                threshold: null
            }
        },
        series: [{
            data: [0.57,0.41,0.51,0.35,0.16,0.16,0.05,0.19,0.27,0.57,0.45,0.59,0.49,0.77,0.56,0.25,0.3,0.28,0.27,0.33,0.45,0.62,0.62,0.46,0.46,0.45,0.68,0.18,0.22,0.28,0.29,0.41,0.34,0.59,0.67,0.69,0.65,0.57,0.73,-0.01,0.32,0.27,0.47,0.47,0.57,0.75,0.7,0.6,0.71,0.88,0.79,-0.11,0.22,0.15,0.07,0.09,0.09,0.09],
        }],
        exporting: {
            sourceWidth: 1500
        },

});

I have 58 days data for highchart's xAxis categories properties. The date difference from 1st day data to 58th date data is 1734 i.e. total number of days are 1734 days. Now, Say, i only want to show 10 labels on x-axis, of equal distance including first and last data, that means, label interval will be 173 days. How can i achieve this label interval no matter what date gap present in x-axis categories ?
Any help ?

A: You can use tickPositioner function, but you should use timestamps as x values not as categories:
xAxis: {
    tickPositioner: function() {
        var positions = [],
            interval = 24 * 3600 * 1000 * 173;

        for (var i = this.dataMin; i <= this.dataMax; i += interval) {
            positions.push(i);
        }

        return positions;
    },
    labels: {
        formatter: function() {
            return Highcharts.dateFormat("%b %y", this.value);
        },
    }
}

Live demo: http://jsfiddle.net/BlackLabel/npq3x2bc/
API Reference: https://api.highcharts.com/highcharts/xAxis.tickPositioner

A:

Highcharts.setOptions({
    time: {
        useUTC: false
    }
});

$('#container-chart').highcharts({
    chart: {
        type: 'line',
        alignTicks: false,
    },
    title: {
        text: "Title 1",
    },
    tooltip: {
        formatter: function() {
            return Highcharts.dateFormat('%b %e, %Y',new Date(this.x))+ '
' + this.y;
        }
    },
    xAxis: {
        categories: [1391122800000,1393542000000,1396216800000,1398808800000,1401487200000,1404079200000,1406757600000,1409436000000,1412028000000,1414710000000,1417302000000,1419980400000,1422658800000,1425078000000,1427752800000,1430344800000,1433023200000,1435615200000,1438293600000,1440972000000,1443564000000,1446246000000,1448838000000,1451516400000,1454194800000,1456700400000,1459375200000,1461967200000,1464645600000,1467237600000,1469916000000,1472594400000,1475186400000,1477868400000,1480460400000,1483138800000,1485817200000,1488236400000,1490911200000,1493503200000,1496181600000,1498773600000,1501452000000,1504130400000,1506722400000,1509404400000,1511996400000,1514674800000,1517353200000,1519772400000,1522447200000,1525039200000,1527717600000,1530309600000,1532988000000,1535666400000,1538258400000,1540940400000],
        // tickInterval: (24 * 3600 * 1000 * 173),
        labels: {
            formatter: function () {
                return Highcharts.dateFormat("%b %y", this.value);
            },
        }
    },
    yAxis: {
        title: { text: ''
        },
         tickInterval:(maxValue/10),
            min: 0,
            max: maxValue,
    },
    legend: {
        enable: true,
    },
        plotOptions: {
            series: {
                marker: {
                    enabled: false
                },
                dataLabels: {
                    enabled: false,
                    allowOverlap: true,
                },
                lineWidth: 2,
                states: {
                    hover: {
                        lineWidth: 3
                    }
                },
                threshold: null
            }
        },
        series: [{
            data: [0.57,0.41,0.51,0.35,0.16,0.16,0.05,0.19,0.27,0.57,0.45,0.59,0.49,0.77,0.56,0.25,0.3,0.28,0.27,0.33,0.45,0.62,0.62,0.46,0.46,0.45,0.68,0.18,0.22,0.28,0.29,0.41,0.34,0.59,0.67,0.69,0.65,0.57,0.73,-0.01,0.32,0.27,0.47,0.47,0.57,0.75,0.7,0.6,0.71,0.88,0.79,-0.11,0.22,0.15,0.07,0.09,0.09,0.09],
        }],
        exporting: {
            sourceWidth: 1500
        },

});

here I have added :
tickInterval:(maxValue/10),
            min: 0,
            max: maxValue,
it means you need to fist get max value and take the nearest value divisible by 10 and use , I hope it will help you


Q: How to reuse React component that has different markup? I have the following component today, which represents a container box that has a heading and different rows. This is how it looks:
var Box = React.createClass({
  render: function() {
    return (
      <BoxHeading title={this.props.headingTitle}/>
      <BoxBody rows={this.props.rows} />
    )
  }
});

var BoxBody = React.createClass({
  render: function() {
    return (
      {this.rows()}
    )
  }

  rows: function() {
    return _.map(this.props.rows, function(row) {
      return (
        <HouseRow />
      );
    }, this);
  }
});

Now my question is: If I want to reuse the Box & BoxBody but instead of using  I want to use another kind of Row, how would I do it?
Would I pass the kind of component that I want as row to the Box?
So, I would do <Box rowType={<HouseRow} /> or something similar?

A: The approach you chose looks really good — you can basically combine Box with every type of row you want, provided it has a correct interface. It is called Object Composition and is a legit and well respected pattern in software engineering.
The only thing is, in React you should do it not by passing a already rendered component, but the component class, like this:
<Box rowComponent={ HouseRow } />

As you see, you don't need to use parenthesis. And inside component, you do something like this:
var RowComponent = this.props.rowComponent;
return (
   <RowComponent />
);

A: <Box rowType={HouseRow} />

This is exactly how you would do it. Pass dynamic content that varies from components as props from a parent. Then in your rows function, return <{@props.rowType} /> should work


Q: What is the usage of OAuth 2.0 client id from Google Fit on Android Im really confused from Google Api platform. Recently guide leads you to generate oAuth Client ID JSON. On the other hand there is no clear reason or need to generate or have at all. Im doing these steps to enable Google Fit on Android:

*

*Get a project on Google APIs

*Enable Google Fit API

*Create OAuth Client ID on Android

*Provide fingerprint and package name (ApplicationID)
that's it ..

but what is the usage of that Json file of OAuth Client ID   ?
or that client Id?
111111111111-aaaaaaaaaaaaaaa.apps.googleusercontent.com (sample)

A: The OAuth Client ID is obtained so that your app can access the Google Fit API. As the SHA-1 of your certificate is already known by Google Fit, you do not need to enter the actual Client ID into your code. Your certificate is part of your app, and identifies the app to Google Fit.
https://developers.google.com/fit/android/get-api-key


Q: t-sql dynamic cursors May I use variable to declaring cursors??
I want to creating dynamic cursor, how can i do this??
Regards
I have table:
CREATE TABLE [UsersUniTask] (
  [id] uniqueidentifier CONSTRAINT [DF_UsersUniTask_id] DEFAULT newid() NOT NULL,
  [userUniID] uniqueidentifier NOT NULL,
  [taskID] int NOT NULL,
  [time] datetime NOT NULL,
  [doTask] int NOT NULL,
  [priority] int NOT NULL,
  CONSTRAINT [PK_UsersUniTask] PRIMARY KEY CLUSTERED ([id]),
  CONSTRAINT [FK_UsersUniTask_UsersUni] FOREIGN KEY ([userUniID])
  REFERENCES [UsersUni] ([id])
  ON UPDATE NO ACTION
  ON DELETE CASCADE
)
ON [PRIMARY]
GO

A: Can you explain more about what you mean? If you are talking about declaring the cursor in a dynamic context as in the following example, then yes you can:
DECLARE @i int -- variable input
DECLARE @valuableData int

SET @i = 1 -- value for that input, this could be set by a query

DECLARE cursorFoo CURSOR FOR
    SELECT valuableData
    FROM myTable
    WHERE someParameter = @i

OPEN cursorFoo

WHILE (1=1)
BEGIN
    FETCH NEXT FROM cursorFoo
         INTO @valuableData

    IF (@@FETCH_STATUS <> 0) BREAK

    SELECT @valuableData -- Do something with your data
END

CLOSE cursorFoo

EDIT due to discussion in comments
You should have two separate program loops here
Loop 1:

*

*Webservice adds tasks to permanent
table with information on priority.

Loop 2:

*

*Server script queries permanent
table for most important task

*Server script removes task from
table and processes task (or hands
that information off to a script
that does the work

*Server script goes back to permanent
table and looks for most important
task

SQL is meant to store data, not loop around and process it. The processing should be done with a server script. That script should get the data from the database. You start to have the concurrency issues you have having right now when SQL is writing and reading and looping through the same temporary table concurrently. You can do processing in SQL, but you should only use temp tables for data that is relevant only to that particular process.


Q: validating bitbucket commit if it has a jira id Hi i need to validate bitbucket commit if it has a jira id. May be apply a pre receive webhook in bitbucket to check if there's a jira id.
Can some guide me. I think we can make a pre webhook - testing the bitbucket commit against a regular expression.


Q: How to auto start openvpn (client) on Ubuntu CLI? I'm using Ubuntu 12.04 64bit. I have an *.ovpn file that works if I type:
sudo openvpn client.ovpn

Now I would like to start up openvpn when I boot the computer.
How can I do this?

A: The openvpn package comes with an init script /etc/init.d/openvpn. This script automatically sets up connection for every .conf (mind the extension) file in /etc/openvpn.
Found this based on information here: https://openvpn.net/index.php/open-source/documentation/howto.html#startup

If you install OpenVPN via an RPM or DEB package on Linux, the installer will set up an initscript. When executed, the initscript will scan for .conf configuration files in /etc/openvpn, and if found, will start up a separate OpenVPN daemon for each file.

A: *

*Download the OpenVPNConfigFile.ovpn. Note that you can rename the file to anything you like.

*Move the ovpn file to /etc/openvpn

*cd /etc/openvpn folder and enter sudo nano yourserver.txt
your_server_user_name
your_server_passowrd

Save and Close

*sudo nano OpenVPNConfigFile.ovpn
Find auth-user-pass and add yourserver.txt next to it so that it becomes
auth-user-pass yourserver.txt

This will allow you to skip entering your credentials everytime you start openvpn connection

*Rename OpenVPNConfigFile.ovpn to OpenVPNConfigFile.conf
sudo mv OpenVPNConfigFile.ovpn OpenVPNConfigFile.conf

*sudo nano /etc/default/openvpn
Uncomment AUTOSTART="all"

*sudo service openvpn start
You should see a message saying that you are connected. The connection will be established every time you start your computer.

A: It would be nice to have a un hacker way of doing it, but this will have to do for now.

*

*Create file  myopenvpn in  /etc/init.d/
nano /etc/init.d/myopenvpn

*Insert into myopenvpn and save:
# OpenVPN autostart on boot script

start on runlevel [2345]
stop on runlevel [!2345]

respawn

exec /usr/sbin/openvpn --status /var/run/openvpn.client.status 10 --cd /etc/openvpn --config /etc/openvpn/client.conf --syslog openvpn

SOURCE: How to auto start OpenVPN client in Debian 6 and Ubuntu 12.04

A: I got a bit stuck on this and ended up writing out all of the instructions for setting it up with systemd manually.
This worked for me using Ubuntu 16.10 and openvpn 2.3.11
Setting up your vpn to run from bash
These examples use expressvpn but most would work the same way
Download your vpn provider's ovpn config file e.g. my_express_vpn_amsterdam_2.ovpn
move that to /etc/openvpn/ and rename it to end in .conf
sudo mv ~/Downloads/my_express_vpn_amsterdam_2.ovpn /etc/openvpn/amsterdam-2.conf

Your VPN provider will provide you with a username and password for connecting over openvpn. Save the userename and then password each on their own line
sudo vim /etc/openvpn/express-vpn-crednetials.txt
# add these lines
YOUR_VPN_USERNAME
YOUR_VPN_PASSWORD
# save the file

now edit /etc/openvpn/amsterdam-2.conf
look for a line that says auth-user-pass and replace it with the path to your credential file
auth-user-pass /etc/openvpn/express-vpn-crednetials.txt

Test your config! Start openvpn like this
sudo openvpn --config /etc/openvpn/amsterdam-2.conf

openvpn should connect without asking for username or password
Remove existing (broken) service config for openvpn
sudo rm /etc/systemd/system/multi-user.target.wants/openvpn.service

Set up openvpn to run as a systemd service
The config that came with openvpn was broken so I removed it and created a new one based on this answer
Create systemd service for openvpn
sudo vim /usr/lib/systemd/system/openvpn@service

add this config:
[Unit]
Description=OpenVPN Robust And Highly Flexible Tunneling Application On %I
After=syslog.target network.target

[Service]
PrivateTmp=true
Type=forking
PIDFile=/var/run/openvpn/%i.pid
ExecStart=/usr/sbin/openvpn --daemon --writepid /var/run/openvpn/%i.pid --cd /etc/openvpn/ --config %i.conf

[Install]
WantedBy=multi-user.target

the %iis used as a wildcard so that this service can be used for multiple vpn configurations. Set it up for the amsterdam-2.conf file that we created earlier
sudo systemctl start openvpn@amsterdam-2.service

the systemd service should now be running on the amsterdam vpn. check its status like so
sudo systemctl status openvpn@amsterdam-2.service

you should see several lines of output ending in Initialization Sequence Completed and your vpn should be running.
Hope this helps! related reading:

*

*How to start 2FA using OpenVPN with systemd

*How to start the OpenVPN client service on Ubuntu 15.04

*Using OpenVPN with systemd

A: If your client.ovpn file doesn't contain a password, then use the following:

*

*Copy your client.ovpn file to /etc/openvpn/
sudo cp -i client.ovpn /etc/openvpn/

*Go to the openvpn folder
cd /etc/openvpn/

*Rename the file from client.ovpn to be client.conf
sudo mv -i client.ovpn client.conf

*

*Now it's ready,

*

*To connect use:
sudo /etc/init.d/openvpn start

*To stop openvpn use:
sudo /etc/init.d/openvpn stop

*To reconnect use:
sudo /etc/init.d/openvpn restart

*To check your ip:
curl ifconfig.co
This should work on startup.
Note: when you put your computer to sleep you should restart or stop Openvpn to be able to connect to the internet
This answer derived from @Robert Polson post.
This is tested on Ubuntu 22.04


Q: Avoiding join in MS Access delete query I am trying to create a delete query to remove records from one table, based on whether or not one of the field exists in another master table. The situation is that I am importing new records into a database, but I want to remove the records that have already been imported, i.e. that already have an account in the master table. The field I need to join on, however is not equal: it is prefixed with a constant three letter code XYZ.
 tbl_to_import.Account     master_table.Account
 123456                    XYZ.123456
 345678                    XYZ.345678

To avoid using a join in the delete query I tried the following:
 Delete tbl_to_import.*
 From tbl_to_import
 Where Exists( Select master_table.Account From master_table
 Where master_table.Account =  ("XYZ."& tbl_to_import.Account) ) = True;

However, the query gets hung up in Access. I'm not sure what I'm doing incorrectly. I don't get an error message, but the query runs without producing anything and I eventually stop it. In this situation, tbl_to_import has 2,700 records and master_table has 50,000 records. Additionally, I am connecting to the master_table via ODBC.
Originally, I constructed two queries using a join to perform the delete. tbl_to_import.Account has a primary key called ID. One query, qry_find_existing_accounts, located the ID numbers in tbl_to_import for which there exists a corresponding account in master_table.Account:
 SELECT DISTINCTROW tbl_to_import.ID AS DELETEID
 FROM tbl_to_import LEFT JOIN master_table
      ON ("XYZ."& tbl_to_import.Account) = master_table.Account
 WHERE ((("XYZ." & [Account])=[master_table].[Account]));

Then I used this query to construct the delete query:
 DELETE DISTINCTROW tbl_to_import.*, tbl_to_import.ID
 FROM tbl_to_import RIGHT JOIN qry_find_existing_accounts
      ON tbl_to_import.ID =qry_find_existing_accounts.DELETEID
 WHERE (((tbl_to_import.ID)=[qry_find_existing_accounts].[DELETEID]));

The query qry_find_existing_accounts worked fine; however, when I tried to run the second query to delete, I got the error: Could not delete from specified tables. Typically, when I get this error, it is because I have not selected unique records only, however, I used DISTINCTROW in both queries.
Any ideas what I am doing wrong and how I can accomplish what I need to do?

A: I'd go with a simpler nested SQL statement:
Delete tbl_to_import.*
From tbl_to_import
Where "XYZ." & tbl_to_import.Account In
(Select master_table.Account From master_table);

This should be fairly fast, especially if your Account fields are indexed.

A: I think you can simplify the query; delete based on the ID, where the IDs are in the query:
DELETE * FROM tbl_to_import
    WHERE tbl_to_import.ID IN (
        SELECT DISTINCT [DELETED] FROM qry_find_existing_accounts
    )


Q: Inserting data into database using AdoDB This is how you insert using AdoDB Databse Abstraction Layer.
<?php
include 'adodb5/adodb.inc.php';
$host = 'localhost';
$user = 'user2000';
$pass = 'password2000';
$dbname = 'w3cyberlearning';
$conn1 = &ADONewConnection('mysql');
$conn1->PConnect($host, $user, $pass, $dbname);
// the MySQL insert statement.
$sql = "INSERT INTO user_infor(id,first_name,last_name, email) values(?,?,?,?) ";
     $my_data = array(
     array(1, 'Paul', 'Mark', 'pm@aa.com'),
     array(2, 'Jam', 'Gill', 'jg@aa.com'),
     array(3, 'Mix', 'Alex', 'mlex@aa.com'),
     array(4, 'King', 'Mix', 'km@aa.com')
);

// loop through the array
for ($i = 0; $i < count($my_data); $i++) {
    $d = $conn1->Execute($sql, $my_data[$i]);
    if (!$d) {
        print 'error' . $conn1->ErrorMsg() . '
';
    }
    echo 'Success!';
    echo "
";
    }

The data is in array format.
What if I use a form.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $age = $_POST['age'];
}

<form enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
    <input type="text" id="name" name="name" />
    <input type="number" id="age" name="age" />
    <input type="submit" value="Submit"/>
</form>

Now, the data comes from two variables $name and $age.
What I am unable to do is replace the above $my_data with the two variables which collects the data. How do I replace them

A: As I see from
$d = $conn1->Execute($sql, $my_data[$i]);

arguments passed to Execute method are query string and array with some values.
So, in your case you can do the same:
$d = $conn1->Execute($sql, array($name, $age));

where $name, $age your variables and $sql is your query string.


Q: Compilation issue on new kernel I have installed Fedora 22 , which has default kernel 4.0.4.
But I have a requirement of Kernel 4.1.4, so I installed kernel 4.1.4 on Fedora 22. and make an entry in grub for new kernel.
Kernel 4.1.4 is installed successfully and I am able to login with new kernel.
output of "uname -a"-
uname -a
Linux localhost.localdomain 4.1.4 #1 SMP Fri Aug 7 10:52:36 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux

Path of new kernel -
/usr/src/linux-4.1.4

Path of include folder -
/usr/src/linux-4.1.4/include

Now I wrote a C program, which uses the macro AF_MPLS, which is defined in new kernel headers. Compilation of c program is failed because AF_MPLS is not in /usr/include/sys/socket.h.
Error found -
RouteMPLS.c: In function âroute_addâ:
RouteMPLS.c:212:24: error: âAF_MPLSâ undeclared (first use in this function)
req.r.rtm_family = AF_MPLS;

Headers file used in RouteMPLS.c
#include <stdio.h>
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>

So, I changed the location of header file a/c to new kernel-
#include "/usr/src/linux-4.1.4/include/linux/socket.h"

still it throws an compilation error, then I tried with
gcc RouteMPLS.c -I /usr/src/linux-4.1.4/include/
In file included from /usr/src/linux-4.1.4/include/linux/kernel.h:6:0,
             from /usr/src/linux-4.1.4/include/linux/skbuff.h:17,
             from /usr/src/linux-4.1.4/include/linux/netlink.h:6,
             from RouteMPLS.c:3:
/usr/src/linux-4.1.4/include/linux/linkage.h:7:25: fatal error: asm/linkage.h: No such file or directory

compilation terminated.
Please guide how can I install our c program with new kernel headers -
Default kernel header location -
/usr/include

New Kernel header location -
/usr/src/linux-4.1.4/include

Thanks in advance.

A: The problem is that you have the linux kernel 4.1.4 header files in the directory for kernel compilation.
To compile user programs, the compiler normally looks for them in /usr/include (well, in the new architectures, it is some more complicated) and there's normally a copy of the kernel headers for the running kernel installed inside /usr/include
But now, you have a kernel headers version mismatch.  You don't say where have you downloaded that sources from, but in the Documentation subdirectory of the kernel source tree, you have some document explaining how to install the kernel headers in the proper place, so the compiler for system applications finds them right.
Read the doc at /usr/src/linux-4.1.4/Documentation for a file which explainst how to install the kernel headers in the proper place.  Mainly, it refers to all files installed under /usr/include/linux, /usr/include/asm and (as is your case) /usr/include/asm-amd64.
Note:
After some search in the kernel source tree, I have found a target headers_install in the Makefile (by trying make help) I suppose serves to install the header files from the kernel tree to the proper place.
So, the most probable way to install the kernel header files is to do:
make headers_install

or (in case you must install them in other place)
INSTALL_HDR_PATH=<new_path> make headers_install

(it says by default installation goes to ./usr)


Q: Can't run background service at a regular period of 3 minutes on Chinese custom ROM to send latitude and longitude I have tried job scheduler and work manager but it does not work in doze mode and not at regular period. I have used normal service which is not working on
some Chinese custom rom phone specially oppo and vivo.
I have used the Alarm Manager to start service but it also not working any type of solution not working on this phone.

A: If you really want to have it working on all devices, I suggest you this approach:

*

*Set up Firebase messaging

*Subscribe all devices to specific topic e.g. "UPDATE_LOCATION"

*Extend FirebaseMessagingService and implement onMessageReceive()

*If your data message contains instruction to update location, call the method to update location from onMessageReceive()

*Trigger recurring messages to "UPDATE_LOCATION" topic from Firebase (CRON job or scheduled tasks)

It's a little more work that methods you have already tried, but it works on all phones and also after device restart and system update.
Additional plus is that you have control over the location updater from your backend (not per device which relies on app update).


Q: How can I customize the output from pygments? If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file?

A: By setting the noclasses attribute to True, only inline styles will be generated. Here's a snippet that does the job just fine:

formatter = HtmlFormatter(style=MyStyle)
formatter.noclasses = True
print highlight(content,PythonLexer(),formatter)

A: @Ignacio: quite the opposite:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

code = 'print "Hello World"'
print highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))

[ ref.: http://pygments.org/docs/formatters/, see HtmlFormatter ]
( Basically it is the same as Tempus's answer, I just thought that a full code snippet may save a few seconds ) )
PS. The ones who think that the original question is ill-posed, may imagine e.g. the task of pasting highlighted code into a blog entry hosted by a third-party service.

A: Pass full=True to the HtmlFormatter constructor.

A: Usually, your code is only one of many things on a web page.  You often want code to look different from the other content.  You, generally, want to control the style of the code as part of the overall page style.  CSS is your first, best choice for this.
However, you can embed the styles in the HTML if that seems better.  Here's an example that shows the <style> tag in the <head> tag.
http://www.w3schools.com/TAGS/tag_style.asp


Q: Select multiple film category I am having trouble with my small film database tag/category query.
My table is:
ID(index),Name(film name),category

One movie can have multiple categories.
SELECT Name  FROM categorytable WHERE category ='Action';

Works fine but if I want other tags I get empty cursor:
SELECT Name  FROM categorytable WHERE category ='Action' AND category ='Sci-Fi';

Example select:
1  Film001        Action
2  Film001        Sci-Fi
3  Film002        Action

EDIT:
My home databese:
ID|NAMEFILM|DESCRIPTION

And complete query is:
SELECT DATABASEFILM.NAMEFILM , DATABASEFILM.DESCRIPTION , NAME from DATABASEFILM , CATEGORY where DATABASEFILM.NAMEFILM=NAME AND category=(SELECT NAME  FROM CATEGORY WHERE category ='Action');

A: The reason your query doesn't work is because each row has only one category.  Instead, you need to do aggregation.  I prefer doing the conditions in the having clause, because it is a general approach.
SELECT Name
FROM categorytable
group by Name
having sum(case when category ='Action' then 1 else 0 end) > 0 and
       sum(case when category ='Sci-Fi' then 1 else 0 end) > 0;

Each clause in the having is testing for the presence of one category.  If, for instance, you changed the question to be "Action films that are not Sci-Fi", then you would change the having clause by making the second condition equal to 0:
having sum(case when category ='Action' then 1 else 0 end) > 0 and
       sum(case when category ='Sci-Fi' then 1 else 0 end) = 0;

A: You can use the OR clause, or if you have multiple categories it will probably be easier to use IN
So either
SELECT Name FROM categorytable WHERE category ='Action' OR category ='Sci-Fi'

Or using IN
SELECT Name
FROM categorytable
WHERE category IN ('Action', 'Sci-Fi', 'SomeOtherCategory ')

Using IN should compile to the same thing, but it's easier to read if you start adding more then just two categories.

A: with mustAppear(category) as (
  select 'Action'
  union all
  select 'Sci-Fi'
)
  select Name -- select those film names for which
  from categorytable as C1
  where not exists ( -- there is no category that must appear with that name
    select M.category
    from mustAppear as M
    where not exists ( -- that does not.
      select *
      from categorytable as C2
      where C2.Name = C1.Name
      and C2.category = M.category
    )
  )

You can also be more direct this way:
select Name
from categorytable
where category = 'Sci-Fi'
intersect
select Name
from categorytable
where category = 'Action';

The advantage of the former query is that you can use it without modification if you create a permanent table (mustAppear, or you can use a table variable @mustAppear) to hold the category list that must match. The latter query is simpler, but it must be rewritten when the categories change.


Q: Can't Load Image from JSON I want to display a list that contain text and image.
The text and image stored on my online database,
i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for CustomListAdaper2:
public class CustomListAdaper2 extends ArrayAdapter<contenus> {
ArrayList<contenus> contenus;
Context context;
int resource;
public CustomListAdaper2(@NonNull Context context, @LayoutRes int resource,
@NonNull ArrayList<contenus> contenus) {
    super(context, resource, contenus);
    this.contenus = contenus;
    this.context = context;
    this.resource = resource;
}@NonNull
@Override
public View getView(int position2, @Nullable View convertView, @NonNull ViewGroup parent) {
    if(convertView==null){
        LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.custom_list_layout_layout, null, true);
    }
    contenus contenus = getItem(position2);
    ImageView imageView = (ImageView) convertView.findViewById(imageView5);
    Picasso.with(context).load(contenus.getImage()).into(imageView);
    TextView textViewtitle = (TextView) convertView.findViewById(R.id.textViewtitle);
    textViewtitle.setText((replacehtml(contenus.getNom())));
    TextView textViewcity = (TextView) convertView.findViewById(R.id.textViewcity);
    textViewcity.setText((replacehtml(contenus.getVille())));
    TextView textViewtime = (TextView) convertView.findViewById(R.id.textViewtime);
    textViewtime.setText((replacehtml(contenus.getTime())));
    TextView textViewprice = (TextView) convertView.findViewById(R.id.textViewprice);
    textViewprice.setText((replacehtml(contenus.getPrix())));

    return convertView;
}

}

this is my code for the json:
public class Multimedia extends AppCompatActivity {
ArrayList<contenus> arrayList2;
ListView lv2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_multimedia);
    arrayList2 = new ArrayList<>();
    lv2 = (ListView) findViewById(R.id.ListView2);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            new ReadJSON().execute("http://wach.ma/mobile/category.php?id=Pour_La_Maison_Et_Jardin");
        }
    });
}

class ReadJSON extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }

    @Override
    protected void onPostExecute(String content) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(content);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONArray jsonArray = null;
        try {
            jsonArray = jsonObject.getJSONArray("articles");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject contenusobject = null;
            try {
                contenusobject = jsonArray.getJSONObject(i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                arrayList2.add(new contenus(
                        contenusobject.getString("picture"),
                        contenusobject.getString("name"),
                        contenusobject.getString("city"),
                        contenusobject.getString("add_time"),
                        contenusobject.getString("price")

                ));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            CustomListAdaper2 adaper2 = new CustomListAdaper2(
                    getApplicationContext(), R.layout.custom_list_layout_layout, arrayList2
            );
            lv2.setAdapter(adaper2);
        }

    }

    @NonNull
    private String readURL(String theURL) {
        StringBuilder content = new StringBuilder();
        try {
            URL url = new URL(theURL);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}
}

A: Just Edit This Code...
ImageView imageView = (ImageView) convertView.findViewById(R.id.your_image_view_id);

Otherwise everything is fine... I test it.
Update
Before using url of the image be sure that
When you set the value you are assigning write position on the model contractor.
arrayList2.add(new contenus(
                    //is this "picture" is first argument
                    contenusobject.getString("picture"),
                    contenusobject.getString("name"),
                    contenusobject.getString("city"),
                    contenusobject.getString("add_time"),
                    contenusobject.getString("price")

));

//Or Check hare

String url = contenus.getImage();
Log.d("image url", url);
Picasso.with(context).load(url).into(imageView);

and what about imageView5 is this right id for imageView?


Q: Running from terminal, changes the character encoding! I think. ( UBUNTU ) I asked that question,
Ubuntu Zend Framework cli securityCheck Error
and i found the problem. Actually it is not about zendframework. Because it happens doctrine too. And it doesnt happen if i run my web site from browser. The problem is as i wrote before.

My operating system using utf8
  character encoding for file names.
  utf8-encoded file names with the php
  is run by the terminal gives the
  error. 'I' is the upper one 'ı' in my
  language. But php expects to be 'i'.
  If i change the file names to ASCII in
  php using iconv , error happens again
  because it cant find the location of
  the file at this time.

How can i run php from cli same like through apache.
PLEASE HELP ! ( thank you in advance )

A: May be this package (or similar) required to run php scripts as cli?

A: Solution is: Everytime solve your own things.
Anyway,
My linux locale is UTF-8 so i've changed it to 8859-9 locale setting. There are many place to change locale settings in ubuntu. But the easiest way to change it in /etc/default/locale.
And i am happy, it's working now.
Thank you.


Q: What is the best practice for disabling a cache request from the Full Page Cache (FPC) in magento (enterprise) I wish to remove the following setting:
<cms>enterprise_pagecache/processor_default</cms>

... from the config.xml of the core  / Enterprise /  PageCache / config.xml file so that the home page will not be cached, (because we have a complicated custom store switch in place).
Since this value is not stored in core_config_data I am unsure of the best way to override the out of the box value.   The comments above the line in the core file do hint that it is not actually bad practice to edit this file, however, can I open this to the community to see what they think?
PS = This is a multi website setup with a custom store switcher.

A: Hole punching is what it sounds like you may need.
Add a etc/cache.xml file with a <config> root to your module. (see Enterprise/PageCache/etc/cache.xml). Choose a unique [placeholder] name.
The placeholders/[placeholder]/block node value must match the class-id of your custom dynamic block, e.g. mymodule/custom
The placeholders/[placeholder]/container node value is the class to generate the content dynamically and handle block level caching
The placeholders/[placeholder]/placeholder node value is a unique string to mark the dynamic parts in the cached page
placeholders/[placeholder]/cache_lifetime is ignored, specify a block cache lifetime in the container’s _saveCache() method if needed
Implement the container class and extends Enterprise_PageCache_Model_Container_Abstract. Use _renderBlock() to return the dynamic content.
Implement the _getCacheId() method in the container to enable the block level caching. Use cookie values instead of model ids (lower cost).
One last note: You DON’T have the full Magento App at your disposal when _renderBlock() is called. Be as conservative as possible.
SOURCE: http://tweetorials.tumblr.com/post/10160075026/ee-full-page-cache-hole-punching


Q: A condition for a subgroup of a finitely generated free abelian group to have finite index
Let $A$ be a free abelian group of finite rank and $B$ be a subgroup of $A$ such that $A=B+pA$ for some prime number $p$. Then how to prove $B$ is a subgroup of finite index in $A$? And if $A=B+pA$ holds for any prime number number $p$, then $A=B$?

I tried to use The Second Isomorphism Theorem for groups, since any subgroup of an abelian group is normal, so we can get $pA/(pA\cap B) \cong\ (B+pA)/B=A/B$, since $A=B+pA$, so the next step will be show $pA/(pA\cap B)$ is finite, then I got stuck. I also tried to use $A/pA=(B+pA)/pA \cong\ B/(pA\cap B)$, and stuck again.
I guess we might need to connect $A/B$  with $A/pA$, since the later the finite, and I don't know how to use the condition that A is with finite rank, any suggestions?

A: Here is Steve D's argument (see comments). I hope Steve will post his own answer. This is a community wiki. [It's very possible of course that Steve's argument is correct but the way I "understood" it is not.]
I'll keep the notation $p$ but I'll only use the hypothesis $p > 1$ (and $p$ integer).
The group $C:=A/B$ is finitely generated. To prove that it is finite it suffices to show that its elements have finite order. Assume by contradiction there is a subgroup $D\subset C$ isomorphic to $\mathbb Z$. The multiplication by $p$ is surjective on $C$, since its image is exactly $p(A/B) = (pA + B)/B = A/B$. Let $E\subset C$ be the subgroup of all those $c$ in $C$ such that $p^nc$ is in $D$ for $n$ large enough. Then $E$ is a nonzero finitely generated torsion free abelian group on which the multiplication by $p$ is bijective. But no such group exists.
EDIT 1. Observation of Pete L. Clark (see Pete's comment below): Steve's argument shows that
(1) if $A$ is a finitely generated abelian group and $n > 1$ an integer satisfying $nA=A$, then $A$ is finite.
Of course this is obvious if one knows that a finitely generated abelian group is the direct sum of a free abelian group with a finite group.
My comment: One can also derive (1) from the result (2) below, stated as Corollary 2.5 in Atiyah-MacDonald, and as Theorem 47(a) in Pete's commutative algebra notes:
(2) Let $R$ be a ring, $J$ an ideal of $R$, and $M$ a finitely generated $R$-module such that $JM = M$. Then there exists $x\in R$ with $x\equiv 1\ (\bmod J)$ such that $xM = 0$.
As you can see in Pete's notes, (2) follows immediately from Cayley-Hamilton.
EDIT 2. Minor variation of the above: state the Nakayama Lemma as follows:

Let $R$ be a ring, $J$ an ideal, $M$ a finitely generated $R$-module and $N$ a submodule of $M$ such that $JM + N = M$. Then there exists $x\in R$ with $x\equiv 1\ (\bmod J)$ such that $xM\subset N$.

In particular, if $A$ is a finitely generated abelian group, $B$ a subgroup, $n > 1$ an integer satisfying $nA+B=A$, then there is a $k$ with $k\equiv 1\ (\bmod n)$ such that $kA\subset B$, showing that the index of $B$ is finite.
EDIT 3. For the sake of completeness, here is a proof of the structure theorem for finitely generated modules over a principal ideal domain, essentially taken from Algebraic Theory of Numbers by Pierre Samuel.
Let $A$ be a PID, $K$ its field of fractions, and $S$ a submodule of $A^n$. The maximum number of linearly independent elements of $S$ is also the dimension of the vector subspace of $K^n$ generated by $S$. Thus this integer, called the rank of $S$, only depends on the isomorphism class of $S$ and is additive with respect to finite direct sums.

Theorem. (a) $S$ is free of rank $r\le n$.
(b) There is a basis $u_1,\dots,u_n$ of $A^n$ and there are nonzero elements $a_1,\dots,a_r$ of $A$ such that $a_1u_1,\dots,a_ru_r$ is a basis of $S$ and $a_1 | a_2 | \cdots | a_r$, where $a | b$ means “$a$ divides $b$”.

We'll need the

Proposition. Let $f$ be an $A$-valued bilinear map defined on a product of two $A$-modules. Then the image of $f$ is an ideal.

Proof of the Proposition. Let $T$ be the set of all ideals of the form $A f(x,y)$, let $A f(x,y)$ and $A f(u,v)$ be two elements of $T$, and suppose that $A f(x,y)$ is maximal in $T$. It suffices to show that $f(x,y) | f(u,v)$.
Claim: $f(x,y) | f(x,v)$ and $f(x,y) | f(u,y)$. Indeed, any generator of $Af(x,y)+Af(x,v)$ is of the form $$a f(x,y)+bf(x,v)=f(x,ay+bv),$$ and the maximality of $A f(x,y)$ implies $f(x,y) | f(x,v)$. The proof of $f(x,y) | f(u,y)$ is similar.
We can assume $f(x,v)=0=f(u,y)$. [Write $f(x,v)=a f(x,y)$ and replace $v$ by $v-ay$. Similarly for $u$.] Using the equality $$f(a x+b u,y+v)=a f(x,y)+b f(u,v)$$ for all $a$ and $b$ in $A$, and arguing as in the proof of the claim, we see that $f(x,y) | f(u,v)$. QED
Proof of the Theorem. We assume (as we may) that $S$ is nonzero, we let $f$ be the bilinear form on $A^n$ whose matrix with respect to the canonical basis is the identity matrix, and we pick a generator $a_1=f(s_1,y_1)$ of $f(S\times A^n)$. [Naively: $a_1$ is the gcd of the coordinates of the elements of $S$.] Clearly, $u_1:=s_1/a_1$ is in $A^n$, and we have
$$A^n=Au_1\oplus y_1^\perp,\quad S=As_1\oplus(S\cap y_1^\perp),$$
where $y_1^\perp$ is the orthogonal of $y_1$. Then (a) follows by induction on $r$. In particular $y_1^\perp$ and $S\cap y_1^\perp$ are free of rank $n-1$ and $r-1$, and (b) follows also by induction. [Note that if $x$ belongs to a basis of $A^n$, then $f(x,y)=1$ for some $y$ in $A^n$.] QED
I don’t know if there is a simple characterization of the rings for which the Proposition holds. (See the Wikipedia entry for Principal ideal rings.)
PDF version of this edit
EDIT 4. A nice application of Nakayama's Lemma (see Theorem 52  p. 48 in Pete L. Clark's commutative algebra notes):
Let $B$ be a commutative ring and $V$ a finitely generated $B$-module.
We start with the following form of Nakayama's Lemma:

If $J$ is an ideal of $B$ satisfying $JV=V$, then $xV=0$ for some $x$ in $B$ with $x\equiv 1$ mod $J$.

Corollary:

If in addition $v$ is in $V$ and satisfies $Jv=0$, then $v=0$.

Subcorollary:

The action of $b\in B$ on $V$ is injective if surjective.

To see this, put $J:=Bb$.
Subsubcorollary:

Let $A$ be a commutative ring, $V$ a finitely generated $A$-module, and $b$ an endomorphism of $V$. Then $b$ is injective if surjective.

To see this, put $B:=A[b]$.
This gives a solution to Exercise 3.15 in Introduction to Commutative Algebra by Atiyah and MacDonald.

A: My answer will be slightly more general: $p$ does not have to be a prime number, but may in fact be any integer greater than one.
As the commenters have said, it is difficult to give a good answer to this question without knowing something about what sort of prerequisite knowledge can be assumed.  I will sketch out several approaches, to the limit of my time and patience.
Here are two facts that I want to use in the proof(s).

Lemma 1: Let $R$ be a nonzero commutative ring.  For any $R$-module $M$, we define the rank of $M$ to be the least cardinality of a generating set for $M$ as an $R$-module.  Then for all $n \in \mathbb{Z}^+$, the rank of $R^n$ is $n$.

Proof: Since the standard basis vectors $e_1,\ldots,e_n$ generate $R^n$, the rank of $R^n$ is at most $n$.  Conversely, let $x_1,\ldots,x_m$ be a set of generators for $M$.  Suppose that $m < n$.  Then we may fill out the set to a (still generating) set consisting of $n$ elements by choosing further elements $x_{m+1},\ldots,x_n$ arbitrarily.  (We have already verified that $\# R^n \geq n$!)  Then there is a unique $R$-linear endomorphism of $R^n$ given by $e_i \mapsto x_i$ for all $i$.  But any finitely generated $R$-module is Hopfian, i.e., any surjective endomorphism must in fact be an isomorphism.  (For this see e.g. $\S 3.8.2$ of my commutative algebra notes.  We are using the result for free $R$-modules, and this has been discussed recently on this site.)  Thus $x_1,\ldots,x_n$ is also a basis for $R^n$ and in particular an $R$-linearly independent set.  But this contradicts our assumption that for some $m < n$, $x_1,\ldots,x_m$ is a generating set: if so, $x_n$ would have to be a linear combination of $x_1,\ldots,x_m$.
Comment: I will be using this result for $R = \mathbb{Z}$ -- in which case it can also be proved using structure theory of modules over a PID -- and for $R = \mathbb{Z}/p\mathbb{Z}$.  Note that when $p$ is prime, as in the OP's statement of the problem, $\mathbb{Z}/p\mathbb{Z}$ is a field and this is just standard linear algebra.

Lemma 2: Let $n \in \mathbb{Z}^+$ and $B \subset A \cong \mathbb{Z}^+$.  The following are equivalent:
(i) $B$ has finite index in $A$.
(ii) The rank of $B$ as a $\mathbb{Z}$-module is $n$.
(ii) $B \cong \mathbb{Z}^n$.

Proof: First recall that for any PID $R$, if $A \cong R^n$ and $B$ is an $R$-submodule of $R$ then $B \cong R^m$ for some $m \leq n$.  This famously follows from structure theory; for an alternate proof (and generalization to infinitely generated modules) see $\S 3.9.2$ of the same notes.  Having established this, (ii) $\iff$ (iii) follows immediately from Lemma 1.
Suppose that $[A:B] = m < \infty$.  Then $B \supset mA \cong m \mathbb{Z}^n$, so $B$ both contains and is contained in a free $R$-module of rank $n$.  It follows from the previous paragraph that $B$ itself has rank $n$.
Suppose that $[A:B]$ is infinite, and consider the short exact sequence
[0 \rightarrow B \rightarrow A \rightarrow A/B \rightarrow 0. ]
Then $A/B$ is an infinite, finitely generated $\mathbb{Z}$-module, so contains an element of infinite order and thus a subgroup $Q$ isomorphic to $\mathbb{Z}$.  The complete preimage of $Q$ in $A$ is isomorphic to $B \oplus \mathbb{Z} \cong \mathbb{Z}^m \oplus \mathbb{Z} \cong \mathbb{Z}^{m+1}$.  Since this is a submodule of $A \cong \mathbb{Z}^n$ we have $m+1 \leq n$ and thus $m < n$.

Proposition: Let $A \cong \mathbb{Z}^n$ be an abelian group, and let $B$ be a subgroup of $A$.  Suppose there exists $p > 1$ such that $B + pA = A$.  Then $[A:B]$ is finite and prime to $p$.

Proof: If $B$ had infinite index in $A$, then by Lemma 2, $B \cong \mathbb{Z}^m$ for some $m < n$ and thus has an $m$ element generating set $x_1,\ldots,x_m$.  Consider the quotient map $q: A \rightarrow A/pA$.  Our hypothesis implies that $q(B) = (B+pA)/pA = A/pA$; in other words, $q$ restricted to $B$ is a surjection and thus $A/pA$ is generated by $q(x_1),\ldots,q(x_m)$.  But $A/pA \cong (\mathbb{Z}/p\mathbb{Z})^n$ is a free rank $n$ module over $R = \mathbb{Z}/p\mathbb{Z}$, so cannot be generated as an $R$-module (equivalently, as an abelian group) by any set with less than $n$ elements: contradiction.
Therefore the index is finite.  If the index were not prime to $p$, then there would exist $B'$ with $B \subset B' \subset A$ and $[A:B'] = p$ (the quotient $A/B$ is a finite abelian group, and finite abelian groups have subgroups of all orders permitted by Lagrange's Theorem).  Since $B' \supset B$, we have $B' + pA = A$.  But also $B' \supset pA$ and thus $A = B' + pA \subset B' + B' = B'$, contradiction.
If the hypotheses of the Proposition hold for every prime $p$, then the index $[A:B]$ is not divisible by any prime $p$, i.e., $[A:B] = 1$ and $B = A$.
Final Comment: I seem to have reached the limit of my patience for now, so I will leave it to someone else to explain how every invocation of my commutative algebra notes or use of algebra beyond the undergraduate level can be replaced by an appeal to the structure theory of finitely generated modules over a PID, at least when $p$ is prime.