text:
Q: I edited an old commit message but git log shows the edited commit with older date higher than commits created more recently I edited a commit message by running git rebase -i <commit-yesterday> and selecting reword option for rebasing. Afterward, I ran push --force to publish the change to the remote repository. My expectation is that when I run git log, I see a list like the following:
commit 11111111
Date: Today 16:00:00
Message: The commit created Today at 16:00:00

commit 22222222
Date: Today 14:00:00
Message: The commit created Today at 14:00:00

commit 33333333
Date: Today 10:00:00
Message: The commit created Today at 10:00:00

commit 44444444
Date: Yesterday 15:00:00
Message: The message of this commit updated Today at 17:00:00 while it was created yesterday at 15:00:00

But I see the following list  that the updated commit is at the top with the old commit date and a new commit ID and the old commit is shown with its old message and old commit ID:
commit 55555555
Date: Yesterday 15:00:00
Message: The message of this commit updated Today at 17:00:00 while it was created yesterday at 15:00:00

commit 11111111
Date: Today 16:00:00
Message: The commit created Today at 16:00:00

commit 22222222
Date: Today 14:00:00
Message: The commit created Today at 14:00:00

commit 33333333
Date: Today 10:00:00
Message: The commit created Today at 10:00:00

commit 44444444
Date: Yesterday 15:00:00
Message: The commit created Yesterday at 15:00:00

A: Every commit has two date-and-time stamps, not just one.  One time stamp is for the author and the other is for the committer.  In a new commit you just made from scratch, Git sets author and committer to be the same, and the two time stamps to be the same.  Copying a commit, however, results in a new committer (you and now) while preserving the original commit's author and author-time stamps, at least by default.
When you use git rebase, or git commit --amend, to "modify" a commit, you don't actually change the original commit.  You can't—nothing can; not even Git itself can change the original commit—so instead, you get a new commit, with a new hash ID, unique to the new commit.  The old hash ID is still valid and still refers to the old commit.  If the old commit becomes unreachable,1 it will eventually expire and the old commit will be truly gone, but Git tries hard to keep it around for at least a month or so, in case you change your mind about it and want it back.
What you don't show here is how you are running git log.  What Git isn't showing here—because you did not ask for it—is the underlying commit graph.  Git is all about commits, and the commits themselves form a Directed Acyclic Graph or DAG.  A lot of Git commands and viewers really should show you the graph, because that graph is super-important.  The git log command can show you the graph, but you have to ask for it:
git log --graph

or my favorite:
git log --all --decorate --oneline --graph

See Pretty git branch graphs and in particular this answer.
To get Git to show you both date-and-time stamps, add --pretty=fuller and omit --oneline, e.g.:
git log --all --decorate --graph --pretty=fuller

In this case, both your original commit and your reworded commit are still reachable—though exactly how, I can't say without viewing the graph—so you see the reworded commit, with its new hash ID, and showing its new message ... and then you also see the original commit, with its original hash ID, and showing its original message.
A graphical viewer, or running git log with --decorate and --graph, will help explain why you can still see the old commit.  Without the graph and its "decorations"—the branch and tag names that allow Git to find commits in the first place, in the jumble of random-looking hash IDs—all we can do is guess why your old commit is also showing up.

1This is a technical term with a rather long definition.  See the web site Think Like (a) Git to get started on that.

A: I found the magic of git log. Since I had rebased the commit, its Commit Date had been changed, but Author Date never changes. However, the command git log sorts commits based on Commit Date (in descending order) but it shows Author Date of commits. This caused confusion. To show both Commit Date and Author Date, use --pretty=fuller option. In other words, running the following command makes all things clear:
git log --pretty=fuller

Usually, Commit Date and Author Date are the same but git rebase, git commit --amend, and cherry-picks are common cases that Commit Date is different from Author Date for a commit.

A: git rebase -i 44444444 will show the commits from 44444444 without including 44444444. And all the commits from the commit you have edited will be having new hashes now. In your case you will see the latest commit hash also updated.
Edit:
I have rerun your scenario and see the output as you expect.
git-test - master ❯ git log --oneline -n 6
78eb09a (HEAD -> master) 222222
6ec4cc9 33333
58d9aea 444444 first message
fc9cae1 oldest

git-test - master ❯ git rebase -i fc9cae1
[detached HEAD 19328bf] 444444 modified message
 Date: Tue Oct 8 14:54:27 2019 +0530
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 b
Successfully rebased and updated refs/heads/master.

git-test - master ❯ git log --oneline -n 6
82b30ed (HEAD -> master) 222222
34c1948 33333
19328bf 444444 modified message
fc9cae1 oldest


