text:
Q: Dygraph - is it possible to position tooltip so that it is clear of the graph I have a dygraph where if you mouse over it, it shows the values of the series at the top of the chart. Sometimes, the line series overlaps with the "tooltip". In FLOT, I used to specify an offset which was used by FLOT to restrict the line to lower threshold so that tooltip area was clear and did not overlap with the actual graph.
Is there a similar way to achieve this using Dygraphs?

A: You could try legend: "follow", or perhaps use a <div> outside the chart as in this example. I don't know of a simple way to achieve the exact effect you're asking for, though.

A: I figured out a good way to do this:
Dygraph supports "valueRange" option for y axis. I found the max value in my series and then set the valueRange to [null, maxYValue*1.2]. This produces a 20% margin from the top allowing tooltip free and clear room to display data without intersecting with the chart lines.


text:
Q: Watch changes in local Storage in Angular 2 I have a menu to appear based on being logged.
I am using json web tokens in local storage for my authentication, I want to watch for a change to localStorage and then re-update my view on new information.
How can I watch for changes to localstorage?
I set my localStorage with this
localStorage.setItem('jwt', my_token);
The things I would like to do is check if I have a token, if I don't nothing happens, but when there is a change fire an event. From what I know I have to create a service, inject it where I want and susbscribe me to the observable.
What I have is the service, I don't know how to watch for the changes.
my service is:
import { Injectable } from 'angular2/core';

@Injectable()
export class LocalStorageService {
    private storage: any;

    constructor() {
        this.storage = localStorage;
    }

    public retrieve(key: string): any {
        var item = this.storage.getItem(key);

        if (item && item !== 'undefined') {
            return JSON.parse(this.storage.getItem(key));
        }

        return;
    }

    public store(key: string, value: any) {
        this.storage.setItem(key, JSON.stringify(value));
    }

}

A: I've created a service that can do this for you if you still haven't found a suitable answer. The h5webstorage already handle watching both localStorage and sessionStorage events and synchronizes the changes. All you have to do is use it like a normal object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Overriding Spring Data Rest Request Mappings We currently have a level 2 RESTful web service.  We are updating the service to incorporate hypermedia support.  We are using Spring Data Rest on the back-end to handle the setting of the HATEOAS properties.  The problem we're having is that we still need to support our legacy API consumers until the migration can be completed, meaning we still need to support responses without HAL properties like "_links" and "_embedded".
For reasons that aren't really worth explaining, we cannot address this problem with URL versioning.  We need instead to be able to map requests with an Accept header of "application/json" to our old controllers, and let SDR handle any requests with "application/hal+json".  In essence, we'd like to use SDR as a fallback to handle API requests that are specifically requesting HAL-formatted responses.
I came across this excerpt in the SDR documentation:

We register a custom HandlerMapping instance that responds only to the
  RepositoryRestController and only if a path is meant to be handled by
  Spring Data REST. In order to keep paths that are meant to be handled
  by your application separate from those handled by Spring Data REST,
  this custom HandlerMapping inspects the URL path and checks to see if
  a Repository has been exported under that name. If it has, it allows
  the request to be handled by Spring Data REST. If there is no
  Repository exported under that name, it returns null, which just means
  "let other HandlerMapping instances try to service this request".
The Spring Data REST HandlerMapping is configured with
  order=(Ordered.LOWEST_PRECEDENCE - 100) which means it will usually be
  first in line when it comes time to map a URL path and your existing
  application will never get a chance to service a request that is meant
  for a Repository. For example, if you have a Repository exported under
  the name "person", then all requests to your application that start
  with "/person" will be handled by Spring Data REST and your
  application will never see that request. If your Repository is
  exported under a different name, however (like "people"), then
  requests to "/people" will go to Spring Data REST and requests to
  "/person" will be handled by your application.

This seems to imply that what we're trying to accomplish is possible, assuming the HandlerMapping order can be configured differently.  I haven't been able to make that work so far though:

*

*Setting SDR's HandlerMapping to Ordered.HIGHEST_PRECEDENCE seems to have no effect.

*Setting SDR's HandlerMapping order to Ordered.LOWEST_PRECEDENCE seemed to disable ordering altogether, and my custom controllers did field the requests, but SDR was no longer responding to any requests.  application/hal+json just resulted in a 406 status.

Is there any way to configure the HandlerMappings correctly such that my custom controllers take priority and SDR fields any requests not specifically mapped to my controllers?


text:
Q: How to make bootstrap 3 dropdown menu working for no JS user I'm looking how to convert dropdown menu on bootstrap for no JS user.
I already see its possible in full CSS but I'm not very friendly with CSS ...
Any one can help me ?

A: There is a possibility.
Download this Bootstrap
Implement this code jsFiddle here
HTML

        Project name

Home

Link

Link

Link

              Dropdown

                    2-level Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Another action

Something else here

Nav header

Separated link

One more separated link

          <form action="" class="navbar-search pull-left">
            <input type="text" placeholder="Search" class="search-query span2">
          </form>

Link

              Menu

Regular link

  Dropdown

        2-level Menu

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Another action

Something else here

Separated link

  Menu

  Menu

CSS
body {
    padding-top: 60px;
    padding-bottom: 40px;
}

.sidebar-nav {
    padding: 9px 0;
}

.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
}

.dropdown:hover .dropdown-menu {
    display: block;
}

.nav-tabs .dropdown-menu, .nav-pills .dropdown-menu, .navbar .dropdown-menu {
    margin-top: 0;
}

.navbar .sub-menu:before {
    border-bottom: 7px solid transparent;
    border-left: none;
    border-right: 7px solid rgba(0, 0, 0, 0.2);
    border-top: 7px solid transparent;
    left: -7px;
    top: 10px;
}
.navbar .sub-menu:after {
    border-top: 6px solid transparent;
    border-left: none;
    border-right: 6px solid #fff;
    border-bottom: 6px solid transparent;
    left: 10px;
    top: 11px;
    left: -6px;
 }

A: Just in case of someone wants a short answer.
HTML

  Dropdown

Another action

Something else here

Separated link

CSS
.dropdown:hover .dropdown-menu {
    display: block;
}

You can try it here

A: In your css put:
.dropdown-menu {display:block;}

.open > .dropdown-menu {display:block !important;}

And your javascript:
$(".dropdown-menu").hide();


text:
Q: Function Overloading in Derived Class I want to know the below code is correct or not
class A
{
public :
    int show (int x, int y);
};

class B : public A
{
public :
    float show (int a, int b); // can i overload this function ?
};

the show function is present in both base and derived class with different written types.
I know function overloading concept (can not overload with different return types).
Is this possible to do so?

A: The code will be compiled successfully. The method A::show will not be overloaded but hidden.
You can call this method with the scope operator.

A: Check this link or this link
Class A
{
Public :
virtual int show (int x, inty) = 0;
};

class B:Public A
{
Public :
float show (int x, int y);
};

A: When i declare base obj and point it to derived class :
A aObj;
B bObj;
aObju = &bObj;
bObj.Show(); // Which function will be called base class or derived class?

A: If you create a derived class object like
1)
B b;
b.show();

OR
2)
A* b = new B();
b->show();

Will always look into derived class, and call B::show().
This is for your particular example, where no virtual functions are present, if virtual functions are present in the base class, the second case can give different results in other cases, but in this particular example even base class virtual functions will make no difference.


text:
Q: Error while deploying NextJS on AWS for serverless framework When I tried to deploy my NextJS app to AWS with serverless framework.
In my next JS app directory, I ran the command npx serverless
and got the following error -
    $ npx serverless

  error:
  Error: Command failed with exit code 1: node_modules/.bin/next build
warn  - Invalid next.config.js options detected:
  - The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).

See more info here: https://nextjs.org/docs/messages/invalid-next-config
warn  - The `target` config is deprecated and will be removed in a future version.
See more info here https://nextjs.org/docs/messages/deprecated-target-config
error - ESLint must be installed in order to run during builds: yarn add --dev eslint
Failed to compile.

./pages/_app.tsx:3:29
Type error: Cannot find module '@mui/material' or its corresponding type declarations.

  1 | import "../styles/globals.css";
  2 |
> 3 | import { CssBaseline } from "@mui/material";
    |                             ^
  4 | import { StyledEngineProvider, ThemeProvider } from "@mui/material/styles";
  5 | import type { AppProps } from "next/app";
  6 | import { appWithTranslation } from "next-i18next";

> Build error occurred
Error: Call retries were exceeded
    at ChildProcessWorker.initialize (C:\Users\bruno.cruz\Documents\INGRESSE-COM\repo\finance-web\node_modules\next\dist\compiled\jest-worker\index.js:1:11661)
    at ChildProcessWorker._onExit (C:\Users\bruno.cruz\Documents\INGRESSE-COM\repo\finance-web\node_modules\next\dist\compiled\jest-worker\index.js:1:12599)
    at ChildProcess.emit (events.js:315:20)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12) {
  type: 'WorkerError'
}
info  - Loaded env from C:\Users\bruno.cruz\Documents\INGRESSE-COM\repo\finance-web\.env
info  - SWC minify release candidate enabled. https://nextjs.link/swcmin
info  - Linting and checking validity of types...
    at makeError (C:\Users\bruno.cruz\.serverless\components\registry\npm\@sls-next\serverless-component@1.18.0\node_modules\@sls-next\serverless-component\node_modules\execa\lib\error.js:59:11)
    at handlePromise (C:\Users\bruno.cruz\.serverless\components\registry\npm\@sls-next\serverless-component@1.18.0\node_modules\@sls-next\serverless-component\node_modules\execa\index.js:114:26)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  shortMessage: 'Command failed with exit code 1: node_modules/.bin/next build',
  command: 'node_modules/.bin/next build',
  exitCode: 1,
  signal: undefined,
  signalDescription: undefined,
  stdout: 'info  - Loaded env from C:\\Users\\bruno.cruz\\Documents\\INGRESSE-COM\\repo\\finance-web\\.env\n' +
    'info  - SWC minify release candidate enabled. https://nextjs.link/swcmin\n' +
    'info  - Linting and checking validity of types...',
  stderr: 'warn  - Invalid next.config.js options detected: \n' +
    '  - The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).\n' +
    '\n' +
    'See more info here: https://nextjs.org/docs/messages/invalid-next-config\n' +
    'warn  - The `target` config is deprecated and will be removed in a future version.\n' +
    'See more info here https://nextjs.org/docs/messages/deprecated-target-config\n' +
    'error - ESLint must be installed in order to run during builds: yarn add --dev eslint\n' +
    'Failed to compile.\n' +
    '\n' +
    './pages/_app.tsx:3:29\n' +
    "Type error: Cannot find module '@mui/material' or its corresponding type declarations.\n" +
    '\n' +
    '\x1B[0m \x1B[90m 1 | \x1B[39m\x1B[36mimport\x1B[39m \x1B[32m"../styles/globals.css"\x1B[39m\x1B[33m;\x1B[39m\x1B[0m\n' +
    '\x1B[0m \x1B[90m 2 | \x1B[39m\x1B[0m\n' +
    '\x1B[0m\x1B[31m\x1B[1m>\x1B[22m\x1B[39m\x1B[90m 3 | \x1B[39m\x1B[36mimport\x1B[39m { \x1B[33mCssBaseline\x1B[39m } \x1B[36mfrom\x1B[39m \x1B[32m"@mui/material"\x1B[39m\x1B[33m;\x1B[39m\x1B[0m\n' +
    '\x1B[0m \x1B[90m   | \x1B[39m                            \x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[0m\n' +
    '\x1B[0m \x1B[90m 4 | \x1B[39m\x1B[36mimport\x1B[39m { \x1B[33mStyledEngineProvider\x1B[39m\x1B[33m,\x1B[39m \x1B[33mThemeProvider\x1B[39m } \x1B[36mfrom\x1B[39m \x1B[32m"@mui/material/styles"\x1B[39m\x1B[33m;\x1B[39m\x1B[0m\n' +
    '\x1B[0m \x1B[90m 5 | \x1B[39m\x1B[36mimport\x1B[39m type { \x1B[33mAppProps\x1B[39m } \x1B[36mfrom\x1B[39m \x1B[32m"next/app"\x1B[39m\x1B[33m;\x1B[39m\x1B[0m\n' +
    '\x1B[0m \x1B[90m 6 | \x1B[39m\x1B[36mimport\x1B[39m { appWithTranslation } \x1B[36mfrom\x1B[39m \x1B[32m"next-i18next"\x1B[39m\x1B[33m;\x1B[39m\x1B[0m\n' +
    '\n' +
    '> Build error occurred\n' +
    'Error: Call retries were exceeded\n' +
    '    at ChildProcessWorker.initialize (C:\\Users\\bruno.cruz\\Documents\\INGRESSE-COM\\repo\\finance-web\\node_modules\\next\\dist\\compiled\\jest-worker\\index.js:1:11661)\n' +
    '    at ChildProcessWorker._onExit (C:\\Users\\bruno.cruz\\Documents\\INGRESSE-COM\\repo\\finance-web\\node_modules\\next\\dist\\compiled\\jest-worker\\index.js:1:12599)\n' +
    '    at ChildProcess.emit (events.js:315:20)\n' +
    '    at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12) {\n' +
    "  type: 'WorkerError'\n" +
    '}',
  failed: true,
  timedOut: false,
  isCanceled: false,
  killed: false
}

  11s » financeWebFront » Error: Command failed with exit code 1: node_modules/.bin/next build
