问:
How to show menu and title on all activities?
I have created three activities explore/deals and packages. I have created my menu using drawer layout. I would like to saw my menu icon on each activity screen. I have created a base activity for menu items and extends that to all activities. I'm attaching my homeactivity code, base activity code and explore activity code below

enter image description here

Here is explore activity code

```<code>package com.example.windows81.travelspoc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class ExploreActivity extends BaseActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_explore);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //getMenuInflater().inflate(R.menu.menu_second, menu);  <- remove this
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
}
</code>```

Here is my homeactivity code

```<code>package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{

ViewPager viewPager;
LinearLayout sliderDotspanel;
NavigationView mNavigationView;
private int dotscount;
private ImageView[] dots;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open,
R.string.close);
    NavigationView mNavigationView = (NavigationView)
findViewById(R.id.navigation);
    mNavigationView.setNavigationItemSelectedListener(this);

    mDrawerLayout.addDrawerListener(mtoggle);
    mtoggle.syncState();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewPager);

    sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
    viewPager.setAdapter(viewPagerAdapter);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

    dotscount = viewPagerAdapter.getCount();
    dots = new ImageView[dotscount];

    for (int i = 0; i < dotscount; i++){
        dots[i] = new ImageView(this);

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));

        LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(8, 0, 8,0);

        sliderDotspanel.addView(dots[i], params);
    }

dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.ic_active));
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            for (int i = 0; i < dotscount; i++){

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
            }

dots[position].setImageDrawable(ContextCompat.getDrawable
(getApplicationContext(), R.drawable.ic_active));

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(mtoggle.onOptionsItemSelected(item)){
        return true;
    }
    switch (item.getItemId()) {
        case R.id.explore:
            // do what you want here
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public class MyTimerTask extends TimerTask{

    @Override
    public void run() {

        HomeActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (viewPager.getCurrentItem() == 0){
                    viewPager.setCurrentItem(1);
                }else if (viewPager.getCurrentItem() == 1){
                    viewPager.setCurrentItem(2);
                }else{
                    viewPager.setCurrentItem(0);
                }

            }
        });

    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.explore) {
        myMethod();
    }
    return false;
}
}
</code>```

Here is my Base activity code

```<code>package com.example.windows81.travelspoc;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

/**
 * Created by Windows 8.1 on 11/15/2017.
 */

public class BaseActivity extends AppCompatActivity{
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.explore:
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
}
</code>```

答:
Create a base activity in which u write code for menu items then extend the base activity to all your inner activities.

For Title

Create a common title layout.

Then in your HomeActivity

```<code>abstract class HomeActivity extends Activity {
  protected TextView txtHeading;
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
  }

  protected void setHeading(int resId) {
     if(tv_title == null)
     txtHeading = findViewById(R.id.tv_title);
     if(tv_title != null)
       txtHeading.setText(resId);
  }
}
</code>```

Then in other activities like activity_main.xml

MainActivity

```<code>class MainActivity extends BaseActivity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      setHeading(R.string.heading_main);
   }
}
</code>```

same goes for other activities

For Same Menu Option

```<code>public class HomeActivity extends Activity {

    // other overidden methods

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item:
                // do what you want here
                return true;
            default:
               return super.onOptionsItemSelected(item);
        }
    }
}
</code>```

Then in child activity

```<code>  public class ChildActivity extends BaseActivity {

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //getMenuInflater().inflate(R.menu.menu_second, menu);  <- remove this
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
    }
</code>```

Body:
I have created three activities explore/deals and packages. I have created my menu using drawer layout. I would like to saw my menu icon on each activity screen. I have created a base activity for menu items and extends that to all activities. I'm attaching my homeactivity code, base activity code and explore activity code below

enter image description here

Here is explore activity code

package com.example.windows81.travelspoc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class ExploreActivity extends BaseActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_explore);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //getMenuInflater().inflate(R.menu.menu_second, menu);  <- remove this
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
}

Here is my homeactivity code

package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{

ViewPager viewPager;
LinearLayout sliderDotspanel;
NavigationView mNavigationView;
private int dotscount;
private ImageView[] dots;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open,
R.string.close);
    NavigationView mNavigationView = (NavigationView)
findViewById(R.id.navigation);
    mNavigationView.setNavigationItemSelectedListener(this);

    mDrawerLayout.addDrawerListener(mtoggle);
    mtoggle.syncState();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewPager);

    sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
    viewPager.setAdapter(viewPagerAdapter);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

    dotscount = viewPagerAdapter.getCount();
    dots = new ImageView[dotscount];

    for (int i = 0; i < dotscount; i++){
        dots[i] = new ImageView(this);

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));

        LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(8, 0, 8,0);

        sliderDotspanel.addView(dots[i], params);
    }

dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.ic_active));
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            for (int i = 0; i < dotscount; i++){

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
            }

dots[position].setImageDrawable(ContextCompat.getDrawable
(getApplicationContext(), R.drawable.ic_active));

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(mtoggle.onOptionsItemSelected(item)){
        return true;
    }
    switch (item.getItemId()) {
        case R.id.explore:
            // do what you want here
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public class MyTimerTask extends TimerTask{

    @Override
    public void run() {

        HomeActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (viewPager.getCurrentItem() == 0){
                    viewPager.setCurrentItem(1);
                }else if (viewPager.getCurrentItem() == 1){
                    viewPager.setCurrentItem(2);
                }else{
                    viewPager.setCurrentItem(0);
                }

            }
        });

    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.explore) {
        myMethod();
    }
    return false;
}
}

Here is my Base activity code

package com.example.windows81.travelspoc;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

/**
 * Created by Windows 8.1 on 11/15/2017.
 */

public class BaseActivity extends AppCompatActivity{
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.explore:
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
}

Body:
Create a base activity in which u write code for menu items then extend the base activity to all your inner activities.

For Title

Create a common title layout.

Then in your HomeActivity

abstract class HomeActivity extends Activity {
  protected TextView txtHeading;
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
  }

  protected void setHeading(int resId) {
     if(tv_title == null)
     txtHeading = findViewById(R.id.tv_title);
     if(tv_title != null)
       txtHeading.setText(resId);
  }
}

Then in other activities like activity_main.xml

MainActivity

class MainActivity extends BaseActivity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      setHeading(R.string.heading_main);
   }
}

same goes for other activities

For Same Menu Option

public class HomeActivity extends Activity {

    // other overidden methods

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item:
                // do what you want here
                return true;
            default:
               return super.onOptionsItemSelected(item);
        }
    }
}

Then in child activity

  public class ChildActivity extends BaseActivity {

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //getMenuInflater().inflate(R.menu.menu_second, menu);  <- remove this
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
    }


来源: stackexchange

问:
Xcode 8 Breakpoint in file not working
I have one file,SignInViewController.swift, in my Xcode project that out of nowhere has begun not stopping on breakpoints. I have a breakpoint in viewDidLoad() and a few in viewDidAppear(). I have several print() calls in both functions to make sure they are executing. Breakpoints work fine in other files including AppDelegate.swift.

There was a point when I trying to figure out what was wrong where I noticed that while I was building the project an error would appear saying Invalid redeclaration of 'signInViewController.swift' and then go away before the build finished and the app would run fine, except for the breakpoints in the file. signInViewController.swift is the old name of the file from months ago before I renamed it to SignInViewController.swift. I haven't seen it before until the breakpoint issue occurred and since I have cleaned the project's build folder and Xcode's derived data I have been unable to replicate. I have a feeling that it is factoring into the problem but I am not sure how/why.

Anyways, here is things I've tried already. Most of them are just for breakpoints not working in general but I figure I should list them anyways even though that is not the case:

Clean Project

Clean Build Folder

Clear Xcode's DerivedData

Making sure breakpoints are enabled (Cmd Y)

Build Settings are set to Debug

Always Show Disassembly enabled and disabled

Debugging enabled in run config

Any help would be very much appreciated.

UPDATE 1 (still no luck):

Tried deleting the Xcode preference as suggested by neprocker's answer here

UPDATE 2:

I have isolated the breakpoint issue to just viewDidLoad() and viewDidAppear() breakpoints elsewhere in the file are working.

UPDATE 3:

Isolated to a specific block of code in viewDidLoad(). viewDidAppear() still not working though.

答:
I was also dealing with the same issue in xcode 9.

I resolved the issue in below ways:

Remove XCode defaults Using below terminal command

```<code>defaults delete com.apple.dt.Xcode.LSSharedFileList
defaults delete com.apple.dt.Xcode
</code>```

Clear(or delete) Xcode's DerivedData from

```<code>/Users/[Your Mac Username]/Library/Developer/Xcode/DerivedData
</code>```

Delete(or uninstall) Xcode.app from Applications and then restart PC

Install fresh copy of Xcode 9