text:
Q: Mysql query select sum where clause I have a MySQL database with 2 tables called mutaties and products
in the mutaties you have for example a product_id(which corresponds to a product id in the products database.
so we now get the current inventory using the SUM(aantal) from the mutaties database.
the product table has for each product a threshold.
What I want to do now is setup a mysql query that gets every product that is below the threshold with his current inventory.
Right now I have this:
SELECT *
  FROM products
     , mutaties
 WHERE SUM(aantal) < threshold

But I get the error invalid use of group function.
What is the best way to do this?
This is my products table:
enter image description here
translation of the columns is id,brand,model,threshold
and this is my mutaties database:
enter image description here
and here is the mutaties table translation of the colums: id product_id quantity date description

A: Like jarlh wrote in that comment, you should probably use the modern JOIN syntax.
Therefore, something like this should work:
select p.id, sum(m.aantal) as aantalsum
from products as p
join mutaties as m on (m.product_id = p.id)
group by p.id, p.threshold
having sum(m.aantal) < p.threshold

Things to note:

*

*If you have products without mutaties, they will not appear in that select. If you need those, use left outer join instead.

*You have products with a threshold of 0, they will probably also not appear at all.

*If you need more columns in your select list, you also need to add them to the group by expression

redpajama_set_name: RedPajamaStackExchange


text:
Q: slow deleting of multiple records in mysql I noticed that on test server deleting multple rows from table takes much time, for example, deleting 100K rows takes about 80-90 seconds. I use innodb engine in mysql. There are not DELETE triggers. The table has now about 23M rows.
The query that takes long is something like:
DELETE FROM contacts WHERE list_id = som_list_id

Index is added.
EXPLAIN SELECT *
FROM contacts
WHERE list_id =118

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  subscribers     ref     FK_list_id  FK_list_id  4   const   1

Here is profiling results:
    SET PROFILING = 1;
    DELETE FROM contacts WHERE list_id = 118;
    SHOW PROFILE FOR QUERY 1;

Status  Duration    CPU_user    CPU_system  Context_voluntary   Context_involuntary     Block_ops_in    Block_ops_out   Messages_sent   Messages_received   Page_faults_major   Page_faults_minor   Swaps   Source_function     Source_file     Source_line
starting    0.000031    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
checking permissions    0.000004    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    check_access    sql_parse.cc    4895
Opening tables  0.000031    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    open_tables     sql_base.cc     4860
System lock     0.000005    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_lock_tables   lock.cc     299
init    0.000079    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_delete    sql_delete.cc   79
updating    94.624119   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_delete    sql_delete.cc   277
end     0.000007    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_delete    sql_delete.cc   356
Waiting for query cache lock    0.000003    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    lock    sql_cache.cc    749
end     0.000006    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
query end   0.012509    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_execute_command   sql_parse.cc    4584
closing tables  0.000018    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_execute_command   sql_parse.cc    4636
freeing items   0.000038    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_parse     sql_parse.cc    5817
logging slow query  0.000006    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    log_slow_statement  sql_parse.cc    1581
logging slow query  0.000000    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    log_slow_statement  sql_parse.cc    1590
cleaning up     0.000003    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    dispatch_command    sql_parse.cc    1443

I tried to copy contacts to contact1 that doesn't have child tables which contacts has:
Results of profiling are similar:
Status  Duration    CPU_user    CPU_system  Context_voluntary   Context_involuntary     Block_ops_in    Block_ops_out   Messages_sent   Messages_received   Page_faults_major   Page_faults_minor   Swaps   Source_function     Source_file     Source_line
starting    0.000028    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
checking permissions    0.000005    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    check_access    sql_parse.cc    4895
Opening tables  0.000035    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    open_tables     sql_base.cc     4860
System lock     0.000014    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_lock_tables   lock.cc     299
init    0.000792    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_delete    sql_delete.cc   79
updating    72.805936   NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_delete    sql_delete.cc   277
end     0.000006    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_delete    sql_delete.cc   356
Waiting for query cache lock    0.000002    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    lock    sql_cache.cc    749
end     0.000006    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL
query end   0.013662    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_execute_command   sql_parse.cc    4584
closing tables  0.000017    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_execute_command   sql_parse.cc    4636
freeing items   0.000044    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    mysql_parse     sql_parse.cc    5817
logging slow query  0.000003    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    log_slow_statement  sql_parse.cc    1581
logging slow query  0.000002    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    log_slow_statement  sql_parse.cc    1590
cleaning up     0.000003    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    dispatch_command    sql_parse.cc    1443

It looks like updating consumes most of the time.
Why does deleting takes so long? Does it take so much time because I/O system of server is slow?
Thank you.

A: Is the table MyISAM?  If so try the
    delete quick from contacts...

Followed by
    optimize table contacts

Using quick does not have the database merge the index during the delete.  Then optimize reclaims unused space defrays the table.


text:
Q: grails getPersistentValue() value changes without saving I am using the getPersistentValue() method to determine how a property changed. However I've discovered that this method returns different values even if I have not explicitly saved the object.
Here's what I've narrowed it all the way down to...
trip.properties=[start:params.startmile,
        end:params.endmile,
        satusFlag:params.statusFlag,
        description:params.description
       ];

  // print statusFlag for checking
  log.debug(trip.getPersistentValue('statusFlag')+":"+trip.statusFlag);

  def driver=driverService.getValidDriver(params.driver,params.date);
  //the persistent value of statusFlag has changed!!!!
  log.debug(trip.getPersistentValue('statusFlag')+":"+trip.statusFlag);

The service call is just another criteria search to return a driver if he/she was employed at a date
 def driver=Drivers.createCriteria().get{
        and{
           eq('id',id);
           eq('division',division);
           le('startDate',compareDate);
           or{
               ge('endDate',compareDate);
               isNull('endDate');
           }
         }

     };
    return service

For some reason this query in a service forces my other objects to update their persistent values? Can someone explain why and how to avoid this?

A: I was able to solve this by importing the transaction annotation
import org.springframework.transaction.annotation.Transactional

and then adding
@Transactional(readOnly = true)

before the method that was being called.
However this won't work in all cases because not all service calls will be read only.


text:
Q: React-Three-Fiber Drei - Swap between Orbit Controls, Map Controls, and Fly Controls I have an app where I would like to move between views when the user clicks a button. Here is what I have so far:
<Canvas >

  <FlyControls enableDamping={false} movementSpeed={3} rollSpeed={0.05} dragToLook={true}  makeDefault={props.cameraView==0} />
  <PerspectiveCamera position={[0,14,2]} heightMin={2} heightMax={2} fov={45} lookat={new THREE.Vector3(0,0,2)} makeDefault={props.cameraView==0} up={new THREE.Vector3(0,0,1)} />

  <MapControls enableDamping={false} movementSpeed={3} rollSpeed={0.01} dragToLook={true} makeDefault={props.cameraView==1}/>
  <OrthographicCamera position={[0,0,20]} zoom={40} fov={45} lookat={new THREE.Vector3(0,0,2)} makeDefault={props.cameraView==1} up={new THREE.Vector3(0,0,1)} />

  <OrbitControls enableDamping={false} makeDefault={props.cameraView==2} />
  <PerspectiveCamera fov={45} position={[posX-2,posY-2,1.5]} lookat={new THREE.Vector3(posX, posY, 1.5)} makeDefault={props.cameraView==2} up={new THREE.Vector3(0,0,1)} />

There are a couple of issues. First, when the orbit controls is not present, the fly controls and map controls work just fine. However, when the orbit controls is added, the app starts with orbit controls and cannot be changed. Second, the lookat and camera positions don't seem to change with the algorithm.
I have also tried this ...
  // Calculations for different camera setups
  let posX = props.currentFixture!=null ? props.fixtures[props.currentFixture]['positions'][0]-props.origin[0] : 0;
  let posY = props.currentFixture!=null ? props.fixtures[props.currentFixture]['positions'][1]-props.origin[1] : 0;
  let lookat = props.cameraView!=2 ? new THREE.Vector3(0,0,2) : new THREE.Vector3(posX, posY, 1.5)

  return (
    <Canvas >

      <FlyControls enableDamping={false} movementSpeed={3} rollSpeed={0.05} dragToLook={true}  makeDefault={props.cameraView==0} />
      <PerspectiveCamera position={[0,14,2]} heightMin={2} heightMax={2} fov={45} lookat={lookat} makeDefault={props.cameraView==0} up={new THREE.Vector3(0,0,1)} />

      <MapControls enableDamping={false} movementSpeed={3} rollSpeed={0.01} dragToLook={true} makeDefault={props.cameraView==1}/>
      <OrthographicCamera position={[0,0,20]} zoom={40} fov={45} lookat={lookat} makeDefault={props.cameraView==1} up={new THREE.Vector3(0,0,1)} />

      <OrbitControls enableDamping={false} makeDefault={props.cameraView==2} />

This has the same issues. It appears that you can't really have separate controls and disable orbit controls, but that can't be right.


text:
Q: ¿Como obtener el valor seleccionado de un SELECT en Angular 4? Estoy iniciando en el framework Angular 4, y tengo una duda respecto al Select,
Necesito saber que opción selecciona el usuario de mi Select.
En mi App.component.html tengo este codigo :
<select name="" id="cantidad" (change)="capturar()">
  <option *ngFor="let dato of datos">
    {{dato}}
  </option>
</select>

Y en mi app.component.ts tengo este :
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  datos;
  constructor(){
    this.datos=[1,2,3,4,5,6,7,8,9,10];
  }
  capturar(){

  }
}

A: Estabas muy cerca, tienes que usar la directiva (ngModel) para a poder obtener el valor del <select>:
Ver Demo Online
<select [(ngModel)]="opcionSeleccionado" (change)="capturar()">
    <option value="0">Selecciona una opción</option>
    <option *ngFor="let dato of datos">
      {{dato}}
    </option>
</select>

<!-- Prueba para ver la opción seleccionado -->
<p [hidden]="opcionSeleccionado == '0'">Haz seleccionado la opción # {{ verSeleccion }}</p>

export class AppComponent  {
  datos;
  // Seleccionamos o iniciamos el valor '0' del <select>
  opcionSeleccionado: string  = '0';
  verSeleccion: string        = '';

  constructor(){
      this.datos = [1,2,3,4,5,6,7,8,9,10];
  }

  capturar() {
      // Pasamos el valor seleccionado a la variable verSeleccion
      this.verSeleccion = this.opcionSeleccionado;
  }
}

A: Estas son las dos maneras que mas recomienda Angular en su documentación Reactive forms o Template-driven forms.
Ejemplo con Reactive forms.
componen.html
<form [formGroup]="paisFormulario">
    <select id="pais" formControlName="pais">
        <option *ngFor="let p of paises" [ngValue]="p">{{ p }}</option>
    </select>
</form>

component.ts
        import { FormControl, FormGroup, Validators } from '@angular/forms';

            export class Component {

                paises: string[] = ['Mexico', 'España', 'Venezuela'];
                default: string = 'Mexico';

                paisFormulario: FormGroup;

                constructor() {
                    this.paisFormulario = new FormGroup({
                        pais: new FormControl(null)
                    });
                 // setValue es para agregarle un valor
                    this.paisFormulario.controls['pais'].setValue(this.default,
 {onlySelf: true});
                // para obtenerlo necesitarias un get por ejemplo
              this.paisFormulario.get('pais');
                }
            }

Template-driven forms
Es el ejemplo que puso Black Sheep Template-driven forms es un  los dos te pueden servir espero y te ayuden.
Puedes leer mas de eso en https://angular.io/guide/forms-overview


text:
Q: Why do I get System.NullReferenceException in my c# script while my executable of the same code is working? I have the following .csx script:
#r "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Management.dll"
using System.Management;
ManagementClass cls = new ManagementClass("\\\\.\\root\\default:StdRegProv");

When I run this using dotnet script I get this error:
System.NullReferenceException: Object reference not set to an instance of an object.
    at System.Management.MTAHelper.IsNoContextMTA()
    at System.Management.MTAHelper.CreateInMTA(Type type)
    at System.Management.ManagementPath.CreateWbemPath(String path)
    at System.Management.ManagementPath..ctor(String path)
    at System.Management.ManagementClass..ctor(String path)
    at Submission#0.<<Initialize>>d__0.MoveNext() in <..path..>\script.csx:line 3
 --- End of stack trace from previous location ---
    at Dotnet.Script.Core.ScriptRunner.Execute[TReturn](String dllPath, IEnumerable`1 commandLineArgs) in <...path...>\Temp\tmpBFB\Dotnet.Script.Core\ScriptRunner.cs:line 110

If I compile the following code in visual studio, everything works fine:
using System.Management;
class Script {
    static void Main() {
        ManagementClass cls = new ManagementClass("\\\\.\\root\\default:StdRegProv");
    }
}

Why ? How can I get my .csx script to work ?

A: dotnet script runs off .NET Core and I don't think WMI works in .NET Core as it needs COM interop. See this.
Also, global runtime dll for .NET CORE is not in GAC but rather in a runtime package store.


text:
Q: Storing escape characters in unix variable I am extracting a part from an existing file and storing it as a string in a variable.The string looks something like this.
var="*a
*b
*c"

Now as * is a special character in unix it doesnot work in further operations(like sed,grep) until I put an escape character infront of every *
Thats why,I am doing something like this -
echo $var | sed 's/\*/\\*/g'

On running this command in bash we get
echo $var | sed 's/\*/\\*/g'

\*a
\*b
\*c

which is the desired output,but when I try to store this in a variable, I am getting back my original variable like so
var=`echo $var | sed 's/\*/\\*/g'`
echo $var

*a
*b
*c

I am assuming this happens because the variable ignores the backslashes interpreting them as escape characters. How can I retain the backslashes and store them as in a variable?

A: The problem is caused by backticks. Use $( ) instead, and it goes away:
var="*a
*b
*c"
var=$(printf '%s\n' "$var" | sed 's/\*/\\*/g')
printf '%s\n' "$var"

(Why is this problem caused by backticks? Because the only way to nest them is to escape the inner ones with backslashes, so they necessarily change how backslashes behave; whereas $( ), because it uses different starting and ending sigils, can be nested natively).

That said, if your shell is one (like bash) with ksh-inspired extensions, you don't need sed at all here, as the shell can perform  simple string replacements natively via parameter expansion:
var="*a
*b
*c"
printf '%s\n' "${var//'*'/'\*'}"

For background on why this answer uses printf instead of echo, see Why is printf better than echo? at [unix.se], or the APPLICATION USAGE section of the POSIX specification for echo.


text:
Q: Trying to add 2 dates with DateTime Object PHP Hi there and thank you for the help. I will try to be breef.
I have a SQL table with one col named "duration" -> type Time
I need to get this "duration" and add to the actual DateTime -> date()
Till now I got something like these:
$id_mission = $_POST["id_mission"];
$sql="SELECT duration FROM missions WHERE id_mission='".$id_mission."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);

How do i pick this: $row['duration'] and convert to DateTime Object?
$date = new DateTime();
$get_datetime = $date->format('Y-m-d H:i:s');
$get_datetime->add(new DateInterval($row['duration']));

I got these sql error:

Fatal error: Call to a member function add() on string in C:\wamp64\www\players\actions\insert_mission.php on line 18

A: This line converts your DateTime object into a string which you are then trying to call the add() method with.  Strings don't have this method.
$get_datetime = $date->format('Y-m-d H:i:s');

To add the date from your row don't use the format method.
$date = new DateTime();
$date->add(new DateInterval($row['duration']));

The error message that you are seeing has nothing to do with SQL, it is telling you that your are trying to treat a string like an object.  Which doesn't work in PHP.


text:
Q: Trying to convert geometry to geography keep failing in MSSQL 2012 In MSSQL I have LineString in Geometry type.
When I try to convert it to geography using :
GEOGRAPHY::STGeomFromText(geom.MakeValid().STUnion(geom.MakeValid().STStartPoint().MakeValid()).STAsText(),4326)

I still get error that
Msg 6522, Level 16, State 1, Line 19 A .NET Framework error occurred during execution of user-defined routine or aggregate "geography":System.ArgumentException: 24200: The specified input does not represent a valid geography instance. Use MakeValid to convert the instance to a valid instance. Note that MakeValid may cause the points of a spatial instance to shift slightly.System.ArgumentException: at Microsoft.SqlServer.Types.SqlGeography..ctor(GeoData g, Int32 srid) at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid)

Any idea how I can convert it to geography ?
Any idea how I can share the LineString ? Its very long (exceeding this post body length)

A: I think that you have a minor error in your select statement. Try this:
GEOGRAPHY::STGeomFromText(geom.MakeValid().STAsText(),4326)

What you are doing is making a union between the linestring and a point, which doesn't really work. All you want to do is make your geometry valid, then convert it to geography.
Note that geography data types need to be in lat, lon already. SQL Server wont reproject data, so if you need to do that, I'd use either org2ogr or Quantum GIS.


text:
Q: Ember: using an #if helper in a component Obviously super new to Ember. Couldn't find an example of what I'm looking to do in docs.
Anyway, I have some code like this:
    {{#if (eq type 1)}}

             {{convert-type measurement showUnits=true myUnits=myUnits}}

    {{else}}
        {{convert-type measurement showUnits=true}}
    {{/if}}

And it seems pretty verbose. I want to do something like:

     {{convert-type
      measurement
      showUnits=true
      (if (eq type 1) myUnits=myUnits) }}

But I keep getting template errors. :/ Is this possible?

A: If think better method is to use computed property:
myUnitsPrim: computed('type', 'myUnits.[]', function() {
  return this.get('type') === 1 ? this.get('myUnits') : null;
})

and then
{{convert-type
      measurement
      showUnits=true
      myUnits=myUnitsPrim }}

or just:
{{convert-type
      measurement
      showUnits=true
      myUnits=(if (eq type 1) myUnits null) }}


text:
Q: UI Automation not working for DataGridView After trying out several solutions, I am in desperate need for help.
I tried several approaches, before finally copying and still being stuck with the solution from Getting full contents of a Datagrid using UIAutomation.
Let's talk code, please consider the comments:
// Get Process ID for desired window handle
uint processID = 0;
GetWindowThreadProcessId(hwnd, out processID);

var desktop = AutomationElement.RootElement;

// Find AutomationElement for the App's window
var bw = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ProcessIdProperty, (int)processID));

// Find the DataGridView in question
var datagrid = bw.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "dgvControlProperties"));

// Find all rows from the DataGridView
var loginLines = datagrid.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem));

// Badumm Tzzz: loginLines has 0 items, foreach is therefore not executed once

foreach (AutomationElement loginLine in loginLines)
{
    var loginLinesDetails = loginLine.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom));

    for (var i = 0; i < loginLinesDetails.Count; i++)
    {
        var cacheRequest = new CacheRequest
        {
            AutomationElementMode = AutomationElementMode.None,
            TreeFilter = Automation.RawViewCondition
        };

        cacheRequest.Add(AutomationElement.NameProperty);
        cacheRequest.Add(AutomationElement.AutomationIdProperty);

        cacheRequest.Push();

        var targetText = loginLinesDetails[i].FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "TextBlock"));

        cacheRequest.Pop();

        var myString = targetText.Cached.Name;
    }

}

I can neither fetch a GridPattern, nor a TablePattern instance from datagrid, both results in an exception:
GridPattern gridPattern = null;

try
{
    gridPattern = datagrid.GetCurrentPattern(GridPattern.Pattern) as GridPattern;
}
catch (InvalidOperationException ex)
{
    // It fails!
}

TablePattern tablePattern = null;

try
{
    tablePattern = datagrid.GetCurrentPattern(TablePattern.Pattern) as TablePattern;
}
catch (InvalidOperationException ex)
{
    // It fails!
}

The rows were added to the DataGridView beforehand, like this:
dgvControlProperties.Rows.Add(new object[] { false, "Some Text", "Some other text" });

I am compiling to .Net Framework 4.5. Tried both regular user rights and elevated admin rights for the UI Automation client, both yielded the same results described here.
Why does the DataGridView return 0 rows?
Why can't I get one of the patterns?
Kudos for helping me out!

Update:
James help didn't to the trick for me. The following code tough returns all rows (including the headers):
var rows = dataGrid.FindAll(TreeScope.Children, PropertyCondition.TrueCondition);

Header cells can then be identified by their ControlType of ControlType.Header.

A: The code that you are copying is flawed. I just tested this scenario with an adaptation of this sample program factoring in your code above, and it works.
The key difference is that the code above is using TreeScope.Children to grab the datagrid element. This option only grabs immediate children of the parent, so if your datagrid is nested it's not going to work. Change it to use TreeScope.Descendants, and it should work as expected.
var datagrid = bw.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "dgvControlProperties"));

Here is a link to how the various Treescope options behave. Also, I don't know how your binding the rows to the grid, but I did it like this in my test scenario and it worked flawlessly.
Hopefully this helps.
public class DataObject
{
    public string FieldA { get; set; }
    public string FieldB { get; set; }
    public string FieldC { get; set; }
}

List<DataObject> items = new List<DataObject>();
items.Add(new DataObject() {FieldA="foobar",FieldB="foobar",FieldC="foobar"});
items.Add(new DataObject() { FieldA = "foobar", FieldB = "foobar", FieldC = "foobar" });
items.Add(new DataObject() { FieldA = "foobar", FieldB = "foobar", FieldC = "foobar" });

dg.ItemsSource = items;

A: Your code looks fine though this could be a focus issue.
Even though you are getting a reference to these automation element objects you should set focus on them (using the aptly named SetFocus method) before using them.
Try:
var desktop = AutomationElement.RootElement;

desktop.SetFocus();

// Find AutomationElement for the App's window
var bw = desktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ProcessIdProperty, (int)processID));

and if that does not work try explicitly focusing on the dataGrid prior to calling "FindAll" on it i.e.
datagrid.SetFocus()

A: Why does the DataGridView return 0 rows?
The DataGridViewRows have a ControlType of ControlType.Custom. So I modified the line
// Find all rows from the DataGridView
var loginLines = datagrid.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem));

To
var loginLines = datagrid.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom));

That gets you all the rows within the DataGridView. But your code has that within the loop.
What pattern is supported by DataGridView (not DataGrid)?
LegacyIAccessiblePattern. Try this-
 LegacyIAccessiblePattern legacyPattern = null;

       try
       {
           legacyPattern = datagrid.GetCurrentPattern(LegacyIAccessiblePattern.Pattern) as LegacyIAccessiblePattern;
       }
       catch (InvalidOperationException ex)
       {
           // It passes!
       }

As I commented on @James answer, there is no support for UIA for DataGridView (again, not DataGrid).
If you search in google with terms: "UI Automation DataGridView" the first result has an incomplete answer. Mike replies with what provider class (Obviously one that extends DataGridView)to create within the source, unfortunately I have no clue as to how to make UIA load that class a provider. If anyone can shed some clues, Phil and I will be extremely pleased!
EDIT
Your DataGridView should implement the interfaces in that link above. Once you do that the ControlType of Row will be ControlType.DataItem instead of ControlType.Custom. You can then use it how you'd use a DataGrid.
EDIT
This is what I ended up doing -
Creating a Custom DataGridView like below. Your datagridview could subclass this too. That will make it support ValuePattern and SelectionItemPattern.
public class CommonDataGridView : System.Windows.Forms.DataGridView,
    IRawElementProviderFragmentRoot,
    IGridProvider,
    ISelectionProvider
{.. }

The complete code can be found @ this msdn link.
Once I did that, I played a bit with visualUIVerify source. Here is how I can access the gridview's cell and change the value. Also, make note of the commented code. I didn't need that. It allows you to iterate through rows and cells.
private void _automationElementTree_SelectedNodeChanged(object sender, EventArgs e)
    {
        //selected currentTestTypeRootNode has been changed so notify change to AutomationTests Control
        AutomationElementTreeNode selectedNode = _automationElementTree.SelectedNode;
        AutomationElement selectedElement = null;

        if (selectedNode != null)
        {
            selectedElement = selectedNode.AutomationElement;

            if (selectedElement.Current.ClassName.Equals("AutomatedDataGrid.CommonDataGridViewCell"))
            {
                if(selectedElement.Current.Name.Equals("Tej")) //Current Value
                {

                    var valuePattern = selectedElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

                    valuePattern.SetValue("Jet");
                }

                //Useful ways to get patterns and values

                //System.Windows.Automation.SelectionItemPattern pattern = selectedElement.GetCurrentPattern(System.Windows.Automation.SelectionItemPattern.Pattern) as System.Windows.Automation.SelectionItemPattern;

                //var row = pattern.Current.SelectionContainer.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewRow", PropertyConditionFlags.IgnoreCase));

                //var cells = row.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewCell", PropertyConditionFlags.IgnoreCase));
                //foreach (AutomationElement cell in cells)
                //{
                //    Console.WriteLine("**** Printing Cell Value **** " + cell.Current.Name);

                //    if(cell.Current.Name.Equals("Tej")) //current name
                //    {

                //        var valuePattern = cell.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

                //        valuePattern.SetValue("Suraj");
                //    }
                //}

                //Select Row
                //pattern.Select();

                //Get All Rows
                //var arrayOfRows = pattern.Current.SelectionContainer.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewRow", PropertyConditionFlags.IgnoreCase));

                //get cells
                //foreach (AutomationElement row in arrayOfRows)
                //{
                //   var cell = row.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "AutomatedDataGrid.CommonDataGridViewCell", PropertyConditionFlags.IgnoreCase));

                //    var gridItemPattern = cell.GetCurrentPattern(GridItemPattern.Pattern) as GridItemPattern;

                //    // Row number.
                //    Console.WriteLine("**** Printing Row Number **** " + gridItemPattern.Current.Row);

                //    //Cell Automation ID
                //    Console.WriteLine("**** Printing Cell AutomationID **** " + cell.Current.AutomationId);

                //    //Cell Class Name
                //    Console.WriteLine("**** Printing Cell ClassName **** " + cell.Current.ClassName);

                //    //Cell Name
                //    Console.WriteLine("**** Printing Cell AutomationID **** " + cell.Current.Name);
                //}

            }
        }

        _automationTests.SelectedElement = selectedElement;
        _automationElementPropertyGrid.AutomationElement = selectedElement;
    }

Hopefully this helps.

A: I run into this problem too, after researching, i figured out that you can only access data grid view with LegacyIAccessible. However, .NET does not support this. So, here are the steps:

*

*there are 2 versions of UIA: managed version and unmanaged version (native code). In some cases, the unmanaged version can do what the managed version can't.

=> as said here, using tblimp.exe (go along with Windows SDK) to generate a COM wrapper around the unmanaged UIA API, so we can call from C#.
I have done it here

*we can use this to access DataGridView now but with very limited data, you can use Inspect.exe to see.

The code is:

using InteropUIA = interop.UIAutomationCore;

if (senderElement.Current.ControlType.Equals(ControlType.Custom))
{
    var automation = new InteropUIA.CUIAutomation();
    var element = automation.GetFocusedElement();
    var pattern = (InteropUIA.IUIAutomationLegacyIAccessiblePattern)element.GetCurrentPattern(10018);
    Logger.Info(string.Format("{0}: {1} - Selected", pattern.CurrentName, pattern.CurrentValue));
}


text:
Q: Button action is not working on subView In one of my iOS project, I have added a subview for Filter ViewController(subview) on my Feed ViewController(main view) programmatically.
There are few button on Filter ViewController to select price, city etc.
The outlets are connected but when I am trying to shoot button action, it is not working.
I have also enabled the isUserInteractionEnabled but still it is not working.
Acc. to me, this is something related to subview on a view !! but to resolve this. Can you suggest me how to shoot a button action of subview it happen ?
class FilterViewController: BaseUIViewController{

   override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)

     cityButton.isUserInteractionEnabled = true
   }

   @IBAction func selectCity(_ sender: Any)
   {
    print("selectCity action")
   }
}

A: Add your FilterViewController as subview to your ViewController using the code below
filterViewController.willMove(toParentViewController: self)
self.view.addSubview(filterViewController.view)
self.addChildViewController(filterViewController)
filterViewController.didMove(toParentViewController: self)

A: @SandeepBhandari solution is still valid for similar issues.
These UIViewController extensions will be useful.
extension UIViewController {

func add(asChildViewController viewController: UIViewController, containerView: UIView) {
    addChild(viewController)
    containerView.addSubview(viewController.view)
    viewController.view.frame = containerView.bounds
    viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    viewController.didMove(toParent: self)
}

func remove(asChildViewController viewController: UIViewController) {
    viewController.willMove(toParent: nil)
    viewController.view.removeFromSuperview()
    viewController.removeFromParent()
}

}


text:
Q: Google apps script export a CSV Date format problem I have an issue that I am trying to resolve with the exported Date formats. My Google sheet has date format as MM/DD/YYYY and the CSV files have date format { Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time) }
Looking to see if there is a way to get this CSV download code to use a date format or MM/DD/YYY.
Snip of code+++++++++++++++++++
function convertRangeToCsvFile_(csvFileName, sheet) {
  // get available data range in the spreadsheet
  var activeRange = sheet.getDataRange();
  try {
    var data = activeRange.getValues();
    var csvFile = undefined;

    // loop through the data in the range and build a string with the csv data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row++) {
        for (var col = 0; col < data[row].length; col++) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = "\"" + data[row][col] + "\"";
          }
        }

        // join each row's columns
        // add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "\r\n";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}


text:
Q: Regarding Kentico 9 site deployment on Azure I want to deploy Kentico 9 site on Azure and want to use shared file system for my media content, can you please suggest which Azure configuration (Azure Cloud Services or Azure Web Apps) I should referred?

A: I'd highly recommend going with Web App over Cloud Services.  Mainly because Web App is almost like running on a regular server where Cloud Services is quite a bit different and harder to work with in my opinion.
Check this article out regarding some issues with Kentico and Azure Blog storage as well as how to setup your storage provider to only store media files.
http://www.kehrendev.com/blog/brenden-kehren/may-2016/problems-with-azure-and-kentico

A: Could you describe what do you mean by shared file system for my media content?
From my experience - it`s (a little bit) easier to deploy (and maintain) Kentico to Azure Web Apps but they do not provide so many customizations - in my humble opinion - the biggest one is you are not able to connect via remote desktop (but this is supported by Azure Cloud Services).
Please note - if you are using Cloud Services you must use Azure Blob Storage - source - which could be in conflict with your requirements.
You can find more information about Web Apps vs Cloud Services vs Virtual Machines on the mentioned page.
TL;DR; - if you do not need customizations, remote desktop and startup tasks - go for WebApps. If not, try to specify more requirements.
You can also check comparinson of the technologies from the Microsoft`s point of view here.

A: It's not clear who you want to share the media with...
If you want to share the assets amongst more Kentico instances or with a 3rd party system, I'd probably use the Azure Blob Storage. Kentico comes with a dedicated file provider for this exact use out of the box. It's called CMS.AzureStorage.
Using the blob storage is not a limiting factor in terms of hosting your app. You can still use all available options: Web Apps, VM or Cloud Service. There are some technical implications, of course. But they're all described in the documentation.
I recommend checking the comparison matrix to find a hosting option that suits your need best. Kentico recommends using App Service (Web Apps) for most projects as it's easiest to maintain. However, you can't use certain features like Kentico Windows services, for instance. Question is, do you really need them?


text:
Q: Parsing ASCII characters with Erlang Confused with what parsing needs to be done and at what end client/server.
When i send an Umlaut 'Ö' to my ejabberd,
it is received by ejabberd as <<"195, 150">>

Following this i send this to my client as Push notifications (via GCM/APNS silently). From there, the client builds by UTF-8 decoding on each numeral one by one (this is wrong).
i.e. 195 is first decoded to gibberish character � and so on.

This reconstruction needs identification if two bytes are to be entertained or 3 or more.
This varies with the language of letters (German here e.g.).
How would the client identify which language it is going to reconstruct (no. of bytes to decode in one go)?
To add more,
lists:flatten(mochijson2:encode({struct,[{registration_ids,[Reg_id]},{data ,[{message,Message},{type,Type},{enum,ENUM},{groupid,Groupid},{groupname,Groupname},{sender,Sender_list},{receiver,Content_list}]},{time_to_live,2419200}]})).

Produced the json as:
"{\"registration_ids\":[\"APA91bGLjnkhqZlqFEp7mTo9p1vu9s92_A0UIzlUHnhl4xdFTaZ_0HpD5SISB4jNRPi2D7_c8D_mbhUT_k-T2Bo_i_G3Jt1kIqbgQKrFwB3gp1jeGatrOMsfG4gAJSEkClZFFIJEEyow\"],\"data\":{\"message\":[104,105],\"type\":[71,82,79,85,80],\"enum\":2001,\"groupid\":[71,73,68],\"groupname\":[71,114,111,117,112,78,97,109,101],\"sender\":[49,64,100,101,118,108,97,98,47,115,100,115],\"receiver\":[97,115,97,115]},\"time_to_live\":2419200}"

where i had given "hi" as message and mochijson gave me ASCII values [104,105].
The groupname field was given the value "Groupname",
the ASCIIs are also correct after json creation i.e. 71,114,111,117,112,78,97,109,101

However when i use http://www.unit-conversion.info/texttools/ascii/
It is decodes as Ǎo��me and not "Groupname".

So, who should do the parsing? How the same should be handled.
My reconstructed message is all gibberuish when the ASCII is reconstructed.
Thanks

A: The things to worry about here is manyfold, and has to do with both the encoding desired or the datastructure. In Erlang, text is handled in one of the following ways:

*

*lists of bytes ([0..255, ...])

*

*This is what you get if you listen to a socket and the data is returned as a list.

*The VM assumes no encoding. They're bytes and mean little more.

*The VM can however interpret these as strings (say in io:format("~s~n", [List])). When that happens (with the ~s flag specifically), the VM assumes the encoding is latin-1 (ISO-8859-1).

*lists of Unicode codepoints ([0..1114111, ...]).

*

*You may get those from files that are read as unicode and as a list.

*You can use them in output when you have a formatter such as io:format("~ts~n", [List]) where ~ts is like ~s but as unicode.

*Those lists represent the codepoints you see in the unicode standard, without any encoding (they are not UTF-x)

*This can work in conjunction with latin-1 lists of characters because the Unicode codepoints and latin1 characters have the same sequence numbers below 255.

*Binaries (<<0..255, ...>>)

*

*This is what you get if you listen or read to/from anything under a binary format.

*The VM can be told to assume many things:

*

*They are sequences of bytes (0..255) without specific meaning (<<Bin/binary>>)

*They are utf-8 encoded sequences (<<Bin/utf-8>>)

*They are utf-16 encoded sequences (<<Bin/utf-16>>)

*They are utf-32 encoded sequences (<<Bin/utf-32>>)

*io:format("~s~n", [Bin]) will still assume any sequence is a latin-1 sequence; io:format("~ts~n", [Bin]) will assume UTF-8 only.

*A mixed list of both unicode lists and utf-encoded binaries (known as iodata()), used exclusively for output.

So in a gist:

*

*lists of bytes

*lists of latin-1 characters

*lists of Unicode codepoints

*binary of bytes

*utf-8 binary

*utf-16 binary

*utf-32 binary

*lists of many of these for output that is quickly concatenated

Also to note: until version 17.0, all Erlang source files were latin-1 only. 17.0 added an option to have the compiler read your source file as unicode by adding this header:
%% -*- coding: utf-8 -*-

The next factor is that JSON, by specification, is assuming UTF-8 as an encoding for everything it has. Furthermore, JSON libraries in Erlang will tend to assume that a binary is a string, and that lists are JSON arrays.
This means that if you want your output to be adequate, you must use UTF-8 encoded binaries to represent any JSON.
If what you have is:

*

*A list of bytes that represent a utf-encoded string, then list_to_binary(List) to get the proper binary representation

*A list of codepoints, then use unicode:characters_to_binary(List, unicode, utf8) to get a utf-8 encoded binary

*A binary representing a latin-1 string: unicode:characters_to_binary(Bin, latin1, utf8)

*A binary of any other UTF encoding: unicode:characters_to_binary(Bin, utf16 | utf32, utf8)
Take that UTF-8 binary, and send it to the JSON library. If the JSON library is correct and the client parses it properly, then it should be right.


text:
Q: using csrf_token in django widget I am trying to make a custom django widget with ajax. The ajax call requires csrf_token.
I need to know how to pass the csrf_token to the widget html.
# forms.py
from django import forms
from widgets import MyWidget

class PenForm(forms.ModelForm):
    color = forms.CharField(widget=MyWidget)
    class Media:
        js = (
            'js/jquery-3.2.1.min.js',
            'js/jquery-ui.min.js',
        )
        css = {
            'all': (
                'css/jquery-ui.min.css',
            )
        }

# widgets.py
from django.forms.widgets import Widget
from django.template import loader
from django.utils.safestring import mark_safe

class MyWidget(Widget):
    template_name = 'my_widget.html'
    def get_context(self, name, value, attrs={}):
        return {'widget': {
            'name': name,
            'value': value,
            'attrs': attrs,
            'csrf_token': '???'
        }}

    def render(self, name, value, attrs=None):
        context = self.get_context(name, value, attrs)
        template = loader.get_template(self.template_name).render(context)
        return mark_safe(template)

Here is my widget html:
<script>
  $( function() {
    $( "#autocomplete_{{ widget.name }}" ).autocomplete({
      source: function( request, response ) {
        $.ajax( {
          url: "/get_colors",
          type: "post",
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          headers: {'X-CSRFToken': '{{ csrf_token }}'},
          data: {
            term: request.term
          },
          success: function( data ) {
            response( data );
          }
        } );
      },
      minLength: 1,
      select: function( event, ui ) {
        log.debug( "Selected: " + ui.item.value + " , " + ui.item.id );
      }
    } );
  } );
</script>

# admin.py
@admin.register(Pen)
class PenAdmin(admin.ModelAdmin):
    form = PenForm
    list_display = ['label', 'color']

I already tried using {{ csrf_token }} which does not work so I'm thinking that I should get the token from the admin get_queryset(self, request) and pass it to the form and then pass it to the widget then to the template.
If this theory is right, then I need to know how to pass the token to the widget.


text:
Q: Using RSpec2 to test a controller's show action I have a fairly simple Rails 3 project where I've defined a custom route:
get 'factions/:name' => 'factions#show', :as => :factions
get 'factions' => 'factions#index'

... which when running rails s gives me the expected page (http://localhost:3000/factions/xyz is HTTP 200 with the app/views/factions/show.html.haml being displayed).  However I've tried multiple different ways of expressing a spec that will work, below is my latest incarnation:
require 'spec_helper'

describe FactionsController do
  render_views

  describe "GET 'show'" do
    before { get '/xyz' }
    subject { controller }
    it { should respond_with(:success) }
    it { should render_template(:show) }
  end

  describe "GET 'index'" do
    it "should be successful" do
      get 'index'
      response.should be_success
    end
  end

end

The GET 'index' spec passes without complaint but no matter what I do the GET 'show' specs cannot pass - even if they do succeed when I am browsing to them locally.
1) FactionsController GET 'show'
     Failure/Error: before { get '/xyz' }
     ActionController::RoutingError:
       No route matches {:controller=>"factions", :action=>"/xyz"}
     # ./spec/controllers/factions_controller_spec.rb:7:in `block (3 levels) in <top (required)>'

The action really should be show but my routes.rb configuration must be incorrect or something.  What gives?
(Additional context: I am using bundle exec spork for speeding up my specs and I have restarted the spork server multiple times just to make sure I'm not completely insane.)

A: Change:
before { get '/xyz' }

To:
before { get :show, :name => 'xyz' }


text:
Q: How much space taken when using System.Linq? Linq functions on List<T> are awesome, however, in this particular file I'm working on there are only 1 line that use it. So I wanted to know how much space this library took upon importing for use? (I'm using the First function.)
If it's taking too much space then it would make sense to create a custom for loop to iterate through instead. But my code is cleaner when using Linq.
For memory usage I think using Linq and using for don't really make that much difference so I want to know disk space usage if I would use it in Unity3D on mobile devices. If anyone can provide a way to determine disk size of any System library it would be very useful!

A: using directive doesn't really import anything into the application. It is merely language construct for using namespaces. What is really important if the assembly is actually included into the build. Look here:

Namespace:  System.Linq
Assembly:  System.Core (in System.Core.dll)

So what really matters is if this assembly is included. And yes, it is included by default in common assemblies that are installed in the system, so by just using Linq you don't make your file bigger.
Edit: question appeared to be in light of mono and Unity. In theory you can build .net app without using System.Core.dll if you are not using external libraries (and some of .net's). But very likely that other libraries that you have to use depend on it. Now regarding mono, it looks like mono treats System.Core as special assembly and it is not necessary to reference it, it is done automatically apparently:
using System;
using System.Linq;

namespace t1
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.WriteLine (typeof(Enumerable).Assembly.Location);
        }
    }
}

