text:
Q: Best way to handle null task inside async method? What is the best way to handle a null task inside an async method?
public class MyClass
{
   private readonly Task task;
   public MyClass(Task task) { this.task = task; }

   public async Task Execute()
   {
      if (task == null)
      {
         await Task.Yield(); /* Is this the best way? */
         return;
      }
      await task;
   }
}

A: You don't need to handle null tasks. Simply null check it:
public async Task Execute()
{
   if (task != null)
   {
       await task;
   }
}

Or even better, simply return the task since you're not adding anything after the await:
public Task Execute()
{
   return task;
}

If you want to return a completed task instead of null you can use Task.FromResult:
public Task Execute()
{
   return task ?? Task.FromResult(false);
}

A: Most asynchronous code is cleaner if tasks are never null. Instead of a null task, use Task.FromResult(0) or some such construct.
public class MyClass
{
  private readonly Task task;
  public MyClass(Task task) { this.task = task ?? Task.FromResult(0); }

  public async Task ExecuteAsync()
  {
    await task;
  }
}

Or, if that's really all your ExecuteAsync is doing:
public Task ExecuteAsync()
{
  return task;
}

Note that the task is already running when the constructor is called, which makes the method name ExecuteAsync a misnomer. If you want the task to start when ExecuteAsync is called, then what you really want to store is a Func<Task>:
public class MyClass
{
  private readonly Func<Task> func;
  public MyClass(Func<Task> func) { this.func = func ?? () => Task.FromResult(0); }

  public async Task ExecuteAsync()
  {
    await func();
  }
}

A:
What is the best way to handle a null task inside an async method?

Best practices typically include not allowing null parameters (unless the business rules require them).
public class MyClass
{
   private readonly Task _task;

   public MyClass(Task task)
   {
     if (task == null)
     {
       throw new ArgumentNullException("task");
     }

     this._task = task;
   }

   public async Task Execute()
   {
      await this._task;
   }
}


text:
Q: what does $f''$ suggests about the graph of $f$?
As I read the question, I only understand $g'(0)=0$ means $g$ has a local minimum or maximum there, so the solution must be A,B or E.
That's all. Can you help me figure out what $g''$ suggests?
Thank you

A: $g''(x)>0$ tells you that it is strictly convex at x. Here is why:
Let $x<y$
$0<\int\limits_x^yf(t)dt=f'(y)-f'(x)$
so $(f'(y)-f'(x))(y-x)>0$ which is an alternative definition of convex

A: *

*$g'(0) = 0$ eliminates (C), since it's slope of tangent at $x=0$ is positive.

*$g''(-1) > 0$ indicates the local convexity at $x=-1$, so (E) is eliminated.

*$g''(x) < 0$ on $x \in (0,2)$ indicates the concavity there, so (B) and (D) are eliminated.

Observe that (A) verifies the above three criteria, so (A) is the answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to manually create a cron job to run a Django script? I have been trying to run some code as a cron job using Django. There are a number of packages that help do this, but they do not seem to support the latest Django version (4.0). Instead of continuing to search for packages, I was wondering if it is possible for me to simply write a python script within my Django folder structure, and manually configure a cron job to run this. Something like setting up:
*/30 * * * * python3.8 /var/djangoproject/crons/cron.py

Is this possible? Is there any drawback or risk in doing it like this instead of using a package that is made for this? I don't see anyone recommending this so before implementing it I wanted to see if this is a good idea.

A: Turns out this is quite easy, and can be achieved by using custom django-admin commands. You basically add a management/commands folder to the project, and add a python script to that folder with a specific structure (see documentation). Say you call the file cron.py. Then a cron can be configured as such:
*/30 * * * * python3.8 /var/djangoproject/manage.py cron


text:
Q: Expose Rails Env to Webpacker I'm running Rails v5 with Webpacker v2. Everything's been smooth so far, but I've hit one hiccup: how to expose Rails helpers to my TypeScript.
I know Webpacker ships with rails-erb-loader, so I was expecting that I'd be able to add .erb to a TypeScript file, and then import that file elsewhere:
// app/javascript/utils/rails.ts.erb
export const env = "<%= Rails.env %>"

export function isEnv(envName: string) {
  return env == envName
}

// app/javascript/packs/application.ts
import { env } from "../utils/rails"

But Webpack can't find the "rails" file even if I modify the typescript loader to include ERB files:
module.exports = {
  test: /.ts(\.erb)?$/,
  loader: 'ts-loader'
}

All I see is:
error TS2307: Cannot find module '../utils/rails'.

What's the best way to go about exposing Rails helpers and variables to my JavaScript?

A: Rails env comes from your environment variable. This means you configure it by setting (in bash for example) the variable in this way:
export RAILS_ENV=production

As a consequence, you don't need to deal with Rails at all.
// app/javascript/utils/rails.ts.erb
export const env = process.env.RAILS_ENV || "development"

export function isEnv(envName: string) {
  return env == envName
}

This comes with a great advantage: you don't have to load the whole rails app just to compile your javascript. Rails can become really slow on first load if your app grows.
Since you won't have access to process.env on the frontend (browser), you also need a way to make it exist. In webpack, this is done through the DefinePlugin:
Update your webpack configuration to use the plugin (in plugins section): new webpack.DefinePlugin({ "process.env": { RAILS_ENV: process.env.RAILS_ENV } }) and you will get a process.env.RAILS_ENV available in the client

A: Rails Env can be accessed through:
process.env.RAILS_ENV


text:
Q: how to split an element in python by keeping the separator hi how can I split this string while keeping '(':
s = ' playsound3Dwhenpossible(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);'
x = s.split("(")
print(x)

I also tried with:
x = s.split("?=(")

but it did not work.
thank you

A: If you just need to keep the separator, you can re-introduce it after the split:
def split_keep_separator(source, sep):
    elements = source.split(sep)
    return [e for t in zip(elements, [sep] * (len(elements))) for e in t][:-1]

And to test it:
s = ' playsound3Dwhenpossible(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);'

x = split_keep_separator(s, "(")
print(x)

# [' playsound3Dwhenpossible',
#  '(',
#  'soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);']

A: If you want to keep the separator '(' in the output array, the simplest is to use a regex split.
import re
s = ' playsound3Dwhenpossible(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);'
x = re.split(r'(\()', s)

A: Based on your input string, It seems your expected output may be,
[' playsound3Dwhenpossible', '(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);']

If so, this seems easiest to me
s = ' playsound3Dwhenpossible(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);'
print s.replace("(","*(").split('*')

First replace and than split.
Instead of '*', you can use whatever, which is NOT in the original string.

A: Another regex-based solution:
import re

s = ' playsound3Dwhenpossible(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);'
splits = re.findall(r'(\(?[^(]+)', s)
print(splits)

Output:
[' playsound3Dwhenpossible', '(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);']

Or if you want to have a generic (or easy to use) function:
split_keep = lambda s, sep : re.findall('({0}?[^{0}]+)'.format(re.escape(sep)), s)
splits = split_keep(s, '(')

This fails in the corner case of having multiple contiguous separators. The following slightly more complex function fixes it:
split_keep = lambda s, sep : re.findall('({0}[^{0}]*|{0}?[^{0}]+)'.format(re.escape(sep)), s)
print(split_keep('((asda((asfasf', '('))

Output:
['(', '(asda', '(', '(asfasf']

A: You could possibly change your split slightly to :
s = ' playsound3Dwhenpossible(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);'

x = s.split(r'\(') #raw
print(x)

