text:
Q: JQuery and Azure Table, Is there a way to insert an entity with JQuery?, What happens with the account key? I need to insert an entity in a Azure Table directly from Javascript in a browser, using the REST Api for Tables, I would like to use jQuery, but i can't found any code to do that, and I don't know, for example, what happens with the account key. Should I expose my account key in the page? I am very sure that is a very very bad idea, any suggestions?

A: Until June 2012, there was no way to do this without sharing your keys which, as you state, is likely to be a very bad idea.
With the June 2012 capabilities, you can consider using a Shared Access Signature to provide varying levels of access to the table, or part of the table.
How you'd use it is very much dependent upon your scenario but I'd expect that you'd want to do this only for authenticated users, passing the Shared Access Signature over an SSL connection with a short expiry time, possibly with a partition key per user if you have a limited number of users.
See http://msdn.microsoft.com/en-us/library/windowsazure/ee395415.aspx


text:
Q: Show certain InfoWindow in Google Map API V3 I wrote the following code to display markers. There are 2 buttons which show Next or Previous Infowindow for markers. But problem is that InfoWindows are not shown using google.maps.event.trigger
Can someone help me with this problem. Thank you.
Here is code:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Common Loader</title>

<markers>
<marker name='Name1' lat='41.051407' lng='28.991134' phone='+902121234561' distance=''/>
<marker name='Name2' lat='40.858746' lng='29.121666' phone='+902121234562' distance=''/>
<marker name='Name3' lat='41.014604' lng='28.972256' phone='+902121234562' distance=''/>
<marker name='Name4' lat='41.012386' lng='26.978350' phone='+902121234562' distance=''/>
</markers>
<input type="button" onclick="showPrevInfo()" value="prev"> <input type="button" onclick="showNextInfo()" value="next">

A: this is how i'm doing it
hope it can help ;)
 /**
  * map
  */
  var myLatlng = new google.maps.LatLng(39.980278, 4.049835);
  var myOptions = {
    zoom: 10,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    scrollwheel: false
  }
 var map = new google.maps.Map(document.getElementById('mapa'), myOptions);

 var infoWindow = new google.maps.InfoWindow();
 var markerBounds = new google.maps.LatLngBounds();
 var markerArray = [];

 function makeMarker(options){
   var pushPin = new google.maps.Marker({map:map});
   pushPin.setOptions(options);
   google.maps.event.addListener(pushPin, 'click', function(){
     infoWindow.setOptions(options);
     infoWindow.open(map, pushPin);
   });
   markerArray.push(pushPin);
   return pushPin;
 }

 google.maps.event.addListener(map, 'click', function(){
   infoWindow.close();
 });

 function openMarker(i){
   google.maps.event.trigger(markerArray[i],'click');
 };

 /**
 *markers
 */
 makeMarker({
   position: new google.maps.LatLng(39.943962, 3.891220),
   title: 'Title',
   content: '

Lorem ipsum
Lorem ipsum dolor sit amet
'
 });

openMarker(0);

A: This code doesn't work because it is triggering click event on markers[markerIndex] which is not map marker but information about DOM element with tag marker.
To get it running you have to add global array which will contain list of map markers:
var markerList = [];

Change initialize() function to push map marker to that list in for loop:
markerList.push(marker);

Change functions showNextInfo() and showPrevInfo() to trigger event on map marker:
//google.maps.event.trigger(markers[markerIndex], "click");
google.maps.event.trigger(markerList[markerIndex], "click");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Collinearity between intercept and slopes that vary by time coding - linear mixed effects model I'm currently trying to run a linear mixed effects model to estimate how stress changes as a function of time (over 6 timepoints). I've noticed that when the intercepts and slopes of stress trajectories are extracted for each individual in my sample, there is a high correlation between these factors. However, this seems to change depending on how time is coded ... any explanation for why this might be happening? How would you usually deal with collinearity between intercepts and slopes? Any suggestions would be greatly appreciated.
Reproducible example below:
#toy data code: https://rpubs.com/mlmcternan/BC-lme
options(width = 100)

library(lme4)
library(nlme)
library(dplyr)
library(kableExtra)
library(psych)
library(car)
library(ggplot2)
library(ggpubr)
library(tidyverse)

set.seed(222)

# simulate data
N <- 150
nobs <- 6
sigma <- 20
sig00 <- 10
b0 <- 80
b1 <- -6

ID = rep(1:N, each = nobs)

# time is coded 0 to 5 here

Time = rep(0:5, 150)
dat <- data.frame(ID, Time)
u0 <- rnorm(N, 0, sig00)
dat$u0 <- rep(u0, each=nobs)
dat$err <- rnorm(900, 0, sigma)
dat$Stress <- (b0 + u0)  + b1*dat$Time + dat$err
dat <- dat[,-c(3:4)]

# fit the model
fit1 <- lme(Stress ~ Time, random=~Time|ID, data=dat, correlation=corCAR1(form=~Time|ID), method="ML",na.action=na.exclude, control=list(opt="optim"))

# extract predictions
predictions <- data.frame(coef(fit1))
names(predictions) <- c("Intercept", "Slope")

# correlate intercept and slope
cor.test(predictions$Intercept, predictions$Slope, method = "pearson")

# Correlation between Intercept and Slope = 0.8057988

# plot correlation
plot(predictions$Intercept, predictions$Slope, main="Scatterplot Example",
     xlab="Intercept ", ylab="Slope ", pch=19)

# Recode time - 0 represents predicted mean at timepoint 2
dat$Time <-  rep(-1:4, 150)

fit1 <- lme(Stress ~ Time, random=~Time|ID, data=dat, correlation=corCAR1(form=~Time|ID), method="ML",na.action=na.exclude, control=list(opt="optim"))

predictions <- data.frame(coef(fit1))
names(predictions) <- c("Intercept", "Slope")
cor.test(predictions$Intercept, predictions$Slope, method = "pearson")
#correlation between intercept and slope = 0.6314682

plot(predictions$Intercept, predictions$Slope, main="Scatterplot Example",
     xlab="Intercept ", ylab="Slope ", pch=19)

A: This turns out to be more of a statistics/math question rather than one about coding. Anyway, I think the reason for your varying correlation is ingrained in the way you define/simulate the data.
Have a look at (both versions of) your simulated data using a spaghetti plot:
library(ggplot2)

ggplot(dat, aes(y = Stress, x = Time, colour=as.factor(ID) )) +
  geom_smooth(method=lm, se=FALSE) + theme(legend.position = "none") +
  geom_vline(xintercept=0)

You will see that the regression lines for each ID are closer together in the middle of the plot (around Time == 2.5) than at each end. This is because b1*Time is bigger for larger values of abs(Time).
Now, when you change the way you code Time from 0 - 5 to -1 - 4, you move the y-axis to the right where the lines are closer together. Because the intercepts are defined as the value of Stress where regression lines cross the y-axis, moving the y-axis  brings the intercepts closer together. Or, in other words, moving the y-axis changes the impact of the slope on the intercept.
This is why it is often recommended to center predictors when you have moderators and/or random slopes. It makes the interpretation of intercepts easier.


text:
Q: Remove item from array in Gutenberg block by index I have a WordPress Gutenberg block that I'm able to add items to an array in. However, I need to provide the user a way to remove a specific list item from the array of items when clicking a button next to the specific item. The data is stored as an array of objects. Outside of WordPress and Gutenberg, this will work on a basic level of removing an item by index from an array. However, the following not only doesn't remove an item, it is also blocking adding new items.
Markup used to trigger delete function
{items.map((item, index) => {
    return (
        <Button
        onClick={removeElement(index)}
        />
        <RichText.Content
            value={item['listItem']}
        />
    )
})}

Used to add new empty item to list
const addListItem = () => {
        setAttributes({
            items: items.concat({
                listItem: ''
            })
        });
    };

How I'm currently attempting to remove the selected object from the array
const removeListItem = index => {
        items.splice(index, 1);
        return items;
    };

I have seen suggestions of using array.filter, but will not remove the index from the array.


text:
Q: What is best way to design worker based back-end I want to design a backend which consists of many workers, database and an API. There are two ways for this in my mind.
First, there is a central API which contains database connection and models. It behaves as a database wrapper and it is Restful. All of workers, and other apps are connected to database with the central API.

Second, there is not a central API, and all of workers and other apps are connected to database directly.

Which is best way? First, second or none of these?


text:
Q: Forbidden: Unable to access VirtualHost URL in Ubuntu I just create new virtual host from path /media/rahul/142E875C2E873630/xampp/htdocs/ that's the path of my mounted drive in ubuntu. Now when I created virtual host of this url its created successfully but now, when I am opening my host url it's showing 403 Forbidden.
My shared.conf:
<VirtualHost *:80>
ServerAdmin admin@example.com
ServerName shared
ServerAlias www.shared.com
DocumentRoot /media/rahul/142E875C2E873630/xampp/htdocs
<Directory />
    Options FollowSymLinks
    AuthType None
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>
<Directory /media/rahul/142E875C2E873630/xampp/htdocs/>
    Require all granted
    Options Indexes FollowSymLinks MultiViews
    AuthType None
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

I have also add url in host file but still getting same error.
Is there any idea why this happening?
About Permissions:

A: It is all about the permissions. The system user (www-data) who runs your web server must have read permissions to the folder htdocs and to the whole path to this folder.
Here I will describe three ways how that could be done:

*

*The short way - just give enough permissions;

*The proper (according to my knowledge) way - using terminal and /etc/fstab;

*The easiest proper way - using GUI tool Disks.

1. Just give enough permissions
For this purpose open a terminal window and type:
sudo chmod 755 /media/rahul/

Or give these permissions through Nemo as it is shown in the screenshot from the question. Please remember 777 is not the best choice.

