问:
How can I set a height of an element relative to her parent and her sibling?

#parent {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  /*overflow: hidden; this only hides */
}

#sibling1 {
  position: relative;
  width: 100%;
}

#sibling2{

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <h3 id="sibling1">Variable Length Title</h3>
  <div id="sibling2"> Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</div>
</div></code>```

How can I get something like this?

Is there a way in css to model the sibling2 height based on the size of the parent and the height occupied by sibling1?

i.e sibling2.height = parent.height - sibling1.height

答:
Not sure what you want to do but according to your screen shot, you can add : overflow: hidden or overflow: auto if you want scroll bar.

#parent {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  overflow: hidden;
}

#parent2 {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  overflow: auto;
}

#sibling1 {
  position: relative;
  width: 100%;
}

#sibling2{

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <h3 id="sibling1">Variable Length Title</h3>
  <div id="sibling2"> Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</div>
</div>

<div id="parent2">
  <h3 id="sibling1">Variable Length Title</h3>
  <div id="sibling2"> Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</div>
</div></code>```

Body:
#parent {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  /*overflow: hidden; this only hides */
}

#sibling1 {
  position: relative;
  width: 100%;
}

#sibling2{

}

Variable Length Title

 Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.

How can I get something like this?

Is there a way in css to model the sibling2 height based on the size of the parent and the height occupied by sibling1?

i.e sibling2.height = parent.height - sibling1.height

Body:
Not sure what you want to do but according to your screen shot, you can add : overflow: hidden or overflow: auto if you want scroll bar.

#parent {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  overflow: hidden;
}

#parent2 {
  height: 150px;
  width: 200px;
  border-style: solid;
  border-color: red;
  overflow: auto;
}

#sibling1 {
  position: relative;
  width: 100%;
}

#sibling2{

}

<div id="parent">
  <h3 id="sibling1">Variable Length Title</h3>
  <div id="sibling2"> Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</div>
</div>

<div id="parent2">
  <h3 id="sibling1">Variable Length Title</h3>
  <div id="sibling2"> Variable lenght text... Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</div>
</div>


来源: stackexchange

问:
Creating pdf file using native js?
A have a project on angularjs and I need to create and download a document for print(no needed to save it on server). It can be .docx, but .pdf is preferable(so simple user won't able to change file). So, I know that there is a framework called PHPWord, but I don't like php at all. And there is another framework called docx.js(but it jquery required).

There is one more problem that I need to add values of variables to the docx template(which located on server, so admin can change it, of course he won't touch variables in this file) and then download fulfilled pdf document. It is not necessary to use docx template, nevertheless this variant is preferable.

Can you give me some recommendation in which way I need to look? Maybe you know some good framework based on native JS?

答: https://bytescout.com/products/developer/pdfgeneratorsdkjs/create-pdf-tutorial-for-javascript.html   please you put a plus. dont forget</p>

ContentLicense: CC BY-SA 3.0

Title: Creating pdf file using native js?


问:
How to verify installed spaCy version?
I have installed spaCy with python for my NLP project.

I have installed that using pip.  How can I verify installed spaCy version?

using

```<code>pip install -U spacy
</code>```

What is command to verify installed spaCy version?

答: If you installed with pip you can try to find it with pip list and get version info with pip show <name>

Title: How to verify installed spaCy version?

Body:
I have installed spaCy with python for my NLP project.

I have installed that using pip.  How can I verify installed spaCy version?

using

pip install -U spacy

What is command to verify installed spaCy version?


问:
Resizing font to fit the current screen size on a website
If I have a font set to a particular size for a desktop screen, can I reduce it using CSS3 @media Rule to also fit well in Mobile devices?

I have this line of code below:

```<code><style>
@media only screen and (min-device-width: 150px) {
.log {font-size: 10px}
}
</style>

<body>
<div class="log" style="font-size: 35px;">
HEADER TEXT<br />
</div>
</body>
</code>```

But it is not responsive when I open the site on my mobile device!!! What am I doing wrong???

答:
In CSS instead of px you can use vw (viewport width) or vh (viewport height) for font size

Open the code snippet in full page mode, and resize your browser, you will see that text size is the same according to screen size

First text will never fall in two lines, it will be smaller on smaller screen sizes

Second text will change font size when you change your browser height

Usually, the vw will do all you need

Some text according to screen Width

Some text according to screen Height
```

Body:
If I have a font set to a particular size for a desktop screen, can I reduce it using CSS3 @media Rule to also fit well in Mobile devices?

I have this line of code below:

HEADER TEXT

But it is not responsive when I open the site on my mobile device!!! What am I doing wrong???

Body:
In CSS instead of px you can use vw (viewport width) or vh (viewport height) for font size

Open the code snippet in full page mode, and resize your browser, you will see that text size is the same according to screen size

First text will never fall in two lines, it will be smaller on smaller screen sizes

Second text will change font size when you change your browser height

Usually, the vw will do all you need

<style>
.view-width {
 font-size: 5vw
}
.view-height {
 font-size: 10vh
}
</style>

<div class="view-width">Some text according to screen Width</div>
<div class="view-height">Some text according to screen Height</div>


问:
add a substring in Python
I am beginner in python i wanna add a substring in my python code. Here is my code

```<code>def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""

if len(acc_id) == 15:
  pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
  pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
  pp_acc_id = "01130066" + acc_id.substring(1)
else:
  return "null"

if not amount:
  pp_amount = str.format("54%02d%s", len(amount), amount)

pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

pp_chksum = str(crc(pp_str))
pp_str += pp_chksum
return pp_str
</code>```

It makes some error in my code. Here is the line:

```<code>pp_acc_id = "01130066" + acc_id.substring(1)
</code>```

i wanna update to add substring. I converted this code from java. What should i do to convert this line in python.

答:
You can conceptually access parts of a string as iterable list of chars:

```<code>mystring = "this is a string"

print mystring[0]   # will print "t"
print mystring[1:]  # will print "his is a string"
print mystring[::2] # will print "ti sasrn" (every other character)
</code>```

For more information about list comprehensions look into your python api or search SO - f.e. explanation-of-how-list-comprehension-works
or is-there-a-way-to-substring-a-string-in-python

Title: add a substring in Python

Body:
I am beginner in python i wanna add a substring in my python code. Here is my code

def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""

if len(acc_id) == 15:
  pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
  pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
  pp_acc_id = "01130066" + acc_id.substring(1)
else:
  return "null"

if not amount:
  pp_amount = str.format("54%02d%s", len(amount), amount)

pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" +          pp_amount + "5802TH" + "6304"

pp_chksum = str(crc(pp_str))
pp_str += pp_chksum
return pp_str

It makes some error in my code. Here is the line:

pp_acc_id = "01130066" + acc_id.substring(1)

i wanna update to add substring. I converted this code from java. What should i do to convert this line in python.

Body:
You can conceptually access parts of a string as iterable list of chars:

mystring = "this is a string"

print mystring[0]   # will print "t"
print mystring[1:]  # will print "his is a string"
print mystring[::2] # will print "ti sasrn" (every other character)

For more information about list comprehensions look into your python api or search SO - f.e. explanation-of-how-list-comprehension-works
or is-there-a-way-to-substring-a-string-in-python


问:
create a dictionary combining other dictionaries python
I have two dictionaries of the type:

```<code>dict1 = {NTID: (ID, CN)}

dict2 = {NTID: INCHI}
</code>```

and I want to get:

```<code>dict3 = {NTID: (ID, CN, INCHI)}
</code>```

I have tried to use zip, as follows:

```<code>dict_3 = dict(zip(dict1, dict2))
</code>```

BUt I get NTID as keys and values. Please note that there are multiple values per each dictionary, but the order of the values between dict1 and dict2 is consistent

EDIT:

An example from dict1 is (keys: '1-4-HYDROXYPHENYL', '4-AMINO-BUTYRATE', 'ACETYLCHOLINE', 'ASN')

```<code>{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)'),
  ('172', 'alpha-ketoglutarate'),
  ('173', 'succinate'),
  ('399', 'Succinate semialdehyde'),
  ('111', 'putrescine'),
  ('114', '4-guanidinobutanoate'),
  ('115', '4-acetamidobutanoate')],
 'ACETYLCHOLINE': [],
 'ASN': [('1', 'glycine'),
  ('45', 'tyrosine'),
  ('74', 'leucine'),
  ('90', 'methionine'),
  ('80', 'valine')]}