builds just like that dmcs Program.cs. Also if you create empty solution in Xamarin studio it also works and only System.dll is in references.

A: The .NET framework is installed on your computer. Its not linked into your .exe binary. Its only referenced, which is quite a difference.
Edit:
In followup to Baldricks question, on mobile devices using Unity there should be taken extra care about additional dependencies. They will get bundled into the "player" and add to download size.

Remove unnecessary code dependencies.

http://docs.unity3d.com/Documentation/Manual/iphone-playerSizeOptimization.html
On the other hand LINQ requires System.Core.dll which is an essential for .NET applications. So your bets are high that its already included and LINQ doesn't add to existing download size.

A: The using directive will just refer to the existing .Net Framework in the computer. It wont always result into directly linking or pulling the assembly in your build.
Referenced assemblies do lead to size growths.
But, however, the using directive does not tell the compiler to include referenced assemblies.
By referencing them in the project, however, you're telling the csc compiler where to find the assembly to link to when compiling.
So the assemblies are not referenced unless I reference them via the project or unless they are actually referenced in the code.

A: Just tried on version 2020.1 of unity and the build size doesn't change after using a function inside linq.
So there is no impact.


text:
Q: Increasing counter ten by ten in Tcolorbox... and refer good? I'm writing a book of probability in arabic, using polyglossia, and I want to increase the counter of some of my boxes ten by ten (the cause of this is that the arabic letters are numeroted with abjad, using unity in the nineth first letters, after using ten's for the nineth next, hundreds for the nineth's next, and thounsand for the 28-th and last letter... you can see this wikipedia in french, I've not another source...http://fr.wikipedia.org/wiki/Num%C3%A9ration_arabe)..
A solution I've found is to increase the counter by 9, in every iteration, with the command phantom={\addtocounter{\tcbcounter}{9}},
but the label of this box is referred to the counter before this command... I saw that it's natural in the doc of the tcolorbox package.. So how can I refer the labels of my examples to the labels after add of 9 to my item... or some other idea. Thank you.
Here's an example from my file..
\documentclass[14pt,a4paper]{extbook}

