问:
Injected IPrincipal Claims empty after adding Claims Transformer
I'm attempting to use Claims based authorization using Windows Authentication in ASP.NET Core. I have a Claims Transformer that sets user Claims. I also inject IPrincipal into by DbContext so I can access the current user when SaveChanges() is called to log who updated entities.

In Startup.cs:

```<code>    services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>()?.HttpContext?.User);
    services.AddTransient<IClaimsTransformation, MyClaimsTransformer>();
</code>```

In MyDbContext.cs:

```<code>    protected readonly IPrincipal _principal ;

    public MyDbContext(DbContextOptions<MyDbContext> options, IPrincipal principal) : base(options)
    {
        _principal = principal;
    }

    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        // Do something with Claim value...
        await base.SaveChangesAsync(cancellationToken);
    }
</code>```

I've added a Claims Transformer to add some Claim info:

```<code>    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        // Add Claims...
        return principal;
    }
</code>```

SaveChangesAsync is called in User Middleware to log the access to the application. Before adding the Claims Transformer, the IPrincipal injected into the DbContext was a WindowsPrincipal, and it contained the Claims I needed such as PrimarySid, etc. Now after adding the transformation, it is a ClaimsPrincipal however the list of Claims is now empty.

Through debugging I can verify that TransformAsync executes before SaveChangesAsync, but the constructor injection in the db context occurs before the transformation (The DbContext is a Scoped service, the Claims Transfomer is Transient).

Summary:

Before adding the Claims Transformer, the injected IPrincipal is a WindowsPrincipal with a populated list of Claims.

After adding the Claims Transformer, the injected IPrincipal is a ClaimsPrincipal with an empty list of Claims.

答:
I had the exact same issue when trying to inject the IPrincipal through the DbContext constructor. I have found that the IPrincipal that was injected in the DbContext was not yet "Transformed" by the ClaimsTransformer.

I have worked around this problem by creating a UserResolverService.

IUserResolverService.cs

```<code>public interface IUserResolverService
{
    IPrincipal GetUser();
}
</code>```

UserResolverService.cs

```<code>public class UserResolverService : IUserResolverService
{
    private readonly IHttpContextAccessor _context;

    public UserResolverService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public IPrincipal GetUser()
    {
        return _context.HttpContext.User;
    }
}
</code>```

MyDbContext.cs

```<code>private readonly IUserResolverService _userResolverService;

// Call this whenever you need the IPrincipal object
public IPrincipal User => _userResolverService.GetUser();

public MyDbContext(IUserResolverService userResolverService, DbContextOptions<MyDbContext> options)
        : base(options)
{
    _userResolverService = userResolverService;
}
</code>```

Startup.cs

```<code>services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
services.AddTransient<IUserResolverService, UserResolverService>();
</code>```

Body:
I'm attempting to use Claims based authorization using Windows Authentication in ASP.NET Core. I have a Claims Transformer that sets user Claims. I also inject IPrincipal into by DbContext so I can access the current user when SaveChanges() is called to log who updated entities.

In Startup.cs:

    services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>()?.HttpContext?.User);
    services.AddTransient<IClaimsTransformation, MyClaimsTransformer>();

In MyDbContext.cs:

    protected readonly IPrincipal _principal ;

    public MyDbContext(DbContextOptions<MyDbContext> options, IPrincipal principal) : base(options)
    {
        _principal = principal;
    }

    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        // Do something with Claim value...
        await base.SaveChangesAsync(cancellationToken);
    }

I've added a Claims Transformer to add some Claim info:

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        // Add Claims...
        return principal;
    }

SaveChangesAsync is called in User Middleware to log the access to the application. Before adding the Claims Transformer, the IPrincipal injected into the DbContext was a WindowsPrincipal, and it contained the Claims I needed such as PrimarySid, etc. Now after adding the transformation, it is a ClaimsPrincipal however the list of Claims is now empty.

Through debugging I can verify that TransformAsync executes before SaveChangesAsync, but the constructor injection in the db context occurs before the transformation (The DbContext is a Scoped service, the Claims Transfomer is Transient).

Summary:

Before adding the Claims Transformer, the injected IPrincipal is a WindowsPrincipal with a populated list of Claims.

After adding the Claims Transformer, the injected IPrincipal is a ClaimsPrincipal with an empty list of Claims.

Body:
I had the exact same issue when trying to inject the IPrincipal through the DbContext constructor. I have found that the IPrincipal that was injected in the DbContext was not yet "Transformed" by the ClaimsTransformer.

I have worked around this problem by creating a UserResolverService.

IUserResolverService.cs

public interface IUserResolverService
{
    IPrincipal GetUser();
}

UserResolverService.cs

public class UserResolverService : IUserResolverService
{
    private readonly IHttpContextAccessor _context;

    public UserResolverService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public IPrincipal GetUser()
    {
        return _context.HttpContext.User;
    }
}

MyDbContext.cs

private readonly IUserResolverService _userResolverService;

// Call this whenever you need the IPrincipal object
public IPrincipal User => _userResolverService.GetUser();

public MyDbContext(IUserResolverService userResolverService, DbContextOptions<MyDbContext> options)
        : base(options)
{
    _userResolverService = userResolverService;
}

Startup.cs

services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
services.AddTransient<IUserResolverService, UserResolverService>();


来源: stackexchange

问:
Trouble Shooting Event on Resize Not Firing
I am using the technique at this link to equalize the height of bootstrap carousel slides, so in the case of an uneven amount of text the slides do not cause the elements below them to bump up and down when advancing slides:

https://snook.ca/archives/javascript/normalize-bootstrap-carousel-heights

function normalizeSlideHeights() {
  $('.carousel').each(function() {
    var items = $('.carousel-item', this);
    items.css('min-height', 0);
    var maxHeight = Math.max.apply(null, items.map(function() {
      return $(this).outerHeight()
    }).get());
    items.css('min-height', maxHeight + 'px');
  })
}

$(window).on('load resize orientationchange', normalizeSlideHeights);
```

The first part of the code works great, all my carousel slides are the same height. The second part where it is looking for changes to the window size to re-adjust the slide height doesn't seem to work at all. I tried editing the original code to just check for 'resize' to simplify it but did not see any difference.

Any insights or ideas to a solution are greatly appreciated, thank you!

答:
Try plain JavaScript. If something in jQuery isn't working for me, I always try plain JavaScript. An example is below:

```<code>window.onresize = function(){normalizeSlideHeights()}
window.onload = function(){normalizeSlideHeights()}
</code>```

This WILL trigger the normalizeSlideHeights() function on resize and load, if the function exists. If this does not work correctly, then the issue is with the function itself.
You could also put some consoleLog() commands to see wether the function actually fires at all on resize.

I know this is not jQuery, but it's almost as short and easy to write. I hope my answer helps you. I do not know for sure that this is the issue.

ContentLicense: CC BY-SA 4.0

Body:
I am using the technique at this link to equalize the height of bootstrap carousel slides, so in the case of an uneven amount of text the slides do not cause the elements below them to bump up and down when advancing slides:

https://snook.ca/archives/javascript/normalize-bootstrap-carousel-heights

function normalizeSlideHeights() {
  $('.carousel').each(function() {
    var items = $('.carousel-item', this);
    items.css('min-height', 0);
    var maxHeight = Math.max.apply(null, items.map(function() {
      return $(this).outerHeight()
    }).get());
    items.css('min-height', maxHeight + 'px');
  })
}

$(window).on('load resize orientationchange', normalizeSlideHeights);

The first part of the code works great, all my carousel slides are the same height. The second part where it is looking for changes to the window size to re-adjust the slide height doesn't seem to work at all. I tried editing the original code to just check for 'resize' to simplify it but did not see any difference.

Any insights or ideas to a solution are greatly appreciated, thank you!

Body:
Try plain JavaScript. If something in jQuery isn't working for me, I always try plain JavaScript. An example is below:

window.onresize = function(){normalizeSlideHeights()}
window.onload = function(){normalizeSlideHeights()}

This WILL trigger the normalizeSlideHeights() function on resize and load, if the function exists. If this does not work correctly, then the issue is with the function itself.
You could also put some consoleLog() commands to see wether the function actually fires at all on resize.

I know this is not jQuery, but it's almost as short and easy to write. I hope my answer helps you. I do not know for sure that this is the issue.


问:
Resource interpreted as Stylesheet but transferred with MIME type text/x-scss
i want to create a website with nodejs but i have a problem with show style in scss and ejs .

i have a scss style in folder ../app/public/scss and i using this middlware for set static file with express :

```<code>    app.use(express.static(path.join(__dirname,'public')));
    app.set('view engine', 'ejs');
    app.set('views' , path.join(__dirname,'../','resources/views'));