Output:
[' playsound3Dwhenpossible(soundspotpoint18, %$videos_sounds_path%/sounds/lavazza_-_auguri_cherubini__15_.mp3, true, false, -52.644483, 0.947368, 90, 1, spotpoint18);']


text:
Q: Error 'Syntax error: "(" unexpected' when declaring arrays in bash Same problem as this OP, but must be a seperate cause.
The following script:
#!/bin/sh
arr=("cat" "dog" "bird")

Works interactively (debian) but fails when called by crontab with:
/bin/sh: 2: /path/zero_check.sh: Syntax error: "(" unexpected

I've tried with #!/bin/bash shebang, and declaring array with declare -a arr=("cat" "dog" "bird"), to no effect.
Any idea why?

A: The problem here is that you are using this shebang:
#!/bin/sh

Whereas arrays are something Bash specific that shell does not allow.
So to make it work, change the shebang of your script to Bash:
#!/bin/bash

A: Specify your interpreter explicitly in the crontab entry. Use
bash /path/zero_check.sh

rather than
/path/zero_check.sh

A: Just for the documentation,
i had an old script to run which had an Syntax Error in the Shebang:
#/bin/bash
instead of
#!/bin/bash
Also check the Script is executable of course.

A: Very similar problem with incorrect bash function declarations. This works OK from the command line, but it causes cron to fail...
function test () { ... }

Cron should save the errors in /var/mail
I also recommend linting with "shellcheck" because it found another error I didn't notice.


text:
Q: Setting up Tomcat with pre-existing MySQL from WAMP I have Tomcat running on 8080 port and WAMP's apache on port 80.
Can I use Tomcat with the existing MySQL setup?
How do I go about it? I have downloaded the mysql connector java 5.1.13.
System Details:
WinXP Pro SP3
WAMPSERVER 2 with Apache 2.2.11 & MySQL 5.1.41
Tomcat 6.0.29

A: I don't see any reason why not. The ports Apache and Tomcat are listening on have nothing to do with the MySQL connection.


text:
Q: Angular 5 Material Dialog box with header strip on top When the Angular Materail dialog box is added and by default it comes up with normal dialog box without any borders or any close button with top strip on it. But here i am trying to add the strip on top the Dialog box as shown below in the picture.

I am planning to show the black strip on top of the dialog box which should touch the above 2 corners. But the problem is if i add any div then i think its not good solution. Is there any Angular Material feature available as of now. So for that i have added the div on top of it. But i think its not a feasible solution. I have to add those strips on multiple dialog boxes. So can anybody help me on this?
The code is below.

Hi {{data.name}}

What's your favorite animal?

  <mat-form-field>
    <input matInput [(ngModel)]="data.animal">
  </mat-form-field>

  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>

Stackblitz Code url
Demo
Can anybody suggest me how to achieve this?
Something like this? See below.

Thanks

A: I just played around using the Inspector Tool and this can be achieved using this:
.mat-dialog-container {
    padding-top: 0 !important;
}

dialog-overview-example-dialog.ng-star-inserted > div {
    margin-right: -24px;
    margin-left: -24px;
}

.mat-dialog-actions {
    margin-right: 0 !important;
    margin-left: 0 !important;
}

.mat-dialog-title {
  margin-top: 15px !important;
}

Note: I haven't looked for any solution which is provided by the framework itself.

A: Use the build in toolbar that is part of material.

        <mat-toolbar role="toolbar" class="task-header">
             Dialog Title

            <button mat-icon-button (click)="close()">
                <mat-icon mat-list-icon>close</mat-icon>
            </button>
        </mat-toolbar>

  Modal Content here

Custom CSS for header
.task-header {
    background-color: transparent;
    padding: 0 5px;
     height: 20px;
}
.fx-spacer {
    flex: 1 1 auto;
}

A: You can use the code below. It's just a hack around. There is no direct support from Angular itself.

  <mat-toolbar color="primary">
    Edit User
  </mat-toolbar>

  <mat-toolbar fxLayout="row" fxLayoutAlign="end center" fxLayoutGap="16px" style="padding: 16px;">
    <button mat-button (click)="something()">Cancel</button>
    <button mat-raised-button (click)="something()" color="primary">Update</button>
  </mat-toolbar>

A: From Angular Material docs you can use this directive on the area you want to have fixed to the top:
MatDialogTitle

Title of a dialog element. Stays fixed to the top of the dialog when scrolling.

Selector: [mat-dialog-title] [matDialogTitle]

Exported as: matDialogTitle

https://material.angular.io/components/dialog/api


text:
Q: How to present iOS keyboard along with the modal presentation of a ViewController? I am building a pin entry viewController very similar to the iOS one you see when you go to Settings->TouchID and it prompts you for pin.
I am trying to mimic its behavior of presenting the iOS keyboard along with (at the same) of the modal presentation of the pin entry viewController. I have noticed other applications like Venmo are able to achieve this as well.
How can I achieve this behavior? My pinEntryView is a textField. I have tried sending it the becomeFirstResponder message in viewDidAppear, and this seems to work; however, it will present the iOS keyboard AFTER the viewController modal presentation has finished. I want the presentation to occur at the same time to give the feeling that the iOS keyboard is actually baked-in/part of the ViewController.
I have tried sending the becomeFirstResponder messages in viewWillAppear, viewWillLayoutSubviews as well, but these are not stable solutions. Sometimes the keyboard is displayed and sometimes its not. Is there anyway to do this?

A: I made the test by setting becomeFirstResponder in the viewDidLoad and it is working fine.
I have one button that calls the modal, and that modal has the next code:

override func viewDidLoad() {
        super.viewDidLoad()
        self.textField.becomeFirstResponder()
}

It has no unexpected behavior.

A: I believe I have had this issue before, and it has quite an interesting solution. What you want to do is call becomeFirstResponder in viewWillAppear before calling super .
override func viewWillAppear(animated: Bool) {
    textField.becomeFirstResponder()
    super.viewWillAppear(animated)
}

Then when you call super the first responder is already set, and then iOS picks up this state and includes the keyboard appear animation in the appearance transaction.
Hopefully this can help you too.


text:
Q: LINQ: Using a ternary ( ?: ) with LINQ let is not enough, need an "IF" but can't seem to get it to work I am trying to include an IF within my LET in LINQ but i can't get it to work, it seems to work for the ternary operator, but this is TRUE or FALSE and i need to have more than 2 options.
I think this explains it well
Basically i have a select which selects items using joins from a DB. Then the i get the status for each record but i have to make a join on separate tables depending on the type from products.type
var tst = from p in products join i in info on p.id equals i.pid

// if p.type = "home" then ...

let status = from s in homestatus
select new { status = s.status }

// if p.type ="offshore" then

let status = from s in offshorestatus
select new { status = s.status }

// if p.type ="internal" then

let status = from s in internalestatus
select new { status = s.status }

select new {
name = p.name,
status = status.StatusText
}

Anybody have any ideas how to do a standard IF so i can select which STATUS (let) i wish to execute.
Thanks in advance

A: You can do that with the conditional operator (1)
var tst = from p in products join i in info on p.id equals i.pid

let status = p.type = "home" ? homestatus.Select(s=>s.status) :
             p.type = "offshore" ? offshorestatus.Select(s=>s.status) :
             p.type = "internal" ? internalestatus.Select(s=>s.status) : null
select new {
name = p.name,
status = status != null ? status.StatusText : string.Empty;
}

If you are not using the status for anything else than the StatusText you could also do it like this
var tst = from p in products join i in info on p.id equals i.pid