2. Make the partition part of the static file system tree: /etc/fstab
Specify static mount point and mount the partition (device) with right permissions through /etc/fstab:
1. Create an appropriate mount point - open a terminal window and type:
sudo mkdir /mnt/shared

2. Find the necessary preliminary information:

*

*Find the partition (device) identification. Type sudo blkid and recognize your target partition (device). Let's assume it is /dev/sda4 with UUID=142E875C2E873630.

*Find your user's uid (user-id) and gid (group-id). In the terminal type: id. The result shall looks something like: uid=1000(rahul) gid=1000(rahul) groups=1000(rahul),..
For further, more complicated permissions settings the data for some other users will be needed, for example id www-data will return: uid=33(www-data) gid=33(www-data),...
3. Edit your /etc/fstab file as root (using sudo) and add new line:

*

*When the device/partition is formatted under NTFS this new line could be:
/dev/sda4 /mnt/shared ntfs uid=1000,gid=33,nls=utf8,umask=0022,fmask=111 0 0

Where:

*

*/dev/sda4 the partition (device) - by /dev location or UUID - that contain a file system.

*/mnt/shared the location where the above partition (device) will be mounted.

*ntfs the type of the target device file system.

*uid=1000,gid=1000 will set ownership permissions for user and group rahul; uid=1000,gid=33 will set ownership permissions for user rahul and group www-data.

*nls=utf8 means Use UTF-8 for converting file names.

*umask=0022 will set the permissions for all folders to drwxr-xr-x or octal 755.

*fmask=111 will set the permissions for all files to -rw-rw-rw- or octal 666.

*When the partition (device) is formatted under ext4 this new line could be:
/dev/sda4 /mnt/shared ext4 default 0 0

Ant the permissions of its content can be further managed as usual - chown, chmod, etc.
4. Save the edits of /etc/fstab, and reload it: sudo mount -a.
Important note! If this is an external (USB) device, if it is unplugged, an error will be appeared. The solution is: 1) Go to Recovery mode, 2) edit /etc/fstab and 3) comment (#) the line described above.

3. Make the partition part of the static file system tree: Disks
1. Open Dash and type Disks:

2. Find your target device and select Edit Mount Options:

3. Edit Mount Options and click on OK:

4. Mount the device - click on the Play button:

Further steps
1. Find the new location of your htdocs folder. It should be something as:
/mnt/shared/xampp/htdocs

2. Edit your shared.conf file:
<VirtualHost *:80>
    ServerAdmin admin@example.com
    ServerName shared
    ServerAlias www.shared.com
    DocumentRoot /mnt/shared/xampp/htdocs
    <Directory />
        #etc ...
    </Directory>
    <Directory /mnt/shared/xampp/htdocs/>
        #etc ...
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

3. Restart Apache2 and try to access your site.

Sources and further reading

*

*Working example with an NTFS device

*Why are the default permissions for /media/username root:root?

*Permission problem on /media/user folder prevents me from accessing external media

*Accessing my NTFS folder with Apache

*Mount NTFS Partition on Startup in Ubuntu

*Fstab - make default permission 755

*How do I correctly mount a NTFS partition in /etc/fstab?

*How can I get octal file permissions from command line?

*"dmask" and "fmask" mount options

*How to mount a new drive on startup


text:
Q: Remote video forwarding using VLC through putty I'm having some problems forwarding video output using putty in a windows machine. I see it like this:

and here: https://superuser.com/a/985789/508625 they told me it was because my vlc was using the Color ASCII video output. I tried other outputs but vlc couldn't play them.
A couple of colleagues are connecting to the server using ubuntu and mac ssh commands in the console and they can see the video perfectly fine; so I think the problem is on my Windows configuration.
I'm using the latest versions of PuTTy and Xming: 0.65 and 6.9.0.31 respectively. The Putty X11 forwarding is enabled and the display uses the value returned by the $DISPLAY variable in the server. The Xming is also running. And when I test a graphic application in the command line (i.e xyes, gedit, vlc) it runs correctly. (if I close the xming, the apps don't open). Finally, I'm using Windows 10, but I've also tested it on Windows 8 with the same results.
Could it have something to do with some weird Xming configuration? What other ways are there to forward video remotely in Windows? (the server is running Ubuntu 14.04 LTS server, so there is no native graphic environment)

A: Maybe you can test with an other client ssh. There is bitvise ssh Client it's similar to Putty and include a SFTP client, a remote client and X11 fowarding too, it works fine.
Here is where you can find it: https://www.bitvise.com/ssh-client-download


text:
Q: What special property do mathematical functions and physical surfaces have that is appropriate for the case of surface plot? In the definition of surface plots in my book, (An introduction to data mining, chapter 3) it is said that:

Surface plots are often used to describe mathematical functions or physical surfaces that vary in a relatively smooth manner.

I don't understand what exactly is meant by the above sentence. What special property do mathematical functions and physical surfaces have that is appropriate for the case of surface plot?

A: Smooth in terms of mathematical functions typically means some function that is differentiable. Surface plots of naturally occurring phenomenon aren't necessarily that smooth (imagine a Fjord or a very steep cliff face), but the more jagged or irregular the data the more difficult it is to visualize the nature of the data without certain elements being occluded in the plot. Here is an example of a discontinuous function from Brunsdon, 2011

Imagine rotating the plot on the lower left so the lower surface is entirely obstructed from the view.
A good point to bring up here is also what type of data can be visualized with a surface plot. Data is typically over a regular grid (x,y) and has one unique value, z, associated with each x,y pair. Geographers sometimes call this 2.5d data. If you have truely 3 dimensional data (that is an x,y pair can have potentially multiple z values), and the data is not regular over a grid, a surface plot may not be possible nor appropriate.


text:
Q: How do i make my code continue to run even after an error? The languaged used for this code is python. So basically the cmd its having trouble replying to is a highlow cmd, this code is suppose to click high or low depend if its above or lower than the number given. I would like it to continue to run the code even if it does run into an error. If you want to you can contact me on my discord: UnPurgable#6969
This is my Code:
from requests import post, get
from utils.logger import register
from time import sleep
from json import loads

import os
path = 'Y:\\Files\\'
listing = os.listdir(path)
try:
for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass

def highlow(log, token, channel_id, timeout, logging):
    request = post(f"https://discord.com/api/v8/channels/{channel_id}/messages", headers={"authorization": token}, data={"content": "pls hl"})

    if request.status_code != 200 and logging["warning"]:
        register(log, "WARNING", f"Failed to send command `pls highlow`. Status code: {request.status_code} (expected 200). Aborting command.")
        return

    if logging["debug"]:
        register(log, "DEBUG", "Successfully sent command `pls highlow`.")

    latest_message = None

    sleep(2)

    for _ in range(0, timeout):
        sleep(1)

        request = get(f"https://discord.com/api/v8/channels/{channel_id}/messages", headers={"authorization": token})

        if request.status_code != 200:
            continue

        latest_message = loads(request.text)[0]

        if latest_message["author"]["id"] == "270904126974590976" and logging["debug"]:
            register(log, "DEBUG", "Got Dank Memer's response to command `pls highlow`.")
            break
        else:
            continue

    if (latest_message is None or latest_message["author"]["id"] != "270904126974590976") and logging["warning"]:
        register(log, "WARNING", f"Timeout exceeded for response from Dank Memer ({timeout} second(s)). Aborting command.")
        return

    number = int(latest_message["embeds"][0]["description"].split("**")[-2])

    data = {
        "application_id": 270904126974590976,
        "channel_id": channel_id,
        "type": 3,
        "data": {
            "component_type": 2,
            "custom_id": latest_message["components"][0]["components"][0]["custom_id"] if number > 50 else latest_message["components"][0]["components"][2]["custom_id"] if number < 50 else latest_message["components"][0]["components"][1]["custom_id"]
        },
        "guild_id": latest_message["message_reference"]["guild_id"],
        "message_flags": 0,
        "message_id": latest_message["id"]
    }

    request = post(f"https://discord.com/api/v9/interactions", headers={"authorization": token}, json=data)

    if (request.status_code == 200 or request.status_code == 204) and logging["debug"]:
        register(log, "DEBUG", "Successfully interacted with button on Dank Memer's response to command `pls highlow`.")
    elif logging["warning"]:
        register(log, "WARNING", f"Failed to interact with button on Dank Memer's response to command `pls highlow`. Status code: {request.status_code} (expected 200 or 204).")

This is the error i get:
File "C:\Users\Dung\Desktop\grank-2\src\main.py", line 60, in <module>
    highlow(log, token, channel_id, config["cooldowns"]["timeout"], config["logging"])
  File "C:\Users\Dung\Desktop\grank-2\src\scripts\highlow.py", line 40, in highlow
    number = int(latest_message["embeds"][0]["description"].split("**")[-2])
IndexError: list index out of range

A: List index out of range means you're trying to access an element that isn't in the list.
From this, I'd say there's only 1 element in latest_message["embeds"][0]["description"].split("**"), meaning latest_message["embeds"][0]["description"].split("**")[-**1**] exists, but latest_message["embeds"][0]["description"].split("**")[-**2**] does not.

A: The reason this is happening is because the message you got from Dank Memer is actually a cooldown message, thus meaning the code tries to get a value that isn't there. Like csjh said, just use a try and except block to make the code carry on executing if it ever encounters that error.


text:
Q: How to use GetDHtmlDocument() in MFC programming? I am trying to use

HRESULT
  GetDHtmlDocument(IHTMLDocument2
  **pphtmlDoc);