</code>```

and in header i define the style by this way :

```<code><link rel="stylesheet" type="text/css" href="/scss/vazir.scss">
<link rel="stylesheet" type="text/css" href="/scss/media-queries.scss">
<link rel="stylesheet" type="text/css" href="/scss/style.scss">
</code>```

and i using the header by this way in the register.ejs :

```<code><%- include('./../header.ejs'); %>
</code>```

Registration

but when i go to the register page it show me this in console :

Resource interpreted as Stylesheet but transferred with MIME type text/x-scss: "http://localhost:3000/scss/vazir.scss".

register:9 Resource interpreted as Stylesheet but transferred with MIME type text/x-scss: "http://localhost:3000/scss/media-queries.scss".

register:10 Resource interpreted as Stylesheet but transferred with MIME type text/x-scss: "http://localhost:3000/scss/style.scss".

whats the problem ? how can i sovle this problem ????

答:
Browsers don't support SCSS. You need to compile it to CSS and serve the CSS files to the browser.

There are various compilers that support it. SASS is the official one. You might want to find one that integrates with your existing build toolchain.

Body:
i want to create a website with nodejs but i have a problem with show style in scss and ejs .

i have a scss style in folder ../app/public/scss and i using this middlware for set static file with express :

    app.use(express.static(path.join(__dirname,'public')));
    app.set('view engine', 'ejs');
    app.set('views' , path.join(__dirname,'../','resources/views'));

and in header i define the style by this way :

<link rel="stylesheet" type="text/css" href="/scss/vazir.scss">
<link rel="stylesheet" type="text/css" href="/scss/media-queries.scss">
<link rel="stylesheet" type="text/css" href="/scss/style.scss">

and i using the header by this way in the register.ejs :

<%- include('./../header.ejs'); %>

Registration

but when i go to the register page it show me this in console :

Resource interpreted as Stylesheet but transferred with MIME type text/x-scss: "http://localhost:3000/scss/vazir.scss".

register:9 Resource interpreted as Stylesheet but transferred with MIME type text/x-scss: "http://localhost:3000/scss/media-queries.scss".

register:10 Resource interpreted as Stylesheet but transferred with MIME type text/x-scss: "http://localhost:3000/scss/style.scss".

whats the problem ? how can i sovle this problem ????


问:
Adobe Air file avoid opening
After creating an adobe air file, I am able to open it using winrar or any other archiving program and see all the contents including the code of my program.

Is there a way to avoid this? Some sort of encryption or something?

Thank you very much.

答:
No. The '.air' file is as much an archive as say. a XPS file.

The question is why do you want such a thing? To avoid source sharing?

If you have issues sharing your source, why don't you use put javascript code on your server and pull them from client side. Of course, this'll mean that they don't work when their network or your server is down.

OwnerDisplayName: Alec Smart

ContentLicense: CC BY-SA 2.5

Title: Adobe Air file avoid opening

OwnerDisplayName: dirkgently


问:
textfield value changing detect in php
```<code> <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />
</code>```

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?

答:
isset() probably works as it should but it will only return false if variable doesn't exist or is null.

If I understand the problem correctly you should do something like:

```<code>if($_POST["aa"]!="please enter your name" && isset($_POST["aa"])){
    //do something
}
</code>```

same is true for other field:

```<code>if($_POST["aab"]!="please enter your email" && isset($_POST["aab"])){
    //do something
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: textfield value changing detect in php

Body:
 <input name="aa" type="text" id="aa" value="please enter your name" size="22"            maxlength="60" />
 <input name="aab" type="text" id="aab" value="please enter your email" size="22"            maxlength="60" />

i have a textfield and it's value is "please enter your name"(likewise i have many fields.i want to add the value to the database only if the value is changed.(if user entered a name)

i used php isset function and it does not work properly.
 how to detect that in php?

Body:
isset() probably works as it should but it will only return false if variable doesn't exist or is null.

If I understand the problem correctly you should do something like:

if($_POST["aa"]!="please enter your name" && isset($_POST["aa"])){
    //do something
}

same is true for other field:

if($_POST["aab"]!="please enter your email" && isset($_POST["aab"])){
    //do something
}


问:
Format time format in columns for Pandas pivot table
I am building a pivot table with Pandas from json data. I'd like to format the column names before sending to to_string().

```<code>import numpy as np
import pandas as pd

json_data = [
 {"year":2019,"month":"2019-11-01","sub_category":"Van fit out","category":"Vehicle","notes":"Heavy duty hooks","gross_amount":8.96},
 {"year":2019,"month":"2019-11-01","sub_category":"Fuel & oil","category":"Vehicle","notes":"Fuel","gross_amount":20.00},
# more data  [...]
 {"year":2020,"month":"2020-02-01","sub_category":"Gutter Vac","category":"WC Equipment + H&S","notes":"Tape Measure + Bungi Cord + Plastic Membrane + Extension reel + Microfibre cloths + Waterproof Jacket","gross_amount":97.94},
 {"year":2020,"month":"2020-02-01","sub_category":"Trad equipment","category":"WC Materials","notes":"Spray Bottle + Microfibres","gross_amount":4.47},
 ]

data = pd.DataFrame(json_data)

# Pivot the data:
pivot = pd.pivot_table(
            data, values=['gross_amount'], index=['category', 'sub_category'],
                    columns=['year', 'month'], aggfunc=np.sum, fill_value=0, dropna=True, margins=True)
# Add total rows for index level 0:
pivot = pd.concat([
        d.append(d.sum(skipna=True).rename((k, 'Total')))
        for k, d in pivot.groupby(level=0)
        ])

# Render to string:
string = pivot.to_string()

print(string)
</code>```

The result is

```<code>                                  gross_amount
year                                      2019       2020     All
month                               2019-11-01 2020-02-01
category           sub_category
All                                      28.96     102.41  131.37
                   Total                 28.96     102.41  131.37
Vehicle            Fuel & oil            20.00       0.00   20.00
                   Van fit out            8.96       0.00    8.96
                   Total                 28.96       0.00   28.96
WC Equipment + H&S Gutter Vac             0.00      97.94   97.94
                   Total                  0.00      97.94   97.94
WC Materials       Trad equipment         0.00       4.47    4.47
                   Total                  0.00       4.47    4.47
</code>```

How can I get the months to be formatted differently (in my case I need the month name)?
I have changed the month to a string in the dataframe before pivoting but then I lose the correct order.

Thanks

答:
It doesn't look like this is possible with pivot_table(), but I managed it with group_by() instead, which accepts a sort argument:

```<code>pivot = data.groupby(['category', 'sub_category', 'year', 'monthname'], sort=False)['gross_amount'].sum().unstack(['year', 'monthname'])
</code>```

The sort=False stops it from sorting alphabetically, and preserves the original order the monts appeared, so the dataframe has to be sorted prior to grouping.

Body:
I am building a pivot table with Pandas from json data. I'd like to format the column names before sending to to_string().

import numpy as np
import pandas as pd

json_data = [
 {"year":2019,"month":"2019-11-01","sub_category":"Van fit out","category":"Vehicle","notes":"Heavy duty hooks","gross_amount":8.96},
 {"year":2019,"month":"2019-11-01","sub_category":"Fuel & oil","category":"Vehicle","notes":"Fuel","gross_amount":20.00},
# more data  [...]
 {"year":2020,"month":"2020-02-01","sub_category":"Gutter Vac","category":"WC Equipment + H&S","notes":"Tape Measure + Bungi Cord + Plastic Membrane + Extension reel + Microfibre cloths + Waterproof Jacket","gross_amount":97.94},
 {"year":2020,"month":"2020-02-01","sub_category":"Trad equipment","category":"WC Materials","notes":"Spray Bottle + Microfibres","gross_amount":4.47},
 ]

data = pd.DataFrame(json_data)

# Pivot the data:
pivot = pd.pivot_table(
            data, values=['gross_amount'], index=['category', 'sub_category'],
                    columns=['year', 'month'], aggfunc=np.sum, fill_value=0, dropna=True, margins=True)
# Add total rows for index level 0:
pivot = pd.concat([
        d.append(d.sum(skipna=True).rename((k, 'Total')))
        for k, d in pivot.groupby(level=0)
        ])

# Render to string:
string = pivot.to_string()

print(string)

The result is

                                  gross_amount
year                                      2019       2020     All
month                               2019-11-01 2020-02-01
category           sub_category
All                                      28.96     102.41  131.37
                   Total                 28.96     102.41  131.37
Vehicle            Fuel & oil            20.00       0.00   20.00
                   Van fit out            8.96       0.00    8.96
                   Total                 28.96       0.00   28.96
WC Equipment + H&S Gutter Vac             0.00      97.94   97.94
                   Total                  0.00      97.94   97.94
WC Materials       Trad equipment         0.00       4.47    4.47
                   Total                  0.00       4.47    4.47

How can I get the months to be formatted differently (in my case I need the month name)?
I have changed the month to a string in the dataframe before pivoting but then I lose the correct order.

Thanks

Body:
It doesn't look like this is possible with pivot_table(), but I managed it with group_by() instead, which accepts a sort argument:

pivot = data.groupby(['category', 'sub_category', 'year', 'monthname'], sort=False)['gross_amount'].sum().unstack(['year', 'monthname'])

The sort=False stops it from sorting alphabetically, and preserves the original order the monts appeared, so the dataframe has to be sorted prior to grouping.


问:
Getting a json from an api with fetch js
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:

```<code>function get(){
      fetch('http://localhost:8082/marca/listar', {
            method: 'GET',
            headers: {},
            mode: 'no-cors', // <---
            cache: 'default'
        })
        .then(Response => { return Response.json() })
        .then(data => {
            console.log(data.nombre)
        });

}
</code>```

This is the url of the api

And I get the following error:

console message image

答:
```<code>fetch('http://localhost:8082/marca/listar',
{ cache: 'default' })
  .then(function (response) {
    if (response.status !== 200) {
      return;
    }
    response.json().then(function (data) {
      data.forEach((element) => {
        element.whatYouWant; /* Change (whatYouWant) to your desired output */
      })
    })
  })
  .catch(function (err) {
    console.log('Fetch Error :-S', err);
  });
</code>```

Body:
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:

function get(){
      fetch('http://localhost:8082/marca/listar', {
            method: 'GET',
            headers: {},
            mode: 'no-cors', // <---
            cache: 'default'
        })
        .then(Response => { return Response.json() })
        .then(data => {
            console.log(data.nombre)
        });

}

This is the url of the api

And I get the following error:

console message image


问:
How to extract partial text information from a label tag using Selenium and Python
I am trying to loop through different checkboxes and check them if the text is present in the list then click if not then move on.

the html element that I have been able to extract is below:

```<code><label>
 <input type ="checkbox" value = "pf29">
 <span> BNN Bloomberg </span>
 <span> class='count'>(16)</span>
<label>
</code>```

when I do element.text it gives me BNN Bloomberg (16). Is there a way to restrict the text output to only BNN Bloomberg?

There are roughly 33 different tags so I cant use any of the string methods to limit the number of characters.

Fairly new to html and selenium so excuse my wording.

Currently this is what my code looks like

```<code>element_list = (driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label"))
source = element_list[3].text
print(source)
</code>```

print(source) gives me BNN Bloomberg (16)

Edit: I have to loop through 21 different elements and look at the text to see what the source is and check the checkbox accordingly.

答:
You can try either of the following css selector.

```<code>element_list =driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label>span:nth-of-type(1)")
source = element_list[3].text
print(source)
</code>```

OR

```<code>element_list =driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label>span:not(.count)")
source = element_list[3].text
print(source)
</code>```

Body:
I am trying to loop through different checkboxes and check them if the text is present in the list then click if not then move on.

the html element that I have been able to extract is below:

 <input type ="checkbox" value = "pf29">
  BNN Bloomberg
  class='count'>(16)

when I do element.text it gives me BNN Bloomberg (16). Is there a way to restrict the text output to only BNN Bloomberg?

There are roughly 33 different tags so I cant use any of the string methods to limit the number of characters.

Fairly new to html and selenium so excuse my wording.

Currently this is what my code looks like

element_list = (driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label"))
source = element_list[3].text
print(source)

print(source) gives me BNN Bloomberg (16)

Edit: I have to loop through 21 different elements and look at the text to see what the source is and check the checkbox accordingly.

Body:
You can try either of the following css selector.

element_list =driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label>span:nth-of-type(1)")
source = element_list[3].text
print(source)

OR

element_list =driver.find_elements_by_css_selector("div[class='modal-dialog-padded-body'] label>span:not(.count)")
source = element_list[3].text
print(source)


问:
Using React within a dynamically loaded es module
I have been loading a native ES Module which can be simplified to src/test.tsx:

```<code>export default class Test {
    constructor() {
        console.log('loaded');
    }
}
</code>```

I can load this in my browser and initialize it great, a la:

```<code>import('http://127.0.0.1:8085/').then(m => {
  const instance = new m.default();
});
</code>```

However.. if I want to add any external dependency, in this case React, I can't seem to figure out how to target es6 and also bundle React, with tsc. So my dist file contains import React from 'react'; for which the browser has no idea how to resolve, and produces:

(index):1 Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

My tsconfig looks like:

```<code>{
    "compilerOptions": {
        "baseUrl": ".",
        "rootDir": "src",
        "module": "es6",
        "target": "es2015",
        "lib": ["es6", "dom"],
        "declaration": true,
        "jsx": "react",
        "outDir": "dist",
        "strict": true,
        "noImplicitAny": false,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "skipLibCheck": true
    },
    "include": ["./src/**/*"]
}
</code>```

Running node v9.5.0, typescript v2.9.2

I have also attempted to use webpack to bundle everything but cannot figure out how to produce a dynamically importable module that way

答:
The problem

After building your typescript files, at the top of your components you are going to have some import statements like the following (assuming you are targeting es2015)

```<code>import React from "react";
</code>```

The browser natively does not know how to resolve "react", for that reason it thinks that you have mistaken it for another relative path such as './react.js', and thus the error

```<code>(index):1 Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".
</code>```

currently there is a proposal import-maps that will enable browsers to natively support theses import statements. Chrome is experimenting with this, and eventually browser javascript will have to provide a way to resolve imported modules.

The solution

You can either do a runtime solution or a compile time solution:

Runtime solution

I'm gonna use systemjs since it is already supported by typescript out of the box, you wanna change "module" to "system" inside compilerOptions, like

```<code> "compilerOptions": {
   ....
   "module":"system"
  }
</code>```

This will make typescript compile to a systemjs compatible code, in your root index html file you wanna include the systemjs file, and u also have to tell systemjs where to look for these modules

```<code>// root index.html
 <script src="https://unpkg.com/systemjs@6.3.2/dist/system.js"></script>
 <script type="systemjs-importmap">
      {
        // for each library you add u have to include it here
        // documentation is here [systemjs import maps][3]d
        "imports": {
          "react": "https://unpkg.com/react@16/umd/react.production.min.js",
          "react-dom": "https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"
        }
      }
  </script>
</code>```

and later you can dynamically load the needed module

```<code>// load your module later
System.import("./dist/index.js").catch()

</code>```

compile time solution

You can use webpack, parcel or any other javascript bundler that will resolve these modules for you at compile time, and give you a bundle that has these modules already bundled within it.

I recommend a compile time solution, as it provides you with much more than just resolving modules, you can use css preprocessors, css modules, base64 inline images, and many things more.

Body:
I have been loading a native ES Module which can be simplified to src/test.tsx:

export default class Test {
    constructor() {
        console.log('loaded');
    }
}

I can load this in my browser and initialize it great, a la:

import('http://127.0.0.1:8085/').then(m => {
  const instance = new m.default();
});

However.. if I want to add any external dependency, in this case React, I can't seem to figure out how to target es6 and also bundle React, with tsc. So my dist file contains import React from 'react'; for which the browser has no idea how to resolve, and produces:

(index):1 Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

My tsconfig looks like:

{
    "compilerOptions": {
        "baseUrl": ".",
        "rootDir": "src",
        "module": "es6",
        "target": "es2015",
        "lib": ["es6", "dom"],
        "declaration": true,
        "jsx": "react",
        "outDir": "dist",
        "strict": true,
        "noImplicitAny": false,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "skipLibCheck": true
    },
    "include": ["./src/**/*"]
}

Running node v9.5.0, typescript v2.9.2

I have also attempted to use webpack to bundle everything but cannot figure out how to produce a dynamically importable module that way

Body:
The problem

After building your typescript files, at the top of your components you are going to have some import statements like the following (assuming you are targeting es2015)

import React from "react";

The browser natively does not know how to resolve "react", for that reason it thinks that you have mistaken it for another relative path such as './react.js', and thus the error

(index):1 Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

currently there is a proposal import-maps that will enable browsers to natively support theses import statements. Chrome is experimenting with this, and eventually browser javascript will have to provide a way to resolve imported modules.

The solution

You can either do a runtime solution or a compile time solution:

Runtime solution

I'm gonna use systemjs since it is already supported by typescript out of the box, you wanna change "module" to "system" inside compilerOptions, like

 "compilerOptions": {
   ....
   "module":"system"
  }

This will make typescript compile to a systemjs compatible code, in your root index html file you wanna include the systemjs file, and u also have to tell systemjs where to look for these modules

// root index.html
 <script src="https://unpkg.com/systemjs@6.3.2/dist/system.js"></script>
 <script type="systemjs-importmap">
      {
        // for each library you add u have to include it here
        // documentation is here [systemjs import maps][3]d
        "imports": {
          "react": "https://unpkg.com/react@16/umd/react.production.min.js",
          "react-dom": "https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"
        }
      }
  </script>

and later you can dynamically load the needed module

// load your module later
System.import("./dist/index.js").catch()

compile time solution

You can use webpack, parcel or any other javascript bundler that will resolve these modules for you at compile time, and give you a bundle that has these modules already bundled within it.

I recommend a compile time solution, as it provides you with much more than just resolving modules, you can use css preprocessors, css modules, base64 inline images, and many things more.


问:
print icon obtained from db - laravel
I want to put together a menu and get an icon dynamically.

the result i want is something like this:

Database table:

code:

    Categoryes
    Stores All

      @foreach($tipos as $tipo)

        {{$tipo->icono }}

tipo)}}">{{$tipo->tipo }}

      @endforeach

