问:
How to remove the first and last minor tick month labels on matplotlib?
I want to generate a chart with the 12 months of a year as the x-axis labels, i.e. 'Jan' to 'Dec', positioned in the middle between the major ticks. I used the code from https://matplotlib.org/3.4.3/gallery/ticks_and_spines/centered_ticklabels.html to create the x-axis. The x-axis created has an additional 'Dec' on the left and 'Jan' on the right, i.e. a total of 14 labels instead of 12 (see attached image). However, only 'Jan' to 'Dec' are wanted on the chart. I would like to know how to remove the 'Dec' label on the left and 'Jan' label on the right? My google searches were only successful with solutions to remove all minor tick labels. Any help will be much appreciated.

I use the following code to generate the chart:

```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

df = pd.DataFrame(np.random.randint(0,100,size=(365, 2)), columns=list('AB'))
df.index = pd.date_range(start='1/1/2022', end='12/31/2022').strftime('%b-%d')

plt.figure()
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))

for tick in ax.xaxis.get_minor_ticks():
    tick.tick1line.set_markersize(0)
    tick.tick2line.set_markersize(0)
    tick.label1.set_horizontalalignment('center')

plt.plot(df['A'], linewidth=0.5, color='tab:red')

plt.show()
</code>```

enter image description here

答:
Try setting your x-axis limit to values between 0 and 365. Sometimes matplotlib uses values a little outside of your data. This way, the first Dec and last Jan are automatically eliminated from the plot.

Here I modified your code with 1 argument: plt.xlim(0,365)

```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

df = pd.DataFrame(np.random.randint(0,100,size=(365, 2)), columns=list('AB'))
df.index = pd.date_range(start='1/1/2022', end='12/31/2022').strftime('%b-%d')

plt.figure()
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))

for tick in ax.xaxis.get_minor_ticks():
    tick.tick1line.set_markersize(0)
    tick.tick2line.set_markersize(0)
    tick.label1.set_horizontalalignment('center')

plt.xlim(0,365)
plt.plot(df['A'], linewidth=0.5, color='tab:red')

plt.show()
</code>```

Body:
I want to generate a chart with the 12 months of a year as the x-axis labels, i.e. 'Jan' to 'Dec', positioned in the middle between the major ticks. I used the code from https://matplotlib.org/3.4.3/gallery/ticks_and_spines/centered_ticklabels.html to create the x-axis. The x-axis created has an additional 'Dec' on the left and 'Jan' on the right, i.e. a total of 14 labels instead of 12 (see attached image). However, only 'Jan' to 'Dec' are wanted on the chart. I would like to know how to remove the 'Dec' label on the left and 'Jan' label on the right? My google searches were only successful with solutions to remove all minor tick labels. Any help will be much appreciated.

I use the following code to generate the chart:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

df = pd.DataFrame(np.random.randint(0,100,size=(365, 2)), columns=list('AB'))
df.index = pd.date_range(start='1/1/2022', end='12/31/2022').strftime('%b-%d')

plt.figure()
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))

for tick in ax.xaxis.get_minor_ticks():
    tick.tick1line.set_markersize(0)
    tick.tick2line.set_markersize(0)
    tick.label1.set_horizontalalignment('center')

plt.plot(df['A'], linewidth=0.5, color='tab:red')

plt.show()

enter image description here

Body:
Try setting your x-axis limit to values between 0 and 365. Sometimes matplotlib uses values a little outside of your data. This way, the first Dec and last Jan are automatically eliminated from the plot.

Here I modified your code with 1 argument: plt.xlim(0,365)

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

df = pd.DataFrame(np.random.randint(0,100,size=(365, 2)), columns=list('AB'))
df.index = pd.date_range(start='1/1/2022', end='12/31/2022').strftime('%b-%d')

plt.figure()
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonthday=16))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))

for tick in ax.xaxis.get_minor_ticks():
    tick.tick1line.set_markersize(0)
    tick.tick2line.set_markersize(0)
    tick.label1.set_horizontalalignment('center')

plt.xlim(0,365)
plt.plot(df['A'], linewidth=0.5, color='tab:red')

plt.show()


来源: stackexchange

问:
Sanitizing non-English letters to use safely in URLs
What is the best way, in .NET, to create safe URLs from titles of posts?
For example, I may have a post "test wıth non enğlİşh çharaçters" and I want to turn this into a URL safe form while still maintaining the readability purpose of the title being URL, such as, "test-with-non-english-characters", and I will use them as http://mysite/blog/5/test-with-non-english-characters I can just iterate over the string characters and either leave ALL letters as they are (not safe to use in URLs), or wipe out all non-English characters and turn them into an underscore etc. (breaks the purpose of readability, as posts will/may be in non English languages). I'm sure that there's a method for converting ş to s and Ğ to G etc. just like in an accent insensitive search query in SQL server.

答:
See my answer to another question to remove accents from a string.

Note that this doesn't completely solve the problem. For example, Asian ideograms or non latin letters will not be transliterated to english (latin) letters using this code.

ContentLicense: CC BY-SA 3.0


问:
Trigger CSS Animations in JavaScript
I don't know how to use JQuery, so I need a method which could trigger an animation using JavaScript only.

I need to call/trigger CSS Animation when the user scrolls the page.

function start() {
  document.getElementById('logo').style.animation = "anim 2s 2s forward";
  document.getElementById('earthlogo').style.animation = "anim2 2s 2s forward";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0px;
}

#logo {
  position: fixed;
  top: 200px;
  height: 200px;
  width: 1000px;
  left: 5%;
  z-index: 4;
  opacity: 0.8;
}

#earthlogo {
  position: fixed;
  top: 200px;
  height: 120px;
  align-self: center;
  left: 5%;
  margin-left: 870px;
  margin-top: 60px;
  z-index: 4;
  opacity: 0.9;
}

@keyframes anim {
  50% {
    filter: blur(10px);
    transform: rotate(-15deg);
    box-shadow: 0px 0px 10px 3px;
  }
  100% {
    height: 100px;
    width: 500px;
    left: 10px;
    top: 10px;
    box-shadow: 0px 0px 15px 5px rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 1, 0.3);
    opacity: 0.7;
  }
}

@keyframes anim2 {
  50% {
    filter: blur(40px);
    transform: rotate(-15deg);
  }
  100% {
    height: 60px;
    width: 60px;
    left: 10px;
    top: 10px;
    margin-left: 435px;
    margin-top: 30px;
    opacity: 0.8;
  }
}

#backstar {
  position: fixed;
  width: 100%;
  z-index: 1;
}

#earth {
  position: absolute;
  width: 100%;
  z-index: 2;
  top: 300px;
}</code>```

```

答:
A more idiomatic solution is to use the Web Animations API.

Here is the example from MDN:

```<code>document.getElementById("alice").animate(
  [
    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
    { color: '#431236', offset: 0.3 },
    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
  ], {
    duration: 3000,
    iterations: Infinity
  }
);
</code>```

OP's example:

```<code>document.getElementById('logo').animate(
    [
        {},
        {
            filter: 'blur(10px)',
            transform: 'rotate(-15deg)',
            box-shadow: '0px 0px 10px 3px',
        },
        {
            height: '100px',
            width: '500px',
            left: '10px',
            top: '10px',
            box-shadow: '0px 0px 15px 5px rgba(0, 0, 0, 0.7)',
            background-color: 'rgba(0, 0, 1, 0.3)',
            opacity: '0.7',
        },
    ],
    {
        duration: 2000,
        delay: 2000,
        fill: 'forwards',
    },
)
</code>```

At the time of writing, it's supported in all major browsers except IE.
Supported browsers

ContentLicense: CC BY-SA 4.0

Title: Trigger CSS Animations in JavaScript

Body:
I don't know how to use JQuery, so I need a method which could trigger an animation using JavaScript only.

I need to call/trigger CSS Animation when the user scrolls the page.

function start() {
  document.getElementById('logo').style.animation = "anim 2s 2s forward";
  document.getElementById('earthlogo').style.animation = "anim2 2s 2s forward";
}

* {
  margin: 0px;
}

#logo {
  position: fixed;
  top: 200px;
  height: 200px;
  width: 1000px;
  left: 5%;
  z-index: 4;
  opacity: 0.8;
}

#earthlogo {
  position: fixed;
  top: 200px;
  height: 120px;
  align-self: center;
  left: 5%;
  margin-left: 870px;
  margin-top: 60px;
  z-index: 4;
  opacity: 0.9;
}

@keyframes anim {
  50% {
    filter: blur(10px);
    transform: rotate(-15deg);
    box-shadow: 0px 0px 10px 3px;
  }
  100% {
    height: 100px;
    width: 500px;
    left: 10px;
    top: 10px;
    box-shadow: 0px 0px 15px 5px rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 1, 0.3);
    opacity: 0.7;
  }
}

@keyframes anim2 {
  50% {
    filter: blur(40px);
    transform: rotate(-15deg);
  }
  100% {
    height: 60px;
    width: 60px;
    left: 10px;
    top: 10px;
    margin-left: 435px;
    margin-top: 30px;
    opacity: 0.8;
  }
}

#backstar {
  position: fixed;
  width: 100%;
  z-index: 1;
}

#earth {
  position: absolute;
  width: 100%;
  z-index: 2;
  top: 300px;
}

Body:
A more idiomatic solution is to use the Web Animations API.

Here is the example from MDN:

document.getElementById("alice").animate(
  [
    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
    { color: '#431236', offset: 0.3 },
    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
  ], {
    duration: 3000,
    iterations: Infinity
  }
);

OP's example:

document.getElementById('logo').animate(
    [
        {},
        {
            filter: 'blur(10px)',
            transform: 'rotate(-15deg)',
            box-shadow: '0px 0px 10px 3px',
        },
        {
            height: '100px',
            width: '500px',
            left: '10px',
            top: '10px',
            box-shadow: '0px 0px 15px 5px rgba(0, 0, 0, 0.7)',
            background-color: 'rgba(0, 0, 1, 0.3)',
            opacity: '0.7',
        },
    ],
    {
        duration: 2000,
        delay: 2000,
        fill: 'forwards',
    },
)

At the time of writing, it's supported in all major browsers except IE.
Supported browsers


问:
[JavaScript]Add elements to a global array in a function and keep them

window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);```

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

答:
Your function's code is fine.

However, you are logging the array using console.log before func1() gets to run, since window.onload fires AFTER everything has loaded.

Body:
window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?


问:
SQL query: total people living in each province
I am using PostgreSQL and Windows.

I have an SQL query issue. The table diagram:

I am having difficulty trying to understand this scenario:

Return the list of provinces alphabetically ordered, and the total count of personnel living in each province where there are at least 5 personnel living in it.

The answer should look something like this:

How can I write a query for this?

答:
I see this as being a join between the Province and Personnel tables:

SELECT pv.Code, pv.Name, COUNT(pl.PersonnelID) AS "Total Personnel"
FROM Province pv
LEFT JOIN Personnel pl
    ON pl.CountryOfOrigin = pv.CountryID
GROUP BY pv.Code, pn.Name;
```

Note that I am including the province code in the query, as perhaps two provinces might occasionally share the same name.  If not, then you may remove the code and use the structure of your current output table.

