问:
Blinking cell script depending on content - how to do indefinitely
Hi I have the following code:

```<code>function onEdit(e) {
  if (e.value == "Requested") {
    var number = 50; // Number of blink
    for (var i = 0; i <= number * 2; i++) {
      if (i % 2 == 0) {
        var color = "white";
      } else {
        var color = "red";
      }
      e.range.setBackground(color);
      SpreadsheetApp.flush();
      Utilities.sleep(1500); // Blink speed (ms)
    }
    e.range.setBackground("white") // Cell color is white after blinks were completed.
  }
}
</code>```

However for some reason the cell blinks less than 10 times or so even though I have set it to 50. Is there a time limit when google runs a for loop? Is there a way to make it indefinite until I change the cell value to something else?

答:
Making so many calls to Google services will count against your daily quotas. More on quotas here https://developers.google.com/apps-script/guides/services/quotas

Only use service calls for something that's really important like fetching and processing data. Find another solution to highlight the edited cell.

Because of latency, you'll never get the blinking to render perfectly, but you could bring the wait time down to 50 milliseconds. Check out the script below. Be advised, this is extremely bad practice and should be avoided at all costs.

```<code>   //junk code: not for use

    var i = 0;

    var isRunning = true;

    while(isRunning) {

      if (i % 2 == 0) {
        var color = "white";
      } else {
        var color = "red";
      }

      i++;
      e.range.setBackground(color);
      SpreadsheetApp.flush();
      Utilities.sleep(30); // Blink speed (ms)
    }
</code>```

Try executing it for several cells. You'll notice that the script will stop executing after some time. That's because Google limits total execution time and will not allow your script to run continuously. If you go to View -> Execution transcript in Script Editor, you'll see something like this 'Execution failed: Exceeded maximum execution time [32.548 seconds total runtime]'.

Body:
Hi I have the following code:

function onEdit(e) {
  if (e.value == "Requested") {
    var number = 50; // Number of blink
    for (var i = 0; i <= number * 2; i++) {
      if (i % 2 == 0) {
        var color = "white";
      } else {
        var color = "red";
      }
      e.range.setBackground(color);
      SpreadsheetApp.flush();
      Utilities.sleep(1500); // Blink speed (ms)
    }
    e.range.setBackground("white") // Cell color is white after blinks were completed.
  }
}

However for some reason the cell blinks less than 10 times or so even though I have set it to 50. Is there a time limit when google runs a for loop? Is there a way to make it indefinite until I change the cell value to something else?

Body:
Making so many calls to Google services will count against your daily quotas. More on quotas here https://developers.google.com/apps-script/guides/services/quotas

Only use service calls for something that's really important like fetching and processing data. Find another solution to highlight the edited cell.

Because of latency, you'll never get the blinking to render perfectly, but you could bring the wait time down to 50 milliseconds. Check out the script below. Be advised, this is extremely bad practice and should be avoided at all costs.

   //junk code: not for use

    var i = 0;

    var isRunning = true;

    while(isRunning) {

      if (i % 2 == 0) {
        var color = "white";
      } else {
        var color = "red";
      }

      i++;
      e.range.setBackground(color);
      SpreadsheetApp.flush();
      Utilities.sleep(30); // Blink speed (ms)
    }

Try executing it for several cells. You'll notice that the script will stop executing after some time. That's because Google limits total execution time and will not allow your script to run continuously. If you go to View -> Execution transcript in Script Editor, you'll see something like this 'Execution failed: Exceeded maximum execution time [32.548 seconds total runtime]'.


来源: stackexchange

问:
fetch user details from log.nsf
hi
My question is : In log.nsf , there are entries database accessed in last week. I am not able to find where these values resides as i am fetching these values from c# and using the domino.dll as reference.

kindly help me out to fetch the number of hits of database from any user in week. So that i can check that my database is active and how much being accessed by users.

Thanks in Advance

Ankit

答: I think you use wrong approach. What I would do is to create a form with two fields - user name and access count and a view sorted by user name. Each time in the database open script search in the view for a document for he current user and update counter (+1). If no document found - create it for current user, set counter to one and save. If you also need dates, you can either add date field to the document and not use counter, just create a document every time your database has been opened and create a view categorized by date to see the usage. Number of documents per day would show you the usage. You can also add category per user if you like. I think using log.nsf for this purpose is not a good approach.</p>

ContentLicense: CC BY-SA 2.5

Title: fetch user details from log.nsf


问:
"The current configuration system does not support user-scoped settings"
We're getting a "The current configuration system does not support user-scoped settings" compilation exception being thrown when navigating to a WCF service on our staging server.

We're getting this exception through the app consuming the WCF service and when we navigate to the .svc test page directly.

This works fine on our test servers - and the websites are setup in the same way (in IIS, in the filesystem etc. etc.).

Does anybody have an idea of what this would be?

答: In my case the problem was that the Web Service reference had its "URL Behavior" property set to "Dynamic" instead of "Static". After setting it to Static the problem went away.

ContentLicense: CC BY-SA 3.0


问:
Uncaught TypeError: Cannot read property 'each' of undefined
I am getting : Uncaught TypeError: Cannot read property 'each' of undefined
at animateIfInview
at atonscroll

and heres the code :

```<code> <script>
 function animateIfInView() {
 $.each($("content-img"), function(key, value) {
 if (isElementInViewport($(value))) {
 $(value).addClass("content-img-in-view");
 } else {
  // (Optional) Fade out when out of view
  $(value).removeClass("content-img-in-view");
  }
  });
  }

  // http://stackoverflow.com/a/7557433/5628
   function isElementInViewport(el) {
    //special bonus for those using jQuery
  if (typeof jQuery === "function" && el instanceof jQuery) {
  el = el[0];
  }

  var rect = el.getBoundingClientRect();

  return (
  rect.top >= 0 &&
  rect.left >= 0 &&
  rect.bottom <=
  (window.innerHeight ||
  document.documentElement.clientHeight) /*or $(window).height() */ &&
  rect.right <=
  (window.innerWidth ||
  document.documentElement.clientWidth) /*or $(window).width() */
  );
  }
  </script>
</code>```

How can I fix this error? what am I missing in code? Thanks guys in advance

答:
I would suggest the following:

```<code>function animateIfInView() {
  $(".content-img").each(function(key, elem) {
    if (isElementInViewport($(elem))) {
      $(elem).toggleClass("content-img-in-view");
    }
  });
}
</code>```

The class selector uses $(".className"), where your code is missing the . in it. Also, if using elements, it is suggested to use .each() versus $.each() which is suggests for Arrays and Objects.

Body:
I am getting : Uncaught TypeError: Cannot read property 'each' of undefined
at animateIfInview
at atonscroll

and heres the code :

How can I fix this error? what am I missing in code? Thanks guys in advance

Body:
I would suggest the following:

function animateIfInView() {
  $(".content-img").each(function(key, elem) {
    if (isElementInViewport($(elem))) {
      $(elem).toggleClass("content-img-in-view");
    }
  });
}

The class selector uses $(".className"), where your code is missing the . in it. Also, if using elements, it is suggested to use .each() versus $.each() which is suggests for Arrays and Objects.


问:
Send opencv Mat image through Qt websocket to HTML client
I'm trying to write an application in c++ using Qt 5.7, basically it should be a websocket server, using qwebsocket for this, capable to send an image elaborated with opencv to an HTML client. What I'm trying to do is encode the image in base64, transmit and on the client put the encoded string in the src of an image tag.
Just to test, I can send/receive text messages correctly, so the websocket architecture is working,  but I have some problems with images. This is my code snippets:

Server

```<code>    cv::Mat imgIn;
    imgIn = cv::imread("/home/me/color.png",CV_LOAD_IMAGE_COLOR);
    QByteArray Img((char*)(imgIn.data),imgIn.total()*imgIn.elemSize());
    QByteArray Img64 = Img.toBase64();
    pClient->sendBinaryMessage(Img64);
</code>```

Client

```<code><img id="ItemPreview" src="" style="border:5px solid black" />
</code>```

....

```<code>websocket.binaryType = "arraybuffer";

websocket.onmessage = function (evt) {
console.log( "Message received :", evt.data );
document.getElementById("ItemPreview").src = "data:image/png;base64," + evt.data;
};
</code>```

I think most of the problems are in the Server, because the base64 sequence I got from the image is different from the one I can get from online converter image/base64.
On the client I receive this error in the console and nothing is showed:

data:image/png;base64,[object ArrayBuffer]:1 GET
  data:image/png;base64,[object ArrayBuffer] net::ERR_INVALID_URL

Any hints?

SOLUTION

Thanks to the suggestions, I can provide the working code:

Server

```<code>    imgIn = cv::imread("/home/me/color.png", CV_LOAD_IMAGE_UNCHANGED);
    std::vector<uchar> buffer;
    cv::imencode(".png",imgIn,buffer);
    std::string s = base64_encode(buffer.data(),buffer.size());
    pClient->sendTextMessage(QString::fromStdString(s));
</code>```

Client

Removed this line:

```<code>    websocket.binaryType = "arraybuffer";
</code>```

The base64 encoding in the server is done using this code:

Encode/Decode base64

答:
This line in the server:

```<code>imgIn = cv::imread("/home/me/color.png",CV_LOAD_IMAGE_COLOR);
</code>```

