问:
How to pass form input value to php function
I want to write a php page in which there is a html form. I want to send all input (number for example) of my form to a php function (instead of a javascript function; I make this to hide my javascript function code).

How can I send input value to php function?

Is it possible to call the php function through onclick="function(param1, param2)"?

I know that javascript is a client-side language while php is server-side.

If it is possible, how can I write the return of the function in an input field?

I want to remain in my page.

Is it correct - action="#"?

My code is:

```<code><form action="#" method="get">
    Inserisci number1:
    <input type="text" name="val1" id="val1"></input>

    <?php echo "ciaoooo"; ?>

    <br></br>
    Inserisci number2:
    <input type="text" name="val2" id="val2"></input>

    <br></br>

    <input type="submit" value="send"></input>
</form>
</code>```

Help me in the implementation of the simple php function and in the passage of values from input to function!
Thanks!

答:
you must have read about function call . here i give you example of it.</p>

```<code><?php
 funtion pr($n)
{
echo $n;
 }
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>
</code>```

Body:
I want to write a php page in which there is a html form. I want to send all input (number for example) of my form to a php function (instead of a javascript function; I make this to hide my javascript function code).

How can I send input value to php function?

Is it possible to call the php function through onclick="function(param1, param2)"?

I know that javascript is a client-side language while php is server-side.

If it is possible, how can I write the return of the function in an input field?

I want to remain in my page.

Is it correct - action="#"?

My code is:

<form action="#" method="get">
    Inserisci number1:
    <input type="text" name="val1" id="val1"></input>

    <?php echo "ciaoooo"; ?>

    Inserisci number2:
    <input type="text" name="val2" id="val2"></input>

    <input type="submit" value="send"></input>
</form>

Help me in the implementation of the simple php function and in the passage of values from input to function!
Thanks!

Body:
you must have read about function call . here i give you example of it.

<?php
 funtion pr($n)
{
echo $n;
 }
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>


来源: stackexchange

问:
How to implement push notification cross-browser?
I have a web application and I need the user to be able to see wether a notification for them has landed. I want the notification icon to change it's state when they have a new one.

Basically, I want to listen when the API endpoint updates it's state for the current user and the front end to change it's state.

I thought of make that endpoint as an observable and the front end as an observer, but I don't know if that fits in what I need.

Any ideas?

答:
I'd suggest to use a web socket implementation, such as Socket.io.

Although there are many alternatives to Socket.io, its major advantage is that it provides multiple fallbacks for older browsers. So, e.g. if web sockets are not available or do not work, it tries AJAX long polling. This way you can even support browsers that were created at a time, when nobody even knew what web sockets are - but to you, the API stays the same.

If you know that you only have to deal with modern browsers, you may use a more lightweight alternative instead, e.g. ws.

If you are looking for something completely different, which is purely based on HTTP and does not require an additional protocol, you might be interested in HTML5 Server-sent events. They work great, but in contrast to web sockets they are not bidirectional, and they are currently not supported in IE and Edge. They also have some other disadvantages. For example, it's not possible to add custom headers to an SSE request.

With HTTP2 it's maybe questionable how much impact web sockets will still have in the future, especially if you take into account that things such as the Streams API are coming. Then, you could basically solve everything using pure HTTP, which has some advantages as well. But right now, the Streams API is not here, so let's wait and see…

ContentLicense: CC BY-SA 3.0


问:
consoling angular form output failed
This is my html view in angular:

```<code><div class="container">
  <div class="row">
        <div class="col-md-3">
        </div>
    <div class="col-md-6">
          <div class="jumbotron">

          <h2>Complete your Profile</h2>
          <h5 style="color:royalblue;">Add your updated Resume to get notified by Recruiters</h5>
          <form #ResumeForm="ngForm"
           (ngSubmit)="submitResume(ResumeForm.value)">
              <div class="form-group">
                <label>Resume</label>
                <input type="file" name="resume" id="resume" class="form-control">
              </div>

                <input value="submit" type="submit">

          </form>

          </div>
    </div>
  </div>
</div>
</code>```

My .ts file is here

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-candidate-reg-complete',
  templateUrl: './candidate-reg-complete.component.html',
  styleUrls: ['./candidate-reg-complete.component.css']
})
export class CandidateRegCompleteComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
  submitResume=function(user){
   console.log(user);
 }

}
</code>```

But the console screen shows only object{}. No form content is shown.
I am trying to take file input.
Can anyone help me?

Thanks in advance.

答:
```<code>    import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-candidate-reg-complete',
  templateUrl: './candidate-reg-complete.component.html',
  styleUrls: ['./candidate-reg-complete.component.css']
})
export class CandidateRegCompleteComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
  submitResume(user){
   console.log(user);
 }

}
</code>```

Title: consoling angular form output failed

Body:
This is my html view in angular:

Complete your Profile

Add your updated Resume to get notified by Recruiters

          <form #ResumeForm="ngForm"
           (ngSubmit)="submitResume(ResumeForm.value)">

                Resume
                <input type="file" name="resume" id="resume" class="form-control">

                <input value="submit" type="submit">

          </form>

My .ts file is here

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-candidate-reg-complete',
  templateUrl: './candidate-reg-complete.component.html',
  styleUrls: ['./candidate-reg-complete.component.css']
})
export class CandidateRegCompleteComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
  submitResume=function(user){
   console.log(user);
 }

}

But the console screen shows only object{}. No form content is shown.
I am trying to take file input.
Can anyone help me?

Thanks in advance.


问:
Android application and Bluetooth commercial subscription
I'm developing an Android BLE App for pairing smartphones with a specific type of custom made devices. With this application you can control it remotely sending and receiving data. Those devices are an industrial product,and they'll be sell soon on the market. The app will be released for free on the Google Play Store.

The question is : should I pay for use Bluetooth technology and the bt logo?
The bill is not cheap..8k$ and taking a look at the Play Store i saw a lot of non-free app with the bt logo,all of them payed the 8k subscription tax required by the bt foundation?

答: You don't need to pay for the Android app, but for the peripheral device itself if you use any of the Bluetooth trademarks (logo for instance).</p>


问:
Android LibGDX: tiled map covers animation
I have a tiled map and an animation. However, the map covers this last and I don't know why. If I add only the animation, I can see it, but not if also I add the map. Please answer me, I can't find the solution!

Here is my code:

```<code>public class MyGdxGame extends ApplicationAdapter implements GestureDetector.GestureListener
{

Texture texture;
SpriteBatch batch;
Sprite sprite;
TextureAtlas textureAtlas;
Animation animation;
float time;
OrthographicCamera orthographicCamera;

Texture corridore;
Sprite spriteCorridore;

TiledMap map;
OrthogonalTiledMapRenderer renderer;

@Override
public void create () {

    batch = new SpriteBatch();
    corridore = new Texture("a.png");
    spriteCorridore = new Sprite(corridore);
    orthographicCamera = new OrthographicCamera(500,500);
    orthographicCamera.position.x=500;
    orthographicCamera.position.y=250;
    map = new TmxMapLoader().load("mappa.tmx");
    renderer = new OrthogonalTiledMapRenderer(map);
    textureAtlas = new TextureAtlas(Gdx.files.internal("corsa.atlas"));
    animation = new Animation(1/20f,textureAtlas.findRegion("a"),textureAtlas.findRegion("b"),
            textureAtlas.findRegion("c"),textureAtlas.findRegion("d"),textureAtlas.findRegion("e"),
            textureAtlas.findRegion("f"),textureAtlas.findRegion("g"),textureAtlas.findRegion("h"),
            textureAtlas.findRegion("i"));
}

@Override
public void render () {
    time = time + Gdx.graphics.getDeltaTime();
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(orthographicCamera.combined);
    batch.begin();
    batch.draw((TextureRegion)animation.getKeyFrame(time,true),orthographicCamera.position.x-spriteCorridore.getWidth()/2,orthographicCamera.position.y-spriteCorridore.getHeight()/2);
    renderer.setView(orthographicCamera);
    renderer.render();

    orthographicCamera.translate(1, 0);
    orthographicCamera.update();

    batch.end();
}

}
</code>```

答:
Render your animation at the top of TiledMapRenderer so change your rendering order.

```<code>@Override
public void render () {
    time = time + Gdx.graphics.getDeltaTime();
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    renderer.setView(orthographicCamera);
    renderer.render();

    batch.setProjectionMatrix(orthographicCamera.combined);
    batch.begin();
    batch.draw((TextureRegion)animation.getKeyFrame(time,true),orthographicCamera.position.x-spriteCorridore.getWidth()/2,orthographicCamera.position.y-spriteCorridore.getHeight()/2);
    batch.end();

    orthographicCamera.translate(1, 0);
    orthographicCamera.update();
}
</code>```

Body:
I have a tiled map and an animation. However, the map covers this last and I don't know why. If I add only the animation, I can see it, but not if also I add the map. Please answer me, I can't find the solution!

Here is my code:

public class MyGdxGame extends ApplicationAdapter implements GestureDetector.GestureListener
{

Texture texture;
SpriteBatch batch;
Sprite sprite;
TextureAtlas textureAtlas;
Animation animation;
float time;
OrthographicCamera orthographicCamera;

Texture corridore;
Sprite spriteCorridore;

TiledMap map;
OrthogonalTiledMapRenderer renderer;

@Override
public void create () {

    batch = new SpriteBatch();
    corridore = new Texture("a.png");
    spriteCorridore = new Sprite(corridore);
    orthographicCamera = new OrthographicCamera(500,500);
    orthographicCamera.position.x=500;
    orthographicCamera.position.y=250;
    map = new TmxMapLoader().load("mappa.tmx");
    renderer = new OrthogonalTiledMapRenderer(map);
    textureAtlas = new TextureAtlas(Gdx.files.internal("corsa.atlas"));
    animation = new Animation(1/20f,textureAtlas.findRegion("a"),textureAtlas.findRegion("b"),
            textureAtlas.findRegion("c"),textureAtlas.findRegion("d"),textureAtlas.findRegion("e"),
            textureAtlas.findRegion("f"),textureAtlas.findRegion("g"),textureAtlas.findRegion("h"),
            textureAtlas.findRegion("i"));
}

@Override
public void render () {
    time = time + Gdx.graphics.getDeltaTime();
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(orthographicCamera.combined);
    batch.begin();
    batch.draw((TextureRegion)animation.getKeyFrame(time,true),orthographicCamera.position.x-spriteCorridore.getWidth()/2,orthographicCamera.position.y-spriteCorridore.getHeight()/2);
    renderer.setView(orthographicCamera);
    renderer.render();

    orthographicCamera.translate(1, 0);
    orthographicCamera.update();

    batch.end();
}

}

Body:
Render your animation at the top of TiledMapRenderer so change your rendering order.

@Override
public void render () {
    time = time + Gdx.graphics.getDeltaTime();
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    renderer.setView(orthographicCamera);
    renderer.render();

    batch.setProjectionMatrix(orthographicCamera.combined);
    batch.begin();
    batch.draw((TextureRegion)animation.getKeyFrame(time,true),orthographicCamera.position.x-spriteCorridore.getWidth()/2,orthographicCamera.position.y-spriteCorridore.getHeight()/2);
    batch.end();

    orthographicCamera.translate(1, 0);
    orthographicCamera.update();
}


问:
IndexOf: how many vowels there are?
I need to have the code tell the user how many of the five vowels (a,e,i,o,u) are in the first string, as well as the second string. This is what I've worked up so far but I'm stuck in terms of how to print how many vowels there are total.</p>

```<code>Scanner in=new Scanner(System.in);

    System.out.println( "Enter String 1: ");
    String s1=in.next();
    System.out.println( "Enter String 2: ");
    String s2=in.next();

   int a= s1.length();

   int b= s2.length();

   if (a<b)
   System.out.println( s2 + "is longer than " + s1);
   else if (b<a)
   System.out.println( s1 + " is longer than " + s2);
   else
   System.out.println(s1 + " and " + s2 + " are the same length.");

   int c=(s1.indexOf(('a')));
   int d=(s1.indexOf(('e')));
   int e=(s1.indexOf(('o')));
   int f=(s1.indexOf(('i')));
   int g=(s1.indexOf(('u')));

   if (c>=0)
   System.out.println( "AFFIRMATIVE FOR A");
   if (d>=0)
   System.out.println( "AFFIRMATIVE FOR E");
   if (e>=0)
   System.out.println( "AFFIRMAtive fOR O");
   if (f>=0)
   System.out.println( "AFFIRMATIVE for I");
   if (g>=0)
   System.out.println( "AFFIRMATIVE for U");