[Mandatory] Set user permission to your app project like

```<code>chmod -R 777 "/Users/[Your Mac Username]/Desktop/TestApp/"
</code>```

[where TestApp is the app project keeping on Desktop]

Open the project and check Build Settings are set to Debug

Make sure breakpoints are enabled and set debug point in your code

ContentLicense: CC BY-SA 3.0

Title: Xcode 8 Breakpoint in file not working

Body:
I was also dealing with the same issue in xcode 9.

I resolved the issue in below ways:

Remove XCode defaults Using below terminal command

defaults delete com.apple.dt.Xcode.LSSharedFileList
defaults delete com.apple.dt.Xcode

Clear(or delete) Xcode's DerivedData from

/Users/[Your Mac Username]/Library/Developer/Xcode/DerivedData

Delete(or uninstall) Xcode.app from Applications and then restart PC

Install fresh copy of Xcode 9

[Mandatory] Set user permission to your app project like

chmod -R 777 "/Users/[Your Mac Username]/Desktop/TestApp/"

[where TestApp is the app project keeping on Desktop]

Open the project and check Build Settings are set to Debug

Make sure breakpoints are enabled and set debug point in your code


问:
About START_STICKY in Service
About using START_STICKY in Android Service.

official document says:

if this service's process is killed while it is started (after
  returning from onStartCommand(Intent, int, int)), then leave it in the
  started state but don't retain this delivered intent. Later the system
  will try to re-create the service. Because it is in the started state,
  it will guarantee to call onStartCommand(Intent, int, int) after
  creating the new service instance;

This is understandable, so when an started service's process is killed due to lack of memory, the OS will automatically try to start the service again later.

My question is, if my code starts the service startService(...), and later stop it(e.g. I have a "STOP" button on my app's UI, when press it, I call stopService(...)), will system later start the service again? Or will the service instance be cleared from memory completely without later being created by system? (No service binding for this scenario)

答:
START_STICKY is the operation mode of the started services, depending on the value they return from on StartCommand() method.START_STICKY is used for services that create the copy of service but it won`t store any result of services which is performed before.

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Logs.d(TAG, "# Service - onStartCommand() starts here");

// If service returns START_STICKY, android restarts service automatically after forced close.
// At this time, onStartCommand() method in service must handle null intent.
return Service.START_STICKY;
</code>```

}

Title: About START_STICKY in Service

Body:
START_STICKY is the operation mode of the started services, depending on the value they return from on StartCommand() method.START_STICKY is used for services that create the copy of service but it won`t store any result of services which is performed before.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Logs.d(TAG, "# Service - onStartCommand() starts here");

// If service returns START_STICKY, android restarts service automatically after forced close.
// At this time, onStartCommand() method in service must handle null intent.
return Service.START_STICKY;

}


问:
getElementById("id").text return object but should be return value from this paragraph
I have a project in HTML/JS.
The problem is that when I want get a value of the paragraph using getElementById("id").text I got object.

var data = document.getElementById("pid").text;
console.log(data);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="pid" >Hello</p></code>```

Chrome:
data returns:

Hello

But I want only Hello value.

Thanks for the answers

答:
text will not return the text node. Use textContent property to access the text node without parsing - vice versa to innerHTML. And innerText will not return that part of the text which is hidden via CSS. So why I suggest to use textContent.

var data = document.getElementById("pid").textContent;
console.log(data);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="pid">Hello</p></code>```

Body:
I have a project in HTML/JS.
The problem is that when I want get a value of the paragraph using getElementById("id").text I got object.

var data = document.getElementById("pid").text;
console.log(data);

Hello

Chrome:
data returns:

Hello

But I want only Hello value.

Thanks for the answers

Body:
text will not return the text node. Use textContent property to access the text node without parsing - vice versa to innerHTML. And innerText will not return that part of the text which is hidden via CSS. So why I suggest to use textContent.

var data = document.getElementById("pid").textContent;
console.log(data);

<p id="pid">Hello</p>


问:
Angular HttpClient data undefined out of subscribe
I'm having trouble with setting up simple GET query with a REST API.

For demonstration purposes I used this REST endpoint:
https://jsonplaceholder.typicode.com/posts/1

It seems that all received data is lost when leaving the scope of the subscribe method. I followed multiple tutorials, that also said I would get a error when accessing attributes without typecasting, but it works fine for me. Why is that so?

```<code>import { Injectable } from '@angular/core';
import { HttpClient  } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import * as _ from 'lodash';

@Injectable()
export class TestService {

    constructor(private http : HttpClient ) { }

    private URI = 'https://jsonplaceholder.typicode.com/posts/1';
    o : object;
    //Object { userId: 1, id: 1, title: "sunt aut facere repellat provident
    //…", body: "quia et suscipit suscipit recusanda…" }

    getData(): void
    {
        this.o = this.http.get(this.URI ).subscribe();

        this.http.get<Post>(this.URI ).subscribe(response => {
            console.log(response)//shows up
            this.o = response;
            console.log(this.o);//shows up
        } );
        console.log(this.o);//undefined
     }
}

interface Post{
    userId: number;
    id : number;
    title : string;
    body : string;
}
</code>```

Screenshot of the console

答:
Update 1 :

```<code>ngOnInit() {
  this.thingService.getThingsGoing()
  .subscribe(data => this.success(data), err => this.failed(err));
}

success(data){
  console.log(data); // <== Use it here
}

failed(err){
  console.log(err);
}
</code>```

First of all, You are using it wrong. You are making 2 requests on the same URL.

```<code>this.o = this.http.get(this.URI ).subscribe();   // <==== Request 1 / No need
    this.http.get<Post>(this.URI ).subscribe(response => {
        console.log(response)//shows up
        this.o = response;
        console.log(this.o);//shows up
    } );   // <==== Request 2
    console.log(this.o);//undefined
</code>```

You are making async call, this.o will be undefined because application has not received the data yet.

When you write it in subscribe() it will be showed up when client receives actual data.

Body:
I'm having trouble with setting up simple GET query with a REST API.

For demonstration purposes I used this REST endpoint:
https://jsonplaceholder.typicode.com/posts/1

It seems that all received data is lost when leaving the scope of the subscribe method. I followed multiple tutorials, that also said I would get a error when accessing attributes without typecasting, but it works fine for me. Why is that so?

import { Injectable } from '@angular/core';
import { HttpClient  } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import * as _ from 'lodash';

@Injectable()
export class TestService {

    constructor(private http : HttpClient ) { }

    private URI = 'https://jsonplaceholder.typicode.com/posts/1';
    o : object;
    //Object { userId: 1, id: 1, title: "sunt aut facere repellat provident
    //…", body: "quia et suscipit suscipit recusanda…" }

    getData(): void
    {
        this.o = this.http.get(this.URI ).subscribe();

        this.http.get<Post>(this.URI ).subscribe(response => {
            console.log(response)//shows up
            this.o = response;
            console.log(this.o);//shows up
        } );
        console.log(this.o);//undefined
     }
}

interface Post{
    userId: number;
    id : number;
    title : string;
    body : string;
}

Screenshot of the console

Body:
Update 1 :

ngOnInit() {
  this.thingService.getThingsGoing()
  .subscribe(data => this.success(data), err => this.failed(err));
}

success(data){
  console.log(data); // <== Use it here
}

failed(err){
  console.log(err);
}

First of all, You are using it wrong. You are making 2 requests on the same URL.

this.o = this.http.get(this.URI ).subscribe();   // <==== Request 1 / No need
    this.http.get<Post>(this.URI ).subscribe(response => {
        console.log(response)//shows up
        this.o = response;
        console.log(this.o);//shows up
    } );   // <==== Request 2
    console.log(this.o);//undefined

You are making async call, this.o will be undefined because application has not received the data yet.

When you write it in subscribe() it will be showed up when client receives actual data.


问:
Regex to check whether a string contains only numbers
```<code>hash = window.location.hash.substr(1);
var reg = new RegExp('^[0-9]$');
console.log(reg.test(hash));
</code>```

I get false on both "123" and "123f". I would like to check if the hash only contains numbers. Did I miss something?

答:
Why dont use something like:

```<code>$.isNumeric($(input).val())
</code>```

Is jquery tested, and the most common case are checked

Body:
hash = window.location.hash.substr(1);
var reg = new RegExp('^[0-9]$');
console.log(reg.test(hash));

I get false on both "123" and "123f". I would like to check if the hash only contains numbers. Did I miss something?

Body:
Why dont use something like:

$.isNumeric($(input).val())

Is jquery tested, and the most common case are checked


问:
Spliting a week of data in to days of the Week SQL
Good Morning All
So I was asked to look where things are getting ordered from on a weekly bases so simple.

```<code>DECLARE @vYearWeek INT
SET @vYearWeek = '201745';