let status = (p.type = "home" ? homestatus.Select(s=>s.status.StatusText) :
             p.type = "offshore" ? offshorestatus.Select(s=>s.status.StatusText) :
             p.type = "internal" ? internalestatus.Select(s=>s.status.StatusText) : null) ?? string.Empty
select new {
name = p.name,
status = status;
}

(1) A ternary operator is any operator that takes three arguments, of which there at present is only one in C# called the conditional operator


text:
Q: what is the "16 bit short address"? I'm using CC2538EM and CCS v6.
i had founded RF example project, and i had studied few days.
and then i got a question about 16 bit short address.
when i used  basicRfSendPacket(RX_ADDR, (unsigned char*)&tTxPacket, PACKET_SIZE) this function, I thought RX_ADDR was Rx_FIFO address. but it wasn't
RX_ADDR was defined 0xBEEF.
and i founded this value is short address.
what is short address ?!
Is that address located in RAM ?
Is it specific address of register ?
that value was allocated
SHORT_ADDR0 , SHORT_ADDR1 and described "The short address used during destination address filtering".
What is the address filtering either..... ?
help me..
Regrads

A: The "short address" is a configuration parameter of the RF transceiver contained in the CC5238 system-on-chip (SoC).  Compare it with other configuration parameters such as "extended address" and "PAN ID".
Here is an excerpt from the CC2520 Software Examples User's Guide:

uint8_t basicRfSendPacket(uint16 destAddr, uint8* pPayload, uint8
  length)
Send packet to the given destination short address. Returns TRUE if
  packet was sent successfully, and FAILED otherwise. If ackRequest is
  TRUE the return value of this function will only be TRUE if an
  acknowledgment is received from the destination.

The first parameter of basicRfSendPacket() is the short address (think like a network address) of the RF tansceiver that you're sending the packet to.  It is not a memory address for RAM or a register.


text:
Q: PHP - How to re-encode a URI I think I have the need to take a uri which has been decoded in PHP, and re-encode it.
Here is the situation:

*

*JavaScript passes encoded uri as query string parameter to php script.

*PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.

*JavaScript reads embedded uri and sets location of current document based on value of hidden input.

On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET.  So when I embed the uri in the hidden input, it becomes un-encoded.  So I would like to run a PHP script which re-encodes the Uri properly ex:
http://my.example.com/dog walk?is=very great

==>

http://my.example.com/dog%20walk?is=very%20great

Is there a pre-built php function for this or should I just write my own?
PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.
Thanks,
Macy

A: Are you looking for : http://fr.php.net/manual/en/function.urlencode.php ?

A: I don't know if will help you, but PHP have 3 useful functions:
$url = parse_url('put the url here');
parse_str( $url['query'], $query ); // generating an array by reference (yes, kinda weird)
echo $query; //in this line, you can encode or decode.

or, if you want to mount a query, you can use http_build_query(); that accepts values from an array, like:
$url = 'http://my.example.com/dog walk?';
$array = Array (
 'is' => 'very_great',
);
$url_created = $url . http_build_query($array);

A: urldecode:
http://www.php.net/manual/en/function.urldecode.php


text:
Q: Phonegap Filetransfer undefined Am testing my phonegap app in a web browser and get the following in console:
'FileTransfer' is undefined

Have tried the following:
1) installing the plugins, the plugin list shows:
cordova-plugin-file 2.0.0-dev "File"
cordova-plugin-file-transfer 1.0.0-dev "File Transfer"
cordova-plugin-media-capture 1.0.0-dev "Capture"
org.apache.cordova.file 1.3.3 "File"
org.apache.cordova.file-transfer 0.5.0 "File Transfer"

2) Added following lines to config.xml
<feature name="File"><param name="ios-package" value="CDVFile" /></feature>
<feature name="FileTransfer"><param name="ios-package" value="CDVFileTransfer" /></feature>

3) Tried including the js files on the html page
4) Have read that FileTransfer can only be called after the device is ready,
but the function is called on a button click - this happens well after deviceready.
Have read most posts about this issue, but am now really stuck - please advise TQ
 //js
function uploadFile_S3(vidfile) {
var filetype = vidfile.type;
var filename_orig = vidfile.name;
var deferred = $.Deferred(),
    ft = new FileTransfer(),
    options = new FileUploadOptions();
    options.fileKey = filename;
    options.fileName = filename;
    options.mimeType = filetype;
    options.chunkedMode = false;
    options.params = {
        "key": filename,
        "AWSAccessKeyId": 'XXX',
        "acl": 'public-read',
        "policy": policyBase64,
        "signature": signature,
        "Content-Type": "image/jpeg"
    };

    ft.upload(imageURI, s3URI,
        function (e) {
            deferred.resolve(e);
        },
        function (e) {
            deferred.reject(e);
        }, options);

    return deferred.promise();
}


text:
Q: Matrix (arrays) in Lua - swap rows and apply row operation I have this code
--[[

Gaussian Elimination in Lua

--]]

-- print matrix
function printmatrix(m)
   for r=1,#m do
      for c=1,#m[r] do
         io.write(m[r][c])
         if c < #m[r] then io.write(", ") end
      end
      print() -- print new line
   end
end