decodes a PNG formatted image, and places it in memory as load of pixel data (plus possibly some row padding, which you don't take account of, see below). That's what you're base64 encoding.

This line in the client:

```<code>document.getElementById("ItemPreview").src = "data:image/png;base64," + evt.data;
</code>```

is expecting a PNG image, but that isn't what you're sending; you've just pushed out a load of raw pixel data, with no dimensions or stride or format information or anything else.

If your client wants a PNG, you're going to have to use something like imencode to write PNG data to a memory buffer, and base64 encode that instead.

One other important thing to note is that decoded images may have row padding... a few bytes on the end of each row for memory alignment purposes. Therefore, the actual length of each image row may exceed the width of the image multiplied by the size of the each pixel in bytes. That means that this operation:

```<code>QByteArray Img((char*)(imgIn.data),imgIn.total()*imgIn.elemSize());
</code>```

may not, in fact, wrap the entire image buffer in your QByteArray. There are various ways to check the stride/step of an image, but you'd best read the cv::Mat docs as it isn't worth me repeating them all here. This only matters if you're doing raw byte-level image manipulation, like you are here. If you use imencode, you don't need to worry about this.

Body:
I'm trying to write an application in c++ using Qt 5.7, basically it should be a websocket server, using qwebsocket for this, capable to send an image elaborated with opencv to an HTML client. What I'm trying to do is encode the image in base64, transmit and on the client put the encoded string in the src of an image tag.
Just to test, I can send/receive text messages correctly, so the websocket architecture is working,  but I have some problems with images. This is my code snippets:

Server

    cv::Mat imgIn;
    imgIn = cv::imread("/home/me/color.png",CV_LOAD_IMAGE_COLOR);
    QByteArray Img((char*)(imgIn.data),imgIn.total()*imgIn.elemSize());
    QByteArray Img64 = Img.toBase64();
    pClient->sendBinaryMessage(Img64);

Client

....

websocket.binaryType = "arraybuffer";

websocket.onmessage = function (evt) {
console.log( "Message received :", evt.data );
document.getElementById("ItemPreview").src = "data:image/png;base64," + evt.data;
};

I think most of the problems are in the Server, because the base64 sequence I got from the image is different from the one I can get from online converter image/base64.
On the client I receive this error in the console and nothing is showed:

data:image/png;base64,[object ArrayBuffer]:1 GET
  data:image/png;base64,[object ArrayBuffer] net::ERR_INVALID_URL

Any hints?

SOLUTION

Thanks to the suggestions, I can provide the working code:

Server

    imgIn = cv::imread("/home/me/color.png", CV_LOAD_IMAGE_UNCHANGED);
    std::vector<uchar> buffer;
    cv::imencode(".png",imgIn,buffer);
    std::string s = base64_encode(buffer.data(),buffer.size());
    pClient->sendTextMessage(QString::fromStdString(s));

Client

Removed this line:

    websocket.binaryType = "arraybuffer";

The base64 encoding in the server is done using this code:

Encode/Decode base64

Body:
This line in the server:

imgIn = cv::imread("/home/me/color.png",CV_LOAD_IMAGE_COLOR);

decodes a PNG formatted image, and places it in memory as load of pixel data (plus possibly some row padding, which you don't take account of, see below). That's what you're base64 encoding.

This line in the client:

document.getElementById("ItemPreview").src = "data:image/png;base64," + evt.data;

is expecting a PNG image, but that isn't what you're sending; you've just pushed out a load of raw pixel data, with no dimensions or stride or format information or anything else.

If your client wants a PNG, you're going to have to use something like imencode to write PNG data to a memory buffer, and base64 encode that instead.

One other important thing to note is that decoded images may have row padding... a few bytes on the end of each row for memory alignment purposes. Therefore, the actual length of each image row may exceed the width of the image multiplied by the size of the each pixel in bytes. That means that this operation:

QByteArray Img((char*)(imgIn.data),imgIn.total()*imgIn.elemSize());

may not, in fact, wrap the entire image buffer in your QByteArray. There are various ways to check the stride/step of an image, but you'd best read the cv::Mat docs as it isn't worth me repeating them all here. This only matters if you're doing raw byte-level image manipulation, like you are here. If you use imencode, you don't need to worry about this.


问:
Chef Cookbooks: Installing Jenkins plugins from GItHub
I am using Chef to deploy my Jenkins instance. I am currently using the Jenkins cookbook found in the Chef Supermarket: https://supermarket.chef.io/cookbooks/jenkins .

I'm managing my plugins by adding them to the _master_war.rb recipe file. Most plugins I'm finding are straight forward, follow the specified instructions in the cookbook supermarket page and can be found for download on the https://wiki.jenkins-ci.org site with a link to a hpi/jpi file.

I'm finding some plugins which are only available via GitHub. For example, https://plugins.jenkins.io/workflow-cps. My current plugin code looks like thus:

```<code># Installs the latest version of the workflow-job Plugin for Jenkins
# The BitBucket Build Status Notifier plugin is dependent on this plugin
# https://github.com/jenkinsci/workflow-job-plugin

jenkins_plugin 'workflow-job-plugin' do
  source 'https://github.com/jenkinsci/workflow-job-plugin.git'
  notifies :restart, 'runit_service[jenkins]', :immediately
end
</code>```

Unfortunately, this syntax does not appear to install the plugin via git successfully on my jenkins instance. The following warning appears after running the recipe on the node jenkins is running on:

```<code>Bitbucket Build Status Notifier Plugin v1.3.3
    workflow-job v1.11 is missing. To fix, install v1.11 or later.
    workflow-cps v1.11 is missing. To fix, install v1.11 or later.
    multiple-scms v0.6 is missing. To fix, install v0.6 or later.
</code>```

What would be the correct way / syntax to use to go about downloading and installing these plugins from github to my jenkins instance using the jenkins cookbook for Chef?

答: I would to to add to this discussion that I found a way to work through this issue. When a page like this one is the official source for a Jenkins plugin: plugins.jenkins.io/workflow-cps, on the right hand side of the screen is an 'Archives' link which will take you to the .hpi listing for all available versions of the given plugin. I.E. updates.jenkins.io/download/plugins/workflow-cps . Using the link address for the listed versions you can source the appropriate .hpi file</p>

Body:
I am using Chef to deploy my Jenkins instance. I am currently using the Jenkins cookbook found in the Chef Supermarket: https://supermarket.chef.io/cookbooks/jenkins .

I'm managing my plugins by adding them to the _master_war.rb recipe file. Most plugins I'm finding are straight forward, follow the specified instructions in the cookbook supermarket page and can be found for download on the https://wiki.jenkins-ci.org site with a link to a hpi/jpi file.

I'm finding some plugins which are only available via GitHub. For example, https://plugins.jenkins.io/workflow-cps. My current plugin code looks like thus:

# Installs the latest version of the workflow-job Plugin for Jenkins
# The BitBucket Build Status Notifier plugin is dependent on this plugin
# https://github.com/jenkinsci/workflow-job-plugin

jenkins_plugin 'workflow-job-plugin' do
  source 'https://github.com/jenkinsci/workflow-job-plugin.git'
  notifies :restart, 'runit_service[jenkins]', :immediately
end

Unfortunately, this syntax does not appear to install the plugin via git successfully on my jenkins instance. The following warning appears after running the recipe on the node jenkins is running on:

Bitbucket Build Status Notifier Plugin v1.3.3
    workflow-job v1.11 is missing. To fix, install v1.11 or later.
    workflow-cps v1.11 is missing. To fix, install v1.11 or later.
    multiple-scms v0.6 is missing. To fix, install v0.6 or later.

What would be the correct way / syntax to use to go about downloading and installing these plugins from github to my jenkins instance using the jenkins cookbook for Chef?


问:
Clearing the text from the python shell
OK, so I am currently messing around coding hangman in python and was wondering if I can clear what it says in the python shell as I don't just wan't the person to read the word.

```<code>import time
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")

time.sleep(2)

guess = input("please enter your guess")
</code>```

I would like to remove all the text  in the shell.

答:
os.system("cls") for windows or os.system("clear") for mac/linux.

Then put that line of code where you wish for the program to delete all the text in the shell.

Title: Clearing the text from the python shell

Body:
OK, so I am currently messing around coding hangman in python and was wondering if I can clear what it says in the python shell as I don't just wan't the person to read the word.

import time
keyword = input(" Please enter the word you want the person to guess")
lives = int(input("How many lives would you like to have?"))
print ("There are ", len(keyword), "letters in the word")

time.sleep(2)

guess = input("please enter your guess")

I would like to remove all the text  in the shell.


问:
Vim Flake8 ignoring project config file
vim-flake8 seems to be ignoring my project-specific config file.  If I run flake8 from the command line in my project root, it works, but when I open vim and try to run flake8 against my files, its not picking up that setting.  I know this because its using a default line-length of 79, instead of my project-specific 120.

I read this post: flake8 not picking up config file, but it doesn't seem to help.  It mentions a bug fixed over a year ago in the comments.

In my project root, I have a .flake8 file with a [flake8] section.

How does vim-flake8 determine what the project root is and where to look for the config file?  Does it just use the directory in which Vim is opened?

答:
I ran into the same problem today. Flake8 ran fine from the command line, but inside of vim every config file seemed do be ignored by syntastic. Running flake8 inside of vim itself (with :!flake8) picked up the config.

Based on the answer from Tomi I fixed it by adding

```<code>    let g:syntastic_python_flake8_args='--config=setup.cfg'
</code>```

to my vim config, which should work if vim is started from the project root. Still a bit hacky but at least the flake8 config stays in a single place.

Title: Vim Flake8 ignoring project config file

Body:
I ran into the same problem today. Flake8 ran fine from the command line, but inside of vim every config file seemed do be ignored by syntastic. Running flake8 inside of vim itself (with :!flake8) picked up the config.

Based on the answer from Tomi I fixed it by adding

    let g:syntastic_python_flake8_args='--config=setup.cfg'

to my vim config, which should work if vim is started from the project root. Still a bit hacky but at least the flake8 config stays in a single place.


问:
Export Range of (Part of) an Excel Sheet to CSV
I'm trying to figure out how to export only a portion of the sheet to csv without cycling through each row or cell and printing them individually to file. I need to maintain local formatting as one requirement.

```<code>Sheets("PI_OUTPUT").Copy
</code>```

This copies the entire sheet. I have formulas in rows 1 to 20000 and columns A to X, but with a variable amount of blank rows after the data has been processed. If I use the copy method I copy all the empty rows, which outputs as rows of commas, etc.

I tried using activesheet.deleterows to trim the output file after the copy, but that gives me an error.

I've tried using:

```<code>Worksheets("PI_OUTPUT").Activate
 Sheets("PI_OUTPUT").Range("A2:X5000").Copy
</code>```

I've tried to use another suggestion: specialcells(xlCellTypeVisible), but I can't seem to get it to work:

```<code>Set rng = Sheets("PI_OUTPUT").SpecialCells(xlCellTypeVisible)
Set Workbook = Workbooks.Add
With Workbook
    Call rng.Copy
    .Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
    .SaveAs filename:=MyPath & MyFileName, FileFormat:=xlCSV
    .Close
End With
</code>```

To make it worse, I have to do it across a number of sheets, all with variable number of columns and rows, all saved to separate files. So I'm looking for something I can repeat a number of times. I've got a folder path pop up to select the location, and have a dynamically constructed file name, but the copy/paste evades to file me.

答:
You can use the code below;</p>
```<code>Sub testexport()
 'Adpated from OzGrid;
 ' export Macro as CSV

Dim wsh As Worksheet

Set wsh = ThisWorkbook.Worksheets("PI_OUTPUT")

With wsh.Range("A2:X20000")

.AutoFilter 1, "<>" 'Filter to get only non-blank cells

'assuming there is no blank cell within a filled row:
wsh.Range(wsh.Cells(2, 1), wsh.Cells(24, 2).End(xlDown)).Copy 'copy non-blank cells

'.AutoFilter should not cancel autofilter as it clears cutcopy mode

End With

Application.DisplayAlerts = False 'avoid "save prompt window"

Workbooks.Add

ActiveSheet.Paste

'Saves to C drive as Book2.csv
ActiveSheet.SaveAs Filename:= _
"C:\Book2.csv" _
, FileFormat:=xlCSV, CreateBackup:=False

ActiveWorkbook.Close

wsh.Range("A2:X20000").AutoFilter 'clear the filter

Application.DisplayAlerts = True 'set to default

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to figure out how to export only a portion of the sheet to csv without cycling through each row or cell and printing them individually to file. I need to maintain local formatting as one requirement.

Sheets("PI_OUTPUT").Copy

This copies the entire sheet. I have formulas in rows 1 to 20000 and columns A to X, but with a variable amount of blank rows after the data has been processed. If I use the copy method I copy all the empty rows, which outputs as rows of commas, etc.

I tried using activesheet.deleterows to trim the output file after the copy, but that gives me an error.

I've tried using:

Worksheets("PI_OUTPUT").Activate
 Sheets("PI_OUTPUT").Range("A2:X5000").Copy

I've tried to use another suggestion: specialcells(xlCellTypeVisible), but I can't seem to get it to work:

Set rng = Sheets("PI_OUTPUT").SpecialCells(xlCellTypeVisible)
Set Workbook = Workbooks.Add
With Workbook
    Call rng.Copy
    .Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
    .SaveAs filename:=MyPath & MyFileName, FileFormat:=xlCSV
    .Close
End With

To make it worse, I have to do it across a number of sheets, all with variable number of columns and rows, all saved to separate files. So I'm looking for something I can repeat a number of times. I've got a folder path pop up to select the location, and have a dynamically constructed file name, but the copy/paste evades to file me.

Body:
You can use the code below;

Sub testexport()
 'Adpated from OzGrid;
 ' export Macro as CSV

Dim wsh As Worksheet

Set wsh = ThisWorkbook.Worksheets("PI_OUTPUT")

With wsh.Range("A2:X20000")

.AutoFilter 1, "<>" 'Filter to get only non-blank cells

'assuming there is no blank cell within a filled row:
wsh.Range(wsh.Cells(2, 1), wsh.Cells(24, 2).End(xlDown)).Copy 'copy non-blank cells

'.AutoFilter should not cancel autofilter as it clears cutcopy mode

End With

Application.DisplayAlerts = False 'avoid "save prompt window"

Workbooks.Add

ActiveSheet.Paste

'Saves to C drive as Book2.csv
ActiveSheet.SaveAs Filename:= _
"C:\Book2.csv" _
, FileFormat:=xlCSV, CreateBackup:=False

ActiveWorkbook.Close

wsh.Range("A2:X20000").AutoFilter 'clear the filter

Application.DisplayAlerts = True 'set to default

End Sub


问:
How do you keep current paginate_button active (bootstrap) after refresh?
I want to click button and keep active currrent button after refresh/reload

My URLs not change when I click other paginate_button , But page is change.

--This button--

https://i.stack.imgur.com/86dJj.jpg

--This code--

```<code><ul class="pagination">
<li class="paginate_button previous disabled" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_previous">
    <a href="#">Previous</a>
</li>
<li class="paginate_button active" aria-controls="dataTables-example" tabindex="0">
    <a href="#">1</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">2</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">3</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">4</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">5</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">6</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0">
    <a href="#">7</a>
</li>
<li class="paginate_button next" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_next">
    <a href="#">Next</a>
</li>
</code>```

答:
move the active class to the
 you want to be active for that page. Example: https://yoursite/page/2 would mean that the second
 would have the active class.

Body:
I want to click button and keep active currrent button after refresh/reload

My URLs not change when I click other paginate_button , But page is change.

--This button--

https://i.stack.imgur.com/86dJj.jpg

--This code--

    Previous

    1

    2

    3

    4

    5

    6

    7

    Next

Body: move the active class to the <li> you want to be active for that page. Example: https://yoursite/page/2 would mean that the second <li> would have the active class.


问:
String Fraction to Value in VBA
How can fraction as a string be converted to a numeric value?

```<code>strFrac = "3/2"
</code>```

Currently doing by splitting string to get numerator and denominator.

```<code>Dim x() As String
x = Split(strFrac, "/")
</code>```

Then using Val() and dividing.

```<code>v = Val(x(0)) / Val(x(1))
</code>```

result: v = 1.5

Is there a more direct approach?  Would be nice if something like Val("3/2") would work.

答:
You want Application.Evaluate

```<code>Sub TEST()
Dim v As Double
Dim strFrac As String
strFrac = "3/2"
v = Application.Evaluate(strFrac)
Debug.Print v
End Sub
</code>```

Title: String Fraction to Value in VBA

Body:
How can fraction as a string be converted to a numeric value?

strFrac = "3/2"

Currently doing by splitting string to get numerator and denominator.

Dim x() As String
x = Split(strFrac, "/")

Then using Val() and dividing.

v = Val(x(0)) / Val(x(1))

result: v = 1.5

Is there a more direct approach?  Would be nice if something like Val("3/2") would work.

Body:
You want Application.Evaluate

Sub TEST()
Dim v As Double
Dim strFrac As String
strFrac = "3/2"
v = Application.Evaluate(strFrac)
Debug.Print v
End Sub


问:
How to Learn MS SQL Server 2005?
I would like to start learning SQL Server 2005 on my own.  Can anyone recommend good books or websites that will be a good start for me?</p>

答:
Books:

Inside Microsoft SQL Server 2005: T-SQL Querying

Inside Microsoft SQL Server 2005: The Storage Engine

Pro SQL Server 2005 Database Design and Optimization

Sites:

SQL Server Programming Hacks

sqlserverpedia

Microsoft SQL Server 2005 – Learning Portal

Good SQL Articles To Read If You Can't Afford Books

OwnerDisplayName: Craig G

Title: How to Learn MS SQL Server 2005?

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: SQLMenace

LastEditorDisplayName: SQLMenace


问:
Using a database to store configuration rather than a configuration file
Unfortunately searching for this kind of material produces a lot of noise for me so I was wondering if anyone here knew of a good resource for anyone wishing to learn how to use a database to store site configuration info rather than a file.

I guess some points I'm interested in are:
1) How to store the data. One array like e107? Separate row for each configurable?
2) How to get the configuration data. Global array?

答:
I'm gonna swear in church and humbly point out that one can do both :)

You can store the configuration parameters in a database and then produce whatever configuration file you need when the parameters are saved.

This is a form of redundancy, but it also gives the following advantages:

You can now combine configuration parameters with ordinary queries.

For each parameter in DB, you can add a default value, which means you can easily "reset" it

You can choose to version handle the configuration more easily (even track changes).

You can even build a web form to modify the configuration (and now you don't need direct access to web server).

Sensitive data is no longer visible on web server filesystem.


问:
Unable to set RSA private key as config var
I'm trying to deploy an Express app to Heroku. The trouble I'm having is that Heroku or something along the way is screwing up the format of the RSA private key string. I have the following in my .env which works locally and is kept out of git:

```<code>TYPE=
PROJECT_ID=
PRIVATE_KEY_ID=
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
CLIENT_EMAIL=
CLIENT_ID=
AUTH_URI=
TOKEN_URI=
AUTH_CERT_URL=
CLIENT_CERT_URL=
</code>```

I initially used https://github.com/xavdid/heroku-config to set the above vars instead of doing it by hand through the dashboard on Heroku, but that private key failed.

Then I tried setting that value manually by copy/pasting (without double quotes) through the Heroku Dashboard, still failed.

Finally I set the value via heroku config:set, but still fails to parse it when the app starts up.

I even tried replacing \n with '\n' as someone did here and using quotes with heroku config:set PRIVATE_KEY="", but still doesn't work.

So my question is, is Heroku doing something funky with the long string value? Or am I missing something. The above values are called/used as shown below:

```<code>const { credential } = require('firebase-admin')

exports.serviceAccount = {
  type: process.env.TYPE,
  project_id: process.env.PROJECT_ID,
  private_key_id: process.env.PRIVATE_KEY_ID,
  private_key: process.env.PRIVATE_KEY,
  client_email: process.env.CLIENT_EMAIL,
  client_id: process.env.CLIENT_ID,
  auth_uri: process.env.AUTH_URI,
  token_uri: process.env.TOKEN_URI,
  auth_provider_x509_cert_url: process.env.AUTH_CERT_URL,
  client_x509_cert_url: process.env.CLIENT_CERT_URL
}

exports.credential = credential.cert(exports.serviceAccount)

exports.databaseURL = process.env.DATABASE_URL

exports.adminConfig = {
  credential: exports.credential,
  databaseURL: exports.databaseURL
}
</code>```

And logs from Heroku:

```<code>2017-06-05T01:50:13.761150+00:00 app[web.1]: > NODE_ENV=production node ./server/server.prod.js
2017-06-05T01:50:14.231853+00:00 app[web.1]: /app/node_modules/firebase-admin/lib/auth/credential.js:129
2017-06-05T01:50:14.231876+00:00 app[web.1]:             throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse private key: ' + error);
2017-06-05T01:50:14.231877+00:00 app[web.1]:             ^
2017-06-05T01:50:14.231878+00:00 app[web.1]:
2017-06-05T01:50:14.231878+00:00 app[web.1]: Error: Failed to parse private key: Error: Invalid PEM formatted message.
2017-06-05T01:50:14.231883+00:00 app[web.1]:     at FirebaseAppError.FirebaseError [as constructor] (/app/node_modules/firebase-admin/lib/utils/error.js:39:28)
2017-06-05T01:50:14.231884+00:00 app[web.1]:     at new FirebaseAppError (/app/node_modules/firebase-admin/lib/utils/error.js:84:23)
2017-06-05T01:50:14.231885+00:00 app[web.1]:     at new Certificate (/app/node_modules/firebase-admin/lib/auth/credential.js:129:19)
2017-06-05T01:50:14.231886+00:00 app[web.1]:     at new CertCredential (/app/node_modules/firebase-admin/lib/auth/credential.js:195:33)
2017-06-05T01:50:14.231887+00:00 app[web.1]:     at Object.cert (/app/node_modules/firebase-admin/lib/firebase-namespace.js:189:58)
2017-06-05T01:50:14.231887+00:00 app[web.1]:     at Object.<anonymous> (/app/server/firebase/index.js:16:33)
2017-06-05T01:50:14.231888+00:00 app[web.1]:     at Module._compile (module.js:569:30)
2017-06-05T01:50:14.231888+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:580:10)
2017-06-05T01:50:14.231889+00:00 app[web.1]:     at Module.load (module.js:503:32)
2017-06-05T01:50:14.231889+00:00 app[web.1]:     at tryModuleLoad (module.js:466:12)
</code>```

答:
I was able to solve my issue using a comment suggestion I found here.

So on the Heroku dashboard for the app, I set the PRIVATE_KEY value to be double quoted:

I then changed

private_key: process.env.PRIVATE_KEY

to

private_key: JSON.parse(process.env.PRIVATE_KEY)

and finally redeployed via git push heroku master and the app started up fine.

2018-10-27: The comments from the link above are gone now. But essentially the commenter had mentioned that the string is effectively a JSON string which needs to be parsed back into a String.

2019-08-01: The domain originally linked is no longer valid. So I have replaced the original link with one from the Wayback Machine.

Body:
I'm trying to deploy an Express app to Heroku. The trouble I'm having is that Heroku or something along the way is screwing up the format of the RSA private key string. I have the following in my .env which works locally and is kept out of git:

TYPE=
PROJECT_ID=
PRIVATE_KEY_ID=
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
CLIENT_EMAIL=
CLIENT_ID=
AUTH_URI=
TOKEN_URI=
AUTH_CERT_URL=
CLIENT_CERT_URL=

I initially used https://github.com/xavdid/heroku-config to set the above vars instead of doing it by hand through the dashboard on Heroku, but that private key failed.

Then I tried setting that value manually by copy/pasting (without double quotes) through the Heroku Dashboard, still failed.

Finally I set the value via heroku config:set, but still fails to parse it when the app starts up.

I even tried replacing \n with '\n' as someone did here and using quotes with heroku config:set PRIVATE_KEY="", but still doesn't work.

So my question is, is Heroku doing something funky with the long string value? Or am I missing something. The above values are called/used as shown below:

const { credential } = require('firebase-admin')

exports.serviceAccount = {
  type: process.env.TYPE,
  project_id: process.env.PROJECT_ID,
  private_key_id: process.env.PRIVATE_KEY_ID,
  private_key: process.env.PRIVATE_KEY,
  client_email: process.env.CLIENT_EMAIL,
  client_id: process.env.CLIENT_ID,
  auth_uri: process.env.AUTH_URI,
  token_uri: process.env.TOKEN_URI,
  auth_provider_x509_cert_url: process.env.AUTH_CERT_URL,
  client_x509_cert_url: process.env.CLIENT_CERT_URL
}

exports.credential = credential.cert(exports.serviceAccount)

exports.databaseURL = process.env.DATABASE_URL

exports.adminConfig = {
  credential: exports.credential,
  databaseURL: exports.databaseURL
}

And logs from Heroku:

2017-06-05T01:50:13.761150+00:00 app[web.1]: > NODE_ENV=production node ./server/server.prod.js
2017-06-05T01:50:14.231853+00:00 app[web.1]: /app/node_modules/firebase-admin/lib/auth/credential.js:129
2017-06-05T01:50:14.231876+00:00 app[web.1]:             throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse private key: ' + error);
2017-06-05T01:50:14.231877+00:00 app[web.1]:             ^
2017-06-05T01:50:14.231878+00:00 app[web.1]:
2017-06-05T01:50:14.231878+00:00 app[web.1]: Error: Failed to parse private key: Error: Invalid PEM formatted message.
2017-06-05T01:50:14.231883+00:00 app[web.1]:     at FirebaseAppError.FirebaseError [as constructor] (/app/node_modules/firebase-admin/lib/utils/error.js:39:28)
2017-06-05T01:50:14.231884+00:00 app[web.1]:     at new FirebaseAppError (/app/node_modules/firebase-admin/lib/utils/error.js:84:23)
2017-06-05T01:50:14.231885+00:00 app[web.1]:     at new Certificate (/app/node_modules/firebase-admin/lib/auth/credential.js:129:19)
2017-06-05T01:50:14.231886+00:00 app[web.1]:     at new CertCredential (/app/node_modules/firebase-admin/lib/auth/credential.js:195:33)
2017-06-05T01:50:14.231887+00:00 app[web.1]:     at Object.cert (/app/node_modules/firebase-admin/lib/firebase-namespace.js:189:58)
2017-06-05T01:50:14.231887+00:00 app[web.1]:     at Object.<anonymous> (/app/server/firebase/index.js:16:33)
2017-06-05T01:50:14.231888+00:00 app[web.1]:     at Module._compile (module.js:569:30)
2017-06-05T01:50:14.231888+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:580:10)
2017-06-05T01:50:14.231889+00:00 app[web.1]:     at Module.load (module.js:503:32)
2017-06-05T01:50:14.231889+00:00 app[web.1]:     at tryModuleLoad (module.js:466:12)


问:
Paste lagging values into collapsed string/vector
How can I take lagging values of a column, and vectorize the pasting of values into a string?

For example, assuming the following data frame, the result would be column 'lagged'

```<code>     date             total_volume      lagged
     <date>           <int>             <chr>
     2017-01-01       323512            323512
     2017-01-02        28014            323512, 28014
     2017-01-03        12323            323512, 28014, 12323
     2017-01-04        11580            323512, 28014, 12323, 11580
     2017-01-05        12161
     2017-01-06        10796
     2017-01-07        10087
     2017-01-08        10406
     2017-01-09        11261
     2017-01-10        11333
</code>```

I tried using the approach:

```<code>df %>%
 mutate(lagged = paste(total_volume[1:row_number()], collapse = ','))
</code>```

but that returns an error.  I can create a function that loops and creates it, but when using the function in dplyr, it does not work correctly.

```<code>function(x) {
 for (i in 1:nrow(x)){
  print(paste(x$total_volume[1:i], collapse = ','))
 }
}
</code>```

答:
I figured out you can also call accumulate directly.

Here's what I came up with, which works with grouping's (ie:  the accumulate is reset at the beginning of a new group):

```<code>df %>%
group_by(group) %>%
mutate(lagged = accumulate(total_volume, paste, collapse = ',')
</code>```

Body:
How can I take lagging values of a column, and vectorize the pasting of values into a string?

For example, assuming the following data frame, the result would be column 'lagged'

     date             total_volume      lagged
     <date>           <int>             <chr>
     2017-01-01       323512            323512
     2017-01-02        28014            323512, 28014
     2017-01-03        12323            323512, 28014, 12323
     2017-01-04        11580            323512, 28014, 12323, 11580
     2017-01-05        12161
     2017-01-06        10796
     2017-01-07        10087
     2017-01-08        10406
     2017-01-09        11261
     2017-01-10        11333

I tried using the approach:

df %>%
 mutate(lagged = paste(total_volume[1:row_number()], collapse = ','))

but that returns an error.  I can create a function that loops and creates it, but when using the function in dplyr, it does not work correctly.

function(x) {
 for (i in 1:nrow(x)){
  print(paste(x$total_volume[1:i], collapse = ','))
 }
}

Body:
I figured out you can also call accumulate directly.

Here's what I came up with, which works with grouping's (ie:  the accumulate is reset at the beginning of a new group):

df %>%
group_by(group) %>%
mutate(lagged = accumulate(total_volume, paste, collapse = ',')


问:
node mongoose how to get a full list of schemas (documents and subdocuments )
I know that I can get a full list of models using modelNames() :

```<code>console.log('MODELS: %j', mongoose.modelNames());
</code>```

Is there any way to get a full list of schemas

i.e.  with the following User model

```<code>const Role = new mongoose.Schema({ .... });
const Permission = new mongoose.Schema({ .... });

const UserSchema = new mongoose.Schema({
  username: { ...  },
  roles: [Role],
  permissions: [Permission]
});
</code>```

I would like to get an Array object like ['Role', 'Permission']

thanks for feedback

答:
```<code>const mongoose = require('mongoose');

//Schema definitions...

const schemas = [];
mongoose.modelNames().forEach(function(modelName){
    schemas.push(mongoose.model(modelName).schema.obj);
})

console.log(schemas);
</code>```

Body:
I know that I can get a full list of models using modelNames() :

console.log('MODELS: %j', mongoose.modelNames());

Is there any way to get a full list of schemas

i.e.  with the following User model

const Role = new mongoose.Schema({ .... });
const Permission = new mongoose.Schema({ .... });

const UserSchema = new mongoose.Schema({
  username: { ...  },
  roles: [Role],
  permissions: [Permission]
});

I would like to get an Array object like ['Role', 'Permission']

thanks for feedback


问:
Material2: Show/Hide md-sidenav depending on media
i would like to open the md-sidenav on large screen and close it on mobile device. What would be the right way to do it inside my application?

Is there any possibility to query the media inside angular2 component?

答:
i've just found a little bit better approach to listen to screen changes in Angular: https://github.com/angular/flex-layout/wiki/ObservableMedia

it's a Angular Flex Layout module that provides the mediaQuery activations notifications as observable. so there is no need to listen to create a resize listener manually.

besides, MediaChange Class provides handy aliases (lg, md, xs etc.) that can be used to make decisions about screen size-specific expressions.

check out examples on their wiki-page.


问:
MySql server PID not found
I have CentOS 6.4 with NGINX.

When I try to start/stop/restart mysql server (/etc/init.d/mysqld restart) I get this error:

```<code>MySQL server PID file could not be found!                  [FAILED]
Starting MySQL..The server quit without updating PID file ([FAILED]/mysql/mysqld.pid).
</code>```

What can I do to solve this problem?

Thanks!

答:
First of all make sure that which folder/file is not exist in /var/run/mysqld/mysqld.pid

if dir not exists then create it as:

```<code>sudo mkdir -p /var/run/mysqld/
</code>```

if mysqld.pid is not exists then create it as:

```<code>sudo touch /var/run/mysqld/mysqld.pid
</code>```

change ownership as:

```<code>sudo chown mysql:mysql -R /var/run/mysqld
chmod 775 -R /var/run/mysqld
</code>```

restart mysql service

```<code>sudo service mysql restart
</code>```

Title: MySql server PID not found

Body:
I have CentOS 6.4 with NGINX.

When I try to start/stop/restart mysql server (/etc/init.d/mysqld restart) I get this error:

MySQL server PID file could not be found!                  [FAILED]
Starting MySQL..The server quit without updating PID file ([FAILED]/mysql/mysqld.pid).

What can I do to solve this problem?

Thanks!

Body:
First of all make sure that which folder/file is not exist in /var/run/mysqld/mysqld.pid

if dir not exists then create it as:

sudo mkdir -p /var/run/mysqld/

if mysqld.pid is not exists then create it as:

sudo touch /var/run/mysqld/mysqld.pid

change ownership as:

sudo chown mysql:mysql -R /var/run/mysqld
chmod 775 -R /var/run/mysqld

restart mysql service

sudo service mysql restart


问:
Swift 3 trying to do conditional with string
I have the following code that was working great in swift 2.3

```<code>"code": self.searchByCode == true ? description : NSNull(),
</code>```

In Swift 3 Im getting this error.

Any clue?

答:
I suggest using nil instead of NSNull() especially you are using the Swift 3 as the following:

```<code>self.searchByCode == true ? description : nil
</code>```

And it should make the error goes away.

Body:
I have the following code that was working great in swift 2.3

"code": self.searchByCode == true ? description : NSNull(),

In Swift 3 Im getting this error.

Any clue?

Body:
I suggest using nil instead of NSNull() especially you are using the Swift 3 as the following:

self.searchByCode == true ? description : nil

And it should make the error goes away.


问:
Clang compile error related to static_assert and boost::hana
Consider the following problem which compiles successfully on Clang 3.8 using -std=c++14.

```<code>#include <boost/hana.hpp>

namespace hana = boost::hana;

int main() {
    constexpr auto indices = hana::range<unsigned, 0, 3>();
    hana::for_each(indices, [&](auto i) {
        hana::for_each(indices, [&](auto j) {
            constexpr bool test = (i == (j == i ? j : i));
            static_assert(test, "error");
        });
    });
}
</code>```

The test is quite non-sensical but that is not the point. Consider now an alternative version where the test is directly put inside the static_assert:

```<code>#include <boost/hana.hpp>

namespace hana = boost::hana;

int main() {
    constexpr auto indices = hana::range<unsigned, 0, 3>();
    hana::for_each(indices, [&](auto i) {
        hana::for_each(indices, [&](auto j) {
            static_assert((i == (j == i ? j : i)), "error");
        });
    });
}
</code>```

Now I get a bunch of compile errors, saying

error: reference to local variable i declared in enclosing lambda expression

Question: What causes the second version to fail?

Edit: Could this be a compiler bug? I turns out that when accessing i before the static_assert, everything compiles again:

```<code>#include <boost/hana.hpp>

namespace hana = boost::hana;

int main() {
    constexpr auto indices = hana::range<unsigned, 0, 3>();
    hana::for_each(indices, [&](auto i) {
        hana::for_each(indices, [&](auto j) {
            constexpr auto a = i;
            static_assert((i == (j == i ? j : i)), "error");
        });
    });
}
</code>```

Update: The same behaviour can be reproduced on Clang 4.0 and the current development branch 5.0.

Update 2: As suggested by @LouisDionne, I filed this as a bug: https://bugs.llvm.org/show_bug.cgi?id=33318.

答: This is a bug in the Clang compiler and was acknowledged as such. Here is the link to it: https://bugs.llvm.org/show_bug.cgi?id=33318.</p>

Body:
Consider the following problem which compiles successfully on Clang 3.8 using -std=c++14.

#include <boost/hana.hpp>

namespace hana = boost::hana;

int main() {
    constexpr auto indices = hana::range<unsigned, 0, 3>();
    hana::for_each(indices, [&](auto i) {
        hana::for_each(indices, [&](auto j) {
            constexpr bool test = (i == (j == i ? j : i));
            static_assert(test, "error");
        });
    });
}

The test is quite non-sensical but that is not the point. Consider now an alternative version where the test is directly put inside the static_assert:

#include <boost/hana.hpp>

namespace hana = boost::hana;

int main() {
    constexpr auto indices = hana::range<unsigned, 0, 3>();
    hana::for_each(indices, [&](auto i) {
        hana::for_each(indices, [&](auto j) {
            static_assert((i == (j == i ? j : i)), "error");
        });
    });
}

Now I get a bunch of compile errors, saying

error: reference to local variable i declared in enclosing lambda expression

Question: What causes the second version to fail?

Edit: Could this be a compiler bug? I turns out that when accessing i before the static_assert, everything compiles again:

#include <boost/hana.hpp>

namespace hana = boost::hana;

int main() {
    constexpr auto indices = hana::range<unsigned, 0, 3>();
    hana::for_each(indices, [&](auto i) {
        hana::for_each(indices, [&](auto j) {
            constexpr auto a = i;
            static_assert((i == (j == i ? j : i)), "error");
        });
    });
}

Update: The same behaviour can be reproduced on Clang 4.0 and the current development branch 5.0.

Update 2: As suggested by @LouisDionne, I filed this as a bug: https://bugs.llvm.org/show_bug.cgi?id=33318.


问:
How do I access double pointer from C code in ASM's stack
I have a main.c function which has the following statement:

```<code>int  initarr(int**arr, int n, int (*initfunc)(int));
</code>```

Then I call the function in c like that:

```<code>success = initarr(&arr, n, getNum);
</code>```

The question is, in assembly code, in MODEL SMALL, the first argument in the function above will be in the memory as WORD or DWORD?

In other words, when I write the code, will this work:

```<code>PUSH BP
MOV BP,SP

PUSH DI
MOV DI, WORD PTR[BP+4] ; DI will hold &arr.
</code>```

And now DI will hold arr's address.

If it is true, How will I be able to access arr[0]'s value if so?

```<code>PUSH BP
MOV BP,SP

PUSH DI
PUSH BX
MOV DI, WORD PTR[BP+4]
MOV BX, WORD PTR[DI]
</code>```

Will BX hold the address of the array? I mean, the address of the first cell?

If so, how can I access arr[0] now?

Perhaps MOV DX, WORD PTR[BX] ?

答:
In model small, addresses are sized 2 bytes. A double pointer is still an address!

in order to access arr[0], you would write the following:

```<code>MOV DI, [BP+4]  ; no need casting, DI register is sized 2 bytes.
MOV SI, [DI]    ; get what DI is pointing to, and put it to SI.
                ; you could say: DI=arr[][], SI = arr[]
MOV AX, [SI]    ; now AX = arr[0]
</code>```

if we would like to access arr[i], we would do the following:

```<code>MOV DI, [BP+4]
MOV SI, [DI]
MOV AX, i
SHL AX, 1   ; because arr[] contains int numbers which are sized 2 bytes.
ADD SI, AX
MOV AX, [SI]    ; now AX = arr[i].  SI = &arr[i].
</code>```

Body:
I have a main.c function which has the following statement:

int  initarr(int**arr, int n, int (*initfunc)(int));

Then I call the function in c like that:

success = initarr(&arr, n, getNum);

The question is, in assembly code, in MODEL SMALL, the first argument in the function above will be in the memory as WORD or DWORD?

In other words, when I write the code, will this work:

PUSH BP
MOV BP,SP

PUSH DI
MOV DI, WORD PTR[BP+4] ; DI will hold &arr.

And now DI will hold arr's address.

If it is true, How will I be able to access arr[0]'s value if so?

PUSH BP
MOV BP,SP

PUSH DI
PUSH BX
MOV DI, WORD PTR[BP+4]
MOV BX, WORD PTR[DI]

Will BX hold the address of the array? I mean, the address of the first cell?

If so, how can I access arr[0] now?

Perhaps MOV DX, WORD PTR[BX] ?

Body:
In model small, addresses are sized 2 bytes. A double pointer is still an address!

in order to access arr[0], you would write the following:

MOV DI, [BP+4]  ; no need casting, DI register is sized 2 bytes.
MOV SI, [DI]    ; get what DI is pointing to, and put it to SI.
                ; you could say: DI=arr[][], SI = arr[]
MOV AX, [SI]    ; now AX = arr[0]

if we would like to access arr[i], we would do the following:

MOV DI, [BP+4]
MOV SI, [DI]
MOV AX, i
SHL AX, 1   ; because arr[] contains int numbers which are sized 2 bytes.
ADD SI, AX
MOV AX, [SI]    ; now AX = arr[i].  SI = &arr[i].


问:
error Class "HTML" not found - Laravel 5.4
I am getting the following error:

Class 'HTML' not found (View:
  C:\WORK\Software\XamppOne\htdocs\APOSTXUI\ContractorsClubField\resources\views\includes_header.blade.php)
  (View:
  C:\WORK\Software\XamppOne\htdocs\APOSTXUI\ContractorsClubField\resources\views\includes_header.blade.php)

I have seen answers for 51., 5.2 and 5.3 - but - I have not seen anything for 5.4.

This is what I got when I did the update:

```<code>PS C:\WORK\Software\XamppOne\htdocs\APOSTXUI\ContractorsClubField> composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Updating laravelcollective/html (v5.4.8 => v5.4): Downloading (100%)
Writing lock file
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postUpdate
> php artisan optimize
Generating optimized class loader
The compiled services file has been removed.
</code>```

I did the following:

composer.json

```<code>"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "laravel/tinker": "~1.0",
    "artisaninweb/laravel-soap": "0.3.*",
    "laravelcollective/html": "5.4"
},
</code>```

then I ran composer update

I put the following in app.php

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Application Name
    |--------------------------------------------------------------------------
    |
    | This value is the name of your application. This value is used when the
    | framework needs to place the application's name in a notification or
    | any other location as required by the application or its packages.
    */

    'name' => 'Laravel',

    /*
    |--------------------------------------------------------------------------
    | Application Environment
    |--------------------------------------------------------------------------
    |
    | This value determines the "environment" your application is currently
    | running in. This may determine how you prefer to configure various
    | services your application utilizes. Set this in your ".env" file.
    |
    */

    'env' => env('APP_ENV', 'production'),

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => env('APP_DEBUG', false),

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => env('APP_URL', 'http://localhost'),

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'UTC',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    */

    'key' => env('APP_KEY'),

    'cipher' => 'AES-256-CBC',

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log settings for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Settings: "single", "daily", "syslog", "errorlog"
    |
    */

    'log' => env('APP_LOG', 'single'),

    'log_level' => env('APP_LOG_LEVEL', 'debug'),

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */
        Laravel\Tinker\TinkerServiceProvider::class,

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        // FROM: https://stackoverflow.com/questions/28847726/laravel-5-class-html-not-found
        //trying to use HTML class (KDC)
         Collective\Html\HtmlServiceProvider::class,
         'Collective\Html\HtmlServiceProvider',
    ],
    'serviceProviders' => [
        'Artisaninweb\SoapWrapper\ServiceProvider',
    ],
    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        'Event' => Illuminate\Support\Facades\Event::class,
        'File' => Illuminate\Support\Facades\File::class,
        'Gate' => Illuminate\Support\Facades\Gate::class,
        'Hash' => Illuminate\Support\Facades\Hash::class,
        'Lang' => Illuminate\Support\Facades\Lang::class,
        'Log' => Illuminate\Support\Facades\Log::class,
        'Mail' => Illuminate\Support\Facades\Mail::class,
        'Notification' => Illuminate\Support\Facades\Notification::class,
        'Password' => Illuminate\Support\Facades\Password::class,
        'Queue' => Illuminate\Support\Facades\Queue::class,
        'Redirect' => Illuminate\Support\Facades\Redirect::class,
        'Redis' => Illuminate\Support\Facades\Redis::class,
        'Request' => Illuminate\Support\Facades\Request::class,
        'Response' => Illuminate\Support\Facades\Response::class,
        'Route' => Illuminate\Support\Facades\Route::class,
        'Schema' => Illuminate\Support\Facades\Schema::class,
        'Session' => Illuminate\Support\Facades\Session::class,
        'Storage' => Illuminate\Support\Facades\Storage::class,
        'URL' => Illuminate\Support\Facades\URL::class,
        'Validator' => Illuminate\Support\Facades\Validator::class,
        'View' => Illuminate\Support\Facades\View::class,
        'SoapWrapper' => Artisaninweb\SoapWrapper\Facade::class,
        //FROM: https://stackoverflow.com/questions/28847726/laravel-5-class-html-not-found
        //trying to access the HTML class
        'FORM' => Collective\Html\FormFacade::class,
        'HTML' => Collective\Html\HtmlFacade::class,
    ],

];
</code>```

Here is the snippet of code that is being ran

```<code><li>
          <a href="{{ HTML::linkRoute('logout') }}">
          <i class="icon-key"></i> Log Out </a>
</li>
</code>```

What am I doing wrong here?

TIA

答:
I found my own answer:
https://laracasts.com/discuss/channels/laravel/laravelcollectivehtml-in-laravel-53?page=1

```<code>$ php artisan config:cache
$ php artisan config:clear
</code>```

The suggestion that this was due to an installation issue was wrong.
I also changed

"laravelcollective/html": "5.4"
to
"laravelcollective/html": "5.4.*"

Thanks!

Body:
I am getting the following error:

Class 'HTML' not found (View:
  C:\WORK\Software\XamppOne\htdocs\APOSTXUI\ContractorsClubField\resources\views\includes_header.blade.php)
  (View:
  C:\WORK\Software\XamppOne\htdocs\APOSTXUI\ContractorsClubField\resources\views\includes_header.blade.php)

I have seen answers for 51., 5.2 and 5.3 - but - I have not seen anything for 5.4.

This is what I got when I did the update:

PS C:\WORK\Software\XamppOne\htdocs\APOSTXUI\ContractorsClubField> composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Updating laravelcollective/html (v5.4.8 => v5.4): Downloading (100%)
Writing lock file
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postUpdate
> php artisan optimize
Generating optimized class loader
The compiled services file has been removed.

I did the following:

composer.json

"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "laravel/tinker": "~1.0",
    "artisaninweb/laravel-soap": "0.3.*",
    "laravelcollective/html": "5.4"
},

