问:
Python: How to zip a file on the fly while uploading it to SFTP?
How to upload a file to SFTP server while zipping it on the fly.

Or in other words, how to take a local file, zip it and upload it to SFTP server at the same time.

答:
I found a solution using GzipFile writer and provide it fileObject that I use as a spy to get the data without actually writing to a file.

Then I yield the results from it right into a queue, that I build on other thread.

Long story short here is the code

Usage

```<code>sftp.putfo(ReaderMaker(unzipped_file_path), remote_path)
</code>```

Implementation

```<code>COMPRESS_LEVEL = 9
BUFF_SIZE = 1024 * 1024

class ReaderMaker:
    def __init__(self, inputFile):
        self.it = self.compressor(inputFile)
        self.queue = Queue.Queue(10)
        task = Thread(target=self.zipper)
        task.start()

    def zipper(self):
        while True:
            try:
                data = self.it.next()
                while len(data) == 0:
                    data = self.it.next()
                self.queue.put(data)
            except StopIteration:
                break
        self.queue.put('')  # this will notify the last item read

    def read(self, n):
        return self.queue.get()

    def compressor(self, inputFile):
        class Spy:
            def __init__(self):
                self.data = ''

            def write(self, d):
                self.data = self.data + d

            def flush(self):
                d = self.data
                self.data = ''
                return d

        f_in = open(inputFile, 'rb')
        spy = Spy()

        f_out = GzipFile('dummy.gz', 'wrb+', COMPRESS_LEVEL, spy)

        while True:
            data = f_in.read(BUFF_SIZE)
            if len(data) == 0:
                break
            f_out.write(data)
            yield spy.flush()

        f_out.close()
        f_in.close()
        yield spy.flush()
</code>```

Body:
I found a solution using GzipFile writer and provide it fileObject that I use as a spy to get the data without actually writing to a file.

Then I yield the results from it right into a queue, that I build on other thread.

Long story short here is the code

Usage

sftp.putfo(ReaderMaker(unzipped_file_path), remote_path)

Implementation

COMPRESS_LEVEL = 9
BUFF_SIZE = 1024 * 1024

class ReaderMaker:
    def __init__(self, inputFile):
        self.it = self.compressor(inputFile)
        self.queue = Queue.Queue(10)
        task = Thread(target=self.zipper)
        task.start()

    def zipper(self):
        while True:
            try:
                data = self.it.next()
                while len(data) == 0:
                    data = self.it.next()
                self.queue.put(data)
            except StopIteration:
                break
        self.queue.put('')  # this will notify the last item read

    def read(self, n):
        return self.queue.get()

    def compressor(self, inputFile):
        class Spy:
            def __init__(self):
                self.data = ''

            def write(self, d):
                self.data = self.data + d

            def flush(self):
                d = self.data
                self.data = ''
                return d

        f_in = open(inputFile, 'rb')
        spy = Spy()

        f_out = GzipFile('dummy.gz', 'wrb+', COMPRESS_LEVEL, spy)

        while True:
            data = f_in.read(BUFF_SIZE)
            if len(data) == 0:
                break
            f_out.write(data)
            yield spy.flush()

        f_out.close()
        f_in.close()
        yield spy.flush()


来源: stackexchange

问:
How to create a PDF-out-of-Sphinx-documentation-tool
Followed this link to try and generate pdf from Sphinx:

https://www.quora.com/How-to-create-a-PDF-out-of-Sphinx-documentation-tool

```<code>$ sphinx-build -b pdf source build/pdf

Error: Cannot find source directory  `/Users/seb/mydocs/source'.

$ make all-pdf
make: *** No rule to make target `all-pdf'.  Stop.
$ make pdf
make: *** No rule to make target `pdf'.  Stop.
</code>```

Since tried in OSX:

```<code>$ conda install -c dfroger rst2pdf=0.93
Fetching package metadata .........
Solving package specifications: .
Error: Package missing in current osx-64 channels:
  - rst2pdf 0.93*
</code>```

You can search for packages on anaconda.org with

```<code>anaconda search -t conda rst2pdf
</code>```

EDIT:

After pip install rst2pdf

```<code>install rst2pdf
register rst2pdf in your conf.py Sphinx config
extensions = ['sphinx.ext.autodoc','rst2pdf.pdfbuilder']
</code>```

But adding 'rst2pdf.pdfbuilder' causes

```<code>Extension error:
Config value 'math_number_all' already present
make: *** [html] Error 1

$ sphinx-build -bpdf sourcedir outdir
</code>```

But what do I specify as sourcedir and outdir? Example please.

EDIT:

Now after make html

and then:

```<code> $ rst2pdf index.rst output.pdf
 index.rst:14: (ERROR/3) Unknown directive type "toctree".

 .. toctree::

 :maxdepth: 2
</code>```

introduction
   tutorial
   multiple_jobs
   deployment
   project

```<code>index.rst:26: (ERROR/3) Unknown interpreted text role "ref".
index.rst:27: (ERROR/3) Unknown interpreted text role "ref".
index.rst:28: (ERROR/3) Unknown interpreted text role "ref".
</code>```

Also:

```<code>$rst2pdf.py index.rst -o mydocument.pdf
</code>```

Does produce a mydocument.pdf but completely different from html and toc to all the pages are not even there?

Image of pdf verse HTML same page

答:
I have succeeded in generating a PDF file for the DevStack document by following the configuration changes in this link:

Here are the steps:

Edit your conf.py (edit or append values)

```<code>extensions = ['rst2pdf.pdfbuilder']
pdf_documents = [('index', u'rst2pdf', u'Sample rst2pdf doc', u'Your Name'),]
</code>```

Install the "rst2pdf" if necessary

```<code>pip install rst2pdf
</code>```

Build the PDF file like this:

```<code>sphinx-build -b pdf doc/source doc/build
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Followed this link to try and generate pdf from Sphinx:

https://www.quora.com/How-to-create-a-PDF-out-of-Sphinx-documentation-tool

$ sphinx-build -b pdf source build/pdf

Error: Cannot find source directory  `/Users/seb/mydocs/source'.

$ make all-pdf
make: *** No rule to make target `all-pdf'.  Stop.
$ make pdf
make: *** No rule to make target `pdf'.  Stop.

Since tried in OSX:

$ conda install -c dfroger rst2pdf=0.93
Fetching package metadata .........
Solving package specifications: .
Error: Package missing in current osx-64 channels:
  - rst2pdf 0.93*

You can search for packages on anaconda.org with

anaconda search -t conda rst2pdf

EDIT:

After pip install rst2pdf

install rst2pdf
register rst2pdf in your conf.py Sphinx config
extensions = ['sphinx.ext.autodoc','rst2pdf.pdfbuilder']

But adding 'rst2pdf.pdfbuilder' causes

Extension error:
Config value 'math_number_all' already present
make: *** [html] Error 1

$ sphinx-build -bpdf sourcedir outdir

But what do I specify as sourcedir and outdir? Example please.

EDIT:

Now after make html

and then:

 $ rst2pdf index.rst output.pdf
 index.rst:14: (ERROR/3) Unknown directive type "toctree".

 .. toctree::

 :maxdepth: 2

introduction
   tutorial
   multiple_jobs
   deployment
   project

index.rst:26: (ERROR/3) Unknown interpreted text role "ref".
index.rst:27: (ERROR/3) Unknown interpreted text role "ref".
index.rst:28: (ERROR/3) Unknown interpreted text role "ref".

Also:

$rst2pdf.py index.rst -o mydocument.pdf

Does produce a mydocument.pdf but completely different from html and toc to all the pages are not even there?

Image of pdf verse HTML same page

Body:
I have succeeded in generating a PDF file for the DevStack document by following the configuration changes in this link:

Here are the steps:

Edit your conf.py (edit or append values)

extensions = ['rst2pdf.pdfbuilder']
pdf_documents = [('index', u'rst2pdf', u'Sample rst2pdf doc', u'Your Name'),]

Install the "rst2pdf" if necessary

pip install rst2pdf

Build the PDF file like this:

sphinx-build -b pdf doc/source doc/build

ContentLicense: CC BY-SA 4.0


问:
Chef - add/change a line in a file
I'm new to Chef / Kitchen. I'd like to change a line in a file on the target VM, such like /etc/sudoers - change Defaults ....

That means, I don't want to use template which would overwrite the file - I want to retain the other content of the file.

Ideally I would like some action like this:

```<code>file_changeLine '/path/to/file/' do
    prefix: "Defaults .*"
end
</code>```

Is there something such? I haven't found in docs. Maybe there are some additional repositories with community-made actions?

答: We really don't recommend this kind of management structure, but if you must, look at the poise-file and line cookbooks on Supermarket. They provide resource-based interfaces for delta updates. Just be aware that this will need a lot of care and feeding as it leads to generally brittle code.

Title: Chef - add/change a line in a file

Body:
I'm new to Chef / Kitchen. I'd like to change a line in a file on the target VM, such like /etc/sudoers - change Defaults ....

That means, I don't want to use template which would overwrite the file - I want to retain the other content of the file.

Ideally I would like some action like this:

file_changeLine '/path/to/file/' do
    prefix: "Defaults .*"
end

Is there something such? I haven't found in docs. Maybe there are some additional repositories with community-made actions?


问:
How does ASP.NET and IIS transform an  tag turn into an image file in the browser?
How does ASP.NET and IIS transform an  tag turn into an image file in the browser?

I am assuming that it locates the file based on the path and renders a FileStream.  I don't see any handlers registered in web.config and my IIS6 configuration doesn't have anything about .jpg, .gif, .png, etc. extensions.

Edit:
Also, how can this process be customized?

答:
The browser sends a request for /path/to/page/localresource.jpg.

IIS finds the file, looks up the MIME type for .jpg in its default MIME-type mapping, and serves the file.

Neither ASP.Net nor the .Net framework are involved.  (unless you set them to be)

ContentLicense: CC BY-SA 2.5

Title: How does ASP.NET and IIS transform an <img src="localresource.jpg"> tag turn into an image file in the browser?


问:
Rails Render Index with URL Parameters
At my work, we are in the middle of breaking up our Rails monolith. We are currently serving our react app through the asset pipeline. I am implementing JWT for authentication. I am trying to pass the token in the url without using sessions/cookies as part of an admin impersonating a user.

```<code>class ReactPagesController < ApplicationController
  def index
    render :index #this will open up the react app
  end
