text:
Q: How do I convert the google private key for the google calendar api into a env file? I'm trying to use JWT to access the google calendar api. I'm using Node to make my call. How can I get this line of JSON into my .env file:
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADAVznWpHSDMU9JXzBwdm1w4ILex6G8tEdEXa3\nr1YPynJ9aT9tPgrDXXnwMMrRd8q2Kvkqi6WaYMkCgYAvSsRQWuOGEkxVRkKG2VHYNW+XzMaiiHmUznfll/5\nsmYDwtRzhqN9eAsEjfj2K99lcJnd8fCKib5a5Ga+kgSBb64jrj9UOJUbOZJDVh4/\nckglGM61BAR+gdl3tCXY4w==\n-----END PRIVATE KEY-----\n"

(I shortened the key in this post to keep it safe and to keep this post clean).
I'm following this guide on setting up jwt to access the google calendar api: https://dev.to/megazear7/google-calendar-api-integration-made-easy-2a68
I can get it to work fine if I have the key as a string in the index.js file like this:
const GOOGLE_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADAVznWpHSDMU9JXzBwdm1w4ILex6G8tEdEXa3\nr1YPynJ9aT9tPgrDXXnwMMrRd8q2Kvkqi6WaYMkCgYAvSsRQWuOGEkxVRkKG2VHYNW+XzMaiiHmUznfll/5\nsmYDwtRzhqN9eAsEjfj2K99lcJnd8fCKib5a5Ga+kgSBb64jrj9UOJUbOZJDVh4/\nckglGM61BAR+gdl3tCXY4w==\n-----END PRIVATE KEY-----\n"

But when I try to set this key in my .env file, like this:
GOOGLE_PRIVATE_KEY = -----BEGIN PRIVATE KEY-----\nMIIEvAIBADAVznWpHSDMU9JXzBwdm1w4ILex6G8tEdEXa3\nr1YPynJ9aT9tPgrDXXnwMMrRd8q2Kvkqi6WaYMkCgYAvSsRQWuOGEkxVRkKG2VHYNW+XzMaiiHmUznfll/5\nsmYDwtRzhqN9eAsEjfj2K99lcJnd8fCKib5a5Ga+kgSBb64jrj9UOJUbOZJDVh4/\nckglGM61BAR+gdl3tCXY4w==\n-----END PRIVATE KEY-----\n

and then access it in my index.js file like this:
const GOOGLE_PRIVATE_KEY = process.env.GOOGLE_PRIVATE_KEY

I get this error:
{"errors":{"library":"PEM routines","function":"get_name","reason":"no start line","code":"ERR_OSSL_PEM_NO_START_LINE"}}

Any thoughts? :)

A: When you put your key on .env, extra slashes are added on the string.
process.env.GOOGLE_PRIVATE_KEY.replace(new RegExp("\\\\n", "\g"), "\n")

This will fix it.


text:
Q: awk compare value with a input can a user input variable($userinput) compare with a value?
awk -F:  '$1 < $userinput { printf .... }'

This comparison expression seems ok to me, but it gives an error?

A: Try doing this :
awk -vuserinput="$userinput" -F: '$1 < userinput {}'

A real example :
read -p "Give me an integer >>> " int
awk -v input=$int '$1 < input {print $1, "is less than", input}' <<< 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Highcharts: min value of y axis on the bottom of chart I would like some help with this chart. If the series values are not 0.0, the minimum value of the chart is 0, and it's correctly on the bottom of the chart:
But if the values are all equal to 0.0, the y-axis line is shown in the middle of the chart:
I try to set
 {min: 0,}

on the y-axis, but it doesn't work. Obviously I can't set a max value because I have a dynamic data. How can I solve this?

A: If you can't set a max, you can set a minRange
yAxis: [{ // Primary yAxis
            min: 0,
            minRange: 0.1,

http://jsfiddle.net/tZayD/


text:
Q: Json to treeview (
*) I get the following data back from my WCF Data Service (I cut out the metadata)
{
  "d": [{
      "CodeId": 6,
      "Title": "A Child Sub Item",
      "Parent":
    },
    {
      "CodeId": 5,
      "Title": "Another Root Item",
      "Parent": -1
    },
    {
      "CodeId": 4,
      "Title": "Child Item",
      "Parent": 2
    },
    {
      "CodeId": 2,
      "Title": "Root Item",
      "Parent": -1
    }
  ]
}

I am trying to get this into a <ul> style tree with Parent = -1 as root and then the rest as sub items of their parent id's.
Can anyone help me please, preferably in jQuery?  I will use this in jstree if someone knows of a better way to do this.
Thanks

A: *

*Loop through those objects and convert them to the type jstree likes, while storing them in another object with CodeId as the key and the object as the value. Remember to preserve the Parent attribute

*Loop through the object you just created, and for each item:

*

*If it's a root node, add it into a list

*If it's not a root node, look up its parent from the object and add it to the parent's child collection

*Feed the list you created in 3.1. into jstree


text:
Q: Add a new column with tag attached to crescent numbers I would like to add a new collumn giving a constant tag with anexed with a crescent numbers logic, line after line.
My input:
position  work

chr1    jil2001
chr4    jil2001
chr3    kou2009
chr9    nai2012
chr7    fandis2005

My expected output:
position  work    tag

chr1    jil2001  Known1
chr4    jil2001  Known2
chr3    kou2009  Known3
chr9    nai2012  Known4
chr7    fan2005  Known5

Cheers!

A: You can create the new column manually;
df$tag <- paste0("Known", seq_len(nrow(df)))


text:
Q: jquery plugin(Impromptu) i am wondering, how can i use this plugin in my html?
$.prompt("Open your javascript console to see the answer.", {
title: "Are you Ready?",
buttons: { "Yes, I'm Ready": true, "No, Lets Wait": false },
submit: function(e,v,m,f){
    // use e.preventDefault() to prevent closing when needed or return false.
    // e.preventDefault();

    console.log("Value clicked was: "+ v);
}
});

that code was from http://trentrichardson.com/Impromptu/

A: I use that library and it's work.
Include library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://trentrichardson.com/Impromptu/jquery-impromptu.js"></script>

CSS:
<link href="http://trentrichardson.com/Impromptu/jquery-impromptu.css" rel="stylesheet" type="text/css" >

Write script:
<script type="text/javascript">
var multiplePromptsCounter = 1;

function openMultiplePrompts(){

    $.prompt("Do you want to open another?", {
        title: "A Prompt Has Opened: "+ multiplePromptsCounter++,
        buttons: { "Yes, Open Another": true, "No, Close This One": false },
        persistent: false,
        submit: function(e,v,m,f){
            if(v){
                e.preventDefault();
                openMultiplePrompts();
            }
        }
    });
}
 </script>

HTML:
<div class="buttons">
<button class="run" onclick="openMultiplePrompts()" >Run It!</button>
</div>

Hope it help you.


text:
Q: Default shipping Hi I have 2 shipping method

*

*free shipping

*USA shipping (This shipping method I have created)

now I want to add default shipping method to the cart is USA shipping, I did that , but when we come to checkout ant change the shipping method so shipping method is not changing can any one help me
I want once user will add a cart in item then default shipping will be USA shipping but on checkout user have 2 options and they can select any of them.


text:
Q: Server fails to start due to java.lang.NoClassDefFoundError I'm trying to start my tomcat server but it fails and gives me
org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.apache.logging.log4j.web.Log4jServletContextListener]
 java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/util/SetUtils

I'm using gradle and I have
dependencies{
...
    implementation 'org.apache.logging.log4j:log4j-core:2.12.2'
    implementation 'org.apache.logging.log4j:log4j-web:2.12.2'
...
}

I have Log4jServletContextListener configued in web.xml as
...
    <context-param>
        <param-name>isLog4jAutoInitializationDisabled</param-name>
        <param-value>true</param-value>
    </context-param>

    <listener>
        <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
    </listener>
...

Here is the complete error
12-Nov-2022 13:11:37.918 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 1 Spring WebApplicationInitializers detected on classpath
12-Nov-2022 13:11:37.981 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.apache.logging.log4j.web.Log4jServletContextListener]
 java.lang.NoClassDefFoundError: org/apache/logging/log4j/core/util/SetUtils
    at org.apache.logging.log4j.web.Log4jWebInitializerImpl.getConfigURI(Log4jWebInitializerImpl.java:196)
    at org.apache.logging.log4j.web.Log4jWebInitializerImpl.initializeNonJndi(Log4jWebInitializerImpl.java:175)
    at org.apache.logging.log4j.web.Log4jWebInitializerImpl.start(Log4jWebInitializerImpl.java:112)
    at org.apache.logging.log4j.web.Log4jServletContextListener.contextInitialized(Log4jServletContextListener.java:64)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4745)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5207)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:986)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.core.util.SetUtils
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1291)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
    ... 17 more

Not sure how to resolve this error


text:
Q: Memory problems trying to convert a large csv file to a raster layer using R I have a large CSV file representation of a geographic raster map - 42011 columns by 18510 rows, around 10GB on disk. The file was created as the output of a convolution using the FFT function, which involved breaking the original raster into six strips, processing each and appending the resulting matrix to the csv file using the overlap-add method.
I am now trying to write the results back to a raster file type (e.g. ESRI bil, GeoTIFF etc) using the R package  raster. Each number in the CSV file maps to the equivalent cell of the raster.
The obvious way to do this in R is:
library(raster)
library(data.table)
data <- fread("data.csv")                                  ## Read in data (as data.table)
data_mat <- data.matrix(data)                              ## Convert to matrix
data_raster <- raster(data_mat, template=existing_raster)  ## Write to raster using existing layer as template

