Email user new link to create a password

Question: For Password Recovery my vb.net application send an email to the user with a link in the following format.
http://<password-reset page url>?id=<userid>&tpr=<times Password Reset>&time=<time when the link was generated>
Times Password Reset is the number of time the user has used a password reset link to reset the password. It's value in the database and the value in query string are matched. To ensure the same password reset link cannot be used twice to reset the password.
Time is use to check that not more than 24 hours have been passed before the link is used.
And userid is used to identify the user.
If all the conditions matches, the user is prompted to change his/her password.
All the fields in the in the encrypted with AES.
I wanted to know if this method is secure?
Answer: Quick answer: No.
Forget all the parameters you use in the URL. Just generate one random, non-guessable string (UUID for example) and put it in the URL as parameter. Then send that URL to the user via the email adress you have stored for him. Store the UUID together with all the parameters you have in your URL now in your database. When the user clicks the link, validate all parameters (timestamp, and so on) and let him set a new password.
Se also the OWASP Cheat Sheet on Password Reset.
Comment: This is actually a pretty good solution and i use it myself. +1


how to use messages with freemarker in spring mvc?

Question: In a .jsp I would use:
<fmt:message key="welcome.title"/>

to display a message from my messages.properties file.
How would I do this with freemarker ?
Answer: Import Spring Macro
<#import "/spring.ftl" as spring/>

Then
<@spring.message "yourMessageKeyGoesHere"/>

But you need to register ResourceBundleMessageSource
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages"/>
</bean>

Keep in mind MessageSource must be called messageSource
Comment: Does not work for me. Returns: "Template not found for name "spring"."
Comment: As I remember, You can import a template by default. @Blankman: you can refer to Freemarker documents.
Comment: Nice answer. Use ReloadableResourceBundleMessageSource if the property file is not on the classpath.
Comment: How it decides which property file (e.g. Locale) will be used?
Answer: @Blankman
No, you don't have to import this manually in each template. You can set an auto_import property in your freemarker settings as showed below.
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
   ...

   <property name="freemarkerSettings">
        <props>
            <prop key="auto_import">spring.ftl as spring</prop>
        </props>
   </property>
</bean>

Comment: i tried the same for spring.ftl via auto-import it gives `java.io.FileNotFoundException: Template spring.ftl not found`
Comment: Change to /spring.ftl /spring.ftl as spring
Answer: Others are fine answers.  Providing java config as example for those that use that.
 @Bean(name = "freemarkerConfig")
public FreeMarkerConfigurer freemarkerConfig() {
    FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
    configurer.setTemplateLoaderPaths("/WEB-INF/views/", 'classpath:/templates');
    Map<String, Object> map = new HashMap<>();
    map.put("xml_escape", new XmlEscape());
    configurer.setFreemarkerVariables(map)
    def settings = new Properties()
    settings['auto_import']  =  'spring.ftl as spring,layout/application.ftl as l,/macros/meh.ftl as meh'
    configurer.setFreemarkerSettings(settings)
    log.info "returning freemarker config"
    return configurer;
}


how to make whole div clickable?

Question: html-

some menu items here
jquery for mouser over on menu items-
function imgchange()
    {
        $('.smenu li').mouseover( function(){
        var src = $(this).find('a').attr('alt');
        $('.hbg').css('background-image', 'url(' + src + ')');
        $(this).find('hbg').attr('title', 'my tootip info');
        });
    }

I am changing the background image of hbg div through jquery on mouse over of menu items(ul li).but i want to bind(href) that div to particular page also so that when user clicks anywhere on div it should redirect to that binded page.as it is redirecting on clickin on  li items.
Is there any property in jquery where we can set the whole div as hyperlink?
Comment: I don't see an `href` in your markup, can you add that piece?
Answer: Here is how you bind a click handler to the div:
$('div.hbg').click(function(e) {
  alert('The div was clicked!');
});

And you probably also want to style it to look clickable:
div.hbg { cursor: pointer; }

Comment: +1 ... on a sidenote does anyone know why is this still showing up as "unanswered" when there is already a multiple upvoted answer?
Comment: @kekekela: "Answered" means there was an "accepted" answer by the OP (the green check mark appears)
Comment: @Neil - In this context, I don't think so.  When you click on the unanswered tab, it shows in the upper right the count of "questions with no upvoted answers", and you see most answers disappear off of this page and show only under the questions page once they have an upvote.  (sort both lists by recent to see what I mean)  This question for instance is no longer showing in the unanswered list even though the answer hasn't been accepted yet.  Maybe its just slow to update.
Answer: $('div.hbg').click(function(){location.href='http://www.google.com'});

You may want to change the mouse cursor so it looks clickable:
$('div.hbg').css('cursor','pointer');

Answer: try to give the div class a width and height and display: block;

how to make whole div clickable?


Bayesian Lasso standardized data application

Question: I am attempting to duplicate Belmonte et al. 2014. The paper applies a Bayesian Lasso to state space models to get better out of sample prediction. Bitto et al 2019 expands on this model. Their expansion includes a simulation study showing that the Bayesian Lasso shrinkage estimator recovered the true coefficients. Both papers, along with Park and Casella 2008, assume that the covariates are standardized mean zero and variance one. However, in most cases data we have is not standardized. How is it possible for data to first be standardized, then analyzed with a Bayesian Lasso and still recover the true DGP in a simulation study? Why is it when I standardize the variables the Bayesian Lasso returns the wrong coefficients and when I don't standardize it returns the right coefficients?
References:
Bitto et al 2019: https://www.sciencedirect.com/science/article/pii/S0304407618302070
Belmonte et al. 2014: https://onlinelibrary.wiley.com/doi/full/10.1002/for.2276
Park and Casella 2008: https://www.tandfonline.com/doi/abs/10.1198/016214508000000337
Answer: In a regression problem, you can have predictors with the most different scales. for example, you may have a predictor that ranges between 0 and 1 alongside another that ranges in the thousands, but still, the first one may be an index with a very strong influence on your outcome variable $y$, much more than the second one. You don't know in principle.
But, let's say they have an equal share of the predicted value $\hat y$. The variance of $\hat y$ can be decomposed (following this fundamental property of variance) in the quadratic form of the parameters $\hat \beta$ and the variance of the predictors.
This means that if we want our two predictors to contribute equally to the variability of $\hat y$, their parameters must be inversely proportional to the respective predictor st. deviation. If they only had equal variance, their parameter would have been the same value.
So, if you scale the predictors to have equal variance, their parameter will be proportional to the influence they have on $\hat y$ (more or less, collinearity also plays a role, but LASSO generally leaves out collinear predictors). But why is this so important for LASSO method?
Because LASSO applies a regularization on all the parameters of the model, which means from a bayesian perspective, that it applies a prior with the same scale on all the parameters. So for the model to make a sensible selection of the predictors, and a good shrinkage of the parameters, the predictors must have a scale proportional to their importance.
For all these reasons, if you don't have prior knowledge of which predictors have more or less effect on $\hat y$, you just scale all them to have equal variance, otherwise you may get a model dangerously biased towards higher-scale predictors.
Comment: While being a nice explanation, I wonder how this answers the actual question.
Comment: too bad! I read it wrong!


Approach for multimodal regression

Question: I am trying to solve a multimodal regression task.
I have two types of time series available.

Continuous data
One-hot encoded event data

Both time series are sparsely and irregularly sampled, with continous timestamps.
For each point in time, a target label is available.
I would like to find a way to create a joined embedding of both data types, ideally regularly sampled, so it can be used as input for a standard RNN-block.
So far, I was not able to find a good approach for this problem.
Answer: More information is needed, e.g., samples of both data types would help.
-Is the meaning of the target variable(s) the same for both?
-What are the unit(s) of the timestamps (hourly, daily, weekly...)?
-Is the one-hot encoding based on the same information as the continuous data, if not, how do they differ?
One approach to equilibrating disparate time series is to aggregate by timestamp and merge  based on time. This means taking disaggregated and irregular time series and aggregating them to a higher level, e.g., hourly time periods can be rolled up to daily, daily to weekly, etc.
Depending on how irregular the time series are, this may or may not regularize the information.
But in the absence of more information, this is speculation.

Approach for multimodal regression


How can I integrate pug templating engine in angular using angular cli?

Question: Currently I'm working on angular project that uses HTML. Now I want to integrate Pug templating engine in my project. How can I integrate Pug in my Angular project using AngularCLI? Any one can help?
Answer: For Angular8 you can run ng add firstname.lastname@example.com.
For Angular6+ run ng add ng-cli-pug-loader.
If your want to update old project to angular8, remove your node_modules and
reinstall all package.
ng-cli-pug-loader
Answer: As far as I know Angular uses its own html parser, looks like your task doens't make a sense. I don't see any reason to intergate pug there.


Trying to stub Server.MapPath with MvcContrib Test helpers and Rhino Mocks 3.5

Question: I'm using MvcContrib's test helpers and Rhino Mocks 3.5 to test an ASP.NET MVC action method. I build my fake controller like so:
var _builder = new TestControllerBuilder();
_builder.InitializeController(_controller);

So I get a fake controller that contains fake HTTP Server etc.
I'm then trying to stub the Server.MapPath method like so
controller.Server.Stub(x => x.MapPath(Arg<string>.Is.Anything)).Return("/APP_DATA/Files/");