</code>```

dict2:

```<code>{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': ['InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)',
  'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2',
  'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2',
  'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1',
  'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2',
  'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)',
  'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1'],
 'ACETYLCHOLINE': [],
 'ASN': ['InChI=1S/C9H11NO3',
  'InChI=1S/C9H11NO2/c10-8',
  'InChI=1S/C3H7NO2/c1-2(4)3(5)6',
  'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3',
  'InChI=1S/C4H9NO3/c1-2(6)3',
  'InChI=1S/C4H8N2O3/c5-2(4(8)',
  'InChI=1S/C6H13NO2/c1-3-4(2)',
  'InChI=1S/C6H9N3O2/c7-5(6(10)',
  'InChI=1S/C4H7NO4/c5-2(4(8)9)',
  'InChI=1S/C4H4O5/c5-2(4(8)9)1-',
  'InChI=1S/C3H7NO2S/c4-2(1-7)3(5)',
  'InChI=1S/C5H10N2O3/c6-3(5(9)'}
</code>```

dict3 (output) should look like:

```<code>{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)', 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)'),
  ('172', 'alpha-ketoglutarate', 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2', 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'),
  ('173', 'succinate', 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'),
  etc...
</code>```

答:
You can try this:

```<code>dict3 = {name: [(*a, b) for a, b in zip(v, dict2[name])]
    for name, v in dict1.items()
}
</code>```

From what I understand, dict1 and dict2 have the same keys and structure but are storing different information related to the same one thing, and you want to merge them both into a common dict3.

Body:
I have two dictionaries of the type:

dict1 = {NTID: (ID, CN)}

dict2 = {NTID: INCHI}

and I want to get:

dict3 = {NTID: (ID, CN, INCHI)}

I have tried to use zip, as follows:

dict_3 = dict(zip(dict1, dict2))

BUt I get NTID as keys and values. Please note that there are multiple values per each dictionary, but the order of the values between dict1 and dict2 is consistent

EDIT:

An example from dict1 is (keys: '1-4-HYDROXYPHENYL', '4-AMINO-BUTYRATE', 'ACETYLCHOLINE', 'ASN')

{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)'),
  ('172', 'alpha-ketoglutarate'),
  ('173', 'succinate'),
  ('399', 'Succinate semialdehyde'),
  ('111', 'putrescine'),
  ('114', '4-guanidinobutanoate'),
  ('115', '4-acetamidobutanoate')],
 'ACETYLCHOLINE': [],
 'ASN': [('1', 'glycine'),
  ('45', 'tyrosine'),
  ('74', 'leucine'),
  ('90', 'methionine'),
  ('80', 'valine')]}

dict2:

{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': ['InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)',
  'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2',
  'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2',
  'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1',
  'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2',
  'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)',
  'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1'],
 'ACETYLCHOLINE': [],
 'ASN': ['InChI=1S/C9H11NO3',
  'InChI=1S/C9H11NO2/c10-8',
  'InChI=1S/C3H7NO2/c1-2(4)3(5)6',
  'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3',
  'InChI=1S/C4H9NO3/c1-2(6)3',
  'InChI=1S/C4H8N2O3/c5-2(4(8)',
  'InChI=1S/C6H13NO2/c1-3-4(2)',
  'InChI=1S/C6H9N3O2/c7-5(6(10)',
  'InChI=1S/C4H7NO4/c5-2(4(8)9)',
  'InChI=1S/C4H4O5/c5-2(4(8)9)1-',
  'InChI=1S/C3H7NO2S/c4-2(1-7)3(5)',
  'InChI=1S/C5H10N2O3/c6-3(5(9)'}

dict3 (output) should look like:

{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)', 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)'),
  ('172', 'alpha-ketoglutarate', 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2', 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'),
  ('173', 'succinate', 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'),
  etc...

Body:
You can try this:

dict3 = {name: [(*a, b) for a, b in zip(v, dict2[name])]
    for name, v in dict1.items()
}

From what I understand, dict1 and dict2 have the same keys and structure but are storing different information related to the same one thing, and you want to merge them both into a common dict3.


问:
local xml parsing in android

Possible Duplicate:

  Parsing local xml file in android

Hi every one, In this folowing link there is a xml parser

http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser/#idc-cover

instead of using
url can i use the xml file stored locally, means inside "res/xml/*.xml"
can any one provide me a code for dat...(am brand new to android, pls help me)

答:
```<code>private void parseData()
    {
         SAXParserFactory spf = SAXParserFactory.newInstance();
         SAXParser sp = null;
        try {
            sp = spf.newSAXParser();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

         // Get the XMLReader of the SAXParser we created.
         XMLReader xr = null;
        try {
            xr = sp.getXMLReader();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         // Create a new ContentHandler and apply it to the XML-Reader
        OfficesParser myExampleHandler = new OfficesParser();
         xr.setContentHandler(myExampleHandler);

         // Parse the xml-data from our URL.
         try {

                        File f = new File("MyLocal.xml");
            xr.parse(new InputSource(new URL(f.toURL()).openStream()));

        } catch (MalformedURLException e) {
            //Log.d("Net Disconnected", "NetDisconeeted");
            // Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            // TODO Auto-generated catch block
            //e.printStackTrace();
        } catch (IOException e) {
            //Log.d("Net Disconnected", "NetDisconeeted");
            // Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            // TODO Auto-generated catch block
            //e.printStackTrace();
        } catch (SAXException e) {
            //Log.d("Net Disconnected", "NetDisconeeted");
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
         catch (Exception e) {
                //Log.d("Net Disconnected", "NetDisconeeted");
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: local xml parsing in android


问:
Is console.log() a javascript built-in method?
I'm working with angular js. My project includes only the angular.min.js file, with no other references of js files like javascript etc.
The code which makes request to the server is as follows:

var app = angular
  .module("myModule", [])
  .controller("myController", function($scope, $http) {

    $http.get("WebService.asmx/GetAllEmployees")
      .then(function(response) {
        $scope.employees = response.data;
        console.log(response.data)
      }, function(reason) {
        $scope.error = reason.data;
      });
  });
```

<p>I'm wondering about the following line: </p>

```console.log(response.data)
```

I could not figure out who's property this function is?

Is this browser builtin function?

答:
Yes, it's built in function.

console is an object which resides in any global (for example window) object of JavaScript. This object contains various methods, out of which log is the one. This displays anything you put on browser console.

Body:
I'm working with angular js. My project includes only the angular.min.js file, with no other references of js files like javascript etc.
The code which makes request to the server is as follows:

var app = angular
  .module("myModule", [])
  .controller("myController", function($scope, $http) {

    $http.get("WebService.asmx/GetAllEmployees")
      .then(function(response) {
        $scope.employees = response.data;
        console.log(response.data)
      }, function(reason) {
        $scope.error = reason.data;
      });
  });

I'm wondering about the following line:

console.log(response.data)

I could not figure out who's property this function is?

Is this browser builtin function?


问:
How to restore a SQL Server 2012 database to SQL Server 2008 R2?
I am trying to restore the backup taken from a SQL Server 2012 to SQL Server 2008 R2, and it giving an error

Specified cast is not valid. (SqlManagerUI)

If you have any solution to this please give comment

thanks.

答:
Here is another option which did the trick for me:
https://dba.stackexchange.com/a/44340

There I used Option B. This is not my idea so all credit goes to the original author. I am just putting it in here also as I know that sometimes links don't function and it is recommended to have the full story handy.

Just one tip from me: First resolve the schema incompatibilities if any. Then pouring in the data should be a breeze.

Option A: Script out database in compatibility mode using Generate script option:

Note: If you script out database with schema and data, depending on your data size, the script will be massive and wont be handled by SSMS, sqlcmd or osql (might be in GB as well).

Option B:

First script out tables first with all Indexes, FK's, etc and create blank tables in the destination database - option with SCHEMA ONLY (No data).

Use BCP to insert data

I. BCP out the data using below script. Set SSMS in Text Mode and copy the output generated by below script in a bat file.

```<code>-- save below output in a bat file by executing below in SSMS in TEXT mode

-- clean up: create a bat file with this command --> del D:\BCP\*.dat

select '"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe" ' /* path to BCP.exe */
    +  QUOTENAME(DB_NAME())+ '.' /* Current Database */
    +  QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+'.'
    +  QUOTENAME(name)
    +  ' out D:\BCP\'  /* Path where BCP out files will be stored */
    +  REPLACE(SCHEMA_NAME(schema_id),' ','') + '_'
    +  REPLACE(name,' ','')
    + '.dat -T -E -SServerName\Instance -n' /* ServerName, -E will take care of Identity, -n is for Native Format */
from sys.tables
where is_ms_shipped = 0 and name <> 'sysdiagrams'                       /* sysdiagrams is classified my MS as UserTable and we dont want it */
/*and schema_name(schema_id) <> 'unwantedschema'    */                             /* Optional to exclude any schema  */
order by schema_name(schema_id)
</code>```

II. Run the bat file that will generate the .dat files in the folder that you have specified.

III. Run below script on the destination server with SSMS in text mode again.

```<code>--- Execute this on the destination server.database from SSMS.

--- Make sure the change the @Destdbname and the bcp out path as per your environment.

declare @Destdbname sysname
set @Destdbname = 'destinationDB' /* Destination Database Name where you want to Bulk Insert in */
select 'BULK INSERT '
/*Remember Tables must be present on destination database */
+ QUOTENAME(@Destdbname) + '.'
+ QUOTENAME(SCHEMA_NAME(SCHEMA_ID))
+ '.' + QUOTENAME(name)
+ ' from ''D:\BCP\' /* Change here for bcp out path */
+ REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '')
+ '.dat'' with ( KEEPIDENTITY, DATAFILETYPE = ''native'', TABLOCK )'
+ char(10)
+ 'print ''Bulk insert for ' + REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') + ' is done... '''
+ char(10) + 'go'
from sys.tables
where is_ms_shipped = 0
and name <> 'sysdiagrams' /* sysdiagrams is classified my MS as UserTable and we dont want it */
--and schema_name(schema_id) <> 'unwantedschema' /* Optional to exclude any schema */
    order by schema_name(schema_id)
</code>```

IV. Run the output using SSMS to insert data back in the tables.

This is very fast BCP method as it uses Native mode.

Body:
Here is another option which did the trick for me:
https://dba.stackexchange.com/a/44340

There I used Option B. This is not my idea so all credit goes to the original author. I am just putting it in here also as I know that sometimes links don't function and it is recommended to have the full story handy.

Just one tip from me: First resolve the schema incompatibilities if any. Then pouring in the data should be a breeze.

Option A: Script out database in compatibility mode using Generate script option:

Note: If you script out database with schema and data, depending on your data size, the script will be massive and wont be handled by SSMS, sqlcmd or osql (might be in GB as well).

Option B:

First script out tables first with all Indexes, FK's, etc and create blank tables in the destination database - option with SCHEMA ONLY (No data).

Use BCP to insert data

I. BCP out the data using below script. Set SSMS in Text Mode and copy the output generated by below script in a bat file.

-- save below output in a bat file by executing below in SSMS in TEXT mode

-- clean up: create a bat file with this command --> del D:\BCP\*.dat

select '"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe" ' /* path to BCP.exe */
    +  QUOTENAME(DB_NAME())+ '.' /* Current Database */
    +  QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+'.'
    +  QUOTENAME(name)
    +  ' out D:\BCP\'  /* Path where BCP out files will be stored */
    +  REPLACE(SCHEMA_NAME(schema_id),' ','') + '_'
    +  REPLACE(name,' ','')
    + '.dat -T -E -SServerName\Instance -n' /* ServerName, -E will take care of Identity, -n is for Native Format */
from sys.tables
where is_ms_shipped = 0 and name <> 'sysdiagrams'                       /* sysdiagrams is classified my MS as UserTable and we dont want it */
/*and schema_name(schema_id) <> 'unwantedschema'    */                             /* Optional to exclude any schema  */
order by schema_name(schema_id)

II. Run the bat file that will generate the .dat files in the folder that you have specified.

III. Run below script on the destination server with SSMS in text mode again.

--- Execute this on the destination server.database from SSMS.

--- Make sure the change the @Destdbname and the bcp out path as per your environment.

declare @Destdbname sysname
set @Destdbname = 'destinationDB' /* Destination Database Name where you want to Bulk Insert in */
select 'BULK INSERT '
/*Remember Tables must be present on destination database */
+ QUOTENAME(@Destdbname) + '.'
+ QUOTENAME(SCHEMA_NAME(SCHEMA_ID))
+ '.' + QUOTENAME(name)
+ ' from ''D:\BCP\' /* Change here for bcp out path */
+ REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '')
+ '.dat'' with ( KEEPIDENTITY, DATAFILETYPE = ''native'', TABLOCK )'
+ char(10)
+ 'print ''Bulk insert for ' + REPLACE(SCHEMA_NAME(schema_id), ' ', '') + '_' + REPLACE(name, ' ', '') + ' is done... '''
+ char(10) + 'go'
from sys.tables
where is_ms_shipped = 0
and name <> 'sysdiagrams' /* sysdiagrams is classified my MS as UserTable and we dont want it */
--and schema_name(schema_id) <> 'unwantedschema' /* Optional to exclude any schema */
    order by schema_name(schema_id)

IV. Run the output using SSMS to insert data back in the tables.

This is very fast BCP method as it uses Native mode.


问:
Method Not Allowed HTTP Exception in Laravel 5.4
I have a form with two text fields and two buttons (edit and delete), when I press edit button, it works fine but when I press delete button, it gives the 'MethodNotAllowedHttp' exception. My code is as follows:

```<code><form action="/laboratory/doctors/update" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">
    </div>
    <div class="form-group">
        <label for="percentage">Percentage:</label>
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">
    </div>
     <button type="submit" class="btn btn-success">Save Changes</button>
    <a href="/laboratory/doctors/{{ $doctor->id }}/delete" class="btn btn-danger">Delete</a>
</form>
</code>```

My Routes are as follows:

```<code>Route::post('/doctors/update', 'DoctorsController@update');
Route::delete('/doctors/{doctor}/delete', 'DoctorsController@destroy');
</code>```

Any help is appreciated.

答:
You have created route of http verbs as delete type and trying to get of type get. So you can change it as get instead delete

```<code> Route::get('/laboratory/doctors/{doctor}/delete', 'DoctorsController@destroy');
</code>```

Also there is other way to make http verb as DELETE but using

Another form tag outside of current form tag.

Or use ajax to make it delete type

Body:
I have a form with two text fields and two buttons (edit and delete), when I press edit button, it works fine but when I press delete button, it gives the 'MethodNotAllowedHttp' exception. My code is as follows:

<form action="/laboratory/doctors/update" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}

        Name:
        <input type="text" class="form-control" id="name" aria-describedby="name" value="{{ $doctor->name }}">

        Percentage:
        <input type="text" class="form-control" id="percentage" value="{{ $doctor->percentage }}">

     <button type="submit" class="btn btn-success">Save Changes</button>
    id }}/delete" class="btn btn-danger">Delete
</form>

My Routes are as follows:

Route::post('/doctors/update', 'DoctorsController@update');
Route::delete('/doctors/{doctor}/delete', 'DoctorsController@destroy');

Any help is appreciated.

Body:
You have created route of http verbs as delete type and trying to get of type get. So you can change it as get instead delete

 Route::get('/laboratory/doctors/{doctor}/delete', 'DoctorsController@destroy');

Also there is other way to make http verb as DELETE but using

Another form tag outside of current form tag.

Or use ajax to make it delete type


问:
regex url to image in php
I am making a profile page where users can set an url to their profile image. How do I check this with regex for example?</p>

答:
You can use cURL for the mime. For the URL validation I use the following, but there are loads out there. You can use FILTER_VALIDATE_URL but it can contain bugs; http://bugs.php.net/51192.

```<code>$url='image.png';

if( preg_match("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", $url) ){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    $mime = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);

    print $mime;

}
</code>```

Title: regex url to image in php

Body:
You can use cURL for the mime. For the URL validation I use the following, but there are loads out there. You can use FILTER_VALIDATE_URL but it can contain bugs; http://bugs.php.net/51192.

$url='image.png';

if( preg_match("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", $url) ){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    $mime = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);

    print $mime;

}


问:
Jenkins: FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
```<code>FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
java.lang.NoClassDefFoundError: Could not initialize class hudson.util.ProcessTree$UnixReflection
at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
at hudson.Launcher$LocalLauncher.kill(Launcher.java:949)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:502)
at hudson.model.Run.execute(Run.java:1737)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
</code>```

Jenkins ver. 2.73.3
MacOSx

Doing an iOS build and upload to hockeyapp.  The .ipa is created successfully, error seems to happen afterwards, seems like on the hockeyapp upload.  I have an android project that works and uploads to hockeyapp successfully though.

Started getting this today after updating Jenkins and plugins.  Was working before.

Any ideas?

答:
happened to me when running an Android build
(Jenkins build 2.86, I just downgraded from 2.87 or something slighlty newer, because of other fails)

```<code>Build step 'Invoke Gradle script' changed build result to SUCCESS
FATAL: Could not initialize class
hudson.util.ProcessTree$UnixReflection
java.lang.NoClassDefFoundError: Could not initialize class
hudson.util.ProcessTree$UnixReflection
at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
at hudson.Launcher$LocalLauncher.kill(Launcher.java:949)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:510)
at hudson.model.Run.execute(Run.java:1724)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
Finished: FAILURE
</code>```

first SUCCESS then FAILURE, hmm weeeird

I remembered that recently I have installed java 9 for experimenting, but still having java 8 set to usl/libexec/java_home, in my .zshrc like:

```<code>export JAVA_HOME=`/usr/libexec/java_home -v 1.8.0_152`
</code>```

but that did not help at all, so I said goodbye to Java 9 with

```<code>sudo rm -rf /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk
</code>```

then went to Manage Jenkins -> Configure System -> Environment variables
 and added

```<code>/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home
</code>```

as JAVA_HOME

after Jenkins restart my builds run like a charm

Body:
FATAL: Could not initialize class hudson.util.ProcessTree$UnixReflection
java.lang.NoClassDefFoundError: Could not initialize class hudson.util.ProcessTree$UnixReflection
at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:667)
at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
at hudson.Launcher$LocalLauncher.kill(Launcher.java:949)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:502)
at hudson.model.Run.execute(Run.java:1737)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)