warn  - Invalid next.config.js options detected:
  - The root value has an unexpected property, target, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, future, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, staticPageGenerationTimeout, swcMinify, trailingSlash, typescript, useFileSystemPublicRoutes, webpack).

See more info here: https://nextjs.org/docs/messages/invalid-next-config
warn  - The `target` config is deprecated and will be removed in a future version.
See more info here https://nextjs.org/docs/messages/deprecated-target-config
error - ESLint must be installed in order to run during builds: yarn add --dev eslint
Failed to compile.

./pages/_app.tsx:3:29
Type error: Cannot find module '@mui/material' or its corresponding type declarations.

  1 | import "../styles/globals.css";
  2 |
> 3 | import { CssBaseline } from "@mui/material";
    |                             ^
  4 | import { StyledEngineProvider, ThemeProvider } from "@mui/material/styles";
  5 | import type { AppProps } from "next/app";
  6 | import { appWithTranslation } from "next-i18next";

> Build error occurred
Error: Call retries were exceeded
    at ChildProcessWorker.initialize (C:\Users\bruno.cruz\Documents\INGRESSE-COM\repo\finance-web\node_modules\next\dist\compiled\jest-worker\index.js:1:11661)
    at ChildProcessWorker._onExit (C:\Users\bruno.cruz\Documents\INGRESSE-COM\repo\finance-web\node_modules\next\dist\compiled\jest-worker\index.js:1:12599)
    at ChildProcess.emit (events.js:315:20)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12) {
  type: 'WorkerError'
}
info  - Loaded env from C:\Users\bruno.cruz\Documents\INGRESSE-COM\repo\finance-web\.env
info  - SWC minify release candidate enabled. https://nextjs.link/swcmin
info  - Linting and checking validity of types...

I'm using aws configure to set my AWS credentials.
My serverless.yml file is as follow,
myNextApplication:
  component: "@sls-next/serverless-component@1.18.0"

How should I deploy my app to AWS cloud with a serverless framework?
Thanks.

A: You need to install the missing dependency npm i @mui/material or yarn add @mui/material. That should fix it. Also, check your next.config.js file. It seems you are adding some things there which do not belong.
More so, to deploy to AWS, just use AWS Amplify. Read the docs to see how to set up with Next.js. It's very simple. Just deploy your code to github, connect to your repo via Amplify and then allow it to build your project for you.

A: Basically serverless nextjs is dead and the newest version are not supported
If AWS lambda is your unique option then try reverting the nextjs version to 11.x


text:
Q: clang static analyzer: Path diagnostic report is not generated This is a Minimal, Complete, and Verifiable example:
#include <QTimer>
#include <QApplication>
#include <QtDebug>

int main(int argc, char *argv[])
{
        QApplication app(argc, argv);
        QObject boo;
        QTimer::singleShot(0, &boo, []() {
                qDebug() << "hi";
        });
}

This is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)

find_package(Qt5Widgets REQUIRED)
include_directories(${Qt5Widgets_INCLUDE_DIRS})

add_executable(boo main.cpp)
qt5_use_modules(boo Widgets)

If I run clang-analyzer against it:
$ mkdir build && cd build && scan-build cmake .. && scan-build cmake --build .
...
warning: Path diagnostic report is not generated. Current output format does not support diagnostics that cross file boundaries. Refer to --analyzer-output for valid output formats
In file included from /tmp/boo/main.cpp:1:
In file included from /usr/include/qt/QtCore/QTimer:1:
/usr/include/qt/QtCore/qtimer.h:154:5: warning: Potential memory leak
    }
    ^

What I can not understand is this:
warning: Path diagnostic report is not generated. Current output format does not support diagnostics that cross file boundaries. Refer to --analyzer-output for valid output formats

But scan-build have no --analyzer-output, how can I include qtimer.h problem
into report?


text:
Q: How to use CSS clases with Tailwind CSS? I am building a site with Next.js and Tailwind and wanted to know if there is any way you can use Tailwind CSS classes along with Next.js classes. For example:

or perhaps something like
<img src={user.picture} className=`rounded{styles.pfp}`>

Is there any way to do that? Do let me know if there is.

A: Yes, the way to do it would be like this:
<img src={user.picture} className={`rounded ${styles.pfp}`}>

with rounded being the Tailwind class and styles.pfp being your class.


text:
Q: Pass object as query string parameter I'd like to pass a search query string to a state.
The URL should look like this:
/goods?filters[paramA]=1&filters[paramB]=2

My state setup is the following:
.state('goods', {
            url:        '/goods?filters',
            …
        })

My link template looks like this:
Menu item label

However, ui-router does not encode it properly and I get:
/goods?filters=[object Object]

How do I do it properly?

A: In order to accomplish what you are wanting you need to be using $stateParams rather then the query string you are trying to use. (although it is possible to use query strings, it is easier to use the $stateParams)
First you need to assign/registered the params with the state:
$stateProvider
.state('someState', {
    url: "/someLinkPath/:Param1",
    templateUrl: 'stateHTML.html',
    controller: function ($stateParams) {
        console.log($stateParams);
    }
});

Then you can construct a $stateParams object and pass it in the link to desired state.
If you do need to use the query string, then you need to flatten the object being added to the string
You could either use $.param (jQuery):
var yourParams = $.param({ param1: Value1, param2: Value2 });

or write you own vanilla JS function like this :
function toQueryString(obj) {
    var parts = [];
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
        }
    }
    return parts.join("&");
}

Edit: After thinking about your issue further I believe that the issue is that you have an object wrapper around your params. When you use this:
Menu item label

I think that by doing this the ui-sref does not know how to handle an object(filter) with a sub object. what you need to be doing is passing in a single object I think if you can change your code to only pass in the params as an object your code will work.
Menu item label


text:
Q: Stop perl overloading or print memory "address" of reference I have a class I created that overloads the "" operator to print out a nice stringified form of the object that is user-readable.
But now, I'd like to actually get the memory address such as:
Some_class=HASH(0xb0aff98)

which is what I would have normally done by using print "$some_object" if I had not already overridden the "" operator.
Is there someway to bypass the overridden method or, failing that, just get the memory address of this object?

A: Use overload::StrVal($o).
use overload '""' => sub { "Hello, World!" };
my $o = bless({});
print($o, "\n");                     # Hello, World!
print(overload::StrVal($o), "\n");   # main=HASH(0x62d038)

A: Two options:

*

*Use overload::StrVal

Public Functions
Package overload.pm provides the following public functions:

*

*overload::StrVal(arg)
Gives the string value of arg as in the absence of stringify overloading. If you are using this to get the address of a reference (useful for checking if two references point to the same thing) then you may be better off using Scalar::Util::refaddr() , which is faster.

*Use Scalar::Util::refaddr()

$addr = refaddr( $ref )
If $ref is reference the internal memory address of the referenced value is returned as a plain integer. Otherwise undef is returned.
   1.    $addr = refaddr "string";           # undef
   2.    $addr = refaddr \$var;              # eg 12345678
   3.    $addr = refaddr [];                 # eg 23456784
   4.
   5.    $obj  = bless {}, "Foo";
   6.    $addr = refaddr $obj;               # eg 88123488


text:
Q: How do you iterate over two dictionaries and grab the values at the same path? I have two dictionaries, that are of similar structure...meaning they(should) have the same key structure, even within nested keys. Also, these dicts could have almost any type of nested structure...list, dict, etc... I want to be able to traverse these dictionaries, and grab the two values and return them from a function.
Simple Example:
dict_a = {'a':1, 'b':2, 'c':{'d':3}}
dict_b = {'a':2, 'b':4, 'c':{'d':6}}
#Note the structure is the same for these dicts
#I want to be able to do something like:
>>get_values( dict_a, dict_b)
[(1,2),(2,4),(3,6)]

I came up with a solution to it myself by traversing one dictionary, and appending each key(or index if it encounters a list) into a list...as a sort of key-path:
key_map = []#A list of all key-paths for a dictionary
generate_key_paths(dict_a, [], key_map)
def generate_key_paths(value, key_list,key_map ):

    new_list = [item for item in key_list]
    if isinstance( value, dict):
        #Handle list
        for key, val in value.iteritems():
            new_list.append( key)
            self._generate_key_paths( val, new_list, key_map )
            new_list = [item for item in key_list]

    elif isinstance( value, list ):
        #Handle list
        for idx,item in enumerate(value):
            new_list.append( idx )
            self._generate_key_paths( item, new_list, key_map )
            new_list = [item for item in key_list]
    else:
        #Handle data--reached farthest point you can go
        #So just append (key-path, value) to key_map
        key_map.append((new_list, value ) )