-- read matrix in CSV format
function readcsv()
   local m = {}
   while true do
      local line = io.read("l") -- read line not including the end of line character
      if line==nil or line=="" then break end -- blank line or bad input ends matrix
      local row, index = {}, 0
      -- the next line is tricky and goes over all entries in the row
      for w in string.gmatch(line,"([^,]*),?") do
     local v = tonumber(w) -- convert entry to a number
     index = index+1
     if v==nil then
        row[index] = 0 -- default value if we coudn't read the number
     else
        row[index] = v -- if number is valid
     end
      end
      m[ #m+1 ] = row
   end
   return m
end

-- determine the size of m and check it is rectangular
function dim(m)
   local rows = #m -- number of rows
   local cols = 0  -- number of columns
   if rows > 0 then cols = #m[1] end
   -- check that matrix is rectangular
   for i=2,rows do
      if cols ~= #m[i] then error("not rectangular!") end
   end
   return rows, cols
end

-- if m[r][c] is zero swap row r with some row i>r to make m[r][c] nonzero, if possible
function swap(m,r,c)
   local nrows, ncols = dim(m)
   if r<=0 or r>nrows or c<=0 or c>ncols then error("position out of range") end
   if m[r][c] ~= 0 then
      -- nothing to do
      return
   end
   -- find a suitable row
   local i=r+1
   while i <= nrows do
      if m[i][c] ~= 0 then break end
      i = i+1
   end
   if i <= nrows then
      -- swap rows i,r
      -- DO IT!
   end
end

-- if m[r][c] is nonzero apply row operations to make each m[i][c]==0 for i>r
function clear(m,r,c)
   local nrows, ncols = dim(m)
   if r<=0 or r>nrows or c<=0 or c>ncols then error("position out of range") end
   if m[r][c] == 0 then
      -- nothing to do
      return
   end
   for i=r+1,nrows do
      local f = m[i][c] / m[r][c] do
      -- apply row_i = row_i - f*row_r
      -- DO IT!**
   end
   end
end

-- apply Gaussian elimination to m to get it into echelon form
function echelon(m)
   local nrows, ncols = dim(m)
   local r,c = 1,1 -- current position
   while r<=nrows and c<=ncols do
      -- try to get a nonzero value at this position
      swap(m,r,c)
      if m[r][c] == 0 then
     -- can't, so move right
     c = c+1
      else
     clear(m,r,c)
     -- done, so move diagonally
     r = r+1
     c = c+1
      end
   end
end

m = readcsv()
print("original:")
printmatrix(m)
echelon(m)
print("echelon form:")
printmatrix(m)

I was hoping someone could clarify on how to write the code (where it says --DO IT! in Lua, I'm fairly new to this thank you
For some context, I'm just experimenting on Gaussian Elimination to try make my work faster during this specific method for computing echelon form -- I'm not too fussed about having 1's as the first non-zero element
It should return this
original:
1, 3, 5, 7
2, 1, -1, 0
3, 4, 4, 7
5, 5, 3, 7
echelon form:
1, 3, 5, 7
0, -5, -11, -14
0, 0, 0, 0
0, 0, 0, 0

A: t.lua:
--[[

Gaussian Elimination in Lua

--]]

-- print matrix
local function printmatrix (m)
    for _, row in ipairs (m) do
        io.write (table.concat (row, ', ') .. '\n')
   end
end

-- read matrix in CSV format
local function readcsv (file)
    io.input (file)
    local m = {columns = 0, rectangular = true}
    for line in io.lines () do
        local row = {}
        -- the next line is tricky and goes over all entries in the row
        for w in line:gmatch '[^,]+' do
            row [#row + 1] = tonumber (w) or 0
        end
        m [#m + 1] = row
        -- Update matrix dimensions
        m.rectangular = m.rectangular and (#row == m.columns or #m == 1)
        m.columns = #row > m.columns and #row or m.columns
    end
    return m
end

-- if m[r][c] is zero swap row r with some row i>r to make m[r][c] nonzero, if possible
local function swap (m, r, c)
    local nrows, ncols = #m, m.columns
    if r <= 0 or r > nrows or c <= 0 or c > ncols then error 'Position out of range' end
    if m [r] [c] ~= 0 then
        -- nothing to do
        return
    end
    -- find a suitable row
    local i = r + 1
    while i <= nrows and m [i] [c] == 0 do
        i = i + 1
    end
    if i <= nrows then
        m [r], m [i] = m [i], m [r]
    end
end

-- if m[r][c] is nonzero apply row operations to make each m[i][c]==0 for i>r
local function clear (m, r, c)
    local nrows, ncols = #m, m.columns
    if r <= 0 or r > nrows or c <= 0 or c > ncols then error 'Position out of range' end
    if m [r] [c] == 0 then
        -- nothing to do
        return
    end
    for i = r + 1, nrows do
        local f = m [i] [c] / m [r] [c]
        for j = 1, #m [i] do
            m [i] [j] = m [i] [j] - f * m [r] [j]
        end
    end
end

-- apply Gaussian elimination to m to get it into echelon form
function echelon (m)
    local nrows, ncols = #m, m.columns
    local r, c = 1, 1 -- current position
    while r <= nrows and c <= ncols do
        -- try to get a nonzero value at this position
        swap (m, r, c)
        if m [r] [c] == 0 then
            -- can't, so move right
            c = c + 1
        else
            clear (m, r, c)
            -- done, so move diagonally
            r = r + 1
            c = c + 1
        end
    end
end

local m = readcsv (arg [1])
print 'Original:'
printmatrix (m)
if m.rectangular then
    echelon (m)
    print 'Echelon form:'
    printmatrix (m)
else
    error 'Matrix not rectangular!'
end

t.scv:
1,3,5,7
2,1,-1,0
3,4,4,7
5,5,3,7

lua t.lua t.csv:
Original:
1, 3, 5, 7
2, 1, -1, 0
3, 4, 4, 7
5, 5, 3, 7
Echelon form:
1, 3, 5, 7
0, -5, -11, -14
0, 0, 0, 0
0, 0, 0, 0

You can also use the standard input (lua t.lua; type the values, terminate with Ctrl + D).

*

*To swap anything in Lua, just do a, b = b, a.

*I used a straightforward approach to your second doit (apply row_i = row_i - f*row_r): for j = 1, #m [i] do m [i] [j] = m [i] [j] - f * m [r] [j] end
`,

*I made your code somewhat more consize and elegant. I also simplified the regular expression used to parse the CSV lines,

*I also made matrix's dimensions and rectangularity calculated during its input.


text:
Q: Erro ao usar whereRaw no Laravel O que estou fazendo de errado nesta queryRaw? O objetivo é exibir os valores somados se ID = ID, mas estou obtendo a soma total da coluna.
Trecho da *query feita no Controller:
//Show
public function show( Pesquisa $pesquisa )
{
    $this->guardaAvaliacao( $pesquisa );

    $pesquisa->load( [
        'respostas' => function ( $relation ) {
            $relation->with( [ 'pergunta.opcoes', 'opcao' ] );
        }
    ] );

    $nota = DB::table('clima.tbl_resposta_super')
        ->selectRaw('sum(nota_original) as nota_original ')
        ->whereRaw('tbl_resposta_super.pesquisa_id', '=' .$pesquisa->id)
        ->groupBy('nota_original')
        ->get();

    dd($nota);

}

A: Ao usar o whereRaw não precisa separar o operador como argumento, como se fosse o where.
$nota = DB::table('clima.tbl_resposta_super')
        ->selectRaw('sum(nota_original) as nota_original ')
        ->whereRaw('tbl_resposta_super.pesquisa_id = ' .$pesquisa->id)
        ->groupBy('nota_original')
        ->get();

A: Para os próximos que tiverem a mesma duvida segue resolução.
        //Recupera e soma Notas
    $notas = DB::table('clima.tbl_resposta_super')
        ->select(DB::raw('sum(nota_original) as nota_original,sum(nota_supervisor) as nota_supervisor, pesquisa_id'))
        ->where('tbl_resposta_super.pesquisa_id', '=', $pesquisa->id)
        ->groupBy('pesquisa_id')
        ->get();


text:
Q: How do I provide real time update in nodejs? I am working on an e-commerce site. There are times where a product would no longer be available but the user would have added it to the cart or added to their saved items. How do I implement the feature such that if the product has been updated, the user would be notified as soon as possible?
I thought about doing a cron job that would check the status of the product if it still available or has been recently updated. But I do not know if that is feasible. I am open to better ideas
Thanks
Similar images are included below

A: What you are trying to achieve falls into real-time updates category and technically there would be more than one option to achieve this.
The chosen solution would depend on your application architecture and requirements. Meanwhile, I can suggest looking into Ably SDK for Node.js which can offer a good starter.
Here down a sample implementation where on the back-end you will be publishing messages upon item's stock reaching its limit:
// create client
var client = new Ably.Realtime('your-api-key');
// get appropriate channel
var channel = client.channels.get('product');
// publish a named (may be the product type in your case) message (you can set the quantity as the message payload
channel.publish('some-product-type', 0);

On the subscriber side, which would be your web client, you can subscribe to messages and update your UI accordingly:
// create client using same API key
var client = new Ably.Realtime('your-api-key');
// get product channel
var channel = client.channels.get('product');
// subscribe to messages and update your UI
channel.subscribe(function (message) {
  const productName = message.name;
  const updatedQuantity = message.data;
  // update your UI or perform whatever action
});

A: Did a live betting app once and of course live updates are the most important part.
I suggest taking a look into websockets. The idea is pretty straight forward. On backend you emit an event let's say itemGotDisabled and on frontend you just connect to your websocket and listen to events.
You can create a custom component that will handle the logic related to webscoket events in order to have a cleaner and more organized code an you can do any type of logic you want to updated to component as easy as yourFEWebsocketInstance.onmessage = (event) => {}.
Of course it's not the only way and I am sure there are packages that implements this in an even more easy to understand and straight forward way.


text:
Q: How to disable a mat-form-field in angular based on a value? How can we disable a matformfield , input field in angular ? . I want to disable the field based on test.status value ,  if status equal to 1 then this form is disabled. Thank you,
<div fxLayout="row" fxLayoutGap="24px">
    <div fxFlex fxLayout="row">
      <mat-form-field appearance="outline" class="pr-4" fxFlexs>
        <mat-label>Description</mat-label>
        <input formControlName="description" matInput>
        <mat-error *ngIf="form.controls.description.hasError('maxlength')">
          Descriptions can't be more than 100 characters!
        </mat-error>
      </mat-form-field>
    </div>
</div>

form builder group
this.form = this.formBuilder.group({ ...
    status: [
        {
          value: test.status
          disabled: true,
        }
    ],
    description: [
        test.description || null, [
          Validators.maxLength(100),
        ]
    ],

A: disabled attribute will not work on  reactive form. You need to set the condition as below :
 this.formName = this.formBuilder.group({
  fieldName: [{value: 'someValue', disabled:(condition)}]
})

for example  :
 this.form = this._fb.group({
       description : [{value: 'someValue', disabled:(this.status>0)},[Validators.required]]
     })

When a form field is disabled , it is not included in the submitted values i.e form object.
You can get the values like below :
this.formName.getRawValue();

Demo

A: Please append/use the below portion in your input-field html:
[disabled]="form.controls.status[0].value==1"
(or)
[attr.disabled]="form.controls.status[0].value == 1? '' :null"
(or)
[class.disable]="form.controls.status[0].value == 1"
Hope this helps.


text:
Q: I am trying to get group name from the groupcollection based on the string match but i am unable to do I am trying to get group name from the groupcollection based on the string match but i am unable to do with the foreach statement  , please advice on my below script, i do not want to call onsuccess function or onerror functions so need to fix in the same code.
context = new SP.ClientContext('/mysite');
this.oWebsite = context.get_web();
context.load(this.oWebsite);
this.groupCollection = oWebsite.get_siteGroups();
context.load(this.groupCollection);

foreach ( Group group1 in groupCollection)
{
    if (group1.Name.ToLower().Contains(ClientCodeTrim.ToLower()))
    {
         PostMyGroup1 = group1.Name;
    }
}

A: Try this
var siteUrl = '/mysite';
var clientContext = new SP.ClientContext(siteUrl);
this.collGroup = clientContext.get_web().get_siteGroups();
clientContext.load(collGroup);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

function onQuerySucceeded() {
    var groupEnumerator = collGroup.getEnumerator();
    while (groupEnumerator.moveNext()) {
        var oGroup = groupEnumerator.get_current();

        if(oGroup.Name.ToLower().Contains(ClientCodeTrim.ToLower())) {
            PostMyGroup1 = oGroup.Name;
        }
    }
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

A: In the code, you have just loaded the web and the sitegroups which do not actually have any information. Unless the request is sent to the server, you wont be able to get the groups information that you are iterating on. You will have to execute
context.executeQueryAsync(onSuccess,onFailure)

in order to get the group collection information and then get the specific group. Any specific reason why you dont want to call onsuccess and failed functions ?


text:
Q: LINQtoCRM and DynamicEntity I found LINQtoCRM (http://linqtocrm.codeplex.com/) and I started playing with it. It's nice, but before I get carried away I found there appears to be a showstopper: I can't figure out how to query against DynamicEntities (so I can query against my custom entities). Can someone confirm if this is currently impossible? Or give an example of how one would go about it?
This works:

            var res = from c in p.Linq<task&gt()
                      select c;
            string msg = "";
            foreach (task dyn in res.ToList<task>())
            {
                msg += dyn.ToString();
            }

If you s/task/DynamicEntity/ it no longer works :)  Just want to confirm it's currently undoable before I go write lots more boilerplate...
edit: angle brackets

A: (I implemented the original version of LinqtoCRM and I'm still a maintainer).
I do not believe dynamic entities are supported. There is some related discussion on the forum. Maybe give XrmLinq a try.


text:
Q: make div as wide as icon-card As you can see, the transparent block in the middle is wider than the containing block. I tried to set left/right, margin-left/right and width, none of them changed the way the block looks.

HTML code:
<ion-list>
    <ion-card ion-item no-lines>

      <button ion-button icon-only clear class="info-icon">
        <ion-icon name="information-circle"></ion-icon>
      </button>

Descriptions go here. blah blah blah blah blah blah blah blah blah blah blah. blah blah blah blah blah blah blah

      <ion-card-content>
      </ion-card-content>
    </ion-card>
</ion-list>

CSS:
ion-card-content {
    background: rgb(0, 0, 0);
    color: #fff;
}

.info-icon {
    position: absolute;
    top:4%;
    right:5%;
}

.dish-description {
    position: absolute;
    top: 20%;
    height: 200px;
    width:50%;
    background-color: rgba(0, 0, 0, 0.7);
    text-align: center;
}

.dish-description h3 {
    color: #fff;
    vertical-align: middle;
}

A: When you have position: absolute, margin no longer works. Try this
.dish-description {
    position: relative;
    top: 20%;
    margin: 10px; //adjust as needed
    height: 200px;
    max-width:50%;
    background-color: rgba(0, 0, 0, 0.7);
    text-align: center;
}

A: There are few ways to do it ,
The trick is , you have to create the main container which holds the inner ion card.
We can use flex or div , For an instances, If youre making a responsive layout .
I would suggest creating using percentage but that does not mean it will solve all issue, keep in mind that ionic framework does have different styling with different operating system . To overwrite ionic styling, there are few ways to it.Use debugging mode from your browser , it will help and save alot of try and error time.
To add on,
There are certain styling that is pre-generated , Like an example
,
whatever you put inside "ion-item" will have a few classes appended to it , like md-inner-item and so on..
So , to answer your question,
First try creating a main container , The div inside the ion-card, put a styling that has the max-width that is not more than the parent DOM.
Example

 //put max-width  to 100%
  <ion-card class="">

 //put max-width : 80%

Descriptions go here. bla

  <ion-card>
  </ion-card>

I hope this helps. :)


text:
Q: Lecture/presentation/event: "conduct" vs. "carry out" vs. "hold" When talking about a lecture, presentation, or event, what verb should be used?
As far as I understand, any of conduct, carry out, or hold are possible here. What's the difference, and which of them (if any) is the best option?
I'm particularly interested in something like this:

Professor A is going to [INSERT VERB] a lecture about B next Thursday, February 14th.

A: You give lectures and presentations. You can also deliver them. You hold an event if you organise it. You may conduct an experiment. You carry out some task.


text:
Q: How do I retrieve the Subscriber List for an Event at runtime? When using a Delegate, I can use Delegate.GetInvocationList() Method to retrieve the invocation list of the delegate at runtime.
Is there a way to access the subscriber list that has been associated with an event? I ran the code from this example (SO#1237001) and the immediate window allowed me to cast the SecondChange event to a System.MultiCastDelegate and then invoke the GetInvocationList method.
However, in my scenario I am working with a System.Windows.Forms.DataGridView and I would like to inspect the invocation list of the CellClick event at runtime.  However, when I try any kind of cast on CellClick, I recieve the following error:

The event
  'System.Windows.Forms.DataGridView.CellClick'
  can only appear on the left hand side
  of += or -=

I can see there are clearly differences in the declarations of these events.  In the Clock example the event is declared like this:
public event Func<DateTime, bool> SecondChange;

And in the DataGridView the event is declared like this:
[SRDescription("DataGridView_CellClickDescr"), SRCategory("CatMouse")]
public event DataGridViewCellEventHandler CellClick
{
    add
    {
        base.Events.AddHandler(EVENT_DATAGRIDVIEWCELLCLICK, value);
    }
    remove
    {
        base.Events.RemoveHandler(EVENT_DATAGRIDVIEWCELLCLICK, value);
    }
}

Why can one call GetInvocationList on the Clock example, but not on the DataGridView event?  Is there any way for me to get the same type of information from the DataGridView event that GetInvocationList returns?

A: The whole point of an event it defines (only) an add/remove API (like how a property defines get/set).
The entire point of an event is that externally you can't do this (access the subscribers). I'm guessing that in the "clock" example, the code that accesses the list is inside the type that declares the event; that is fine: inside the type, you have full access to the backing implementation (often a delegate field).
Externally, you should only care about your own handlers, that you already know about because you subscribed them. Attempts to fetch the backer exist, but it is brittle and not recommended. In this case, it uses an EventHandlerList, for example.
Why do you need this? It usually means that you are doing something wrong (sorry, but it does).


text:
Q: How to bind visibiility and content of label based on validation done on the text entered by user in textbox? I am writing simple application. The UI has two textboxes, for Username and Password, and button to submit the information. I wanted to use routed commands instead of buttonclick event.
Username should contain alphanumeric characters only, if user enter any other special characters, it should display a label saying invalid characters entered. So I wanted to bind the visibility and content of that label based on the validation done on Username textbox field.
Below is code I have made but it is not working as expected. Can any one help me where I am doing wrong?
Below my main Window
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;

namespace ExcelUtility
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    ViewModel viewModelObj = new ViewModel();
    public MainWindow()
    {
        InitializeComponent();
    }

    void navigatePageExecuted(object target, ExecutedRoutedEventArgs e)
    {
        SubmitUserDetails(txtUserName.Text + ";" + txtPassword);
    }

    void navigatePageCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
         if (!string.IsNullOrWhiteSpace(txtUserName.Text))
        {
            viewModelObj.Username = txtUserName.Text;
        }
        e.CanExecute = viewModelObj.VaidUserName;        }

    private void SubmitUserDetails(string credentials)
    {
        this.Cursor = Cursors.Wait;
        prgValidate.Visibility = Visibility.Visible;
        MainGrid.IsEnabled = false;
        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.RunWorkerAsync(credentials);
    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        prgValidate.Visibility = Visibility.Collapsed;
        string Result = (string)e.Result;
        MessageBox.Show(Result); //Here I need to call some other functions based on return value for simplicity i have changed
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        string[] credentials = e.Argument.ToString().Split(';');
        e.Result = viewModelObj.validateCredentials(credentials[0], credentials[1]);
    }
}
}

This is my xaml
<Window x:Class="ExcelUtility.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ExcelUtility"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:BoolToVisibleOrHidden x:Key="BoolToVisibilityConverter"/>
</Window.Resources>
<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:CommandsLibrary.navigatePageCommand}" Executed="navigatePageExecuted" CanExecute="navigatePageCanExecute"/>
</Window.CommandBindings>
<Grid Name="MainGrid">
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="40,44,0,0" Name="tbUserName" Text="Username" VerticalAlignment="Top" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="136,42,0,0" Name="txtUserName" VerticalAlignment="Top" Width="163" Text="{Binding Username, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="138,19,0,0" Name="tbNotify" Text="{Binding Notification, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="161" Visibility="{Binding NotVaidUserName,Converter={StaticResource BoolToVisibilityConverter}}" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="138,98,0,0" Name="txtPassword" VerticalAlignment="Top" Width="161" />
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="44,107,0,0" Name="tbPassword" Text="Password" VerticalAlignment="Top" Width="65" />
    <Button Command="{x:Static local:CommandsLibrary.navigatePageCommand}" Content="Submit" Height="23" HorizontalAlignment="Left" Margin="172,167,0,0" Name="btnSubmit" VerticalAlignment="Top" Width="109" />
    <ProgressBar Height="24" IsIndeterminate="True" Visibility="Collapsed"  HorizontalAlignment="Left" Margin="52,232,0,0" Name="prgValidate" VerticalAlignment="Top" Width="257" />
</Grid>
</Window>

This is my viewModel
using System;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;

namespace ExcelUtility
{
  public class ViewModel
  {
    public event PropertyChangedEventHandler PropertyChanged;
    private bool _notVaidUserName;
    public bool NotVaidUserName
    {
        get { return _notVaidUserName; }
        set
        {
            _notVaidUserName = value;
            RaisePropertyChanged("NotVaidUserName");
        }
    }

    private string notification;
    public string Notification
    {
        get
        {
            return notification;
        }
        set
        {
            if (notification != value)
            {
                notification = value;
                RaisePropertyChanged("Notification");
            }
        }
    }

    private string username;
    public string Username
    {
        get
        {
            return username;
        }
        set
        {
            if (username != value)
            {
                username = value;
                NotVaidUserName = VaidateUserName(username);
                RaisePropertyChanged("Username");
            }
        }
    }

    public bool VaidateUserName(string strUsername)
    {
        bool bValidUserName = false;
        if (!string.IsNullOrWhiteSpace(strUsername))
        {
            if (new Regex(@"^[a-zA-Z0-9]*$").IsMatch(strUsername))
            {
                bValidUserName = true;
                if (strUsername.Length > 7)
                {
                    Notification = "Max allowed key length is 6";
                    bValidUserName = false;
                }
            }
            else
            {
                Notification = "No special characters allowed";
            }
        }
        return bValidUserName;
    }

    public string validateCredentials(string Username, string Password)
    {
        return "Valid Credentials";
    }

    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

class BoolToVisibleOrHidden : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        object returnvalue = new object();
        returnvalue = (bool)value ? Visibility.Visible : parameter != null ? Visibility.Collapsed : Visibility.Hidden;
        return returnvalue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (Visibility)value == Visibility.Visible;
    }
}
}

A: First define two properties like below:
private bool isValid = true;
    public bool IsValid
    {
        get
        {
            return isValid;
        }
        set
        {
            if (isValid != value)
            {
                isValid = value;
                OnPropertyChanged("IsValid");
            }
        }
    }
    private string username;
    public string Username
    {
        get
        {
            return username;
        }
        set
        {
            if(username != value)
            {
                username = value;
                IsValid = ValidateForSpecialCharacters(username);
                OnPropertyChanged("Username");
            }
        }
    }

Then bind them to your xaml like this:
    <TextBlock Text="Username contains special characters."
               Visibility="{Binding IsValid,Converter={StaticResource BoolToVisibilityConverter}}" />
    <TextBox Text="{Binding Username, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />

PS: Don't forget to implement BoolToVisibility converter class and ValidateForSpecialCharacter method. I think you can handle it on your own. By the way, if I were you, I would use ValidationRule instead of this way.
Hope this help.

A: You must create a boolToVis converter, which convert False to collapsed and True to visible.
After this, you can bind the bool value to the visibility property of your item.
This is the converter (you can put this in a single file and call it from xaml):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace yourNamespace.ViewModel
{
    [ValueConversion(typeof(bool), typeof(bool))]
    public class InverseBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
           System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                return !(bool)value;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
           System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                return !(bool)value;
            }
            return value;
        }
    }
}

then, from your xaml, at the the beginning of the file:
<UserControl.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</UserControl.Resources>

or if you use a window:
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>

then, finally, in your textBox:
<dxe:TextEdit Visibility="{Binding YOURBOOLFLAG, Converter={StaticResource BoolToVis}}" EditValue="TextHere"/>

(TextEdit is a devexpress element; you can also use the classic textBox in the same way)
in this way, when you see that the text is not correct for you, you can set the bool flag to false and hide the element.

A: You could simply implement a converter that check the username character like so:
class VisibilityConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var rgx = new Regex(@"^[a-zA-Z0-9]*$");
        if (value == null) return Visibility.Hidden;
        return (rgx.IsMatch(value.ToString()))?Visibility.Hidden:Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

don't forget to add the converter to the window resources
 <Window.Resources>
    <conv:VisibilityConverter x:Key="VisibilityConverter"/>
</Window.Resources>

and finally use that converter in your UI to check the string entered in the textBox
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="50"/>
        <RowDefinition Height="50"/>
        <RowDefinition Height="50"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="Username" Grid.Column="0" Grid.Row="0"/>
    <TextBlock Text="Password" Grid.Column="0" Grid.Row="1"/>
    <TextBox  Grid.Column="1" Grid.Row="0" Text="{Binding Username,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
    <TextBox  Grid.Column="1" Grid.Row="1" Text="{Binding Password,Mode=TwoWay}"/>
    <Button Content="login" IsEnabled="{Binding Username,Converter={StaticResource VisibilityConverter},Mode=TwoWay}" Grid.Column="1" Grid.Row="2"/>
    <TextBlock Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Text="invalid characters entered"  VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding Username,Converter={StaticResource VisibilityConverter}}"></TextBlock>

</Grid>


text:
Q: When to create a new table? I have an application with employees and their work contracts.
Each work contract has a Vacation. We keep track of how many days the company owes the employee ("VacationOwe") and how many he has taken ("VacationTaken").
Should I make this "VacationOwe" and "VacationTaken" a property of the Contract, or should I create a class (table) called Vacaction with the properties "VacationOwe", "VacationTaken" and "ContractId" and join the two tables?
What are the advantange of both methods?
Is there any rule when you should create a new class or table or keep the data in one.

A: If the two properties are truly only related to an employee, there's no benefit of creating a separate table. Performance will be worse and you'll constantly have to join on those tables.
For this specific example, it seems like the vacation days may also be linked to a year. If that's the case, a separate table would make sense so you can track vacation days taken/owed by employee and year.

A:
should I make this "VacationOwe" and "VacationTaken" a propertie o the employee

Most probably...No. Because this defeats normalization. Also, it does not provide information about when the vacations were taken (in case you care about that). In addition to that, you have to do this calculation for every employee, every year.

Use a class (table) Call Vacaction with properties "VacationOwe" and "VacationTaken" and "EmployeeId" and cross the two tables?

It is not good to have a singleton class in this case. In general you should avoid singletons in most cases.
So what to do? Well, if you system does not care about vacation details, you could go with the first solution. Maybe you want to consider option (A) below or If you would like to have a more generic approach you could do something similar to option (B). It all depends on your detailed requirements.


text:
Q: Angular 4 with TypeScript: passing parameters by reference I'm just starting to develop a web application with angular 4 with TypeScript language.
My question is: if I initialize a string variable with the value of a data field in my class, it looks like the value is passed for copy and not for reference.
Is there a way to pass the parameter for reference?
Example:
export class MyObject {
   string1: string;
   string2: string;
}

export class MyClass {
   myString: string;
   object: MyObject;
   array[]: MyObject[];

   constructor() {
      this.array = [{
       string1: this.myString;
       string2: this.myString;
      }];
   }

}

If I tried to change the value of field this.myString and then use string interpolation in my HTML template
{{myString}}

{{array[0].string1}} {{array[0].string2}}

the only value that has changed is myString, while the other two values remained the same as myString's first value. This is because it seems that the passage of the parameters has been done for value and not by reference.
Sorry if the question is trivial, but I'm learning TypeScript right now

A: You should to change value from array like
<input [(ngModel)]="array[0].string1">

In ur array new instances of myString;

A: This is generally the way variables work in Javascript (also most other modern programming languages, Java, C#, etc). A common way to pass by reference is to create an additional object that holds the string and assign the reference to that object anywhere you need it.
For example:
export interface MyObject {
   string1: Ref;
   string2: Ref;
}
export interface Ref {
    value: string
}
export class MyClass {
   myString: Ref;
   array: MyObject[];

   constructor() {
      this.myString = { value: "old Vlaue"};
      this.array = [{
       string1: this.myString,
       string2: this.myString
      }];
      this.myString.value = "New Value"
   }
}

When you bind you then use:
{{myString.value}}

{{array[0].string1.value}} {{array[0].string2.value}}


text:
Q: A .NET exception (TypeLoadException) occured in the module I have a Visual studio project with lots of commercial DLL files that I use in my program.
I have used many of these DLL files so far without any problem.
Yesterday I had to use a yet another DLL file. I linked the DLL file as a referense (as usual), I can see it is added to the project since code-completion works and I could build the project successfully.
But when I run this on the target PC, I get a TypeLoadException.
A .NET exception (TypeLoadException) occured in the module

I tried to catch and print the exact information in the exception but I did not help at all.
Below is the complete exception that I receive:
A .NET exception (TypeLoadException) occured in the module LightSwitch\nError message: Could not load type 'Backbone2.LightMode_Status_Ctr_1' from assembly 'Backbone2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.\nThrowing method: DiagModule.SetSwitch\n

(I can not perform any debugging and provide more info, since I build my project as  dll which is then used on the target PC, and actually I can run the program on my PC since it is missing all the required hardware)

A: Check whether the dll is built for the same architecture as your pc. I mean, if your pc is 64 bit, make sure that the dll is built corresponding to that and vice versa

A: Thanks for all the replies, I managed to find the issue.
The problem was that the project included a couple of library files (dll) with different versions in different folders. During runtime (still don´t know why) a dll file would be choose and since the file was different between different versions, some methods were missing. So updating the DLL files to the same version in all folders fixed the issue.

A: Check that the DLL is in the right location (or in GAC) on the target PC.

A: Launch FusLogVw.exe -- it is part of .Net SDK and could be launched from VS 2010 command prompt. Configure logging to record all failures. Reproduce problem, refresh view in FusLogVw.exe window. You should be able to find record that corresponds to your problem, it will tell you exactly what it is doing and you should be able to figure out how to correct the problem.

A: Check if you are reference one version of the DLL and another one is loaded (from GAC) during runtime.


text:
Q: Convert a string to uppercase at compile time Is it possible to convert a string to uppercase at compile-time without any size limitation?
Eg.:
char* myString = TO_UPPERCASE("a big string here!");

Would generate:
char* myString = "A BIG STRING HERE!";

A: It is possible, using Boost.Hana and C++14.
#include <iostream>
#include <boost/hana/unpack.hpp>
#include <boost/hana/string.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/value.hpp>
#include <boost/hana/core/to.hpp>

constexpr char to_upper(char c) noexcept
{
    switch(c) {
    default: return c;
    case 'b': return 'B';
    case 'i': return 'I';
    case 'g': return 'G';
    case 's': return 'S';
    case 't': return 'T';
    case 'r': return 'R';
    case 'n': return 'N';
    // The other characters in the alphabet.
    }
}

auto to_upper_str = [](auto hana_str) noexcept {
    return boost::hana::unpack(hana_str, [](auto... chars) noexcept {
        return boost::hana::string_c<
            boost::hana::char_c<to_upper(boost::hana::value(chars))>...>;
    });
};

int main()
{
    auto str = to_upper_str(BOOST_HANA_STRING("Big string."));
    std::cout << boost::hana::to<const char*>(str) << '\n';
}

This outputs BIG STRING. See on Coliru.

A: As long as you won't try to pass string chain directly to the template and you create helper variable to store this sequence to be further upper_cased you can utilize this code (c++1z):
#include <utility>
#include <iostream>
#include <type_traits>
#include <typeinfo>

template <class T>
struct string_literal_length;

template <std::size_t N>
struct string_literal_length<char const[N]>{
    static constexpr std::size_t value = N;
};

template <class STR_T, STR_T &, class = std::make_index_sequence<string_literal_length<STR_T>::value>>
struct string_literal;

template <class STR_T, STR_T &STR, std::size_t... Is>
struct string_literal<STR_T, STR, std::index_sequence<Is...>> {
    static constexpr std::size_t size = string_literal_length<STR_T>::value;
    static constexpr char value[string_literal_length<STR_T>::value] = {STR[Is]...};
};

constexpr char str[] = "abc";

template <class SL, class = std::make_index_sequence<SL::size>>
struct string_literal_to_upper;

template <class SL, std::size_t... Is>
struct string_literal_to_upper<SL, std::index_sequence<Is...>>{
    static constexpr char value[SL::size] = { ((SL::value[Is] >= 'a' && SL::value[Is] <= 'z')?(static_cast<char>(SL::value[Is] - 'a' + 'A')):(SL::value[Is]))...};
};

int main() {
    std::cout << string_literal_to_upper<string_literal<decltype(str), str>>::value << std::endl;
}

Output:

ABC

[live demo]
Edit:
To work in VS the code need to be a little bit modified:
#include <utility>
#include <iostream>
#include <type_traits>
#include <typeinfo>

template <class T>
struct string_literal_length;

template <std::size_t N>
struct string_literal_length<char const[N]>{
    static constexpr std::size_t value = N;
};

template <class STR_T, STR_T *, class = std::make_index_sequence<string_literal_length<STR_T>::value>>
struct string_literal;

template <class STR_T, STR_T *STR, std::size_t... Is>
struct string_literal<STR_T, STR, std::index_sequence<Is...>> {
    static constexpr std::size_t size = string_literal_length<STR_T>::value;
    static constexpr char value[string_literal_length<STR_T>::value] = { (*STR)[Is]...};
};

struct Literal {
   static constexpr char const str[] = "abc";
};

template <class SL, class = std::make_index_sequence<SL::size>>
struct string_literal_to_upper;

template <class SL, std::size_t... Is>
struct string_literal_to_upper<SL, std::index_sequence<Is...>>{
    static constexpr char value[SL::size] = { ((SL::value[Is] >= 'a' && SL::value[Is] <= 'z')?(static_cast<char>(SL::value[Is] - 'a' + 'A')):(SL::value[Is]))...};
};

int main() {
    std::cout << string_literal_to_upper<string_literal<decltype(Literal::str), &Literal::str>>::value << std::endl;
}

[live demo]


text:
Q: mod redirect and rewrites ( Part 2 ) Further to my previous questions i am getting my self into a mess, so i will try and lay my problem/s out as best as i can here.
I am tidying up my URL structure but have the problem that my urls are well indexed in Search engines, so i need to rewrite my urls while also redirect them.
With help earlier on a previous question i currently have the following in my .htaccess
Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

# Rewrite A newly added section rewrite ( no redirect required )
RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

So, this is all working as expected, but i have another url that ends in a index.php that sometimes but not always has php variables, this i also need to rewrite and redirect, by trying to do it myself i am creating a conflict of some sorts, and its not working as expected.
The URL i need to rewrite & redirect with a 301 is below
http://www.mydomain.com/news/dentistry_dental/index.php?month=February&year=2011

With the previous index.php rule it currently displays as

http://www.mydomain.com/news/dentistry_dental/?month=February&year=2011

Half way there i guess... I need it to be the following

http://www.mydomain.com/dental_news/February/2011

Baring in mind that the url sometimes has no variables as below
http://www.mydomain.com/news/dentistry_dental/index.php

Which is currently with the index.php rule above is showing as

http://www.mydomain.com/news/dentistry_dental/

This needs to be

http://www.mydomain.com/dental_news/

So yes, i am totally crap at this stuff, it is entirely new to me, so if i can get this sorted ill be a very happy bunny indeed!
Thanks All
EDIT
Ok my current .htaccess looks as below.
Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]
RewriteRule ^dental_news/$ /news/dentistry_dental/index.php [L]

As it stands with this, The following occurs
www.mydomain.com/news/dentistry_dental/index.php
-> www.mydomain.com/dental_news/

( ^ Correct )
www.mydomain.com/news/dentistry_dental/index.php?month=May&year=2011
-> www.mydomain.com/dental_news/April/2011

( ^ Wrong : Showing right path in url bar, but displaying article_detail.php instead of index.php with variables)
I am guessing that 2 of the rules are similar and one is picking up the index.php with year and month variables and sending to article_detail page. I might be wrong however and i have no idea how to fix.
EDIT #2
Current .htaccess as below.
Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^dentalsupportuk.com [nc]
rewriterule ^(.*)$ http://www.dentalsupportuk.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.dentalsupportuk.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]
RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)$ news/dentistry_dental/index.php?month=$1&year=$2&redirect [L]

www.mydomain.com/dental_news/ is now rewriting to  www.mydomain.com/dental_news/ which doesnt exist so 404 error ( should be rewriting to www.mydomain.com/news/dentistry_dental/ )
www.mydomain.com/dental_news/100/some-title is now rewriting as expected to www.mydomain.com/news/dentistry_dental/article_detail.php with the variables ( working )
www.mydomain.com/news/dentistry_dental/article_detail.php?article=100&title=some-title is redirecting as expected to www.mydomain.com/dental_news/100/some-title and displaying correctly ( working )
www.mydomain.com/news/dentistry_dental/index.php?month=May&year=2010 is redirecting but crashing out Firefox stating ( Firefox has detected that the server is redirecting the request for this address in a way that will never complete. ) ( Not Working, is this some sort of loop causing this? )
www.mydomain.com/dental_news/July/2010/   the rewriting is giving me a 404 error.
So yes, im all over the place, maybe ive put in wrong order or something, but the more i mess the more im scared of breaking everything. Any ideas?
Regards
M

A: Try adding the follow two rules:
RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]

RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]

I don't believe it causes any conflicts, and seems to cover the two scenarios you described.
EDIT
OK, so if I'm getting this correct, the URLs that are /dental_news/2968/Redefining-oral-hygiene-intervention should be rewritten to /news/dentistry_dental/article_detail.php with the proper querystrings.  And then the /dental_news/April/2011 should be rewritten to /news/dentistry_dental/index.php.  So...if that is the case, you should be able to add the following rule:
RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)$ news/dentistry_dental/index.php?month=$1&year=$2&redirect [L]

It would also probably make sense to make the following update:
Current: RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]
Updated: RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]
The difference there being that it is more specific, and the first regex group will only match a group of digits, and will help to avoid conflict with your rule that is rewriting to the index.php file.
EDIT 2
I believe I tested all of the URLs you provided, and they seem to be working now.  There were a couple of redirect loops that we weren't accounting for.  Hopefully this will help...
Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

RewriteRule dental_news/$ /news/dentistry_dental/?rewrite [L]

# Rewrite dental news article to neat nice url
# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&rewrite [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [R=301]

# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]

# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)/?$ news/dentistry_dental/index.php?month=$1&year=$2&rewrite [L]

Hope this helps.