but in my method under test the call to Server.MapPath("/APP_DATA/Files/") returns null.
This is the test
    const string STOCK_NUMBER_ID = "1";
    const string FULL_FILE_PATH = "App-Data/Files";

    var controller = CreateStockController();
    _uploadedFileTransformer.Stub(x => x.ImageBytes).Return(new byte[10]);
    _uploadedFileTransformer.Stub(x => x.ConvertFileToBytes(FULL_FILE_PATH)).Return(true);

    controller.Server.Stub(x => x.MapPath(Arg<string>.Is.Anything)).Return("/App_Data/Files/");

    controller.AddImage(Guid.NewGuid(), STOCK_NUMBER_ID);

What I am missing?
Comment: Could we see the test?  Looks like a possible missing repository.Playback().
Comment: I've added the test to the OP. I didn't think we needed to use record and playback in Rhino Mocks v3.5 - am I wrong?
Comment: Could you also paste `CreateStockController()`? I am not familiar with test helper you are using, but where is controller.Server created?
Comment: Good point, in fact after further investigation I find its not being created. How would I create it and have appear as part of my fake controller? Is it possible? I'm wondering why the MvcContrib Testhelpers don't already do it.
Comment: Record/Playback is not REQUIRED, but some people still use it.  Frequently, they do a record(), but forget to execute the playback() and their stubs/mocks don't work.  However, I just did a test on a sample MVC project using MVCContrib and I'm seeing the same thing -- the controller.Server is a Rhino.Mocks proxy, but the MapPath stub isn't working.  I'm going to play around and see what is happening.
Answer: Old post but I was searching for this and I found a solution, MvcContrib's TestHelper probably got it fixed because for me it's working.
_builder.HttpContext.Server.Stub(s => s.MapPath("~/" + filepath)).Repeat.Once().Return(mapedPath);

Answer: Looks like this is a bug in MVCContrib (at least with what I have on my machine -- v22.214.171.124).  When setting up the controller context, it's using Rhino.Mocks record/replay mode, but (and this is the bug), it doesn't put the HttpServer mock into replay mode.  It puts everything else in replay mode but not that one.
So a quick fix is to do:
controller.Server.Replay();

As part of your "arrange" section of your test.  Then it works fine.
Comment: Patrick, I tried what you suggested, I added controller.Server.Replay() but I still have the same problem. I'm using MvcContrib v22.214.171.124 with MVC2. I seem to have ages on this problem so in the end I added a HTTPServerUtilityBase parameter to my action method and created a custom model binder which provides me with a Server object. Then in my test I created my own stub of HttpServerUtilityBase and stubbed out the MapPath method. Its all working nicely but I would have preferred that the TestHelper provide me with the correct stub in the first place.
Comment: Ok.  The sample project I tried it on was MVC1.  Looks like the bug still exists in MVC2.  Should be easy to fork the code from CodePlex, fix and submit.  Glad you got it working!


My class function is performed twice

Question: <?php
  /*
  * class: C_QUESTION_MULTIPLE_CHOICE_SINGLE_ANSWER
  * properties:
  * functions:
  */

  class C_QUESTION_MULTIPLE_CHOICE_SINGLE_ANSWER extends C_QUESTION {
    protected $q_type = 'T_MULTIPLE_CHOICE_SINGLE_ANSWER';

    protected $q_type_info;
    /*
    * $choices:
    * choices['A'] = array(answer = 'Y', description = '')
    * choices['B'] = array(answer = 'N', description = '')
    */
    protected $choices;

    public $output_info = '';
    public $count = 0;

    function __construct($q_content, $option = 'load') {
        // call parent's construct function to handle question base class information
        // in parent construct function, it will call parent's load or save function by itself.

        parent::__construct($q_content, $option);
        if (! $this->op_status) {
            // call function failed
            return;
        }

        // handle multiple choice part
        switch ($option) {
            case 'save':
            // $option = false, don't call parent::save() function
            // parent construct function will call parent save function
              $this->save($q_content, false);
              break;
        }
    } // end of construct function

    function save($q_content, $option = true) {
        $this->count++;
        $this->output_info .= '
'.$this->count.'
';
    } // end of save function

  }

In the above code, the sub-class function save is performed twice. If I don't call parent construct function:
/* don't call parent construct function
        parent::__construct($q_content, $option);
        if (! $this->op_status) {
            // call function failed
            return;
        }
*/

The function save() will be performed once.
In the parent construct function, the parent class QUESTION will cal it's own save() function. The sub-class C_QUESTION_MULTIPLE_CHOICE_SINGLE_ANSWER override the parent function save(). So in the sub-class construction function, I manually call parent::__construct() function. But I don't why the sub-class save() function is called twice. I debug this by sub-class properties
public $output_info = '';
public $count = 0;
Please help me.
Thanks a lot.
=========================================================================================
I debuged several times after post the above question, found:
parent class QUESTION: __construct() function:
function __construct($q_content, $option = 'load') {
    // set the operation status to true. If this operation fails, this will be set to false
    $this->op_status = true;
switch ($option) {
    case 'load':
      if (!$q_content['qid']) {
        $this->op_status = false;
        drupal_set_message(t('question id :qid not exist. Please contact site administrator!', array(':qid' => $q_content['qid'])), 'error');

        break;
      }

      $this->basic['qid'] = $this->extra['qid'] = $q_content['qid'];
      $this->load($this->basic['qid']);

      break;

    case 'save':
      **//$this->save($q_content);
      self::save($q_content);**

      break;
}

}
if I use $this->save to call parent itself save function, this statement not only call parent::save function, but also will call sub class::save function. It's very funny and confuse.
If I use self::save statement in the parent class QUESTION, then it won't call sub class::save function.
My question is, since I've already overrided parent::save function in the sub class, I should call parent::save, then call $this->save in the sub-class do something for subclass. Why when I call parent::save, it will perform both parent::save and sub-class::save. It really confuse me.
I tried to find answer in the php manual and internet, but I didn't find the relevant article can make me clear. They only say, self::function() is used for the static member function, and $this->function() is used for other member and function. But my function and member are not static. Or the default function and member are static?
Really appreciate for who can help me.
Thanks a lot.
Answer: In php OOP, $this-> referrer to the current instant of the class, whereas self:: referrer to the class where self:: is declared.self:: is also use to referrer to static functions and properties.
So, in your case, you have to change the call to your parent's save() function as self::save() within the parent's construct function.
Also, within your child class, you can call $this->save() to call the save function of the child, because you are overriding the parent's save function.you can also use self::save() within the child class.if you want to call parent's save function from a child class then you can use parent::save() in your child class.
No, default functions aren't static.to make them static you have to add static keyword in front of the function declaration.note that you can't declare __construct(),__deconstruct() as static.
Since your functions aren't static, when you referrer to them as self:: you are referring to the current class.it's called Scope Resolution Operator (::). also read this SO answer
Comment: It's really confuse. Say, if I use $this->save in the parent construction function, when I call parent::__construct function, it will perform parent::save and child class::save function. What I expect is when I call parent::__construct function, it only perform parent::save function.
Comment: @user28506 If you use `$this->save()` in parent's construct and when you call it as `parent::__construct()` it should only call the overridden method(child's method).can you update the post with the codes you are using to initialize the class and invoke those methods ? also make sure to update the codes of classes to reflect what you have now.

My class function is performed twice


Multivariate biological time series : VAR and seasonality