Body:
I see this as being a join between the Province and Personnel tables:

SELECT pv.Code, pv.Name, COUNT(pl.PersonnelID) AS "Total Personnel"
FROM Province pv
LEFT JOIN Personnel pl
    ON pl.CountryOfOrigin = pv.CountryID
GROUP BY pv.Code, pn.Name;

Note that I am including the province code in the query, as perhaps two provinces might occasionally share the same name.  If not, then you may remove the code and use the structure of your current output table.


问:
jQuery index on each function
I am curious why I need this index

```<code>$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });
</code>```

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

答:
try </p>

```<code> var buttonId = $(this).attr("id");
</code>```

Title: jQuery index on each function

Body:
I am curious why I need this index

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

Body:
try

 var buttonId = $(this).attr("id");


问:
How can i fixed the npm run deploy problem
I am trying put my new react application on github pages but I cannot resolve some things...

I'm follow the tutorial on this link "https://github.com/gitname/react-gh-pages" and when i run the command "npm run deploy", the following message appears:

[Failed to compile.

static/js/main.9e58b467.js from UglifyJs
SyntaxError: Unexpected token: punc ({) [./~/react-router-dom/umd/react-router-dom.production.min.js:11,866]

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! portfolio@0.1.0 build: react-scripts build
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the portfolio@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/arthur/.npm/_logs/2022-02-06T21_32_24_524Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! portfolio@0.1.0 predeploy: npm run build
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the portfolio@0.1.0 predeploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.]1

Things that I'm already try...

Install a webpack plugging with "npm install --save uglifyjs-webpack-plugin"

Delete the package-lock.json, the node-modules directory and clean the npm cache, and npm install again...

Please help! I don't know what to do now...

The link to the repository is https://github.com/ArthurBMessias/react-port

答:
Changing my "react-scripts" property in my package.json to version "5.0.0"

```<code>"react-scripts": "5.0.0"
</code>```

worked for me!

Body:
Changing my "react-scripts" property in my package.json to version "5.0.0"

"react-scripts": "5.0.0"

worked for me!


问:
How to mount a Sinatra application inside another Sinatra app?
I am trying to write a Sinatra application that groups components together (sort of like controllers). So for the "blog" related things, I want an app called Blog mounted at /blog. All of the routes contained in the Blog app would be relative to its mounted path, so I could simply define an index route without having to specify the mount path in the route.

I originally handled this by using a config.ru file and maping the routes to the different apps. The problem with this that I ran into, was that I was using various sinatra gems/extensions/helpers that needed to be included in all of the apps, so there was a lot of duplicate code.

How can I mount one sinatra app inside of another so that the routes defined in the app are relative to where the app is mounted? If this is not possible out-of-the-box, can you show a code sample of how this could be done?

Here's a simplified example of what it might look like:

```<code>class App
  mount Blog, at: '/blog'
  mount Foo, at: '/bar'
end

class Blog
  get '/' do
    # index action
  end
end

class Foo
  get '/' do
    # index action
  end
end
</code>```

答:
I just meet the same problems.

I found that whatever inclued  extend register or  rack middleware style use had problems.

You can use Ruby to solve this problems like that:

require "sinatra"

class App < Sinatra::Base

  class << self
    def define_routes(&block)
      class_eval(&block)
    end
  end

end

App.define_routes do

  get "/hello"
    "hello world"
  end
end
```

Body:
I am trying to write a Sinatra application that groups components together (sort of like controllers). So for the "blog" related things, I want an app called Blog mounted at /blog. All of the routes contained in the Blog app would be relative to its mounted path, so I could simply define an index route without having to specify the mount path in the route.

I originally handled this by using a config.ru file and maping the routes to the different apps. The problem with this that I ran into, was that I was using various sinatra gems/extensions/helpers that needed to be included in all of the apps, so there was a lot of duplicate code.

How can I mount one sinatra app inside of another so that the routes defined in the app are relative to where the app is mounted? If this is not possible out-of-the-box, can you show a code sample of how this could be done?

Here's a simplified example of what it might look like:

class App
  mount Blog, at: '/blog'
  mount Foo, at: '/bar'
end

class Blog
  get '/' do
    # index action
  end
end

class Foo
  get '/' do
    # index action
  end
end


问:
Using remote MySQL database on Heroku running Django app
I've been struggling with the following problem:
I have a MySQL database running on a remote web host. I connect to the MySQL database in my Django app (I use it as the main database). The Django app is running on a Heroku server but I get different data results  compared to running it locally.

Am I missing something, or are changes done on Heroku not committed to the database?

MySQL settings:

```<code>DATABASES = {
 #   'default': {
  #      'ENGINE': 'django.db.backends.sqlite3',
   #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxx',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxx',
        'PORT': 'xxx',
    }
}
</code>```

答:
I believe Juan Carlos Hernández is correct.  To expand on his answer, Heroku uses it's own database instance, unless you tell it otherwise by pointing the DATABASE_URL to the one you would like to use.  Please note that Heroku will prevent you from overwriting the DATABASE_URL in use since that will destroy the existing database.  Although tagged as ruby-on-rails, the answers I found here seem relevant.

To summarize, you just have to run

```<code>heroku config:add DATABASE_URL=mysql://dbusername:dbpassword@databasehostIP:3306/databasename
heroku config:add SHARED_DATABASE_URL=mysql://dbusername:dbpassword@databasehostIP:3306/databasename
</code>```

Then do

```<code>heroku restart
</code>```

Or you can change these variables in the Heroku panel.

Body:
I've been struggling with the following problem:
I have a MySQL database running on a remote web host. I connect to the MySQL database in my Django app (I use it as the main database). The Django app is running on a Heroku server but I get different data results  compared to running it locally.

Am I missing something, or are changes done on Heroku not committed to the database?

MySQL settings:

DATABASES = {
 #   'default': {
  #      'ENGINE': 'django.db.backends.sqlite3',
   #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
   # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxx',
        'USER': 'xxx',
        'PASSWORD': 'xxx',
        'HOST': 'xxx',
        'PORT': 'xxx',
    }
}

Body:
I believe Juan Carlos Hernández is correct.  To expand on his answer, Heroku uses it's own database instance, unless you tell it otherwise by pointing the DATABASE_URL to the one you would like to use.  Please note that Heroku will prevent you from overwriting the DATABASE_URL in use since that will destroy the existing database.  Although tagged as ruby-on-rails, the answers I found here seem relevant.

To summarize, you just have to run

heroku config:add DATABASE_URL=mysql://dbusername:dbpassword@databasehostIP:3306/databasename
heroku config:add SHARED_DATABASE_URL=mysql://dbusername:dbpassword@databasehostIP:3306/databasename

Then do

heroku restart

Or you can change these variables in the Heroku panel.


问:
index.php and protecting of its content
What are the chances hackers are able to download index.php file from the server (not the result, but the content of index.php file)? Do you recommend to put the content of index.php to modules/index_content.php, where modules folder is .htaccess protected AND index.php contains the only string <?php require_once('modules/index_content.php') ?> ?  Does it make sense?

答:
Source code disclosure can happen on a well-configured server and is not as rare as you might think. As the others have said, if your server-configuration is sound, then there won't be a problem with people requesting PHP files directly.

However you could still be vulnerable to:

Script Source Accessible through Backup

Many editors leave backup files with common file extensions, such as ~ or .bak. Your server may not run these through the PHP interpreter as they are commonly configured to do so by file extension. Leave these backup files around and you could be disclosing your source.

Local file inclusion

There can also be a problem if you have a webapp that uses user-input to read other files. If the script is not validating the user input correctly, it could be vulnerable to LFI. Scripts such as these should only read whitelisted files, or at a minimum be restricted to a certain directory. If "../" is accepted, then you have a Directory Traversal vulnerability which will exacerbate the above two vulnerabilities to be even more serious.

Add to this, many servers have enabled

Directory Browsing

which is when your server will list the files in a directory if a default file is not present (index.html, index.php, default.htm etc.). This won't disclose any source in its own right but does allows many of the files (server-side processed or not) on the server to be enumerated to the malicious user, making it very easy to focus further attacks.

Source disclosure via alternate server

Another accidental scenario can be when two web servers are pointed (perhaps indirectly) at the same document root. If one of the web servers is not configured to process PHP, then the source can be disclosed. I have seen this happen by accident a number of times when a web-server is configured to reverse-proxy to a chained app-server for certain URL patterns (usually by directory). e.g. have Tomcat handle everything under /forum.

SQL injection

Pretty much every serious DBMS has a function that allows it to read files on the system. If you don't protect your database inputs (please just use parameterised queries) you may be vulnerable to source code disclosure through this mechanism. Mind you, in this scenario, source-code disclosure is your last concern.

I'm sure there's loads of others, but these are some of the most common ways I see this kind of disclosure. Just remember that security is a process and is wide-ranging in its scope. Often it is the interaction of concerns, systems or applications that were treated as separate entities that causes the problems.

Title: index.php and protecting of its content


问:
Set formControlName to Template Variable
I'm working in an Angular v12 project. I have a form with many controls. In my template, I'm creating loops to display these controls. The controls are displayed in blocks in various positions (so all the outer divs matter).

When I set up these loops with a span, it works fines and shows the value of control I need:

```<code><div class="d-flex" *ngFor="let rowGroup of rowGroups">
   <div class="square" *ngFor="let group of rowGroup">
      <div class="d-flex" *ngFor="let i of [1,2,3]">
         <div class="block" *ngFor="let j of [1,2,3]">
            <span>
              {{this.form.get(group+'-'+i+'-'+j)?.value}}
            </span>
         </div>
      </div>
   </div>
</div>
</code>```

But now, instead of a span, I want to be able to use a material input. But I need to be able to set the formControlName to the template variables (group+'-'+i+'-'+j).

```<code><div class="d-flex" *ngFor="let rowGroup of rowGroups">
   <div class="square" *ngFor="let group of rowGroup">
      <div class="d-flex" *ngFor="let i of [1,2,3]">
         <div class="block" *ngFor="let j of [1,2,3]">
            <mat-form-field appearance="outline">
               <input matInput formControlName="{{VARIABLE(group+'-'+i+'-'+j) HERE?}}">
            </mat-form-field>
         </div>
      </div>
   </div>
</div>
</code>```

Is there a way to do that?

答:
You simply need to bind it as:

formControlName="{{group+'-'+i+'-'+j}}"
```
<p>So your html would be something as below:</p>
<pre class="lang-html prettyprint-override"><code><form [formGroup]="form"> <!-- You would need this binding too  -->
  <div class="d-flex" *ngFor="let rowGroup of rowGroups">
    <div class="square" *ngFor="let group of rowGroup">
      <div class="d-flex" *ngFor="let i of [1,2,3]">
        <div class="block" *ngFor="let j of [1,2,3]">
          <mat-form-field appearance="outline">
            <input matInput formControlName="{{group+'-'+i+'-'+j}}">
          </mat-form-field>
        </div>
      </div>
    </div>
  </div>