However, my PC runs out of memory at the stage of trying to create the matrix:
Error: cannot allocate vector of size 5.8 Gb
In addition: Warning messages:
1: In matrix(if (intOK) NA_integer_ else NA_real_, nrow = d[1L], ncol = d[2L],  :
   Reached total allocation of 16108Mb: see help(memory.size)
etc

The computer is running 64-bit R with 16GB of RAM.
Things I've tried so far include:

*

*bigmemory - this looked promising, as the raster function can take a big.matrix as it's input, but the package is not currently available for windows.

*ff - I haven't fully grasped the capabilities of this package so far, but at present I can't see a way to get from the data.table to an ff object, and I'm not sure there would then be a way to get from that to a raster layer.

*Sparse matrices (using package "Matrix") - the CSV is probably more than 50% 0s. However, I can't currently work out a way to read it from disk as a sparse matrix, or to get it from a data.table into a sparse matrix. Whether I would then be able to get to a raster, I have no idea.
I am most familiar with R, but also have a working knowledge of Python and access to ArcGIS. I'm not sure if the question is better here or on gis.stackexchange, but it seems like primarily a programming problem. Any suggestions gratefully received!

A: Big matrices have always been problems in R. I'm not familiar with geographic raster map. But is it possible to partition your data frame to pieces and generate matrices in a way that does not lose information?
"ff" packages could be of help. I found a related tutorial here, it shows a lot of examples of using "ff" package for large object. Specifically, page 20, "working with array and matrices", hopefully it helps.ff packages examples


text:
Q: Smallest interval whose sum exceeds a threshold In a non-negative 1D array x, we wish to find the shortest slice such that x[start:end].sum() > threshold, with the optional constraint that start <= argmax(x) < end. Must work with floats and integers.
Is there a known algorithm to accomplish this? I have implemented one here, but it's not as fast as I wish, and ideally there shouldn't be a heavyweight dependency (e.g. numba). Example:
x = [0, 1, 2, 3, 4, 9, 7, 1, 0, 0, 0]
threshold = 3 + 4 + 9 + 7 - .01

start, end = func(x, threshold)
print(x[start:end])

[3 4 9 7]

@גלעד ברקן's answer is acceptably fast in numba; my implem. Though, non-numba is strongly preferred, meaning minimizing if, for, etc - unless someone can point to a lightweight numba...

A: This reminds me of the problem of finding the smallest window that includes all members of a set, which can be solved in O(n) time and O(k) space with two pointers. In our case, O(1) space would seem to be enough since we're only interested in a sum.
Move the right pointer until the sum is achieved. Move the left pointer just until the sum is again too low. Then move the right pointer, etc. Addressing the argmax constraint left to the reader.

A: Just my few cents:

*

*Because the array is non-negative the list containing running sum at each index is already a sorted list.

*Compute running sum at each index and construct a list of tuples (running_sum, current_index).

*If the running sum at an index exceeds the threshold look for the greatest value that is less than (running_sum - threshold) in the list of running sums excluding the one at current index using binary search

*Now the current range is the [index_found_by_binary_search+1, curr_index]

*Minimize upon all such ranges.
In your example:
the running sum is: [0, 1, 3, 6, 10, 19, 26, 27, 27, 27, 27]
The sum(26) exceeds threshold of 22.99 at index = 6
Now difference between threshold and sum is 26 - 22.99 = 3.01.
Look for the greatest value that is smaller than 3.01 - this can be done by binary search.
We need greatest value because we want to minimize the range.
The greatest value is 3 that is smaller than 3.01 and can be found at index 2.
The result is the range [2+1, 6] = [3,6]
Now do this all along the array and minimize upon the length of the range.
Not sure if that is what you already did.

A: Thanks to @גלעד ברקן for the pointers. Numba/plain Python is here (just add @jit), with greedy validation, and below's Cython (numpy tutorial), which equals Numba's speed on float64 and is 10% faster for float32 when len(x)=1e6. They're x10 faster than the fastest numpy-vectorized implem I could come up with.
Note, for float32 and long sequences, it suffers from roundoff imprecision, and instead one should compute the sum as (though it's slower):
cs = np.hstack([0., np.cumsum(x)])
sm = cs[end] - cs[start]

import cython

float_int = cython.fused_type(cython.floating, cython.integral)

@cython.wraparound(False)
cpdef int smallest_interval_over_threshold(float_int[:] x, float_int threshold):
    cdef Py_ssize_t N = x.shape[0]
    cdef float_int[:] x_view = x

    cdef Py_ssize_t left = 0
    cdef Py_ssize_t right = 1
    cdef Py_ssize_t min_size = N
    cdef float_int sm = x_view[left]

    while right < N:
        if sm > threshold:
            min_size = min(min_size, right - left)
            sm -= x_view[left]
            left += 1
        else:
            sm += x_view[right]
            right += 1

    while left < N and sm > threshold:
        min_size = min(min_size, right - left)
        sm -= x[left]
        left += 1

    cdef int min_size_int = <int>min_size
    return min_size_int

The argmax constraint is easily satisfied by bounding left and right appropriately, and of course we can fetch the exact indices easily once we know the right interval. Unlike Numba, Cython's lightweight while retaining Python's syntax minus typing (at least for my case).


text:
Q: SharePoint get "Modified By" field from Library using REST API I want to retrieve the OOTB Modified By value using REST API.
I tried the below options in my REST Query:
Editor/Title&$expand=Modified By
Editor/Title&$expand=Editor

I am getting the error : The expression "Modified By" is not valid.
Please suggest how to achieve this?
To check the "Modified By" field name , I have queried all fields using below request:
https://servername/_api/web/lists/getbytitle('MyLibrary')/Fields?$select=Title,InternalName

Here's the response for "Modified By":
<d:InternalName>Editor</d:InternalName><d:Title>Modified By</d:Title>

Please help me here!
Thanks!

A: You can use below syntax
$select=Editor/Title&$expand=Editor/Id

You query will turn into
https://servername/_api/web/lists/getbytitle('MyLibrary')/Items?$select=Title,InternalName,Editor/Title&$expand=Editor/Id

A: You need to use expand with the this Editor field.
In the $expand, you should specify the person field you want to expand.
$select=Editor/Title&$expand=Editor
Try below query:
https://servername/_api/web/lists/getbytitle('MyLibrary')/fields?$select=Title,InternalName,Editor/Title&$expand=Editor


text:
Q: Why doesn't gdb see when `stdio` is changed? According to the GNU C library it's allowed to assign to stdio just as if they were ordinary variables (I know this is an extension). I tried following program:
#include <stdio.h>
int main()
{
    stdout = NULL;

    printf("Crash and %s\n", "burn");

    return 0;
}

When running the program it will segfault as expected, but when I run it in gdb the value of stdout is still not NULL:
_IO_vfprintf_internal (s=0x0, format=0x400631 "Crash and %s\n",    ap=0x7fffffffe210) at vfprintf.c:1297
1297    vfprintf.c: No such file or directory.
(gdb) print stdout
$1 = (struct _IO_FILE *) 0x7ffff7dd77a0
(gdb)

Why doesn't gdb report the correct value of stdout?
Investigating this further I see that it seem to store stdout at address 0x600940, looking for a struct _IO_FILE* there I'd find a pointer that's the same as gdb reports as stdio:
(gdb) print stdout
$1 = (struct _IO_FILE *) 0x7ffff7dd77a0
(gdb) print (void*)0x600940
$2 = (void *) 0x600940
(gdb) print (struct _IO_FILE*)0x600940
$3 = (struct _IO_FILE *) 0x600940
(gdb) print *(struct _IO_FILE**)0x600940
$4 = (struct _IO_FILE *) 0x7ffff7dd77a0
(gdb) n
7       puts("Crash and burn");
(gdb) print *(struct _IO_FILE**)0x600940
$5 = (struct _IO_FILE *) 0x0
(gdb) print &stdio
No symbol "stdio" in current context.
(gdb) print &stdout
$6 = (struct _IO_FILE **) 0x7ffff7dd7d90

Here it looks like gdb think that stdout is located at 0x7ffff7dd7d90, but in reality it's located at 0x600940.
I'm using GNU gdb (GDB) 7.4.1-debian and gcc version 4.7.2 (Debian 4.7.2-5) (x86-64).

A: I think that your gdb is functioning correctly.  Look at these lines you quoted:
_IO_vfprintf_internal (s=0x0, format=0x400631 "Crash and %s\n",    ap=0x7fffffffe210) at vfprintf.c:1297
1297    vfprintf.c: No such file or directory.
(gdb) print stdout
$1 = (struct _IO_FILE *) 0x7ffff7dd77a0
(gdb)

The signature of _IO_vfprintf_internal() has the destination stream s as the first parameter.  Because you are in a different level of your stack and stdout is not a global variable, it get re-assigned.  But you can see that your assignment took hold because s=0x0.


text:
Q: Correct update logic I have an application which has a database. DB is updated downloading from the server xml.I want to understand the logic of the update. My ways I was not correct.Here are my ways:

*

*You use a single link to Xml. Xml will be updated. It will only store a new record.
Outcome: user missed what the update does not get it.

*Each xml will hold a reference to the following xml. Outcome: user missed a lot of xml will have the download process and will not know when will the update.

*Xml will store all the records for all the time, but then after a while it becomes very large. Result of heavy traffic
Please tell me the correct update logic.

A: The best way would be to put some logic on your the server:

*

*Application asks the server for updates, sending current database version as a parameters

*Server check the application database version against the latest one, and compute the list of changes that occured

*Server reply to the application by sending all theses changes, so the application can update its database content (along with its database version)

A: I would go this way.

*

*I would keep track of the updating process. like saving last updated date or else a version of update.

*When I send the request to the server I would send this date or the version number along with the request (POST or GET method).

*Now depending on the date or version I would get the XML file from the server. Then I will update the contents.

*If user is new then there will be no date or version parameter sent to server. Then the complete XML would come. If they will to update from first, then you can go with updating part by part with your own way(like regular intervals of time) till the current version of update is reached if you concern about traffic.Then from there you can continue. Again you can keep track of date or version number and start updating process as usual.


text:
Q: How should I design my relational tables? I am curious to the practicality of structuring my database. Imagine I want to conduct a survey, asking a group of students what are their top 3 preferences out of 10 options. The objective is to find out ranking of the 10 options by looking at the count of students' choices.
Initially, my thought process is to create the following relational tables.
CREATE TABLE person (
    personID BIGSERIAL NOT NULL PRIMARY KEY,
    personName VARCHAR(50));

CREATE TABLE preference (
    preferenceID BIGSERIAL NOT NULL PRIMARY KEY,
    personID INT REFERENCES person(personID),
    preference1 VARCHAR(50),
    preference2 VARCHAR(50),
    preference3 VARCHAR(50));

But I begin to stumble on achieving my objective. Since the count of each preference has to be considered in all 3 columns, my current solution is to then manipulate my data (using Excel) until I have the following table:
CREATE TABLE preferenceV2 (
    personID INT,
    preference VARCHAR(50));

Here, personID is no longer PK nor is it unique, and preference can be either of the 10 options. Now, I can achieve my objective by counting the number of votes for each preference and rank them accordingly (through use of PowerBI for example).
However, I realised I end up not leveraging on relational database and the process of manipulating into table preferenceV2 is manual and prone to errors. What should be the best way for me to approach this?

A: You should have:
CREATE TABLE preferences (
    preferenceID BIGSERIAL NOT NULL PRIMARY KEY,
    personID INT REFERENCES person(personID),
    preference VARCHAR(50)

So if one person have 3 preference you would have
   preferenceID personID preference
        1          1         A
        2          1         B
        3          1         C
        4          2         B
        5          2         C
        6          2         D

In this case you can do
  SELECT preference, COUNT(preference)
  FROM preferences
  GROUP BY preference


text:
Q: How to distribute python module under a specific name I have python module, named models.py which i would like to upload to PyPi. When afterwards i install it using pip i would like it to appear as a package.
To explain myself, I have following project structure:
my_utils
  mapper/
    models.py
    MANIFEST.in
    setup.py
    README
  logger/
    logger.py
    logger_conf.json
    MANIFEST.in
    README
    setup.py

I would like to create a distributed package out mapper.models, but when it is being installed on target machine, i would like it to appear in site-packages under mapper_tools.models.
My setup.py:
from distutils.core import setup

setup(
    name='mapper_tools',
    version='0.1.0',
    description='some description',
    author='myname',
    author_email='my@email.com',
    url='https://github.com/mapper-tools',
    py_modules=['models'],
)

My MANIFEST.in:
include models.py README

Currently, after running pip install mapper-tools, I find models.py right under site-packages and I would like it to appear under mapper_tools.
Can i specify the structure that should be installed without changing the layout of my project?


text:
Q: Laravel passport send dynamic token scopes in oauth/token API I have user_master table, role_master table and a child table called user_roles which have references of user id and role id which indicates which user belongs to which role.
I have one more permission table which indicates which permissions belong to which roles.
For example:

user master table:
id           user_master     password
1            John                 some_md5
2            Jane                 some_md5

role_master table:
id           role_name
1           Administrator
2           Data entry operator

user_roles:
id           user_id          role_id
1             1                    1
2             2                    2

permissions:
id           permission_name           role_id
1           content.create                 1
2           content.create                 2
3           content.delete                    1
In Laravel passport token scope doc, its mentioned that we can pass the token scopes in AuthServiceProvider. But in this case, the roles and permissions scope are dynamic so is it best practice to load them in AuthServiceProvider from database table?
And in oauth/token API, we are supposed to pass the scope. But as per this dynamic example, we can not pass * as scope because some roles have limited accessibility and some roles can access everything. So once we have user name and password sent as POST from web/mobile applications, then how we can pass the scope because before oauth/token triggers, we will not have user roles and scope information.
Any help really appreciated. Thanks!


text:
Q: Sendgrid each markup is not working with table tag I'm creating a dynamic template in Sendgrid and I tried to use the each markup with this code:

{{#each data}}

{{this.name}}

{{/each}}

But when I saved this template the code is converted to:
{{#each data}}
{{/each}}

{{this.name}}

This happens only with table tag, when I tried to use each with other tags, like p and b this error doesn't happens.
Do you know what happens? How could I fix it?

A: This one is answered here: In Sendgrid Design template, how to use handlebar iteration for table?
There's an undocumented workaround that can be used, check the duplicate.

A: I receive this answer from sendgrid support
Good afternoon,
Thank you for contacting SendGrid Support! I would be happy to help you!
Thank you for going into depth with that example, that is very helpful. Just to clarify what you are seeing is when you are creating this template you are creating it in the design editor and the **** statement to end the conditional statement that it is being moved to the top is that correct? If so this is currently a bug that our engineers are aware of in the design editor so what I suggest when using dynamic templates with conditional statements is using strictly the code editor and not the design editor at all. Hopefully in the future this bug will be fixed in the design editor but unfortunately I do not have a time frame on this and recommend using the code editor. Also when I say code editor I do not mean creating a code module in a design template, I recommend creating the whole template in the code editor.
I look forward to hearing back from you


text:
Q: Codeigniter Updating Edit Page I have created an edit page which repopulates their information into the correct fields (based on the ID) and they can amend the details...
What I want now is for the Submit button to update this information in the database table?
This is the Edit Section in my Controller:
function edit($id = 0){

    $this->load->model('blogmodel');

if( $this->input->post() ){ #if form submitted

    $data   = array();

    $id     = $this->input->post('id'); #to be used in the where clause for updation

    $data['name'] = $this->input->post('name');
    $data['address'] = $this->input->post('address');
    $data['sEmail'] = $this->input->post('sEmail');

    $this->blogmodel->update_blog($data,$id);

}else{

    // Form Validation required
    $this->load->library('form_validation');

    $this->form_validation->set_rules('name', 'Name', 'required');
    $this->form_validation->set_rules('address', 'Address', 'required');
    $this->form_validation->set_rules('sEmail', 'Sender Email', 'required|valid_email');

    $this->form_validation->set_message('required', '%s is required');
    $this->form_validation->set_error_delimiters('', '
');

    $sql  = 'SELECT * FROM databse.blogs WHERE id = ?';

    echo $sql . ' - '. $id;
    $sql_params = array($id);
    $query = $this->db->query($sql, $sql_params);
    $form = $query->row_array();

    //$date['form'] = $form;

    $data['inputs'] = array('name' => $form['name'],
                            'address' => $form['address'],
                            'semail' => $form['email'],
                            'nickname' => $form
    );

    $data['Name']= $form['name'];
    $data['Address']= $form['address'];
    $data['Email']= $form['email'];

    $this->load->view('blog_content',$data);

    $data = $this->input->post();
    $result = $this->blogmodel->update_blog($data,$id);
    $this->load->view('blog_success');

}

}
}

So Far this is my Model:
function send_blog(&$data){

    $data['name'] = $this->input->post('name');
    $data['address'] = $this->input->post('address');
    $data['sEmail'] = $this->input->post('sEmail');

    $sql = "UPDATE database.blogs (name, address, email) WHERE id = $id
    VALUES (".$this->db->escape($data['name']).",
            ".$this->db->escape($data['address']).",
            '".$data['sEmail']."');";

    $this->db->query($sql);

}

function update(&$data,$id){

    $data['name'] = $this->input->post('name');
    $data['address'] = $this->input->post('address');
    $data['sEmail'] = $this->input->post('sEmail');

    $this->db->where('id', $this->input->post('id'));
    $this->db->update('blog', $data);
}
   }

A: What is the current_url() here? I'm guessing it to be function edit(). In your function edit just do the below changes:
function edit($id = 0){
    if( $this->input->post() ){ #if form submitted
        $data   = array();
        $id     = $this->input->post('id'); #to be used in the where clause for updation
        /*
            Retrieve all the post variables in the $data and send to model for updation
        */
        $this->your_model->update_function( $data, $id );
        redirect('controller/edit/'.$id, 'refresh'); #redirect to the same function to show the form or success page
    }else{
        /*
        Your rest of the function as it is
        */
    }
}

Update
Your controller changes:
function edit($id = 0){
    if( $this->input->post() ){ #if form submitted

        $data   = array();

        $id     = $this->input->post('id'); #to be used in the where clause for updation

        $data['name']           = $this->input->post('name');
        $data['address']        = $this->input->post('address');
        $data['sEmail']         = $this->input->post('sEmail');
        $data['nickname']       = $this->input->post('nickname');
        $data['blogregion']     = $this->input->post('blogregion');
        $data['startdate']      = $this->input->post('startdate');
        $data['blogtitle']      = $this->input->post('blogtitle');
        $data['timesperweek']   = $this->input->post('timesperweek');
        $data['profiletext']    = $this->input->post('profiletext');
        $data['abouttext']      = $this->input->post('abouttext');
        $data['status']         = 0;
        $data['userid']         = $id;

        $this->newblogsetupmodel->update_blogforus( $data, $id );

        redirect('newblogsetup/edit/'.$id, 'refresh'); #redirect to the same function to show the form or success page

    }else{
        #rest of the controller here
    }
}

Your model changes:
function update_blogforus($data, $id){
    echo "
";print_r( $data );die; #to print the data received from controller, see if its coming okay or make correction in the controller for the same
    /*$data['name']           = $data['name'];
    $data['address']        = $data['address'];
    $data['sEmail']         = $data['sEmail'];
    $data['nickname']       = $data['nickname'];
    $data['blogregion']     = $data['blogregion'];
    $data['startdate']      = $data['startdate'];
    $data['blogtitle']      = $data['blogtitle'];
    $data['timesperweek']   = $data['timesperweek'];
    $data['profiletext']    = $data['profiletext'];
    $data['abouttext']      = $data['abouttext'];
    $data['status']         = 0;
    //$data['userid'] = $data['user']->id;
    */
    $this->db->where('id', $id);
    $this->db->update('newblogsetup', $data);
    echo $this->db->last_qeury();die; #to see the query being executed, run it in your phpMyadmin and see if its updating as required.
}

New Changes
Controller:
$data['id'] = $id;  #save the data in an element to echo in the hidden field of the form
$this->load->view('newblogsetup_sent', $data); #load the data to the page

In your edit page change this line
<?php echo form_hidden('id');?>

To:
<?php echo form_hidden( 'id', $id );?>


text:
Q: SQL. Get samples of data in group query I have a simple table with only 2 columns:
| name | domain |

I need a SQL query to get this data:
| domain | names count | sample name 1 | ...2 | ...3 | ...4 | ...5 |

So, the first part is simple, just grouping by domain and getting names count. But the second part, where I need to take 5 samples (they can be random) of names in the group - I have no idea how to resolve it.

A: You can use window functions and aggregation:
select
    domain,
    count(*) names_count,
    max(case when rn = 1 then name end) sample_name_1,
    max(case when rn = 2 then name end) sample_name_2,
    max(case when rn = 3 then name end) sample_name_3,
    max(case when rn = 4 then name end) sample_name_4,
    max(case when rn = 5 then name end) sample_name_5
from (
    select t.*, row_number() over(partition by domaine order by rand()) rn
    from mytable t
) t
group by domain

The subquery ranks names having the same domain randomly. Then, the outer query aggregates by domain, and uses conditional aggregation to bring the first 5 randomly ranked names per group.

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT domain, names_count,
  samples[OFFSET(0)] AS sample_name_1,
  samples[SAFE_OFFSET(1)] AS sample_name_2,
  samples[SAFE_OFFSET(2)] AS sample_name_3,
  samples[SAFE_OFFSET(3)] AS sample_name_4,
  samples[SAFE_OFFSET(4)] AS sample_name_5
FROM (
  SELECT domain,
    COUNT(name) names_count,
    ARRAY_AGG(name ORDER BY RAND() LIMIT 5) samples
  FROM `project.dataset.table`
  GROUP BY domain
)


text:
Q: Meteor (React) : Access Local Package component in Meteor App Migrating from blaze to react.I have written one Local Package in meteor-react. And added it in my project using command "meteor add package_name" successfully. I wants to use(in router/call components in jsx) the package components which are define in local package. In blaze it was easy one has to just write template name {{> template_name}}. But in react I have no idea about it. How to do that? Thanks in advance!

A: If you exported the react component from your local package like e.g. in /packages/your_local_package_name/index.js you wrote export { ComponentName } from './theFileYouDefinedItIn.js'; then it's as easy as writing:
import { ComponentName } from 'meteor/your_meteor_username:your_local_package_name';

But it really depends on how you exported the component. These might be helpful resources: https://guide.meteor.com/structure.html#meteor-structure and https://docs.meteor.com/api/packagejs.html


text:
Q: How can i pass multiple parameters in location.href in php? example (this is not working)
location.href = 'freecreate?fname=+fname+"&Mnumber="+Mnumber+"&sitename="+sitename';

A: Add double quotes(") after fname= , Use this:
location.href = "freecreate?fname="+fname+"&Mnumber="+Mnumber+"&sitename="+sitename;

A: If you are working with php variables just Declare them,
assign values and append them
using . operator
See the example below:
<?php

    $fname="bhansa";
    $Mnumber ="number";
    $sitename ="stack";
    echo "<script>window.location = 'freecreate?fname=".$fname."+&Mnumber=".$Mnumber."+&sitename=".$sitename."'</script>";

?>

Use @Dhara Parmar's method if you want to use in javascript.


text:
Q: Как сканировать файл txt из jar-файла Я хочу считать текст с файла output.txt и вывести его через JOptionPane, но, естественно, он не считывается. Не могли бы вы намекнуть, как использовать файл из jar?
Файл существует в jar файле:

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class HelloWorld {
    public static void main(String[] args) throws IOException {
        Scanner my = new Scanner(new File("output.txt"));
        String result = my.nextLine();
        JOptionPane.showConfirmDialog(null, result);
    }
}

A: Если текстовый файл находится в том же jar-файле, который запускается, для его чтения следует использовать не File, а InputStream, который следует получить при помощи метода ClassLoader::getResourceAsStream.  При условии, что файл output.txt находится в корне jar-файла, можно использовать Thread.currentThread().getContextClassLoader().getResourceAsStream("output.txt") или getClass().getResourceAsStream("/output.txt").
Также стоит использовать try-with-resources для автоматического закрытия сканера/потока ввода.
import javax.swing.*;
import java.io.*;
import java.util.*;

public class HelloWorld {
    public static void main(String[] args) throws IOException {
        try (Scanner my = new Scanner(Thread.currentThread()
                .getContextClassLoader().getResourceAsStream("output.txt"))
        ) {
            String result = my.nextLine();
            JOptionPane.showConfirmDialog(null, result);
        };
    }
}

A: Вытащить файл из jar-архива и положить его в папку с проектом. Лучше положить в корневой каталог, чтобы лучше было считывать от туда.
Структура jar это упакованный архив в zip формате. Поэтому читать файл из него можно только если использовать этот протокол. Можно также читать специальный URL, который поддерживает этот формат.
jar:file://файл.jar!/output.txt

Подробнее о jar файлах можно прочитать в Java Tutorial.


text:
Q: Can I move appsettings.json out of the app directory? I want to put my appsettings.json file outside of the web folder so that I can avoid storing it in source control. How can I do this?

A: If you truly don't want it in your source control, the best advice is to keep it where it is and simply add it to the ignores for your source control, so it's never committed, as @PmanAce suggested.
However, I personally think files like appsettings.json should be committed. They essentially serve to document the configuration necessary for the application. Without that as a guide, how is any one supposed to know what should go in the appsettings.json they'll have to create because it won't be included in the pull from your source control?
That said, there is the issue of storing sensitive data to think about. However, there's other ways around this. You can use other means of configuration such as environment variables and/or user secrets to override anything in appsettings.json. Therefore, for things like connection strings, provide a placeholder in your appsettings.json so it's self-documenting that a value for that needs to be provided, but for your own personal use, utilize user secrets and/or environment variables to override that value with something real. That way, you can freely and safely commit appsettings.json, fully documenting what settings are necessary for your application, without worry that personal or secret information is being included with it.

A: It doesn't like relative paths, it seems. But, this works...
public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            if (!hostingContext.HostingEnvironment.IsDevelopment())
            {
                var parentDir = Directory.GetParent(hostingContext.HostingEnvironment.ContentRootPath);
                var path = string.Concat(parentDir.FullName, "\\config\\appsettings.json");

                config.AddJsonFile(path, optional: false, reloadOnChange: true);
            }
        })
        .UseStartup<Startup>()
        .Build();

So, it's another settings file on top of the sources added by default.

A: For .Net Core 6 i had to set root folder before i could change app configuration as posted by @ian-warburton, because if not it throws the error:

System.NotSupportedException: The web root changed from
"C:\app\wwwroot" to "C:\app". Changing the host configuration using
WebApplicationBuilder.WebHost is not supported. Use
WebApplication.CreateBuilder(WebApplicationOptions) instead.

The folder were the app will run is the current working directory.
It is valid for running from visual studio and docker container with the standard Dockerfile, at least.
const string ConfigFolder = "./Config"; //can be relative or fullpath
IConfiguration configuration = null; //so it can be used on other configuration functions bellow

//create the WebApplication on the current folder
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args =args,
     WebRootPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "wwwroot")), //point where if serving static files from default location. Works for my case. May need some adjustments in other cases.

});

//load config file, build it, give it to WebApplication and keep the config variable for further use.
builder.WebHost.ConfigureAppConfiguration(
    (hostingContext, config) =>
        {
            var path = Path.Combine( ConfigFolder, "appsettings.json");

            config.AddJsonFile(path, optional: false, reloadOnChange: true);
            config.AddEnvironmentVariables();
            configuration = config.Build();
        });


text:
Q: Highlighting changing text in a java swing jtextcomponent I am trying to highlight some code in a JEditorPane like this:
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

public class Driver
{
    public static void main(String[] args)
    {
        try
        {
            //create a simple frame with an editor pane
            JFrame frame = new JFrame("Highlight Test");
            JEditorPane pane = new JEditorPane();
            frame.getContentPane().add(pane);
            frame.setSize(300, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            //string to put in the pane
            String text = "1234567890";

            //grab the highlighter for the pane
            Highlighter highlighter = pane.getHighlighter();

            //store all the text at once
            pane.setText(text);

            //go through all the characters
            for(int i = 0; i < text.length(); i++)
            {
                //highlight the latest character
                highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);

                //sleep for a quarter second
                Thread.sleep(250);
            }
        }catch(Exception ex){}
    }

}

This will highlight the characters one at a time and all the characters will remain highlighted. Now, I'd like the same behavior (all the characters remain highlighted) but I'd like to change the text in between highlights, like this:
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

public class Driver
{
    public static void main(String[] args)
    {
        try
        {
            //create a simple frame with an editor pane
            JFrame frame = new JFrame("Highlight Test");
            JEditorPane pane = new JEditorPane();
            frame.getContentPane().add(pane);
            frame.setSize(300, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            //string to put in the pane
            String text = "1234567890";

            //grab the highlighter for the pane
            Highlighter highlighter = pane.getHighlighter();

            //go through all the characters
            for(int i = 0; i < text.length(); i++)
            {
                //place a new string in the pane
                pane.setText(pane.getText() + text.charAt(i));

                //highlight the latest character
                highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);

                //sleep for a quarter second
                Thread.sleep(250);
            }
        }catch(Exception ex){}
    }

}

Notice the text in the pane is changing and then I'm applying a new highlight. The old highlights go away- I'd like them to stay. My assumption is the highlights go away each time you setText(). So, is there any way to keep the highlights in the text component while changing the text?

A: i didn't tried the following code but what i suggest is just try to highlight both latest character and previous ones too like this:
        //go through all the characters
        for(int i = 0; i < text.length(); i++)
        {
            //place a new string in the pane
            pane.setText(pane.getText() + text.charAt(i));
          //highlight the previous characters
          if (i > 0) {
           for ( int j=i-1; j >= 0; j--)
             highlighter.addHighlight(j, j+1 , DefaultHighlighter.DefaultPainter);
           }
            //highlight the latest character
            highlighter.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);

            //sleep for a quarter second
           // Thread.sleep(250);
        }
    }catch(Exception ex){}