</code>```

答:
Try</p>

```<code>int count = s1.split("a").length - 1
</code>```

Title: IndexOf: how many vowels there are?

Body:
I need to have the code tell the user how many of the five vowels (a,e,i,o,u) are in the first string, as well as the second string. This is what I've worked up so far but I'm stuck in terms of how to print how many vowels there are total.

Scanner in=new Scanner(System.in);

    System.out.println( "Enter String 1: ");
    String s1=in.next();
    System.out.println( "Enter String 2: ");
    String s2=in.next();

   int a= s1.length();

   int b= s2.length();

   if (a<b)
   System.out.println( s2 + "is longer than " + s1);
   else if (b=0)
   System.out.println( "AFFIRMATIVE FOR A");
   if (d>=0)
   System.out.println( "AFFIRMATIVE FOR E");
   if (e>=0)
   System.out.println( "AFFIRMAtive fOR O");
   if (f>=0)
   System.out.println( "AFFIRMATIVE for I");
   if (g>=0)
   System.out.println( "AFFIRMATIVE for U");

Body:
Try

int count = s1.split("a").length - 1


问:
Benchmark on different String dictionaries shows that the normal one is faster, and I don't know why
I'm doing some benchmark on several string dictionaries, because I wanted to find out how performs the different configurations, and I got surprised that the normal Dictionary<String,String> is the faster. Probably because I'm missing some concept or I'm doing something wrong, but these are the results I got:

```<code>Collection:             2147482 items.
Random Keys:            1000 keys.

Normal dictionary
        Add 1000 items:         573ms.
        Get 1000 keys:          0ms.

Normal Dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         642ms.
        Get 1000 keys:          0ms.

Normal Dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         1661ms.
        Get 1000 keys:          0ms.

Sorted dictionary
        Add 1000 items:         11996ms.
        Get 1000 keys:          5ms.

Sorted dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         11097ms.
        Get 1000 keys:          5ms.

Sorted dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         9814ms.
        Get 1000 keys:          5ms.