function in MFC programming.
Basically, I am trying to render GUI in a HTML View Dialog application (C++ w/ MFC) given different configuration (loading input).
So I put following code in a OnInitDialog() function.
BOOL CSampleProgramDlg::OnInitDialog()
{
    CDHtmlDialog::OnInitDialog();

    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    SetIcon(m_hIcon, TRUE);
    SetIcon(m_hIcon, FALSE);

    // My code starts from here....
    HRESULT hr = S_OK;
    IHTMLDocument2 *pphtmlDoc;

    //MessageBox(_T("If I let this MessageBox to pop-up, the code works fine."));

    hr = GetDHtmlDocument(&pphtmlDoc);

    IHTMLElement *e;
    hr = GetElement(_T("someElement"), &e);

    if (SUCCEEDED(hr))
        e->put_innerHTML(_T("
someLoadingInputWillGoHereLater
"));

    //My code ends here.....

    return TRUE;
}

As I commented out in the above code, if I let the Messagebox to pop-up the element with ID="someElement" will print out "someLoadingInputWillGoHereLater".
But if I comment out the Messagebox, GetDHtmlDocument() returns "E_NOINTERFACE" HRESULT, and it makes the code not working.
I can only guess it maybe "focus" issue. I cannot figure out the exact cause, though.
So I ask for your help. =(

A: Your calling to GetDHtmlDocument() and GetElement() will return E_NOINTERFACE.
According to my knowledge, you are not always guaranteed to have html document completely loaded when you're performing in CDHtmlDialog::OnInitDialog().
Instead, you should override CDHtmlDialog::OnDocumentComplete() in CSampleProgramDlg. It's a callback function that'll be called when document is loaded. You can assess the document then.
void CSampleProgramDlg::OnDocumentComplete(
   LPDISPATCH pDisp,
   LPCTSTR szUrl
)
{
    // You can get the document and elements here safely
}

Your calling to MessageBox() may somehow trigger the document to be loaded in advance. Though I'm not 100% sure for it.
Hope that helps.


text:
Q: selenium python runing firefox with TOR (windows) I am trying to run python selenium (firefox driver) with tor.
I checked this link (Using Selenium WebDriver with Tor) but this is the java implementation.
I am relatively new to selenium and I encounter problems in translate the java code to the Python API.
Someone encounter this issue before?

A: Here is the code that works for me in Python 2.7 (I last updated it on March 12, 2015). As an added bonus, it fills in the username and password field on agora and asks you to fill in captcha that you see then clicks the submit button. You need to create a default firefox profile that has it's proxy set to tor (127.0.0.1:9050) and fill the path to that profile name into the startbrowser function profiler variable:
from selenium import webdriver
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.common.exceptions import NoSuchFrameException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

username = 'agora username'
password = 'agora password'
def go_to_page(br):
    #page_num = page_num - 1
    #start_results = page_num * 100
    #start_results = str(start_results)
    url = 'http://agorahooawayyfoe.onion'
    print '[*] loading url: '+url
    br.get(url)
    #br.get_screenshot_as_file('agora.tiff')
    usernamed = br.find_element_by_name("username")
    usernamed.send_keys(username) # password
    passwordd = br.find_element_by_name("password") # enterCaptcha
    passwordd.send_keys(password)
    captchad = br.find_element_by_name("enterCaptcha")
    capt = raw_input('enter captcha you see on screen: ')
    captchad.send_keys(capt)
    br.implicitly_wait(3)
    br.find_element_by_name("submit").click()

def start_browser():
    profiler = webdriver.FirefoxProfile('/Users/your username/Library/Application Support/Firefox/Profiles/vxh0qxtt.tor')
    br = webdriver.Firefox(firefox_profile=profiler)
    br.implicitly_wait(10)
    return br

def main():
    br = start_browser()
    go_to_page(br)

main()


text:
Q: Python ZipFile empties file in root folder I am having issues with zipping a folder. Everything goes fine, all files that are in directories get zipped just fine. But there needs to be a version file in the root of the zip file, and when I zip it, and then unzip, the file is empty, 0 bytes.
This is the code I am using in Python to zip a directory recursively:
from contextlib import closing
import os
from zipfile import ZipFile, ZIP_DEFLATED

def zipdir(self, basedir, archive_name):
    """Zip a directory."""
    assert os.path.isdir(basedir)
    with closing(ZipFile(archive_name, "w", ZIP_DEFLATED)) as z:
        for root, dirs, files in os.walk(basedir):
            for fn in files:
                filepath = os.path.join(root, fn)
                zfn = filepath[len(basedir) + len(os.sep):]
                z.write(filepath, zfn)

The dir structure is as follows:
/root
   version.file
   /somedir
      file1
      file2
      file3
   /anotherdir
      file1
      file2
      file3
   /etcdir
      file1
      file2
      file3

When I zip root, the version.file is empty (e.g. 0 bytes), and I have no idea why.
Regards


text:
Q: Breaking a monolith into microservices using templates for similar apps I have a huge monolith application, a ASP.NET MVC Framework service offering ~50 different "groups" of unrelated data, separated into 50 different controllers/business logics. I was tasked into breaking this monolith into 50 microservices (each one hosted in Docker containers).
What I'm planning to do is to create a "template application" using ASP.NET Core to serve as a reference project and, for each of those 50 applications, I will fork this "template" project, add the corresponding controller with the necessary business logic and may need or not to customize this template to add some specific features.
For example, one application may need to respond to requests using a CSV format instead of the JSON, which is the standard for ~45 apps. So, I would modify the "template project" to include this "CSV response" feature and it would be used by the other ~4 projects that would use it.
What I can see currently:
PROS

*

*Developing a ASP.NET Core application is easy, but it requires some configurations and customizations (CORS, Cache, routes, etc.) that would be already defined into "my company template" project.

CONS

*

*Forking and merging the template project can be troublesome. If we find a security issue in the template, it would be necessary to manually update all of the 50 projects and fix some potential merge conflicts.

Is there another option available in ASP.NET Core to make this "template" project easier for updates and maintenance? Or a design pattern for this?

A: Just use a class library. Common functionality and even base controllers and such can all go there and be referenced by the actual API projects. Your common config can be added to the class library as IServiceCollection extensions:
public static class IServiceCollectionExtensions
{
    public static IServiceCollection AddMyCors(this IServiceCollection services)
    {
        services.AddCors(...);
        return services;
    }

    ...
}

Then, any change to this library automatically propagates to your APIs because of the direct reference.
However, bear in mind, that pretty much the entire point of microservices is loose-coupling. You should really only share this kind of functionality for things that are relatively static and won't change. Making changes that requires every single one of 50 services to be updated, pretty much defeats the entire point.
If there's too much common, shared functionality, you have to ask yourself if you've truly decomposed the services into subdomains. A very common mistake in this way is not realizing that the actual data should be segregated as well. Ideally, each microservice should have its own data store (database, for example). If you are trying to make the microservices share the same data store, then you will inevitably end up with significant cross-over and it will be difficult if not impossible to segregate their domains. That means you loose niceties like foreign keys sometimes and you may need to even incur some data duplication. That's where CQRS, event sourcing, and other related patterns start to come into play.


text:
Q: .net Serialization/Deserialization of complex types I'm trying to deserialize an object which was serialized with an earlier version of the same assembly (strong named), so only the version number is different (same application, same assembly, class hasn't changed). I use the BinaryFormatter for serializing/deserializing.
I created a custom SerializationBinder which takes care of the version number problem. This works fine for simple classes.
Now the problem is, my class has a dataset member with objects of another class in it. This is where the deserialization fails. Is there any possibility, I can deserialize these objects at all?
We have lots of customers who have serialized objects in their databases, so it should be possible to deserialize them with newer versions too without changing the serialization concept in general. Deserialization worked for all the years but now we had to change the version number of our assemblies which causes the problem.
The code is too complex to post the whole thing, I narrowed it down to a simple example which throws the same exception when it comes to deserializing.
ClassA - Class to serialize,
ClassB - Objects of ClassB in ClassA.dataset
<Serializable()> _
Public Class ClassA
    Public ID As Int64
    Public data As DataSet
End Class

<Serializable()> _
Public Class ClassB
    Public str As String = ""
    Public num As Int64
End Class

Initializing of the object to serialize and method calls for serializing and deserializing
Imports System
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports serialisierung

Public Class Form1

    Private Sub btnSerialize_Click(sender As Object, e As EventArgs) Handles btnSerialize.Click

        Try

            Dim myClassA As ClassA = Nothing
            myClassA = New ClassA()

            myClassA.data = New DataSet
            myClassA.data.Tables.Add("ClassA")
            myClassA.data.Tables(0).Columns.Add("ClassB", GetType(ClassB))

            Dim myClassB As New ClassB()
            myClassB.str = "some String"
            myClassB.num = 3

            Dim drClassB As DataRow
            drClassB = myClassA.data.Tables(0).NewRow
            drClassB.Item("ClassB") = myClassB
            myClassA.data.Tables(0).Rows.Add(drClassB)

            Dim ser As New CSerializer
            ser.serialize(myClassA)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
      End Sub

    Private Sub btnDeserialize_Click(sender As Object, e As EventArgs) Handles btnDeserialize.Click

        Try

            Dim ser As New CSerializer
            Dim obj As ClassA = ser.deserialize()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
      End Sub
End Class

Serialization class
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

Public Class CSerializer

    Private filename As String = "C:\bin.txt"

    Public Sub serialize(obj As ClassA)

        Try

            If (File.Exists(filename)) Then
                File.Delete(filename)
            End If

            Dim stream As FileStream = File.Create(filename)
            Dim formatter As New BinaryFormatter()

            formatter.Serialize(stream, obj)
            stream.Close()

        Catch ex As Exception
        End Try

    End Sub

    Public Function deserialize() As ClassA

        Dim obj As ClassA

        Try

            Dim stream As FileStream
            Dim formatter As New BinaryFormatter()
            formatter.Binder = New AllowAllAssemblyVersionsDeserializationBinder()
            formatter.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            stream = File.OpenRead(filename)

            obj = formatter.Deserialize(stream)
            stream.Close()

        Catch ex As Exception
            Dim str As String = ex.Message
        End Try

        Return obj

    End Function

End Class

NotInheritable Class AllowAllAssemblyVersionsDeserializationBinder
    Inherits System.Runtime.Serialization.SerializationBinder

    Public Overrides Function BindToType(ByVal AssemblyName As String, ByVal TypeName As String) As System.Type

        Dim myType As Type = GetType(ClassA)
        Dim beginTypeName As String
        Dim TypeToDeserialize As Type

        If TypeName.StartsWith("System.") Then
            If TypeName.IndexOf("[") >= 0 Then
                beginTypeName = TypeName.Substring(0, TypeName.IndexOf("["))
                TypeName = String.Format("{0}[[{1}]]", beginTypeName, myType.AssemblyQualifiedName)
            End If
        Else
            AssemblyName = myType.Assembly.ToString
            TypeName = myType.FullName
        End If

        TypeToDeserialize = Type.GetType(String.Format("{0}, {1}", TypeName, AssemblyName))

        Return TypeToDeserialize

    End Function

End Class

The serialized object looks like that (saved as a file in the example, our application stores the serialized object in a database.
    ÿÿÿÿ          Qserialisierung, Version=1.2.3.4, Culture=neutral, PublicKeyToken=e3eee34ac29f76ba   NSystem.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089   serialisierung.ClassA   IDdata    System.Data.DataSet                        System.Data.DataSet   DataSet.RemotingVersion   XmlSchemaXmlDiffGramSystem.Version          ©<?xml version="1.0" encoding="utf-16"?>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="ClassA">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="ClassB" msdata:DataType="serialisierung.ClassB, serialisierung, Version=1.2.3.4, Culture=neutral, PublicKeyToken=e3eee34ac29f76ba" type="xs:anyType" msdata:targetNamespace="" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>   •<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"><NewDataSet><ClassA diffgr:id="ClassA1" msdata:rowOrder="0" diffgr:hasChanges="inserted"><ClassB xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><str>some String</str><num>3</num></ClassB></ClassA></NewDataSet></diffgr:diffgram>   System.Version   _Major_Minor_Build   _Revision           ÿÿÿÿÿÿÿÿ


text:
Q: How to escape a % in magento translation Inside Mage_Core.csv have the following line

"Please input a valid CSS-length. For example 100px or 77pt or 20em or
  .5ex or 50%."

The problem is, Magento expect this % to be a parameter, and gives me the error

"vsprintf(): Too few arguments"

How can i ignore this '%' ?

A: For a literal percent character, use %%
Reference: Magento uses vsprintf to format translations https://secure.php.net/vsprintf


text:
Q: kubectl run fails failed to discover supported resources: just setup a 3 node cluster on gke and attempted to use kubectl run to deploy a container.
I get
error: failed to discover supported resources: unable to retrieve the complete list of server APIs: metrics.k8s.io/v1beta1: an error on the server ("service unavailable") has prevented the request from succeeding

A: The error suggests that the cluster might be in an upgrading state.
For that, you can use the Google SDK and determine if it's being upgraded:
gcloud container clusters describe CLUSTER_NAME --zone ZONE/--region REGION

If not, check that you're actually pointing your kubectl tool to correct cluster:
kubectl config current-context

gcloud has the advantage that it can automatically configure your kubectl client:
gcloud container clusters get-credentials CLUSTER_NAME --zone ZONE/--region REGION

If the cluster is being in that state for quite a long time (usually several hours), there might be an error in the cluster backend (since GKE is a managed implementation of Kubernetes). If that's the case, you might want to reach out to support to review your case.


text:
Q: Java IOException while trying to copy inputstream to outputstream I'am trying to write the inputstream image to OutputStream to display the image in the browser this is the code:
try
{
    InputStream input = Filer.readImage("images/test.jpg");
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1)
    {
        responseBody.write(buffer, 0, bytesRead);
    }
}
catch(IOException e)
{
    System.out.println(e);
}

the readImage:
public static InputStream readImage(String file) throws IOException {
    try (InputStream input = new FileInputStream(file)) {

        return input;
    }
}

but I get an error while writing:
java.io.IOException: Stream Closed

any ideas?

A: The try-with-resources closes the stream when you exit the block
try (InputStream input = new FileInputStream(file)) {

ie. when your method returns.
Just remove it and take care of closing the stream at the end of your other method body.
As stated in the comments, here's a link to the official tutorial on try-with-resources.

A: Taken from oracle tutorial the resource is closed when the statement completes:

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:


text:
Q: vim-surround not working for me. s key deletes instead of surrounds Just installed the surround plugin.
New buffer, type Hello World. Say I want to surround that with quotes.
In normal mode, V to get into visual mode, s to get into surround
Except it doesn't, s deletes the entire line.

A: This can also be a key binding collision with the yankstack plugin. To fix it, append call yankstack#setup() to your .vimrc file. For more info, see the discussion on GitHub.

A: The default visual mode mapping of surround.vim is Shift-S, not lowercase s.
You can check whether it's defined with :verbose vmap S. Do the other surround.vim mappings (ys, cs, ...) work? If not, check :scriptnames and :set runtimepath? for troubleshooting.


text:
Q: I have been trying to implement a secure transmission of emailing using smtp protocol in AWS Lambda and it doesn't work It's a Spring Boot Java Lambda for secure smtp mail transmission and it does not work while it does work in another api code of Spring Boot. Whenever I run this code it gives either SecurityException on one occassion or AuthenticationException on another and when I use getDefaultInstance() method of Session instead of getInstance() it gives "cannot create a default session".
It does not even creates an object for Authenticator and gives Authentication Exception on Lambda.
---code below--
import java.util.Properties;

import javax.mail.PasswordAuthentication;
import javax.mail.Session;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class EmailConfig {

    private String username = "";
    private String password = "";
    @Bean
    public Session getEmailSession(Environment env) {
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password); // username & password coming from vault
                    }
                });
        return session;
    }
}