</form>
</code>```

PS: The above should work if {{this.form.get(group+'-'+i+'-'+j)?.value}} worked for you. In case if it doesn't work, please do share the form FormGroup structure defined in ts file.

Body:
I'm working in an Angular v12 project. I have a form with many controls. In my template, I'm creating loops to display these controls. The controls are displayed in blocks in various positions (so all the outer divs matter).

When I set up these loops with a span, it works fines and shows the value of control I need:

              {{this.form.get(group+'-'+i+'-'+j)?.value}}

But now, instead of a span, I want to be able to use a material input. But I need to be able to set the formControlName to the template variables (group+'-'+i+'-'+j).

            <mat-form-field appearance="outline">
               <input matInput formControlName="{{VARIABLE(group+'-'+i+'-'+j) HERE?}}">
            </mat-form-field>

Is there a way to do that?

Body:
You simply need to bind it as:

formControlName="{{group+'-'+i+'-'+j}}"

So your html would be something as below:

<form [formGroup]="form"> <!-- You would need this binding too  -->
  <div class="d-flex" *ngFor="let rowGroup of rowGroups">
    <div class="square" *ngFor="let group of rowGroup">
      <div class="d-flex" *ngFor="let i of [1,2,3]">
        <div class="block" *ngFor="let j of [1,2,3]">
          <mat-form-field appearance="outline">
            <input matInput formControlName="{{group+'-'+i+'-'+j}}">
          </mat-form-field>
        </div>
      </div>
    </div>
  </div>
</form>

PS: The above should work if {{this.form.get(group+'-'+i+'-'+j)?.value}} worked for you. In case if it doesn't work, please do share the form FormGroup structure defined in ts file.


问:
Loose coupling in Dart
I was trying to implement loose coupling in one of my Flutter projects. It was not able to find the method.
Have replicated the same in a simple Dart code, how can I fix this, and is there some way to achieve loose coupling in Dart?

```<code>abstract class A{}

class B extends A{
  void help(){
    print("help");
  }
}

class C {
  A b;
  C({required this.b});
  void test(){
     b.help();
  }

}

void main() {
 var c = C(b:B());
  c.test();

}
</code>```

Giving error at b.help(), the method does on exist.

Exact error

```<code>The method 'help' isn't defined for the type 'A'.
</code>```

答:
b is known to be of type A, and the A interface does not provide a help method.

I don't know exactly what your definition of "loose coupling" is (it'd be better to describe a specific problem that you're trying to solve), but if you want help to be callable on type A, then you must add it to the A interface.

You alternatively could explicitly downcast b to B with a runtime check:

class C {
  A b;
  C({required this.b});
  void test() {
    // Shadow `this.b` with a local variable so that the local
    // variable can be automatically type-promoted.
    final b = this.b;
    if (b is B) {
      b.help();
    }
  }
}
```
<p>Or if you want duck typing, you could declare (or cast) <code>b</code> as <code>dynamic</code>:</p>
<pre class="lang-dart prettyprint-override"><code>class C {
  dynamic b;
  C({required this.b});
  void test() {
    try {
      b.help();
    } on NoSuchMethodError {}
  }
}
</code>```

although I would consider the last form to be bad style.

Title: Loose coupling in Dart

Body:
I was trying to implement loose coupling in one of my Flutter projects. It was not able to find the method.
Have replicated the same in a simple Dart code, how can I fix this, and is there some way to achieve loose coupling in Dart?

abstract class A{}

class B extends A{
  void help(){
    print("help");
  }
}

class C {
  A b;
  C({required this.b});
  void test(){
     b.help();
  }

}

void main() {
 var c = C(b:B());
  c.test();

}

Giving error at b.help(), the method does on exist.

Exact error

The method 'help' isn't defined for the type 'A'.

Body:
b is known to be of type A, and the A interface does not provide a help method.

I don't know exactly what your definition of "loose coupling" is (it'd be better to describe a specific problem that you're trying to solve), but if you want help to be callable on type A, then you must add it to the A interface.

You alternatively could explicitly downcast b to B with a runtime check:

class C {
  A b;
  C({required this.b});
  void test() {
    // Shadow `this.b` with a local variable so that the local
    // variable can be automatically type-promoted.
    final b = this.b;
    if (b is B) {
      b.help();
    }
  }
}

Or if you want duck typing, you could declare (or cast) b as dynamic:

class C {
  dynamic b;
  C({required this.b});
  void test() {
    try {
      b.help();
    } on NoSuchMethodError {}
  }
}

although I would consider the last form to be bad style.


问:
To cover the page side to side with a div?
enter image description here

How do i fill those borders at the side of those div elements?
I want the background-color property of the div to cover the area it is on completely side to side

this is my css for both of those div:

```<code>.res {
    background-color: coral;
    width: 100%;
    overflow: hidden;
    object-fit: fill;
    margin: 0px;
    border: 0px;
    padding: 0px;
}
</code>```

as you see, i've tried everything i found, but none of those worked

答:
Add

```<code>body {
    margin: 0;
}
</code>```

to your CSS file. It should fix it.

Body:
enter image description here

How do i fill those borders at the side of those div elements?
I want the background-color property of the div to cover the area it is on completely side to side

this is my css for both of those div:

.res {
    background-color: coral;
    width: 100%;
    overflow: hidden;
    object-fit: fill;
    margin: 0px;
    border: 0px;
    padding: 0px;
}

as you see, i've tried everything i found, but none of those worked

Body:
Add

body {
    margin: 0;
}

to your CSS file. It should fix it.


问:
Q/A - Edit license amount for Microsoft subscriptions without partner API - Passing ajaxsessionkey from selenium to requests module
I currently use selenium to login to Microsoft admin center and increase or decrease an office subscription of my choosing; however I want to try and use just the http requests library that comes with python to make my request.

Why I am doing this - I can't use the partner api to increase license to due to specific circumstances. I have access to my client's MS admin account and want to use python to increase a license when creating a user using the MS graph.

What I tried -
I first tried to create http requests to login into MS....that didn't seem possible: Logging into Microsoft Online website programatically with C# & Difference between CSRF and X-CSRF-Token I tried but seems I need to find the xsrf token that gets generated when using the webpage normally.

So I decided to use selenium to login to MS, then figure out how to use the commerce API when you are logged into MS.

Here is my code:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.actions import action_builder
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from auths.AA_auth import interm_auth, otpauth
from selenium.common import exceptions
import time

import requests
import json
def browser_options():
    options = Options()
    options.headless = True
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    browser_options.browser = webdriver.Chrome(options=options)
    return browser_options.browser

def mslogin(msdata):
    #Go to the specific subscription in question
    browser_options.browser.get("https://admin.microsoft.com/Adminportal/Home?#/subscriptions/webdirect/ENTERSKUIDHERE")

    #Enter email
    ms_username = browser_options.browser.find_element_by_css_selector('#i0116')
    ms_username.send_keys("ENTERADMINEMAIL")

    wait = WebDriverWait(browser_options.browser, 10)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#idSIButton9')))
    ms_usernameaccept = browser_options.browser.find_element_by_css_selector('#idSIButton9')
    ms_usernameaccept.send_keys(Keys.ENTER)

    #Enter password
    wait = WebDriverWait(browser_options.browser, 5)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#i0118')))
    ms_password = browser_options.browser.find_element_by_css_selector('#i0118')
    ms_password.send_keys("ENTERADMINPASSWORD")

    wait = WebDriverWait(browser_options.browser, 10)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#idSIButton9')))
    ms_passwordaccept = browser_options.browser.find_element_by_css_selector('#idSIButton9')
    ms_passwordaccept.send_keys(Keys.ENTER)

    #Getting past the reduced password inquiry webpage
    wait = WebDriverWait(browser_options.browser, 5)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#idBtn_Back')))
    reducedlogingcancel = browser_options.browser.find_element_by_css_selector('#idBtn_Back')
    reducedlogingcancel.send_keys(Keys.ENTER)
    time.sleep(1)

    #Get cookieinfo
    request_cookies_browser =  browser_options.browser.get_cookies()
    browser_options.browser.close()
    print(request_cookies_browser)

    s = requests.Session()
    for cookie in request_cookies_browser:
        s.cookies.set(cookie['name'], cookie['value'])

    X = ENTERNUMBERHERE

    patchheaders = {
                "accept":"application/json, text/plain, */*",
                "content-type": "application/json",
            }
    licenseincrease = {
        "totalLicenses":X
    }
    licenseincrease_json = json.dumps(licenseincrease)
    getlicense = s.patch("https://admin.microsoft.com/fd/commerceapi/my-org/subscriptions/ENTERSKUIDHERE", headers=patchheaders, data=licenseincrease_json)
    getlicense_json = getlicense.json()
    print(getlicense_json)
</code>```

However I was getting an error:

```<code>{Message: "There was an error processing the request.", StackTrace: "", ExceptionType: ""}
</code>```

Is there something I am missing to fix this issue? OR Is there a better method to use the commerce API using http requests?

NOTE: (This is setup as a question and answer. If you have a better method of doing this please leave an answer or comment below)

答:
To make a patch request with the commerce api (when logged into MS) you need to add the s.AjaxSessionKey to the request. After you add the key, it should return back the subscription json data where you can check the total license amount:

```<code>patchheaders = {
                "accept":"application/json, text/plain, */*",
                "content-type": "application/json",
                "ajaxsessionkey":s.cookies.get("s.AjaxSessionKey")
            }
</code>```

Body:
I currently use selenium to login to Microsoft admin center and increase or decrease an office subscription of my choosing; however I want to try and use just the http requests library that comes with python to make my request.

Why I am doing this - I can't use the partner api to increase license to due to specific circumstances. I have access to my client's MS admin account and want to use python to increase a license when creating a user using the MS graph.

What I tried -
I first tried to create http requests to login into MS....that didn't seem possible: Logging into Microsoft Online website programatically with C# & Difference between CSRF and X-CSRF-Token I tried but seems I need to find the xsrf token that gets generated when using the webpage normally.

So I decided to use selenium to login to MS, then figure out how to use the commerce API when you are logged into MS.

Here is my code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.actions import action_builder
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from auths.AA_auth import interm_auth, otpauth
from selenium.common import exceptions
import time

import requests
import json
def browser_options():
    options = Options()
    options.headless = True
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    browser_options.browser = webdriver.Chrome(options=options)
    return browser_options.browser

