问:
Solr: Get DataImportHandler to ignore missing elements
I'm trying to use DIH to import data from an XML source I do not maintain. This XML has optional elements grouped as attributes, for example color or flavor. Not all entities have all the attributes, which is perfectly fine and valid. Sadly, DIH skips these entities when I still want them. This is my data-config.xml

```<code><dataConfig>
  <dataSource type="FileDataSource" name="datasource"/>
  <document>
   <entity
     name="files"
     processor="FileListEntityProcessor"
     baseDir="C:\\"
     fileName="recipe_page.*xml"
     recursive="false"
     rootEntity="false"
     dataSource="null">
     <entity
      name="file"
      processor="XPathEntityProcessor"
      url="${files.fileAbsolutePath}"
      forEach="/results|/results/recipe"
      stream="true"
      transformer="TemplateTransformer">
       <field column="recipe_id" xpath="/results/recipe/recipeID" />
       <field column="recipe_title" xpath="/results/recipe/recipeTitle" />
       <field column="color" xpath="/results/recipe/attributes/Color" default="" />
       <field column="drink_classification" xpath="/results/recipe/attributes/DrinkClassification" default="" />
       <field column="flavor" xpath="/results/recipe/attributes/Flavor" default="" />
       <field column="uid" template="recipe_${file.recipe_id}" />
       <field column="document_type" template="recipe" />
    </entity>
   </entity>
  </document>
</dataConfig>
</code>```

How can I tell DIH to ignore missing elements or set default values for these at least?

答:
I'm not sure, that I know how to let XPathEntityProcessor know to ignore missing xpath statements, but I have an idea, that you could set default values for fields by using Transformer and particulary TemplateTransformer

You can use the template transformer to construct or modify a field
  value, perhaps using the value of other fields. You can insert extra
  text into the template.

I'm expecting that something like this should work for you:

```<code><entity name="en" pk="id" transformer="TemplateTransformer" ...>

  <!-- generate a full address from fields containing the component parts -->
  <field column="color" template="default-color" />
</entity>
</code>```

Here I'm trying to replace field value with a value, however, I'm not sure that it will help (I expect it to replace value, if it exists, however, it should be double checked)

In this case, it will be possible to create custom Transformer:

```<code>public class DefaultValueTransformer {
        public Object transformRow(Map<String, Object> row) {
                String color= row.get("color");
                if (artist != null)
                        row.put("color", "default-color-value");

                return row;
        }
}
</code>```

and later to use as this:

```<code><entity name="entity" query="..." transformer="my.package.DefaultValueTransformer">
</code>```

Body:
I'm trying to use DIH to import data from an XML source I do not maintain. This XML has optional elements grouped as attributes, for example color or flavor. Not all entities have all the attributes, which is perfectly fine and valid. Sadly, DIH skips these entities when I still want them. This is my data-config.xml

<dataConfig>
  <dataSource type="FileDataSource" name="datasource"/>
  <document>
   <entity
     name="files"
     processor="FileListEntityProcessor"
     baseDir="C:\\"
     fileName="recipe_page.*xml"
     recursive="false"
     rootEntity="false"
     dataSource="null">
     <entity
      name="file"
      processor="XPathEntityProcessor"
      url="${files.fileAbsolutePath}"
      forEach="/results|/results/recipe"
      stream="true"
      transformer="TemplateTransformer">
       <field column="recipe_id" xpath="/results/recipe/recipeID" />
       <field column="recipe_title" xpath="/results/recipe/recipeTitle" />
       <field column="color" xpath="/results/recipe/attributes/Color" default="" />
       <field column="drink_classification" xpath="/results/recipe/attributes/DrinkClassification" default="" />
       <field column="flavor" xpath="/results/recipe/attributes/Flavor" default="" />
       <field column="uid" template="recipe_${file.recipe_id}" />
       <field column="document_type" template="recipe" />
    </entity>
   </entity>
  </document>
</dataConfig>

How can I tell DIH to ignore missing elements or set default values for these at least?

Body:
I'm not sure, that I know how to let XPathEntityProcessor know to ignore missing xpath statements, but I have an idea, that you could set default values for fields by using Transformer and particulary TemplateTransformer

You can use the template transformer to construct or modify a field
  value, perhaps using the value of other fields. You can insert extra
  text into the template.

I'm expecting that something like this should work for you:

<entity name="en" pk="id" transformer="TemplateTransformer" ...>

  <!-- generate a full address from fields containing the component parts -->
  <field column="color" template="default-color" />
</entity>

Here I'm trying to replace field value with a value, however, I'm not sure that it will help (I expect it to replace value, if it exists, however, it should be double checked)

In this case, it will be possible to create custom Transformer:

public class DefaultValueTransformer {
        public Object transformRow(Map<String, Object> row) {
                String color= row.get("color");
                if (artist != null)
                        row.put("color", "default-color-value");

                return row;
        }
}

and later to use as this:

<entity name="entity" query="..." transformer="my.package.DefaultValueTransformer">


来源: stackexchange

问:
Mouse hover on image parts show hints
I have an html page with simple, static image like this : Image

I need a way that putting mouse (hover) on any object, for example - "BED" to get a tooltip that - "There is bed".

I know how hover works at pure html, with blocks or any  teg, but I need a way of doing/tracking the user cursor, and when it enters in specific zone, to show the hint. Probably some JS required. How can I setup this unknown geometric forms with their coordinates to achieve my goal?

答:
In addition of the prev answer you can also add this jQuery to your page. It makes the tooltip show more prominent and also quicker:

```<code>$( function() {
  $( document ).tooltip();
} );
</code>```

This native jQuery function uses the 'title' attribute! Don't forget to add these like this:

```<code><img title='This is a test!!' src='test.png'>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Mouse hover on image parts show hints

Body:
In addition of the prev answer you can also add this jQuery to your page. It makes the tooltip show more prominent and also quicker:

$( function() {
  $( document ).tooltip();
} );

This native jQuery function uses the 'title' attribute! Don't forget to add these like this:

<img title='This is a test!!' src='test.png'>


问:
How to remove string with specific value from a string using JavaScript?
Suppose my string is like:

```<code>var str = "USA;UK;AUS;NZ"
</code>```

Now from some a source I am getting one value like:

```<code>country.data = "AUS"
</code>```

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

```<code>var someStr= str.substring(0, str.indexOf(country.data))
</code>```

In this case I got the same result.

答:
var str = "USA;UK;AUS;NZ"
console.log(str + " <- INPUT");
str = str.split(';');

for (let i = 0; i < str.length; i++) {
  if (str[i] == 'AUS') {
    str.splice(i, 1);
  }
}
console.log(str.join(';') + " <- OUTPUT");```

Body:
Suppose my string is like:

var str = "USA;UK;AUS;NZ"

Now from some a source I am getting one value like:

country.data = "AUS"

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

var someStr= str.substring(0, str.indexOf(country.data))

In this case I got the same result.


问:
Android - Audio Track noises
I'm receiving some bytes[] through a WebSocketClient on my Android App. Those bytes are MP3 bytes :
Layer III frame Single channel MPEG-1 no checksums 48 kHz, 32 kbit/s
What I am trying to do is to write each bytes[] into an AudioTrack as soon as I receive one. Problem is, those bytes[] are MP3, which is a compressed format not accepted by the AudioTrack class. I'm trying to decode them into PCM.
And here is how I create my Audio Track :

```<code>final AudioTrack player = new AudioTrack.Builder()
            .setAudioAttributes(new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build())
            .setAudioFormat(new AudioFormat.Builder()
                    .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                    .setSampleRate(48000)
                    .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
                    .build())
            .setBufferSizeInBytes(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT))
            .build();
</code>```

Finally here is what the server is sending me. I don't know how I should be building my Audio Track to match this format. The sample rate is set to 48000 Hz, I tried CHANNEL_OUT_STEREO and MONO. I tried all of the ENCODING parameters but I still have a very poor quality and a high pitched voice. Don't know what I'm doing wrong.

Stream #0:0: Audio: mp3 (libmp3lame), 48000 Hz, mono, s16p, 32 kb/s

EDIT:
As I said in the comment, I tried something I found on a related post regarding the JLayer decoding, here is the new code:

```<code>public void addSample(byte[] data) throws BitstreamException, DecoderException {
    Decoder decoder = new Decoder();
    InputStream bis = new ByteArrayInputStream(data);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    Bitstream bits = new Bitstream(bis);
    SampleBuffer pcmBuffer = (SampleBuffer) decoder.decodeFrame(bits.readFrame(), bits);

    for (int i = 0; i < pcmBuffer.getBufferLength(); i++) {
        if (pcmBuffer.getBuffer()[i] != 0) {
            outStream.write(pcmBuffer.getBuffer()[i] & 0xff);
            outStream.write((pcmBuffer.getBuffer()[i] >> 8) & 0xff);
        }
    }
    System.out.println("--------");
    for (int j = 0; j < outStream.toByteArray().length; j++) {
        System.out.println(outStream.toByteArray()[j]);
    }
    System.out.println("--------");
    mTrack.write(outStream.toByteArray(), 0, outStream.toByteArray().length);
    bits.closeFrame();
}
</code>```

Instead of directly writing the short[] data contained in the pcmBuffer, I decoded them in byte[] thanks to an outStream and some mask operation. I get the exact same result (robotic voice). But then as you can see I tried to loop inside the byteArray I'm writing into my AudioTrack, and I tried to print each data. Here is a sample of results :

```<code>11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 48
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 46
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 44
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 44
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 45
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 48
11-20 10:18:42.331 1749-2268/? I/System.out: 0
</code>```

So as I suspected, the data are actually written as (LEFT, RIGHT, LEFT, RIGHT)... I don't know how to get a real mono MP3 signal from those.

答:
AFAIK, your code would work if the input is PCM already, so you need some sort of 3rd party code.

If you don't want to mess around with native code (C/C++) and JNI bridges, I suggest you to use JLayer

EDIT: Your edit seems OK. HAve you been tried to play directly the MP3 samples (using JLayer), instead of using AudioTrack?

Code sample:

```<code>Player player;
/* create your input stream, bis in your code */
player = new Player(bis);
player.play();
</code>```

Title: Android - Audio Track noises

Body:
I'm receiving some bytes[] through a WebSocketClient on my Android App. Those bytes are MP3 bytes :
Layer III frame Single channel MPEG-1 no checksums 48 kHz, 32 kbit/s
What I am trying to do is to write each bytes[] into an AudioTrack as soon as I receive one. Problem is, those bytes[] are MP3, which is a compressed format not accepted by the AudioTrack class. I'm trying to decode them into PCM.
And here is how I create my Audio Track :

final AudioTrack player = new AudioTrack.Builder()
            .setAudioAttributes(new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build())
            .setAudioFormat(new AudioFormat.Builder()
                    .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                    .setSampleRate(48000)
                    .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
                    .build())
            .setBufferSizeInBytes(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT))
            .build();

Finally here is what the server is sending me. I don't know how I should be building my Audio Track to match this format. The sample rate is set to 48000 Hz, I tried CHANNEL_OUT_STEREO and MONO. I tried all of the ENCODING parameters but I still have a very poor quality and a high pitched voice. Don't know what I'm doing wrong.

Stream #0:0: Audio: mp3 (libmp3lame), 48000 Hz, mono, s16p, 32 kb/s

EDIT:
As I said in the comment, I tried something I found on a related post regarding the JLayer decoding, here is the new code:

public void addSample(byte[] data) throws BitstreamException, DecoderException {
    Decoder decoder = new Decoder();
    InputStream bis = new ByteArrayInputStream(data);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    Bitstream bits = new Bitstream(bis);
    SampleBuffer pcmBuffer = (SampleBuffer) decoder.decodeFrame(bits.readFrame(), bits);

    for (int i = 0; i < pcmBuffer.getBufferLength(); i++) {
        if (pcmBuffer.getBuffer()[i] != 0) {
            outStream.write(pcmBuffer.getBuffer()[i] & 0xff);
            outStream.write((pcmBuffer.getBuffer()[i] >> 8) & 0xff);
        }
    }
    System.out.println("--------");
    for (int j = 0; j < outStream.toByteArray().length; j++) {
        System.out.println(outStream.toByteArray()[j]);
    }
    System.out.println("--------");
    mTrack.write(outStream.toByteArray(), 0, outStream.toByteArray().length);
    bits.closeFrame();
}

Instead of directly writing the short[] data contained in the pcmBuffer, I decoded them in byte[] thanks to an outStream and some mask operation. I get the exact same result (robotic voice). But then as you can see I tried to loop inside the byteArray I'm writing into my AudioTrack, and I tried to print each data. Here is a sample of results :

11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 48
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 46
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 44
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 44
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 45
11-20 10:18:42.331 1749-2268/? I/System.out: 0
11-20 10:18:42.331 1749-2268/? I/System.out: 48
11-20 10:18:42.331 1749-2268/? I/System.out: 0

So as I suspected, the data are actually written as (LEFT, RIGHT, LEFT, RIGHT)... I don't know how to get a real mono MP3 signal from those.

Body:
AFAIK, your code would work if the input is PCM already, so you need some sort of 3rd party code.

If you don't want to mess around with native code (C/C++) and JNI bridges, I suggest you to use JLayer

EDIT: Your edit seems OK. HAve you been tried to play directly the MP3 samples (using JLayer), instead of using AudioTrack?

Code sample:

Player player;
/* create your input stream, bis in your code */
player = new Player(bis);
player.play();


问:
How to render SDL2 texture into GTK3+ window?
I am creating a music player and trying to use GTK3+ for creating user interface. I am using SDL_CreateWindowFrom function to let SDL2 use GTK3+ window rather than creating one but cann't figure out the steps I need to follow in order to render the SDL2 textures into GTK3+ window.

Code getting GTK3 window ID

```<code>window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "---");
gtk_widget_show(window);
gdkWin = gtk_widget_get_window(GTK_WIDGET(window));
data->playContext->winID = GDK_WINDOW_XID(gdkWin);
gtk_main();
</code>```

Code Setting SDL2 window

```<code>playContext->display->window = SDL_CreateWindowFrom((const void *)playContext->winID);
playContext->display->renderer = SDL_CreateRenderer(playContext->display->window, -1, playContext->display->render_flags);
</code>```

Code Rendering SDL2 textures

```<code>SDL_RenderClear(playContext->display->renderer);
SDL_RenderCopy(playContext->display->renderer, playContext->textureQ.head->bmp, NULL, NULL);
SDL_RenderPresent(playContext->display->renderer);
</code>```

答:
Since example you put is effectively incomplete even on most important bits (e.g. renderer creation flags), and you don't specify which part gives you a problem, here is my example (which, on my system, works on both gtk2 and gtk3 - I wouldn't vouch it is completely fine though):</p>

```<code>#include <stdio.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <SDL.h>
#include <stdbool.h>

static SDL_Window *sdl_window;
static SDL_Renderer *sdl_renderer;
static SDL_Surface *sdl_surface;
static GtkWindow *gtk_window;
static GtkWidget *gtk_da;
static void *gdk_window;
static void *window_id;

static gboolean idle(void *ud) {
    (void)ud;
    if(!sdl_window) {
        printf("creating SDL window for window id %p\n", window_id);
        sdl_window = SDL_CreateWindowFrom(window_id);
        printf("sdl_window=%p\n", sdl_window);
        if(!sdl_window) {
            printf("%s\n", SDL_GetError());
        }
        sdl_renderer = SDL_CreateRenderer(sdl_window, -1, 0);
        printf("sdl_renderer=%p\n", sdl_renderer);
        if(!sdl_renderer) {
            printf("%s\n", SDL_GetError());
        }
    } else {
        SDL_SetRenderDrawColor(sdl_renderer, 255, 0, 0, 255);
        SDL_RenderClear(sdl_renderer);
        SDL_RenderPresent(sdl_renderer);
    }
    return true;
}

int main(int argc, char **argv) {
    gtk_init(&argc, &argv);
    gtk_window = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(gtk_window, "test");

    gtk_da = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(gtk_window), gtk_da);
    gtk_widget_show_all(GTK_WIDGET(gtk_window));

    gdk_window = gtk_widget_get_window(GTK_WIDGET(gtk_da));
    window_id = (void*)(intptr_t)GDK_WINDOW_XID(gdk_window);

    SDL_Init(SDL_INIT_VIDEO);

    g_idle_add(&idle, 0);
    gtk_main();
    return 0;
}
</code>```

Body:
I am creating a music player and trying to use GTK3+ for creating user interface. I am using SDL_CreateWindowFrom function to let SDL2 use GTK3+ window rather than creating one but cann't figure out the steps I need to follow in order to render the SDL2 textures into GTK3+ window.

Code getting GTK3 window ID

window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "---");
gtk_widget_show(window);
gdkWin = gtk_widget_get_window(GTK_WIDGET(window));
data->playContext->winID = GDK_WINDOW_XID(gdkWin);
gtk_main();