It's Throwing error in Lambda :
2022-02-27T04:49:42.216+05:30
Copy
software/amazon/awssdk/regions/Region: java.lang.NoClassDefFoundError
java.lang.NoClassDefFoundError: software/amazon/awssdk/regions/Region
at aws.smtp.lambda.demo.SendMessageEmailRequest.main_meth(SendMessageEmailRequest.java:47)
at aws.smtp.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:42)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
Caused by: java.lang.ClassNotFoundException: software.amazon.awssdk.regions.Region. Current classpath: file:/var/task/
software/amazon/awssdk/regions/Region: java.lang.NoClassDefFoundError java.lang.NoClassDefFoundError: software/amazon/awssdk/regions/Region at aws.smtp.lambda.demo.SendMessageEmailRequest.main_meth(SendMessageEmailRequest.java:47) at aws.smtp.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:42) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.base/java.lang.reflect.Method.invoke(Unknown Source) Caused by: java.lang.ClassNotFoundException: software.amazon.awssdk.regions.Region. Current classpath: file:/var/task/
Code below :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath />
    </parent>
    <groupId>aws.smtp.lambda</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot Lambda smtp</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>bundle</artifactId>
            <version>2.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
            <version>1.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-ses</artifactId>
            <version>1.9.16</version> </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-ses</artifactId>
            <version>1.11.561</version>
        </dependency>

    </dependencies>

</project>
package aws.smtp.lambda.demo;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.amazonaws.services.lambda.runtime.Context;
//import com.amazonaws.services.lambda.runtime.RequestHandler;
//import com.amazonaws.services.lambda.runtime.events.ScheduledEvent;

@SpringBootApplication
public class LambdaFunctionHandler /*implements RequestHandler<ScheduledEvent, String>*/ {

    //private Context applicationContext;
//  @Autowired
    private SendMessageEmailRequest reqSES = new SendMessageEmailRequest();

    /*@Autowired
    private AmazonSESSample sesSample = new AmazonSESSample();*/
    /*@Autowired
    private SimpleEmail simpleEmail = new SimpleEmail();
    */
    public LambdaFunctionHandler() {

    }
/*  public LambdaFunctionHandler(Context context) {
        applicationContext = context;
    }*/

    /*public void initialize() {
        applicationContext = new SpringApplicationBuilder(LambdaFunctionHandler.class).web(WebApplicationType.NONE)
                .run();
    }*/

    public String handleRequest(/*ScheduledEvent input,*/ Context context) throws Exception {
    /*  try {
            if(Objects.isNull(applicationContext)) {
                initialize();
            }*/
            context.getLogger().log("Input: " );
//          simpleEmail.sendMail();
//          sesSample.sendMail();
            System.out.println("Going Inside SES Class ");
            reqSES.main_meth();
            return "Hello World - " ;//+ input;
        /*}
        catch(Exception ex) {
            ex.printStackTrace();
            return "Failure";
        }*/
    }

    public static void main(String args[]) {

    }
}
package aws.smtp.lambda.demo;

import javax.mail.MessagingException;

//snippet-end:[ses.java2.sendmessage.request.import]
import org.springframework.stereotype.Service;

//snippet-start:[ses.java2.sendmessage.request.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.Body;
import software.amazon.awssdk.services.ses.model.Content;
import software.amazon.awssdk.services.ses.model.Destination;
import software.amazon.awssdk.services.ses.model.Message;
import software.amazon.awssdk.services.ses.model.SendEmailRequest;
//import software.amazon.awssdk.services.ses.model.SesException;