then I ran composer update

I put the following in app.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Application Name
    |--------------------------------------------------------------------------
    |
    | This value is the name of your application. This value is used when the
    | framework needs to place the application's name in a notification or
    | any other location as required by the application or its packages.
    */

    'name' => 'Laravel',

    /*
    |--------------------------------------------------------------------------
    | Application Environment
    |--------------------------------------------------------------------------
    |
    | This value determines the "environment" your application is currently
    | running in. This may determine how you prefer to configure various
    | services your application utilizes. Set this in your ".env" file.
    |
    */

    'env' => env('APP_ENV', 'production'),

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => env('APP_DEBUG', false),

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => env('APP_URL', 'http://localhost'),

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'UTC',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | This key is used by the Illuminate encrypter service and should be set
    | to a random, 32 character string, otherwise these encrypted strings
    | will not be safe. Please do this before deploying an application!
    |
    */

    'key' => env('APP_KEY'),

    'cipher' => 'AES-256-CBC',

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log settings for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Settings: "single", "daily", "syslog", "errorlog"
    |
    */

    'log' => env('APP_LOG', 'single'),

    'log_level' => env('APP_LOG_LEVEL', 'debug'),

    /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */
        Laravel\Tinker\TinkerServiceProvider::class,

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        // FROM: https://stackoverflow.com/questions/28847726/laravel-5-class-html-not-found
        //trying to use HTML class (KDC)
         Collective\Html\HtmlServiceProvider::class,
         'Collective\Html\HtmlServiceProvider',
    ],
    'serviceProviders' => [
        'Artisaninweb\SoapWrapper\ServiceProvider',
    ],
    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        'Event' => Illuminate\Support\Facades\Event::class,
        'File' => Illuminate\Support\Facades\File::class,
        'Gate' => Illuminate\Support\Facades\Gate::class,
        'Hash' => Illuminate\Support\Facades\Hash::class,
        'Lang' => Illuminate\Support\Facades\Lang::class,
        'Log' => Illuminate\Support\Facades\Log::class,
        'Mail' => Illuminate\Support\Facades\Mail::class,
        'Notification' => Illuminate\Support\Facades\Notification::class,
        'Password' => Illuminate\Support\Facades\Password::class,
        'Queue' => Illuminate\Support\Facades\Queue::class,
        'Redirect' => Illuminate\Support\Facades\Redirect::class,
        'Redis' => Illuminate\Support\Facades\Redis::class,
        'Request' => Illuminate\Support\Facades\Request::class,
        'Response' => Illuminate\Support\Facades\Response::class,
        'Route' => Illuminate\Support\Facades\Route::class,
        'Schema' => Illuminate\Support\Facades\Schema::class,
        'Session' => Illuminate\Support\Facades\Session::class,
        'Storage' => Illuminate\Support\Facades\Storage::class,
        'URL' => Illuminate\Support\Facades\URL::class,
        'Validator' => Illuminate\Support\Facades\Validator::class,
        'View' => Illuminate\Support\Facades\View::class,
        'SoapWrapper' => Artisaninweb\SoapWrapper\Facade::class,
        //FROM: https://stackoverflow.com/questions/28847726/laravel-5-class-html-not-found
        //trying to access the HTML class
        'FORM' => Collective\Html\FormFacade::class,
        'HTML' => Collective\Html\HtmlFacade::class,
    ],

];