Question: I have a multivariate time series dataset including interacting biological and environmental variables (plus possibly some exogenous variables). Beside seasonality, there is no clear long-term trend in the data. My purpose is to see which variables are related to each other. Forecasting is not really looked for.
Being new to time-series analysis, I read several references. As far as I understand, Vector Autoregressive (VAR) model would be appropriate, but I don't feel comfortable with seasonality and most examples I found concerned economics field (as often with time series analysis…) without seasonality.
What should I do with my seasonal data?
I considered deseasonalizing them – for example in R, I would use decompose and then use the $trend + $rand values to obtain a signal which appears pretty stationary (as judged per acf).
Results of the VAR model are confusing me (a 1-lag model is selected while I would have intuitively expected more, and only coefficients for autoregression – and not for regression with other lagged variables - are significant).
Am I doing anything wrong, or should I conclude that my variables are not (linearly) related / my model is not the good one (subsidiary question: is there a non-linear equivalent to VAR?).
[Alternatively, I read I could probably use dummy seasonal variables, though I can't figure out exactly how to implement it].
Step-by-step suggestions would be very appreciated, since details for experienced users might actually be informative to me (and R code snippets or links towards concrete examples are very welcome, of course).
Comment: What about a multivariate ARMA model? It's similar to VAR, but if I understand correctly, permits more dynamical interaction between variables. Someone else may be able to confirm/ reject my suspicion.
Comment: Much depends on how you think about seasonality. My patchy reading of the literature indicates that economists often regard seasonality as an uninteresting nuisance while environmental scientists often feel much more positive about it. The method of dummy variables as used in economics hinges, frequently, on data being quarterly or monthly and effects of holidays (in every sense of the word) being sometimes spikey; witn environmental data you can sometimes do well with some Fourier (sinusoidal) terms and need not resort to dummies.
Comment: Thanks, @Nick Cox. Fourier terms do not appear to be a solution in my particular case, where variables show more complicated seasonal pattern than sinusoidal signals (unless I use several harmonics, but this is not so much the purpose here). And despite seasonality is clearly not an uninteresting nuisance term in my case, I was more looking for something helping me to explain the extra variability in the data beyond seasonality (i.e., the longer-term trend) as a function of other variables.
Answer: I know this question is pretty much old but it remained unanswered. Perhaps the main question is not how to remove the seasonal cycle in the data but it is part of it, so I'll give it a try: To remove seasonality from a data set there are several methods, from simple monthly-aggregated averages to fitting a sinusoidal (or another appropriate harmonic) function with non-linear fitting methods like Nelder-Mead.
The easiest way is to average data belonging to all Januaries, to all Februaries, and so on, i.e., you create a composited annual cycle, which then you can subtract from your data


Number of 4x4 matrices such sum of all rows and columns is zero.

Question: The number of matrices $A = [a_{ji}], 1 \le i,j \le 4$ such that $a_{ij} = +- 1$ and $\sum_{i = 1}^{4}a_{ij} = \sum_{j=1}^{4}a_{ij} = 0$ is...
I solved it by first selecting two values of "i" which is $\binom{4}{2}$ and two values of "j" similarly. Now if I fill thes four positions by 1, the value of remaining positions also get fixed because sum of all rows and columns is zero. So answer should be 36 $(\binom{4}{2}\times \binom{4}{2})$but the correct answer is 90.
Why this method is wrong and what is the correct way of solving this?
Answer: You are both over-counting and under-counting!
First, you are over-counting:
Suppose you first pick $i=1,2$ and $j=1,2$. So, $a_{11}$, $a_{12}$, $a_{21}$, and  $a_{22}$ are all set to $1$. But that forces  $a_{33}$, $a_{34}$, $a_{43}$, and  $a_{44}$ to be a $1$ as well.
OK, but now start with $i=3,4$ and $j=3,4$. Then $a_{33}$, $a_{34}$, $a_{43}$, and  $a_{44}$ are a $1$. But that forces $a_{11}$, $a_{12}$, $a_{21}$, and  $a_{22} $ to $1$. So, you get the exact same matrix.
But, you are also under-counting, since it is not true that there must be two row with the same entries being a $1$. Consider:
$$\begin{bmatrix}
1& 1 &-1 & -1 \\
 -1& 1 &1 & -1 \\
-1& -1 &1 & 1 \\
1& -1 &-1 & 1 \\
\end{bmatrix}$$
OK, here's how you can get them all.
First, pick two entries from the first column that are a $1$
Then, for the second row, you have the following possibilities:
$A$. Pick the exact same entries.  That can be done in one way only, and it forces the rest of the matrix, so $ 1$ possibility
$B$. Pick the 'opposite' entries (example, if you picked entries $1$ and $2$ for row $1$, pick $3$ and $4$ for row $2$). That can also only be done in one way. Now, notice that for the third row, since rows $1$ and $2$ do not share any entries, you can still pick any two entries from row $3$, so $6$ possibilities for that one. Of course, after row $3$ is done, row $4$ is forced, so option $B$ leads to a total of $6$ possibilities
C. Row $2$ shares one entry with row $1$, which can be done in $4$ ways ($2$ choices for the shared entry, and $2$ for the other two entries. (Example: if the entries for row $1$ are $1$ and $2$, then for row $2$ we can pick $1$ and $3$, $1$ and $4$, $2$ and $3$, and $2$ and $4$)). Then for row $3$, you cannot use the shared entry from rows $1$ and $2$, but you have to pick the one non-shared entry, and then one out of the remaining $2$ entries, so $2$ options there  (Example, if you picked entries $1$ and $2$ for row $1$, and entries $1$ and $3$ for row $2$, then the entries for row $3$ can only be $2$ and $4$ or $3$ and $4$)
And again, since row $4$ is now fixed, option $C$ gives $4\cdot 2 = 8$ possibilities.
Finally, since there were $6$ ways to pick the first two entries for row $1$, that gives $6 \cdot(1 + 6 + 8) = 90$ possibilities
Answer: You are counting it wrong,you only count some of teh matrices.
What do you mean by picking 2 values for $i$ and two for $j$?
To understand the problem, consider this matrix
$$\begin{bmatrix}
-1& 1 &-1 & 1 \\
 -1& -1 &1 & 1 \\
1& -1 &1 & -1 \\
1& 1 &-1 & -1 \\
\end{bmatrix}$$
Which are the two $i$'s and 2 $j$'s which give this matrix?
Comment: Ok, I got that my method is wrong but how to solve it?


cURL, cat, python and missing parts from a web page

Question: I have downloaded a web page(charset=iso-8859-1) using curl
curl "webpage_URL" > site.txt

The encoding of my terminal is utf-8. Here I try to see the encoding of this file:
file -i site.txt
site.txt: regular file

Now: the strange thing: If I open the file with nano I find all the words that are visible in a normal browser. BUT when I use:
cat site.txt

some words are missing. This fact makes me curious and after some hours of research I didn't figure out why.
In python too, it does't find all the words:
def function(url):
   p = subprocess.Popen(["curl", url], stdout=subprocess.PIPE)
   output, err = p.communicate()
   print output
   soup=BeautifulSoup(output)
   return soup.body.find_all(text=re.compile('common_word'))

I also tried to use urllib2 but I had no success.
What am I doing wrong?
Comment: have you tried cat -A file.txt ?
Comment: It works with `cat -v site.txt`
Comment: I wrote `cat -v` instead of `cat -A` because, at least my version of cat doesn't have the `-A` option.
Comment: yes, looked like that could be solved using cat options :)
Best Regards!
Answer: If somebody will face the same problem:
The root of my problem were some carriage return characters (\r) that are present in the web page. The terminal cannot print them. This wouldn't be a big problem, but the whole line that contains a \r is skipped.
So, in order to see the content of the entire file: this characters should be escaped with the -v or -e  option:
cat -v site.txt

(thanks to MendiuSolves who has suggested to use the cat command options)
In order to solve a part of the python problem: I changed the return value from soup.body.find_all(text=re.compile('common_word')) to soup.find_all(text=re.compile('common_word'))
It is obvious that if the word you search for is on one of the line containing a \r and you will print it you will not see the result. The solution could be either filter the character or write the content in a file.


Remove Cached UNC URL Credentials Win 10/Server 2012

Question: I need to remove the UNC\URL credentials of a share accessed via IP UNC\URL from File Explorer.  For example, last week I logged into 10.10.10.20\someshare, and now, when I go to it, I do not have to put in name and password.  Here are the things I have done that do not work:
<code>net use (does not display anything)
net use * /d (returns, but no change)
Net use \\10.10.10.20\someshare /d (network connection could not be found)
net use \\10.10.10.20\ipc$ /d (network connection could not be found)
I restarted explorer.exe after those commands
I ran klist purge after those commands
I checked the Credential Manager (nothing)
*update* I checked Stored User Names and Passwords (nothing)
I looked in the registry for the IP (since this lasts through reboots) but there was nothing
</code>
Even after all those things AND restarting computers, the share comes right up, with no prompts, when typed in File Explorer.  Any ideas?  This makes troubleshooting very difficult.  Also, you cannot log in with different credentials.  Finally, I do not want this behavior, as I have a requirement to have users supply the credentials each time.
Comment: Usually Windows will put saved credentials in the Credential Manager in the Control Panel
Comment: As stated, there are no entries in the Credential Manager.
Comment: Sorry, the notes indicating you had checked the credential manager were in code text box. Do you still get prompted from other workstations that might not have already logged on? What kind of network share is this?
Comment: Yes, if I log in at some other workstation, the first time, taking care NOT to save credentials, I will have to supply credentials.  After that, I go right in.  This is a standard Windows network share, with it's own share name and password - i.e., not AD.  Your question has prompted me to think - what if I made a second share, with different credentials?  I will report back.
Answer: This information windows save in registry.
Press Win+R to bring up the Run dialog box. Type regedit and hit Enter.
For windows 8

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths

For windows server 2012 is more complicated

[HKEY_USERS\S-1-5-21---****-500\Software\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths]
Comment: start-->run--> rundll32.exe keymgr.dll, KRShowKeyMgr
Comment: Removing these entries has no effect.  I still go right in, it just doesn't autofill the UNC\URL bar.  The desired objective is to **not** automatically access the share, but to be forced to use name and password each time.
Comment: There are no entries in Stored User Names and Passwords.
Answer: If you have already removed all instances of saved credentials and you are still able to connect to a share without providing explicit credentials, I believe there are two possibilities:

Your share is allowing anonymous/guest connections
You are logged into your workstation with credentials that are valid for the share and Windows is just passing through your credentials automatically. This could be either domain credentials or even local credentials that just happen to have the same username/password as an account on the fileserver.
Comment: The share is not allowing anonymous logins.  I am prompted for passwords from other Win 10 systems (which are then promptly cached, somewhere, on the disk and are never requested again.)  Neither the workstation (Computer)  nor the User objects have been granted permissions to the share.


Job Application

Question: I have a content type called "Job", that has fields for the job and an email field for the job contact. At the bottom of each job node  there should be a button "apply now". If you click on the button, there should be a form with textfields, file upload (for the resumee) etc. If you send your application, an email should be sent to the job contact email (which is inside the job node).
What is the best way to achieve this? First I was thinking about using webforms, but I don't know how to get the job contact email form the node as the sendto webform email.
Answer: You can create two content types

Job
Job Application

In Job Application, where you have resume upload etc, add a entity reference field to Job content type.
Then when you list the Job and add a link Apply Now to create Job Application.
Use Entity Refernce Prepopulate module to prepopulate the entity reference in Job Applciation based on URL.
Here is good video tutorial expaining Enity Reference Prepopualte module.
Answer: That's one of the default webform behaviours. Create and save the webform. Then, within the node/%nid/edit page, go to Webform > Emails and fill in your email there. There's no need to have the email as a separate field on the node.
Comment: But the email is different for each node. The user should enter the email but the user should not need to enter his email within the webform (or ever have to create the webform manually).
Comment: ok, in that case, use @wolverine's solution.