end
</code>```

Is it possible to render a view and pass along parameters in the url?

I want this to open up the index page with url parameter (i.e. localhost:4000/users?jwt=abc.def.ghi

I've tried doing something like render :index, jwt: abc.def.ghi, but that doesn't work. Is the only way to do this via redirect_to?

答:
You are actually defining a redirection:

You want to go to localhost:4000/users

The page display the index page, and URL becomes localhost:4000/users?id=123

For the normal webpage, changing URL will make the browser redirect. As you can see the result when executing this JS in the Chrome Console:

```<code>window.location.href = "google.com"
</code>```

the browser will redirect you to google.com

So, for a Rails's application, you should do a redirection by redirect_to to achieve the current needs.

However, if you really want to change the URL without redirection, you can do it via Javascript. Just use window.history to change your URL

Your controller:

```<code># app/controllers/users_controller.rb
def index
  @desired_id = 123
end
</code>```

and your view

```<code><%-# app/views/users/index.html.erb %>
<!-- rest of HTML -->
<script>
  window.history.pushState("", "", "?id=<%= j @desired_id %>");
</script>
</code>```

Title: Rails Render Index with URL Parameters

Body:
At my work, we are in the middle of breaking up our Rails monolith. We are currently serving our react app through the asset pipeline. I am implementing JWT for authentication. I am trying to pass the token in the url without using sessions/cookies as part of an admin impersonating a user.

class ReactPagesController < ApplicationController
  def index
    render :index #this will open up the react app
  end
end

Is it possible to render a view and pass along parameters in the url?

I want this to open up the index page with url parameter (i.e. localhost:4000/users?jwt=abc.def.ghi

I've tried doing something like render :index, jwt: abc.def.ghi, but that doesn't work. Is the only way to do this via redirect_to?

Body:
You are actually defining a redirection:

You want to go to localhost:4000/users

The page display the index page, and URL becomes localhost:4000/users?id=123

For the normal webpage, changing URL will make the browser redirect. As you can see the result when executing this JS in the Chrome Console:

window.location.href = "google.com"

the browser will redirect you to google.com

So, for a Rails's application, you should do a redirection by redirect_to to achieve the current needs.

However, if you really want to change the URL without redirection, you can do it via Javascript. Just use window.history to change your URL

Your controller:

# app/controllers/users_controller.rb
def index
  @desired_id = 123
end

and your view

<%-# app/views/users/index.html.erb %>
<!-- rest of HTML -->
<script>
  window.history.pushState("", "", "?id=<%= j @desired_id %>");
</script>


问:
Repetitive sublayout - How can I make it unique - to meet ADA requirements
I have a search box that is loaded twice - once for desktop and once for mobile.

Device determines which is displayed. However, due to ADA, the labeling needs to be unique.

Is there a way to call the sublayout and generate unique tag for each of the html elements to use?

Or, is there a way to generate a tag within the sublayout to ensure the tags are unique.

```<code><div id="desktop">
<sc:Sublayout Path="~/site/sublayouts/Shared/QuickSearch.ascx" runat="server" />
</div>
<div id="mobile-search" class="hidden">
<sc:Sublayout Path="~/site/sublayouts/Shared/QuickSearch.ascx" runat="server" />
</div>
</code>```

----------- within the layout

```<code><div class="searchtool">
<img src="/includes/images/search.png" alt="Search" style="float:left"/>
<div style="float:left">
<fieldset class="search"  aria-labelledby="Name">
</code>```

The alt and aria-labelledby tags need to be unique.

Thanks

答:
Just an idea, pass the device as a parameter and make the label e.g. "search-desktop" or "search-mobile".

See here for details - http://imjo.hn/2012/02/23/passing-properties-into-sitecore-sublayouts/

```<code><sc:Sublayout Path="~/site/sublayouts/Shared/QuickSearch.ascx" runat="server"
 Parameters="device=mobile" />

<img src="/includes/images/search.png" alt="Search-<%=GetParameter("device") %>" style="float:left"/>
</code>```

Here's the helper functions mentioned in that article.

```<code>private NameValueCollection _ParameterCollection;
public NameValueCollection ParameterCollection
{
    get
    {
        if (_ParameterCollection == null)
        {
            _ParameterCollection = new NameValueCollection();
            string[] parameters = (Parent as Sublayout).Parameters.Split('&');
            string[] pair;
            foreach (string paramPair in parameters)
            {
                pair = paramPair.Split('=');
                _ParameterCollection.Add(pair[0], pair[1]);
            }
        }
        return _ParameterCollection;
    }
}

public string GetParameter(string key)
{
    string value = String.Empty;
    string parameterValue = ParameterCollection.Get(key);
    if (parameterValue != null)
    {
        value = parameterValue;
    }
    return value;
}
</code>```

Body:
I have a search box that is loaded twice - once for desktop and once for mobile.

Device determines which is displayed. However, due to ADA, the labeling needs to be unique.

Is there a way to call the sublayout and generate unique tag for each of the html elements to use?

Or, is there a way to generate a tag within the sublayout to ensure the tags are unique.

<sc:Sublayout Path="~/site/sublayouts/Shared/QuickSearch.ascx" runat="server" />

<sc:Sublayout Path="~/site/sublayouts/Shared/QuickSearch.ascx" runat="server" />

----------- within the layout

<fieldset class="search"  aria-labelledby="Name">

The alt and aria-labelledby tags need to be unique.

Thanks

Body:
Just an idea, pass the device as a parameter and make the label e.g. "search-desktop" or "search-mobile".

See here for details - http://imjo.hn/2012/02/23/passing-properties-into-sitecore-sublayouts/

<sc:Sublayout Path="~/site/sublayouts/Shared/QuickSearch.ascx" runat="server"
 Parameters="device=mobile" />

<img src="/includes/images/search.png" alt="Search-<%=GetParameter("device") %>" style="float:left"/>

Here's the helper functions mentioned in that article.

private NameValueCollection _ParameterCollection;
public NameValueCollection ParameterCollection
{
    get
    {
        if (_ParameterCollection == null)
        {
            _ParameterCollection = new NameValueCollection();
            string[] parameters = (Parent as Sublayout).Parameters.Split('&');
            string[] pair;
            foreach (string paramPair in parameters)
            {
                pair = paramPair.Split('=');
                _ParameterCollection.Add(pair[0], pair[1]);
            }
        }
        return _ParameterCollection;
    }
}

public string GetParameter(string key)
{
    string value = String.Empty;
    string parameterValue = ParameterCollection.Get(key);
    if (parameterValue != null)
    {
        value = parameterValue;
    }
    return value;
}


问:
How to know if a Javascript Callback is Synchronous or Asynchronous?

Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

```<code>$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});
</code>```

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

答:
A callback is a function that will get executed once an Asynchronous process is completed. Let's say we have an object person with the following data.

```<code>var person = {
 id: 1034
 name: 'Julio',
 age: 23,
 moneyInBank: 0
}
</code>```

We want to get the the moneyInBank for this person but we don't have access to that information in our local environment. We need to get it from a database in another server, this could take a while depending internet connection, optimization, etc.

getMoneyInBank(person.id, callback) is going to go over that process and fetch the information we need. If we were to run the next script without the callback.

```<code>getMoneyInBank(person.id);
console.log(person.money);
</code>```

We will get 0 in the output because getMoneyInBank has not finished by the time the log is executed. If we want to make sure we will print meaningful information we need to change our code to something like this.

```<code>getMoneyInBank(persion.id, function(){
  console.log(person.money);
});
</code>```

Using a callback the log only is going to be called when getMoneyInBank finishes.

Body:
Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

Body:
A callback is a function that will get executed once an Asynchronous process is completed. Let's say we have an object person with the following data.

var person = {
 id: 1034
 name: 'Julio',
 age: 23,
 moneyInBank: 0
}

We want to get the the moneyInBank for this person but we don't have access to that information in our local environment. We need to get it from a database in another server, this could take a while depending internet connection, optimization, etc.

getMoneyInBank(person.id, callback) is going to go over that process and fetch the information we need. If we were to run the next script without the callback.

getMoneyInBank(person.id);
console.log(person.money);

We will get 0 in the output because getMoneyInBank has not finished by the time the log is executed. If we want to make sure we will print meaningful information we need to change our code to something like this.

getMoneyInBank(persion.id, function(){
  console.log(person.money);
});

Using a callback the log only is going to be called when getMoneyInBank finishes.


问:
How to debug javascript promises?
I am trying to understand how to debug asynchronous code that is based on promises. By Promises I mean ECMAScript 6 based promises and by debugging I mean using the built-in chrome or firefox debugger.

What I am having trouble with - is that when an error occurs I can't seem to get the stack trace no matter how I 'reject' it.

I tried these:

```<code>console.log(new Error('Error occured'));
throw new Error('Throwing an Error');
return new Error('Error returned by the onRejected function');
reject(new Error('Pass Error to the reject function'));
</code>```

But none of those returns the actual error in the code, or the stack trace.

So my question is - how to properly debug javascript Promises?

答:
The best way to debug promised is to listen to unhandledRejection event of your process.

For example, here is how you might set it up and dump a stack trace...

```<code> process.on('unhandledRejection', (reason, p) => {
   console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
   // Stack Trace
   console.log(reason.stack);
 });
</code>```

Title: How to debug javascript promises?

Body:
I am trying to understand how to debug asynchronous code that is based on promises. By Promises I mean ECMAScript 6 based promises and by debugging I mean using the built-in chrome or firefox debugger.

What I am having trouble with - is that when an error occurs I can't seem to get the stack trace no matter how I 'reject' it.

I tried these:

console.log(new Error('Error occured'));
throw new Error('Throwing an Error');
return new Error('Error returned by the onRejected function');
reject(new Error('Pass Error to the reject function'));

But none of those returns the actual error in the code, or the stack trace.

So my question is - how to properly debug javascript Promises?

Body:
The best way to debug promised is to listen to unhandledRejection event of your process.

For example, here is how you might set it up and dump a stack trace...

 process.on('unhandledRejection', (reason, p) => {
   console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
   // Stack Trace
   console.log(reason.stack);
 });


问:
Best way for insert data (data type image )
I have use  query  fir insert ( insert into )
Other table other database table inclusive  (data type image ) is size table 150 Gb

 Now fast way for  insert

sql server 2014

答:
i use this for insert 500,000,000 rows from a table to another table in another database .

```<code>    declare @counter int=100
    while 1=1
    begin
        set @counter=@counter-1
        declare @maxid long=isnull((select top(1) id from destinationTable),0)
        insert into destinationTable
           select top(50000) * from sourceTable where id>@maxid
        if @@rowcount=0 or @counter<0
           break
    end