Here is the snippet of code that is being ran

           Log Out

What am I doing wrong here?

TIA

Body:
I found my own answer:
https://laracasts.com/discuss/channels/laravel/laravelcollectivehtml-in-laravel-53?page=1

$ php artisan config:cache
$ php artisan config:clear

The suggestion that this was due to an installation issue was wrong.
I also changed

"laravelcollective/html": "5.4"
to
"laravelcollective/html": "5.4.*"

Thanks!


问:
I've tried to bypass ManyToMany relation between 2 models in Django but not sure that it's correct
I'm learning Django,but i don't understand the models.ManyToManyField.So,to bypass i've tried to create 3 models.A,B and C.A and B are the to models which should be in models.ManyToManyField relationship.As i don't understand how it work,i've create a third model called C.And my C model receives 2 Foreign keys coming from A and B,it's the table which puts A and B in a ManyToMany relashionship.I've tried to insert data,and all seems okay.Here is my test code

```<code>class A(models.Model):
    a_name=models.CharField(max_length=50)

    def __str__(self):
        return self.a_name

class B(models.Model):
    b_name=models.CharField(max_length=50)

    def __str__(self):
        return self.b_name

#The table which links A and B with Many to Many relationship and receive A and B Foreign Keys
class C(models.Model):
    a=models.ForeignKey(A,on_delete=models.CASCADE)
    b=models.ForeignKey(B,on_delete=models.CASCADE)
    c_name=models.CharField(max_length=50)

    def __str__(self):
        return self.c_name
</code>```