def mslogin(msdata):
    #Go to the specific subscription in question
    browser_options.browser.get("https://admin.microsoft.com/Adminportal/Home?#/subscriptions/webdirect/ENTERSKUIDHERE")

    #Enter email
    ms_username = browser_options.browser.find_element_by_css_selector('#i0116')
    ms_username.send_keys("ENTERADMINEMAIL")

    wait = WebDriverWait(browser_options.browser, 10)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#idSIButton9')))
    ms_usernameaccept = browser_options.browser.find_element_by_css_selector('#idSIButton9')
    ms_usernameaccept.send_keys(Keys.ENTER)

    #Enter password
    wait = WebDriverWait(browser_options.browser, 5)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#i0118')))
    ms_password = browser_options.browser.find_element_by_css_selector('#i0118')
    ms_password.send_keys("ENTERADMINPASSWORD")

    wait = WebDriverWait(browser_options.browser, 10)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#idSIButton9')))
    ms_passwordaccept = browser_options.browser.find_element_by_css_selector('#idSIButton9')
    ms_passwordaccept.send_keys(Keys.ENTER)

    #Getting past the reduced password inquiry webpage
    wait = WebDriverWait(browser_options.browser, 5)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#idBtn_Back')))
    reducedlogingcancel = browser_options.browser.find_element_by_css_selector('#idBtn_Back')
    reducedlogingcancel.send_keys(Keys.ENTER)
    time.sleep(1)

    #Get cookieinfo
    request_cookies_browser =  browser_options.browser.get_cookies()
    browser_options.browser.close()
    print(request_cookies_browser)

    s = requests.Session()
    for cookie in request_cookies_browser:
        s.cookies.set(cookie['name'], cookie['value'])

    X = ENTERNUMBERHERE

    patchheaders = {
                "accept":"application/json, text/plain, */*",
                "content-type": "application/json",
            }
    licenseincrease = {
        "totalLicenses":X
    }
    licenseincrease_json = json.dumps(licenseincrease)
    getlicense = s.patch("https://admin.microsoft.com/fd/commerceapi/my-org/subscriptions/ENTERSKUIDHERE", headers=patchheaders, data=licenseincrease_json)
    getlicense_json = getlicense.json()
    print(getlicense_json)

However I was getting an error:

{Message: "There was an error processing the request.", StackTrace: "", ExceptionType: ""}

Is there something I am missing to fix this issue? OR Is there a better method to use the commerce API using http requests?

NOTE: (This is setup as a question and answer. If you have a better method of doing this please leave an answer or comment below)

Body:
To make a patch request with the commerce api (when logged into MS) you need to add the s.AjaxSessionKey to the request. After you add the key, it should return back the subscription json data where you can check the total license amount:

patchheaders = {
                "accept":"application/json, text/plain, */*",
                "content-type": "application/json",
                "ajaxsessionkey":s.cookies.get("s.AjaxSessionKey")
            }


问:
Issues converting Hex to Short getting the wrong value
I have a function that converts 2 char values into an unsigned short:

```<code>unsigned short ToShort(char v1, char v2) {
    unsigned short s = ((v1 << 8) | v2);
    return s;
}
</code>```

It works most of the time, but occasionally I get a number that is not correct. As we can see, some of the numbers in my output file are around 65000 when they should be a low number. This happens for large numbers as well.

One the left, we have good output. On the right, I have my own output.

Both outputs use the same input. Bytes are read from a file and stored into an array of chars. This array contained short values. You can see the error when some of the values are put into a short.

答:
char gets a sign extension when OR'ed. Instead of v2 you could do:

```<code>(v2 & 0xFF)
</code>```

unsigned char would be feasible, too.

Body:
I have a function that converts 2 char values into an unsigned short:

unsigned short ToShort(char v1, char v2) {
    unsigned short s = ((v1 << 8) | v2);
    return s;
}

It works most of the time, but occasionally I get a number that is not correct. As we can see, some of the numbers in my output file are around 65000 when they should be a low number. This happens for large numbers as well.

One the left, we have good output. On the right, I have my own output.

Both outputs use the same input. Bytes are read from a file and stored into an array of chars. This array contained short values. You can see the error when some of the values are put into a short.

Body:
char gets a sign extension when OR'ed. Instead of v2 you could do:

(v2 & 0xFF)

unsigned char would be feasible, too.


问:
Send a GET Request to a Webstie which has domain HTTPS by using Winsock2
I'm trying to make a GET request to Webserver, I have been successful toward Websites having HTTP domain. The problem remaining is that I can't send a request successfully toward Websites having HTTPS domain.

I have to use Winsock in C++ to accomplish this assignment. This is my code that have been successful toward HTTP:

```<code>void GET_request(URL url)
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;
    struct hostent* localHost;
    string request_header;
    char* localIP;
    int find_index;
    url.URL_detach();

    //Create a Request Header.
    request_header = "GET "+ url.path + " HTTP/1.0\r\n";
    request_header += "Host: " + url.host + "\r\n";
    request_header += "Connection: close\r\n";
    request_header += "Cache-Control: max-age=0\r\n";
    request_header += "Upgrade-Insecure-Requests: 1\r\n";
    request_header += "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\r\n";
    request_header += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n";
    request_header += "Accept-Encoding: gzip, deflate\r\n";
    request_header += "\r\n";

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
    }

    Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    localHost = gethostbyname(url.host.c_str());
    localIP = inet_ntoa(*(struct in_addr *)*localHost->h_addr_list);        //Return IP of HOST
    SockAddr.sin_port = htons(80);                                          //PORT 80 (HTTP)
    SockAddr.sin_family = AF_INET;                                          // TCP/IP
    SockAddr.sin_addr.s_addr = inet_addr(localIP);

    if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0)
    {
        cout << "Could not connect to Server";
        system("pause");
    }

    send(Socket, request_header.c_str(), strlen(request_header.c_str()), 0);

    int nDataLength;
    while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            Response_Header += buffer[i];
            i += 1;
        }
        find_index = Response_Header.find("</html>");
    }
    Response_Header.erase(find_index + 7);
    closesocket(Socket);
    WSACleanup();

}
</code>```

答:
Jav HTTPS Networking: The Settlement

My whole purpose of learning HTTPS was to create a downloader to be used in my custom installer. All I will do is present my code for doing that; which includes my custom library. You can easily replace my custom library code with your own.

To get the job done I will be utilizing the OpenSSL SDK. This library abstracts away Linux/Win32 Sockets and the TLS Handshake and Certificate verification. Which means you don't need to study Brian Hall - Beej's Network Programming, or Anthony Jones - Network Programming For Windows. And you definitely don't need to pick up Joshua Jones - Implementing SSL_TLS.

You only need to study TutorialPoints.com tutorial on HTTP. I never ever could read off all of TutorialPoints.com tutorials. I simple look at the part about GET command and the five types of HTTP Server Resonse. POST command is sometimes required to download a file, but not in my case.

100:STATUS_PROCESSING

200:STATUS_OK

300:STATUS_REDIRECTED

400:STATUS_FAILED

500:STATUS_SERVER_ERROR

In the case of downloading a file, you are bound to get STATUS_REDIRECTED; as it seems servers give other dedicated servers the job of storing big files to be downloaded.

Final Note: This code makes use of GNU, Mingw extension. Namely the ability to copy the address of a goto label into a void pointer; This simplifies my conditional goto branching. You can use a flag instead. You can even eliminate goto and use your own mechanism. I used goto as it made the code easier to write.

Jav/file/buffer.h

```<code>#ifndef JAV_BUFFER_HPP
#define JAV_BUFFER_HPP

#include <Jav/bits.h> /* bitMove */

namespace Jav {

enum { KB=1024, MB=KB*1024, GB=MB*1024 };

/** Represents a chunk of data from a particular source. Eg: file, network
  *
  * Buffer is not meant to operate as dynamic memory,
  * that allocates and reallocates memory to constantly increase/ decrease capacity.
  * Consider using std::string for such purpose.
*/
struct Buffer
{
 uint8_t *begin; // begin of allocated memory
 uint8_t *pos;   // position in buffer
 uint8_t *end;   // end of data written to buffer
 uint8_t *max;   // end of allocated memory

 Buffer();
 explicit Buffer(std::size_t size);
 Buffer(std::size_t size,std::size_t max);
 Buffer(Buffer &&move);
 Buffer& operator= (Buffer &&move);
 ~Buffer();

 explicit operator bool()const { return begin; }
 bool isEmpty()const           { return begin == end; }
 std::size_t size()const       { return end - begin; }
 std::size_t unread()const     { return pos >= end ? 0 : end - pos; }
 std::size_t space()const      { return max - pos; }
 std::size_t freeSpace()const  { return max - end; }
 std::size_t capacity()const   { return max - begin; }
 void clear()                   { end = pos = begin; }
};

/** Represents a chunk of data from a particular source. Eg: file, network */
class FileBuffer
{
 public:
    FileBuffer();
    explicit FileBuffer(std::size_t size);
    FileBuffer(std::size_t size,std::size_t max);
    FileBuffer(FileBuffer &&move);
    FileBuffer& operator= (FileBuffer &&move);
    ~FileBuffer();

 public:
    explicit operator bool()const { return begin; }
    std::size_t size()const       { return end - begin; }
    std::size_t unread()const     { return pos >= end ? 0 : end - pos; }
    std::size_t space()const      { return max - pos; }
    std::size_t freeSpace()const  { return max - end; }
    std::size_t capacity()const   { return max - begin; }
    void clear()                    { end = pos = begin; }

 private:
    int64_t fpos;   // pos in file
    uint8_t *begin; // begin of allocated memory
    uint8_t *pos;   // position in buffer
    uint8_t *end;   // end of data written to buffer
    uint8_t *max;   // end of allocated memory

 private:
    friend class FileBase;
    friend class ReadableFile;
    friend class WritableFile;
};

/// Read From Buffer

void* read   (Buffer&, void *dest, size_t dest_size);
void* readBeg(Buffer&, void *dest, size_t dest_size);
void* read   (Buffer&, int offset, void *dest, size_t dest_size);
void* readBeg(Buffer&, int offset, void *dest, size_t dest_size);

/// Write Into Buffer

void write(Buffer&,const void *src,size_t);
void writeBeg(Buffer&,const void *src,size_t);
void writeEnd(Buffer&,const void *src,size_t);
void insert(Buffer&,const void *src,size_t);
void insertBeg(Buffer&,const void *src,size_t);

void write(Buffer&,int offset,const void *src,size_t);
void writeBeg(Buffer&,int offset,const void *src,size_t);
void writeEnd(Buffer&,int offset,const void *src,size_t);
void insert(Buffer&,int offset,const void *src,size_t);
void insertBeg(Buffer&,int offset,const void *src,size_t);

/// Data Management
void notifyDataWritten(Buffer&,std::size_t);
void notifyDataRead(Buffer&,std::size_t);
bool shiftBytes(Buffer&,byte *from,byte *to);

/// Size Management
void setCapacity(Buffer&,std::size_t);

#include "Buffer.inl"

}

#endif // JAV_BUFFER_HPP
</code>```

Jav/string/parser.h

```<code>#ifndef JAV_PARSER_HPP
#define JAV_PARSER_HPP

#include <Jav/string/cstring.h>
#include <Jav/error/error.h>
#include <string>
#include <stdio.h>

namespace Jav {

class Parser
{
 public:
    Parser(const char *bytes) : bytes(bytes) {}
    Parser(const Parser &parser) : bytes(parser.bytes) {}

 public:
    const char* skipSpaces(const char *it);
    const char* skipAllSpaces(const char *it);
    const char* nextLine(const char *it);
    ...

 public:
    const char* skipSpaces(const char *it, const char *end);
    const char* skipAllSpaces(const char *it, const char *end);
    const char* nextLine(const char *it, const char *end);
    ...

 protected:
    const char *bytes;
};
...

}

#endif // JAV_PARSER_HPP
</code>```

Net.h