</code>```

An this is the code I'm using to test it:

```<code>    static void Main(string[] args)
    {
        String[] col = GenerateCollectionUnsorted(Int32.MaxValue / 1000).ToArray();
        Int32 len = col.Length;
        Console.WriteLine("Collection:\t\t" + len.ToString() + " items.");

        String[] randomKeys = GetRandomKeys(col, 1000);
        Console.WriteLine("Random Keys:\t\t" + randomKeys.Length.ToString() + " keys.");

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal dictionary");
        TestDic(col, randomKeys, new Dictionary<String, String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary");
        TestDic(col,randomKeys, new SortedDictionary<String,String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("\nEnd");
        Console.ReadKey(true);
    }

    static void TestDic(String[] col, String[] randomKeys, IDictionary<String,String> dic)
    {
        Stopwatch crono = new Stopwatch();

        crono.Start();
        foreach (String s in col)
            dic.Add(s, s);
        crono.Stop();

        Console.WriteLine("\tAdd "+randomKeys.Length.ToString()+" items:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");

        crono.Reset();
        crono.Start();
        String sv;
        foreach (var rk in randomKeys)
        {
            sv = dic[rk];
            sv.ToString();
        }
        crono.Stop();
        Console.WriteLine("\tGet " + randomKeys.Length.ToString() + " keys:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");
    }

    static String[] GetRandomKeys(String[] col, Int32 count)
    {
        Random ran = new Random(DateTime.Now.Millisecond);

        List<Int32> indexSelection = new List<int>();
        List<String> selection = new List<string>();

        Int32 len = col.Length;

        while (indexSelection.Count < count)
        {
            Int32 value = ran.Next(0, len - 1);
            if (!indexSelection.Contains(value))
            {
                indexSelection.Add(value);
                selection.Add(col[value]);
            }
        }
        return selection.ToArray();
    }

    static IEnumerable<String> GenerateCollection(Int32 count)
    {
        for (int i = 0; i < count; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
        }
    }

    static IEnumerable<String> GenerateCollectionUnsorted(Int32 amount)
    {
        for (int i = 0; i < amount / 2; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
            yield return (amount-i).ToString("X").PadLeft(5, '0');
        }
    }
</code>```

Any idea why is this happening?

EDIT 1: It was my understanding that sorted dictionary would be slower adding items, and faster getting them because the collection is sorted. And also that comparing strings with a OrdinalIgnoreCase or InvariantCultureIgnoreCase should be faster that a normal comparision, so the seek should be faster. But maybe my understanding is completely wrong :D

Thanks in advance.

EDIT 2: As curiosity, I've made some test on String comparisons:

```<code>Collection:             2147482 items.
Random Keys:            1000 keys.

CurrentCulture
        LookUp:         158209ms.

CurrentCultureIgnoreCase
        LookUp:         160710ms.

InvariantCulture
        LookUp:         132765ms.

InvariantCultureIgnoreCase
        LookUp:         133409ms.

Ordinal
        LookUp:         36115ms.

OrdinalIgnoreCase
        LookUp:         36329ms.
</code>```

答:
Because only the normal dictionary with the default comparer is actually a normal dictionary, all the others are sorted dictionaries.

So, the result is very consistent.

Edit:

With that fixed, the result is different. :)

A sorted dictionary is slower when adding items as they need to be sorted, but it's not faster when getting items. Searching the binary tree is fast, but searching the hash list that a regular dictionary uses is faster. When the binary tree grows, there will be more steps to locate each item, while a dictionary mostly grows by adding more buckets so the number of compares is barely affected.

Comparing strings with Ordinal is faster than regular (CurrentCulture) compare, and OrdinalIgnoreCase is faster than CurrentCultureIgnoreCase, but it's not certain that OrdinalIgnoreCase is faster than CurrentCulture. InvariantCulture compare is not faster than a regular compare, it just uses a different culture. The reason that ordinal compare is a lot faster is that it doesn't have to bother with cultural settings at all.

By the way, I noticed an error in the GetRandomKeys method. It will never pick the last item, as you are getting a random number between 0 and Length - 2.

ContentLicense: CC BY-SA 4.0

Body:
I'm doing some benchmark on several string dictionaries, because I wanted to find out how performs the different configurations, and I got surprised that the normal Dictionary<String,String> is the faster. Probably because I'm missing some concept or I'm doing something wrong, but these are the results I got:

Collection:             2147482 items.
Random Keys:            1000 keys.

Normal dictionary
        Add 1000 items:         573ms.
        Get 1000 keys:          0ms.

Normal Dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         642ms.
        Get 1000 keys:          0ms.

Normal Dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         1661ms.
        Get 1000 keys:          0ms.

Sorted dictionary
        Add 1000 items:         11996ms.
        Get 1000 keys:          5ms.

Sorted dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         11097ms.
        Get 1000 keys:          5ms.

Sorted dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         9814ms.
        Get 1000 keys:          5ms.

An this is the code I'm using to test it:

    static void Main(string[] args)
    {
        String[] col = GenerateCollectionUnsorted(Int32.MaxValue / 1000).ToArray();
        Int32 len = col.Length;
        Console.WriteLine("Collection:\t\t" + len.ToString() + " items.");

        String[] randomKeys = GetRandomKeys(col, 1000);
        Console.WriteLine("Random Keys:\t\t" + randomKeys.Length.ToString() + " keys.");

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal dictionary");
        TestDic(col, randomKeys, new Dictionary<String, String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary");
        TestDic(col,randomKeys, new SortedDictionary<String,String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("\nEnd");
        Console.ReadKey(true);
    }

    static void TestDic(String[] col, String[] randomKeys, IDictionary<String,String> dic)
    {
        Stopwatch crono = new Stopwatch();

        crono.Start();
        foreach (String s in col)
            dic.Add(s, s);
        crono.Stop();

        Console.WriteLine("\tAdd "+randomKeys.Length.ToString()+" items:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");

        crono.Reset();
        crono.Start();
        String sv;
        foreach (var rk in randomKeys)
        {
            sv = dic[rk];
            sv.ToString();
        }
        crono.Stop();
        Console.WriteLine("\tGet " + randomKeys.Length.ToString() + " keys:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");
    }

    static String[] GetRandomKeys(String[] col, Int32 count)
    {
        Random ran = new Random(DateTime.Now.Millisecond);

        List<Int32> indexSelection = new List<int>();
        List<String> selection = new List<string>();

        Int32 len = col.Length;

        while (indexSelection.Count < count)
        {
            Int32 value = ran.Next(0, len - 1);
            if (!indexSelection.Contains(value))
            {
                indexSelection.Add(value);
                selection.Add(col[value]);
            }
        }
        return selection.ToArray();
    }

    static IEnumerable<String> GenerateCollection(Int32 count)
    {
        for (int i = 0; i < count; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
        }
    }

    static IEnumerable<String> GenerateCollectionUnsorted(Int32 amount)
    {
        for (int i = 0; i < amount / 2; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
            yield return (amount-i).ToString("X").PadLeft(5, '0');
        }
    }

Any idea why is this happening?

EDIT 1: It was my understanding that sorted dictionary would be slower adding items, and faster getting them because the collection is sorted. And also that comparing strings with a OrdinalIgnoreCase or InvariantCultureIgnoreCase should be faster that a normal comparision, so the seek should be faster. But maybe my understanding is completely wrong :D

Thanks in advance.

EDIT 2: As curiosity, I've made some test on String comparisons:

Collection:             2147482 items.
Random Keys:            1000 keys.

CurrentCulture
        LookUp:         158209ms.

CurrentCultureIgnoreCase
        LookUp:         160710ms.

InvariantCulture
        LookUp:         132765ms.

InvariantCultureIgnoreCase
        LookUp:         133409ms.

Ordinal
        LookUp:         36115ms.

OrdinalIgnoreCase
        LookUp:         36329ms.

ContentLicense: CC BY-SA 2.5


问:
Why do some arrays mirror each other in PowerShell?
I am using PowerShell 2.0. When I make a new variable as an array and then set another variable to be equal to the first one, the second variable "mirrors" the first one.  After changing an object in the original array, the exact same change appears in the second array. For instance,

```<code>$array0001 = 6, 7, 3, 4, 0
$array0002 = $array0001
$array0001[3] = 55
$array0002
</code>```

with the output being

```<code>6
7
3
55
0
</code>```

I notice that when you set the second variable to have the same value as the first variable, except this time enclosed within a subexpression operator, modifications to the first array do not affect the second array. For instance,

```<code>$array0001 = 6, 7, 3, 4, 0
$array0002 = $($array0001)
$array0001[3] = 55
$array0002
</code>```

with the output being

```<code>6
7
3
4
0
</code>```

Why does enclosing the value in a subexpression operator change the behavior of the variable? Is there another or better way to avoid making array variables that "mirror" each other?

ETA: I have now found that $array0002 = @($array0001) and $array0002 = &{$array0001} both accomplish the exact same objective.

答:
When setting one array equal to another like that, the different variables are simply referencing eachother, it's not a true copy.
This  is essentially the same thing that you are asking. From that link, serializing the data to do a deep copy is a good way around it. </p>

```<code>#Original data
$Array1

# Serialize and Deserialize data using BinaryFormatter
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $Array1)
$ms.Position = 0

#Deep copied data
$Array2 = $bf.Deserialize($ms)
$ms.Close()
</code>```

Body:
I am using PowerShell 2.0. When I make a new variable as an array and then set another variable to be equal to the first one, the second variable "mirrors" the first one.  After changing an object in the original array, the exact same change appears in the second array. For instance,

$array0001 = 6, 7, 3, 4, 0
$array0002 = $array0001
$array0001[3] = 55
$array0002

with the output being

6
7
3
55
0

I notice that when you set the second variable to have the same value as the first variable, except this time enclosed within a subexpression operator, modifications to the first array do not affect the second array. For instance,

$array0001 = 6, 7, 3, 4, 0
$array0002 = $($array0001)
$array0001[3] = 55
$array0002

with the output being

6
7
3
4
0

Why does enclosing the value in a subexpression operator change the behavior of the variable? Is there another or better way to avoid making array variables that "mirror" each other?

ETA: I have now found that $array0002 = @($array0001) and $array0002 = &{$array0001} both accomplish the exact same objective.

Body:
When setting one array equal to another like that, the different variables are simply referencing eachother, it's not a true copy.
This  is essentially the same thing that you are asking. From that link, serializing the data to do a deep copy is a good way around it.

#Original data
$Array1

# Serialize and Deserialize data using BinaryFormatter
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $Array1)
$ms.Position = 0

#Deep copied data
$Array2 = $bf.Deserialize($ms)
$ms.Close()


问:
Oracle sql pattern sorting
I have a pattern like this - "pqrst ##ind##123456##ind## hggff 1234". I have to extract numbers between ##ind## and ##ind##. Using pl/sql. Suggest</p>

答:
```<code>SET ESCAPE OFF
DECLARE
    matches VARCHAR2(100) := 'pqrst ##ind##123456##ind## hggff 1234';
    mismatches VARCHAR2(100) := 'pqrst ##id##123456##ind## hggff 1234';
BEGIN
    DBMS_OUTPUT.PUT_LINE('matches:' || REGEXP_REPLACE(matches
            ,'(.*##ind##(.*)##ind##.*)?.*', '\2'));
    DBMS_OUTPUT.PUT_LINE('mismatches:' || REGEXP_REPLACE(mismatches
            ,'(.*##ind##(.*)##ind##.*)?.*', '\2'));
END;
/
matches:123456
mismatches:
PL/SQL procedure successfully completed.
</code>```

Title: Oracle sql pattern sorting


问:
BLOB Storage - 100+ GB, MySQL, SQLite, or PostgreSQL + Python
I have an idea for a simple application which will monitor a group of folders, index any files it finds. A gui will allow me quickly tag new files and move them into a single database for storage and also provide an easy mechanism for querying the db by tag, name, file type and date. At the moment I have about 100+ GB of files on a couple removable hard drives, the database will be at least that big. If possible I would like to support full text search of the embedded binary and text documents. This will be a single user application.

Not trying to start a DB war, but what open source DB is going to work best for me? I am pretty sure SQLLite is off the table but I could be wrong.

答: My preference would be to store the document with the metadata. One reason, is relational integrity. You can't easily move the files or modify the files without the action being brokered by the db. I am sure I can handle these problems but it isn't as clean as I would like and my experience has been that most vendors can handle huge amounts of binary data in the database these days. I guess I was wondering if PostgreSQL or MySQL have any obvious advantages in these areas, I am primarily familiar with Oracle. Anyway, thanks for the response, if the DB knows where the external file is it will also be easy to bring the file in at a later date if I want. Another aspect of the question was if either database is easier to work with when using Python. I'm assuming that is a wash.</p>

OwnerDisplayName: Ethan Post

LastEditorDisplayName: Eddie


问:
CRLF parsing blues in C#
I have the following code:

```<code>  string myTest = "Line1Test" + Environment.NewLine +
                  "Line2Test" + Environment.NewLine +
                  "Line3Test" + Environment.NewLine;
  string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray());
</code>```

What I'm getting is data every other line in the new array.  I think this is because the split line is splitting for both line feeds and carriage returns, but how can I just get one element per line?

答:
```<code>string[] parseStr = myTest.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.None
);
</code>```

Title: CRLF parsing blues in C#

Body:
I have the following code:

  string myTest = "Line1Test" + Environment.NewLine +
                  "Line2Test" + Environment.NewLine +
                  "Line3Test" + Environment.NewLine;
  string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray());

What I'm getting is data every other line in the new array.  I think this is because the split line is splitting for both line feeds and carriage returns, but how can I just get one element per line?


问:
WebSocket connect to TIdHTTPServer, handshake issue
I'm using C++Builder 10.1 Berlin to write a simple WebSocket server application, which listens on a port for some commands sent from a web browser, like Google Chrome.

On my Form, I have a TMemo, TButton and TIdHTTPServer, and I have this code:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
 IdHTTPServer1->Bindings->DefaultPort = 55555;
 IdHTTPServer1->Active = true;
}

void __fastcall TForm1::IdHTTPServer1Connect(TIdContext *AContext)
{

  Memo1->Lines->Add(AContext->Binding->PeerIP);
  Memo1->Lines->Add( AContext->Connection->IOHandler->ReadLn(enUTF8));
  Memo1->Lines->Add( AContext->Data->ToString());

}

void __fastcall TForm5::IdHTTPServer1CommandOther(TIdContext *AContext, TIdHTTPRequestInfo *ARequestInfo,
          TIdHTTPResponseInfo *AResponseInfo)
{

UnicodeString svk,sValue;
TIdHashSHA1 *FHash;
TMemoryStream *strmRequest;

FHash = new TIdHashSHA1;
strmRequest  =  new TMemoryStream;

strmRequest->Position = 0;
svk = ARequestInfo->RawHeaders->Values["Sec-WebSocket-Key"];

Memo1->Lines->Add("Get:"+svk);
      AResponseInfo->ResponseNo         = 101;
      AResponseInfo->ResponseText       = "Switching Protocols";
      AResponseInfo->CloseConnection    = False;
      //Connection: Upgrade
      AResponseInfo->Connection         = "Upgrade";
      //Upgrade: websocket
      AResponseInfo->CustomHeaders->Values["Upgrade"] = "websocket";

      sValue = svk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
      sValue = TIdEncoderMIME::EncodeBytes( FHash->HashString(sValue) );
      AResponseInfo->CustomHeaders->Values["Sec-WebSocket-Accept"] = sValue;
      AResponseInfo->ContentText = "Welcome here!";

      AResponseInfo->WriteHeader();

 UnicodeString URLstr = "http://"+ARequestInfo->Host+ARequestInfo->Document;
      if (ARequestInfo->UnparsedParams != "") URLstr = URLstr+"?"+ARequestInfo->UnparsedParams;
      Memo1->Lines->Add(URLstr);
      Memo1->Lines->Add(ARequestInfo->Command );
      Memo1->Lines->Add("--------");
      Memo1->Lines->Add(ARequestInfo->RawHeaders->Text );
      Memo1->Lines->Add(AContext->Data->ToString() );
}
```