</code>```

50000 has been selected after test Several numbers . it is best for this table .

for another table this number is 500000 , it depends on the table.

tip

my source database was alive.

destination database in a weak

@counter is for avoid grow up log file

this query run as job

i think if your databases is not alive , you have more choices

Body:
i use this for insert 500,000,000 rows from a table to another table in another database .

    declare @counter int=100
    while 1=1
    begin
        set @counter=@counter-1
        declare @maxid long=isnull((select top(1) id from destinationTable),0)
        insert into destinationTable
           select top(50000) * from sourceTable where id>@maxid
        if @@rowcount=0 or @counter<0
           break
    end

50000 has been selected after test Several numbers . it is best for this table .

for another table this number is 500000 , it depends on the table.

tip

my source database was alive.

destination database in a weak

@counter is for avoid grow up log file

this query run as job

i think if your databases is not alive , you have more choices


问:
Bulk with Concat (Upload all images from a folder)
I'm having a little bit of trouble with the function Bulk, I'm not sure how to do it. So, I need to upload all the images that I have in one folder into one table, I can upload 1 image with the next code:

```<code>Insert into ImageTest(ID, Imagen)
SELECT 'SQL Server Image', *
FROM OPENROWSET (BULK N'C:\Users\G11904\Pictures\Students\0001.PNG', SINGLE_BLOB) image;
</code>```

ImageTest only has 2 columns, ID which is an NVARCHAR. The ID is going to save the name of the image. Imagen is an Varbinary, which is where I'm going to store my image.

I have ten images on my folder right now (Later on I will have like a thousand images).

My folder where I have all my images:

So I try the next code to try to store all the images:

```<code>DECLARE @cnt INT = 0;
DECLARE @cntImage INT = 1;
WHILE @cnt < 3000
BEGIN
Insert into ImageTest(ID, Imagen)
SELECT 'SQL Server Image', *
FROM OPENROWSET (BULK CONCAT(N'C:\Users\G11904\Pictures\Students\000', @cntImage, '.PNG'), SINGLE_BLOB) image;
SET @cntImage = @cntImage + 1
END
</code>```

But I'm getting this error:

Incorrect syntax near CONCAT.

Can someone help to try and solve this issue? I'm not sure what I'm doing wrong.

答:
Try to use dynamic query;

```<code>DECLARE @cnt INT = 0;
DECLARE @cntImage INT = 1;
declare @query nvarchar(1000)
declare @imagePath nvarchar(1000)
WHILE @cnt < 3000
BEGIN
set @imagePath  = CONCAT(N'C:\Users\G11904\Pictures\Students\000', @cntImage, '.PNG')
set @query =
    'Insert into ImageTest(ID, Imagen)
    SELECT ''SQL Server Image'', *
    FROM OPENROWSET (BULK '''+@imagePath+''', SINGLE_BLOB) image; '
    print @query
    exec sp_executesql @query
    SET @cntImage = @cntImage + 1
END
</code>```

OPENROWSET expects string. You can't pass a variable.

Body:
I'm having a little bit of trouble with the function Bulk, I'm not sure how to do it. So, I need to upload all the images that I have in one folder into one table, I can upload 1 image with the next code:

Insert into ImageTest(ID, Imagen)
SELECT 'SQL Server Image', *
FROM OPENROWSET (BULK N'C:\Users\G11904\Pictures\Students\0001.PNG', SINGLE_BLOB) image;

ImageTest only has 2 columns, ID which is an NVARCHAR. The ID is going to save the name of the image. Imagen is an Varbinary, which is where I'm going to store my image.

I have ten images on my folder right now (Later on I will have like a thousand images).

My folder where I have all my images:

So I try the next code to try to store all the images:

DECLARE @cnt INT = 0;
DECLARE @cntImage INT = 1;
WHILE @cnt < 3000
BEGIN
Insert into ImageTest(ID, Imagen)
SELECT 'SQL Server Image', *
FROM OPENROWSET (BULK CONCAT(N'C:\Users\G11904\Pictures\Students\000', @cntImage, '.PNG'), SINGLE_BLOB) image;
SET @cntImage = @cntImage + 1
END

But I'm getting this error:

Incorrect syntax near CONCAT.

Can someone help to try and solve this issue? I'm not sure what I'm doing wrong.

Body:
Try to use dynamic query;

DECLARE @cnt INT = 0;
DECLARE @cntImage INT = 1;
declare @query nvarchar(1000)
declare @imagePath nvarchar(1000)
WHILE @cnt < 3000
BEGIN
set @imagePath  = CONCAT(N'C:\Users\G11904\Pictures\Students\000', @cntImage, '.PNG')
set @query =
    'Insert into ImageTest(ID, Imagen)
    SELECT ''SQL Server Image'', *
    FROM OPENROWSET (BULK '''+@imagePath+''', SINGLE_BLOB) image; '
    print @query
    exec sp_executesql @query
    SET @cntImage = @cntImage + 1
END

OPENROWSET expects string. You can't pass a variable.


问:
Object oriented coding in a multi threaded request environment - PHP
I am writing a web application in an object oriented design. This application would be interacting with the database pretty often. A few regular operations are verifying a user's ACL permissions for the function/method requested, performing certain functions etc. In a nutshell, the database would be used a lot. So my question here is, if I do develop my application using OOP, and declare class level variables which would be used to set the input coming in, and if there is any parallel or concurrent request coming in from another user, would the input data be changed??

Would I have to do something separate to make sure that the application is multi-threaded and the input coming in be not changed until the process isn't finished??

ex:

```<code>class myProces{
var $input1;
var $input2;

    function process1($ip1, $ip2){
      $this->input1 = $ip1;
      $this->input2 = $ip2;
      $this->getDataDB();
    }

    function getDataDB(){
     //do some database activity with the class level variables;
     // I would pass the values in the class level variables;
    $query = "select column from table where col1 = $this->input1 and col2= $this->input2";

    mysql_query($query);

    return something;
    }

}
</code>```

Now if I have two users hitting my application at the same time, and make a call to the functions in this class

user1:
$obj = new myProces();
$obj->process1(1,2);

user2:
$obj = new myProces();
$obj->process1(5,6);

Now if I do have class level variables, would they have changed values when concurrent requests come in?? Would PHP doing any kind of handling for multi threading? I am not sure if Apache can act as a message queue, where requests can be queued.

Can anybody explain if OOP for web applications with heavy number of users is good or if any kind of multithreading has to be done by developers??

答:
First: try to learn about PDO (unless that VAR before the variables, means that you're using PHP4).

Second: As konforce and Grossman said, each user gets differents instances of PHP.

Third: This problem may occur in Java projects (and others), that uses static objects or static methods. Don't worry with this in PHP.

Body:
I am writing a web application in an object oriented design. This application would be interacting with the database pretty often. A few regular operations are verifying a user's ACL permissions for the function/method requested, performing certain functions etc. In a nutshell, the database would be used a lot. So my question here is, if I do develop my application using OOP, and declare class level variables which would be used to set the input coming in, and if there is any parallel or concurrent request coming in from another user, would the input data be changed??

Would I have to do something separate to make sure that the application is multi-threaded and the input coming in be not changed until the process isn't finished??

ex:

class myProces{
var $input1;
var $input2;

    function process1($ip1, $ip2){
      $this->input1 = $ip1;
      $this->input2 = $ip2;
      $this->getDataDB();
    }

    function getDataDB(){
     //do some database activity with the class level variables;
     // I would pass the values in the class level variables;
    $query = "select column from table where col1 = $this->input1 and col2= $this->input2";

    mysql_query($query);

    return something;
    }

}

Now if I have two users hitting my application at the same time, and make a call to the functions in this class

user1:
$obj = new myProces();
$obj->process1(1,2);

user2:
$obj = new myProces();
$obj->process1(5,6);

Now if I do have class level variables, would they have changed values when concurrent requests come in?? Would PHP doing any kind of handling for multi threading? I am not sure if Apache can act as a message queue, where requests can be queued.

Can anybody explain if OOP for web applications with heavy number of users is good or if any kind of multithreading has to be done by developers??


问:
JSON google geocode API get country
I have a JSON: http://maps.googleapis.com/maps/api/geocode/json?latlng=49,19&sensor=false

and I need get only short_name of country. (For this example 'SK').
Therefore I get the short_name which the attribute "types" contains [ "country", "political" ].

I have...

```<code> data.results[0].address_components
</code>```

thanks.

答:
```<code><?php
$address = '77-379 North End road, London London SW61NP, United Kingdom'; // Your address(Please USe exist address)
$prepAddr = str_replace(' ','+',$address);

$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=API_KEY&sensor=false');
$output= json_decode($geocode);

if ( isset($output->results) ) {
    if ( isset($output->results[0]) ) {
        if ( isset($output->results[0]->address_components) ) {
            foreach ($output->results[0]->address_components as $key => $value) {
                if ( isset($value->types) ) {
                    if ( isset($value->types[0]) ) {
                        if($value->types[0] == 'country'){
                            print_r($value->short_name); //GB
                        }
                    }
                }
            }
        }
    }
} ?>
</code>```

Title: JSON google geocode API get country

Body:
I have a JSON: http://maps.googleapis.com/maps/api/geocode/json?latlng=49,19&sensor=false

and I need get only short_name of country. (For this example 'SK').
Therefore I get the short_name which the attribute "types" contains [ "country", "political" ].

I have...

 data.results[0].address_components

thanks.


答:
You can easily check:</p>

```<code>function isSync(func, ...args){
 var isSync = false;
 const res = func(...args, r => isSync = true);
 if(res instanceof Promise) res.then(r => isSync = true);
 return isSync;
}

