text:
Q: CSpice in Visual C++ 2015: Link errors I'm trying to use Nasa's CSpice toolkit, but when I try to build my code I receive errors like
LNK2028    unresolved token (0A0004E6) "extern "C" void __cdecl spkpos_c(char const *,double,char const *,char const *,char const *,double * const,double *)"
I have already placed the library (cspice.lib) into the linker
Project Property page and imported the headers.
Any ideas on what the issue might be?
Code:
#include <iostream>
#include "stdafx.h"
#include "Calculation.h"
#include <ctime>
#include <string>
#include <sstream>

SpiceDouble* Calculation::sunPosition()
{
//--Kernels--
//Load Earth data
furnsh_c("..\data\earth_pck\earth_latest_high_precision.bpc");
//Load LeapSeconds tabulation for time convertion
furnsh_c("..\data\all_spk\naif0011.tls.pc");
//Framework used is J2000, so it does not need to be loaded

//--Variables--
SpiceDouble epochTime;
SpiceDouble sunPosition[3];
SpiceDouble lightYears;

//--Calculation--
//Seconds past J2000 TDB
time_t t = time(0);
struct tm* utcNow = gmtime(&t);
std::string month;
switch (utcNow->tm_mon)
{
case 0:
    month = "JAN";
    break;
case 1:
    month = "FEB";
    break;
case 2:
    month = "MAR";
    break;
case 3:
    month = "APR";
    break;
case 4:
    month = "MAY";
    break;
case 5:
    month = "JUN";
    break;
case 6:
    month = "JUL";
    break;
case 7:
    month = "AUG";
    break;
case 8:
    month = "SEP";
    break;
case 9:
    month = "OCT";
    break;
case 10:
    month = "NOV";
    break;
case 11:
    month = "DEC";
    break;
}

std::stringstream format;
format << (utcNow->tm_year + 1900) << " ";
format << month << " " << utcNow->tm_mday << " ";
format << utcNow->tm_hour << ":";
format << utcNow->tm_min << ":";
format << utcNow->tm_sec;

ConstSpiceChar* et = format.str().c_str();
str2et_c(et, &epochTime);

//Get current sun position relative to earth, using earth as the inertia center
spkpos_c("sun", epochTime, "iau_earth", "none", "earth", sunPosition, &lightYears);
printf("%f", sunPosition);

return sunPosition;
}

A: Solved it.
Solution: library was x64, Visual C++ was configured for x86.
 -> Ran "vcvarsall.bat amd64" in cmd and changed the project to build x64


text:
Q: Cual es la diferencia entre este ciclo for: for(auto i: vector) y un ciclo for de la forma for(int i = 0; i < vector.size(); i++) Estaba viendo un video de un código para un programa en C++ que cuenta los números primos de un numero inicial a uno final y los guarda en un vector, pero hay un punto donde usan el ciclo for del titulo para mostrar los números dentro del vector, pero es la primera vez que lo veo.
Me gustaría saber para que sirve independientemente del contexto en el que se use (por eso no coloco ningún tipo de código) y cual es la diferencia con el otro tipo de ciclo for que coloque.
Gracias de antemano.

A: For clásico:
for (int i=0; i<vector.size(); i++)

Este es el bucle for que lleva con nosotros desde los inicios de C++. De hecho es una de las características heredadas de C.
Si bien este bucle es bastante sencillo de implementar presenta algunos inconvenientes:

*

*Necesidad de iterar expresamente i

*En cada iteración se está invocando el método size()
Este bucle se podría mejorar de la siguiente forma:
for (int i=0, end=vector.size(); i<end; i++)

Ahora ya no se invoca el método size() en cada iteración pero a cambio hemos conseguido un bucle un poco más engorroso y feo. Además de que tenemos una variable end que tenemos que evitar modificar a toda costa.
Para simplificar un poco este código, el estándar C++11 nos ofreció el for basado en rangos:
for(auto item : vector)

Esta forma del bucle es mucho más legible y elimina los problemas asociados a la forma anterior:

*

*No tenemos que preocuparnos de incrementar ninguna variable ni iterador

*No se está invocando el método size en cada iteración

*No tenemos que gestionar el fin de la iteración

¿Pero entonces el primer for ya no sirve para nada?
Ni mucho menos. No hay que olvidar que el for basado en rangos necesita una colección sobre la que iterar. Así, si no tenemos una colección como tal no podremos utilizar, al menos en principio, este nuevo for:
for (int i=0; i<5; i++) // <<--- No hay colección

Además, el for basado en rangos no tiene niguna flexibilidad a la hora de determinar los desplazamientos a través de la colección. Si necesitamos iterar de una forma no convencional (indices pares, intercalar decrementos, ...) no podremos usar el for basado en rangos
for (int i=0; i<vector.size(); i+=2)

Otro caso que no se puede abordar con el for basado en rangos lo encontramos cuando queremos eliminar elementos de la colección.
En algunos contenedores el método erase te devuelve un iterador al siguiente elemento de la colección.
Dado que el for basado en rangos no te deja interactuar con el proceso de iteración, no lo puedes utilizar en este caso.
for (auto it=vector.begin(); it!=vector.end(); /* sin incremento */)
{
    if (*it % 2 == 0) // Eliminamos los elementos pares
        it = vector.erase(it);
    else
        it++;
}

Adaptadores para el for basado en rangos
Realmente te he engañado a medias. Hay casos que se pueden tratar con el for basado en rangos pero para ello necesitamos adaptar nuestra colección.
Por ejemplo, para iterar en reversa podemos hacer lo siguiente
std::vector<int> datos = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

class reverse
{
public:
    reverse(std::vector<int> & datos)
        : datos{datos}
    { }

    auto begin()
    { return datos.rbegin(); }

    auto end()
    { return datos.rend(); }

private:
    std::vector<int> & datos;
};

for (int item : reverse(datos))
{ std::cout << item; }

En este caso también existe un adaptador ya hecho en BOOST. El ejemplo es solo para fines didácticos.
Como ves, para usar el for basado en rangos en escenarios particulares tenemos que ser capaces de crear el adaptador correspondiente

redpajama_set_name: RedPajamaStackExchange


text:
Q: Folder name for a pro version of a WordPress.org theme? I am developing a free theme and users can download it from WordPress.org. I am working on pro version of the same theme. What should be the name of the pro version's folder?
My theme's name is BizPoint. If I name the pro version's folder as 'BizPoint-Pro', whatever changes the user has done using customizer, are lost. If I use pro version's folder name as 'BizPoint', users won't be able to install pro version without deleting the free theme.
How is this conflict handled?

A: It is best to make the Pro version a plugin instead of a theme. That way you don't have duplicate code bases, and the theme_mods are not split, and the updates are separate.
Put the hooks you need into the free theme, and your Pro plugin will have no trouble.

A: There is no conflict as those are two different themes and data structure should not be expected to be the same. Expecting data reuse is maybe a nice to have but  in practice it is hard to do.
A more realistic approach is to have data migration as part of the activation of the "pro" theme, ot just have it as explicit UI featuer when you detect that there is a "free" theme installed on the server.


text:
Q: Server side pagination is not working as expected I am developing a MERN stack app where I am trying to implement server side pagination.
Note that I am using React Query for managing server state.
On the root route, I display two posts.

When I click on the Next button, NEXT two blog posts should be displayed. However, this is not happening. I see the same two posts on page 2 as on page 1.

Where is the problem?
I think, there is either some problem with my server side pagination logic or with React Query. I suspect React Query is not fetching blog posts when I click on the Next button; instead it is fetching the posts from the cache. (I could be wrong here).
These are my code snippets:
postControllers.js
const asyncHandler = require("express-async-handler");
const Post = require("../models/postModel");

const fetchAllPosts = asyncHandler(async (req, res) => {
  const { pageNumber } = req.body;
  const pageSize = 2;
  const postCount = await Post.countDocuments({});
  const pageCount = Math.ceil(postCount / pageSize);
  const posts = await Post.find({})
    .limit(2)
    .skip(pageSize * (pageNumber - 1));
  res.json({ posts, pageCount });
});

postRoutes.js
const express = require("express");

const { fetchAllPosts, createPost } = require("../controllers/postControllers");

const router = express.Router();

router.get("/api/posts", fetchAllPosts);

module.exports = router;

Posts.js
import React, { useState } from "react";
import { useFetchAllPosts } from "../hooks/postsHooks";
import Spinner from "../sharedUi/Spinner";

const Posts = () => {
  const [pageNumber, setPageNumber] = useState(1);

  const { data, error, isLoading, isError } = useFetchAllPosts(pageNumber);

  const handlePrevious = () => {
    setPageNumber((prevPageNum) => prevPageNum - 1);
  };
  const handleNext = () => {
    setPageNumber((prevPageNum) => prevPageNum + 1);
  };
  return (

      {isLoading ? (
        <Spinner />
      ) : isError ? (

{error.message}

      ) : (
        data.posts.map((post) => (

            {post.title}

        ))
      )}

        {isLoading ? (
          <Spinner />
        ) : isError ? (

{error.message}

        ) : (

            <button
              disabled={pageNumber === 1}
              className="bg-blue-400 px-1 py-0.5 text-white rounded"
              onClick={handlePrevious}
            >
              Previous
            </button>

{data.pageCount && `Page ${pageNumber} of ${data.pageCount}`}

            <button
              disabled={pageNumber === data.pageCount}
              className="bg-blue-400 px-1 py-0.5 text-white rounded"
              onClick={handleNext}
            >
              Next
            </button>

        )}

  );
};

export default Posts;

postHooks.js
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import axios from "axios";

export const useFetchAllPosts = (pageNumber) => {
  const response = useQuery(["posts"], async () => {
    const { data } = await axios.get("/api/posts", pageNumber);
    return data;
  });

  return response;
};

A: all dependencies of a query (= everything that is used inside the query function) needs to be part of the query key. React Query will only trigger auto fetches when the key changes:
export const useFetchAllPosts = (pageNumber) => {
  const response = useQuery(["posts", pageNumber], async () => {
    const { data } = await axios.get("/api/posts", pageNumber);
    return data;
  });

  return response;
};

to avoid hard loading states between pagination, you might want to set keepPreviousData: true
see also:

*

*the official pagination example

*the guide on paginated queries