SELECT
  LEFT(Orders.ProductWhsLocation,1) AS 'Area',
  COUNT(Orders.HostOrderNo) AS 'Picked'
FROM CHDS_Common.dbo.OMOrder Orders
  LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
  WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
  GROUP BY LEFT(ProductWhsLocation,1)
  ORDER BY LEFT(ProductWhsLocation,1);
</code>```

And this works fine ... how ever I need to got deeper now and spilt it in to days. Now logic would say this will be simple as:

```<code>DECLARE @vYearWeek INT
SET @vYearWeek = '201745';

SELECT
  LEFT(Orders.ProductWhsLocation,1) AS 'Area',
  CASE WHEN Cal.DW = 1 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Sunday',
  CASE WHEN Cal.DW = 2 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Monday',
  CASE WHEN Cal.DW = 3 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Tuesday',
  CASE WHEN Cal.DW = 4 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Wednesday',
  CASE WHEN Cal.DW = 5 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Thuresday',
  CASE WHEN Cal.DW = 6 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Friday',
  CASE WHEN Cal.DW = 7 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Saturday'
FROM CHDS_Common.dbo.OMOrder Orders
  LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
GROUP BY LEFT(ProductWhsLocation,1)
ORDER BY LEFT(ProductWhsLocation,1);
</code>```

But as you all know ERROR :(
Column 'CHDS_Management.dbo.Calendar.DW' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Any Help on sorting this out would be great many thanks all.

答:
Pivot Query would work in this scenario

--Improved Answer

step1: Get day of week either by date in calendar table or day number

step 2: use pivot table to get count of rows by day

```<code>SELECT *

FROM
(
    SELECT
  LEFT(Orders.ProductWhsLocation,1) AS 'Area',
  COUNT(Orders.HostOrderNo) OrderCount,
  DATENAME(weekday,cal.dt) 'DayName'
  FROM CHDS_Common.dbo.OMOrder Orders
  LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
GROUP BY LEFT(ProductWhsLocation,1),cal.dw
) AS SourceTable PIVOT(SUM(OrderCount) FOR [DayName] IN([SUNDAY]
                                                        ,[MONDAY]
                                                        ,[TUESDAY]
                                                        ,[WEDNESDAY]
                                                        ,[THURSDAY]
                                                        ,[FRIDAY]
                                                        ,[SATURDAY] )

) AS PivotTable;
</code>```

Body:
Good Morning All
So I was asked to look where things are getting ordered from on a weekly bases so simple.

DECLARE @vYearWeek INT
SET @vYearWeek = '201745';

SELECT
  LEFT(Orders.ProductWhsLocation,1) AS 'Area',
  COUNT(Orders.HostOrderNo) AS 'Picked'
FROM CHDS_Common.dbo.OMOrder Orders
  LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
  WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
  GROUP BY LEFT(ProductWhsLocation,1)
  ORDER BY LEFT(ProductWhsLocation,1);

And this works fine ... how ever I need to got deeper now and spilt it in to days. Now logic would say this will be simple as:

DECLARE @vYearWeek INT
SET @vYearWeek = '201745';

SELECT
  LEFT(Orders.ProductWhsLocation,1) AS 'Area',
  CASE WHEN Cal.DW = 1 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Sunday',
  CASE WHEN Cal.DW = 2 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Monday',
  CASE WHEN Cal.DW = 3 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Tuesday',
  CASE WHEN Cal.DW = 4 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Wednesday',
  CASE WHEN Cal.DW = 5 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Thuresday',
  CASE WHEN Cal.DW = 6 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Friday',
  CASE WHEN Cal.DW = 7 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Saturday'
FROM CHDS_Common.dbo.OMOrder Orders
  LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
GROUP BY LEFT(ProductWhsLocation,1)
ORDER BY LEFT(ProductWhsLocation,1);

But as you all know ERROR :(
Column 'CHDS_Management.dbo.Calendar.DW' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Any Help on sorting this out would be great many thanks all.

Body:
Pivot Query would work in this scenario

--Improved Answer

step1: Get day of week either by date in calendar table or day number

step 2: use pivot table to get count of rows by day

SELECT *

FROM
(
    SELECT
  LEFT(Orders.ProductWhsLocation,1) AS 'Area',
  COUNT(Orders.HostOrderNo) OrderCount,
  DATENAME(weekday,cal.dt) 'DayName'
  FROM CHDS_Common.dbo.OMOrder Orders
  LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
GROUP BY LEFT(ProductWhsLocation,1),cal.dw
) AS SourceTable PIVOT(SUM(OrderCount) FOR [DayName] IN([SUNDAY]
                                                        ,[MONDAY]
                                                        ,[TUESDAY]
                                                        ,[WEDNESDAY]
                                                        ,[THURSDAY]
                                                        ,[FRIDAY]
                                                        ,[SATURDAY] )

) AS PivotTable;


问:
Google Play Sign in for Unity
I am trying to integrate Google play Services so that i can have achievements and leader boards in my game.I have tried the following code - </p>

```<code>public Text myText;

void Awake()
{
    PlayGamesPlatform.Activate();
}

public void SignIN()
{
    Social.localUser.Authenticate((bool Success) =>
    {
        if (Success)
        {
            myText.text = "Yayy!!";
        }
        else
        {
            myText.text = "Not AGAIN!!";
        }
    });
}

public void SignOUT()
{
    PlayGamesPlatform.Instance.SignOut();
    if (Social.localUser.authenticated == false)
    {
        myText.text = "SIGNED OUT!!";
    }
}
</code>```

<p>where SignIN() and SignOUT() are called in buttons Sign IN and Sign OUT but i am unable to Sign in.I have Copy pasted resources from Google play developer console into Unity(Window - Google Play Services - SetUp - Android)and also linked my apk with GooglePlayServices on Developer Console. But it's no use i am unable to sign in, please help. </p>

答:
Maybe you have missed the configuration steps? This code is from the link, and anyway it assumes you have also configured the settings.</p>

```<code>using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;

PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
    // enables saving game progress.
    .EnableSavedGames()
    // registers a callback to handle game invitations received while the game is not running.
    .WithInvitationDelegate(<callback method>)
    // registers a callback for turn based match notifications received while the
    // game is not running.
    .WithMatchDelegate(<callback method>)
    // requests the email address of the player be available.
    // Will bring up a prompt for consent.
    .RequestEmail()
    // requests a server auth code be generated so it can be passed to an
    //  associated back end server application and exchanged for an OAuth token.
    .RequestServerAuthCode(false)
    // requests an ID token be generated.  This OAuth token can be used to
    //  identify the player to other services such as Firebase.
    .RequestIdToken()
    .Build();