I think that it's specially help when table C model also has attributes.How do you find the idea?Will it create problems in a more complex web app or i can keep on working that way?

答:
What you're doing is effectively creating an intermediary using a third model (normally it's done using through)

```<code>class A(models.Model):
    a_name=models.CharField(max_length=50)
    b_name = models.ManyToManyField(to='B', through='C')

    def __str__(self):
        return self.a_name
</code>```

What this in essence says is that you're mapping a many to many field to B through the intermediary model C. Django by default creates something like this during a manytomany field mapping:

```<code>class a_b(models.Model):
    a=models.ForeignKey(A,on_delete=models.CASCADE)
    b=models.ForeignKey(B,on_delete=models.CASCADE)
</code>```

Implicitly created connecting a to b. But if you want to add additional fields to this connection use through to create an intermediary.

So the benefit of doing it implicitly, i.e

```<code>class A(models.Model):
    a_name=models.CharField(max_length=50)
    b_name = models.ManyToManyField(B)

    def __str__(self):
        return self.a_name
</code>```

is that you can use functions like .add() and .remove() instead of having to create a C object.

A more concrete example, say that I have a person model

```<code>class Person(models.Model):
    name = models.CharField(max_length=12)
</code>```

and a ClassRoom model:

```<code>class ClassRoom(models.Model):
    room_number = models.IntegerField()
    people_in_room = models.ManyToManyField(Person)
</code>```

