text:
Q: Spark Scala - Winsorize DataFrame columns within groups I am pre-processing data for machine learning inputs, a target value column, call it "price" has many outliers, and rather than winsorizing price over the whole set I want to winsorize within groups labeled by "product_category". There are other features, product_category is just a price-relevant label.
There is a Scala stat function that works great:
df_data.stat.approxQuantile("price", Array(0.01, 0.99), 0.00001)
// res19: Array[Double] = Array(3.13, 318.54)

Unfortunately, it doesn't support computing the quantiles within groups. Nor does is support window partitions.
df_data
    .groupBy("product_category")
    .approxQuantile($"price", Array(0.01, 0.99), 0.00001)

// error: value approxQuantile is not a member of
//   org.apache.spark.sql.RelationalGroupedDataset

What is the best way to compute say the p01 and p99 within groups of a spark dataframe, for the purpose of replacing values beyond that range, ie winsorizing?
My dataset schema can be imagined like this, and its over 20MM rows with appx 10K different labels for "product_category", so performance is also a concern.
df_data and a winsorized price column:
+---------+------------------+--------+---------+
|   item  | product_category |  price | pr_winz |
+---------+------------------+--------+---------+
| I000001 |     XX11         |   1.99 |   5.00  |
| I000002 |     XX11         |  59.99 |  59.99  |
| I000003 |     XX11         |1359.00 | 850.00  |
+---------+------------------+--------+---------+
supposing p01 = 5.00, p99 = 850.00 for this product_category

A: Here is what I came up with, after struggling with the documentation (there are two functions approx_percentile and percentile_approx that apparently do the same thing).
I was not able to figure out how to implement this except as a spark sql expression, not sure exactly why grouping only works there. I suspect because its part of Hive?
Spark DataFrame Winsorizor

*

*Tested on DF in 10 to 100MM rows range

// Winsorize function, groupable by columns list
// low/hi element of [0,1]
// precision: integer in [1, 1E7-ish], in practice use 100 or 1000 for large data, smaller is faster/less accurate
// group_col: comma-separated list of column names
import org.apache.spark.sql._

def grouped_winzo(df: DataFrame, winz_col: String, group_col: String, low: Double, hi: Double, precision: Integer): DataFrame = {
    df.createOrReplaceTempView("df_table")

    spark.sql(s"""
    select distinct
    *
    , percentile_approx($winz_col, $low, $precision) over(partition by $group_col) p_low
    , percentile_approx($winz_col, $hi, $precision) over(partition by $group_col) p_hi

    from df_table
    """)
    .withColumn(winz_col + "_winz", expr(s"""
        case when $winz_col <= p_low then p_low
             when $winz_col >= p_hi then p_hi
             else $winz_col end"""))
    .drop(winz_col, "p_low", "p_hi")

}

// winsorize the price column of a dataframe at the p01 and p99
// percentiles, grouped by 'product_category' column.

val df_winsorized = grouped_winzo(
   df_data
   , "price"
   , "product_category"
   , 0.01, 0.99, 1000)


text:
Q: PowerApps Data Source Changed to Stored Procedure The data source in PowerApps gallery was a SQL View.
Search('[dbo].[vwCandidate]', textSearchCandidate.Text, "NameLast", "NameFirst", "MiscellaneousTags", "EmailAddress", "PhoneNumber")

The selected record populated a global variable for the form item.
Set(varCandidate, gallerySearchResults.Selected)

Everything works as expected.  Then, I changed the data source to use a stored procedure to move the search from PowerApps to SQL server. After doing so I received the error message

"Incompatible Type. We can't evaluate your formula because the context
  variable types are incompatible with the types of the values in other
  places in your app"

I cannot revert back to the view that was working without getting the same error. I'm hoping my only option is NOT to use a new variable and change every occurrence in the form/App. I'd like to avoid this if possible.
I cannot view the form so I'm not sure how to debug properly. My hunch is the date fields being returned via Flow are causing the problem. They are 'smalldatetime' types and the Flow is returning a string 'yyyy-mm-ddThh:mm:ss.000' even though 'date' is being requested.
"PhoneNumber": {
  "type": "string"
},
"CandidateStatus": {
  "type": "string"
},
"DateApplied": {
  "type": "string",
  "format": "date"
},

Flow JSON here does not seem to like any of the other 'date' format types.
Are there any workarounds from Flow?  Should I reformat the date values when I am setting the global variable?  Advice?

A: Turns out, I was on the right track thinking that the DATE data type coming from Flow as a string.  Here's why:
A new record was created using a Patch function while setting the global variable:
Set(varCandidate, Patch('[dbo].[candidate]', Defaults('[dbo].[candidate]'), {DateApplied: DateTimeValue(Text(Now())), CreatedDate:DateTimeValue(Text(Now())), CreatedBy:varUser.Email}))

The "DateApplied" field was a "DATE" type in the SQL table and it was coming from Flow as a string "2019-03-13T17:40:52.000".  The recordset from Flow was being set to the same global variable when I wanted to edit the record
Set(varCandidate, gallerySearchResults.Selected)

The error "Incompatible Type" (see question for full error message) was due to this field being a "Date Value" in a new record and a "string" in an edit record.
My fix is to remove this "Date" type fields from the patch and modify the Flow to retrieve the newly created record record by ID.

A: *

*Reset everything back, including the data source, then save and close the app completely, re-test.

*Remove any flow connections then save and close the app completely , re-test, then re-add the flow connections.
I don't why but PowerApps some times persist data connection errors until you have close the app down.
And just to confirm PowerApps doesn't support stored procedures as data sources, only as write using the patch function etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve original coefficients after performing regression on normalised data without using Scikit-Learn? I am reading data from a file using pandas which looks like this:
data.head()

   ldr1  ldr2  servo
0   971   956     -2
1   691   825   -105
2   841   963    -26
3   970   731     44
4   755   939    -69

I proceed to normalize this data to perform gradient descent:
my_data = (my_data - my_data.mean())/my_data.std()
my_data.head()

       ldr1      ldr2     servo
0  1.419949  1.289668  0.366482
1 -0.242834  0.591311 -1.580420
2  0.647943  1.326984 -0.087165
3  1.414011  0.090200  1.235972
4  0.137231  1.199041 -0.899949

I perform multivariate regression and end up with fitted parameters on the normalized data:
Thetas:  [[ 0.31973117  0.45401309 -0.12941108]]

I would like to plot the plane of best fit on the original data and not the normalized data using the normalized thetas.
I used scipy.optimize.curve_fit to perform multivariate linear regression and come up with the optimal fitted parameters. I know that the original thetas should be close to the following:
[   0.26654135   -0.15218007 -107.79915373]

How can I get the 'original' thetas for the original data-set in order to plot, without using Scikit-Learn?
Any suggestions will be appreciated.

As per the answer below:
m
ldr1     731.891429
ldr2     714.080000
servo    -21.388571
dtype: float64
s
ldr1     168.392347
ldr2     187.583221
servo     52.904576
dtype: float64

I then proceed with:
original_thetas = np.dot(theta, s) + m

which yields:
original_thetas
ldr1     862.420572
ldr2     844.609144
servo    109.140572
dtype: float64

I am not sure if I am performing the calculation incorrectly or if the method presented does not work for the coefficients themselves.

A: I believe you just need to store the mean and standard deviations
m = data.mean()
s = data.std()

And then inverse the transformation
theta * s + m


text:
Q: How to create a function that totals an order with several items? I need to create a function which will return the total of an order. I've been given three tables with the following variables
Table 1 - Order

*

*Order_ID

*Date_Placed

*Date_Fulfilled

Table 2 - Order Product

*

*Order_ID

*Product_ID

*Product_Quantity

Table 3 - Product

*

*Product_ID

*Price

I'm struggling to put together a coherent function. Any help would be greatly appreciated.
I've already attempted to set up the function with joins between both tables, but am unable to figure out where I should be putting my equation.
BEGIN

    SELECT order.order_id, SUM(product.price * order_item.quantity)
    FROM `order`
    JOIN `order_item` ON order.order_id = order_product.order_id
    JOIN `product` ON order_product.product_id = product.product_id;
END $$

A: You might be surprised, but the orders table is not needed for this query.  You can just aggregate off the other two tables:
SELECT oi.order_id, SUM(p.price * oi.quantity)
FROM order_item oi JOIN
     product p
     ON po.product_id = p.product_id
GROUP BY oi.order_id;

A: You'll need to take your select statement, and group it by your order.order_id. That way you'll have one row per order, with the sum total of that order.
SELECT order.order_id, SUM(product.price * order_item.quantity) as total_price
FROM `order`
JOIN `order_item` ON order.order_id = order_product.order_id
JOIN `product` ON order_product.product_id = product.product_id
GROUP BY order.order_id

A: this will work:
SELECT order.order_id, SUM(product.price * order_item.quantity)
FROM order o,
JOIN order_item  oi,
JOIN product p  where
o.order_id = oi.order_id and
oi.product_id = p.product_id
group by order_product.product_id = product.product_id;


text:
Q: No module named v4.proto.omni I have installed pysnmp-4.x.I am getting following error during running a SNMP program.
I am using pysnmpSE 3.5.2 now but getting same error. I found that pysnmpSE doesn't hav v4 module. I was suggested that following error should resolved if pySNMP SE 3.x is used.
Traceback (most recent call last):
  File "C:\Documents and Settings\ggne0622\Desktop\Python\google-python-exercises\babynames\SimpleAgent.py", line 18, in <module>
    from twistedsnmp import agent, agentprotocol, bisectoidstore
  File "C:\Python27\Lib\site-packages\twistedsnmp\agent.py", line 4, in <module>
    from twistedsnmp import datatypes
  File "C:\Python27\Lib\site-packages\twistedsnmp\datatypes.py", line 7, in <module>
    from twistedsnmp.pysnmpproto import v2c,v1
  File "C:\Python27\Lib\site-packages\twistedsnmp\pysnmpproto.py", line 13, in <module>
    from pysnmp.v4.proto.omni import v2c,v1, error, rfc1157, rfc1905
ImportError: No module named v4.proto.omni

Code:
#!/usr/bin/env python
from twisted.internet.iocpreactor import reactor
from twisted.internet import error as twisted_error
from twistedsnmp import agent, agentprotocol, bisectoidstore
#from twisted.internet import interfaces
try:
from twistedsnmp import bsdoidstore
except ImportError:
import warnings
warnings.warn( """No BSDDB OID Storage available for testing""" )
bsdoidstore = None
def createAgent( oids ):
ports = [161]+range(20000,25000)
for port in ports:
try:
        `agentObject = reactor.IOCPReactor.listenUDP(port,`   `agentprotocol.AgentProtocol(snmpVersion = 'v2c',agent = agent.Agent(dataStore =`   `bisectoidstore.BisectOIDStore(OIDs = oids,),),),)`
    `except twisted_error.CannotListenError:`
        `pass`
    `else:`
        `return agentObject, port`

testingOIDs = {
'.1.3.6.1.2.1.1.1.0': 'Some tool out in the field',
'.1.3.6.1.2.1.1.2.0': '.1.3.6.1.4.1.88.3.1',
'.1.3.6.1.2.1.1.3.0': 558566090,
'.1.3.6.1.2.1.1.4.0': "support@somewhere.ca",
'.1.3.6.1.2.1.1.5.0': "NameOfSystem",
'.1.3.6.1.2.1.1.6.0': "SomeHeadEnd, West Hinterlands, Canada",
}
def main(oids=testingOIDs):
agent, port = createAgent( oids )
if __name__ == "__main__":
reactor.IOCPReactor.callWhenRunning( main )
reactor.IOCPReactor.run()

A: TwistedSNMP does not seem to be designed to work with PySNMP 4.x. Thus you should either use PySNMP 3.x / PySNMP SE or switch to PySNMP 4.x which has its own Twisted binding.


text:
Q: Ria service not accessible to client (RequiresAuthentication service) I have 2 Domain Service in my Silverlight solution, both of them has RequiresAuthentication attribute. When user go to application and they login, they can call service A and it working properly but when user call service B it throw exception Load operation failed for query 'X'. Access to operation 'X' was denied.
How to fix this problem?