And then once you have a list of key-path,value tuples...take the path, and try to reach it
on the second dictionary to get its value...
val_list = []
for item in key_map:
    value = get_value( item[0] )
    if value is not None:
        val_list.append( (item[1], value ) )
def get_value( key_list ):
    value = dict_b
    for item in key_list:
        try:
            value = value[item]
        except:
            value = None
            break
    return value

This works quite well for all structures a dictionary could have, but it seems like a lot of work. Is there a more pythonic way of achieving this? Is there a faster, more efficient way?
EDIT: I'm looking for a value that isn't a list or a dict, so when these values are reached, it should iterate inside them, until it finds a value. It is guaranteed that if it's a list,  it will be a list of dicts, so there should always be some sort of key:value relationship to follow.
For example a possible dict could look like this:
dict_a = {'a':1, 'b':2, 'c':[{'d':5},{'e':6}]}
dict_b = {'a':2, 'b':4, 'c':[{'d':10},{'e':12}]}
Answer: [(1,2), (2,4), (5,10), (6,12)]

A: dict_a = {'a':1, 'b':2, 'c':{'d':3,'e':{'f':4}}}
dict_b = {'a':2, 'b':4, 'c':{'d':6,'e':{'f':7}}}

Here is 1st version, that just unpacks and combines
def gen(dict1, dict2):
    for key in dict1:
        if isinstance(dict1[key],dict):
            for item in gen(dict1[key],dict2[key]):
                yield item
        else:
            yield dict1[key], dict2[key]

# prints [(1, 2), (4, 7), (3, 6), (2, 4)]
print list(gen(dict_a, dict_b))

Here is 2nd version, that also sorts source (but i think, that better to sort the resulted list)
def gen(dict1, dict2):
    for key in sorted(dict1):
        if isinstance(dict1[key],dict):
            for item in gen(dict1[key],dict2[key]):
                yield item
        else:
            yield dict1[key], dict2[key]

print list(gen(dict_a, dict_b))

# prints [(1, 2), (2, 4), (3, 6), (4, 7)]
print list(gen(dict_a,dict_b))

This src is based on flatten generator, that may be found in many different tuts