Now this lets me add people to a classroom and remove like so

```<code>c.people_in_room.add(Person.objects.create(name='TestPerson')
</code>```

and remove using remove however the relationship of the person to the classroom is unknown, i.e. is it a student or is it a teacher? So what you can do is create an intermediary model

```<code>class ClassRoomRelationship(models.Model):
    classroom = models.ForeignKeyField(ClassRoom)
    person = models.ForeignKeyField(Person)
    relationship = models.CharField(max_length=12)

class ClassRoom(models.Model):
    room_number = models.IntegerField()
    people_in_room = models.ManyToManyField(Person, through='ClassRoomRelationship')
</code>```

Now you can explicitly have the relationship of each person to each classroom.

Body:
I'm learning Django,but i don't understand the models.ManyToManyField.So,to bypass i've tried to create 3 models.A,B and C.A and B are the to models which should be in models.ManyToManyField relationship.As i don't understand how it work,i've create a third model called C.And my C model receives 2 Foreign keys coming from A and B,it's the table which puts A and B in a ManyToMany relashionship.I've tried to insert data,and all seems okay.Here is my test code

class A(models.Model):
    a_name=models.CharField(max_length=50)

    def __str__(self):
        return self.a_name

class B(models.Model):
    b_name=models.CharField(max_length=50)

    def __str__(self):
        return self.b_name