PlayGamesPlatform.InitializeInstance(config);
// recommended for debugging:
PlayGamesPlatform.DebugLogEnabled = true;
// Activate the Google Play Games platform
PlayGamesPlatform.Activate();
</code>```

Title: Google Play Sign in for Unity

Body:
I am trying to integrate Google play Services so that i can have achievements and leader boards in my game.I have tried the following code -

public Text myText;

void Awake()
{
    PlayGamesPlatform.Activate();
}

public void SignIN()
{
    Social.localUser.Authenticate((bool Success) =>
    {
        if (Success)
        {
            myText.text = "Yayy!!";
        }
        else
        {
            myText.text = "Not AGAIN!!";
        }
    });
}

public void SignOUT()
{
    PlayGamesPlatform.Instance.SignOut();
    if (Social.localUser.authenticated == false)
    {
        myText.text = "SIGNED OUT!!";
    }
}

where SignIN() and SignOUT() are called in buttons Sign IN and Sign OUT but i am unable to Sign in.I have Copy pasted resources from Google play developer console into Unity(Window - Google Play Services - SetUp - Android)and also linked my apk with GooglePlayServices on Developer Console. But it's no use i am unable to sign in, please help.

Body:
Maybe you have missed the configuration steps? This code is from the link, and anyway it assumes you have also configured the settings.

using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;

PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
    // enables saving game progress.
    .EnableSavedGames()
    // registers a callback to handle game invitations received while the game is not running.
    .WithInvitationDelegate(<callback method>)
    // registers a callback for turn based match notifications received while the
    // game is not running.
    .WithMatchDelegate(<callback method>)
    // requests the email address of the player be available.
    // Will bring up a prompt for consent.
    .RequestEmail()
    // requests a server auth code be generated so it can be passed to an
    //  associated back end server application and exchanged for an OAuth token.
    .RequestServerAuthCode(false)
    // requests an ID token be generated.  This OAuth token can be used to
    //  identify the player to other services such as Firebase.
    .RequestIdToken()
    .Build();

PlayGamesPlatform.InitializeInstance(config);
// recommended for debugging:
PlayGamesPlatform.DebugLogEnabled = true;
// Activate the Google Play Games platform
PlayGamesPlatform.Activate();


问:
Angular 2 redirect from child router
I have appRoutes in my Angular 2 app

```<code>const appRoutes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    {
        path: 'component-two', component: AppComponent2,
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
        ]
    },
];
</code>```

How I can redirect from my LoginComponent to HomeComponent?

答:
```<code>const appRoutes: Routes = [
{
    path: '',
    component: LoginComponent,
    children: [
           { path: '', redirectTo: 'home', pathMatch: 'full' },
           { path: 'home', component: HomeComponent }
              ]
}
];
</code>```

You have to do this.

Title: Angular 2 redirect from child router

Body:
I have appRoutes in my Angular 2 app

const appRoutes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    {
        path: 'component-two', component: AppComponent2,
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
        ]
    },
];

How I can redirect from my LoginComponent to HomeComponent?

Body:
const appRoutes: Routes = [
{
    path: '',
    component: LoginComponent,
    children: [
           { path: '', redirectTo: 'home', pathMatch: 'full' },
           { path: 'home', component: HomeComponent }
              ]
}
];

You have to do this.


问:
message queue thinking
We have implemented a message queue by using C# Queue. We know we only have ONE consumer to take available message out from the queue for processing with a while loop. We also know there is only ONE producer to put message onto the queue.

We have a lock on above message queue to make sure the consumer and producer cannot access the queue simultaneously.

My question is is that lock necessary? If the Queue increase its Count property AFTER an item is actually added and if the consumer check the Count before retrieve, the consumer should get a complete message item even we don't have that lock. Right? So we will not face a partial message item issue. Then we can get rid of that lock?

That lock will slow down the system and occasionally we can see the retrieve thread is blocked for a while because we have a very heavy producer.

EDIT:

Unfortunately we are using .Net 3.5.

答:
You should be Locking; the class isn't threadsafe.  If you're using the Queue in System.Collections, there is a thread-safe Queue handy (System.Collections.Queue.Synchronized() returns such a Queue).  Otherwise, be sure to use the object provided Queue<T>.SyncRoot to synchronize:

```<code>using System.Collections.Generic;
public static class Q_Example
{
    private readonly Queue<int> q = new Queue<int>();
    public void Method1(int val)
    {
        lock(q.SyncRoot)
        {
            q.EnQueue(val);
        }
    }