console.log( isSync([].map.bind([])) );
</code>```

Title: How to know if a Javascript Callback is Synchronous or Asynchronous?

Body:
You can easily check:

function isSync(func, ...args){
 var isSync = false;
 const res = func(...args, r => isSync = true);
 if(res instanceof Promise) res.then(r => isSync = true);
 return isSync;
}

console.log( isSync([].map.bind([])) );


问:
SUM in SQL returning incorrect amount
This will seem incredibly simple but I can't figure out why the following query is returning an incorrect number.

I have put the data set into excel and done the calculations just to verify. The sum of m1 is 36785. When I remove areas 900 and 995. It comes to 18653. From looking at this query, what is the flaw? If I leave the () off it, the value calculated is 1716093. The query as shown below returns a value of 36785.

```<code>select sum(m1)
from dbo.sizeclassreportgov
where own='10' and (area !='900' or area != '995');
</code>```

答:
I think what you're looking for will be:

```<code>select sum(m1)
from dbo.sizeclassreportgov
where own='10' and area not in ('900', '995');
</code>```

area !='900' or area != '995' will always evaluate to true (unless area is NULL).

(If area does contain any NULL values, you'd need to use (area not in ('900', '995') or area is null).)

Title: SUM in SQL returning incorrect amount

Body:
This will seem incredibly simple but I can't figure out why the following query is returning an incorrect number.

I have put the data set into excel and done the calculations just to verify. The sum of m1 is 36785. When I remove areas 900 and 995. It comes to 18653. From looking at this query, what is the flaw? If I leave the () off it, the value calculated is 1716093. The query as shown below returns a value of 36785.

select sum(m1)
from dbo.sizeclassreportgov
where own='10' and (area !='900' or area != '995');

Body:
I think what you're looking for will be:

select sum(m1)
from dbo.sizeclassreportgov
where own='10' and area not in ('900', '995');

area !='900' or area != '995' will always evaluate to true (unless area is NULL).

(If area does contain any NULL values, you'd need to use (area not in ('900', '995') or area is null).)


答:
you can use redirect_to

```<code>redirect_to users_url, id: 5
</code>```

will get you to /users?id=5

Title: Rails Render Index with URL Parameters

Body:
you can use redirect_to

redirect_to users_url, id: 5

will get you to /users?id=5


问:
Is it posible to send multiple message to Google Home through DialogFlow?
On facebook Chatbot or others platform we can send message directly to the user.
So for one question we can send multiple answer.

Now, that i'm developing for Google Home, I need to do the same.
I didn't find this opttion.
Dialogflow HTTP call to my server is the only output available.

So is there anything i missed to send message back to user in case I have a multiple messages answer?
(Or do I have to bufferise very message my hook creates before sending it back?)

Thanks

答:
The conversation model for the Google Assistant is different - you can only send a message to the user in response to the user sending you a message. You can only send a single response, but it may have multiple parts (up to two Simple responses, containing messages, plus other features such as cards and carousels).

If you need to send multiple things back - you may need to rethink how you're doing it or how much you're sending back at a time. The Assistant is primarily for audible responses, and a long audible response is generally not a good UX.


问:
How to use Application Helpers in Ruby on Rails
I'm attempting to post a random testimonial on each page of a site.

I started off by using an application helper like this:

```<code>module ApplicationHelper

  def random_testimonial
    @random_testimonial = Testimonial.find(:first, :offset => rand(Testimonial.count))
  end

end
</code>```

In my view I can reference the method but it's being called on each reference, which makes sense.

I'd like this to be called once on each page view exposing a Testimonial object I can use within the view.

What should I be looking for to do this?

答:
While that works, and I have certainly been known to do this, it violates the MVC separation of concerns. View helpers are not supposed to contain controller/model type logic, which this does.

You might consider refactoring this back into the application controller.  Helpers are supposed to be for view formatting and stuff, more than as a function (which is what I kept wanting to do when I got started.)

If you got back into your Testimonail model, do could do

```<code>def self.random
  Testimonial.find(:first, :offset => rand(Testimonial.count))
end
</code>```

then in your application controller, you could do:

```<code>def random_testimonial
  @random_testimonial ||= Testimonial.random
end
</code>```

and call it from a before_filter

This has the advantage of moving the database logic back into the model where it belongs.

OwnerDisplayName: Chris Stewart

Body:
I'm attempting to post a random testimonial on each page of a site.

I started off by using an application helper like this:

module ApplicationHelper

  def random_testimonial
    @random_testimonial = Testimonial.find(:first, :offset => rand(Testimonial.count))
  end

end

In my view I can reference the method but it's being called on each reference, which makes sense.

I'd like this to be called once on each page view exposing a Testimonial object I can use within the view.

What should I be looking for to do this?

Body:
While that works, and I have certainly been known to do this, it violates the MVC separation of concerns. View helpers are not supposed to contain controller/model type logic, which this does.

You might consider refactoring this back into the application controller.  Helpers are supposed to be for view formatting and stuff, more than as a function (which is what I kept wanting to do when I got started.)

If you got back into your Testimonail model, do could do

def self.random
  Testimonial.find(:first, :offset => rand(Testimonial.count))
end

then in your application controller, you could do:

def random_testimonial
  @random_testimonial ||= Testimonial.random
end

and call it from a before_filter

This has the advantage of moving the database logic back into the model where it belongs.

OwnerDisplayName: Scott Miller


问:
Internal server error ajax submission
I have a function that triggers on a button click that passes the following argument: insertSongPlay(newSong.songID); when I console.log the newSong.songID I see a value of 90, which is desired.

This function is called here which runs an ajax call:

```<code>function insertSongPlay(songID)

{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/Album/InsertSongPlay/",
        data: JSON.stringify({ "songID": songID }),
        success: function(data)
        {

            console.log("submitted");
            console.log(songID);
            //TODO: Indicate Success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
            console.log(errorThrown);
        }
    });
}
</code>```

Here is the corresponding ajax url found in my AlbumController:

```<code>public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}
</code>```

Then in my EntityDataAccess.cs the following is run from the InsertSongPlay entity data access:

```<code>public static SongPlayDaily InsertSongPlay(int songID)
{
    using(var Context = GetContext())
    {
        var currentSongPlay = Context.SongPlayDailies.FirstOrDefault(x => x.SongID == songID && x.PlayDate == DateTime.Now.Date);
        if (currentSongPlay != null)
            currentSongPlay.NumberOfPlays++;
        else
        {
            currentSongPlay = new SongPlayDaily();
            currentSongPlay.SongID = songID;
            currentSongPlay.PlayDate = DateTime.Now.Date;
            currentSongPlay.NumberOfPlays = 1;
            Context.SongPlayDailies.Add(currentSongPlay);
        }
        Context.SaveChanges();
        return currentSongPlay;
    }
}
</code>```

However, my ajax call always throws an error and prints Internal Server Error to the console log. The Visual Studio debug mode indicates some sort of circular reference error. I'm not quite sure where I'm going wrong.

Thanks!

答:
Is it because you're missing the [HttpPost] attribute over your controller action?</p>

```<code>[HttpPost]
public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}
</code>```

Title: Internal server error ajax submission

Body:
I have a function that triggers on a button click that passes the following argument: insertSongPlay(newSong.songID); when I console.log the newSong.songID I see a value of 90, which is desired.

This function is called here which runs an ajax call:

function insertSongPlay(songID)

{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/Album/InsertSongPlay/",
        data: JSON.stringify({ "songID": songID }),
        success: function(data)
        {

            console.log("submitted");
            console.log(songID);
            //TODO: Indicate Success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
            console.log(errorThrown);
        }
    });
}

Here is the corresponding ajax url found in my AlbumController:

public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}

Then in my EntityDataAccess.cs the following is run from the InsertSongPlay entity data access:

public static SongPlayDaily InsertSongPlay(int songID)
{
    using(var Context = GetContext())
    {
        var currentSongPlay = Context.SongPlayDailies.FirstOrDefault(x => x.SongID == songID && x.PlayDate == DateTime.Now.Date);
        if (currentSongPlay != null)
            currentSongPlay.NumberOfPlays++;
        else
        {
            currentSongPlay = new SongPlayDaily();
            currentSongPlay.SongID = songID;
            currentSongPlay.PlayDate = DateTime.Now.Date;
            currentSongPlay.NumberOfPlays = 1;
            Context.SongPlayDailies.Add(currentSongPlay);
        }
        Context.SaveChanges();
        return currentSongPlay;
    }
}

However, my ajax call always throws an error and prints Internal Server Error to the console log. The Visual Studio debug mode indicates some sort of circular reference error. I'm not quite sure where I'm going wrong.

Thanks!

Body:
Is it because you're missing the [HttpPost] attribute over your controller action?

[HttpPost]
public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}


问:
How can the NuGet Documentation section be used?
As of lately, I see that the NuGet package pages include a Documentation section:

In all packages that I've checked, though, the only contents of that section is a seemingly expandable Show more item, which, when expanded, reveals to sport no further content.

As the docs do not appear to contain any hint about how that item works, I am asking here: How can I provide (presumably) package documentation for a NuGet package that will show up in that section? (And can you point out any example package that illustrates what the docs will look like on the NuGet package website?)

Notably, my packages contain the documentation XML files generated by the C# compiler from documentation comments. Yet, nothing shows up in the Documentation section, so that's not what is supposed to appear there.

答:
The section you are mentioning is on a specific packages page on Nuget.org. For example on the RestSharp package page, this shows the Documentation near the top of the page. This section is NOT related to any package data/details. I point out RestSharp because this package does come with a readme.txt file (which is displayed after installing that package). I initially thought it might be related to the readme.txt file. However, it is not!

No, this section is only displayed when you manually configure it from the NuGet website. See the image below (taken from a package I have previously uploaded):

You can manually add text, direct the website to a file, or upload a file directly. It is in markdown format.


问:
Difference between now and future date as x day , y hours , z minutes via php Carbon
I'm using laravel 5.5 and Carbon DateTime Library and have a future date and want to display difference between that time and Now.

But note that I want to display differences as this format :

```<code>x day , y hours , z minutes
</code>```

that shows how many days, hours and minutes is left to that future date

答:
Use the diff() method and d, h and i properties like this:

```<code>$diff = $date->diff(now());