A: You need an authentication service as mentioned in the comment that likely does not have RequiresAuthentication set, unless you wish to do your authentication in ASP.NET first and then why bother with that service?
I implemented my services as defined here: http://www.codeproject.com/KB/silverlight/IssueVisionSilverlightPt3.aspx#AuthenticationService
but what wasn't apparent is in ValidateUser(userName, password, out userData), userData can not be null here or FormsAuthentication.Encrypt(ticket) will always return null and therefor not set your auth cookie for Silverlight to send to your domain service requests. You can determine if the cookie is being sent by using Fiddler and you absolutely need this for the auth and domain services to "talk to each other".
The more quirky part is [EnableClientAccess(RequiresSecureEndpoint = true)] as this seems to want requiresSSL=true in your web.config forms section and all traffic has to pass through https. For me this means detecting this on the client and redirecting before any auth is triggered.


text:
Q: Problem in compilation of MINPACK library with CUDA code I need to solve a nonlinear system of equations and I found the MINPACK library to do the job.
But I need the code to work with CUDA and I'm not able to compile the code.
I'm facing this problem:
nvcc -arch sm_61 -Iinc -I/usr/local/include obj/main.o -o oi -L/usr/local/lib64 -lcuminpack
nvlink error   : Undefined reference to 'dpmpar' in 'obj/main.o'
make: *** [makefile:55: oi] Erro 255

My main file is:
main.cu
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define __cminpack_double__
#include <cminpack-1/cminpack.h>
#define real __cminpack_real__

typedef struct{
  real fnorm1, fnorm2;
  int info;
  real solution[2];
} ResultType;

__cminpack_attr__ int fcn(void *p, int n, const real *x, real *fvec, int iflag){

    --fvec;
    --x;

    fvec[0] = x[0] + x[0]*x[1] - 4.0;
    fvec[1] = x[0] + x[1] -3.0;

    return 0;
}

__global__ void SolvingSystem(ResultType *pResults){

    int info;

    real fnorm1, fnorm2, tol;

    int n = 2;

    real fvec[2];
    real x[2];

    const int lwa = (n*(3*n + 13))/2;
    real wa[50];

    tol = sqrt(dpmpar(1));

    x[0] = 1.98;
    x[1] = 1.02;

    printf("Initial Guess: %g, %g\n", x[0], x[1]);
}

int main(int argc, char const *argv[]){

    cudaSetDevice(0);

    ResultType *reuslt_GPU, *reuslt_CPU;

    cudaMalloc((void**)&reuslt_GPU, sizeof(ResultType));
    cudaMallocHost((void**)&reuslt_CPU, sizeof(ResultType));

    printf("Solving System...\n");

    dim3 grid(1, 1, 1);
    dim3 block(1, 1, 1);

    SolvingSystem<<< grid, block>>>(reuslt_GPU);

    cudaDeviceSynchronize();
    printf("Done!\n");

    return 0;
}

And my makefile is:
makefile
# MakeFile

# Program Name
EXE = oi

# Compilers
NVCC := nvcc

ALL_LIBRARIES := cuminpack
LIBDIR :=  /usr/local/lib64

# Directories
SRCDIR := src
OBJDIR := obj
INCDIR := inc /usr/local/include

#Flags
NVCCARCHFLAG := -arch sm_61
NVCCFLAGS    := -std=c++11
LDFLAGS      := $(addprefix -L, $(LIBDIR))

INCLUDES     := $(addprefix -I, $(INCDIR))
LIBRARIES    := $(addprefix -l, $(ALL_LIBRARIES))
LIBRARIES    +=

ALL_CPFLAGS := -MMD
ALL_CPFLAGS += $(NVCCARCHFLAG)
ALL_CPFLAGS += $(NVCCFLAGS)

ALL_LDFLAGS := $(LDFLAGS)

# Files
C_FILES := $(wildcard $(SRCDIR)/*.c)
CU_FILES := $(wildcard $(SRCDIR)/*.cu)

C_OBJ := $(patsubst $(SRCDIR)/%.c, $(OBJDIR)/%.o, $(C_FILES))
CU_OBJ := $(patsubst $(SRCDIR)/%.cu, $(OBJDIR)/%.o, $(CU_FILES))

C_DEP := $(patsubst $(SRCDIR)/%.c, $(OBJDIR)/%.d, $(C_FILES))
CU_DEP := $(patsubst $(SRCDIR)/%.cu, $(OBJDIR)/%.d, $(CU_FILES))

SRC := $(C_FILES) $(CU_FILES)
OBJ := $(C_OBJ) $(CU_OBJ)
DEP := $(C_DEP) $(CU_DEP)

COMPILE.c := $(NVCC) -MMD -g $(INCLUDES) -c
COMPILE.cu := $(NVCC) $(ALL_CPFLAGS) $(INCLUDES) -dc

.PHONY: all clean

all:$(EXE)

$(EXE): $(OBJ)
    $(NVCC) $(NVCCARCHFLAG) $(INCLUDES) $^ -o $@ $(ALL_LDFLAGS) $(LIBRARIES)

$(OBJDIR)/%.o: $(SRCDIR)/%.c | $(OBJDIR)
    $(COMPILE.c) $< -o $@

$(OBJDIR)/%.o: $(SRCDIR)/%.cu | $(OBJDIR)
    $(COMPILE.cu) $< -o $@

$(OBJDIR):
    @mkdir -p $@

# Cleaning up
clean:
    @echo Cleaning up...
    @rm -f -r $(OBJDIR)
    @rm $(EXE)

# Including dependency
-include $(DEP)

The main file needs to be finished and that's the reason to some unused variables.
I just can't figure out what is causing this error, I think the problem is in cuminpack library, but I don't now how to fix it.
I'm using cminpack-1.3.8 from this website: http://devernay.free.fr/hacks/cminpack/
I installed the library using cmake then make and make install. Then I went to source folder and did make cuda. This last command generated libcuminpack.a file in cuda directory, then I copied this .a file to /usr/local/lib64 where cmake installed the other libraries files.
If anyone could help me I would be very thankful
EDIT
Files from the cminpack library
cminpack.h
...
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
...
#if defined(__CUDA_ARCH__) || defined(__CUDACC__)
#define __cminpack_attr__ __device__
#ifndef __cminpack_real__
#define __cminpack_float__
#define __cminpack_real__ float
#endif
#define __cminpack_type_fcn_nn__        __cminpack_attr__ int fcn_nn
#define __cminpack_type_fcnder_nn__     __cminpack_attr__ int fcnder_nn
#define __cminpack_type_fcn_mn__        __cminpack_attr__ int fcn_mn
#define __cminpack_type_fcnder_mn__     __cminpack_attr__ int fcnder_mn
#define __cminpack_type_fcnderstr_mn__  __cminpack_attr__ int fcnderstr_mn
#define __cminpack_decl_fcn_nn__
#define __cminpack_decl_fcnder_nn__
#define __cminpack_decl_fcn_mn__
#define __cminpack_decl_fcnder_mn__
#define __cminpack_decl_fcnderstr_mn__
#define __cminpack_param_fcn_nn__
#define __cminpack_param_fcnder_nn__
#define __cminpack_param_fcn_mn__
#define __cminpack_param_fcnder_mn__
#define __cminpack_param_fcnderstr_mn__
...
__cminpack_attr__
__cminpack_real__ CMINPACK_EXPORT __cminpack_func__(dpmpar)( int i );

dpmpar.c
#include "cminpack.h"
#include <float.h>
#include "cminpackP.h"

#define DPMPAR(type,X) _DPMPAR(type,X)
#define _DPMPAR(type,X) type ## _ ## X

__cminpack_attr__
real __cminpack_func__(dpmpar)(int i)
{
/*     ********** */

/*     Function dpmpar */
...

A: Based on talonmies's comment I was able to compile the code defining the __device__ function dpmpar in main.cu file.
Then I found this post https://forums.developer.nvidia.com/t/external-calls-to-device-functions/17737 where the guy answered that CUDA doesn't have a linker on the device side, so it's not possible to call a __device__ function from a different .cu file.
With this in mind, I copied only the files that I needed from the library and made some modifications, like changing __cminpack_attr__ to __device__ and I rewrote the header file too. So basically I made my own device library (thank's again to talonmies's).
The last thing I did was move all this new files to the same folder where my main.cu and my makefile lives and I rewrote the makefile.
Now the code compile fine!!


text:
Q: zend framework: Creating the Default Module I did everything as it is written in the book of Vaswani V. - the Zend Framework. A Beginner's Guide (page 33), but the page "http://square.localhost/default/index/index" returns the response "not found". What is wrong?

A: I had the exact same problem with that part of the book.  Fortunately, the book's companion site (zf-beginners-guide.com) has an errata/troubleshooting section that solves the problem nicely. Quoting from the site:

If you see a "File not found" error after implementing the modular
  directory layout and accessing the URL
  http://square.localhost/default/index/index, check that the new
  virtual host supports .htaccess overrides. You can enable this by
  adding the following lines to your virtual host configuration,
  remembering to change the directory path to your virtual host's
  document root.

<Directory "/usr/local/apache/htdocs/square/public">
   AllowOverride All
   Options All
</Directory>

Incidentally, if you're using Ubuntu, it may not have mod_rewrite enabled by default. (I just ran into the exact same problem myself BTW). If you're still having trouble, try this:
sudo a2enmod rewrite
sudo service apache2 restart

(Big thanks to Mahok for the help on that, BTW!)


text:
Q: Scrollable Content Size Ambiguity with empty UIScrollView (XCode 6) In my project, I have multiple empty scrollview (layout with AutoLayout) in multiple view controllers. At run time, views will be add to those scrollview base on user and their desirable content. This was fine in XCode 5, IB editor never show any warning.
Recently when I update to XCode 6 to gain access to iOS 8 and new iPhone simulators. I found that all those empty scroll view that used to be ok (no warning in XCode 5) now showing warning of scrollable content size ambiguity. I check my AutoLayout and it seems ok.
Any idea what cause this?
P.S. but every thing seems ok when I run with simulator and device, no layout issue.

A: According what you describe the ambiguity is solved in run time, so when you are designing in IB this constraints don't exists.
If you want to avoid this warning you can set intrinsic size to Placeholder in IB as shown:

A: For 2022:
It's changed slightly.
Here's the warning:

If you are building the scrollview/stackview in code, you'll get that warning.
Here's exactly how to get rid of the warning:

Tap on the specific scroll view in question. Go to Size Inspector (fifth button of right-hand panel), go to the bottom, tap "Ambiguity" and select "never verify"
Note that the intrinsic size placeholder mechanism is not now relevant to this problem.

A: 1) Add a UIView inside scrollview.
2) Give constraints Leading,Trailing,Top,Bottom as 0.
3) Add two extra constraints to UIView Align to centre X and Y.


text:
Q: About non-abelian finite simple groups Let $S$ be a non-abelian finite simple group. Also let $\pi(n)$ be the set of prime divisors of a positive integer $n$. Is it true that $$\big|\pi(|\mathrm{Out}(S)|)-\pi(|S|)\big|<\big|\pi(|S|)\big|?$$
Thanks in advance for your attention.


text:
Q: How to show full object in Chrome console var functor=function(){
    //test
}

functor.prop=1;

console.log(functor);

this only show the function part of the functor, cannot show the properties of the functor in console.

A: this worked perfectly for me:
for(a in array)console.log(array[a])

you can extract any array created in console for find/replace cleanup and posterior usage of this data extracted

A: I made a function of the Trident D'Gao answer.
function print(obj) {
  console.log(JSON.stringify(obj, null, 4));
}

How to use it
print(obj);

A: You might get even better results if you try:
console.log(JSON.stringify(obj, null, 4));

A: Use console.dir() to output a browse-able object you can click through instead of the .toString() version, like this:
console.dir(functor);

Prints a JavaScript representation of the specified object. If the object being logged is an HTML element, then the properties of its DOM representation are printed [1]

[1] https://developers.google.com/web/tools/chrome-devtools/debug/console/console-reference#dir

A: var gandalf = {
  "real name": "Gandalf",
  "age (est)": 11000,
  "race": "Maia",
  "haveRetirementPlan": true,
  "aliases": [
    "Greyhame",
    "Stormcrow",
    "Mithrandir",
    "Gandalf the Grey",
    "Gandalf the White"
  ]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));

A: You might get better results if you try:
console.log(JSON.stringify(functor));

A: I wrote a function to conveniently print things to the console.
// function for debugging stuff
function print(...x) {
    console.log(JSON.stringify(x,null,4));
}