Code Setting SDL2 window

playContext->display->window = SDL_CreateWindowFrom((const void *)playContext->winID);
playContext->display->renderer = SDL_CreateRenderer(playContext->display->window, -1, playContext->display->render_flags);

Code Rendering SDL2 textures

SDL_RenderClear(playContext->display->renderer);
SDL_RenderCopy(playContext->display->renderer, playContext->textureQ.head->bmp, NULL, NULL);
SDL_RenderPresent(playContext->display->renderer);

Body:
Since example you put is effectively incomplete even on most important bits (e.g. renderer creation flags), and you don't specify which part gives you a problem, here is my example (which, on my system, works on both gtk2 and gtk3 - I wouldn't vouch it is completely fine though):

#include <stdio.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <SDL.h>
#include <stdbool.h>

static SDL_Window *sdl_window;
static SDL_Renderer *sdl_renderer;
static SDL_Surface *sdl_surface;
static GtkWindow *gtk_window;
static GtkWidget *gtk_da;
static void *gdk_window;
static void *window_id;

static gboolean idle(void *ud) {
    (void)ud;
    if(!sdl_window) {
        printf("creating SDL window for window id %p\n", window_id);
        sdl_window = SDL_CreateWindowFrom(window_id);
        printf("sdl_window=%p\n", sdl_window);
        if(!sdl_window) {
            printf("%s\n", SDL_GetError());
        }
        sdl_renderer = SDL_CreateRenderer(sdl_window, -1, 0);
        printf("sdl_renderer=%p\n", sdl_renderer);
        if(!sdl_renderer) {
            printf("%s\n", SDL_GetError());
        }
    } else {
        SDL_SetRenderDrawColor(sdl_renderer, 255, 0, 0, 255);
        SDL_RenderClear(sdl_renderer);
        SDL_RenderPresent(sdl_renderer);
    }
    return true;
}

int main(int argc, char **argv) {
    gtk_init(&argc, &argv);
    gtk_window = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(gtk_window, "test");

    gtk_da = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(gtk_window), gtk_da);
    gtk_widget_show_all(GTK_WIDGET(gtk_window));

    gdk_window = gtk_widget_get_window(GTK_WIDGET(gtk_da));
    window_id = (void*)(intptr_t)GDK_WINDOW_XID(gdk_window);

    SDL_Init(SDL_INIT_VIDEO);

    g_idle_add(&idle, 0);
    gtk_main();
    return 0;
}


问:
How to reinstall rpm package?
I have installed a package from .rpm file and it is stored in /opt.

After some configuration I found that I need to reinstall the software.  So I deleted the directory and attempted to reinstall the file with rpm -i XXX.rpm.  But it tells me that package xxx is already installed.

How can I reinstall it?

答:
Starting with version 4.12.0 there's --reinstall option.

From RPM 4.12.0 Release Notes:

New --reinstall mode which can handle changing file policies
  (RhBug:966715)

From man rpm:

rpm {--reinstall} [install-options] PACKAGE_FILE ...

This reinstalls a previously installed package.

Title: How to reinstall rpm package?


问:
Exercise: Implement an abstract class
So i'm following a C# beginner tutorial at dotnetcademy.net and one of the exercises is to Implement an abstract class.

and the goals are:
1. Create a class named SpaceStation that is abstract
2. On that abstract class, add a abstract method called FireLaser
3. Create a derived class called DeathStar that implements the FireLaser method to write "Pew pew" to the Console followed by a new line.

the code that you start with is:

```<code>using System;

// Implement your classes here

public class Program
{
    public static void Main()
    {
    }
}
</code>```

so i wrote this but it says on return that "Since 'DeathStar.FireLaser()' returns void, a return keyword must not be followed by an object expression"
but i don't know what else to write, i've tried multiple other things

```<code>using System;

// Implement your classes here
public abstract class SpaceStation
{
    public abstract void FireLaser();
}

public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        return  Console.WriteLine("Pew pew");
    }
}

public class Program
{
    public static void Main()
    {
    }
}
</code>```

So if anybody has a solution so i can reflect it on what i wrote that would be nice or if anybody can say what it should be instead.

答:
Remove the return statement from the overridden FireLaser method:

```<code>public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        Console.WriteLine("Pew pew");
    }
}
</code>```

Title: Exercise: Implement an abstract class

Body:
So i'm following a C# beginner tutorial at dotnetcademy.net and one of the exercises is to Implement an abstract class.

and the goals are:
1. Create a class named SpaceStation that is abstract
2. On that abstract class, add a abstract method called FireLaser
3. Create a derived class called DeathStar that implements the FireLaser method to write "Pew pew" to the Console followed by a new line.

the code that you start with is:

using System;

// Implement your classes here

public class Program
{
    public static void Main()
    {
    }
}

so i wrote this but it says on return that "Since 'DeathStar.FireLaser()' returns void, a return keyword must not be followed by an object expression"
but i don't know what else to write, i've tried multiple other things

using System;

// Implement your classes here
public abstract class SpaceStation
{
    public abstract void FireLaser();
}

public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        return  Console.WriteLine("Pew pew");
    }
}

public class Program
{
    public static void Main()
    {
    }
}

So if anybody has a solution so i can reflect it on what i wrote that would be nice or if anybody can say what it should be instead.

Body:
Remove the return statement from the overridden FireLaser method:

public class DeathStar : SpaceStation
{
    public override void FireLaser()
    {
        Console.WriteLine("Pew pew");
    }
}


问:
Two way data binding - ngModel
In the below angular2 component,

```<code>export class HomeComponent implements OnInit {
  homeTitle = "Welcome to the home page";
  myString = "I like red";
  myBoolean = false;

  alertMe(val){
    alert(val);
  }

  obj = {
    name: "Yoshi",
    belt: "Black"
  };

  constructor() { }

  ngOnInit() {
  }

}
</code>```

two way data binding does not work for below view,

```<code><p>
  {{homeTitle}}
</p>

<!--  Property binding -->

<!-- input value="Hai" -->
<input [value]="myString">
<input [required]="myBoolean">

<button (click)="alertMe('I like x')">Click me</button>

<hr>
<!-- All above elements are working fine -->

<!-- 2 way data binding -->
<input [(ngModel)]="obj.name">
<p>{{obj.name}}</p>
<p>{{obj.belt}}</p>
</code>```

Why obj.name does not render in the input element?

答:
sorry, i saw it now.. you have to specify name="myModelName" in input:

like <input name="myModelName" [(ngModel)]="obj.name">

Title: Two way data binding - ngModel

Body:
In the below angular2 component,

export class HomeComponent implements OnInit {
  homeTitle = "Welcome to the home page";
  myString = "I like red";
  myBoolean = false;

  alertMe(val){
    alert(val);
  }

  obj = {
    name: "Yoshi",
    belt: "Black"
  };

  constructor() { }

  ngOnInit() {
  }

}

two way data binding does not work for below view,

  {{homeTitle}}

<input [value]="myString">
<input [required]="myBoolean">

<button (click)="alertMe('I like x')">Click me</button>

<input [(ngModel)]="obj.name">

{{obj.name}}

{{obj.belt}}

Why obj.name does not render in the input element?


问:
Gradle won't pick up Android build tools unless opened in Android Studio
I'm preparing an Android build pipeline in Jenkins, on a Windows build server. Jenkins uses a number of workspaces and will often re-use them. I've noticed that when Jenkins re-uses a workspace, there are no problems and a build goes perfectly. But when it first checks out a new workspace, the gradle wrapper complains that it cannot install Android build-tools. The build tools (the exact version) are already installed.

I can open another older workspace and run the gradle build in there and it works perfectly and then, with the same login and in the exact same cmd session, go to the new workspace and run the same command and it complains that it cannot install Android build-tools.

A note about the Android configuration: I'm storing the Android SDK in C:\android-sdk\ and have given every user access to that directory. ANDROID_HOME and ANDROID_SDK are set as system-wide variables. This is the most convenient solution- this way every user that logs in, domain account or otherwise, is (in theory) able to immediately build the solution without having to set up their own SDK, and we don't end up with a lot of duplicated SDK data.

I can fix the issue manually by opening the workspace folder in Android Studio. Just doing this alone seems to fix the issue. My hypothesis is that somewhere there's a cached value in the project metadata telling gradle where to find the Android build-tools, and when I open Android Studio it updates this value.

Obviously the work-around isn't adequate because the build needs to work consistently every time without human intervention. Is there some command I can use to refresh this cache? Or perhaps some configuration files that are checked into git that shouldn't be?