{{ $diff->d . ' days, ' . $diff->h . ' hours, ' . $diff->i . ' minutes' }}
</code>```

http://carbon.nesbot.com/docs/

Body:
I'm using laravel 5.5 and Carbon DateTime Library and have a future date and want to display difference between that time and Now.

But note that I want to display differences as this format :

x day , y hours , z minutes

that shows how many days, hours and minutes is left to that future date

Body:
Use the diff() method and d, h and i properties like this:

$diff = $date->diff(now());

{{ $diff->d . ' days, ' . $diff->h . ' hours, ' . $diff->i . ' minutes' }}

http://carbon.nesbot.com/docs/


问:
mySQL select with old table and new table query
Hey all i am trying to figure out why my query code below does not seem to work:

```<code>SELECT id, itemName, itemRUDate, Sum(itemsSold) AS SumOf
FROM productr, productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC
</code>```

The table productr2010 is the OLD data and productr is a brand new table for this year (2011). When i try running the query i get this:

```<code>Column 'id' in field list is ambiguous
</code>```

I'm not sure what i need to do in order for it to grad data from both tables? I've also tried this:

```<code>SELECT productr.id, productr.itemName, productr.itemRUDate, Sum(productr.itemsSold) AS    SumOf
FROM productr, productr2010
WHERE productr.itemRUDate >= '2010/12/01' AND productr.itemRUDate <= '2011/01/22'
AND productr2010.itemRUDate >= '2010/12/01' AND productr2010.itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC
</code>```

And i get only the data from the productr table and not that and productr2010 table.

I'm sure i am just overlooking something easy..

UPDATE

Got it using this:

```<code>SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
UNION
SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC
</code>```

David

答:
You need to select your data from both joined tables, as below.

```<code>SELECT productr.itemName, productr2010.itemName,
</code>```

This will result in two separate columns for each piece of data, rather than a single column with both tables' data.

Body:
Hey all i am trying to figure out why my query code below does not seem to work:

SELECT id, itemName, itemRUDate, Sum(itemsSold) AS SumOf
FROM productr, productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC

The table productr2010 is the OLD data and productr is a brand new table for this year (2011). When i try running the query i get this:

Column 'id' in field list is ambiguous

I'm not sure what i need to do in order for it to grad data from both tables? I've also tried this:

SELECT productr.id, productr.itemName, productr.itemRUDate, Sum(productr.itemsSold) AS    SumOf
FROM productr, productr2010
WHERE productr.itemRUDate >= '2010/12/01' AND productr.itemRUDate <= '2011/01/22'
AND productr2010.itemRUDate >= '2010/12/01' AND productr2010.itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC

And i get only the data from the productr table and not that and productr2010 table.

I'm sure i am just overlooking something easy..

UPDATE

Got it using this:

SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
UNION
SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC

David

Body:
You need to select your data from both joined tables, as below.

SELECT productr.itemName, productr2010.itemName,

This will result in two separate columns for each piece of data, rather than a single column with both tables' data.


问:
Resend form with jquery when submit
My form have different ID, because use for save informations, and use jquery for manage these forms and submit with jquery

My question it´s about how i can, after submit, resend some data as for example ID with a value and send as post

```<code>jQuery("#form_config").submit();
</code>```

I send form and all works, but when save information i need reload this form but also send some input hidden generate during the process and reload this form with this new informations or values send after send form with jquery by post also

I need know how send values inside this .submit() to the form

Thank´s

答:
Your question was poorly worded but this might help you repopulate the form after submission.

```<code>jQuery("#form_config").submit(function(event){
        event.preventDefault();

        //insert whatever you want to "send some input hidden generate during the process"

        //then

        //jQuery("#fieldOneId").val("values inside this .submit() to the form")
        //jQuery("#fieldTwoId").val("values inside this .submit() to the form")
        //jQuery("#fieldNId").val("values inside this .submit() to the form")
    }
</code>```

Edit:

still unsure of your question but this works for what I believe you are asking.

```<code><body>

  <form>
    <div>
      <input id="first" type="text"><br>
      <input id="second" type="text"><br>
      <input type="submit">
    </div>
  </form>

  <script>
  $( "form" ).submit(function( event ) {
    const first = $( "#first" ).val()
    const second = $( "#second" ).val()
    $("#first").val(second)
    $("#second").val(first)
    event.preventDefault();
  });
  </script>
</body>
</code>```

Title: Resend form with jquery when submit

Body:
My form have different ID, because use for save informations, and use jquery for manage these forms and submit with jquery

My question it´s about how i can, after submit, resend some data as for example ID with a value and send as post

jQuery("#form_config").submit();

I send form and all works, but when save information i need reload this form but also send some input hidden generate during the process and reload this form with this new informations or values send after send form with jquery by post also

I need know how send values inside this .submit() to the form

Thank´s

Body:
Your question was poorly worded but this might help you repopulate the form after submission.

jQuery("#form_config").submit(function(event){
        event.preventDefault();

        //insert whatever you want to "send some input hidden generate during the process"

        //then

        //jQuery("#fieldOneId").val("values inside this .submit() to the form")
        //jQuery("#fieldTwoId").val("values inside this .submit() to the form")
        //jQuery("#fieldNId").val("values inside this .submit() to the form")
    }

Edit:

still unsure of your question but this works for what I believe you are asking.

<body>

  <form>
    <div>
      <input id="first" type="text"><br>
      <input id="second" type="text"><br>
      <input type="submit">
    </div>
  </form>

  <script>
  $( "form" ).submit(function( event ) {
    const first = $( "#first" ).val()
    const second = $( "#second" ).val()
    $("#first").val(second)
    $("#second").val(first)
    event.preventDefault();
  });
  </script>
</body>


问:
How to change Background color of table row based on respective cell data using angularjs?
I want to change Background color of row based on cell data, like if it matches first four characters from table cell "td", then row should change its color to red.

here is my example, it is working but it takes whole cell data.but i want row color should change once it matches first four characters from cell.

```<code> <style>
        .bgRed{
            background-color:red;
        }
    </style>

<body ng-app="myApp">
    <div ng-controller="myController">
        <div class="container" style="margin-top:40px;">
            <div class="row">
                {{error}}
                <div class="col-md-6">
                    <table class="table table-bordered table-condensed">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Class Name</th>
                                <th>Roll No</th>
                                <th>Email</th>
                            </tr>
                        </thead>
                        <tbody ng-repeat="std in students">
                            **<tr ng-class="{'bgRed': std.Name === 'Prash'}>**
                                <td>{{std.Name}}</td>
                                <td>{{std.ClassName}}</td>
                                <td>{{std.RollNo}}</td>
                                <td>{{std.Email}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</code>```

and my table is

Table row should change to red if table cell data "Prash or Prashant" matches.instead of taking "Prashant Olekar"

how to achive this please help. Thank you

答:
you can use a custom filter to set class according to condition of your row data,

html

```<code><tbody ng-repeat="std in students | filter:filterColor">
    <tr class="{{std.class}}">
        <td>{{std.Name}}</td>
        <td>{{std.ClassName}}</td>
        <td>{{std.RollNo}}</td>
        <td>{{std.Email}}</td>
    </tr>
</tbody>
</code>```

js

```<code>    $scope.filterColor = function (item) {
        if (your condition) {
            item.class = 'your class';
        }
        else
            item.class = 'some other class';
        return true;
    };
</code>```

Body:
I want to change Background color of row based on cell data, like if it matches first four characters from table cell "td", then row should change its color to red.

here is my example, it is working but it takes whole cell data.but i want row color should change once it matches first four characters from cell.

                {{error}}

                                Name
                                Class Name
                                Roll No
                                Email

                            **
**
                                {{std.Name}}
                                {{std.ClassName}}
                                {{std.RollNo}}
                                {{std.Email}}

and my table is

Table row should change to red if table cell data "Prash or Prashant" matches.instead of taking "Prashant Olekar"

how to achive this please help. Thank you

Body:
you can use a custom filter to set class according to condition of your row data,

html

<tbody ng-repeat="std in students | filter:filterColor">
    <tr class="{{std.class}}">
        <td>{{std.Name}}</td>
        <td>{{std.ClassName}}</td>
        <td>{{std.RollNo}}</td>
        <td>{{std.Email}}</td>
    </tr>
</tbody>

js

    $scope.filterColor = function (item) {
        if (your condition) {
            item.class = 'your class';
        }
        else
            item.class = 'some other class';
        return true;
    };


问:
Wrtie a file to a new file with addition text based on criteria within source file in python
I am trying to get a Python script that will open a few text files, read the content and every time it finds a word from a list, block that out with new text, then write it to a new file, for each file.

Right now, I can get it to write all of the source files to a single file, which is my script below, but I am not sure how to proceed to having a new file for every source file.

```<code>import os

KeyWords=["Magic","harry","wand"]

rootdir = "C:\\books"

fileslist = []

##blanks file and preps for new data
fileout = open(rootdir+"\\output\\newfile.txt","w")
print (fileout)
fileout.write("Start of file\n\nLocation of output: "+rootdir+"\\output \n\nFiles that are being Processed:\n\n")
fileout.close()

def sourcelist(fileslist):

        file=open(fileslist,"r")
        fileout=open(rootdir+"\\output\\newfile.txt", "a")

        for line in file:
                if any(word.lower() in line.lower() for word in KeyWords):
                    print("Word Found\n\n" + '\t'+line + "\nEnd\n")
                    fileout.write("<<<SEARCH TERM FOUND>>>\n\n" + '\t'+line + "\n<<<END OF BLOCK>>>\n")
                else:
                    #print('\t'+line)   #No need to print the lines with no Key words in
                    fileout.write('\t'+line)
        #return    #not sure what return does?

for root, dirs, files in os.walk(rootdir):
    dirs.clear()

    for file in files:
        filepath = root + os.sep + file
        if filepath.endswith(".txt"):
            fileslist.append(filepath)
    for path in fileslist:
        sourcelist(path)

    print("\n".join(fileslist))
    with open(rootdir+"\\output\\newfile.txt","a") as output:
        output.write("\n".join(fileslist)+"\n\n\n")
        output.close()
</code>```

答:
This is a bit tough to answer as a whole, but here's a general approach.

I have the following file structure:

```<code>hp_extracts: # directory
    hp_parser.py
    -- inps/
       -- harry_1.txt
       -- harry_2.txt
    -- outs/
       <nothing>
</code>```

Contents of inps/harry_1.txt:

```<code>When Harry got his wand it was Magic
something something magic something
something harry something
</code>```

Contents of inps/harry_2.txt:

```<code>magic something something
something
harry something something
</code>```

This is the contents of hp_parser.py:

```<code>import os

all_files = os.listdir('inps/')
keywords=["magic","harry","wand"]

for file in all_files:
    with open('inps/{}'.format(file)) as infile, open('outs/{}'.format(file), 'w') as outfile:
        for line in infile:
            #print(line)
            for word in line.split():
                if word.lower() in keywords:
                    line = line.replace(word, '<<<SEARCH TERM FOUND>>> {} <<<END OF BLOCK>>>'.format(word))
            outfile.write(line)
</code>```

Body:
I am trying to get a Python script that will open a few text files, read the content and every time it finds a word from a list, block that out with new text, then write it to a new file, for each file.

Right now, I can get it to write all of the source files to a single file, which is my script below, but I am not sure how to proceed to having a new file for every source file.

import os

KeyWords=["Magic","harry","wand"]

rootdir = "C:\\books"

fileslist = []

##blanks file and preps for new data
fileout = open(rootdir+"\\output\\newfile.txt","w")
print (fileout)
fileout.write("Start of file\n\nLocation of output: "+rootdir+"\\output \n\nFiles that are being Processed:\n\n")
fileout.close()

def sourcelist(fileslist):

        file=open(fileslist,"r")
        fileout=open(rootdir+"\\output\\newfile.txt", "a")

        for line in file:
                if any(word.lower() in line.lower() for word in KeyWords):
                    print("Word Found\n\n" + '\t'+line + "\nEnd\n")
                    fileout.write("<<<SEARCH TERM FOUND>>>\n\n" + '\t'+line + "\n<<<END OF BLOCK>>>\n")
                else:
                    #print('\t'+line)   #No need to print the lines with no Key words in
                    fileout.write('\t'+line)
        #return    #not sure what return does?

for root, dirs, files in os.walk(rootdir):
    dirs.clear()

    for file in files:
        filepath = root + os.sep + file
        if filepath.endswith(".txt"):
            fileslist.append(filepath)
    for path in fileslist:
        sourcelist(path)

    print("\n".join(fileslist))
    with open(rootdir+"\\output\\newfile.txt","a") as output:
        output.write("\n".join(fileslist)+"\n\n\n")
        output.close()

Body:
This is a bit tough to answer as a whole, but here's a general approach.

I have the following file structure:

hp_extracts: # directory
    hp_parser.py
    -- inps/
       -- harry_1.txt
       -- harry_2.txt
    -- outs/
       <nothing>

Contents of inps/harry_1.txt:

When Harry got his wand it was Magic
something something magic something
something harry something

Contents of inps/harry_2.txt:

magic something something
something
harry something something

This is the contents of hp_parser.py:

import os

all_files = os.listdir('inps/')
keywords=["magic","harry","wand"]

for file in all_files:
    with open('inps/{}'.format(file)) as infile, open('outs/{}'.format(file), 'w') as outfile:
        for line in infile:
            #print(line)
            for word in line.split():
                if word.lower() in keywords:
                    line = line.replace(word, '<<<SEARCH TERM FOUND>>> {} <<<END OF BLOCK>>>'.format(word))
            outfile.write(line)


问:
How to disable the same choice in two different select html tags
The title is probably confusing, but I will explain. I need to make a frontend of the web page for the online reservation of flights. On the page, there are two dropdown menus where a user has to choose the airport from which he wants to travel, and the destination. So, a part of my task, and a question is, how can I disable the two same choices? Logically, one cannot fly from Paris to Paris.</p>

答:
On load you could, in a sense, snapshot the original options via slice(). Then in your event listener filter them based off of what was selected in your origin select box. Once you have that select group of options you empty out the destination select box and repolulate it with the filtered ones.

const destination = document.getElementById('destination');

const originalOptions = Array.from(destination.options).slice(0);

document.getElementById('origin').addEventListener('change', e => {
  const currentOptions = Array.from(originalOptions).filter(option => option.value !== e.currentTarget.value);

  destination.length = 0;

  currentOptions.forEach(option => destination.appendChild(option));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="origin">
  <option value="paris">Paris</option>
  <option value="london">London</option>
  <option value="australia">Australia</option>
</select>

<select id="destination">
  <option value="london">London</option>
  <option value="paris">Paris</option>
  <option value="australia">Australia</option>
</select></code>```

Body:
On load you could, in a sense, snapshot the original options via slice(). Then in your event listener filter them based off of what was selected in your origin select box. Once you have that select group of options you empty out the destination select box and repolulate it with the filtered ones.

const destination = document.getElementById('destination');

const originalOptions = Array.from(destination.options).slice(0);

document.getElementById('origin').addEventListener('change', e => {
  const currentOptions = Array.from(originalOptions).filter(option => option.value !== e.currentTarget.value);

  destination.length = 0;

  currentOptions.forEach(option => destination.appendChild(option));
});

<select id="origin">
  <option value="paris">Paris</option>
  <option value="london">London</option>
  <option value="australia">Australia</option>
</select>

<select id="destination">
  <option value="london">London</option>
  <option value="paris">Paris</option>
  <option value="australia">Australia</option>
</select>


问:
The node API for `babel` has been moved to `babel-core` React webpack
I'm trying to use my React native Android app working as a website.I'm following this tutorial

when i run webpack-dev-server it showing below error.

webpak.cofig.js

```<code>module.exports = {
    entry: "./entry.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    presets: ['es2015', 'stage-0', 'react']
                }
            }
        ]
    },
    resolve: {
        alias: {
            "react-native": "react-native-web"
        }
    }
};
</code>```

entry.js

```<code>document.write(require('./../testreact/index.android.js'));
</code>```

package.json

```<code>{
    "name": "testreact",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "adb reverse tcp:8081 tcp:8081 && node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "babel": "^6.23.0",
        "babel-polyfill": "^6.23.0",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "babel-preset-stage-0": "^6.24.1",
        "firebase": "^4.1.2",
        "react": "^16.0.0-alpha.12",
        "react-native": "0.45.1",
        "react-native-router-flux": "^3.38.0",
        "react-native-web": "0.0.104",
        "react-navigation": "^1.0.0-beta.11",
        "webpack": "^3.0.0",
        "webpack-dev-server": "^2.5.0"
    },
    "devDependencies": {
        "autoprefixer": "^7.1.1",
        "babel-core": "^6.25.0",
        "babel-jest": "20.0.3",
        "babel-loader": "^7.1.0",
        "babel-preset-react-native": "2.0.0",
        "jest": "20.0.4",
        "react-test-renderer": "16.0.0-alpha.12"
    },
    "jest": {
        "preset": "react-native"
    }
}
</code>```

UPDATE

答: In case this hasn't been solved, in your webpack config file use babel-loader instead of babel-core.

Body:
I'm trying to use my React native Android app working as a website.I'm following this tutorial

when i run webpack-dev-server it showing below error.

webpak.cofig.js

module.exports = {
    entry: "./entry.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    presets: ['es2015', 'stage-0', 'react']
                }
            }
        ]
    },
    resolve: {
        alias: {
            "react-native": "react-native-web"
        }
    }
};