```<code>#ifndef JAV_APP_NET_HPP
#define JAV_APP_NET_HPP

#include <Jav/string/parser.h>
#include <Jav/string/cstring.h>
#include <Jav/file/buffer.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>

enum { STATUS_UNKNOWN, STATUS_OK, STATUS_REDIRECT, STATUS_FAIL  };

struct Url
{
 Jav::cstring port;
 Jav::cstring host;
 Jav::cstring path;
};

bool parseUrl(Url&,const char *url);

struct Net
{
 public:
    Net(const char *url);
    Net(Net&&);
    Net& operator=(Net&&);
    ~Net();

 public:
    void requestFile();
    size_t recieveResponse(Jav::Buffer&);

 private:
    void on_openssl_fail(int line);

 private:
    Url url;
    SSL_CTX *ctx;
    BIO *web;
    SSL *ssl;
};

struct ServerResponseParser : Jav::Parser
{
    int status;
    size_t content_size;
    Jav::cstring content_url;
    Jav::cstring status_string;

    ServerResponseParser() : Jav::Parser(NULL) {}
    bool parse(Jav::Buffer &response,Net &store);

 protected:
    bool parseStatusLine(Jav::Buffer &response,Net &store);
    bool parseAttribute(Jav::Buffer &response,Net &store);
};

void init_openssl_library();

#endif
</code>```

Net.cpp

```<code>#include <Jav/error/error.h>
#include <Jav/string/compare.h>
#include <Jav/string/builder.h>
#include <Jav/string/charconv.h>
#include "Net.h"
#include <openssl/err.h>
extern "C" _CRTIMP int __cdecl __MINGW_NOTHROW  _fileno (FILE*);
#include <openssl/applink.c> //essential to avoid no applink runtime error

void init_openssl_library()
{
 SSL_library_init();
 SSL_load_error_strings();
 OPENSSL_config(NULL);
}

bool parseUrl(Url &obj,const char *url)
{
 const char *scheme, *scheme_end;
 const char *host, *host_end;
 const char *path;

 if(url == NULL)
    throw Jav::Error("url is null");

 scheme = url;
 scheme_end = Jav::nextPosOf("://",scheme);
 if(scheme_end == NULL) throw Jav::Error("Url Error: invalid scheme");

 host = scheme_end + 3;
 path = host_end = Jav::nextPos('/',host);

 // Erase port number from host name
 host_end = Jav::nextPosOf(':',{host,host_end});
 if(host_end == NULL) host_end = path;

 obj.port = Jav::cstring(scheme,scheme_end);
 obj.host = Jav::cstring(host,host_end);
 obj.path = path;

 return true;
}

Net::Net(const char *url)
{
    parseUrl(this->url,url);

    const SSL_METHOD *method = SSLv23_method();
    if(method == NULL) on_openssl_fail(__LINE__);

    ctx = SSL_CTX_new(method);
    if(ctx == NULL) on_openssl_fail(__LINE__);

    // Cannot fail???
    //SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,verify_callback);
    //SSL_CTX_set_verify_depth(ctx,4);

    const long flags = SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION;
    SSL_CTX_set_options(ctx,flags);

    web = BIO_new_ssl_connect(ctx);
    if(web == NULL) on_openssl_fail(__LINE__);

    auto hostName = Jav::buildString("?:?",this->url.host,this->url.port);
    if(BIO_set_conn_hostname(web,hostName.c_str()) != 1)
        on_openssl_fail(__LINE__);

    BIO_get_ssl(web,&ssl);
    if(ssl == NULL) on_openssl_fail(__LINE__);

    const char *PREFERRED_CIPHERS = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
    if(SSL_set_cipher_list(ssl,PREFERRED_CIPHERS) != 1)
        on_openssl_fail(__LINE__);

    if(SSL_set_tlsext_host_name(ssl,this->url.host) != 1)
        on_openssl_fail(__LINE__);

    //out = BIO_new_fp(stdout,BIO_NOCLOSE);
    //if(out == NULL) on_openssl_fail(__LINE__);

    if(BIO_do_connect(web) != 1) on_openssl_fail(__LINE__);
    if(BIO_do_handshake(web) != 1) on_openssl_fail(__LINE__);

    X509 *cert = SSL_get_peer_certificate(ssl);
    if(cert == NULL) on_openssl_fail(__LINE__);
    X509_free(cert);

    //How to get the following verify method to not fail
    //if(SSL_get_verify_result(ssl) != X509_V_OK) on_openssl_fail(__LINE__);
}

Net::Net(Net &&rhs)
 : ctx(Jav::bitMove<SSL_CTX>(&rhs.ctx)),
   ssl(Jav::bitMove<SSL>(&rhs.ssl)),
   web(Jav::bitMove<BIO>(&rhs.web)),
   url(rhs.url)
{
}

Net& Net::operator=(Net &&rhs)
{
 Jav::bitMove<SSL_CTX>(&ctx,&rhs.ctx);
 Jav::bitMove<SSL>(&ssl,&rhs.ssl);
 Jav::bitMove<BIO>(&web,&rhs.web);
 url = rhs.url;
 return *this;
}

Net::~Net()
{
    //SSL_free(ssl);
    SSL_CTX_free(ctx);
    //BIO_free(out);
    BIO_free(web);
}

void Net::requestFile()
{
    auto cmd = Jav::buildString(
                    "GET ? HTTP/1.1\r\n"
                    "Host: ?\r\n"
                    "Connection: close\r\n\r\n",
                    url.path, url.host
                );

    if(BIO_write(web, cmd.c_str(), cmd.size()) <= 0)
        on_openssl_fail(__LINE__);
}

size_t Net::recieveResponse(Jav::Buffer &buf)
{
    size_t numRead = BIO_read(web, buf.end, buf.freeSpace());
    if(numRead < 0) on_openssl_fail(__LINE__);

    buf.end += numRead;
    return numRead;
}

void Net::on_openssl_fail(int line)
{
 ERR_print_errors_fp(stderr);
 throw Jav::Error("problem at line %i\n",line);
}

bool ServerResponseParser::parseStatusLine(Jav::Buffer &response,Net &store)
{
    void *section = &&PARSE_HTTP_VERSION;

    if(response.unread() == 0) goto STORE;

    PARSE_HTTP_VERSION:
    {
     const char *begin = (char*)response.pos;
     const char *end = Jav::nextPosOf(' ',{begin,(char*)response.end});
     if(end == NULL) goto STORE;

     if( !Jav::isMatch({begin,end},"HTTP") )
        throw Jav::Error("Expected HTTP version in status line of Server response");

     response.pos = (uint8_t*)end+1;
     section = &&PARSE_STATUS_CODE;
    }

    PARSE_STATUS_CODE:
    {
     const char *begin = (char*)response.pos;
     const char *end = Jav::nextPosOf(' ',{begin,(char*)response.end});
     if(end == NULL) goto STORE;

     if(end - begin != 3) throw Jav::Error("status code requires 3 digits: %i",end-begin);

     status = begin[0] == '2' ? STATUS_OK :
              begin[0] == '3' ? STATUS_REDIRECT :
              begin[0] == '4' ? STATUS_FAIL :
                /** ELSE */  STATUS_UNKNOWN;

     if(!std::isdigit(begin[1]) || !std::isdigit(begin[2]))
        throw Jav::Error("status code should be a number");

     response.pos = (uint8_t*)end+1;
     section = &&PARSE_STATUS_STRING;
    }

    PARSE_STATUS_STRING:
    {
     const char *begin = (char*)response.pos;
     const char *end = Jav::nextPosOf("\r\n",{(char*)response.pos,(char*)response.end});
     if(end == NULL) goto STORE;

     status_string = Jav::cstring(begin,end);
     response.pos = (uint8_t*)end+1;
    }

    if(status == STATUS_FAIL)
        throw Jav::Error("Request Failed: %s",status_string.str());

    if(status == STATUS_UNKNOWN)
        throw Jav::Error("Unsupported status code");

    return true;

    STORE:
    {
     if(response.pos == response.begin && !response.isEmpty())
        throw Jav::Error("Failed to parse status line of server response");

     shiftBytes(response,response.pos,response.begin);
     response.pos = response.begin;
     store.recieveResponse(response);

     if(response.isEmpty())
        throw Jav::Error("Failed to parse status line of server response");

     goto *section;
    }
}

bool ServerResponseParser::parseAttribute(Jav::Buffer &response,Net &store)
{
    enum { VAR_LOCATION=1, VAR_CONTENT_LENGTH, VAR_CONTENT_TYPE };

    void *section = &&PARSE_VARIABLE;
    int var;

    PARSE_VARIABLE:
    {
        const char *begin = (char*)response.pos;
        const char *end = Jav::nextPosOf(':',{begin,(char*)response.end});
        if(end == NULL) goto STORE;

        if( Jav::isMatch({begin,end},"Content-Length") ) var = VAR_CONTENT_LENGTH;
        else if( Jav::isMatch({begin,end},"Content-Type") ) var = VAR_CONTENT_TYPE;
        else if( Jav::isMatch({begin,end},"Location") ) var = VAR_LOCATION;
        else                                         var = 0;

        response.pos = (uint8_t*)skipSpaces(end+1);
        section = &&PARSE_VALUE;
    }

    PARSE_VALUE:
    {
        const char *begin = (char*)response.pos;
        const char *end = Jav::nextPosOf("\r\n",{begin,(char*)response.end});
        if(end == NULL) goto STORE;

        switch(var)
        {
         case VAR_LOCATION:
            if(status == STATUS_REDIRECT) content_url = Jav::cstring(begin,end);
            break;

         case VAR_CONTENT_LENGTH:
            if(status == STATUS_OK)
            if(!Jav::ston(begin,end,content_size,Jav::STON_UINT_DEC))
                throw Jav::Error("Content-Length is not a number");
            break;

         case VAR_CONTENT_TYPE:
            if(var == STATUS_OK)
            if(!Jav::isMatch({begin,end},"application/"))
                throw Jav::Error("mime type Expected: application/*, Found: %s",Jav::cstring(begin,end).str());
        }

        response.pos = (uint8_t*)end+2;
        return true;
    }

    STORE:
    {
     if(response.pos == response.begin && !response.isEmpty())
        throw Jav::Error("Failed to parse attribute of server response");

     shiftBytes(response,response.pos,response.begin);
     response.pos = response.begin;
     store.recieveResponse(response);

     if(response.isEmpty())
        throw Jav::Error("Failed to parse attribute of server response");

     goto *section;
    }
}

bool ServerResponseParser::parse(Jav::Buffer &response,Net &store)
{
    parseStatusLine(response,store);

    PARSE_ATTRIBUTES:
    while(true)
    {
        if(response.unread() == 0) goto STORE;

        if(Jav::isMatch(response.pos,"\r\n"))
        {
         response.pos += 2;
         return true;
        }

        parseAttribute(response,store);
    }

    STORE:
    {
     if(response.pos == response.begin && !response.isEmpty())
        throw Jav::Error("Failed to parse server response");

     shiftBytes(response,response.pos,response.begin);
     response.pos = response.begin;
     store.recieveResponse(response);

     if(response.isEmpty())
        throw Jav::Error("Failed to parse server response");

     goto PARSE_ATTRIBUTES;
    }
}
</code>```

main.cpp