/**
* To run this Java V2 code example, ensure that you have setup your development environment, including your credentials.
*
* For information, see this documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
@Service
public class SendMessageEmailRequest {

 public void main_meth(/*String[] args*/) {
     System.out.println(" Inside SES Class : main_meth");
     final String USAGE = "\n" +
             "Usage:\n" +
             "    SendMessage <sender> <recipient> <subject> \n\n" +
             "Where:\n" +
             "    sender - an email address that represents the sender. \n"+
             "    recipient -  an email address that represents the recipient. \n"+
             "    subject - the  subject line. \n" ;
     System.out.println("Inside SES Class ");
      /* if (args.length != 3) {
         System.out.println(USAGE);
          System.exit(1);
        }*/

     String sender = ""; // written correctly in the original code
     String recipient = ""; // written correctly in the original code
     String subject = "Amazon SES test (AWS SDK for Java)";

     Region region = Region.AP_SOUTH_1; // failing in this line
     /*SesClient client = SesClient.builder()
             .region(region)
             .build();*/

     // The email body for non-HTML email clients
     String bodyText = "Hello,\r\n" + "See the list of customers. ";

     // The HTML body of the email
     String bodyHTML = "" + "" + "" + "
Hello!
"
             + "
 See the list of customers.
" + "" + "";

     try {
         System.out.println(" Inside SES Class : main_meth : in try block");
        // send(client, sender, recipient, subject, bodyText, bodyHTML);
         //client.close();
         System.out.println("Done");

     } catch (/*Messaging*/Exception e) {
         e.getStackTrace();
     }
 }

 // snippet-start:[ses.java2.sendmessage.request.main]
 /*public void send(SesClient client,
                         String sender,
                         String recipient,
                         String subject,
                         String bodyText,
                         String bodyHTML
 ) throws MessagingException {

     Destination destination = Destination.builder()
             .toAddresses(recipient)
             .build();

     Content content = Content.builder()
             .data(bodyHTML)
             .build();

     Content sub = Content.builder()
             .data(subject)
             .build();

     Body body = Body.builder()
             .html(content)
             .build();

     Message msg = Message.builder()
             .subject(sub)
             .body(body)
             .build();

     SendEmailRequest emailRequest = SendEmailRequest.builder()
             .destination(destination)
             .message(msg)
             .source(sender)
             .build();

     try {
         System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
         client.sendEmail(emailRequest);

     } catch (SesException e) {
         System.err.println(e.awsErrorDetails().errorMessage());
         System.exit(1);
     }
     // snippet-end:[ses.java2.sendmessage.request.main]
 }*/
}

A: Look at using the Amazon Simple Email Service if you need email functionality from either an AWS Lambda function or even a Spring Boot app. There are no issues when doing so.  You can easily send an email message using this SES Java Code:
// snippet-start:[ses.java2.sendmessage.request.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.*;
import software.amazon.awssdk.services.ses.model.Message;
import software.amazon.awssdk.services.ses.model.Body;
import javax.mail.MessagingException;
// snippet-end:[ses.java2.sendmessage.request.import]