text:
Q: OpenRecordset and Eval() General explanation of my program:

*

*I do reference controls on form for user input. (start Date ex)
8/1/2017  and End Date ex 8/31/2017)

*Then my query runs based on the parameter and returns a single value: ex) 12345.23

*Run the VBA function.

Problem: the querydef knows nothing about the previously opened query. Therefore, I would like to supply the parameters in VBA but I'm clueless from this point:
Set qry = CurrentDb.QueryDefs("2_Total")
Set rst = qry.OpenRecordset
For Each prm In qry.Parameters
    prm.Value = Eval(prm.Value)
Next

my SQL code :
SELECT Sum(dbo_SO_SalesHistory.DollarsSold) AS SumOfDollarsSold
FROM dbo_SO_SalesHistory
HAVING (((dbo_SO_SalesHistory.InvoiceDate) Between [Forms]![RUN]![textBeginOrderDate] And [Forms]![RUN]![textendorderdate]));

Here is the full code:
Option Compare Database

Option Explicit
Public Function TRANS2()

    Dim xlApp As Excel.Application
    Dim xlWB As Excel.Workbook
    Dim xlWS As Excel.Worksheet
    Dim acRng As Variant
    Dim xlRow As Integer

    Dim qry As QueryDef
    Dim rst As Recordset
    Dim prm As DAO.Parameter
    Set xlApp = New Excel.Application
    Set xlWB = xlApp.Workbooks.Open("C:\Users\J\Desktop\August 2017.xlsx")
    Set xlWS = xlWB.Worksheets("Totals")

    xlRow = (xlWS.Columns("K").End(xlDown).Row)
    Set qry = CurrentDb.QueryDefs("2_Total")
    Set rst = qry.OpenRecordset
    For Each prm In qry.Parameters
        prm.Value = Eval(prm.Value)
    Next

    Dim c As Integer
    c = 11   'C is the one that stores column number, in which c=1 means column A, 11 is for column K, 12 for Column L
    xlRow = xlRow + 11

     Do Until rst.EOF
        For Each acRng In rst.Fields
            xlWS.Cells(xlRow, c).Formula = acRng
            c = c + 1
        Next acRng
        xlRow = xlRow + 1
        c = 1
        rst.MoveNext
        If xlRow > 25 Then GoTo rq_Exit
    Loop