A: You are looking for an equivalent of flatten(zipTree(...)) (functions which don't exist but whose names should get my point across).
from collections import Mapping

def treezipFlat(t1,t2):
    if isinstance(t1,Mapping) and isinstance(t2,Mapping):
        assert set(t1)==set(t2)
        for k,v1 in t1.items():
            v2 = t2[k]
            for tuple in treezipFlat(v1,v2):
                yield tuple
    else:
        yield (t1,t2)

Demo:
>>> dict_a = {'a':1, 'b':2, 'c':{'d':3}}
>>> dict_b = {'a':2, 'b':4, 'c':{'d':6}}
>>> list( treezipFlat(dict_a, dict_b) )
[(1, 2), (3, 6), (2, 4)]

You can furthermore yield the tuple of paths by augmenting the function like so:
from collections import Mapping

def treezipItems(t1,t2, path=[]):
    if isinstance(t1,Mapping) and isinstance(t2,Mapping):
        assert set(t1)==set(t2)
        for k,v1 in t1.items():
            v2 = t2[k]
            for tuple in treezipItems(v1,v2, path=path+[k]):
                yield tuple
    else:
        yield (path, (t1,t2))

>>> list( treezipItems(dict_a, dict_b) )
[(['a'], (1, 2)), (['c', 'd'], (3, 6)), (['b'], (2, 4))]

Imho I feel the natural thing here is a function called treezip:
def treezip(t1,t2):
    if isinstance(t1,Mapping) and isinstance(t2,Mapping):
        assert set(t1)==set(t2)
        R = {}
        for k,v1 in t1.items():
            v2 = t2[k]
            R[k] = treezip(v1,v2)
        return R
    else:
        return (t1,t2)

>>> from pprint import pprint as pp
>>> treezip(dict_a, dict_b)
{'a': (1, 2), 'c': {'d': (3, 6)}, 'b': (2, 4)}

Then a function called flattenValues (or flattenItems if you want to preserve keys).


text:
Q: pushing button will call a number table view I have a tableview controller and that is connected to a detailviewcontroller.
I my detailviewcontroller, I have a image a title a description and 4 buttons.
I want the 4 buttons to call 4 separate numbers.
button name call1, call2, call3, call4.
at the moment i have this:
- (void)viewDidLoad
{
    [super viewDidLoad];

    _TitleLabel.text = _DetailModal[0];
    _DescriptionLabel.text = _DetailModal[1];
    _ImageView.image = [UIImage imageNamed:_DetailModal[2]];

    self.navigationItem.title = _DetailModal[0];

    if ([_TitleLabel.text isEqualToString:@"alex"]) {

    }

//so the the names are stored in _TitleLabel, so if Alex is chosen from the tableviewcontroller. I want the 4 buttons in the detailviewcontoller to be call buttons. So I have to be able to give the 4 buttons separate tel numbers.
Can some one please help


text:
Q: can java's Long hold a SQL BIGINT(20) value? I have a table in an SQL database where the values' data type is BIGINT(20), and I need to get those data to my logic in Java for processing.
What should be the appropriate data type in java to store the BIGINT(20) value returned ?
(I thought of using Long but there is BigInteger also, can't figure out what is good or suitable)

A: MySQL BIGINT: min value (-2^63), max value (2^63-1). Maximum unsigned value (2^64-1).
https://dev.mysql.com/doc/refman/8.0/en/integer-types.html
Java Long: min value (-2^63), max value (2^63-1). Maximum unsigned value (2^64-1).
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
So, these two types are the same size :)

A: It depends on the database server. A Java long is always implemented as 8 bytes since it is part of the standard.
On MSSQL, the bigint type is 8 bytes, so it is a perfect match.

A: Long is perfect  mapping for big Int of database

A: The BIGINT type is not part of the SQL standard, so there is no guarantee that it will work the same in all databases. However, at least MSSQL, MySQL, Oracle, Postgresql, and IBM DB2 agree that it uses 8 bytes (where most are signed, but in DB2 it's an unsigned 63-bit value ).
Since a Java Long is also 64 bits, it should work fine. Since longs are a lot faster than BigIntegers, so you should almost certainly use a long.


text:
Q: Does setting the platform when compiling a c# application make any difference? In VS2012 (and previous versions...), you can specify the target platform when building a project. My understanding, though, is that C# gets "compiled" to CIL and is then JIT compiled when running on the host system.
Does this mean that the only reasons for specifying a target platform are to deliberately restrict users from running the software on certain architectures or to force the application to run as 32 bit on a 64 bit machine? I can't see that it would be to do with optimization, as I guess that happens at the CIL-->Native stage, which happens Just-In-Time on the host architecture?
This MS Link does not seem to offer any alternative explanation and I can find no suggestion of the fact that you should, for example, release separate 32 / 64 bit versions of the same application - it would seem logical that something compiled for "anycpu" should run just as well and, again, optimizations will be applied at the JIT stage.

A:
Does this mean that the only reasons for specifying a target platform are to deliberately restrict users from running the software on certain architectures or to force the application to run as 32 bit on a 64 bit machine?

Yes, and this is critical if you're using native code mixed with your managed code.  It does not change what gets optimized at runtime, however.
If your code is 100% managed, then AnyCPU (or the new AnyCPU Prefer 32-Bit) is likely fine.  The compiler optimizations will be the same, and the JIT will optimize at runtime based on the current executing platform.

I can find no suggestion of the fact that you should, for example, release separate 32 / 64 bit versions of the same application

There is no reason to do this unless you're performing interop with non-managed code, in which case, that will require separate 32 and 64 bit DLLs.

A: Reed has a good answer here. However, I think it's also important to point out that this setting is just a flag in the DLL - it pretty much has no effect whatsoever in most situations. It is the runtime loader's (the bit of native code that starts the .NET runtime) responsibility to look at this flag, and direct the appropriate version of of the .NET runtime to be started up.
Because of this - the flag will mostly only matter when it is set on an EXE file - and have no effect when set on a DLL.
For example - if you have a '32-bit-flagged .NET DLL' which is used by either a 64-bit-flagged .NET EXE, or an any-cpu-flagged .NET EXE, and you run the EXE on a 64-bit machine - then the loader will start the 64-bit runtime. When it comes time to load the 32-bit DLL, it's too late - the 64-bit runtime has already been chosen, so your program will fail (I believe it's a BadImageFormatException that you will receive).


text:
Q: Collect data and make response SailsJS I just started to learn SailsJS and I ran into the following problem:
In the UserController I've got following method:
  /**
   * `UserController.create()`
   */
  create: function (req, res) {

    var d = {};

    c = {'fullname' : 'Sergiu Pirlici'}

    User.findOne(c, function(err, found) {
      d.found = found;
    });

    User.destroy(c, function(err){
      d.destroyed = !err;
    });

    if(req.method == 'GET') {
      res.view(d);
    }
    else if(req.method == 'POST') {

      var dat = req.params.all();

      User.create(dat, function(err, created){
        d.err = err;
        if(!err) {
          d.created = created;
        }
      });

    }

    d.foo = true;

    res.json(d);
  },

In variable d I want to collect data and pass it to view or send as JSON.
But in the value of d is {'foo': true}.
I understant that this happens because precedent actions are asynchronous.
Is there an another way to collect data and pass it to response?
How can I do this?

A: you can use a service http://sailsjs.org/#/documentation/concepts/Services
then pass a callback parameter.
so on the UserService.js
module.exports = {
    FindOne: function(cb){
        User.findOne(c, function(err, found) {
              cb(found);
            });
    }

};

then on your controller:
UserService.FindOne(function(found){
    //other logic
    var d = { result : found } ;
    res.json(d);
});


text:
Q: Generic with a lower bounded wildcard  super Dog> class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
public class Mixer<A extends Animal>{
    public <C extends Cat> Mixer<? super Dog> useMe(A a, C c){
        //return new Mixer<Object>();//KO
        return new Mixer<Animal>(); //OK
    }
}

The return parameter is Mixer<? super Dog> so if is a defined with a lower bounded wildcard
Why do I have a compiler error when I return a Mixer<Object> and there is no compiler error with Mixer<Animal>?

A: The problem is not in the return type of your method, rather it is the Generic Type bound to your class Mixer.
Let's see what went wrong: -
public <C extends Cat> Mixer<? super Dog> useMe(A a, C c)

The return type Mixer<? super Dog> means, you can return any Mixer of type Dog or a super-type of Dog, may be Animal.
    //return new Mixer<Object>();//KO
    return new Mixer<Animal>(); //OK

So, both the return statments would have worked fine, because, both Animal and Object is a super-type of Dog.
But, the reason why the first one does not fits in is because, you have declared your class as: -
public class Mixer<A extends Animal>

So, you have bound your type that can be associated with Mixer class to either Animal or its subtype.
Now, since, Object is not a subtype of Animal, you can't just create: -
new Mixer<Object>();

So, you can create instances of your class like:-
new Mixer<Animal>(); // OR
new Mixer<Dog>();  // Dog extends Animal  // OR
new Mixer<Cat>();  // Cat extends Animal

// **** But NOT like this ******
new Mixer<Object>();  // Object does not extend Animal


text:
Q: jquery-steps styling finish button I'm trying to style the Finish button for jquery-steps, however it appears to have an inline style:
<li class="ui button" aria-hidden="false" style="display: list-item;">
How can I remove this style, it's interfering with my styling.

A: You can do it in css like
li.button { display:block;}


text:
Q: Optimization of K-fold cross validation for implicit recommendation systems I have been trying to test my recommendation system using k-fold cross validation. My recommendation system is based on implicit feedback.Since, I am trying to implement k-fold cross validation on my user-item matrix, I can't use scikit-learn's native k-fold methods(can I?). I am having trouble implementing my k-fold cross validation technique. I seem to be using a lot of for loops, and it's becoming very slow. I have gone through these links : Optimize this function with numpy (or other vectorization methods) and Speed up for loop with numpy but I can't seem to apply it to my code. Can somebody help me out?
My code:
 def TrainRepeat2(counts,FinalArr,k=3):

  """
  parameters:
  -------------------------------------------

  counts : user-item matrix
  k  :  No of folds
  FinalArr : shuffled indices

  Example:
  if k = 3
  FinalArr will be a list containing 3 lists with randomly shuffled indices
"""

   # No of factors
   num_factors= [10,20]
   PartitionList = range(k)

   # Iterating over the number of factors
   for i in range(len(num_factors)):

       # iterating over the folds
       for partition in PartitionList:

          # Keep one fold for testing
          validation = counts[FinalArr[partition],:]

         # CKeep the rest for training
          validation_list = [x for x in PartitionList if x != partition]

           # Train over the rest
           for t in validation_list:

             train = counts[FinalArr[t],:]
             train = sparse.csr_matrix(train)
             print "THe evaluation is being done for factor no %d" %(num_factors[i])
             reg_param = 5

             MF_als = ImplicitMF(train,validation,num_factors = num_factors[i],num_iterations=80,reg_param = reg_param,num_threads=14)
             user_vectors,item_vectors=  MF_als.train_model(flag,leaveone=False)

Specifically, the algorithm is o(N^3). I want to somehow remove the for loops and optimize the code.
Any help would be appreciated
Thanks!

A: Edited per comment
At the end of the day if you want to run cross validation n number of times, you are going to have to loop n times.  Whether that loop is hidden to you (and hopefully written very efficiently, either in cython or something similar) or visible in your code, that will happen.
I think at a high level what you want is here:
http://scikit-learn.org/stable/modules/cross_validation.html
Things you need to do:
write a classifier object, that takes in train_data,train_class,test_data returns a list of predictions for test_data.  This is your "recommender" class, and is in function to any of the sklearn classifiers.
Write a scoring object.  Per your comment below, this should take in two arrays of the same length, the prediction and the correct classification, and calculate the error.  Then you can use those two objects directly in the sample sklearn code below.
Assuming:
your full dataset is in df
your "target" (however defined) is in targets
clf is your classifier (or recommender in this case)
scorer is how you calculate error
n_samples = len(df)
cv = cross_validation.ShuffleSplit(n_samples, n_iter=3, test_size=0.3, random_state=0)

cross_validation.cross_val_score(clf, df, targets, scoring = scorer,cv=cv)

array([ 0.97...,  0.97...,  1.        ])


text:
Q: How to rename img files upon uploading/compressing using PHP? I want to upload img-files using php, compress them, and rename them. I am stuck at the rename part. Can someone look at my code and tell me how I could achieve that?
this is my html form:
    <form method='post' action='' enctype='multipart/form-data'>
      <input type="file" name="imagefile1" accept="image/*" capture="environment">
      <input type="submit" value='upload1' name='upload1'>
    </form>

this is my php code:
            if(isset($_POST['upload1'])){

            // Getting file name
            $filename = $_FILES['imagefile1']['name'];

            // Valid extension
            $valid_ext = array('png','jpeg','jpg');

            // Location
            $location = "uploads/".$filename;

            // file extension
            $file_extension = pathinfo($location, PATHINFO_EXTENSION);
            $file_extension = strtolower($file_extension);

            // Check extension
            if(in_array($file_extension,$valid_ext)){

                // Compress Image
                compressImage($_FILES['imagefile1']['tmp_name'],$location,20);

            }else{
                echo "Invalid file type.";
            }
            }

             // Compress image
            function compressImage($source, $destination, $quality) {

              $info = getimagesize($source);

             if ($info['mime'] == 'image/jpeg')
               $image = imagecreatefromjpeg($source);

             elseif ($info['mime'] == 'image/gif')
               $image = imagecreatefromgif($source);

             elseif ($info['mime'] == 'image/png')
              $image = imagecreatefrompng($source);

                  imagejpeg($image, $destination, $quality);}

A: Simply use the information you already retrieve to give your image a new name:
$filename = $_FILES['imagefile1']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$image_name = $yours_new_name.'.'.$ext;


text:
Q: Data Contracts Not Matching Doesn't Cause An Error in WCF I have a WCF service that implements a data contract. I then have a client that consumes that service with it's own implementation of the data contract.
If the data contracts don't match exactly, it doesn't generate any sort of error, nor does it return any data.
public class RecipeClient : ClientBase<IRecipeService>, IRecipeService
{
    public RecipeEntity[] GetAllRecipes()
    {
        var recipe = Channel.GetAllRecipes();
        return recipe;
    }
}

In the above example, after the call is made, recipe contains an empty array of RecipeEntity.
I would expect it to not return any data, but why doesn't it generate an error?

A: It is for backward compatibility. If you add in datacontract of existing service some not required properties, all existing clients will work without errors.

A: As if was mentioned it's for backward compatibility, but you can mark some properties as required. And if there is no such property in a message, an exception will be thrown:
[DataContract]
public class Recipe
{
    [DataMember]
    public string Name { get; set; }
    [DataMember(IsRequired = true)]
    public string Rank { get; set; }
}


text:
Q: C++ Performance: template vs boost.any I was wondering if using boost.any (Without RTTI) classes anywhere templates can be used will slow down the program. Since boost any is actually a wrapper around a template class, one could say that with the modern compiler-optimalisations it will produce the same effect, am I right?
tpl_vs_any.hpp
#include <iostream>
#include <vector>

using namespace std;

template<class T> class tpl
{
    T content;
public:
    tpl(const T& value) : content(value) {}
    operator T() const
    {
        return content;
    }
};

class any
{
public:

    any() : content(0) {}

    any(const any& other) : content(other.content -> clone()) {}

    template<class T> any(const T& value) : content(new holder<T>(value))
    {
    }

    ~any()
    {
        delete content;
    }

    class placeholder
    {
    public:
        placeholder() {}
        virtual placeholder* clone() const = 0;
    };

    template<class T> class holder : public placeholder
    {
    public:
        T content;

        holder(const T& value) : content(value) {}
        ~holder() {}

        placeholder* clone() const
        {
            return new holder<T>(content);
        }
    };

    template<class T> operator T () const
    {
        return dynamic_cast<holder<T>*>(content)->content;
    }

    placeholder* content;
};

template<class T> void test()
{
    for (int i = 0; i < 10000; ++i)
    {
        vector<T> a;
        a.push_back(23.23);
        a.push_back(3.14);

        double x = (double)a[0];
    }
}

So would it be correct to say that:
test<any>();

Is exactly as fast as:
test<tpl<double>>();

Assuming that you know, just like the compiler does at the second example, that boost::any is only used as double in this situation? (No RTTI for the any class).
I'm more wondering about the arguments for and against this thesis.
Also, are there specific situations where there is difference between those methods?
Edit:
Performance test 2:

*

*Example 1: 1,966.57 ms

*Example 2: 1,320.37 ms

It seems like there is a relativly large difference.
Edit 2:
Since it was not fair to compare the primary data type double against the class any I've made a new test:
#include "tpl_vs_any.hpp"

int main()
{
    test<any>();
    return 0;
}

Speed: 1,794.54 ms
#include "tpl_vs_any.hpp"

int main()
{
    test<tpl<double>>();
    return 0;
}

Speed: 1,715.57 ms
Tested it multiple times, pretty much the same benchmarks.

A:
So would it be correct to say that:
...
Is exactly as fast as:
...
Assuming that you know, just like the compiler does at the second example, that boost::any is only used as double in this situation?

No. Current compilers do nowhere near that kind of level of introspection. boost::any will be slower.
Of course, you could just run the code and find out for yourself.

A: boost::any internally holds a pointer to an object, which it allocates with new. One of the things that makes std::vector significantly faster than, say, std::list is that vector keeps all of its objects in a contiguous storage in a single allocation, which aside from the obvious reduction in memory allocation overhead, is also a lot more cache-friendly.
There's also the detail of adding RTTI to the allocation, which is generally trivial overhead, but in the case of really small types like double significantly increases the storage overhead.
boost::any is not part of the standard; it's a specific implementation of a specific template. So you might as well just benchmark it; there aren't a bunch of other competing "standard implementations".


text:
Q: What's the difference between multi-(single outputs) NN vs single-(multi targets) NN? I'm working on this following autoregressive problem with Keras/TF :
Inputs :
m examples x 10 timesteps (sequence length) x 7 features
(With each value being a real value)
Outputs :
m examples x 4 targets/"labels" (real values that I want to predict)
So far, using LSTMs with Dense layers at the end (edited). So for one example, I give 7 features in a sequence of size 10 and I just want 4 real values out of it (I'm predicting current values according to previous values).
My question is the following  :
What is the difference between predicting :
a. 1 output with dimensions m x 4
b. 4 outputs with each of dimensions m x 1
I've tried both methods and I don't see any particular difference but I want to understand what they both do. In the second case, I know I can specify different losses and different weight for the losses on each variable that I want to predict but this seems to be less correct than the first method.
#python / Keras-TF
#a. multi output
model = Model(inputs = X_input, outputs = [Output1,Output2,Output3,Output4])
prediction = model.predict(X_test_normalized) #returns an inconvenient list of 4 [2 by 1 vectors] which in the end gives me m*4 real values as wanted

###### vs ######

#b. single output
model = Model(inputs = X_input, outputs = [Output1]) #vector of dimension 4
prediction = model.predict(X_test_normalized) #returns a m*4 matrix

A: It does not make a difference most of the time. If your output layers are dense ones, each of them will have a n*1 weight matrix. If you have a single output layer the weight has the shape n*4 instead. Generally one big output layer is faster, as one big matrix multiplication often faster than multiple small ones.
You can weight the outputs of the single output layer, too. Just multiply it with a weight vector of the size of your outputs before giving it to the loss.


text:
Q: How to troubleshoot a timed out error on putty when connecting with ssh on an azure virtual machine I just came out with a nice Debian 9 "Stretch" Virtual Machine hosted with Microsoft Azure. I've already used PuTTY, PuTTYgen and Pageant to connect with ssh to it and i've saved all this configuration into the PuTTY's startup window.
Once connected i've managed the VM, created the authorized_keys file and copied my public key in it under the .ssh directory.
But this afternoon, while running my PuTTY again, it isn't able to reach the VM and throw me a "timed out" connection after some time.
I've already tried :

*

*Restart the VM via the Azure Portal

*Redeploy the VM via the Azure Portal

*Running with and without Pageant

*Checking over and over the configuration ...

What I can't do :

*

*Reset user's credentials and ssh configuration thought the Azure Portal (Missing VMForLinuxAccess extension)

*Use Azure CLI

*Change VM's configuration (I don't own the VM rights)

Have you any idea how to troubleshoot this problem ?
Thanks in advance.

A: Just put comments as an answer.

Have you any idea how to troubleshoot this problem?

You could telnet VMpublicIP with port 22 to check if network traffic blocking. Also, you can capture the network traffic packages to analyze the network traces between the client and server via tool Wireshark or Network monitor.
Moreover, you can find the Troubleshoot SSH connections to an Azure Linux VM  and Detailed SSH troubleshooting steps for issues connecting to a Linux VM in Azure.


text:
Q: UML diagram of whole project in intellij idea How can I get a diagram of all classes in the project in intellij idea?

A: IntelliJ Ultimate Edition provides a diagram feature. More details in the docs.
If you are using IntelliJ Community Edition then you'll need to install a plugin such as:

*

*Code Iris

*Plant UML
You can install these plugins from Preferences > Plugins ...


text:
Q: Бесконечная генерация кривой CatmullRomSpline в LIBGDX Вопрос:
Позволяет ли CatmullRomSpline добавлять/удалять новые точки для генерации бесконечной незамкнутой кривой в процессе выполнения программы? Если позволяет, то как мне достичь такой генерации с учетом исключения, описанным ниже?
К примеру: в Vector2[] dataPoints инициализированы три точки. Через них проходит кривая. По кривой я перемещаю текстуру. Если текстура достигла половины кривой, то создать новую точку, провести через нее кривую, а пройденное расстояние удалить. Но есть исключение в том, что начальная и конечная точки только контролируют построение кривой, но сама кривая через них может не проходит. Изображение для примера (рисовал "на глаз").

Код, который получилось написать по туториалу:
public class MyCatmullRomSpline {

private int mCountSections; //кол-во делений(точек) между основными точками указанными в dataPoints
private Vector2[] mSections; //массив делений
private ShapeRenderer mShapeRenderer;
private CatmullRomSpline<Vector2> mSpline;
private Vector2 out;
private float speed; //скорость перемещения чего-либо по кривой

public GCatmullRomSpline(Vector2[] dataPoints, boolean closed, int countSections){

    speed = dataPoints.length - 1;

    mSpline = new CatmullRomSpline<Vector2>(dataPoints, closed);
    mSections = new Vector2[countSections];

    mCountSections = countSections;

    mShapeRenderer  = new ShapeRenderer();

    initSpline();
}

private void initSpline(){
    out = new Vector2();

    mSpline.valueAt(out, Gdx.graphics.getDeltaTime());
    mSpline.derivativeAt(out, Gdx.graphics.getDeltaTime());

    for (int i = 0; i < mCountSections; ++i){
        mSections[i] = new Vector2();
        mSpline.valueAt(mSections[i], ((float)i)/((float)mCountSections-1));
    }
}

float current = 0;

public void render(SpriteBatch batch, Texture texture){
    mShapeRenderer.begin(ShapeRenderer.ShapeType.Line);

    float derivativeAverage = 0;
    for (float i = 0; i < 1; i += 1f/mCountSections) {
        mSpline.derivativeAt(out, i);
        derivativeAverage += out.len();
    }
    derivativeAverage /= mCountSections;

    mSpline.derivativeAt(out, current);
    current += derivativeAverage / speed * Gdx.graphics.getDeltaTime() / out.len();
    current %= 1;

    if (current >= 1) current -= 1;
    mSpline.valueAt(out, current);

    batch.begin();
    batch.draw(texture, out.x - 18, out.y - 18, 36, 36);
    batch.end();

    for (int i = 0; i < mCountSections-1; ++i){
        mShapeRenderer.line(
                mSpline.valueAt(mSections[i], ((float)i)/((float)mCountSections-1)),
                mSpline.valueAt(mSections[i+1], ((float)(i+1))/((float)mCountSections-1)));
    }

    mShapeRenderer.end();
    }
}

A: Для начала - сплайн Эрмита - кубическая кривая, которая задаётся начальной и конечной точками P(i), P(i+1) и производными в этих точках M(i), M(i+1)
Сплайн Кэтмулл-Рома - набор эрмитовых сплайнов, для обеспечения гладкости сшивки которых (гладкость первого порядка, т.е. в точках сочленения совпадают значения и наклон) используется простая зависимость - наклон в точке сшивки определяется равным наклону отрезка между двумя соседями этой точки (и амплитуда вектора производной может ещё нормироваться, но обычно используется просто номер точки, т.е. разность делится пополам)
M(i) = (P(i+1) - P(i-1)) / (t(i+1)-t(i-1))

Вот пример построения по точкам A,B,C,D,F
Направление в точке B определяется разностью C-A, в точке С - разностью D-B, в точке D - разностью F-C

Для построения одного КМ сплайна требуется 4 точки, двух - 5 точек, N - N+3 точек. Можно достроить сплайны и до конечных точек, если задать какие-то дополнительные ограничения (например, кривизна, и соответственно вторая производная в конечной точке нулевая)
Зная значение в некой точке кривой и производную в ней же (методы библиотека, как уже автор показал, предоставляет), мы можем разделить кривую на два сплайна. Данная точка станет стартовой точкой сплайна, а новую начальную точку последовательности можно перерассчитать, чтобы сохранить программный интерфейс в виде набора точек.
Но пока неясно, как это поможет генерировать бесконечную кривую.


text:
Q: How to uncollapse columns in PHPExcel I am continuing work a DB to PHPExcel generated spreadsheet. The last remaining problem I am having is that all the rows but the last one are collapsed when the spreadsheet opens. I need them all expanded. Right now the user has to grab the top border and drag it down to expose the row above it. I've tried:
$phpExcel->getActiveSheet()->getRowDimension($row)->setVisible(true);
$phpExcel->getActiveSheet()->getRowDimension($row)>setCollapsed(false);

$row is the current row number.


text:
Q: Xamarin Android and the splash screen Developing a cross-platform application with PCL I noted that the Android app starts with a blank screen with the title of the app. After a while my First ContentPage is showed. Can I remove the First blank screen? If not, Can be customized? Where is declared/defined?
Thank you


text:
Q: Theory: Buffered video download and delay Could someone please explain me the way it works? My understanding below, may have mistakes.
We have two ways of downloading a movie and watching it at the same time:
1) Buffered
2) Non-buffered
In the first case we are downloading as much data as we are capable of (simply depends on the speed of our internet provider assures). In the second case we are downloading as much data as we need to watch a movie from a certain point - in other words in one second, we download 1 second of the movie.
Next - delay. My professor says there is no difference between buffered and non-buffered download of a movie - a potential delay is the same. How could it be?
So could someone please tell me if the above is true/how it works? And second part: what impact has buffered download on delays?
Thanks!