/**
 * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SendMessageEmailRequest {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    SendMessage <sender> <recipient> <subject> \n\n" +
                "Where:\n" +
                "    sender - an email address that represents the sender. \n"+
                "    recipient -  an email address that represents the recipient. \n"+
                "    subject - the  subject line. \n" ;

          if (args.length != 3) {
            System.out.println(USAGE);
             System.exit(1);
           }

        String sender = args[0];
        String recipient = args[1];
        String subject = args[2];

        Region region = Region.US_EAST_1;
        SesClient client = SesClient.builder()
                .region(region)
                .build();

        // The email body for non-HTML email clients
        String bodyText = "Hello,\r\n" + "See the list of customers. ";

        // The HTML body of the email
        String bodyHTML = "" + "" + "" + "
Hello!
"
                + "
 See the list of customers.
" + "" + "";

        try {
            send(client, sender, recipient, subject, bodyText, bodyHTML);
            client.close();
            System.out.println("Done");

        } catch (MessagingException e) {
            e.getStackTrace();
        }
    }

    // snippet-start:[ses.java2.sendmessage.request.main]
    public static void send(SesClient client,
                            String sender,
                            String recipient,
                            String subject,
                            String bodyText,
                            String bodyHTML
    ) throws MessagingException {

        Destination destination = Destination.builder()
                .toAddresses(recipient)
                .build();

        Content content = Content.builder()
                .data(bodyHTML)
                .build();

        Content sub = Content.builder()
                .data(subject)
                .build();

        Body body = Body.builder()
                .html(content)
                .build();

        Message msg = Message.builder()
                .subject(sub)
                .body(body)
                .build();

        SendEmailRequest emailRequest = SendEmailRequest.builder()
                .destination(destination)
                .message(msg)
                .source(sender)
                .build();

        try {
            System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
            client.sendEmail(emailRequest);

        } catch (SesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        // snippet-end:[ses.java2.sendmessage.request.main]
    }
}


text:
Q: Getting selected value of listbox windows phone 7 I am trying to get the selected value from a list box on the Windows Phone 7 platform. The data in my listbox is made up of three columns, consisting of 2 text blocks and 1 image object.
How should i put the code in the way that i can get the text (The data in any of the text block) of the selected one?
Below is my code for defining the grid:
        //Define grid column, size

        Grid schedule = new Grid();

        foreach (var time in timeSplit)
        {
            timeList = time;
            //Column 1 to hold the time of the schedule
            ColumnDefinition scheduleTimeColumn = new ColumnDefinition();
            GridLength timeGrid = new GridLength(110);
            scheduleTimeColumn.Width = timeGrid;
            schedule.ColumnDefinitions.Add(scheduleTimeColumn);

            //Text block that show the time of the schedule
            TextBlock timeTxtBlock = new TextBlock();
            timeTxtBlock.Text = time;
            //Set the alarm label text block properties - margin, fontsize
            timeTxtBlock.FontSize = 28;
            timeTxtBlock.Margin = new Thickness(0, 20, 0, 0);
            //Set the column that will hold the time of the schedule
            Grid.SetColumn(timeTxtBlock, 0);

            schedule.Children.Add(timeTxtBlock);
        }

        foreach (var title in titleSplit)
        {
            titleList = title;

            //Column 2 to hold the title of the schedule
            ColumnDefinition scheduleTitleColumn = new ColumnDefinition();
            GridLength titleGrid = new GridLength(500);
            scheduleTitleColumn.Width = titleGrid;
            schedule.ColumnDefinitions.Add(scheduleTitleColumn);

            //Text block that show the title of the schedule
            TextBlock titleTxtBlock = new TextBlock();

            if (title.Length > 10)
            {
                string strTitle = title.Substring(0, 10) + "....";
                titleTxtBlock.Text = strTitle;
            }
            else
            {
                titleTxtBlock.Text = title;
            }

            //Set the alarm label text block properties - margin, fontsize
            titleTxtBlock.FontSize = 28;
            titleTxtBlock.Margin = new Thickness(60, 20, 0, 0);
            //Set the column that will hold the title of the schedule
            Grid.SetColumn(titleTxtBlock, 1);

            schedule.Children.Add(titleTxtBlock);
            //scheduleListBox.Items.Add(schedule);
        }

        foreach (var category in categorySplit)
        {
            categoryList = category;

            //Column 3 to hold the image category of the schedule
            ColumnDefinition categoryImageColumn = new ColumnDefinition();
            GridLength catImgnGrid = new GridLength(70);
            categoryImageColumn.Width = catImgnGrid;
            schedule.ColumnDefinitions.Add(categoryImageColumn);

            TextBlock categoryTxtBlock = new TextBlock();
            categoryTxtBlock.Text = category;

            //set the category image and its properties - margin, width, height, name, background, font size
            Image categoryImage = new Image();
            categoryImage.Margin = new Thickness(-50, 15, 0, 0);
            categoryImage.Width = 50;
            categoryImage.Height = 50;
            if (category == "Priority")
            {
                categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/exclamination_mark.png", UriKind.Relative));
            }
            else
                if (category == "Favourite")
                {
                    categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/star_full.png", UriKind.Relative));
                }

            Grid.SetColumn(categoryImage, 2);
            schedule.Children.Add(categoryImage);
        }

        scheduleListBox.Items.Add(schedule);
    }

Code for selected value of listbox:
    string selectedName;

    private void scheduleListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
    {
        //Get the value of selected value in scheduleListBox

        if (null != scheduleListBox.SelectedItem)
        {
            selectedName = (scheduleListBox.SelectedItem as ListBoxItem).Content.ToString();
        }
        MessageBox.Show("Selected name : " + selectedName);

    }

A: ListBoxItem.Content is the Grid you added to ListBox.Items. Then you can access Grid.Children to get added TextBlocks, resp. their Text properties.
Above is a formal answer. On another note and despite your code containing lots of white spaces, I don't believe that it can work. For example you're adding several images (textblocks) into a single grid cell. Is that intended? I don't think so. Didn't you want to use listbox itm with just one date (is it a date?), one title and one image? If so, change your logic.

A: ben tan !
you can get Tab of control :
Example:
string a = "abc"
grid myGrid = new grid();
myGrid.Tag = a;

when selectionChange you get Tab in control Grid ?


text:
Q: What's the usage of 'await 0'? Summary
I'm looking at TODO MVC Example with shadow DOM and customElements and in litRender.js there's a weird code in invalidate() function:'await 0'. I want to know what's the purpose of this code.
Background
I did a little search on Google but I couldn't find any case like that. I'm very new to javascript and Webpack so I have no idea how to debug the application(I tried to re-bundle it with --devtool option, but I got errors).
The author's explanation is(sorry for translation):

litRender.js can be found under src/libs and helps render each component of this application. Each component uses a mix of litRender in the form of class SomeComponent extends LitRender (HTMLElement). If the content is updated several times a time code is intended to help improve performance by not rendering every time, it collected the rendering time. Calling this.invalidate on a component that extends it will reserve a call to the render function defined in the component.

As the author mentioned above, invalidate() is used to render shadow DOM. Here's how the author uses it.
Main question
I want to know what does 'await 0' in litRender.js really does.

A: After one year I finally found the answer: await 0 was used in order to free event loop so browser can draw frame.
Note: My explanation is verbose and has some poor grammer usages. It may be better to read MDN doc linked above.
Since JS is designed to be a single-threaded(while there exists a web worker) languaged, it has a concurrency model called event loop. Consider a following situation:
console.log('before timeout')
setTimeout(() => console.log('inside timeout'), 0)
console.log('after timeout')

Result will be:
before timeout
after timeout
inside timeout

It can be confusing at first. You might think: The timeout was set with delay of 0, thereby it would execute its callback before executing next line of code! But that's not true.
To understand the above code, let's first see how JS handle code execution. It has a storage called stack that tracks where the current function execution was originated from.
function a() {
  console.log('a()')
}

a()
console.log('end')

In the above code, code outside brackets are executed first. Then, function a will be executed. At this point, the stack will look like this:
    a
(Main) -> code outside every brackets

If some function calls another function the called one gets stacked on the previous one. Now the function the end and JS clears it from the top of the stack, go back to previous position, execute remaining code until it reaches the end, and so on. By utilizing stack JS can figure out where to go after current function ends.
Then what happens when we execute the setTimeout? The important thing here is that setTimeout is not a language feature but a platform feature which browser deals with. The browser waits for the given time while continuing following code execution. Then the timeout ends and the browser needs to execute its callback, but the problem is that the another piece of code might still on execution. To solve this, the browser makes callback as a task and register it in task queue. Tasks in it will be executed in sequence when the stack is empty.
This explains the odd behavior of the first code snippet: setTimeout's callback gets registered as task and it waits until stack is empty. After logging the second message main code execution ends and callback finally gets executes.
Promise is handled in similar way(but as microtask). Whether or not the right side of await is a promise, every codes that needs to be exexuted after await gets registered as microtask. The main benefit of doing so is related to the fact that browser only draw frame when the stack empty. By registering remaining code as microtask stack gets empty before the microtask gets executed, therefore browser can draw frame in that timing.

A: awaitstatament must be used into a async code so as the docs say here into the description section, await will be used to pause the execution of the function until the promise is resolved or rejected, so if the statement next to await is not a promise, so JS will consider as a resolved promise.
Hope it can help you understand.


text:
Q: Dynamically Query like a return type function Dynamically Query like a return type function can we use dynamically function like a dynamically return type function in my programming area is this possible
<html>
<head>
<title>Dynamic Querys</title>
</head>
<body>
<?php
public function fun($table){
 $query="SELECT * FROM ".$table;
 return $query;

}
echo fun("student");
?>
</body>
</html>

A: You can do like this
function insert_data($table,$data){
    $sql ="INSERT INTO ".$table;
    $sql .=" (".implode(",",array_keys($data)).") VALUES";
    $sql .=" ('".implode("','", array_values($data))."')";
    $query=$conn->query($sql);
    if ($query) {
        return true;
    }
    else{
        return false;
    }
    $query->close();
}

Call upper function for insert the data into table. hope this will solve your issue
$data=array('name' => "Yasir", 'age' => 25, 'education' => "Master");
$fet=insert_data("student",$data);

A: As you want the deleting method, there it is:
   function insert_data($table,$columnName,$matchingWord){
       if($columnName == null && $matching == null || $columnName == '' && $matching == ''){
          $sql= "DELETE FROM".$columnName." WHERE 1";
       }
       else{
          $sql = "DELETE FROM".$columnName."WHERE".$columnName."=".$matchingWord."";
       }
       $query=$conn->query($sql);
       if ($query) {
            return true;
       }
       else{
            return false;
       }
        $query->close();
    }

call upper function just like this.
  insert_data("users","id","3");

It will delete the user where the id is equals to 3.
And if you will not give $columnName & $matchinWord it will automatically truncate the table.


text:
Q: My RichTextBox change backgroundcolor when Enabled is set to false How can I set the backgroundcolor and fontcolor to be "normal" on a disabled (i.e. Enabled = false) RichTextBox?
Thanks

A: Windows User Interface guidelines demand that a control that is disabled appears disabled.  With the obvious benefit that the user can tell that it won't make sense to keep banging the mouse on the control, trying to set the focus to it.  Like all controls in the toolbox, RichTextBox implements this guideline as well.  Overriding its painting behavior is not practical.  Consider the ReadOnly property.

A: Emulate the property of being disabled. Implement a property that when set to false the control won't get focus or all key strokes are ignored.
Pretty bizarre in my opinion but the programmer wants what the programmer wants! ;-]

A: I would create a new control that inherits from RichTextBox. You could the override the BackColor property to always return something like white for example. Something similar could be done with the font color. Off the top of my head I think you could do something such as:
class CustomRichTextBox : System.Windows.Forms.RichTextBox {
     public override System.Drawing.Color BackColor {
          get { return System.Drawing.Color.White; }
          set { base.BackColor = System.Drawing.Color.White; }
     }
}

Though that may not work because you would probably have to override the OnPaint method to get around default greyed out behavior.
Another option would be to simply use  the readonly property instead. ReadOnly is almost the same as enabled = false, except that you can actually still click in the text box (you just can't edit it). When it is readonly, you still have control over the normal color properties without having to override anything.
If you wanted to be even more creative, you could add a delegate to the Enter event of the RichTextBox that set the focus to some other control to prevent the user from even clicking in the box (which enabled doesn't let you do)


text:
Q: Best way to initialize unknown types with parameters? I'm trying to genericize some of our code by being able to instantiate objects that inherit from a base class without knowing the types of those objects.  So I want to just be able to drop a dll in a directory and be able to instantiate those objects.
I was looking into MEF, but I can't export the parameters because they're not defined in code (loaded from a database).  So it doesn't look like MEF is the way to go.
Reflection works great, but that seems too fragile to rely on.
Is there something I'm missing that would allow me to do this with MEF, is there another framework that would allow me to do this better, or is reflection simply the answer here?

A: If you only would spawn instance form a dll (assembly) on which you don't know anything could try do something like that :
_binaryData = File.ReadAllBytes(_path);
temporary   = Assembly.Load(_binaryData);

foreach (Type type in temporary.GetTypes().Where(x =>  typeof(IBase) ).IsAssignableFrom(x))
    var istance = (IBase) FormatterServices.GetUninitializedObject(x)

I do not recomend to do that, i suggest another aproach, store auxiliary information on that dll before load it or use attribute on type of your dll to help furhter analisis (and then loading).


text:
Q: Laravel custom user verification email issue In my laravel application i'm trying to create a customized user verification email template.
First I created a folder called, Notifications inside the App, Inside my Notifications folder I have a file called CustomVerifyEmailNotification.php
app/Notifications/CustomVerifyEmailNotification.php

Following is my code inside the CustomVerifyEmailNotification.php
<?php

namespace Illuminate\Auth\Notifications;

use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\URL;

class CustomVerifyEmailNotification extends Notification
{
    /**
     * The callback that should be used to build the mail message.
     *
     * @var \Closure|null
     */
    public static $toMailCallback;

    /**
     * Get the notification's channels.
     *
     * @param  mixed  $notifiable
     * @return array|string
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Build the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $verificationUrl = $this->verificationUrl($notifiable);

        if (static::$toMailCallback) {
            return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl);
        }

        return (new MailMessage)
            ->subject(Lang::get(''.('sentence.Verify Email Address').''))
            ->line(Lang::get(''.('sentence.If you did not create an account, no further action is required.').''));
    }

    /**
     * Get the verification URL for the given notifiable.
     *
     * @param  mixed  $notifiable
     * @return string
     */
    protected function verificationUrl($notifiable)
    {
        return URL::temporarySignedRoute(
            'verification.verify',
            Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
            [
                'id' => $notifiable->getKey(),
                'hash' => sha1($notifiable->getEmailForVerification()),
            ]
        );
    }

    /**
     * Set a callback that should be used when building the notification mail message.
     *
     * @param  \Closure  $callback
     * @return void
     */
    public static function toMailUsing($callback)
    {
        static::$toMailCallback = $callback;
    }
}

Then I changed my User.php according to following code
<?php

namespace App;

use App/Notifications/CustomVerifyEmailNotification;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable,Billable;
    use HasRoles;

     public function sendEmailVerificationNotification()
    {
        $this->notify(new CustomVerifyEmailNotification);
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = [
        'name','last_name', 'email', 'password','username','mobile','propic','user_roles','user_source',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

But,
use App/Notifications/CustomVerifyEmailNotification;

showing me an error saying syntax error, unexpected '/', expecing ';' or ','
Because of that I'm also getting an error here
public function sendEmailVerificationNotification()
    {
        $this->notify(new CustomVerifyEmailNotification);
    }

error is, undefined type 'App\CustomVerifyEmailNotification'
How can I fix this issue and create this custom verification email
I'm using laravel 6

A: The namespace should be
namespace App\Notifications

and not
namespace Illuminate\Auth\Notifications;

And in the user.php instead of
use App/Notifications/CustomVerifyEmailNotification;

you should use
use App\Notifications\CustomVerifyEmailNotification;


text:
Q: How to keep the caret on the same place in my contenteditable div while clicking buttons? I am trying to create an icon in my contenteditable div after clicking on a button with the icon. The issue is that while selecting the icon/button I lose the caret in the text. I want this caret back at its old place after closing the buttons.
I made a JS-Fiddle to illustrate the issue: JSFiddle
PS: The question is especially about the caret. It doesn't matter a lot to me if the icon is inserted or not. That part should be easy to figure out :).
html

How to return the caret where it was in the sentence after clicking the buttons?

Maybe prevent the caret from being removed after clicking the buttons?

I know I can store the current selection by using window.getSelection(). If I would be able to reactivate this selection, that would be great!

        <button>✔</button>
        <button>✯</button>
        <button>✘</button>

        <button class="add-icon">Add Icon</button>

css
#new-mail-content{
  background-color: white;
  min-height: 5em;
}
#write-mail button{
  height: 30px;
}
#emotepicker{
  display: none;
  position: absolute;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background-color: rgba(0,0,0,0.1);
  text-align: center;
}
div{
  padding: 2px;
}