\usepackage{titlesec}

\usepackage{amsmath,amssymb}
\usepackage[most]{tcolorbox}

\usepackage{boxedminipage}
\usepackage{slashbox}

\usepackage{titlesec}

\usepackage{enumitem}

\usepackage{minitoc}

\usepackage{rotating}

\usepackage{fmultico}
\setlength{\columnseprule}{0.1pt}

\usepackage{fancyhdr}
\pagestyle{fancy}

\usepackage{pdflscape}

\usepackage{array}

\usepackage{polyglossia}
\setmainlanguage[numerals=maghrib]{arabic}
\setotherlanguage{english}

\newfontfamily\arabicfont[Script=Arabic, AutoFakeSlant=-0.02]{Amiri}
\setsansfont[Script=Arabic,Scale=1.5]{Amiri}

\tikzstyle{boxwhite} =
    [draw=white, thick, scale=.7, fill=white,
        line width=0.1pt, text=black, rectangle,
        font=\Large,
        left, minimum height=.5cm]

\newcounter{example}

\newtcolorbox[auto counter,
number within=section,
number freestyle={\noexpand\arabic{section}\noexpand\alph{\tcbcounter}}]{example}[2][]{
enhanced,
colback=white,
colframe=white,
top=-.7cm,
bottom=-2mm,
enlarge top by=\baselineskip/2+1mm,
enlarge top at break by=0mm,pad at break=2mm,
fontupper=\normalsize,
label={#2},
overlay unbroken and first={
\node[boxwhite]
at ([xshift=1.4cm,yshift=-.15cm]frame.north east)
{\strut\RL{\setlength{\extrarowheight}{-30.5pt}\textbf{$\begin{array}{c}
\hline
\rule{0pt}{2ex}
\mbox{\RL{مثال}}
\\
\mbox{\large\thetcbcounter}
\rule{0pt}{1.5ex}
\end{array}$}}};},
breakable,
width=1.048\textwidth,
arc=0pt,outer arc=0pt,
enlarge left by=-.085\textwidth,
extrude right by=-5pt,
extrude left by=-5pt,
#1}%

\newtcolorbox[use counter from=example]{example9}[2][]{
enhanced,
phantom={\addtocounter{\tcbcounter}{9}},
colback=white,
colframe=white,
top=-.7cm,
bottom=-2mm,
enlarge top by=\baselineskip/2+1mm,
enlarge top at break by=0mm,pad at break=2mm,
fontupper=\normalsize,
label={#2},
overlay unbroken and first={%
\node[boxwhite]
at ([xshift=1.4cm,yshift=-.15cm]frame.north east)
{\strut\RL{\setlength{\extrarowheight}{-30.5pt}\textbf{$\begin{array}{c}
\hline
\rule{0pt}{2ex}
\mbox{\RL{مثال}}
\\
\mbox{\large\thetcbcounter}
\rule{0pt}{1.5ex}
\end{array}$}}};},
breakable,
width=1.048\textwidth,
arc=0pt,outer arc=0pt,
enlarge left by=-.085\textwidth,
extrude right by=-5pt,
extrude left by=-5pt,
#1}%
\begin{document}

\begin{example}{ex0:a}
First
\end{example}
\begin{example}{ex0:b}
Second
\end{example}
\begin{example}{ex0:c}
....
\end{example}
\begin{example}{ex0:d}
....
\end{example}
\begin{example}{ex0:e}
....
\end{example}
\begin{example}{ex0:f}
....
\end{example}
\begin{example}{ex0:g}
....
\end{example}
\begin{example}{ex0:h}
....
\end{example}
\begin{example}{ex0:i}
....
\end{example}
\begin{example}{ex0:j}
....
\end{example}
\begin{example9}{ex0:k}
\LR{A good numeroted}
\end{example9}
\begin{example}{ex0:l}
\LR{A bad numeroted}
\end{example}
\LR{but the reference \ref{ex0:k} of the ten-th exercise is bad...}

 \end{document}

A: If you want to reference a counter you must increase it by \refstepcounter. This changes the internal command used by label.
So you should increase the counter by
\addtocounter{\tcbcounter}{8}\refstepcounter{tcbcounter}}

so that the last step does the right things.


text:
Q: How do I make if else statements if my data contains regex string in R? I have two lines of code
file.list <- file.list[order(as.numeric(str_match(file.list, "-R\\s*(.*?)\\s*-")[,2]))]

and
file.list<-file.list[str_order(gsub("W.*1-","", file.list), numeric = TRUE)]

The first line of code will sort the names in the order R1,R2,R3,R4,R5 if my file.list contains:
file.list<-c( "W2345_S-001-R2-20D_790.datavalue.csv",
         "W2346_S-001-R4-20D_792.datavalue.csv",
         "W2347_S-001-R1-20D_789.datavalue.csv",
         "W2348_S-001-R3-20D_791.datavalue.csv",
         "W2349_S-001-R5-20D_793.datavalue.csv")

The second line of code will sort the names in the order R1_1, R1_2, R1_9, R1_10, R2_1, R2_2, R2_9, R2_10 if my file.list contains:
file.list= c("W2345_S-001-R1_1.csv",
             "W2346_S-001-R1_10.csv",
             "W2347_S-001-R1_2.csv",
             "W2348_S-001-R1_9.csv",
             "W2345_S-001-R2_1.csv",
             "W2346_S-001-R2_10.csv",
             "W2347_S-001-R2_2.csv",
             "W2348_S-001-R2_9.csv")

How do I construct an if else statement, such that if  file.list contains the names in the format as shown (eg. "W2345_S-001-R2-20D_790.datavalue.csv"), run the first line, else run the second line?

A: We can use one process for either:
file.list[do.call(order, strcapture("R([0-9]+)_?([0-9]*).*", file.list, list(a=0L,b=0L)))]
# [1] "W2347_S-001-R1-20D_789.datavalue.csv"
# [2] "W2345_S-001-R2-20D_790.datavalue.csv"
# [3] "W2348_S-001-R3-20D_791.datavalue.csv"
# [4] "W2346_S-001-R4-20D_792.datavalue.csv"
# [5] "W2349_S-001-R5-20D_793.datavalue.csv"

file.list2[do.call(order, strcapture("R([0-9]+)_?([0-9]*).*", file.list2, list(a=0L,b=0L)))]
# [1] "W2345_S-001-R1_1.csv"  "W2347_S-001-R1_2.csv"  "W2348_S-001-R1_9.csv"
# [4] "W2346_S-001-R1_10.csv" "W2345_S-001-R2_1.csv"  "W2347_S-001-R2_2.csv"
# [7] "W2348_S-001-R2_9.csv"  "W2346_S-001-R2_10.csv"

The regex is the same, and sorts either of your file.list vectors.

A: You can use any with grepl which will return a single boolean value if any of the values match your regex:
if(any(grepl("-R\\s*(.*?)\\s*-", file.list))){
  file.list <- file.list[order(as.numeric(str_match(file.list, "-R\\s*(.*?)\\s*-")[,2]))]
} else {
  file.list <- file.list[str_order(gsub("W.*1-","", file.list), numeric = TRUE)]
}

You can test this with changing the input to test_list and creating a fresh file.list:
test_list <- c( "W2345_S-001-R2-20D_790.datavalue.csv",
              "W2346_S-001-R4-20D_792.datavalue.csv",
              "W2347_S-001-R1-20D_789.datavalue.csv",
              "W2348_S-001-R3-20D_791.datavalue.csv",
              "W2349_S-001-R5-20D_793.datavalue.csv")

file.list <- c()
if(any(grepl("-R\\s*(.*?)\\s*-", test_list))){
  file.list <- test_list[order(as.numeric(str_match(test_list, "-R\\s*(.*?)\\s*-")[,2]))]
} else {
  file.list <- test_list[str_order(gsub("W.*1-","", test_list), numeric = TRUE)]
}
# returns first line

# or
test_list <-  c("W2345_S-001-R1_1.csv",
             "W2346_S-001-R1_10.csv",
             "W2347_S-001-R1_2.csv",
             "W2348_S-001-R1_9.csv",
             "W2345_S-001-R2_1.csv",
             "W2346_S-001-R2_10.csv",
             "W2347_S-001-R2_2.csv",
             "W2348_S-001-R2_9.csv")

file.list <- c()
if(any(grepl("-R\\s*(.*?)\\s*-", test_list))){
  file.list <- test_list[order(as.numeric(str_match(test_list, "-R\\s*(.*?)\\s*-")[,2]))]
} else {
  file.list <- test_list[str_order(gsub("W.*1-","", test_list), numeric = TRUE)]
}
# returns second line


text:
Q: Differential of Haar integral function Let $C^k$ action of a compact Lie group $G$ on $R^m$, $D(g)$ denote the differential of the map $x\in R^m \mapsto g(x) \in R^m$ at the origin and $\mu$ is the normalized Haar mesure on $G$, consider a map:
$F(x)=\int_{G} {D(g)^{-1}\left(g(x)\right)}d\mu$
How to calculate the differential $DF$ of $F$ at origin?
Is this right?
$DF(x)=\int_{G} {D(g)^{-1}\left(D(g)(x)\right)}d\mu=\int_{G} {D(g^{-1})D(g)(x)}d\mu=\int_{G} {D(g^{-1}g)(x)}d\mu=x$
Thank you


text:
Q: Summing over rows containing particular strings in R I have a dataframe where the first column contains names of campaigns. I need to sum up all rows where the campaign names contain certain strings (it can appear in different places within the name, i.e. sometimes in the beginning sometimes in the end). The dataframe looks something like this:
    Campaign          Impressions
1   Local display     1661246
2   Local text        1029724
3   National display  325832
4   National Audio    498900
5   Audio local        597339
6   TV Regional        597339
...

So in this case I want to sum up all rows containing "local" in to one row, "national" into one, "regional" into one etc, like this:
    Campaign     Impressions
1   Local        939293929
2   National     9232423423
2   Regional     1123123123

How can this be achieved? I've been trying with ddply without success....

A: You could use grep to find the rows that match the Campaign column categories ('Local', 'National', 'Regional') in a loop (lapply).  Subset the dataset ('df') based on grep and sum the 'Impressions' column and rbind the list elements.
res1 <- do.call(rbind,lapply(c('Local', 'National', 'Regional'),
               function(x) {
         x1 <- df[grep(x, df$Campaign, ignore.case=TRUE),]
        data.frame(Campaign= x, Impressions=sum(x1$Impressions))}))

Or use data.table.  Keep only the 'Local', 'National', 'Region' in the 'Category' using sub and use that as "grouping" variable to sum the column 'Impressions'.
library(data.table)
setDT(df)[, list(Impressions=sum(Impressions)),by=
   list(Category=sub('.*?(Local|National|Region).*','\\U\\1', Campaign,
   ignore.case=TRUE, perl=TRUE))]

data
df <- structure(list(Campaign = c("Local display", "Local text",
"National display",
"National Audio", "Audio local", "TV Regional"), Impressions =
c(1661246L, 1029724L, 325832L, 498900L, 597339L, 597339L)), .Names =
c("Campaign", "Impressions"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

A: I guess you should use the grep function : say your data.frame is called mydata then

Local = grep(mydata$Campaign, pattern = "Local")
National = grep(mydata$Campaign, pattern = "National")
Regional = grep(mydata$Campaign, pattern = "Regional")
mydata_sum = data.frame(Campaign = c("Local", "National", "Regional"), Impressions = c(sum(mydata$Impressions[Local]), sum(mydata$Impressions[National]), sum(mydata$Impressions[Regional])))

A: Here's my approach using dplyr:
library(dplyr)
library(stringr)

categories <- "Local|National|Regional"

mydf %>%
  mutate(Campaign = tolower(str_extract((Campaign), ignore.case(categories)))) %>%
  group_by(Campaign) %>%
  summarise(sum(Impressions))

I needed to add the tolower, after extracting the strings, to make sure the group_by groups "local" together with "Local".


text:
Q: How to obtain and use the result of an asynchronous function which resides inside a synchronous one? I'll try to explain this as briefly as possible but the question is long (I know). I have to show you the structure of the code so you can understand why I need to do what I am hopelessly trying to!
I'm working on an Electron/AngularJS project which uses SQLite as its database. I have installed the 'node-sqlite3' npm package and the problem is with my usage of one of this package's APIs.
There is a login page that needs to do simple login stuff, e.g. check the username and password provided by the user, to the ones stored in the database.
For the sake of testing, I am just checking the username input and returning that user's 'username' plus 'password' in an object; really simple... or so I thought.
The process includes 2 Angularjs services, one 'Login.controller' and the view for the login page.
The code for each one is shown below:
Login.view.html :
<md-button ng-click="vm.login(vm.username)"> Login </md-button>

vm.username is the username field that the user types into.
vm.login() is a function inside the Login.controller.
Login.controller.js :
function LoginController($scope, authService, dbService) {

        var vm = this;

        //=== Variables ===//
        vm.username = '';

        //=== Function declarations ===//
        vm.login = login;

        //=== Function implementations ===//
        function login(username) {
            authService.authUser(username);
        }

    }

I have also used 'requirejs' in this project so I have omitted the lines about dependency injection and 'define'. The controller works fine.
authService is the service responsible for further authentication stuff but for now doesn't have much in it.
dbService is the service which connects to SQLite database and (hopefully later) performs the queries and returns the results to other services/controllers which need them.
As shown in the code, login() function accepts a username parameter and passes the data to authUser function in authService.
authService.js :
function authService(dbService) {

        // The main service object which is exposed to other components.
        var exposedObj = {
            authUser: authUser
        };

        return exposedObj;

        //=== Function implementations ===//
        function authUser(username) {
            dbService.findUser(username);
        }

    }

As you can see, this service also connects to dbService.
authUser() does the same thing as login() function did in the controller; accepts the username and passes it along to findUser() function in dbService. As I said earlier, these are just baby steps, so forgive the redundancy of files and services, they are meant to be filled with meaningful code later on.
dbService.js :
function dbService() {
        .
        .
        .

        //=== Function implementations ===//
        function findUser(username) {
            var result = {};

            let sql = `SELECT username, password
                        FROM auth_user
                        WHERE username = ?;`;

            db.serialize(() => {
                db.get(sql, username, (err, row) => {
                    if (err) {
                        console.error(err);
                    }
                    result = row;
                });
            });
            return result;
        }
    }

The database connection and other irrelevant lines have been removed. This is the actual pit that I'm stuck at.
The query results in ONE row only which is an Object and that is the guy whom I'm after.
I have defined a result object at the top and that is the main thing that I want to return from findUser() function.
Therefore, the result of the query should be poured into result object. If this is to happen, I can easily use the returned value of findUser() in the previous service (authService) and move forward in my code.
At the moment, the line return result naturally returns nothing, an empty object. The node-sqlite .get() (here) function is an asynchronous function. Therefore, return result is executed earlier than result = row;. Ultimately I just want to fill the result object.
I have to mention that I have tried Promises, async/await and another solution mentioned here and also here. None of them were helpful. It is most probably me who hasn't understood those solutions properly and implemented them wrong, but either way, I have been stuck with this seemingly simple problem for several hours. Any help is truly appreciated.
Purya
** *EDIT:
If anyone ever gets stuck in async calls and comes here along their way, I've got the solution:
The last file (dbService.js) should be changed to return a Promise. This example may help your problem:
function findUser(username) {
            let sql = `SELECT username, password
                        FROM auth_user
                        WHERE username = ?;`;

            return new Promise((dbResolve, dbReject) => {
                db.serialize(() => {
                    db.get(sql, username, (err, res) => {
                        if (err) dbReject(err);
                        dbResolve(res);
                    });
                });
            });
        }

And on your recieving end (the function which needs the result of this Promise), you can do something like this:
let dbPromise = dbService.findUser(username);

dbPromise
        .then((dbResolve) => {
            /* do something with the result which is inside "dbResolve" */
        })
        .catch((dbReject) => {
            console.log(dbReject);
        });


text:
Q: Python continue from the point where exception was thrown Hi is there a way to continue from the point where exception was thrown?
eg I have the following psudo code
unique code 1
unique code 2
unique code 3

if I want to ignore the exceptions of any of the unique code statements I will have to do it like this:
try:
  #unique code 1
except:
  pass

try:
  #unique code 2
except:
  pass

try:
  #unique code 3
except:
  pass

but this isn't elegant to me, and for the life of me I can't remember how I resolved this kind of problem last time... what I want to have is something like
try:
  unique code 1
  unique code 2
  unique code 3
except:
  continue from last exception raised

UPDATED:
REASON: The reason I am asking about this is the above 3 lines of code share the same kind of exceptions, lets say, extract information from an array, and in this particular scenario I don't really care about the exception of value not in the array.

A: Wrap each of the code sections into a function and then try calling each in a for-loop:
def code1():
    #unique code 1

def code2():
    #unique code 2

def code3():
    #unique code 3

for section in [code1, code2, code3]:
    try:
        section()
    except:
        pass

Edit: If your still looking for another way, you could use a decorator to make each call "safe" buy returning any errors instead of throwing them. Not sure if this is really pythonic or a great way to do things but it is a way:
def safe_call(fn):
    def wrapper(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except Exception as error:
            return error
    return wrapper

@safe_call
def code1():
    #unique code 1

@safe_call
def code2():
    #unique code 2

@safe_call
def code3():
    #unique code 3

code1()
code2()
code3()

A: We can use a while loop:
#!/urs/bin/env python

 check = 0
 while True:
     try:
         if check == 0:
             #unique_code_one ()
             check += 1
         if check == 1:
             #unique_code_two ()
             check += 1
         if check == 2:
             #unique_code_three()
     except:
         check = 2


text:
Q: AWS Lambda PhantomJS - multi language font support I have a Lambda function to generate PDF using PhantomJS. The english version works like a charm but the issue is with other languages (Japanese, Hindi, Urdu, etc...)
I tried the solutions provided for bundling the fonts and the font config with the lambda function but no success.
Can someone suggest where am I going wrong?
CSS:
@font-face {
    font-family: 'Noto Serif Devanagari';
    src: url('./fonts/NotoSerifDevanagari-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

FontConfig:
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <dir>/var/task/fonts</dir>
  <cachedir>/tmp/fonts-cache/</cachedir>
  <config></config>
</fontconfig>

Thanks.

A: Finally found the solution to my problem. The method to support fonts is similar to what I was doing above except for one change:
@font-face {
    font-family: 'Noto Serif Devanagari';
    font-weight: normal;
    font-style: normal;
}

src: url('./fonts/NotoSerifDevanagari-Regular.ttf') format('truetype');
Removed the src: url() line as this was converting the text to raster image and the PDF size was increasing due to this.
Also, just add the required fonts in the ./fonts folder in your bundle and use the following line in your nodejs code:
process.env.FONTCONFIG_PATH='/var/task/fonts';

or better add FONTCONFIG_PATH as an environment variable in your lambda function with the value - /var/task/fonts
Closing this question as the above solution is working now.


text:
Q: How to make strstr efficient so that it does not catch unwanted substrings For example, if the string is "Only for Geeky People" and I am looking for only "Geek" substring not "Geeky", it would say the word is not present.
ie strstr("Only for Geeky People", "Geek") would be NULL.
How do I address such an issue?

A: You have to deal with it by wrapping strstr() in a function, perhaps str_word() (which avoids reserved names), that does extra checking after finding the word.  Or, at least, that is probably the most sensible way to deal with it.
Padding the search string with spaces won't work.  Leading padding would prevent the code from finding "Geek" or "(Geek is not pejorative)"; trailing padding would prevent it from finding "Ozymandias is a Geek".  Etc.  If you want to go OTT, you could consider going for a powerful regular expression library like PCRE, but it is overkill for this task (and the POSIX <regex.h> isn't sufficiently powerful — it doesn't recognize word boundaries).
char *str_word(char *haystack, const char *needle)
{
    char *from = haystack;
    size_t length = strlen(needle);
    char *found;
    while ((found = strstr(from, needle)) != NULL)
    {
        if (found > haystack && isalpha((unsigned char)found[-1]))
            from += length;
        else if (isalpha((unsigned char)found[length]))
            from += length;
        else
            return found;
    }
    return NULL;
}

Note that this allows the function to find the Geek in "Ozymandias is such a Geeky Geek".
Beware trying to add const-correctness to this.  You can use this easily enough:
const char *str_word(const char *haystack, const char *needle);

However, you can't return a non-const char * when passed a const char * without a cast that removes the const-ness somewhere along the line.  Returning a const char * punts the process of removing const-ness to the calling code.  This matters in a context such as:
char *word = str_word(line, "Geek");

You have a variable array containing a line of input; you want to search for the word in that line, and get a non-const pointer back.
Test code:
#include <ctype.h>
#include <stdio.h>
#include <string.h>

extern char *str_word(char *haystack, const char *needle);

char *str_word(char *haystack, const char *needle)
{
    char *from = haystack;
    size_t length = strlen(needle);
    char *found;
    while ((found = strstr(from, needle)) != NULL)
    {
        if (found > haystack && isalpha((unsigned char)found[-1]))
            from += length;
        else if (isalpha((unsigned char)found[length]))
            from += length;
        else
            return found;
    }
    return NULL;
}

int main(void)
{
    const char search[] = "Geek";
    char haystacks[][64] =
    {
        "Geek",
        "(Geek is not pejorative)",
        "Ozymandias is a Geek",
        "Ozymandias is such a Geeky Geek",
        "No prizes for Geekiness",
        "Only for Geeky people",
        "Howling 'Geek' gets you nowhere",
        "A Geek is a human",
        "Geeky people run the tech world",
    };
    enum { NUM_HAYSTACKS = sizeof(haystacks) / sizeof(haystacks[0]) };

    for (int i = 0; i < NUM_HAYSTACKS; i++)
    {
        char *word = str_word(haystacks[i], search);
        if (word == NULL)
            printf("Did not find '%s' in [%s]\n", search, haystacks[i]);
        else
            printf("Found '%s' at [%s] in [%s]\n", search, word, haystacks[i]);
    }

    return 0;
}

Test results:
Found 'Geek' at [Geek] in [Geek]
Found 'Geek' at [Geek is not pejorative)] in [(Geek is not pejorative)]
Found 'Geek' at [Geek] in [Ozymandias is a Geek]
Found 'Geek' at [Geek] in [Ozymandias is such a Geeky Geek]
Did not find 'Geek' in [No prizes for Geekiness]
Did not find 'Geek' in [Only for Geeky people]
Found 'Geek' at [Geek' gets you nowhere] in [Howling 'Geek' gets you nowhere]
Found 'Geek' at [Geek is a human] in [A Geek is a human]
Did not find 'Geek' in [Geeky people run the tech world]


text:
Q: Tomcat7 hangs during web app shutdown I am currently using tomcat - 7.0.52
Following is the thread dump when tomcat hangs. In this pool-3-thread-1 is the thread which hangs but I am unable to debug which application code is starting it.
(If i press ctrl+c it shutdowns the tomcat but hangs when i use shutdown.bat)
Tomcat Thread dump

A: Issue was related to Hibernate(4.0), as hibernate was unable to close ConnectionProvider (org.hibernate.engine.jdbc.connections.spi.ConnectionProvider).
To close ConnectionProvider manually --

    try{
            SessionFactoryImpl sf = (SessionFactoryImpl)factory;
            ConnectionProvider cp = sf.getConnectionProvider();
            if (Stoppable.class.isInstance(cp)) {
                ((Stoppable) cp).stop();
            }
        }catch(Exception e){
            LOGGER.error("unable to stop connectionProvider",e);
        }
        this.factory.close();
    }


text:
Q: Unable to run D program on mac system when using dependency I am pretty new to D language. I am working on existing code developed by others. Previous developers were using linux environment to build and run the D Application.
I am trying to do the same in MAC as it is my local environment.
Here is how my jub.json file looks like
{
    "name" : "dsmasher",
    "description" : "Hello World - A minimal DUB bundle.",
    "dependencies" : {
        "d2sqlite3": "~>0.9.7",
        "botan": "~>1.12.9"
    }
}

The program is very simple
import std.stdio;

int main () {
   return 0;
}

But when I build it throws following errors.
/Library/D/dmd/src/druntime/import/object.d(3440,23): Error: template memutils.refcounted.RefCounted!(X509CertificateImpl, ThreadMem).RefCounted.opCast does not match any template declaration
/Library/D/dmd/src/druntime/import/object.d(3440,49): Error: template memutils.refcounted.RefCounted!(X509CertificateImpl, ThreadMem).RefCounted.opCast does not match any template declaration
/Library/D/dmd/src/druntime/import/object.d(3441,39): Error: template memutils.refcounted.RefCounted!(X509CertificateImpl, ThreadMem).RefCounted.opCast does not match any template declaration
../../../.dub/packages/memutils-0.4.9/memutils/source/memutils/vector.d(790,10): Error: template instance object.__equals!(const(RefCounted!(X509CertificateImpl, ThreadMem)), const(RefCounted!(X509CertificateImpl, ThreadMem))) error instantiating
../../../.dub/packages/memutils-0.4.9/memutils/source/memutils/helpers.d(71,27):        instantiated from here: opEquals!()
../../../.dub/packages/botan-1.12.9/botan/source/botan/tls/server.d(689,38):        instantiated from here: opEquals!(RefCounted!(Vector!(RefCounted!(X509CertificateImpl, ThreadMem), ThreadMem), ThreadMem))
/Library/D/dmd/bin/dmd failed with exit code 1.
  ^^^ Terminated, exit code: 2 ^^^
************  Build terminated.  ************

I am using dmd compiler for this.
Please help if you have any idea.

A: This appears to be a bug in Botan. According to Travis CI, their build fails with the same message.


text:
Q: Getting error like "syntax error at or near "TEXT" Getting below error:
I am adding new column to postgresql
newColquery ='ALTER TABLE dwb_weekly_snapshot ADD COLUMN CT_ID data_type TEXT'

  File "C:/Users/bz_dyadav/PycharmProjects/pythonProject/venv/Scripts/dwb_update.py", line 24, in <module>
    result_dwb_snapshot = cursor.execute(newColquery)
  File "D:\python\Python37\lib\site-packages\pg8000\legacy.py", line 205, in execute
    raise cls(msg)
pg8000.dbapi.ProgrammingError: {'S': 'ERROR', 'V': 'ERROR', 'C': '42601', 'M': 'syntax error at or near "TEXT"', 'P': '60', 'F': 'scan.l', 'L': '1134', 'R': 'scanner_yyerror'}

A: In the documentation on ALTER TABLE the text data_type refers to your data type, not the literal word. It's in bold-italic meaning "placeholder name".
Easy fix:
newColquery ='ALTER TABLE dwb_weekly_snapshot ADD COLUMN CT_ID TEXT'


text:
Q: GPU restart Mac Pro 3rd Gen. Early 2009 with GTX 1070, how to diagnose? Frequent, almost daily GPU restarts. From the console, under System reports, there's a painful record of the Kernel panics. Here's the most recent one:
Thu Sep  7 15:10:19 2017

Event:               GPU Reset
Date/Time:           Thu Sep  7 15:10:19 2017
Application:         WindowServer
Path:
Tailspin:            /Library/Logs/DiagnosticReports/gpuRestart2017-09-07-151019.tailspin
GPUSubmission Trace ID: 0
OS Version:          Mac OS X Version 10.12.6 (Build 16G29)
Graphics Hardware:   NVIDIA Chip Model
Signature:           8

Report Data:
NVDA(Graphics): Channel exception! Exception type = 0x8 DMA Engine Error (FIFO Error 8)
Channel Info: [0, 0x2, 0x2, 0x9d7]
Version Info: [com.nvidia.web.GeForceWeb, 10.1.8, 0x4e554e, 22510759, 378.05.05.25f01, 1]

Resource Manager Info:
 4443564e 000000d0 a24a219a 697c239f 00000001 00000014 ......etc

Basically, I'm hoping someone can point me in the right direction. Is it hardware related? Software? What else can I provide to help debug?

A: NVIDIA recommends that the system in which the card is installed should supply 500W: https://www.nvidia.com/en-us/geforce/products/10series/geforce-gtx-1070/
However, Apple warns that across all the PCIe expansion slots, not to pull more than 300W: https://support.apple.com/kb/sp506?locale=en_US
So, my guess is that whenever the GPU power consumption spikes, perhaps when you're playing games or videos, the Logic Board shuts off as a precaution.


text:
Q: Integrability of the sum of integrable and non-intergable functions Suppose $\int_\Omega |f_1|\,dx <\infty$ and $\int_\Omega |f_2|\,dx =\infty$, for measurable $f_1,f_2:\Omega\to\mathbb R$. Is it true that
$$
\int_\Omega|f_1+f_2|\,dx=\infty\,?
$$

A: Yes, it's true. It's imminent from this inequality
$$ |f_2|=|f_2+f_1-f_1|\leq |f_2+f_1|+|f_1| $$


text:
Q: populating 1 column of rows that have values 0 using SQL window functions possibly with next max/prev min value of row index this is one iteration of the test data:
DECLARE @trial TABLE (id int)

INSERT INTO @trial (id)
VALUES (0), (0),(3), (0), (0),(0), (7), (0),(9), (0), (0),(12), (0), (0),(15)

select * from @trial

The numbers will always be a sequence of 0 or the row number. In any set if the number is not zero, the number will always represent the row so it will always be increasing.
I need the 0's to take on the next max value. So the output should be this:
3
3
3
7
7
7
7
9
9
12
12
12
15
15
15

please help!!

A: SQL tables represent unordered sets.  There is no ordering -- and no cumulative max -- unless you have a column that specifies the ordering.
This is easy to include by having an identity column.  Such a column will preserve insertion order, which is apparently what you want.  So, this does what you want:
DECLARE @trial TABLE (id int identity, val int)

INSERT INTO @trial (val)
VALUES (1), (0),(0), (0), (0),(0), (7), (0),(9), (0), (0),(12), (0), (14),(0)

select * from @trial

select max(val) over (order by id) as running_max
from @trial
order by id;

EDIT:
In your sample data, you want to look forward as well as backward.  For this, you can use a case expression to find the cases where the first rows have 0:
select (case when max(val) over (order by id) = 0
             then min(case when val > 0 then val end) over (order by id desc)
             else max(val) over (order by id)
        end) as running_max
from trial
order by id;

Here is a db<>fiddle.

A: I think this is what you're looking for
declare @trial table (id int)

insert into @trial (id)
values (0), (0),(3), (0), (0),(0), (7), (0),(9), (0), (0),(12), (0), (0),(15)  ;

;with
seq_cte as (select row_number() over (order by (select null)) rn from @trial),
break_cte as (select s.rn, isnull(t.id, 0)  input_n, iif(isnull(t.id, 0)=0, 0, 1) seq_break,
                     lag(iif(isnull(t.id, 0)=0, 0, 1), 1, 0) over (order by s.rn) seq_break_lag
              from seq_cte s left join @trial t on s.rn=t.id),
group_cte as (select *, sum(bc.seq_break_lag) over (order by bc.rn) break_grp from break_cte bc),
join_v_cte as (select id, (row_number() over (order by id))-1 jrn from @trial where id<>0)
select vc.id
from group_cte gc
     join
     join_v_cte vc on gc.break_grp=vc.jrn;

Results
id
3
3
3
7
7
7
7
9
9
12
12
12
15
15
15


text:
Q: Assign Promise.all result to object properties If I want to assign two resolved promises to two variables, I can do this:
const [a, b] = await Promise.all([first(), second()])

But assign I have an object with properties, instead of a and b, how can I affect the result to object properties?
This does not works:
const x = {}
const [x.a, x.b] = await Promise.all([first(), second()])

Is there a way to do this?

A: If you're after a one-liner, I'm sorry to disappoint. Dereferencing assignment is meant for terse object expansion into variables, but not data-mapping between objects.
I would also encourage you to avoid clever code because if it's hard to read it's hard to understand which means it's hard to verify that it's working as expected for all appropriate edge cases.
In this case, adding more lines is trivially easy and clear:
const [a, b] = await Promise.all([first(), second()])

const x = {
  a,
  b
}

as a follow up question, what if you don't want to produce a and b variables within the current scope? For example, what if a and b are already defined and you need to avoid a naming conflict?
In that case, adding a little more code to be explicit is useful:
const [xA, xB] = await Promise.all([first(), second()])

const x = {
  a: xA,
  b: xB
}

A: You can't use const (which declares variables) if you want to assign to properties:
const x = {};
[x.a, x.b] = await Promise.all([first(), second()]);

Notice that the semicolon is necessary here, if you want to omit them and let them be automatically inserted where ever possible needed, you will need to put one at the begin of the line:
const x = {}
;[x.a, x.b] = await Promise.all([first(), second()])


text:
Q: How to use DateDiff() Function across day transition in ArcGIS Field Calculator? I am trying to calculate the time difference between two fields using the DateDiff() function in minutes. I have successfully calculated the times that fall within the same day but I am having trouble with the times that are occurring in day transition (after 11:59 PM). For example: My date fields are as such,
MM\dd\yyyy hh:mm:ss tt
So between these two times
01\17\2007 11:57:08 PM and 01\18\2007 12:15:01 AM
The field calculator would apply a huge negative number. I am thinking a conditional statement is needed for basic arithmetic but am at a loss.
Please be as detailed as possible. I am not a developer.

A: Update: Based on some testing I just did, I do not know why the function wasn't working for you. Per PolyGeo's answer there are issues related to both database type and field definition, but based on your question and comments you are working in a file geodatabase (folder.gdb), your field type is date, and your date/time are in a single field. You want the time difference in minutes. In that case you need to:

*

*Add a numeric field (short, long, float, double) to your table. You
cannot calculate in this manner to a date format field.

*Right-click the new field heading in the table and select the Field
Calculator.

*Enter DateDiff ("n", [date1], [date2]) in the Field Calculator and
click Ok.

This should give you the numeric value in minutes between the two times. If you want seconds, per your later comment, replace the n with an s. I tested both successfully.
Now, if your date and time are in two different date fields, that may be causing the problem because the DateDiff function is assuming the times are in the same day. But I don't believe that to be the case, since the code below also worked for you - particularly the x number of days line.

I'm not an expert on the function or its ArcGIS implementation, but based on your description and some reading I see two issues with your method and proposed solution:

*

*If it is correct (and I no longer believe it is) that it ignores
either the date or the time portion for any single calc, your comment proposed
solution assumes there are no fields that differ more than 24 hours.

*As you've already found if the two times cross a day boundary
you can no longer arrive at the difference by subtracting them in
either order (hence the error in your comment math - the actual
difference between the two times is 1073 seconds). DateDiff doesn't
function this way. It treats the date as a value in a continuous sequence from an 'arbitrary' date, not a value in a sequence that resets each day.

If you want to treat times as a sequence that resets each day as in your comment, the math is different. Unless you know your data will never be more than 24 hours different, your calculation needs another step to compare days before then comparing the time. That step is also required to determine which method of seconds calculation (same day or adjacent days) is necessary. See the following untested code, which would go in the codeblock section (may need to check the Show Codeblock box); the lower box (TimeDiffField=) would just contain y.
dim x
dim y
dim das1
dim das2

das1 = (datepart ("h", [date1]) * 3600) + (datepart ("n", [date1]) * 60) + (datepart ("s", [date1]))
das2 = (datepart ("h", [date2]) * 3600) + (datepart ("n", [date2]) * 60) + (datepart ("s", [date2]))
x = datediff ("d", [date1], [date2])

if x < 1 then
     y = datediff ("s", [date1], [date2])
else then
     y = (86400 - das1) + das2 + ((x-1) * 86400)
end if

A: It is possible that you may be encountering the same issue as in this ArcGIS Discussion Forum thread.
From there the advice would seem to be:

Is the data in a GeoDatabase? If the data is a shapefile then you
  probably won't get good or any results. If the data is in a PGDB then
  try testing queries in Access directly. When it works move them into
  ArcMap. If it's in SDE then test using SQL queries.
Are the columns in a date datatype?  Also what is the target column
  data type?
The target needs to be integer or float if you are calculating
  minutes.
Check out the date functions at:
http://www.techonthenet.com/access/functions/


text:
Q: C# - get event from SetWindowText We are writing a plugin for an existing VB6 application (via COM interop), and we are requiring some functionality that they do not support.  We could easily get the required functionality if we could somehow receive an event for when a particular control's text on their window changes.
We can already grab their existing window handle of the control with FindWindow and get the text with GetWindowText.
Is there any unmanaged/pinvoke method to receive an event when the text on a window is changed?
We do not want to poll with a while loop--we may want to do this on several of their controls in the future.
PS - I know there are ways to intercept p/invoke calls (google EasyHook), but we do not want to intercept every call to SetWindowText.  We just want to receive it for one control, and using something like EasyHook is probably adding unnecessary complexity.

A: You could try creating a new class in c# that derives from NativeWindow.
Override the WndProc function, and if the message if of type WM SETWINDOWTEXT add your functionality - ignore all other messages and call the base class implementation
protected override void WndProc(ref Message m)
{
    switch (m.Msg)
    {
        case WM SETWINDOWTEXT:
            // Custom code here
            break;
    }
    base.WndProc(ref m);
}

Create an instance of this C# class and call the AssignHandle function with the hWnd for the control that you got with FindWindow.
See this link for further details and a more in depth explanation:
Overriding WndProc in the NativeWindow class

A: There is no such event for general windows. If the control is an Edit control, it may send EN_CHANGE via WM_NOTIFY to its parent, however you can not inject managed code to another process to intercept the notification. I suggest you to contact the author of the VB6 app to add a COM event for you, or give up the notification requirement.