#The table which links A and B with Many to Many relationship and receive A and B Foreign Keys
class C(models.Model):
    a=models.ForeignKey(A,on_delete=models.CASCADE)
    b=models.ForeignKey(B,on_delete=models.CASCADE)
    c_name=models.CharField(max_length=50)

    def __str__(self):
        return self.c_name

I think that it's specially help when table C model also has attributes.How do you find the idea?Will it create problems in a more complex web app or i can keep on working that way?

Body:
What you're doing is effectively creating an intermediary using a third model (normally it's done using through)

class A(models.Model):
    a_name=models.CharField(max_length=50)
    b_name = models.ManyToManyField(to='B', through='C')

    def __str__(self):
        return self.a_name

What this in essence says is that you're mapping a many to many field to B through the intermediary model C. Django by default creates something like this during a manytomany field mapping:

class a_b(models.Model):
    a=models.ForeignKey(A,on_delete=models.CASCADE)
    b=models.ForeignKey(B,on_delete=models.CASCADE)

Implicitly created connecting a to b. But if you want to add additional fields to this connection use through to create an intermediary.

So the benefit of doing it implicitly, i.e

class A(models.Model):
    a_name=models.CharField(max_length=50)
    b_name = models.ManyToManyField(B)

    def __str__(self):
        return self.a_name

is that you can use functions like .add() and .remove() instead of having to create a C object.

A more concrete example, say that I have a person model

class Person(models.Model):
    name = models.CharField(max_length=12)

and a ClassRoom model:

class ClassRoom(models.Model):
    room_number = models.IntegerField()
    people_in_room = models.ManyToManyField(Person)

Now this lets me add people to a classroom and remove like so