```

but it prints the label not the icon

What should I do to show my icons?

答:
You have to use {!! !!} to display the raw unescaped HTML of your icon:

```<code>{!! $tipo->icono !!}
</code>```

This way it doesn't get escaped with htmlspecialchars.

Basically {{ $var }} will be compiled to <?php htmlspecialchars($var); ?> and {!! $var !!} to <?php echo $var; ?>.

See the docs on how to display data in Blade templates for more information.

Title: print icon obtained from db - laravel

Body:
I want to put together a menu and get an icon dynamically.

the result i want is something like this:

Database table:

code:

    Categoryes
    Stores All

      @foreach($tipos as $tipo)

        {{$tipo->icono }}

tipo)}}">{{$tipo->tipo }}

      @endforeach

but it prints the label not the icon

What should I do to show my icons?

Body:
You have to use {!! !!} to display the raw unescaped HTML of your icon:

{!! $tipo->icono !!}

This way it doesn't get escaped with htmlspecialchars.

Basically {{ $var }} will be compiled to <?php htmlspecialchars($var); ?> and {!! $var !!} to <?php echo $var; ?>.

See the docs on how to display data in Blade templates for more information.


问:
How to use MutationObserver in Google Tag Manager to detect a new element in DOM?
I'm trying to detect an element being added to my div in GTM. I'm using Angular 8 and I'm not sure if Angular triggers a DOMNodeInserted event. Here's my code in GTM:

```<code>function () {
  return $('.taglist-list.what').bind('DOMNodeInserted DOMNodeRemoved', function(element){
    console.log('dom changed');

    if($(this).hasClass('gtm--user-generated-what')){
      console.log(element.target);
    }

  });
}
</code>```

The dom-changed is never triggered.

答:
I've done similar work in Google Tag Manager using mutation observers. They're supported in pretty much every modern browser.

Here is how it could be used for your specific problem with vanilla mutation observers (and your jquery added into the function):

```<code>var mutationTarget = document.querySelector('.taglist-list.what');
var observedAtts = {attributes: false, childList: true, subtree: false};

var mutationFunction = function(mutationList, observer) {
  mutationList.forEach(function (mutation) {
    if (mutation.type === 'childList') {
       mutation.addedNodes.forEach(function(elem) {
          if($(elem).hasClass('gtm--user-generated-what')){
             console.log(element.target);
          }
       });
    }
  });
};