text:
Q: git diff release tag and commitID I am writing a powershell script that gets me the files changed between release tag and last commit. But the problem I am encountering an issue it doesn't  include the last commit file.  Below are commands.
$LatestTag= $(git rev-list --tags --max-count=1)
$ReleaseTag = $(git describe --tags $LatestTag)
$CommitId =  $(git rev-parse HEAD)

$files=$(git diff $ReleaseTag..$CommitId~ --name-only)

The files includes all changed files except the last committed file.

A: Tilde in $CommitId~ means "previous commit". Just remove it to run diff with the last commit:
$files=$(git diff $ReleaseTag..$CommitId --name-only)


text:
Q: Are there any XML Parsers for Ruby that fully support XPath 2.0? I need to see if a node exists within a particular XML document.  If the node does not exist, then I would like to use another value.  With XPath 1.0 this involves craziness using concat.  With XPath 2.0, I can get it to work with:
if (boolean(path-to-preferred-node)) then path-to-preferred-node else default-to-other-node

We need to use XPath 2.0 for this which rules out Nokogiri.
Any help would be greatly appreciated.


text:
Q: Clarification about proof involving product/sum manipulation In this post, the following simplification was made:
$$2\pi i\sum_k\lim_{x\to ia_k}(x-ia_k)
\frac{x^2e^{itx}}{\prod_j(x^2+a_j^2)}\\
=-\pi\sum_ke^{-ta_k}a_k\sum_{j\neq k}\frac1{a_j^2-a_k^2}.$$
What I have done is the following, but am unsure why it is wrong:
$$
2\pi i\sum_k\lim_{x\to ia_k}(x-ia_k)
\frac{x^2e^{itx}}{\prod_k(x^2+a_k^2)}\\
=2\pi i\sum_k \frac{(ia_k)^2e^{-ta_k}}{\prod_k (ia_k+ia_k)}.
$$
Even after reduction it does not matched the stated closed form. Where does the $\sum_{i\neq j}$ come from? I am unfamiliar with this notation.
Thank you!

A: For a given $k$, the $k$-th inner term of the sum is (before taking the limit)
$$\begin{split}
(x-ia_k)\frac{x^2e^{itx}}{\prod_j(x^2+a_j^2)} &= \frac {(x - ia_k)}{x^2+a_k^2}
\cdot\frac{x^2e^{itx}}{\prod_{j \neq k}(x^2 + a_j^2)}\\
&=\frac {1}{x+ia_k}\cdot\frac{x^2e^{itx}}{\prod_{j\neq k}(x^2+a_j^2)}\\
\end{split}$$
where we used the fact that $x^2+a_k^2=(x-ia_k)(x+ia_k)$.
This implies
$$\lim_{x\rightarrow ia_k}(x-ia_k)\frac{x^2e^{itx}}{\prod_j(x^2+a_j^2)}=-\frac 1 {2ia_k}\frac{a_k^2e^{-ta_k}}{\prod_{j\neq k}(a_j^2-a_k^2)}$$
which yields the final result.


text:
Q: How avoid form elements move when get focus I added a style for when input text get focus. Then, all other elements below move every time the textbox gets/loses focus.

input[type=text]:focus {
  border: 3px solid #555;
  outline-offset: 0;
}
<input id="CodPostal" name="CodPostal" type="text" value placeholder="focus here">

 text

<input id="Name" name="Name" type="text" value>

I googled it and tried with outline-offset: 0; but didn't work

A: you can use box-shadow or outline instead

input[id="CodPostal"]:focus {
  box-shadow: 0 0 0 3px #555;
}
/* or */
input[id="Name"]:focus {
  outline: 3px solid #555
}
<input id="CodPostal" name="CodPostal" type="text" value>

 text