rq_Exit:
    rst.Close
    Set rst = Nothing
    Set xlWS = Nothing
    xlWB.Close acSaveYes
    Set xlWB = Nothing
    xlApp.Quit
    Set xlApp = Nothing
    Exit Function

End Function

p.s. I could have set the cell to value returned by DSum() but I would like to do the way I did.
My good reference is https://msdn.microsoft.com/en-us/library/office/ff193967.aspx.

Edit:

Set qry = CurrentDb.QueryDefs("2_Total")

For Each prm In qry.Parameters
    prm.Value = Eval(prm.Value)
Next
Set rst = qry.OpenRecordset

I moved Set rst = qry.OpenRecordset after For Each, and now I'm getting

The expression you entered contains invalid syntax.

on line   prm.Value = Eval(prm.Value)
Any advice on this would be highly appreciated.

A: Your sql query is syntactically wrong. You can't use HAVING clause without the GROUP BY clause. I think you need to use the WHERE clause instead like below :
SELECT Sum(dbo_SO_SalesHistory.DollarsSold) AS SumOfDollarsSold
FROM dbo_SO_SalesHistory
WHERE (((dbo_SO_SalesHistory.InvoiceDate) Between [Forms]![RUN]![textBeginOrderDate]
And [Forms]![RUN]![textendorderdate]));