    public int Method2()
    {
        lock(q.SyncRoot)
        {
            return q.Dequeue();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: message queue thinking

Body:
You should be Locking; the class isn't threadsafe.  If you're using the Queue in System.Collections, there is a thread-safe Queue handy (System.Collections.Queue.Synchronized() returns such a Queue).  Otherwise, be sure to use the object provided Queue<T>.SyncRoot to synchronize:

using System.Collections.Generic;
public static class Q_Example
{
    private readonly Queue<int> q = new Queue<int>();
    public void Method1(int val)
    {
        lock(q.SyncRoot)
        {
            q.EnQueue(val);
        }
    }

    public int Method2()
    {
        lock(q.SyncRoot)
        {
            return q.Dequeue();
        }
    }
}


问:
Need a loop to add 30 minutes as a time in HTML
i have made a webpage using html and php that allows users to book appointments, but my slots are every 30 minutes but the way i am currently doing it will not add 30 minutes on to the database </p>

```<code><?php ob_start( ); ?>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="Nav.css">

    <title>Book Barber</title></head>
    <body>
    <?php
            echo " <div class='navigation'><a href='BarberHomeScreen.php'>Home</a><div class='dropdown'><button class='dropdownButton'>Account<i class='fa fa-caret-down'></i></button><div class='dropdownContent'><a href='MyAccount.php'>My Account</a><a href='SignOut.php'>Sign Out</a></div></div></div>";
    ?>
        <h1>Booking a barber appointment for <?php session_start();echo $_SESSION['customerName'];?></h1>
        <form method="POST" action="#">

            <input type="date" name="selectDate" />
            <input type="submit" name="submitDate"/>

        <?php
            if(isset($_POST['submitDate'])){

                //if the submit button has been pressed, connect to the db
                //and search for all the available tables on that selected day
                $conn = mysql_connect(localhost, "root", "");
                if(!$conn){
                    die("Could not connect: " . mysql_error());
                }

                  $selectedDb = mysql_select_db('booking', $conn);
                  if(!$selectedDb){
                    die("Can't use the selected db: " . mysql_error());
                  }

                  //selects all the bookings for the date chosen in the form
                  $query= "SELECT * FROM booking WHERE BookingDate = '" . $_POST['selectDate'] . "' ORDER BY customerID, BookingTime";
                  $result = mysql_query($query);
                  //stop php while table headers outputted
                  ?>

                  <table border="1">
                      <tr></tr>
                      <tr>
                          <th>Barber</th>
                          <th>9:00</th>
                          <th>9:30</th>
                          <th>10:00</th>
                          <th>10:30</th>
                          <th>11:00</th>
                          <th>11:30</th>
                          <th>12:00</th>
                          <th>12:30</th>
                          <th>13:00</th>
                          <th>13:30</th>
                          <th>14:00</th>
                          <th>14:30</th>
                          <th>15:00</th>
                          <th>15:30</th>
                          <th>16:00</th>
                      </tr>
                  <?php //start php again to output the bookings available or not

                 /*The next bulk of php is outputting the table showing which slots are booked and which are available.
                 two while loops are needed, the outer one loops through the tables, the inner while loops through
                 each of the times for the table.
                 Then while the loops are repeating they check if this booking
                 is for the current timeslot and table being looked at. If so it puts an X in the td and carries out mysql_fetch_assoc
                 again to get the next booking from the $result. This continues for each of the slots in the table.
                 */
                    $row = mysql_fetch_assoc($result);
                       $time = 9;
                       echo "<tr>";
                       echo "<td>" . $count . "</td>";
                       while($time <= 16){//time begins at 9 and stops at 16. Would be better to get this from the db too.
                           if((Time($row['BookingTime'])==$time)){
                               echo "<td style='background-color:lightCoral'>X</td>";
                               $row = mysql_fetch_assoc($result);
                           }else{
                               echo "<td style='background-color:lightGreen'><a href='MakeBarberBooking.php?&time=" . $time. "&date=" . $_POST['selectDate'] ."'>Book</a></td>";
                           }

                           $time=$time+0.5;
                       }
                        echo "</tr>";

                    }//end while

            //end if submit pressed

                ?>
                </table>
            </form>
    </body>
</html>
<?php

ob_end_flush( );
 ?>
</code>```

<p>the system loops through each time slot using the time=time+0.5 but that records the time as 10.5 instead of 10:30 for instance </p>

答:
You could use PHP's DatePeriod function.

First create the start and end times. Then create a date interval and loop over the object.

N.B. its worth noting you may need to add the interval to the dtEnds to get the loop to include the last period.

```<code>// set format the date string is formatted as
$format = 'Y-m-d H:i:s';

// set the start and end date
$dtStarts = new DateTime();
$dtEnds   = new DateTime::createFromFormat($format, '2017-12-01 06:00:00');

// create intervals that we would like to loop over
// i.e. 1 day at a time, or every 45 minutes
$dtInterval         = DateInterval::createFromDateString('1 days');
$dtIntraDayInterval = DateInterval::createFromDateString('45 minutes');

// set day period/range
$dpPeriod = new DatePeriod( $dtCalStarts, $dtInterval, $dtCalEnds );

// loop oveer each period in the day
foreach ( $dpPeriod as $dtDay ){
    echo "```";
    var_dump($dtDay);
    echo "```";
}
</code>```

Body:
i have made a webpage using html and php that allows users to book appointments, but my slots are every 30 minutes but the way i am currently doing it will not add 30 minutes on to the database

<?php ob_start( ); ?>

        <link rel="stylesheet" type="text/css" href="Nav.css">

    <title>Book Barber</title>

    <?php
            echo "
Home
<button class='dropdownButton'>Account</button>
My AccountSign Out

";
    ?>

Booking a barber appointment for <?php session_start();echo $_SESSION['customerName'];?>

        <form method="POST" action="#">

            <input type="date" name="selectDate" />
            <input type="submit" name="submitDate"/>

        <?php
            if(isset($_POST['submitDate'])){

                //if the submit button has been pressed, connect to the db
                //and search for all the available tables on that selected day
                $conn = mysql_connect(localhost, "root", "");
                if(!$conn){
                    die("Could not connect: " . mysql_error());
                }

                  $selectedDb = mysql_select_db('booking', $conn);
                  if(!$selectedDb){
                    die("Can't use the selected db: " . mysql_error());
                  }

                  //selects all the bookings for the date chosen in the form
                  $query= "SELECT * FROM booking WHERE BookingDate = '" . $_POST['selectDate'] . "' ORDER BY customerID, BookingTime";
                  $result = mysql_query($query);
                  //stop php while table headers outputted
                  ?>

                          Barber
                          9:00
                          9:30
                          10:00
                          10:30
                          11:00
                          11:30
                          12:00
                          12:30
                          13:00
                          13:30
                          14:00
                          14:30
                          15:00
                          15:30
                          16:00

                  <?php //start php again to output the bookings available or not

                 /*The next bulk of php is outputting the table showing which slots are booked and which are available.
                 two while loops are needed, the outer one loops through the tables, the inner while loops through
                 each of the times for the table.
                 Then while the loops are repeating they check if this booking
                 is for the current timeslot and table being looked at. If so it puts an X in the td and carries out mysql_fetch_assoc
                 again to get the next booking from the $result. This continues for each of the slots in the table.
                 */
                    $row = mysql_fetch_assoc($result);
                       $time = 9;
                       echo "
";
                       echo "" . $count . "	";
                       while($time <= 16){//time begins at 9 and stops at 16. Would be better to get this from the db too.
                           if((Time($row['BookingTime'])==$time)){
                               echo "X	";
                               $row = mysql_fetch_assoc($result);
                           }else{
                               echo "Book	";
                           }

                           $time=$time+0.5;
                       }
                        echo "
";

                    }//end while

            //end if submit pressed

                ?>

            </form>

<?php

ob_end_flush( );
 ?>

the system loops through each time slot using the time=time+0.5 but that records the time as 10.5 instead of 10:30 for instance

Body:
You could use PHP's DatePeriod function.

First create the start and end times. Then create a date interval and loop over the object.

N.B. its worth noting you may need to add the interval to the dtEnds to get the loop to include the last period.

// set format the date string is formatted as
$format = 'Y-m-d H:i:s';

// set the start and end date
$dtStarts = new DateTime();
$dtEnds   = new DateTime::createFromFormat($format, '2017-12-01 06:00:00');

// create intervals that we would like to loop over
// i.e. 1 day at a time, or every 45 minutes
$dtInterval         = DateInterval::createFromDateString('1 days');
$dtIntraDayInterval = DateInterval::createFromDateString('45 minutes');

// set day period/range
$dpPeriod = new DatePeriod( $dtCalStarts, $dtInterval, $dtCalEnds );

// loop oveer each period in the day
foreach ( $dpPeriod as $dtDay ){
    echo "<pre>";
    var_dump($dtDay);
    echo "</pre>";
}


问:
Mark-up Validation
I am attempting to clean up some HTML after it being chopped and altered many times.

When I go to Validate the page I keep getting a kick back saying this

"end tag for "table" which is not finished"

bit confused as i believe I closed it? here is a sample.

I also tried

```<code><table align="center" border="0" cellpadding="0" cellspacing="0" class="widthtable" width="650"< </table>
</code>```

thanks in advance.

答:
You should close your table tags correctly. </p>

```<code><table .. **>**</table>

<table align="center" border="0" cellpadding="0" cellspacing="0" class="widthtable" width="650"> </table>
</code>```

Title: Mark-up Validation

Body:
I am attempting to clean up some HTML after it being chopped and altered many times.

When I go to Validate the page I keep getting a kick back saying this

"end tag for "table" which is not finished"

bit confused as i believe I closed it? here is a sample.

I also tried

<table align="center" border="0" cellpadding="0" cellspacing="0" class="widthtable" width="650"<

thanks in advance.

Body:
You should close your table tags correctly.

<table .. **>**</table>

<table align="center" border="0" cellpadding="0" cellspacing="0" class="widthtable" width="650"> </table>


问:
Code Golf: Finite-state machine!

Finite state machine

A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected. Leaving some formalities aside, A run of a finite state machine is composed of:

alphabet, a set of characters.

states, usually visualized as circles. One of the states must be the start state. Some of the states might be accepting, usually visualized as double circles.

transitions, usually visualized as directed arches between states, are directed links between states associated with an alphabet letter.

input string, a list of alphabet characters.

A run on the machine begins at the starting state. Each letter of the input string is read; If there is a transition between the current state and another state which corresponds to the letter, the current state is changed to the new state. After the last letter was read, if the current state is an accepting state, the input string is accepted. If the last state was not an accepting state, or a letter had no corresponding arch from a state during the run, the input string is rejected.

Note: This short descruption is far from being a full, formal definition of a FSM; Wikipedia's fine article is a great introduction to the subject.

Example

For example, the following machine tells if a binary number, read from left to right, has an even number of 0s:

The alphabet is the set {0,1}.

The states are S1 and S2.

The transitions are (S1, 0) -> S2, (S1, 1) -> S1, (S2, 0) -> S1 and (S2, 1) -> S2.

The input string is any binary number, including an empty string.

The rules:

Implement a FSM in a language of your choice.

Input

The FSM should accept the following input:

```<code><States>       List of state, separated by space mark.
               The first state in the list is the start state.
               Accepting states begin with a capital letter.
<transitions>  One or more lines.
               Each line is a three-tuple:
               origin state, letter, destination state)
<input word>   Zero or more characters, followed by a newline.
</code>```

For example, the aforementioned machine with 1001010 as an input string, would be written as:

```<code>S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010
</code>```

Output

The FSM's run, written as <State> <letter> -> <state>, followed by the final state. The output for the example input would be:

```<code>S1 1 -> S1
S1 0 -> s2
s2 0 -> S1
S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
s2 0 -> S1
ACCEPT
</code>```

For the empty input '':

```<code>S1
ACCEPT
</code>```

Note: Following your comments, the S1 line (showing the first state) might be omitted, and the following output is also acceptable:

```<code>ACCEPT
</code>```

For 101:

```<code>S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
REJECT
</code>```

For '10X':

```<code>S1 1 -> S1
S1 0 -> s2
s2 X
REJECT
</code>```

Prize

A 250 rep bounty will be given to the shortest solution.

Reference implementation

A reference Python implementation is available here. Note that output requirements have been relaxed for empty-string input.

Addendum

Output format

Following popular demand, the following output is also acceptable for empty input string:

```<code>ACCEPT
</code>```

or

```<code>REJECT
</code>```

Without the first state written in the previous line.

State names

Valid state names are an English letter followed by any number of letters, _ and digits, much like variable names, e.g. State1, state0, STATE_0.

Input format

Like most code golfs, you can assume your input is correct.

Summary of answers:

Cobol - 4078 characters

Python - 171 characters, 568 characters, 203 characters, 218 characters, 269 characters

sed - 137 characters

ruby - 145 characters, 183 characters

Haskell - 192 characters, 189 characters

LISP - 725 characters

Perl - 184 characters

Bash - 184 characters

Rexx - 205 characters

Lua - 356 characters

F# - 420 characters

C# - 356 characters

Mixal - 898 characters

The sed 137 solution is the shortest, ruby 145 is #2. Currently, I can't get the sed solution to work:

```<code>cat test.fsm | sed -r solution.sed
sed -r solution.sed test.fsm
</code>```

both gave me:

```<code>S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010
</code>```0

so unless It there are clarifications the bounty goes to the ruby solution.

答:
Common Lisp - 725

```<code>(defun split (string)
  (loop for i = 0 then (1+ j)
     as j = (position #\Space string :start i)
     collect (subseq string i j)
     while j))

(defun do-fsm ()
  (let* ((lines (loop for l = (read-line *standard-input* nil)
      until (not l)
     collect (split l)))
  (cur (caar lines))
  (transitions (subseq lines 1 (- (length lines) 1))))
    (if (or (loop for c across (caar (last lines))
      do (format t "~a ~a" cur c)
        when (not (loop for tr in transitions
       when (and (equal cur (car tr))
          (equal c (char (cadr tr) 0)))
       return (progn (format t " -> ~a~%"
        (setq cur (caddr tr)))
       t)
         ))
        return t)
     (lower-case-p (char cur 0)))
 (format t "~%REJECT~%")
 (format t "ACCEPT~%"))))
</code>```

No real attempt to minimize the code -- Common Lisp pays a heavy penalty in the required input processing, so I don't think there's much chance of this solution winning :-)

Title: Code Golf: Finite-state machine!

Body:
Finite state machine

A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected. Leaving some formalities aside, A run of a finite state machine is composed of:

alphabet, a set of characters.

states, usually visualized as circles. One of the states must be the start state. Some of the states might be accepting, usually visualized as double circles.

transitions, usually visualized as directed arches between states, are directed links between states associated with an alphabet letter.

input string, a list of alphabet characters.

A run on the machine begins at the starting state. Each letter of the input string is read; If there is a transition between the current state and another state which corresponds to the letter, the current state is changed to the new state. After the last letter was read, if the current state is an accepting state, the input string is accepted. If the last state was not an accepting state, or a letter had no corresponding arch from a state during the run, the input string is rejected.

Note: This short descruption is far from being a full, formal definition of a FSM; Wikipedia's fine article is a great introduction to the subject.

Example

For example, the following machine tells if a binary number, read from left to right, has an even number of 0s:

The alphabet is the set {0,1}.

The states are S1 and S2.

The transitions are (S1, 0) -> S2, (S1, 1) -> S1, (S2, 0) -> S1 and (S2, 1) -> S2.

The input string is any binary number, including an empty string.

The rules:

Implement a FSM in a language of your choice.

Input

The FSM should accept the following input:

<States>       List of state, separated by space mark.
               The first state in the list is the start state.
               Accepting states begin with a capital letter.
<transitions>  One or more lines.
               Each line is a three-tuple:
               origin state, letter, destination state)
<input word>   Zero or more characters, followed by a newline.

For example, the aforementioned machine with 1001010 as an input string, would be written as:

S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010

Output

The FSM's run, written as <State> <letter> -> <state>, followed by the final state. The output for the example input would be:

S1 1 -> S1
S1 0 -> s2
s2 0 -> S1
S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
s2 0 -> S1
ACCEPT

For the empty input '':

S1
ACCEPT

Note: Following your comments, the S1 line (showing the first state) might be omitted, and the following output is also acceptable:

ACCEPT

For 101:

S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
REJECT

For '10X':

S1 1 -> S1
S1 0 -> s2
s2 X
REJECT

Prize

A 250 rep bounty will be given to the shortest solution.

Reference implementation

A reference Python implementation is available here. Note that output requirements have been relaxed for empty-string input.

Addendum

Output format

Following popular demand, the following output is also acceptable for empty input string:

ACCEPT

or

REJECT

Without the first state written in the previous line.

State names

Valid state names are an English letter followed by any number of letters, _ and digits, much like variable names, e.g. State1, state0, STATE_0.

Input format

Like most code golfs, you can assume your input is correct.

Summary of answers:

Cobol - 4078 characters

Python - 171 characters, 568 characters, 203 characters, 218 characters, 269 characters

sed - 137 characters

ruby - 145 characters, 183 characters

Haskell - 192 characters, 189 characters

LISP - 725 characters

Perl - 184 characters

Bash - 184 characters

Rexx - 205 characters

Lua - 356 characters

F# - 420 characters

C# - 356 characters

Mixal - 898 characters

The sed 137 solution is the shortest, ruby 145 is #2. Currently, I can't get the sed solution to work:

cat test.fsm | sed -r solution.sed
sed -r solution.sed test.fsm

both gave me:

sed: -e expression #1, char 12: unterminated `s' command

so unless It there are clarifications the bounty goes to the ruby solution.

Body:
Common Lisp - 725

(defun split (string)
  (loop for i = 0 then (1+ j)
     as j = (position #\Space string :start i)
     collect (subseq string i j)
     while j))

(defun do-fsm ()
  (let* ((lines (loop for l = (read-line *standard-input* nil)
      until (not l)
     collect (split l)))
  (cur (caar lines))
  (transitions (subseq lines 1 (- (length lines) 1))))
    (if (or (loop for c across (caar (last lines))
      do (format t "~a ~a" cur c)
        when (not (loop for tr in transitions
       when (and (equal cur (car tr))
          (equal c (char (cadr tr) 0)))
       return (progn (format t " -> ~a~%"
        (setq cur (caddr tr)))
       t)
         ))
        return t)
     (lower-case-p (char cur 0)))
 (format t "~%REJECT~%")
 (format t "ACCEPT~%"))))

No real attempt to minimize the code -- Common Lisp pays a heavy penalty in the required input processing, so I don't think there's much chance of this solution winning :-)


答:
Besides that ProEvilz already commented about Sql Injection, adding .5 will not magically make it into a date/time format.

Work with the date object (or DateTime class in php5.4+) and for each iteration you use this:

Initial value would be

```<code>$currentTime = "09:00";
$nextTime = date("H:i", strtotime($currentTime ." +30 MINUTE"));
</code>```

$nextTime would be 09:30..

Title: Need a loop to add 30 minutes as a time in HTML

Body:
Besides that ProEvilz already commented about Sql Injection, adding .5 will not magically make it into a date/time format.

Work with the date object (or DateTime class in php5.4+) and for each iteration you use this:

Initial value would be

$currentTime = "09:00";
$nextTime = date("H:i", strtotime($currentTime ." +30 MINUTE"));

$nextTime would be 09:30..


问:
How to bundle Electron application and windows service together?
I am very new with electron application. I need some help with election installation.
I have an Electron desktop application and a windows service.
I can start and stop my pre installed services by using sudo-prompt package.
I am creating windows installer by using electron-winstaller package.
But I want to bundle my windows service along with my electron application. My requirement is when I install my electron package then it should install my service also, when I uninstall my package then that service should be uninstalled.

Please help me out. Any clue, Any suggestions will be appreciated.
If you think this should be achieved with something else then please do suggest me.

答:
Electron's windows installer packager strikes me a specific case tool that would likely hit limitations in scenarios like this.  I would use a general case tool instead such as the Free and Open Source  Windows Installer XML Toolset aka WiX.   I would also use with that another FOSS application called Industrial Strength Windows Installer XML aka IsWiX.

WiX allows you to describe and build MSI databases using an XML/XSD domain specific language.  It supports MSBuild for easy integration with your CI/CD pipeline.   IsWiX* is a set of project templates and graphical designers that provide an opinionated project structuring (scaffolding) and greatly speeds up the learning curve and implementation.   For example, this installer you describe could be done without writing a single line of XML.

For more information see: https://github.com/iswix-llc/iswix-tutorials

The desktop-application and windows-service tutorials should** show you everything you need to know to author this installer.   Basically follow the desktop-application all the way through and then skip to the final portion of the windows-service tutorial where you define the windows service.

I'm the maintainer of IsWiX

** This assumes your service exe is a proper Windows service that interfaces with the windows service control manager.  If it's really just a console app that runs as a service you will need to include a program such as srvany.exe.   This will require one line of hand crafted XML to extended the service definition in the registry with the proper command line value to be passed to your exe.    An example can be found here: Wix installer to replace INSTSRV and SRVANY for user defined service installation


问:
Automatic nexus artifact versioning using Jenkins 2 Jenkinsfile script
I currently have a Jenkins DSL script defining my release pipeline(below). I was wondering if there is a way to automatically increase the version number of the released artifact for every build, so that I can publish it to Nexus with a new unique version number, rather than having to set it manually. I have used a plugin in the past that does this automatically with regular Jenkins jobs but I can't figure out how to do so with the pipeline script.</p>

```<code>node('master') {
       //input 'Proceed?'

       stage 'Checkout'
              checkout scm

       stage 'Build'
              dir('./collector') {
                     sh "./gradlew clean build -Penv=${ENVIRONMENT}"
              }

       stage 'Flyway Migrate'
              dir('./database') {
                     sh "./gradlew flywayMigrate -i -Penv=${ENVIRONMENT}"
              }

       stage 'Run cucumber Tests'
              dir('./collector') {
                     sh "./gradlew cucumber -Penv=${ENVIRONMENT}"
              }

       stage 'Publish artifact to Nexus'
              dir('./collector') {

                withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'NEXUS_PASSWORD',
                    usernameVariable: 'NEXUS_USERNAME', passwordVariable: 'NEXUS_PASSWORD']]) {
                            sh ("./gradlew publish -Pnexus_username=" + env.NEXUS_USERNAME+" -Pnexus_password=" + env.NEXUS_PASSWORD+ " -Penv=${ENVIRONMENT}--stacktrace")
                     }

                  }

           //stage ''
    }
</code>```

答:
You can use the VersionNumberPlugin in your pipeline to set the version number in a highly configurable way.

Dumb example:

```<code>script{
    version = VersionNumber(versionNumberString: '1.0.${BUILDS_ALL_TIME}')
}
</code>```

Body:
I currently have a Jenkins DSL script defining my release pipeline(below). I was wondering if there is a way to automatically increase the version number of the released artifact for every build, so that I can publish it to Nexus with a new unique version number, rather than having to set it manually. I have used a plugin in the past that does this automatically with regular Jenkins jobs but I can't figure out how to do so with the pipeline script.

node('master') {
       //input 'Proceed?'

       stage 'Checkout'
              checkout scm

       stage 'Build'
              dir('./collector') {
                     sh "./gradlew clean build -Penv=${ENVIRONMENT}"
              }

       stage 'Flyway Migrate'
              dir('./database') {
                     sh "./gradlew flywayMigrate -i -Penv=${ENVIRONMENT}"
              }

       stage 'Run cucumber Tests'
              dir('./collector') {
                     sh "./gradlew cucumber -Penv=${ENVIRONMENT}"
              }

       stage 'Publish artifact to Nexus'
              dir('./collector') {

                withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'NEXUS_PASSWORD',
                    usernameVariable: 'NEXUS_USERNAME', passwordVariable: 'NEXUS_PASSWORD']]) {
                            sh ("./gradlew publish -Pnexus_username=" + env.NEXUS_USERNAME+" -Pnexus_password=" + env.NEXUS_PASSWORD+ " -Penv=${ENVIRONMENT}--stacktrace")
                     }

                  }

           //stage ''
    }