Jenkins ver. 2.73.3
MacOSx

Doing an iOS build and upload to hockeyapp.  The .ipa is created successfully, error seems to happen afterwards, seems like on the hockeyapp upload.  I have an android project that works and uploads to hockeyapp successfully though.

Started getting this today after updating Jenkins and plugins.  Was working before.

Any ideas?

Body:
happened to me when running an Android build
(Jenkins build 2.86, I just downgraded from 2.87 or something slighlty newer, because of other fails)

Build step 'Invoke Gradle script' changed build result to SUCCESS
FATAL: Could not initialize class
hudson.util.ProcessTree$UnixReflection
java.lang.NoClassDefFoundError: Could not initialize class
hudson.util.ProcessTree$UnixReflection
at hudson.util.ProcessTree$UnixProcess.kill(ProcessTree.java:647)
at hudson.util.ProcessTree$UnixProcess.killRecursively(ProcessTree.java:668)
at hudson.util.ProcessTree$Unix.killAll(ProcessTree.java:589)
at hudson.Launcher$LocalLauncher.kill(Launcher.java:949)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:510)
at hudson.model.Run.execute(Run.java:1724)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
Finished: FAILURE

first SUCCESS then FAILURE, hmm weeeird

I remembered that recently I have installed java 9 for experimenting, but still having java 8 set to usl/libexec/java_home, in my .zshrc like:

export JAVA_HOME=`/usr/libexec/java_home -v 1.8.0_152`

but that did not help at all, so I said goodbye to Java 9 with

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk

then went to Manage Jenkins -> Configure System -> Environment variables
 and added

/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

as JAVA_HOME

after Jenkins restart my builds run like a charm


问:
Parser Error : Could not create type
I have created webservice and published it on local machine. Then I have uploaded it on server.

Now while I tried to access webservice it gives following error :

Parser Error Message: Could not create type 'webservice.myservice'

Source Error:
Line 1:  <%@ WebService Language="C#" CodeBehind="myservice.asmx.cs" Class="webservice.myservice" %>

I tried This link but unable to solve my problem.

What should I do?

答:
I'm fairly certain this is just a summary of what Glenn said, but I ran into this issue because my application was created from the directory one level too high in the directory structure.

For example, my web service was in SiteProject_1/SiteProject_2/service.asmx

Originally SiteProject_1 was what I converted into the application within IIS. I was able to resolve the issue by removing that application within IIS and instead making SiteProject_2 into the application.

Title: Parser Error : Could not create type


问:
Iterating through a vector of tuples c+17 style don't work?
I am currently looking neat ways in which i can iterate this vector of tuples..

This is what I am currently doing?

```<code>#include <experimental/filesystems>
#include <tuple>
#include <iostream>
#include <vector>

std::tuple<std::experimental::filesystem::path, std::experimental::filesystem::file_status, std::size_t>
file_info(const std::experimental::filesystem::directory_entry &entry)
{

    const std::experimental::filesystem::file_status fs(std::experimental::filesystem::status(entry));
    return {entry.path(),
                fs,
                std::experimental::filesystem::is_regular_file(fs) ? std::experimental::filesystem::file_size(entry.path()) : 0u};

}

int main ()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);  // string_dir_to_test_files is just a string
    std::experimental::filesystem::directory_entry dir_path(_path);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << std::endl;
        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
        std::vector<std::tuple<std::experimental::filesystem::path,std::experimental::filesystem::file_status, std::size_t>> items;
        std::transform(std::experimental::filesystem::directory_iterator(_path),{},back_inserter(items),file_info);
        for( auto const& index : items)
        {
            std::cout << std::get<0>(index) << std::endl; // This line could be written better?
        }
    }
    else
    {
        std::cout << "No data to build database with!" << std::endl;
        exit(1);
    }

    return 0;
}
</code>```

Even though it does the job, it does not seem to be "reader" friendly, is there other ways in which I can the iterate the elements of the vector, in a more reader friendly manner?

One way I tried to make the for loop a bit more readable was by making like this:

```<code>for (auto const& [path, status, size] : items) {
    std::cout << path << std::endl;
}
</code>```

But this somehow give me this error:

```<code>/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected unqualified-id before ‘[’ token
         for(auto const& [path, status, size] : items)
                         ^
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected ‘;’ before ‘[’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:26: error: ‘path’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                          ^~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:26: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:39:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
   class path
         ^~~~
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
/home/noob/soundcloud/src/include/database/database.cpp:31:32: error: ‘status’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                                ^~~~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:32: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:41:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
   file_status status(const path& __p, error_code& __ec) noexcept;
               ^~~~~~
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
/home/noob/soundcloud/src/include/database/database.cpp:31:40: error: capture by copy of incomplete type ‘<unresolved overloaded function type>’
         for(auto const& [path, status, size] : items)
                                        ^~~~
/home/noob/soundcloud/src/include/database/database.cpp: In lambda function:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘{’ before ‘:’ token
         for(auto const& [path, status, size] : items)
                                              ^
/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘;’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘)’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
make[2]: *** [src/include/database/CMakeFiles/database.dir/database.cpp.o] Error 1
make[1]: *** [src/include/database/CMakeFiles/database.dir/all] Error 2
make: *** [all] Error 2
</code>```

答:
In C++17, you may do:</p>

```<code>for (auto const& [path, status, size] : items) {
    std::cout << path << std::endl;
}
</code>```

Body:
I am currently looking neat ways in which i can iterate this vector of tuples..