答:
Figured it out. Gradle looks in two places, in order of priority, for your SDK: Firstly, it checks whether a local.properties file specifies the SDK. Then, it tries the ANDROID_HOME (not ANDROID_SDK) system variable. Opening a folder in Android Studio generates the local.properties file, which is why that work-around worked.

I had no local.properties file, but my ANDROID_HOME was set to the Android Studio install folder rather than the Android SDK. When I moved it to the SDK and re-started the Jenkins agent service it worked.


问:
Alfresco association
I am trying to understand the Alfresco associations. I have understood the concept behind peer association as well as parent child association with examples.

I am referring their official docs example (peer association) : http://docs.alfresco.com/5.2/tasks/dev-extensions-content-models-tutorials-add-association.html

Screenshot :

Question: I am not following how mandatory and many parameters can be used within source? Most of examples, I have seen, those are set to same as target. Can anybody explain the use-case where I can set many is true in source and false in target with real use-case/example?

答: Suppose you have a Contract and you want to associate it with a Customer. This is a Many-to-One relationship. A Contract is associated with only one Customer (target, many=false) but a Customer can have many Contracts (source, many=true).</p>

Title: Alfresco association


问:
PHP and dropdown insert error
Hello I  want to insert in a table the values selected from a dropdown menu and values from a user that was previosly created . When I do the insert the only values that get inserted into the tables area the ones from the drop down list. But the other values dont get inserted.  Please help me. Here is the code.</p>

```<code>   $query= "INSERT INTO employee (UserName, Password, Name, LastName, " .
    "Email, Phone, Classification_ClassificationID) VALUES" .
    " ('$user1', SHA('$password1'),'$name', '$lastname', '$email', " .
            " '$phone_number', '$classification_id')";
       queryMysql($query);

     echo '<p>Account Created.</p>';
     echo $user1;
        }
echo '<h1> Grupo Asignado:</h1>' ;

if (isset ($_POST['submit'])){

foreach ($_POST['toinsert'] as $insert_id) {
$query = "INSERT INTO groupusers (GroupsID, Employee_UserName) Values ('$insert_id', '$user1')" ;
queryMysql($query);
echo mysql_num_rows($result);

echo '<br />';
     }
     }

  $query = "SELECT * FROM employeegroups";
  $result = queryMysql($query);

  while ($row = mysql_fetch_array($result)) {
    echo '<input type="checkbox" value="' .$row['GroupsID'] . '" name="toinsert[]" />';
    echo $row['GroupName'];

    echo '<br />';

   }

echo '<input type="submit" name="submit" value="Insert" />';

echo '</form>';
echo '</body>';
echo '</html>';
?>
</code>```

答:
```<code>queryMysql($query);
echo mysql_num_rows($result);
</code>```

Where are you setting this $result? It's not explicity passed back from your queryMysql() function, so either it's unset at this point, or it's a global variable (bad idea).

As well, have you checked that the queries are actually executing? The mysql query functions return boolean FALSE if the query fails. If you're assuming they succeeded and proceed in your code, you'd end up with the symptoms you have.

ContentLicense: CC BY-SA 2.5

Title: PHP and dropdown insert error

Body:
Hello I  want to insert in a table the values selected from a dropdown menu and values from a user that was previosly created . When I do the insert the only values that get inserted into the tables area the ones from the drop down list. But the other values dont get inserted.  Please help me. Here is the code.

   $query= "INSERT INTO employee (UserName, Password, Name, LastName, " .
    "Email, Phone, Classification_ClassificationID) VALUES" .
    " ('$user1', SHA('$password1'),'$name', '$lastname', '$email', " .
            " '$phone_number', '$classification_id')";
       queryMysql($query);

     echo '
Account Created.
';
     echo $user1;
        }
echo '
 Grupo Asignado:
' ;

if (isset ($_POST['submit'])){

foreach ($_POST['toinsert'] as $insert_id) {
$query = "INSERT INTO groupusers (GroupsID, Employee_UserName) Values ('$insert_id', '$user1')" ;
queryMysql($query);
echo mysql_num_rows($result);

echo '
';
     }
     }

  $query = "SELECT * FROM employeegroups";
  $result = queryMysql($query);

  while ($row = mysql_fetch_array($result)) {
    echo '<input type="checkbox" value="' .$row['GroupsID'] . '" name="toinsert[]" />';
    echo $row['GroupName'];

    echo '
';

   }

echo '<input type="submit" name="submit" value="Insert" />';

echo '</form>';
echo '';
echo '';
?>

Body:
queryMysql($query);
echo mysql_num_rows($result);

Where are you setting this $result? It's not explicity passed back from your queryMysql() function, so either it's unset at this point, or it's a global variable (bad idea).

As well, have you checked that the queries are actually executing? The mysql query functions return boolean FALSE if the query fails. If you're assuming they succeeded and proceed in your code, you'd end up with the symptoms you have.


问:
Espresso Tests cannot access class file
I get the following errors where i try to run a ui test.

```<code>/Users/etiennelawlor/workspace/MovieHub/app/src/androidTest/java/com/etiennelawlor/moviehub/MoviesFragmentTest.java

Error:(34, 28) error: cannot access AppCompatActivity class file for android.support.v7.app.AppCompatActivity not found

Error:(34, 58) error: cannot infer type arguments for ActivityTestRule<>

Error:(41, 41) error: cannot access IdlingResource class file for android.support.test.espresso.IdlingResource not found

Error:(51, 40) error: cannot access RecyclerView class file for android.support.v7.widget.RecyclerView not found

Error:Execution failed for task ‘:app:compileDebugAndroidTestJavaWithJavac’.
Compilation failed; see the compiler error output for details.
</code>```

Here is my Test class : https://github.com/lawloretienne/MovieHub/blob/226492727e4d467b337ed4b689edb05eec0368c2/app/src/androidTest/java/com/etiennelawlor/moviehub/MoviesFragmentTest.java

Am I missing something?

Here is my Gradle file

https://github.com/lawloretienne/MovieHub/blob/master/app/build.gradle

答:
The build.gradle explicitly excludes all dependencies of the production apk, which in turn, excludes the compat library from the instrumentation apk.
I am not sure why this is required because I have never experienced that bug mentioned in the comment.

Basically, removing this block:

```<code>configurations.implementation.dependencies.all { implementationDependency ->
    println "Excluding implementation dependency: ${implementationDependency.getName()}"
    configurations.androidTestImplementation.dependencies.all { androidTestImplementationDependency ->
        configurations.androidTestImplementation.exclude module: "${implementationDependency.getName()}"
    }
}
</code>```

will fix it.

Title: Espresso Tests cannot access class file

Body:
I get the following errors where i try to run a ui test.

/Users/etiennelawlor/workspace/MovieHub/app/src/androidTest/java/com/etiennelawlor/moviehub/MoviesFragmentTest.java

Error:(34, 28) error: cannot access AppCompatActivity class file for android.support.v7.app.AppCompatActivity not found

Error:(34, 58) error: cannot infer type arguments for ActivityTestRule<>

Error:(41, 41) error: cannot access IdlingResource class file for android.support.test.espresso.IdlingResource not found

Error:(51, 40) error: cannot access RecyclerView class file for android.support.v7.widget.RecyclerView not found

Error:Execution failed for task ‘:app:compileDebugAndroidTestJavaWithJavac’.
Compilation failed; see the compiler error output for details.

Here is my Test class : https://github.com/lawloretienne/MovieHub/blob/226492727e4d467b337ed4b689edb05eec0368c2/app/src/androidTest/java/com/etiennelawlor/moviehub/MoviesFragmentTest.java

Am I missing something?

Here is my Gradle file

https://github.com/lawloretienne/MovieHub/blob/master/app/build.gradle

Body:
The build.gradle explicitly excludes all dependencies of the production apk, which in turn, excludes the compat library from the instrumentation apk.
I am not sure why this is required because I have never experienced that bug mentioned in the comment.

Basically, removing this block:

configurations.implementation.dependencies.all { implementationDependency ->
    println "Excluding implementation dependency: ${implementationDependency.getName()}"
    configurations.androidTestImplementation.dependencies.all { androidTestImplementationDependency ->
        configurations.androidTestImplementation.exclude module: "${implementationDependency.getName()}"
    }
}

will fix it.


问:
AWS PHP SDK 3.36 GetObject method throwing SignatureDoesNotMatch error
We are currently unable to download objects from S3, using the AWS PHP SDK v. 3.36. via the GetObject method.

We are seeing the following error:

```<code>Error executing "GetObject" on "<object path>";
AWS HTTP error: Client error: `GET <object path>` resulted in a `403 Forbidden` response:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>SignatureDoesNotMatch</Code>
  <Message>The request signature we calcul (truncated...)  SignatureDoesNotMatch (client): The request signature we calculated does not match the signature you
    provided. Check your key and signing method.
    - <?xml version="1.0" encoding="UTF-8"?>
      <Error>
        <Code>SignatureDoesNotMatch</Code>
        <Message>The request signature we calculated does not match the signature you provided.
          Check your key and signing method.

<remaining message redacted>
</code>```

S3 Client setup:

```<code>public function __construct($key, $secret, $region='us-east-1') {
    $this->key = $key;
    $this->secret = $secret;
    $this->handler = new S3Client([
        'credentials' => [
            'key'    => $key,
            'secret' => $secret
        ],
        'region' =>$region,
        'version' => '2006-03-01'
    ]);
}
</code>```

Call to GetObject method:

```<code>public function getFile($bucket, $sourcefile, $saveToDestination = null) {
    $getarray = array(
        'Bucket' => $bucket,
        'Key' => $sourcefile,
    );

    if ($saveToDestination) {
        $getarray['SaveAs'] = $saveToDestination;
    }

    return $this->handler->getObject($getarray);

}
</code>```

For the IAM user in question, full access to S3 is provided and the credentials used above have been verified.

