text:
Q: Creating a partition on my soft-delete indicator column In SQL Server 2008 R2 I am exploring the use of partitioning tables.
We have a soft-delete scheme which is sometimes an IsDeleted bit NOT NULL and sometimes a DateDeleted date NULL
I want to focus on the first case, the bit.
I am considering partitioning this table on the bit because the table is almost always queried and joined including this column.
How would I go about this process? Is it a bad idea?
I first tried to step through the wizard but the script it generated for me seemed awkward (multiple drops of constraints, creation of a new CI)

A: The following is a sample script I just created that shows how to create a table that contains an IsDeleted Field.
After the table is created and filled with 10,000 rows, I add a partitioning function and scheme, and some filegroups and files to contain the partitions.  In real life, you would want to create these filegroups and files on dedicated LUNs to take advantage of extra I/Os and piecemeal restore.
I then alter the table so it makes use of the partitioning function, thereby moving the existing rows into the appropriate filegroup.  Since you cannot perform an 'ALTER TABLE...ALTER CONSTRAINT` to alter the primary key to use the partitioning function, you are forced to drop the primary key and recreate it with the new partitioning function.  This does mean the clustered index will be turned into a heap until you can create the new clustered index with the partitioning function.
USE Test;
GO
CREATE TABLE IsDeletedTest
(
    IsDeletedTestID INT NOT NULL CONSTRAINT PK_IsDeletedTest PRIMARY KEY
        CLUSTERED IDENTITY(1,1)
    , IsDeleted BIT NOT NULL CONSTRAINT DF_IsDeletedTest_IsDeleted
                DEFAULT ((0))
);
GO
/* INSERT 10,000 rows into IsDeletedTest */
INSERT INTO IsDeletedTest (IsDeleted) VALUES (CAST(RAND() * 2 AS INT));
GO 10000
ALTER DATABASE Test ADD FILEGROUP IsDeleted0FG;
ALTER DATABASE Test ADD FILE
    (NAME='IsDeletedFile0', FILENAME='C:\SQLServer\Data\IsDeletedFile0.mdf')
    TO FILEGROUP IsDeleted0FG;
ALTER DATABASE Test ADD FILEGROUP IsDeleted1FG;
ALTER DATABASE Test ADD FILE
    (NAME='IsDeletedFile1', FILENAME='C:\SQLServer\Data\IsDeletedFile1.mdf')
    TO FILEGROUP IsDeleted1FG;
ALTER DATABASE Test ADD FILEGROUP IsDeleted2FG;
ALTER DATABASE Test ADD FILE
    (NAME='IsDeletedFile2', FILENAME='C:\SQLServer\Data\IsDeletedFile2.mdf')
    TO FILEGROUP IsDeleted1FG;
GO
/* Create a partition function using a BIT datatype for the valid values
     of 1 and 0 */
CREATE PARTITION FUNCTION IsDeletedPF (BIT)
AS RANGE LEFT FOR VALUES (0,1);

/* Create a partition scheme that implements the partition function */
CREATE PARTITION SCHEME IsDeletedPS AS PARTITION IsDeletedPF
    TO (IsDeleted0FG, IsDeleted1FG, IsDeleted2FG);

/* MOVE the clustered index into the various filegroups
    according to partition scheme */
ALTER TABLE IsDeletedTest DROP CONSTRAINT PK_IsDeletedTest
    WITH (MOVE TO IsDeletedPS(IsDeleted));
GO
ALTER TABLE IsDeletedTest ADD CONSTRAINT PK_IsDeletedTest
    PRIMARY KEY CLUSTERED (IsDeleted, IsDeletedTestID)
    WITH (
                     ONLINE=OFF, ALLOW_ROW_LOCKS=ON, ALLOW_PAGE_LOCKS=ON,
             FILLFACTOR=100 /* adjust this as necessary */
                 )
    ON IsDeletedPS(IsDeleted);

/* Show the movement of a single row from partition 1 to partition 2 */
SELECT IsDeleted, COUNT(1) FROM dbo.IsDeletedTest GROUP BY IsDeleted;
SELECT O.Name, PS.partition_number, PS.row_count
FROM sys.dm_db_partition_stats PS
    INNER JOIN sys.objects O ON PS.object_id = O.object_id
WHERE O.Name = 'IsDeletedTest';
UPDATE dbo.IsDeletedTest
    SET IsDeleted = CASE WHEN IsDeleted = 0 THEN 1 ELSE 0 END
    WHERE IsDeletedTestID = 10000;
SELECT IsDeleted, COUNT(1) FROM dbo.IsDeletedTest GROUP BY IsDeleted;
SELECT O.Name, PS.partition_number, PS.row_count
FROM sys.dm_db_partition_stats PS
    INNER JOIN sys.objects O ON PS.object_id = O.object_id
WHERE O.Name = 'IsDeletedTest';
GO

DROP TABLE IsDeletedTest;
DROP PARTITION SCHEME IsDeletedPS;
DROP PARTITION FUNCTION IsDeletedPF;
ALTER DATABASE Test REMOVE FILE IsDeletedFile0;
ALTER DATABASE Test REMOVE FILE IsDeletedFile1;
ALTER DATABASE Test REMOVE FILE IsDeletedFile2;
ALTER DATABASE Test REMOVE FILEGROUP IsDeleted0FG;
ALTER DATABASE Test REMOVE FILEGROUP IsDeleted1FG;
ALTER DATABASE Test REMOVE FILEGROUP IsDeleted2FG;

I just ran this and got the following results:

As you can see, the table had an almost perfect distribution of rows in the IsDeleted = 0 and IsDeleted = 1 state.  Updating a row from 0 to 1 resulted in the row moving to the other partition.
I hope this helps show how to alter a table to take advantage of partitioning on an IsDeleted soft-delete BIT field.
When I ran the wizard to partition this table, with the option to script to a new query window, I got this code:
USE [Test]
GO
BEGIN TRANSACTION
ALTER TABLE [dbo].[IsDeletedTest] DROP CONSTRAINT [PK_IsDeletedTest];

ALTER TABLE [dbo].[IsDeletedTest] ADD  CONSTRAINT [PK_IsDeletedTest] PRIMARY KEY NONCLUSTERED
(
    [IsDeletedTestID] ASC
) WITH (
    PAD_INDEX = OFF
    , STATISTICS_NORECOMPUTE = OFF
    , SORT_IN_TEMPDB = OFF
    , IGNORE_DUP_KEY = OFF
    , ONLINE = OFF
    , ALLOW_ROW_LOCKS = ON
    , ALLOW_PAGE_LOCKS = ON
    )
ON [PRIMARY]

CREATE CLUSTERED INDEX [ClusteredIndex_on_IsDeletedPS_635194638000795374] ON [dbo].[IsDeletedTest]
(
    [IsDeleted]
) WITH (
    SORT_IN_TEMPDB = OFF
    , DROP_EXISTING = OFF
    , ONLINE = OFF
    )
ON [IsDeletedPS]([IsDeleted])

DROP INDEX [ClusteredIndex_on_IsDeletedPS_635194638000795374] ON [dbo].[IsDeletedTest]

COMMIT TRANSACTION

As far as I can tell, this code looks like it doesn't work.  It drops the PK, then recreates it, without using the partitioning function.  It then creates a clustered index, using the partitioning function, but then immediately drops it!