This is what I am currently doing?

#include <experimental/filesystems>
#include <tuple>
#include <iostream>
#include <vector>

std::tuple<std::experimental::filesystem::path, std::experimental::filesystem::file_status, std::size_t>
file_info(const std::experimental::filesystem::directory_entry &entry)
{

    const std::experimental::filesystem::file_status fs(std::experimental::filesystem::status(entry));
    return {entry.path(),
                fs,
                std::experimental::filesystem::is_regular_file(fs) ? std::experimental::filesystem::file_size(entry.path()) : 0u};

}

int main ()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);  // string_dir_to_test_files is just a string
    std::experimental::filesystem::directory_entry dir_path(_path);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << std::endl;
        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
        std::vector<std::tuple<std::experimental::filesystem::path,std::experimental::filesystem::file_status, std::size_t>> items;
        std::transform(std::experimental::filesystem::directory_iterator(_path),{},back_inserter(items),file_info);
        for( auto const& index : items)
        {
            std::cout << std::get<0>(index) << std::endl; // This line could be written better?
        }
    }
    else
    {
        std::cout << "No data to build database with!" << std::endl;
        exit(1);
    }

    return 0;
}

Even though it does the job, it does not seem to be "reader" friendly, is there other ways in which I can the iterate the elements of the vector, in a more reader friendly manner?

One way I tried to make the for loop a bit more readable was by making like this:

for (auto const& [path, status, size] : items) {
    std::cout << path << std::endl;
}

But this somehow give me this error:

/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected unqualified-id before ‘[’ token
         for(auto const& [path, status, size] : items)
                         ^
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected ‘;’ before ‘[’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:26: error: ‘path’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                          ^~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:26: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:39:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
   class path
         ^~~~
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
/home/noob/soundcloud/src/include/database/database.cpp:31:32: error: ‘status’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                                ^~~~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:32: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:41:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
   file_status status(const path& __p, error_code& __ec) noexcept;
               ^~~~~~
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
/home/noob/soundcloud/src/include/database/database.cpp:31:40: error: capture by copy of incomplete type ‘<unresolved overloaded function type>’
         for(auto const& [path, status, size] : items)
                                        ^~~~
/home/noob/soundcloud/src/include/database/database.cpp: In lambda function:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘{’ before ‘:’ token
         for(auto const& [path, status, size] : items)
                                              ^
/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘;’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘)’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
make[2]: *** [src/include/database/CMakeFiles/database.dir/database.cpp.o] Error 1
make[1]: *** [src/include/database/CMakeFiles/database.dir/all] Error 2
make: *** [all] Error 2

Body:
In C++17, you may do:

for (auto const& [path, status, size] : items) {
    std::cout << path << std::endl;
}


问:
Synchronise data between Desktop and app (best practise)
I have a website which uses Mysql database. Now I am developing a nativescript app. I was wondering what are the options to synchronise data between desktop and app. For example, if somebody comments on the post, the comment should appear on the app without reloading it. After some research I found Firebase real time database, the problem is the I would have to duplicate and synchronise Mysql and firebase databases. another options in my mind is use to websockets. Could anybody advise what are other options and what are the best practise? Thank you very much.</p>

答:
Ideally this should have been thought through and planned at the initial system design & architecture stage and should have planned Firebase or such cloud database service which could have helped in implementing realtime updates between different connected clients/nodes.

At this stage it would be better if you implement WebSockets to send data for realtime updates to connected clients.


问:
Set attribute of standard HTML-tag using JSF
Me again about JSF. This time I have another JSF page, looking like:

```<code><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <f:loadBundle var="messages" basename="ch.bfh.web2.stundenplan.Messages"/>
    <head>
        <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style.css">
        <script type="text/javascript" src="${pageContext.request.contextPath}/script.js">    </script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <f:view>
            <h1><h:outputText value="#{messages.graphicalTitle}"/><h:commandButton value="#{messages.btnBack }" type="submit" action="return"></h:commandButton></h1>
            <h:outputText value="#{displayCalendarBean.text}"></h:outputText>
            <iframe src="#{displayCalendarBean.calendarSource }" style=" border-width:0 " width="800" height="600" frameborder="0" scrolling="no"></iframe>
        </f:view>
    </body>
</html>
</code>```

This time, JSF complains about the iframe. What I really would like to do is something like

```<code><iframe src="someUrl.php?param1=#{someBean.someProperty}&param2=#{someBean.someProperty2}"></iframe>
</code>```

But i thought maybe it doesn't work that way. So I generate the entire property in the bean and try to put it in there entirely.

What do I need to do to have the EL expression replaced?

Edit:
Error: org.apache.jasper.JasperException: /displayCalendar.jsp(17,16) #{...} is not allowed in template text

I'm using JSF 2.0 on Dynamic Web Module 2.5 with Java 1.5. And this doesn't come from eclipse but a MyFaces' error page is shown. I could post the component tree but I think it doesn't change anything here.

Stack trace:

```<code>javax.faces.FacesException: org.apache.jasper.JasperException: /displayCalendar.jsp(17,16) #{...} is not allowed in template text
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.wrap(ExceptionHandlerImpl.java:241)
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:156)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:258)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.apache.jasper.JasperException: /displayCalendar.jsp(17,16) #{...} is not allowed in template text
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:102)
at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:706)
at org.apache.jasper.compiler.Node$ELExpression.accept(Node.java:958)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:865)
at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1763)
at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:347)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:589)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at org.apache.myfaces.context.servlet.ServletExternalContextImpl.dispatch(ServletExternalContextImpl.java:368)
at org.apache.myfaces.view.jsp.JspViewDeclarationLanguage.buildView(JspViewDeclarationLanguage.java:94)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:66)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239)
... 13 more
</code>```

Maybe there's another way: I would like to use Google Calendar API using the publish tools. Any even better way to do this?

答: Deferred EL #{...} in template text is only allowed when you're using Facelets, the successor of JSP. Use ${...} instead. It won't auto-create the managed bean, but it will just work if the managed bean is already been auto-created by #{...} before in the code.

Body:
Me again about JSF. This time I have another JSF page, looking like:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <f:loadBundle var="messages" basename="ch.bfh.web2.stundenplan.Messages"/>

        <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style.css">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>

        <f:view>

<h:outputText value="#{messages.graphicalTitle}"/><h:commandButton value="#{messages.btnBack }" type="submit" action="return"></h:commandButton>

            <h:outputText value="#{displayCalendarBean.text}"></h:outputText>

        </f:view>

This time, JSF complains about the iframe. What I really would like to do is something like

But i thought maybe it doesn't work that way. So I generate the entire property in the bean and try to put it in there entirely.

What do I need to do to have the EL expression replaced?

Edit:
Error: org.apache.jasper.JasperException: /displayCalendar.jsp(17,16) #{...} is not allowed in template text

I'm using JSF 2.0 on Dynamic Web Module 2.5 with Java 1.5. And this doesn't come from eclipse but a MyFaces' error page is shown. I could post the component tree but I think it doesn't change anything here.

Stack trace:

javax.faces.FacesException: org.apache.jasper.JasperException: /displayCalendar.jsp(17,16) #{...} is not allowed in template text
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.wrap(ExceptionHandlerImpl.java:241)
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:156)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:258)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.apache.jasper.JasperException: /displayCalendar.jsp(17,16) #{...} is not allowed in template text
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:102)
at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:706)
at org.apache.jasper.compiler.Node$ELExpression.accept(Node.java:958)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:865)
at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1763)
at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:347)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:589)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at org.apache.myfaces.context.servlet.ServletExternalContextImpl.dispatch(ServletExternalContextImpl.java:368)
at org.apache.myfaces.view.jsp.JspViewDeclarationLanguage.buildView(JspViewDeclarationLanguage.java:94)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:66)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239)
... 13 more

Maybe there's another way: I would like to use Google Calendar API using the publish tools. Any even better way to do this?


问:
How to perform shallow clone using Composer?
I've got the following composer.json:

```<code>{
    "require": {
        "php": ">=5.2.0",
        "queueit/KnownUser.V3.PHP": "dev-master"
    },
    "config": {
        "autoloader-suffix": "ComposerManager",
        "vendor-dir": "../../../all/libraries/composer"
    },
    "prefer-stable": true,
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "queueit/KnownUser.V3.PHP",
                "version": "dev-master",
                "source": {
                    "type": "git",
                    "url": "https://github.com/queueit/KnownUser.V3.PHP.git",
                    "reference": "master"
                }
            }
        }
    ]
}
</code>```

However when I run:

```<code>$ composer -vvv update
...
Cloning master
Executing command (CWD): git clone --no-checkout 'https://github.com/queueit/KnownUser.V3.PHP.git' '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && cd '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && git remote add composer 'https://github.com/queueit/KnownUser.V3.PHP.git' && git fetch composer
</code>```

the cloning process takes very long time and the repository grows over 25MB in size:

```<code>$ du -hs ~/.composer/cache/vcs/https---github.com-queueit-KnownUser.V3.PHP.git/
25M ~/.composer/cache/vcs/https---github.com-queueit-KnownUser.V3.PHP.git/
</code>```

Then the Composer stops with the timeout:

[Symfony\Component\Process\Exception\ProcessTimedOutException]

      The process "git clone --no-checkout 'https://github.com/queueit/KnownUser.V3.PHP.git' '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && cd '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && git remote add composer 'https://github.com/queueit/KnownUser.V3.PHP.git' && git fetch composer" exceeded the timeout of 300 seconds.

I assume the repository is too big to clone all the git objects.

How I can clone the repository quicker by using a shallow clone?

For example by passing extra --depth 1 or --single-branch git parameters into Git command, so it can be automatically picked up by Composer?

I expect the change to be self-contained within the composer.json file, so no external configuration should be required when invoked this file on the other systems or by other users when running composer install.

答:
Shallow cloning using Composer isn't officially supported (without any patching) as the git parameters are hardcoded.

There is already a feature request to add this: Add support for git shallow clones. However implementing this feature can cause some issues (such as not reaching the locked commits if the depth is not so high@stof and other).

Furthermore there is a pull request which attempts to implement shallow clones by adding an extra --git-clone-depth parameter (tests shows some good results). However the change has been abandon due to faster git clones using cache.

For the quick hack, it's possible to edit git parameters in doDownload() in src/Composer/Downloader/GitDownloader.php, e.g. by changing --depth 1 --single-branch in this line:

```<code>$command = 'git clone --no-checkout ...'
</code>```

Or find the way to apply depth 1 setting into git config.

The easiest workaround (without any hacks) for bigger repositories is just to increase the timeout by specifying the variable like:

```<code>COMPOSER_PROCESS_TIMEOUT=0 composer install
</code>```

Body:
I've got the following composer.json:

{
    "require": {
        "php": ">=5.2.0",
        "queueit/KnownUser.V3.PHP": "dev-master"
    },
    "config": {
        "autoloader-suffix": "ComposerManager",
        "vendor-dir": "../../../all/libraries/composer"
    },
    "prefer-stable": true,
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "queueit/KnownUser.V3.PHP",
                "version": "dev-master",
                "source": {
                    "type": "git",
                    "url": "https://github.com/queueit/KnownUser.V3.PHP.git",
                    "reference": "master"
                }
            }
        }
    ]
}

However when I run:

$ composer -vvv update
...
Cloning master
Executing command (CWD): git clone --no-checkout 'https://github.com/queueit/KnownUser.V3.PHP.git' '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && cd '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && git remote add composer 'https://github.com/queueit/KnownUser.V3.PHP.git' && git fetch composer

the cloning process takes very long time and the repository grows over 25MB in size:

$ du -hs ~/.composer/cache/vcs/https---github.com-queueit-KnownUser.V3.PHP.git/
25M ~/.composer/cache/vcs/https---github.com-queueit-KnownUser.V3.PHP.git/

Then the Composer stops with the timeout:

[Symfony\Component\Process\Exception\ProcessTimedOutException]

      The process "git clone --no-checkout 'https://github.com/queueit/KnownUser.V3.PHP.git' '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && cd '.../sites/all/libraries/composer/queueit/KnownUser.V3.PHP' && git remote add composer 'https://github.com/queueit/KnownUser.V3.PHP.git' && git fetch composer" exceeded the timeout of 300 seconds.

I assume the repository is too big to clone all the git objects.

How I can clone the repository quicker by using a shallow clone?

For example by passing extra --depth 1 or --single-branch git parameters into Git command, so it can be automatically picked up by Composer?

I expect the change to be self-contained within the composer.json file, so no external configuration should be required when invoked this file on the other systems or by other users when running composer install.

Body:
Shallow cloning using Composer isn't officially supported (without any patching) as the git parameters are hardcoded.

There is already a feature request to add this: Add support for git shallow clones. However implementing this feature can cause some issues (such as not reaching the locked commits if the depth is not so high@stof and other).

Furthermore there is a pull request which attempts to implement shallow clones by adding an extra --git-clone-depth parameter (tests shows some good results). However the change has been abandon due to faster git clones using cache.

For the quick hack, it's possible to edit git parameters in doDownload() in src/Composer/Downloader/GitDownloader.php, e.g. by changing --depth 1 --single-branch in this line:

$command = 'git clone --no-checkout ...'

Or find the way to apply depth 1 setting into git config.

The easiest workaround (without any hacks) for bigger repositories is just to increase the timeout by specifying the variable like:

COMPOSER_PROCESS_TIMEOUT=0 composer install


问:
Cassandra Snapshot
I have around 5 TB Cassandra cluster in my organization. We plan to take a full backup (snapshot on all keyspaces at cluster level) to another mount point with a retention period of 10 days. Can someone guide me what could be the best size for this mount point.

答:
Snapshots are taken per node. For a cluster-wide snapshot, use a parallel ssh utility (pssh) to execute nodetool snapshot -t snapshot_name across a cluster; this will provide an eventually consistent backup of the cluster.

The snapshot will be created in data_directory_location/keyspace_name/table_name-UUID/snapshots/snapshot_name.

If your mount point is local, it will need to be large enough to accommodate the total size of the snapshot files at the node-level. If the mount point is remote, it will need to be large enough to contain the combined total of the snapshots for all nodes.

https://docs.datastax.com/en/cassandra/2.1/cassandra/operations/ops_about_snapshots.html
https://docs.datastax.com/en/cassandra/3.0/cassandra/tools/toolsSnapShot.html

Title: Cassandra Snapshot


问:
generated HTML vs JSON, Google Apps Script
I've a web app in Google Apps Script where I take a list of restaurants data(name, address, phone etc.) from Google Sheet and show them to my website through AJAX. Currently the resulted data are generated HTML created from Google Apps Script and I was thinking if there's any way to load the list faster. Then I thought of JSON, but I researched about it and found it's not that much of difference in loading time. Here is the HTML code that renders for each of the row data in sheet,

```<code>  for (var i=0; i<rng.length; i++)
  {
    if (rng[i][0] != "") {
      html += '<br><div class="row">
                  <div class="col s4">
                      <img class="circle responsive-img" src="img/logos/'+rng[i][0]+'.png" />
                  </div>
                  <div class="col s8">
                      <h5>'+rng[i][1]+'</h5>
                      <p><b>'+rng[i][2]+'</b></p>
                      <p>'+rng[i][3]+'</p>
                      <a class="waves-effect waves-light btn btn-sm red lighten-2" href="menu.html?id='+rng[i][0]+'">See Menu</a>
                  </div>
              </div><hr><br>';
    }
  }
</code>```

So for each row of data it creates that part of HTML code and returns the entire HTML in my website where I get it through jQuery AJAX. Now, my question is, is the above method better or should I use JSON to get the raw data only & render it through the client-side?

答: Sending over prepared HTML should make the site render faster, especially if the client has low-power CPU. But, more than HTML vs JSON, the delay is likely to be due to slow Google Apps Script execution. All that string concatenation should not be happening on every call of doGet, it's a waste of time. Process the data once, each time the spreadsheet is edited (using a trigger), and store the output, be it HTML or JSON, on a separate sheet of the spreadsheet, or in Script Cache. This way doGet will only has to retrieve a string and serve it immediately.