Body:
You can use the VersionNumberPlugin in your pipeline to set the version number in a highly configurable way.

Dumb example:

script{
    version = VersionNumber(versionNumberString: '1.0.${BUILDS_ALL_TIME}')
}


问:
How to set metadata in sys_file_metadata for file id in TYPO3 6.2
I try to update the medatadata informations (EXIF) for images in a folder. Via the StorageRepository I can read the metadata from file system. I now want to put the recieved information into the TYPO3 database. I think I found the corresponding mysql table called sys_file_metadata where the informations are stored for each file id.

My question now is, if there are any functions or methods to put the recieved metadata into the database or do I have to put it in via a mysql query?

答:
Just use the datahandler for this. https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Typo3CoreEngine/UsingDataHandler/Index.html

And indeed it's stored in sys_file_metadata


问:
Regular expressions REGEX 4 digits PIN code with at least one different than others
I tried different regex which I found here but they are not working.

for example:

```<code>1111 = false
1112 = true
</code>```

It's my homework so I must do it in regex :)

答:
How about this?

```<code>(?=^\d{4}$)(\d)+(?!\1)\d\d*
</code>```

The first look-ahead group (?=^\d{4}$) insists that the whole string consists of  4 digits.

The first capture group then matches any number of digits: (\d)+.

