text:
Q: Mysql table name not working in uppercase I need to change mysql is accept both uppercase and lowercase table name ,
select * from users

the above query working fine but the below query is not working,
select * from USERS

A: windows = lowercase.
I do not recommend changing the mysqld config to 0 or 2.

*

*lower_case_table_names = 0    (comparisons are case-sensitive)
If set to 0, table names are stored as specified and comparisons are case-sensitive.

*lower_case_table_names = 1    (comparisons are not case-sensitive)
If set to 1, table names are stored in lowercase on disk and comparisons are not case sensitive.

*lower_case_table_names = 2    (comparisons are case-sensitive)
If set to 2, table names are stored as given but compared in lowercase.
If you want to change it, find my.ini file in windows usually mysql directory, in wamp check the bin directory and add the "lower_case_table_names = 0" or "lower_case_table_names = 2"
This option also applies to database names and table aliases.
Reference to https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_lower_case_table_names

A: It depends on your system (Unix, Windows and Mac OS for the main values).
You need to set your system variable "lower_case_table_names" to 1 or 2, to make your database case insensitive.
SET lower_case_table_names=1;

or
SET lower_case_table_names=2;

click at Mysql.com and here

A: Table and database names are stored on disk using the lettercase specified in the CREATE TABLE or CREATE DATABASE statement. Name comparisons are case sensitive. You should not set this variable to 0 if you are running MySQL on a system that has case-insensitive file names (such as Windows or Mac OS X). If you force this variable to 0 with --lower-case-table-names=0 on a case-insensitive file system and access MyISAM tablenames using different lettercases, index corruption may result.
http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html

A: Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix.
In MySQL, databases correspond to directories within the data directory.
Each table within a database corresponds to at least one file within the database
directory. Consequently, the case sensitivity of the underlying operating system
plays a part in the case sensitivity of database and table names.

Read the section: 8.2.2. Identifier Case Sensitivity
But to solve your problem, you could create a view of the table setting the name as the different case.  But then what happens to users

A: One option can be setting all the table names to either lower or upper as per your OS needs.
select concat('rename table ', table_name, ' to ' , lower(table_name) , ';') from information_schema.tables where table_schema = 'your_schema_name';

copy all the lines and execute them :)

A: I spent ages trying to resolve this, where all other SQL queries were working without issue on my system.
As it turns out, I'd added the new table I was looking for into a different database by accident (working on a different project).
I recommend just double check you're looking for the right table, in the right database, in the right domain... Good luck!

A: In order to have your SQL tables created in either Uppercase or camelCase, do the following.
Step 1: open your MySQL my.ini configuration file:
               => [Linux]\xampp\mysql\bin\my.ini
               => [Windows]C:\xampp\mysql\bin\my.ini
               => [xampp] click on mysql -> config then open my.ini file
Step 2: Search [mysqld] in my.ini file
Step 3: Add this lower_case_table_names=2
Step 4: save the file and restart MySQL service or (Xampp)
You can now create SQL Tables in case sensitive format.


text:
Q: Android : Retrofit and using dynamic URLS Good morning.  I am pretty new to Retrofit, taking on the project from another.  We need to talk to a API that uses a code in the url for each call
E.g http://www.example.com/CODE/review
I thought I would try the obvious but Retrofit is complaining about Attribute value must be a constant
public interface ApiService{
        public static final String ref = getRefCode();

        //TODO: Use ref number to identify users
        @Headers({
                "Accept: application/json",
                "Content-Type: application/json"})
        @GET("/" + ref + "/RepairStatus")
        void getRepairStatus(@Header("If-None-Match") String ifNoneMatch, RestCallback<RepairStatusResponse> callback);

        @Headers({
                "Accept: application/json",
                "Content-Type: application/json"})
        @POST("/" + ref + "/Review")
        void postReview(@Body ReviewRequest reviewRequest);

    }

Sorry if I am missing the obvious :)

A: Don't you do something like this:
@GET("/group/{id}/users") List<User> groupList(@Path("id") int groupId);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python pandas function to create new dfs in a loop I have a df including every match of Premier League 2019/2020 season. I want to make a function which create a new df, including all home matches of one club. Df looks like that.
HomeTeam:    AwayTeam:    Winner:
Liverpool    Brighton    Liverpool
Chelsea      Watford     Chelsea
Brighton     Liverpool   Liverpool

Function I have made:
'''Function to create df of home games of every team
    c = Club name'''

def team_home_df(c):
    return data[(data['HomeTeam'] == c)]

Then to assign it to a variable, I need to do it like that:
liverpool_home_df = team_home_df('Liverpool')

I would like to ask you, how to make it in a loop, to get every team's df with name standard "Team_home_df"?
I have got all team names in array.
teams = []
clubs = data['HomeTeam'].unique()
teams.append(clubs)
#check the list
print(teams)

Output
[array(['Liverpool', 'WestHam', 'Bournemouth', 'Burnley', 'CrystalPalace',
       'Watford', 'Tottenham', 'Leicester', 'Newcastle', 'ManUnited',
       'Arsenal', 'AstonVilla', 'Brighton', 'Everton', 'Norwich',
       'Southampton', 'ManCity', 'SheffieldUnited', 'Chelsea', 'Wolves'],
      dtype=object)]


text:
Q: C# How to instantiate inherited objects via a static method? I'm currently working on an isometric tile-based game. Currently, I have a grid with tiles and those objects contain data about their position, type and various objects(like trees) that can be placed on top of them.
I created an abstract TileObject class and there is another class called Tree which inherites from TileObject. My goal is to have a static function which is responsible for creating these TileObjects without using constructor.
I've tried this with Generics too (even using the Activator class) but didn't seem to work.
My thoughts would be generics, system.type, typeof but I'm unable to put these all together.
public abstract class TileObject
{
    protected TileObject() { }

    public Tile Parent { get; set; }
    public string ObjectType { get; set; }

    public static TileObject CreateObject(string objName, Tile parent)
    {

    }
}

public class Tree : TileObject
{

}

This solution could work in my opinion but it seems so hardcoded
public static TileObject CreateObject(string objName, Tile parent)
{
    TileObject x;
    if(objName == "Tree")
        x = new Tree();
    else if(objName == "Chair")
        ...
}

A: One solution could be generics !
Here is an example :

public static TileObject CreateObject<T>(Tile parent) where T : TileObject, new()
{
    TileObject x = new T();
}

Take a look at where T : TileObject, new()
What it means is your type T will be a TileObject, so you don't even have to take care of the type.


text:
Q: Correct way to add attachment to email in magento 2.3.3+ From the release of new version of magento 2 come with some changes in code base
I can't add attachment to email anymore. My case used new TransportBuilder class extend from origin

Magento\Framework\Mail\Template\TransportBuilder

for send email
I have searched some tutorials or guide in google but seem all of them outdates now
Is there any best way to add attachment without impact other function ? No override approach allowed here

A: Found this official answer from magento here
https://community.magento.com/t5/Magento-DevBlog/Backward-incompatible-Changes-in-the-
Mail-Library-for-Magento-2/ba-p/144787


text:
Q: how to merge two files to skip duplicate data I have two different large files (each one more than 300,000 lines) and I want to combine them in a specific way. Some rows of the two data measure the same thing; when columns 9, 14, 15, 16, 17 are reciprocally equal, I suppose they are measuring the same thing and I want to output from file1 and skip the file2 rows in order to skip duplicate data. Otherwise, I want to output all rows from both files. The other columns in the duplicate rows may not be equal reciprocally, and the precision of file 1 is better than file 2, and that is the reason for choosing rows from file1 rather than file 2.
For example, since columns 9, 14, 15, 16, and 17 of the three first lines of the two following files are reciprocally equal, so the first three lines of the two datasets measure the same thing and thus I want to output from File 1 and skip the File2 data. For the fourth lines of the datasets, since columns 14 of the two files are not reciprocally equal. I output both lines from two files.
I used this script
awk '!seen[$9,$14,$15,$16,$17]++' File1 File2 > output

, which works well for small data. However, when I use it for large data sets, it skips some not duplicate data and I dont know the reason. It is deeply appreciated if anyone could help which script I can use for merging the datasets.
File1
28  208   48  198  1110   2.04   33 0.0   34.40 3.3 0.0 0   8.0 1985  1  1 SMO1   -9 -9 -9
24  102   26   99  2100   2.61  129 0.0   42.90 3.3 0.0 0   8.0 1985  1  1 EYA    -9 -9 -9
89  294   26  106  1162   4.54 -115 0.0   70.80 3.3 0.0 0   8.0 1985  1  1 GYA    -9 -9 -9
38   88   41   86  1100   3.50  155 0.0   56.30 3.8 0.0 0  10.0 1985  1  1 KOL1   -9 -9 -9

File2
24  102   22  100  1110   2.04   33 0.0   34.40 3.3 0.0 0   8.0 1985  1  1 SMO1   -9 -9 -9
24  102   26   99  2100   2.61  129 0.0   42.90 3.3 0.0 0   8.0 1985  1  1 EYA    -9 -9 -9
24  102   26  106  1162   4.54 -115 0.0   70.80 3.3 0.0 0   8.0 1985  1  1 GYA    -9 -9 -9
38   88   41   86  1100   3.50  155 0.0   56.30 3.8 0.0 0  10.0 2000  1  1 KOL1   -9 -9 -9

output
28  208   48  198  1110   2.04   33 0.0   34.40 3.3 0.0 0   8.0 1985  1  1 SMO1   -9 -9 -9
24  102   26   99  2100   2.61  129 0.0   42.90 3.3 0.0 0   8.0 1985  1  1 EYA    -9 -9 -9
89  294   26  106  1162   4.54 -115 0.0   70.80 3.3 0.0 0   8.0 1985  1  1 GYA    -9 -9 -9
38   88   41   86  1100   3.50  155 0.0   56.30 3.8 0.0 0  10.0 1985  1  1 KOL1   -9 -9 -9
38   88   41   86  1100   3.50  155 0.0   56.30 3.8 0.0 0  10.0 2000  1  1 KOL1   -9 -9 -9


text:
Q: Under-clocking an 10gb Ethernet SFP+ module The Xilinx device on the Picozed board is a version of the Zynq 7030. The 7030 in general has a GTX transceiver, which in principle is rated to 12.5Gb/s SERDES with the relevant line coding for 10gig Ethernet.
Unfortunately, the specific chip on the Picozed has its GTX transceiver down rated to a reduced 6.6Gb/s.
Is it possible to use a reduced line rate with off the shelf 10gig Ethernet networking hardware (modules and switches)?
Without knowing enough about the precise tech, at first glance, I can't see a problem in principle with the TX side since it would result in a reduced implicit clock frequency. On the RX side it seems more problematic: the other end would need to either realise or be told to transmit at a reduced rate.
Is this something that can be made to work?