```<code>#include <Jav/error/error.h>
#include <Jav/console/screen.h>
#include <Jav/file/file.h>
#include "Net.h"

int main(int argc,const char **argv)
{
    Jav::Buffer buf(4096);

    init_openssl_library();
    Net net("https://www.apachefriends.org/xampp-files/7.4.27/xampp-windows-x64-7.4.27-2-VC15-installer.exe");
    net.requestFile();

    ServerResponseParser parser;
    parser.parse(buf,net);

    if(parser.status == STATUS_REDIRECT)
    {
     buf.clear();
     net = Net(parser.content_url);
     net.requestFile();
     parser.parse(buf,net);

     if(parser.status != STATUS_OK)
        throw Jav::Error("Server is playing games");
    }

    // How to deduce filename from the HTTP Server Response
    Jav::wFile file = Jav::createNewFile<Jav::wFile>("download.exe");

    Jav::ConsoleScreen screen = Jav::openTerminal<Jav::ConsoleScreen>();
    Jav::cstring progress(100);

    size_t totalWrit = 0;

    while(true)
    {
        if(buf.unread() == 0)
        {
         buf.clear();
         net.recieveResponse(buf);
         if(buf.isEmpty()) return 0;
        }

        size_t numWrit = file.write(buf.pos,buf.unread());
        totalWrit += numWrit;
        buf.pos += numWrit;

        Jav::Point screen_pos = getCursorPos(screen);
        Jav::Point screen_sz = getScreenSize(screen);

        auto sz = sprintf(progress,"%i/%i %i%%",totalWrit,parser.content_size,(int)(totalWrit*100.0/parser.content_size));
        memset(progress+sz,' ',screen_sz.x-sz);
        screen.write(progress,sz);
        setCursorPos(screen,0,screen_pos.y);
    }
}
</code>```

Body:
I'm trying to make a GET request to Webserver, I have been successful toward Websites having HTTP domain. The problem remaining is that I can't send a request successfully toward Websites having HTTPS domain.

I have to use Winsock in C++ to accomplish this assignment. This is my code that have been successful toward HTTP:

void GET_request(URL url)
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;
    struct hostent* localHost;
    string request_header;
    char* localIP;
    int find_index;
    url.URL_detach();

    //Create a Request Header.
    request_header = "GET "+ url.path + " HTTP/1.0\r\n";
    request_header += "Host: " + url.host + "\r\n";
    request_header += "Connection: close\r\n";
    request_header += "Cache-Control: max-age=0\r\n";
    request_header += "Upgrade-Insecure-Requests: 1\r\n";
    request_header += "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\r\n";
    request_header += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n";
    request_header += "Accept-Encoding: gzip, deflate\r\n";
    request_header += "\r\n";

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
    }

    Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    localHost = gethostbyname(url.host.c_str());
    localIP = inet_ntoa(*(struct in_addr *)*localHost->h_addr_list);        //Return IP of HOST
    SockAddr.sin_port = htons(80);                                          //PORT 80 (HTTP)
    SockAddr.sin_family = AF_INET;                                          // TCP/IP
    SockAddr.sin_addr.s_addr = inet_addr(localIP);

    if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0)
    {
        cout << "Could not connect to Server";
        system("pause");
    }

    send(Socket, request_header.c_str(), strlen(request_header.c_str()), 0);

    int nDataLength;
    while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            Response_Header += buffer[i];
            i += 1;
        }
        find_index = Response_Header.find("");
    }
    Response_Header.erase(find_index + 7);
    closesocket(Socket);
    WSACleanup();

}

Body:
Jav HTTPS Networking: The Settlement

My whole purpose of learning HTTPS was to create a downloader to be used in my custom installer. All I will do is present my code for doing that; which includes my custom library. You can easily replace my custom library code with your own.

To get the job done I will be utilizing the OpenSSL SDK. This library abstracts away Linux/Win32 Sockets and the TLS Handshake and Certificate verification. Which means you don't need to study Brian Hall - Beej's Network Programming, or Anthony Jones - Network Programming For Windows. And you definitely don't need to pick up Joshua Jones - Implementing SSL_TLS.

You only need to study TutorialPoints.com tutorial on HTTP. I never ever could read off all of TutorialPoints.com tutorials. I simple look at the part about GET command and the five types of HTTP Server Resonse. POST command is sometimes required to download a file, but not in my case.

100:STATUS_PROCESSING

200:STATUS_OK

300:STATUS_REDIRECTED

400:STATUS_FAILED

500:STATUS_SERVER_ERROR

In the case of downloading a file, you are bound to get STATUS_REDIRECTED; as it seems servers give other dedicated servers the job of storing big files to be downloaded.

Final Note: This code makes use of GNU, Mingw extension. Namely the ability to copy the address of a goto label into a void pointer; This simplifies my conditional goto branching. You can use a flag instead. You can even eliminate goto and use your own mechanism. I used goto as it made the code easier to write.

Jav/file/buffer.h

#ifndef JAV_BUFFER_HPP
#define JAV_BUFFER_HPP

#include <Jav/bits.h> /* bitMove */

namespace Jav {

enum { KB=1024, MB=KB*1024, GB=MB*1024 };

/** Represents a chunk of data from a particular source. Eg: file, network
  *
  * Buffer is not meant to operate as dynamic memory,
  * that allocates and reallocates memory to constantly increase/ decrease capacity.
  * Consider using std::string for such purpose.
*/
struct Buffer
{
 uint8_t *begin; // begin of allocated memory
 uint8_t *pos;   // position in buffer
 uint8_t *end;   // end of data written to buffer
 uint8_t *max;   // end of allocated memory

 Buffer();
 explicit Buffer(std::size_t size);
 Buffer(std::size_t size,std::size_t max);
 Buffer(Buffer &&move);
 Buffer& operator= (Buffer &&move);
 ~Buffer();

 explicit operator bool()const { return begin; }
 bool isEmpty()const           { return begin == end; }
 std::size_t size()const       { return end - begin; }
 std::size_t unread()const     { return pos >= end ? 0 : end - pos; }
 std::size_t space()const      { return max - pos; }
 std::size_t freeSpace()const  { return max - end; }
 std::size_t capacity()const   { return max - begin; }
 void clear()                   { end = pos = begin; }
};

/** Represents a chunk of data from a particular source. Eg: file, network */
class FileBuffer
{
 public:
    FileBuffer();
    explicit FileBuffer(std::size_t size);
    FileBuffer(std::size_t size,std::size_t max);
    FileBuffer(FileBuffer &&move);
    FileBuffer& operator= (FileBuffer &&move);
    ~FileBuffer();

 public:
    explicit operator bool()const { return begin; }
    std::size_t size()const       { return end - begin; }
    std::size_t unread()const     { return pos >= end ? 0 : end - pos; }
    std::size_t space()const      { return max - pos; }
    std::size_t freeSpace()const  { return max - end; }
    std::size_t capacity()const   { return max - begin; }
    void clear()                    { end = pos = begin; }

 private:
    int64_t fpos;   // pos in file
    uint8_t *begin; // begin of allocated memory
    uint8_t *pos;   // position in buffer
    uint8_t *end;   // end of data written to buffer
    uint8_t *max;   // end of allocated memory

 private:
    friend class FileBase;
    friend class ReadableFile;
    friend class WritableFile;
};

/// Read From Buffer

void* read   (Buffer&, void *dest, size_t dest_size);
void* readBeg(Buffer&, void *dest, size_t dest_size);
void* read   (Buffer&, int offset, void *dest, size_t dest_size);
void* readBeg(Buffer&, int offset, void *dest, size_t dest_size);

/// Write Into Buffer

void write(Buffer&,const void *src,size_t);
void writeBeg(Buffer&,const void *src,size_t);
void writeEnd(Buffer&,const void *src,size_t);
void insert(Buffer&,const void *src,size_t);
void insertBeg(Buffer&,const void *src,size_t);

void write(Buffer&,int offset,const void *src,size_t);
void writeBeg(Buffer&,int offset,const void *src,size_t);
void writeEnd(Buffer&,int offset,const void *src,size_t);
void insert(Buffer&,int offset,const void *src,size_t);
void insertBeg(Buffer&,int offset,const void *src,size_t);

/// Data Management
void notifyDataWritten(Buffer&,std::size_t);
void notifyDataRead(Buffer&,std::size_t);
bool shiftBytes(Buffer&,byte *from,byte *to);

/// Size Management
void setCapacity(Buffer&,std::size_t);

#include "Buffer.inl"

}

#endif // JAV_BUFFER_HPP

Jav/string/parser.h

#ifndef JAV_PARSER_HPP
#define JAV_PARSER_HPP

#include <Jav/string/cstring.h>
#include <Jav/error/error.h>
#include <string>
#include <stdio.h>

namespace Jav {

class Parser
{
 public:
    Parser(const char *bytes) : bytes(bytes) {}
    Parser(const Parser &parser) : bytes(parser.bytes) {}

 public:
    const char* skipSpaces(const char *it);
    const char* skipAllSpaces(const char *it);
    const char* nextLine(const char *it);
    ...

 public:
    const char* skipSpaces(const char *it, const char *end);
    const char* skipAllSpaces(const char *it, const char *end);
    const char* nextLine(const char *it, const char *end);
    ...

 protected:
    const char *bytes;
};
...

}

#endif // JAV_PARSER_HPP

Net.h

#ifndef JAV_APP_NET_HPP
#define JAV_APP_NET_HPP

#include <Jav/string/parser.h>
#include <Jav/string/cstring.h>
#include <Jav/file/buffer.h>
#include <openssl/bio.h>
#include <openssl/ssl.h>

enum { STATUS_UNKNOWN, STATUS_OK, STATUS_REDIRECT, STATUS_FAIL  };

struct Url
{
 Jav::cstring port;
 Jav::cstring host;
 Jav::cstring path;
};

bool parseUrl(Url&,const char *url);

struct Net
{
 public:
    Net(const char *url);
    Net(Net&&);
    Net& operator=(Net&&);
    ~Net();

 public:
    void requestFile();
    size_t recieveResponse(Jav::Buffer&);

 private:
    void on_openssl_fail(int line);

 private:
    Url url;
    SSL_CTX *ctx;
    BIO *web;
    SSL *ssl;
};

struct ServerResponseParser : Jav::Parser
{
    int status;
    size_t content_size;
    Jav::cstring content_url;
    Jav::cstring status_string;

    ServerResponseParser() : Jav::Parser(NULL) {}
    bool parse(Jav::Buffer &response,Net &store);

 protected:
    bool parseStatusLine(Jav::Buffer &response,Net &store);
    bool parseAttribute(Jav::Buffer &response,Net &store);
};

void init_openssl_library();

#endif

Net.cpp

#include <Jav/error/error.h>
#include <Jav/string/compare.h>
#include <Jav/string/builder.h>
#include <Jav/string/charconv.h>
#include "Net.h"
#include <openssl/err.h>
extern "C" _CRTIMP int __cdecl __MINGW_NOTHROW  _fileno (FILE*);
#include <openssl/applink.c> //essential to avoid no applink runtime error

void init_openssl_library()
{
 SSL_library_init();
 SSL_load_error_strings();
 OPENSSL_config(NULL);
}