jquery/javascript
$(".add-icon").click(function(){
    $("#emotepicker").toggle();
});

A: Use the jquery focus method in your click event method.
You might want to make the new-mail-content div into a text area. Something like this should work.
$(".add-icon").click(function(){
    $("#emotepicker").toggle();
    $("#new-mail-content").focus();
});

Here is a link to the documentation: https://api.jquery.com/focus/

A: This should do what you need:
var caretpos =0 ;
$(".add-icon").click(function(){
    $("#emotepicker").toggle();
});

$('#close').click(function(e){
    $("#emotepicker").toggle();
  $("#new-mail-content").focus();
  var node = document.querySelector("new-mail-content");
  node.focus();
  var textNode = node.firstChild;
  var caret = caretpos;
  var range = document.createRange();
  range.setStart(textNode, caret);
  range.setEnd(textNode, caret);
  var sel = window.getSelection();
  sel.removeAllRanges();
  sel.addRange(range);
})

function getCaretCharacterOffsetWithin(element) {
    var caretOffset = 0;
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
            var range = win.getSelection().getRangeAt(0);
            var preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        var textRange = sel.createRange();
        var preCaretTextRange = doc.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
}

function showCaretPos() {
    var el = document.getElementById("new-mail-content");
    var caretPosEl = document.getElementById("caretposition");
    caretpos = getCaretCharacterOffsetWithin(el);
    caretPosEl.innerHTML = "Caret position: " + carePosEl;
}

document.body.onkeyup = showCaretPos;
document.body.onmouseup = showCaretPos;

https://jsfiddle.net/bdy2Ltwo/4/


text:
Q: React-router-dom: How to update the props on a wrapper component? I have my App component like this:

const App = (props) => (
  <BrowserRouter>
    <PageTheme {...some props I'd like to change on route change}>
      <Switch>
        <Route exact path="/example">
          <Example {...props} />
        </Route>
        <Route exact path="/example/detail/:exampleId">
          <ExampleDetail {...props} />
        </Route>
      </Switch>
    </PageTheme>
  </BrowserRouter>
);

The PageTheme component wrapping the Switch has some navigation UI, as well as some options about a page's background color, etc..  Is there a way to provide PageTheme some specific props for each route? Or is the best option to put a new PageTheme component inside of each Route? Thanks!

A: What you can do is to use withRouter and wrap PageTheme with it:
export default withRouter(PageTheme);

Or use useLocation hook if PageTheme is function component. Than you will have access to location and do your magic based on current route/url.


text:
Q: How to make a div autoscroll like flickr home page I want to make a login page like flickr website. I tried to learn how they designed it and the conclusion was they made a div autoscroll. My question is how to make a div auto scrollable on page load. And if there is any other way to achieve the same design then share.

A: I don't know what flickr is but this is an auto scrolling div curtesy of sitepoint: https://www.sitepoint.com/community/t/auto-scrolling-a-div-with-overflow-scroll-auto/2291 I imagine it would be easy enough to bend this to what you are looking for, make it horizontal etc.

 Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.


text:
Q: Twitter Boostrap 3 page is not responsive I created a sample page with a header containing an image. But the page is not responsive. I added the class img-responsive to the img tag but yet it is not responsive. Here is the code:
<!DOCTYPE html>

        <title>A Sample Bootstrap Page</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="css/style.css" rel="stylesheet">

Some text here

The style.css includes the following:
#header #logo
{
    display: block;
    margin-left: auto;
    margin-right: auto;
}

A: Remove the img tag height="100" as suggested above and add this to your style.css
#header #logo {
   display: block;
   margin-left: auto;
   margin-right: auto;
   height: 100px;
}

As for the image not being responsive make sure the bootstrap style for .img-responsive is being used
In firebug/developer tools you should see a class of
.img responsive {
   max-width: 100%;
   height: auto;
   display: block;
}

As for resolving your issue I'll be glad to solve it if you can make a codepen/snippet example for me to see/look at

A: You should do like this,even needn't use custom class to style, bootstrap provided enough.

<!DOCTYPE html>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  <meta charset="utf-8">
  <title>JS Bin</title>


text:
Q: Trying to create a project in a sub folder gives " overlaps the location of another project" error I'm new to Java / Eclipse.
I've opened eclipse and set the workspace to a folder named MyBook.
Next I want to create a bunch of projects in subfolders of the workspace.  I want to create a project in MyBook\Ch-01\MyExampleApple and then create a project in MyBook\Ch-02\MyExampleBanana, etc...  When I try to create the first project I get the error "MyBook\Ch-01\MyExampleApple overlaps the location of another project Ch-01".
How do I create a new project in a sub folder of the workspace?  Do I need to change the workspace to match the subfolder before I can create the project?
[The product I currently use doesn't have the concept of a workspace, and you always specify the full location of any new project.  Please let me know what the correct procedure is for this in Eclipse.]

A: 1-Take for workspace "MyBook"
2-In eclipse, create a "Java project" ch-01.
3-right click on ch-01 , new, project "MyExampleApple"
for each folder like ch-01 do number 2 and 3.
:)
This will create a subFolder in your Workspace and a project inside this subFolder.
workspace  subfolder   project
MyBook    \Ch-01      \MyExampleApple
:D


text:
Q: React play different audio files at once - working with different refs I'm creating a small app that plays an audio file and have some functionalities (loop, stop, mute). My goal is to add some more audio files that all should be played and stopped at once (one button to control all), but each will have a mute button, and  I'm not sure what is the best practice to do so. I used useRef and thought maybe I need to set a refs array but how will I be able to start/stop them all at once, but still have the ability to control the mute separately?
This is my code so far. I guess I should split and have a different component for the audio sounds. Thanks for helping!
import React, {useState, useRef, useEffect} from 'react'
import {ImPlay2} from "react-icons/im"
import {ImStop} from "react-icons/im"
import styled from "styled-components"
import drums from '../loopfiles/DRUMS.mp3'
//import other audio files//

const AudioPlayer = () => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [isLooping, setIsLooping] = useState(false);
    const [isOnMute, setIsOnMute] = useState(false);
    const audioRef = useRef(new Audio(drums));

    useEffect(() => {
        if (isOnMute) {
            audioRef.current.volume=0;
        }
        else {
            audioRef.current.volume=1;
        }
      }, [isOnMute]);
    useEffect(() => {
        if (isPlaying) {
            audioRef.current.play();
        } else {
            audioRef.current.pause();
            audioRef.current.load();
        }
      }, [isPlaying]);
      useEffect(() => {
        if (isLooping) {
            audioRef.current.loop = true;
        } else {
            audioRef.current.loop = false;
        }
      }, [isLooping]);
  return (

        {!isPlaying ? (
        <button type="button"
        className="play"
        onClick={() => setIsPlaying(true)}>
        <ImPlay2></ImPlay2> Play
        </button>
        ) : (
        <button type="button"
        className="pause"
        onClick={() => setIsPlaying(false)}>
        <ImStop></ImStop> Stop
        </button>
        )}
        <Flex>
            <Switcher selected={isLooping} />
            <Text
            onClick={() => setIsLooping(true)}>
            Loop
            </Text>
            <Text
            onClick={() => setIsLooping(false)}>
            Unloop
            </Text>
        </Flex>
        <Flex>
            <Switcher selected={isOnMute} />
            <Text
            onClick={() => setIsOnMute(true)}>
            Mute
            </Text>
            <Text
            onClick={() => setIsOnMute(false)}>
            UnMute
            </Text>
        </Flex>

  )
}
const Flex = styled.div`
  margin-top: 5px;
  display: flex;
  align-items: center;
  border-radius: 2px;
  background: grey;
  height: 20px;
  width: 120px;
  position: relative;
  margin-bottom: 5px;
`;
const Switcher = styled.div`
  background: black;
  border-radius: 2px;
  height: 20px;
  line-height: 41px;
  width: 50%;
  cursor: pointer;
  position: absolute;
  transition: 0.5s;
  -webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  z-index: 1;
  left: ${({ selected }) =>
    selected === true ? "0px" : "60px"};
`;

const Text = styled.div`
  color: ${({ selected }) => (selected ? "black" : "white")};
  font-size: 13px;
  font-weight: 20;
  line-height: 4px;
  padding: 30;
  width: 50%;
  text-align: center;
  cursor: pointer;
`;
export default AudioPlayer

A: If you would like to mute/unmute individual sounds, but play/pause all sounds together, then you will need to create a mute/unmute slider for each sound. I can think of a number of ways to do this. The "best choice" might depend upon the standards in the rest of the application, how many sounds you're importing, and whether they're likely to change.
Method 1: One way to do this would be creating one array containing isOnMute values for each sound and another array containing all refs, and then map(...) over each of the elements of the isOnMute array to create your sliders.
Method 2: Another way would be to have one array of objects containing all sounds, and then the ref and the isOnMute values could be stored within each object. You could map(...) over that to create your sliders as well.
Method 3: You could also create separate child components for each sound like you said, and then pass the mute property between the parent AudioPlayer and the child AudioChannel components.
Then anytime the play/pause button is clicked, you would need to update each of the refs in the array (via a forEach or each of the child components via toggling a single isPlaying property).
Regardless of which you choose, I also might like to recommend the use-sound npm package. It makes managing multiple sounds and their properties a little bit less cumbersome in my opinion, including the ability to play and pause with a single method call.