<p>From Chrome, I execute this Javascript code:</p>

```var connection = new WebSocket('ws://localhost:55555');

connection.onopen = function () {
  connection.send('Ping');
};
```

<p>But I get this error from Chrome:</p>

<blockquote>
  <p>VM77:1 WebSocket connection to 'ws://localhost:55555/' failed: One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 0</p>
</blockquote>

<p>I expect the WebSocket connection to be successful, and then I can send data between the web browser and my server application.</p>

<p>Maybe somebody already knows what is wrong and can show a full example of how to achieve this?</p>

<hr>

<p>Here is what my application's Memo1 shows:</p>

```
192.168.0.25
GET / HTTP/1.1
Get:TnBN9qjOJiwka2eJe7mR0A==
http://
HOST:
--------
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://bcbjournal.org
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: TnBN9qjOJiwka2eJe7mR0A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
```

<p>Here is what Chrome shows:</p>

<p><strong>Response Request:</strong></p>

```
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Content-Type: text/html; charset=ISO-8859-1
Content-Length: 13
Date: Thu, 08 Jun 2017 15:04:00 GMT
Upgrade: websocket
Sec-WebSocket-Accept: 2coLmtu++HmyY8PRTNuaR320KPE=
```

<p><strong>Request Headers</strong></p>

```
GET ws://192.168.0.25:55555/ HTTP/1.1
Host: 192.168.0.25:55555
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://bcbjournal.org
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: TnBN9qjOJiwka2eJe7mR0A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
```

答:
You are misusing TIdHTTPServer

You are making two big mistakes:

Your OnConnect event handler is reading the client's initial HTTP request line (the GET line).  It should not be reading anything from the client at all, as doing so interfers with TIdHTTPServer's handling of the HTTP protocol.

After the event handler reads the request line and exits, TIdHTTPServer then reads the next line (the Host header) and interprets that as the request line instead, which is why:

the ARequestInfo->Command property is "HOST:" instead of "GET".

the ARequestInfo->Host, ARequestInfo->Document, ARequestInfo->Version, ARequestInfo->VersionMajor, ARequestInfo->VersionMinor properties are all wrong.

you end up having to use the OnCommandOther event when you should be using the OnCommandGet event instead.

You are accessing the TMemo in your TIdHTTPServer events without synchronizing with the main UI thread.  TIdHTTPServer is a multi-threaded component.  Its events are fired in the context of worker threads.  VCL/FMX UI controls are not thread-safe, so you must synchronize properly with the main UI thread.

You are not implementing the WebSocket protocol correctly

Your server is not validating everything in the handshake that the WebSocket protocol requires a server to validate (which is fine for testing, but make sure you do it for production).

But more importantly, TIdHTTPServer is not well-suited for implementing WebSockets (that is a TODO item).  The only thing about the WebSocket protocol that involves HTTP is the handshake.  After the handshake is finished, everything else is WebSocket framing, not HTTP.  To handle that in TIdHTTPServer requires you to implement the entire WebSocket session inside of the OnCommandGet event, reading and sending all WebSocket frames, preventing the event handler from exiting, until the connection is closed.  For that kind of logic, I would suggest using TIdTCPServer directly instead, and just handle the HTTP handshake manually at the beginning of its OnExecute event, and then loop the rest of the event handling the WebSocket frames.

Your OnCommandOther event handler is not currently performing any WebSocket I/O after the handshake is finished.  It is returning control to TIdHTTPServer, which will then attempt to read a new HTTP request.  As soon as the client sends a WebSocket frame to the server, TIdHTTPServer will fail to process it since it is not HTTP, and will likely send an HTTP response back to the client, which will get misinterpreted, causing the client to fail the WebSocket session and close the socket connection.

With that said, try something more like this instead:

```<code>#include ...
#include <IdSync.hpp>

class TLogNotify : public TIdNotify
{
protected:
    String FMsg;

    void __fastcall DoNotify()
    {
        Form1->Memo1->Lines->Add(FMsg);
    }

public:
    __fastcall TLogNotify(const String &S) : TIdNotify(), FMsg(S) {}
};

__fastcall TForm1::TForm1(TComponent *Owner)
    : TForm(Owner)
{
    IdHTTPServer1->DefaultPort = 55555;
}

void __fastcall TForm1::Log(const String &S)
{
    (new TLogNotify(S))->Notify();
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    IdHTTPServer1->Active = true;
}

void __fastcall TForm1::IdHTTPServer1Connect(TIdContext *AContext)
{
    Log(_D("Connected: ") + AContext->Binding->PeerIP);
}

void __fastcall TForm1::IdHTTPServer1Disconnect(TIdContext *AContext)
{
    Log(_D("Disconnected: ") + AContext->Binding->PeerIP);
}

void __fastcall TForm5::IdHTTPServer1CommandGet(TIdContext *AContext, TIdHTTPRequestInfo *ARequestInfo, TIdHTTPResponseInfo *AResponseInfo)
{
    Log(ARequestInfo->RawHTTPCommand);

    if (ARequestInfo->Document != _D("/"))
    {
        AResponseInfo->ResponseNo = 404;
        return;
    }

    if ( !(ARequestInfo->IsVersionAtLeast(1, 1) &&
          TextIsSame(ARequestInfo->RawHeaders->Values[_D("Upgrade")], _D("websocket")) &&
          TextIsSame(ARequestInfo->Connection, _D("Upgrade")) ) )
    {
        AResponseInfo->ResponseNo         = 426;
        AResponseInfo->ResponseText       = _D("upgrade required");
        return;
    }

    String svk = ARequestInfo->RawHeaders->Values[_D("Sec-WebSocket-Key")];

    if ( (ARequestInfo->RawHeaders->Values[_D("Sec-WebSocket-Version")] != _D("13")) ||
          svk.IsEmpty() )
    {
        AResponseInfo->ResponseNo = 400;
        return;
    }

    // validate Origin, Sec-WebSocket-Protocol, and Sec-WebSocket-Extensions as needed...

    Log(_D("Get:") + svk);

    AResponseInfo->ResponseNo         = 101;
    AResponseInfo->ResponseText       = _D("Switching Protocols");
    AResponseInfo->CloseConnection    = false;
    AResponseInfo->Connection         = _D("Upgrade");
    AResponseInfo->CustomHeaders->Values[_D("Upgrade")] = _D("websocket");

    TIdHashSHA1 *FHash = new TIdHashSHA1;
    try {
        String sValue = svk + _D("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
        sValue = TIdEncoderMIME::EncodeBytes( FHash->HashString(sValue) );
        AResponseInfo->CustomHeaders->Values[_D("Sec-WebSocket-Accept")] = sValue;
    }
    __finally {
        delete FHash;
    }

    AResponseInfo->WriteHeader();

    String URLstr = _D("http://") + ARequestInfo->Host + ARequestInfo->Document;
    if (!ARequestInfo->UnparsedParams.IsEmpty()) URLstr = URLstr + _D("?") + ARequestInfo->UnparsedParams;
    Log(URLstr);
    Log(_D("--------"));
    Log(ARequestInfo->RawHeaders->Text);

    // now send/receive WebSocket frames here as needed,
    // using AContext->Connection->IOHandler directly...
}
</code>```

That being said, there are plenty of 3rd party WebSocket libraries available. You should use one of them instead of implementing WebSockets manually.  Some libraries even build on top of Indy.

Body:
I'm using C++Builder 10.1 Berlin to write a simple WebSocket server application, which listens on a port for some commands sent from a web browser, like Google Chrome.

On my Form, I have a TMemo, TButton and TIdHTTPServer, and I have this code:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
 IdHTTPServer1->Bindings->DefaultPort = 55555;
 IdHTTPServer1->Active = true;
}

void __fastcall TForm1::IdHTTPServer1Connect(TIdContext *AContext)
{

  Memo1->Lines->Add(AContext->Binding->PeerIP);
  Memo1->Lines->Add( AContext->Connection->IOHandler->ReadLn(enUTF8));
  Memo1->Lines->Add( AContext->Data->ToString());

}