text:
Q: In C language, how to call my function instead of system library function Platform - Linux
I have a typical requirement, where I need to give higher priority to my function then system provided function.
Lets say I have a third party library or executable. It calls many system functions such strcpy or strlen etc. I can not modify the executable/library as I do not have access to code.
Now I have implemented my own strlen or strcpy functions. When the third party library or executable is executing it should call my functions instead of system library functions.
Is it possible. If yes, can somebody guide me how to do this.
LD_PRELOAD trial result
As per suggestion here, I tried with LD_PRELOAD. I tried to override malloc function.
    #include <string.h>

    void *malloc(int size)
    {
        void *ptr = NULL;
        printf("Inside my malloc function\n");
        ptr = malloc(size);
        return ptr;
    }

I put the above code in a c file and built mem.so file and executed below command.

export LD_PRELOAD=./mem.so

So now I have overwritten malloc function.
If execute ls or clear command I get below result, which is logical.
Inside my malloc function
Inside my malloc function
Inside my malloc function
Inside my malloc function
Inside my malloc function

It looks my overloaded malloc function is invoked recursively. Only one time call I need. How can I achieve that.

A: Your malloc needs to call the real malloc. Use dlsym(3) to find the symbol.
RTLD_NEXT finds the next such reference.
#include <stdio.h>
#include <dlfcn.h>
void *malloc(size_t size)
{
  static void * (*func)();

  if(!func)
     func = (void *(*)()) dlsym(RTLD_NEXT, "malloc");
  printf("malloc(%d) is called\n", size);
  return(func(size));
}


text:
Q: ArrayList в ArrayList. Как это понять? Как работать с этим:
private List<List<Object>> data;

Как это понять?
Есть ячейки листа, в его ячейках находятся другие ячейки другого листа?
А уж в этой ячейке уже лежат объекты?

A: List<List<Object>> data - это двумерный массив. Проще всего представить себе это как обычную таблицу, у которой есть строки и столбцы.
Так что, data.get(0) - это первая строка. data.get(0).get(0) - первая строка и первый столбец, то есть это [0;0] ячейка в таблице.


text:
Q: How can I scale selected image iPhone sdk? suppose I have selected image from image picker,and now I want to scale that image and want to set that scaled image in button or in any image view.

A: Did you take a look at the contentMode property of the UIImageView.
typedef enum {
   UIViewContentModeScaleToFill,
   UIViewContentModeScaleAspectFit,
   UIViewContentModeScaleAspectFill,
   UIViewContentModeRedraw,
   UIViewContentModeCenter,
   UIViewContentModeTop,
   UIViewContentModeBottom,
   UIViewContentModeLeft,
   UIViewContentModeRight,
   UIViewContentModeTopLeft,
   UIViewContentModeTopRight,
   UIViewContentModeBottomLeft,
   UIViewContentModeBottomRight,
} UIViewContentMode;

A: when you picking an image from picker, it should returt UIImage type. just set it as image to any UIView sublass (button are UIView sub class too):
[yourUIImageView setImage:UIImageFronUIPicker];
[yourUIButton setBackgroundImage:UIImageFronUIPicker];

and so on...

A: Implement a UIImagePickerControllerDelegate in your view controller and implement the delegate methods below
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {

    [selectedImageBtn setImage:image forState:UIControlStateNormal];
    [[imagePicker parentViewController] dismissModalViewControllerAnimated:YES];

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [[imagePicker parentViewController] dismissModalViewControllerAnimated:YES];
}


text:
Q: Why can't I use jQuery prop to get the CSS setting? In the HTML file, I have created a DOM element:

and I set the attributes in css file:
#colorOne{
    position: absolute;
    top: 70%;
    left: 8%;
    width: 36px;
    height: 36px;
    border-color: black;
    border-width: 5px;
    border-style: solid;
    background-color: white;
}

However, as I command
$('#colorOne').prop('width');    $('#colorOne').prop('height');

If I want to get any attribute of the element colorOne by $.prop, it only shows undefined. But I also noticed that  if I change prop to css and I can get what I want.
And if I write

And the $.prop works.
I want to know why is that. How does the browser engine handle these two different writing methods?
(1. inline style 2. setting the attributes in .css file)

A: css is what you want.
Try:
$('#colorOne').css('width');
$('#colorOne').css('height');

$.prop is use to access attributes like name, href, etc.
If you still want to use prop, you will have to set width, height attributes in html elements.

$('#colorOne').prop('width');

The above works because, width is an attribute to the element #colorOne.
If width of the element is changed by js or css(using !important) in anyway, $.prop will give you wrong answer. But $.css will give you the correct one.

A: If you want to get the final, computed style with jQuery you need to use .css().
This uses getComputedStyle internally so you can use it with styles from several different sources.
Here is what jQuery does internally to do this:
function (elem, name) {
    var ret, defaultView, computedStyle, width, style = elem.style;

    name = name.replace(rupper, "-$1").toLowerCase();

    if ((defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle(elem, null))) {

        ret = computedStyle.getPropertyValue(name);
        if (ret === "" && !jQuery.contains(elem.ownerDocument.documentElement, elem)) {
            ret = jQuery.style(elem, name);
        }
    }

    // A tribute to the "awesome hack by Dean Edwards"
    // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
    // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
    if (!jQuery.support.pixelMargin && computedStyle && rmargin.test(name) && rnumnonpx.test(ret)) {
        width = style.width;
        style.width = ret;
        ret = computedStyle.width;
        style.width = width;
    }

    return ret;
}

When you perform a .attr or .prop call you're reading an HTML attribute/property and not a style. If you read the style attribute you're only getting that and not the actual computed style from all the stylesheets etc.


text:
Q: Tcpdump command - Linux - Unix I'm using the tcpdump command to capture traffic on the network interface eth0
tcpdump -Xvv -n -i eth0 -c 300 > captureFile.txt
in the shell appear the next message
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
300 packets captured
302 packets received by filter
0 packets dropped by kernel
How i can do message don't display in the command line???

A: Add 2>/dev/null at the end of the command line:
tcpdump -Xvv -n -i eth0 -c 300 > captureFile.txt 2>/dev/null

Tcpdump writes the message to standard error, and the > redirection works on standard out only.
If you want the message to appear in captureFile.txt, use:
tcpdump -Xvv -n -i eth0 -c 300 > captureFile.txt 2>&1

For more information on redirection, see http://www.tldp.org/LDP/abs/html/io-redirection.html

A: If I understand you correctly, you want to suppress output of that command.
If you want to suppress:

*

*just messages (regular output), use:
command > /dev/null

*just the errors (not recommended):
command 2> /dev/null

*both errors and regular messages (again, not recommended):
command > /dev/null 2>&1

This requires tcpdump to dump captured data to a file. You can do this by using the -w switch:
tcpdump -w capture.log


text:
Q: How can I scan documents from a Lexmark x543n over the network on OS X 10.6 I just got a Lexmark x543dn and have some trouble getting my computer to recognize it as a scanner. The printer is working fine from my OS X 10.6 machine, setup was as easy as it gets. I just connected it to my network, gave it a name and added it under that name as a networked printer in OS X.
According to the Apple support website, the driver in OS X (I upgraded to the newest drivers already) should also provide scanning capabilities. However when I run the image capture app included in OS X it tells me that there are no scanners available.
Can anybody tell me what I have to do to get OS X to recognize the scanner?
Thanks

A: I got it working as follows on my Lexmark X543. (may not be your desired solution but should serve as a workaround at least.)

*

*Got it setup as a printer with the general network setup (and being able to print over the network) (mac-standard-install.html topic)

*logged onto my router and identified the printer's IP-address.

*web browsed to the printer's webserver: like http://192.168.1.7 (in my case)

*Click scan profile in the left hand side menu, choose the settings and scanning destination and start to scan (was using shortcut one for me so I had to press #1 on the scanner.

*Scanned document was saved on the desired path on my computer, (so it worked very well.)
HTH.

A: You might want to try the Lexmark driver.  It was released on 09/29/2010.  The release notes:

This package installs a TWAIN Data Source (DS) for use with TWAIN-compliant applications for Network Scanning and Image Capture module for direct-attached devices in the Mac OS X system.


text:
Q: InputBox in Word 2010 VBA I'd like to add code to my template where the macro asks "What page is the table on?" and the user can type in the response, i.e., 38.  Afterward, the text, "[Table Page 38]" is inserted, one after the other, into the same, specified Word document.
Dim strPageInfo As String
strPageInfo = InputBox("Type page number for table placeholder.")

Any help would be greatly appreciated.

A: The following snippet will just insert the input number into the text selection. I am not sure if this is exactly what you are looking for.
Dim strPageInfo As String
strPageInfo = InputBox("Type page number for table placeholder.")
Selection.TypeText Text:="[Table Page " + strPageInfo + "]";

Here's a list of macros for your reference as well. You may be able to find exactly what you are needing to do if this doesn't work.
http://wordribbon.tips.net/C0694_Macros.html


text:
Q: .NET App Won't Connect to DB - IIS 8.5 Deployment I'm adding a new .NET MVC App that runs on the same data model as an older .NET app to IIS 8.5 and for now uses the same connection string for Microsoft SQL Server. It is giving me an error I can't figure out.
Here's the (censored) connection string I'm using for both apps:
Data Source=www2.oursite.com;Initial Catalog=*******;Persist Security Info=True;User ID=******;Password=●●●●●●●●●●●●●●●●;MultipleActiveResultSets=True;Integrated Security=False

This is the error I recieve:

SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details. )

The new app belongs to the same AppPool as the old app, and the directory is granted permissions for that AppPool. I have also tried adding the app to its own AppPool in case that's the issue, and it doesn't seem to change anything.
When I go into the AppPool settings and set Load User Profile = True, marvelously, the app runs without any errors. However, it cannot retrieve any items from the database. It's like the database were totally empty.
Possibly related facts:

*

*The apps are two different target runtimes for .NET. The old runs on v4.7.2. The new runs on .NET 5.0.

*

*The two apps use the same data model - they are dependent on another .NET Module. The .NET Module runs EntityFramework v4.0.30319. The old application uses EntityFramework v4.0.30319. The new application uses EntityFramework v6.44.

*IIS (Version 8.5) itself is run on Windows Server 2012. (Yes, we pray to upgrade this year.)

*To run these apps on IIS, I package them and move them manually into the webroot, where I then set the settings.

*Both apps run in AppPool where the CLR Version is 4.7.2. Both are set to Integrated.

*When I try loading the new app and it spits out the above error, it takes a long time, like there's a timeout happening when the app tries to connect to the SQL Server.

*I tried setting the AppPool Identity to LocalService, LocalSystem, and NetworkService. Setting to LocalSystem gives me the same error as when I set LoadUserProfile = True -  the app runs, but it's as if it's database queries are returning empty sets of data. The other settings just give the error.
This is all I can think of that might be relevant. Let me know if I can provide more info. I am no expert on this.
Does anyone have any clue? Usually when I'm stuck like this, I can figure it out with some fiddling or come up with a workaround, but I'm so lost here.
What I've tried:

*

*I've granted the AppPool permissions on the project folder.

*I've also tried putting the new app into a different AppPool.

*I've set UserProfile = True, got the app running but not retrieving data (see above)

*I tried setting the connection string in web.config, appsettings.json, and in IIS.

*I've made sure the old project and new project have NO differing settings in IIS.

*I've trawled through logs. I've did a looooooot of fiddling.


text:
Q: Pass Concatenated Variable and String as Argument to Template Helper If I try to pass a Variable and String as an argument to a template helper I end up with the string literal:
{{#ContainerSurface class='progressBarContainer {{namespace}}'}}

Ends up as <div class="famous-surface progressBarContainer {{namespace}}">
If I try to do
{{#ContainerSurface class={{'progressBarContainer ' + namespace}}

I end up with error:

=> Errors prevented startup:
While building the application:
     client/cordova/pages/widgets/progressBar/progressBar.html:2: Expected identifier, number,
     string, boolean, or null
     ...sBarContainer' class={{'progressBarContai...
     ^
=> Your application has errors. Waiting for file change.

I can make a Template Helper that returns the String + Variable, but that makes for messy code as I need to do this more than once.

A: You can actually do 1 helper , and use this Package,to use on other templates.
Template.foo.helpers = function () {
 thisHelperIsAvaibleEverywhere:function(){
     return "Test";
  }
};
Template.foo2.inheritsHelpersFrom("thisHelperIsAvaibleEverywhere");

Now just declare 1 template helper, and inherit to the others templates.
Where foo2 it the name of the other template.


text:
Q: xUnit tests don't show up when Active solution platform is x64 I have Visual Studio Pro 2015 and I'm trying to run xUnit tests in my solution.  When I compile with Active solution platform set to "Any cpu" all my tests show up in Test Explorer.  If I switch to x64 and rebuild (successfully), none of them show up in Test Explorer.  Is this some kind of limitation of xUnit?  I haven't found anything to that effect online.

A: As covered in this question, the runner runs either x86 or x64, so if you build it to be specific, you need the runner to be in aligment with what you're compiling to:- ,


text:
Q: Android: Making Bitmaps Disappear When Touched As is, 100 pink circles (same bitmap) appear scattered randomly over the phone screen (as is supposed to).  When I tap one of the circles, that circle should disappear (change to the background color).  I think I have a fundamental misunderstanding of Android and View in general.I think I have a couple obvious errors (that are not so obvious to me, but I've been staring at it so long that I figured I needed some help).  Currently, the screen shows the random circles but nothing more.  Touching the screen does nothing.  Any better ideas to make the circles disappear? It recently reorganized all the bitmaps when you touched it, but I did something recently, and it stopped.  The bitmap is 30px by 30px.
public class DrawV extends View {
    private Bitmap bit_dot;
    private int width;
    private int height;
    public int[] width_array = new int[100];
    public int[] height_array = new int[100];
    private View dotV = (View)findViewById(R.id.bigdocpic);//bitmap
    Random rand = new Random();

public DrawV(Context context) {
    super(context);
    bit_dot = BitmapFactory.decodeResource(getResources(), R.drawable.dot_catch);
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    width = metrics.widthPixels;
    height = metrics.heightPixels;
}

@Override
//draws 100 randomly placed similar bitmaps
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int height_dimension;
    int width_dimension;
    for (int i = 0; i < 100; i++){
        height_dimension = rand.nextInt(height) + 1;
        width_dimension = rand.nextInt(width) + 1;
        canvas.drawBitmap(bit_dot, width_dimension, height_dimension, null);
        width_array[i] = width_dimension;//
        height_array[i] = height_dimension;//
    }
}

@Override
public boolean onTouchEvent(MotionEvent event){
    Paint p = new Paint();
    p.setColor(Color.WHITE);
    Path path = new Path();
    Canvas c = new Canvas();
    for (int i = 0; i < 100; i++){
        if ((event.getX() == width_array[i]) && (event.getY() == height_array[i]))
            c.drawCircle(width_array[i], height_array[i], 15, p);
    }
    invalidate();
    return false;//false or true?
}

//set visibility of bitmap to invisible
public boolean onTouch(View v, MotionEvent event) {
    dotV.setVisibility(View.INVISIBLE);
    invalidate();
    return false;//false or true? not understanding
}}

Help?

A: Your onTouchEvent isn't really doing anything important as-is, and you don't have the concept of a circle object.
onDraw should really be drawing these circles from an array/list created earlier - say a List<MyCircles> or MyCircles[]. On touch, you could iterate through all of your circles until you find one that is closest, remove that circle from the array or list, then invalidate.
The reason nothing is happening at all is even though you're drawing those circles again in onTouchEvent, you're redrawing everything yet again in onDraw (invalidate() calls draw/onDraw).
Ideally, create your list of circles in your initializer, draw them in onDraw, and update them in onTouch (That is, delete). There may be a simpler way to do this but this is, at the very least, a more proper approach.


text:
Q: which way is better? I am developing an E-Commerce website using React, Redux, the website shows some products, these products can be sorted or filtered by a selectbox with some options.
I have two options for filtering products:
1 - fetching products everytime from the server and doing a check in the fetch function for example:
products = products.filter(p =>
    options.find(o => p.categories.find(category=> category=== o))
);

2 - fetching products once then creating a reducer that filters products every time different option is selected
Which one would be better in the term of best practice and performance??
UPDATE: fetch function
const fetchProducts = (categories) => {
  fetch('products API')
    .then(res => {
      let { products } = res.data;

      if (!categories && categories.length > 0) {
        products = products.filter(p =>
          categories.find(category => p.categories.find(size => size === category))
        );
      }

      return dispatch({
        type: FETCH_PRODUCTS,
        payload: products
      });
    })
    .catch(err => {
      console.log('Could not fetch products);
    });
};

A: It depends on the application you are building. If you are handling a large dataset then you should prefer server-side filtering.
The reason being that client-side filtering might result in a number of issues. For example, the client might show previously cached data to the user even though things on the server have been updated.
Also, you can implement techniques like throttling and debouncing to improve your application's efficiency.
In short, if your dataset is small, you can go on with client-side filtering. But to always be safe, I prefer server-side filtering.


text:
Q: How to use querySelector in a PopUp Modal

const pokemonContainer = document.getElementById('pokemonContainer');

pokemonContainer.innerHTML += `

`;

const allComments = document.querySelector('.all-comments');
allComments.appendChild(
Hello World
);

I'm trying querySelector('.all-comments') but as it's in pokemonContainer that's why It's returning undefined. Someone can please guide me on how to query select something placed in innerHTML as given above?

A: Node.appendChild() expects a node element as parameter, you can create a text node using Document.createTextNode():
allComments.appendChild(document.createTextNode('Hello World'));

Demo:

const pokemonContainer = document.getElementById('pokemonContainer');

pokemonContainer.innerHTML += `

`;

const allComments = document.querySelector('.all-comments');
allComments.appendChild(document.createTextNode('Hello World'));

Update: You cannot pass
Hello World
 directly to appendChild(). First you need to create a node of the type you want, then set the text, finally pass that node to the method.
OR: You can try using Element.insertAdjacentHTML()

const pokemonContainer = document.getElementById('pokemonContainer');

pokemonContainer.innerHTML += `

`;

const allComments = document.querySelector('.all-comments');
allComments.insertAdjacentHTML('beforeend', '
Hello World
');


text:
Q: Colocar menu na margem inferior do navbar Bootstrap 3 Tenho o seguinte menu:

Ele ficou desse tamanho porque o cliente exigiu que a logo ficasse maior, porém o menu ficou no topo da navbar. Como faço para que ela fique na base inferior da navbar?

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

Início

Quem Somos

Serviços

Galeria

Contato

A: Para retirar os cantos redondos:
.navbar{
   border-radius: 0;
}

Posicionar o menu no canto inferior direito:
#myNavbar{
   position: absolute;
   bottom: 0;
   right: 0;
}

Exemplo (execute em tela cheia):

.navbar{
   border-radius: 0;
}

#myNavbar{
   position: absolute;
   bottom: 0;
   right: 0;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

Início

Quem Somos

Serviços

Galeria

Contato


text:
Q: Issues with search box I am having another issue with my search form... i have three search fields the [year] [month] [name] but this is where i have an issue, i want to be that if the mysql_num_rows  <= 0 it should echo no records found for search key word. this is my code...
if ((empty($_POST['son_admin_query_year'])) && (empty($_POST['son_admin_query_month'])) && (empty($_POST['son_name']))) {

    echo "please search for something the boxes are empty.";

} else {

    if (
    isset($_POST['son_admin_query_year']) || isset($_POST['son_admin_query_month']) || isset($_POST['son_name'])) {
        $search_data = $_POST['son_name'];
        $search_year = $_POST['son_admin_query_year'];
        $search_mnth = $_POST['son_admin_query_month'];

        $search_data = mysql_real_escape_string($search_data);
        $search_year = mysql_real_escape_string($search_year);
        $search_mnth = mysql_real_escape_string($search_mnth);

        include_once("../../includes/db.php");

        $query = "SELECT * FROM importers WHERE im_name LIKE '%".$search_data."%' OR year LIKE '%".$search_year."%' OR month LIKE '%".$search_mnth."%'";
        $results = mysql_query($query) or die(mysql_error());

        echo "ROWS number ="."::".mysql_num_rows($results);
        if (mysql_num_rows($results) >= 1) {

            echo "
";
            echo '
';
            echo "
Importers Name	Address	Month	Year	View More

";

            while ($row = mysql_fetch_array($results)) {
                $add = $row['address'];
                $im_name = $row['im_name'];
                $state = $row['state'];
                $phone = $row['phone'];
                $email = $row['email'];
                $cac_no = $row['coc_no'];
                $son_mth = $row['month'];
                $son_year = $row['year'];

                $but_more = "<button class='btn btn-success'>View More</button>";

                echo "
";
                echo $im_name;
                echo "	";
                echo $add;
                echo "	";
                echo $son_mth;
                echo "	";
                echo $son_year;
                echo "	";
                echo $but_more;
                echo "	";
                echo "
";

            }
            echo "
";
            echo "
";
            //echo "
<button type='button' class='btn' id='print'>Print PDF</button>
";

        } else {
        }
    }
}


text:
Q: QR Code Scanner Integration with C# WPF I am writing one WPF application(MVVM) which needs to read data from QR Code Images using QR Code Scanner(Model: Symbol DS4308 - USB to connect with desktop). I googled for the same and identified that we can read QR Data using Textbox and it works. But my application won't have a textbox to capture the QR Code data but I need to get the scanner to provide the Event once scanning is done.
I tried with notepad and scanner writes the scanned values to it when scanning QR Code.
Is there any generic open source libraries to get the scanner events?

A: I haven't worked with the 4308 specifically, but I program Symbol scanners at work so I'm familiar with them.
First of all, forget about keyboard mode. It's handy for scanning directly into documents etc but it sounds like you want to read the scanner directly. If so, go to the DS4308 data sheet and scan in the barcode in section 6-6 for "Simple COM Port Emulation". This will cause the scanner to now appear as a serial device, which you can then read with the C# SerialPort class:
this.Scanner = new SerialPort(this.SymbolPort);
this.Scanner.BaudRate = 9600;
this.Scanner.DataReceived += Scanner_DataReceived;
this.Scanner.Open();
.
.
.
private void Scanner_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    var len = this.Scanner.BytesToRead;
    var bytes = new byte[len];
    this.Scanner.Read(bytes, 0, len);
    var str = Encoding.ASCII.GetString(bytes);
    // do something with str here
}

If you want to make your app really user friendly then you can also determine which COM port to use programatically using the device PID and VID. To get the PID/VID just go to device manager and check the properties for the device. To find the COM port use the code on this SO post, although that will search all devices installed on the system irrespective of whether or not they're actually plugged in so you'll want to cross-check it against SerialPort.GetPortNames().


text:
Q: Finding a date and replacing a word - Python I have a code as below where i am filtering out dates which are older then 2 days and making it bold and changing it's color.
In this I also want to replace the Warning to Failed where the date found is older then 2 days.
Can anyone please help how we can achieve it through below code.
import re
from datetime import datetime
ht ="""

32356
cfra03
04-07-2020
Ssv
Warning

32367
c017
04-08-2020
SDR
Completed

29451
c10
04-05-2020
SR
Warning

"""

date_var = re.findall(r"[\d]{2}-[\d]{2}-[\d]{4}", ht)
for s in date_var:
    element_date = datetime.strptime(s, "%m-%d-%Y")
    if (datetime.now() - element_date).days > 2:
        ht = ht.replace(s, ''+s+'')
print (ht)

current output is-

32356
cfra03
04-07-2020
Ssv
Warning

32367
c017
04-08-2020
SDR
Completed

29451
c10
04-05-2020
SR
Warning

Output should be-

32356
cfra03
04-07-2020
Ssv
Warning

32367
c017
04-08-2020
SDR
Completed

29451
c10
04-05-2020
SR
Failed

'''

A: This code:
import re
from datetime import datetime
ht ="""

32356
cfra03
04-07-2020
Ssv
Warning

32367
c017
04-08-2020
SDR
Completed

29451
c10
04-05-2020
SR
Warning

"""

result = []
rows = ht.split('
')
for row in rows :
    date_var = re.findall(r"[\d]{2}-[\d]{2}-[\d]{4}", row, re.DOTALL)
    for s in date_var:
        element_date = datetime.strptime(s, "%m-%d-%Y")
        if (datetime.now() - element_date).days > 2:
            row = row.replace(s, ''+s+'')
            row = row.replace( 'Warning', 'Failed') # or whatever
    result.append(row)

print ('
'.join(result))

gives this result:

32356
cfra03
04-07-2020
Ssv
Warning

32367
c017
04-08-2020
SDR
Completed

29451
c10
04-05-2020
SR
Failed

You may add HTML around Failed as you like.


text:
Q: Space generated by a reflection Suppose I embed a mirror (not necessarily plane) in some space (say a manifold). Is there a theory that tells you how to classify the "space" generated by the reflection (the one you see if you were inside the ambient space)? That is, is there a theory of "reflected spaces"? Are there non trivial examples of such simple reflected spaces known?
PS : note that the reflection can be self-similar : http://mathcraft.wonderhowto.com/inspiration/math-craft-inspiration-week-christmas-chaos-0131820/


text:
Q: R: Same Function With Different Outputs When evaluate in dplyr::mutate() I am new to R and tidyverse. Now I encountered a problem:
Suppose we have the character "2-Jan-01":
When running the function, we get:
as.Date("2-Jan-01", tryFormats = c("%y-%b-%d", "%b-%y-%d"))

[1] "2002-01-01"

However, when I use the command mutate:
df %>%
mutate(birth_date=as.Date(as.character(birth),
tryFormats = c("%y-%b-%d", "%b-%y-%d")))

When converting the entry 2-Jan-01, I get NA instead of 2002-01-01.
I do not understand why the same function will evaluate to different values inside and outside of the mutate. Can anyone explain it? Thank you in advance!

A: Your code runs fine for me.
librayr(dplyr)

df <- tibble(
  birth = "2-Jan-01"
)

Leaving your code untouched:
df %>%
  mutate(birth_date = as.Date(
    as.character(birth),
    tryFormats = c("%y-%b-%d", "%b-%y-%d")
  ))

I get:
  birth    birth_date
  <chr>    <date>
1 2-Jan-01 2002-01-01

(Note that I used a tibble, but it works just the same with a traditional data frame).
Now, there is no reason to use as.character() in your code since "birth" is already of the class character. So removing it, we have:
df %>%
  mutate(
    birth_date = as.Date(
      birth,
      tryFormats = c("%y-%b-%d", "%b-%y-%d")
    ))

Which gives the same result.
And if you don't want to keep the old "birth" column, you can use transmute() instead:
df %>%
  transmute(
    birth_date = as.Date(
      birth,
      tryFormats = c("%y-%b-%d", "%b-%y-%d")
    ))

Which gives:
  birth_date
  <date>
1 2002-01-01


text:
Q: AVPlayerViewController stuck on first frame of local video In one of my ViewControllers, I have an AVPlayerViewController. In my viewDidLoad I have
self.videoPlayerController = [AVPlayerViewController new];

Then, I play a video using the following method
- (void)playVideo:(NSURL*)videoURL {
    [self presentViewController:self.videoPlayerController animated:YES completion:^(){
        AVPlayer *player = [[AVPlayer alloc] initWithURL:videoURL];
        [self.videoPlayerController setVideoGravity:AVLayerVideoGravityResizeAspect];
        [self.videoPlayerController setPlayer:player];
        [self.videoPlayerController.player play];
    }];
}

When playing a video for the first time, the AVPlayerViewController appears, but the video is stuck on the first frame, and will not play. No audio plays either.
In iOS 10.0, the seekbar in the on screen controls show that the video is playing (it will progress to the end). In iOS 10.2 however, the seekbar is stuck at 0:00 as well.
I am experiencing this problem on iPads with iOS versions 10.0 and 10.2, however, it works in the XCode simulator (both 10.0 and 10.2).
My problem is similar in nature to this.
Also, the video plays correctly if you close the ViewController containing the AVPlayerViewController, reopen it, and attempt to play the video again.

A: I guess that the problem is in your video file. Try to download another video mp4 video sample. Add it to your project and try.


text:
Q: Flask-login not importing I'm trying to import Flask-login so I can use it:
from flask_login import LoginManager, login_required

However, it doesn't seem to import correctly, returning this error:
TypeError: login_required() missing 1 required positional argument: 'func'

I have user loaders, etc.:
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'account.login'

login_manager.init_app(app)

@login_manager.user_loader
def load_user(user_id):
    return app.get(user_id)

@login_manager.unauthorized_handler
def unauthorized():
    return "Unauthorized!"

When running pip3 install flask-login, it shows that it's already there. It's important to note there is no error when running it, however my IDE shows there is no module named flask-login.


text:
Q: Search/List Users Filter Expression Syntax in RingCentral SCIM 2.0 API In the RingCentral API reference there is a Search/List Users function that requires a filter expression. What is the syntax of this filter expression? The description of the filter parameter is simply "only support 'userName' or 'email' filter expressions for now".

A: The Search/List Users API is a SCIM 2.0 API so it follows the SCIM 2.0 conventions as defined by IETF RFC-7644.
Here's the section on filtering:
https://www.rfc-editor.org/rfc/rfc7644#section-3.4.2.2

3.4.2.2.  Filtering
Filtering is an OPTIONAL parameter for SCIM service providers. Clients MAY discover service provider filter capabilities by looking at the filter attribute of the ServiceProviderConfig endpoint (see Section 4).  Clients MAY request a subset of resources by specifying the filter query parameter containing a filter expression. When specified, only those resources matching the filter expression SHALL be returned. The expression language that is used with the filter parameter supports references to attributes and literals.
Attribute names and attribute operators used in filters are case insensitive.  For example, the following two expressions will evaluate to the same logical value:
filter=userName Eq "john"
filter=Username eq "john"

For RingCentral, you can use the following examples:
https://platform.ringcentral.com/scim/v2/Users?filter=userName eq "john@example.com"
https://platform.ringcentral.com/scim/v2/Users?filter=email eq "john@example.com"

In the SCIM API, a user can only have a single username but multiple email addresses. For RingCentral, they are the same because RingCentral only supports a single email address.


text:
Q: Safari icon from iPhone showing in macOS Dock Just now a Safari icon appeared to the left of my Dock with a tooltip saying it was from my iPhone. I have never seen this before! What is the point of it, why has it appeared today for the first time, and why has it now disappeared again?

A: This is Apple Handoff in action:

With Handoff, you can start something on one device (Mac, iOS, or Apple Watch)   and then pick it up on another without losing focus on what you're doing. For example, look at a webpage on your iPhone, then pick up where you left off in Safari on your Mac. You can use Handoff with many Apple apps—for example, Calendar, Contacts, Pages, or Safari. Some third-party apps may also work with Handoff.

(Image and text attribution: Apple.com)


text:
Q: UItableviewcell wonky display, they just can't get the screen width correctly with iphone6+. (objc) I just made a login screen using uitableviewcell instead of uiscrollview for simplicity, but it turned out to be a disaster.
I color the cell green so you can see it clearly. Here's how it looks in iPhone6+:

And here's how it looked in iPhone 5:

So the problems here are the UILabel and UITextField doesn't get the ip6+ screensize. I use this code to set them up which should be getting the correct screen size
screenWidth = [[UIScreen mainScreen] bounds].size.width;
UITableViewCell *cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 44)];
UITextField *field = [[UITextField alloc] initWithFrame:cell.contentView.layer.bounds];
OR
UILabel *uiLabel = [[UILabel alloc] initWithFrame:cell.contentView.frame];

My main question would be, if UIScreen doesn't work, how do we get proper width for iphone 6+ ??

A: The UITableViewCell will consider the width of the xib in the Interface Builder as its original width. If your xib is of iPhone 5 (i.e. 320 x 568), then the UITableViewCell's width will be set to 320px. If the xib in the IB is of iPhone 6+ (i.e. 414 x 736), the cell's width will be set as 414px.
To have a similar viewing experience in all devices, Apple recommends using Autolayout.
Just give the constraints to the tableview. Set the constraints of the tableview with respect to the superview and the UITableViewCell will automatically adjust with the screen size of the device. Also give the constraints to your UILabel.
Otherwise, you need to give screenWidth as width to the cell's content view and the UILabel.

A: OK, after experimenting, this code solved the problem:
UILabel *uiLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 44)];

so lesson of the day:
contentView.frame and contentView.layer.bounds DOESN'T get the correct cell size from UITableViewCell. Not sure why.
Can anyone enlighten me? Thanks!


text:
Q: Error when using AWS Android S3 SDK: Source not found - The JAR of this class file belongs to container 'Android private libraries' I'm working on an Android App with AWS Android SDK, especifically using S3, and I started receiving the following error:
Source not found - The JAR of this class file belongs to container
'Android private libraries' which does not allow modifications to source attachments
on its entries.

that happens on the line
s3Client = new AmazonS3Client(credentials);

when I try to create a new client to connect to S3.
I had to replace an old version of the SDK (1.7.1.1) with a newer version (2.1.0) in order to use PersistableDownload class to pause/resume downloads. I don't understand why is this happening since I'm not trying to change the library. What I remember doing:
- Removed the old library
- Added the new one
- Removed and added again several imports on the start of .java files
- Using an older device for the weekend (android API level 8)

Here is a extend part of the code. That might help.
AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY_ID, SECRET_KEY);

Region region = Region.getRegion(regions);

AmazonS3Client s3Client = null;
try {
    s3Client = new AmazonS3Client(credentials);
    s3Client.setRegion(region);
} catch (Exception e) {
    e.printStackTrace();
}
return s3Client;

Any help is aprpreciated to solve this. Thanks!
Edit: I forgot to say that I tried rolling back the old library and that gives me the same error. Most annoying part is that it was working before.

A: I believe this is related to the Android version. During the weekend I was using a cell with version 2.2.3, and now I'm using another device with version 4.4.4.
Version 1.7.1 of the SDK had no S3 issues with Android 2.2.3. Already posted a issue on the gitHub project and if/when the developers reply I'll update this.

A: the minimum version for the Android SDK is API level 10 which is 2.3.3. Also, yesterday we just released a new version that is considered our General Availability release taking version 2 of our SDK out of developer preview! I've added a post to GitHub to clarify the issue over there as well!


text:
Q: writing an SQL query I wrote this query but it's not executing
ResultSet rs6 = stmt.executeQuery(
    "UPDATE customer SET BALANCE = BALANCE + amount WHERE MOBILENUMBER = '"+phone+"' ");
rs6.next();
System.out.print("your account balance is  " +rs6.getString("BALANCE"));

amount is a double
what's wrong with it?

A: You should use executeUpdate for updates. The result of which will return the number of rows updated (not some arbitrarily updated columns new value). In order to get the new balance you are going to need to execute a follow up query.
Also, use prepared statements, they are good, really.

A: you just committed update command, not select command, so you cannot get the balance

A: UPDATE statements do not (usually) return a result. If you really want to update the data, you should use executeUpdate() instead. It will return the number of rows affected by the update.
If you actually want to retrieve the rows specified by the where condition, you should use a SELECT statement. That will return a ResultSet that you can loop through.

A: Update queries do not return results.  You will need to update in one statement and select in a second.  Also, please use parameterized queries - something like this would be better
PreparedStatement stmt = connection.prepareStatement("UPDATE customer SET BALANCE = BALANCE + ? WHERE MOBILENUMBER = ?");

stmt.setDouble(1, amount);
stmt.setString(2, phone);

stmt.execute();
stmt.close();

stmt = connection.prepareStatement("SELECT BALANCE from customer where MOBILENUMBER = ?");
stmt.setString(1, phone);

ResultSet rs6 = stmt.execute();
rs6.next();
System.out.print("your account balance is " +rs6.getString("BALANCE"));

rs6.close();
stmt.close();


text:
Q: Win32API: How to determine if EN_CHANGE was because of user action, not software action? I find this situation comes up from time to time, and I never seem to have a really robust generic solution to it.
I have a control - in this example an EDIT control on a dialog.  I want to take certain actions in response to the user - and only the user - modifying the contents of the edit control.
The edit control can be set programmatically - e.g. when the dialog is being setup, there may be an initial value placed into the edit field.  Or when the user selects an item from a listview, that selection's text may well be what's placed into the edit field.
But when the user modifies the contents of the edit field, I need to know that, and respond (in this scenario, I want to clear the selection from the corresponding listview).
I am currently looking at what control has focus, and only considering EN_CHANGE's to be "from the user" if the edit control has focus.
This works beautifully under Windows 7.  This fails under XP (I haven't tested Vista yet).
In XP, if the edit field has the focus, but the user clicks on the list view, and the list view tells the edit control to set its contents, then I get a notification from the edit control which claims to still have focus (::GetFocus() == HWND of edit control).  But this incorrect state doesn't occur in Win7.
This is a layered interface, so I cannot modify the list-view notification handler.  It gets a selection change, and updates the edit field without my involvement or ability to really intervene other than to get notifications from both of them.
Any thoughts on how to generically, permanently solve the "Is this control notification really from the user" conundrum?

A: You can always track LVM_ITEMCHANGING, LVM_ITEMCHANGED, and EN_MSGFILTER messages. If the edit box is modified between LVM_ITEMCHANGING and LVM_ITEMCHANGED without an EN_MSGFILTER in between then you can probably assume the user did not modify the item. Or just check to see if there are any items selected when EN_CHANGE fires and if not or the text doesn't match the selected item, assume it is a user edit.
Or use ES_MULTILINE (from EN_CHANGE documentation):

The EN_CHANGE notification is not sent
  when the ES_MULTILINE style is used
  and the text is sent through
  WM_SETTEXT.

A: I'd suggest using the right message.  EN_CHANGE is too generic, you want to know if the user typed or pasted text.  So why not subclass the control and watch for WM_KEYPRESS messages?
Alternatively, you can set a flag in your other code that sets the edit control content.  You might be able to assume that anything that makes your wndproc re-entrant represents a programmatic change.
You aren't looking for something actually secure, are you?  If you just want to exclude set content calls that's fairly straightforward.  If you want to differentiate between user action and programmatic simulation of user keypresses, that's a much harder problem.


text:
Q: Groovy enhancement name: Access map values directly in a List of Maps Dear Groovy specialists,
I stumbled upon a phenomenon in Groovy which I would describe as follows:
Given a list of maps that share some common keys, it is possible to access the Map values directly via the List.
Example:
ArrayList people = [
        ["height": 172, "age": 42],
        ["height": 180, "age": 66],
        ["height": 180, "age": null],
        ["height": 180],
        ["age": 10]
]

println "people.height: " + people.height
println "people.age: " + people.age

Output:
people.height: [172, 180, 180, 180, null]
people.age: [42, 66, null, null, 10]

Does this syntax (e.g. people.height / people.age) have a name?
Thanks in advance!
PS: This answer would be another example of the mentioned syntax

A:
Does this syntax (e.g. people.height / people.age) have a name?

That is Groovy's syntax for property access.
(Note that a property is a different thing than a field and Groovy has a bunch of special dynamic stuff that happens during property access.)


text:
Q: How to embed CKEditor to our html page using javascript? I try to embed ckeditor to my html page but i got a error like this (Uncaught TypeError: Cannot read property 'getEditor' of undefined).How to fix this error or how to embed that in any another methods?
Note:[Please put the code]

A: Simple sample:
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<textarea id="editor" name="editor" >content</textarea>
<script>

// This call can be placed at any point after the
// <textarea>, or inside a <head><script> in a
// window.onload event handler.

// Replace the <textarea id="editor"> with an CKEditor
// instance, using default configurations.

CKEDITOR.replace( 'editor' );

</script>

Demo Local Screenshot:

And below is the HTML code.
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CKEditor</title>
        <script src="//cdn.jsdelivr.net/jquery/3.1.0/jquery.min.js"> </script>
    <script src="ckeditor/ckeditor.js"></script>
</head>
<body>
    <textarea id="editor1"  name="editor1"></textarea>
    <script>
        CKEDITOR.replace( 'editor1' );
    </script>
</body>
</html>

Important : Dont use CDN it will throw undefined error, since it will look up for config.js etc. Download the source from this CKEditor Dowload and then refer your path to the ckeditor js and load the HTML. TADA :)
Let me know if that helps.


text:
Q: Uploading form-data with NestJS using Sequelize / PostgreSQL I'VE FOUND THE SOLUTION!!!
I'm writing the backend in Nest.Js / PostgreSQL using Sequelize.js.
I want to upload form-data (field + file); and save: file to static/uploads, field with file URL to the DB.
I've managed to write the code for file upload with Multer.js, but I'm struggling with sending data (not a file actually) to the DB.
Please, advise how to write the controller and service.
app.module.ts
@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: process.env.PUBLIC_DIR || path.join(__dirname, '../../public'),
      serveRoot: '/static',
    }),
    DatabaseModule,
    ConfigModule.forRoot({ isGlobal: true }),
    UsersModule,
    AuthModule,
    PostsModule,
    MulterModule.register({
      dest: './static/uploads',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

posts.module.ts
@Module({
  imports: [
    MulterModule.register({
      dest: 'static/uploads',
    }),
    DatabaseModule,
  ],
  providers: [PostsService, ...postsProviders],
  controllers: [PostsController],
  exports: [PostsService],
})
export class PostsModule {}

file.entity.ts
@Table
export class File extends Model<File> {
    @Column({
        type: DataType.STRING,
        allowNull: false,
    })
    name: string;

    @Column({
        type: DataType.STRING,
        allowNull: false,
    })
    url: string;

    @ForeignKey(() => Post)
    @Column({
        type: DataType.INTEGER,
        allowNull: false,
    })
    postId: number;

    @BelongsTo(() => Post)
    post: Post;
}

file.dto.ts
export class FileDto {
    @IsNotEmpty()
    readonly name: string;

    @IsNotEmpty()
    readonly url: string;
}

posts.controller.ts
@Post('images')
    @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: process.env.PUBLIC_DIR || path.join(__dirname, '../../../public'),
        filename: editFileName,
      }),
      fileFilter: imageFileFilter,
    }),
  )
    async uploadedFile(@UploadedFile() file, @Request() req, @Body() body ): Promise<File> {
    return await this.postService.createFile(req.post.id, file, body.name);
  }

posts.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { Post } from './post.entity';
import { PostDto } from './dto/post.dto';
import { User } from '../users/user.entity';
import { POST_REPOSITORY } from '../../core/constants';
import { FILE_REPOSITORY } from '../../core/constants';

@Injectable()
export class PostsService {
    constructor(
        @Inject(POST_REPOSITORY) private readonly postRepository: typeof Post,
        @Inject(FILE_REPOSITORY) private readonly fileRepository: typeof File,
    ) { }

   async create(post: PostDto, userId): Promise<Post> {
        return await this.postRepository.create<Post>({ ...post, userId });
    }

    async createFile(postId: number, file: any, bodyName ): Promise<File> {
        return await this.fileRepository.save({
          name: bodyName,
          url: `${process.env.URL}/static/${file.filename}`,
          postId: postId,
        });
        }

    async findAll(): Promise<Post[]> {
        return await this.postRepository.findAll<Post>({
            include: [{ model: User, attributes: { exclude: ['password'] } }],
        });
    }

    async findOne(id): Promise<Post> {
        return await this.postRepository.findOne({
            where: { id },
            include: [{ model: User, attributes: { exclude: ['password'] } }],
        });
    }

    async delete(id, userId) {
        return await this.postRepository.destroy({ where: { id, userId } });
    }

    async update(id, data, userId) {
        const [numberOfAffectedRows, [updatedPost]] = await this.postRepository.update({ ...data }, { where: { id, userId }, returning: true });

        return { numberOfAffectedRows, updatedPost };
    }
}

Also, I got an error in posts.service.ts -
 Property 'save' does not exist on type '{ new (fileBits: BlobPart[], fileName:
 string, options?: FilePropertyBag): File; prototype: File; }'.ts(2339)

Appreciate any help )


text:
Q: Dynamic cell calculation for each row Im trying to create a tbale with dynamic cells and a calcultion is performed after each row. However, I cannot seem to get the element total for each rw in the table, it only ever ammneds the firt or comes out 'undefined'.
Code for creating table:
$(document).ready(function () {

    $(document).on('click', '.add', function () {
        var html = '';
        html += '
';
        html += '<input type="text" name="item_name[]" oninput="calc()" class="form-control item_name" />	';
        html += '<input type="text" name="item_quantity[]" class="form-control item_quantity" />	';
        html += '<input type="text" name="item_unit[]" class="form-control item_unit" />	';
        //NEW ONES!!!!!!!!!!!!!!!
        html += '<select name="item_glass[]" class="form-control item_glass"><option value="">Select Glass Type</option><?php echo fill_unit_select_box($connect); ?></select>	';
        html += '<select name="item_splash[]" class="form-control item_splash"><option value="">Select Splash</option><?php echo fill_unit_select_box3($connect); ?></select>	';

        html += '<input type="text" name="item_HQuan[]" class="form-control item_HQuan" />	';
        html += '<select name="item_HDiam[]" class="form-control item_HDiam"><option value="">Select Hole Diameter</option><?php echo fill_unit_select_box2($connect); ?></select>	';
        html += '<input type="text" name="item_CQuan[]" class="form-control item_CQuan" />	';

        //Total
        html += '<input type="text" name="item_Total[]" id="item_total[]" class="form-control item_total" disabled/>	';

        html += '<button type="button" name="remove" class="btn btn-danger btn-sm remove">Delete Row</button>
';
        $('#item_table').append(html);
    });

Code I've tried for testing get element and change it for each row:
function calc(x){

  var i = x.rowIndex;
  document.getElementById("item_total[]").value = "test";

}

function calc(x){

  var i = x.rowIndex;
  document.getElementById("item_total[]")[i].value = "test";

}

function calc(x){

  var i = x.rowIndex;
  document.getElementByName("item_total")[i].value = "test";

}

None of these work and i've no idea how to fix this?

A: May I suggest you use querySelector() instead. With it you can find elements using CSS selectors, like this, using the attribute selector:
document.querySelector('[name="item_name[]"]')

Updated based on a comment
If you have multiple input with the same name, you could use querySelectorAll() and loop the result, e.g.
var els = document.querySelectorAll('[name="item_name[]"]');
for (var i = 0; i < els.length ; i++) {

   // do something with e.g. each value
   var val = parseFloat(els[i].value);   // or parseInt(), so it becomes a number

}

Do note, the inner brackets might needs to be escaped, like this, to work properly cross browsers:
'[name="item_name\\[\\]"]'

Notes:
Your getElementById() won't work since the item_name[] is not an id.
Your getElementByName() won't work since you misspelled it. Should be getElementsByName() with an s in Elements


text:
Q: Css Positioning Issue How can I move div over images using CSS? I tried a lot but failed.
CSS
.mytooltip
{
    border: 1px solid #FF0000;
    background-color: #C0C0C0;
    width: 100px;
    height: 100px;
    position: inherit;
    top: 250px;
    left: 150px;
    z-index: 9999;
}

.myfloorplan
{
    position: inherit;
}

Html

            MyLabel

            MyLabel

Should be ....

A: You need to use position:absolute; and make sure your main container is position:relative;
An example is at http://jsfiddle.net/Pqz5F/
#container{
    position:relative;}
.mytooltip
{
    position:absolute;
    top:50px;
    left:0;
    border: 1px solid #FF0000;
    background-color: #C0C0C0;
    width: 100px;
    height: 100px;

    z-index: 9999;
}

.myfloorplan
{
    position: inherit;
}


text:
Q: Shrink data files below initial size SQL Server 2005 Inherited a database with min size for one data file (primary) at 10 gigs and the min size for a secondary file to 6 gigs.

*

*Why would someone have created a secondary data file (NDF)?

*How do I shrink these below the initial sizes set for the fiels.

A: 1. Why would someone have created a secondary data file (NDF)?

This is a way to get create two files on the operating system. Some advantages:

*

*2 file handles

*possibility of splitting across different disks or storage subsystems (fast/slow) even if you don't do it right away

*prepare for partitioning

*controlling per-file operations, like shrinkfile below

*allows a large db on a prod system to be restored onto a test/dev system that does not have a single large enough disk for single-file. Thus 2x 400GB files on a prod system (same folder) is restored onto 2 different 500GB disks on the dev system.

2. How do I shrink these below the initial sizes set for the files

Use DBCC SHRINKFILE instead of DBCC SHRINKDATABASE. It can be set to any desired size, even smaller than initial, as long as it is greater than the size of data currently stored.  To reach smaller sizes, set the target
DBCC SHRINKFILE (1, 0);  -- file id 1, to 0% free space

To find out the file ids, you can use (while in the db)
select * from sysfiles

A: *

*You would create secondary data files to distribute your database over multiple disk drives.

*You can't shrink the original file below the initial size.  You can shrink the NDF file so that it's empty (see DBCC SHRINKFILE, EMPTYFILE option), then drop the file and recreate it (if you want) at the size you want.  The shrink will move the data to other files in the file group.


text:
Q: Amazon MWS Flat File Modify Listing I'm trying to find the documentation for how the flat file looks for modifying the quantity of a product on Amazon.
This is what we send at the moment but it would be good to see what the list of headings we can use.
SKU | Quantity
000 | 1

I'm guessing that this is correct,
SKU | Price | Quantity
000 | 9.99  | 1

Any links would be welcome.
Amazon's MWS site https://developer.amazonservices.com/

A: You can get to the full description of the flat file feed specifications to send the flat file in the correct format to the MWS by going to the following URL after you're logged into your sellercentral or mws account.
https://sellercentral.amazon.com/gp/help/help.html/ref=ag_13461_cont_help?ie=UTF8&itemID=13461&language=en_US

A: have a look at the scratchpad, this will bring back flat files so you can see how they look.
https://mws.amazonservices.co.uk/scratchpad/index.html - UK Version
https://mws.amazonservices.com/scratchpad/index.html - General (US) version


text:
Q: jquery show spinner when processing When '.btn-save' is clicked, a server side script(probably php) would connect with the server to upload image or form data to the server. While this process is happening I want a spinner to show.
My HTML for the spinner is:

My CSS:
.spinner {
    z-index: 9999;
    position: fixed;
    background: rgba(0, 0, 0, 0.1);
    width: 100%;
    height: 100%;
    top: 0; left: 0; right: 0; bottom: 0;
    display: none;
}
.spinner img {
    position: fixed;
    left: 50%;
    top: 50%;
    z-index: 10000;
}

I found an answer that suggested doing something like this:
        $body = $("body");

        $(document).on({
            ajaxStart: function() { $body.addClass("loading");    },
             ajaxStop: function() { $body.removeClass("loading"); }
        });

The CSS:
body.loading {
    overflow: hidden;
}

body.loading .spinner {
    display: block;
}

I want to know if this will work for me or if you could suggest something different in my case.

A: When using an ajax you can simply use this:
$.ajax({
  url:'/sample/url',
  type:'POST',
  //it will fired when the data is currently processing
  beforeSend: function(){

   $('body').addClass("loading");
  },
  success: function(){
   $('body').removeClass("loading");
  },
  error: function(){
  }
});

A: I done similar thing ,
<form id="feedback">

<input type="submit" value="submit" >

In your jquery after button click,
$('#feedback').submit(function (event) {
        $("#loader_login").css("display", "block");

       //data process

       $("#loader_login").css("display", "none");
}

A: In your case, the ajaxStart and ajaxStop functions do not undestand the variable $body, as it is defined outside of them.
You need to use $("body").addClass("loading") inside the ajaxStart function, and similar for removeClass too.


text:
Q: Multi-statement in a line What's wrong with my code?
- it compiles correctly the 'while' structure
- it compiles correctly the colon separeted statements
- but reports syntax error if colon separeted statements are in a 'while' structure. Here it is:
0x363> while (a>b) { a=3 }
0x36e > a=3 : b=2
0x376 > while (a>b) { a=3 : b=2 }
syntax error

I suppose my stmt_list is wrong - but what's the correct solution?

Note: I do not use any special terminal character like ';'

stmt:
    .....
    | WHILE '(' expr ')' stmt_list  { $$ = opr(WHILE, 2, $3, $5); }
    .....

stmt_list:
    stmt                { $$ = $1; }
    | stmt ':' stmt         { $$ = opr(':', 2, $1, $3); }
    | '{' stmt_list '}'     { $$ = $2; }
    ;

A: Are you deliberately trying to restrict statement lists to no more than two statements? That seems odd to me.
Also, your while statement is ambiguous, since a stmt_list could be a=3 : b=2 (without the {}). Consequently, the following is legal but can be parsed two ways:
while (a>b) while (c>d) a=b : c=d

What I would have expected would be:
stmt:
   ...
   | while '(' expr ')' stmt  /* NOT stmt_list */
   ...
   | '{' stmt_list '}'
   ;

stmt_list:
   stmt
   | stmt_list ':' stmt
   ;

None of that explains where your syntax error is coming from, though. I suspect the answer has to do with how you compose statements into a program, since your example demonstrates that a program is not a stmt_list (unless you have some hack to insert colons at line ends).


text:
Q: How to pass an argument to a function in data binding? I have two variables inside my layout file :
<data>
  <variable name="createExpenseViewModel" type="com.lionosur.dailyexpenses.viewModels.MainViewModel"/>
  <variable name="createExpenseConverter" type="com.lionosur.dailyexpenses.converters.createExpenseActivityConverter.Companion"/>
</data>

My view model has an method to return the live data :
fun getAllExpenseItems(): LiveData<List<Expense>> {
    return expenseRepository.getAllExpenseItems()
}

I need to observe this data and populate an spinner,
class createExpenseActivityConverter {
    // contains all the static methods to convert the data for the ui
    companion object {

        fun getExpenseCategoryListFromSource(list:List<Source>):ArrayList<String> {
            val categoryItems = ArrayList<String>()
            categoryItems.addAll(list.map { it.sourceName })
            return categoryItems
        }
    }
}

to populate a spinner I need to supply an array list of string
<Spinner
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/expense_category"
        android:entries="@{()-> createExpenseViewModel.getAllSourceItems(1) }"
        app:layout_constraintStart_toStartOf="@+id/textView"
        android:layout_marginTop="20dp"
        app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintWidth_percent="0.7"
/>

in android:entries I need to convert the observed data to array list of string, how do I pass the @{()-> createExpenseViewModel.getAllSourceItems(1) } result in to another static method createExpenseViewConverter.getExpenseCategoryListFromSource(sourceList) which would return a array list of string.
in my activity i have setup binding like this
binding = DataBindingUtil.setContentView(this, R.layout.activity_create_expense)

val mainViewModel =  DaggerExpenseComponent.builder()
    .setContext(this)
    .build()
    .getExpenseViewModel()

binding.setLifecycleOwner(this)
binding.createExpenseViewModel = mainViewModel

A: You'll need to use below syntax for that :
android:entries="@{createExpenseConverter.getExpenseCategoryListFromSource(createExpenseViewModel.getAllSourceItems(1))}"

Here, what we've done is accessed your input from MainViewModel object createExpenseViewModel using getAllSourceItems() method;
And then passing it to another class createExpenseActivityConverter object createExpenseConverter using method getExpenseCategoryListFromSource() which returns you ArrayList<String> that your spinner requires.

Edit:
When you use LiveData in DataBinding, Data-binding Compiler takes care of refreshing data just like ObservableFields. All you need to do is provide your LifeCycleOwner to your databinding object.
For Example:
If your activity has ViewDataBinding let's say mActivityBinding using which you provide your ViewModel to set LiveData in xml binding, then after setting your ViewModel consider setting LifecycleOwner like below code :
//Some Activity having data-binding
... onCreate() method of activity
    mActivityBinding.setViewModel(myViewModel);
    mAcivityBinding.setLifecycleOwner(this); // Providing this line will help you observe LiveData changes from ViewModel in data-binding.
...

Refer here


text:
Q: QGIS 3: ALKIS vs Google Satellite arange Layer congruently ist possible to move the google layer by offset to fit the (correct positioned) alkis layer? (Alkis: UTM Zone 32N)
I know I can change the projection, but I tried some without success.
My Project KBS/CRS is EPSG:25832.
I read some similar threads but none of some helped.
Regards
Edit: Image added

PS: I load google with this link "https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}" as "X Y Z Tiles" out of the browser-list.


text:
Q: How to set the Store View after login automatically for the whole session? After logging into the backend and navigating to Catalog / Manage Products, the the dropdown "Choose store view" is set to "All Store Views" instead of the defined default Store View.
After changing the dropdown "Choose store view" to the desired Storeview the Store View is set.
How is it possible to set the Store View after login automatically for the whole session?

A: So you cannot do this by default but what you could do, and sorry this is only concept, would be to expand on the admin user to add a new attribute for default store.
Then expand the store selector to read the default value from the user and set this value.
Not 100% sure how to code this but technically it should be possible just not sure how much effort it would be.

A: You cannot set the default store view for an admin user for the whole session. However, what you can do is to set the store at the product grid level. A possible solution is to add a column called default_store_id to the table admin_user and then set the desired store id for each user. Next, override the method _getStore() in Mage_Adminhtml_Block_Catalog_Product_Grid:
protected function _getStore()
{
    $storeId = (int) Mage::getSingleton('admin/session')->getUser()->getDefaultStoreId();
    if (!$storeId) {
        $storeId = (int) $this->getRequest()->getParam('store', 0);
    }
    return Mage::app()->getStore($storeId);
}


text:
Q: Can I loop files for get MD5 with java Thread? I am currently trying to get a list of files with a list of your Hash in MD5.
Being something that can take a long time I'm trying to do it with threads, but fail updating views with list.nullPointer
The code is the following some idea
for (File file : files) {
            ListRunable listaRunable = new ListRunable(file);
            listRunable.start();
            String md5 = listRunable.getMD5();
            file = listRunable.getFile();
            updateHashes(file, md5);
        }

Some idea why it fails?


text:
Q: Error:(11, 0) Declaring custom 'clean' task when using the standard Gradle lifecycle plugins is not allowed Hello i am working now on android application with 2 modules the first is my app with buildgradle like
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.alexvasilkov:android-sign-release:0.8.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'com.alexvasilkov.sign'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "dz.condorpos"
        minSdkVersion 17
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            storeFile file("foldable-layout-release-key.keystore")
            keyAlias "release"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile project(':library')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.squareup.okhttp3:okhttp:3.8.1'
    compile 'com.github.barteksc:android-pdf-viewer:1.4.0'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.alexvasilkov:android-commons:2.0.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.afollestad:easyvideoplayer:0.3.0'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.google.firebase:firebase-database:10.0.1'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
    compile 'com.google.firebase:firebase-storage:10.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'

    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

the second module is a library included to my project here is the buildgradle(module:library):
apply plugin: 'com.android.library'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
    }
}
// New version can be uploaded with 'gradlew clean :library:jar :library:uploadArchives'
apply from: 'gradle-mvn-push.gradle'

dependencies {
}

the project buildgradle is like :
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {

        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects { project ->
    repositories {
        jcenter()
        maven { url 'https://dl.bintray.com/drummer-aidan/maven' }
    }
    // Enabling checkstyle for all sub projects
    project == rootProject || project.afterEvaluate {
        project.apply plugin: 'checkstyle'

        project.extensions.getByName('checkstyle').with {
            toolVersion = '6.15'
            configFile file("${rootDir}/checkstyle.xml")
        }

        task checkstyle(type: Checkstyle) {
            source 'src'
            include '**/*.java', '**/*.xml'
            classpath = files()
        }

        project.tasks.getByName('check').dependsOn 'checkstyle'

        project.extensions.getByName('android').with {
            lintOptions {
                ignore 'GoogleAppIndexingWarning', 'ContentDescription'
            }
        }

    }
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
}

the project was working perfectly till yesterday when i added a compile dependencies of picasso in my app module after the gradle sync failed it show this
 Error:(11, 0) Declaring custom 'clean' task when using the standard Gradle lifecycle plugins is not allowed.

now even if i remove picasso the error still happening Of course I did not ask the question before long research i found some solutions but didnt work like this
note : an old version of my project still working normal with the same clean task but after some gardle syncs i will get this problem.
I would like to thank you in advance for your assistance

A: After so many research i found we have to just comment the line of clean task in bulid.gradle(Project) like below :
   //    task clean(type: Delete) {
        //        delete rootProject.buildDir
        //    }][1]


text:
Q: draw images in the screen when having a state manager in pygame I'm trying to create a more efficient game with pygame following some example I was able to find online. Basically right now I'm creating various state in different files that are then managed by the game.py and the main.py file. My problem is I'm having an hard time understanding how to use the code for my needs: in my code after showing two random images in the left and in the right side of the screen I'd like to use the def answer(self) to show the self.answered_img in the middle of the screen after a keyboard character("q" or "r") is pressed and then wait two seconds before showing other two random images:
Usually I would have  done this by writing
def answer(self):
   self.screen.blit(self.answered_img, middle_rect)
   pygame.time.wait(2000)

but with my current code structure I have not the self.screen variable.
This is the rest of my code
game_app.py
import pygame
from .base import BaseState
import os

import random

class GameApp(BaseState):
    def __init__(self):
        super(GameApp, self).__init__()

        self.answered_img = pygame.image.load(
            os.path.join("data", "assets", "images", "feedback", "img_feedback_0.png")
        )

        image_path = os.path.join("data", "assets", "images", "stimuli")

        self.dict = {}

        ## One
        one_path = os.path.join(image_path, "blue")
        one_path_list = os.listdir(one_path)

        self.dict[0] = [
            (
                pygame.image.load(os.path.join(one_path, path)),
                os.path.basename(os.path.join(one_path, path)),
            )
            for path in one_path_list
        ]

        ## Two
        two_path = os.path.join(image_path, "orange")
        two_path_list = os.listdir(two_path)

        self.dict[1] = [
            (
                pygame.image.load(os.path.join(two_path, path)),
                os.path.basename(os.path.join(two_path, path)),
            )
            for path in two_path_list
        ]

        self.image()

    def get_event(self, event):
        if event.type == pygame.QUIT:
            self.quit = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                self.quit = True
            if event.key == pygame.K_q:
                print("q")
                self.keyboard_pressed()
            if event.key == pygame.K_r:
                print("r")
                self.keyboard_pressed()

    def draw(self, surface):
        surface.fill(pygame.Color("black"))

        left_rect = self.left_image.get_rect(midleft=(50, surface.get_height() / 2))

        right_rect = self.right_image.get_rect(
            midright=(surface.get_width() - 50, surface.get_height() / 2)
        )

        surface.blit(self.left_image, left_rect)
        surface.blit(self.right_image, right_rect)

    def keyboard_pressed(self):
        self.answer()

        self.image()

    def image(self):
        left_list = self.dict[0]
        self.left_image = random.choice(left_list)[0]

        right_list = self.dict[1]
        self.right_image = random.choice(right_list)[0]

    def answer(self):

    # show the self.ansered_img

        pygame.time.wait(2000)

this is the rest of my code:
main.py
pygame.init()
pygame.mouse.set_visible(False)

screen = pygame.display.set_mode((800, 600))

states = {
    "GAME_APP": GameApp(),
}

game = Game(screen, states, ""GAME_APP": ")
game.run()

pygame.quit()
sys.exit()

game.py
import pygame

class Game(object):
    def __init__(self, screen, states, start_state):
        self.done = False
        self.screen = screen
        self.clock = pygame.time.Clock()
        self.fps = 60
        self.states = states
        self.state_name = start_state
        self.state = self.states[self.state_name]

    def event_loop(self):
        for event in pygame.event.get():
            self.state.get_event(event)

    def flip_state(self):
        current_state = self.state_name
        next_state = self.state.next_state
        self.state.done = False
        self.state_name = next_state
        persistent = self.state.persist
        self.state = self.states[self.state_name]
        self.state.startup(persistent)

    def update(self, dt):
        if self.state.quit:
            self.done = True
        elif self.state.done:
            self.flip_state()
        self.state.update(dt)

    def draw(self):
        self.state.draw(self.screen)

    def run(self):
        while not self.done:
            dt = self.clock.tick(self.fps)
            self.event_loop()
            self.update(dt)
            self.draw()
            pygame.display.update()

How can I show an image in different functions that are not the def draw(self, surface) one?


text:
Q: Uncaught Type error in React JS I get the below error message when I open my html file.
TypeError: undefined is not a function (near
'..._react2.default.createClass...')
(anonymous function)bundle.js 966
_webpack_require bundle.js 20
(anonymous function)bundle.js 73
_webpack_require bundle.js 20
(anonymous function)bundle.js 63
_webpack_require bundle.js 64

This is my Html code

This is my app.js file
   import firstComponent from './firstComponent'
This is my first component.js file
import React from 'react'
import ReactDOM from 'react-dom'
var CommentBox=React.createClass({
 render:function(){
   return(

                HelloWorldCommentBox

   );
   }
  });
  ReactDOM.render(
  <commentBox/>,
       document.getElementById('content')
  );

Please Help me with this

A: The name of the component has to started with a capital letter and you have to use use the same name when you use the component.
The component is

<CommentBox/>

not

<commentBox/>


text:
Q: Error al visualizar imagen con cv2 - Exception in Tkinter callback espero me puedan ayudar, estoy trabajando con la libreria cv2, quiero visualizar una imagen en una frame, pero me genera error, si le quito el frame me la visualiza, pero si coloco el frame que creo me genera error, ademas me deja la imagen abierta, no la cierra.
def visualizar_imagen(self):
        frame60 = LabelFrame(self.windows_leer_imagen, borderwidth=0)
        frame60.place(x =20, y = 120)
        path = '/oftica/Visuales/' + self.miid_nombre_imagen + '.png'
        image = cv2.imread(path)
        cv2.imshow(frame60, image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

me genera el siguiente error

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\panto\AppData\Local\Programs\Python\Python38\lib\tkinter      \__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Oftica\oftalmenu.py", line 326, in visualizar_imagen
    cv2.imshow(frame60, image)
cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function   imshow'
> Overload resolution failed:
>  - Can't convert object of type 'LabelFrame' to 'str' for 'winname'
>  - Can't convert object of type 'LabelFrame' to 'str' for 'winname'
>  - Can't convert object of type 'LabelFrame' to 'str' for 'winname'

Agradezco me pueden ayudar a identificar mi error
Muchas gracias de antemano.


text:
Q: Need support in this issue OSError: [WinError 127] The specified procedure could not be found While importing mdanalysis by conda install mdanalysis
I'm facing the following error message:
[WinError 127] The specified procedure could not be found
I tried the suggestion from this article but without success.
Any ideas how to fix it?


text:
Q: How to add text from a file as a header into multiple files which are in separate folder? I have a text file with some text in it, I need that text to be as header in all the files which are in different folder using batch script.
Let us say Header.txt is the file with text This is Heading and I want this text to be as heading in each and every text file of the folder C:\...\*.txt.
For example Body.txt is one of the files in different folder with text as I am the body. I want the text in Body.txt to be as:

This is Heading
I am the body

A: Try this (adapt file names and paths accordingly):
for %%F in ("C:\...\*.txt") do (
    > "%%~F.tmp" type "Header.txt"
    >> "%%~F.tmp" type "%%~F"
    move /Y "%%~F.tmp" "%%~F"
)

This combines the content of Header.txt and the processed text file in a temporary file (for instance, the text file is Body.txt, so the temporary file is Body.txt.tmp), then it moves the temproary file over the original text file, hence it gets replaced. Note that the heading in the file Header.txt must be terminated with a line-break; otherwise, the heading and the first line of the text file are combined into a single line of text.

In order to check the files whether the already have been inserted the header to, you could redirect their first lines into a variable and compare them with the first line of the header file, like this:
< "Header.txt" set /P HEAD=""
for %%F in ("C:\...\*.txt") do (
    < "%%~F" set /P LINE=""
    setlocal EnableDelayedExpansion
    if not "!LINE!"=="!HEAD!" (
        endlocal
        > "%%~F.tmp" type "Header.txt"
        >> "%%~F.tmp" type "%%~F"
        move /Y "%%~F.tmp" "%%~F"
    ) else endlocal
)

Every single file is checked individually here. For this you need delayed expansion as you are writing to and reading from the same variable within a block of code, that is the for loop.


text:
Q: Get Connection from injected DataSource throws exception with multiple datasources in Micronaut Data JDBC Couldn't get connection from injected DataSource like spring and as written in documentation(Configuring Multiple Data Sources) https://micronaut-projects.github.io/micronaut-sql/latest/guide/#:~:text=Configuring%20Multiple%20Data%20Sources throws
Suppressed: io.micronaut.transaction.exceptions.NoTransactionException: No current transaction present. Consider declaring @Transactional on the surrounding method
        at io.micronaut.transaction.jdbc.TransactionalConnectionInterceptor.intercept(TransactionalConnectionInterceptor.java:65)
        at io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:137)
        at io.micronaut.transaction.jdbc.TransactionalConnection$Intercepted.close(Unknown Source)
        at com.demo.service.DemoService.processRecords(DemoService.java:116)
        ... 11 common frames omitted
    Caused by: io.micronaut.transaction.jdbc.exceptions.CannotGetJdbcConnectionException: No current JDBC Connection found. Consider wrapping this call in transactional boundaries.
        at io.micronaut.transaction.jdbc.DataSourceUtils.doGetConnection(DataSourceUtils.java:135)
        at io.micronaut.transaction.jdbc.DataSourceUtils.getConnection(DataSourceUtils.java:93)
        at io.micronaut.transaction.jdbc.TransactionalConnectionInterceptor.intercept(TransactionalConnectionInterceptor.java:63)
        ... 14 common frames omitted

A: I solved my problem by unwrapping injected DataSource (more):
DataSource db1Ds = ((DelegatingDataSource) db1DataSource).getTargetDataSource();
Connection db1Conn = db1Ds.getConnection();
/* or
Connection db1Conn = ((DelegatingDataSource) db1DataSource).getConnection();
*/

I don't know that there is short solution or not.


text:
Q: Is it possible to specify a custom timing functions for CSS transitions? I use CSS transitions pretty frequently now but find it limiting to only have access to ease-in, ease-out etc. The bezier-curve option appears to allow the most control but even this does not allow you to specify an actual easing equation that would simulate elastic easing etc.. Is there another option or does one need to resort to javascript to perform this type of animation?

A: I found there is no way to do an elastic transition with pure CSS. However you can cheat and do a CSS animation. This is what apple uses on their site:
@-webkit-keyframes open-1 {
    from { opacity:0; -webkit-transform:translate3d( 210px, -145px, 0); }
    25%  { opacity:1; -webkit-transform:translate3d( -15.6px, 4.1px, 0); }
    30%  { opacity:1; -webkit-transform:translate3d( -10.3px, 2.7px, 0); }
    35%  { opacity:1; -webkit-transform:translate3d( 0, 0, 0); }
    40%  { opacity:1; -webkit-transform:translate3d( 4.5px, -1.2px, 0); }
    45%  { opacity:1; -webkit-transform:translate3d( 2.9px, -0.8px, 0); }
    50%  { opacity:1; -webkit-transform:translate3d( 0, 0, 0); }
    55%  { opacity:1; -webkit-transform:translate3d( -1.3px, 0.3px, 0); }
    60%  { opacity:1; -webkit-transform:translate3d( -0.8px, 0.2px, 0); }
    65%  { opacity:1; -webkit-transform:translate3d( 0, 0, 0); }
    70%  { opacity:1; -webkit-transform:translate3d( 0.4px, -0.1px, 0); }
    75%  { opacity:1; -webkit-transform:translate3d( 0.2px, -0.1px, 0); }
    80%  { opacity:1; -webkit-transform:translate3d( 0, 0, 0); }
    85%  { opacity:1; -webkit-transform:translate3d( -0.1px, 0, 0); }
    90%  { opacity:1; -webkit-transform:translate3d( -0.1px, 0, 0); }
    to   { opacity:1; -webkit-transform:translate3d( 0, 0, 0); }
}

These animations are used to great extent on Apple's own website:
http://www.apple.com/mac/
Obviously this is powerful to some extent -- since the animations are percentages you can easily change he duration and retain the effect.
However, this is still very static. Let's say you want to click a button and have it perform an elastic scaling animation. No problem, one animation can be used over and over again for each button. But let's say you want to have an element elastically snap it's position to wherever the user most recently clicked or tapped on the screen. Well in this case you'd need to dynamically recalculate the keyframes and then apply the animation to the element.
At the time of this writing I don't know that there are any good examples of dynamically generating CSS animations on the fly inside of javascript. In fact it probably warrants another question. All in all this is the only pure CSS way I found to do render a complex easing equation such as elastic easing purely with CSS.

A: Actually you don't need a JavaScript library to support complex easing functions like bounce-ease-in or elastic-ease-out.  Here's the CSS3 Animation Generator tool which generates the keyframes for you, and enables 12 additional easing functions not supported by the w3c spec:
http://www.css3animationgenerator.com/

A: You can use Caesar to generate CSS for different equations.

A: i know that if you're using mootools you could write your own equation:
http://mootools.net/docs/core/Fx/Fx.Transitions

Class: Fx.Transition
This class is only useful for math
  geniuses who want to write their own
  easing equations. Returns an Fx
  transition function with 'easeIn',
  'easeOut', and 'easeInOut' methods.

Maybe the other libraries like jquery or prototype have the same class, probably they do have something similar.
Good Luck!