entry.js

document.write(require('./../testreact/index.android.js'));

package.json

{
    "name": "testreact",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "adb reverse tcp:8081 tcp:8081 && node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "babel": "^6.23.0",
        "babel-polyfill": "^6.23.0",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "babel-preset-stage-0": "^6.24.1",
        "firebase": "^4.1.2",
        "react": "^16.0.0-alpha.12",
        "react-native": "0.45.1",
        "react-native-router-flux": "^3.38.0",
        "react-native-web": "0.0.104",
        "react-navigation": "^1.0.0-beta.11",
        "webpack": "^3.0.0",
        "webpack-dev-server": "^2.5.0"
    },
    "devDependencies": {
        "autoprefixer": "^7.1.1",
        "babel-core": "^6.25.0",
        "babel-jest": "20.0.3",
        "babel-loader": "^7.1.0",
        "babel-preset-react-native": "2.0.0",
        "jest": "20.0.4",
        "react-test-renderer": "16.0.0-alpha.12"
    },
    "jest": {
        "preset": "react-native"
    }
}

UPDATE


问:
zlib Not Found in Mac High Sierra
I am trying to build a program unigen from source.  I run the program's configure script and get the error

```<code>...
checking for gzread in -lz... no
configure: error: zlib not found, see http://www.zlib.net
</code>```

I verified zlib is installed via homebrew (although it is keg-only).  Based on other posts, I also verified xcode command line tools are installed via

```<code>xcode-select --install
</code>```

If I run, which zlib, it does not print anything to the console.  I am not sure what else I can do to properly configure zlib or if there is something else wrong.

答:
There is an error in the configure script. It must be getting an unrelated and unexpected error that is causing it to conclude that the link to gzread() failed when it probably didn't.

zlib is most definitely there in High Sierra, and links fine with -lz. I just tried a small program much like the test program in the configure script:

```<code>int gzread();
int main() {
    return gzread();
}
</code>```

and compiled it with no problem in High Sierra using cc -o test test.c -lz.

Title: zlib Not Found in Mac High Sierra

Body:
I am trying to build a program unigen from source.  I run the program's configure script and get the error

...
checking for gzread in -lz... no
configure: error: zlib not found, see http://www.zlib.net

I verified zlib is installed via homebrew (although it is keg-only).  Based on other posts, I also verified xcode command line tools are installed via

xcode-select --install

If I run, which zlib, it does not print anything to the console.  I am not sure what else I can do to properly configure zlib or if there is something else wrong.

Body:
There is an error in the configure script. It must be getting an unrelated and unexpected error that is causing it to conclude that the link to gzread() failed when it probably didn't.

zlib is most definitely there in High Sierra, and links fine with -lz. I just tried a small program much like the test program in the configure script:

int gzread();
int main() {
    return gzread();
}

and compiled it with no problem in High Sierra using cc -o test test.c -lz.


问:
Cooccurrence in Mongodb
I am familiar with relational database such as MySQL. Recently I'm working on project that use MongoDb to stock 100,000 Documents. The structure of these Docs is as such:

```<code>    {
      "_id" : "1",
      "abstract" : "In this book, we present ....",
      "doi" : "xxxx/xxxxxx",
      "authors" : [
                   "Davis, a",
                   "louis, X",
                   "CUI, Li",
                   "FANG, Y"
                    ]
      }
</code>```

I would like to extract the cooccurrence matrix or cooccurrence value of all possible combination of authors (only pairs). the expected output is:

```<code>{ [auth1 , auth2 : 5 ] [auth1, auth3 : 1] [auth2, auth8 : 9]....}
</code>```

which means that auth1 and auth2 collaborate 5 times (in 5 books) auth2 and auth8 collaborate 9 times...

In relation database, possible solution could be:
in a table auth-book for example:

```<code>    INSERT INTO auth-book (id_book, id_auth) VALUES
              (1, 'auth1'),
              (1, 'auth2'),
              (1, 'auth3'),
              (2, 'auth1'),
              (2, 'auth5'),
              (2, 'auth87'),
              (2, 'auth2')...
</code>```

the query that calculate cooccurrence or collaboration of authors is:

```<code>     SELECT   a.id_auth a, b.id_auth b, COUNT(*) cnt
     FROM     auth-book a JOIN auth-booke b ON b.id_book= a.id_book AND   .id_auth > a.id_auth
     GROUP BY a.id_auth, b.id_auth
</code>```

output: [auth1 auth2 => 2][auth1 auth3 => 1][auth2 auth3 => 1]... etc.

I have no idea how to implement such a query in mongodb

答:
This is a wee bit scary but it seems to work.  Basically, we $lookup against ourselves and leverage the fact that lookup of a string into an array of strings is an implicit $in-like operation.

```<code> db.foo.aggregate([
 // Create single deduped list of authors:
 {$unwind: "$authors"}
 ,{$group: {_id:null, uu: {$addToSet: "$authors"} }}

 // Now unwind and go lookup into the authors array in the same collection.  If $uu
 // appears anywhere in the authors array, it is a match.
 ,{$unwind: "$uu"}
 ,{$lookup: { from: "foo", localField: "uu", foreignField: "authors", as: "X"}}

 // OK, lots of material in the pipe here.  Brace for a double unwind -- but
 // in this data domain it is probably OK because not every book has the same
 // set of authors, which will attenuate the result $lookup above.
 ,{$unwind: "$X"}
 ,{$unwind: "$X.authors"}

 // The data is starting to be clear here.  But we see two things:
 // self-matching (author1->author1) and pairs of inverses
 // (author1->author2 / author2->author1).  We don't need self matches and we
 // only need "one side" of the inverses.   So... let's do a strcasecmp
 // on them.  0 means the same so that's out.  So pick 1 or -1 to get one side
 // of the pair; doesn't really matter!  This is why the OP has b.id_auth > a.id_auth
 // in the SQL equivalent: to eliminate self match and one side of inverses.
 ,{$addFields: {q: {$strcasecmp: ["$uu", "$X.authors"] }} }
 ,{$match: {q: 1}}

 // And now group!
 ,{$group: {_id: {a: "$uu", b: "$X.authors"}, n: {$sum:1}}}
            ]);
</code>```