A: Here is a snippet for you/
Also do not forget to use according ids instead of idx and idx2
const AudioList = () => {
  /* here populate the array in format: array of objects
  {
    drums: mp3file,
    isPlaying: boolean,
    setIsPlaying: boolean,
    isLooping: boolean,
    setIsLooping: boolean,
    isOnMute: boolean,
    setIsOnMute: boolean,
  }[]
   */

  const [audios, setAudios] = useState([
    { isPlaying: true, isOnMute: false, isLooping: true, drums: "Your mpr" },
  ]); // use initial audios

  return (

      <button
        onClick={() => {
          // similar to start all, mute all, you have full controll logic over all elements
          // also you could implement add new audiofile, or delete, similar logic :)
          setAudios((audios) =>
            audios.map((audio) => ({ ...audio, isPlaying: false }))
          );
        }}
      >
        Stop all
      </button>

        {audios.map((audio, idx) => (
          <AudioPlayer
            key={idx}
            {...audio}
            setIsPlaying={(val) =>
              setAudios((audios) =>
                audios.map((audio, idx2) =>
                  idx === idx2 ? { ...audio, isPlaying: val } : audio
                )
              )
            }
            // similar for setMute and setLopping function,
            // i think you can figure it out, it is just a snippet:)
          />
        ))}

  );
};

const AudioPlayer = ({
  drums,
  isPlaying,
  setIsPlaying,
  isLooping,
  setIsLooping,
  isOnMute,
  setIsOnMute,
}) => {
  const audioRef = useRef(new Audio(drums));

  // also you have full controll of element inside component
  useEffect(() => {
    if (isOnMute) {
      audioRef.current.volume = 0;
    } else {
      audioRef.current.volume = 1;
    }
  }, [isOnMute]);
  useEffect(() => {
    if (isPlaying) {
      audioRef.current.play();
    } else {
      audioRef.current.pause();
      audioRef.current.load();
    }
  }, [isPlaying]);
  useEffect(() => {
    if (isLooping) {
      audioRef.current.loop = true;
    } else {
      audioRef.current.loop = false;
    }
  }, [isLooping]);
  return (

      {!isPlaying ? (
        <button
          type="button"
          className="play"
          onClick={() => setIsPlaying(true)}
        >
          <ImPlay2></ImPlay2> Play
        </button>
      ) : (
        <button
          type="button"
          className="pause"
          onClick={() => setIsPlaying(false)}
        >
          <ImStop></ImStop> Stop
        </button>
      )}
      <Flex>
        <Switcher selected={isLooping} />
        <Text onClick={() => setIsLooping(true)}>Loop</Text>
        <Text onClick={() => setIsLooping(false)}>Unloop</Text>
      </Flex>
      <Flex>
        <Switcher selected={isOnMute} />
        <Text onClick={() => setIsOnMute(true)}>Mute</Text>
        <Text onClick={() => setIsOnMute(false)}>UnMute</Text>
      </Flex>

  );
};

A: I changed the following:
I added Audios.js containing:
const audios = () => {
    return [
        {
            color: 'lightgreen',
            isOnMute: false,
            audio: drums,
            title: 'Drums'
        }, ...

AudioList.js:
const AudioList = ({isPlaying, isLooping}) => {
    const [audioToPlay, setAudioToPlay] = useState();
    useEffect(()=> {
        setAudioToPlay(audios())
    },[]) ....//and mapped through <AudioItem>:

AudioItem.js:
  const AudioItem = ({audio, isPlaying, isLooping}) => {
  const [isOnMute, setIsOnMute] = useState(false);
  const audioRef = useRef(null);
  useEffect(() => {
    if (isLooping) {
        audioRef.current.loop = true;
    } else {.... //other functionality

added a progressBar.js:
const ProgressBar = ({isPlaying}) => {
const [completed, setCompleted] = useState({
    count: 0
});const intervalId = useRef(null)

useEffect(() => {...

ControlPanel.js:
const ControlPanel = ({
setIsLooping, isLooping, isPlaying, setIsPlaying}) => {
      return (

        <PlayButton> //....

and Home.js containing controlpanel, AudioList, ProgressBar:
const Home = () => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [isLooping, setIsLooping] = useState(false);

  return (

        <ControlPanel
         setIsLooping={setIsLooping} //....


text:
Q: Apache/php redirect loop Here is the situation in the smallest explanation I can give.
From php, I do a redirect with the following function
function redirect($loc)
{
    session_write_close();
    header("Location: $loc");
    exit();
}

For example, redirect('http://www.google.com/');
The problem is that when I attempt to do redirect('https://local.application.com') the browser gets a header that says Location: https://local-apps.application.com. https://local-apps.application.com is the uri that the original request comes through.
I've used xdebug to step through the php code right up to header('Location: $loc'); call and I can verify 100% that $loc == 'https://local.application.com' because xdebug tells me so. However, for SOME reason, the browser gets Location: https://local-apps.application.com. This causes an infinite loop as https://local-apps.application.com once again redirects to https://local.application.com.
What is maybe going on?!
The extremely weird part is that putting the SAME EXACT code in our qa environment yields the expected behavior and NO INIFINITE loop is caused. In qa the urls are qa-apps.application.com and qa.application.com.
I don't know if my local Apache is doing this. I doubt it's php's fault because xdebug shows me for certain that the $loc variable is set to the right uri and I'm doing an exit right after.
I've also tried using Charles web proxy to act as a man in the middle to look at traffic but it also shows Location: https://local-apps.application.com instead of the expected Location: https://local.application.com.
Is there an Apache setting that would alter outgoing headers? What should I do?
EDIT 1
I altered my Apache access log to print out the Location header in the response and it is the correct value. So apache isn't doing anything weird here.
EDIT 2
I removed all entries from my /etc/hosts file. I then installed dnsmasq and set it up as the primary DNS server for my computer. I tested this by doing dig @127.0.0.1 local.application.com and then dig @127.0.0.1 www.google.com to make sure I had set it up correctly.
I added address=/local.application.com/127.0.0.1 and address=/local-apps.application.com/127.0.0.1 to the dnsmasq config and restarted dnsmasq. I even restarted my computer after setting it up as a daemon that starts on reboot.
I get the same weird behavior on my local machine. My webbrowser goes into an infinite loop.
More info if you are curious
I'm putting together an oauth2 implementation in my workplace.
The authorize point exists on my local machine at local-apps.application.com/authorize (local-apps) because that's where mobile apps will access it. In production it would be apps.application.com/authorize. (Sorry, I can't control the subdomains being used).
Depending on the client_id in the initial oauth2 auhorize request I will first redirect to a client appropriate domain. From local-apps.application.com/authorize I'll go to local.client-1.com/authorize and then from there I would redirect to local.client-1.com/login if the oauth2 credentials are validated successfully.. Why the extra redirect? 1. A limitation in the way our templating system works and the fact that it depends on the domain to load the proper html. 2. The sessions for php don't transfer across domains so I have to start the php session on the right domain. I can't change it. I just have to deal with it. Please don't make suggestions related to this url scheme thingy. I just want to know why php redirects to one url and the browser get a different url in the header.

A: It seems, you have a same ip addresses in /etc/hosts file or you can check your Apache virtual host file to make sure the correct path.
Note: Apache configuration files location and directory structure depends on the linux distro.


text:
Q: How to fix FPS Cap on my Gaming Laptop EDIT: Any type of power saving thing is DISABLED and is currently not active on my Computer, this includes NVIDIA BatteryBoost and Windows Power Options. I am 95% sure that Power Savings is not a factor in this problem (the 5% is some application that I may have that does it without me knowing, excluding GeForce Experience) although there still is a chance that it could be that.
It's as basic as that. I have an Asus ROG G751JL with an Intel i7-4720HQ CPU and GTX 965m GPU.
For some strange reason, I've noticed that my PC loves to CAP the framerate when the GPU can not maintain a certain Framerate so it locks the framerate at something and uses less of my GPU.
I'm sorry if I sound vague but what I am saying is this: let's say The Forest is currently running at (true story) 43 FPS, 2-5 seconds later the framerate locks at 40 and never goes up or down no matter how hard I try. I have GPU-Z on my secondary monitor and I see that GPU usage is never at 100%. I understand that not all games use the GPU's full raw power but what's weird is the GPU usage is always jumping between 76-96%, the lower usage, lower FPS obviously.
I wonder if this is the NVIDIA GameReady driver at work keeping a stable "good looking" FPS, or it's my laptop itself. I tried switching the power mode to 'Prefer Maximum Performance' in the Control Panel but all that does is force the GPU to run at its full turbo boost clock and doesn't change the FPS lock that happens to my games.
This happens to ALL my games, even simple generic 3D applications. Any help will be greatly appreciated. I will look at this question for the next few weeks daily. Thanks for any replies (even if they are no help at all)!

A: Are you using BatteryBoost?
NVIDIA BatteryBoost extends battery life by limiting the maximum frame rate. This reduces the load on the GPU and therefore power consumption. You should be able to adjust or disable this feature in GeForce Experience.

A: For me it had to do with the laptops G-Sync.
Games run much faster and responsive (even tho screen tearing happens now)
Open "Nvidia control panel", click "setup G-Sync" and uncheck the box "Enable G-Sync" and click apply.