Body:
I've a web app in Google Apps Script where I take a list of restaurants data(name, address, phone etc.) from Google Sheet and show them to my website through AJAX. Currently the resulted data are generated HTML created from Google Apps Script and I was thinking if there's any way to load the list faster. Then I thought of JSON, but I researched about it and found it's not that much of difference in loading time. Here is the HTML code that renders for each of the row data in sheet,

  for (var i=0; i<rng.length; i++)
  {
    if (rng[i][0] != "") {
      html += '

'+rng[i][1]+'

'+rng[i][2]+'

'+rng[i][3]+'

                      See Menu

';
    }
  }

So for each row of data it creates that part of HTML code and returns the entire HTML in my website where I get it through jQuery AJAX. Now, my question is, is the above method better or should I use JSON to get the raw data only & render it through the client-side?


问:
Web scraping using Python and Selenium
I am using the following code to submit a form using Python.
When the value entered is correct, it redirects to a new page called http://localhost/a/my.php. How do i check whether the page is redirected using python so that I can know that the values entered where correct.

```<code>from selenium import webdriver

webpage = r"http://localhost/a/"
driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe")
for i in range(10):
    searchterm = i # edit me
    driver.get(webpage)
    sbox = driver.find_element_by_class_name("txtSearch")
    sbox.send_keys(searchterm)

    submit = driver.find_element_by_class_name("sbtSearch")
    submit.click()
</code>```

答:
to check whether the page is redirected properly or not, use a WebDriverWait (aka "explicit wait") with proper
expected_conditions clause set to one of the following:

Python :

url_to_be :

```<code>WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))
</code>```

url_matches :

```<code>WebDriverWait(driver, 10).until(EC.url_matches("https://www.google.co.in/"))
</code>```

url_contains :

```<code>WebDriverWait(driver, 10).until(EC.url_contains("google"))
</code>```

url_changes :

```<code>WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))
</code>```

Title: Web scraping using Python and Selenium

Body:
I am using the following code to submit a form using Python.
When the value entered is correct, it redirects to a new page called http://localhost/a/my.php. How do i check whether the page is redirected using python so that I can know that the values entered where correct.

from selenium import webdriver

webpage = r"http://localhost/a/"
driver = webdriver.Chrome("C:\chromedriver_win32\chromedriver.exe")
for i in range(10):
    searchterm = i # edit me
    driver.get(webpage)
    sbox = driver.find_element_by_class_name("txtSearch")
    sbox.send_keys(searchterm)

    submit = driver.find_element_by_class_name("sbtSearch")
    submit.click()

Body:
to check whether the page is redirected properly or not, use a WebDriverWait (aka "explicit wait") with proper
expected_conditions clause set to one of the following:

Python :

url_to_be :

WebDriverWait(driver, 10).until(EC.url_to_be("https://www.google.co.in/"))

url_matches :

WebDriverWait(driver, 10).until(EC.url_matches("https://www.google.co.in/"))

url_contains :

WebDriverWait(driver, 10).until(EC.url_contains("google"))

url_changes :

WebDriverWait(driver, 10).until(EC.url_changes("https://www.google.co.in/"))

ContentLicense: CC BY-SA 4.0


问:
How can I edit files in c:/inetpub/wwwroot/testsite on vista/IIS7?
I've got IIS7 installed and have a simple website at:

c:/inetpub/wwwroot/testsite

I can copy files into there, but I can't edit them:

I can open them but cannot save them back

the files themselves are not write-protected

the folder itself ("testsite") IS write protected, so I took the write-protection off (right-click, properties, uncheck read-only, continue as administrator, etc.) and it pretends to change it but then always sets it back to read-only

What is the modus operandi for editing web files on IIS7 on Vista?

答:
You have a couple choices:

Replace the permissions on the entire folder.

log on as administrator and do what you need to.

OwnerDisplayName: Edward Tanguay

OwnerDisplayName: Chris Lively


问:
Clean debug output function?
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

```<code>__FILE__
__LINE__
</code>```

but there's a problem in my opinion... When I'm writing a function like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}
</code>```

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}
</code>```

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

答:
replace error with #define

something like:

```<code>#ifdef DEBUG
#define error(a,b) printf("Error at %s: %s\n", (a), (b))
#else
#define error(a,b)
#endif
</code>```

You could also move AT into error instead of passing it each time

Title: Clean debug output function?

Body:
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

__FILE__
__LINE__

but there's a problem in my opinion... When I'm writing a function like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

Body:
replace error with #define

something like:

#ifdef DEBUG
#define error(a,b) printf("Error at %s: %s\n", (a), (b))
#else
#define error(a,b)
#endif

You could also move AT into error instead of passing it each time


问:
select html till i reach a specific class
I have a html like this:

```<code><table>
<tr>
<td>a1</td>
<td>a2</td>

</tr>

<tr>
<td>b1</td>
<td>b2</td>

</tr>

<tr>
<td>c1</td>
<td>c2</td>

</tr>

<tr class="total">
<td>d1</td>
<td>d2</td>

</tr>

<tr>
<td>e1</td>
<td>e2</td>

</tr>

</table>
</code>```

now i want to select only the html till i reach 'total' class, so the hmtl i want jquery to select is:

```<code><tr>
<td>a1</td>
<td>a2</td>

</tr>

<tr>
<td>b1</td>
<td>b2</td>

</tr>

<tr>
<td>c1</td>
<td>c2</td>

</tr>

<tr class="total">
<td>d1</td>
<td>d2</td>

</tr>
</code>```

the code i tried for this was:

```<code>console.log($("table .total").parentsUntil("table").html());
</code>```

but this gives all the tr's (that is, including e1,e2 rows, which i dont want)

if i had gotten the correct html, (ie, till d series), i would perform an action on the each of the tr's to get a perticular value (i mean for ex i want a1, b1, c1, and d1 only, not e1, so i put total class on the d series only).

can anyone help me to get only html till 'total'?

Thanks in advance...

答:
Established what is excluded:

```<code>var exc = $('.total').nextAll('tr').add('.total');
</code>```

Then collect everything but the exclusions.

```<code>var inc = $('tr').not(exc);
</code>```

Demo

/* Get All
 after `.total` and add `.total`
|| as well
*/
var exc = $('.total').nextAll('tr').add('.total');

/* Get all
 but not the
 in the exc var */
var inc = $('tr').not(exc);

// Just to demonstarte that it worked
inc.css('background', 'cyan');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
td {
  border: 1px solid #000
}</code>```

    a1
    a2

    b1
    b2

    c1
    c2

    d1
    d2

    e1
    e2

```

Body:
I have a html like this:

a1
a2

b1
b2

c1
c2

d1
d2

e1
e2

now i want to select only the html till i reach 'total' class, so the hmtl i want jquery to select is:

a1
a2

b1
b2

c1
c2

d1
d2

the code i tried for this was:

console.log($("table .total").parentsUntil("table").html());

but this gives all the tr's (that is, including e1,e2 rows, which i dont want)

if i had gotten the correct html, (ie, till d series), i would perform an action on the each of the tr's to get a perticular value (i mean for ex i want a1, b1, c1, and d1 only, not e1, so i put total class on the d series only).

can anyone help me to get only html till 'total'?

Thanks in advance...

Body:
Established what is excluded:

var exc = $('.total').nextAll('tr').add('.total');

Then collect everything but the exclusions.

var inc = $('tr').not(exc);

Demo

/* Get All <tr> after `.total` and add `.total`
|| as well
*/
var exc = $('.total').nextAll('tr').add('.total');

/* Get all <tr> but not the <tr> in the exc var */
var inc = $('tr').not(exc);

// Just to demonstarte that it worked
inc.css('background', 'cyan');