Title: Cooccurrence in Mongodb

Body:
I am familiar with relational database such as MySQL. Recently I'm working on project that use MongoDb to stock 100,000 Documents. The structure of these Docs is as such:

    {
      "_id" : "1",
      "abstract" : "In this book, we present ....",
      "doi" : "xxxx/xxxxxx",
      "authors" : [
                   "Davis, a",
                   "louis, X",
                   "CUI, Li",
                   "FANG, Y"
                    ]
      }

I would like to extract the cooccurrence matrix or cooccurrence value of all possible combination of authors (only pairs). the expected output is:

{ [auth1 , auth2 : 5 ] [auth1, auth3 : 1] [auth2, auth8 : 9]....}

which means that auth1 and auth2 collaborate 5 times (in 5 books) auth2 and auth8 collaborate 9 times...

In relation database, possible solution could be:
in a table auth-book for example:

    INSERT INTO auth-book (id_book, id_auth) VALUES
              (1, 'auth1'),
              (1, 'auth2'),
              (1, 'auth3'),
              (2, 'auth1'),
              (2, 'auth5'),
              (2, 'auth87'),
              (2, 'auth2')...

the query that calculate cooccurrence or collaboration of authors is:

     SELECT   a.id_auth a, b.id_auth b, COUNT(*) cnt
     FROM     auth-book a JOIN auth-booke b ON b.id_book= a.id_book AND   .id_auth > a.id_auth
     GROUP BY a.id_auth, b.id_auth

output: [auth1 auth2 => 2][auth1 auth3 => 1][auth2 auth3 => 1]... etc.

I have no idea how to implement such a query in mongodb

Body:
This is a wee bit scary but it seems to work.  Basically, we $lookup against ourselves and leverage the fact that lookup of a string into an array of strings is an implicit $in-like operation.

 db.foo.aggregate([
 // Create single deduped list of authors:
 {$unwind: "$authors"}
 ,{$group: {_id:null, uu: {$addToSet: "$authors"} }}

 // Now unwind and go lookup into the authors array in the same collection.  If $uu
 // appears anywhere in the authors array, it is a match.
 ,{$unwind: "$uu"}
 ,{$lookup: { from: "foo", localField: "uu", foreignField: "authors", as: "X"}}

 // OK, lots of material in the pipe here.  Brace for a double unwind -- but
 // in this data domain it is probably OK because not every book has the same
 // set of authors, which will attenuate the result $lookup above.
 ,{$unwind: "$X"}
 ,{$unwind: "$X.authors"}

 // The data is starting to be clear here.  But we see two things:
 // self-matching (author1->author1) and pairs of inverses
 // (author1->author2 / author2->author1).  We don't need self matches and we
 // only need "one side" of the inverses.   So... let's do a strcasecmp
 // on them.  0 means the same so that's out.  So pick 1 or -1 to get one side
 // of the pair; doesn't really matter!  This is why the OP has b.id_auth > a.id_auth
 // in the SQL equivalent: to eliminate self match and one side of inverses.
 ,{$addFields: {q: {$strcasecmp: ["$uu", "$X.authors"] }} }
 ,{$match: {q: 1}}

 // And now group!
 ,{$group: {_id: {a: "$uu", b: "$X.authors"}, n: {$sum:1}}}
            ]);


问:
Mapping classes c#
I am writing a tranformer that takes some input and gives an output.I need to call a specific tranformer based on my input type.

```<code>public static myentrypoint( template t);
{
   //I could do something like this.
   switch(t)
   {
        case t1:
         transformt1(..);
        case t2:
         transformt1(..);
         ....
   }
}

Trasform1 : Itransform
{
    tranform1(...);
}

Trasform2 : Itransform
{
    tranform2(...);
}
</code>```

I need to map which function to call based on what my template is. I can do a switch but are there more cleaner ways to do this using some design patterns ? I was thinking a of writing a static dictionary. I am new to OOP so any suggestions would be great.

答:
The way that I do these types of situations is through the use of Generics. (Shameless self-promotion of a blog post)

Basically, you'll have your base class set up like this:

```<code>public abstract class Transformer<T>
    where T : Template
{
    public abstract void Transform(T item);
}
</code>```

Then you derive for each of your types like this:

```<code>public class Transformer1 : Tansformer<Template1>
{
    public void Transform(Template1 item)
    {

    }
}

public class Transformer2 : Transformer<Template2>
{
    public void Transform(Template2 item)
    {

    }
}
</code>```

Then you'll just need a factory to give you the correct Transformer.

```<code>public class TransformFactory
{
    public Transformer<T> GetTransformer<T>(T item)
    {
        if (item is Template1)
            return new Transformer1();
        else if (item is Template2)
            return new Transformer2();
        // ...
    }
}
</code>```

The benefit of this approach is that you'll be able to encapsulate all behavior on that specific type in the concrete implementations. If there is any common behavior on them all, you can do that in the abstract base.

Title: Mapping classes c#

Body:
I am writing a tranformer that takes some input and gives an output.I need to call a specific tranformer based on my input type.

public static myentrypoint( template t);
{
   //I could do something like this.
   switch(t)
   {
        case t1:
         transformt1(..);
        case t2:
         transformt1(..);
         ....
   }
}

Trasform1 : Itransform
{
    tranform1(...);
}

Trasform2 : Itransform
{
    tranform2(...);
}

I need to map which function to call based on what my template is. I can do a switch but are there more cleaner ways to do this using some design patterns ? I was thinking a of writing a static dictionary. I am new to OOP so any suggestions would be great.

Body:
The way that I do these types of situations is through the use of Generics. (Shameless self-promotion of a blog post)

Basically, you'll have your base class set up like this:

public abstract class Transformer<T>
    where T : Template
{
    public abstract void Transform(T item);
}

Then you derive for each of your types like this:

public class Transformer1 : Tansformer<Template1>
{
    public void Transform(Template1 item)
    {

    }
}

public class Transformer2 : Transformer<Template2>
{
    public void Transform(Template2 item)
    {

    }
}

Then you'll just need a factory to give you the correct Transformer.

public class TransformFactory
{
    public Transformer<T> GetTransformer<T>(T item)
    {
        if (item is Template1)
            return new Transformer1();
        else if (item is Template2)
            return new Transformer2();
        // ...
    }
}

The benefit of this approach is that you'll be able to encapsulate all behavior on that specific type in the concrete implementations. If there is any common behavior on them all, you can do that in the abstract base.


问:
How to countdown timer based on database column value
There are not many solutions/tutorials on how user inserted value in database could be used as a dynamic timer countdown that does not reset after the page is refreshed.

I'm facing a problem where the value is displayed but static. Is there any other way of implementing this?

database & web

How could I add functionality to redirect or stop the countdown timer?

index.php

```<code><?php
session_start();
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'root';
$dbName = 'student';

$conn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName,$conn);

$duration="";
$query="select duration from table1";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)){
$duration=$row["duration"];
}

$_SESSION["duration"]=$duration;
$_SESSION["start_time"]=date("Y-m-d H:i:s");

$end_time=$end_time=date('Y-m-d H:i:s',strtotime('+'.$_SESSION["duration"].'minutes',strtotime($_SESSION["start_time"])));
$_SESSION["end_time"]=$end_time;
include_once 'response.php';
?>

<div id="response"> </div>

    <script type="text/javascript">
    setInterval(function()
    {
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET","response.php",false);
    xmlhtpp.send(null);
    document.getElementById("response").innerHTML=xmlhttp.responseText;
    },1000);
    </script>
</code>```

response.php

```<code><?php

$from_start=date('Y-m-d H:i:s');
$to_end=$_SESSION["end_time"];

$first=strtotime($from_start);
$second=strtotime($to_end);

$differenceinseconds=$second-$first;

echo gmdate("H:i:s",$differenceinseconds);

?>
</code>```

答:
I ran your code and found a couple issues:

There is a JavaScript error

This is because there is a typo in the Javascript code on the following line:

```<code>xmlhtpp.send(null);
</code>```

Change that to

```<code>xmlhttp.send(null);
</code>```

And the Asynchronous requests should execute properly.

The line include_once 'response.php'; will have the effect of echoing the formatted date string above the
, which will yield two formatted timestamps when the AJAX requests are running. Remove that include_once line to avoid that scenario.

The code for response.php doesn't call session_start();. Unless your error handler settings are such that E_NOTICE errors are ignored, there will likely be an error message at the top of the timer:

E_NOTICE : type 8 -- Undefined variable: _SESSION -- at line 12

See a demonstration in this phpFiddle.

Body:
There are not many solutions/tutorials on how user inserted value in database could be used as a dynamic timer countdown that does not reset after the page is refreshed.

I'm facing a problem where the value is displayed but static. Is there any other way of implementing this?

database & web

How could I add functionality to redirect or stop the countdown timer?

index.php

<?php
session_start();
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'root';
$dbName = 'student';

$conn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName,$conn);

$duration="";
$query="select duration from table1";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)){
$duration=$row["duration"];
}

$_SESSION["duration"]=$duration;
$_SESSION["start_time"]=date("Y-m-d H:i:s");

$end_time=$end_time=date('Y-m-d H:i:s',strtotime('+'.$_SESSION["duration"].'minutes',strtotime($_SESSION["start_time"])));
$_SESSION["end_time"]=$end_time;
include_once 'response.php';
?>

response.php

<?php

$from_start=date('Y-m-d H:i:s');
$to_end=$_SESSION["end_time"];

$first=strtotime($from_start);
$second=strtotime($to_end);

$differenceinseconds=$second-$first;

echo gmdate("H:i:s",$differenceinseconds);

?>

Body:
I ran your code and found a couple issues:

There is a JavaScript error

This is because there is a typo in the Javascript code on the following line:

xmlhtpp.send(null);

Change that to

xmlhttp.send(null);

And the Asynchronous requests should execute properly.

The line include_once 'response.php'; will have the effect of echoing the formatted date string above the <div>, which will yield two formatted timestamps when the AJAX requests are running. Remove that include_once line to avoid that scenario.

The code for response.php doesn't call session_start();. Unless your error handler settings are such that E_NOTICE errors are ignored, there will likely be an error message at the top of the timer:

E_NOTICE : type 8 -- Undefined variable: _SESSION -- at line 12

See a demonstration in this phpFiddle.