var obs = new MutationObserver(mutationFunction);
obs.observe(mutationTarget, observedAtts);
</code>```

Here is a generic example:
https://codepen.io/abissonnette/pen/yLeLYjo

There is maybe more of a discussion around "should GTM be used for this kind of hacky stuff". Especially as @Aluan points out above - the implementation would be subject to change without notice. There are many things we shouldn't do but if there is a business need for it then you'll have to weight the risk vs rewards.

Body:
I'm trying to detect an element being added to my div in GTM. I'm using Angular 8 and I'm not sure if Angular triggers a DOMNodeInserted event. Here's my code in GTM:

function () {
  return $('.taglist-list.what').bind('DOMNodeInserted DOMNodeRemoved', function(element){
    console.log('dom changed');

    if($(this).hasClass('gtm--user-generated-what')){
      console.log(element.target);
    }

  });
}

The dom-changed is never triggered.

Body:
I've done similar work in Google Tag Manager using mutation observers. They're supported in pretty much every modern browser.

Here is how it could be used for your specific problem with vanilla mutation observers (and your jquery added into the function):

var mutationTarget = document.querySelector('.taglist-list.what');
var observedAtts = {attributes: false, childList: true, subtree: false};

var mutationFunction = function(mutationList, observer) {
  mutationList.forEach(function (mutation) {
    if (mutation.type === 'childList') {
       mutation.addedNodes.forEach(function(elem) {
          if($(elem).hasClass('gtm--user-generated-what')){
             console.log(element.target);
          }
       });
    }
  });
};

var obs = new MutationObserver(mutationFunction);
obs.observe(mutationTarget, observedAtts);

Here is a generic example:
https://codepen.io/abissonnette/pen/yLeLYjo

There is maybe more of a discussion around "should GTM be used for this kind of hacky stuff". Especially as @Aluan points out above - the implementation would be subject to change without notice. There are many things we shouldn't do but if there is a business need for it then you'll have to weight the risk vs rewards.


Title: How to specify dates as x-axis labels in ggplot? Trying to match dates with geom_vline() R

Body:
> All_Services_wDUPS
         Var1 Freq
1  2020-03-13    2
2  2020-03-16    5
3  2020-03-18   23
4  2020-03-19    9
5  2020-03-20    5
6  2020-03-21   69
7  2020-03-22   30
8  2020-03-23   33
9  2020-03-24   10
10 2020-03-25    2
11 2020-03-26    2
12 2020-03-27    5
13 2020-03-28    1
14 2020-03-29    9
15 2020-03-30    8
16 2020-03-31   10
17 2020-04-01    1
18 2020-04-03    5
19 2020-04-04    2
20 2020-04-05    1
21 2020-04-06    5
22 2020-04-07    7
23 2020-04-08    8
24 2020-04-09   10
25 2020-04-10  240
26 2020-04-11  102
27 2020-04-12   27
28 2020-04-13    3
29 2020-04-14    1
30 2020-04-15   11
31 2020-04-16   29
32 2020-04-17   10
33 2020-04-18    3
34 2020-04-19    4
35 2020-04-20    5
36 2020-04-21    5
37 2020-04-22    4
38 2020-04-23   10
39 2020-04-24    6
40 2020-04-27    6
41 2020-04-28    8
42 2020-04-29   21
43 2020-04-30    8
44 2020-05-01   10
45 2020-05-02    4
46 2020-05-03    4
47 2020-05-04    4
48 2020-05-05    3
49 2020-05-06    6
50 2020-05-07    4
51 2020-05-08    3
52 2020-05-09    1
53 2020-05-10    1
54 2020-05-11    6
55 2020-05-12    2
56 2020-05-13    1
57 2020-05-14    5
58 2020-05-15    6
59 2020-05-16    2
60 2020-05-17    2
61 2020-05-19    4
62 2020-05-20   32
63 2020-05-21   16

And here is my code

ggplot(data=All_Services_wDUPS, aes(x=Var1, y=Freq, group=1)) +
  #Verticle lines
  geom_vline(xintercept = as.numeric(as.Date("2020-03-13")), size=1.2, color = "grey", linetype=2) +
  geom_vline(xintercept = as.numeric(as.Date("2020-05-01")), size=1.2, color = "grey", linetype=2) +
  geom_vline(xintercept = as.numeric(as.Date("2020-05-22")), size=1.2, color = "grey", linetype=2) +
  annotate("text", x=as.Date("2020-03-13"), y=200, label= "First Case of COVID-19", angle=90, vjust=1.2, size=5) +
  annotate("text", x=as.Date("2020-05-01"), y=200, label= "Texas Reopens at 25%", angle=90, vjust=1.2, size=5) +
  annotate("text", x=as.Date("2020-05-22"), y=200, label= "Texas Reopens at 50%", angle=90, vjust=1.2, size=5) +

  #Blue Line TRend
  geom_line(color = "dodgerblue", size = 1.4) +
  geom_point(color = "dodgerblue", size = 2) +
  geom_text(aes(label=Freq),hjust=.3, vjust=-1.2, size=5) +
  ggtitle(label = "All Sales During COVID-19",
          subtitle = "San Antonio") +
  ylab("Sales in Units") +
  xlab("") +
  theme(axis.text.x =
          element_text(size  = 10,
                       angle = 0,
                       hjust = 1,
                       vjust = 1)) +
  #THEME
  theme_minimal() +
  #X & Y Axis line
  theme(axis.line = element_line(size = 1, colour = "grey42")) +
  #Larger Font
  theme(text = element_text(size=20))  +
  scale_x_date(breaks = "7 days", date_labels = "%b-%d")

This is the plot that is generated

My problem is that I need dates on my geom_vline() because they are landing on the x axis where there is no label, so its difficult to understand right away.

How can I specify the dates

2020-03-13
2020-05-01
2020-05-22

and still have some ticks on the other x labels?

Body:
Unfortunately, your plot is a bit of a mess with repetitions and elements that cancel others out. Therefore, I have conducted a somewhat larger cleanup of the code:

library(tidyverse)

All_Services_wDUPS <- tibble(
  Var1 = as.Date(c("2020-03-13", "2020-03-16", "2020-03-18", "2020-03-19", "2020-03-20", "2020-03-21", "2020-03-22", "2020-03-23", "2020-03-24", "2020-03-25", "2020-03-26", "2020-03-27", "2020-03-28", "2020-03-29", "2020-03-30", "2020-03-31", "2020-04-01", "2020-04-03", "2020-04-04", "2020-04-05", "2020-04-06", "2020-04-07", "2020-04-08", "2020-04-09", "2020-04-10", "2020-04-11", "2020-04-12", "2020-04-13", "2020-04-14", "2020-04-15", "2020-04-16", "2020-04-17", "2020-04-18", "2020-04-19", "2020-04-20", "2020-04-21", "2020-04-22", "2020-04-23", "2020-04-24", "2020-04-27", "2020-04-28", "2020-04-29", "2020-04-30", "2020-05-01", "2020-05-02", "2020-05-03", "2020-05-04", "2020-05-05", "2020-05-06", "2020-05-07", "2020-05-08", "2020-05-09", "2020-05-10", "2020-05-11", "2020-05-12", "2020-05-13", "2020-05-14", "2020-05-15", "2020-05-16", "2020-05-17", "2020-05-19", "2020-05-20", "2020-05-21")),
  Freq = as.integer(c(2, 5, 23, 9, 5, 69, 30, 33, 10, 2, 2, 5, 1, 9, 8, 10, 1, 5, 2, 1, 5, 7, 8, 10, 240, 102, 27, 3, 1, 11, 29, 10, 3, 4, 5, 5, 4, 10, 6, 6, 8, 21, 8, 10, 4, 4, 4, 3, 6, 4, 3, 1, 1, 6, 2, 1, 5, 6, 2, 2, 4, 32, 16))
)

vlines <- tibble(
  x = as.Date(c("2020-03-13", "2020-05-01", "2020-05-22")),
  y = 200,
  label = c("First Case of COVID-19", "Texas Reopens at 25%", "Texas Reopens at 50%"),
)

ggplot(All_Services_wDUPS, aes(Var1, Freq)) +

  #Vertical lines
  geom_vline(aes(xintercept = x), vlines, size=1.2, color = "grey", linetype = 2) +
  geom_text(aes(x, y, label = label), vlines, angle = 90, vjust = 1.2, size = 5) +

  #Blue Line Trend
  geom_line(color = "dodgerblue", size = 1.4) +
  geom_point(color = "dodgerblue", size = 2) +
  geom_text(aes(label = Freq), hjust = .3, vjust = -1.2, size = 5) +

  labs(x = "",
       y = "Sales in Units",
       title = "All Sales During COVID-19",
       subtitle = "San Antonio") +

  theme_minimal() +
  theme(text = element_text(size = 20),
        axis.line = element_line(size = 1, colour = "grey42"),
        axis.ticks = element_line(size = 1, colour = "grey42")
        ) +
  scale_x_date(breaks = seq.Date(as.Date("2020-03-13"), as.Date("2020-05-22"), "week"),
               date_labels = "%b-%d")

Your three events are all on the same weekday, so we can just align the weekly axis breaks with the events.

Your theme_minimal() had removed the ticks, so to bring them back I specified axis.ticks in theme(). Importantly, theme() must come after theme_minimal(), or else your changes will be overwritten.

Now it is a simple matter of creating a custom breaks vector breaks = seq.Date(as.Date("2020-03-13"), as.Date("2020-05-22"), "week") in scale_x_date().

I also moved the data for the vertical lines into a separate data frame, reducing the number of layers needed for those from 6 to 2.

Furthermore, I consolidated the plot and axis labels into labs() and finally, I removed some clutter and superfluous code.


问:
watch not getting all in Vue
```<code><template>
 <v-form :model='agency'>
  <v-layout row wrap>
    <v-flex xs12 sm12 lg12 >
      <v-layout row wrap>
       <v-flex xs12 md12 class="add-col-padding-right">
        <v-radio-group
         v-model="agency.location"
         :mandatory="true"
         label="Please select one of the options below">
           <v-radio label="NYC" value="nyc"></v-radio>
           <v-radio label="SAN JOSE" value="san_jose"></v-radio>
        </v-radio-group>
       </v-flex>
      </v-layout>
    </v-flex>
  </v-layout>
 </v-form>
</template>