void __fastcall TForm5::IdHTTPServer1CommandOther(TIdContext *AContext, TIdHTTPRequestInfo *ARequestInfo,
          TIdHTTPResponseInfo *AResponseInfo)
{

UnicodeString svk,sValue;
TIdHashSHA1 *FHash;
TMemoryStream *strmRequest;

FHash = new TIdHashSHA1;
strmRequest  =  new TMemoryStream;

strmRequest->Position = 0;
svk = ARequestInfo->RawHeaders->Values["Sec-WebSocket-Key"];

Memo1->Lines->Add("Get:"+svk);
      AResponseInfo->ResponseNo         = 101;
      AResponseInfo->ResponseText       = "Switching Protocols";
      AResponseInfo->CloseConnection    = False;
      //Connection: Upgrade
      AResponseInfo->Connection         = "Upgrade";
      //Upgrade: websocket
      AResponseInfo->CustomHeaders->Values["Upgrade"] = "websocket";

      sValue = svk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
      sValue = TIdEncoderMIME::EncodeBytes( FHash->HashString(sValue) );
      AResponseInfo->CustomHeaders->Values["Sec-WebSocket-Accept"] = sValue;
      AResponseInfo->ContentText = "Welcome here!";

      AResponseInfo->WriteHeader();

 UnicodeString URLstr = "http://"+ARequestInfo->Host+ARequestInfo->Document;
      if (ARequestInfo->UnparsedParams != "") URLstr = URLstr+"?"+ARequestInfo->UnparsedParams;
      Memo1->Lines->Add(URLstr);
      Memo1->Lines->Add(ARequestInfo->Command );
      Memo1->Lines->Add("--------");
      Memo1->Lines->Add(ARequestInfo->RawHeaders->Text );
      Memo1->Lines->Add(AContext->Data->ToString() );
}

From Chrome, I execute this Javascript code:

var connection = new WebSocket('ws://localhost:55555');

connection.onopen = function () {
  connection.send('Ping');
};

But I get this error from Chrome:

VM77:1 WebSocket connection to 'ws://localhost:55555/' failed: One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 0

I expect the WebSocket connection to be successful, and then I can send data between the web browser and my server application.

Maybe somebody already knows what is wrong and can show a full example of how to achieve this?

Here is what my application's Memo1 shows:

192.168.0.25
GET / HTTP/1.1
Get:TnBN9qjOJiwka2eJe7mR0A==
http://
HOST:
--------
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://bcbjournal.org
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: TnBN9qjOJiwka2eJe7mR0A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

Here is what Chrome shows:

Response Request:

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Content-Type: text/html; charset=ISO-8859-1
Content-Length: 13
Date: Thu, 08 Jun 2017 15:04:00 GMT
Upgrade: websocket
Sec-WebSocket-Accept: 2coLmtu++HmyY8PRTNuaR320KPE=

Request Headers

GET ws://192.168.0.25:55555/ HTTP/1.1
Host: 192.168.0.25:55555
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://bcbjournal.org
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: TnBN9qjOJiwka2eJe7mR0A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

Body:
You are misusing TIdHTTPServer

You are making two big mistakes:

Your OnConnect event handler is reading the client's initial HTTP request line (the GET line).  It should not be reading anything from the client at all, as doing so interfers with TIdHTTPServer's handling of the HTTP protocol.

After the event handler reads the request line and exits, TIdHTTPServer then reads the next line (the Host header) and interprets that as the request line instead, which is why:

the ARequestInfo->Command property is "HOST:" instead of "GET".

the ARequestInfo->Host, ARequestInfo->Document, ARequestInfo->Version, ARequestInfo->VersionMajor, ARequestInfo->VersionMinor properties are all wrong.

you end up having to use the OnCommandOther event when you should be using the OnCommandGet event instead.

You are accessing the TMemo in your TIdHTTPServer events without synchronizing with the main UI thread.  TIdHTTPServer is a multi-threaded component.  Its events are fired in the context of worker threads.  VCL/FMX UI controls are not thread-safe, so you must synchronize properly with the main UI thread.

You are not implementing the WebSocket protocol correctly

Your server is not validating everything in the handshake that the WebSocket protocol requires a server to validate (which is fine for testing, but make sure you do it for production).

But more importantly, TIdHTTPServer is not well-suited for implementing WebSockets (that is a TODO item).  The only thing about the WebSocket protocol that involves HTTP is the handshake.  After the handshake is finished, everything else is WebSocket framing, not HTTP.  To handle that in TIdHTTPServer requires you to implement the entire WebSocket session inside of the OnCommandGet event, reading and sending all WebSocket frames, preventing the event handler from exiting, until the connection is closed.  For that kind of logic, I would suggest using TIdTCPServer directly instead, and just handle the HTTP handshake manually at the beginning of its OnExecute event, and then loop the rest of the event handling the WebSocket frames.

Your OnCommandOther event handler is not currently performing any WebSocket I/O after the handshake is finished.  It is returning control to TIdHTTPServer, which will then attempt to read a new HTTP request.  As soon as the client sends a WebSocket frame to the server, TIdHTTPServer will fail to process it since it is not HTTP, and will likely send an HTTP response back to the client, which will get misinterpreted, causing the client to fail the WebSocket session and close the socket connection.

With that said, try something more like this instead:

#include ...
#include <IdSync.hpp>

class TLogNotify : public TIdNotify
{
protected:
    String FMsg;

    void __fastcall DoNotify()
    {
        Form1->Memo1->Lines->Add(FMsg);
    }

public:
    __fastcall TLogNotify(const String &S) : TIdNotify(), FMsg(S) {}
};

__fastcall TForm1::TForm1(TComponent *Owner)
    : TForm(Owner)
{
    IdHTTPServer1->DefaultPort = 55555;
}

void __fastcall TForm1::Log(const String &S)
{
    (new TLogNotify(S))->Notify();
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    IdHTTPServer1->Active = true;
}

void __fastcall TForm1::IdHTTPServer1Connect(TIdContext *AContext)
{
    Log(_D("Connected: ") + AContext->Binding->PeerIP);
}

void __fastcall TForm1::IdHTTPServer1Disconnect(TIdContext *AContext)
{
    Log(_D("Disconnected: ") + AContext->Binding->PeerIP);
}