table,
td {
  border: 1px solid #000
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>a1</td>
    <td>a2</td>
  </tr>
  <tr>
    <td>b1</td>
    <td>b2</td>
  </tr>
  <tr>
    <td>c1</td>
    <td>c2</td>
  </tr>
  <tr class="total">
    <td>d1</td>
    <td>d2</td>
  </tr>
  <tr>
    <td>e1</td>
    <td>e2</td>
  </tr>
</table>


问:
PHP Strange issue with working code
There is a technique by which the list of (N+1) bit codes can be generated from (N)-bit codes.

Take the list of N bit codes in the given order and call it List-N

Reverse the above list (List-N), and name the new reflected list: Reflected-List-N

Prefix each member of the original list (List-N) with 0 and call this new list 'A'

Prefix each member of the new list (Reflected-List-N) with 1 and call this new list 'B'

The list of codes with N+1 bits is the concatenation of Lists A and B.

A Demonstration of the above steps: Generating the list of 3-bit Mystery Codes from 2-Bit Mystery Codes

2-bit list of codes: 00, 01, 11, 10

Reverse/Reflect the above list: 10, 11, 01, 00

Prefix Old Entries with 0:  000, 001, 011, 010

Prefix Reflected List with 1:  110, 111, 101, 100

Concatenate the lists obtained in the last two steps:  000, 001, 011, 010, 110, 111, 101, 100

I found solution but when I enter 65 for example getting error

PHP Fatal error:  Out of memory (allocated 538968064) (tried to allocate 20 bytes) in /home/pLR62k/prog.php on line 27

on Ideone http://goo.gl/WB3DKh

What Am I doing wrong?

```<code><?php
function MysteryCodes($input){
    $initArr=array(0,1);
    if($input==1){
        return $initArr;
    }
    else {
        $list=array();
        $list[0]=$initArr;
        for ($i=1; $i<$input; $i++)
            {
                $prevIndex=$i-1;
                $reflectedListN = array_reverse($list[$prevIndex]);
                $listA=prefixR($list[$prevIndex], '0');
                $listB=prefixR($reflectedListN, '1');
                $list[$i]=array_merge($listA, $listB);
            }
    }
    return array_slice($list[$input-1], -$input);
}

function prefixR($input, $prefix){
    $result=array();
    foreach($input as $value){
        $result[]=$prefix.$value;
    }
    return $result;
}

fscanf(STDIN, "%d", $inp);
if($inp>=1 && $inp<=65){
$result=MysteryCodes($inp);
$output="";
foreach($result as $key=>$value)
    $output.="$value\n";

fwrite(STDOUT, $output);
}
</code>```

答:
What you did is almost correct, except "array_merge". This will utilize more memory .

Below code will work Like a Charm!!!!

```<code>    $length = 100;//input value

    if($length > 1) {
        $mysteryArray = ['0', '1'];
        for ($i=2; $i <= $length; $i++) {
            $reverseArray = array_reverse($mysteryArray);

            $tempArray = [];

            foreach ($mysteryArray as $key => $value) {
                $tempArray[] = '0' . $value;
            }

            foreach ($reverseArray as $key => $value) {
                $tempArray[] = '1' . $value;
            }

            if($i != $length) {
                $mysteryArray = array_slice($tempArray, 0, $i+$length);
            } else {
                $mysteryArray = array_slice($tempArray, -$length, $length);
            }

        }
        foreach ($mysteryArray as $key => $value) {
            echo $value . '<br>';
        }
    } else {
        echo '1';
    }
</code>```

Title: PHP Strange issue with working code

Body:
There is a technique by which the list of (N+1) bit codes can be generated from (N)-bit codes.

Take the list of N bit codes in the given order and call it List-N

Reverse the above list (List-N), and name the new reflected list: Reflected-List-N

Prefix each member of the original list (List-N) with 0 and call this new list 'A'

Prefix each member of the new list (Reflected-List-N) with 1 and call this new list 'B'

The list of codes with N+1 bits is the concatenation of Lists A and B.

A Demonstration of the above steps: Generating the list of 3-bit Mystery Codes from 2-Bit Mystery Codes

2-bit list of codes: 00, 01, 11, 10

Reverse/Reflect the above list: 10, 11, 01, 00

Prefix Old Entries with 0:  000, 001, 011, 010

Prefix Reflected List with 1:  110, 111, 101, 100

Concatenate the lists obtained in the last two steps:  000, 001, 011, 010, 110, 111, 101, 100

I found solution but when I enter 65 for example getting error

PHP Fatal error:  Out of memory (allocated 538968064) (tried to allocate 20 bytes) in /home/pLR62k/prog.php on line 27

on Ideone http://goo.gl/WB3DKh

What Am I doing wrong?

<?php
function MysteryCodes($input){
    $initArr=array(0,1);
    if($input==1){
        return $initArr;
    }
    else {
        $list=array();
        $list[0]=$initArr;
        for ($i=1; $i<$input; $i++)
            {
                $prevIndex=$i-1;
                $reflectedListN = array_reverse($list[$prevIndex]);
                $listA=prefixR($list[$prevIndex], '0');
                $listB=prefixR($reflectedListN, '1');
                $list[$i]=array_merge($listA, $listB);
            }
    }
    return array_slice($list[$input-1], -$input);
}

function prefixR($input, $prefix){
    $result=array();
    foreach($input as $value){
        $result[]=$prefix.$value;
    }
    return $result;
}

fscanf(STDIN, "%d", $inp);
if($inp>=1 && $inp<=65){
$result=MysteryCodes($inp);
$output="";
foreach($result as $key=>$value)
    $output.="$value\n";

fwrite(STDOUT, $output);
}

Body:
What you did is almost correct, except "array_merge". This will utilize more memory .

Below code will work Like a Charm!!!!

    $length = 100;//input value

    if($length > 1) {
        $mysteryArray = ['0', '1'];
        for ($i=2; $i <= $length; $i++) {
            $reverseArray = array_reverse($mysteryArray);

            $tempArray = [];

            foreach ($mysteryArray as $key => $value) {
                $tempArray[] = '0' . $value;
            }

            foreach ($reverseArray as $key => $value) {
                $tempArray[] = '1' . $value;
            }

            if($i != $length) {
                $mysteryArray = array_slice($tempArray, 0, $i+$length);
            } else {
                $mysteryArray = array_slice($tempArray, -$length, $length);
            }

        }
        foreach ($mysteryArray as $key => $value) {
            echo $value . '<br>';
        }
    } else {
        echo '1';
    }


问:
php get file extension from image
so i want to get the file extension from the img so if i upload a image i can use mutiple file exts but when i use this code to get the file ext it does not work</p>

```<code>$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $id = $row['user_id'];
        $sql = "SELECT * FROM users WHERE user_id='$id'";
        $result = mysqli_query($conn, $sql);
        while ($rowImg = mysqli_fetch_assoc($result)) {
            if ($rowImg['status'] == 0) {
                $filename = "../assets/IMGS/profile/Avatar".$id.".*";
                $fileinfo = glob($filename);
                $fileext = explode(".", $fileinfo[0]);
                $fileactualext = $fileext[1];

                echo "<img src='../assets/IMGS/profile/Avatar".$id.".".$fileactualext."?".mt_rand()."'>";
            } else {
                echo '<img src="../assets/IMGS/profile/def-image.png">';
            }
        }
    }
}
</code>```

答:
Try to get your filepath with image and store ina variable $filename then try this

```<code><?php
$path_parts = pathinfo($filename);
$extension =  $path_parts['extension'];
?>
</code>```

Title: php get file extension from image

Body:
so i want to get the file extension from the img so if i upload a image i can use mutiple file exts but when i use this code to get the file ext it does not work

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $id = $row['user_id'];
        $sql = "SELECT * FROM users WHERE user_id='$id'";
        $result = mysqli_query($conn, $sql);
        while ($rowImg = mysqli_fetch_assoc($result)) {
            if ($rowImg['status'] == 0) {
                $filename = "../assets/IMGS/profile/Avatar".$id.".*";
                $fileinfo = glob($filename);
                $fileext = explode(".", $fileinfo[0]);
                $fileactualext = $fileext[1];

                echo "";
            } else {
                echo '';
            }
        }
    }
}

Body:
Try to get your filepath with image and store ina variable $filename then try this

<?php
$path_parts = pathinfo($filename);
$extension =  $path_parts['extension'];
?>