bool parseUrl(Url &obj,const char *url)
{
 const char *scheme, *scheme_end;
 const char *host, *host_end;
 const char *path;

 if(url == NULL)
    throw Jav::Error("url is null");

 scheme = url;
 scheme_end = Jav::nextPosOf("://",scheme);
 if(scheme_end == NULL) throw Jav::Error("Url Error: invalid scheme");

 host = scheme_end + 3;
 path = host_end = Jav::nextPos('/',host);

 // Erase port number from host name
 host_end = Jav::nextPosOf(':',{host,host_end});
 if(host_end == NULL) host_end = path;

 obj.port = Jav::cstring(scheme,scheme_end);
 obj.host = Jav::cstring(host,host_end);
 obj.path = path;

 return true;
}

Net::Net(const char *url)
{
    parseUrl(this->url,url);

    const SSL_METHOD *method = SSLv23_method();
    if(method == NULL) on_openssl_fail(__LINE__);

    ctx = SSL_CTX_new(method);
    if(ctx == NULL) on_openssl_fail(__LINE__);

    // Cannot fail???
    //SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,verify_callback);
    //SSL_CTX_set_verify_depth(ctx,4);

    const long flags = SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION;
    SSL_CTX_set_options(ctx,flags);

    web = BIO_new_ssl_connect(ctx);
    if(web == NULL) on_openssl_fail(__LINE__);

    auto hostName = Jav::buildString("?:?",this->url.host,this->url.port);
    if(BIO_set_conn_hostname(web,hostName.c_str()) != 1)
        on_openssl_fail(__LINE__);

    BIO_get_ssl(web,&ssl);
    if(ssl == NULL) on_openssl_fail(__LINE__);

    const char *PREFERRED_CIPHERS = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
    if(SSL_set_cipher_list(ssl,PREFERRED_CIPHERS) != 1)
        on_openssl_fail(__LINE__);

    if(SSL_set_tlsext_host_name(ssl,this->url.host) != 1)
        on_openssl_fail(__LINE__);

    //out = BIO_new_fp(stdout,BIO_NOCLOSE);
    //if(out == NULL) on_openssl_fail(__LINE__);

    if(BIO_do_connect(web) != 1) on_openssl_fail(__LINE__);
    if(BIO_do_handshake(web) != 1) on_openssl_fail(__LINE__);

    X509 *cert = SSL_get_peer_certificate(ssl);
    if(cert == NULL) on_openssl_fail(__LINE__);
    X509_free(cert);

    //How to get the following verify method to not fail
    //if(SSL_get_verify_result(ssl) != X509_V_OK) on_openssl_fail(__LINE__);
}

Net::Net(Net &&rhs)
 : ctx(Jav::bitMove<SSL_CTX>(&rhs.ctx)),
   ssl(Jav::bitMove<SSL>(&rhs.ssl)),
   web(Jav::bitMove<BIO>(&rhs.web)),
   url(rhs.url)
{
}

Net& Net::operator=(Net &&rhs)
{
 Jav::bitMove<SSL_CTX>(&ctx,&rhs.ctx);
 Jav::bitMove<SSL>(&ssl,&rhs.ssl);
 Jav::bitMove<BIO>(&web,&rhs.web);
 url = rhs.url;
 return *this;
}

Net::~Net()
{
    //SSL_free(ssl);
    SSL_CTX_free(ctx);
    //BIO_free(out);
    BIO_free(web);
}

void Net::requestFile()
{
    auto cmd = Jav::buildString(
                    "GET ? HTTP/1.1\r\n"
                    "Host: ?\r\n"
                    "Connection: close\r\n\r\n",
                    url.path, url.host
                );

    if(BIO_write(web, cmd.c_str(), cmd.size()) <= 0)
        on_openssl_fail(__LINE__);
}

size_t Net::recieveResponse(Jav::Buffer &buf)
{
    size_t numRead = BIO_read(web, buf.end, buf.freeSpace());
    if(numRead < 0) on_openssl_fail(__LINE__);

    buf.end += numRead;
    return numRead;
}

void Net::on_openssl_fail(int line)
{
 ERR_print_errors_fp(stderr);
 throw Jav::Error("problem at line %i\n",line);
}

bool ServerResponseParser::parseStatusLine(Jav::Buffer &response,Net &store)
{
    void *section = &&PARSE_HTTP_VERSION;

    if(response.unread() == 0) goto STORE;

    PARSE_HTTP_VERSION:
    {
     const char *begin = (char*)response.pos;
     const char *end = Jav::nextPosOf(' ',{begin,(char*)response.end});
     if(end == NULL) goto STORE;

     if( !Jav::isMatch({begin,end},"HTTP") )
        throw Jav::Error("Expected HTTP version in status line of Server response");

     response.pos = (uint8_t*)end+1;
     section = &&PARSE_STATUS_CODE;
    }

    PARSE_STATUS_CODE:
    {
     const char *begin = (char*)response.pos;
     const char *end = Jav::nextPosOf(' ',{begin,(char*)response.end});
     if(end == NULL) goto STORE;

     if(end - begin != 3) throw Jav::Error("status code requires 3 digits: %i",end-begin);

     status = begin[0] == '2' ? STATUS_OK :
              begin[0] == '3' ? STATUS_REDIRECT :
              begin[0] == '4' ? STATUS_FAIL :
                /** ELSE */  STATUS_UNKNOWN;

     if(!std::isdigit(begin[1]) || !std::isdigit(begin[2]))
        throw Jav::Error("status code should be a number");

     response.pos = (uint8_t*)end+1;
     section = &&PARSE_STATUS_STRING;
    }

    PARSE_STATUS_STRING:
    {
     const char *begin = (char*)response.pos;
     const char *end = Jav::nextPosOf("\r\n",{(char*)response.pos,(char*)response.end});
     if(end == NULL) goto STORE;

     status_string = Jav::cstring(begin,end);
     response.pos = (uint8_t*)end+1;
    }

    if(status == STATUS_FAIL)
        throw Jav::Error("Request Failed: %s",status_string.str());

    if(status == STATUS_UNKNOWN)
        throw Jav::Error("Unsupported status code");

    return true;

    STORE:
    {
     if(response.pos == response.begin && !response.isEmpty())
        throw Jav::Error("Failed to parse status line of server response");

     shiftBytes(response,response.pos,response.begin);
     response.pos = response.begin;
     store.recieveResponse(response);

     if(response.isEmpty())
        throw Jav::Error("Failed to parse status line of server response");

     goto *section;
    }
}

bool ServerResponseParser::parseAttribute(Jav::Buffer &response,Net &store)
{
    enum { VAR_LOCATION=1, VAR_CONTENT_LENGTH, VAR_CONTENT_TYPE };

    void *section = &&PARSE_VARIABLE;
    int var;

    PARSE_VARIABLE:
    {
        const char *begin = (char*)response.pos;
        const char *end = Jav::nextPosOf(':',{begin,(char*)response.end});
        if(end == NULL) goto STORE;

        if( Jav::isMatch({begin,end},"Content-Length") ) var = VAR_CONTENT_LENGTH;
        else if( Jav::isMatch({begin,end},"Content-Type") ) var = VAR_CONTENT_TYPE;
        else if( Jav::isMatch({begin,end},"Location") ) var = VAR_LOCATION;
        else                                         var = 0;

        response.pos = (uint8_t*)skipSpaces(end+1);
        section = &&PARSE_VALUE;
    }

    PARSE_VALUE:
    {
        const char *begin = (char*)response.pos;
        const char *end = Jav::nextPosOf("\r\n",{begin,(char*)response.end});
        if(end == NULL) goto STORE;

        switch(var)
        {
         case VAR_LOCATION:
            if(status == STATUS_REDIRECT) content_url = Jav::cstring(begin,end);
            break;

         case VAR_CONTENT_LENGTH:
            if(status == STATUS_OK)
            if(!Jav::ston(begin,end,content_size,Jav::STON_UINT_DEC))
                throw Jav::Error("Content-Length is not a number");
            break;

         case VAR_CONTENT_TYPE:
            if(var == STATUS_OK)
            if(!Jav::isMatch({begin,end},"application/"))
                throw Jav::Error("mime type Expected: application/*, Found: %s",Jav::cstring(begin,end).str());
        }

        response.pos = (uint8_t*)end+2;
        return true;
    }

    STORE:
    {
     if(response.pos == response.begin && !response.isEmpty())
        throw Jav::Error("Failed to parse attribute of server response");

     shiftBytes(response,response.pos,response.begin);
     response.pos = response.begin;
     store.recieveResponse(response);

     if(response.isEmpty())
        throw Jav::Error("Failed to parse attribute of server response");

     goto *section;
    }
}

bool ServerResponseParser::parse(Jav::Buffer &response,Net &store)
{
    parseStatusLine(response,store);

    PARSE_ATTRIBUTES:
    while(true)
    {
        if(response.unread() == 0) goto STORE;

        if(Jav::isMatch(response.pos,"\r\n"))
        {
         response.pos += 2;
         return true;
        }

        parseAttribute(response,store);
    }

    STORE:
    {
     if(response.pos == response.begin && !response.isEmpty())
        throw Jav::Error("Failed to parse server response");

     shiftBytes(response,response.pos,response.begin);
     response.pos = response.begin;
     store.recieveResponse(response);

     if(response.isEmpty())
        throw Jav::Error("Failed to parse server response");

     goto PARSE_ATTRIBUTES;
    }
}

main.cpp

#include <Jav/error/error.h>
#include <Jav/console/screen.h>
#include <Jav/file/file.h>
#include "Net.h"

int main(int argc,const char **argv)
{
    Jav::Buffer buf(4096);

    init_openssl_library();
    Net net("https://www.apachefriends.org/xampp-files/7.4.27/xampp-windows-x64-7.4.27-2-VC15-installer.exe");
    net.requestFile();

    ServerResponseParser parser;
    parser.parse(buf,net);

    if(parser.status == STATUS_REDIRECT)
    {
     buf.clear();
     net = Net(parser.content_url);
     net.requestFile();
     parser.parse(buf,net);

     if(parser.status != STATUS_OK)
        throw Jav::Error("Server is playing games");
    }

    // How to deduce filename from the HTTP Server Response
    Jav::wFile file = Jav::createNewFile<Jav::wFile>("download.exe");

    Jav::ConsoleScreen screen = Jav::openTerminal<Jav::ConsoleScreen>();
    Jav::cstring progress(100);

    size_t totalWrit = 0;

    while(true)
    {
        if(buf.unread() == 0)
        {
         buf.clear();
         net.recieveResponse(buf);
         if(buf.isEmpty()) return 0;
        }

        size_t numWrit = file.write(buf.pos,buf.unread());
        totalWrit += numWrit;
        buf.pos += numWrit;

        Jav::Point screen_pos = getCursorPos(screen);
        Jav::Point screen_sz = getScreenSize(screen);

        auto sz = sprintf(progress,"%i/%i %i%%",totalWrit,parser.content_size,(int)(totalWrit*100.0/parser.content_size));
        memset(progress+sz,' ',screen_sz.x-sz);
        screen.write(progress,sz);
        setCursorPos(screen,0,screen_pos.y);
    }
}


问:
ActionLink called only once in IE
I have an MVC blog app that makes a call to Ajax for updating a flag.

In IE (and only in IE, in other browsers it runs fine), I can call an ActionLink only once. If I click after the first time, the ajax action in the controller is not invoked.