<script>

  export default {

   data: function () {
    return {
      agency: {
        id: '',
        name: '',
        location: '',
        contacts: {
          name: '',
          number: '',
          address: ''
        }
      },
      final_location_contact: {
       name: '',
       number: '',
       address: ''
      }
    }
   }
   watch: {
    agency: {
      handler(val){
       if (this.agency.location === "nyc") {
        this.final_location_contact = this.agency.contacts;
       }
    }
   },
   created: function() {
    this.fetchAgency();
   },
   method: {
    fetchAgency() {
      this.$axios.get('/agency.json')
      .then(response => {
        if (Object.keys(response.data).length > 0) {
          this.agency = response.data;
        }
      }).
      then(() => {
      });
    },
   }
  }
</script>
</code>```

The issue I am facing here is when the page loads, and the fetchAgency method runs and I am able to get the agency data. When I select first option from the radio button, then I am able to assign the value agency.contacts values to final_location_contact. But the issue arrises when I first select the San Jose Radio button option and after that I select nyc radio button then I am  not able to assign the value agency.contacts values to final_location_contact as I checked using  debugger the value of agency.contacts is empty. But it not empty if I select nyc the first time. Any Idea where could be the issue?

```<code>'agency.location': {
  handler (newValue, oldValue) {
    if (newValue === "nyc") {
      this.final_location_contact = this.agency.contacts;
    }
    else {
      this.final_location_contact.name: '',
      this.final_location_contact.number: '',
      this.final_location_contact.address: ''
    }
  }
 }
</code>```

答:
The problem you're running into, is that in the eyes of JavaScript, you aren't changing the value of agency when you change agency.location. In the eyes of the language agency is still the same object, no matter what you do to its properties. That watcher is waiting for a change to the entire object, like agency = {different: "object"} what I would recommend you do is break out location to its own top level property and adjust that, like this:

data: function () {
    return {
      location: '',
      agency: {
        id: '',
        name: '',
        location: '',
        contacts: {
          name: '',
          number: '',
          address: ''
        }
      },
      final_location_contact: {
       name: '',
       number: '',
       address: ''
      }
    }
   }
```

<p>That way, you can set a watcher on that property like so:</p>

<pre class="lang-js prettyprint-override"><code>watch: {
    location: function(val) {
      this.agency.location = val
       if (val === "nyc") {
        this.final_location_contact = this.agency.contacts;
       }
    }
   },
</code>```

Title: watch not getting all in Vue

Body:
<template>
 <v-form :model='agency'>
  <v-layout row wrap>
    <v-flex xs12 sm12 lg12 >
      <v-layout row wrap>
       <v-flex xs12 md12 class="add-col-padding-right">
        <v-radio-group
         v-model="agency.location"
         :mandatory="true"
         label="Please select one of the options below">
           <v-radio label="NYC" value="nyc"></v-radio>
           <v-radio label="SAN JOSE" value="san_jose"></v-radio>
        </v-radio-group>
       </v-flex>
      </v-layout>
    </v-flex>
  </v-layout>
 </v-form>
</template>

The issue I am facing here is when the page loads, and the fetchAgency method runs and I am able to get the agency data. When I select first option from the radio button, then I am able to assign the value agency.contacts values to final_location_contact. But the issue arrises when I first select the San Jose Radio button option and after that I select nyc radio button then I am  not able to assign the value agency.contacts values to final_location_contact as I checked using  debugger the value of agency.contacts is empty. But it not empty if I select nyc the first time. Any Idea where could be the issue?

'agency.location': {
  handler (newValue, oldValue) {
    if (newValue === "nyc") {
      this.final_location_contact = this.agency.contacts;
    }
    else {
      this.final_location_contact.name: '',
      this.final_location_contact.number: '',
      this.final_location_contact.address: ''
    }
  }
 }

Body:
The problem you're running into, is that in the eyes of JavaScript, you aren't changing the value of agency when you change agency.location. In the eyes of the language agency is still the same object, no matter what you do to its properties. That watcher is waiting for a change to the entire object, like agency = {different: "object"} what I would recommend you do is break out location to its own top level property and adjust that, like this:

data: function () {
    return {
      location: '',
      agency: {
        id: '',
        name: '',
        location: '',
        contacts: {
          name: '',
          number: '',
          address: ''
        }
      },
      final_location_contact: {
       name: '',
       number: '',
       address: ''
      }
    }
   }

That way, you can set a watcher on that property like so:

watch: {
    location: function(val) {
      this.agency.location = val
       if (val === "nyc") {
        this.final_location_contact = this.agency.contacts;
       }
    }
   },


问:
opengl glDrawArray throws exception
I'm new to openGL and I need to directly use it for debuging perpose can anyone please tell me why in this code glDrawArray should throw exception (trying to access memory at 0x00000000)</p>

```<code>glEnableClientState(GL_VERTEX_ARRAY);
float data[8];
data[0] = 10;
data[1] = 10;
data[2] = 10;
data[3] = 20;
data[4] = 20;
data[5] = 20;
data[6] = 20;
data[7] = 10;
glVertexPointer(2,GL_FLOAT,0,data);
glDrawArrays(GL_LINE_LOOP,0,4);
glDisableClientState(GL_VERTEX_ARRAY);
</code>```

答:
Perhaps you have enabled another array with glEnableClientState at another point in your program and didn't disable it. So glDrawArrays tries to read from another array that causes the problem.

EDIT:: It could also be, that the code you showed us is not the real code and you call glVertexPointer at a completely different place than glDrawArrays. When giving data as vertex pointer, you only tell it to take the vertices from data, when glDrawArrays is called. The vertex data is not copied, so data has to still exist when glDrawArrays is called (at the moment it's a local variable, but with the code snippet you gave us it should work).

EDIT: I also suppose you are not using any buffer objects, as that could also be a problem, if a vertex buffer is bound when you call glVertexPointer.

Title: opengl glDrawArray throws exception

Body:
I'm new to openGL and I need to directly use it for debuging perpose can anyone please tell me why in this code glDrawArray should throw exception (trying to access memory at 0x00000000)

glEnableClientState(GL_VERTEX_ARRAY);
float data[8];
data[0] = 10;
data[1] = 10;
data[2] = 10;
data[3] = 20;
data[4] = 20;
data[5] = 20;
data[6] = 20;
data[7] = 10;
glVertexPointer(2,GL_FLOAT,0,data);
glDrawArrays(GL_LINE_LOOP,0,4);
glDisableClientState(GL_VERTEX_ARRAY);


问:
Sql: How to get previous row/day close quote?
I've a "classic" sql table for Stock Quotes:

Date, Ticker, Open, High, Low, Close, Volume

I want to calculate % change of day, so i need to get Previous day Close and Today Close.

How can I do efficently  in standard Sql ?

EDIT: my data example. Change value have to be calculated getting previous day close.

Thanks

答:
In any reasonable database you would simply use lag().  Oh well, that precludes MS Access.  You can do this with a correlated subquery.  The following gets the previous close:

```<code>select q.*,
       (select top (1) q2.close
        from quotes as q2
        where q2.ticker = q.ticker and q2.quotedate < q.quotedate
        order by q2.quotedate desc
       ) as prev_close
from quotes as q;
</code>```

I'm not sure exactly how you are calculating the change, but you can use a subquery:

```<code>select q.*,
       (close - prev_close) / prev_close as change_ratio
from (select q.*,
             (select top (1) q2.close
              from quotes as q2
              where q2.ticker = q.ticker and q2.quotedate < q.quotedate
              order by q2.quotedate desc
             ) as prev_close
      from quotes as q
     ) as q;
</code>```

Body:
In any reasonable database you would simply use lag().  Oh well, that precludes MS Access.  You can do this with a correlated subquery.  The following gets the previous close:

select q.*,
       (select top (1) q2.close
        from quotes as q2
        where q2.ticker = q.ticker and q2.quotedate < q.quotedate
        order by q2.quotedate desc
       ) as prev_close
from quotes as q;

I'm not sure exactly how you are calculating the change, but you can use a subquery:

select q.*,
       (close - prev_close) / prev_close as change_ratio
from (select q.*,
             (select top (1) q2.close
              from quotes as q2
              where q2.ticker = q.ticker and q2.quotedate < q.quotedate
              order by q2.quotedate desc
             ) as prev_close
      from quotes as q
     ) as q;


问:
Need to install urllib2 for Python 3.5.1
I'm running Python 3.5.1 for Mac. I want to use urllib2 module. I tried installing it but I was told that it's been split into urllib.request and urllib.error for Python 3.

My command (running from the framework bin directory for now because it's not in my path):

```<code>sudo ./pip3 install urllib.request
</code>```

Returns this:

```<code>Could not find a version that satisfies the requirement urllib.request (from versions: )
No matching distribution found for urllib.request
</code>```

I got the same error before when I tried to install urllib2 in one fell swoop.

答:
In Python 3, urllib2 was replaced by two in-built modules named urllib.request and urllib.error

Adapted from source

So replace this:

```<code>import urllib2
</code>```

With this:

import urllib.request as urllib2
```

Body:
I'm running Python 3.5.1 for Mac. I want to use urllib2 module. I tried installing it but I was told that it's been split into urllib.request and urllib.error for Python 3.

My command (running from the framework bin directory for now because it's not in my path):

sudo ./pip3 install urllib.request

Returns this:

Could not find a version that satisfies the requirement urllib.request (from versions: )
No matching distribution found for urllib.request

I got the same error before when I tried to install urllib2 in one fell swoop.

Body:
In Python 3, urllib2 was replaced by two in-built modules named urllib.request and urllib.error

Adapted from source

So replace this:

import urllib2

With this:

import urllib.request as urllib2


问:
Is there function in pytorch similar to tf.contrib.distributions.percentile of tensorflow?
Is there a function in PyTorch that does the same as tf.contrib.distributions.percentile of Tensorflow?

答:
i don't know the pro and con,
but there is method to use cupy with pytorch dlpack:</p>

<p>(cupy doesn't support pytorch tensor directly, CuPy functions does not accept torch tensors.) </p>

```<code>import torch
from torch.utils.dlpack import to_dlpack
from torch.utils.dlpack import from_dlpack
import cupy

x = torch.Tensor([1, 2, 3]).cuda()
dx = to_dlpack(x)
cx = cupy.fromDlpack(dx)
print(cupy.percentile(cx, 30)) # 30-th percentile of x
# 1.5999999642372131
</code>```

Body:
i don't know the pro and con,
but there is method to use cupy with pytorch dlpack:

(cupy doesn't support pytorch tensor directly, CuPy functions does not accept torch tensors.)

import torch
from torch.utils.dlpack import to_dlpack
from torch.utils.dlpack import from_dlpack
import cupy

x = torch.Tensor([1, 2, 3]).cuda()
dx = to_dlpack(x)
cx = cupy.fromDlpack(dx)
print(cupy.percentile(cx, 30)) # 30-th percentile of x
# 1.5999999642372131


问:
Are local variables of consecutive structs being held in consecutive memory locations?
For example, consider the following code:

```<code>struct user
{
    char username[20];
};

struct admin
{
    char rootpass[20];
};
</code>```

Can I overwrite rootpass by overflowing username?

答:
Even if you can you shouldn't.

The answer to your question depends on architecture and compiler, but you shouldn't even be asking this question.

NEVER access array elements out of range (for an array defined as [N] only elements 0 ... N-1 are valid).

Body:
For example, consider the following code:

struct user
{
    char username[20];
};

struct admin
{
    char rootpass[20];
};

Can I overwrite rootpass by overflowing username?


问:
Problems in configuring OpenWrt for socket programming
I have a code which receives packets from the Ethernet and sends it via wireless network. This works on a wireless box which uses OpenWrt. The code is written below. It gives me the following error at runtime. Based on the printf statements I feel the error is somewhere on this syntax, but I cant figure out whats wrong.

Probable region of error:

```<code>  if(sendto(b_sock, buf, sizeof(v2vmessage), 0, (struct sockaddr *)&tx_addr, sizeof(tx_addr)) < 0)
</code>```

Error:

```<code>Receving packets
Packets received
Sending packet started
Variables initialized
Send test
./dsrc_dsrc: can't resolve symbol 'sendto' in lib './dsrc_dsrc'.
</code>```

Code:

```<code>#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#include <stdio.h>

#include <fcntl.h>
#include <string.h>
#include <sys/time.h>
#include <arpa/inet.h>  /* for sockaddr_in */

#define BROADCAST_IP "192.168.255.255"
#define BROADCAST_PORT 4545

struct v2vmessage
{
  ...
  ...
};

int b_sock=-1;

void init_socket()
{
  unsigned short b_port = BROADCAST_PORT;
  struct sockaddr_in b_addr;
  int broadcastPermission;
  char* rx_ip = BROADCAST_IP;

  if ((b_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
    perror("socket() failed");

  /* Set socket to allow broadcast */
  broadcastPermission = 1;
  if (setsockopt(b_sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, sizeof(broadcastPermission)) < 0)
    perror("setsockopt() failed");

  int opts;
  opts = fcntl(b_sock,F_GETFL);
  if(opts < 0)
    perror("fcntl get failed");

  opts = (opts | O_NONBLOCK);
  if(fcntl(b_sock,F_SETFL,opts) < 0)
    perror("fcntl set failed");

  memset(&b_addr, 0, sizeof(b_addr));   /* Zero out structure */
  b_addr.sin_family = AF_INET;                 /* Internet address family */
  b_addr.sin_addr.s_addr = inet_addr(rx_ip);/* Broadcast IP address */
  b_addr.sin_port = htons(b_port);         /* Broadcast port */

  if (bind(b_sock, (struct sockaddr *) &b_addr, sizeof(b_addr)) < 0)
    perror("rx bind() failed");
}

void send_thread_body(v2vmessage *buf)
{
  printf("Sending packet started\n");
  char *tx_ip = BROADCAST_IP;
  unsigned short tx_port = BROADCAST_PORT;
  struct sockaddr_in tx_addr;

  printf("Variables initialized\n");

  memset(&tx_addr, 0, sizeof(tx_addr));   /* Zero out structure */
  tx_addr.sin_family = AF_INET;                 /* Internet address family */
  tx_addr.sin_addr.s_addr = inet_addr(tx_ip);/* Broadcast IP address */
  tx_addr.sin_port = htons(tx_port);         /* Broadcast port */

  printf("Send test\n");

  if(sendto(b_sock, buf, sizeof(v2vmessage), 0, (struct sockaddr *)&tx_addr, sizeof(tx_addr)) < 0)
    perror("tx sent diff num bytes than expected");
}

int main(int argc, char *argv[])
{
  init_socket();
  {
    int sock, length, n,p;
    socklen_t fromlen;
    struct sockaddr_in server;
    struct sockaddr_in from;

    if (argc < 2)
    {
      fprintf(stderr, "ERROR, no port provided\n");
      exit(0);
    }

    sock=socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
      perror("Opening socket");
    length = sizeof(server);
    bzero(&server,length);
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(atoi(argv[1]));
    if (bind(sock,(struct sockaddr *)&server,length)<0)
      perror("binding");
    fromlen = sizeof(struct sockaddr_in);
    v2vmessage *buf;

    while (1)
    {
      printf("Receving packets\n");
      n = recvfrom(sock,buf,sizeof(v2vmessage),0,(struct sockaddr *)&from,&fromlen);
      if (n < 0)
        perror("recvfrom");
      printf("Packets received\n");
      send_thread_body(buf);
      printf("Packets sent\n");
    }
  }
  return 0;
}
</code>```

答: In the main(), replace v2vmessage* buf by v2vmessage buf and in the following while(1), replace the buf by &buf to solve the problem. Since, no memory was allocated to the pointer, hence it gave an error at runtime.

Body:
I have a code which receives packets from the Ethernet and sends it via wireless network. This works on a wireless box which uses OpenWrt. The code is written below. It gives me the following error at runtime. Based on the printf statements I feel the error is somewhere on this syntax, but I cant figure out whats wrong.

Probable region of error:

  if(sendto(b_sock, buf, sizeof(v2vmessage), 0, (struct sockaddr *)&tx_addr, sizeof(tx_addr)) < 0)

Error:

Receving packets
Packets received
Sending packet started
Variables initialized
Send test
./dsrc_dsrc: can't resolve symbol 'sendto' in lib './dsrc_dsrc'.

Code:

#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#include <stdio.h>

#include <fcntl.h>
#include <string.h>
#include <sys/time.h>
#include <arpa/inet.h>  /* for sockaddr_in */

#define BROADCAST_IP "192.168.255.255"
#define BROADCAST_PORT 4545

struct v2vmessage
{
  ...
  ...
};

int b_sock=-1;

void init_socket()
{
  unsigned short b_port = BROADCAST_PORT;
  struct sockaddr_in b_addr;
  int broadcastPermission;
  char* rx_ip = BROADCAST_IP;

  if ((b_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
    perror("socket() failed");

  /* Set socket to allow broadcast */
  broadcastPermission = 1;
  if (setsockopt(b_sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, sizeof(broadcastPermission)) < 0)
    perror("setsockopt() failed");

  int opts;
  opts = fcntl(b_sock,F_GETFL);
  if(opts < 0)
    perror("fcntl get failed");

  opts = (opts | O_NONBLOCK);
  if(fcntl(b_sock,F_SETFL,opts) < 0)
    perror("fcntl set failed");

  memset(&b_addr, 0, sizeof(b_addr));   /* Zero out structure */
  b_addr.sin_family = AF_INET;                 /* Internet address family */
  b_addr.sin_addr.s_addr = inet_addr(rx_ip);/* Broadcast IP address */
  b_addr.sin_port = htons(b_port);         /* Broadcast port */

  if (bind(b_sock, (struct sockaddr *) &b_addr, sizeof(b_addr)) < 0)
    perror("rx bind() failed");
}

void send_thread_body(v2vmessage *buf)
{
  printf("Sending packet started\n");
  char *tx_ip = BROADCAST_IP;
  unsigned short tx_port = BROADCAST_PORT;
  struct sockaddr_in tx_addr;

  printf("Variables initialized\n");

  memset(&tx_addr, 0, sizeof(tx_addr));   /* Zero out structure */
  tx_addr.sin_family = AF_INET;                 /* Internet address family */
  tx_addr.sin_addr.s_addr = inet_addr(tx_ip);/* Broadcast IP address */
  tx_addr.sin_port = htons(tx_port);         /* Broadcast port */

  printf("Send test\n");

  if(sendto(b_sock, buf, sizeof(v2vmessage), 0, (struct sockaddr *)&tx_addr, sizeof(tx_addr)) < 0)
    perror("tx sent diff num bytes than expected");
}

int main(int argc, char *argv[])
{
  init_socket();
  {
    int sock, length, n,p;
    socklen_t fromlen;
    struct sockaddr_in server;
    struct sockaddr_in from;

    if (argc < 2)
    {
      fprintf(stderr, "ERROR, no port provided\n");
      exit(0);
    }

    sock=socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
      perror("Opening socket");
    length = sizeof(server);
    bzero(&server,length);
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(atoi(argv[1]));
    if (bind(sock,(struct sockaddr *)&server,length)<0)
      perror("binding");
    fromlen = sizeof(struct sockaddr_in);
    v2vmessage *buf;

    while (1)
    {
      printf("Receving packets\n");
      n = recvfrom(sock,buf,sizeof(v2vmessage),0,(struct sockaddr *)&from,&fromlen);
      if (n < 0)
        perror("recvfrom");
      printf("Packets received\n");
      send_thread_body(buf);
      printf("Packets sent\n");
    }
  }
  return 0;
}


问:
How can I use a javascript variable in css?
I'm trying to generate a grid with Javascript. The user should input a number to establish the size of the grid. If I run the code with a specific number inserted into the javascript code and css it works fine, but as soon as I change the number with a variable and use only the user input it gives me a weird grid.

Here's the code

    const container = document.querySelector(".container");

    //CREATE GRID
    function grid (size) {
        size = prompt("How many squares wide do you want your grid to be?");
        container.style.gridTemplateColumns = "repeat(7, 1ft)";
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                const square = document.createElement("div");
                square.classList.add("square");
                square.style = "background-color: white; border: 1px solid black";
                container.appendChild(square);
            }
        }
    }

    grid(7);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .container {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    width: 500px;
    height: 500px;
    border: 2px dotted lightgray;

    }</code>```

```

In this case if I select 7 as the user input it works, but if I replace 7 with "size", which is the variable it doesn't

答:
Here's an example solution very similar to your attempt. Notice that I corrected the typo ft to fr in the code snippet. This uses back-tick strings (template literals) for interpolation, but you could also use + to join strings together.

const container = document.querySelector(".container");

//CREATE GRID
function grid(size) {
  container.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
  for (let row = 0; row < size; row++) {
    for (let column = 0; column < size; column++) {
      const square = document.createElement("div");
      square.classList.add("square");
      container.appendChild(square);
    }
  }
}

size = prompt("How many squares wide do you want your grid to be?");
grid(size);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: grid;
  width: 500px;
  height: 500px;
  border: 2px dotted lightgray;
}

.container>.square {
  background-color: white;
  border: 1px solid black
}</code>```

```
</div>
</div>
</p>

<p>Here is an example using css variables instead:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const container = document.querySelector(".container");

//CREATE GRID
function grid(size) {
  container.style.setProperty('--grid-size', size);
  for (let row = 0; row < size; row++) {
    for (let column = 0; column < size; column++) {
      const square = document.createElement("div");
      square.classList.add("square");
      container.appendChild(square);
    }
  }
}

size = prompt("How many squares wide do you want your grid to be?");
grid(size);</code>```

.container {
  display: grid;
  width: 500px;
  height: 500px;
  border: 2px dotted lightgray;
  grid-template-columns: repeat(var(--grid-size), 1fr);
}

.container>.square {
  background-color: white;
  border: 1px solid black
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main class="container"></main></code>```

Body:
I'm trying to generate a grid with Javascript. The user should input a number to establish the size of the grid. If I run the code with a specific number inserted into the javascript code and css it works fine, but as soon as I change the number with a variable and use only the user input it gives me a weird grid.

Here's the code

    const container = document.querySelector(".container");

    //CREATE GRID
    function grid (size) {
        size = prompt("How many squares wide do you want your grid to be?");
        container.style.gridTemplateColumns = "repeat(7, 1ft)";
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                const square = document.createElement("div");
                square.classList.add("square");
                square.style = "background-color: white; border: 1px solid black";
                container.appendChild(square);
            }
        }
    }

    grid(7);

    .container {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    width: 500px;
    height: 500px;
    border: 2px dotted lightgray;

    }

In this case if I select 7 as the user input it works, but if I replace 7 with "size", which is the variable it doesn't

Body:
Here's an example solution very similar to your attempt. Notice that I corrected the typo ft to fr in the code snippet. This uses back-tick strings (template literals) for interpolation, but you could also use + to join strings together.

const container = document.querySelector(".container");

//CREATE GRID
function grid(size) {
  container.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
  for (let row = 0; row < size; row++) {
    for (let column = 0; column < size; column++) {
      const square = document.createElement("div");
      square.classList.add("square");
      container.appendChild(square);
    }
  }
}

size = prompt("How many squares wide do you want your grid to be?");
grid(size);

.container {
  display: grid;
  width: 500px;
  height: 500px;
  border: 2px dotted lightgray;
}

.container>.square {
  background-color: white;
  border: 1px solid black
}

<main class="container"></main>

Here is an example using css variables instead:

const container = document.querySelector(".container");

//CREATE GRID
function grid(size) {
  container.style.setProperty('--grid-size', size);
  for (let row = 0; row < size; row++) {
    for (let column = 0; column < size; column++) {
      const square = document.createElement("div");
      square.classList.add("square");
      container.appendChild(square);
    }
  }
}

size = prompt("How many squares wide do you want your grid to be?");
grid(size);

.container {
  display: grid;
  width: 500px;
  height: 500px;
  border: 2px dotted lightgray;
  grid-template-columns: repeat(var(--grid-size), 1fr);
}

.container>.square {
  background-color: white;
  border: 1px solid black
}

<main class="container"></main>


问:
Remove empty dicts in nested dictionary with recursive function
I'm trying to remove non-values from a nested dictionary.  My first effort works fine, but unfortunately keys pointing to now empty dicts still persist.

So if i do:

```<code>pass1 = stripper(my_dict)
return stripper(pass1)
</code>```

This works, but i'm thinking a more elegant nested solution might be possible?

```<code>def stripper(self, data):
    if isinstance(data, dict):
        d = ({k: stripper(v) for k, v in data.items()
             if v not in [u'', None]})
        if d:
            return d
    else:
        return data
</code>```

Edit:

Failing example, dict below returns as {'foo': 'bar', 'bar': None}:

```<code>{
    'foo': 'bar',
    'bar': {
        'foo': None,
        'one': None
    }
}
</code>```

答:
To extend the accepted answer to include objects that might be an element of a list:

```<code>def strip_empties_from_list(data):
    new_data = []
    for v in data:
        if isinstance(v, dict):
            v = strip_empties_from_dict(v)
        elif isinstance(v, list):
            v = strip_empties_from_list(v)
        if v not in (None, str(), list(), dict(),):
            new_data.append(v)
    return new_data

def strip_empties_from_dict(data):
    new_data = {}
    for k, v in data.items():
        if isinstance(v, dict):
            v = strip_empties_from_dict(v)
        elif isinstance(v, list):
            v = strip_empties_from_list(v)
        if v not in (None, str(), list(), dict(),):
            new_data[k] = v
    return new_data
</code>```

To use:

```<code>data = {
  'None': None,
  'empty_list': [],
  'empty_dict': {},
  'empty_string': '',
  'list_with_empties': ['', {}, [], None, {'more_empties': '', 'and_even_more': [''], 'one_thing_i_care_about': 'hi'}]
}
stripped_data = strip_empties_from_dict(data)
print(stripped_data)
</code>```

Body:
I'm trying to remove non-values from a nested dictionary.  My first effort works fine, but unfortunately keys pointing to now empty dicts still persist.

So if i do:

pass1 = stripper(my_dict)
return stripper(pass1)

This works, but i'm thinking a more elegant nested solution might be possible?

def stripper(self, data):
    if isinstance(data, dict):
        d = ({k: stripper(v) for k, v in data.items()
             if v not in [u'', None]})
        if d:
            return d
    else:
        return data

Edit:

Failing example, dict below returns as {'foo': 'bar', 'bar': None}:

{
    'foo': 'bar',
    'bar': {
        'foo': None,
        'one': None
    }
}

Body:
To extend the accepted answer to include objects that might be an element of a list:

def strip_empties_from_list(data):
    new_data = []
    for v in data:
        if isinstance(v, dict):
            v = strip_empties_from_dict(v)
        elif isinstance(v, list):
            v = strip_empties_from_list(v)
        if v not in (None, str(), list(), dict(),):
            new_data.append(v)
    return new_data

def strip_empties_from_dict(data):
    new_data = {}
    for k, v in data.items():
        if isinstance(v, dict):
            v = strip_empties_from_dict(v)
        elif isinstance(v, list):
            v = strip_empties_from_list(v)
        if v not in (None, str(), list(), dict(),):
            new_data[k] = v
    return new_data

To use:

data = {
  'None': None,
  'empty_list': [],
  'empty_dict': {},
  'empty_string': '',
  'list_with_empties': ['', {}, [], None, {'more_empties': '', 'and_even_more': [''], 'one_thing_i_care_about': 'hi'}]
}
stripped_data = strip_empties_from_dict(data)
print(stripped_data)


问:
Lazy/Enforced Initialization of Primitive Typed Property in C#
Often when coding in C# I like to use this pattern for a lazy getter property:

```<code>private string _myProp;
string MyProp => _myProp ?? (_myProp = getMyProp());
</code>```

I think this is pretty standard C# practice. The function getMyProp() is just some function that computes and returns a string. It is called just once to initialize the property, and henceforth it's cached. I can use this for any object type I like, not just string. However, when I try to do it for a primitive type like an int, I run into an issue. For example, if I try the following:

```<code>private int _operationCount;
int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser());
</code>```

I get a compiler error here. It says:

Error CS0019  Operator '??' cannot be applied to operands of type 'int' and 'int'

I understand the error means that int is a primitive type, so we can't apply the null-checking operator to it, because an int is never null. But is there any way I can achieve what I want here? I'm looking for a solution with the following:

On the first access, the int property is initialized to the return value of the function call.

On subsequent accesses, the int property is retrieved from a loaded variable in memory i.e. the function is not called again.

Update: Why Write Properties Like This?

The original question just cited "laziness" as the reason for writing one of these properties, but as I collaborated on this question I realised that probably the primary use case I have for the above pattern using the ?? operator is enforced initialization. By forcing initialization of a property this way, it'll always be initialized the first time you access it. Meaning you don't have to worry about injecting an initial value into multiple constructors- which clutters them up on the one hand and also isn't reliable because you might forget to initialize in one of the constructors.

答:
One solution is to make the backing type nullable, and put a call to the Value property on the RHS:

```<code>private int? _operationCount;
public int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser()).Value;
</code>```

Here's a full working solution with a dummy implementation of the backing function:

```<code>using System;

public class Program
{
    public static void Main()
    {
        X x = new X();
        Console.WriteLine("Hello World " + x.OperationCount);
    }
}

class X
{
    private int? _operationCount;
    public int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser()).Value;
    private int GetOperationCountFromUser() => 38;
}
</code>```

Thanks to juharr's comment, the explanation for why this works is because the compiler converts nullable ?? expression to nullable.GetValueOrDefault(expresion) when nullable is a Nullable<T>. This explains why the RHS, the default, must be a primitive type, while the LHS is the nullable type.

Body:
Often when coding in C# I like to use this pattern for a lazy getter property:

private string _myProp;
string MyProp => _myProp ?? (_myProp = getMyProp());

I think this is pretty standard C# practice. The function getMyProp() is just some function that computes and returns a string. It is called just once to initialize the property, and henceforth it's cached. I can use this for any object type I like, not just string. However, when I try to do it for a primitive type like an int, I run into an issue. For example, if I try the following:

private int _operationCount;
int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser());