text:
Q: React JS mapping with firebase I am trying to map with an arrow function from two collections in firebase so:
How do you map two different collections in one arrow function?
Trying to do this but I cant find a way of how to introduce users.map

          {clients.map((client, user) => (

              {user.userName}
              {client.email}
              {client.balance}

          ))}

full example
class Clients extends Component {
  state = {};

  render() {
    const { clients, users } = this.props;

    if ((clients, users)) {
      return (

                 Micro Bloggin

                      User
                      Topic
                      Date

                  {clients.map(client => (

                          {client.firstName}
                          {client.email}
                          {client.balance}

                              <Link
                                  to={`/client/${client.id}`}
                                  className="btn btn-info btn-sm"
                              >
                                   Read More
                              </Link>

                  ))}

      );
  } else {
      return <Spinner />;
  }
}


text:
Q: Render email HTML in a VueJS component without impacting the global styles I'm drafting a VueJS app which allows users to insert an email HTML template, do some processing and download the processed template afterwards.
I have two components and trying to render the HTML via the HTMLViewer component with v-html function as follows:
Home:
<template>

    <mdb-container>
      <mdb-row>
        <mdb-col>

            <mdb-input
              type="textarea"
              label="Paste your HTML here:"
              outline
              :rows="25"
              v-model="emailTemplate"
            />

        </mdb-col>
        <mdb-col>
          <HTMLViewer :emailTemplate="emailTemplate" />
        </mdb-col>
      </mdb-row>
      <mdb-row class="ml-1">
        <mdb-btn outline="default">Next</mdb-btn>
        <mdb-btn outline="danger" @click="clearEmailTemplate">Clear</mdb-btn>
      </mdb-row>
    </mdb-container>

</template>

HTMLViewer:
<template>

</template>

The problem I'm facing is the fact that the email template CSS styles overwrite the ones from the parent component (Home).
I tried to use iFrame which solves this issue but also creates a lot of different problems related to interacting with the HTML template, therefore I would like to avoid iframe as much as possible.
My question is - is there a good way to make sure the inserted email template HTML does not affect the global styles?


text:
Q: Facing some errors in CRUD operation? I created a program for CRUD but facing issues
Controller program :-
const Greeting = require("../models/model.js");
exports.create = (req, res) => {
  if (!req.body.message) {
    return res.status(400).send({ message: "Note content can not be empty" });
  }
  const greeting = new Greeting({
    name: req.body.name || "Name Needed",
    message: req.body.message,
  });

  Greeting.pushData(greeting);
};

modules.js
const GreetingSchema = mongoose.Schema(
  {
    name: String,
    message: String,
  },
  {
    timestamps: true,
  }
);
module.exports = mongoose.model("Greeting", GreetingSchema);
const Schema = mongoose.model("Greeting", GreetingSchema);