After this, there must be a digit is different to the first capture group: (?!\1)\d

Finally, there can be any number of digits trailing: \d*

Body:
I tried different regex which I found here but they are not working.

for example:

1111 = false
1112 = true

It's my homework so I must do it in regex :)

Body:
How about this?

(?=^\d{4}$)(\d)+(?!\1)\d\d*

The first look-ahead group (?=^\d{4}$) insists that the whole string consists of  4 digits.

The first capture group then matches any number of digits: (\d)+.

After this, there must be a digit is different to the first capture group: (?!\1)\d

Finally, there can be any number of digits trailing: \d*


问:
How to capture CAAnimation
I want to capture each frame of the animation on CALayer to generate mp4 movie file.

So, I wrote codes below.

frames is total frame number in the animation, frameTime is 1 / 60 second, and animationLayer has already been added on UIImageView.

```<code>for i in 0...(frames - 1) {

    //add the animation on specified frame to the CALayer
    animationGroup.speed = 0
    animationGroup.timeOffset = frameTime * i
    animationLayer.add(animationGroup, forKey: "morph")

    //capture the frame of the animation.
    UIGraphicsBeginImageContextWithOptions(drawView.bounds.size, true, 0.0)
    drawView.drawHierarchy(in: drawView.bounds, afterScreenUpdates: true)
    uiImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    uiImage = globalFunc.resizeUIImage(uiImage, scale, 400)
    cgImage = uiImage.cgImage!

    //add the captured image to movie file.
    movieCreator.create(image: cgImage)

    animationLayer.removeAnimation(forKey: "moprh")
}
</code>```

This code doesn't work.

The image of each frame doesn't display and movie file is created but there's no animation.

I tried DispatchQueue.main.asyc and CAtransition.begin(), .setCompletionBlock, .commit() in the code above, but they didn't work.

What should I do to get what I want?

答:
You should not draw the view hierarchy into the image context. You should instead render the presentation layer like this:

```<code>if let presentationLayer = drawView.layer.presentation() {
    presentationLayer.render(in: context)
}
</code>```

The presentation layer represents the layer's content which is currently drawn on the screen.

Title: How to capture CAAnimation

Body:
I want to capture each frame of the animation on CALayer to generate mp4 movie file.

So, I wrote codes below.

frames is total frame number in the animation, frameTime is 1 / 60 second, and animationLayer has already been added on UIImageView.

for i in 0...(frames - 1) {

    //add the animation on specified frame to the CALayer
    animationGroup.speed = 0
    animationGroup.timeOffset = frameTime * i
    animationLayer.add(animationGroup, forKey: "morph")

    //capture the frame of the animation.
    UIGraphicsBeginImageContextWithOptions(drawView.bounds.size, true, 0.0)
    drawView.drawHierarchy(in: drawView.bounds, afterScreenUpdates: true)
    uiImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    uiImage = globalFunc.resizeUIImage(uiImage, scale, 400)
    cgImage = uiImage.cgImage!

    //add the captured image to movie file.
    movieCreator.create(image: cgImage)

    animationLayer.removeAnimation(forKey: "moprh")
}

This code doesn't work.

The image of each frame doesn't display and movie file is created but there's no animation.

I tried DispatchQueue.main.asyc and CAtransition.begin(), .setCompletionBlock, .commit() in the code above, but they didn't work.

What should I do to get what I want?

Body:
You should not draw the view hierarchy into the image context. You should instead render the presentation layer like this:

if let presentationLayer = drawView.layer.presentation() {
    presentationLayer.render(in: context)
}

The presentation layer represents the layer's content which is currently drawn on the screen.


问:
How to handle the value I get from a HashMap
I want my getv() function return the value from a HashMap. I get errors no matter how I modify my code:

```<code>enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    Env: HashMap<char, Type>,
}
impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.Env.insert(name, ty);
    }

    fn getv(self, name: char) -> Type {
        match self.Env.get(&name) {
            Some(Type) => Type, // <------- Always error here
            None => Type::TyInt,
        }
    }
}
</code>```

答:
You don't have to make your type Copy or Clone ... if you're happy working with the reference.

When things like this pop up while writing Rust, its generally best to re-evaluate how you're calling the code. Can it be made simpler?

You can either have the caller expect the Option<&V>, or just force something out... perhaps like this:

```<code>fn getv(&self, name: char) -> &Type {
    self.env.get(&name).unwrap_or(&Type::TyInt)
}
</code>```

This simplifies your code and makes it pretty clear what you're after. Here it is in action:

```<code>use std::collections::HashMap;

#[derive(Debug)]
enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    env: HashMap<char, Type>,
}

impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.env.insert(name, ty);
    }

    fn getv(&self, name: char) -> &Type {
        self.env.get(&name).unwrap_or(&Type::TyInt)
    }
}

fn main() {
    let mut te = TypeEnv {
        env: HashMap::new(),
    };
    {
        let arg = te.getv('c');

        println!("{:?}", arg); // "TyInt" - because nothing was found
    }

    te.set('c', Type::TyBool);

    let arg = te.getv('c'); // "TyBool" - because we stored it in the line above.

    println!("{:?}", arg);
}
</code>```

Also, your existing implementation of getv takes ownership of self ... notice how I added the reference getv(&self). If you don't have this, this type (as far as I can tell) becomes basically useless.

Body:
I want my getv() function return the value from a HashMap. I get errors no matter how I modify my code:

enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    Env: HashMap<char, Type>,
}
impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.Env.insert(name, ty);
    }

    fn getv(self, name: char) -> Type {
        match self.Env.get(&name) {
            Some(Type) => Type, // <------- Always error here
            None => Type::TyInt,
        }
    }
}

Body:
You don't have to make your type Copy or Clone ... if you're happy working with the reference.

When things like this pop up while writing Rust, its generally best to re-evaluate how you're calling the code. Can it be made simpler?

You can either have the caller expect the Option<&V>, or just force something out... perhaps like this:

fn getv(&self, name: char) -> &Type {
    self.env.get(&name).unwrap_or(&Type::TyInt)
}

This simplifies your code and makes it pretty clear what you're after. Here it is in action:

use std::collections::HashMap;

#[derive(Debug)]
enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    env: HashMap<char, Type>,
}

impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.env.insert(name, ty);
    }

    fn getv(&self, name: char) -> &Type {
        self.env.get(&name).unwrap_or(&Type::TyInt)
    }
}

fn main() {
    let mut te = TypeEnv {
        env: HashMap::new(),
    };
    {
        let arg = te.getv('c');

        println!("{:?}", arg); // "TyInt" - because nothing was found
    }

    te.set('c', Type::TyBool);

    let arg = te.getv('c'); // "TyBool" - because we stored it in the line above.

    println!("{:?}", arg);
}

Also, your existing implementation of getv takes ownership of self ... notice how I added the reference getv(&self). If you don't have this, this type (as far as I can tell) becomes basically useless.


问:
JSON - Unable to parse
I am unable to parse the following piece.
Please let me know if you have any clue(s)</p>