A: A lot of the simpler SFP+ transceivers (direct attach copper cable, short-reach optical fiber) are really little more than analog devices and wouldn't care about the clock (fun fact: friends of mine use SFP optical transmitters to simply distribute a 10 MHz clock, and it works).
None of the stock networking hardware would be prepaed for a 50% rate mismatch, and I'd doubt their PLLs would lock reliably.
So, while point-to-point between devices using relatively dumb SFP+ transceivers might work with arbitrary clocks, I'd not expect functionality with stock networking hardware. It's more likely that you can convince your Zynq's transmitter to work at the full rate than that...
I don't know whether that's viable on your board, but maybe you could use the PCIe endpoints to have 2 or 4 lanes to a 10 GigE network card.

A: While the SFP+ modules themselves might work at a lower rate (and if they don't contain CDRs, then there should be no issues with running at pretty much whatever rate you like), whatever is at the other end generally expects the data rate to be within something like +/- 200 ppm or so.  If it's outside of this range, the link will not come up.  Also, bear in mind that the recovered RX clock is hardly ever re-used for TX, so your receiver would still have to work at 10G.  Most CDR circuits these days don't even use PLLs in the loop, they generate a half rate clock and then use phase interpolators, this way one PLL can be shared across several TX and RX channels.  And then in many cases the RX data is synchronized back into the TX clock domain with an elastic buffer, so even if the RX channel did lock onto the data, the elastic buffer would either overflow or underflow continuously and the link would be unusable.


text:
Q: How to properly include the same .h file in two separate .cpp files? I have a project consisting of 6 files; main.cpp, functions.h, tennisplayer.h, tennisplayer.cpp, tennisteam.h & tennisteam.cpp which are roughly defined as follows:
// main.cpp

#include "tennisteam.h"
#include <iostream>
#include <string>
#include <exception>

// some main() code that needs functions.h definitions

// functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include "tennisplayer.h"
#include <iostream>
#include <string>
#include <limits>

// some constants & function definitions needed by both main.cpp & tennisteam.cpp

#endif

// tennisplayer.h

#ifndef TENNISPLAYER_H
#define TENNISPLAYER_H

#include <string>
#include <vector>

// tennisplayer class declarations

#endif

// tennisplayer.cpp

#include "tennisplayer.h"
#include <iostream>
#include <fstream>

// tennisplayer class definitions

// tennisteam.h

#ifndef TENNISTEAM_H
#define TENNISTEAM_H

#include "tennisplayer.h"
#include <string>
#include <vector>

//

#endif

// tennisteam.cpp

#include "tennisteam.h"
#include <iostream>
#include <fstream>

// tennisteam class definitions

However, when I include functions.h into both main.cpp & tennisteam.cpp via tennisteam.h I get a linker error along the lines of:
/usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: /tmp/ccv30cX0.o:tennisteam.cpp:(.text+0x0): multiple definition of `function(std::string const&)'; /tmp/ccRThgpp.o:main.cpp:(.text+0x0): first defined here

I'm aware this is a linker error. I've looked around for a fix but all I come across are posts instructing me to use include guards which I have done already. Is there something I'm missing here? Any help would be appreciated.

A: You have function function(std::string const&) that you not only declared but also defined in your header file. If you need to have it defined there instead of a .cpp file, mark it as inline.
This results in two cpp files (namely main.cpp and tennisteam.cpp) ending up with a definition of that function, because they both include that header file.


text:
Q: Removing information from Tuples I know tupules can't be edited but I'm planning on creating a new one. I'm importing information from a file and then cutting out the first name, last name, and year of birth. I just don't know how to edit it so I can cut out everything past the comma to get each element. Sorry if this is confusing!
Here's my code!
#Open file for employee information
employee_info_file=open('employees.txt','r')

#Loop for all employees
for line in employee_info_file:
    #Read info and convert to tupule
    employee_info=employee_info_file.readline()
    employee_tupule=(employee_info)

    #Designate first name, last name, and year born
    first_name=
    last_name=
    year_born=

employee_tupule prints like this
Mark,Acrobello,8/12/1988

But each line has a different length for first name, last name, and DOB. lease help! thanks!

A: I hope I understood you correctly..
you are reading a file and in each line, there is an employee with some data in this format: "Mark,Acrobello,8/12/1988" and you want to have a tuple that has 3 elements, name, last name, and the date.
you can achieve that by using the split method on the string:
employee_tuple = tuple("Mark,Acrobello,8/12/1988".split(","))
print(employee_tople)

prints:
('Mark', 'Acrobello', '8/12/1988')


text:
Q: Touchevents not firing on IOS Safari in React custom carousel component after first swipe I created a custom photo carousel component in React (because external libraries were either too hard to work with or did not do the things that I wanted it to do), where you can swipe to the next/previous photo on mobile. Everything works fine on Android, but it's just IOS Safari.
The Problem
I have a page that maps out several carousels. The first carousel in the map works perfectly fine. Subsequent carousels will swipe correctly AFTER the first slide, but once it transitions to the second slide, the touch events stop firing, and it will not swipe. What I want is all the carousels like the first carousel. No error messages seen either. See video:
Code
Here is the custom component:
import { useState, useEffect } from 'react'

const Carousel = ({ children }) => {
  const IMG_WIDTH = 400

  const [currentIndex, setCurrentIndex] = useState(0)
  const [lastTouch, setLastTouch] = useState(0)
  const [movement, setMovement] = useState(0)
  const [transitionDuration, setTransitionDuration] = useState('')
  const [transitionTimeout, setTransitionTimeout] = useState(null)
  const maxLength = children.length - 1,
    maxMovement = maxLength * IMG_WIDTH

  useEffect(() => {
    return () => {
      clearTimeout(transitionTimeout)
    }
  }, [])

  const transitionTo = (index, duration) => {
    setCurrentIndex(index)
    setMovement(index * IMG_WIDTH)
    setTransitionDuration(`${duration}s`)

    setTransitionTimeout(
      setTimeout(() => {
        setTransitionDuration('0s')
      }, duration * 100))
  }

  const handleMovementEnd = () => {
    const endPosition = movement / IMG_WIDTH
    const endPartial = endPosition % 1
    const endingIndex = endPosition - endPartial
    const deltaInteger = endingIndex - currentIndex

    let nextIndex = endingIndex

    if (deltaInteger >= 0) {
      if (endPartial >= 0.1) {
        nextIndex++
      }
    } else if (deltaInteger < 0) {
      nextIndex = currentIndex - Math.abs(deltaInteger)
      if (endPartial > 0.9) {
        nextIndex++
      }
    }

    transitionTo(nextIndex, Math.min(0.5, 1 - Math.abs(endPartial)))
  }

  const handleMovement = delta => {
    clearTimeout(transitionTimeout)

    const maxLength = children.length - 1
    let nextMovement = movement + delta

    if (nextMovement < 0) {
      nextMovement = 0
    }

    if (nextMovement > maxLength * IMG_WIDTH) {
      nextMovement = maxLength * IMG_WIDTH
    }
    setMovement(nextMovement)
    setTransitionDuration('0s')
  }

  const handleTouchStart = event => {
    setLastTouch(event.nativeEvent.touches[0].clientX)
  }

  const handleTouchMove = event => {
    const delta = lastTouch - event.nativeEvent.touches[0].clientX
    setLastTouch(event.nativeEvent.touches[0].clientX)
    handleMovement(delta)
  }

  const handleTouchEnd = () => {
    handleMovementEnd()
    setLastTouch(0)
  }

  return (

      <div
        className="swiper"
        style={{
          transform: `translateX(${movement * -1}px)`,
          transitionDuration: transitionDuration
        }}>
        {children} // This is just  tags

        {[...Array(children.length)].map((bullet, index) => (
          <div key={`bullet-${index}`} className={`dot ${currentIndex === index && 'red-dot'}`} />
        ))}

  )
}

export default Carousel

And here is the part of my code where I am using the custom component:
return (
    <>
      <Announcement />

        <Title />
        {Component} // This is just a component that simply maps out the Carousel, nothing special and no extra styling

      ...
    </>
  )

And CSS:
.main {
    overflow: hidden;
    position: relative;
    touch-action: pan-y;
}

.swiper {
    display: flex;
    overflow-x: visible;
    transition-property: transform;
    will-change: transform;
}

What I know/tried

*

*Removing some of the components above the Carousel (eg. Title, Announcement, etc.) makes part of the slides other than the first slide swipable. It can be half of the height of the slide or 1/3 of the height that is swipable, depending on how much I remove. This excludes the first carousel, that one still works perfectly fine

*I've tried removing a bunch of CSS, didn't work

*Tried adding event listeners to the 'main' div, maybe I did something wrong but swiping one carousel ends up swiping all the carousels

*Thought it had something to do with the touch event handler functions I created in my custom carousel component, but it seems like they work fine, because after changing them to console.logs and manually translating the slides, the touch events are still not firing.

Update #1
I put the touch event handlers in a new div that wraps {child}. The second slide is swipeable now but the third slide is still a bust.
References
This is the tutorial link I followed to create the carousel for more context to the custom carousel component.

A: After days and hours, the solution is kind of odd. I'm guessing you need to set the target correctly to the element's div id. I put this in the useEffect, so the result looks like this:
useEffect(() => {
    document.getElementById(id).addEventListener('touchstart', () => false, { passive: false })

    return () => {
      clearTimeout(transitionTimeout)
    }
  }, [])

NOTE that the id MUST be unique especially if creating a map of the same component like what I did. Otherwise, swiping one carousel will swipe all carousels.


text:
Q: Azure Functions "Could not load assembly" when running in live environment My function app has a project reference: MyFA.csproj --> MyLibrary.csproj. When I build, MyLibrary.dll is in bin folder as expected. But when I test in the live environment I get Could not load assembly MyLibrary error. I went to Process Explorer in Kudu and searched for MyLibrary and found the dll sitting at
w3wp.exe:5328 -> C:\DWASFiles\Sites\mawsFnPlaceholder51_v1\Temporary ASP.NET Files\root\26c08606\ff1fbe16\assembly\dl3\05ad04a1\e5a46c4a_273ad401\MyLibrary.DLL

but somehow it's not loading when I need it.
Any idea why this is?


text:
Q: Hebrew send to google spreadsheet from PowerShell Hebrew correctly Please help.
In console look hebrew correct but in spreadsheet is not correctenter image description here
    $import = New-Object System.Collections.ArrayList($null)
$import.Add( @("route_id"))
$import.Add( @( 'אבא אבן 1 הרצליה' ))  | Out-NULL

try {

   $Response = Set-GSheetData -accessToken $accessToken -rangeA1 "A1:X$($import.Count)" -sheetName "23-07-21" -spreadSheetID $SpreadsheetID -values $import -Verbose
   $Response | ConvertTo-Json

} catch {
    $err = $_.Exception
    $err | Select-Object -Property *
    "Response: "
    $err.Response
    }

A: Hebrew might not be supported in Sheets, you would need to install a font. You can try with this one
https://fonts.google.com/noto/specimen/Noto+Sans+Hebrew?query=hebrew
Update
After testing using the Rest API, it works, so the issue might be related on how the PowerShell process hebrew characters.
I've found some information on how to process hebrew characters in the Windows Powershell
[Console]::OutputEncoding = [Text.Encoding]::GetEncoding(1255)

Make sure the console is outputting the right characters and the POST a request to Google Sheets

A: It's bug in the psmodule. Author must specify encoding UTF8.
https://github.com/umn-microsoft-automation/UMN-Google/pull/50


text:
Q: Javascript - Converting between Unicode string and ArrayBuffer Does somebody know a script that is able to convert a string to a ArrayBuffer using unicode encoding?
I´m creating a browser-side eqivalent of the "Buffer" of node.js. The only encoding that is left is unicode. All others are done.
Thanks for your help!

A: I found it out by myself.
Decoding:
var b = new Uint8Array(str.length*2);
for(var i = 0; i < b.length; i+=2){
    var x = str.charCodeAt(i/2);
    var a = x%256;
    x -= a;
    x /= 256;
    b[i] = x;
    b[i+1] = a;
}

Encoding
var s = "";
for(var i = 0; i < this.length;){
    s += String.fromCharCode(this[i++]*256+this[i++]);
}


text:
Q: WPF Custom ICommand implementation and the CanExecuteChanged event in my WPF UI, I use RoutedCommands that I refer to in my xaml via the following code:
Command="viewModel:MessageListViewModel.DeleteMessagesCommand"

I don't like this static link to my ViewModel class,I think this is not as nice as creating a custom ICommand implementation and use a syntax like the following
Command="{Binding DeleteMessagesCommand}"

Having created one, I notice one major drawback of what I've done: RoutedCommands utilize the CommandManager and (in some way that is completely opaque to me) fire the CommandManager.RequerySuggested event, so that their CanExecute Method is requeried automatically. As for my custom implementation, CanExecute is only fired once at startup and never again after that.
Does anybody have an elegant solution for this?

A: Just implement the CanExecuteChanged event as follows:
public event EventHandler CanExecuteChanged
{
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
}

When you assign the command to a control, it subscribes to the CanExecuteChanged event. If you "redirect" it to the CommandManager.RequerySuggested event, the control will be notified whenever CommandManager.RequerySuggested is triggered.

A: I very much prefer the DelegateCommand implementation of Prism for viewmodel binding (http://msdn.microsoft.com/en-us/library/ff654132.aspx). You can invoke CanExecute() on every command invoker by calling RaiseCanExecuteChanged on it.
Simple usage example:
public class ViewModel
{
   public ViewModel()
   {
      Command = new DelegateCommand<object>(x => CommandAction(), x => CanCommandAction());
   }

   bool state;

   public void ChangeState(bool value)
   {
      state = value;
      Command.RaiseCanExecuteChanged();
   }

   public DelegateCommand<object> Command {get; private set;}

   private void CommandAction()
   {
      //do smthn
   }

   private bool CanCommandAction() { return true == state; }
}

//and binding as usual
Command="{Binding Command}"


text:
Q: Getting 'Invoke-Sqlcmd' is not recognized as the name of a cmdlet when running powershell scripts in scheduled task as a not administrator Why do i get

'Invoke-Sqlcmd' is not recognized as the name of a cmdlet when running powershell scripts as a scheduled task as a not administrator.

if I add Import-Module "sqlps" -DisableNameChecking to the script it?


text:
Q: Polar coordinates for a triangle-shaped domain. I have to integrate the function $f(x,y)=\displaystyle\frac{x^2}{x^2+y^2}$ and the domain is given by the triangle determined by the points $(0,0)$, $(1,-1)$ and $(1,1)$.
Would polar coordinates be a good change of variables?. I tried with this first because the integral would be simplified to $\displaystyle\int\displaystyle\int\displaystyle\frac{r^2\cos^2\theta}{r^2\cos^2\theta+r^2\sin^2\theta}r\;drd\theta=\displaystyle\int\displaystyle\int r\cos^2\theta\;drd\theta$ that seems a lot handier.
But what would be the limits of integration if I'm working with polar coordinates?.
The plan so far would be work with the upper triangle determined by the points $(0,0);(1,0);(1,1)$ first and then work with the other one. Then I have $0\leq\theta\leq\pi/4$ but how could I determine de limits of $r$?. Seems that $r$ is given by a function of $\theta$ that I have some issues to find; looking at some trigonometric values an appropriate approach may be given by the definition $r(\theta)=2\sin\theta$ so that $r(0)=0$ and $r(\pi/4) = \sqrt{2}$ but this correct?.
Also, since it works reversed for the lower triangle -determined by $(0,0);(1,0);(1,-1)$- should I set the limits reversed for the integral?
This is, if for the upper triangle I have $\int_0^{\pi/4}\int_{1}^{2\sin(\theta)}\small p(r,\theta)r \operatorname{dr}\operatorname{d\theta}$ then for the lower one I would work with $\int_{\color{red}{-\pi/4}}^{\color{red} 0}\int_{2\sin(\theta}^{1}\small p(r,\theta)r \operatorname{dr}\operatorname{d\theta}$ ?
Am I proceeding correctly?, maybe there is a better change of variables?
EDIT: I changed the limits of the last integral, the former one $\left(\int_0^{\pi/4}\right)$ was going through the upper triangle again...

A: The polar-coordinate change probably is a good choice, yes. The problem is to express $r$, along the vertical edge, as a function of $\theta$. That vertical edge consists of points where $x = 1$, i.e., where $r \cos \theta  = 1$. So $r$ can be expressed as $1 / \cos(\theta)$. That means that your integral becomes
$$
\int_{\theta = -\pi/4}^{\pi/4} \int_{r = 0}^{1/\cos(\theta)} r \cos^2 \theta dr~d\theta
$$
I don't know whether that integral works out nicely or not .... but it looks as if it does,  and I'll leave it to you to do the actual integration.

A: If you consider the triangle with vertices $(0,0)$ , $(1,-1)$ and $(1,1)$, then the side with vertices $(1,-1)$ and $(1,1)$ is the locus of points
$$z=r e^{i\theta}$$
s.t. $\operatorname{Re}(z)\stackrel{!}{=}1$, i.e. $r\cos\theta=1\Leftrightarrow r(\theta)=\frac{1}{\cos\theta}$, with $\theta\in[-\frac{\pi}{4},\frac{\pi}{4}]$.
If you consider the triangle with vertices $(0,0)$ , $(1,0)$ and $(1,1)$ you follow the same lines, with $\theta\in [0,\frac{\pi}{4}]$.


text:
Q: Get class from options in slect2.js tags I am using select2.js library with following code, I would like to have all classes from options tag to the select2 list, something like <li class="active select2-selection__choice" title="AA"><span ...
<select id="example" multiple="multiple" style="width:100%">
<option value="AA" class="active" selected>AA</option>
<option value="BB" class="stanby" selected>BB</option>
<option value="CC"class="active" selected>CC</option>

$("#example").select2();

Here is the fiddle to work with.

A: This can be achieved by providing a custom selectionAdapter option. I created one based on Select2 implementation of MultipleSelection.
// create our custom selection adapter by extending the select2 default one
$.fn.select2.amd.define('select2-ClassPreservingMultipleSelection',[
    'jquery',
    'select2/selection/multiple',
    'select2/utils'
], function ($, MultipleSelection, Utils) {
    function ClassPreservingMultipleSelection ($element, options) {
        ClassPreservingMultipleSelection.__super__.constructor.apply(this, arguments);
    }

    Utils.Extend(ClassPreservingMultipleSelection, MultipleSelection);

    // this function was changed to propagate the `selection` argument
    ClassPreservingMultipleSelection.prototype.selectionContainer = function (selection) {
        var $baseContainer = ClassPreservingMultipleSelection.__super__.selectionContainer.apply(this, arguments);

        // this line is what actually adds your CSS-classes
        return $baseContainer.addClass(selection.element.className);
    };

    // this is a copy-paste of the base method with only one line changed
    ClassPreservingMultipleSelection.prototype.update = function (data) {
        this.clear();

        if (data.length === 0) {
            return;
        }

        var $selections = [];

        for (var d = 0; d < data.length; d++) {
            var selection = data[d];

            // This is the only changed line in this method - we added the 'selection' propagation
            var $selection = this.selectionContainer(selection);
            var formatted = this.display(selection, $selection);

            $selection.append(formatted);
            $selection.prop('title', selection.title || selection.text);

            $selection.data('data', selection);

            $selections.push($selection);
        }

        var $rendered = this.$selection.find('.select2-selection__rendered');

        Utils.appendMany($rendered, $selections);
        console.log($rendered.html());
    };

    return ClassPreservingMultipleSelection;
});

$("#example").select2({
    selectionAdapter: $.fn.select2.amd.require('select2-ClassPreservingMultipleSelection')
});

Here's an updated JsFiddle for you.


text:
Q: How can I get bitmap using glide in onCreate? I'm using MVVM model. So what I have to do is first, getting datas containing URLs and others from retrofit.
Second is getting images from URLs and notifying Viewpager after first process.
I did the first. but when I try the second process, the error occurred

java.lang.IllegalArgumentException: You must call this method on a
  background thread

I referred this site http://bumptech.github.io/glide/doc/getting-started.html#background-threads
to use glide on background thread.
I don't have to use Asynctask in observe that is my constraint to develop. How can I solve the second process?
 detailViewModel.getIndexItem().observe(this, Observer<DetailModel>(){
                t->

            binding.item = t

            image_list = binding.item.thumbnail_list_320.toString().split("#")
            for(image in image_list) {
                val futureTarget: FutureTarget<Bitmap> = Glide.with(context)
                    .asBitmap()
                    .load(image)
                    .submit(500, 500)

                val bitmap = futureTarget.get()
                bitmaps.add(bitmap).apply {
                    if(this){
                        viewPagerAdapter.notifyDataSetChanged()
                        transitionLayout.visibility=View.GONE
                        detailLayout.visibility=View.VISIBLE
                    }
                }
            }
        })

A: If you want to get bitmap on UI Thread, implement as below, You can try
detailViewModel.getIndexItem().observe(this, Observer<DetailModel>(){
            t->

        binding.item = t

        image_list = binding.item.thumbnail_list_320.toString().split("#")
        for(image in image_list) {
            Glide.with(this)
                .asBitmap()
                .override(500, 500)
                .load("image url")
                .into( object: CustomTarget<Bitmap>() {
                    override fun onResourceReady(
                        bitmap: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        // UI Thread
                        Log.e(TAG, "$bitmap")
                        bitmaps.add(bitmap).apply {
                            if(this){
                                viewPagerAdapter.notifyDataSetChanged()
                                transitionLayout.visibility=View.GONE
                                detailLayout.visibility=View.VISIBLE
                            }
                        }
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {

                    }

                })

        }
    })

A: Simple and elegant in java:
Bitmap bitmap;
Glide.with(mContext).load(PHOTOURL).apply(options).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                 bitmap = resource;
                }
            }).into(IMAGEVIEW);

with implementation 'com.github.bumptech.glide:glide:4.10.0'. Note that, it is asynchronous and takes some time to load bitmap. I hope it helps. Best regards.


text:
Q: Generic map as function argument I wrote a method:
fn foo(input: HashMap<String, Vec<String>>) {...}

I then realized that for the purpose of writing tests, I'd like to have control of the iteration order (maybe a BTreeMap or LinkedHashMap). This led to two questions:

*

*Is there some trait or combination of traits I could use that would essentially express "a map of string to string-vector"? I didn't see anything promising in the docs for HashMap.

*It turns out that in this method, I just want to iterate over the map entries, and then the items in each string vector, but couldn't figure out the right syntax for specifying this. What's the correct way to write this?
fn foo(input: IntoIterator<(String, IntoIterator<String>)>) {...}

A: There are not traits that define a common interface for containers. The only trait that maybe is suited for your is the Index trait.
See below for a working example of the correct syntax for IntoIterator and the Index traits. You need to use references if you don't want consume the input, so be careful with lifetime parameters.
use std::ops::Index;
use std::iter::IntoIterator;
use std::collections::HashMap;

// this consume the input
fn foo<I: IntoIterator<Item = (String, String)>>(input: I) {
    let mut c = 0;
    for _ in input {
        c += 1;
    }
    println!("{}", c);
}

// maybe you want this
fn foo_ref<'a, I: IntoIterator<Item = (&'a String, &'a String)>>(input: I) {
    let mut c = 0;
    for _ in input {
        c += 1;
    }
    println!("{}", c);
}

fn get<'a, I: Index<&'a String, Output = String>>(table: &I, k: &'a String) {
    println!("{}", table[k]);
}

fn main() {
    let mut h = HashMap::<String, String>::new();
    h.insert("one".to_owned(), "1".to_owned());
    h.insert("two".to_owned(), "2".to_owned());
    h.insert("three".to_owned(), "3".to_owned());

    foo_ref(&h);
    get(&h, &"two".to_owned());
}

Edit
I changed the value type to everything implements the IntoIterator trait :
use std::ops::Index;
use std::iter::IntoIterator;
use std::collections::HashMap;
use std::collections::LinkedList;

fn foo_ref<'a, B, I, >(input: I)
    where B : IntoIterator<Item = String>, I: IntoIterator<Item = (&'a String, &'a B)> {
    //
}

fn get<'a, B, I>(table: &I, k: &'a String)
    where B : IntoIterator<Item = String>, I: Index<&'a String, Output = B>
{
    // do something with table[k];
}

fn main() {
    let mut h1 = HashMap::<String, Vec<String>>::new();
    let mut h2 = HashMap::<String, LinkedList<String>>::new();

    foo_ref(&h1);
    get(&h1, &"two".to_owned());

    foo_ref(&h2);
    get(&h2, &"two".to_owned());
}

A: There's no such trait to describe an abstract HashMap. I believe there's no plan to make one. The best answer so far is your #2 suggestion: for a read-only HashMap you probably just want something to iterate on.
To answer at the syntax level, you tried to write:
fn foo(input: IntoIterator<(String, IntoIterator<String>)>)

But this is not valid because IntoIterator takes no template argument:
pub trait IntoIterator where Self::IntoIter::Item == Self::Item {
    type Item;
    type IntoIter: Iterator;
    fn into_iter(self) -> Self::IntoIter;
}

It takes two associated types, however, so what you really wanted to express is probably the following (internally I changed the nested IntoIterator to a concrete type like Vec for simplicity):
fn foo<I>(input: I)
where I: IntoIterator<
             Item=(String, Vec<String>),
             IntoIter=IntoIter<String, Vec<String>>>

However the choice if IntoIterator is not always suitable because it implies a transfer of ownership. If you just wanted to borrow the HashMap for read-only purposes, you'd be probably better with the standard iterator trait of a HashMap, Iterator<Item=(&'a String, &'a Vec<String>)>.
fn foo_iter<'a, I>(input: I)
where I: Iterator<Item=(&'a String, &'a Vec<String>)>

Which you can use several times by asking for a new iterator, unlike the first version.
let mut h = HashMap::new();
h.insert("The Beatles".to_string(),
    vec!["Come Together".to_string(),
         "Twist And Shout".to_string()]);
h.insert("The Rolling Stones".to_string(),
    vec!["Paint It Black".to_string(),
         "Satisfaction".to_string()]);
foo_iter(h.iter());
foo_iter(h.iter());
foo(h);
//foo(h); <-- error: use of moved value: `h`

Full gist
EDIT
As asked in comments, here is the version of foo for nested IntoIterators instead of the simpler Vec:
fn foo<I, IVecString>(input: I)
where
I: IntoIterator<
    Item=(String, IVecString),
    IntoIter=std::collections::hash_map::IntoIter<String, IVecString>>,
IVecString: IntoIterator<
    Item=String,
    IntoIter=std::vec::IntoIter<String>>


text:
Q: VBA: Creating a Pivot Table with long caracters I am trying to create a simple pivot table with the following code:
Dim rngA As Range
Dim rngB As Range
Set rngA = Sheets("Sheet1").Range("C4:G10")
Set rngB = Sheets("Sheet2").Range("Q2")

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngA, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:=rngB, TableName:="My_Pivot_Table", DefaultVersion:=xlPivotTableVersion14

My data countains lines of text which are really long (up to 900 caracters), => this is the reason why my VBA Code can not create the table. With shorter text or with the Macro recorder it works.
I am getting 2 different errors:

*

*If I exchange ".Create" for ".Add" I get: "Compile error : Named argument not found" on the word "Version" in the last line of code.

*with .create I get "type Mismatch",

and it seems different from the other questions I found on Stackoverflow.
Any idea how to fix it?
EDIT:
The Code works if I exchange
SourceData:=rngA

with
SourceData:="Sheet1!R4C3:R10C7"

A: PivotCaches.Add does not take Version as an argument
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.pivotcaches.add.aspx
So if you remove that, you are left with: (Which compiles)
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase,
SourceData:=rngA).CreatePivotTable TableDestination:=rngB,
TableName:="My_Pivot_Table", DefaultVersion:=xlPivotTableVersion14

However, I think the correct code is more like this:
Dim rngA As Range
Dim rngB As Range

Set rngA = Sheets("Sheet1").Range("G4:G10")
Set rngB = Sheets("Sheet2").Range("Q2")

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngA,
                 Version:=6).CreatePivotTable TableDestination:= rngB,
                     TableName:="My_Table", DefaultVersion:=6


text:
Q: How to create Multi-metric Alarm? There are multiple instances with servicename-N running & i am able to push custom metric using python sdk to Namespace-X. However when i create alarm it only let me select One metric from one of the instances. i have tried Metric Math based alarm but the email notification doesnt include detail information(serviceName, instanceID).
Any pointers to achieve this(eg. have meta data like serviceName in notification email) ?
scenario image

A: You can achieve this by creating a Metric Insights alarm (https://aws.amazon.com/about-aws/whats-new/2022/12/amazon-cloudwatch-metrics-insights-alarms/).

Amazon CloudWatch Metrics Insights alarms enables customers to alarm on entire fleets of dynamically changing resources with a single alarm using standard SQL queries...With Metric Insights alarms you can set alarms using Metric Insight queries that monitor multiple resources without having to worry if the resources are short lived or not. For example, you can set a single alarm that alerts when any of your EC2 instances reaches a high threshold for CPU utilization and the alarm will evaluate new instances that are launched afterwards.

Alternatively, you can create an alarm for each individual time series and then create a composite alarm that groups the individual alarms. You can then put your action on the composite alarm. https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_Composite_Alarm.html


text:
Q: Headless unit testing for WebView2 I'm writing unit tests for a class that wraps the WebView2 browser control (WPF version if it matters).
Is there a way to run WebView2 in the equivalent of a headless mode so I don't have to actually load a window in order to test it? I've tried passing --headless in as an additional browser argument but EnsureCoreWebView2Async still spins forever so I assume it's one of the ignored arguments.


text:
Q: Resultant of two polynomials in $K[X,Y]$ is a polynomial in $K[X]$ with degree less than the product of the original ones I'm trying to prove the following:
Let $f, g$ be two polynomials in $K[X,Y]$ with $K$ a field and consider them as polynomials in one indeterminate with coefficientes in$ K[X]$, ie, as elements of $K[X][Y]$, then the resultant of these two polynomials would be another polynomial $d \in K[X]$ and I want to show that $\operatorname{deg}(d) \leq \operatorname{deg}(f)\operatorname{deg}(g)$.
I found it in a textbook on algebraic geometry as part of some proof but there is no hint or reference on how to prove it and I have no idea on how to get the result.
Could someone give a proof about this result?
Thanks a lot.

A: Expand $f$ and $g$ as polynomials in $y$ as follows:
$$f= a_0y^d+a_1y^{d-1}+\cdots+a_d$$
$$g= b_0y^e+b_1y^{e-1}+\cdots+b_e.$$
Then the resultant of these two polynomials is given by the determinant of the Sylvester matrix. Here's an example when $f$ has degree three in $y$ and $g$ has degree two in $y$:
$$S=
\begin{pmatrix} a_0 & & b_0 & & \\
 a_1 & a_0 & b_1 & b_0 & \\
 a_2 & a_1 & b_2 & b_1 & b_0 \\
 a_3 & a_2 & & b_2 & b_1 \\
 & a_3 & & & b_2 \end{pmatrix}$$
Now recall that $\renewcommand{\s}{\sigma}\det S = \sum_{\s\in S_{d+e}} |\s|\prod s_{i\s(i)}$. I claim that when $s_{ij}\neq 0$, $\deg_x s_{ij} \leq \deg(f)-d+i-j$ or $\deg_x s_{ij} \leq \deg(g)-e+i-j+e=\deg(g)+i-j$ depending on whether $j\leq e$ or not. Therefore $$\deg_x \prod s_{i\s(i)} \leq e(\deg(f)-d)+d(\deg(g)) + \sum i-\s(i).$$ As $\sum i-\s(i) =0$ and $e(\deg(f)-d) + d(\deg(g)) \leq \deg(f)\deg(g)$, we have the result.

A: Here is an example. Let $f=x^2y^3+7xy^5+17$ and $g=x^5+6x+5y^2x-1$. Then the resultant is given by
$$
{\rm Res}(f,g,y)=49x^{27} - 70x^{24} + 1470x^{23} - 245x^{22} + 25x^{21} - 1680x^{20} + 17920x^{19} - 5880x^{18}
 + 940x^{17} - 15195x^{16} + 110880x^{15} - 53340x^{14} + 11520x^{13} - 61870x^{12} + 347835x^{11} - 216720x^{10} + 58600x^9 - 99300x^8 + 442199x^7 - 332665x^6 + 1010645x^5 -
17710x^4 + 1470x^3 - 49x^2.
$$
So we see that the degree is less than $\deg(f)\deg(g)=6\cdot 5=30$.
Since the resultant is a determinant polynomial coming from the Sylvester matrix, the estimate follows from it, see here.


text:
Q: ¿Cómo restar a dos entradas distintas un valor variable? supongamos que tengo una tabla de productos con la siguiente estructura:
descripcionProducto  stockProducto  fechaVencimientoProducto
------------------------------------------------------------
producto1            5              05/10/19
producto1            5              10/10/19
producto2            3              07/10/19

Y supongamos que quiero dar de baja 6 ítems del producto 1, dando de baja (es decir poner en 0 el stock) primero el que tiene la fecha de vencimiento más próxima y luego el que le siga.
Lo que he probado es lo siguiente, pero me resta en todas las columnas 6 ítems dejando en negativo todos los stocks, pero no sé cómo subtraer un total de 6 a la columna.
UPDATE stock SET stockProducto = stockProducto - 6 WHERE stockProducto > 0 AND descripcionProducto = "producto1";

A: la solución que desarrollé involucra triggers. Cuando detecta que hay un update en la tabla y si el valor de stock de algún producto queda por debajo de 0, entonces busca la siguiente entrada que tenga un stock mayor a 0 (y que además tenga la fecha de vencimiento más próxima) y le resta el valor negativo de la entrada anterior, luego, para evitar tener un stock negativo actualizo el valor para que quede en 0. Lo bueno es que si el nuevo update genera un valor de stock negativo, por lo que pude probar, el trigger se dispara nuevamente y es recursivo.
En la tabla de ejemplo habría que agregar el idProducto que sea un autonumérico para poder indentificar cada entrada.
CREATE TRIGGER IF NOT EXISTS stockNegativo
    AFTER UPDATE
    ON stock
    WHEN new.stockProducto < 0
BEGIN
    UPDATE ingresos
        SET stockProducto = stockProducto + new.stockProducto
        WHERE stockProducto > 0
            AND idProducto = (SELECT idProducto FROM stock
                WHERE stockProducto > 0
                    AND descripcion = old.descripcion
                    ORDER BY fechaVencimientoProducto LIMIT 1);
    UPDATE stock
        SET stockProducto = 0
        WHERE stockProducto < 0
            AND idProducto = (SELECT idProducto FROM stock
                WHERE stockProducto < 0
                    AND descripcion = old.descripcion
                    ORDER BY fechaVencimientoProducto LIMIT 1);
END;


text:
Q: How can this query break my mysql replication? I have a standard one directional master-slave setup.
The tables have MyIsam storage engine.
The Versions are:
Master
Server version: 5.1.41-3ubuntu12.10-log
Protocol version: 10
1st Slave:
Server version: 5.1.41-3ubuntu12.10
Protocol version: 10
2nd Slave:
Server version: 5.1.49-1ubuntu8.1
Protocol version: 10
I have set up all users beside a dedicated replication user to be read only on the slaves.
The following statement, executed on the master, gets not replicated correctly:
$insert = "INSERT INTO search_affiliate_product
(film_id, ext_id, affiliate_id, `status`, url, created_at)
SELECT film_id, LPAD(imdb, 7, '0'), $affiliate_id, 5, CONCAT('http://www.imdb.com/title/tt', LPAD(imdb, 7, '0'),'/'), NOW() FROM search_film_entity
WHERE film_id NOT IN (SELECT film_id FROM search_affiliate_product WHERE affiliate_id = $affiliate_id)
AND status IN (5, 9)
AND release_year BETWEEN 0 AND $year
AND imdb > 0";

The slave gets this error:
Error 'Duplicate entry '271769' for key 'PRIMARY'' on query. Default database:     'flimmit_search_14'. Query: 'INSERT INTO `search_affiliate_product` (`affiliate_id`,     `ext_id`, `url`, `status`, `film_id`, `created_at`, `updated_at`) VALUES ('16', '1991/JohnnyStecchino', 'http://www.cineman.ch/movie/1991/JohnnyStecchino/review.html', '5', '102164', '2011-10-26 02:30:05', '2011-10-26 02:30:05')'

I also made some other observations:

*

*The statement gets transferred "as is" over the bin log (relay log and master log), so the explicit data that is inserted is not contained, but the whole statement with the select and subselect is executed on the slave, relying on the local data.

*If i look at the master and slave table and sort by primary key, I see a range of inserts produced by the statement above on both servers. The rows before and after that are in sync. Also a lot of rows in that range that is produced by that statement is equal. But there are also discrepancies.
I thought that the problem may because by concurrent sql transactions. So that the inserting process interferes with other inserts and therefore the values get mixed up, where on the slave this does not happen because the log is processed procedurally.
I also noticed that during the inserting process of the statement some IDs seem to be inserted that are not inserte on the other server, and some duplicates get inserted (duplicates on the field ext_id which is populated by the imdb field from the other table, which is unique...
I am really stuck here.
Any suggestions? I would really like to understand why this is happening.
I thought about selecting all the ids and making single insert statements in the application or lock the table before executing it. I think this could solve it, but i would really like to understand the error.
The next weird thing is that the second slave seems to run fine! only the first slave is getting problems. I just don't understand it.

A: this kind of replication can only be done reliably under innodb with the following settings in place on the client
[mysqld]
innodb_flush_log_at_trx_commit=1
sync_binlog=1

A: I would say that your AUTO_INCREMENT counters for the (guessing) ID column on the search_affiliate_product table have got out of step. Specifically I suspect that the AUTO_INCREMENT value on the first slave got ahead of the equivalent master value somehow. I guess the value on slave server 2 has remained in step which is why the error does not occur there.
If you run the following on master, server 1 and server 2 you should be able to see whether this is true or not:
select auto_increment
 from information_schema.tables
 where table_name = 'search_affiliate_product';

One of the reasons why this might happen is data being inserted into the search_affiliate_product directly on the slave server 1 i.e. not via the master, hence incrementing the AUTO_INCREMENT value and causing it to get ahead of the master.
A simple fix for this is to get the max id from slave server 1 using:
select max(id) from search_affiliate_product;

Let's say you get a value of 123456. Add 100 to it for good luck and then alter the auto_increment value of the master search_affiliate_product table:
alter table search_affiliate_product auto_increment = 123556;

Then try running the insert again.
If this isn't the case then I guess it is back to the drawing board!


text:
Q: Intent Based Android Security Vulnerabilities, Violating the Device and Network Abuse policy We have got this mail from google says,
During review, we found that your app violates the Device and Network Abuse policy:
We don't allow code that introduces or exploits security vulnerabilities. Check out the App Security Improvement Program to find out about the most recent security issues flagged to developers.
You can read through the Device and Network Abuse policy page for more details and examples of common violations.
For example, your app contains an Intent Redirection issue which can allow malicious apps to access private app components or files.
androidx.activity.ComponentActivity.startActivityForResult
...................................................
We replaced ComponentActivity.startActivityForResult with registerForActivityResult
Am I missing anything else.
Google is not specific about the source of the cause
What could be the source of the cause, how to overcome it?


text:
Q: Will replacing workspace path affect definition queries in Maps or Layer Files? I am doing a cleaning up project for some of my data. This requires a data structure.
That means I will have to replace the workspace path in the MXDS.
The old structure of the data will be something as follows:
c\project\type\data\sources
With the new structure being:
C\project\data\sources
I believe it possible to use map document or layer find and replace workspacepath. If I do this though will this effect layer settings such as definition queries?
I have read in the scripting for ArcGIS ESRI book the following:
When workspaces in a map document are modified, there are a few things that MAY NOT WORK
joins and relates associated with raster layers. Definition Queries MAY no longer work because of slightly different SQL syntax (then gives an example of FILE GEODATABASES to Personal Ones).
If I am just making straight change for the location of the data like a shapefile in a new location or file geodatabase in a new location, will this effect definition queries that might be stored in maps?

A: If you are moving a shapefile or file geodatabase feature class that is the source of a layer to a new location, and then you change the source of that layer to be the same shapefile or file geodatabase feature class in that new location then the definition query will still work.
If you are changing the source of a layer to a different shapefile or file geodatabase feature class then it will depend on whether the SQL used by the definition remains valid.  For example, a field used by the definition query may not exist or be spelled the same in that or file geodatabase feature class.


text:
Q: Im using ssh2_exec functionin php why it doesn't pass more then 3 parameters? Why the ssh2_exec function doesn't pass more than three parameters?
$stream_1 = ssh2_exec($ssh, "/root/Script/Auto_Traces/show_ng_trace.sh $a $b $c $d $e");

In this case only $a $b $c are passing but not $d and $e, how can I solve it?

A: I suspect there are spaces in some of the first 3 variables, so they're being treated as multiple arguments. Then the last 2 arguments are being ignored.
In case any of the variables have spaces (or other special characters) in them, you should escape them.
$ae = escapeshellarg($a);
$be = escapeshellarg($b);
// repeat for the rest of variables
$stream_1 = ssh2_exec($ssh, "/root/Script/Auto_Traces/show_ng_trace.sh $ae $be $ce $de $ee");


text:
Q: How do you retrieve a post by slug name through REST API? It works for my pages but not for my posts. If I go to example.com/wp-json/wp/v2/pages?slug=page-name it will retrieve the page correctly. If I go to example.com/wp-json/wp/v2/posts?slug=post-name it will not retrieve a post in the same way. Can someone tell me how to get a post by slug name? The post does have a category too, but I don't know if it's necessary or how to properly add that to the query. All the documentation I have found refers to the [filter] function which is no longer supported.

A: Posts: sitename.com/wp-json/wp/v2/posts?slug=post-slug
Pages: sitename.com/wp-json/wp/v2/pages?slug=page-slug
Custom post type: sitename.com/wp-json/wp/v2/POST_TYPE?slug=post-slug


text:
Q: property seems to be empty in viewDidLoad I have a view controller which contains some data. There is an action button:
- (IBAction)readMorePressed:(id)sender {
    DetailedItem *itemVc = [self.storyboard instantiateViewControllerWithIdentifier:@"Item"];;

    itemVc.postTitle = self.postTitle;
    itemVc.category = self.category;
    itemVc.content = self.content;

    [self.navigationController pushViewController:itemVc animated:YES];

}

As you can see, I try to set the title, the category and the content properties.
self.postTitle, self.category and self.content are not nil, confirmed via
debugging)
Though, at the viewDidLoad method of the DetailedItem view controller, the _postTitle, _category and _content properties seem to be nil, so I cannot present them in the UI.
Am I missing something here?


text:
Q: Plesk doesn't upload backups to FTP, saves locally instead I have a weird problem with Plesk. I used to have scheduled backups saved on the server but changed that to FTP repository. The problem is that Plesk keeps saving backups on the same server and doesn't upload anything on my FTP. I could assume that there is something wrong with the FTP access but I don't get any notifications about this although I've added my email address into the scheduled backups settings. Please give me a piece of advice

A: I had the same problem for days until I noticed that the /usr partition it wasn't large enough to hold the temporal backup. The issue was due to a lack of space on the /usr partition; the backups worked previously because there was enough space on /usr to hold them during the backup job, however the backup (~3.4 GB) was too large at that moment. So I added 10 extra Gb to that partition and the problem was solved.
Plesk: 11.0.9 Update #55 CentOs 6.4

A: You have not provided Plesk version you running.
I had similar problem, it started after upgrade to plesk version 11. Please have a look at this post; instructions provided by dischneider resolved my issue:
http://forum.parallels.com/showthread.php?t=260857

A:
I could assume that there is something wrong with the FTP access

Try to perform manual backup to FTP repository.
Also check /usr/local/psa/PMM/logs/pmmcli.log for error messages.

A: Thank you all, your comments were helpful. The real reason was caused by a problem with connecting to FTP. That's why the backups were left on the server.

A: Another issue for those experiencing this problem is that some FTP servers will not accept transfers greater than a certain filesize. This is the case for Amazon S3, it will not accept fiels larger than 5GB on PUT. We had to use the multi-compression feature to get it working.

A: As jersoncito suggested, this can happen when your /usr partition is too small to hold the data. Plesk always creates a local backup and then transfers it off to FTP. When it's successful it will delete the local backup - but when there's a problem, it will leave it local.
If you can't resize the /usr partition, you can bind mount a larger directory into the something else - say /var/temp:
service psa stop

mount --bind /var/tempfiles /usr/local/psa/PMM/tmp
mount --bind /var/tempfiles /usr/local/psa/tmp

service psa restart

There's a KB article on this subject here: http://kb.parallels.com/114415


text:
Q: Generating video or images of geometrical objects from data I'm working in a course's project to predict the velocity and position of the solar system planets (and other objects). It will be really cool if I can visualize the predicted objects data, if it's possible generating 3D images, if in video that's amazing.
 Do you know any library that lets me to use this data to generate an image or video? (I don't care in which language)
Data:
- simulation step (time line step for a video)
- positions of the objects
- radius and/or colours of the objects
Thanks in advance, any suggestion is welcome.

A: There are several approaches that I've used (all via Python) for this type of visualization:
VPython is super easy to learn and you'll be able to get dynamic 3D visualization of planets spinning around a sun in minutes.  There are contributions to help make movies as well, but I haven't used these.
One can also just use OpenGL directly, via, say, PyOpenGL within a wxPython window, or, using, for example, PyGlet.  This approach is a bit more basic than VPython and will probably take longer to do, and the only way I know to make movies is via screenshots, etc.
VTK is an very impressive 3D visualization library, but is much harder to learn.  VTK, like the others, will do dynamic visualization out-of-the-box, and it's the only one that has a built-in module for making images and movies.  It is, though, a much more complicated library, but if you want planets spinning around a star, with a contour plot of a gas cloud, in the midst of a vector-field ion-storm, VTK can do it.  There's also MayaVi which makes VTK a bit more accessible and interactive.

A: I have a very rough idea that might be useful as a starting point, although it would need quite a bit of fleshing out in order to look properly professional. Does your data give the position of each planet in space at a given point in time? If so, you could:
1) Project your position data into twospace if it was originally 3-D (allowing you to use 2-D methods to represent data that still looks like it's being displayed in 3-D on the screen)
2) The result should be a series of 2-D matrices storing the locations of your planets. Let the matrix elements be 1 if they correspond to the location of a planet, and let them be 0 otherwise. (If you were to plot the matrix, it would look like a handful of white dots on a black background.)
3) Use the use morphological dilation to take every position point and set the values of their neighbors to 1 instead of 0, so that when you plot you get a set of disc-shaped white objects centered on the points from step (2).
4) Use a program to write each matrix from (3) to an image file, and put them in a common folder.
5) At runtime, use another program to import each image from the folder one at a time, displaying them on the screen in the same figure window. The result should be that each image representing the planets at time t replaces the picture for time (t-1). This should look optically the same as if a video file were playing in that window.
The end result would be a moving-picture show of a bunch of white circles in orbit against a black background. Would that be useful?


text:
Q: Can't start mysql with kernel error I'm trying start mysql but this not working.I'm open syslog and see this error.
May 22 08:40:28 blacker-ubuntu systemd[1]: Starting MySQL Community
Server...
May 22 08:40:28 blacker-ubuntu kernel: [ 3175.104982] audit: type=1400 audit(1495417228.964:347): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/18181/status" pid=18181 comm="mysqld" requested_mask="r" denied_mask="r" fsuid=124 ouid=124
May 22 08:40:28 blacker-ubuntu kernel: [ 3175.104995] audit: type=1400 audit(1495417228.964:348): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=18181 comm="mysqld" requested_mask="r" denied_mask="r" fsuid=124 ouid=0
May 22 08:40:28 blacker-ubuntu kernel: [ 3175.105030] audit: type=1400 audit(1495417228.964:349): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/18181/status" pid=18181 comm="mysqld" requested_mask="r" denied_mask="r" fsuid=124 ouid=124
May 22 08:40:29 blacker-ubuntu systemd[1]: mysql.service: Main process exited, code=exited, status=1/FAILURE
May 22 08:40:43 blacker-ubuntu systemd[1]: Stopped MySQL Community Server.
May 22 08:40:43 blacker-ubuntu systemd[1]: mysql.service: Unit entered failed state.
May 22 08:40:43 blacker-ubuntu systemd[1]: mysql.service: Failed with result 'exit-code'.

*

*Mysql version 5.7.18-0ubuntu0.17.04.1

*Ubuntu Gnome 17.04


text:
Q: What are the "OCHI Root Hub Simulation" usb devices? I'm currently doing some experimenting with USB (using node-usb), and I'm printing out each connected device:
Connected Devices:
 - [05ac:12ab] iPad 4/Mini1 (Apple, Inc.)
 - [05ac:8206] Bluetooth HCI (Apple, Inc.)
 - [04f2:0939] undefined (Chicony Electronics Co., Ltd)
 - [05ac:8242] Built-in IR Receiver (Apple, Inc.)
 - [04f2:0833] undefined (Chicony Electronics Co., Ltd)
 - [05ac:8502] Built-in iSight (Apple, Inc.)
 - [05ac:8005] OHCI Root Hub Simulation (Apple, Inc.)
 - [05ac:8005] OHCI Root Hub Simulation (Apple, Inc.)
 - [05ac:8005] OHCI Root Hub Simulation (Apple, Inc.)
 - [05ac:8005] OHCI Root Hub Simulation (Apple, Inc.)

The format is - [vendorId:productId] productName (vendorName). The undefined productNames are due to a bug in how I pad the vendorID (I think), they're my mouse and keyboard. The rest are all pretty self-explainitory
But what I want to know is, what's OHCI Root Hub Simulation? I would suspect it's related to EHCI Root Hub Simulation and XHCI Root Hub Simulation, because I could find many articles mentioning them in conjunction (but not defining them). I would also suspect that they are classifications/types/protocols/divisions of USB, as I vaguely remember a broken link to an "OHCI Specification".
Am I correct?

A: They represent your computer's USB controller, which the computer is communicating with using the UHCI protocol. (That is, it's a USB 2.0 controller.) You see several of them because your computer has multiple USB ports.
If you look carefully at these devices' addresses and port numbers, you'll be able to see which devices are plugged into which ports. If you have any USB hubs, you may want to try hooking them up to see a more "interesting" device tree.


text:
Q: I get Error when I try to read installed Software of a remote PC with PHP I want to read the installed Software of a remote PC with PHP. I use the following code, but get always an ERROR. (Remote PC = WinXP, Server=WinServer 2019; PHP= V8.1.6)
<?php
set_time_limit(600);
define('HKLM', 0x80000002);
$loc=new COM("WbemScripting.SWbemLocator");
$wmi=$loc->ConnectServer('10.92.114.73',"root/default",'username','password');

$reg=$wmi->Get("StdRegProv");
$key_path = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall';
$sub_paths = new VARIANT();
$Names = new VARIANT();
$Types = new VARIANT();
$DName = new VARIANT();
$DVersion = new VARIANT();

$reg->EnumKey(HKLM, $key_path, $sub_paths); //******* in this line the Error is coming ********
//print $server_name['Username']." - ".$server_name['Password'];
foreach($sub_paths as $sub_path){
    $key_path2=$key_path.'\\'.$sub_path;

    $ergebnis=$reg->EnumValues(HKLM, $key_path2, $Names, $Types);
    if($ergebnis==0 && count($Names)>1){
        for($i = 0; $i < count($Names); $i++){
            if($Names[$i]=="DisplayName" && $Types[$i]==1){
                $reg->GetStringValue(HKLM, $key_path2, "DisplayName", $DName);
            }
            if($Names[$i]=="DisplayVersion" && $Types[$i]==1){
                $reg->GetStringValue(HKLM, $key_path2, "DisplayVersion", $DVersion);
            }
        }
        if($DName){
            print $DName;
        }
        if($DVersion){
            print " -- ".$DVersion."
";
        }
        else{
            print "
";
        }
    }
}
print "Ende Test";
?>

Fatal error: Uncaught com_exception: Source: SWbemObjectExDescription: Type mismatch in C:\Apache24\htdocs\wmi_programs.php:17 Stack trace: #0 C:\Apache24\htdocs\wmi_programs.php(17): variant->EnumKey(2147483650, 'SOFTWARE\Micros...', Object(variant)) #1 {main} thrown in C:\Apache24\htdocs\wmi_programs.php on line 17


text:
Q: Content in meta tag Like the first image, the meta tag is displayed correctly in inspect elements mode but incorrectly displayed in view page source mode as in the second image. Thank you for suggesting a solution to this problem.

A: I understood the answer:
Because, by default, the HTML encoding engine will only safelist the basic latin alphabet (because browsers have bugs. So we're trying to protect against unknown problems). The &XXX values you see still render as correctly as you can see in your screen shots, so there's no real harm, aside from the increased page size.
If the increased page size bothers you then you can customise the encoder to safe list your own character pages (not language, Unicode doesn't think in terms on language)
To widen the characters treated as safe by the encoder you would insert the following line into the ConfigureServices() method in startup.cs;
    services.AddSingleton<HtmlEncoder>(
  HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
                                            UnicodeRanges.Arabic }));

Arabic has quite a few blocks in Unicode, so you may need to add more blocks to get the full range you need.


text:
Q: How to get an element's rect BEFORE a transform? Currently, Element.getBoundingClientRect() gives the position and dimensions of an element, but it automatically accounts for transformations via the CSS transform property. How can I get the rectangle without the transformation?
In the example below, I would want the output to be 10 10 100 100.

const rect = div.getBoundingClientRect()
document.write(`${rect.left} ${rect.top} ${rect.width} ${rect.height}`)
body {
    margin: 10px;
}

div {
    background: red;
    width: 100px;
    height: 100px;
    transform: translate(1px, 1px) scale(0.5)
}

A:
Here is already an answer, you can read more on this post:
  How do I retrieve an HTML element's actual width and height?

So, you can get the actual value "before" transform by changing your code to the following

document.write(`${div.offsetLeft} ${div.offsetTop} ${div.offsetWidth} ${div.offsetHeight}`)
body {
    margin: 10px;
}

div {
    background: red;
    width: 100px;
    height: 100px;
    transform: translate(1px, 1px) scale(0.5)
}


text:
Q: Angular Headers not adding to the specific request, when i am having different headers from interceptors Unable to add headers for specific request, Interceptor headers are overriding the normal request headers.
Please find the below code.
request code...
let headers = new HttpHeaders();
        headers = headers.append('access-token', headerData['access-token']);
        headers = headers.append('client', headerData.client);
        headers = headers.append('uid', headerData.uid);

        console.log(headers);
        let args = {};
        args = {
            password: passwordData.password,
            password_confirmation: passwordData.password_confirmation
        };
        return this.http.put<{ response: any, body: any }>
            (this.getServerPath() + this.options.resetPasswordPath, args, { headers, observe: 'body' });

interceptors...
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const username = 'lotvue';
    const password = 'sp4WpwykOyHmIV%X^eCq';
    // debugger;
    const headers = new HttpHeaders({
      Authorization: 'Basic ' + btoa(username + ':' + password),
    });
    const clone =  req.clone({headers});
    console.log(clone);

    return next.handle(clone).pipe(
      catchError(this.handleError)
    );
  }

can anyone help me.

A: Try using setHeaders
let cloneParams =
{
   setHeaders: {
        Authorization: `Basic ${btoa(username +':'+ password)}`,
     };

const clone =  req.clone(cloneParams);


text:
Q: Finding the equation for a sinusoidal cycle/function given points. We are given the population of a fictional animal at different years:
$$\begin{array}{l|r}
\textrm{Year} & \textrm{Population}\\\hline
1945 & 347,0000\\
1955 & 76,000\\
1965 & 295,000\\
1975 & 84,000\\
1985 & 243,000\\
1995 & 92,000
\end{array}$$
We are asked to come up with a formula for the population over time. I am so lost. I can get a graph to go through the first 2 points, or I can get it to go through all of the maximums or all of the minimums, but I can't get it to go through all of the points in one go.

A: On the drawing of the given data, one can see that the maximums and minimums are respectively linear functions of the years. It is easy to express both linear équations, which are significant of the evolution of the population.
Of course, it is possible to find a "damped" sinusoidal function which accurately fits the six given points (with a 10 years half-period) The coefficients $C_0, C_1, C_2, C_3$are computed thanks to linear regression. But what is the meaning of such a function ? This is questionable ! Why not a one year period, ore else ? Are you sure that the problem requires such a sinusoidal model ? If statistical computations have to be carried out, why not directly using the given data instead of an intermediate function with, may be, no real significance!


text:
Q: medium-zoom pagination issues In my project I use medium-zoom  with pagination. On first page it works well but on second, third, fourth... I have to click several times for close image...on second page...two times, on third 3 times...
it seems to be a problem with maybe any index number?
Here is my code:
<template>

      <jw-pagination :items="info" :page-size="10" @changePage="onChangePage"></jw-pagination>

</template>

A: You will pretty much need to detach the event listeners here. Because it should be a lot of them added everytime due to the updated hook.
A naive implementation would be to add mediumZoom on the mounted hook. And when you do have a new changePage event, to detach it from all the images, then to apply it to the new ones with the same mediumZoom call.
Below is a way to see which event listeners (and probably how many) you have linked to a specific VueJS component. Select it in the Vue devtools and then, you will have access to the element's properties via $vm0.


text:
Q: Deleting items in ReactJS, using useState and useContext As a fairly new addict to programming, I'm stuck with a simple app that lists items. Adding items, is OK. But as for deleting one item, I just can't figure out how to implement this function. Now on clicking an item the whole array of items is deleted. I have tried to put the deleteItem function in other files, but I seem to have mixed up the references.
ItemContext.js:
import React, { useState, createContext } from 'react';
import { v1 as uuidv1 } from 'uuid';
export const ItemContext = createContext();

export const ItemProvider = (props) => {
  const [items, setItems] = useState([
    {
      name: "Red Beans",
      amount: 23,
      id: uuidv1()
    },
    {
      name: "Nuts for Bunnies",
      amount: 33,
      id: uuidv1()
    },
    {
      name: "Chopped Tomatoes",
      amount: 2,
      id: uuidv1()
    }
]);
  return (
      <ItemContext.Provider value={[items, setItems]} >
        {props.children}
      </ItemContext.Provider>
   );
}

AddItem.js:
    import React, { useState, useContext } from 'react';
import { ItemContext } from './ItemContext';

const AddItem = () => {
  const [name, setName] = useState('');
  const [amount, setAmount] = useState('');
  const [items, setItems] = useContext(ItemContext);

  const updateName = (e) => {
    setName(e.target.value)
  }

  const updateAmount = (e) => {
    setAmount(e.target.value)
  }

  const addItem = (e) => {
    e.preventDefault();
    setItems(prevItems => [...prevItems, {name: name, amount: amount, key: items.id}])
  }

  return (
      <form className="new-item" onSubmit={addItem}>
        <input type="text" name="name" value={name} onChange={updateName} placeholder="Add a new item"/>
        <input type="text" name="amount" value={amount} onChange={updateAmount} placeholder="Amount"/>
        <button>Submit</button>
      </form>
   );
}

export default AddItem;

Item.js:
import React, { useState, useContext } from 'react';
import { ItemContext } from './ItemContext';

const Item = ({name, amount, /*deleteItem*/ }) => {
  const [id, setId] = useState('');
  const [items, setItems] = useContext(ItemContext);

  const deleteItem = (id) => {
    // const newItems = items.filter(item => items.id !== id);
    // setItems(newItems);
    const newItems = Object.assign([], ...items)
    items.splice(id, 1);
    setItems(newItems);
  }

  return (

{name}

{amount}

      <button onClick={() => deleteItem(items.id)} className="delete-btn">Delete</button>

  );
}

export default Item;

ItemsList.js:
import React, { useState, useContext } from 'react';
import Item from './Item';
import { ItemContext } from './ItemContext';
import { v1 as uuidv1 } from 'uuid';

const ItemsList = () => {
  const [items, setItems] = useContext(ItemContext);
  const [id, setId] = useState('');

  const deleteItem = (id) => {
    // const newItems = items.filter(item => items.id !== id);
    // setItems(newItems);
    const newItems = Object.assign([], ...items)
    items.splice(id, 1);
    setItems(newItems);
  }

  return (

      {items.map(item => (
        <Item name={item.name} amount={item.amount} key={uuidv1()} deleteItem={deleteItem}/>
      ))}

   );
}

export default ItemsList;

A: Initially you need to provide a valid initial value to the ItemContext context you are creating. Its signature should match what the context value will be. I suggest using an object instead of an array.
export const ItemContext = createContext({
  items: [],
  addItem: () => {},
  deleteItem: () => {}
});

Then define addItem and deleteItem handlers to include in the context value. You want to avoid exposing out the setItems state function directly so ItemProvider maintains control over the state invariant.
const initialState = [
  {
    name: "Red Beans",
    amount: 23,
    id: uuidv1()
  },
  {
    name: "Nuts for Bunnies",
    amount: 33,
    id: uuidv1()
  },
  {
    name: "Chopped Tomatoes",
    amount: 2,
    id: uuidv1()
  }
];

const ItemProvider = (props) => {
  const [items, setItems] = useState(initialState);

  const addItem = (item) => setItems((items) => [...items, item]);
  const deleteItem = (id) =>
    setItems((items) => items.filter((item) => item.id !== id));

  const value = {
    items,
    addItem,
    deleteItem
  };

  return (
    <ItemContext.Provider value={value}>
      {props.children}
    </ItemContext.Provider>
  );
};

Then destructure the ItemContext value where you are consuming it.
AddItem.js - Make sure to assign a new uuidV1 GUID for new items. I think this was your biggest issue, you were assigning undefined to a key property (key: items.id) instead of creating a new GUID for the id property.
import React, { useState, useContext } from 'react';
import { ItemContext } from './ItemContext';

const AddItem = () => {
  const [name, setName] = useState("");
  const [amount, setAmount] = useState("");
  const { addItem } = useContext(ItemContext);

  const updateName = (e) => {
    setName(e.target.value);
  };

  const updateAmount = (e) => {
    setAmount(e.target.value);
  };

  const submitHandler = (e) => {
    e.preventDefault();
    addItem({
      name: name,
      amount: amount,
      id: uuidv1() // <-- new GUID here!!
    });
  };

  return (
    <form className="new-item" onSubmit={submitHandler}>
      <input
        type="text"
        name="name"
        value={name}
        onChange={updateName}
        placeholder="Add a new item"
      />
      <input
        type="text"
        name="amount"
        value={amount}
        onChange={updateAmount}
        placeholder="Amount"
      />
      <button>Submit</button>
    </form>
  );
};

Item.js - Get deleteItem from the context and ensure to pass item id to component.
import React, { useState, useContext } from 'react';
import { ItemContext } from './ItemContext';

const Item = ({ name, amount, id }) => {
  const { deleteItem } = useContext(ItemContext);

  return (

{name}

{amount}

      <button onClick={() => deleteItem(id)} className="delete-btn">
        Delete
      </button>

  );
};

ItemsList.js - Set the React key to the current item id and also pass the id as a prop to `Item.
import React, { useState, useContext } from 'react';
import Item from './Item';
import { ItemContext } from './ItemContext';

const ItemsList = () => {
  const { items } = useContext(ItemContext);

  return (

      {items.map((item) => (
        <Item
          key={item.id} // <-- Static React key to item
          id={item.id} // <-- Pass id as prop for delete handler to use
          name={item.name}
          amount={item.amount}
        />
      ))}

  );
};

Demo


text:
Q: Adding extra parameter to method? I have below aspect.
@Around("somePublicMethod()")
    public Object doAction(ProceedingJoinPoint call) throws Throwable {
        SomeObject client = null;
        Object result = null;

        try
        {
            client = someDao.getResult();

            Object[] allArgs = call.getArgs();
            allArgs[allArgs.length-1] = client;

            // Do the call, passing in the managed SiperianClientWrapper
            result = call.proceed(allArgs);
        }
        catch(Exception ex)
        {

            throw ex;
        }

I have one service method as below. This method is intercepted by above aspect
public SomeEntity getEntities(String name, String pwd, SomeObject client){

//some logic

}

above method is called as below.
someService.getEntities("name","pwd",null);

What aspect does is, SomeObject has null and null is replaced by some actual value.
My question is instead of passing null as a parameter value, is it possible to add an extra parameter using Reflection with in the Aspect? In my case SomeObject parameter can be added dynamically?
so that finally i have to call the service as someService.getEntities("name","pwd"); and the SomeObject will be added dynamically by Aspect?
Thanks!

A: If your java file is declared with a method declaration as
public SomeEntity getEntities(String name, String pwd, SomeObject client){

then that is what you have to use. A method call like
someService.getEntities("name","pwd");

will not compile.
Reflection cannot change the compiled byte code.
Trying to invoke this method through reflection with only the first two arguments will cause an IllegalArgumentException.

A: It's possible to extend class and overload method if you're willing to use ajc compiler since javac compiler wouldn't compile.
Resources online are kind of scarce, but AspecJ in Action should be great resource to study this topic.


text:
Q: How can I handle the Return key in a CEdit control? How can I handle the Return key (VK_RETURN) in a CEdit control? The CEdit control is parented to a CDialog.

A: The correct answer is to handle the WM_GETDLGCODE / OnGetDlgCode message. In there you can specify that you want all keys to be handled by your class.
UINT CMyEdit::OnGetDlgCode()
{
    return CEdit::OnGetDlgCode() | DLGC_WANTALLKEYS;
}

A: Make certain the Edit Control style ES_WANTRETURN is set in the dialog resource for the control

A: By default, the Return key closes an MFC dialog. This is, because the Return key causes the CDialog's OnOK() function to be called. You can override that function in order to intercept the Return key. I got the basic idea from this article (see Method 3 at the end).
First, make sure that you have added a member for the edit control to your dialog using the Class Wizard, for example:
CEdit m_editFind;

Next, you can add the following function prototype to the header file of your dialog:
protected:
    virtual void OnOK();

Then you can add the following implementation to the cpp file of your dialog:
void CMyDialog::OnOK()
{
    if(GetFocus() == &m_editFind)
    {
        // TODO: Add your handling of the Return key here.
        TRACE0("Return key in edit control pressed\n");

        // Call `return` to leave the dialog open.
        return;
    }

    // Default behavior: Close the dialog.
    CDialog::OnOK();
}

Please note: If you have an OK button in your dialog which has the ID IDOK, then it will also call OnOK().
If this causes any problems for you, then you have to redirect the button to another handler function.
How to do this is also described in Method 3 of the article that I have mentioned above.

A: I encounter this problem myself.  After a little experiment, a simple way existed if you just want to get the do something (after some editing etc) on the return (not specific for which editor you have focus) - I would just create a invisible default button, and let that button handle the 'return' key instead of default Ok button (of course, Ok button should be set default key to false)

A: You could also filter for the key in your dialog's PreTranslateMessage. If you get WM_KEYDOWN for VK_RETURN, call GetFocus. If focus is on your edit control, call your handling for return pressed in the edit control.
Note the order of clauses in the if relies on short-circuiting to be efficient.
BOOL CMyDialog::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN &&
        pMsg->wParam == VK_RETURN &&
        GetFocus() == m_EditControl)
    {
        // handle return pressed in edit control
        return TRUE; // this doesn't need processing anymore
    }
    return FALSE; // all other cases still need default processing
}


text:
Q: Transferring Calls From External IVR to Amazon Connect I'm currently setting up a Amazon Connect call center with a Lex bot that handles customer needs. The idea is that a prior IVR (CISCO), will transfer the call over to Amazon Connect.
Has anyone had any luck passing over any data collected/associated with the CISCO (or any other external) IVR to Amazon Connect?
I know that when transferring a call from one Amazon Connect flow to another Amazon Connect flow, a Previous Contact ID indicates the ID of the previous call, but I was wondering if the same is available when coming from an external IVR.
Thanks!

A: There is no built-in way to transfer data from an external IVR into Amazon Connect (or really any other ACD system, for that matter). What you need to do is store the data associated with the phone # in a database or other central location (preferably in AWS), and then access that data via Lambda within your Amazon Connect contact flows.

A: There is no out of the box functionality available for transferring data from external IVR to Amazon Connect. However, you can transfer the call to Amazon Connect by calling connect.startOutboundVoiceContact method of Amazon Connect.
You can pass the information/data in the form of attributes.
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Connect.html#startOutboundVoiceContact-property

A: So what you could do is claim a number of delivery numbers, Cisco would use these to deliver the voice. Cisco would call an API which uses the delivery number as a key in DynamoDB when the contact flow in Connect associated with that delivery number would read the data from the DynamoDB with a Lambda and then use the data passed.


text:
Q: How to know which package hold current function in R? When I ?filter,Rstudio let me choose:
Help on topic 'filter' was found in the following packages:

Linear Filtering on a Time Series
(in package stats in library C:/Program Files/R/R-3.5.3/library)
Return rows with matching conditions
(in package dplyr in library C:/Users/me/Documents/.checkpoint/2019-12-11/lib/x86_64-w64-mingw32/3.5.3)

When I use filter() in my script,how to know is it stats::filter() or dplyr::filter()?

A: You could do the following to find the package name that a function is currently loaded from
environmentName(environment(filter))

As for handling it I would stick with using stats::filter() or dplyr::filter() if it's only a few uses or declaring one as a new function altogther
filter_stats <- stats::filter
filter_stats()

The library conflicted is also useful for conflicts especially with conflict_scout() and conflict_prefer().  You could do conflict_prefer("filter", "stats"), for example, to override the default behavior of the most recent package taking priority.  There are a few other alternative methods mentioned on the conflicted libraries readme.
There are also the base calls conflicts() or conflicts(detail = TRUE).

A: The generic solution is to inspect topenv(environment(function_name)) (and potentially calling environmentName on the result). But just printing function_name (i.e. using the name without calling it) also works.
That said, this should generally not be used as a mechanism at runtime; instead, ensure that the expected packages are loaded. The easiest ways of doing this are:

*

*Either use explicit namespace qualification, i.e. dplyr::filter instead of filter; this is best practice in most modern languages, but it can be quite burdensome, especially when doing exploratory analysis.

*Always use library instead of require when importing a package. Unlike require, library will raise an error if the corresponding package couldn't be loaded.


text:
Q: runtime error in code for solving smallest even divisible The problem was to find the smallest even number that is divisible by 17 and 32 and has a square root greater than 120.
This code outputs 32 which obviously isn't true. Can anyone spot my error?
#include <iostream>
#include <math.h>
#include <stdio.h>

using namespace std;

int main()
{
    int i = 1;
    if(i%2!=0){
        i++;
    }
    while(i%17!=0 && i%32!=0 && sqrt(i)<120){
        i+=2;
    }
    cout<<i<<endl;
}

A: i%17!=0 && i%32!=0 && sqrt(i)<120 here is the problem. Your stopping condition should be:
while (it is NOT (Divisible by 17 AND Divisible by 18 AND its root more than 120)).
This is equal to:
while(!(i%17==0 && i%32==0 && sqrt(i)>120))

Or even shorter using Demorgan Law:
while(i%17!=0 || i%32!=0 || sqrt(i)<=120)

A: Your boolean expression is wrong. You need to loop while any of the conditions is true since it has to end when i % 17 == 0, i % 32 == 0 or sqrt(i) <= 120. The negation of this is an or'd expression.

A: The answer is
#include <math.h>       /* ceil */
#include <iostream>
int main ()
{
    std::cout<<ceil((120*120)/(32*17))*(32*17);
}

Do not use loops for simple math problems

A: To improve efficiency, you should start with LCM of 17 & 32 i.e. 544 and then work your way up instead of starting from 1.