Job Application


How are these column vectors linearly independent?

Question: I know that the column vector is the column of numbers and that there are 5 of them in this example:

But I don't see how they are linearly independent (i.e. the only scalar solution is 0),. What is going on here?

Is this right?
$$c1 * \begin{bmatrix} 1 & 0 & 0 & 0 & 0 \end{bmatrix} + c2 * \begin{bmatrix} 3 & 1 & 0 & 0 & 0 \end{bmatrix} + c4 * \begin{bmatrix} 3 & 0 & 1 & 0 & 0 \end{bmatrix}$$
So if linearly independent than $$c_1v1 + c_2v2 + c_4v4 = (0,0,0)$$
So the set of equations that can be created is:
$$c_1 + 3c_3 + 3c_4 = 0$$
$$c_2 = 0$$
$$c_3 = 0$$
So the only solution for the scalars is trivial? Is this the right way to show linear independence?
Answer: The author tells you that $a_3 = -2 a_1 + a_2$ and $b_3 = -2 b_1 + b_2$ so $(a_1, a_2, a_3) $ and $(b_1, b_2, b_3)$  are linearly dependent.
However, $(b_1, b_2, b_4)$ are linearly independent as there doesn't exist $(\lambda, \mu, \rho)\neq 0_{\mathbb{R}^3}, \lambda b_1 + \mu b_2 + \rho b_3 = 0_{\mathbb{R}^5}$.
You can see it quickly by analysing the components of $b_1 = 1 e_1$, so $\lambda e_1 + 3 \mu e_1 + \mu e_2 + 3 \rho e_1 + \rho e_3=0$.
We can rewrite to be understood easier as : $(\lambda + 3\mu+3\rho,\mu,\rho,0,0)=(0,0,0,0,0)$
The component in front of $e_3$ must be zero, therefore $\rho = 0$. However, the component in front of $e_2$ must be zero $\mu = 0$. Finally, you need the component in front of $e_1$ to be zero, therefore $\lambda = 0$, so they are linearly independent.
Comment: @Jwan622 Yes, you made the same thing as what I wrote.
Comment: I made an edit to my post... is it the same thing?
Comment: @Jwan622 This is the right way to prove linear independance. There are harder ways, but you'll find out about it later.
Comment: Are b2 b3 and b4 linearly independent as well? What's a quick way to show this?
Comment: You wrote pb3, should it be pb4?
Comment: @Jwan622 Use the same method as I used. It's not really hard nor long.


É comum ter vários servidores diferentes para uma mesma aplicação web?

Question: Cenário:
Estou começando a participar do desenvolvimento de uma aplicação web. Essa aplicação ainda não está disponível "online", ou seja, só temos ela aqui no servidor de testes onde temos, na mesma máquina, instalado o Redis, SQL Server, IIS, entre outras coisas.
Vamos começar a testar essa aplicação online, ou seja, queremos publicar esta aplicação para que possamos testar a nível de usuário final.
Procuramos algumas hospedagens, etc. E acabei me deparando com o seguinte problema: Não encontrei nenhuma hospedagem que tenha tudo o que preciso. Então, acabei 'distribuindo' a aplicação em três hospedagens diferentes, digo, uso a hospedagem A para deixar o meu banco de dados SQL Server, na hospedagem B fica o Redis e na hospedagem C fica a aplicação ASP.NET que acessa estes bancos de dados.
Como sempre trabalhei com aplicações desktop e o contato web que tive foi de aplicações interna onde tudo (Redis, SQL Server, Aplicação ASP.NET) fica na mesma máquina, isso acaba me parecendo meio estranho.
Dúvida:
Essa é uma abordagem comumente usada? Manter cada coisa em um servidor diferente pode me trazer algum tipo de problema?
Comment: Uma coisa importante a considerar é que se recomenda pra grandes aplicações ou escalabilidade é ter o DB em MÁQUINA diferente. Só que não pode confundir isso com DB em REDE diferente. Em rede diferente, a perda pode não compensar a suposta melhor performance do DB. Principalmente se a rede for a própria internet. Além disso, quem acessa o DB é o servidor da aplicação, e não o cliente. Então não existe a vantagem do paralelismo que se ouve falar quando se usa uma CDN pra imagens e JS, por exemplo.
Comment: nesse caso eu acho que perderia performasse, é muito mais rápido o site recolher o conteúdo do próprio servidor do que de outro, e como você quer usar 3 servidores, isso aumentaria 2 solicitações para o usuário poder acessar o conteúdo da página. Na minha opinião isso não é nenhum pouco viável nesse caso.
Comment: Não tem nada de mais. O problema que pode ter é o custo. Se usasse tecnologias que pudessem ser aproveitadas num único ambiente, poderia reduzir o custos drasticamente e simplificar tudo num único servidor. Mas isso tudo também depende do volume de tráfego esperado. Se for um volume alto, é melhor manter da forma como está fazendo, em servidores separados e então vai incrementando com mirrors/load balance, etc. Resumindo, o ponto que deve se preocupar mais é o volume de tráfego. Caso tenha sempre um volume baixo, não compensa toda essa estrutura. Estaria jogando dinheiro no ralo.
Comment: Alguns sites tem vários servidores, tanto que a cada período de tempo o **ip** do ping muda. exemplo o Google.
Comment: Sim, mas eu quis dizer especificamente nesse caso. Onde manterei o SQL Server em um, o Redis em outro e a aplicação em outro.
Comment: @BrumazziD.B. Nesse caso não tem perda de performance, pelo contrário. É comum ter servidores com "balanceamento de carga" onde apontam para servidores diferentes, replicações, etc. Não aumentaria as requisições, elas serão feitas do mesmo jeito, o que muda é o caminho.
Answer:
Essa é uma abordagem comumente usada?

Comum não é. É um pouco extravagante, mas não é errada.

Manter cada coisa em um servidor diferente pode me trazer algum tipo de problema?

Os problemas estão mais relacionados com a complexidade da sua contingência. A escolha de não deixar tudo centralizado pode ou não ser um bônus de performance. Também há a questão da qualidade de cada serviço, a complexidade da administração deles e alguma coisa envolvendo custos. Em resumo, a divisão pode ser tanto uma vantagem quanto uma desvantagem.
Por exemplo, se seu servidor Redis cair, sua aplicação não necessariamente deixará de funcionar, principalmente se o Redis for usado como cache de segundo nível da sua aplicação. Agora, se seu SQL Server cair, mesmo com o Redis funcionando, você derrubará a aplicação mesmo com os outros serviços funcionando. A contingência é muito mais fácil de administrar quando centralizada.
Por outro lado, estabelecer essa divisão cria uma forma interessante de paralelismo. A carga de trabalho fica dividida em três lugares diferentes, que pode ser convertida em ganho de performance.
Answer: Estou respondendo baseado no que foi perguntado. Está falando de ter servidores em hospedagens diferentes. As outras respostas dizem coisas que fazem sentido em uma hospedagem com servidores diferentes. Elas estão corretas para o cenário que resolveram responder, não para o cenário da pergunta.
Pra mim a pergunta deixa claro que a separação só está ocorrendo porque não encontraram um lugar que fornecesse tudo junto.

Depende do que considera normal. A maioria dos sites são muito simples e precisam de um estrutura bem simples. Por exemplo, é raro o site que precisa de Redis de fato.
É muito raro encontrar alguma hospedagem que oferece SQL Server e não ASP.NET. Muitas oferecem os dois e o Redis (que tenho dúvidas ser necessário).
Esta estrutura até funciona, mas gerará tráfego entre as hospedagens, gerando custos, o que não é o ideal e vai aumentar a bastante a latência de resposta do site. Quanto mais volume de acesso tiver, mais terá dificuldade em lidar com uma estrutura totalmente descentralizada.
Não há como ter melhor performance por ter serviços que são dependentes um do outro em locais físicos diferentes. Isto só gerará maior latência, sem nenhum ganho.
Sem dúvida o fato de ter a carga distribuída pode dar melhor performance que ter tudo em um servidor só, mas só se o servidor estiver sobrecarregado, caso contrário só agregará latência sem nenhum ganho. Só medindo para ter certeza quando se deve separar servidores.
Se a opção for ter servidores separados na mesma rede, aí o ganho pode ser mais interessante, mas só nos casos de grande volume de acesso. Se a carga é pequena, adicionar servidores com serviços dependentes entre si, ainda que na mesma rede, certamente adicionará latência, mas pequena e aceitável porque o volume exige isto.
Existe ainda uma possibilidade de se usar datacenters diferentes para aumentar o tempo de disponibilidade, afinal um datacenter pode sair do ar. Mas se fizer isto, deverá ter cópia total de todos os componentes nos dois datacenters. Ou seja, terá um ou mais servidores em cada um deles contendo os 3 serviços relatados: SQL Server, Redis, ASP.NET (provavelmente um IIS).
Mesmo se for pensar em distribuição de carga, isto tem que ser um trabalho de engenharia, não um acidente de percurso.
Possível é, mas não recomendaria fazer, é mais complexo e mais custoso.
Procure um local que atenda todas necessidades. O Azure, só para citar um exemplo, atende.
Você pode pegar uma instância onde pode colocar os 3 serviços juntos ou pode contratar os serviços separados (em geral fica bem mais caro).
Este site, por exemplo, que é um exemplo de site de altíssimo volume que tem seus próprios servidores e organizam sua estrutura de acordo com sua necessidade, eles só usam um segundo datacenter como espelho da estrutura regular, não separam cada serviço em uma hospedagem diferente. Eles separam os serviços em servidores diferentes porque este é um dos sites mais acessados do mundo.
A sua necessidade é parecida com a do Stack Overflow? Se não, vá pelo simples. Vá pelo que está acostumado. Só crie complexidade no sistema quando a necessidade surgir.
Coloquei no GitHub para referência futura.
Answer:
Irei basear minha premissa em que não existe diferença entre qualidade de serviço entre as hospedagens contratadas. Me refiro a diferença de qualidade entre hospedagens que existe.
Para essa resposta, irei idealizar que são todas iguais.