void __fastcall TForm5::IdHTTPServer1CommandGet(TIdContext *AContext, TIdHTTPRequestInfo *ARequestInfo, TIdHTTPResponseInfo *AResponseInfo)
{
    Log(ARequestInfo->RawHTTPCommand);

    if (ARequestInfo->Document != _D("/"))
    {
        AResponseInfo->ResponseNo = 404;
        return;
    }

    if ( !(ARequestInfo->IsVersionAtLeast(1, 1) &&
          TextIsSame(ARequestInfo->RawHeaders->Values[_D("Upgrade")], _D("websocket")) &&
          TextIsSame(ARequestInfo->Connection, _D("Upgrade")) ) )
    {
        AResponseInfo->ResponseNo         = 426;
        AResponseInfo->ResponseText       = _D("upgrade required");
        return;
    }

    String svk = ARequestInfo->RawHeaders->Values[_D("Sec-WebSocket-Key")];

    if ( (ARequestInfo->RawHeaders->Values[_D("Sec-WebSocket-Version")] != _D("13")) ||
          svk.IsEmpty() )
    {
        AResponseInfo->ResponseNo = 400;
        return;
    }

    // validate Origin, Sec-WebSocket-Protocol, and Sec-WebSocket-Extensions as needed...

    Log(_D("Get:") + svk);

    AResponseInfo->ResponseNo         = 101;
    AResponseInfo->ResponseText       = _D("Switching Protocols");
    AResponseInfo->CloseConnection    = false;
    AResponseInfo->Connection         = _D("Upgrade");
    AResponseInfo->CustomHeaders->Values[_D("Upgrade")] = _D("websocket");

    TIdHashSHA1 *FHash = new TIdHashSHA1;
    try {
        String sValue = svk + _D("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
        sValue = TIdEncoderMIME::EncodeBytes( FHash->HashString(sValue) );
        AResponseInfo->CustomHeaders->Values[_D("Sec-WebSocket-Accept")] = sValue;
    }
    __finally {
        delete FHash;
    }

    AResponseInfo->WriteHeader();

    String URLstr = _D("http://") + ARequestInfo->Host + ARequestInfo->Document;
    if (!ARequestInfo->UnparsedParams.IsEmpty()) URLstr = URLstr + _D("?") + ARequestInfo->UnparsedParams;
    Log(URLstr);
    Log(_D("--------"));
    Log(ARequestInfo->RawHeaders->Text);

    // now send/receive WebSocket frames here as needed,
    // using AContext->Connection->IOHandler directly...
}

That being said, there are plenty of 3rd party WebSocket libraries available. You should use one of them instead of implementing WebSockets manually.  Some libraries even build on top of Indy.


问:
Wrong date display in Google Script
My code displays a wrong date compared to the given parameters and i don't understand why ...

```<code>timezone = "Europe/Paris";
date = new Date(2017,11,31,15,01,0,0);
Logger.log(Utilities.formatDate(date, timezone, 'YYYY-MM-dd HH:mm'));
</code>```

The result is:

[17-06-08 13:51:38:726 PDT] 2018-12-31 15:01

and should be:

[17-06-08 13:51:38:726 PDT] 2017-12-31 15:01

答:
For reasons I cannot explain this seems to happen because you defined YYYY in capitals. Tried this in scripts:

```<code>  var timezone = "Europe/Paris";
  var date = new Date(2017,11,31,15,01,0,0);
  Logger.log(Utilities.formatDate(date, timezone, 'yyyy-MM-dd HH:mm'));
</code>```

And outputs:

[17-06-08 23:01:26:459 CEST] 2017-12-31 15:01

Title: Wrong date display in Google Script

Body:
My code displays a wrong date compared to the given parameters and i don't understand why ...

timezone = "Europe/Paris";
date = new Date(2017,11,31,15,01,0,0);
Logger.log(Utilities.formatDate(date, timezone, 'YYYY-MM-dd HH:mm'));

The result is:

[17-06-08 13:51:38:726 PDT] 2018-12-31 15:01

and should be:

[17-06-08 13:51:38:726 PDT] 2017-12-31 15:01

Body:
For reasons I cannot explain this seems to happen because you defined YYYY in capitals. Tried this in scripts:

  var timezone = "Europe/Paris";
  var date = new Date(2017,11,31,15,01,0,0);
  Logger.log(Utilities.formatDate(date, timezone, 'yyyy-MM-dd HH:mm'));

And outputs:

[17-06-08 23:01:26:459 CEST] 2017-12-31 15:01


问:
Stop a tkinter function that has a "return"
My code is currently graphing and writing text files of the graph data.  I want it to stop doing this.  Instead of stopping, it just starts the process over.  I've tried several things (stopping get_data function, stopping update_graph function, having a separate stop function).  What am I missing?

```<code>def on_click(self):

    if self.ani is None:
        # animation is not running; start it
        return self.start()

def start(self):
    self.points = int(tkvar.get()) + 1
    self.ani = animation.FuncAnimation(
        self.fig,
        self.update_graph,
        frames=self.points,
        interval=int(self.interval.get()),
        repeat=True)
    self.running = True
    self.btn.config(text='Started')
    self.ani._start()
    print('started animation')

def get_data(self, i):
    files = tkvar.get()
    global after_id
    global filenumber
    global tkvars
    filenumber = int(files)

    inttime = tkvars.get()
    thetime = inttime.encode()
    ser.write(thetime)
    f = open("Serial" + str(i) + ".txt", 'w+')#encoding='utf-8')
    #f = open("serial%d.txt") % (i)
    data=ser.readline() #read the defined serial import
    f.write(str(data)) #place data into the text file
    f.close() #close the text file

    lines = open("Serial" + str(i) + ".txt", 'r+')#, encoding='utf-8')  #open that same text file (reading priviledges)

    read_serial=lines.readline() #read the text file
    global mylist
    mylist = [int(x) for x in read_serial.split(',') if x.strip().isdigit()] #make the read data an interger and strip it of any data that is not a number (comma, ending/beginning letters)
    global x
    x = np.linspace(340, 850, num=len(mylist)) #creation of x axis
    ax1.clear()
    lines.close() #close the text file
    ax1.plot(x, mylist)
    plt.ylim([0, 1000])
    print(filenumber)
    print(i)
    return i
    if True:
        self.after_id = self.after(1, self.get_data, i+1)

def update_graph(self, i):
    self.get_data(i)
    global mylist
    global x
    global filenumber
    self.line.set_data(x, mylist)#(self.get_data()) # update graph
    if i >= self.points + 1:
        #root.update()
        self.btn.config(text='Start')
        self.stop()
        self.running = False
        self.ani = None
    return self.line,

def stop(self):
    self.after_cancel(self.after_id)
</code>```

答:
I do not know if this is the only problem, but it is certainly part of the problem. This code does not do what you think it does:

```<code>self.after(0, self.get_data(i+1))
</code>```

The above is identical to the following:

```<code>result = self.get_data(i+1)
self.after(0, result)
</code>```

... which for all intents and purposes the same as this:

```<code>result = self.get_data(i+1)
result()
</code>```

When you call after, you must give it a callable. Also, you shouldn't give a value of zero because under some conditions you will prevent the event loop from being able to process events such as requests to refresh the display. You should at the very least give a value of 1, and preferably something a bit bigger.

The proper way to use after to call a function with an argument is like this:

```<code>self.after(1, self.get_data, i+1)
</code>```

I presume you also intended to be able to cancel the call to self.get_data, so you need to do this:

```<code>self.after_id = self.after(1, self.get_data, i+1)
</code>```

... and then modify stop to be this:

```<code>def stop(self):
    self.after_cancel(self.after_id)
</code>```

Body:
My code is currently graphing and writing text files of the graph data.  I want it to stop doing this.  Instead of stopping, it just starts the process over.  I've tried several things (stopping get_data function, stopping update_graph function, having a separate stop function).  What am I missing?

def on_click(self):

    if self.ani is None:
        # animation is not running; start it
        return self.start()

def start(self):
    self.points = int(tkvar.get()) + 1
    self.ani = animation.FuncAnimation(
        self.fig,
        self.update_graph,
        frames=self.points,
        interval=int(self.interval.get()),
        repeat=True)
    self.running = True
    self.btn.config(text='Started')
    self.ani._start()
    print('started animation')

def get_data(self, i):
    files = tkvar.get()
    global after_id
    global filenumber
    global tkvars
    filenumber = int(files)

    inttime = tkvars.get()
    thetime = inttime.encode()
    ser.write(thetime)
    f = open("Serial" + str(i) + ".txt", 'w+')#encoding='utf-8')
    #f = open("serial%d.txt") % (i)
    data=ser.readline() #read the defined serial import
    f.write(str(data)) #place data into the text file
    f.close() #close the text file

    lines = open("Serial" + str(i) + ".txt", 'r+')#, encoding='utf-8')  #open that same text file (reading priviledges)

    read_serial=lines.readline() #read the text file
    global mylist
    mylist = [int(x) for x in read_serial.split(',') if x.strip().isdigit()] #make the read data an interger and strip it of any data that is not a number (comma, ending/beginning letters)
    global x
    x = np.linspace(340, 850, num=len(mylist)) #creation of x axis
    ax1.clear()
    lines.close() #close the text file
    ax1.plot(x, mylist)
    plt.ylim([0, 1000])
    print(filenumber)
    print(i)
    return i
    if True:
        self.after_id = self.after(1, self.get_data, i+1)

def update_graph(self, i):
    self.get_data(i)
    global mylist
    global x
    global filenumber
    self.line.set_data(x, mylist)#(self.get_data()) # update graph
    if i >= self.points + 1:
        #root.update()
        self.btn.config(text='Start')
        self.stop()
        self.running = False
        self.ani = None
    return self.line,

def stop(self):
    self.after_cancel(self.after_id)

Body:
I do not know if this is the only problem, but it is certainly part of the problem. This code does not do what you think it does:

self.after(0, self.get_data(i+1))

The above is identical to the following:

result = self.get_data(i+1)
self.after(0, result)

... which for all intents and purposes the same as this:

result = self.get_data(i+1)
result()

When you call after, you must give it a callable. Also, you shouldn't give a value of zero because under some conditions you will prevent the event loop from being able to process events such as requests to refresh the display. You should at the very least give a value of 1, and preferably something a bit bigger.

The proper way to use after to call a function with an argument is like this:

self.after(1, self.get_data, i+1)

I presume you also intended to be able to cancel the call to self.get_data, so you need to do this:

self.after_id = self.after(1, self.get_data, i+1)

... and then modify stop to be this:

def stop(self):
    self.after_cancel(self.after_id)


问:
Find Missing Records From Table A For Table B Where They Don't Exist in Table C
I have 3 tables:

```<code>Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)
</code>```

Some Customer records have some CustomerEvent records with an EventType, some Customer records have no CustomerEvent records.

How do I identify/insert missing CustomerEvent records of each EventType for each Customer record?

My actual issue is a bit more detailed than that, however, this is the piece I'm struggling with.

Can I use one select statement to identify all missing CustomerEvent records? Or would I need to UNION on each EventType record?

答:
Using cross join to generate a set of all CustomerId, EventTypeId and filtering out those that exist in CustomerEvent with not exists()

```<code>select c.CustomerId, e.EventTypeId
from Customer c
  cross join EventType e
where not exists (
  select 1
  from CustomerEvent ce
  where c.CustomerId = ce.CustomerId
    and e.EventTypeId = ce.EventTypeId
    )
</code>```

Body:
I have 3 tables:

Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)

Some Customer records have some CustomerEvent records with an EventType, some Customer records have no CustomerEvent records.

How do I identify/insert missing CustomerEvent records of each EventType for each Customer record?

My actual issue is a bit more detailed than that, however, this is the piece I'm struggling with.

Can I use one select statement to identify all missing CustomerEvent records? Or would I need to UNION on each EventType record?

Body:
Using cross join to generate a set of all CustomerId, EventTypeId and filtering out those that exist in CustomerEvent with not exists()

select c.CustomerId, e.EventTypeId
from Customer c
  cross join EventType e
where not exists (
  select 1
  from CustomerEvent ce
  where c.CustomerId = ce.CustomerId
    and e.EventTypeId = ce.EventTypeId
    )


问:
WSO2 Identity Server 5.0.0 Api for session management
Does WSO2 Identity Server has api for session management?

I have an app with SAML SSO.
What I would like to achieve is to check if for given saml token there is an active session.

答: Seems like it does, you should investigate the documentation here and here, those links were provided by a WSO2 team member to me or ask directly to your local  WSO2 office.</p>


问:
Relative path for Folder.Files
I have an Excel file, and in the same folder I have a folder with CSV files I want to include. Using the From Folder query thing, the first step will give the following query:

```<code>= Folder.Files("D:\OneDrive\Documents\Health\Concept2")
</code>```

Now, this path will not be the same on my laptop for example, but the Excel file will always be in the Health directory...

I get an error if I try to just pass a relative path to Folder.Files, but is there a way to work around this? A fancy function? Some variable or thing I don't know about because I'm a total newb in this area?

Attempt 1

```<code>= Folder.Files(".\Concept2")
= Folder.Files("Concept2")
</code>```

❌DataFormat.Error: The supplied folder path must be a valid absolute path.

Attempt 2

```<code>= Folder.Files(Activeworkbook.Path & "\Concept2")
</code>```

❌ Expression.Error: The name 'Activeworkbook.Path' wasn't recognized.  Make sure it's spelled correctly.

Title: Relative path for Folder.Files

Body:
I have an Excel file, and in the same folder I have a folder with CSV files I want to include. Using the From Folder query thing, the first step will give the following query:

= Folder.Files("D:\OneDrive\Documents\Health\Concept2")

Now, this path will not be the same on my laptop for example, but the Excel file will always be in the Health directory...

I get an error if I try to just pass a relative path to Folder.Files, but is there a way to work around this? A fancy function? Some variable or thing I don't know about because I'm a total newb in this area?