A: The partioning column must be in the clustering index.  Therefore, if the value of IsDeleted changes the row has to move from one bit of disk to another.  If your intention in using the flag was to defer the IO cost of the delete by performing an UPDATE instead of a DELETE this solution is counterproductive.  With it you will be perfoming both a DELETE (from the row's current location) and and INSERT to its new location.  If the intention was to isolate archive data then you are onto a winner.  I would suggest you use filtered indexes on the active partion of your table, too.


text:
Q: Maximizing $\sum_{i,j=1}^{n}|\operatorname{deg}\ x_{i}-\operatorname{deg}\ x_{j}|^{3}$ over all simple graphs with $n$ vertices For a simple graph $G$ on $n$ vertices, let us define
$$\mathcal{I}_{n}(G)=\sum_{i,j=1}^{n}|\operatorname{deg}\ x_{i}-\operatorname{deg}\ x_{j}|^{3}$$
I am highly interested in finding $\sup \mathcal{I}_{n}$ over all graphs with $n$ vertices (or at least some tight upper bound). What I have tried myself, was noticing that $\mathcal{I}_{n}$ must be maximized by a threshold graph:

Sketch of proof: This index $\mathcal{I}_{n}$ is a convex function of degree sequence
  $\operatorname{deg} \ x_{1},...,\operatorname{deg} \ x_{n}$. Call the set of all such graphic sequences $D$. Then we
  can look on $D^{∗}=\mathcal{Con}D$ - a convex hull of $D$. It must then attain it's
  maximum on some extreme point of $D^{∗}$. It can be shown, that such
  extreme points of $D^{*}$ are exactly those corresponding to threshold
  graphs.

But this didn't lead me too far. I will be glad for any insight.
Simulations show that the optimum occurs for $k$ isolated vertices and a complete graph on the other $n−k$ where $k=\lfloor\frac{n+1}5\rfloor$. The same count occurs for $k$ vertices of degree $n−1$ and no other edges so the other $n−k$ have degree $k$. Do You have any ideas on how to prove it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: DocFX: Generate API documentation for multiple projects I'm working on a project that has multiple projects in a solution.  I would like to be able to generate the documentation from an outside directory to keep the application code folders clean.  When I try to set the src directory in my docfx.json, it doesn't seem to like absolute paths, nor does it like relative paths.
{
  "metadata":
  [{
         "src":
         [{
               "files": ["../../../Repos/Wsi.Extranet.CommonServices/Wsi.Extranet.CommonServices/**/*.csproj"]
               "exclude":
               [
                    "**/obj/**",
                    "**/bin/**",
                    "_site/**"
               ]
        }],
        "dest": "api"
}],
"build": {
"content": [
  {
    "files": [
      "api/**.yml",
      "api/index.md"
    ]
  },
  {
    "files": [
      "articles/**.md",
      "articles/**/toc.yml",
      "toc.yml",
      "*.md"
    ],
    "exclude": [
      "obj/**",
      "_site/**"
    ]
  }
],
"resource": [
  {
    "files": [
      "images/**"
    ],
    "exclude": [
      "obj/**",
      "_site/**"
    ]
  }
],
"overwrite": [
  {
    "files": [
      "apidoc/**.md"
    ],
    "exclude": [
      "obj/**",
      "_site/**"
    ]
  }
],
"src":    "../../../Repos/Wsi.Extranet.CommonServices/Wsi.Extranet.CommonServices",
"dest": "_site",
"globalMetadataFiles": [],
"fileMetadataFiles": [],
"template": [
  "default"
],
"postProcessors": [],
"noLangKeyword": false
 }
}

It says it built fine but didn't find any files and the directory that it searches for is staying in the current directory.
D:\temp\WsiApiDocs\docfx_project>docfx metadata
Info: Config file docfx.json found, start generating metadata...
Info: No files are found with glob pattern **/*.csproj, excluding
    **/obj/**,**/bin/**,_site/**, under directory "D:\temp\WsiApiDocs\docfx_project"
Info: Completed executing in 54.0087 milliseconds.

Build succeeded.
    0 Warning(s)
    0 Error(s)

When I attempt to put the relative path in the files property, I get the following:
D:\temp\WsiApiDocs\docfx_project>docfx metadata
Info: Config file docfx.json found, start generating metadata...
Info: No files are found with glob pattern
 ../../../Repos/Wsi.Extranet.CommonServices/Wsi.Extranet.CommonServices/**/*.csproj,
excluding **/obj/**,**/bin/**,_site/**, under directory
 "D:\temp\WsiApiDocs\docfx_project"
**Warning: NOTE that `../` is currently not supported in glob pattern, please use `../` in `src` option instead.**
Info: Completed executing in 48.9621 milliseconds.

Build succeeded with warning.
Warning: NOTE that `../` is currently not supported in glob pattern, please use `../` in `src` option instead.
    1 Warning(s)
    0 Error(s)

So my confusion seems to be in how to use the src option instead.  If use the src in metadata, then it seems that I can't specify the file and exclusion info.  I tried to use a src property on the same level as metadata but that seemed to do nothing.

A: Just as the error states

../ is currently not supported in glob pattern

files, exclude etc. use glob patterns. Set a base directory instead via src:
{
  "metadata": [
    {
      "src": [
        {
          "files": "Repos/Wsi.Extranet.CommonServices/Wsi.Extranet.CommonServices/**.csproj",
          "exclude": [
            "**/obj/**",
            "**/bin/**"
          ],
          "src": "../../.." // <---- base directory
        }
      ],
      "dest": "api"
    }
  ],
  "content": [
    {
      "files": [
        "api/**.yml",
        "api/index.md"
      ]
    }
    // ...
  ]
}

Here is an exmaple of structuring multiple projects


text:
Q: how to exclude some routes when user is not logged in zfcuser? So, i am new in Zend Framework, i installed ZfcUser and i want when the user is not logged to didn't access to some routes for example : /blog/article/add,
actually i use <?php if($this->zfcUserIdentity()) :?> to check if the user is logged but how can i redirect the user to my login route/user if is try to access to /blog/article/add,
so plz if someone has any idea i will be very appreciative :)

A: I disagree with the selected answer because it's not really practical to do these kind of things inside every action of every controller that you want to deny access to.
There are two big modules out there that are used for this task. The first one being BjyAuthorize and the other big one being ZfcRbac. Please check them out. ZfcRbac is my favorite (because i wrote documentation for it) but it requires PHP 5.4+

A: Simple Way:
in controller:
if (!$this->zfcUserAuthentication()->hasIdentity()) {
    return $this->redirect()->toRoute('route_to_login',array('param' => $param));
}

Some more:
(after auth zfcuset will redirect you to previous controller)
in module.config.php
'controllers' => array(
    'invokables' => array(
        'zfcuser' => 'Application\Controller\UserController',
    ),
...
),

next copy file vendor\zf-commons\zfc-user\src\ZfcUser\Controller\UserController.php
to module Application (same folder as in module.config.php)
delete all function except authenticateAction
add:
    use Zend\Session\Container;
and change
return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
to
$redirect_session = new Container('redirect');
        $redirect = $redirect_session->redirect;
        if($redirect!='')
        {
            unset($_SESSION['redirect']);
            return $this->redirect()->toRoute($redirect, array('lang' => $lang));
        }
        return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute(),array('param' => $param));

and at last add in controller
use Zend\Session\Container;
...
if (!$this->zfcUserAuthentication()->hasIdentity()) {
            $redirect_session = new Container('redirect');
            $redirect_session->redirect = 'route_to_this_controller_action';
            return $this->redirect()->toRoute('route_to_login',array('param' => $param));
        }


text:
Q: Using numpy on an embedded python interpreter using VS2008 under Windows 7 Let's take a look at my project.
I'm using Visual Studio 2008, Python 2.7 and numpy 1.8.1 (but I have tried several versions and none worked). My project is being compiled on debug mode.
It's a very simple code:
/* = Main.cpp file = */
#include "stdafx.h"
#include "Python.h"

int _tmain(int argc, _TCHAR* argv[])
{
    PyObject *pName, *main;
    Py_Initialize();

    pName = PyUnicode_FromString("main");
    main = PyImport_Import(pName);

    Py_XDECREF(pName);

    if (main != NULL)
    {
        printf("Python Module Loaded!!\n");
    }
    else
    {
        printf("Unable to load Python Module!!\n");
    }
    return 0;
}

And
""" = Main.py file = """
print 'Hello World!'

If I execute this code, I get:

As it is expected.
My problem arises as soon as I change main.py into:
""" = Main.py file = """
import numpy
print 'Hello World!'

Then I get the:

I have tried to run main.py separately on a python interpreter (not embedding it into C++) and then everything works just fine:

I have also tried a modification on the main.cpp as follows:
#include "stdafx.h"
#include "Python.h"

int _tmain(int argc, _TCHAR* argv[])
{
    PyObject *pName, *main;
    Py_Initialize();

    PyRun_SimpleString("import numpy");

    return 0;
}

From this code the output is:

Finally I also tried compiling original version of main.cpp code in release mode and then the output is:

So, my question here is: What can I do to get numpy working under debug compilations using an embedded interpreter on Visual Studio 2008?

A: You know you have to have use a python debug version built don't you? That is probably your problem. (I would leave a comment but no rep ):   )


text:
Q: Build excluding test modules My project has the following structure:
├── api
│   ├── api.go
│   ├── api_test.go
│   ├── other_files...
├── cmd
│   └── main.go

Under cmd/main.go I have the entrypoint of my Go project.
Since I am also creating some test files, I have other classes used for test purposes.
My go.mod is like:
require (
    github.com/gorilla/mux v1.8.0
    github.com/stretchr/testify v1.6.1          <-used for test
    gotest.tools v2.2.0+incompatible            <-used for test
    k8s.io/api v0.19.0
    k8s.io/apimachinery v0.19.0
    k8s.io/client-go v0.19.0
)

My doubt is related to the build phase:
When doing go build ./cmd/main.go, am I selecting only the correct modules used from main.go and all its references across the code, excluding the unused modules listed in go.mod used for test classes?
Is there any ldd command to be sure I am linking only the required modules?
I assume that Go is optimized to do that, but I would like to be sure about that.

A: When you run go build, it will:

*

*Examine the package being built for import statements

*Examine each of the imported packages for import statements

*... and so on, until it finds all transitive dependencies.

*For each package to be built, it then examines the build constraints, and builds the files that are not excluded. *_test.go files are excluded by default, go test explicitly includes them when building tests.

This means that:

*

*Test files won't be included in a non-test build unless you explicitly include them.

*Unreferenced packages won't be included at all.

*What's in go.mod is irrelevant to the build: it's used only for dependency management, not compilation.

A: When go builds a package normally (go build or go install) it will ignore any files with the name pattern *_test.go. This means that object code for any packages that are only imported from those test files will not be linked into your executable.
So if you're just careful not to import the test packages from your non-test code you're good.
If you're not sure, you can check the "build list" by running:
go list -m all

From the root of your module. This will list the set of modules providing packages for the build.
Ref: go - The main module and the build list


text:
Q: I can't find maven from "Build Tool" in IntelliJ As I describe in the title, the maven item should be find in Settings --> Build Tools, however there is no this item in my IDE, I'm using IntelliJ IDEA Community Edition 2016.2.2.

A: Problem solved, I just need to check the Maven Integration plugin and apply it as following.


text:
Q: using logstash with elastic cloudid There instructions on how to configure logstash with elastic cloud using the cloud.id are not complete.  Specifically the instructions do not say what to put into the output section in the *.conf file if you put the cloud.id and cloud.auth into logstash.yml. Using the cloud.id is supposed the negate the need to put the URL of the ES instance.
If you put nothing in the output section logstash throws a config error.  If you put something there, illogical since nothing should be needed, it tries to connect to ES on localhost:
 output {
      elasticsearch {
      }
    }

Here is error as logstash is not using the cloud.id.
[WARN ][logstash.outputs.elasticsearch] Attempted to resurrect connection to dead ES instance, but got an error. {:url=>"http://127.0.0.1:9200/", :error_type=>LogStash::Outputs::ElasticSearch::HttpClient::Pool::HostUnreachableError, :error=>"Elasticsearch Unreachable: [http://127.0.0.1:9200/]

A: You should repeat the login information in the output section despite it's being illogical, as stated here. The output of your pipeline shall look something like this:
output {
  elasticsearch {
    hosts => ["https://xxxxxxxxxxxx.eu-central-1.aws.cloud.es.io:9243"]
    user => "myUsername"
    password => "myPassword"
 }
 stdout { codec => rubydebug }
}

A: cloud.id and cloud.auth are only meant for configuring:

*

*internal modules (such as netflow)

*the Logstash monitoring

*the centralized pipeline management
The elasticsearch output is another beast that requires its own configuration and does not (yet) benefit from the main configuration.


text:
Q: Unable to select durable function in Azure Logic app editor I have created a python durable function

So there is a trigger function(HTTP) - that should be accessible from Logic app, orchestrator function, and activity.
However, if I want to select this function in a logic app I cannot see it

A: After reproducing from my end, I could able to see the HTTP Trigger functions where the route is set to null.
To reproduce we have created 2 HTTP functions
Function1 where the route is set to null

Function2 where the route is not set to null

In my logic app


text:
Q: Google Search Console API not returning enough data https://developers.google.com/webmaster-tools/search-console-api-original/v3/searchanalytics/query
Google Analytics tells me ~20k pages were visited from Google search, but the Google Search Console API returns just under 5k urls. Changing startRow doesn't help.
What's really odd is I've connected Google Search Console to Google Analytics, and when viewing GSC data in GA (Acquisition -> Search Console -> Landing Pages) the GSC data there also gives me ~20k rows.
How do I get all ~20k rows out of the Google Search Console API?
date_str = '2017-12-20'
start_index = 0
row_limit = 5000
next_index = 5000
rows = []
while next_index == row_limit:
  req = webmasters_service.searchanalytics().query(
      siteUrl='https://tenor.com/',
      fields='responseAggregationType,rows',
      body={
          "startDate": date_str,
          "endDate": date_str,
          "searchType": search_type,
          "dimensions": [
              "page",
          ],
          "rowLimit": row_limit,
          "startRow": start_index,
      },
  )
  try:
      resp = req.execute()
      next_rows = resp['rows']
      rows += next_rows
      next_index = len(next_rows)
      start_index += next_index
  except Exception as e:
      print(e)
      break
return rows

A: For anyone else viewing this post:
When I view 'Search Results' under 'Performance' in the sidebar of the google search console webpage, at the end of the url there is a variable 'resource_id=sc-domain%3example.com'. I recommend using this resource_id variable as your siteURL.


text:
Q: Discord js, TypeError: Supplied parameter was neither a User nor a Role I am trying to make a bot, which when a command is entered, it will change the permission of a channel for only that user. However, when trying to overwrite the permission I keep getting this type error.

TypeError: Supplied parameter was neither a User nor a Role.

I keep getting the error, pointing towards the message.member.id ,any help would be appreciated all questions relating to this are to do with roles rather than users.

        const permissions = new Permissions([
        'MANAGE_CHANNELS',
        'EMBED_LINKS',
        'ATTACH_FILES',
        'READ_MESSAGE_HISTORY',
        'MANAGE_ROLES',
        ]);

        const nextChannel = message.guild.channels.find(channel => channel.name === "b2");
        nextChannel.overwritePermissions([
            {
                id: message.member.id,
                deny: permissions,
            },
        ]);

A: As the error states, you did not provide a User nor a Role you provided a GuildMember
You need to replace message.member.id with message.user.id

A: Here is the solution below - Taken that you are on v11
nextChannel.overwritePermissions(message.author.id
            {
              SEND_MESSAGES: false
            },
        );

I hope this helped you continue.


text:
Q: Creating DOM elements with different text I'm trying to dynamically create DOM elements that display each object value for all objects in the array.
I used a for loop to create the elements and tried matching content iterations to the array iterations, but it doesn't work. Below is my code (this is a simplified version to get the code working).
let divTwo = document.querySelector('.div-two');
let bigArray = [{
    first: 'Joe',
    location: 'Washington'
  },
  {
    first: 'Jon',
    location: 'Boston'
  },
  {
    first: 'Brian',
    location: 'New York'
  },
];
let smallArray = ['first', 'location'];

function addNames() {
  for (let i = 0; i < bigArray.length; i++) {
    for (let j = 0; j < smallArray.length; j++) {
      let newSpan = document.createElement('span');

      newSpan.id = 'spanny' + (j + 1);
      divTwo.appendChild(newSpan);
      document.getElementById('spanny1').textContent = bigArray[j].first;
      document.getElementById('spanny2').textContent = bigArray[j].location;

      // newSpan[0].textContent = bigArray[0].first;     *also doesn't work*
      // newSpan[1].textContent = bigArray[0].location;  *also doesn't work*
    }
  }
}

addNames();

A: You don't really want to add these IDs to the <span>s, since they will appear three times each on your page, which is invalid.
You're probably looking for something like this. You want to get the i-th element of bigArray, then get the value associated with the key given by the j-th element in smallArray. So use bigArray[i][smallArray[j]].
function addNames() {
  for (let i = 0; i < bigArray.length; i++) {
    for (let j = 0; j < smallArray.length; j++) {
      let newSpan = document.createElement("span");

      divTwo.appendChild(newSpan);
      newSpan.textContent = bigArray[i][smallArray[j]];
    }
  }
}

It's cleaner using ECMAScript 6+:
function addNames() {
  bigArray.forEach((data) => divTwo.append(...smallArray.map((key) => Object.assign(document.createElement("span"), {
    textContent: data[key]
  }))));
}


text:
Q: CSS3 custom animation triggering after :hover I'm creating a series of "windows" or "doggie doors" that, when hovered on, seem to push back into the "window" just like a doggie door.
I've been able to create a natural looking effect of the doggie door closing.  It swings back and forth a couple times and then rests back to its default position.
My problem is that I haven't been able to figure out a way to trigger the swing when the hover is released.  I know its a logic issue because I've seen examples of it done here and using keyframes [here][2].  I also know I could solve this with javascript but I'm sticking strictly to CSS for this site.
UPDATE:
Here is the working example. Fiddle
Thank you Nobita!
HTML:

CSS:
* {
    list-style: none;

}
.door {
    width: 300px;
    height: 300px;
    margin: 0;
    position: relative;
    perspective:1000px;
    -webkit-perspective:1000px;
    /* Safari and Chrome */
}
.door img {
    background-color: #E8585A;
    width: 100%;
    display: block;
    position: relative;
    transform-origin: top;
    -ms-transform-origin: top;
    /* IE 9 */
    -webkit-transform-origin: top;
    /* Safari and Chrome */
    -moz-animation: swing 2s;
    -webkit-animation: swing 2s;
    animation: swing 2s;
    z-index: 10;
}

.door:hover img {
      transform-origin: top;
    -webkit-transform-origin: top;
    -webkit-transform: rotateX(-60deg);
    -webkit-transition: all .2s;
    background-color: #00a99d;
    -webkit-animation: swing;
    /* Safari and Chrome */
}
@-webkit-keyframes swing {
    0%, 20%, 40%, 60%, 80%, 100% {
        -webkit-transform-origin: top center;
    }
    0% {
        -webkit-transform: rotateX(-60deg);
    }
    20% {
        -webkit-transform: rotateX(-60deg);
    }
    40% {
        -webkit-transform: rotateX(25deg);
    }
    60% {
        -webkit-transform: rotateX(-20deg);
    }
    80% {
        -webkit-transform: rotateX(5deg);
    }
    100% {
        -webkit-transform: rotateX(0deg);
    }
}

A: Nice technique, I didn't know you could trigger animations when hovering off a div!
I fiddled a bit and hopefully got it working even if not as smoothly as expected, but it's probably enough to take a step further in the right direction.
The problem here is - I guess - that you're not declaring an animation on hover state (as suggested in your links), but just a transition. So I tried adding a transition for the 'door' to open on hover...
.door:hover img {
  transform-origin: top;
  transform: rotateX(-60deg);
  transition: all .2s;

...and an animation which will fire on mouseout:
   animation: swing;
 }

Hope this fiddle shows what you need or at least helps you someway.
Anyway very glad myself to have learnt something new, thanks.

* {
    list-style: none;
    -webkit-transition: all .5s ease-out;
    -moz-transition: all .5s ease-out;
    -o-transition: all .5s ease-out;
    transition: all .5s ease-out;

}
*:hover {
    -webkit-transition: all .2s ease-out;
    -moz-transition: all .2s ease-out;
    -o-transition: all .2s ease-out;
    transition: all .2s ease-out;
}
.door {
    width: 300px;
    height: 300px;
    margin: 0;
    position: relative;
    perspective:1000px;
    -webkit-perspective:1000px;
    /* Safari and Chrome */
}
.door img {
    background-color: #E8585A;
    width: 100%;
    display: block;
    position: relative;
    transform-origin: top;
    -ms-transform-origin: top;
    /* IE 9 */
    -webkit-transform-origin: top;
    /* Safari and Chrome */
    -moz-animation: swing 2s;
    -webkit-animation: swing 2s;
    animation: swing 2s;
    z-index: 10;
}

.door:hover img {
      transform-origin: top;
    -webkit-transform-origin: top;
    -webkit-transform: rotateX(-60deg);
    -webkit-transition: all .2s;
    background-color: #00a99d;
    -webkit-animation: swing;
    /* Safari and Chrome */
}
@-webkit-keyframes swing {
    20%, 40%, 60%, 80%, 100% {
        -webkit-transform-origin: top center;
    }
    20% {
        -webkit-transform: rotateX(-60deg);
    }
    40% {
        -webkit-transform: rotateX(25deg);
    }
    60% {
        -webkit-transform: rotateX(-20deg);
    }
    80% {
        -webkit-transform: rotateX(5deg);
    }
    100% {
        -webkit-transform: rotateX(0deg);
    }
}

A: I got it working in Firefox v22 using the :not pseudo-class like so:
Working Example
.door img:not(:hover) {
    transform-origin: top;
    animation: swing 2s;
}

This pseudo class combination looks like a bad hack, but it works.
The animation still needs some work for -webkit- browsers...


text:
Q: HTML2FPDF - Positioning the writeHTML output I have the following code:
function convert($contents, $name){
  echo($link); //prints nothing
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  $pdf->SetFont('Arial','B',16);
  $pdf->Cell(40,10, "Entry Report");
  $pdf->SetFont('Arial', '', 12);
  $pdf->Cell(100,10, $_SESSION['currdate']);
  $pdf->WriteHTML( $contents );
  $pdf->Output($name, "D");
}

By default the writeHTML content is positioned within the PDF at the top...How do I offset the wrriten content that is placed in the pdf by the writeHTML function...

A: In FPDF you can use SetX(), SetY() or SetXY().


text:
Q: Java Custom Logger - Not logging proper classname I am trying to create a Custom Logger.
My code is given below and the Properties file is also given below.
It works in the sense that I get log messages and details in the log file in the format I want.
However, all logs are logged with same ClassName - MyLogger. I want the 'name' I am passing in the constructor to be logged as ClassName instead of the MyLogger ClassName.
Appreciate any help in that regard.
Java Code:
    public class MyLogger {

    private static Logger log;

    public static MyLogger getLogger(String name) {
        return new MyLogger(name);
    }

    private MyLogger(String name) {
        log = Logger.getLogger(name);
        try {
            LogManager.getLogManager().readConfiguration(new FileInputStream("./logging.properties"));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MyLogger.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | SecurityException ex) {
            Logger.getLogger(MyLogger.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void log(Level LogLevel, String logMessage, Object param1) {
        log.log(LogLevel, logMessage, param1);
    }

    public void log(Level LogLevel, String logMessage, Throwable e) {
        log.log(LogLevel, logMessage, e);
    }

    public void log(Level LogLevel, String logMessage) {
        log.log(LogLevel, logMessage);
    }
}

logging.properties File content:
handlers = java.util.logging.FileHandler
java.util.logging.FileHandler.level     = ALL
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format = %1$tF %1$tT %4$s %2$s %5$s%6$s%n
java.util.logging.FileHandler.limit     = 1048576
java.util.logging.FileHandler.count     = 5
java.util.logging.FileHandler.append    = true
java.util.logging.FileHandler.pattern   = ./logs/log-%u-%g.log

--

A: The documentation for SimpleFormatter.format explains that the source parameter (%2$s in the format string) is "a string representing the caller, if available; otherwise, the logger's name". This looks at the stack to determine the direct caller, which in your case will always be  the MyLogger class.
To use the logger name instead, use %3$s in the java.util.logging.SimpleFormatter.format configuration rather than %2$s.

A: Per API docs you can use the log precise methods:

There are a set of "logp" methods (for "log precise") that are like the "log" methods, but also take an explicit source class name and method name.

Combine that with the inferCaller method to make your bridge look transparent:
 public void log(Level LogLevel, String logMessage) {
    StackTraceElement stack = inferCaller();
    log.logp(stack.getClassName(), stack.getMethodName(), LogLevel, logMessage);
 }

private boolean isPrintImplFrame(String cname) {
    return MyLogger.class.getName().equals(cname);
}

private StackTraceElement inferCaller() {
    StackTraceElement stack[] = (new Throwable()).getStackTrace();
    int ix = 0;
    while (ix < stack.length) {
        StackTraceElement frame = stack[ix];
        String cname = frame.getClassName();
        if (isPrintImplFrame(cname)) {
            break;
        }
        ix++;
    }

    while (ix < stack.length) {
        StackTraceElement frame = stack[ix];
        String cname = frame.getClassName();
        if (!isPrintImplFrame(cname)) {
            return frame;
        }
        ix++;
    }

    return new StackTraceElement(MyLogger.class.getName(), "log",
            MyLogger.class.getName(), -1);
}

Using this method your code will find the stack frame that is calling your bridge logger that is not the bridge logger itself.


text:
Q: In xpath how you compare text() with \r\n (line break)? I want to get the node :
//script[starts-with(text(). '\r\nvar name')]
but it seems xpath does not recognize \r\n escape characters. Any ideas how to match them?
Note: I am using html agility pack

A: Use:
//script[starts-with(., '
var name')]

Most often XML is normalized by the XML parser and there is only a single NL character left -- therefore, if the above expression doesn't select the wanted script elements, try with:
//script[starts-with(., '
var name')]

Or, this would work in both cases:
//script
    [(starts-with(., '
') or starts-with(., '
'))
   and
    starts-with(substring-after(., '
'), 'var name')
    ]


text:
Q: Proof for law of complex exponents using only differential equation I just read that an elegant proof exists that the law of exponents also holds for complex numbers ($a,b,z$ all complex): $$e^{a+b}=e^ae^b,$$ which only uses the definition that $$y=e^{zt}$$ is a solution to $$dy/dt=zy,$$ with initial condition $y(0)=1$, so in particular $e^z=y(1).$
I can only find a proofs which use the trig-representation of complex numbers.
Can anybody help?
Thank you!

A: Another way is to see that any $f: \mathbb{C} \to \mathbb{C}$ satisfying $f'(z) = f(z)$ and $f(0) = 1$ is analytic in $\mathbb{C}$ (entire) and admits a power series representation
$$ f(z) = \sum_{n=0}^{\infty} a_n z^n$$
The fact that $f'(z) = f(z)$ and $f(0) = 1$ easily give us
$$f(z) = \sum_{n=0}^{\infty} \frac{z^n}{n!}$$
Now it is easy to verify that $f$ indeed satisfies the above differential equation and initial conditions (and hence is the unique function) and that
$$f(a+b) = f(a)f(b)$$

A: Let $g(z) = e^{a+z}/e^a$.  Then $g'(z) = g(z)$ and $g(0) = 1$.  So $g(z) = e^z$, and we have that $e^{a+z} = e^ae^z$.
That assumes that $e^z$ is the only solution to  $f'(z)=f(z)$ with $f(0)=1$.

A: If you define $e^z$ as the unique solution to the ODE $f'(z)=f(z)$ with initial condition $f(0)=1$, then you have by the product rule:
$$ (e^ze^{c-z})'=e^ze^{c-z} + e^z(-e^{c-z})=0.$$
Thus $e^ze^{c-z}$ is a constant. Using the initial condition $e^0=1$ we find that $e^ze^{c-z}=e^c$. Now let $z=a$ and $c=a+b$ and the result follows.


text:
Q: PHP - Unset $_SESSION variables using foreach Is it possible to unset $_SESSION variables using a foreach cycle? This is an example.
<?php
session_start();
$_SESSION['one'] = 'one';
$_SESSION['two'] = 'two';
$_SESSION['three'] = 'three';
print_r($_SESSION);
foreach($_SESSION as $value) {
    unset($value);
}
session_destroy();
print_r($_SESSION);
?>

I think that this script should work but it's not working for me. It gives me this output, without unsetting the variables :

Array ( [one] => one [two] => two [three] => three )Array ( [one] =>
  one [two] => two [three] => three )

Maybe it's a problem related to superglobal arrays. I can anyway unset the variables using their key :
unset($_SESSION['one']);

A: You must get the key and unset $_SESSION[$key] or pass your variable by reference (not sure if you can unset a reference).
foreach($_SESSION as $key => $value) {
    unset($_SESSION[$key]);
}

foreach($_SESSION as &$value) {
    unset($value);
}

A: Pass the variable by reference :
foreach($_SESSION as &$value) {
    // edit $value
}

A: unset it with,
unset($_SESSION);


text:
Q: how can i use a javascript in gridview row I want to use a flash chart in a gridview. you can see my codes in below:
        DataTable tbl = new DataTable();
        tbl.Columns.Add("chart");
        DataRow rw;

        rw = tbl.NewRow();
        rw["chart"] = @"

                ";
        tbl.Rows.Add(rw);
        GridView1.DataSource = tbl;
        GridView1.DataBind();

I must create dynamicly my datasource. But i can see just string value instead of my chart in gridview when page running. But chart code is running correctly between table tags. How can i use these codes in gridview??
KR

A: What kind of column are you using in grid-view to show "chart" data? That column would be (correctly) escaping your html. I would suggest using TemplateColumn with dive and all your script can be put in markup (aspx) page. The dynamic part within your script can come from data row using data binding expressions (<%# Eval('Column Name') %>).


text:
Q: Parameter Map in jasper query This is my query in jasper.jrxml:
<queryString>
        <![CDATA[SELECT c.id,
    b.nom_beneficier,
    c.date_saisie,
    cat.designation,
    c.montant_brut,
    c.montant_rs,
    c.net_rs,
    id_exercice
    FROM
    crs_certificat c,
    crs_beneficier b,
    crs_categorie_taux cat
    WHERE
     c.id_beneficier = b.id
     AND c.categorie = cat.id
     AND id_exercice = //I want to pass a parameter here
     AND c.delete_stat = 0]]>
    </queryString>

How can I put paramter in this query and call it whenever I want ?
EDIT:
This is where I declared my parameter but jasper can't see it:
<subDataset name="tableDataset" uuid="7a7abe40-c5fa-40c9-bc37-a573ee7d748a">
        <property name="com.jaspersoft.studio.data.defaultdataadapter" value="New Data Adapter "/>
        <parameter name="exercice" class="java.lang.Integer"/>
        <queryString>
            <![CDATA[SELECT c.id, nom_beneficier, date_saisie, designation, montant_brut, montant_rs, net_rs
FROM crs_certificat c, crs_beneficier b, crs_categorie_taux cat
WHERE id_beneficier = b.id and categorie = cat.id AND id_exercice = $P{exercice}]]>
        </queryString>
        <field name="id" class="java.lang.Integer"/>
        <field name="nom_beneficier" class="java.lang.String"/>
        <field name="date_saisie" class="java.sql.Date"/>
        <field name="designation" class="java.lang.String"/>
        <field name="montant_brut" class="java.lang.Double"/>
        <field name="montant_rs" class="java.lang.Double"/>
        <field name="net_rs" class="java.lang.Double"/>
    </subDataset>


text:
Q: Yii2 NOT IN condition not working I use this for query not in:
 $usertypes=Usertype::find()->where(['not in ','user_type_id',['2,3,4']])->all();

Error:
Database Exception – yii\db\Exception

Undefined offset: 1
Failed to prepare SQL: SELECT * FROM usertype WHERE user_type_id NOT IN :qp0
also tried the array format as ['2','3','4'] but not works?What is the issue?

A: Try This :
$usertypes=Usertype::find()
           ->where(['not in','user_type_id',[2,3,4]])
           ->all();

OR :
$usertypes=Usertype::find()
               ->where(['NOT',['user_type_id'=>[2,3,4]]])
               ->all();

Refer : http://www.bsourcecode.com/yiiframework2/select-query-model/#In-Condition

A: Maybe remove space character from 'not in '?
$usertypes=Usertype::find()->where(['not in', 'user_type_id', ['2,3,4']])->all();

A: you can use "not" word or "<>"
 $usertypes=Usertype::find()->where(['not',['user_type_id'=>['2,3,4']]])->all();

or this
 $usertypes=Usertype::find()->where(['<>',['user_type_id'=>['2,3,4']]])->all();

A: Try to use ->andFilterWhere instead of where ->where
Try this:
$usertypes = Usertype::find()
           ->andFilterWhere(['NOT IN','user_type_id',[2,3,4]])
           ->all();


text:
Q: URL forwarding with modrewrite in an htaccess file I'm currently in the process of adapting my .htaccess file, but need help.
The URLs should all be redirected.
The big characters should be converted into small characters.
If the called address exists, the file should be called directly.
All other addresses that do not exist should be forwarded to Index.php.
The following link is now called:

*

*www.example.com/test1/test2/test3.html

*example.com/TeST1/TEST2/test3.html

*www.example.com/test1/test2/test3
The forwarding should always call the Index.php and the following should be in the address line:
http://example.com/test1/test2/test3.html
If I have variables (example.com/TeST1/TEST2/test3.html?id=6&test=hello) these should of course also be transferred.
So that my CSS files and images can be properly integrated, I think I have to deactivate the forwarding for certain file types.
The following folders should be excluded from the redirection: css, media, img
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ /index.php [L,QSA]

Can someone write the file or help me with it?

A: Try:
RewriteEngine On

RewriteMap lc int:tolower
RewriteCond ${REQUEST_FILENAME} !-d
RewriteCond ${REQUEST_FILENAME} !-f
RewriteRule (.*[A-Z].*) /${lc:$1} [R=302,L]
# if you encounter double slashes, remove the slash before ${lc...

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /index.html [QSA,L]


text:
Q: Android connect to Wifi programmatically if wifi name match I would like to build an app, that checks all the available WiFi networks,
If a network's SSID matches a search key then connect to that network, if two networks match then connect to the one with the higher signal strength.
e.g. SearchKey = "Open";
here is the code to check check all the wifi names :
    if (networkInfo.isConnected()) {
                ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();
            List<ScanResult> results = wifiManager.getScanResults();
            int size  = results.size();
            HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
            try {
                for (int i = 0; i < size; i++) {
                    ScanResult result = results.get(i);
                    if (!result.SSID.isEmpty()) {
                        String key = result.SSID + " " + result.capabilities;
                        Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);
}

Then I would need to
Arrays.asList(mItems).contains("Open")

I am stuck here, How to do a proper check if the keyword "Open" exits, if so, then get the whole name and use below. ?
online sample how to conenct.
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);

WifiManager wifiManager = (WifiManager).getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

UPDATE CODE ------------------------------  - --------------------------------- - -- ---------------------------------------
How to check, This works But Now I need to implement Search by signal strength
if (!result.SSID.isEmpty()) {
                        String key = result.SSID + " " + result.capabilities;
                        Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);

                        if(result.SSID.contains("Open")) {
                            String useSSID = result.SSID;
                            Log.w(TAG, "useSSID => " + useSSID);

                            connectToWifi(MainActivity.this, useSSID);
                            break;
                        }
                        else { Log.e(TAG, "NO result  contains"); }

Now how can I query my :
ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();

                if (!signalStrength.containsKey(key)) {
                    signalStrength.put(key, i);
                    mItems.add(result);
                } else {
                    int position = signalStrength.get(key);
                    ScanResult updateItem = mItems.get(position);
                    if (calculateSignalStength(wifiManager, updateItem.level) > calculateSignalStength(wifiManager, result.level)) {
                        mItems.set(position, updateItem);
                    }
                }

                     if(mItems.contains("Open")) {
                                String useSSID = mItems #how to the name SSID name from mItems ???
                                Log.w(TAG, "useSSID => " + useSSID);

                                connectToWifi(MainActivity.this, useSSID);
                                break;
                            }
                            else { Log.e(TAG, "NO result  contains"); }

=== Now my question is how to the SSID name from mItems ?
Thanks guys for your help.

A: Here is a snippet for the same:
public string getValidSSID()
{
    List<ScanResult> results = wifiManager.getScanResults();
    HashMap<String,ScanResult> distinctNetworks = new HashMap<String, ScanResult>();
    for(ScanResult scanResult :  results)
    {
        if(scanResult.SSID.contains("Open"))
        {
            if(!distinctNetworks.containsKey(scanResult))
            {
                distinctNetworks.put(scanResult.SSID, scanResult);
            }
            else
            {
                if(WifiManager.compareSignalLevel(scanResult.level, distinctNetworks.get(scanResult.SSID).level)>0)
                {
                    distinctNetworks.put(scanResult.SSID, scanResult);
                }
            }
        }
    }
    Set<String> networks  = distinctNetworks.keySet();// This will only contain one key which will be ths ssid with the max strength containing "open" in SSID
    for (String s : networks) {
        return s;
    }
}


text:
Q: the_excerpt didn't appear - woocommerce / wordpress HMTL original rendered:

     3 - Blog Post

     <img width="150" height="150" src="http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-150x150.jpg" class="attachment-thumbnail size-thumbnail wp-post-image" alt="" srcset="http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-150x150.jpg 150w, http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-300x300.jpg 300w, http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-768x768.jpg 768w, http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal.jpg 900w" sizes="(max-width: 150px) 100vw, 150px" />

HTML after setup_postdata( $post );

                3 - Blog Post

            <img width="150" height="150" src="http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-150x150.jpg" class="attachment-thumbnail size-thumbnail wp-post-image" alt="" srcset="http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-150x150.jpg 150w, http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-300x300.jpg 300w, http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal-768x768.jpg 768w, http://localhost/PHP/wordpress/wp-content/uploads/2017/04/imagem-principal.jpg 900w" sizes="(max-width: 150px) 100vw, 150px" />

Bem-vindo ao WordPress. Esse é o seu primeiro post. Edite-o ou exclua-o, e então comece a escrever!

Weird things:

The code:

<?php
$args = array( 'numberposts' => '3' );
$recent_posts = wp_get_recent_posts( $args );
foreach($recent_posts as $post)
{
    ?>

            <a href="<?php echo get_the_permalink($post['ID']); ?>">
                <?php echo $post['post_title']; ?>

            <?php echo get_the_post_thumbnail($post['ID'], 'thumbnail'); ?>
            <?php
            $my_excerpt = get_the_excerpt($post['ID']);
            if ( '' != $my_excerpt ) {
              // Some string manipulation performed
            }
            echo $my_excerpt // Outputs the processed value to the page
            ?>

<?php
}
wp_reset_query();
?>

      <?php
        $args = array( 'numberposts' => '3' );
        $recent_posts = wp_get_recent_posts( $args );
        foreach($recent_posts as $post) { ?>

                <a href="<?php echo get_the_permalink($post['ID']) ?>">
                  <?php echo $post['post_title'] ?>

                <?php echo get_the_post_thumbnail($post['ID'], 'thumbnail'); ?>

                <?php
                $my_excerpt = get_the_excerpt($post['ID']);
                if ( '' != $my_excerpt ) {
                  // Some string manipulation performed
                }
                echo $my_excerpt // Outputs the processed value to the page
                ?>

      <?php
      }
        wp_reset_query();
      ?>

When I change the position of the code and remove title and thumbnail, the code works well:
  <?php
    $args = array( 'numberposts' => '3' );
    $recent_posts = wp_get_recent_posts( $args );
    foreach($recent_posts as $post) { ?>

            <?php
            $my_excerpt = get_the_excerpt($post['ID']);
            if ( '' != $my_excerpt ) {
              // Some string manipulation performed
            }
            echo $my_excerpt // Outputs the processed value to the page
            ?>

  <?php
  }
    wp_reset_query();
  ?>

I call the recent posts in my wordpress / woocommerce page, but when I call the excerpt, it didn't appear, title and thumbnail are ok. I have worked on it all day long, but I couldn't figure out what happen. When I change "echo $my_excerpt" with a simple word, it works. The problem should be when I put the content in a array. I had followed the documentation as you can see:
https://codex.wordpress.org/Function_Reference/get_the_excerpt
Examples
get_the_excerpt() can be used to retrieve and store the value in a variable, without outputting it to the page.
<?php
$my_excerpt = get_the_excerpt();
if ( '' != $my_excerpt ) {
    // Some string manipulation performed
}
echo $my_excerpt; // Outputs the processed value to the page
?>

My code:
      <?php
        $args = array( 'numberposts' => '3' );
        $recent_posts = wp_get_recent_posts( $args );
        foreach($recent_posts as $post) { ?>

                <a href="<?php echo get_permalink($post['ID']) ?>">
                  <?php echo $post['post_title'] ?>

                <?php echo get_the_post_thumbnail($post['ID'], 'thumbnail'); ?>

                <?php
                $my_excerpt = get_the_excerpt();
                if ( '' != $my_excerpt ) {
                  // Some string manipulation performed
                }
                echo $my_excerpt // Outputs the processed value to the page
                ?>

      <?php
      }
        wp_reset_query();
      ?>

A: Edit: I have altered your code try using this one.
<?php
$args = array( 'numberposts' => '3' );
$recent_posts = wp_get_recent_posts( $args );
foreach($recent_posts as $post)
{
    setup_postdata( $post ); // Edit: This will force wordpress to setup the data
    ?>

            <a href="<?php echo get_the_permalink($post['ID']); ?>">
                <?php echo $post['post_title']; ?>

            <?php echo get_the_post_thumbnail($post['ID'], 'thumbnail'); ?>
            <?php
            $my_excerpt = get_the_excerpt($post['ID']);
            if ( '' != $my_excerpt ) {
              // Some string manipulation performed
            }
            echo $my_excerpt // Outputs the processed value to the page
            ?>

<?php
}
wp_reset_query();
?>

Try this. I have provided post id to your get the excerpt.
<?php
$my_excerpt = get_the_excerpt($post['ID']);
if ( '' != $my_excerpt ) {
  // Some string manipulation performed
}
echo $my_excerpt // Outputs the processed value to the page
?>

A: Well, after a plenty of options, tests, feedbacks and research, I've found a way to make it.
Thank you everyone!
My final code:

Testando - Posts Recentes

<?php
    query_posts( array('posts_per_page'=>3) );
    while ( have_posts() ) : the_post();
?>

                <img class="card-img-top img-fluid" src="<?php the_post_thumbnail(); ?>">

<?php the_title(); ?>

                      <?php
                        the_excerpt();
                      ?>

                    <a class="btn btn-primary" href="<?php the_permalink(' ') ?>">Ler o post

      <?php
        endwhile;
        wp_reset_query(); // resets main query
      ?>


text:
Q: Rails migration for updated gem We have this gem that recently got a version boost which included a lot of new migrations.
What seems to be the consensus when running new migrations on apps with existing installations without having to wipe the database and start again?
At the moment our install_generator just copies in the updated migration.rb file but immediately conflicts with apps that already have the old tables.
So I'm looking for the cleanest way to handle gem updates that include new migrations.

A: Migrations inside gems are supposed to be written in a way such that while running new migrations, you don't have to delete old tables. Which gem are you using?


text:
Q: android sax not parsing "dc:creator"? Hope someone can provide some guidance - i've been using android sax parser with several feeds. Now when I want to parse an item that contains following:
<category>category</category>
<dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">creator</dc:creator>
<dc:date xmlns:dc="http://purl.org/dc/elements/1.1/">2011-10-13T07:00:15Z</dc:date>
<geo:lat>51.95271682739258</geo:lat>
<geo:long>-0.21096819639205933</geo:long>

I can get the value of "category" tag, but nothing for the others.
The code used follows examples from http://www.ibm.com/developerworks/opensource/library/x-android/, in particular snippet to parse the tags:
Element item = channel.getChild("item");

item.getChild("category").setEndTextElementListener(new EndTextElementListener() {
  public void end(String body) {
   Log.e("mydebug","cat>>"+body+"<");
  }
});
item.getChild("dc:creator").setEndTextElementListener(new EndTextElementListener() {
  public void end(String body) {
   Log.e("mydebug","creator>>"+body+"<");
  }
});

generates this output:
10-13 14:13:12.763: ERROR/mydebug(609): cat>>category<
10-13 14:13:12.763: ERROR/mydebug(609): cat>>category2<

I'm using the following:
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Log;
import android.util.Xml;

Anything I'm missing?
Only thing I can guess is that ":" in the tag is giving me problems, but I couldn't find any examples of similar issue.
Many thanks for reading.

A: When using the startElement() and endElement() methods in your DefaultHandler, both the local name and qualified name values are passed in.  Make sure you're checking the qualified name for things like 'dc:creator' or else they won't match.
See the official documentation here:  http://developer.android.com/reference/org/xml/sax/helpers/DefaultHandler.html#startElement%28java.lang.String,%20java.lang.String,%20java.lang.String,%20org.xml.sax.Attributes%29
Also, you may consider using the XML Pull Parser as it's a bit more light weight than SAX and might be more appropriate for your needs:  http://developer.android.com/reference/org/xmlpull/v1/XmlPullParserFactory.html

A: You are using an API that only looks at the localname of the element:  Android Documentation
Try this instead:
item.getChild("creator").setEndTextElementListener(new EndTextElementListener() {
  public void end(String body) {
   Log.e("mydebug","creator>>"+body+"<");
  }
});


text:
Q: Using if/then condition with dictionary object I am new to python and have been working through a handful of activities. Currently I am working with Conditions. I created a dictionary of months and I am using an if/then condition to check if user input is in the dictionary. If the User input is not in the dictionary the output should say 'Bad Month' My code is as follows:
months = {1: 'January',
          2: 'February',
          3: 'March',
          4: 'April',
          5: 'May',
          6: 'June',
          7: 'July',
          8: 'August',
          9: 'September',
          10: 'October',
          11: 'November',
          12: 'December'}
choice = input

choice = input('Enter an integer value for a month:')
result = choice

if int(choice) in months:
    print('months')

else:
    print('Bad month')

When any integer above 12 is entered the output is 'Bad Month' but when I enter a number from 1-12 the output is just months? I've tried a number of print statements but none that I have tried work. I'm stuck.

A: You'll want to cast the user input from what input() takes as string to an integer that you can compare to the keys() of your dictionary, and print the corresponding value of that key.
months = {1: 'January',
          2: 'February',
          3: 'March',
          4: 'April',
          5: 'May',
          6: 'June',
          7: 'July',
          8: 'August',
          9: 'September',
          10: 'October',
          11: 'November',
          12: 'December'}

choice = int(input('Enter an integer value for a month: ')) # cast user input to integer

if choice in months:        # check if user input exists in the dictionary keys
    print(months[choice])   # print corresponding key value
else:
    print('Bad month')

Demo:
Enter an integer value for a month: 4
April

A: You can go several routes here. If you want to keep your code outline, try
if int(choice) in months:
    print('months')

else:
    print('Bad month')

As several comments suggested, a better approach might be to use the get syntax (tutorial).
months.get(input, "Bad Month")

Will check for input and if it can't find it, return Bad Month.  Just print what the get function returns, and it'll do what you are looking for.


text:
Q: Append element to 2D array How can I append an element to first or second element of a numpy array in python?
My code does not work.
I did like this:
my_num = np.array([[],[]])
my_num[0] = np.append(my_num[0],6)
print(my_num[0])

But my_num is empty.

A: Maybe try this:
my_num[0] = np.append(my_num[0],np.array([6]))

The second argument in append must be the same "shape" as the first (i.e., an array). See Numpy docs here.


text:
Q: `UIScrollView` `bounds` are different in `viewDidAppear` than last `viewDidLayoutSubviews` In attempt to improve the UI for smaller devices, when a UIScrollView contentSize.height is greater than it's bounds.height (I'm calling this an overflow) I want to tweak the UI.
My issue is: I'm finding the layout of the views is different after appearing on screen (in viewDidAppear(:)) than it is in the last viewDidLayoutSubviews() (could be called multiple times).
In order to determine if a scrollView is overflowing, we need to know both the scrollView.bounds and scrollView.contentSize. Which I thought would be determined in the last call of viewDidLayoutSubviews().
Below examples my scenario. It's running an interface built in xib with the scrollView set up there too. Note there are no hiding/showing of views to interfere with the layout values, simply runs through.
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    printOverflow(type: #function)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    printOverflow(type: #function)
}

private func printOverflow(type: String) {
    let isOverflowY = scrollView.contentSize.height > scrollView.bounds.height
    debugPrint("[Overflow] \(type) \(isOverflowY ? "Overflow" : "Fits")")
}

// After running prints:
// "[Overflow] viewDidLayoutSubviews() Fits"
// "[Overflow] viewDidAppear(_:) Overflow"

My question is: why can I not get the final layout of the subviews in the last viewDidLayoutSubviews()?
I also tried adding a view.layoutIfNeeded() in viewWillAppear(:), indeed this fires another viewDidLayoutSubviews() as you'd expect but the bounds properties are still different to that in viewDidAppear(:) (despite actually now printing "Overflow")

A: From Apple's docs (italics are mine):

func viewDidLayoutSubviews()
When the bounds change for a view controller'€™s view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view'€™s subviews have been adjusted. Each subview is responsible for adjusting its own layout.

So, viewDidLayoutSubviews() can (and will) be called before subviews have been completely configured by auto-layout. That's also why we see viewDidLayoutSubviews() being called multiple times during loading / displaying.
If you subclass UIScrollView like this:
class MyScrollView: UIScrollView {

    override func layoutSubviews() {
        super.layoutSubviews()
        printOverflow(type: #function)
    }

    private func printOverflow(type: String) {
        let isOverflowY = contentSize.height > bounds.height
        debugPrint("MyScrollView {Content Size: \(contentSize.height) Bounds Height: \(bounds.height)} [Overflow] \(type) \(isOverflowY ? "Overflow" : "Fits")")
    }

}

You'll see that you get the correct heights.
What exactly are trying to do to "improve the UI for smaller devices"? There may be other (better?) options...

Edit
Here's a very simple example showing the sizing at each stage. The custom view changes its height anchor (if necessary) in its layoutSubviews() function:
import UIKit
class MySizingView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
        if frame.height != 200.0 {
            heightAnchor.constraint(equalToConstant: 200.0).isActive = true
        }
        print(#function, "self height:", frame.height)
    }
}

class SizingTestViewController: UIViewController {

    let myView: MySizingView = {
        let v = MySizingView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(myView)
        NSLayoutConstraint.activate([
            // constrain width and center X & Y
            //    its height will be set by its own height constraint
            myView.widthAnchor.constraint(equalToConstant: 300.0),
            myView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        ])
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print(#function, "myView height:", myView.frame.height)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(#function, "myView height:", myView.frame.height)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print(#function, "myView height:", myView.frame.height)
    }

}

Debug console output should be:
viewWillAppear(_:) myView height: 0.0
viewDidLayoutSubviews() myView height: 0.0
layoutSubviews() self height: 0.0
viewDidLayoutSubviews() myView height: 200.0
layoutSubviews() self height: 200.0
viewDidAppear(_:) myView height: 200.0


text:
Q: Issue with Rendering Ajax/Rails Situation: Currently have a comment model that paginates under a micropost. I am trying to make the next button render comments that belong to the micropost.
Issue: I am unsure how to go about making a route/action inorder to bring these comments through.
Codes: I have some code that I will provide below, if anything isn't right please assist.
All help is much Appreciated.
References: Issue with Ajax Appending
User Controller
  def show
    @user = User.find(params[:id])
    @micropost = Micropost.new
    @comment = Comment.new
    @comment = @micropost.comments.build(params[:comment])
    @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 10, :page => params[:page])
  end

Pagination JS
$("#CommentPagin").on('click', 'a', function(e){
    // Get data from server - make sure url has params for per_page and page.
    $.get($(this).attr('href'), function(data){
        // refresh client with data
        $("#cc").append(data);
    });
});

Comment Section

  <% comments = micropost.comments.paginate(:per_page => 5, :page => params[:page]) %>

  <%= will_paginate comments, :page_links => false , :class =>"pagination" %>

<%= render 'users/comments' %>

Comment Rendering Section

<% comments = micropost.comments.paginate(:per_page => 5, :page => params[:page]) %>
<%= render comments %>

UPDATE
User Model
class User < ActiveRecord::Base
  has_many :microposts
  has_many :comments
end

Micropost Model
class Micropost < ActiveRecord::Base
  belongs_to :user
  has_many :comments
  accepts_nested_attributes_for :comments
end

Comment Model
class Comment < ActiveRecord::Base
  attr_accessible :content, :user_id, :micropost_id
  belongs_to :micropost, :counter_cache => true
  belongs_to :user
  belongs_to :school
end

Routes.rb
kit::Application.routes.draw do
  resources :pages
  resources :application
  resources :schools
  resources :microposts
  resources :comments
  resources :users
  resources :sessions
  resources :password_resets
  resources :relationships, only: [:create, :destroy]
  resources :users do
      member do
        get :following, :followers
      end
  end
  resources :microposts do
    member do
      post :vote_up, :unvote
    end
  end
  resources :microposts do
    member do
      post :upview
    end
  end
  resources :microposts do
    resources :comments
  end
  resources :schools do
    collection do
        get :mostrecent
        get :mostdiscussed
        get :highestrated
        get :viewcount
    end
  end

  match "/users/:id/personalstream" => "users#personalstream"
  match "/schools/:id/mostrecent" => "schools#mostrecent"
  match "/schools/:id/mostdiscussed" => "schools#mostdiscussed"
  match "/schools/:id/viewcount" => "schools#viewcount"
  match "/schools/:id/highestrated" => "schools#highestrated"
  match "/schools/:id", :to => 'schools#show', :as => "school"
  match "/microposts/:id/comments" => "microposts#comments"
  match "/microposts/:id/upview" => "microposts#upview"
  match "/microposts/:id/vote_up" => "microposts#vote_up"
  match "/microposts/:id/unvote" => "microposts#unvote"
  get "log_out" => "sessions#destroy", :as => "log_out"
  get "sign_in" => "sessions#new", :as => "sign_in"
  get "sign_up" => "users#new", :as => "sign_up"
  get "home" => "users#home", :as => "home"

  root to: "schools#index"

end

A: add a new action to the microposts controller:
app/controllers/microposts_controller.rb
def comments
  @micropost = Micropost.find(params[:id])
  @comments = @micropost.comments

  # we dont need all the html head stuff
  render :layout => false
end

write a view (app/views/microposts/comments.html.erb) where you display all the @comments as you want
and add a new member to you microposts resource get :comments
now you can try in the browser /microposts/(add a micropost id here)/comments
this should deliver you all the comments for the user and format them as you wish.
the last part is the simplest: when the user clicks on the div, make a request to this site via ajax and attach the answer to the div where you want to display the comments. the code could look like this:
$("#CommentPagin").click( function(){
  $("#CommentPagin").load( "<%= micropost_comments_path( @user ) %>" );
});

hope you got an idea. report back if its not working


text:
Q: Skip Item Android Grid View in condition I'm trying to build an android application,I have a 3 columns gridview that show a list of points,I want to jump to next line in a condition even when some of the  columns are empty
Example I want to do something like this:
 ARX ARH
 BRH BRX BRY
 CRH
 DRH DRY

A:
Try this One
  your List item Row XML would be like this
  Abc.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@android:color/darker_gray">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_margin="5dp">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name1"
            android:textSize="18sp"
            android:background="@android:color/white"
            android:layout_margin="5dp"/>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name2"
            android:textSize="18sp"
            android:layout_margin="5dp"
            android:background="@android:color/white"/>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name3"
            android:textSize="18sp"
            android:layout_margin="5dp"
            android:background="@android:color/white"/>

    </LinearLayout>

</LinearLayout>

And CustomAdapter for List Would be like this

public class Custom_Adapter_Products extends BaseAdapter {
    Context context;
    String[] list = {"AAA","AAA","AAA","AAA","AAA","","AAA", "AAA","AAA"};

    public Custom_Adapter_Products(Context context){
        this.context = context;
    }

    @Override
    public int getCount() {
        return (list.length/3);
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int pos, View convertView, ViewGroup parent) {
        try{
            int position = (pos*3);
            ViewHolder holder;
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null)
            {
                convertView = vi.inflate(R.layout.abc, null);
                holder = createViewHolder(convertView);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            if(!list[position].equals("")){
                holder.textView1.setText(list[position]);
                holder.textView1.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView1.setVisibility(View.GONE);
            }

            if(!list[position+1].equals("")){
                holder.textView2.setText(list[position]);
                holder.textView2.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView2.setVisibility(View.GONE);
            }

            if(!list[position+2].equals("")){
                holder.textView3.setText(list[position]);
                holder.textView3.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView3.setVisibility(View.GONE);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder
    {
        public TextView textView1;
        public TextView textView2;
        public TextView textView3;
    }

    private ViewHolder createViewHolder(View v) {
        ViewHolder holder = new ViewHolder();
        try{
            holder.textView1 = (TextView) v.findViewById(R.id.textView1);
            holder.textView2 = (TextView) v.findViewById(R.id.textView2);
            holder.textView3 = (TextView) v.findViewById(R.id.textView3);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return holder;
    }
}


text:
Q: How do I add and commit file in a git repository while in different directory While working on a different directory, How do I run git commands like add and commit on a local git repository that is present in a different directory...?
I found the below command for getting the status..
git -C /Users/raj/Documents/Spring/spring-project-5/ status
But replacing 'status' with add or commit doesn't seem to be working..

A: If you are in a bash session, you also have the simpler option of:
pushd /Users/rajkumarpurushothaman/Documents/Spring/spring-project-5
git add .
git commit -m "a message"
git push
popd

(using git add . here, not git add *)


text:
Q: C++: Simple CUDA volume reconstruction code crashing I am currently working on a more comprehensive project involving CUDA. During the recent days I have been encountering errors that I have been desperately trying to bugfix. However, I couldn't figure it out, so I made up a minimal example now that shows the same behaviour. I have to say I am kind of new to CUDA. I am using Visual Studio 2015 and the CUDA  Toolkit 7.5.
The program involves creating a 3D-volume on the GPU memory and then calculating values and writing them to the volume. I have tried to make the code as simple as possible:
First ist the main.cpp file:
#include "cuda_test.h"

int main() {

    size_t const xDimension = 500;
    size_t const yDimension = 500;
    size_t const zDimension = 1000;

    //allocate volume part memory on gpu
    cudaPitchedPtr volume = ct::cuda::create3dVolumeOnGPU(xDimension, yDimension, zDimension);

    //start reconstruction
    ct::cuda::startReconstruction(volume,
                                  xDimension,
                                  yDimension,
                                  zDimension);

return 0;

}
Then the cuda_test.h that is the header file for the actual .cu file:
#ifndef CT_CUDA
#define CT_CUDA

#include <cstdlib>
#include <stdio.h>
#include <cmath>

//CUDA
#include <cuda_runtime.h>

namespace ct {

    namespace cuda {

        cudaPitchedPtr create3dVolumeOnGPU(size_t xSize, size_t ySize, size_t zSize);
        void startReconstruction(cudaPitchedPtr volume,
                                 size_t xSize,
                                 size_t ySize,
                                 size_t zSize);

    }

}

#endif

And then the cuda_test.cu file that contains the actual function implementations:
#include "cuda_test.h"

namespace ct {

    namespace cuda {

        cudaPitchedPtr create3dVolumeOnGPU(size_t xSize, size_t ySize, size_t zSize) {
            cudaExtent extent = make_cudaExtent(xSize * sizeof(float), ySize, zSize);
            cudaPitchedPtr ptr;
            cudaMalloc3D(&ptr, extent);
            printf("malloc3D: %s\n", cudaGetErrorString(cudaGetLastError()));
            cudaMemset3D(ptr, 0, extent);
            printf("memset: %s\n", cudaGetErrorString(cudaGetLastError()));
            return ptr;
        }

        __device__ void addToVolumeElement(cudaPitchedPtr volumePtr, size_t ySize, size_t xCoord, size_t yCoord, size_t zCoord, float value) {
            char* devicePtr = (char*)(volumePtr.ptr);
            //z * xSize * ySize + y * xSize + x
            size_t pitch = volumePtr.pitch;
            size_t slicePitch = pitch * ySize;
            char* slice = devicePtr + zCoord*slicePitch;
            float* row = (float*)(slice + yCoord * pitch);
            row[xCoord] += value;
        }

        __global__ void reconstructionKernel(cudaPitchedPtr volumePtr, size_t xSize, size_t ySize, size_t zSize) {

            size_t xIndex = blockIdx.x;
            size_t yIndex = blockIdx.y;
            size_t zIndex = blockIdx.z;

            if (xIndex == 0 && yIndex == 0 && zIndex == 0) {
                printf("kernel start\n");
            }

            //just make sure we're inside the volume bounds
            if (xIndex < xSize && yIndex < ySize && zIndex < zSize) {

                //float value = z;
                float value = sqrt(sqrt(sqrt(5.3))) * sqrt(sqrt(sqrt(1.2))) * sqrt(sqrt(sqrt(10.8))) + 501 * 0.125 * 0.786 / 5.3;

                addToVolumeElement(volumePtr, ySize, xIndex, yIndex, zIndex, value);

            }

            if (xIndex == 0 && yIndex == 0 && zIndex == 0) {
                printf("kernel end\n");
            }

        }

        void startReconstruction(cudaPitchedPtr volumePtr, size_t xSize, size_t ySize, size_t zSize) {
            dim3 blocks(xSize, ySize, zSize);
            reconstructionKernel <<< blocks, 1 >>>(volumePtr,
                                                   xSize,
                                                   ySize,
                                                   zSize);
            printf("Kernel launch: %s\n", cudaGetErrorString(cudaGetLastError()));
            cudaDeviceSynchronize();
            printf("Device synchronise: %s\n", cudaGetErrorString(cudaGetLastError()));
        }

    }

}

The function create3dVolumeOnGPU allocates a 3-dimensional "volume" in the gpu memory and returns a pointer to it. This is a host function. The second host function is startReconstruction. The only thing it does is launching the actual kernel with as many blocks as there are voxels in the volume. The kernel function is reconstructionKernel. It just calculates an arbitrary value out of some constants and then calls addToVolumeElement (device function) to write the result in the corresponding voxel (adding it).
Now, the problem is that it crashes. If I launch with debugger (NSight), NSight interrupts giving the error message:
CUDA grid launch failed: CUcontext: 2358451327088 CUmodule: 2358541519888 Function: _ZN2ct4cuda20reconstructionKernelE14cudaPitchedPtryyy
The console outputs:
malloc3D: no error
memset: no error
kernel started
kernel end

If I launch in release mode the whole machine resets.
However, if I change the volume dimensions to be smaller it works, for example:
    size_t const xDimension = 100;
    size_t const yDimension = 100;
    size_t const zDimension = 100;

However, the amount of free GPU memory should not be the problem (card has 4GB VRAM).
It would be nice if someone could have a look at it and maybe give me a tip what could cause the problem.

A:
Now, the problem is that it crashes
It would be nice if someone could have a look at it and maybe give me a tip what could cause the problem.

I think it's likely you are running into a WDDM TDR issue.  On windows, any time a kernel running on a WDDM GPU takes more than about 2 seconds to execute, you may run into the WDDM TDR watchdog (assuming you haven't made any changes to the watchdog).
Furthermore, launching kernels like this:
reconstructionKernel <<< blocks, 1 >>>(...);

where the threads-per-block number is 1, means that only one thread in each warp (and in each block) is active.  But the GPU likes to have 32 active threads per warp.  So the net effect is inefficient utilization of the GPU resources; perhaps as much as 97% of the GPU horsepower sits idle when you run kernels this way.
So if your code is flexible enough to allow this:
reconstructionKernel <<< blocks, 1 >>>(...);

or equivalently this:
reconstructionKernel <<< blocks/256, 256 >>>(...);

(this is just a representative example; I realize you have a multidimensional grid, and the above probably isn't exactly relevant for your case)
then the second invocation method will almost certainly be more efficient, leading to a shorter execution time for the same work.
So I believe when you tested your code with multiple threads per block, you did something like the above, and it reduced the execution time below the TDR limit.
That's a perfectly fine solution, but if you end up adding more work to your kernel (more total threads, or more work per thread) then you may run into the limit again.  In that case, the linked article explains a possible work-around.
As an aside, kernel launch configurations like this:
kernel<<<1, ?>>>(...);

or this:
kernel<<<?, 1>>>(...);

are never recommended for high performance code on the GPU.


text:
Q: Pulling alt/title tags from a thumbnail image when swapping out featured image? I am using a pretty basic Javascript function to swap out featured images depending on which thumbnail the user clicks. The image swaps out fine, but the title/alt tags always remain the same as the default featured image which is shown on page load. I am wondering how I can pull the alt/title tags over from the thumbnail images when they are selected. Any help greatly appreciated!
UPDATE edited to reflect working code thanks to ROK!
HTML:

{% if product.images.size == 0 %}

{% else %}

  {% if product.images.size > 1 %}

    {% for image in product.images %}

    {% endfor %}

  {% endif %}

{% endif %}

Javscript:
// Load variant image into feature area
$('.product-photo-thumb a').click(function(e) { e.preventDefault();
    $elem = $(this);
    var newAttributes = {
        src: $elem.attr('href'),
        title: $elem.data('title'),
        alt: $elem.data('alt')
    }
    $('#product-photo-container img').attr(newAttributes);
});

A: Javascript for this would look something like this:
// Load variant image into feature area
$('.product-photo-thumb a').click(function(e) { e.preventDefault();
    $elem = $(this).find('img')[0];
    var newAttributes = {
        src: $elem.attr('src'),
        title: $elem.attr('title'),
        alt: $elem.attr('alt')
    }
    $('#product-photo-container img').attr(newAttributes);
});

Read all of the parameters directly from the image and reapply them to the feature img.


text:
Q: Best way to evaluate a matrix-based polynomial in C++ all. I'm trying to set up a program that evaluates a polynomial depending on the user input of X. Another part of the program I want is to then add these polynomials together. I'm using a 2D array to do this.  What do you think would be the best way to write the evaluation function. Been working at this for hours and I'm still not quite sure how to do it. Thanks in advance.
polynomial.h
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H

#include <iostream>
using namespace std;

#define MAX 100

class Polynomial {
      friend ostream &operator<< (ostream &, const Polynomial &);
      public :
             Polynomial ();
             void enterTerms();
             int evaluate(Polynomial p, int x);
             Polynomial operator +(const Polynomial & );
      private :
             int terms[MAX][2]; //either static size(MAX rows) or use "new" for dynamic allocation
             int n; //number of terms
};

#endif

polynomial.cpp
#include "polynomial.h"

using namespace std;

ostream &operator<< (ostream & out, const Polynomial & p){
        for ( int i = 0 ; i < p.n ; i++ ){
            if ( i == p.n - 1 )//last term does not have + appended
                  out << p.terms[i][0] <<"x^"<<p.terms[i][1]<<endl;
            else
                  out << p.terms[i][0]<<"x^"<<p.terms[i][1]<<" + ";
        }
        return out;
}
Polynomial :: Polynomial(){
         for ( int i = 0; i < MAX; i++ ){
             terms[i][0] = 0;
             terms[i][1] = 0;
         }
}
void Polynomial :: enterTerms(){//enterTerms() not in constructor so that no prompt for entering
//terms while doing + - etc., they also produce Poylnomial instance (i.e. invoke constructor)
      int num;
      cout<<"enter number of terms in polynomial\n";
      cin >> num;
      n = num >= 0 ? num : 1;
      cout << "enter coefficient followed by exponent for each term in polynomial\n";
      for ( int i = 0; i < n ; i++)
              cin >> terms[i][0] >> terms[i][1] ;
}
Polynomial Polynomial :: operator + ( const Polynomial & p ){
           Polynomial temp, sum;
           temp.n = n + p.n;
           int common = 0;

          // first write sum as concatenation of p1 and p2
           for ( int i = 0 ; i < n ; i++ ){
                   temp.terms[i][0] = terms[i][0];
                   temp.terms[i][1] = terms[i][1];
           }
           //notice j and k for traversing second half of sum, and whole p2 resp
           for ( int j = n, k = 0; j < n + p.n, k < p.n ; j++, k++ ){
                   temp.terms[j][0] = p.terms[k][0];
                   temp.terms[j][1] = p.terms[k][1];
           }
           for ( int l = 0; l < temp.n - 1 ; l++ ){ // 0 to 1 less than length
               for ( int m = l + 1 ; m < temp.n ; m++ ){ // 1 more than l to length,so that compared pairs are non redundant
                   if( temp.terms[l][1] == temp.terms[m][1] ){
                           common++;   //common terms reduce no. of terms in sum (see sum.n decl)
                           temp.terms[l][0] +=  temp.terms[m][0]; //coefficients added if exponents same
                           temp.terms[m][0] = 0;
                   }
               }
           }
           sum.n = temp.n - common;  //if you place it above, common taken as 0 and sum.n is same as temp.n (logical error)

           //just to debug, print temporary array
           cout << endl << temp;

           for ( int q = 0, r = 0; q < temp.n; q++ ){
                    if ( temp.terms[q][0] == 0 )
                       continue;
                    else{
                         sum.terms[r][0] = temp.terms[q][0];
                         sum.terms[r][1] = temp.terms[q][1];
                         r++;
                    }
           }

           cout << endl << sum;
           return sum;
       }

int Polynomial :: evaluate(Polynomial p, int x)
{
    Polynomial terms;
    return 0;
}

int main()
{

    Polynomial p1 , p2;
    p1.enterTerms();
    p2.enterTerms();
    cout << "Please enter the value of x:" << endl;
    cin >> x;
    //evaluate(p1);
    //evaluate(p2);
    p1 + p2;
    system("PAUSE");
    //cin.get();
    return 1;
}

A: Please consider a simpler data structure.  A common approach is to use a single array, where the index is the power of x.  Just use zeros where no such term exists.  Then x^3 + 2*x + 1 is written {1, 2, 0, 1}, since there's no x^2.  Also note the reverse order, since p[0] represents x^0.  This drastically simplifies operations like addition.
As far as evaluation, just think about the equation.  If your polynomial is x^2 + 3*x + 5, and you want to evaluate for x=7, what do you do?  Start with power 0, and accumulate each term into a single variable.

A: You can follow and complete my functions here:
float polyval_point(Eigen::VectorXf v,float x)
{
    float s = 0;
    for (int i=0;i<v.size();i++)
    {
    s += v[i] * pow(x,i);
    }
    return s;
}

Eigen::VectorXf polyval_vector(Eigen::VectorXf v,Eigen::VectorXf X)
{
    Eigen::VectorXf S(X.size());
    for (int i=0;i<X.size();i++)
    {
    S[i] = polyval_point(v,X[i]);
    }
    return S;
}


text:
Q: Resolving to Option[Nothing]? Given:
scala> def f[F[_], A, B](x: F[A], y: F[B]): F[B] = y
f: [F[_], A, B](x: F[A], y: F[B])F[B]

How does the output type of the below call evaluate to Option[Nothing]?
scala> :t f( Option(42), ???)
Option[Nothing]

A: https://www.scala-lang.org/files/archive/spec/2.12/03-types.html#conformance This part of the spec is especially useful here.
Take your function:
scala> def f[F[_], A, B >: Nothing <: Any](fa: F[A], fb: F[B]): F[B] = fb
f: [F[_], A, B](fa: F[A], fb: F[B])F[B]

The compiler sees this as (More or less):
scala> def fAnnotated[F[_], A >: Nothing <: Any, B >: Nothing <: Any](fa: F[A], fb: F[B]): F[B] = fb
fAnnotated: [F[_], A, B](fa: F[A], fb: F[B])F[B]

So, the compiler infers that your types have a lower bound of Nothing and an upper bound of Any. We can see this in action with your example.
scala> :t f(Option(42), ???)
Option[Nothing]

And with a contravariant type ctor Any is inferred:
scala> trait T[-A]
defined trait T

scala> :t f(new T[Int]{}, ???)
T[Any]

The scala compiler looks for the most restrictive version of a type where soundness holds good. As it cannot find B (there really is no such thing as B) it infers Nothing for the invariant and covariant cases and Any for the contravariant case.

A: See the definition of ???:
def ??? : Nothing = throw new NotImplementedError

So F is Option and B is Nothing, thus your return type is Option[Nothing].


text:
Q: How to change add media button in moodle tinymce editor? I've been learning Moodle CMS and I'm stuck in one problem. I'm using tinymce as a default editor. There's insert video button but popup window doesn't have full functionality as an original tinymce insert video popup window.

How can I change it? I want to choose HTML5 from Type and control the Dimensions of the video. But now it's not possible in Moodle Tinymce Editor.

A: After hours of searching google, I came to an answer on the moodle forum
Here's what I did to use original tinymce media insert:
1) Adding media plugin to the config file: lib/editor/tinymce/lib.php
'plugins' => 'safari,...,media',

2) From moodle admin settings of tinymce editor, add media button.


text:
Q: How to I convert coordinates keeping all the info from the dataframe I have a list of coordinates in Lambert78 coordinate system which I want to convert to WGS84. I want these converted coordinates added as 2 additional columns to my dataframe so I can keep labelnames.
This is the dataset:
label   Ycoord    Xcoord
AB_01   227426.9  199559.0
AB_02   227426.9  199559.0
...

What I would like is a dataframe like this:
label   Ycoord    Xcoord    Ycoord_wgs   Xcoord_wgs
AB_01   227426.9  199559.0  5.92          58.56
AB_02   227316.9  199859.0  5.74          57.68

Converting the coordinates is no problem with something like spTransform but then I loose the connection to the labelnames.
Does someone have a suggestion?

A: This returns a data.frame with the desired columns by creating a SpatialPoints object and then binding a transformation of the object's coordinates to the original data.frame.  However, the wgs84 coordinates are slightly off compared to what you posted, so please provide more information about the "Lambert 78" coordinate system to match the crs correctly.
library(sp)
coord_df <- data.frame(label=c('AB_01', 'AB_02'), Ycoord=c(227426.9, 227316.9), Xcoord=c(199559.0, 199859.0), stringsAsFactors = FALSE)
proj4_lambert <- '+proj=lcc +lat_1=51.16666723333334 +lat_2=49.83333389999999 +lat_0=90 +lon_0=4.367486666666666 +x_0=150000.013 +y_0=5400088.438 +ellps=intl +towgs84=-99.1,53.3,-112.5,0.419,-0.83,1.885,-1.0 +units=m +no_defs'
#see https://spatialreference.org/ref/sr-org/56/
coord_sp <- SpatialPoints(coords=coord_df[,c('Xcoord', 'Ycoord')],  proj4string = CRS(proj4_lambert))
coord_df_final <- cbind(coord_df, coordinates(spTransform(coord_sp, CRS('+init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0')))[,2:1])
colnames(coord_df_final)[4:5] <- c('Ycoord_wgs', 'Xcoord_wgs')
coord_df_final
#  label   Ycoord Xcoord Ycoord_wgs Xcoord_wgs
#1 AB_01 227426.9 199559   51.35447   5.080160
#2 AB_02 227316.9 199859   51.35346   5.084451

A: We can use the sf package and dplyr to keep the original columns, change coordinate systems, and then bring those back into the data.frame.
library(sf)
library(dplyr)

df <- readr::read_table("label   Ycoord    Xcoord
AB_01   227426.9  199559.0
AB_02   227426.9  199559.0")

df <- df %>%
  st_as_sf(crs = 31370, coords = c("x" = "Xcoord", "y" = "Ycoord"), remove = F) %>%
  st_transform(crs = 4326)

coords <- st_coordinates(df)

mutate(df,
       x_wgs1984 = coords[,1],
       y_wgs1984 = coords[,2])

#> Simple feature collection with 2 features and 5 fields
#> geometry type:  POINT
#> dimension:      XY
#> bbox:           xmin: 5.08016 ymin: 51.35447 xmax: 5.08016 ymax: 51.35447
#> epsg (SRID):    4326
#> proj4string:    +proj=longlat +datum=WGS84 +no_defs
#> # A tibble: 2 x 6
#>   label  Ycoord Xcoord           geometry x_wgs1984 y_wgs1984
#> * <chr>   <dbl>  <dbl>        <POINT [°]>     <dbl>     <dbl>
#> 1 AB_01 227427. 199559 (5.08016 51.35447)      5.08      51.4
#> 2 AB_02 227427. 199559 (5.08016 51.35447)      5.08      51.4


text:
Q: Strange output for a simple OpenMP program on Multi2sim v4.0.1 I'm trying to run a simple program using OpenMP
the program is as follows
#include <iostream>
#include <fstream>
#include <vector>
#include <omp.h>
#include <algorithm>
#include <math.h>
#include <map>
#include <string>
#include <ctime>
using namespace std;

#define NUM 10

void openMP()
{
    omp_set_num_threads(1);
    int sum =0;
    #pragma omp parallel for shared(sum)
    {
        for (int i=0;i<100;i++)
        {
            sum++;
        }
    }
    cout<<"sum = "<<sum<<endl;

}
int main()
{
    cout<<"Open MP \n";
    openMP();
return 0;
}

Now when I compile it using
g++ test.cpp -fopenmp -o test
and run it on ubuntu terminal
./test
the output is correct - I think - as follows
Open MP
sum = 100

But when I try to run it using Multi2sim using these 2 files I was given by my instructor
multicore-config:
[ General ]
Cores = 4
Threads = 1

multicore-mem-config:
[CacheGeometry geo-l1]
Sets = 256
Assoc = 2
BlockSize = 64
Latency = 2
Policy = LRU
Ports = 2

[CacheGeometry geo-l2]
Sets = 512
Assoc = 4
BlockSize = 64
Latency = 20
Policy = LRU
Ports = 4

[Module mod-l1-0]
Type = Cache
Geometry = geo-l1
LowNetwork = net-l1-l2
LowModules = mod-l2

[Module mod-l1-1]
Type = Cache
Geometry = geo-l1
LowNetwork = net-l1-l2
LowModules = mod-l2

[Module mod-l2]
Type = Cache
Geometry = geo-l2
HighNetwork = net-l1-l2
LowNetwork = net-l2-mm
LowModules = mod-mm

[Module mod-mm]
Type = MainMemory
BlockSize = 256
Latency = 200
HighNetwork = net-l2-mm

[Network net-l2-mm]
DefaultInputBufferSize = 1024
DefaultOutputBufferSize = 1024
DefaultBandwidth = 256

[Network net-l1-l2]
DefaultInputBufferSize = 1024
DefaultOutputBufferSize = 1024
DefaultBandwidth = 256

[Entry core-0]
Arch = x86
Core = 0
Thread = 0
DataModule = mod-l1-0
InstModule = mod-l1-0

[Entry core-1]
Arch = x86
Core = 1
Thread = 0
DataModule = mod-l1-0
InstModule = mod-l1-0

[Entry core-2]
Arch = x86
Core = 2
Thread = 0
DataModule = mod-l1-0
InstModule = mod-l1-0

[Entry core-3]
Arch = x86
Core = 3
Thread = 0
DataModule = mod-l1-0
InstModule = mod-l1-0

And then using this instruction in Ubuntu terminal
m2s --x86-config multicore-config.txt --mem-config multicore-mem-config.txt --x86-sim detailed test

I get the output
; Multi2Sim 4.0.1 - A Simulation Framework for CPU-GPU Heterogeneous Computing
; Please use command 'm2s --help' for a list of command-line options.
; Last compilation: May  8 2013 10:01:31

Open MP
sum = 83

;
; Simulation Statistics Summary
;

[ General ]
Time = 53.17
SimEnd = ContextsFinished
Cycles = 3691870

[ x86 ]
SimType = Detailed
Time = 53.15
Contexts = 4
Memory = 37056512
EmulatedInstructions = 3292450
EmulatedInstructionsPerSecond = 61943
Cycles = 3691558
CyclesPerSecond = 69452
FastForwardInstructions = 0
CommittedInstructions = 2081157
CommittedInstructionsPerCycle = 0.5638
CommittedMicroInstructions = 3113721
CommittedMicroInstructionsPerCycle = 0.8435
BranchPredictionAccuracy = 0.9375

why is the output in Multi2sim 83 while the output in a normal run is 100
Also why does it take so much time to run on Multi2Sim ?
Any help would be appreciated.

A: I don't really know m2s, but it could be the case that the culprit is:
#pragma omp parallel for shared(sum)
    {
        for (int i=0;i<100;i++)
        {
            sum++; // Concurrent access to a shared variable!!!
        }
    }

In your first test the fact that you explicitly set the number of threads to 1:
omp_set_num_threads(1);

saves you from race conditions. I would suggest trying with:
#pragma omp parallel for shared(sum) reduction(+:sum)
for (int i=0;i<100;i++) {
            sum++;
}

to see if you can obtain the desired behavior.


text:
Q: What is the use of CertUI framework in iOS programming? I want to delete CertUI framework from Xcode to fix an "bundle not loaded" issue. I want to know the use of CertUI framework in iOS programming so that i could know if it is needed to me! Thanks in advance!

A: It is either AppleOpenSource or a 3rd party framework on GitHub. So someone added it, one can only wonder why?
The GitHub page does not have a ReadMe so it is hard to say what it does. neither does the Apple source.