Esse caso não é tão diferente quanto você imagina. Pode ser não visível, mas é comum sim. Não entre os três que citou, mas geralmente entre o servidor de banco de dados e o da aplicação.
Mesmo que você contrate um único host, não garante que tudo que irá colocar estará em um único servidor, e é o que geralmente acontece.
Ao configurar o banco de dados, aplicação e o redis você irá apontar o local, que um host te dá os dados de acesso, mas não tem certeza que serão no mesmo servidor. Hosts diferentes são apenas servidores diferentes (isso não levando em consideração a qualidade de cada um).
Existem alguns pontos em relação em separar os serviços em hosts diferentes, que são:
Segurança
Seu servidor WEB fica disponível para usuários anônimos, levando em consideração que algo não está como deveria, você deixa seu banco de dados e demais informações insegura, por alguma falhar de segurança.
E levamos em consideração que se algum dos hosts for "acessado externamente", você terá um tempo para se prevenir antes de chegar aos demais.
Performance
Caso seja configurado corretamente, você não terá perda de performance, pelo contrário. Você é obrigado a fazer as requisições, independente se estiver em um host ou não. Grandes empresas como o Google, Facebook e o StackOverFlow utilizam servidores diferenciados, justamente por questões de performance, dentre outras.
É muito comum ver em grandes empresas um host apenas para balanceamento de carga, o que ajuda a manter o serviço online (claro, isso geralmente é implícito, mas acontece).
Escalabilidade
Uma das maiores dificuldades hoje é escalar o hardware necessário para o sistema funcionar. Separando em hosts, você consegue fazer uma diferenciação melhor de onde está o gargalo e se precisa ou não alterar as configurações de hardware.
UPTIME
Como o @CiganoMorrisonMendez disse em sua resposta, você consegue manter sua aplicação funcionando mesmo se um algum desses hosts caírem (exceto o da aplicação, logicamente).
Hoje você possui ferramentas para cachear seu sistema e garantir uma funcionalidade quase que independentes, utilizando alguns recursos para salvar os dados caso o host do banco pare de funcionar. Claro, você precisa preparar sua aplicação para isso, mas é possível.
Custos
Separar seu sistema em hospedagens diferentes, gera custos elevados em seus serviços, o que pode gerar problemas para muitos.
Complexidade
A dificuldade de se manter três hospedagens é maior do que uma centralizada. Isso irá gerar uma complexidade maior para manter a aplicação em funcionamento.
Uma má configuração desses recursos poderá gerar mau funcionamento da aplicação e/ou perda de performance, como muitos dizem.
Referências:

Why is it not advisable to have the database and web server on the same machine?
Stackchange Performance
How to host a single website on multiple servers?
Autoscale - Facebook
Balanceamento de Carga


Good designing of gRPC status and response

Question: As a server side who provide gRPC API of calling some services, which is the reasonable way to return the service have succeed or not?
Case 1. Return as a Response
The server returns success or failure as a response message.
// message Succeed{ bool value = 1; }
// rpc DoJob(google.protobuf.Empty) returns (Succeed) {}

Status Impl::DoJob(ServerContext* context,
  const Empty* request, Succeed* response) {

  bool success = service_.job();
  response->set_value(success);

  return Status::OK;
}

Case 2. Return as a Status Code
The server returns success or failure as a status code.
// rpc DoJob(google.protobuf.Empty) returns (google.protobuf.Empty) {}

Status Impl::DoJob(ServerContext* context,
  const Empty* request, Empty* response) {

  bool success = service_.job();

  if (success) return Status::OK
  return Status::CANCELLED;
}

As a client using the gRPC API, which case is easier to understand? Should Status code only indicate network status? Any advice is appreciated.
Answer: Status is intended to be used by services to communicate error or success.
gRPC uses a single combined status for network and service errors to simplify error handling on the client-side. If your service returns UNAVAILABLE because one of its dependencies is down, the client will treat that the same as UNAVAILABLE because your service is down (which is a dependency of the client).
Some of the status codes are even reserved for services to use:

INVALID_ARGUMENT
NOT_FOUND
ALREADY_EXISTS
FAILED_PRECONDITION
ABORTED
OUT_OF_RANGE
DATA_LOSS


Collecting CheckPoint Firewall Rules using OPSEC API

Question: I need to collect Firewall Rules data belonging to my client remotely using OPSEC API. I researched a little bit on the net and found out that I could use OPSEC API's LEA(Log Export API)(more info: https://www.fir3net.com/Firewalls/Check-Point/a-quick-guide-to-checkpoints-opsec-lea.html). I also found out that there is a project named fw1-lograbber (https://github.com/certego/fw1-loggrabber). I am quite new to network security and practically do not know anything about CheckPoint Firewalls. So my question is a brief explanation on the basics of Firewall Rules for CheckPoint and how to collect them using OPSEC API. More specifically are the rules included in the checkpoint logs or is there a specific method in LEA to grab the rules?
Thank you all!
Answer: To collect firewall rules you can't use LEA, this API is able to work with CheckPoint logs.
To read rules and objects you need to use CPMI API. There are some samples at CheckPoint website, ask for your customer to download the documentation and sample.
CheckPoint OPSEC Documentation: https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk63026
Comment: Try to parse $FWDIR\rulebases_5_0.fws (rule database) and $FWDIR\objects_5_0.c database file.

The CPMI API it's hard to implement. If you want to read information, try parsing this files. If want to write, use the CPMI API.
Comment: Thank you very much! Here all the object types are specified, do you know explicitly how to collect the rule objects? Thanks again!


dotvvm: Auto play video list (presentation)

Question: I like to build a Video presentation website with dotvvm.
when nothing happens it has to start every time a new video from a list.
with the bootstrap/MediaObject i can't find the event 'video ready playing' so we can start the next video.
what is the best way to solve this with Dotvvm, i don't want to go back to angular for this.
Bas
UPDATE:
At this moment I use the html5  tags, is there also a dotvvm component ?
sample:
    <dot:Content ContentPlaceHolderID="ContentTemplate">

    <video ID="video1" width="320" height="240" autoplay>
        <source src="/Style/video/video1.mp4" type="video/mp4">
        Your browser does not support the video tag.
    </video>
    <button onclick="playPause()">Play/Pause</button>

can we get the nextVideo from the viewModel  and how do we do this ?
Comment: Can you clarify the question a little bit?
Maybe a piece of code of the MediaObject.
Are you using the commerical Bootstrap for DotVVM controls, or a pure Bootstrap library?
Answer: 1) Set javascript variable
you can set this way - eg. by button with command
MyView.dothtml
...
<dot:button Click="{command: SetNextVideo()}" Text="Set next video" />
...

MyViewModel.cs
....
IDotvvmRequestContext _requestContext;
...

public void SetNextVideo()
{
  //_requestContext.ResourceManager.AddStartupScript("alert('my javascript after command');");
  _requestContext.ResourceManager.AddStartupScript("nextVideo = ...... ");
}

2. Get current value of Viewmodel property in View
or you can declare declare string property in viewmodel and in your javascript you can get current value by knockout call like this:
Viewmodel
public string MyFoo {get;set;} = "bar";

View:

It depends on your script what you realy want to do :)


CSS Align image below paragraph