Here is the partial part of code of the View:

```<code><div id="news_comment_state_@(Model.Id)">@(Model.FlControlled==false?"Da approvare":@Model.FlApproved?"Approvato":"Respinto")</div>
    @Ajax.ActionLink("Approva", "ApproveDenyComment", new { IdComment = Model.Id, ApproveDeny = true }, new AjaxOptions { UpdateTargetId = "news_comment_state_"+@Model.Id})
    <br />
    @Ajax.ActionLink("Respingi", "ApproveDenyComment", new { IdComment = Model.Id, ApproveDeny = false }, new AjaxOptions { UpdateTargetId = "news_comment_state_"+@Model.Id})
</code>```

If I put a breakpoint in the controller it is fired only once per Link, then it is never called again. Where is the error? Maybe cache problem?

答: Sounds like cache. Add a random integer to the end to make sure you get a fresh request.</p>

Title: ActionLink called only once in IE

Body:
I have an MVC blog app that makes a call to Ajax for updating a flag.

In IE (and only in IE, in other browsers it runs fine), I can call an ActionLink only once. If I click after the first time, the ajax action in the controller is not invoked.

Here is the partial part of code of the View:

@(Model.FlControlled==false?"Da approvare":@Model.FlApproved?"Approvato":"Respinto")

    @Ajax.ActionLink("Approva", "ApproveDenyComment", new { IdComment = Model.Id, ApproveDeny = true }, new AjaxOptions { UpdateTargetId = "news_comment_state_"+@Model.Id})

    @Ajax.ActionLink("Respingi", "ApproveDenyComment", new { IdComment = Model.Id, ApproveDeny = false }, new AjaxOptions { UpdateTargetId = "news_comment_state_"+@Model.Id})

If I put a breakpoint in the controller it is fired only once per Link, then it is never called again. Where is the error? Maybe cache problem?


问:
How to retrieve all localStorage items without knowing the keys in advance?
I want to show all of the keys and storage written before.
My code is below. I created a function (allStorage) but it doesn't work.
How can I do this? </p>

```<code>    function storeUserScribble(id) {
        var scribble = document.getElementById('scribble').innerHTML;
        localStorage.setItem('userScribble',scribble);
    }

    function getUserScribble() {
        if ( localStorage.getItem('userScribble')) {
            var scribble = localStorage.getItem('userScribble');
        }
        else {
            var scribble = 'You can scribble directly on this sticky... and I will also remember your message the next time you visit my blog!';
        }
        document.getElementById('scribble').innerHTML = scribble;
    }

    function clearLocal() {
        localStorage.clear();
        return false;
    }

    function allStorage() {
        var archive = [];
        for (var i = 0; i<localStorage.length; i++) {
            archive[i] = localStorage.getItem(localStorage.key(i));
        }
    }
</code>```

答:
To get all of the "localStorage", copy it and set the localStorage where you want

```<code>let localstorage= {...localStorage}
let content = 'localStorage.clear()

$.each(localstorage,(i,e)=> {
   content+=`localStorage.setItem('${i}','${e}');`})
copy(content)
</code>```

Body:
I want to show all of the keys and storage written before.
My code is below. I created a function (allStorage) but it doesn't work.
How can I do this?

    function storeUserScribble(id) {
        var scribble = document.getElementById('scribble').innerHTML;
        localStorage.setItem('userScribble',scribble);
    }

    function getUserScribble() {
        if ( localStorage.getItem('userScribble')) {
            var scribble = localStorage.getItem('userScribble');
        }
        else {
            var scribble = 'You can scribble directly on this sticky... and I will also remember your message the next time you visit my blog!';
        }
        document.getElementById('scribble').innerHTML = scribble;
    }

    function clearLocal() {
        localStorage.clear();
        return false;
    }

    function allStorage() {
        var archive = [];
        for (var i = 0; i<localStorage.length; i++) {
            archive[i] = localStorage.getItem(localStorage.key(i));
        }
    }

Body:
To get all of the "localStorage", copy it and set the localStorage where you want

let localstorage= {...localStorage}
let content = 'localStorage.clear()

$.each(localstorage,(i,e)=> {
   content+=`localStorage.setItem('${i}','${e}');`})
copy(content)


问:
Automated way of deleting millions of rows from Postgres tables
Postgres Version: PostgreSQL 10.9 (Ubuntu 10.9-1.pgdg16.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609, 64-bit

Before I ask my question, I would like to explain why I'm looking into this. we have a history table which has more than 5 million rows and growing every hour.

As the table length grows the select queries are becoming slower, even though we have a proper index. So ideally the first choice for us to delete the old records which are unused.

Approach #1

We tried deleting the records from the table using simple delete from table_name where created_date > certain_date where is_active = false

This took a very long time.

Approach #2

Create a script which would delete the rows with the cursor-based approach.

This also takes a very long time.

Approach #3

Created a new unlogged table.

Create an index on the new_table.

Copy the contents from the old table to a new table

Then set table is logged.

Rename the master table as a backup.

Issues with this approach, it requires some downtime.

On live productions instances, this would result in missing data / resulting in failures

Approach #4

On further investigation, the performant way to delete unused rows is if we create a table with partition https://www.postgresql.org/docs/10/ddl-partitioning.html - Which we could drop the entire partition immediately.

Questions with the above approach are

How can I create a partition on the existing table?

Will that require downtime?

How can we configure Postgres to create partition automatically, we can't really create partitions manually everyday right?

Any other approaches are also welcome, the thing is I really want this to be automated than manual because I would extend this to multiple tables.

Please let me know your thoughts, which would very helpful

答:
Answering specifically to  the below:

How can we configure Postgres to create partition automatically, we can't really create partitions manually everyday right?

As you are using Postgres 10, you could use https://github.com/pgpartman/pg_partman for auto management of partitions.


问:
Attempt to call a nil value when changing an IntValue for leaderstats
I'm trying to make an admin panel, everytime I want to change the value with a username
Code:

leaderstats Script;

--// Set up folder

local AdminModule = require(game:GetService('ServerScriptService').leaderstats.MainModule)
game.Players.PlayerAdded:Connect(function(plr)
    local leaderstats = Instance.new('Folder', plr)
    leaderstats.Name = 'leaderstats'

    local Playtime = Instance.new('IntValue', leaderstats)

    Playtime.Name = 'Playtime'
end)

AdminModule.GivePoints('happy_speler', 500)
```
<p>MainModule:</p>
<pre class="lang-lua prettyprint-override"><code>local module = {
    GivePoints = function(plr, amount)
        plr:WaitForChild('leaderstats'):WaitForChild('Playtime').Value = amount
    end,

}

return module
</code>```

答:
The error is telling you that you have tried to call a function that doesn't exist.

Looking at the AdminModule.GivePoints function, it looks like it expects a Player object for the plr argument, but you have passed in a string. The string library does not have a WaitForChild function, so calling plr:WaitForChild is throwing the error.

The way to fix this is to properly pass in a Player object :

```<code>local Players = game:GetService("Players")
local ServerScriptService = game:GetService("ServerScriptService")
local AdminModule = require(ServerScriptService.leaderstats.MainModule)

Players.PlayerAdded:Connect( function(plr)
    local leaderstats = Instance.new('Folder', plr)
    leaderstats.Name = 'leaderstats'

    local Playtime = Instance.new('IntValue', leaderstats)
    Playtime.Name = 'Playtime'

    if plr.Name == 'happy_speler' then
        AdminModule.GivePoints(plr, 500)
    end
end)
</code>```

Body:
I'm trying to make an admin panel, everytime I want to change the value with a username
Code:

leaderstats Script;

--// Set up folder

local AdminModule = require(game:GetService('ServerScriptService').leaderstats.MainModule)
game.Players.PlayerAdded:Connect(function(plr)
    local leaderstats = Instance.new('Folder', plr)
    leaderstats.Name = 'leaderstats'

    local Playtime = Instance.new('IntValue', leaderstats)

    Playtime.Name = 'Playtime'
end)

AdminModule.GivePoints('happy_speler', 500)

MainModule:

local module = {
    GivePoints = function(plr, amount)
        plr:WaitForChild('leaderstats'):WaitForChild('Playtime').Value = amount
    end,

}

return module

Body:
The error is telling you that you have tried to call a function that doesn't exist.

Looking at the AdminModule.GivePoints function, it looks like it expects a Player object for the plr argument, but you have passed in a string. The string library does not have a WaitForChild function, so calling plr:WaitForChild is throwing the error.

The way to fix this is to properly pass in a Player object :

local Players = game:GetService("Players")
local ServerScriptService = game:GetService("ServerScriptService")
local AdminModule = require(ServerScriptService.leaderstats.MainModule)

Players.PlayerAdded:Connect( function(plr)
    local leaderstats = Instance.new('Folder', plr)
    leaderstats.Name = 'leaderstats'

    local Playtime = Instance.new('IntValue', leaderstats)
    Playtime.Name = 'Playtime'

    if plr.Name == 'happy_speler' then
        AdminModule.GivePoints(plr, 500)
    end
end)


问:
[JavaScript]Add elements to a global array in a function and keep them

window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);```

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

答:
Let's focus on why the console.log in the end is empty.

Note that :

window. onload() is invoked when all resources (the document, objects,
images, css, etc) have finished rendering.

So after the console output the list value, if will execute the func1 and assign the value to list, but before that list is just an empty array.

If could see the following snippet, if you put the console to the window.onload function, it works as epected.

You could use push to add item to array and use index to access a specific element.

window.onload = function(){
    func1();
    console.log(list);
    func2()
    console.log(list)
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}
console.log(list);
function func2(){
list[0] =9999

}```

Body:
window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?


问:
Twitter Search Data for a keywrod
I'm new to the twitter api and doing an academic project for behavior
analysis for specific set of tweets. I'm interested in getting the
past data for a particular search query ( combination of keywords and
certain constraints ) for a period of at least 2 month and if possible
further.
The Search API lets us retrieve only 1500 tweets. Is that correct?
What can be the possible methods/or already implemented code to
download such a dataset?

I'm sorry if it doesnt look like a coding problem but I'm unable to find any comprehensive resource on web.

答:
you can archive them by yourself:

http://www.readwriteweb.com/archives/10_ways_to_archive_your_tweets.php

or you could make simple script which does the same

and in no-time you will have yourself 20 days worth of tweets.

Title: Twitter Search Data for a keywrod


问:
Average of predictions from many models versus prediction from the best fitted model?
I have a dataset containing about 700 data points. I randomly shuffle the dataset, then split the dataset in 80:20 ratio for training and testing. Then I use Gaussian process regression (GPR) for fitting the training dataset.

I repeated this process 6 times, and each time I get a new model with varying R2 between 0.50 to 0.80. Now which model should I use for further predictions? Should I take an average of predictions from all the six models, or just choose the best fitted model? If I chose the best fitted model, will there be concern for reproducibility? If there is any other better approach for the fitting, please let me know. Thanks.

答: You can try a Gaussian mixture model that combines all your GP models and gives you a probability distribution over all your results. Also, you can provide different weights for each GP model you have when forming a Gaussian mixture. The weights could be your R2 for example.</p>