I get a compiler error here. It says:

Error CS0019  Operator '??' cannot be applied to operands of type 'int' and 'int'

I understand the error means that int is a primitive type, so we can't apply the null-checking operator to it, because an int is never null. But is there any way I can achieve what I want here? I'm looking for a solution with the following:

On the first access, the int property is initialized to the return value of the function call.

On subsequent accesses, the int property is retrieved from a loaded variable in memory i.e. the function is not called again.

Update: Why Write Properties Like This?

The original question just cited "laziness" as the reason for writing one of these properties, but as I collaborated on this question I realised that probably the primary use case I have for the above pattern using the ?? operator is enforced initialization. By forcing initialization of a property this way, it'll always be initialized the first time you access it. Meaning you don't have to worry about injecting an initial value into multiple constructors- which clutters them up on the one hand and also isn't reliable because you might forget to initialize in one of the constructors.

Body:
One solution is to make the backing type nullable, and put a call to the Value property on the RHS:

private int? _operationCount;
public int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser()).Value;

Here's a full working solution with a dummy implementation of the backing function:

using System;

public class Program
{
    public static void Main()
    {
        X x = new X();
        Console.WriteLine("Hello World " + x.OperationCount);
    }
}

class X
{
    private int? _operationCount;
    public int OperationCount => _operationCount ?? (_operationCount = GetOperationCountFromUser()).Value;
    private int GetOperationCountFromUser() => 38;
}