IAM policy (AmazonS3FullAccess):

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "*"
        }
    ]
}
</code>```

答:
Did a bit of digging and found this. Either:
a) the api keys are incorrect or

b) the Content-Length header is not being provided in the request or

c) a non UTF-8 encoded string value in the request URI.

Hope this helps out.

Body:
We are currently unable to download objects from S3, using the AWS PHP SDK v. 3.36. via the GetObject method.

We are seeing the following error:

Error executing "GetObject" on "<object path>";
AWS HTTP error: Client error: `GET <object path>` resulted in a `403 Forbidden` response:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
  SignatureDoesNotMatch
  <Message>The request signature we calcul (truncated...)  SignatureDoesNotMatch (client): The request signature we calculated does not match the signature you
    provided. Check your key and signing method.
    - <?xml version="1.0" encoding="UTF-8"?>
      <Error>
        SignatureDoesNotMatch
        <Message>The request signature we calculated does not match the signature you provided.
          Check your key and signing method.

<remaining message redacted>

S3 Client setup:

public function __construct($key, $secret, $region='us-east-1') {
    $this->key = $key;
    $this->secret = $secret;
    $this->handler = new S3Client([
        'credentials' => [
            'key'    => $key,
            'secret' => $secret
        ],
        'region' =>$region,
        'version' => '2006-03-01'
    ]);
}

Call to GetObject method:

public function getFile($bucket, $sourcefile, $saveToDestination = null) {
    $getarray = array(
        'Bucket' => $bucket,
        'Key' => $sourcefile,
    );

    if ($saveToDestination) {
        $getarray['SaveAs'] = $saveToDestination;
    }

    return $this->handler->getObject($getarray);

}

For the IAM user in question, full access to S3 is provided and the credentials used above have been verified.

IAM policy (AmazonS3FullAccess):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "*"
        }
    ]
}


问:
Why can I printf to the screen but not a file in Java?
I wrote a method to printf a String to an external file, but I get a compiler error on the printf method. I used another method to printf the same String to the screen, and the only difference is the file declaration and replacing System.out.printf with outFile.printf; that method has no errors. What is the error in this method, and how can I fix it?</p>

```<code>public static void printFile(String master)
{
    File outFile = new File("output-file.txt");
    /* code that divides the string into tokens and assigns them to
    variables name, diameter, mass, and gravity */
    outFile.printf("%n%-10s%10s%10s%10s", name, diameter, mass, gravity);
}
</code>```

答:
File doesn't have a printf method - you can however create a PrintStream from a file:

```<code>PrintStream ps = new PrintStream(outFile);
ps.printf("%n%-10s%10s%10s%10s", name, diameter, mass, gravity);
</code>```

Note that you will need to close the PrintStream when you are done using it and it is good practice to specify an encoding.

Body:
I wrote a method to printf a String to an external file, but I get a compiler error on the printf method. I used another method to printf the same String to the screen, and the only difference is the file declaration and replacing System.out.printf with outFile.printf; that method has no errors. What is the error in this method, and how can I fix it?

public static void printFile(String master)
{
    File outFile = new File("output-file.txt");
    /* code that divides the string into tokens and assigns them to
    variables name, diameter, mass, and gravity */
    outFile.printf("%n%-10s%10s%10s%10s", name, diameter, mass, gravity);
}

Body:
File doesn't have a printf method - you can however create a PrintStream from a file:

PrintStream ps = new PrintStream(outFile);
ps.printf("%n%-10s%10s%10s%10s", name, diameter, mass, gravity);

Note that you will need to close the PrintStream when you are done using it and it is good practice to specify an encoding.


问:
How can I parse a string in JS which is the result of google location api?
Here is the result of ajax request:

```<code>console.log(locations.output);
/*
{
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
}
</code>```

Now I need to make an autocomplete list of the result. I mean I need to make such a thing:

```<code><ul>
  <li>Tehran Province, Iran</li>
  <li>Tehran, Tehran Province, Iran</li>
  <li>Tehranpars, Tehran, Tehran Province, Iran</li>
  <li>Tehran Bazaar, Tehran, Tehran Province, Iran</li>
</ul>
</code>```

But I don't know how can I select the value of description of the result. Here is my code:

```<code>var html = "<ul>";
$.each(locations.output, function (index, value) {
    console.log(value);
})
var html += "</ul>";

/*
"
p
r
e
d
.
.
.
</code>```

As you can see, the result is lots of single characters. How can I get that values?

答:
In order to get the JavaScript object from the response you can use JSON.parse(). This method parses a JSON string, constructing the JavaScript value or object described by the string:

```<code>var response = JSON.parse(locations.output);
</code>```

Than you can use response in your code like this:

// Mocking response variable for code example..
var response = {"predictions": [{"description": "Tehran Province, Iran","id": "4c45c924b261e2bb262360fb5a25d4b9a94088a7","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJf5Us9YQBjj8R0OohvHQms1U","reference": "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg","structured_formatting": {"main_text": "Tehran Province","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Iran"},"terms": [{"offset": 0,"value": "Tehran Province"},{"offset": 17,"value": "Iran"}],"types": ["administrative_area_level_1", "political", "geocode"]},{"description": "Tehran, Tehran Province, Iran","id": "14788d031b564588682273730e2e16d2617d3548","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ2dzzH0kAjj8RvCRwVnxps_A","reference": "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk","structured_formatting": {"main_text": "Tehran","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran"},{"offset": 8,"value": "Tehran Province"},{"offset": 25,"value": "Iran"}],"types": ["locality", "political", "geocode"]},{"description": "Tehranpars, Tehran, Tehran Province, Iran","id": "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJX5PM9hwdjj8R6zn_mu5suoE","reference": "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG","structured_formatting": {"main_text": "Tehranpars","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehranpars"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]},{"description": "Tehran Now, Tehran, Tehran Province, Iran","id": "1f7583f258e7e92f03b818ba10c48e20d2bd9f59","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ61k7RLICjj8RnvjuZpbZeEM","reference": "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k","structured_formatting": {"main_text": "Tehran Now","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Now"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["sublocality_level_1", "sublocality", "political", "geocode"]},{"description": "Tehran Bazaar, Tehran, Tehran Province, Iran","id": "7a97ba4c05dcb1b11c2153bd39673b6737aa5748","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJJX5my-8Bjj8RfAUG71zqw8s","reference": "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf","structured_formatting": {"main_text": "Tehran Bazaar","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Bazaar"},{"offset": 15,"value": "Tehran"},{"offset": 23,"value": "Tehran Province"},{"offset": 40,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]}], "status": "OK"};
var html = '
';

$.each(response.predictions, function (index, value) {
  html += '
' + value.description + '
';
});
html += '
';

$('#output').html(html);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="output"></div></code>```

Body:
Here is the result of ajax request:

console.log(locations.output);
/*
{
   "predictions" : [
      {
         "description" : "Tehran Province, Iran",
         "id" : "4c45c924b261e2bb262360fb5a25d4b9a94088a7",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJf5Us9YQBjj8R0OohvHQms1U",
         "reference" : "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg",
         "structured_formatting" : {
            "main_text" : "Tehran Province",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Province"
            },
            {
               "offset" : 17,
               "value" : "Iran"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      },
      {
         "description" : "Tehran, Tehran Province, Iran",
         "id" : "14788d031b564588682273730e2e16d2617d3548",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ2dzzH0kAjj8RvCRwVnxps_A",
         "reference" : "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk",
         "structured_formatting" : {
            "main_text" : "Tehran",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran"
            },
            {
               "offset" : 8,
               "value" : "Tehran Province"
            },
            {
               "offset" : 25,
               "value" : "Iran"
            }
         ],
         "types" : [ "locality", "political", "geocode" ]
      },
      {
         "description" : "Tehranpars, Tehran, Tehran Province, Iran",
         "id" : "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJX5PM9hwdjj8R6zn_mu5suoE",
         "reference" : "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG",
         "structured_formatting" : {
            "main_text" : "Tehranpars",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehranpars"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      },
      {
         "description" : "Tehran Now, Tehran, Tehran Province, Iran",
         "id" : "1f7583f258e7e92f03b818ba10c48e20d2bd9f59",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJ61k7RLICjj8RnvjuZpbZeEM",
         "reference" : "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k",
         "structured_formatting" : {
            "main_text" : "Tehran Now",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Now"
            },
            {
               "offset" : 12,
               "value" : "Tehran"
            },
            {
               "offset" : 20,
               "value" : "Tehran Province"
            },
            {
               "offset" : 37,
               "value" : "Iran"
            }
         ],
         "types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
      },
      {
         "description" : "Tehran Bazaar, Tehran, Tehran Province, Iran",
         "id" : "7a97ba4c05dcb1b11c2153bd39673b6737aa5748",
         "matched_substrings" : [
            {
               "length" : 6,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJJX5my-8Bjj8RfAUG71zqw8s",
         "reference" : "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf",
         "structured_formatting" : {
            "main_text" : "Tehran Bazaar",
            "main_text_matched_substrings" : [
               {
                  "length" : 6,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Tehran, Tehran Province, Iran"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Tehran Bazaar"
            },
            {
               "offset" : 15,
               "value" : "Tehran"
            },
            {
               "offset" : 23,
               "value" : "Tehran Province"
            },
            {
               "offset" : 40,
               "value" : "Iran"
            }
         ],
         "types" : [ "neighborhood", "political", "geocode" ]
      }
   ],
   "status" : "OK"
}

Now I need to make an autocomplete list of the result. I mean I need to make such a thing:

Tehran Province, Iran

Tehran, Tehran Province, Iran

Tehranpars, Tehran, Tehran Province, Iran

Tehran Bazaar, Tehran, Tehran Province, Iran

But I don't know how can I select the value of description of the result. Here is my code:

var html = "
";
$.each(locations.output, function (index, value) {
    console.log(value);
})
var html += "
";

/*
"
p
r
e
d
.
.
.

As you can see, the result is lots of single characters. How can I get that values?

Body:
In order to get the JavaScript object from the response you can use JSON.parse(). This method parses a JSON string, constructing the JavaScript value or object described by the string:

var response = JSON.parse(locations.output);

Than you can use response in your code like this:

// Mocking response variable for code example..
var response = {"predictions": [{"description": "Tehran Province, Iran","id": "4c45c924b261e2bb262360fb5a25d4b9a94088a7","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJf5Us9YQBjj8R0OohvHQms1U","reference": "CjQtAAAA6j_9DtMr30DQ9h8dzemfD2NaWEWBgf5yFlQ92XW4EZvHXqZ8Ob6wGkedetO1xNiZEhCGeIk7jBXCQP_ad4V0R-YeGhSIcGtxcxPh-G4e2DMT97Be4xdfkg","structured_formatting": {"main_text": "Tehran Province","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Iran"},"terms": [{"offset": 0,"value": "Tehran Province"},{"offset": 17,"value": "Iran"}],"types": ["administrative_area_level_1", "political", "geocode"]},{"description": "Tehran, Tehran Province, Iran","id": "14788d031b564588682273730e2e16d2617d3548","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ2dzzH0kAjj8RvCRwVnxps_A","reference": "CkQ1AAAAGXsNCFct3XK9JukMD-C7D7j1f0b-Rk0uBZFULZ9TKziZVKz2HWeNWZ5xWU-aNIceYEioJRxHmYS_O7DhMW32YBIQzGS_zTt6aijJx_onRU9DTRoU-cPuoOF16KrzlFY_4EGlwVf1Izk","structured_formatting": {"main_text": "Tehran","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran"},{"offset": 8,"value": "Tehran Province"},{"offset": 25,"value": "Iran"}],"types": ["locality", "political", "geocode"]},{"description": "Tehranpars, Tehran, Tehran Province, Iran","id": "09a979a1ac286c1ff2ee94c5d36258910d7f6ec6","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJX5PM9hwdjj8R6zn_mu5suoE","reference": "ClRBAAAACKbtLWiAm5kV0JzYtPOLhQTuMxlMMIXxPGRmuLUF7xuAlx7Mueo91OuJmB4mTwo3T0NhnNhamVDUsKFE0fNffkZi1Bv-ZQs1TcXLNx195C0SELOTSsOMn6pYeSnFMtvVqsIaFCxWipFk_wIxDKVoLi8Cd8g993cG","structured_formatting": {"main_text": "Tehranpars","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehranpars"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]},{"description": "Tehran Now, Tehran, Tehran Province, Iran","id": "1f7583f258e7e92f03b818ba10c48e20d2bd9f59","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJ61k7RLICjj8RnvjuZpbZeEM","reference": "ClRBAAAAydlnsS8Fjw9ibBXXX-XS4xuY4-7yEqMSZNTz66Q-4hRNnGdEGyOICqFbm4VQ4-ZV7O8fftoznes6-u-6sZyvz8Gp3N3hPLASFvtoWeJBPS8SEE8pPnxD20v8_NPnWLANDG8aFPfquA7RBNHvpEgiH5Q0eIqmtl5k","structured_formatting": {"main_text": "Tehran Now","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Now"},{"offset": 12,"value": "Tehran"},{"offset": 20,"value": "Tehran Province"},{"offset": 37,"value": "Iran"}],"types": ["sublocality_level_1", "sublocality", "political", "geocode"]},{"description": "Tehran Bazaar, Tehran, Tehran Province, Iran","id": "7a97ba4c05dcb1b11c2153bd39673b6737aa5748","matched_substrings": [{"length": 6,"offset": 0}],"place_id": "ChIJJX5my-8Bjj8RfAUG71zqw8s","reference": "ClREAAAABs4mvt65BUJ7Z2arVA_cv7V0tdPJKoVy010IOFrlS-L6VfhrEmIQAuxTXVQhnAA19fjEtVbPag3lfb-UrsmnMROnzvXiffA7MKUvgASMwvwSEGx-aGYRXyP1Q9Bxr7HmMVIaFKaxQEb8tg4L7IlRIbITWpG4F5Mf","structured_formatting": {"main_text": "Tehran Bazaar","main_text_matched_substrings": [{"length": 6,"offset": 0}],"secondary_text": "Tehran, Tehran Province, Iran"},"terms": [{"offset": 0,"value": "Tehran Bazaar"},{"offset": 15,"value": "Tehran"},{"offset": 23,"value": "Tehran Province"},{"offset": 40,"value": "Iran"}],"types": ["neighborhood", "political", "geocode"]}], "status": "OK"};
var html = '<ul>';

$.each(response.predictions, function (index, value) {
  html += '<li>' + value.description + '</li>';
});
html += '</ul>';

$('#output').html(html);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="output"></div>


问:
Spring Security: session expiration without redirect to expired-url?
I'm using Spring Security 3.0.2 form based authentication. But I can't figure out how I can configure it so that when a session expires that the request is not redirect to an other page (expired-url) or displays a 'session expires' message.

I don't want any redirect or messages, I want that a anonymous session is started just like when a user without a session enters the website.

My current configuration:

```<code><http>
  <intercept-url pattern="/login.action*" filters="none"/>
  <intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
  <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
  <form-login login-page="/login.action"
               authentication-failure-url="/login.action?error=failed"
               login-processing-url="/login-handler.action"/>
  <logout logout-url="/logoff-execute.action"
          logout-success-url="/logoff.action?done=1"/>
  <remember-me key="remember-me-security" services-ref="rememberMeServices"/>
  <session-management >
    <concurrency-control max-sessions="1"
                         error-if-maximum-exceeded="false"
                         expired-url="/login.action?error=expired.url"/>
  </session-management>
</http>
</code>```

答:
You can try:</p>

```<code>    <logout invalidate-session="true"
             logout-url="/LoginPage.jsf?error_logout=logoutComSucesso"/><!--invalido logout-success-url="/LoginPage.jsf?auth_error" -->
    <session-management session-fixation-protection="newSession" invalid-session-url="/LoginPage.jsf?error=sessionExpired"
                    session-authentication-error-url="/LoginPage.jsf?auth_error=BadCredencials" >
    </session-management>
</code>```

Body:
I'm using Spring Security 3.0.2 form based authentication. But I can't figure out how I can configure it so that when a session expires that the request is not redirect to an other page (expired-url) or displays a 'session expires' message.

I don't want any redirect or messages, I want that a anonymous session is started just like when a user without a session enters the website.

My current configuration:

<http>
  <intercept-url pattern="/login.action*" filters="none"/>
  <intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
  <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
  <form-login login-page="/login.action"
               authentication-failure-url="/login.action?error=failed"
               login-processing-url="/login-handler.action"/>
  <logout logout-url="/logoff-execute.action"
          logout-success-url="/logoff.action?done=1"/>
  <remember-me key="remember-me-security" services-ref="rememberMeServices"/>
  <session-management >
    <concurrency-control max-sessions="1"
                         error-if-maximum-exceeded="false"
                         expired-url="/login.action?error=expired.url"/>
  </session-management>
</http>

Body:
You can try:

    <logout invalidate-session="true"
             logout-url="/LoginPage.jsf?error_logout=logoutComSucesso"/><!--invalido logout-success-url="/LoginPage.jsf?auth_error" -->
    <session-management session-fixation-protection="newSession" invalid-session-url="/LoginPage.jsf?error=sessionExpired"
                    session-authentication-error-url="/LoginPage.jsf?auth_error=BadCredencials" >
    </session-management>


问:
Processes accessing a Shared Memory segment returning different values
I'm new to the IPCS concept,i want to achieve that one process creates and initializes a shared memory and then calls another process which attaches to the same shared memory segment and prints the data in the shared memory.
However i'm unable to achieve it:

AlgoCommon.h

```<code>struct sub_algo_shm
{
int time;
int pno;
};
struct AlgoShm
{
int head;
int tail;
char fFlag;
struct sub_algo_shm algoshm;
};
</code>```

AlgoThrottle.c

```<code>#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
        {
                int shmid ;
                struct timeval CurTime;
                struct timespec nTime;
                struct AlgoShm *shmaddr,*ptr;

                ptr = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));
                //Creating Shared Memory
                if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
                {
                        perror("shmget:error");
                }
                else
                {
                        printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
                        //Attaching to Shared Memory
                        shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
                        if(shmaddr < 0)
                        {
                                perror(" shmat :error");
                        }
                        else
                        {
                                printf(" SHM Segment attached at [%x] ",shmaddr);
                        }
                        //Loading/Initializing Data Blocks in SHM
                        clock_gettime(CLOCK_REALTIME,&nTime);
                        printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
                        ptr->head = 5;
                        ptr->tail = 3;
                        ptr->fFlag = '0';
                        ptr->algoshm.time = 0;
                        ptr->algoshm.pno = 1;
                        //memcpy(shmaddr,&ptr,sizeof(ptr));
                        printf(" AlgoThrottle|ptr->head [%d] ",ptr->head);
                //      sleep(1);
                        system("./AlgoRead");

                }

        return 0;
        }
</code>```

AlgoRead.c

```<code>#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
    {

    int shmid ;
    struct AlgoShm *shmaddr,*ptr1 ;
    ptr1 = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));

    if((shmid = shmget(key,SHM_SIZE,0)) < 0)
    {

    perror(" AlgoRead|shmget:error ");
    }
    else
    {
            printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

            if((shmaddr = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
            {
                    perror("AlgoRead|shmat error");
            }
            else
            {
                    //memcpy(ptr1,shmaddr,sizeof(struct AlgoShm));
                    printf(" AlgoRead|Attached to Segment at Address[%x] \n ",shmaddr);
                    printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
            }
    }

    return 0;
    }
</code>```

This is my output:

```<code>Shm created key=[111119]
 Segment Id [1179615678]  SHM Segment attached at [4a6b4000]  Time in N secs[114594083]
 AlgoRead|SHM Created shmid [1179615678]  AlgoRead|Attached to Segment at Address[624cb000]
  AlgoRead|ptr1->head [36810768] ptr1->tail [0] ptr1->fFlag[▒]
   AlgoThrottle|ptr->head [5]
</code>```

Also,system call's output is showing first then the printf statement even after i used a sleep(1) before invoking system()

答:
first thing, if you are using shared memory then why malloc() ? shared memory itself will attach shmid with shared memory you don't have to do  explicitly malloc().

second thing, you are attaching shmaddr pointer with memory returned by shmat() but putting data into ptr, ptr is attached with heap memory not with shared memory. So either put the data into shmaddr pointer or replace this

```<code>shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
</code>```

with

```<code>ptr = (struct AlgoShm *)shmat(shmid,0,0);
</code>```

and don't allocate memory using mallocc().then do

```<code>                ptr->head = 5;
                ptr->tail = 3;
                ptr->fFlag = '0';
                ptr->algoshm.time = 0;
                ptr->algoshm.pno = 1;
</code>```

do all these modification in both process. and finally you should do shmdt() for de-attaching shared memory otherwise it will be a memory leakage.

I modified your code as
one.c :

```<code>int main()
{
        int shmid ;
        struct timeval CurTime;
        struct timespec nTime;
        struct AlgoShm *shmaddr,*ptr;
        if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
        {
                perror("shmget:error");
        }
        else
        {
                printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
                ptr = (struct AlgoShm *)shmat(shmid,0,0);
                if(shmaddr < 0)
                {
                        perror(" shmat :error");
                }
                else
                {
                        printf(" SHM Segment attached at [%x] ",ptr);
                }
                clock_gettime(CLOCK_REALTIME,&nTime);
                printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
                ptr->head = 5;
                ptr->tail = 3;
                ptr->fFlag = 'a';
                ptr->algoshm.time = 10;
                ptr->algoshm.pno = 11;
                printf(" AlgoThrottle|ptr->head [%x] ",ptr->head);

        }
        system("./AlgoRead");
        return 0;
}
</code>```

two.c :

```<code>int main()
{
        int shmid ;
        struct AlgoShm *shmaddr,*ptr1 ;
        if((shmid = shmget(key,SHM_SIZE,0)) < 0)
        {

                perror(" AlgoRead|shmget:error ");
        }
        else
        {
                printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

                if((ptr1 = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
                {
                        perror("AlgoRead|shmat error");
                }
                else
                        printf(" AlgoRead|Attached to Segment at Address[%x] \n ",ptr1);
                printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
        }
        shmdt(ptr1);
        return 0;
}
</code>```

I hope it helps you and my advise to you is to go through man page of shmget(), shmat() & shmdt() properly.

Body:
I'm new to the IPCS concept,i want to achieve that one process creates and initializes a shared memory and then calls another process which attaches to the same shared memory segment and prints the data in the shared memory.
However i'm unable to achieve it:

AlgoCommon.h

struct sub_algo_shm
{
int time;
int pno;
};
struct AlgoShm
{
int head;
int tail;
char fFlag;
struct sub_algo_shm algoshm;
};

AlgoThrottle.c

#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
        {
                int shmid ;
                struct timeval CurTime;
                struct timespec nTime;
                struct AlgoShm *shmaddr,*ptr;

                ptr = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));
                //Creating Shared Memory
                if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
                {
                        perror("shmget:error");
                }
                else
                {
                        printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
                        //Attaching to Shared Memory
                        shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
                        if(shmaddr < 0)
                        {
                                perror(" shmat :error");
                        }
                        else
                        {
                                printf(" SHM Segment attached at [%x] ",shmaddr);
                        }
                        //Loading/Initializing Data Blocks in SHM
                        clock_gettime(CLOCK_REALTIME,&nTime);
                        printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
                        ptr->head = 5;
                        ptr->tail = 3;
                        ptr->fFlag = '0';
                        ptr->algoshm.time = 0;
                        ptr->algoshm.pno = 1;
                        //memcpy(shmaddr,&ptr,sizeof(ptr));
                        printf(" AlgoThrottle|ptr->head [%d] ",ptr->head);
                //      sleep(1);
                        system("./AlgoRead");

                }

        return 0;
        }

AlgoRead.c

#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
    {

    int shmid ;
    struct AlgoShm *shmaddr,*ptr1 ;
    ptr1 = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));

    if((shmid = shmget(key,SHM_SIZE,0)) < 0)
    {

    perror(" AlgoRead|shmget:error ");
    }
    else
    {
            printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

            if((shmaddr = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
            {
                    perror("AlgoRead|shmat error");
            }
            else
            {
                    //memcpy(ptr1,shmaddr,sizeof(struct AlgoShm));
                    printf(" AlgoRead|Attached to Segment at Address[%x] \n ",shmaddr);
                    printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
            }
    }

    return 0;
    }

This is my output:

Shm created key=[111119]
 Segment Id [1179615678]  SHM Segment attached at [4a6b4000]  Time in N secs[114594083]
 AlgoRead|SHM Created shmid [1179615678]  AlgoRead|Attached to Segment at Address[624cb000]
  AlgoRead|ptr1->head [36810768] ptr1->tail [0] ptr1->fFlag[▒]
   AlgoThrottle|ptr->head [5]

Also,system call's output is showing first then the printf statement even after i used a sleep(1) before invoking system()

Body:
first thing, if you are using shared memory then why malloc() ? shared memory itself will attach shmid with shared memory you don't have to do  explicitly malloc().

second thing, you are attaching shmaddr pointer with memory returned by shmat() but putting data into ptr, ptr is attached with heap memory not with shared memory. So either put the data into shmaddr pointer or replace this

shmaddr = (struct AlgoShm *)shmat(shmid,0,0);

with

ptr = (struct AlgoShm *)shmat(shmid,0,0);

and don't allocate memory using mallocc().then do

                ptr->head = 5;
                ptr->tail = 3;
                ptr->fFlag = '0';
                ptr->algoshm.time = 0;
                ptr->algoshm.pno = 1;

do all these modification in both process. and finally you should do shmdt() for de-attaching shared memory otherwise it will be a memory leakage.

I modified your code as
one.c :

int main()
{
        int shmid ;
        struct timeval CurTime;
        struct timespec nTime;
        struct AlgoShm *shmaddr,*ptr;
        if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
        {
                perror("shmget:error");
        }
        else
        {
                printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
                ptr = (struct AlgoShm *)shmat(shmid,0,0);
                if(shmaddr < 0)
                {
                        perror(" shmat :error");
                }
                else
                {
                        printf(" SHM Segment attached at [%x] ",ptr);
                }
                clock_gettime(CLOCK_REALTIME,&nTime);
                printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
                ptr->head = 5;
                ptr->tail = 3;
                ptr->fFlag = 'a';
                ptr->algoshm.time = 10;
                ptr->algoshm.pno = 11;
                printf(" AlgoThrottle|ptr->head [%x] ",ptr->head);

        }
        system("./AlgoRead");
        return 0;
}

two.c :

int main()
{
        int shmid ;
        struct AlgoShm *shmaddr,*ptr1 ;
        if((shmid = shmget(key,SHM_SIZE,0)) < 0)
        {

                perror(" AlgoRead|shmget:error ");
        }
        else
        {
                printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

                if((ptr1 = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
                {
                        perror("AlgoRead|shmat error");
                }
                else
                        printf(" AlgoRead|Attached to Segment at Address[%x] \n ",ptr1);
                printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
        }
        shmdt(ptr1);
        return 0;
}

I hope it helps you and my advise to you is to go through man page of shmget(), shmat() & shmdt() properly.


答:
You can use replace() with a regex containing the searched country, this is how should be the regex /(AUS;?)/.

This is how should be your code:

var str = "USA;UK;AUS;NZ";
var country = "AUS";
var reg = new RegExp("("+country+";?)");
str = str.replace(reg, '');
console.log(str);```

This will remove the ; after your country if it exists.

Title: How to remove string with specific value from a string using JavaScript?

Body:
Suppose my string is like:

var str = "USA;UK;AUS;NZ"

Now from some a source I am getting one value like:

country.data = "AUS"

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

var someStr= str.substring(0, str.indexOf(country.data))

In this case I got the same result.

Body:
You can use replace() with a regex containing the searched country, this is how should be the regex /(AUS;?)/.

This is how should be your code:

var str = "USA;UK;AUS;NZ";
var country = "AUS";
var reg = new RegExp("("+country+";?)");
str = str.replace(reg, '');
console.log(str);

This will remove the ; after your country if it exists.


问:
how JVM handel internally if two user defined class loader loads same class?
How JVM managing internally

If load same version of class loads in two different user defined class loader?

2 . If load different version of class loads in two different user defined class loader (same class name and package). If JVM loads both classes which will be referred in my application.

We know JVM loads the class in the combination of class, package & Klass loader.

I want to know how internally JVM handle these situations.

答:
Inside a JVM instance, information about loaded types is stored in a logical area of memory called the method area. For each type it loads, JVM stores the different type of information in the method area including:
•   The fully qualified name of the type
•   Whether or not the type is a class or an interface
•   A reference to class ClassLoader – information about the classloader used to load this type</p>


问:
Trying to create a stored procedure (from text file) in java using MySQL connector
As title says I'm trying to read and create a stored procedure from a simple text file... everything works fine in MySQL but as soon as I run the same SQL though the connector i get a syntax error.

```<code> BufferedReader br = new BufferedReader(new FileReader("st1.txt"));
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String storedproc1 = sb.toString();
    System.out.println(storedproc1);
    PreparedStatement ps2 = conn.prepareStatement(storedproc1);
    ps2.execute();
</code>```

Which gives this output:

I'll reiterate that the SQL works fine in MySQL workbench .

答:
The answer was wonderfully simple! Apparently the jdbc doesn't like the

```<code>Delimiter $$
</code>```

line, I simply got rid of that line and the $$ after the

```<code>end
</code>```

All is well! :)

Body:
As title says I'm trying to read and create a stored procedure from a simple text file... everything works fine in MySQL but as soon as I run the same SQL though the connector i get a syntax error.

 BufferedReader br = new BufferedReader(new FileReader("st1.txt"));
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String storedproc1 = sb.toString();
    System.out.println(storedproc1);
    PreparedStatement ps2 = conn.prepareStatement(storedproc1);
    ps2.execute();

Which gives this output:

I'll reiterate that the SQL works fine in MySQL workbench .

Body:
The answer was wonderfully simple! Apparently the jdbc doesn't like the

Delimiter $$

line, I simply got rid of that line and the $$ after the

end

All is well! :)


问:
Safari blocks play() on video despite being called from click event
I'm creating some custom video controls for an html5  element. I've bound a click event handler to a play/pause button which calls .play() on the corresponding video.

From my research, Safari will block calls to .play() unless you are in a click handler, however it is blocking my calls to .play() despite the fact that I am triggering it from within a click handler, like so:

```<code>$('.video-container .play-pause').click(function(event){
    var $video = $(event.currentTarget).parent().find('video');
    if($video[0].paused)
      $video[0].play();
    else
      $video[0].pause();
});
</code>```

And the error:

```<code>Unhandled Promise Rejection: NotSupportedError (DOM Exception 9): The operation is not supported.
</code>```

which is originating from $video[0].play();.

Safari Version 11.0.1 (13604.3.5)

OSX High Sierra 10.13.1 (17B48)

Any ideas?

答:
Eugh. The solution was to use an absolute path for the video source, not a relative one.

This is wrong: <video src="assets/vid.mp4"></video>

This is correct: <video src="http://example.com/assets/vid.mp4"></video>

Body:
I'm creating some custom video controls for an html5  element. I've bound a click event handler to a play/pause button which calls .play() on the corresponding video.

From my research, Safari will block calls to .play() unless you are in a click handler, however it is blocking my calls to .play() despite the fact that I am triggering it from within a click handler, like so:

$('.video-container .play-pause').click(function(event){
    var $video = $(event.currentTarget).parent().find('video');
    if($video[0].paused)
      $video[0].play();
    else
      $video[0].pause();
});

And the error:

Unhandled Promise Rejection: NotSupportedError (DOM Exception 9): The operation is not supported.

which is originating from $video[0].play();.

Safari Version 11.0.1 (13604.3.5)

OSX High Sierra 10.13.1 (17B48)

Any ideas?


问:
Why there is not `package` type of thing by default in postgres like oracle have?
Why postgres have not given  package like thing ,so that same type of function can be placed inside a individual collective unit . In current approach if postgres we have too write individual function that make to messy for origination of code.

答:
There's a exhaustive discussion in PostgreSQL community about Oracle-style packages, as you can see here. I've been following this discussion from afar, IMHO there's a consensus that hackers should focus on more significant issues - related to Oracle to PostgreSQL migration - than packages.

In short, there's the need but it's at the end of the queue.