  pushData = (greeting) => {
     const data = new Schema({
       name: greeting.name,
       message: greeting.message
     });
    data
    .save()
    .then((data) => {
      res.send(data);
    })
    .catch((err) => {
      res
        .status(500)
        .send({
          message: err.message || "Error Occurred while creating Greeting",
        });
    });
  }

module.exports = {pushData};

and getting errors:
*
TypeError: Greeting is not a constructor
at exports.create (E:\Projects\Greeting-App_backend - Copy\controller\controller.js:9:20)
at Layer.handle [as handle_request] (E:\Projects\Greeting-App_backend - Copy\node_modules\express\lib\router\layer.js:95:5)
at next (E:\Projects\Greeting-App_backend - Copy\node_modules\express\lib\router\route.js:137:13)*

A: The error shows that your Greeting model is not a constructor. Check your model again to see if it's in the right format of how to create constructor in Javascript.
function Greeting(greeting) {
    this.name = greeting.name;
    this.message = greeting.message;
}

A: There are few errors in your code.

*

*pushData method should be part of Schema if you want to keep it inside models and access through model Schema. No need to export pushData if you do it like below.

GreetingSchema.methods.pushData = (greeting) => {
  // your code
}
module.exports =  mongoose.model("Greeting", GreetingSchema);

*In controller it will be -

greeting.pushData(greeting);


text:
Q: How can I add a search bar with a flat list in react native (no json)? I am building an app, where I have a list and I would like to search the items in the list with a search input how can I do?
const videos = [
    {name: 'Unity Pro', link:'https://www.youtube.com/watch?v=A7btOci5Gs4&t',key:'1'},
    {name: 'video2', link:'https://www.youtube.com/watchv=K36nOkqjbso&ab_channel=AppleExplained',key:'2'},
    {name: 'video3', link:'https://www.youtube.com/watch?v=A7btOci5Gs4&t',key:'3'},

]

const ListVideos = ({navigation}) => {
    return(
(code....)
               <FlatList data={videos}
            renderItem={({ item }) => (
                <TouchableOpacity style={styles.button} onPress={() => {Linking.openURL(item.link)}}>
                <IonIcon name="open-outline" size={16} color="white" style={{justifyContent:"center", alignContent:'center', alignItems:"center", alignSelf:"center", paddingRight:10}}/>
                <Text style={styles.inbuttonText} >{item.name}</Text>
                </TouchableOpacity>
            )}

            >
            </FlatList>

A: Use TextInput to filter your list. Set a state for your current variable and a data that will be filtered using your current input text. Something like this.
const [searchText, setSearchText] = useState();

//filtering
const searchFilteredData = searchText
    ? flatListData.filter((x) =>
            x.<filterItem>.toLowerCase().includes(searchText.toLowerCase())
      )
    : flatListData;

Then, in your render for TextInput:
    <TextInput
        placeholder="Search..."
        style={}
        onChangeText={(text) => {
            setSearchText(text);
        }}
        value={searchText}
    />

and your flatlist:
    <FlatList
        data={searchFilteredData}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
    />

change filterItem based on your data structure. For example your data looks like this:
data = [
    {
        id: "1",
        name: "John Smith",
    },
    {
        id: "2",
        name: "John Willow",
    },

use x.name in the filter function.


text:
Q: How to give a geometrical interpretation of a linear transformation? The question reads as follows:
Let
$$A=\begin{bmatrix}-1/2 & -\sqrt{3}/2\\\sqrt{3}/2& -1/2\end{bmatrix}$$
and let $T = \Bbb{R}^2 \to \Bbb{R}^2$ be the linear transformation described as $T(x) = Ax$

Give a geometrical interpretation of the linear transformation and calculate A$^{2021}$

The solution says that $A$ rotates the vectors in an angle of $2\pi/3$, but how do you see that? And what does the matrix even mean? Does it describe the evolution of the first vector column as it rotates?

A: Every matrix of the form
$$\begin{pmatrix}a & -b \\b & a \\\end{pmatrix}
\in \Bbb R^{2\times2}\tag 1$$
can be regarded as complex number $z=a+ib\in\Bbb C$ by identifying
$$
1\leftrightarrow\begin{pmatrix}1 & 0 \\0 & 1 \\\end{pmatrix}
\qquad\text{and}\qquad
i\leftrightarrow\begin{pmatrix}0 & -1 \\1 & 0 \\\end{pmatrix}
$$
Notice that $i^2 = -1$.
As any multiplication with a complex number is a zoom-and-rotate, this is also the case for your choice of $z=A= (-1 +\sqrt 3)/2$.  Notice that $|A|=\sqrt{a^2+b^2}=1$, thus a multiplication by $A$ is a rotation with no zoom. Also notice that $A^3=1$ because it is a 3rd root of unity and therefore
$$A^{2021} = A^{2021\text{ mod }3}= A^2 = A^{-1} = A^{T}
$$
The geometric interpretation is an (anti-)clockwise rotation by 120°, where the handed-ness of your unit vectors determines the handed-ness of the rotation.  With usual depictions of compex numbers, the rotation is 120° anti-clockwise.

If you don't want complex numbers in that context, then notice that any matrix of the form $(1)$ can be written as
$$\begin{pmatrix}a & -b \\b & a \\\end{pmatrix}
= \sqrt{a^2+b^2} \begin{pmatrix}\cos\phi & -\sin\phi \\\sin\phi & \cos\phi \\\end{pmatrix}
$$
where again $\sqrt{a^2+b^2}=1$ and $\phi = 2\pi/3\text{ mod }2\pi$. Thus, again we see that $A$ is a rotation by 120° (mod 360°).

A: Here I'm gonna use $V$ to denote the vector you called $x$.
Pick any vector $V=\begin{bmatrix} x \\ y \end{bmatrix}$.
Compute the angle between $V$ and $A\cdot V$.
You'll find out this angle is $\frac{2\pi}{3}$. This is what the matrix $A$ does when you multiply it by a vector on the right: it rotates it clock-wise by an angle of $\frac{2\pi}{3}$.
This matrix is a particular case of a  rotation matrix on the plane.

A: The image of the vector $\left(\begin{matrix}1\\0\end{matrix}\right)$ is the first column of your matrix.
The image of the vector $\left(\begin{matrix}0\\1\end{matrix}\right)$ is the second column of your matrix.
As is the case with any 2x2 matrix, you can get an idea of what the transformation does simply by sketching these two vectors comprising the first and second columns of the matrix.
To check you can also compare the matrix with the standard form of a rotation anticlockwise by angle $\theta$ which is $$\left(\begin{matrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{matrix}\right)$$
Now it should be clear that is is a rotation anticlockwise by $120^o$.
I assume you can do the last part.


text:
Q: Angular Material md-input-container takes large space I am working with a angular material sample. According to my default code md-input-container takes large space. My output as follows.

But I have found md-input-content with less space as follows.

I am not sure how to do that. My example  of md-input-container code as follows.
  <md-input-container class="md-block" flex-sm>
    Name
    <input md-maxlength="50" required name="name" ng-model="user.name"/>
  </md-input-container>

A: you can read this  documentation for that
simple code snippet about your question:

    <md-input-container class="md-block">
       Name
       <input md-maxlength="50" required name="name" ng-model="user.name"/>
    </md-input-container>

    <md-input-container class="md-block">
           Surname
           <input md-maxlength="50" required name="surname" ng-model="user.surname"/>
    </md-input-container>


text:
Q: Concatenate .Wav file by their header into 1 Temp File How do i concatenate .Wav files's header into one Temp file. I am trying to merge multiple segments of Telephone call. And in Database this all Segments will have same call ID because it is one call but multiple segments.

A: See this CodeProject article: http://www.codeproject.com/Articles/35725/C-WAV-file-class-audio-mixing-and-some-light-audio
The relevant part is the class WAVFile.cs - the merging of two WAV files is implemented in its method MergeAudioFiles (line 1326).
This gist contains WAVFile.cs. Other things which are useful:

*

*The header of a WAV file is created inside the Create method (starting from line 441, as per the WAV format specification, see Wikipedia or the full specification)

*the header of a WAV file is read/loaded in the Open method (line 93).

*you can set additional metadata in the optional INFO section, http://www.robotplanet.dk/audio/wav_meta_data has a pretty nice overview. This is not implemented in the class referenced above.

To create a temporary file (MSDN):
string tempFileName = Path.GetTempFileName();


text:
Q: Identifying memory leaks in python I've a method in python, which isn't memory intensive at all, but each time my code snippet reaches that method, after around 30-40 iterations, the system's RAM reaches 100% and my system freezes. The same method wasnt giving any issues before, but now I simple cant seem to find a way out of method. Any specific reason? I've got i5 processor (CPU usage is not even 50%) and 8Gb RAM. The code snippet is as follows:
def modify_data(self, data, col):
    """
    Convert Raw scores to Z-scores.

    Args:
        data (Pandas DataFrame): DataFrame storing raw scores
        col (String): The column on which conversion is being done

    Returns:
        z_score (Pandas DataFrame): New DataFrame storing z-scores instead of raw scores.
    """
    print "inside modify_data"
    # Now calculate z-score based on rolling windows for columns calculated above.

    z_score = pd.DataFrame()

    score = data
    z_scores = []

    ctr = 0

    indeces = score.index.tolist()

    for idx in indeces:
        row = score.ix[idx]

        n = min(idx, self.window)

        if self.use_window:
            subdata = score.iloc[ctr-n:ctr+1]
        else:
            subdata = score.iloc[:ctr+1]

        row = score.ix[idx]
        x = row[0]

        mu = subdata.mean()
        sigma = subdata.std()
        new_score = (x-mu)/sigma

        z_scores = np.append(z_score, new_score)

        ctr += 1

        z_scores = np.array(z_scores)
        tmpDF = pd.DataFrame(data=z_scores, columns=[col])

        z_score = z_score.append(tmpDF)

    return z_score

Earlier I had implemented:
for index, row in score.iterrows():

to iterate over loop, and thought maybe iterrows is slow performance based, and hence switched over to iterating over index list. But even that didnt seem to help. Any inputs will be really helpful
Thanks..


text:
Q: Azure App gateway ingress controller with private AKS cluster not working I am new to kubernetes, so please bear with me. I have created a azure kubernetes private cluster, i have deployed the pods for a basic webapplication & CLusterIP service , I have enabled App gateway ingress controller for the aks and deployed the ingress service that looks like below, in the ingress controller the backend is shown healthy, meaning it is able to reach the pod and get 200 ok response. However when i try to access my application by using the public IP of the ingress controller i get a 404 not found from the Application gateway. My aks cluster and ingress are in same Vnet  & I have verified that the route table of the aks cluster subnet has been added to ingress subnet.
I am not sure if there is any special configuration needed for using AGIC with private AKS.
Does anyone have any idea about this?
Thank you!

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: apigw-ingress
  annotations:
    kubernetes.io/ingress.class: azure/application-gateway

spec:
  rules:
  - host: backendpocwebapp.<location>.cloudapp.azure.com
    http:
      paths:

      - path: "/"
        pathType: Prefix
        backend:
          service:
            name: nextjspocapp
            port:
              number: 80

Below is my clusterIp service exposing port 80:

apiVersion: v1
kind: Service
metadata:
  name: nextjspocapp
  annotations:
     service.beta.kubernetes.io/azure-dns-label-name: backendpocwebapp

  labels:
    run: nextjspocapp
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 3000
  selector:
    app: nextjspocapp

Below is the deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
    name: nextjspocapp
    labels:
        app: nextjspocapp
        tier: poc
spec:
    revisionHistoryLimit: 5
    replicas: 2
    selector:
        matchLabels:
            tier: poc
    template:
        metadata:
            name: nextjspocapp
            labels:
                app: nextjspocapp
                tier: poc

        spec:
            containers:
                - name: nextjspocapp
                  image: <imagename>:tag
                  ports:
                    - containerPort: 3000

Added ingress controller and ingress service to aks , expected to access the pods using ingress public IP

A: Not an expert at all in AKS, but from the App Gateway perspective, it looks like the HTTP requests sent by your probes are the correct port and hostname, while your regular traffic isn't sending the correct hostname.  Usually 404's are experienced when the site is alive, listening, but the requested hostname doesn't match any bindings.  Your regular traffic might even be using the IP as a hostname.
The hostname can either be specified in the backend HTTP settings by overriding the hostname received by App Gateway clients, or by making sure the hostname you are hitting the App Gateway with matches what the backend is expecting.
This page has all the annotations but the anchor is for the backend hostname:
https://azure.github.io/application-gateway-kubernetes-ingress/annotations/#backend-hostname


text:
Q: Can asyncPipe in angular2 can improve UI performance? In the Tour Of Heros angular2 example, the retrieved data via promise is extracted as Hero[] as described in Extracting the data in the then callback. Instead of that extraction logic, an Observable can be used with an impure asyncPipe.
Is there any UI performance gain if I use Observable? If so, how?

A: You can set the components changeDetection: ChangeDetectionStrategy.OnPush  to avoid unnecessary change detection runs for this component and its children. The |async pipe then calls ChangeDetectorRef.markForCheck() to register the component for change detection in the next change detection cycle, but only when new values arrive.
This way change detection work is reduced notably because it's only run when necessary, which improves performance.


text:
Q: When should I mark a column as the primary key? I have a table like this:
// cookies
+----+---------+-------------------+------------+
| id | user_id |       token       |   expire   |
+----+---------+-------------------+------------+
| 1  | 32423   | dki3j4rf9u3e40... | 1467586386 |
| 2  | 65734   | erhj5473fv34gv... | 1467586521 |
| 3  | 21432   | 8u34ijf34t43gf... | 1467586640 |
+----+---------+-------------------+------------+

A few days that I think about it. I guess I don't need to id column. Currently id column is PK and also I have an unique-index on token column to make it both unique and fast for searching.
Now I want to know, can I remove id column from the table and make token column as the PK? Is that normal?
To be honest, I've never created a table without id column (it's always been the PK) so far, So that's weird for me to choose token column as the PK.

A: To the extent that token is a wide varchar, I would stick with the AI int PK that you already have. Joins will be faster. So too will inserts. Updates would likely be the same speed, as, why would that column be updated thus forcing index tree changes. But, inserts are faster for the child relationships by not dragging the wide varchar into an index tree.
It comes down to preference and readability too. As for readability, there is little of that with such a varchar. It is not as if it is a category like 'shoes'. It is a miserable unreadable non-human form. So as for readability, there is little argument for having the token as PK. Granted though, at times, it may be slightly useful.
Additional composites (multi-column indexes)
When you start combining the PK of choice with other fellow columns in composites (additional indexes you may choose to have), the thin int will become very apparent to be the best choice. Even with moderately large datasets.

A: 3 Years later after you posted this question I felt that I had to say something. Taking into account that this question pops up when other developers with the same problem as yours struggle to make a decision on such a structured table.
Without saying much, I want to give you a scenario:
Imagine you had a task to check manually if these two values are the same value1 = 1223611547921cvdfr and value2 = 1223611547921cvdfr... What would you do? Well the right step would be to compare each character between the two values from start to finish. And then *seconds later when you're done, you say, well these values are the same.
But what happens if you were to compare these two values value1 = 2 and value2 = 2? Within a split second you say "they're the same".
Same scenario occurs with computers complicated values lead to longer comparison or load time. Often this time is little to notice but what happens if you run a site like facebook where Billions of Users log in online everytime?
So it's quicker to SELECT user_id WHERE id = "1" than SELECT user_id WHERE token = "dki3j4rf9u3e40...".
Normally though what I'd do is add a security key, more like a Guid or token that must be passed together with the Id on the request before user information is returned from the server. So say for example, you get the user by id and then confirm that the user has the same security key as the one provided. Otherwise, return not-found.
Sometimes it's about simplicity, and simplicity is the preferred way in modern programming. I have seen developers using wrong methods while they keep saying "it's my preference". Often what you prefer leads to bad coding, it's important to remain vigilant and look for Modern Design Patterns as Techs evolve.

A: In general we often prefer Id of the table to be the Primary key, but what primary says is that it should be not null and should uniquely identify the rest records of the table (Columns) , so if you want to make the token as a primary key you can easily make it, but make sure it (Id) should not be depend on the other tables.
so whenever you will have to fetch any record you can easily fetch it by using the token.


text:
Q: upload Image or video to server using AsyncTask Hey guys i'm new to android app development, i'm trying to upload file to server using AsyncTask, but when i click a upload button app get crashed, please help with this.(Sorry if there is any language mistake).
UploadFileToServer class
/**
 * Uploading the file to server
 * */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

       try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(

                    new AndroidMultiPartEntity.ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });
            File sourceFile = new File(filePath);

            // Adding file data to http body
            entity.addPart("image",new FileBody(sourceFile));//new FileBody(sourceFile)

            // Extra parameters pass to server

            totalSize = entity.getContentLength();
            httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;

    }

logcat error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
#1. E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
#2.Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
E/AndroidRuntime:     at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)

Complete error window as follows:
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:  Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at com.appnings.cameratrial.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:166)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at com.appnings.cameratrial.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:139)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at com.appnings.cameratrial.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:114)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-18 20:51:23.109 14829-15007/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856)
10-18 20:51:23.440 569-649/? E/android.os.Debug: !@Dumpstate > dumpstate -k -t -z -d -o /data/log/dumpstate_app_error