// how to call it
let obj = { a: 1, b: [2,3] };
print('hello',123,obj);

will output in console:
[
    "hello",
    123,
    {
        "a": 1,
        "b": [
            2,
            3
        ]
    }
]

A: With modern browsers, console.log(functor) works perfectly (behaves the same was a console.dir).

A: Another method is to wrap function into an array:
console.log( [functor] );


text:
Q: How to import application properties from iot hub message enrichment into azure data explorer We are using azure iot hub and azure iot edge devices for multiple of our customers. The devices are sending their telemetry data using iot hub telemetry messages. In the iot hub we use message routing -> enrich messages to add the customer id to the messages application properties. This works pretty good if we forward the messages to service bus topics and consume them using azure functions as the application properties are easily accessable there.
Instead of using Azure functions, we now want to store all the telemetry data directly in azure data explorer databases and we want to split the messages to one dedicated database per customer (the name of the database is the customer-id).
So far I could not figure out how to access the application properties from iot hub when importing data to the data explorer? I am not even sure that it is possible, but i really hope it is.

A: Unfortunately automatically routing messages to different databases is not currently supported, please add a request to Azure Data Explorer user voice. For now, you can do the message routing to a dedicated event hub per customer (i.e. per database) and create one Azure Data Explorer data connection per database.
Please note that within a data connection you can dynamically route the messages to different tables by adding the table information to the event properties, see sample here


text:
Q: У меня проблема с Aiogram FSM. Проблема в том что мне нужно писать боту два раза, чтобы он переключил стейт на новый Почему-то мне нужно писать боту два раза чтобы он переключился на след. состояние
async def state1(message: types.Message, state: FSMContext):
    await message.answer('Вы уверены что хотите начать тренировку? да/нет')
    await state.update_data(ans=message.text.lower())
    await reg.check_3.set()