Thanks to juharr's comment, the explanation for why this works is because the compiler converts nullable ?? expression to nullable.GetValueOrDefault(expresion) when nullable is a Nullable<T>. This explains why the RHS, the default, must be a primitive type, while the LHS is the nullable type.


问:
Tmux, cron doesn't work with my python script on google clouds
so i am trying to run my python script 24/7 using google cloud machine, I want to use tmux and cron but i think i am doing something wrong and it doesn't work for me. When i run my script in SSH window it works perfectly but when i close it. It doesn't post to twitter or edit my json file.

I tried looking for answer in google but no luck for me.
I have tried using tmux and running my script with infinite loop and no lock.
I have tried using cron without infinite loop and run my script every 5 minutes and no luck.
I have tried using cron inside tmux and no luck.

import requests
import json
import time
import twitter

class TodayILearned():
    def __init__(self):
        self.link = 'https://www.reddit.com/r/todayilearned/new/.json'

    def get_info(self):
        try:
            r = requests.get(self.link, headers = {'User-agent': 'your bot 0.1'})
            r.raise_for_status()
        except requests.exceptions.HTTPError as error:
            print(f'There is problem:\n{error}')
            return False
        new_til = json.loads(r.content)
        new_til = new_til["data"]["children"][0]['data']['title']
        new_til = new_til.replace('TIL', '').replace('Til', '').strip()
        for _ in range(len(new_til) - 1):
            if new_til[0].isalpha() == False:
                new_til = new_til.replace(new_til[0], '').strip()#.capitalize()
            else:
                break
        new_til = new_til.split(' ', 1)
        if new_til[0].lower() == 'this' or new_til[0].lower() == 'that' or new_til[0].lower() == 'about' or new_til[0].lower() == 'of':
            new_til.pop(0)
        new_til = ' '.join(new_til)
        new_til = new_til[:1].upper() + new_til[1:]
        if new_til[-1].isalnum() == True:
            new_til += '.'
        return new_til if len(new_til) < 280 else False #change for 140 when twitter working

    def save_new_dict(self, new_dict):
        with open('til_news_base.json', 'w') as json_file:
            json.dump(new_dict, json_file, indent=2)

    def read_json_file(self):
        with open('til_news_base.json') as json_file:
            data = json.load(json_file)
        self.last_key = int(sorted(list(data.keys()))[-1])
        return data

    def post_on_twitter(self, new_post):
        TOKEN = 'xxx'
        TOKEN_KEY = 'xxx'
        CON_SEC = 'xxx'
        CON_SEC_KEY = 'xx'
        my_auth = twitter.OAuth(TOKEN,TOKEN_KEY,CON_SEC,CON_SEC_KEY)
        twit = twitter.Twitter(auth=my_auth)
        twit.statuses.update(status=new_post)

    def program(self):
        wait_for_seconds = 30
        while True:
            #first load the base from file
            dict_with_news = self.read_json_file()
            #second get new posts from reddit
            new_info = self.get_info()
            #check if new post in base or if is it last post
            if new_info != False:
                if new_info != dict_with_news[str(self.last_key)]:
                    dict_with_news[str(self.last_key + 1)] = new_info
                    print(new_info)
            #add to base if not
                    self.save_new_dict(dict_with_news)
            #print new TIL on twitter
                    self.post_on_twitter(new_info)
            #wait Xs
            time.sleep(wait_for_seconds)