A: Given you haven't posted the error log (from logcat) it would be hard to guess.
Common thing you might have missed:
<uses-permission android:name="android.permission.INTERNET" />

outside the application tag in the Manifest.xml

A: Tried importing different Apache lib files, some classes missing in some lib files finally after couple of imports it worked. thank you all. happy coding.

A: I solved the same problem
1.Use the right way to add jars.

Right click your lib folder and choice "add library", and input to project.

*In settings.gradle, add it.

packagingOptions {
  exclude 'META-INF/DEPENDENCIES'
      exclude 'META-INF/NOTICE'
      exclude 'META-INF/LICENSE'
      exclude 'META-INF/LICENSE.txt'
      exclude 'META-INF/NOTICE.txt'
  }

*

*Compile environment:

*

*Android Studio 1.4

*target sdk:21

*jars:httpclient-4.3.6.jar,httpcore-4.3.3.jar, httpmime-4.3.6.jar


text:
Q: Calling a function from another class from within an unordered_multimap? This is related to my last post that you can find here: Creating an unordered_map of std::functions with any arguments. I have now gone ahead and extended this out to classes. So let's say I have three different classes. And these classes all have different methods except for getVariable() and setVariable(int). So for this example we will class them ClassA, ClassB, and ClassC.
I also have a base class which I want to use as my driver. Essentially, if I want to set the variable between ClassA and ClassC I would call the base class' setVariable function.
#ifndef BASE_CLASS_HPP
#define BASE_CLASS_HPP

#include <unordered_map>
#include <functional>
#include <utility>
#include <string>
#include <any>

template<class A, class B>
class BaseClass
{
  public:
    BaseClass() { bindThem(); }

    std::pair<int,int> getValue()
    {
      // return classA and ClassB's values
    }

    void setValue(int newVal)
    {
      auto iter = functions.equal_range("setValue");
      std::any_cast<void(*)(int)>(mapIter->second)(newVal);
    }
  private:
    std::unordered_multimap<std::string,std::any> functions;

    void bindThem()
    {
      functions.emplace("setValue",&A::setValue);
      functions.emplace("setValue",&B::setValue);
      functions.emplace("getValue",&A::getValue);
      functions.emplace("getValue",&B::getValue);
    }

};

I then have in main:
#include <iostream>

#include "baseClass.hpp"
#include "classA.hpp"
#include "classB.hpp"
#include "classC.hpp"

int main()
{
  ClassA a;
  ClassB b;
  ClassC c;

  c.setValue(20);

  BaseClass<ClassA,ClassB> base1;
  BaseClass<ClassA,ClassC> base2;

  base1.setValue(15);

  auto values = base1.getValues();

}

I can place the functions withing my map, however, when I try to any_cast I don't get anything in return. I also tried:
std::any_cast<void(A::*)(int)>(mapIter->second)(newVal);

But that also gives me a compiler error of must use .* or ->* and I have tried everything to get it to compile and I don't really know what I am doing wrong. I also realized, if I called it that way, then I wouldn't be able to access B's setVariable function since I am using A's namespace.
Is there anyway I can get this to work how I want it to? I am essentially trying to modify those class values without having to make any copies of those classes and instead directly modify them from within this driver.

A: I still don't quite understand the purpose of such structure, but here an option how to make it at least compile:
#include <unordered_map>
#include <functional>
#include <utility>
#include <string>
#include <any>

template<class A, class B>
class BaseClass
{
  public:
    BaseClass() { bindThem(); }

    std::pair<int,int> getValue()
    {
      auto range = functions.equal_range("getValue");
      return
        {
          (a.*std::any_cast<int(A::*)()>(*range.first))(),
          (b.*std::any_cast<int(B::*)()>(*range.second))()
        };
    }

    void setValue(int newVal)
    {
      auto range = functions.equal_range("setValue");
      (a.*std::any_cast<void(A::*)(int)>(*range.first))(newVal);
      (b.*std::any_cast<void(B::*)(int)>(*range.second))(newVal);
    }
  private:
    std::unordered_multimap<std::string,std::any> functions;

    void bindThem()
    {
      functions.emplace("setValue",&A::setValue);
      functions.emplace("setValue",&B::setValue);
      functions.emplace("getValue",&A::getValue);
      functions.emplace("getValue",&B::getValue);
    }

    A a;
    B b;
};

class ClassA
{
public:
    void setValue(int){}
    int getValue() {return 0;}
};

class ClassB
{
public:
    void setValue(int){}
    int getValue() {return 1;}
};

int main()
{
    BaseClass<ClassA, ClassB> x;
    x.setValue(3);
    auto i = x.getValue();
}

Please note several things:

*

*I've added members to BaseClass since to call member functions you need an object to be called on.

*I'm using first and last iterators of the range from equal_range, but the order of elements in that range is implementation defined. So to make things work you need to take care of distinguishing which container element corresponds to class A and which to class B.


text:
Q: How to find the memory used by any object class Help
{
public:
        Help();
        ~Help();

        typedef std::set<string> Terms;
        typedef std::map<string, std::pair<int,Terms> > TermMap;
        typedef std::multimap<int, string, greater<int> > TermsMap;

private:

        TermMap  terms;
        TermsMap    termsMap;
};

How can we find the memory used (in bytes) by the objects term and termsMap. Do we have any library ?

A:
How can we find the memory used (in
  bytes) by the objects term and
  termsMap. Do we have any library ?

You should use your own allocator type.
typedef std::set<string,
    your_allocator_1_that_can_count_memory_consumption_t> Terms;

typedef std::map<string, std::pair<int,Terms>,
    your_allocator_2_that_can_count_memory_consumption_t> TermMap;

typedef std::multimap<int, string, greater<int>,
    your_allocator_3_that_can_count_memory_consumption_t> TermsMap;

I have not yet checked this idea for std::string so if it is difficult to implement just use your own class fixed_string which just wraps char s[max-string-lenght].
And when you need in your program to find out memory consumption just get it from your_allocator_1_that_can_counts_memory_consumption_t, your_allocator_2_that_can_counts_memory_consumption_t,
your_allocator_3_that_can_counts_memory_consumption_t.
Edited
For UncleBens I want to clarify my point.
As far as I understand the question of the ARV it is necessary to know how much memory is allocated for set::set and std::map including all memory allocated for elements of the set and the map. So it is not just sizeof(terms).
So I just suggested a very simple allocator. Without going into too much details it might look like this:
template <class T>
class your_allocator_1_that_can_counts_memory_consumption_t {
public:
   // interfaces that are required by the standart
private:
   std::allocator<T> std_allocator_;
   // here you need to put your variable to count bytes
   size_t globale_variable_for_allocator_1_to_count_bytes_;
};

This allocator just counts number of allocated and deallocated bytes and for real allocation and deallocation use its member std_allocator_. I might need to debug it under gdb in order to set a breakpoint on malloc() and on free() to make sure that every allocation and deallocation actually goes through my allocator.
I would be grateful if you point me at some problems with this idea since I have already implemented it in my program that runs on Windows, Linux and HP-UX and I simply asks my allocators in order to find how much memory each of my containers use.

A: Short Answer: No
Long Answer:
-> The basic object yes. sizeof(<TYPE>) but this is only useful for limited things.
-> A container and its contained members: NO
If you make assumptions about the structures used to implement these objects you can estimate it. But even that is not really useful ( apart from the very specific case of the vector).
The designers of the STL deliberately did not define the data structures that should be used by these containers. There are several reasons for this, but one of them (in my opinion) is to stop people making assumptions about the internals and thus try and do silly things that are not encapsulated by the interface.
So the question then comes down to why do you need to know the size?
Do you really need to know the size (unlikely but possible).
Or is there a task you are trying to achieve where you think you need the size?