<input id="Name" name="Name" type="text" value>

https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow
The box-shadow CSS property adds shadow effects around an element's frame. You can set multiple effects separated by commas. A box shadow is described by X and Y offsets relative to the element, blur and spread radii, and color.

and

https://developer.mozilla.org/en-US/docs/Web/CSS/outline
The outline CSS property is a shorthand to set various outline properties in a single declaration: outline-style, outline-width, and outline-color.

and about outline-offset

https://developer.mozilla.org/en-US/docs/Web/CSS/outline-offset
The outline-offset CSS property sets the amount of space between an outline and the edge or border of an element.


text:
Q: What is the correct way to initialize an object as a static member of a C++ class I have a date class like below which I use to find the resultant date after adding/subtracting a few days.
The constructor validates the input date and throws an exception if invalid.
class date
{
    private:
        int day;
        int month;
        int year;

        bool isValid(date& d);

    public:
        date(); //default to starting of say Gregorian calendar
        date(string strDate); // takes DD/MM/YYYY format string to initialize day, month and year

        //static date today;

        int operator- (date& d); //difference of two dates in no. of days
        int operator- (int days); //get the date a few days before this date
        void operator+ (int days); //get the date a few days after this date
};

In addition to the above I also want to keep track of today's date as part of the class itself which other parts of the program can use for calculation purposes.
Is it possible to have a static member as written in the commented line above and have the class itself initialize the object?
If yes how do we initialize the object?
If no then what is the correct way of dealing with the "today" object?
I read other posts but all posts seem to deal with static members of basic types.
However here multiple statements has to executed in order to get system date and hence I am thinking it is different from the other posts.

A: You absolutely can uncomment the code, exactly as written. But that merely "declares" the variable. To "define" it, in exactly one source file (such as the .cpp/.cc file with the rest of the code), near the top (and outside all functions), put the line:
date date::today;

That defines the variable (like other class members are defined).
Note that only date methods can access it, since it's private. If you want other parts of the program to be able to (only) read it, you can do one of two things:

*

*Add a public static method to the class:
static const date &Today() { return today; }

*Add a second, public static variable inside the class which referred to the first - but then you have to worry about the two names.

*

*Inside the class, change today to _today, and add:
public:
   static const date &today;

*And inside the .cpp/.cc you need to define them:
date date::_today;
const date &date::today = date::_today;

With that, inside the date class you can modify _today, while other parts of the program can read today.


text:
Q: apple in-app subscription information missing but NO in-app purchase used a. I removed all the in-app purchase products. Its empty. (there was an Auto-Renewable Subscription)
b. My app (not published yet) has in-app purchase OFF too (in capabilities).
Anyway, in subscription groups, one is there and i cannot delete it: I just don't find the way or it simply can't be removed.
But above that, the app is being rejected "because we cannot locate the in-app purchases within your app." and they also mention missing information related to the subscription.
Anyhow, they don't realise that the App does not use it or something is confusing them.
any clues??

EDIT: Answer from review board today:
"However, you have not deleted the In-App Purchase products; they are still attached to the binary.
Please delete the In-App Purchase products from iTunes Connect, then resubmit your binary, so that we may continue the review."
And they sent this link: Delete an in-app purchase
Well, what else, as you can see in the screenshots I had already deleted  the product before sending the new build...
I am starting to think that maybe they need weeks to update its status?


text:
Q: mui-datatables fixedHeader option is not working My requirement is to generate tables using material design in reactjs environment. I want sorting, column hide/show, csv download, fixing of the header while vertical scrolling  and filtering of data of a specific column over the entire table.
I found the below design components:

*

*https://material-ui.com/demos/tables/

*https://github.com/gregnb/mui-datatables

*https://github.com/mbrn/material-table

*https://github.com/techniq/mui-virtualized-table
from the above 4 options, the most suitable package for implementing my table seemed to be mui-datatables (the 2nd option) with all the implementations built in for the table component. However, when I am trying to fix the header using fixHeader in options property of the table the header is not fixed for vertical scrolling. To fix the header, I changed the fixedHeader props of the table component in the mui-datable to true. The code for the testing the implementation: https://codesandbox.io/s/mmqyr28q6p

A: You have to give your table a height then only fixedHeader will work. Put       tableBodyHeight: '400px' in your MUiDatatable options


text:
Q: Prevent Duplicate Documents in MongoDB? I'm trying to figure out the best way to prevent duplicate documents from being saved in MongoDB.
Right now my form takes the user_url from the user. The logic is:

*

*Check if the user_url is valid. (dns.lookup)

*If user_url is new, save it to the database and return url_ID.

*If user_url is old, just return the url_ID.
I think my 2 options are:
var findOneURL = function(user_url, done) {
    URL.findOne({
        orig_url: user_url
    }, (err, data) => {
        if (err) {
            done(err);
        }
        done(null, data);
    })
}

or
var findEditThenSave = function(user_url, done) {
    URL.findById(user_url, (err, data) => {
        if (err) {
            done(err);
        }

        data.save((err, data) => {
            if (err) {
                done(err);
            }
            done(null, data);
        });
    })
};