Attempt 1

= Folder.Files(".\Concept2")
= Folder.Files("Concept2")

❌DataFormat.Error: The supplied folder path must be a valid absolute path.

Attempt 2

= Folder.Files(Activeworkbook.Path & "\Concept2")

❌ Expression.Error: The name 'Activeworkbook.Path' wasn't recognized.  Make sure it's spelled correctly.


问:
Rails 5 - Strong Parameters for Nested Attributes on Associated Objects
I am trying to create a nested attribute form for my Request model.

My parameters are not saving correctly when the Create action is triggered. Though in my console, the data is structured correctly for how I want it to be entered.

The :quantity attribute is on the JoinTable model of RequestDrink.

How can I white-list these parameters correctly?

Console Output

```<code>Started POST "/requests" for 127.0.0.1 at 2017-06-08 12:38:40 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"3ljcH44E7ZrEXNztlgGacyA0nyumNsTX6NyMMu9N+3SY0rCRXSsj/hsg0JP8jtVfDFkcEWOWHi/VwHrgertlLg==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "event_date_id"=>"1", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"16", "arrival_time(5i)"=>"38", "drinks_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}],  "commit"=>"Submit"}
Completed 404 Not Found in 18ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Drink with ID=1 for Request with ID=):

app/controllers/requests_controller.rb:34:in `create'
</code>```

app/models/request.rb

```<code>class Request < ApplicationRecord
    has_many :request_drinks
    has_many :drinks, through: :request_drinks

    accepts_nested_attributes_for :drinks
end
</code>```

app/models/drinks.rb

```<code>class Drink < ApplicationRecord
    has_many :request_drinks
    has_many :requests, through: :request_drinks
end
</code>```

app/models/request_drink.rb

```<code>class RequestDrink < ApplicationRecord
    belongs_to :request
    belongs_to :drink
end
</code>```

app/controllers/request_controller.rb

```<code>class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  def index
    redirect_to root_path unless admin_signed_in?
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active
  end

  def edit
  end

  def create
    @request = Request.new(request_params)
    @request.people = (@request.males || 0) + (@request.females || 0)

    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :event_date_id,
                                      :drinks_attributes => [:id, :quantity]
      )
    end
end
</code>```

app/views/requests/_form.html.erb

```<code><%= form_with(model: request, local: true) do |f| %>
...
      <h4>Drinks</h4>
      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>
        <%= number_field_tag "request[drinks_attributes][][quantity]", 0, in: 0..10 %>
        <%= d.name %>
        <br />
      <% end %>
...
<% end %>
</code>```

答:
Thank you, this worked as well as tweaking my parameters a little more. This is the completed code

app/models/request.rb

```<code>class Request < ApplicationRecord
   has_many :request_drinks
   has_many :drinks, through: :requests

   accepts_nested_attributes_for :request_drinks
end
</code>```

app/controllers/request_controller.rb

```<code>class RequestController < ApplicationRecord
...
    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :is_deleted,
                                      :approved,
                                      :attended,
                                      :event_date_id,
                                      :request_drinks_attributes => [:request_id, :drink_id, :quantity]
                                      :table_location_ids => []
      )
    end
end
</code>```

app/views/requests/_form.html.erb

```<code>...
<h4>Drinks</h4>
      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[request_drinks_attributes][][request_id]", request.id %>
        <%= hidden_field_tag "request[request_drinks_attributes][][drink_id]", d.id %>
        <%= number_field_tag "request[request_drinks_attributes][][quantity]", 0, in: 0..10 %>
        <%= d.name %>
        <br />
      <% end %>
</code>```

Body:
I am trying to create a nested attribute form for my Request model.

My parameters are not saving correctly when the Create action is triggered. Though in my console, the data is structured correctly for how I want it to be entered.

The :quantity attribute is on the JoinTable model of RequestDrink.

How can I white-list these parameters correctly?

Console Output

Started POST "/requests" for 127.0.0.1 at 2017-06-08 12:38:40 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"3ljcH44E7ZrEXNztlgGacyA0nyumNsTX6NyMMu9N+3SY0rCRXSsj/hsg0JP8jtVfDFkcEWOWHi/VwHrgertlLg==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "event_date_id"=>"1", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"16", "arrival_time(5i)"=>"38", "drinks_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}],  "commit"=>"Submit"}
Completed 404 Not Found in 18ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Drink with ID=1 for Request with ID=):

app/controllers/requests_controller.rb:34:in `create'

app/models/request.rb

class Request < ApplicationRecord
    has_many :request_drinks
    has_many :drinks, through: :request_drinks

    accepts_nested_attributes_for :drinks
end

app/models/drinks.rb

class Drink < ApplicationRecord
    has_many :request_drinks
    has_many :requests, through: :request_drinks
end

app/models/request_drink.rb

class RequestDrink < ApplicationRecord
    belongs_to :request
    belongs_to :drink
end

app/controllers/request_controller.rb

class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  def index
    redirect_to root_path unless admin_signed_in?
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active
  end

  def edit
  end

  def create
    @request = Request.new(request_params)
    @request.people = (@request.males || 0) + (@request.females || 0)

    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :event_date_id,
                                      :drinks_attributes => [:id, :quantity]
      )
    end
end

app/views/requests/_form.html.erb

<%= form_with(model: request, local: true) do |f| %>
...

Drinks

      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>
        <%= number_field_tag "request[drinks_attributes][][quantity]", 0, in: 0..10 %>
        <%= d.name %>

      <% end %>
...
<% end %>

Body:
Thank you, this worked as well as tweaking my parameters a little more. This is the completed code

app/models/request.rb

class Request < ApplicationRecord
   has_many :request_drinks
   has_many :drinks, through: :requests

   accepts_nested_attributes_for :request_drinks
end

app/controllers/request_controller.rb

class RequestController < ApplicationRecord
...
    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :is_deleted,
                                      :approved,
                                      :attended,
                                      :event_date_id,
                                      :request_drinks_attributes => [:request_id, :drink_id, :quantity]
                                      :table_location_ids => []
      )
    end
end

app/views/requests/_form.html.erb

...
<h4>Drinks</h4>
      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[request_drinks_attributes][][request_id]", request.id %>
        <%= hidden_field_tag "request[request_drinks_attributes][][drink_id]", d.id %>
        <%= number_field_tag "request[request_drinks_attributes][][quantity]", 0, in: 0..10 %>
        <%= d.name %>
        <br />
      <% end %>


问:
How to pass form-data of body tag of URL using volley
How can I pass the data to form-data of body tag of URL in Volley ? here I show you screen shot which I tried with multiple request but not worked.

please help me.

答:
Use getParams method to add body parameters to volley request

```<code>@Override
protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> params = new HashMap<>();
// the POST Body parameters:
if (pack.getParams() != null && pack.getParams().size() > 0) {
    params = pack.getParams();
    return params;
}
return super.getParams();
</code>```

}

Pack is wrapper class that contains address, bodyparams, passwords and more.

Create a Map<String, String> and put your body parameters inside it.

Body:
Use getParams method to add body parameters to volley request

@Override
protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> params = new HashMap<>();
// the POST Body parameters:
if (pack.getParams() != null && pack.getParams().size() > 0) {
    params = pack.getParams();
    return params;
}
return super.getParams();

}

Pack is wrapper class that contains address, bodyparams, passwords and more.

Create a Map<String, String> and put your body parameters inside it.


问:
A dotfile that will set the default node version on a project using nvm?
In ruby when using rbenv you can make a .ruby-version file and put it in the local directory. https://gist.github.com/fnichol/1912050
I'm looking for something similar to this using NVM?

Question:

Is there a property to set in package.json or a file to create that will set the default version of node of a project?

答:
There is now some native support for this built into direnv's stdlib. It's documented in their wiki, but the source is just as easy to read, or type direnv stdlib to find it).

```<code>$ node -v
v8.0.0
$ cat .node-version
4.3.2
$ cat .envrc
use node
$ export NODE_VERSIONS=~/.nvm/versions/node
$ export NODE_VERSION_PREFIX=v
$ direnv allow
direnv: loading ~/.config/direnv/direnvrc
direnv: loading .envrc
direnv: using node
direnv: Successfully loaded NodeJS v4.3.2 (via .node-version), from prefix (~/.nvm/versions/node/v4.3.2)
direnv: export +CPATH +LD_LIBRARY_PATH +LIBRARY_PATH +PKG_CONFIG_PATH ~MANPATH ~PATH
$ node -v
v4.3.2
$ direnv deny
direnv: error .envrc is blocked. Run `direnv allow` to approve its content.
$ node -v
v8.0.0
</code>```

If you want node_modules/.bin in your path, just add the line layout node to your .envrc (the source is also in direnv stdlib output).

Body:
There is now some native support for this built into direnv's stdlib. It's documented in their wiki, but the source is just as easy to read, or type direnv stdlib to find it).

$ node -v
v8.0.0
$ cat .node-version
4.3.2
$ cat .envrc
use node
$ export NODE_VERSIONS=~/.nvm/versions/node
$ export NODE_VERSION_PREFIX=v
$ direnv allow
direnv: loading ~/.config/direnv/direnvrc
direnv: loading .envrc
direnv: using node
direnv: Successfully loaded NodeJS v4.3.2 (via .node-version), from prefix (~/.nvm/versions/node/v4.3.2)
direnv: export +CPATH +LD_LIBRARY_PATH +LIBRARY_PATH +PKG_CONFIG_PATH ~MANPATH ~PATH
$ node -v
v4.3.2
$ direnv deny
direnv: error .envrc is blocked. Run `direnv allow` to approve its content.
$ node -v
v8.0.0

If you want node_modules/.bin in your path, just add the line layout node to your .envrc (the source is also in direnv stdlib output).