A: If you are looking for the full memory usage of an object, this can't be solved in general in C++ - while we can get the size of an instance itself via sizeof(), the object can always allocate memory dynamically as needed.
If you can find out how big the individual element in a container are, you can get a lower bound:
size = sizeof(map<type>) + sum_of_element_sizes;

Keep in mind though that the containers can still allocate additional memory as an implementation detail and that for containers like vector and string you have to check for the allocated size.

A: If you're looking for the actual block of memory, the numerical value of a pointer to it should be it. (Then just add the number of bytes, and you have the end of the block).

A: the sizeof() operator ought to do it:
size_t bytes = sizeof(Help::TermMap);


text:
Q: Как сделать управление для 2D персонажа в Unity на ПК, без двойного прыжка и с поворотом игрока в разные стороны Как сделать управление для 2D персонажа в Unity на ПК, без двойного прыжка и с поворотом игрока в разные стороны

A: Как настроить скрипт показано в видео
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public class PF : MonoBehaviour
{
    Rigidbody2D rb;
    public float speed;
    public float jumpheight;
    public Transform groundCheck;
    bool isGrounded;
    Animator anim;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void Update()
    {
        Flip();
        CheckGround();
        rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
            rb.AddForce(transform.up * jumpheight, ForceMode2D.Impulse);

    }
    void Flip()
    {
        if (Input.GetAxis("Horizontal") > 0)
        transform.localRotation = Quaternion.Euler(0, 0, 0);
        if (Input.GetAxis("Horizontal") < 0)
        transform.localRotation = Quaternion.Euler(0, 180, 0);
    }
    void CheckGround()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, 1);
        isGrounded = colliders.Length > 1;
    }
}


text:
Q: Text and lines don't look right Since I updated my video drivers, sometimes text and lines on the screen don't appear quite right. Everything looks fine with default drivers that come with Windows, but I had to update the drivers due to errors when using VirtualBox.
The symptom comes and goes. It's hard to tell what exactly triggers it, and what clears it is also somewhat unpredictable. Sometimes it will clear up when I choose another window, change the zoom level, or scroll within the same window. Sometimes it seems none of these work.
The system is an HP EliteBook 8530p with ATI Mobility Radeon HD 3650 graphics. OS is Windows Ultimate x64. Below is an example screenshot showing the text distortion even as I write this post.

What could be causing this? I used AMD's detection tool to confirm I'd downloaded the right driver. Is there some advanced setting I need to tweak that might just not be right for my system?

A: I would try an older version of the video driver if the new one is giving you grief. I have had issues before when updating video drivers. I did not check the site, but I would imagine AMD would have a prior version handy.


text:
Q: Using Update, Delete and Insert Statements in a single Stored Procedure on SQL Server 2008 R2 I have a scenario that requires me to firstly set a range of column values in a table to Null, then I add the logic to re-calculate the new NULL values with an Update statement following the previous Update statement. Lastly I run my final comparison script (within a cursor) which inserts the new values into a table.
Do I need to use the GO command between each major command?
Example:
Drop Table1

Update Table2
Set Col1=NULL,Col2=NULL

Insert into Table3 (Col1,Col2)

Is using a GO between each statement a requirement as sometimes this works but lately it's been giving me issues?
Thanks,

A: As mentioned above, GO is not an SQL syntax, but SSMS separator.
If you really need to perform all those actions in the single SP, you can use a dynamic SQL. The're two abilities to execute dynamic SQL in the SQL server" sp_executesql and execute (command).
Additional information according to the dynamic SQL can be found here: http://www.sommarskog.se/dynamic_sql.html or here: http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure
In this case your script will be like following:
create proc myProc
as
declare @sql nvarchar(max);

set @sql = N'Drop Table1';
exec sp_executesql @sql;

set @sql = N'Update Table2
Set Col1=NULL,Col2=NULL';
exec sp_executesql @sql;

set @sql = N'Insert into Table3 (Col1,Col2)';
exec sp_executesql @sql;
go

But need to check if you really need to perform the above operations in the mentioned above manner...


text:
Q: Codeigniter How to in Array use where OR, AND clause I am looking for query in Codeigniter works like where OR, AND both works.
This is working Perfect!
$srcArr2['emp_id']=8;
$srcArr2['status']='2';
$this->db->where($srcArr2);
$query = $this->db->get('tickets');
$res = $query->result_array(); // as array
print_r ($res);

query is:
Need to add  OR  in where with $srcArr1['ass_id']=12;
I try but not working.
$srcArr1['ass_id']=12;
$srcArr2['emp_id']=8;
$srcArr2['status']='2';
$this->db->where($srcArr2);
$this->db->where_in($srcArr1);
$query = $this->db->get('tickets');
$res = $query->result_array(); // as array
print_r ($res);

Thank You, in Advance for help

A: You can use or_where_in to achieve the same,
$this->db->or_where_in($srcArr1);

Official doc.

A: $this->db->where($srcArr2);
$this->db->or_where($srcArr1);

https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-dataenter link description here


text:
Q: How to arrange a weekly schedule in org-mode? I'd like to put my schedule into org-mode, so that I can see my classes in the agenda.  I have different classes, repeated every week, all of them taking 90 minutes.  I was thinking about something like this:
* My schedule
** Differential equations
   <2012-10-04 Thu 11:45 +1w>--<2012-10-04 Thu 13:15 +1w>

However, there are two problems: I can see only the next instance in the agenda, and I can't see the ending time.  Any ideas?

A: I'm pretty sure you're searching for the org-diary-class, mentionned in the Worg faq.
Your exemple would then be (assuming classes end on December 20th) :
** 11:45-13:15 Differential equations
   <%%(org-diary-class 10 4 2012 12 20 2012 2)>

You can add weeks where there are no classes after the last number (which is 2 for tuesday).
If you don't like having the time in the headline, you can use :
%%(org-diary-class 10 04 2012 12 20 2012 2) 11:45-13:15 Differential Equations

Last time I checked, it required %% not to be indented, so I guess each of these awesome solutions have their slight drawback.


text:
Q: C++ - Opening text files sequentially I have hundreds of .txt files ordered by number: 1.txt, 2.txt, 3.txt,...n.txt. In each file there are two columns with decimal numbers.
I wrote an algorithm that does some operations to one .txt file alone, and now I want to recursively do the same to all of them.
This helpful question gave me some idea of what I'm trying to do.
Now I'm trying to write an algorithm to read all of the files:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
int i, n;
char filename[6];
double column1[100], column2[100];
for (n=1;n=200;n++)
{
sprintf(filename, "%d.txt", n);
ifstream datafile;
datafile.open(filename);
    for (i=0;i<100;i++)
    {
    datafile >> column1[i] >> column2[i];
    cout << column1[i] << column2[i];
    }
datafile.close();
}
return 0;
}

What I think the code is doing: it is creating string names from 1.txt till 200.txt, then it opens files with these names. For each file, the first 100 columns will be associated to the arrays column1 and column2, then the values will be shown on the screen.
I don't get any error when compiling it, but when I run it the output is huge and simply won't stop. If i set the output to a .txt file it reaches easily some Gb!
I also tried decreasing the loop number and reduce the numbers of columns (to 3 or so), but I till get an infinite output. I would be glad if someone could point the mistakes I'm doing in the code...
I am using gcc 5.2.1 with Linux.
Thanks!

A: *

*6-element array is too short to store "200.txt". It must be at least 8 elements.

*The condition n=200 is wrong and is always true. It should be n<=200.

A: If all your files are in the same directory, you could also use boost::filesystem, e.g.:
auto path = "path/to/folder";
std::for_each(boost::filesystem::directory_iterator{path},
        boost::filesystem::directory_iterator{},
        [](boost::filesystem::directory_entry file){
            // test if file is of the correct type
            // do sth with file
        });

I think this is a cleaner solution.


text:
Q: Why lifting of binary function into the list monads goes over all the element combinations? Say, if I want to create a cartesian product of two lists, I could do (here in Haskell, but I can do the same e.g. in Scala or any other FP-able language)
cartesianProd = liftM2 (,)

then
>cartesianProd [1,2] [3,4]
>[(1,3),(1,4),(2,3),(2,4)]

Obviously, using (lifting) + instead of tuple pairing, will produce list of sums of all combinations.
By FP definition, "lifting is a concept which allows you to transform a function into a corresponding function within another (usually more general) setting." The way I understand it, if I have monadic arguments, I can transform my binary function to work with them via liftM2. Where does the cartesian product comes from, though? Intuitively, I would expect [(1,3), (2,4)] from the example above.

A: I don't know much about Haskell but for your question I would recommend reading this section of Learn You a Haskell: http://learnyouahaskell.com/functors-applicative-functors-and-monoids#the-newtype-keyword .
The gist of it is that some types could satisfy classes such as functor or monad laws in more than one way. Lists for instance could be applicative functors in the way that they are in the haskell standard library (applies the function to every possibility from each list), or they could be applicative functors in the way that you expect them to (apply the function to corresponding elements in the lists).
The designers of haskell thought that the cartesian product version was more useful so they made that the default interpretation. They also however realized that your interpretation also satisfied appropriate laws and was also useful and so you should try running the below code.
module Main where

import qualified Control.Applicative as CA

prod :: (CA.Applicative f) => f a -> f b -> f (a, b)
prod = CA.liftA2 (,)

main :: IO ()
main = do
        print $ prod [1,2] [3,4]
        print . CA.getZipList $ prod (CA.ZipList [1,2]) (CA.ZipList [3,4])

A: Well the reason is that the M in liftM2 means monad. In fact liftM2 is defined as
 liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
 liftM2 f a b = do
   a' <- a
   b' <- b
   return (f a b)

This relies on monadic bind operation >>= :: m a -> (a -> m b) -> m b. In a list, >>= is equivalent to concatMap, so your code is
 cartProd f a b = concatMap (\a' -> concatMap (\b' -> f a b) b) a

This applies (,) to each and every pair of as and bs in our list and so we get a cartesian product. Incidentally it would be better practice to use liftA2 which works over all monads + applicatives.
I'll skip over the thorny issue of why the list monad is concatMap and relegate that till you come across it in a nice book like LYAH or Real World Haskell. Instead the behavior you want is zip or the more general zipWith :: (a -> b -> c) -> [a] -> [b] -> [c].