```<code><HTML>
<HEAD>
<SCRIPT>
var s = '{"CCMP_11":{"QuestionText":"\u003cp\u003eFor all inputs received, automated sanity checks with the last cycle data are performed and QC of control totals are conducted.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_11","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":2.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_20":{"QuestionText":"\u003cp\u003eAll client deliverable reports / files (interim and final) containing compliance sensitive data are clearly marked with requisite compliance circulation warning before sharing with the client.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_20","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.25,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_21":{"QuestionText":"\u003cp\u003eAll system changes and QC results are reviewed by a senior team member. Review comments are incorporated and rerun test results are shared with the project manager and formal sign off is taken.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_21","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_6":{"QuestionText":"\u003cp\u003eNo parallel tools (eg. Deconstructor tool) are used for QC and automated QCs are established for any deliverable\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_6","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.25,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_12":{"QuestionText":"\u003cp\u003eAll the Javelin-to-Javelin integrations are in place as a precursor to implementing Next Gen Sales Compensation (NGSC)\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_12","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":2.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_29":{"QuestionText":"\u003cp\u003eError-free runs are celebrated and team achievements are recognized at least once a quarter.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_29","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.66667,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_18":{"QuestionText":"\u003cp\u003eResponsibilities are clearly defined and accountability is created within the team as to who will implement and who will check the compliance aspects.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_18","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Implemented, but not doing consistently","Answer":4,"OverallMean":3.5,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_4":{"QuestionText":"\u003cp\u003eStandard reusable templates are created for deliverables and/or communication that are shared with the client on a regular basis:\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_4","CheckBoxListItems":"E-mail templates||||Minutes of Meeting||||Status Updates||||Adhoc/Change Request Form","CheckBoxListLabels":"1||||2||||3||||4","CheckBoxes":null,"CheckBoxResponseCodes":"1,3","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.6,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_3":{"QuestionText":"\u003cp\u003eParameterization: All Ad-hoc Inputs to the system have a placeholder within the system and are handled through data inputs (e.g. consuming adjustment blocks for sales,  goal adjustment, payout adjustment, eligibility exceptions,   product weights, report metrics, plan parameters)\u003c/p\u003e\u003cp\u003eA list of all use cases that need system changes during or between operations is maintained by the project and is being worked with JPS team for building the same within the system.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_3","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.5,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_8":{"QuestionText":"\u003cp\u003eThe Individual who runs operations does NOT have access to make system changes ( e.g. data structure change, business rule change, procedure change, report template change, etc.)\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_8","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":2.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CRM_4":{"QuestionText":"\u003cp\u003eAn internal ZS approval and a formal client sign-off on the scope of all change requests and the revised timelines (if any) is obtained, as per the ChaRM framework.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_4","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.16667,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"CRM_5":{"QuestionText":"\u003cp\u003ePeer reviews are formally planned and conducted for all changes. All outcomes are documented and action items tracked until completion.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_5","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.33333,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"CRM_1":{"QuestionText":"\u003cp\u003e* All changes impacting the creation or change of business rules are documented in accordance with the Change Request Management (ChaRM) framework and have the following sections:\u003c/p\u003e\u003cp\u003e\u003col\u003e\u003cli\u003eChange description\u003c/li\u003e\u003cli\u003eImpacted deliverables\u003c/li\u003e\u003cli\u003eBusiness use cases and expected results\u003c/li\u003e\u003cli\u003eChange details for inputs, process and output sections along with assumptions\u003c/li\u003e\u003cli\u003eInput/output mockups indicating changes for all business cases\u003c/li\u003e\u003cli\u003eRisks, if any\u003c/li\u003e\u003cli\u003eCosts, if any\u003c/li\u003e\u003c/ol\u003e\u003c/p\u003e\u003cp\u003eClear owner(s) are identified who will be accountable for tracking all requirement/business rule change decisions and documenting them properly.\u003c/p\u003e \u003cp\u003eClick here to understand ChaRM framework in detail.\u003cbr /\u003e\u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-43529\"\u003ehttps://zspace.zsassociates.com/docs/DOC-43529\u003c/a\u003e\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_1","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.16667,"SectionName":"Change Request Management","IsChecked":true,"SectionId":3},"CRM_2":{"QuestionText":"\u003cp\u003eOnTrak/ client tool or Excel template is used by the project team and/or client to implement a structured review-approve process for:\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"\u003cp\u003eFollowing parameters should be added for each ticket - Complexity, Business impact, process impact, scope, ownerships, impact on deliverables, testing and functional design, timelines, business context.\u003c/p\u003e \u003cp\u003e\u003ca target=_blank href = \"https://zspace.zsassociates.com/docs/DOC-45596\"\u003eClick here\u003c/a\u003e to see the OnTrak guides on ZSpace.\u003c/p\u003e","QuestionId":"CRM_2","CheckBoxListItems":"Observed defects, enhancements, issues, rework, Adhocs and operational items||||Changes of Business rules||||Change requests and operations related items (e.g. approvals, confirmations, Input notification, etc.)","CheckBoxListLabels":"1||||2||||3","CheckBoxes":null,"CheckBoxResponseCodes":"2","AnswerText":"Implemented, but not doing consistently","Answer":4,"OverallMean":3.66667,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"CRM_3":{"QuestionText":"\u003cp\u003eA comprehensive impact analysis of change requests is conducted using Data Flow Diagrams (DFDs) and documented. A template capturing the impact of all change requests and associated dependencies is maintained internally by the team.\u003c/p\u003e\u003cp\u003ePlease refer to the ChaRM framework for the template:\u003cbr /\u003e\u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-43529\"\u003ehttps://zspace.zsassociates.com/docs/DOC-43529\u003c/a\u003e\u003cp\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_3","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Implementation in progress","Answer":3,"OverallMean":3.83333,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"PM_3":{"QuestionText":"\u003cp\u003e* Cross-work stream trainings are planned and imparted to team members.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_3","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":2.75,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_5":{"QuestionText":"\u003cp\u003eAll the project team members are provided in the moment/immediate feedback by applying the COIN framework. The channels leveraged include email, informal/formal meeting or ZS COIN app.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_5","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.33333,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_7":{"QuestionText":"\u003cp\u003eThe EVOLVE program sheet is maintained for all team roles and is used for team reviews and role discussions with team members.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_7","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.33333,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_4":{"QuestionText":"\u003cp\u003e* Backup and succession planning is done periodically (at least each semester) and well documented. The team structure and upcoming resource needs are also reviewed as a part of the same.\u003c/p\u003e\u003cp\u003eClick on the link below to see sample documents on ZSpace\u003cbr /\u003e \u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-45693\"\u003ehttps://zspace.zsassociates.com/docs/DOC-45693\u003c/a\u003e\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_4","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":4,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_6":{"QuestionText":"\u003cp\u003eThe project Consultant/Manager has a formal one on one discussion with each team member at least once a quarter.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_6","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.66667,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_8":{"QuestionText":"\u003cp\u003eThe project manager sets specific short and long-term goals for each individual for each review period.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_8","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_2":{"QuestionText":"\u003cp\u003e* A training, transition \u0026 onboarding plan is setup for the project which includes a list of courses that each team member should take and is consistently followed for all project onboardings.\u003cp\u003e\u003c/p\u003eThe training, transition and onboarding plans should also cover:\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"\u003cp\u003eClick on the link below to see sample documents on ZSpace \u003cbr /\u003e\u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-45692\"\u003ehttps://zspace.zsassociates.com/docs/DOC-45692\u003c/a\u003e\u003c/p\u003e","QuestionId":"PM_2","CheckBoxListItems":"Client Business context and team structure||||Business rules||||Project SOW and noteworthy Work orders/Change requests||||Process Visio Diagrams for system overview and detailed sections||||Project Calendar||||SLA details||||System Access setup||||System inputs||||System setup including Javelin Suite||||Deliverables||||Tools","CheckBoxListLabels":"1||||2||||3||||4||||5||||6||||7||||8||||9||||10||||11","CheckBoxes":null,"CheckBoxResponseCodes":"1,2","AnswerText":"Implementation in progress","Answer":3,"OverallMean":3.5,"SectionName":"People Management","IsChecked":false,"SectionId":6}}';
var v = JSON.parse(s);
</SCRIPT>
</HEAD>
<body>
TESTING JSON
</BODY>
</HTML>
</code>```

答:
Thanks for the inputs but I found a way to solve this</p>

```<code><JsonObj> = Json(<strForJson>.Replace("/\u0000/g", ""), "string", JsonRequestBehavior.AllowGet);
</code>```

Title: JSON - Unable to parse

Body:
I am unable to parse the following piece.
Please let me know if you have any clue(s)

TESTING JSON

Body:
Thanks for the inputs but I found a way to solve this

<JsonObj> = Json(<strForJson>.Replace("/\u0000/g", ""), "string", JsonRequestBehavior.AllowGet);