Question: I'm trying to align the image below the Benefits paragraph but for some reason it won't allow me to position it there. I used background-position: % %; When I change it to be more lower than the paragraph, my image hides and when I give the section more height, The image isn't showing aswell.
I am only allowed to use CSS (so need to work with css background properties, and not HTML for this project.

/*derde section*/

.participation h3 {
    font-family: fraktur;
    font-weight: 100;
    font-size: 10em;
    width: 50%;
    color: #4A4A4A;
    text-align: left;
}

.participation {
    /* width: 80%; */
    display: grid;
    grid-template-columns: 1fr;
    margin: 50px auto;
    /* border: 2px solid #000000; */
    background-image: url('../images/peace.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: 13% 82%;
    justify-items: end;
}

.participation p {
    width: 47%;
    margin: 15px 40px;
}

.benefits h3 {
    font-family: baskerville;
    font-weight: 100;
    font-size: 10em;
    width: 50%;
    color: #000000;
    text-align: left;
}

.benefits {
    /* width: 80%; */
    display: grid;
    grid-template-columns: 1fr;
    margin: 50px auto;
       background-image: url('http://thomasdebelder.be/zengarden%20website//images/kop2.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: right bottom;
    justify-items: end;

}

.benefits p {
    width: 47%;
    margin: 15px 40px;
}

/*einde derde section*/

Participation

Strong visual design has always been our focus. You are modifying this page, so strong CSS skills are necessary too, but the example files are commented well enough that even CSS novices can use them as starting points. Please see the CSS Resource Guide for advanced tutorials and tips on working with CSS.

You may modify the style sheet in any way you wish, but not the HTML. This may seem daunting at first if you’ve never worked this way before, but follow the listed links to learn more, and use the sample files as a guide.

Download the sample HTML and CSS to work on a copy locally. Once you have completed your masterpiece (and please, don’t submit half-finished work) upload your CSS file to a web server under your control. Send us a link to an archive of that file and all associated assets, and if we choose to use it we will download it and place it on our server.

Benefits

Why participate? For recognition, inspiration, and a resource we can all refer to showing people how amazing CSS really can be. This site serves as equal parts inspiration for those working on the web today, learning tool for those who will be tomorrow, and gallery of future techniques we can all look forward to.

Answer: You can add a big padding to the section at the bottom and adjust the background like this :

/*derde section*/

.participation h3 {
    font-family: fraktur;
    font-weight: 100;
    font-size: 10em;
    width: 50%;
    color: #4A4A4A;
    text-align: left;
}

.participation {
    /* width: 80%; */
    display: grid;
    grid-template-columns: 1fr;
    margin: 50px auto;
    /* border: 2px solid #000000; */
    background-image: url('../images/peace.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: 13% 82%;
    justify-items: end;
}

.participation p {
    width: 47%;
    margin: 15px 40px;
}

.benefits h3 {
    font-family: baskerville;
    font-weight: 100;
    font-size: 10em;
    width: 50%;
    color: #000000;
    text-align: left;
}

.benefits {
    /* width: 80%; */
    display: grid;
    grid-template-columns: 1fr;
    margin: 50px auto;
       background-image: url('http://thomasdebelder.be/zengarden%20website//images/kop2.png');
    background-repeat: no-repeat;
    background-position: 73% 100%;
    justify-items: end;
    padding-bottom: 400px;

}

.benefits p {
    width: 47%;
    margin: 15px 40px;
}

/*einde derde section*/

Participation

Strong visual design has always been our focus. You are modifying this page, so strong CSS skills are necessary too, but the example files are commented well enough that even CSS novices can use them as starting points. Please see the CSS Resource Guide for advanced tutorials and tips on working with CSS.

You may modify the style sheet in any way you wish, but not the HTML. This may seem daunting at first if you’ve never worked this way before, but follow the listed links to learn more, and use the sample files as a guide.

Download the sample HTML and CSS to work on a copy locally. Once you have completed your masterpiece (and please, don’t submit half-finished work) upload your CSS file to a web server under your control. Send us a link to an archive of that file and all associated assets, and if we choose to use it we will download it and place it on our server.

Benefits

Why participate? For recognition, inspiration, and a resource we can all refer to showing people how amazing CSS really can be. This site serves as equal parts inspiration for those working on the web today, learning tool for those who will be tomorrow, and gallery of future techniques we can all look forward to.

Answer: One option would be add a padding-bottom to the h3 element to give room for the background image. Like this:

/*derde section*/

.participation h3 {
    font-family: fraktur;
    font-weight: 100;
    font-size: 10em;
    width: 50%;
    color: #4A4A4A;
    text-align: left;
}

.participation {
    /* width: 80%; */
    display: grid;
    grid-template-columns: 1fr;
    margin: 50px auto;
    /* border: 2px solid #000000; */
    background-image: url('../images/peace.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: 13% 82%;
    justify-items: end;
}

.participation p {
    width: 47%;
    margin: 15px 40px;
}

.benefits h3 {
    font-family: baskerville;
    font-weight: 100;
    font-size: 10em;
    width: 50%;
    color: #000000;
    text-align: left;
    padding-bottom: 100%;
}

.benefits {
    /* width: 80%; */
    display: grid;
    grid-template-columns: 1fr;
    margin: 50px auto;
       background-image: url('http://thomasdebelder.be/zengarden%20website//images/kop2.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: right 60%;
    justify-items: end;

}

.benefits p {
    width: 47%;
    margin: 15px 40px;
}

/*einde derde section*/

Participation

Strong visual design has always been our focus. You are modifying this page, so strong CSS skills are necessary too, but the example files are commented well enough that even CSS novices can use them as starting points. Please see the CSS Resource Guide for advanced tutorials and tips on working with CSS.

You may modify the style sheet in any way you wish, but not the HTML. This may seem daunting at first if you’ve never worked this way before, but follow the listed links to learn more, and use the sample files as a guide.

Download the sample HTML and CSS to work on a copy locally. Once you have completed your masterpiece (and please, don’t submit half-finished work) upload your CSS file to a web server under your control. Send us a link to an archive of that file and all associated assets, and if we choose to use it we will download it and place it on our server.

Benefits

Why participate? For recognition, inspiration, and a resource we can all refer to showing people how amazing CSS really can be. This site serves as equal parts inspiration for those working on the web today, learning tool for those who will be tomorrow, and gallery of future techniques we can all look forward to.

Comment: than i get this: http://thomasdebelder.be/test.png Doesn't work in my case

CSS Align image below paragraph


Link outside div tag encompasses empty space

Question: I have a link outside a div like in the following example:

Now, the link does work on any part of the div, but it is also present outside the div, mainly to the right side of it where there isn't anything. How can I fix this to make the link only work inside the div tag?
Here's the code in jsfiddle: http://jsfiddle.net/BWPHS/
Comment: That's not a valid way of doing it. Make the `A` tag `display: block` *inside* the DIV.
Comment: @JaredFarrish Depending on the doctype, I think [wrapping an `` around block-level elements actually is valid](http://html5doctor.com/block-level-links-in-html-5/).
Comment: @sdleihssirhc - Ok, HTML5 does allow (didn't know that). All kinds of goodies!
Answer: Note, DIV elements are display: block by default, so you don't need that in the DIV. What you do need to do is make the A the same height, and resolve the padding and margin to taste.

http://jsfiddle.net/BWPHS/3/
Note, as sdleihssirc notes, HTML5 does allow it (if you use the DOCTYPE). Note, to resolve the specific issue for HTML5, you would need to apply the height and width to the A tag:

http://jsfiddle.net/BWPHS/2/
And, as thirtydot points out, you can display: inline-block or float: left the #something element and apply display: block to the A and it should work perfectly for you:
#something,
#something a {
  padding: 0;
  margin: 0;
}
#something {
  display: inline-block;
  background: red;
}
#something a:link {
  display: block;
  width: 200px;
  height: 100px;
}

http://jsfiddle.net/BWPHS/6/
And you probably want to try to avoid using inline style attributes.
Comment: Looking good. I'd give you an upvote if I hadn't already given you an upvote.
Comment: It would be better to drop the `width` and `height` from the `div` to avoid duplication, and use `float: left` or `display: inline-block` instead.
Comment: @thirtydot - Something like this? http://jsfiddle.net/BWPHS/5/ (The small gap at the bottom is a bit of a problem.)
Comment: Yeah, that's it. You can get rid of the gap at the bottom by adding `vertical-align: top` to the `a` (or simply using `display: block` on the `a` instead of `display: inline-block`).
Comment: @thirtydot - This is probably more like what you were thinking (and no gap): http://jsfiddle.net/BWPHS/6/


Constructing an Object from a Class Reference

Question: I have a method which constructs an object, calls an Execute method, and frees the object. The type of object is determined by a TClass descendant passed into the method.
Note this is Delphi for Win32 I am talking about, not .NET.
Edit: I should point out that this is Delphi 2006, as it has been noted in answers below that in future versions the NewInstance call may not be required. In my case, however, it is required. As such, I would imagine the answer to my question (is it safe? and does CreateForm() have a potential leak) would need to be answered on the basis that this is Delphi 2006
Edit#2: seems that the solutions given for D2007 & D2009 do in fact work for D2006. I must have picked up the "NewInstance" habit from an earlier version of Delphi...
function TPageClassFactory.TryExecute(ScrnClass: TCustomPageClass): boolean;
//TCustomPageClass = class of TCustomPage
var
  ScrnObj: TCustomPage; //TCustomPage defines an abstract Execute() method
begin
  Result := FALSE; //default
  ScrnObj := TCustomPage(ScrnClass.NewInstance); //instantiate
  try
    ScrnObj.Create(Self);  //NB: Create() and Execute() are *virtual* methods
    ScrnObj.Execute;
  finally
    FreeAndNil(ScrnObj);
  end;
  Result := TRUE;
end;

What I want to know is whether this is safe - what will happen here if Create() raises an exception?
Looking at a similar example, from Forms.pas.TApplication.CreateForm(), a different approach has been taken to exception handling (I've cut out the irrelevant bits below):
procedure TApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
var
  Instance: TComponent;
begin
  Instance := TComponent(InstanceClass.NewInstance);
  TComponent(Reference) := Instance;
  try
    Instance.Create(Self);
  except
    TComponent(Reference) := nil;
    raise;
  end;
end;

In the Forms.pas method, does this mean that memory is leaked when an exception occurs in the Create() method? My understanding was that InstanceClass.NewInstance allocated memory, thus in this case the memory is not being deallocated/released/freed?
Answer: You should put the create out of the try finally block.
But a better solution is:
type
  TMyClass = class ()
  public
    constructor Create(...); virtual;
    function Execute: Boolean; virtual;
  end;
  TMyClassClass = class of TMyClass;

procedure CreateExecute(const AClass: TMyClassClass): Boolean;
var
  theclass : TMyClass;
begin
  theclass := AClass.Create;
  try
    Result := theclass.Execute;
  finally
    theclass.Free;
  end;
end;

Comment: I am using Delphi 2006 - my understanding of why is a little hazy, but NewInstance is required either because AClass.Create() does not allocate memory, or because it creates an instance of the base class type, rather than the given class type. As a result, I think create needs to be *in* the try
Comment: I'm using D2006 too and happily use Create on class type references without NewInstance. And frankly, I would be surprised if this was any different in, say, D5.
Comment: Yup, there is no difference between classname.create and classtypevar.create. Both create an instance and call the constructor.
Comment: Graza, you are wrong. Gamecat's solution works in every version of Delphi I can remember. Back before D4, anyway. You are also wrong about putting Create in the try. See Allen Bauer's blog for why.
Comment: If Create() is virtual, and AClass refers to a class that is a *descendant* of TMyClass (eg TMySubClass = class(TMyClass), and then CreateExecute is called with TMySubClass as the argument), will calling AClass.Create() create a TMyClass object, or a TMySubClass object?
Comment: Actually, I just tested and it appears that the correct class is indeed created. I wonder why they do it this way in CreateForm()?
Comment: Graza, yes, *if* the constructor is virtual. (As with Gamecat's example.)
Comment: Constructor is virtual. I've now gone from the test apps used to check doing it *without* NewInstance, into production code, and all is working. The ways suggested here were always how I'd instinctually have done it, but something in past projects led me to the NewInstance route for some reason.
Comment: NewInstance is used in VCL's TApplication to create Forms... Check .dpr file ;)
Comment: I'm pretty sure I used CreateForm() as an example some time in the past because I couldn't get the more "straightforward" code working for some reason. I'm a little baffled at this point though, which CreateForm() uses NewInstance (or at least why it still uses it)
Comment: This behaviour with class references (ie not having to call NewInstance) dates all the way back to Delphi 1. I still have Delphi 1 code that I use now (cross compiling to Delphi XE2 no less) and it makes heavy use of this.
Answer: There have been a few questions raised in comments that I'd like to clarify.
First is the continued myth that the constructor needs to be virtual. It does not. Consider this example:
type
  TBase = class
    constructor Create(x: Integer);
  end;
  TDerived = class(TBase)
    field: string;
  end;
  TMetaclass = class of TBase;

var
  instance: TBase;
  desiredClass: TMetaclass;
begin
  desiredClass := TDerived;
  instance := desiredClass.Create(23);
  Assert(instance.ClassName = 'TDerived');
  Assert(instance is TDerived);
  Assert(instance.field = '');
end;

The created object will be a full-fledged instance of class TDerived. Enough memory will have been allocated to hold the string field, which didn't exist in the base class.
There are two conditions that must be true before you'll need a virtual constructor:

The constructor will be called virtually. That is, you'll have a variable of the base-class metaclass type, and it will hold a value of a derived class, and you will call a constructor on that variable. That's demonstrated in the code above. If all your constructor calls are directly on the class names themselves (i.e., TDerived.Create(23)), then there's nothing to be gained from virtual methods.
A subclass of the base class will need to override the constructor to provide class-specific initialization. If all descendants use the same construction, and only vary in other methods, ten there's no need to make the constructor virtual.

What's important to realize here is that those two rules are no different from the factors that determine when the make any other method virtual. Constructors aren't special in that regard.
The constructor knows which class to construct based not on the class where the constructor was defined, but on the class the constructor was called on, and that class is always passed as a hidden first parameter for every constructor call.

Second is the issue of whether NewInstance should be called in place of or in addition to the constructor. I think other comments have already established that it has nothing to do with compatibility with older Delphi versions. All versions have supported calling constructors on class references without the need for NewInstace. Rather, the confusion comes from looking at TApplication.CreateForm and treating it as an example of how things should be done. That's a mistake.
CreateForm calls NewInstance before calling the constructor because CreateForm's primary reason for existence is to ensure that the global form variable that the IDE declares is valid during the form's own event handlers, including OnCreate, which runs as part of the constructor. If the CreateForm method had done the usual construction pattern, then the global form variable would not yet have had a valid value. Here's what you might have expected to see:
TComponent(Reference) := InstanceClass.Create(Application);

Simple and obvious, but that won't work. Reference won't get assigned a value until after the constructor returns, which is long after the form has triggered some events. If you follow good programming practice and never refer to that variable from within the form class itself, then you'll never notice. But if you follow the documentation's instructions, which are written for an inexperienced audience, then you will refer to the global form variable from within the form's own methods, so the CreateForm method does what it can to make sure it's assigned in time.
To do that, it uses a two-step construction technique. First, allocate memory and assign the reference to the global variable:
Instance := TComponent(InstanceClass.NewInstance);
TComponent(Reference) := Instance;

Next, call the constructor on the instance, passing the TApplication object as the owner:
Instance.Create(Self);

It's my opinion that CreateForm should be called exactly once in any program. I'd prefer zero times, but it has the side effect of defining Application.MainForm, which is important for other aspects of a Delphi program.

Third is the notion that it's unusual for an object to call a constructor on itself.
In fact, this happens all the time. Every time you call an inherited constructor, you're calling a constructor on an object that already exists. The inherited constructor is not allocating a new object. Likewise, the VCL has some examples of non-inherited calls of constructors. TCustomForm.Create delegates much of its construction tasks to its CreateNew constructor.
Comment: Brilliant!
Re CreateForm(): That makes perfect sense. Really, it sounds like a workaround due to the fact that the default project templates encourage the use of Global variables (which I've always thought was naughty of Borland!)
Comment: Re #3: Probably its best that some sort of "InitMembers" method is declared instead, but if for example an object calls its own Create method long after it has been created, in order to reinitialise itself, would it be freed at that point if an exception occurred?
Comment: No, Graza, the destructor won't get called in that case. Constructors know whether they're supposed to do allocation before they initialize. If they're just initializing, they don't set up a stack frame to make the destructor get called.
Comment: Good to know. Then it still seems a bit odd that in the case of Application.CreateForm() that the destructor gets called on exception, as in this case Create() is not allocating memory, InitInstance() is. But I'm now steering clear of that way of doing things, so I'll happily leave that unexplained
Answer: Edit:
Didn't fully remember how it was in old delphi versions but apparently this should work in all based on other replies.
Note, Create has been calling Destroy on fail for as long as I can remember. It shouldn't be after I think.
Code would be:
procedure TPageClassFactory.TryExecute(ScrnClass: TCustomPageClass);
var
  ScrnObj: TCustomPage;
begin
  ScrnObj := ScrnClass.Create(Self);  // Exception here calls the destructor
  try
    ScrnObj.Execute; // Exception here means you need to free manually
  finally
    FreeAndNil(ScrnObj); // Be free!
  end;
end;

I removed the result returned by the original function as it can never be false, only "unassigned" (exception) or true. You could after all get an exception before you assign result to false. ;)
Comment: Delphi 2006 - can't use Gamecat's solution & need to use NewInstance. My understanding is that because of this, Create() is not allocating memory, thus can (and should) be inside the try..finally.
Comment: The point is that (at least under Delphi 2007) the raised exception in the constructor leads to the destructor being called "behind-the scene", so doing it again in the finally block is an error.
Comment: I've only messed around with Create in this manner in later versions and you are indeed correct in that the destructor is called if Create fails. How it is for very early delphis I don't know, the poster did not specify a version.
Comment: Ah, I actually had some code above the creation in my original code, which *can* result in FALSE, but didn't think to remove the result from the "cut-down" version I posted
Comment: Just tested and indeed the destructor is called even if Create is called in this way. Which I think is a bit strange... an object can call its own create method after construction, which is *not* reconstructing it, so why is Destroy called? No problem though - you've given me a better way to do this
Comment: Destructors have *always* been called upon construction failure. And NewInstance has *never* been required in place of a bona-fide constructor call, for all versions of Delphi, even the first one. If your experience is otherwise, then you were doing something wrong.
Answer: Re your question about memory being leaked when Create() raises an exception: You should try it out for yourself. I just did on Delphi 2007, and with your code FastMM4 shows an error dialog about the attempt to call a virtual method on an already freed object, namely Destroy(). So the exception in Create will already lead to the destructor being called and the memory being freed, so your code is actually wrong. Stick to the idiom used in the answer by Gamecat, and everything should work.
Edit:
I just tried on Delphi 4, and the behaviour is the same. Test code:
type
  TCrashComp = class(TComponent)
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

constructor TCrashComp.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  raise Exception.Create('foo');
end;

destructor TCrashComp.Destroy;
begin
  Beep;
  inherited Destroy;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  C: TComponent;
begin
  C := TComponent(TCrashComp.NewInstance);
  try
    C.Create(nil);
    C.Tag := 42;
  finally
    C.Free;
  end;
end;

With FastMM4 the Free in the finally block gives the same error, because C has been freed already. On application shutdown the exception and the exception string are reported as memory leaks, though. This is however not a problem with the code, but with the runtime.
Comment: Using BDS2006 - does this apply (destroy called automatically) when Create() is being called in the way I am calling it (in this case it is not used as a "constructor" and does not allocate memory for the object, but is simply a method which initialises things).

(AObject.Create <> TObject.Create)
Comment: If Create() overrides the method in the base class it will work. If not you should get a warning about hiding a method, and it probably will not work. Not that you would do that...
Comment: Actually, I don't understand the need for NewInstance, at all. I have never used it in similar places.
Comment: NewInstance is used in a lot of examples, maybe it's a remnant from an early Delphi or C++ Builder and everyone since has just copied. ;)
Comment: This is kind of weird, as even the Delphi 1 help says not to call NewInstance as it will be called automatically by the constructor. I wonder what this is all about.


How to accurately drop-tune an acoustic guitar?

Question: I like to play in drop-D, for a variety of reasons mostly involving the use of a low drone string, simplicity of fingering certain chord-shapes quickly, and I like some of the interesting possibilities with regard to open strings and minimal fingering, especially high up the neck.  I play largely by ear, and like to improvise a lot, so it's really important the intonation is very accurate.  Even though other people might not hear the difference, a little bit off and it gets confusing as to where to go next, and isn't pleasing when you go to let something really stand out and it's just wrong to my ears.
On my electric I have adjusters for intonation, it's 24 frets, easy to play, and sounds great.  But it's not always convenient, or easily portable, and it's precious to me.  My acoustics are, well, cheap.  I've tried lots of things, but always seem to be a few cents sharp at the 7th fret on a drop-D 6th string when tuned accurately with open strings.  Or tuned accurately at the 7th fret, flattish when open.
I've tried modelling a saddle that mimicks the positioning on my electric, adjusting the nut, even using screws, toothpicks, or anything about the right size and shape to wedge in there, on either end, to get the intonation right.  I've come a lot closer, but still a bit off, which drives me nuts.
Anyone out there with experience adjusting intonation on an acoustic guitar for drop-D tuning who might have a word of advice that doesn't involve spending a bunch of money?
Comment: @ToddWilcox - you beat me to it ! Putting a different gauge string that intonates with the existing saddle seems a sensible thing to do. It will also match the tensions of the other strings better.
Comment: Putting a slightly thicker string on for the D tuning, if the string has the same elasticity as the thinner one and all else remains the same, will not change the intonation at all- only changing the playing length and/or the frets will do that.  But it will improve the tension and is a good idea in any case.
Comment: Is your lowest string intonated correctly when tuned to E? Have you tried a slightly thicker string for the low string?
Answer: The problem is that if your bottom string is in tune on the frets when tuned to E, it's simply going to play sharp when tuned down.  Unfortunately, you either need a D-string which is a bit more elastic (so it goes up less when stretched) than your E-string, or you need to compensate the nut and/or the bridge-shortening the string length at the nut, or lengthening it at the bridge, or both.  Or you could lower the string in the nut and/or bridge.  All of this will of course adversely affect the intonation of the string when tuned back up to E, and lowering may cause buzzing.
If you have a guitar you want permanently for drop tuning, you could conceivably do the compensation yourself: shortening the mensur (the acoustic length) of the bottom string a couple of millimeters at the nut and lengthening it at the bridge (assuming you have enough material there) should do the trick.  You have to be pretty good with a file, though.  Don't try it on an expensive instrument.
Good luck.
edited for accuracy.  Sorry, must have been half asleep: you of course need to shorten the string length at the nut if you want it to not play so sharp on the frets.
Comment: Adjusting the nut will only affect the open string's pitch. From 1st fret on, no difference.
Comment: Tim- if you adjust the nut without retuning the open string, you are correct.  But if you tune the open string up to pitch after adjusting the nut, it will now play higher or lower on all the frets, depending on whether you made its open length longer or shorter.  I do it all the time on vielles with all gut strings, where the intonation problems between strings on the frets are much more acute than on guitars with modern strings, and thus must be compensated at both nut and bridge.
Comment: @jdmayfield- sorry, as I said in my edit, I made a mistake in my answer.  If you shorten the D string at the nut (by extending the nut downward) this can compensate (at least approximately) for the drop tuning.   The difficulty is, you must do this without raising the string above where it was, or that will cancel out your compensation.  Depending on how the nut is made, you might be able to glue a bit of plastic (or bone or whatever) to it that shortens the D string a bit without lifting it.  It should be possible to get pretty good intonation this way.
Comment: Yes.  I can get it to be very accurate all up the neck, by making a custom saddle or extension just on the low D string-- essentially lengthening the string and adjusting intonation on the frets;  but then when it's open it is almost a quarter-tone low (≈15-20 cents).  Works great for bar chords, but sounds wobbly when the string is open, say if you strike an open D or D minor chord.  Since I like to take advantage of the low open D, and also play all the way up the neck, this a problem.  Definitely does not give the effect I'm looking for when I go to ring a low open D, or use it as a drone.
Comment: Nice, @Scott.  I think that's probably it.  Shorting via the nut hasn't worked yet because it's raising it a tad.  But if I sort of mute it with my fingernail just below instead, it does seem to get the right open pitch.   I do need to switch to a thicker string as Todd and Tim mentioned, as well.  So really all of the above are good answers.  I think it will need a pretty good jump in guage to compensate properly.  Hopefully pick one up next few days.  Thanks guys!  I'll try it out and post an update when I get a chance.
Comment: @jdmayfield- good luck and please do let us know how it works out.


Script não salva palavra completa se tiver acento

Question: tenho um script que funciona muito bem em meu dashboard, porém coloquei ele em outra página e não está funcionando.
Quando uma palavra tem acento, ex: "Natália" o sistema está salvando no bd apenas "Nat" excluindo o restante que faz parte da palavra.
<code>include "painel_dados/bd.php";

// recebendo os dados do formulario
$nome   = $_POST['nome'];
$cpf    = $_POST['cpf'];

$query = $mysqli->prepare('INSERT INTO `associados` (`nome`, `cpf`) values (?,?)')or die($mysqli->error);
$query->bind_param('ss', $nome, $cpf);
$query->execute();
</code>
Onde estou errando?
Se eu der um

echo $nome;

a palavra aparece certinho. Só na hora de salvar no bd que ela vai incompleta.
Comment: Ainda bem que vc descobriu porque com o código postado não iríamos descobrir nunca.
Comment: Verifique se o seu banco está com o formato utf-8.
Comment: Está. Descobri o problema. O erro estava na pagina onde tinha o formulário, ela estava em iso
Answer: Descobri o erro.
A página onde estava o formulário estava com

charset=iso-8859-1

troquei para

UTF-8

E funcionou


Error inserting data into Django database field with a OneToOnefield

Question: I've asked this question before and tried to Google it but I've had no luck, so I have simplified my question.  I have two very simple models: one holds some shift numbers and the other holds some data related to the sale of gift cards during a shift.  In this case, we have an employee who worked shift "1234" and sold $200.45 and $43.67 worth of gift card from each of two terminals.  The models are below:
class Data_Shifts(models.Model):
    shift_id = models.CharField(max_length=25, primary_key=True, db_column="shift_id", verbose_name="Shift ID")

    def __str__(self):
        return str(self.shift_id)

class Data_GiftCards(models.Model):
    shift_id = models.OneToOneField('Data_Shifts', on_delete=models.CASCADE, primary_key=True, db_column="shift_id", verbose_name="Shift ID")
    net_sales_terminal_1 = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    net_sales_terminal_2 = models.DecimalField(max_digits=8, decimal_places=2, default=0)

    def __str__(self):
        return str(self.shift_id)

I then try to insert some test data into the table using the following command:
Data_GiftCards.objects.create(shift_id="1234", net_sales_terminal_1="200.45", net_sales_terminal_2="43.67")

Upon submitting the web form, I get the following error:
Cannot assign "'1234'": "Data_GiftCards.shift_id" must be a "Data_Shifts" instance.
I am boggled by this.  I have a workaround that bypasses django and inserts directly into the table successfully, but this is dirty and I'd prefer to use the proper Pythonic Django way.  What am I doing wrong here?
Many thanks in advance.
Answer: That is because you name your field shift_id. Django's ORM maps the name of the field in your model to an instance of the related model, not to an ID.
You can still work with IDs instead of instances, but then you have to add _id to the end of your field name.
In your case, you have two options, you can simply do that, which would mean your query should look like:
Data_GiftCards.objects.create(shift_id_id="1234", net_sales_terminal_1=200.45, net_sales_terminal_2=43.67)

But shift_id_id looks redundant, so you can tweak the other end and remove the _id suffix in your model:
class Data_GiftCards(models.Model):
    shift = models.OneToOneField('Data_Shifts', on_delete=models.CASCADE, primary_key=True, db_column="shift_id", verbose_name="Shift ID")
    net_sales_terminal_1 = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    net_sales_terminal_2 = models.DecimalField(max_digits=8, decimal_places=2, default=0)

    def __str__(self):
        return str(self.shift)

Then you will have to query as you are doing, but you should not use strings if the field types are numeric.
Data_GiftCards.objects.create(shift_id="1234", net_sales_terminal_1=200.45, net_sales_terminal_2=43.67)

Also, you don't need the attribute db_column="shift_id". If your field name is shift, the name of the field in the database table will already be shift_id.
Comment: Spot on!  Thanks Marc!  I find this strange though....I mean, if I specify the "primary_key=" argument then it just uses "shift_id" as the PK...I guess the additional "_id" is somehow hidden within the Django ORM somewhere.  Regardless, thank you again.
Comment: Yes, I think you'll get used to it and end up liking it. It comes more natural. Because the ORM is meant to be an object interface to your database, "split" should be a reference to the object, not to the ID. Hence the name ORM (Object-Relational Mapping). On the table level, though, it automatically adds the _id because the reference there is an ID, not to the whole record on the related table. And you can also use the suffix in the ORM if you need to use ID references.