def program():
    class_til = TodayILearned()
    class_til.program()

if __name__ == "__main__":
    program()
```

I want it to run every 5 minutes but no luck, it doesn't post new stuff to twitter after i close SSH.
after opening my SSH connection to google cloud i write:
tmux, change directory to place where my python file and json file is. i run my python script using python3. I can see in console my new news and i can see it on twitter. I am waiting for 5 minutes and every time new stuff is posted on reddit i can see it in my console and posted on twitter. I close my SSH and there are no new posts on twitter or in json file. I open SSH again and there are no errors or anything. I tried also cron: i used command '*/5 * * * * python 3 /python_programs/watch_for_new_TIL_facts.py'
without '' of course. and still no luck.
I tried this command in cron in tmux and without it. I have created stuff as normal user and as root.

答: In your crontab, you have a space between Python and 3. Eliminate it.

Body:
so i am trying to run my python script 24/7 using google cloud machine, I want to use tmux and cron but i think i am doing something wrong and it doesn't work for me. When i run my script in SSH window it works perfectly but when i close it. It doesn't post to twitter or edit my json file.

I tried looking for answer in google but no luck for me.
I have tried using tmux and running my script with infinite loop and no lock.
I have tried using cron without infinite loop and run my script every 5 minutes and no luck.
I have tried using cron inside tmux and no luck.

import requests
import json
import time
import twitter

class TodayILearned():
    def __init__(self):
        self.link = 'https://www.reddit.com/r/todayilearned/new/.json'

    def get_info(self):
        try:
            r = requests.get(self.link, headers = {'User-agent': 'your bot 0.1'})
            r.raise_for_status()
        except requests.exceptions.HTTPError as error:
            print(f'There is problem:\n{error}')
            return False
        new_til = json.loads(r.content)
        new_til = new_til["data"]["children"][0]['data']['title']
        new_til = new_til.replace('TIL', '').replace('Til', '').strip()
        for _ in range(len(new_til) - 1):
            if new_til[0].isalpha() == False:
                new_til = new_til.replace(new_til[0], '').strip()#.capitalize()
            else:
                break
        new_til = new_til.split(' ', 1)
        if new_til[0].lower() == 'this' or new_til[0].lower() == 'that' or new_til[0].lower() == 'about' or new_til[0].lower() == 'of':
            new_til.pop(0)
        new_til = ' '.join(new_til)
        new_til = new_til[:1].upper() + new_til[1:]
        if new_til[-1].isalnum() == True:
            new_til += '.'
        return new_til if len(new_til) < 280 else False #change for 140 when twitter working

    def save_new_dict(self, new_dict):
        with open('til_news_base.json', 'w') as json_file:
            json.dump(new_dict, json_file, indent=2)

    def read_json_file(self):
        with open('til_news_base.json') as json_file:
            data = json.load(json_file)
        self.last_key = int(sorted(list(data.keys()))[-1])
        return data

    def post_on_twitter(self, new_post):
        TOKEN = 'xxx'
        TOKEN_KEY = 'xxx'
        CON_SEC = 'xxx'
        CON_SEC_KEY = 'xx'
        my_auth = twitter.OAuth(TOKEN,TOKEN_KEY,CON_SEC,CON_SEC_KEY)
        twit = twitter.Twitter(auth=my_auth)
        twit.statuses.update(status=new_post)

    def program(self):
        wait_for_seconds = 30
        while True:
            #first load the base from file
            dict_with_news = self.read_json_file()
            #second get new posts from reddit
            new_info = self.get_info()
            #check if new post in base or if is it last post
            if new_info != False:
                if new_info != dict_with_news[str(self.last_key)]:
                    dict_with_news[str(self.last_key + 1)] = new_info
                    print(new_info)
            #add to base if not
                    self.save_new_dict(dict_with_news)
            #print new TIL on twitter
                    self.post_on_twitter(new_info)
            #wait Xs
            time.sleep(wait_for_seconds)

def program():
    class_til = TodayILearned()
    class_til.program()

if __name__ == "__main__":
    program()

I want it to run every 5 minutes but no luck, it doesn't post new stuff to twitter after i close SSH.
after opening my SSH connection to google cloud i write:
tmux, change directory to place where my python file and json file is. i run my python script using python3. I can see in console my new news and i can see it on twitter. I am waiting for 5 minutes and every time new stuff is posted on reddit i can see it in my console and posted on twitter. I close my SSH and there are no new posts on twitter or in json file. I open SSH again and there are no errors or anything. I tried also cron: i used command '*/5 * * * * python 3 /python_programs/watch_for_new_TIL_facts.py'
without '' of course. and still no luck.
I tried this command in cron in tmux and without it. I have created stuff as normal user and as root.


问:
How can I use different background images for different pages in a multipage form using Drupal?
I'm using the webform module with page breaks to display a large form. I would like to have different images for the background of each of these different form pages. Does anyone have a suggestion for how I could do this in Drupal?

Thanks in advance.

答: I figured out two ways to solve this. The first way was to use javascript to detect some pre-defined element on the page and based on the attributes of that element, add the background-image css to the div. The second way, and admittedly more drupal-like, is to add a preprocess function to the template.php file that accesses the form page number and puts a div around it with the number in it. Then you can just style that div. Thanks!</p>