问:
Chef is running the wrong recipe
I'm trying to set up Varnish in front of a Wordpress multi-site using Chef.  I am new to the system that was set up by others, and I'm a bit of a beginner in general.

I have created a new recipe and added it to the run list, but when I run chef-client, it executes a different recipe in place of the one I wrote.  Specifically, it runs the only recipe that my recipe includes.

Here is my recipe, which I copied almost verbatim from a pre-existing, working recipe that we use for a different site:

```<code>#
# Cookbook Name:: web_varnish_config
# Recipe:: wordpress
#

include_recipe 'web_varnish_config::default'

all_wordpress_backends = search(:node, "chef_environment:#{node.chef_environment} AND roles:web_wordpress")
all_wordpress_backends.sort_by!{ |n| n[:fqdn] } # Sort the nodes to prevent config-order thrashing.

# Error state
if all_wordpress_backends.empty?
  Chef::Log.warn("At least one node with recipes:web_wordpress must exist for chef_environment:#{node.chef_environment}. Skipping Varnish configuration.")
  return
end

template "/etc/varnish/default.vcl" do
  source "etc/varnish/wordpress.vcl.erb"
  mode "0644"
  variables(
    :all_wordpress_backends => all_wordpress_backends
  )
  notifies :restart, "service[varnish]", :delayed
end

# Use a share secret for our Varnish instances that is available to our Webservers
# so that Wordpress can clear the Varnish cache.
include_recipe 'chef-vault'
settings = chef_vault_item_for_environment("web_wordpress", "varnish")
if !settings.nil? and settings.key?('secret')
  file "/etc/varnish/secret" do
    content settings['secret']
    mode "0600"
    notifies :restart, "service[varnish]", :delayed
  end
end
</code>```

When I run chef-client, it runs web_varnish_config::default instead of this recipe, web_varnish_config::wordpress.  This is what my chef-client output looks like (tried to copy all of it, but couldn't so here's the beginning and the end, what I think is most relevant):

```<code>Starting Chef Client, version 13.6.4
resolving cookbooks for run list: ["yum-epel::default", "serversetup-midd::cent7", "serversetup-midd::rootpassword", "midd_yum_cron::default", "fw-midd::default", "chef-client::config", "chef-client::default", "chef_client_updater::default", "centrify-midd::default", "centrify-midd::sshd", "midd_spacewalk::client", "commvault-midd::default", "serversetup-midd::webserver", "fw-midd::webserver", "centrify-midd::webserver", "chef-vault::default", "ssl-config-midd::miis", "ssl-config-midd::midd", "php-midd::default", "ssl-config-midd::wordpress", "web_php_config", "web_apache_config", "web_apache_config::ssl_context", "web_wordpress", "cookbook_versions::all", "ssl-config-midd::davisfellowsforpeace", "ssl-config-midd::davisprojectsforpeace", "ssl-config-midd::davisuwcscholars", "varnish-midd::default", "fw-midd::varnishserver", "web_varnish_config::backend", "web_varnish_config::wordpress"]
Synchronizing Cookbooks:
  - smbfs (0.5.0)
  - compat_resource (12.19.0)
  - web_php_config (1.1.0)
  - ohai (5.1.0)
  - midd_spacewalk (0.4.3)
  - windows (3.0.5)
  - yum (5.0.1)
  - firewalld (1.1.5)
  - cookbook_versions (1.0.0)
  - serversetup-midd (2.6.10)
  - commvault-midd (2.3.1)
  - cron (4.1.3)
  - php-midd (2.0.6)
  - ssl-config-midd (2.2.1)
  - chef-vault (3.0.0)
  - logrotate (2.2.0)
  - selinux (2.0.3)
  - ssh_authorized_keys (0.4.0)
  - chef_client_updater (2.0.3)
  - web_wordpress (2.0.10)
  - varnish-midd (2.0.3)
  - chef-client (8.1.6)
  - users (5.1.0)
  - yum-epel (2.1.2)
  - web_apache_config (2.0.10)
  - web_varnish_config (2.3.2)
  - sshd (1.3.1)
  - fw-midd (3.2.5)
  - midd_yum_cron (1.0.0)
  - web_sshkeys (1.0.2)
  - web_git_tracking_branch (1.1.0)
  - centrify-midd (3.1.1)
</code>```

And at the end:

```<code>Recipe: web_varnish_config::backend
   * cookbook_file[/var/www/html/check.html] action create (up to date)
   * web_apache_config_vhost[vhost-7-wwwhealthcheck.conf] action create
   * template[/etc/httpd/conf.d/vhost-7-wwwhealthcheck.conf] action create (up to date)
 (up to date)
 # NOTE: Below is where I'm expecting web_varnish_config:wordpress
 Recipe: web_varnish_config::default
   * service[varnish] action enable (up to date)
   * template[/etc/varnish/varnish.params] action create (up to date)
   * service[varnishncsa] action enable (up to date)
   * service[varnishncsa] action start (up to date)
   * cookbook_file[/etc/systemd/system/varnishncsa.service] action create (up to date)
</code>```

If I take out the include line, chef-client skips this entirely, without errors.

Any ideas?

答:
So it turns out I had forgotten to update the name of a role in:

```<code># I needed to change roles:web_wordpress to roles:web_wordpress_new
all_wordpress_backends = search(:node, "chef_environment:#{node.chef_environment} AND roles:web_wordpress")
</code>```

Which means my problem was extremely specific and probably not helpful to others, but there it is.

Title: Chef is running the wrong recipe

Body:
I'm trying to set up Varnish in front of a Wordpress multi-site using Chef.  I am new to the system that was set up by others, and I'm a bit of a beginner in general.

I have created a new recipe and added it to the run list, but when I run chef-client, it executes a different recipe in place of the one I wrote.  Specifically, it runs the only recipe that my recipe includes.

Here is my recipe, which I copied almost verbatim from a pre-existing, working recipe that we use for a different site:

#
# Cookbook Name:: web_varnish_config
# Recipe:: wordpress
#

include_recipe 'web_varnish_config::default'

all_wordpress_backends = search(:node, "chef_environment:#{node.chef_environment} AND roles:web_wordpress")
all_wordpress_backends.sort_by!{ |n| n[:fqdn] } # Sort the nodes to prevent config-order thrashing.

# Error state
if all_wordpress_backends.empty?
  Chef::Log.warn("At least one node with recipes:web_wordpress must exist for chef_environment:#{node.chef_environment}. Skipping Varnish configuration.")
  return
end

template "/etc/varnish/default.vcl" do
  source "etc/varnish/wordpress.vcl.erb"
  mode "0644"
  variables(
    :all_wordpress_backends => all_wordpress_backends
  )
  notifies :restart, "service[varnish]", :delayed
end

# Use a share secret for our Varnish instances that is available to our Webservers
# so that Wordpress can clear the Varnish cache.
include_recipe 'chef-vault'
settings = chef_vault_item_for_environment("web_wordpress", "varnish")
if !settings.nil? and settings.key?('secret')
  file "/etc/varnish/secret" do
    content settings['secret']
    mode "0600"
    notifies :restart, "service[varnish]", :delayed
  end
end

When I run chef-client, it runs web_varnish_config::default instead of this recipe, web_varnish_config::wordpress.  This is what my chef-client output looks like (tried to copy all of it, but couldn't so here's the beginning and the end, what I think is most relevant):

Starting Chef Client, version 13.6.4
resolving cookbooks for run list: ["yum-epel::default", "serversetup-midd::cent7", "serversetup-midd::rootpassword", "midd_yum_cron::default", "fw-midd::default", "chef-client::config", "chef-client::default", "chef_client_updater::default", "centrify-midd::default", "centrify-midd::sshd", "midd_spacewalk::client", "commvault-midd::default", "serversetup-midd::webserver", "fw-midd::webserver", "centrify-midd::webserver", "chef-vault::default", "ssl-config-midd::miis", "ssl-config-midd::midd", "php-midd::default", "ssl-config-midd::wordpress", "web_php_config", "web_apache_config", "web_apache_config::ssl_context", "web_wordpress", "cookbook_versions::all", "ssl-config-midd::davisfellowsforpeace", "ssl-config-midd::davisprojectsforpeace", "ssl-config-midd::davisuwcscholars", "varnish-midd::default", "fw-midd::varnishserver", "web_varnish_config::backend", "web_varnish_config::wordpress"]
Synchronizing Cookbooks:
  - smbfs (0.5.0)
  - compat_resource (12.19.0)
  - web_php_config (1.1.0)
  - ohai (5.1.0)
  - midd_spacewalk (0.4.3)
  - windows (3.0.5)
  - yum (5.0.1)
  - firewalld (1.1.5)
  - cookbook_versions (1.0.0)
  - serversetup-midd (2.6.10)
  - commvault-midd (2.3.1)
  - cron (4.1.3)
  - php-midd (2.0.6)
  - ssl-config-midd (2.2.1)
  - chef-vault (3.0.0)
  - logrotate (2.2.0)
  - selinux (2.0.3)
  - ssh_authorized_keys (0.4.0)
  - chef_client_updater (2.0.3)
  - web_wordpress (2.0.10)
  - varnish-midd (2.0.3)
  - chef-client (8.1.6)
  - users (5.1.0)
  - yum-epel (2.1.2)
  - web_apache_config (2.0.10)
  - web_varnish_config (2.3.2)
  - sshd (1.3.1)
  - fw-midd (3.2.5)
  - midd_yum_cron (1.0.0)
  - web_sshkeys (1.0.2)
  - web_git_tracking_branch (1.1.0)
  - centrify-midd (3.1.1)

And at the end:

Recipe: web_varnish_config::backend
   * cookbook_file[/var/www/html/check.html] action create (up to date)
   * web_apache_config_vhost[vhost-7-wwwhealthcheck.conf] action create
   * template[/etc/httpd/conf.d/vhost-7-wwwhealthcheck.conf] action create (up to date)
 (up to date)
 # NOTE: Below is where I'm expecting web_varnish_config:wordpress
 Recipe: web_varnish_config::default
   * service[varnish] action enable (up to date)
   * template[/etc/varnish/varnish.params] action create (up to date)
   * service[varnishncsa] action enable (up to date)
   * service[varnishncsa] action start (up to date)
   * cookbook_file[/etc/systemd/system/varnishncsa.service] action create (up to date)

If I take out the include line, chef-client skips this entirely, without errors.

Any ideas?

Body:
So it turns out I had forgotten to update the name of a role in:

# I needed to change roles:web_wordpress to roles:web_wordpress_new
all_wordpress_backends = search(:node, "chef_environment:#{node.chef_environment} AND roles:web_wordpress")

Which means my problem was extremely specific and probably not helpful to others, but there it is.