@dp.message_handler(state=reg.check_3)
async def state4(message: types.Message, state=FSMContext):
    ans = message.text.lower()
    if ans == 'да' or ans == 'yes' or ans == 'y':
        await state.update_data(ans=message.text.lower())
        await reg.check_2.set()
    else:
        await message.answer('Тренировка отменена.')
        await state.finish()```

A: await YOUR_STATE.next()
переход к следующему состоянию из класса FSM


text:
Q: Check which user clicked on which link I have few links on my website, how can I record into database which user clicked on which link. I have records of the links into database and users. I have created a table in which there will be userid, linkid. But im not sure how to code this php. Any ideas?
EDIT:
pagename

the link above goes to a page where the link is counted and it looks for the url into the database and redirects to that page. But i want to see which user clicked it.

A: Most easiest way would be to pass a link-identifier as the URI parameter
An example:
pagename

Now you can get what the user clicked by checking $_GET['clicked']

It seems I misunderstood the question
You can do this on your page.php
$id = $_GET['id']; //Get the page id
$userid = $_SESSION['id']; // Get the user id if stored in session

//Do something with the user id

header("location: ..."); //redirect to a different place
exit;

A: Instead of linking to http://www.google.com/ for example, link to:
redirect.php?href=http%3A%2F%2Fwww.google.com%2F
In redirect.php, you INSERT your record into the database and do something like:
 header("Location: ".$_GET['href']);


text:
Q: Difference between two ways of creating arrays I just encountered a problem about an array in Powershell and I just want to understand what was happening.
Why is this way :
$Path = 'C:\'
$File1 = $Path + 'File1.txt'
$File2 = $Path + 'File2.txt'
$Files= @($File1, $File2)

Different from this way :
$Path = 'C:\'
$Files= @($Path + 'File1.txt', $Path + 'File2.txt')

Because with the first one, I can parse it like this :
$Files| ForEach-Object {
    $Test = Get-Item -Path $_
}

But I can't with the second one, unless I created it like this :
$Path = 'C:\'
$Files = @(($Path + 'File1.txt'), ($Path + 'File2.txt'))

Is there another clean way to create an array ?
Thank you !

A: In the first instance, you are creating an array with 2 elements. In the second instance, you are creating an array with a single element. PowerShell is not processing $Path + 'File1.txt' as one.
You can check the number of elements in an array by using $Files.Count: it will show 2 for the first method, and 1 for the second.
You can get around this by using brackets () as you have identified, or using {} to wrap the variable:
$Files= @("${Path}File1.txt", "${Path}File2.txt")

If your plan is to use this in a ForEach-Object, you could just use $Path in that loop:
$Path = 'C:\'
$Files= @('File1.txt', 'File2.txt')

$Files| ForEach-Object {
    $Test = Get-Item -Path "${Path}$_"
}

Addendum
As per Bacon Bits' helpful comment, this is due to Operator Precedence, with , having a higher precedence than +
@($Path + 'File1.txt', $Path + 'File2.txt')

becomes:
($Path) + ('File1.txt', $Path) + ('File2.txt')

instead of:
($Path + 'File1.txt'), ($Path + 'File2.txt')


text:
Q: How can I see if two rectangles have one equal point using java? I have rectangle A = upper left point (-4,-1), bottom right point (-2-2) and rectangle B upper left point (-2,-2), bottom right point (-1,-3)
then:
Rectangle first = new Rectangle(-4,-1,2,1);  //x1,y1,width,height
Rectangle second = new Rectangle(-2,-2,1,1);

OK, I have 2 rectangles with 1 same point.
I use first.intersects(second) and this returns false..
How can I use java to do this, I need something return True if One point or more into Rectangle A belongs Rectangle B?
My code  now:
public class GeometriaRectangle2 {
public static void main(String[] args) {
    Scanner lector = new Scanner(System.in);
    while (lector.hasNextLine()) {
        String a[] = lector.nextLine().split(",");
        int b[] = new int[a.length];

        for (int i = 0; i < a.length; i++) {
            b[i] = Integer.parseInt(a[i]);
        }
        int c = Math.abs(b[0] - b[2]);
        int d = Math.abs(b[1] - b[3]);
        int e = Math.abs(b[4] - b[6]);
        int f = Math.abs(b[5] - b[7]);
        Rectangle r = new Rectangle(b[0], b[1], c, d);
        Rectangle r2 = new Rectangle(b[4], b[5], e, f);
        int tw = r.width;
        int th = r.height;
        int rw = r2.width;
        int rh = r2.height;
        if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
            System.out.println(false);
        }
        int tx = r.x;
        int ty = r.y;
        int rx = r2.x;
        int ry = r2.y;
        rw += rx;
        rh += ry;
        tw += tx;
        th += ty;
        // overflow || intersect or attached
        if ((rw < rx || rw >= tx) && (rh < ry || rh >= ty)
                && (tw < tx || tw >= rx) && (th < ty || th >= ry)) {
            System.out.println(true);
        } else {
            System.out.println(false);
        }
    }
}

}
Example: input:
-3,3,-1,1,1,-1,3,-3
-3,3,-1,1,-2,4,2,2
output:
False
True

A: java.awt.Rectangle is part of AWT and is designed for representing discrete areas in images (and on the screen). Points and dimensions are integers. The intersects() method does what you want, and the rectangles you have given do not intersect. false is the correct value.
Think of pixels in an image. The coordinates of a java.awt.Rectangle are essentially the centers of pixels, the dimensions are the count. So new Rectangle(-4, -1, 2, 1), for example, does not have its bottom right at (-2, -2) as you assume, its bottom right is at (-3, -1):

The upper-most left-most pixel of the red rectangle is the pixel at (-4, -1). The bottom-most right-most pixel is the pixel at (-3, -1). Also note that it does not overlap the blue rectangle.
Even if this were not the case, your rectangles do not intersect. They touch at one point, but do not overlap. Arguably, the intersection is a "rectangle" at (-2, -2) with width 0 and height 0 - which is empty.

A: You may also modifies the current code of intersects function to suit your needs. In your case you want to state it true when there is a pair of points from two rectangles (even the side line's) are sharing the same coordinate - (read: attached). Thus, you may try something like this:
public boolean intersectsOrAttached(Rectangle r, Rectangle r2) {
    int tw = r.width;
    int th = r.height;
    int rw = r2.width;
    int rh = r2.height;
    if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
        return false;
    }

    int tx = r.x;
    int ty = r.y;
    int rx = r2.x;
    int ry = r2.y;
    rw += rx;
    rh += ry;
    tw += tx;
    th += ty;

    //overflow || intersect or attached
    return ((rw < rx || rw >= tx) &&
        (rh < ry || rh >= ty) &&
        (tw < tx || tw >= rx) &&
        (th < ty || th >= ry));
}

UPDATE:
Actually online judging system is a little bit tricky.
I managed to get it accepted partially, I'm not sure whether it's time or memory constraints, as well as some overlooked bound-cases that we couldn't figure out easily.
But here it is, it's better if you can make it optimized by yourself:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class OverlappingRectangles {

    public static void main(String[] args) {
        String f = args[0];
        try {
            BufferedReader br = new BufferedReader(new FileReader(f));
            while (br.ready()) {
                String cs[] = br.readLine().split(",");
                int[] ci = new int[cs.length];
                int i = 0;
                for (String s : cs) {
                    ci[i] = Integer.parseInt(s);
                    i += 1;
                }

                if (ck(ci[0], ci[1], ci[2], ci[3], ci[4], ci[5], ci[6], ci[7])) {
                    System.out.println("True");
                } else {
                    System.out.println("False");
                }
            }
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
    }

    public static boolean ck(int rx, int ry, int rw, int rh, int tx, int ty, int tw, int th) {
        //ATTENTION!
        //rx,ry -> upper-left corner of rect A
        //rw,rh -> bottom-right corner of rect A
        //tx,ty -> upper-left corner of rect B
        //tw,th -> bottom-right corner of rect B
        return ((rw < rx || rw >= tx)
                && (rh < ry || rh >= ty)
                && (tw < tx || tw >= rx)
                && (th < ty || th >= ry));
    }
}


text:
Q: Spring JPA: Data not saved to Database when processing from an Async method I have an app that uses Spring JPA and does some background processes using the @Async spring annotation. The process require saving the parameters in the database or if it already exist update the db.
This doesn't work fine as my data entity doesn't get persisted in the database after the @Async method is done. But when I removed the @Async annotation from the method, all things work fine. My data saved or updated to DB.
Does anyone have an idea what could be wrong or what I may be missing?
Thanks.
** UPDATE [CODE SAMPLE]
ASYNCSERVICE
@Service
@EnableAsync
class AsyncService() {
    @Async
    public void process(firstEntity, secondEntity) {
        firstEntity = prepareParams(firstEntity);
        secondEntity = prepareParams(secondEntity);
        save(firstEntity, secondEntity);
    }
}

ENTITYRELATIONSERVICE
@Transactional
@Service
class EntityRelationService() {

    private SecondEntityRepo secondEntityRepo;

    @Autowired
    public EntityRelationService(SecondEntityRepo secondEntityRepo) {
        this.secondEntityRepo = secondEntityRepo;
    }

    @Transactional
    public void save(p1, p2) {
        p2.setRelation(p1);

        this.secondEntityRepo(p2);
    }
}

BEAN CONFIG
@Bean
@Primary
@ConfigurationProperties(prefix = "app.database")
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}

@Bean
@Primary
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
    sf.setDataSource(dataSource());
    sf.setPackagesToScan("com.app");
    Properties props = new Properties();
    props.put("hibernate.use_sql_comments", false);
    props.put("hibernate.show_sql", true);
    sf.setHibernateProperties(props);
    return sf;
}

@Bean
public HibernateTransactionManager transactionManager() {
    HibernateTransactionManager transactionManager =
            new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactory().getObject());
    return transactionManager;
}

A: I'm guessing the @Async method is on the same class as @Transactional.
Be ware : @Async will make a new thread that will NOT be transactional (so no write in DB). With Spring proxy stuff, your async method need to call a method on another class in order to have the @Transactional back.
In other word, create a new empty class with a @Async method that just call your main method in original class (that have the @Transactional).
A simple example will look like this:
a proxy to the real service:
@Service
@EnableAsync
class AsyncService() {
    private SyncService syncService;

    @Async
    public void process(String param) {
        syncService.process(param);
    }
}

And the real service:
@Service
@Transactional
class SyncService() {
    public void process(String param) {
        // ... Do whatever you want
    }
}

A: I had a similar issue:
Whenever a method (A) throws an exception all changes are rolled back. Also all changes that happened inside other methods that were called from method (A) are rolled back.
My solution was to put the following annotation on a method where I was sure to always save the object no matter what happens elsewhere:
import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void doStuff() {
...
}


text:
Q: Comparison of user account created date + 6 months to current date: how? Im trying to create comparison of user account created date + 6 months and see if its greater than site current date and if it is to block user. (6 month expiration for user accounts)
How can I write rules comparison with numeric compare greater than withing drupal rules? Token is installed.


text:
Q: Does Urbancode Deploy have the ability to share properties across applications? Some other deployment platforms such as Octopus Deploy have the concept of shared variables/properties/values across applications. For instance, there may be 25 applications that all consume an API at a configurable URL. In the case that the URL changes, it would be ideal to change that value in one place.
Is there anything in UCD that supports that type of arrangement?

A: You can set a "system" level variable for this under "Settings"->"Properties" in the top bar. These properties can be referenced with the syntax ${p:system/property-name} and are accessible across all applications.

A: While System level variables are global, the Resource tree variables are likely what you want. The Resource tree is a hierarchical, cascading set of variables that can be overridden at lower branches, but inherit from parent branches.

*

*At the root level, create folder (Resource Group) for each Application

*Under the Application folder, create folder for each
Environment in the Application

*Under the Environment folder, add the Agents (target machines)

*Under the Agents, map the corresponding    Components Add additional
folders as needed or desired

Here is the documentation on resources:
https://www.ibm.com/support/knowledgecenter/en/SS4GSP_7.1.1/com.ibm.udeploy.doc/topics/getstart_resource_create.html


text:
Q: Only one root object is allowed by .kv I am doing an online kivy tutorial. Below is the code that I have written. It is exactly as was in the tutorial video.
But when I run the code I get the following error:
 ...
     1:import FadeTransition kivy.uix.screenmanager.FadeTransition
     2:
 >>  3:ScreenManagement:
     4: transition: FadeTransition()
     5:
 ...
     Only one root object is allowed by .kv

I think the error is with the FadeTransition because I have two instances-MainScreen and AnotherScreen but I do not know how to rectify it. And in the tutorial video the code ran properly. So why isn't it executing in my computer?
Below is the code that I have written
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

class MainScreen(Screen):
   pass

class AnotherScreen(Screen):
   pass

class ScreenManagement(ScreenManager):
   pass

presentation = Builder.load_string('''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
   transition: FadeTransition()
   MainScreen:
   AnotherScreen:

<MainScreen>:
   name: "main"
   Button:
       text: "Next Screen"
       font_size: 50
       on_release: root.app.current = "other"

<AnotherScreen>:
   name: "other"
   Button:
       text: "Back Home"
       font_size: 50
       on_release: root.app.current = "main"

 ''')

 class MainApp(App):
    def build(self):
        return presentation()

 if __name__=="__main__":
     MainApp().run()

Thanks in advance.

A: Try this code it might help a bit took a long time for me to figure it out:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

class MainScreen(Screen):
   pass

class AnotherScreen(Screen):
  pass

class ScreenManagement(ScreenManager):
  pass

presentation = ('''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
   transition: FadeTransition()
   MainScreen:
   AnotherScreen:

<MainScreen>:
   name: "main"
   Button:
      text: "Next Screen"
      font_size: 50
      on_release: root.app.current = "other"

<AnotherScreen>:
   name: "other"
   Button:
      text: "Back Home"
      font_size: 50
      on_release: root.app.current = "main"

''')

class MainApp(App):
   def build(self):
      return Builder.load_string(presentation)

if __name__=="__main__":
    MainApp().run()

A: I came across the exact issue as you while watching the same video. You will need to do this instead (assuming you want a fade transition):
Main.py file:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

class ScreenManagement(ScreenManager): #here you are creating a screen manager called ScreenManagement
    pass
class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

presentation = Builder.load_file("Main2.kv") #telling the app which .kv file to use

class MainApp(App):
    def build(self):
        return presentation

runMain = MainApp()
runMain.run()

Now over to your Main2.kv file:
#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition() #telling the screen manager to use a fade transition
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: "main" #this name is what the screen manager uses to distinguish which screen to go to
    Button:
        text: "Go To Next Screen"
        color:0,0,0,1
        background_color: 1,1,1,1
        size_hint: 1,0.10
        pos:0,200
        font_size: 30
        on_release: app.root.current = "another" #the screen that the screen manager is told to go to

<AnotherScreen>:
    name: "another"
    Button:
        text: "Go To Main Screen"
        color:0,0,0,1
        background_color: 1,1,1,1
        size_hint: 1,0.10
        pos:0,200
        font_size: 30
        on_release: app.root.current = "main"

Hope that helped.

A: In your kv file, you need to surround ScreenManagement class with "<" and ">" as shown in the example below.
main.py
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen

class ScreenManagement(ScreenManager):
    pass

class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

class MainApp(App):
    def build(self):
        return ScreenManagement()

if __name__ == "__main__":
    MainApp().run()

main.kv
#: import FadeTransition kivy.uix.screenmanager.FadeTransition

<ScreenManagement>:
    transition: FadeTransition()
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: "main"
    Button:
        text: "Go To Next Screen"
        color:0,0,0,1
        background_color: 1,1,1,1
        size_hint: 1,0.10
        pos:0,200
        font_size: 30
        on_release: app.root.current = "another"

<AnotherScreen>:
    name: "another"
    Button:
        text: "Go To Main Screen"
        color:0,0,0,1
        background_color: 1,1,1,1
        size_hint: 1,0.10
        pos:0,200
        font_size: 30
        on_release: app.root.current = "main"

Output


text:
Q: How to redirect from http to https in react? My Audits in Chrome are showing me a net::ERR_EMPTY_RESPONSE because Lighthouse was unable to reliably load the page I requested. Google developers is giving me the suggestion to configure my server (node.js?) to redirect from http to https.
I tried the react module "react-https-redirect", but still not passing the audit. I implemented the module like so:
render() {
    return (
            <HttpsRedirect>
              <App />
            </HttpsRedirect>
    );
}

What do I have to configure to realise the automatic redirection?

A: Answer is here you should use react-https-redirect but as the author says there is some security issues with this. if you can configure the server or use nginx as gateway that would be better than using this module.


text:
Q: MongoDB : does Collection.Find() support promise I was trying to revamp an old Nodejs web service to replace callback functions with chained promises.
When querying mongodb we used the syntax below to iterate through a result set.
collection.find(filter).toArray(function(err, items) {
          if (err) {
            throw(err);
          } else {
            console.log(items);

          }

If I try to replace the .toArray() section with a .then() I get the below error "col.find(...).then is not a function".
If I replace .find() with .findOne().then(), the code works perfectly.
Any help is appreciated.

A: find returns a Cursor, but the cursor's toArray method returns a promise. So you can do:
collection.find(filter).toArray().then(...)

A: I assume you're using mongoosejs.
collection.find() is just a query.  To cause it to execute and return a promise, you need to call .exec() on it.:
collection.find(filter).exec()
    .then(items => console.log(items))
    .catch(err => { // handle error })

The mongoose docs give you more details on how to use mongoose with either callbacks or promises:  https://mongoosejs.com/docs/api.html#model_Model.find


text:
Q: Android Accelerometer Issue My game uses the accelerometer, everything works fine but I noticed there is going to be a slight issue with some phones. The game forces the orientation to be landscape however some phones have a default screen orientation of landscape...
Right now I was always assuming the user was going to have to tilt their phone to see the game correctly, this would mean the accelerometer reading for the X axis would move the player in the Y and the Y reading would move the player in the X. With the phones that have a default landscape screen the X will correspond to the X in game and the Y for the Y in game (as they wont need to tilt their phones.)
My question is how do I handle this? I can adapt the code to invert the X and Y directions based on the phones orientation, so how would I get the current orientation of the phone programmatically? If there is a better way that would be great
Hope that makes sense
EDIT:
Actually would it be safe to assume that if the devices length is greater than its height the screen would be defaulted to landscape?

A: Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();

from http://developer.android.com/reference/android/view/Display.html:

public int getRotation ()
Returns the rotation of the screen from its "natural" orientation. The
  returned value may be Surface.ROTATION_0 (no rotation),
  Surface.ROTATION_90, Surface.ROTATION_180, or Surface.ROTATION_270.
  For example, if a device has a naturally tall screen, and the user has
  turned it on its side to go into a landscape orientation, the value
  returned here may be either Surface.ROTATION_90 or
  Surface.ROTATION_270 depending on the direction it was turned. The
  angle is the rotation of the drawn graphics on the screen, which is
  the opposite direction of the physical rotation of the device. For
  example, if the device is rotated 90 degrees counter-clockwise, to
  compensate rendering will be rotated by 90 degrees clockwise and thus
  the returned value here will be Surface.ROTATION_90.

You'll have to experiment with the devices to make sure android knows the "natural" orientation correctly. If so, then just check for ROTATION_90 (or ROTATION_270) to see if the device is on it's side or not. If so, then switch x and y axis.

A: Here a solution provided by NVidia to deal nicely with the device default orientation:
https://stackoverflow.com/a/14313663/1489493


text:
Q: C ASCII value of extended character set In this link you can see that the extended ASCII value is 'ÿ' is 255.
When I try to print it in C typecasted to integer
printf("%u \n", 'ÿ');   [In]
warning: multi-character character constant [-Wmultichar] [Out]

Actually I need to read a file containing four such characters and use their extended ASCII values (characters may have any extended ASCII value from 0 to 255)
Any tips or suggestions on how to do so (I was using fscanf to perform this operation but open to other ways/any way).


text:
Q: Spring JPA Specify entity's table name on the repository interface I have a scenario where I want to create multiple repositories for the same entity class.
The first and simplest scenario I want to save some of the instances of my class as rows in a different table than the primary table (which is designated on the entity itself).
other scenarios would be to create remote back ups hence the whole datasource would be different.
Does Spring allow things like that?

A: I'm not sure you'll want this, but here it is anyway... The best I could find using Spring Data Repositories is the following:
(1a) Manually define 2 repository beans to use 2 datasources:
@Bean
@Qualifier("db1")
public ModelJpaRepository modelJpaRepositoryDb1() {
    JpaRepositoryFactoryBean<ModelJpaRepository, Model, String> myFactory = new JpaRepositoryFactoryBean<ModelJpaRepository, Model, String>();
    myFactory.setRepositoryInterface(ModelJpaRepository.class);
    myFactory.setEntityManager(entityManagerFactory1().createEntityManager());
    myFactory.afterPropertiesSet();
    return myFactory.getObject();
}

@Bean
@Qualifier("db2")
public ModelJpaRepository modelJpaRepositoryDb2() {
    JpaRepositoryFactoryBean<ModelJpaRepository, Model, String> myFactory = new JpaRepositoryFactoryBean<ModelJpaRepository, Model, String>();
    myFactory.setRepositoryInterface(ModelJpaRepository.class);
    myFactory.setEntityManager(entityManagerFactory2().createEntityManager());
    myFactory.afterPropertiesSet();
    return myFactory.getObject();
}

(1b): Define the 2 datasources (referred to by the previous repository definitions):
@Bean(name = "dataSource1")
public DataSource dataSource1() {
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName(...);
    bds.setUrl(...);
    bds.setUsername(...);
    bds.setPassword(...);
    return bds;
}

@Bean(name = "dataSource2")
public DataSource dataSource2() {
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName(...);
    bds.setUrl(...);
    bds.setUsername(...);
    bds.setPassword(...);
    return bds;
}

(1c): Define 2 entityManagers - 1 per datasource (referred to by the previous repository definitions):
@Bean
public EntityManagerFactory entityManagerFactory1() {
    LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactory.setDataSource(dataSource1());
    entityManagerFactory.setPersistenceUnitName("pu1");
    entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
    entityManagerFactory.setJpaProperties(jpaProperties());
    entityManagerFactory.afterPropertiesSet();
    return entityManagerFactory.getNativeEntityManagerFactory();
}

@Bean
public EntityManagerFactory entityManagerFactory2() {
    LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactory.setDataSource(dataSource2());
    entityManagerFactory.setPersistenceUnitName("pu2");
    entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
    entityManagerFactory.setJpaProperties(jpaProperties());
    entityManagerFactory.afterPropertiesSet();
    return entityManagerFactory.getNativeEntityManagerFactory();
}

(2) Inject the 2 repositories and use them:
@Autowired
@Qualifier("db1")
private ModelJpaRepository modelJpaRepositoryDb1;

@Autowired
@Qualifier("db2")
private ModelJpaRepository modelJpaRepositoryDb2;

...

modelJpaRepositoryDb1.save(model);
modelJpaRepositoryDb2.save(model);

(3) Define the "OtherModel" and include the "Model" as embedded:
@Entity
@Table(name = "OTHER_TABLE")
public class OtherTable {

    @Id
    @Column(name = "ID", nullable = false)
    private long id;

    @Embedded
    private Model model;

    public OtherTable(Model model) {
        this.model = model;
        this.id = model.getId();
    }
}

For info, This answer suggests using @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS), to achieve define an additional model (inheritance vs composition).
(4) Define the 2 repositories for the OtherTable:
@Bean
@Qualifier("db1")
public OtherTableJpaRepository otherTableJpaRepositoryDb1() {
    JpaRepositoryFactoryBean<OtherTableJpaRepository, OtherTable, String> myFactory = new JpaRepositoryFactoryBean<OtherTableJpaRepository, OtherTable, String>();
    myFactory.setRepositoryInterface(OtherTableJpaRepository.class);
    myFactory.setEntityManager(entityManagerFactory1().createEntityManager());
    myFactory.afterPropertiesSet();
    return myFactory.getObject();
}

@Bean
@Qualifier("db2")
public OtherTableJpaRepository otherTableJpaRepositoryDb2() {
    JpaRepositoryFactoryBean<OtherTableJpaRepository, OtherTable, String> myFactory = new JpaRepositoryFactoryBean<OtherTableJpaRepository, OtherTable, String>();
    myFactory.setRepositoryInterface(OtherTableJpaRepository.class);
    myFactory.setEntityManager(entityManagerFactory2().createEntityManager());
    myFactory.afterPropertiesSet();
    return myFactory.getObject();
}

(5) Inject and use them all:
@Autowired
@Qualifier("db1")
private ModelJpaRepository modelJpaRepositoryDb1;

@Autowired
@Qualifier("db2")
private ModelJpaRepository modelJpaRepositoryDb2;

@Autowired
@Qualifier("db1")
private OtherTableJpaRepository otherTableJpaRepositoryDb1;

@Autowired
@Qualifier("db2")
private OtherTableJpaRepository otherTableJpaRepositoryDb2;

// ...

modelJpaRepositoryDb1.save(model);
otherTableJpaRepositoryDb1.save(new OtherTable(model));

modelJpaRepositoryDb2.save(model);
otherTableJpaRepositoryDb2.save(new OtherTable(model));


text:
Q: How to focus input date field in react? Could you please tell me How to focus input date field in react?I am using a plugin of semantic
https://www.npmjs.com/package/semantic-ui-calendar-react
I want to focus date input field on button click here is my code.
here is my code
https://codesandbox.io/s/3l414mno5
focus = () => {
    console.log(this.a);
    this.a[0].onFocus();
    // this.inputRef.focus()
  };

the focus is not coming in input field why?
any update ?

A: To enable a focus on button click, you need to set a ref like this :
    this.logButton = React.createRef();
    ref={this.logButton}

and access it in button click like below:
focus = e => {
    this.logButton.current.openPopup();
};

openPopup()  - is a fucntion to open the calendar popup, the plugin your using, has code like this, check here
demo and In multiple data fields, use dynamic refs. Hope it helps.


text:
Q: Issues in filtering rows using np.where I am trying to assign values to rows where a condition is verified (True/False).
for i in range(0,3):

new_dataset=df[str(i)][df[str(i)]["Current Amount"] != "3m"]
  for i in range(0,3):
    df[i]['Value'] = np.where(df[i]['Amount']== True, 100, 50)

where i can span from 0 to 3. Value is the new column that I would like to create; Amount is a column already existing in the original dataframe. In the first part, I create new dataframes filtering rows having current amounts equal to 3 million.
However I got the following error:
   /anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:4: SettingWithCopyWarning:
    A value is trying to be set on a copy of a slice from a DataFrame.
    Try using .loc[row_indexer,col_indexer] = value instead

    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
      after removing the cwd from sys.path.

I have tried to follow the steps suggested in this post: How to deal with SettingWithCopyWarning in Pandas?, but it seems that it is still continuing to be not clear to me how to fix the issue.
Could you please help me to fix the issue? I would really appreciate it.

A: Why is not used solution without [i] and compare by True if column is boolean?
df['Value'] = np.where(df['Amount'], 100, 50)

EDIT: Here is necessary DataFrame.copy:
new_dataset=df[str(i)][df[str(i)]["Current Amount"] != "3m"].copy()


text:
Q: Append one value from a dictionary to a list Currently I'm working on program that has a large dictionary containing all cards from a normal deck of cards.
What I want to do is append every card used to a list. I'll use randint() to generate a random integer which will pick the card number.
cards = {1.1:"Ace of Spades",
     1.2:"Ace of Clubs",
     1.3:"Ace of Diamonds",
     1.4:"Ace of Hearts",

     2.1:"Two of Spades",
     2.2:"Two of Clubs",
     2.3:"Two of Diamonds",
     2.4:"Two of Hearts",

     3.1:"Three of Spades",
     3.2:"Three of Clubs",
     3.3:"Three of Diamonds",
     3.4:"Three of Hearts",

     4.1:"Four of Spades",
     4.2:"Four of Clubs",
     4.3:"Four of Diamonds",
     4.4:"Four of Hearts",

and then another to pick the suit. Then I want to append the value of the card chosen to a list. So say for example I pick 3.2, which is the three of clubs. I'd want to append that value to a list all automatically.
So one integer is generated. Say 6, another value is randomly generated, say 3,the card would be 6 of Diamonds, I'd want to append the second value, which would be "Six of Diamonds" to the list.
How would I do this?

A: # you do not have to write all the names of cards. you can use loop method.
# first create a list of suit and rank names and an empty list for cards.
# then use for loop and append all cards to a list.

suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
cards=[]
for rank in rank_names:
    for suit in suit_names:
        cards.append(rank+' of '+suit)

print cards

# import random. random has a built in method which chooses elements from list randomly; you can use it instead of ranint.
import random
removed_cards=[]
# create ans empty list for removed cards and append randomly chosen cards to that list.
removed_cards.append(random.choice(cards))

A: Try appending it to a list.
Code:
import random

cards = {1.1:"Ace of Spades",
     1.2:"Ace of Clubs",
     1.3:"Ace of Diamonds",
     1.4:"Ace of Hearts",
      2.1:"Two of Spades",
     2.2:"Two of Clubs",
     2.3:"Two of Diamonds",
     2.4:"Two of Hearts",

     3.1:"Three of Spades",
     3.2:"Three of Clubs",
     3.3:"Three of Diamonds",
     3.4:"Three of Hearts",

     4.1:"Four of Spades",
     4.2:"Four of Clubs",
     4.3:"Four of Diamonds",
     4.4:"Four of Hearts"}

used_cards = []

def add_card():
    used_cards.append(cards[random.randint(1, 5) + random.randint(1, 5) * 0.1])

add_card()
add_card()

print used_cards

Output:
['Three of Diamonds', 'Three of Spades']

PS:
Considering my not complete cards dictionary, this part
cards[random.randint(1, 5) + random.randint(1, 5) * 0.1

generates the random number to get the random card. You may want to modify the range(1, x) to the number you require.
Edit:
As @Peter DeGlopper said, you may want to change the way you are storing the cards in the dictionary. You could use a tuple like (1, 1) instead of 1.1, to avoid floating point inaccuracies.


text:
Q: php preg_replace for all occurences of specific html tag I'm going to replace all
CONTENT
 content .

m1

 lets go

m2

but running preg_replace("/<pre(.*)<\/pre>/s", "SAMAN", $input_lines); would output this:
SAMAN

while i need this output:
SAMAN lets go SAMAN

here is my live test result

A: * quantifier is greedy, append it with ? to turn it into non-greedy. i.e. your regex should be: /<pre(.*?)<\/pre>/s

A: The Code is:
<?php
$input_lines='
m1

 lets go

m2

';

$new_string=preg_replace("/(\r?\n?
\r?\n?)/s","SAMAN",$input_lines);
echo $new_string;
?>

Outputs:
SAMAN lets go SAMAN

Regex Pattern Explanation:
(                   # Begin capture group
    \r?\n?          # Optional newline characters on Windows and Linux

   # Match from opening pre tag to closing pre tag
    \r?\n?          # Optional newline characters on Windows and Linux
)                   # End capture group
/s                  # Force all dots in pattern to allow newline characters

My answer very closely resembles LeleDumbo's answer which probably performs to the asker's satisfaction.  I merely omitted the unnecessary < from the closing pre tag, and included some newline characters so that $new_string doesn't have any hidden characters in it (this may or may not be an issue depending on usage).


text:
Q: Google Street View with deviceorientation (Full Tilt) I am trying to create a Google Street View that can be controlled via a devices orientation.
I am using Full Tilt to normalize devices / OS and it seems to be doing a really good job. In fact, it seems very close indeed to the solution I'm after.
However, at various positions, the view seems to jump rapidly (although it seems to resolve to the correct location) and is not as smooth as I would like. This seems particularly obvious if the device is held at around 90 degrees (upright) and rotated slightly to the left or right.
JS Fiddle has an example and would need to be viewed on a mobile device or tablet to see the effect. Following the link further down will only work if you can get to the edit mode where the deviceorientation is allowed to work.
Any ideas if there is a way to resolve this? Or if I'm on to a loser here?

var map;

google.maps.event.addDomListener(window, "load", function () {

  // Set up map
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    // Initial
    center:{
      lat: 35.6735408,
      lng: 139.570305,
    },
    disableDefaultUI: true,
    streetViewControl: true,
  });

  // Set up street view
  google.maps.streetViewViewer = 'photosphere';
  var street_view = new google.maps.StreetViewPanorama(document.getElementById('street-view'), {
    addressControl: false,
    fullscreenControl: false,
    zoomControl: false,
  });
  street_view.setPano('2qVB_HA94-kQCAzwffO44g');

  // When street view ready, update map position and pov
  street_view.addListener('status_changed', function(){
    var position = street_view.getPosition();
    if( map ){
      map.setCenter(position);
      map.setStreetView(street_view);
    }
  });

  // FULL TILT ORIENTATION
  var promise = new FULLTILT.getDeviceOrientation({ 'type': 'world' });

  var deviceOrientation;

  promise
  .then(function(controller) {
    deviceOrientation = controller;
  })
  .catch(function(message) {
    console.error(message);
  });

  (function draw() {

    if (deviceOrientation) {

      var euler = deviceOrientation.getScreenAdjustedEuler();

   //  debug
   console.log('alpha: %d, beta: %d, gamma: %d', euler.alpha, euler.beta, euler.gamma);
      document.getElementById('alpha').innerHTML = euler.alpha.toFixed(2);
      document.getElementById('beta').innerHTML = euler.beta.toFixed(2);
      document.getElementById('gamma').innerHTML = euler.gamma.toFixed(2);

      // Set POV
      if( euler.alpha != 0 && euler.beta != 0 && euler.gamma !=0 ){
       street_view.setPov({
          heading: euler.alpha*-1,
          pitch: euler.beta-90,
        });
      }
    }
    requestAnimationFrame(draw);
  })();

});

/*! Full Tilt v0.5.2 / http://github.com/richtr/Full-Tilt */
!function(a){function b(a){return a=+a,0===a||isNaN(a)?a:a>0?1:-1}function c(a){var b=new Promise(function(b,c){var d=function(e){setTimeout(function(){a&&a.data?b():e>=20?c():d(++e)},50)};d(0)});return b}function d(){o=n?(a.screen.orientation.angle||0)*j:(a.orientation||0)*j}function e(a){l.orientation.data=a;for(var b in l.orientation.callbacks)l.orientation.callbacks[b].call(this)}function f(a){l.motion.data=a;for(var b in l.motion.callbacks)l.motion.callbacks[b].call(this)}if(void 0===a.FULLTILT||null===a.FULLTILT){var g=Math.PI,h=g/2,i=2*g,j=g/180,k=180/g,l={orientation:{active:!1,callbacks:[],data:void 0},motion:{active:!1,callbacks:[],data:void 0}},m=!1,n=a.screen&&a.screen.orientation&&void 0!==a.screen.orientation.angle&&null!==a.screen.orientation.angle?!0:!1,o=(n?a.screen.orientation.angle:a.orientation||0)*j,p=h,q=g,r=i/3,s=-h,t={};t.version="0.5.2",t.getDeviceOrientation=function(a){var b=new Promise(function(b,d){var e=new t.DeviceOrientation(a);e.start();var f=new c(l.orientation);f.then(function(){e._alphaAvailable=l.orientation.data.alpha&&null!==l.orientation.data.alpha,e._betaAvailable=l.orientation.data.beta&&null!==l.orientation.data.beta,e._gammaAvailable=l.orientation.data.gamma&&null!==l.orientation.data.gamma,b(e)}).catch(function(){e.stop(),d("DeviceOrientation is not supported")})});return b},t.getDeviceMotion=function(a){var b=new Promise(function(b,d){var e=new t.DeviceMotion(a);e.start();var f=new c(l.motion);f.then(function(){e._accelerationXAvailable=l.motion.data.acceleration&&l.motion.data.acceleration.x,e._accelerationYAvailable=l.motion.data.acceleration&&l.motion.data.acceleration.y,e._accelerationZAvailable=l.motion.data.acceleration&&l.motion.data.acceleration.z,e._accelerationIncludingGravityXAvailable=l.motion.data.accelerationIncludingGravity&&l.motion.data.accelerationIncludingGravity.x,e._accelerationIncludingGravityYAvailable=l.motion.data.accelerationIncludingGravity&&l.motion.data.accelerationIncludingGravity.y,e._accelerationIncludingGravityZAvailable=l.motion.data.accelerationIncludingGravity&&l.motion.data.accelerationIncludingGravity.z,e._rotationRateAlphaAvailable=l.motion.data.rotationRate&&l.motion.data.rotationRate.alpha,e._rotationRateBetaAvailable=l.motion.data.rotationRate&&l.motion.data.rotationRate.beta,e._rotationRateGammaAvailable=l.motion.data.rotationRate&&l.motion.data.rotationRate.gamma,b(e)}).catch(function(){e.stop(),d("DeviceMotion is not supported")})});return b},t.Quaternion=function(a,c,d,e){var f;this.set=function(a,b,c,d){this.x=a||0,this.y=b||0,this.z=c||0,this.w=d||1},this.copy=function(a){this.x=a.x,this.y=a.y,this.z=a.z,this.w=a.w},this.setFromEuler=function(){var a,b,c,d,e,f,g,h,i,k,l,m;return function(n){return n=n||{},c=(n.alpha||0)*j,a=(n.beta||0)*j,b=(n.gamma||0)*j,f=c/2,d=a/2,e=b/2,g=Math.cos(d),h=Math.cos(e),i=Math.cos(f),k=Math.sin(d),l=Math.sin(e),m=Math.sin(f),this.set(k*h*i-g*l*m,g*l*i+k*h*m,g*h*m+k*l*i,g*h*i-k*l*m),this.normalize(),this}}(),this.setFromRotationMatrix=function(){var a;return function(c){return a=c.elements,this.set(.5*Math.sqrt(1+a[0]-a[4]-a[8])*b(a[7]-a[5]),.5*Math.sqrt(1-a[0]+a[4]-a[8])*b(a[2]-a[6]),.5*Math.sqrt(1-a[0]-a[4]+a[8])*b(a[3]-a[1]),.5*Math.sqrt(1+a[0]+a[4]+a[8])),this}}(),this.multiply=function(a){return f=t.Quaternion.prototype.multiplyQuaternions(this,a),this.copy(f),this},this.rotateX=function(a){return f=t.Quaternion.prototype.rotateByAxisAngle(this,[1,0,0],a),this.copy(f),this},this.rotateY=function(a){return f=t.Quaternion.prototype.rotateByAxisAngle(this,[0,1,0],a),this.copy(f),this},this.rotateZ=function(a){return f=t.Quaternion.prototype.rotateByAxisAngle(this,[0,0,1],a),this.copy(f),this},this.normalize=function(){return t.Quaternion.prototype.normalize(this)},this.set(a,c,d,e)},t.Quaternion.prototype={constructor:t.Quaternion,multiplyQuaternions:function(){var a=new t.Quaternion;return function(b,c){var d=b.x,e=b.y,f=b.z,g=b.w,h=c.x,i=c.y,j=c.z,k=c.w;return a.set(d*k+g*h+e*j-f*i,e*k+g*i+f*h-d*j,f*k+g*j+d*i-e*h,g*k-d*h-e*i-f*j),a}}(),normalize:function(a){var b=Math.sqrt(a.x*a.x+a.y*a.y+a.z*a.z+a.w*a.w);return 0===b?(a.x=0,a.y=0,a.z=0,a.w=1):(b=1/b,a.x*=b,a.y*=b,a.z*=b,a.w*=b),a},rotateByAxisAngle:function(){var a,b,c=new t.Quaternion,d=new t.Quaternion;return function(e,f,g){return a=(g||0)/2,b=Math.sin(a),d.set((f[0]||0)*b,(f[1]||0)*b,(f[2]||0)*b,Math.cos(a)),c=t.Quaternion.prototype.multiplyQuaternions(e,d),t.Quaternion.prototype.normalize(c)}}()},t.RotationMatrix=function(a,b,c,d,e,f,g,h,i){var k;this.elements=new Float32Array(9),this.identity=function(){return this.set(1,0,0,0,1,0,0,0,1),this},this.set=function(a,b,c,d,e,f,g,h,i){this.elements[0]=a||1,this.elements[1]=b||0,this.elements[2]=c||0,this.elements[3]=d||0,this.elements[4]=e||1,this.elements[5]=f||0,this.elements[6]=g||0,this.elements[7]=h||0,this.elements[8]=i||1},this.copy=function(a){this.elements[0]=a.elements[0],this.elements[1]=a.elements[1],this.elements[2]=a.elements[2],this.elements[3]=a.elements[3],this.elements[4]=a.elements[4],this.elements[5]=a.elements[5],this.elements[6]=a.elements[6],this.elements[7]=a.elements[7],this.elements[8]=a.elements[8]},this.setFromEuler=function(){var a,b,c,d,e,f,g,h,i;return function(k){return k=k||{},c=(k.alpha||0)*j,a=(k.beta||0)*j,b=(k.gamma||0)*j,d=Math.cos(a),e=Math.cos(b),f=Math.cos(c),g=Math.sin(a),h=Math.sin(b),i=Math.sin(c),this.set(f*e-i*g*h,-d*i,e*i*g+f*h,e*i+f*g*h,f*d,i*h-f*e*g,-d*h,g,d*e),this.normalize(),this}}(),this.setFromQuaternion=function(){var a,b,c,d;return function(e){return a=e.w*e.w,b=e.x*e.x,c=e.y*e.y,d=e.z*e.z,this.set(a+b-c-d,2*(e.x*e.y-e.w*e.z),2*(e.x*e.z+e.w*e.y),2*(e.x*e.y+e.w*e.z),a-b+c-d,2*(e.y*e.z-e.w*e.x),2*(e.x*e.z-e.w*e.y),2*(e.y*e.z+e.w*e.x),a-b-c+d),this}}(),this.multiply=function(a){return k=t.RotationMatrix.prototype.multiplyMatrices(this,a),this.copy(k),this},this.rotateX=function(a){return k=t.RotationMatrix.prototype.rotateByAxisAngle(this,[1,0,0],a),this.copy(k),this},this.rotateY=function(a){return k=t.RotationMatrix.prototype.rotateByAxisAngle(this,[0,1,0],a),this.copy(k),this},this.rotateZ=function(a){return k=t.RotationMatrix.prototype.rotateByAxisAngle(this,[0,0,1],a),this.copy(k),this},this.normalize=function(){return t.RotationMatrix.prototype.normalize(this)},this.set(a,b,c,d,e,f,g,h,i)},t.RotationMatrix.prototype={constructor:t.RotationMatrix,multiplyMatrices:function(){var a,b,c=new t.RotationMatrix;return function(d,e){return a=d.elements,b=e.elements,c.set(a[0]*b[0]+a[1]*b[3]+a[2]*b[6],a[0]*b[1]+a[1]*b[4]+a[2]*b[7],a[0]*b[2]+a[1]*b[5]+a[2]*b[8],a[3]*b[0]+a[4]*b[3]+a[5]*b[6],a[3]*b[1]+a[4]*b[4]+a[5]*b[7],a[3]*b[2]+a[4]*b[5]+a[5]*b[8],a[6]*b[0]+a[7]*b[3]+a[8]*b[6],a[6]*b[1]+a[7]*b[4]+a[8]*b[7],a[6]*b[2]+a[7]*b[5]+a[8]*b[8]),c}}(),normalize:function(a){var b=a.elements,c=b[0]*b[4]*b[8]-b[0]*b[5]*b[7]-b[1]*b[3]*b[8]+b[1]*b[5]*b[6]+b[2]*b[3]*b[7]-b[2]*b[4]*b[6];return b[0]/=c,b[1]/=c,b[2]/=c,b[3]/=c,b[4]/=c,b[5]/=c,b[6]/=c,b[7]/=c,b[8]/=c,a.elements=b,a},rotateByAxisAngle:function(){var a,b,c=new t.RotationMatrix,d=new t.RotationMatrix,e=!1;return function(f,g,h){return d.identity(),e=!1,a=Math.sin(h),b=Math.cos(h),1===g[0]&&0===g[1]&&0===g[2]?(e=!0,d.elements[4]=b,d.elements[5]=-a,d.elements[7]=a,d.elements[8]=b):1===g[1]&&0===g[0]&&0===g[2]?(e=!0,d.elements[0]=b,d.elements[2]=a,d.elements[6]=-a,d.elements[8]=b):1===g[2]&&0===g[0]&&0===g[1]&&(e=!0,d.elements[0]=b,d.elements[1]=-a,d.elements[3]=a,d.elements[4]=b),e?(c=t.RotationMatrix.prototype.multiplyMatrices(f,d),c=t.RotationMatrix.prototype.normalize(c)):c=f,c}}()},t.Euler=function(a,b,c){this.set=function(a,b,c){this.alpha=a||0,this.beta=b||0,this.gamma=c||0},this.copy=function(a){this.alpha=a.alpha,this.beta=a.beta,this.gamma=a.gamma},this.setFromRotationMatrix=function(){var a,b,c,d;return function(e){a=e.elements,a[8]>0?(b=Math.atan2(-a[1],a[4]),c=Math.asin(a[7]),d=Math.atan2(-a[6],a[8])):a[8]<0?(b=Math.atan2(a[1],-a[4]),c=-Math.asin(a[7]),c+=c>=0?-g:g,d=Math.atan2(a[6],-a[8])):a[6]>0?(b=Math.atan2(-a[1],a[4]),c=Math.asin(a[7]),d=-h):a[6]<0?(b=Math.atan2(a[1],-a[4]),c=-Math.asin(a[7]),c+=c>=0?-g:g,d=-h):(b=Math.atan2(a[3],a[0]),c=a[7]>0?h:-h,d=0),0>b&&(b+=i),b*=k,c*=k,d*=k,this.set(b,c,d)}}(),this.setFromQuaternion=function(){var a,b,c;return function(d){var e=d.w*d.w,f=d.x*d.x,j=d.y*d.y,l=d.z*d.z,m=e+f+j+l,n=d.w*d.x+d.y*d.z,o=1e-6;if(n>(.5-o)*m)a=2*Math.atan2(d.y,d.w),b=h,c=0;else if((-.5+o)*m>n)a=-2*Math.atan2(d.y,d.w),b=-h,c=0;else{var p=e-f+j-l,q=2*(d.w*d.z-d.x*d.y),r=e-f-j+l,s=2*(d.w*d.y-d.x*d.z);r>0?(a=Math.atan2(q,p),b=Math.asin(2*n/m),c=Math.atan2(s,r)):(a=Math.atan2(-q,-p),b=-Math.asin(2*n/m),b+=0>b?g:-g,c=Math.atan2(-s,-r))}0>a&&(a+=i),a*=k,b*=k,c*=k,this.set(a,b,c)}}(),this.rotateX=function(a){return t.Euler.prototype.rotateByAxisAngle(this,[1,0,0],a),this},this.rotateY=function(a){return t.Euler.prototype.rotateByAxisAngle(this,[0,1,0],a),this},this.rotateZ=function(a){return t.Euler.prototype.rotateByAxisAngle(this,[0,0,1],a),this},this.set(a,b,c)},t.Euler.prototype={constructor:t.Euler,rotateByAxisAngle:function(){var a=new t.RotationMatrix;return function(b,c,d){return a.setFromEuler(b),a=t.RotationMatrix.prototype.rotateByAxisAngle(a,c,d),b.setFromRotationMatrix(a),b}}()},t.DeviceOrientation=function(b){this.options=b||{};var c=0,d=200,e=0,f=10;if(this.alphaOffsetScreen=0,this.alphaOffsetDevice=void 0,"game"===this.options.type){var g=function(b){return null!==b.alpha&&(this.alphaOffsetDevice=new t.Euler(b.alpha,0,0),this.alphaOffsetDevice.rotateZ(-o),++e>=f)?void a.removeEventListener("deviceorientation",g,!1):void(++c>=d&&a.removeEventListener("deviceorientation",g,!1))}.bind(this);a.addEventListener("deviceorientation",g,!1)}else if("world"===this.options.type){var h=function(b){return b.absolute!==!0&&void 0!==b.webkitCompassAccuracy&&null!==b.webkitCompassAccuracy&&+b.webkitCompassAccuracy>=0&&+b.webkitCompassAccuracy<50&&(this.alphaOffsetDevice=new t.Euler(b.webkitCompassHeading,0,0),this.alphaOffsetDevice.rotateZ(o),this.alphaOffsetScreen=o,++e>=f)?void a.removeEventListener("deviceorientation",h,!1):void(++c>=d&&a.removeEventListener("deviceorientation",h,!1))}.bind(this);a.addEventListener("deviceorientation",h,!1)}},t.DeviceOrientation.prototype={constructor:t.DeviceOrientation,start:function(b){b&&"[object Function]"==Object.prototype.toString.call(b)&&l.orientation.callbacks.push(b),m||(n?a.screen.orientation.addEventListener("change",d,!1):a.addEventListener("orientationchange",d,!1)),l.orientation.active||(a.addEventListener("deviceorientation",e,!1),l.orientation.active=!0)},stop:function(){l.orientation.active&&(a.removeEventListener("deviceorientation",e,!1),l.orientation.active=!1)},listen:function(a){this.start(a)},getFixedFrameQuaternion:function(){var a=new t.Euler,b=new t.RotationMatrix,c=new t.Quaternion;return function(){var d=l.orientation.data||{alpha:0,beta:0,gamma:0},e=d.alpha;return this.alphaOffsetDevice&&(b.setFromEuler(this.alphaOffsetDevice),b.rotateZ(-this.alphaOffsetScreen),a.setFromRotationMatrix(b),a.alpha<0&&(a.alpha+=360),e-=a.alpha),a.set(e,d.beta,d.gamma),c.setFromEuler(a),c}}(),getScreenAdjustedQuaternion:function(){var a;return function(){return a=this.getFixedFrameQuaternion(),a.rotateZ(-o),a}}(),getFixedFrameMatrix:function(){var a=new t.Euler,b=new t.RotationMatrix;return function(){var c=l.orientation.data||{alpha:0,beta:0,gamma:0},d=c.alpha;return this.alphaOffsetDevice&&(b.setFromEuler(this.alphaOffsetDevice),b.rotateZ(-this.alphaOffsetScreen),a.setFromRotationMatrix(b),a.alpha<0&&(a.alpha+=360),d-=a.alpha),a.set(d,c.beta,c.gamma),b.setFromEuler(a),b}}(),getScreenAdjustedMatrix:function(){var a;return function(){return a=this.getFixedFrameMatrix(),a.rotateZ(-o),a}}(),getFixedFrameEuler:function(){var a,b=new t.Euler;return function(){return a=this.getFixedFrameMatrix(),b.setFromRotationMatrix(a),b}}(),getScreenAdjustedEuler:function(){var a,b=new t.Euler;return function(){return a=this.getScreenAdjustedMatrix(),b.setFromRotationMatrix(a),b}}(),isAbsolute:function(){return l.orientation.data&&l.orientation.data.absolute===!0?!0:!1},getLastRawEventData:function(){return l.orientation.data||{}},_alphaAvailable:!1,_betaAvailable:!1,_gammaAvailable:!1,isAvailable:function(a){switch(a){case this.ALPHA:return this._alphaAvailable;case this.BETA:return this._betaAvailable;case this.GAMMA:return this._gammaAvailable}},ALPHA:"alpha",BETA:"beta",GAMMA:"gamma"},t.DeviceMotion=function(a){this.options=a||{}},t.DeviceMotion.prototype={constructor:t.DeviceMotion,start:function(b){b&&"[object Function]"==Object.prototype.toString.call(b)&&l.motion.callbacks.push(b),m||(n?a.screen.orientation.addEventListener("change",d,!1):a.addEventListener("orientationchange",d,!1)),l.motion.active||(a.addEventListener("devicemotion",f,!1),l.motion.active=!0)},stop:function(){l.motion.active&&(a.removeEventListener("devicemotion",f,!1),l.motion.active=!1)},listen:function(a){this.start(a)},getScreenAdjustedAcceleration:function(){var a=l.motion.data&&l.motion.data.acceleration?l.motion.data.acceleration:{x:0,y:0,z:0},b={};switch(o){case p:b.x=-a.y,b.y=a.x;break;case q:b.x=-a.x,b.y=-a.y;break;case r:case s:b.x=a.y,b.y=-a.x;break;default:b.x=a.x,b.y=a.y}return b.z=a.z,b},getScreenAdjustedAccelerationIncludingGravity:function(){var a=l.motion.data&&l.motion.data.accelerationIncludingGravity?l.motion.data.accelerationIncludingGravity:{x:0,y:0,z:0},b={};switch(o){case p:b.x=-a.y,b.y=a.x;break;case q:b.x=-a.x,b.y=-a.y;break;case r:case s:b.x=a.y,b.y=-a.x;break;default:b.x=a.x,b.y=a.y}return b.z=a.z,b},getScreenAdjustedRotationRate:function(){var a=l.motion.data&&l.motion.data.rotationRate?l.motion.data.rotationRate:{alpha:0,beta:0,gamma:0},b={};switch(o){case p:b.beta=-a.gamma,b.gamma=a.beta;break;case q:b.beta=-a.beta,b.gamma=-a.gamma;break;case r:case s:b.beta=a.gamma,b.gamma=-a.beta;break;default:b.beta=a.beta,b.gamma=a.gamma}return b.alpha=a.alpha,b},getLastRawEventData:function(){return l.motion.data||{}},_accelerationXAvailable:!1,_accelerationYAvailable:!1,_accelerationZAvailable:!1,_accelerationIncludingGravityXAvailable:!1,_accelerationIncludingGravityYAvailable:!1,_accelerationIncludingGravityZAvailable:!1,_rotationRateAlphaAvailable:!1,_rotationRateBetaAvailable:!1,_rotationRateGammaAvailable:!1,isAvailable:function(a){switch(a){case this.ACCELERATION_X:return this._accelerationXAvailable;case this.ACCELERATION_Y:return this._accelerationYAvailable;case this.ACCELERATION_Z:return this._accelerationZAvailable;case this.ACCELERATION_INCLUDING_GRAVITY_X:return this._accelerationIncludingGravityXAvailable;case this.ACCELERATION_INCLUDING_GRAVITY_Y:return this._accelerationIncludingGravityYAvailable;case this.ACCELERATION_INCLUDING_GRAVITY_Z:return this._accelerationIncludingGravityZAvailable;case this.ROTATION_RATE_ALPHA:return this._rotationRateAlphaAvailable;case this.ROTATION_RATE_BETA:return this._rotationRateBetaAvailable;case this.ROTATION_RATE_GAMMA:return this._rotationRateGammaAvailable}},ACCELERATION_X:"accelerationX",ACCELERATION_Y:"accelerationY",ACCELERATION_Z:"accelerationZ",ACCELERATION_INCLUDING_GRAVITY_X:"accelerationIncludingGravityX",ACCELERATION_INCLUDING_GRAVITY_Y:"accelerationIncludingGravityY",ACCELERATION_INCLUDING_GRAVITY_Z:"accelerationIncludingGravityZ",ROTATION_RATE_ALPHA:"rotationRateAlpha",ROTATION_RATE_BETA:"rotationRateBeta",ROTATION_RATE_GAMMA:"rotationRateGamma"},a.FULLTILT=t}}(window);
#map{
  width: 200px; height: 200px; position: absolute; right: 20px; bottom: 20px;
}
#street-view{
  width: 100%; height: 100%; position: absolute; top: 0; left: 0;
}
#debug{
  position: absolute; top: 0; left: 0; padding: 10px; border: 1px solid white; color: white;
}

  alpha:  |
  beta:  |
  gamma:


text:
Q: Umbraco media does not have an approved file type I cannot upload anything other than images using TinyMCE in Umbraco Content. I get an error:

Cannot upload this file, it does not have an approved file type

I have checked umbracoSettings disallowedUploadFiles, there is no docx there:
<disallowedUploadFiles>
    ashx,aspx,ascx,config,cshtml,vbhtml,asmx,
    air,axd,swf,xml,html,htm,svg,php,htaccess
</disallowedUploadFiles>

Also Developer -> Data Types -> Media Picker has Pick only images disabled. I use Umbraco 7.5.9. I can upload anything using Media section.
It seems like \Umbraco\Views\common\dialogs\mediapicker.html
        <umb-photo-folder
            min-height="105"
            min-width="150"
            max-height="250"
            ideal-items-per-row="3"
            on-click="clickHandler"
            ng-model="images"
            images-only="{{onlyImages}}"  <!-- always true -->
            filter-by="searchTerm" />

If I manually set it to false,  mediapicker would allow me to upload anything but I can't pick non-image files.
Any other ideas on what I should check?
Posted it in Umbraco issue tracking.

A: Sorry for posting late. I have just came across an option to allow certain files and stop all other files from uploading in umbraco. Below option is used.
<allowedUploadFiles>jpg,xls</allowedUploadFiles>

The setting is available at "config\umbracoSettings.config".
If not added, we can add the setting. More information is available in the below link
https://our.umbraco.com/documentation/reference/config/umbracosettings/

A: I realise this is a bit late, and my issue was todo with Flash (SWF) files. I was trying to add a media type (to no avail, complete newbie).
Then I noticed this post, and removed swf from the umbraco config settings file and it then allowed me to upload.


text:
Q: EF 2.1 + Npgsql + ExecuteSqlCommand = syntax error at or near "$1"

Since EF Core 2.1 the SQLs are checked for injection. That's fine.
But what's the correct way to pass the arguments into ExecuteSqlCommand?
var content = "whatever";

...
var command = @"NOTIFY test, '{0}'";
ctx.Database.ExecuteSqlCommand(command, content);

Executes "NOTIFY test, '@p0'". That's wrong.

ctx.Database.ExecuteSqlCommand($"NOTIFY test, {content}");

Message: 42601: syntax error at or near "$1".

var command = $"NOTIFY test, {content}";
ctx.Database.ExecuteSqlCommand(command);

Works, but "warning EF1000: The SQL expression passed to 'FromSql' embeds data that will not be parameterized. (...)".
  Wrong. That's exactly what I'm trying to fix.

var command = @"NOTIFY test, @Content";
ctx.Database.ExecuteSqlCommand(command, new SqlParameter("@Content", content));

InvalidCastException: "value must be an NpgsqlParameter." Oh, well.

var command = @"NOTIFY test, @Content";
ctx.Database.ExecuteSqlCommand(command, new NpgsqlParameter("@Content", content));
(or)
ctx.Database.ExecuteSqlCommand(command, new NpgsqlParameter("Content", content));

Message: 42601: syntax error at or near "$1". SERIOUSLY?

var command = @"NOTIFY test, {0}";
(or)
var command = @"NOTIFY test, $1";
(or)
var command = @"NOTIFY test, @Content";
ctx.Database.ExecuteSqlCommand(command, new NpgsqlParameter{Value = content});

Message: 42601: syntax error at or near "$1".
  I quit.

Am I missing something?

*

*.NET Core 2.1.301

*EF Core 2.1.1

*Npgsql 2.1.1

A: PostgreSQL simply doesn't support parameters in NOTIFY statements... If you try with a regular DML such as SELECT or INSERT everything should work.
If you really want to parameterize the notification, you can still do client-side string interpolation but be sure to sanitize user input otherwise you're open to SQL injection.

A: I am missing something I guess:
While looking at the documentation(http://www.npgsql.org/doc/index.html)
there is a sample such as this
Also, could you show sample table structure?
var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";

using (var conn = new NpgsqlConnection(connString))
{
    conn.Open();

    // Insert some data
    using (var cmd = new NpgsqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandText = "INSERT INTO data (some_field) VALUES (@p)";
        cmd.Parameters.AddWithValue("p", "Hello world");
        cmd.ExecuteNonQuery();
    }

    // Retrieve all rows
    using (var cmd = new NpgsqlCommand("SELECT some_field FROM data", conn))
    using (var reader = cmd.ExecuteReader())
        while (reader.Read())
            Console.WriteLine(reader.GetString(0));
}
You can find more info about the ADO.NET API in the MSDN docs or in many tutorials on the Internet.

based on "NOTIFY test, " I have no idea what are you trying to do


text:
Q: PowerShell change printer configuration from Administration tab Im able to create and install printers using powershell. Now i also need to automate the printer configuration and need to change multiple values in the Administration tab.

How can i do that via powershell? I tried Set-PrinterProperty but i can't get it to work.
Thanks

A: One way I found easy to implement this was to start from current printer configuration, using Get-PrinterConiguration, then look at the xml and change whatever you need to, then use Set-PrinterProperty to push up the new xml.
Below is a function I created a while ago to update Printer Tray. It should (hopefully) get you started.
Function Set-MyDefaultPrinterTray {
#Requires -module PrintManagement
<#
    .SYNOPSIS
    Update Default Tray assignment of printer

    .EXAMPLE
    > Set-MyDefaultPrinterTray -ComputerName (Get-Content C:\temp\epicprinter\servers.txt) -PrintQueue ZZZ_Adil_Test03 -Tray 4 -Verbose
    VERBOSE: Change tray to Tray4 on epswcdcqvm001
    VERBOSE: Getting PrintConfiguration...
    VERBOSE: epswcdcqvm001 : CurrentTray is psk:AutoSelect
    VERBOSE: epswcdcqvm001 : New Tray ns0000:Tray4
    VERBOSE: Performing the operation "Update Tray" on target "epswcdcqvm001".
    VERBOSE: epswcdcqvm001 : Setting new tray assignment
    VERBOSE: epswcdcqvm001 : Adding to success table
    VERBOSE: Change tray to Tray4 on epswcdcqvm002
    VERBOSE: Getting PrintConfiguration...
    VERBOSE: epswcdcqvm002 : CurrentTray is psk:AutoSelect
    VERBOSE: epswcdcqvm002 : New Tray ns0000:Tray4
    VERBOSE: Performing the operation "Update Tray" on target "epswcdcqvm002".
    VERBOSE: epswcdcqvm002 : Setting new tray assignment
    VERBOSE: epswcdcqvm002 : Adding to success table
    VERBOSE: Change tray to Tray4 on epswcdcqvm001
    VERBOSE: Getting PrintConfiguration...
    VERBOSE: epswcdcqvm001 : CurrentTray is ns0000:Tray4
    VERBOSE: epswcdcqvm001 : New Tray ns0000:Tray4
    VERBOSE: Performing the operation "Update Tray" on target "epswcdcqvm001".
    VERBOSE: epswcdcqvm001 : Setting new tray assignment

    Name                           Value
    ----                           -----
    epswcdcqvm002                  Succeed
    epswcdcqvm001                  Succeed

    .EXAMPLE
    D:\> Set-MyDefaultPrinterTray -PrintServer 'epswcdcqvm001','epswcdcqvm002' -PrintQueue ZZZ_Adil_Test03 -Tray Tray2 -Verbose
    VERBOSE: Change tray to Tray2 on epswcdcqvm001
    VERBOSE: Getting PrintConfiguration...
    VERBOSE: epswcdcqvm001 : CurrentTray is psk:AutoSelect
    VERBOSE: epswcdcqvm001 : New Tray ns0000:Tray2
    VERBOSE: Performing the operation "Set-EpicDefaultPrinterTray" on target "epswcdcqvm001".
    VERBOSE: epswcdcqvm001 : Setting new tray assignment
    VERBOSE: Change tray to Tray2 on epswcdcqvm002
    VERBOSE: Getting PrintConfiguration...
    VERBOSE: epswcdcqvm002 : CurrentTray is psk:AutoSelect
    VERBOSE: epswcdcqvm002 : New Tray ns0000:Tray2
    VERBOSE: Performing the operation "Set-EpicDefaultPrinterTray" on target "epswcdcqvm002".
    VERBOSE: epswcdcqvm002 : Setting new tray assignment
#>
    [CMDLETBINDING(SupportsShouldProcess)]
    param(
            [Parameter(Mandatory,ValueFromPipeline,Position=0)]
            [Alias('PrintServer')]
            [string[]]$ComputerName,
            #[string[]]$PrintServer,

            [Parameter(Mandatory,Position=1)]
            [string]$PrintQueue,

            [ValidateSet('1','2','3','4','Tray1','Tray2','Tray3','Tray4','AutoSelect','ManualFeed')]
            $Tray='AutoSelect'
        )
    BEGIN
    {
           switch ($tray)
           {
             1  {$tray='Tray1';break}
             2  {$tray='Tray2';break}
             3  {$tray='Tray3';break}
             4  {$tray='Tray4';break}
           }

           $result = @{}
    }
    PROCESS
    {

        Foreach ($ps in $ComputerName)
        {
            Write-Verbose "Change tray to $tray on $ps"

            try
            {
                if (! (Test-Connection -ComputerName $ps -Count 1 -Quiet)) {
                    throw "Not Pingable"
                }

                Write-Verbose "Getting PrintConfiguration..."
                $PrintConfiguration = Get-PrintConfiguration -ComputerName $ps -PrinterName $PrintQueue
                $PrintTicketXML = [xml]$PrintConfiguration.PrintTicketXML

                $currentTray = ($PrintTicketXML.PrintTicket.Feature).where({$_.name -eq 'psk:JobInputBin'}).option.name
                Write-Verbose "$ps : CurrentTray is $currentTray "

                if ($Tray -eq 'AutoSelect') {
                    $NewTray= "psk:$Tray"
                } else {
                    $NewTray= "ns0000:$Tray"
                }

                Write-Verbose "$ps : New Tray $NewTray "

                $UpdatedPrintTicketXML = $PrintConfiguration.PrintTicketXML -replace "$currentTray","$NewTray"

                if ($PSCmdlet.ShouldProcess($ps,"Update Tray")  ) {
                    Write-Verbose "$ps : Setting new tray assignment"
                    Set-PrintConfiguration -ComputerName $ps -printername $PrintQueue -PrintTicketXml $UpdatedPrintTicketXML
                   if (!$result.ContainsKey($ps)) {
                        Write-Verbose "$ps : Adding to success table"
                        $result.Add($ps,'Succeed')
                    }
                }

            }
            catch
            {
                    if (!$result.ContainsKey($ps)) {
                        Write-Verbose "$ps : Adding to fail table"
                        $result.Add($ps,'Fail')
                    }

                Write-Error $error[0].exception
            }

        }
    }
    END
    {
           $result
    }

}

A: Best way to do this is to use the below Windows tool, it should, but of course it isn't guaranteed, work with the "Administration tab".

*

*Rundll32 printui.dll,PrintUIEntry
The way this tool works is, you firstly set the printer with the settings you want (configure your Administration tab accordingly) and export the settings to a file with a command like this (in CMD or PowerShell):
RUNDLL32 PRINTUI.DLL,PrintUIEntry /Ss /n "PRINTER_NAME" /a "C:\printerSettings.dat" g d u

At "PRINTER_NAME" you enter your desired printer name (with quotation marks) and at "C:..." the location where the settings file should be saved. The parameters at the end here aren't necessarily, with the you specify what gets saved to the file, without any parameters everything gets saved and that might be best here...
Now, your settings are saved in a file, you'll then use that file for restoring settings on other printers with the same drivers with something like this:
RUNDLL32 PRINTUI.DLL,PrintUIEntry /Sr /n "PRINTER_NAME" /a "C:\printerSettings.dat" g d u p i r

The difference as you might noticed are the commands "/Ss" for saving and "/Sr" for restoring and different parameters at the end. Here a bit tricky thing to notice - if you run this with administration rights the above code should work fine, but otherwise you'll get a error. The problem is "g" parameter here, as it tries to change/restore the default settings of the printer and not only the settings for the current user. The settings for the current user are restored with "u". So you will maybe need to remove the "g" parameter.
Other parameters are described at the link, the more important ones I'll copy here (this are for restoring - "/Sr" command):

*

*r: If the printer name stored in the file is different from the name of the printer being restored to, then use the current printer name. This cannot be specified with f. If neither r nor f is specified and the names do not match, restoration of the settings fails.

*f: If the printer name stored in the file is different from the name of the printer being restored to, then use the printer name in the file. This cannot be specified with r. If neither f nor r is specified and the names do not match, restoration of the settings fails.

*i: If the driver in the saved settings file does not match the driver for the printer being restored to, then the restoration fails.

*p: If the port name in the file being restored from does not match the current port name of the printer being restored to, the printer's current port name is used.

*d: Use to restore printer specific data, such as the printer's hardware ID.


text:
Q: NodeJS - installing local module npm i /path/to/module/folder will create a dependency for your project on local module
it creates a link to that folder as the docs says

• npm install < folder >:
Install the package in the directory as a symlink in the current
  project. Its dependencies will be installed before it's linked. If
   sits inside the root of your project, its dependencies may be
  hoisted to the toplevel node_modules as they would for other types of
  dependencies.

*

*there is a flag --no-bin-links that prevent creating links only to bin's files

What i want is : is there a way to be able to make dependency on that local module by copy it not link it, so i can make changes and won't reflect on other projects until i manually npm update my-local-module it

PS : from what i searched that was the default behavior of npm install <folder> but they changed it.

A: You can create a tarball from your-local-module with npm-pack and then install it offline using npm-install:
npm install <tarball file>

Install a package that is sitting on the filesystem. Note: if you just want to link a dev directory into your npm root, you can do this more easily by using npm link. The filename must use .tar, .tar.gz, or .tgz as the extension.


text:
Q: My ListView is not smooth when I set Bitmap to ImageView I use adapter with ListView this is implementation of getView
@Override
public View getView(int position, View convertView, ViewGroup parent){
    ItemViewHolder viewHolder;
    if(convertView == null){
        convertView = (RelativeLayout)inflater.inflate(resource,parent, false);
        viewHolder = new ItemViewHolder();
        viewHolder.itemTextName = (TextView)convertView.findViewById(R.id.item_name);
        viewHolder.itemTextExpDate = (TextView)convertView.findViewById(R.id.item_exp_date);
        viewHolder.itemImage = (ImageView)convertView.findViewById(R.id.item_image);

    }
    else{

        viewHolder = (ItemViewHolder)convertView.getTag();
    }

    Item item = listItem.get(position);
    if(listItem != null){
        viewHolder.itemTextName.setText(item.getName());
        viewHolder.itemTextExpDate.setText(""+item.getDaysleft());
        viewHolder.itemImage.setImageBitmap(item.getImage());
    }
    return convertView;
}

static class  ItemViewHolder  {
    View baseView;
    TextView itemTextName;
    TextView itemTextExpDate;
    ImageView itemImage;

}

When I set Bitmap to ImageView the ListView is not smooth.
Am I implement the correct code in getView ?

A: Look on this simple code how you can use Holder pattern simple implementation you must only extern it
On start use Integer.toString or something not
viewHolder.itemTextExpDate.setText(""+item.getDaysleft());

When you use setImage... the  getView will be called multiple times.
Why you are checking is it null and 1 line faster you use it ? No sense.
if(listItem != null){
        viewHolder.itemTextName.setText(item.getName());
        viewHolder.itemTextExpDate.setText(""+item.getDaysleft());
        viewHolder.itemImage.setImageBitmap(item.getImage());
    }

And the most important thing you don't set holder on the View this code doesn't crash for you?
Look at topics:
Lazy loading
getView called multiple times
getView called multiple times 2

A: Try adding : convertView.setTag(viewHolder) in the if-block. Also, use a method like Universal Image Loader for loading images in list view