问:
Errors attempting to add a web reference
I have a link http://xxx.yyy.net/zzz/OpacAccess?wsdl that opens in IE and shows the methods of web service correctly.

However, I have a console application where I'm trying to add a web reference but I'm not able to get it working.  I right-click the project and click "Add service reference..."  From here, I click "Advanced..." and from there I click "Add Web Reference...".  When I enter the URL here, it shows me the methods correctly, but I'm unable to add the reference (the button is greyed-out) and the following error is shown:

There was an error downloading 'http://xxx.yyy.net/zzz/OpacAccess?wsdl'.  Unable to connect to the remote server.  No connection could be made because the target machine actively refused it 127.0.0.1:80.

If I use the visual studio command-line with the following command,
wsdl http://xxx.yyy.net/zzz/OpacAccess?wsdl
, I get "There was an error processing http://xxx.yyy.net/zzz/OpacAccess?wsdl", followed by the above errors.

Thanks very much in advance for any assistance you could provide.

答:
In general, when you can access something through the browser, but not through another program you believe should work like the browser, then the problem is that the other program is not, in fact, behaving like the browser does.

The most common reason for this is proxy settings. The browser will usually  have them set (perhaps automatically through Group Policy or the equivalent), and your other program will not.


问:
Issue on ngOptions track by
I have some issue with AngularJs option/selector which I uses ngOptions to create. The problem I have is that it doesn't trigger the method I have in ngChange. I found out that's because in actionList the name property isn't unique. So if I change so they are unique it will works as intended. However I want them to be named like how it is now.

So I guess I could try something like ng-options="action.name for action in ctrl.actionList track by action.value". But it doesn't work. Anyone who can help me out here?

HTML

```<code><select id="someOptions" class="dropdown dropdown-md"
    ng-model="ctrl.settingAction"
    ng-change="ctrl.onChangeAction()"
    ng-options="action.name for action in ctrl.actionList">
</select>
</code>```

Data structure

```<code>actionList = [{
    name: "Running Man"
    value: "RUN"
}, {
    name: "Running Man"
    value: "JUMP"
}]
</code>```

JS

```<code>public onChangeAction(): void {
    console.log(this.settingAction);
}
</code>```

答:
DEMO

angular.module('myApp',[]).controller('myCtrl', function($scope){
 var ctrl = this;
 this.actionList =[{
    "name": "Running Man",
    "value": "RUN"
}, {
    "name": "Running Man",
    "value": "JUMP"
}];

this.onChangeAction = function(){
 alert(this.settingAction.value);
}

 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
 <select id="someOptions" class="dropdown dropdown-md"
    ng-model="ctrl.settingAction"
    ng-change="ctrl.onChangeAction()"
    ng-options="action.name for action in ctrl.actionList">
</select>
</div></code>```

Title: Issue on ngOptions track by

Body:
I have some issue with AngularJs option/selector which I uses ngOptions to create. The problem I have is that it doesn't trigger the method I have in ngChange. I found out that's because in actionList the name property isn't unique. So if I change so they are unique it will works as intended. However I want them to be named like how it is now.

So I guess I could try something like ng-options="action.name for action in ctrl.actionList track by action.value". But it doesn't work. Anyone who can help me out here?

HTML

<select id="someOptions" class="dropdown dropdown-md"
    ng-model="ctrl.settingAction"
    ng-change="ctrl.onChangeAction()"
    ng-options="action.name for action in ctrl.actionList">
</select>

Data structure

actionList = [{
    name: "Running Man"
    value: "RUN"
}, {
    name: "Running Man"
    value: "JUMP"
}]

JS

public onChangeAction(): void {
    console.log(this.settingAction);
}

Body:
DEMO

angular.module('myApp',[]).controller('myCtrl', function($scope){
 var ctrl = this;
 this.actionList =[{
    "name": "Running Man",
    "value": "RUN"
}, {
    "name": "Running Man",
    "value": "JUMP"
}];

this.onChangeAction = function(){
 alert(this.settingAction.value);
}

 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
 <select id="someOptions" class="dropdown dropdown-md"
    ng-model="ctrl.settingAction"
    ng-change="ctrl.onChangeAction()"
    ng-options="action.name for action in ctrl.actionList">
</select>
</div>


问:
VBA How to get text from lines below when using Line Input?
I am trying to get copy information from an email saved as a .txt file to an excel sheet.
The issues I am running in to is when I use a Do Loop with the Line Input function I can not get information from text lines that are not on the current line. I would also like the code to copy the line containing the deliminator.

This is the code I am using:

```<code> intFreefile = FreeFile
 Open ThisWorkbook.Path & "\temp567.txt" For Input As #intFreefile
 lngRecordsInEmail = 0
 Do Until EOF(intFreefile)
     Line Input #intFreefile, strText
     If InStr(1, strText, strDelimiter) > 0 Then
         If InStrRev(1, strText, strDelimiter) = 1 Then
         ' if last character in line = deliminator then
         ' how do i get the text on 2 lines below?

         Else
         ws.Cells(lngRow, 1).Value = strText
         End If

         If blColourCell Then
             ws.Cells(lngRow, 1).Interior.ColorIndex = 35
        End If
         strText2 = strText2 + 1
         lngRow = lngRow + 1
         lngTotalRecords = lngTotalRecords + 1
         lngRecordsInEmail = lngRecordsInEmail + 1
    End If
 Loop
 Close
</code>```

答:
My favorite method which is also faster than looping through the file contents is to read the entire text from the file into an array in one go and then work with the array. This will also give you more control to retrieve text from the 2 lines that you want.

Is this what you are trying? (Untested)

```<code>Dim MyData As String, strData() As String
Dim i As Long

intFreefile = FreeFile

'~~> Open file and read it on one go
Open ThisWorkbook.Path & "\temp567.txt" For Binary As #intFreefile
MyData = Space$(LOF(1))
Get #intFreefile, , MyData
Close #intFreefile '<~~ Close the text file after reading from it

'~~> This array has the entire contents from the text file
strData() = Split(MyData, vbCrLf)

For i = LBound(strData) To UBound(strData)
    '~~> Last character in line = deliminator
    If Right(strData(i), 1) = strDelimiter Then
        Debug.Print strData(i)
        Debug.Print strData(i + 1)
        Debug.Print strData(i + 2)
    '~~> Else if the deliminator is somewhere else
    ElseIf InStr(1, strData(i), strDelimiter) Then
        Debug.Print strData(i)
    End If
Next i
</code>```

Body:
I am trying to get copy information from an email saved as a .txt file to an excel sheet.
The issues I am running in to is when I use a Do Loop with the Line Input function I can not get information from text lines that are not on the current line. I would also like the code to copy the line containing the deliminator.

This is the code I am using:

 intFreefile = FreeFile
 Open ThisWorkbook.Path & "\temp567.txt" For Input As #intFreefile
 lngRecordsInEmail = 0
 Do Until EOF(intFreefile)
     Line Input #intFreefile, strText
     If InStr(1, strText, strDelimiter) > 0 Then
         If InStrRev(1, strText, strDelimiter) = 1 Then
         ' if last character in line = deliminator then
         ' how do i get the text on 2 lines below?

         Else
         ws.Cells(lngRow, 1).Value = strText
         End If

         If blColourCell Then
             ws.Cells(lngRow, 1).Interior.ColorIndex = 35
        End If
         strText2 = strText2 + 1
         lngRow = lngRow + 1
         lngTotalRecords = lngTotalRecords + 1
         lngRecordsInEmail = lngRecordsInEmail + 1
    End If
 Loop
 Close

Body:
My favorite method which is also faster than looping through the file contents is to read the entire text from the file into an array in one go and then work with the array. This will also give you more control to retrieve text from the 2 lines that you want.

Is this what you are trying? (Untested)

Dim MyData As String, strData() As String
Dim i As Long

intFreefile = FreeFile

'~~> Open file and read it on one go
Open ThisWorkbook.Path & "\temp567.txt" For Binary As #intFreefile
MyData = Space$(LOF(1))
Get #intFreefile, , MyData
Close #intFreefile '<~~ Close the text file after reading from it

'~~> This array has the entire contents from the text file
strData() = Split(MyData, vbCrLf)

For i = LBound(strData) To UBound(strData)
    '~~> Last character in line = deliminator
    If Right(strData(i), 1) = strDelimiter Then
        Debug.Print strData(i)
        Debug.Print strData(i + 1)
        Debug.Print strData(i + 2)
    '~~> Else if the deliminator is somewhere else
    ElseIf InStr(1, strData(i), strDelimiter) Then
        Debug.Print strData(i)
    End If
Next i


问:
Table getting out of div
I have div in my View

Here is code

```<code><div style="width: 100%; text-align: center; margin-top: 10px;">
    <table class="table" style="table-layout: fixed;">
        <tr style="background: white">
            <th></th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                Invoice
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                Status
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                First -Last Name
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                Invoice printed
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                Invoice paid
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                Payment reminder printed
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                1st overdue notice printed
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                2nd overdue notice printed
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                Open invoice with VAT€
            </th>
            <th style="font-size: 20px; text-align: center;color:#1d69b4;">
                Select all
            </th>

            <th></th>
        </tr>

    </table>
</div>
</code>```

On 1920*1080 all ok, but on 1366*768 some columns outta div.

Like this

I try to use style="table-layout: fixed;"

But it's look like this

How I can make my table to look right?

答: Try using max-width for the table and set the value to anything less than 100%, remove table-layout style. </p>

Title: Table getting out of div

Body:
I have div in my View

Here is code

                Invoice

                Status

                First -Last Name

                Invoice printed

                Invoice paid

                Payment reminder printed

                1st overdue notice printed

                2nd overdue notice printed

                Open invoice with VAT€

                Select all

On 1920*1080 all ok, but on 1366*768 some columns outta div.

Like this

I try to use style="table-layout: fixed;"

But it's look like this

How I can make my table to look right?