c.people_in_room.add(Person.objects.create(name='TestPerson')

and remove using remove however the relationship of the person to the classroom is unknown, i.e. is it a student or is it a teacher? So what you can do is create an intermediary model

class ClassRoomRelationship(models.Model):
    classroom = models.ForeignKeyField(ClassRoom)
    person = models.ForeignKeyField(Person)
    relationship = models.CharField(max_length=12)

class ClassRoom(models.Model):
    room_number = models.IntegerField()
    people_in_room = models.ManyToManyField(Person, through='ClassRoomRelationship')

Now you can explicitly have the relationship of each person to each classroom.


问:
Simple Angular Module not working properly
So I'm trying to do a small test app with angular js I have

    {{firstName + " " + lastName}}

in the the body and this

```<code><script>
      var testapp = angular.module("testApp",[]);
      testapp.controller("myCtrl",function ($scope) {
          $scope.firstName = "John";
          $scope.lastName = "Doe";
      });
  </script>
</code>```

is what it's going off of. However, I'm still receiving this:

How can I get it to display what I want which is "John Doe"? I know I'm probably doing something simple wrong...

答:
Your code is working fine in the code snippet editor.
Could you please post more details

Please find below the working example

var testapp = angular.module("testApp",[]);
      testapp.controller("myCtrl",function ($scope) {
          $scope.firstName = "John";
          $scope.lastName = "Doe";
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="myCtrl">
    {{firstName + " " + lastName}}
  </div></code>```

Body:
So I'm trying to do a small test app with angular js I have

    {{firstName + " " + lastName}}

in the the body and this

is what it's going off of. However, I'm still receiving this:

How can I get it to display what I want which is "John Doe"? I know I'm probably doing something simple wrong...

Body:
Your code is working fine in the code snippet editor.
Could you please post more details

Please find below the working example

var testapp = angular.module("testApp",[]);
      testapp.controller("myCtrl",function ($scope) {
          $scope.firstName = "John";
          $scope.lastName = "Doe";
      });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="myCtrl">
    {{firstName + " " + lastName}}
  </div>


问:
pass an array of array in a subroutine
If I have the following code (thanks to M. Chinoune) in a subroutine

```<code>type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array

type(ragged_array) :: raggar

allocate( raggar%vectors(2) )
allocate( raggar%vectors(1)%elements(3) )
allocate( raggar%vectors(2)%elements(4) )

raggar%vectors(1)%elements=0
raggar%vectors(2)%elements=0
</code>```

if I want to pass raggar in an other subroutine to modify size of raggar. should I do something like :

```<code>CALL MySubroutine(raggar)
</code>```

or

```<code>CALL MySubroutine(raggar%vectors%elements)
</code>```

And then, in my subroutine how can I declare it ?

```<code>SUBROUTINE MySubroutine(raggar)
type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array

type(ragged_array), INTENT(INOUT):: raggar
</code>```

I did many tried but I always get error such as :

The type of the actual argument differs from the types of the dummy argument.

or

the shape matching rules of actual arguments and dummy argument have been violated

答:
Place type definitions into a module and use it in a program and subroutine.</p>

```<code>module my
type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array
end module

program probe
use my
type(ragged_array) :: ragarr
allocate( ragarr%vectors(2) )
allocate( ragarr%vectors(1)%elements(3) )
allocate( ragarr%vectors(2)%elements(4) )
ragarr%vectors(1)%elements=0
ragarr%vectors(2)%elements=0
CALL MySubroutine(ragarr)
end program

SUBROUTINE MySubroutine(rr)
use my
type(ragged_array), INTENT(INOUT):: rr
end subroutine
</code>```

Title: pass an array of array in a subroutine

Body:
If I have the following code (thanks to M. Chinoune) in a subroutine

type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array

type(ragged_array) :: raggar

allocate( raggar%vectors(2) )
allocate( raggar%vectors(1)%elements(3) )
allocate( raggar%vectors(2)%elements(4) )

raggar%vectors(1)%elements=0
raggar%vectors(2)%elements=0

if I want to pass raggar in an other subroutine to modify size of raggar. should I do something like :

CALL MySubroutine(raggar)

or

CALL MySubroutine(raggar%vectors%elements)

And then, in my subroutine how can I declare it ?

SUBROUTINE MySubroutine(raggar)
type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array

type(ragged_array), INTENT(INOUT):: raggar

I did many tried but I always get error such as :

The type of the actual argument differs from the types of the dummy argument.

or

the shape matching rules of actual arguments and dummy argument have been violated

Body:
Place type definitions into a module and use it in a program and subroutine.

module my
type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array
end module

program probe
use my
type(ragged_array) :: ragarr
allocate( ragarr%vectors(2) )
allocate( ragarr%vectors(1)%elements(3) )
allocate( ragarr%vectors(2)%elements(4) )
ragarr%vectors(1)%elements=0
ragarr%vectors(2)%elements=0
CALL MySubroutine(ragarr)
end program

SUBROUTINE MySubroutine(rr)
use my
type(ragged_array), INTENT(INOUT):: rr
end subroutine


问:
Can't center div in bootstrap row
I can't center this div class = "light" in my bootstrap row. I've tried using .center-block and .text-center. Here's my HTML and CSS. It makes an orb that I want centered. </p>

```<code><div class = "container lightcontainer">
        <div class = "row">
                <div class = "col-xs-12">
                    <div class = "light"></div>
                </div>
        </div>
    </div>

.light {
    display: none;
    width: 100px;
    height: 100px;
    background-color: #fff;
    z-index: 10;
    box-shadow:
        inset 0 0 50px #fff,      /* inner white */
        inset 20px 0 80px #f0f,   /* inner left magenta short */
        inset -20px 0 80px #0ff,  /* inner right cyan short */
        inset 20px 0 300px #f0f,  /* inner left magenta broad */
        inset -20px 0 300px #0ff, /* inner right cyan broad */
        0 0 50px #fff,            /* outer white */
        -10px 0 80px #f0f,        /* outer left magenta */
        10px 0 80px #0ff;
    position: absolute;
    top: 0;
    left: 0;
    border-radius: 40%;
    margin: 0 auto;
}
</code>```

答:
Try adding left: 0; right:0px;  margin: 0 auto; to the class .light for aligning that to center and style the parent div for vertically aligning using transform and top

.light {
  //  display: none;
    width: 100px;
    height: 100px;
    background-color: #fff;
    z-index: 10;
    box-shadow:
        inset 0 0 50px #fff,      /* inner white */
        inset 20px 0 80px #f0f,   /* inner left magenta short */
        inset -20px 0 80px #0ff,  /* inner right cyan short */
        inset 20px 0 300px #f0f,  /* inner left magenta broad */
        inset -20px 0 300px #0ff, /* inner right cyan broad */
        0 0 50px #fff,            /* outer white */
        -10px 0 80px #f0f,        /* outer left magenta */
        10px 0 80px #0ff;
    position: absolute;
    top: 0;
    left: 0;
    right:0px;
    border-radius: 40%;
    margin: 0 auto;

}

.light-holder{
     position: fixed;
     width:100%;
     top: 50%;
     transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "container lightcontainer">
        <div class = "row">
                <div class = "col-xs-12 light-holder">
                    <div class = "light"></div>
                </div>
        </div>
    </div></code>```

Title: Can't center div in bootstrap row

Body:
I can't center this div class = "light" in my bootstrap row. I've tried using .center-block and .text-center. Here's my HTML and CSS. It makes an orb that I want centered.

.light {
    display: none;
    width: 100px;
    height: 100px;
    background-color: #fff;
    z-index: 10;
    box-shadow:
        inset 0 0 50px #fff,      /* inner white */
        inset 20px 0 80px #f0f,   /* inner left magenta short */
        inset -20px 0 80px #0ff,  /* inner right cyan short */
        inset 20px 0 300px #f0f,  /* inner left magenta broad */
        inset -20px 0 300px #0ff, /* inner right cyan broad */
        0 0 50px #fff,            /* outer white */
        -10px 0 80px #f0f,        /* outer left magenta */
        10px 0 80px #0ff;
    position: absolute;
    top: 0;
    left: 0;
    border-radius: 40%;
    margin: 0 auto;
}

Body:
Try adding left: 0; right:0px;  margin: 0 auto; to the class .light for aligning that to center and style the parent div for vertically aligning using transform and top

.light {
  //  display: none;
    width: 100px;
    height: 100px;
    background-color: #fff;
    z-index: 10;
    box-shadow:
        inset 0 0 50px #fff,      /* inner white */
        inset 20px 0 80px #f0f,   /* inner left magenta short */
        inset -20px 0 80px #0ff,  /* inner right cyan short */
        inset 20px 0 300px #f0f,  /* inner left magenta broad */
        inset -20px 0 300px #0ff, /* inner right cyan broad */
        0 0 50px #fff,            /* outer white */
        -10px 0 80px #f0f,        /* outer left magenta */
        10px 0 80px #0ff;
    position: absolute;
    top: 0;
    left: 0;
    right:0px;
    border-radius: 40%;
    margin: 0 auto;

}

.light-holder{
     position: fixed;
     width:100%;
     top: 50%;
     transform: translateY(-50%);
}

<div class = "container lightcontainer">
        <div class = "row">
                <div class = "col-xs-12 light-holder">
                    <div class = "light"></div>
                </div>
        </div>
    </div>


问:
Deny access to favicon
I currently have 2 domains using the same httpdocs folder, what i need to do is to deny the access to the favicon when the request comes from one of my domains or simply redirect it to another favicon file.
I've been trying to solve this by editing the .htaccess file but i can't figure out how to make the RewriteRule to work.

Thank you very much

答:
To deny access to the favicon.ico completely you can use a <Files> directive in your .htaccess file:

```<code><Files favicon.ico>
  Order deny,allow
  Deny from all
</Files>
</code>```

If you wanted to redirect instead, you might do it this way:

```<code>RewriteEngine On

RewriteCond %{HTTP_HOST} ^host1.domain.com$
RewriteRule ^favicon.ico /host1-favicon.ico

RewriteCond %{HTTP_HOST} ^host2.domain.com$
RewriteRule ^favicon.ico /host2-favicon.ico
</code>```

Title: Deny access to favicon

Body:
To deny access to the favicon.ico completely you can use a <Files> directive in your .htaccess file:

<Files favicon.ico>
  Order deny,allow
  Deny from all
</Files>

If you wanted to redirect instead, you might do it this way:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^host1.domain.com$
RewriteRule ^favicon.ico /host1-favicon.ico

RewriteCond %{HTTP_HOST} ^host2.domain.com$
RewriteRule ^favicon.ico /host2-favicon.ico


问:
How do I remove the line breaks around my <input> element?
I have the following HTML...

```<code><label for="addnewlocationpostcode">Postcode: </label>
<input type="text" id="addnewlocationpostcode" placeholder="Enter postcode" />
<button id="addnewlocationpostcodecheck" type="button" class="btn btn-primary inline"><span class="glyphicon glyphicon-search"></span></button>
</code>```

When this is displayed in the browser, all three elements are on separate lines. I want them all on one line.

Using Chrome's inspector, I can see that the margin of the input element seems to be full width, even though Chrome claims the margin is zero...

My (uneducated) guess is that if the margin is full width, the element has to be its own line.

However, if I type $("#addnewlocationpostcode").css("margin") into the console, it gives an output of "0px" which sounds like jQuery thinks the margin is zero.

I don't have any CSS set on any of these elements. The only CSS that is used on the page is the standard Bootstrap .css file that I downloaded from their site. Even if I had some custom CSS set, I still don't understand how Chrome shows the margin as being the full width of the container when I select the element, but jQuery reports it as zero.

I tried setting the margin manually using $("#addnewlocationpostcode").css("margin-right", "10px") and the like, but it didn't make any difference what value I used, it always looked the same.

Anyone able to explain what's going on? More to the point, how do I fix it so that all three elements are on one line?

答:
It turned out to be caused by jQuery Steps, which I'm using on the page. It's not the CSS for the plug-in, but something in the Javacript, as when I commented that out, the elements displayed correctly.

Which doesn't really help me much, as I can't control what CSS the plug-in emits. Looks like I might need to rethink either using that plug-in or the way I display these elements.

Body:
I have the following HTML...

Postcode:
<input type="text" id="addnewlocationpostcode" placeholder="Enter postcode" />
<button id="addnewlocationpostcodecheck" type="button" class="btn btn-primary inline"></button>

When this is displayed in the browser, all three elements are on separate lines. I want them all on one line.

Using Chrome's inspector, I can see that the margin of the input element seems to be full width, even though Chrome claims the margin is zero...

My (uneducated) guess is that if the margin is full width, the element has to be its own line.

However, if I type $("#addnewlocationpostcode").css("margin") into the console, it gives an output of "0px" which sounds like jQuery thinks the margin is zero.

I don't have any CSS set on any of these elements. The only CSS that is used on the page is the standard Bootstrap .css file that I downloaded from their site. Even if I had some custom CSS set, I still don't understand how Chrome shows the margin as being the full width of the container when I select the element, but jQuery reports it as zero.

I tried setting the margin manually using $("#addnewlocationpostcode").css("margin-right", "10px") and the like, but it didn't make any difference what value I used, it always looked the same.

Anyone able to explain what's going on? More to the point, how do I fix it so that all three elements are on one line?