It's not working terribly well at the moment but this is the live version:
https://kindly-fisherman.glitch.me/
EDIT2: I think I got it working properly now. Here's my logic:
Saving to database: dns.lookup -> findByURL -> (If it doesn't exist) -> countURLs -> findAndUpdateURL -> Return what was saved to database.
OR -> (If it exists) -> Return the record.
Retrieving from database: findByID

A: The best choice is findOneAndUpdate query with upsert and returnNewDocument options
db.collection.findOneAndUpdate({ orig_url: user_url }, { $set: { orig_url: user_url }}, { upsert: true, returnNewDocument: true })

In mongoose
URL.findOneAndUpdate({orig_url: user_url }, { $set: { orig_url: user_url }}, { upsert: true, new: true }, (err, data) => {
    if (err) {
        done(err);
    }
    // data will contain your document
    done(null, data);
});

upsert option specifies whether to insert document if not found, new (returnNewDocument in mongo's console) - whether to return old or updated document - if false (default is false) you will have null for inserted documents.

A: Instead of using
 db.insert()

you should use
db.update()

and specify
$upsert: true

[here]


text:
Q: Does appcache auto invalidate files not in manifest Let say on first version of manifest, we have file call abc.css . Subsequently, on second version of manifest, we remove abc.ss and append new file def.css . Does browser automatically invalidate abc.ss and remove from the caching list in browser upon second time user visited the website?

A: No. Once files are cached using the app cache. They remain in cache, and the browser doesn't even contact the server to validate files or to see if any changes were made.
If you need to modify a file that is cached by the application cache, then you need to modify your manifest file.
From http://www.html5rocks.com/en/tutorials/appcache/beginner/

You must modify the manifest file itself to inform the browser to refresh cached files.


text:
Q: How do I write to a VFP database from an MVC application I am working with an MVC application, problem is, is it possible to write to a Visual FoxPro database from an MVC application? .. If possible any help in regards with this will be highly appreciated.
UPDATE:
I am currently working on a website for a doctor. She wants her clients to be able to make an appointment with her at and given time using the website, which must then link the clients data to VFP software that shes currently using. All i need to do is to be able to take the records of each clients bookings and write it into her current softwares database. The company that created the software for her are granting me access to her database. I am using the code first approach in MVC.

A: Leveen,
I'm currently doing similar access from MVC to a foxpro db. My MVC is on a different server than the foxpro table.

*

*If you had the same setup, I recommend that you use WCF service running on the server where the foxpro database is. Your WCF will need to instantiate a VFP dll which in turn process CRUD requests to your foxpro db.

*If your IIS is on the same server as the foxpro db, you can skip WCF and instantiate VFP dll directly from MVC.

*Have you look into VFP Entitiy Framework Provider? https://github.com/tombrothers/VfpEntityFrameworkProvider2
Cheers

A: There are multiple ways to handle this. One simple way is to create a separate class library that does all the data access and CRUD operations. Within that DLL, it doesn't really matter if you are doing EF, LinqToVFP, VFP EF or direct ADO.Net commands (I wouldn't suggest COM DLL approach which could be tempting and seem to be easy initially - on the long run you might have frustrations especially with versioning).
You can individually test that class library with or without a web application (from anywhere, like a command window, windows form app, simply using LinqPad etc).
One thing you need to make sure is to enable 32 bit in application pool.


text:
Q: Method parameter type same as the method's class Python I'm making a card game with python in which certain cards have health and attack attributes. When I play the card, I want to subtract the attack attribute of the player's card from the health attribute of the enemy's card, as defined in the attack method. These types of cards are called Battle Cards. Because only Battle Cards can be attacked, I want to make sure in the attack method's parameter that the enemy's card being attacked is a Battle Card.
class Card:
    """A class to hold a card."""

    def __init__(self, title: str, description=""):
        """Initialize the card."""

        # A title for the card.
        self.title = title

        # This is a description of the card.
        self.description = description

    def __str__(self):
        """Return a string representation of the card."""
        return self.title

class BattleCard(Card):
    """A class to hold a battle card."""

    def __init__(self, title: str, health: int, attack: int, description=""):
        """Initialize the battle card."""

        # Initialize the parent class.
        super().__init__(self, title, description)

        # Add battle card attributes
        self.health = health
        self.attack = attack

        # Add alive variable
        self.alive = True

    def __str__(self):
        return f"{self.title}: {self.health} health, {self.attack} attack"

    def attack(self, enemy: BattleCard):
        """Play the battle card"""
        enemy.health -= attack
        enemy.check_if_alive()

    def check_if_alive(self):
        if self.health < 0:
            self.alive = False

if __name__ == '__main__':
    card1 = BattleCard("Laser", 5, 3, "Burns up opponents.")
    card2 = BattleCard("Electric", 5, 7, "Shoots lightning at enemies.")
    cards = [card1, card2]

    cards[0].attack(cards[1])
    print(*cards)

But when I run the following code, I get this error:
Traceback (most recent call last):
  File "C:\Users\Joel Conrad\SublimeTextProjects\Card Game\cards.py", line 18, in <module>
    class BattleCard(Card):
  File "C:\Users\Joel Conrad\SublimeTextProjects\Card Game\cards.py", line 34, in BattleCard
    def play(self, enemy: BattleCard):
NameError: name 'BattleCard' is not defined
[Finished in 2.7s]

How can I make sure that the enemy parameter is always a Battle Card within the Battle Card class?


text:
Q: Cells and pointers variables class Cell<T> {
    T first;
    Cell<T> next;
    Cell(T f,Cell<T> n) {
       first=f;
       next=n;
    }
}

Suppose we have three variables ls1, ls2 and ptr of type Cell<Character> and the cells and-pointers diagram below gives the initial situation:

Draw the cells-and-pointers diagram which would represent the situation after the following lines
of code have been executed:
ls2.next.first='z';
ls1.next=ls1.next.next;
for(ptr=ls2; ptr!=null; ptr=ptr.next)
ls1 = new Cell(ptr.first,ls1);

Attempt:
After the first line b is changed to z.
After the second line y is changed to z.
But i'm not sure if that is right or what happens next.

A: You're right about the first part. The line ls2.next.first='z'; would change your lists to be:
ls1 --> x --> y --> z --> c
ls2 --> a ---------^

You basically change the value of the cell.
Then, the second line ls1.next=ls1.next.next; would discard the y element of the first list:
ls1 --> x --> z --> c
ls2 --> a ---^

And then you have a for loop. Inside this loop you run over all the elements of ls2 and create new elements at the head of ls1, as such:
ls1 --> a --> x --> z --> c
ls2 --> a ---------^

ls1 --> z --> a --> x --> z --> c
ls2 --> a ---------------^

ls1 --> c --> z --> a --> x --> z --> c
ls2 --> a ---------------------^

Note that when you create these new cells, you pass their value (for some reason in your code called first) to the constructor, thus creating completely new object which are not connected.

A: ls1 = czaxzc
ls2 = azc
Below you have the code in Java.
public class Main {

    public static void main(String[] args) {
        Cell<Character> c = new Cell<>('c',null);
        Cell<Character> b = new Cell<>('b',c);
        Cell<Character> y = new Cell<>('y',b);
        Cell<Character> x = new Cell<>('x',y);
        Cell<Character> a = new Cell<>('a',b);

        Cell<Character> ls1 = x;
        Cell<Character> ls2 = a;

        ls2.next.first = 'z';
        ls1.next = ls1.next.next;
        for (Cell ptr = ls2; ptr != null; ptr = ptr.next) {
            ls1 = new Cell(ptr.first, ls1);
        }

        print(ls1);
        print(ls2);

    }

    public static void print(Cell list) {
        for (Cell ptr = list; ptr != null; ptr = ptr.next) {
            System.out.print(ptr.first);
        }
        System.out.println("");
    }

    static class Cell<T> {
        T first;
        Cell<T> next;

        Cell(T f, Cell<T> n) {
            first = f;
            next = n;
        }
    }

}


text:
Q: Wifi Direct createGroup not working on some Samsung Phones (S7, A5 etc) I want to get an Access point out of my android mobile device so that a legacy device can connect to the mobile device. To do this I use the createGroup API [https://developer.android.com/reference/android/net/wifi/p2p/WifiP2pManager.html#createGroup(android.net.wifi.p2p.WifiP2pManager.Channel,%20android.net.wifi.p2p.WifiP2pManager.ActionListener)] as in the example [https://github.com/DrJukka/MyWifiMesh]
It works perfectly fine in quite a few devices, however I see that on some Samsung devices like S7 Edge, A5 and others, the API returns success and it does give the SSID and password, however the legacy device cannot connect to those SSID and password (I think that it doesn't broadcast the SSID and password, it just gives a dummy SSID and password).
Has anybody encountered this issue before and is there a solution to this. Also, the issue is that it returns success, provides an Access point but no device can connect to the Access Point.


text:
Q: How can I curry a function with optional parameters that generates Js.t objects in ReasionML/BuckleScript? I have the following function
[@bs.obj]
external route:
  (
    ~_method: string,
    ~path: string,
    ~action: list(string) => unit,
    ~options: Js.t({..})=?,
    unit
  ) =>
  _ =
  "";

Since functions can be partially applied, I expect to be able to do this:
let get = route(~_method="GET");

but it gives me this error:
This expression's type contains type variables that can't be generalized:
(~path: string, ~action: list(string) => unit, ~options: {_.. }=?,
unit) =>
{. "_method": string, "action": list(string) => unit,
  "options": Js.undefined({.. }), "path": string}

What am I doing wrong here?

A: This is not actually about the optional parameters and currying, but about value restriction and non-generalized, aka weak, type variables. TL;DR; either turn get into a syntactic function by adding a parameter, e.g., let get () = route(~_method="GET") ();, or create a *.rei interface file for your module.
Longer Story
The .. row variable denotes a polymorphic type that the compiler couldn't reduce to a normal monomorphic type (since there is evidently no usage of this function) nor it can trust that the partial application route(~_method="GET") has not actually already accessed the options parameter and may be stored somewhere in it, which should define the type.
Therefore, the compiler, can't leave it as a polymorphic variable, nor can it give a concrete type, as a result, it produces a weak type variable, which could be seen as a reference cell for the future defined concrete type. Like an uninitialized type. It will be initialized later, by the code that uses the get function. If, at the end of the day, the type is never used, it may escape the scope of the module, which is forbidden by the OCaml/Reason typing rules. Therefore, you shall either give it a monotype manually (i.e., constraint it to some monomorphic type), or create an interface file where this value is hidden (i.e., not present), and therefore couldn't leak the scope of the module. Basically, just creating an empty .mli/.rei file with the same name as your .ml/.re file will resolve this issue. Another common solution is to turn get into a syntactic function, i.e., something with syntactically explicit variables, e.g.,
let get () = route(~_method="GET") ();

Further Reading

*

*https://ocamlverse.github.io/content/weak_type_variables.html

*http://caml.inria.fr/pub/docs/manual-ocaml/polymorphism.html#sec51

*https://v1.realworldocaml.org/v1/en/html/imperative-programming-1.html#side-effects-and-weak-polymorphism


text:
Q: Merge a php array and a php object I want to merge an array like first element to an object like second element.
Is it possible to merge a php object and a php array? If so, How do I merge these?
I have snipped via print_r
First Element (array)
Array
(
    [start_date] => 2014-12-28
)

Second Element (object)
Bannerlookup Object
(
    [_new:CActiveRecord:private] =>
    [_attributes:CActiveRecord:private] => Array
        (
            [id] => 1
            [name] => First Banner
            [description] => My first banner description goes here
            [type] => 1
            [position] => 1
            [price] => 20
            [status] => 1
        )

    [_related:CActiveRecord:private] => Array
        (
        )

    [_c:CActiveRecord:private] =>
    [_pk:CActiveRecord:private] => 1
    [_alias:CActiveRecord:private] => t
    [_errors:CModel:private] => Array
        (
        )

    [_validators:CModel:private] =>
    [_scenario:CModel:private] => update
    [_e:CComponent:private] =>
    [_m:CComponent:private] =>
)

Thanks in advance :)

A: First convert the object to array.
$new_array = json_decode(json_encode($your_object), true);

Now merge it with the existing array.
$merged_array = array_merge( $old_array, $new_array) ;

merging will cause the same key override by the second array. See Array Merge Manual

A: wow you can do this with more readeblilty and much easier like
$combination = CMap::mergeArray($my_array, $my_model->attributes);

every model has a function getAttributes() which will give you an array of models attributes, and then you can use that, no NEED of JSONENCODEDECODEing it :D


text:
Q: namerror when trying to plot return value I am training a GAN and using a function to train the model. For the output, I would like to create lists, losses_G and losses_D, to track performance of the GAN which I can plot (using matplotlib).
def train(self, dataLoader, lr, num_epochs, criterion):

    losses_G = []
    losses_D = []

    for epoch in range(num_epochs):

        running_D_loss = 0
        running_G_loss = 0

        for index, real_X in enumerate(dataLoader):

            # TODO device
            labels = torch.ones(real_X.shape[0], 1)
            self.discriminator.zero_grad()
            real_X = real_X.type(torch.float32)

            # real forward
            output = self.discriminator(real_X)
            error_D_real = criterion(output, labels)
            error_D_real.backward()
            D_x = output.mean().item()

            # fake forward
            labels_fake = torch.zeros(real_X.shape[0], 1)
            noise = torch.randn(real_X.shape[0], 100)
            fake_data = self.generator(noise)
            output = self.discriminator(fake_data.detach().squeeze())

            error_D_fake = criterion(output, labels_fake)
            error_D_fake.backward()
            D_G_z1 = output.mean().item()

            optimizer_D.step()

            # generator
            labels.fill_(1)
            self.generator.zero_grad()

            output = self.discriminator(fake_data)
            error_G = criterion(output, labels)
            D_G_z2 = output.mean().item()
            error_G.backward()

            optimizer_G.step()

            error_D = error_D_real + error_D_fake
            running_D_loss += error_D.item()
            running_G_loss += error_G.item()

            if index % 1 == 0:
                print(f'epoch {epoch + 1}, index {index + 1}: g_loss={running_G_loss:.4f}, d_loss={running_D_loss:.4f}')
                print(f'D(x): {D_x:.3f}, D(G(z)): {D_G_z1:.3f} {D_G_z2:.3f}')
                print()

                #possible point of differences to get code to print losses

        losses_G.append(running_G_loss)
        losses_D.append(running_D_loss)
    return losses_G, losses_D

 x= train (self, dataLoader, lr, num_epochs, criterion)
 print (x)

As a sanity check, I tried to print out the return value of the function but instead of getting the full list for each index that is run, I am only getting the final value.
Any help on this?


text:
Q: stack controls on mobile view Viewing from a desktop my label and two textbox controls are aligned horizontally. However when the user views the site on mobile I would like the textboxes to stack on top of each other. I am using a media query to adjust to a mobile view. All the other lines stack fine (with the textbox under the label) The problem with the address is that I have two textboxes, I would like one on each line. Any suggestions? Any questions let me know thanks
Current CSS
.row { clear: none; width: 100%; overflow: hidden; margin: 5px 0; }
.label { float: left; text-align: right; margin-right: 10px; width: 130px;}
.value { float: left; text-align: left;}

html

            <asp:Label ID="lblSiteAddress" runat="server" Text="Site Address"></asp:Label>

            <asp:TextBox ID="txtSiteAddress" runat="server" Width="192px" Height="22px"></asp:TextBox>
            <asp:TextBox ID="txtSiteAddress2" runat="server" Width="192px" Height="22px"></asp:TextBox>![enter image description here][1]

A: Try this:
.value input[type='text'] {
    display: block;
    clear: both;
    /* Additional style here */
}


text:
Q: Link two visualforce pages with different SObjects? I am pretty new to Visualforce, so I'm sure I'm missing something silly.  Essentially I'm trying to create a "wizard" with visualforce pages for our outside sales team.  I have created a button on the task object that goes to a VF page with four different buttons: New Contact, New Opportunity, New Task, and New Order.
The New Order button links to an external URL, so that was easy and done.  My problem is with the other buttons.  If for example I want to create a new opportunity, I'm having issues with the second VF page (for the new opportunity) linking to the original page, because they are different objects.  When a user clicks on the New Opportunity button on the original VF page, I would like it to go to a new VF page where it asks the user for the information on the opportunity (the name, stage, close date, etc.)  However, when I click on the New Opportunity button, I receive the error "Invalid conversion from runtime type SOBJECT:Opportunity to SOBJECT:Task".  I assume this is because the VF page that the user is sent to when they click the New Opportunity button has a standard controller of Opportunity (when the original VF page had a standard controller of Task).
I have tried changing the standard controller on the New Opportunity VF page to Task, however I am then unable to save my VF page because it has input fields for the Opportunity object (and not the Task object).  I am linking the specific code I'm talking about below.  Any help or advice would be appreciated!
Extension:
public class RouteSalesExtension
{
    private ApexPages.StandardController sc;
    public Opportunity opp1;
    public Task task1 {get; set;}

    public RouteSalesExtension(ApexPages.StandardController standardController)
    {
        this.task1 = (Task)standardController.getRecord();
        sc = standardController;
        task1 = [select ID, Who.ID, What.ID from Task where Id =: ApexPages.currentPage().getParameters().get('id') limit 1];
    }

    public PageReference ToOppPage1()
    {
        return Page.RouteSalesOpp1;
    }

Original VF Page:
<apex:page standardController="Task" extensions="RouteSalesExtension" title="Begin Route Sales">
    <apex:form >
        <apex:pageBlock title="Route Sales Information">
            <apex:pageBlockButtons location="top">
                <apex:commandButton action="{!SetStartTime}" value="Start Meeting"/>
            </apex:pageBlockButtons>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton action="{!ToOrderPage1}" value="New Order"/>
                <apex:commandButton action="{!ToOppPage1}" value="New Opportunity"/>
                <apex:commandButton action="{!ToTaskPage1}" value="New Meeting"/>
                <apex:commandButton action="{!ToContactPage1}" value="New Contact"/>
                <apex:commandButton action="{!CreateOpportunityforOrder}" value="Create Order"/>
            </apex:pageBlockButtons>
        <apex:inputField id="Comments" value="{!Task.Description}"
        label="Meeting Notes"/>
        <apex:outputField value="{!task1.Who.Id}" rendered="false"/>
        <apex:outputField value="{!task1.What.Id}" rendered="false"/>
        <apex:outputField value="{!task1.Id}" rendered="false"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Page that should go to new opportunity but errors out:
<apex:page standardController="Opportunity" extensions="RouteSalesExtension" title="Route Sales Opp">
    <apex:form >
        <apex:pageBlock title="Route Sales Information">
        <apex:inputField value="{!Opportunity.Name}"
        label="Opportunity Name"/>
        <apex:inputField value="{!Opportunity.CloseDate}"
        label="Close Date"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>

A: Revising my answer as I missed this detail
You have two pages for different standradControllers referring to the same extension class:
   <apex:page standardController="Task" extensions="RouteSalesExtension" title="Begin Route Sales">

and
<apex:page standardController="Opportunity" extensions="RouteSalesExtension" title="Route Sales Opp">

The error you are getting is on this line:
this.task1 = (Task)standardController.getRecord();

because when the Opportunity page is displayed, you are casting an Opportunity SObject to a Task
So, how to get around this:
Options

*

*Use separate controllerExtensions, one per SObject

*Use a custom controller (not an extension) that can handle multiple pages such as in a wizard metaphor. Note that this may run into viewstate issues if you have lots of data across all possible pages.  SFDC VF doc has a good example of a wizard flow via a custom controller

*Modify your constructor to examine the ID of the result of getRecord() and cast to the appropriate SObject (Task, Opportunity,...) see here for a somewhat related issue.  You would use the ID method getSobjectType()
Which option to choose is a subject for debate.
Option 1 would tend to be used if you expect to add Sobject-specific behavior over time and want to kepp this all in one class per Sobject
Option 2 would tend to be used when you go back and forth between different pages across some logical transaction.
Option 3 would tend to be used when you are providing common functionality for many SObjects across many VF pages
Of course, there are other patterns and the above is not comprehensive (more based on my experience)
Original answer
Your controller method
public PageReference ToOppPage1()
    {
        return Page.RouteSalesOpp1;
    }

should look like:
public PageReference ToOppPage1()
    {
        PageReference resPg = Page.RouteSalesOpp1;
        resPg.setRedirect(true);
        resPg.getParameters().put('someparm','someparmval');  // if needed
        return resPg;
    }

All that said, you can avoid a lot of this by using the URLFOR function on the commandButton as in :
<apex:commandButton
     action="{!URLFOR($Page.routeSalesOppo1,$ObjectType.Opportunity,[retURL=$Currentpage.URL])}"
     value="New Opportunity"/>


text:
Q: Asana API - Create Webhook I'm trying to create asana webhook through apex.
I keep failing the authentication phase - handshake:

{"errors":[{"message":"Could not complete activation handshake with
  target URL. Please ensure that the receiving server is accepting
  connections and supports SSL","help":"For more information on API
  status codes and how to handle them, read the docs on errors:
  https://asana.com/developers/documentation/getting-started/errors"}]}

I'm missing some thing and not sure what.
I tried to create a class with @RestResource notation for handshake post callback:
@RestResource(urlMapping = '/AsanaWeb/*')
global class asanaCallbackCtrl {

public asanaCallbackCtrl(system.RestRequest req) {

}

@HttpPost
global static void doPost() {
    asanaCallbackCtrl ctrl = new asanaCallbackCtrl(RestContext.request); //asanaCallbackCtrl.newInstance(RestContext.request);
    RestResponse resp  = ctrl.executePost();
    RestContext.response.statusCode   = resp.statusCode;
    RestContext.response.responseBody = resp.responseBody;
   // the record not inserted to database..
   Log__c log = new Log__c();
    log.Body__c = JSON.serialize(resp.responseBody);
    log.Response_Hedears__c =  JSON.serialize(resp.headers);
    log.Staus_Code__c = string.valueOf(resp.statusCode);
    insert log;
}

public RestResponse executePost() {
    RestResponse  resp    = new RestResponse();
    RestResponse res = RestContext.response;

    try {
        Blob targetBlob = Blob.valueOf(res.headers.get('X-Hook-Secret'));
        // Generate SHA1 digest
        Blob hashSHA1 = Crypto.generateDigest('hmacSHA1', targetBlob);
        // For Rackspace Compatiblity encode the binary into BASE 64
        // this will result in 28 chars long string
        String hashBase64SHA1 = EncodingUtil.base64encode (hashSHA1);

        resp.addHeader('X-Hook-Secret', res.headers.get('X-Hook-Secret'));
        // verify the incoming request as legit; throw exception otherwise

        resp.statusCode = 200;
    }

    catch (Exception e) {
        resp.statusCode = 500;// set per doc (403 or 500)

    }

    // persist some log so you have a record of the incoming request
    return resp;
}

/**
 * Create a new task using Asana API
 */
public static HttpResponse createWebhook() {
    object resource = '486792005021811';

    string target = 'https://bringgsb-bringg.cs17.force.com/AsanaWeb/services/apexrest/AsanaWeb/486792005021811';
    NewWebhook newHook = new NewWebhook(resource, target);

    //NewTask newTask = new NewTask(new string[]{'139836167870950'}, '6125975198930', 'Lee Test Api', 'Test Notes');
    String JSONString = JSON.serialize(newHook);
    JSONString = '{"data":' + JSONString + '}';
    HttpResponse res;
    string base64Key = createAuthorizationHeader('0/859eb48d9719099d88cb2cfab4dbcb2e');
    /**
     * API call cannot be made while test class in running.
     * so setting the expected response on which code would run
     */
    if (Test.isRunningTest()) {

    } else {
        res = sendHttp(asanaEndPoint + '/webhooks', 'POST', JSONString  , 'Basic ' + base64Key);
    }
    return res;
}

}
I added this class to my site (Enable apex classes), but not sure if I put the correct url for my target: (i'm running in sandbox)
https://**[siteURL?]**/services/apexrest/**[domainName?]**/AsanaWeb/486792005021811

A: Setting up and debugging webhooks can be tricky
My example below is for Shopify but it may help you in your setup
Site (sandbox) definition:
http://sandboxName-myCompanyName.mysandboxPod.force.com/shopify

or, specifically
http://dev-foocompany.cs79.force.com/shopify

The URL that you place into the webhook originator:
https://dev-foocompany.cs79.force.com/shopify/services/apexrest/shopify/neworder

The essence of the REST class is:
@RestResource(urlMapping='/shopify/*')
    global class ShopifyWebhookResponder
@HttpPost
    global static void doPost() {
      RestResponse resp  = ShopifyWebHookResponder.newInstance(RestContext.request).executePost();
      RestContext.response.statusCode   = resp.statusCode;
      RestContext.response.responseBody = resp.responseBody;
    }

    public RestResponse executePost() {
      RestResponse  resp    = new RestResponse();

      try {
        // verify the incoming request as legit; throw exception otherwise
        resp.responseBody = ... // process the body and build response
        resp.statusCode = 200;
      }

      catch (Exception e) {
        resp.statusCode = // set per doc (403 or 500)
      }

      // persist some log so you have a record of the incoming request
      return resp;
}

The two keys are:

*

*Return the correct HTTP statusCode per the doc of the webhook originator

*Persist to a custom object Log__c (or use Platform Events) everything that happens to your webhook responder as you won't be able to use debug statements as there is no running user to trace.


text:
Q: My tiled map game keeps flickering on the edges of the tiles when the camera moves There is an awful flickering that happens occasionally on my screen from top to bottom. It only happens when the camera moves around (which follows my player character). It does not matter where I am on the map for this to happen. If I stop moving at the right moment, the lines will remain visible until I start moving again. I've added a screenshot so you can see what it looks like:

If you look closely, you might notice that the lines represent a part of my "mountain wall" tile (That tile is used a little bit lower in the map):

I've tried putting the cam.update() in the beginning of the update() method, as some other people on StackOverflow have suggested, but that doesn't seem to work. I have also made sure that there is absolutely no space in between tiles in the tileset image. Most questions I see about this issue experience a different kind of flickering than I am.
Here is the code of my screen and all the rendering that happens:
    public PlayScreen(MyGame game){
        cam = new OrthographicCamera();
        batch = new SpriteBatch();
        gameMap = new TestMap(startMap);
        player = new Player(this);

        Gdx.input.setInputProcessor(this);
    }

    public void update(float delta){
        player.update(delta);

        Rectangle playerRect = player.getNextRectangle(delta);
        Rectangle teleportRect = gameMap.teleportTo(playerRect);

        if(!gameMap.isColliding(playerRect)){
            player.setPosition(playerRect);
        }
        if(teleportRect != null){
            player.setPosition(teleportRect);
        }

        cam.viewportHeight = Gdx.graphics.getHeight() / zoomLevel;
        cam.viewportWidth = Gdx.graphics.getWidth() / zoomLevel;

        cam.position.x = player.getX() + (player.getWidth() / 2);
        cam.position.y = player.getY() + (player.getHeight() / 2);
        cam.update();
    }

    @Override
    public void render(float delta) {
        update(delta);

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        gameMap.render(cam);

        Gdx.graphics.setTitle("FPS: "+Gdx.graphics.getFramesPerSecond());
        gameMap.getMapRenderer().getBatch().begin();
        player.draw(gameMap.getMapRenderer().getBatch());
        gameMap.getMapRenderer().getBatch().end();
    }