Q: Chained creational OOP design pattern problem I am creating a class that is responsible for validating a configuration. This class calls other classes that validate said config by creating new instances in the form of a chain. At first glance, the code structure looks horrible, but It works. Anyway, I think it's not the best way to handle this logic.
I leave here a simplified version of the code in TypeScript, but I also leave it in Python and Java for reference only:
class Validator {
    private _notValidatedConfig: NotValidatedConfig

    constructor(notValidatedConfig: NotValidatedConfig) {
        this._notValidatedConfig = notValidatedConfig
    }

    validateConfig(): ValidatedConfig {
        return (
            new Phase4Validation(
                new Phase3Validation(
                    new Phase2Validation(
                        new Phase1Validation(
                            this._notValidatedConfig
                        ).validate()
                    ).validate()
                ).validate()
            ).validate()
        )
    }

    // Alternative
    validateConfig2(): ValidatedConfig {
        const validatedPhase1Config: ValidatedPhase1Config = new Phase1Validation(this._notValidatedConfig).validate()
        const validatedPhase2Config: ValidatedPhase2Config = new Phase2Validation(validatedPhase1Config).validate()
        const validatedPhase3Config: ValidatedPhase3Config = new Phase3Validation(validatedPhase2Config).validate()
        const validatedPhase4Config: ValidatedPhase4Config = new Phase4Validation(validatedPhase3Config).validate()
        return validatedPhase4Config;
    }
}

*

*Python

*Java Disclaimer: I don't have any experience with Java, so maybe there are some syntax errors.

The "alternative" is the same code, but not directly chained, instead, for every validation, it's creating a new variable.
I think the "alternative" is more readable but performs worse.
What do you think about this code? what did you change? How would you face this problem or with what design pattern or framework? (programming language doesn't matter for these question)

A: I would create a base class Validation and just create derived classes from it if it is necessary to add new validation:
public abstract class Validation
{
    public Validation(string config)
    {

    }

    public abstract string Validate();
}

and its concrete implementations:
public class Phase1Validation : Validation
{
    public Phase1Validation(string config) : base(config)
    {}

    public override string Validate()
    {
        if (true)
            return null;

        return "There are some errors Phase1Validation";
    }
}

public class Phase2Validation : Validation
{
    public Phase2Validation(string config) : base(config)
    {

    }

    public override string Validate()
    {
        if (true)
            return null;

        return "There are some errors in Phase2Validation";
    }
}

and then just create a list of validators and iterate through them to find errors:
public string Validate()
{
    List<Validation> validations = new List<Validation>()
    {
        new Phase1Validation("config 1"),
        new Phase2Validation("config 2")
    };

    foreach (Validation validation in validations)
    {
        string error = validation.Validate();
        if (!string.IsNullOrEmpty(error))
            return error;
    }

    return null; // it means that there are no errors
}

UPDATE:
I've little bit edited my classes to fit your new question requirements:

*

*validations should be ordered. Added Order property

*get config from previous validation and send it to the next validation

It can be seen that this approach allows to avoid to write nested classes like this:
new Phase4Validation(
   new Phase3Validation(
      new Phase2Validation(...).validate()
   ).validate()
).validate()

So you can add new classes without editing validation classes and it helps to keep Open CLosed Principle of SOLID principles.
So the code looks like this:
Abstractions:
public abstract class Validation
{
    // Order to handle your validations
    public int Order { get; set; }

    // Your config file
    public string Config { get; set; }

    public Validation(int order)
    {
        Order = order;
    }

    // "virtual" means that method can be overriden
    public virtual string Validate(string config)
    {
        Config = config;

        if (true)
            return null;

        return "There are some errors Phase1Validation";
    }
}

And its concrete implementations:
public class Phase1Validation : Validation
{
    public Phase1Validation(int order) : base(order)
    {
    }
}

public class Phase2Validation : Validation
{
    public Phase2Validation(int order) : base(order)
    {
    }
}

And method to validate:
string Validate()
{
    List<Validation> validations = new List<Validation>()
    {
        new Phase1Validation(1),
        new Phase2Validation(2)
    };

    validations = validations.OrderBy(v => v.Order).ToList();
    string config = "";
    foreach (Validation validation in validations)
    {
        string error = validation.Validate(config);
        config = validation.Config;
        if (!string.IsNullOrEmpty(error))
            return error;
    }

    return null; // it means that there are no errors
}

A: I leave here my own answer, but I'm not going to select it as correct because I think there exist better answers (besides the fact that I am not very convinced of this implementation).
A kind of Decorator design pattern allowed me to do chain validation with greater use of the dependency injection approach.
I leave here the code but only for Python (I have reduced the number of phases from 4 to 2 to simplify the example).
from __future__ import annotations

import abc
from typing import cast
from typing import Any
from typing import TypedDict

NotValidatedConfig = dict
ValidatedConfig = TypedDict("ValidatedConfig", {"foo": Any, "bar": Any})

class InvalidConfig(Exception):
    ...

# This class is abstract.
class ValidationHandler(abc.ABC):
    _handler: ValidationHandler | None

    def __init__(self, handler: ValidationHandler = None):
        self._handler = handler

    # This method is abstract.
    @abc.abstractmethod
    def _validate(self, not_validated_config: NotValidatedConfig):
        ...

    def _chain_validation(self, not_validated_config: NotValidatedConfig):
        if self._handler:
            self._handler._chain_validation(not_validated_config)
        self._validate(not_validated_config)

    def get_validated_config(self, not_validated_config: NotValidatedConfig) -> ValidatedConfig:
        self._chain_validation(not_validated_config)

        # Here we convert (in a forced way) the type `NotValidatedConfig` to
        # `ValidatedConfig`.
        # We do this because we already run all the validations chain.
        # Force a type is not a good way to deal with a problem, and this is
        # the main downside of this implementation (but it works anyway).
        return cast(ValidatedConfig, not_validated_config)

class Phase1Validation(ValidationHandler):

    def _validate(self, not_validated_config: NotValidatedConfig):
        if "foo" not in not_validated_config:
            raise InvalidConfig('Config miss "foo" attr')

class Phase2Validation(ValidationHandler):

    def _validate(self, not_validated_config: NotValidatedConfig):
        if not isinstance(not_validated_config["foo"], str):
            raise InvalidConfig('"foo" must be an string')

class Validator:
    _validation_handler: ValidationHandler

    def __init__(self, validation_handler: ValidationHandler):
        self._validation_handler = validation_handler

    def validate_config(self, not_validated_config: NotValidatedConfig) -> ValidatedConfig:
        return self._validation_handler.get_validated_config(not_validated_config)

if __name__ == "__main__":
    # "Pure Dependency Injection"
    validator = Validator((Phase2Validation(Phase1Validation())))
    validator.validate_config({"foo": 1, "bar": 1})

What is the problem with this approach?: the lightweight way in which the types are concatenated. In the original example, the Phase1Validation generates a ValidatedPhase1Config, which is safely used by the Phase2Validation. With this implementation, each decorator receives the same data type to validate, and this creates safety issues (in terms of typing). The Phase1Validation gets NotValidatedConfig, but the Phase2Validation can't use that type to do the validation, they need the Phase1Validation.


Q: Issues with persistent volume on DigitalOcean Kubernetes cluster Just created a managed 2-node Kubernetes (ver. 1.22.8) cluster on DigitalOcean (DO).
After installing WordPress using Bitnami Helm chart, and then installing a WP plugin, the site became unreachable.
Looking into DO K8s dashboard in the deployment section, the wordpress deployment shows the following error:
0/2 nodes are available: 2 pod has unbound immediate PersistentVolumeClaims.

AttachVolume.Attach failed for volume "pvc-c859847e-f250-4e71-9ed3-63c92cc01f50" : rpc error: code = DeadlineExceeded desc = context deadline exceeded

MountVolume.MountDevice failed for volume "pvc-c859847e-f250-4e71-9ed3-63c92cc01f50" : rpc error: code = Internal desc = formatting disk failed: exit status 1 cmd: 'mkfs.ext4 -F /dev/disk/by-id/scsi-0DO_Volume_pvc-c859847e-f250-4e71-9ed3-63c92cc01f50' output: "mke2fs 1.45.5 (07-Jan-2020)\nThe file /dev/disk/by-id/scsi-0DO_Volume_pvc-c859847e-f250-4e71-9ed3-63c92cc01f50 does not exist and no size was specified.\n"

Readiness probe failed: HTTP probe failed with statuscode: 404

As I'm quite new to K8s, I don't know much how to troubleshoot this.
Any help would be much appreciated.
UPDATE
I was able to reproduce the error and found what triggers it.
WordPress Bitnami charts installs several WP plugins by default. As soon as I try to delete them, the error shows up and the persistent volume gets corrupted...
Is this maybe a bug or it's standard behavior?


Q: ArrayList duplicate element show-up in list view I'm developing an app (twitter-like) and my feed is based on a listview + adapter. by default you get the 20 first elements of your feeds and when scrolling down and reaching the end of the list, the fragment which contain the view send a request to twitter to get the remaining feeds and as soon as we get them, I update the list handle by the adapter and send the data notification changed. the overall process works but I got a but at the end of the list.
When reaching the end of the list and getting the new list, the last tweets is duplicated which mean that in my feed you have 2 times the same tweets.
For example, you have this feed: tweetA, tweetB, tweetC. When reaching tweetC, we asking for the old tweets and once received, I'm using method called setData to give the new list to the adapter and request the notify data set change. but when you get the list and update, you see the listview showing:
tweetA, tweetB, tweetC, tweetC, tweet D, tweetF
I was thinking it's coming from the new list received and not the listview and thinking that I can just remove the first element of the new list but the issue remain, in my case (when removing the first element), tweet D disappear and show tweetF
here is the code:
Feedfragment :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Log.d(TAG, "inside onCreateView");

    View view = inflater.inflate(R.layout.twitter_swip_list,container, false);
    mlistview = (ListView) view.findViewById(R.id.listview) ;
    TwitterTimeLines twitt = new          TwitterTimeLines(mActivity,TwitterHomeActivity.getTwitterHandler());
        twitt.getTimeline(handler);     return view;
}

handler is used to get back the result from twitter
private final Handler handler = new Handler() {
    @Override
    public void handleMessage(android.os.Message msg) {
        ArrayList<Status> status = (ArrayList<Status>) msg.obj ;
        mStatus = status;
        mTwitterFeedAdapter.setData (mStatus);
        mTwitterFeedAdapter.notifyDataSetChanged();
        }
    }
} ;

Adapter :
public View getView(final int position, View convertView, ViewGroup parent) {
    Log.d(TAG,"position"+position) ;
    mPosition = position;

    mViewHolder = new TweetViewHolder(mActivity);

    mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;

    if(convertView == null) {
        convertView = mInflater.inflate(R.layout.twitter_feed,null) ;
        mViewHolder.userProfilePicture = (ImageView) convertView.findViewById(R.id.profileImg) ;
        mViewHolder.userRealName = (TextView)    convertView.findViewById(R.id.userName) ;
         ....
        convertView.setTag(mViewHolder) ;
    }
    else {
        mViewHolder = (TweetViewHolder) convertView.getTag() ;
    }
    /* detect end of the list and request old tweets*/
    if(position >= mStatus.size() - 1 ){
       mTweetFeedFragment.populateOldTimeLine();

    /* both classes are used to extract data and put it in a easy
    user format */
    mTweetMediaInfo = new TweetMediaInfo(mStatus.get(position));
    mTweetInfo = new TweetInfo(mStatus.get(position));

    showTweetContent();

    return convertView ;

}

public void setData(ArrayList<Status> status){
    mStatus = status;
}

Any idea ?

A: you can use HasHSet like this for removing the redudancey
list = new ArrayList<String>(new LinkedHashSet<String>(list))


Q: UWSGI Bad Gateway - Connection refused while connecting to upstream Trying to get a basic Django app running on nginx using UWSGI. I keep getting a 502 error with the error in the subject line. I am doing all of this as root, which I know is bad practice, but I am just practicing. My config file is as follows (it's included in the nginx.conf file):
server {
    listen 80;
    server_name 104.131.133.149;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/root/headers;
}

location / {
    include         uwsgi_params;
    uwsgi_pass      127.0.0.1:8080;
}
}

And my uwsgi file is:
[uwsgi]
project = headers
base = /root

chdir = %(base)/%(project)
home = %(base)/Env/%(project)
module = %(project).wsgi:application

master = true
processes = 5

socket = 127.0.0.1:8080
chmod-socket = 666
vacuum = true

As far as I can tell I am passing all requests on port 80 (from nginx.conf) upstream to localhost, which is running on my VH, where uwsgi is listening on port 8080. I've tried this with a variety of permissions, including 777. If anyone can point out what I'm doing wrong please let me know.

A: Ok so the issue was not starting up uwsgi with --socket 127.0.0.1:8080 option set! That was in my upstart script which now looks like:
start on runlevel [2345]
stop on runlevel [!2345]

setuid root
setgid root

exec /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites --socket 127.0.0.1:8080

A: I've faced something like that.
I put the project to work doing like so:
upstream project {
    server project-backend:8000;
}

server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name project.alx.corp;

        ssl_certificate /etc/nginx/ssl/cert.crt;
        ssl_certificate_key /etc/nginx/ssl/cert.key;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers     HIGH:!aNULL:!MD5;

     location /static/ {
         alias /code/static/;
     }

    location / {
                proxy_pass http://project;
        include     /etc/nginx/uwsgi_params;
    }
}

[uwsgi]

base = /code/project
module = project.wsgi:application
logto = /code/logs/uwsgi.log
http-socket = 0.0.0.0:8000
master = 1
processes = 2
threads = 2


Q: Resetting Score In Restart of Game I am making a VR game, in which there is only one level which is on main scene and the other scene is of "end" on which the game Over text Score is visible with Restart(which reloads the main scene) and Exit Button.
My problem is, M using this script as my ScoreManager script given below. I want this score in end scene too and this is working as m using PlayerPrefs
But the main problem is, when clicking the restart at the end scene, the game reloads the Main scene but that score Still have the same value of the previous game. I want it to set to Zero.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

namespace CompleteProject
{
    public class ScoreManager : MonoBehaviour
    {
        public static int score ;        // The player's score.
        Text text;                      // Reference to the Text component.

        void Awake()
        {
            // Set up the reference.
            text = GetComponent<Text>();
            score = 0;
            score = PlayerPrefs.GetInt("Score");
        }

        void Update ()
        {

            // Set the displayed text to be the word "Score" followed by the score value.
            text.text = "Score: " + score;
            PlayerPrefs.SetInt("Score", score);

        }
    }
}

I have also used DeleteKey(string) to delete the score, but nothing happened.

A: You said you tried DeleteKey(int score)  but it didn't work. Your code does not have the DeleteKey function anywhere. If you don't know how to use that function, the code below will show you how to use it. If you actually know how to use it but it's not working as mentioned in your question, then call PlayerPrefs.Save() after it. This should delete the key and update it right away.
To reset the score after each game, put the code in the OnDisable() function.
void OnDisable()
{
    PlayerPrefs.DeleteKey("Score");
    PlayerPrefs.Save();
}

To reset it when game begins, get the current score like you did in the Awake() function then change the function above to OnEnable().

A: The problem you still get the previous session of your score so you need to reset the saved values by resetting the value back to zero ,by using the line :
PlayerPrefs.SetInt("Score", 0);
 public static int score ;
        Text text;
        void Start(){

            PlayerPrefs.SetInt("Score", 0);
            // Set up the reference.
            text = GetComponent<Text>();
            score = 0;
            score = PlayerPrefs.GetInt("Score",0);
        }
        void Update ()
        {

            // Set the displayed text to be the word "Score" followed by the score value.
            text.text = "Score: " + score;
            PlayerPrefs.SetInt("Score", score);

        }


Q: scroll event on Hostlistener I have defined template
@Component({
    selector: 'name',
    directives: [ ... ],
    templateUrl: 'name.html'
})

and class
export class ProductGridComponent implements OnInit {
    @HostListener('scroll', ['$event'])
    onScroll(e) {
        alert(window.pageYOffset)
    }

    products = [];
}

But it does not shot anything , however when i replace scroll and onScroll with click and onClick it indeed show the alert.
Why does not it work with scroll , does angular2 has any other implementation for it?
Thanks

A: You can create a custom directive like bellow
import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[scroller]'
})
export class ScrollerDirective {

  @HostListener('scroll') scrolling(){
    console.log('scrolling');
  }

  @HostListener('click') clicking(){
    console.log('clicking...');
  }

  constructor() { }

}

And then assuming you have a html template like

use the following css
.full-width{
    width: 200px;
    height: 200px;
    overflow: auto;
}

.double-width{
    width:400px;
    height: 100%;
}

the console will print "scrolling" on running the app if you move the horizontal scroll bar.
Here the key is that - the scoller directive should be in the parent not in the child div.

A: @HostListener('document:wheel', ['$event.target'])
public onWheel(targetElement) {
    console.log()
}

A: Set (scroll)="yourFunction($event)" within the template at the corresponding element.

A: You could do it by the following code as well:
import { HostListener} from "@angular/core";

@HostListener("window:scroll", [])
onWindowScroll() {
 //we'll do some stuff here when the window is scrolled
}

A: For those who were still not managed to figure this out with any of above solutions, here's a running code that is tested on Angular 12
@HostListener('document:wheel', ['$event.target'])
onScroll(): void {
  console.log("Scrolling");
}

A: In angular 10 and above, when listening to window events do the following:
import { HostListener } from '@angular/core';

@HostListener('window:scroll', ['$event']) onScroll($event: Event): void {
    if($event) {
      console.log($event));
    }
  }

A: Assuming you want to display the host scroll (and not the windows one) and that you are using angular +2.1
  @HostListener('scroll', ['$event']) private onScroll($event:Event):void {
    console.log($event.srcElement.scrollLeft, $event.srcElement.scrollTop);
  };


Q: Multiple if blocks or single if/else block? Which will typically have better running time, multiple if blocks or a single if/else block?
if (statement1) {
    /* do something */
    return result;
}
if (statement2) {
    /* do something */
    return result;
}
if (statement3) {
    /* do something */
    return result;
}

Versus:
if (statement1) {
    /* do something */
    return result;
} else if (statement2) {
    /* do something */
    return result;
} else if (statement3) {
    /* do something */
    return result;
}

I've always used the first style when the logical statements weren't in any way related, and the second if they were.
EDIT
To clarify why this thought popped into my head, I am programming a prime checker and have an if block that looks something like this:
if(n<2) return 0;
if(n==2) return 1;
if(n%2==0) return 0;
...

A:
Which will typically have better running time, multiple if blocks or a single if/else block?

This is largely irrelevant as the semantics are different.
Now, if the goal is comparing the case of
if (a) { .. }
else if (b) { .. }
else { .. }

with
if (a) { return }
if (b) { return }
return

where no statements follow the conditional then they are the same and the compiler (in the case of a language like C) can optimize them equivalently.

A: Always go for if else if... when you know only one of the condition is to be executed, Writing multiple if's will make the compiler to check for each and every condition even when the first condition is met which will have a performance overhead, multiple if's can be used when u want to check and perform multiple operations based on certain condition

A: The if/else approach is faster, because it will skip evaluating the following conditions after one test succeeds.
However, the two forms are only equivalent if the conditions are mutually exclusive. If you just mindlessly convert one form into the other, you will introduce bugs. Make sure that you get the logic right.


Q: Attach Angular component to document body I would like to render an Angular component (an overlay) as a direct child of the documents body element. Today this can be done as follows:
constructor(
  private applicationRef: ApplicationRef,
  private componentFactoryResolver: ComponentFactoryResolver,
  @Inject(DOCUMENT) private document: Document,
  private injector: Injector
) {}

public renderOverlayInBody(): void {
  const overlayRef = this.componentFactoryResolver
    .resolveComponentFactory(OverlayComponent)
    .create(this.injector);
  this.applicationRef.attachView(overlayRef.hostView);
  const overlayRoot = (overlayRef.hostView as EmbeddedViewRef<unknown>)
    .rootNodes[0] as HTMLElement;

  // This component can be appended to any place in the DOM,
  // in particular directly to the document body.
  this.document.body.appendChild(overlayRoot);
}

Demo in Stackblitz
Unfortunately, ComponentFactoryResolver has been deprecated in Angular 13 and may be removed in Angular 16. The suggested replacement is ViewContainerRef.createComponent:
constructor(private viewContainerRef: ViewContainerRef) {}

public ngOnInit(): void {
  // This component can only be appended to the current one,
  // in particular not directly to the document body.
  this.viewContainerRef.createComponent(OverlayComponent);
}

While this is much simpler to read, it doesn't allow to render components as direct children of the documents body element. Is there any way to do that, which doesn't rely on currently deprecated code?


Q: Why not show chinese word in Smartface App Studio IDE? Why,
function Page1_Self_OnShow() {
//Comment following block for removing navigationbar/actionbar sample
//Copy this code block to every page onShow
    header.init(this); header.setTitle("Page1中国文字");
    header.setRightItem("RItem");
    header.setLeftItem();
    this.statusBar.transparent = true; /**/
}

Chinese word not show in Smartface App Studio IDE?

A: There is a problem about the visuality of these kind of characters on Smartface desktop ide. But actually it works fine. About the visual problem, there is a reported bug and it will be fixed with the new versions of Smartface.
But for now, you can show chinese characters on device without any problem.
I copied your code (the below code):
function Page1_Self_OnShow() {
    //Comment following block for removing navigationbar/actionbar sample
    //Copy this code block to every page onShow
    header.init(this);
    header.setTitle("Page1中国文字");
    header.setRightItem("RItem");
    header.setLeftItem();
    this.statusBar.transparent = true;
    /**/
}

And this code block looks wrong on ide (this is the bug):

It should be setTitle("Page1中国文字"); but it is lack of the last " character.
As I said before this is only a visual bug.
When I run this app on device (by using device emulator or publish), it is seen as in the below screenshot:


Q: Java not found while installing Websphere Application Server I am trying to install the Websphere Application Server (32bit) in Ubuntu 14.04.3 (64bit) using the IBM installation manager a silent install and a response file.
The commands I am using are:
sudo ./IBMIM --launcher.ini silent-install.ini -input
ibm_im_response_file.xml -acceptLicense

In the logs I see the following:

WARNING: /opt/IBM/WebSphere/AppServer/bin/iscdeploy.sh: 44:
  /opt/IBM/WebSphere/AppServer/bin/iscdeploy.sh:
  /opt/IBM/WebSphere/AppServer/java/bin/java: not found

although this file exists, but it's a link to /opt/IBM/WebSphere/AppServer/java/jre/java
EDIT: same happens when using the GUI
EDIT2: I tried doing the same under Ubuntu 12.04 and it worked. Apparently there is some problem regarding the 32bit version that is related to the ia32-libs package that is no longer available in 14.04.

A: If you are trying to Install Websphere Application Server through Installation Manager then you need to select IBM SDK provided with Websphere Application Server.
If you don't choose the IBM SDK you will be need to enter the JAVA Path in next steps.


Q: Delete all files and folders in multiple directory but leave the directoy Well I like this nice piece of code right here it seems to work awesomely but I can't seem to add any more directories to it
DirectoryInfo dir = new DirectoryInfo(@"C:\temp");

foreach(FileInfo files in dir.GetFiles())
{
    files.Delete();
}

foreach (DirectoryInfo dirs in dir.GetDirectories())
{
    dirs.Delete(true);
}

I would also like to add in special folders as well like History and cookies and such how would I go about doing that (I would like to include at least 4-5 different folders)

A: Perhaps something like this would help.  I did not test it.
public void DeleteDirectoryFolders(DirectoryInfo dirInfo){
    foreach (DirectoryInfo dirs in dirInfo.GetDirectories())
    {
        dirs.Delete(true);
    }
}

public void DeleteDirectoryFiles(DirectoryInfo dirInfo) {
    foreach(FileInfo files in dirInfo.GetFiles())
    {
        files.Delete();
    }
}

public void DeleteDirectoryFilesAndFolders(string dirName) {
  DirectoryInfo dir = new DirectoryInfo(dirName);
  DeleteDirectoryFiles(dir)
  DeleteDirectoryFolders(dir)
}

public void main() {
  List<string> DirectoriesToDelete;
  DirectoriesToDelete.add("c:\temp");
  DirectoriesToDelete.add("c:\temp1");
  DirectoriesToDelete.add("c:\temp2");
  DirectoriesToDelete.add("c:\temp3");
  foreach (string dirName in DirectoriesToDelete) {
    DeleteDirectoryFilesAndFolders(dirName);
  }
}

A: Here's a recursive function that will delete all files in a given directory and navigate down the directory structure. A pattern string can be supplied to only work with files of a given extension, as per your comment to another answer.
Action<string,string> fileDeleter = null;
fileDeleter = (directoryPath, pattern) =>
{
    string[] files;
    if (!string.IsNullOrEmpty(pattern))
        files = Directory.GetFiles(directoryPath, pattern);
    else
        files = Directory.GetFiles(directoryPath);

    foreach (string file in files)
    {
        File.Delete(file);
    }

    string[] directories = Directory.GetDirectories(directoryPath);
    foreach (string dir in directories)
        fileDeleter(dir, pattern);
};

string path = @"C:\some_folder\";
fileDeleter(path, "*.bmp");

Directories are otherwise left alone, and this can obviously be used with an array or list of strings to work with multiple initial directory paths.
Here is the same code rewritten as a standard function, also with the recursion as a parameter option.
public void DeleteFilesFromDirectory(string directoryPath, string pattern, bool includeSubdirectories)
{
    string[] files;
    if (!string.IsNullOrEmpty(pattern))
        files = Directory.GetFiles(directoryPath, pattern);
    else
        files = Directory.GetFiles(directoryPath);

    foreach (string file in files)
    {
        File.Delete(file);
    }

    if (includeSubdirectories)
    {
        string[] directories = Directory.GetDirectories(directoryPath);
        foreach (string dir in directories)
            DeleteFilesFromDirectory(dir, pattern, includeSubdirectories);
    }
}


Q: Array acting strange in Lua I am a noob in Lua. I have two arrays
First one:

levels={
-- 1
{
{9,9,9,9,9,9,9,9,9},
{9,9,9,9,9,9,9,9,9},
{9,9,1,0,9,0,3,9,9},
{9,9,9,9,9,9,9,9,9},
{9,9,9,9,9,9,9,9,9}
}
,
-- 2
{
{9,9,9,9,9},
{9,9,9,9,9},
{9,9,1,9,9},
{9,9,0,9,9},
{9,9,0,9,9},
{9,9,0,9,9},
{9,9,0,9,9},
{9,9,3,9,9},
{9,9,9,9,9},
{9,9,9,9,9}
}
,
-- 3
{
{9,9,9,9,9,9,9,9,9,9},
{9,9,9,9,9,9,9,9,9,9},
{9,9,0,9,0,9,9,9,9,9},
{9,9,1,0,0,9,0,3,9,9},
{9,9,9,9,9,9,9,9,9,9},
{9,9,9,9,9,9,9,9,9,9}
}
}

And The second I declare it like this:

playingLevel=levels[1]

The problem is that after I change playingLevel values, the levels array also changes the same way. I want to change only playingLevel.

A: table values are references in lua. when you do
playingLevel=levels[1]

you are not copying the table value at levels[1] into playingLevel, you are getting a reference to the actual data at levels[1], so changing an array value through playingLevel is essentially the same as changing the value as if you wrote levels[1][some_index] = new_value.
if you want a copy of the data, you will need a function that will create the copy for you. (either a shallow or deep copy depending on your use case)
so your code would look like playingLevel = copyTable(levels[1]) instead where copyTable is your custom implementation of a function that knows how to create a copy of the target table.


Q: How do i export tfs 2010 comments into a changelog file? I want to export TFS2010 comments from a date range or continually, (which ever works) into a changelog.txt file or similar.
I have looked all over the web trying to find examples or documentation on how to do this, but cannot find anything.
Also microsoft's website seems to just redirect me to TFS2012.

A: You can use the following command to output the "History" between a date range, but this will get you a lot more than the comments.
tf history "$/Project/Main" /format:detailed /noprompt /recursive /v:D"13 Jun 2013 00:00"~D"01 Jun 2013 00:00"

You could use the Brief format, but this is limited in it's width, and will truncate longer comments.
Once you have your "Log" you will have to parse it yourself. TFS does not have a format like git does.
You could create a console App that reads the history from Console.In.ReadToEnd() and then parses it into just comments and just pipe the results of your tf history into it.
You could also query the TFS API for this information using the VersionControlServer.QueryHistory Method, and just get the comments and output those.


Q: Detect edge crossing in vis.js Is there a way to detect if edges cross each other in vis.js graph-2d?
I am trying to layout a directed graph with the Sugiyama algorithm, but its a little bit tricky. Is there an available Javascript implementation/tutorial of that algorithm or the edge-crossing?
I have seen many papers with pseudo-code and very specific implementations but they aren't very helpful for me.


Q: Python - Removing paragraph breaks in input So I have written a program (however ugly) that counts the number of words and the instances of each unique word in a given input.
My problem is that I want to use it for song lyrics, but most lyric sets come with multiple paragraph breaks.
My question is: how can I take a user input of lyrics with paragraph breaks and reduce the input down to a single string?
This is my code so far:
Song = {}
lines = []

while True:
    line = input("")
    if line:
        lines.append(line)
    else:
        break

string = '\n'.join(lines)

def string_cleaner(string):
    string = string.lower()
    newString = ''
    validLetters = " abcdefghijklmnopqrstuvwxyz"
    newString = ''.join([char for char in string if char in validLetters])
    return newString

def song_splitter(string):
    string = string_cleaner(string)
    words = string.split()
    for word in words:
        if word in Song:
            Song[word] += 1
        else:
            Song[word] = 1

Expected input:
Well, my heart went "boom"
When I crossed that room
And I held her hand in mine
Whoah, we danced through the night
And we held each other tight
And before too long I fell in love with her
Now I'll never dance with another
(Whooh)
Since I saw her standing there
Oh since I saw her standing there
Oh since I saw her standing there

Desired output:
This song has 328 words.
39 of which are unique.

This song is 11% unique words.
('i', 6)
('her', 4)
('standing', 3)
.... etc

A: The following example code extracts all the words (English alphabet only) from every line and process them (counts the number of words, and retrieve instances of each unique word).
import re

MESSAGE = 'Please input a new line: '
TEST_LINE = '''
Well, my heart went "boom"
When I crossed that room
And I held her hand in mine
Whoah, we danced through the night
And we held each other tight
And before too long I fell in love with her
Now I'll never dance with another
(Whooh)
Since I saw her standing there
Oh since I saw her standing there well well
Oh since I saw her standing there
'''

prog = re.compile(r'\w+')

class UniqueWordCounter():

    def __init__(self):
        self.data = {}

    def add(self, word):
        if word:
            count = self.data.get(word)
            if count:
                count += 1
            else:
                count = 1
            self.data[word] = count

# instances of each unique word
set_of_words = UniqueWordCounter()
# counts the number of words
count_of_words = 0

def handle_line(line):
    line = line.lower()
    words = map(lambda mo: mo.group(0), prog.finditer(line))
    for word in words:
        global count_of_words
        count_of_words += 1
        set_of_words.add(word)

def run():
    line = input(MESSAGE)

    if not line:
        line = TEST_LINE

    while line:
        '''
        Loop continues as long as `line` is not empty
        '''

        handle_line(line)

        line = input(MESSAGE)

    count_of_unique_words = len(set_of_words.data.keys())
    unique_percentage = count_of_unique_words / count_of_words

    print('-------------------------')
    print('This song has {} words.'.format(count_of_words))
    print('{} of which are unique.'.format(count_of_unique_words))
    print('This song is {:.2%} unique words.'.format(unique_percentage))

    items = sorted(set_of_words.data.items(), key = lambda tup: tup[1], reverse=True)
    items = ["('{}', {})".format(k, v) for k, v in items]

    print('\n'.join(items[:3]))
    print('...')

run()

If you want to handle lyrics in other languages, you should check out this link.


Q: Split python list objects separated by u' ' I have a python list object containing elements as follows:
[u'Sentence 1 blabla.'],
[u'Sentence 2 blabla.'],
...

I want to extract the contents inside ' ' present in the list and store each as separate lines in a text file. Please help me with the same

A: u'blablabla' is Unicode. You can convert it into string using str(unicode)
Example:
a = [[u'qweqwe'],[u'asdasd']]

str(a[0][0]) will be string qweqwe.
Now you can write it into file as usual.
Try this example for clarity:
a = [[u'qweqwe'],[u'asdasd']]
print type(a[0][0])
print type(str(a[0][0]))

Output:
<type 'unicode'>
<type 'str'>

A: Firstly, Given that you have a list of lists, I am going to assume that you are going to convert the given list from unicode to an UTF8 string. For this lets have a function convertList which takes a list of lists as an input
So your initial value for l would be
[[u'Sentence 1 blabla.'],
[u'Sentence 2 blabla.'],
...]

Notice that this is a list of lists. Now for each list item, loop through the items within that list and convert them all to UTF8.
def convertList(l):
    newlist = []
    for x in l:
        templ = [item.encode('UTF8') for item in x]
        newlist.append(templ)
    return newlist

l = [[u'Sentence 1 blabla.'], [u'Sentence 2 blabla.']]
l = convertList(l) # This updates the object you have
# Now do the filewrite operations here.
f = open('myfile.txt','w')
for iList in l:
    for items in iList:
        f.write(items+'\n')
f.close()

This will write to the file myfile.txt as follows

Sentence 1 blabla.
Sentence 2 blabla.


Q: Scientific number format in R Considering the code below.
x <- c(3423, 123412121, 4567121)
format(x, scientific = TRUE)

[1] "3.423000e+03" "1.234121e+08" "4.567121e+06"

The results are using different exponential each time like e+03, e+08, e+06.
Is there a way to get the results with a fixed exponential ? Like say all output should be in e+03 ?
Thank You.

A: With options(scipen=999) you get the full number without e+03 and so on. Maybe there is a way with options(scipen=...)


Q: How to log a particular address from an STM32 NUCLEO-F334R8 with an inbuilt ST-LINK in real time using SWD & openOCD without halting the processor? I am trying to learn how to debug an MCU non-intrusively using SWD & openOCD.

while (1)
  {
      my_count++;
      HAL_GPIO_TogglePin(LD2_GPIO_Port,LD2_Pin);
      HAL_Delay(750);
  }

The code running on my MCU has a free running counter "my_count" . I want to sample/trace the data stored in the address holding "my_count" in real time :
I was doing it this way:

 while(1){// generic algorithm no specific language
mdw 0x00000000200000ac; //openOCD command to read from an address
}

0x200000ac is the address of the variable my_count from the .map file.
But, this method is very slow and experiences data drops at high frequencies.
Is there any other way to trace the data at high frequencies without experiencing data drops?

A: I made some napkin math, and I have an idea that may work.
As per Reference Manual, page 948, the max baud rate for UART of STM32F334 is 9Mbit/s.
If we want to send memory at the specific address, it will be 32 bits. 1 bit takes 1/9Mbps or 1.111*10^(-7)s, multiply that by 32 bits, that makes it 3.555 microseconds. Obviously, as I said, it's purely napkin math. There are start and stop bits involved. But we have a lot of wiggle room. You can easily fit 64 bits into transmission too.
Now, I've checked with the internet, it seems the ST-Link based on STM32F103 can have max baud rate of 4.5Mbps. A bummer, but we simply need to double our timings. 3.55*2 = 7.1us for 32-bit and 14.2us for 64-bit transmission. Even given there is some start and stop bit overhead, we still seem to fit into our 25us time budget.
So the suggestion is the following:
You have a timer set to 25us period that fires an interrupt, that activates DMA UART transmission. That way your MCU actually has very little overhead since DMA will autonomously handle the transmission, while your MCU can do whatever it wants in the meantime. Entering and exiting the timer ISR will be in fact the greatest part of the overhead caused by this, since in the ISR you will literally flip a pair of bits to tell DMA to send stuff over UART @ 4.5Mbps.


Q: matrix manipulation - why is a normal loop producing different results? My question is related to this question. I was trying to model the list comprehension provided by @shuttle87  in his/her answer to the question to a regular old-fashioned loop. Here is what my code snippet looks like:
matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
    for e in i:
        sqd.append(e*e)
print(sqd)

My problem is that my code returns a list i.e., [4, 0, 4, 0, 4, 0, 4, 0, 4] instead of a matrix i.e., [[4, 0, 4], [0, 4, 0], [4, 0, 4]]. What can i be possibly doing wrong?
disclaimer: I am aware there are wonderful python libraries that can do this for e.g., numpy. I like understanding things through intuition and thus this question...so forgive my naivety.

A: You have a single list sqd that you are appending scalar values to, so it will always just be a 1-dimensional list. If you want a list of lists (i.e. 2-dimensional matrix), you need to append lists to sqd, not scalar values:
matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
    row = []  # create a new list for each row
    for e in i:
        row.append(e*e)  # append scalar to the row list
    sqd.append(row)  # append row to matrix list
print(sqd)

A: Because you append numbers to sqd inside the inner for e in i loop. Instead, you need to append those numbers to a temp list, then append that list to sqd.
matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
    row = []
    for e in i:
        row.append(e*e)
    sqd.append(row)
print(sqd)

Or, as a list-comprehension:
matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = [[e * e for e in row] for row in matrix]
print(sqd)

A: You have two for loops here. Your outer loop is going through the Columns of the matrix.
Your inner loop is going through the rows.
Your inner loop runs through the entire loop before going down to your next column.
Now that you understand that flow, you need to see that your list "sqd" has only one operation it is performing. That operation of append will happen for every loop of the inner loop. Each loop you are growing that list by adding the latest operation.
To create the matrix you wish to see, you are going to want some more work between your inner and outer loop.
I would recommend making a new list for every iteration of your outer loop. This new list will be appended by the inner loop, and once the inner loop completes, you can add this new temp list to "sqd".


Q: Fetch request returning status cors and readable stream I am making a fetch call to my back end, here is the call.

    const response = await fetch(apiUrl + '/recipes', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Token token=${user.token}`
      },
      body: JSON.stringify({
        recipe: {
          recipeId: uri
        }
      })
    })

Then this is the route I send the call to on my backend

router.post('/recipes', requireToken, (req, res) => {
  req.body.recipe.owner = req.user.id
  Recipe.create(req.body.recipe)
    .then(recipe => {
      console.log('Recipe object saved is', recipe)
      res.status(201).json({ recipe: recipe.toObject() })
    })
    .catch(err => handle(err, res))
})

When I do this, the correct object logs right before it sends back. Here is an example of what gets logged

{ __v: 0,
  updatedAt: 2018-10-19T15:47:16.809Z,
  createdAt: 2018-10-19T15:47:16.809Z,
  recipeId: 'http://www.edamam.com/ontologies/edamam.owl#recipe_7dae4a3b1f6e5670be3c2df5562e4782',
  owner: 5bc9fc6a3682194cdb8d6fa5,
  _id: 5bc9fc843682194cdb8d6fa7 }

However, when I console.log what I get back on the front end, I get this.

Response {type: "cors", url: "http://localhost:4741/recipes", redirected: false, status: 201, ok: true, …}
body: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 201
statusText: "Created"
type: "cors"
url: "http://localhost:4741/recipes"
__proto__: Response

On the call, it does record the action with my database, so the information gets saved, and is logged right before it should be sent back, however the proper information is not sent back.
Thank you ahead of time for any response.

A: Since you're using fetch to make the request, the response is encapsulated in the Response object, and to access it you have to call the async method json(). Just like the following:
const Response = await fetch(apiUrl + '/recipes', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Token token=${user.token}`
  },
  body: JSON.stringify({
    recipe: {
      recipeId: uri
    }
  })
});

const json = await Response.json();
console.log(json);

You can play with another example in your chrome console.
(async () => {
  const Response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const res = await Response.json();
  console.log(res);
})();

UPDATE
Another way to do that is:
(async () => {
  const response = await (
    await fetch('https://jsonplaceholder.typicode.com/todos/1')
  ).json();

  console.log(response);
})();

I hope this helps.


Q: Combining Two Near Identical MySQL Queries New to this community... I have to say I love this resource though, it's fantastic. :)
(Before I go further, I want to point out that I have already achieved an undesirable yet functional solution to this problem using multiple queries and then combining what I get using a PHP array, but I'm weak with MySQL and what I've done simply isn't elegant or efficient, and I'd very much appreciate any assistance you can give me to actually help me improve it.  My project uses dozens and dozens of SQL queries and I'd like to learn to write them properly.)
I'm essentially trying to merge two near identical MySQL recordsets, using a UNION statement or something along those lines.  I've been looking around for ages trying to find a solution to this, and at this point it remains beyond me.  So, here's my first question:
My data structure is relatively simple, but I suspect the way in which I want to use it is perhaps a little less commonplace.  I have a series of users regularly transmitting data from their mobile devices to a PHP server which processes them and stores their contents in a MySQL database.  This is where it gets a little unorthodox, perhaps -- Users are effectively links in a closed chain.  At all times, every user has one other user serving as their link, or, I prefer, 'Target', while they themselves serve as the Target for someone else.  This model can be thought of in a linear fashion: A targets B, B targets C, C targets D, D targets A.
The data's stored in two tables:

*

*Users: Contains data about users (e.g. UserID, Name, Age, etc etc... TargetID)

*Packages: Contains data about all user updates (e.g. UserID, Timestamp, etc etc...)

Upon receiving a request from a user, I want to:

*

*Firstly, pull the most recent update from the Packages table, along with biographical information from the Users table pertaining to the Target of our User.

*Secondly, pull the most recent update from the Packages table, along with biographical information from the Users table pertaining to whoever has our User as their Target.
This might be a little confusing, so to clarify:
Using the aforementioned model, if I get a request from B, I want the most recent Package from A and the most recent Package from C returned in a single recordset, along with related biographical information.  I'm not actually interested in B!
The best I have managed to achieve at this point involves THREE queries:

*

*Initially, checking the Users table for the correct TargetID for our User.
SELECT TargetID FROM Users WHERE Users.UserID = [VALUE SUBMITTED IN USER REQUEST];

*Querying both tables to produce Result 1.
SELECT Users.UserID, Users.Name, Users.TargetID, Packages.Timestamp, Packages.Latitude, Packages.Longitude, Packages.Message FROM Users, Packages WHERE Packages.UserID = Users.UserID AND Users.UserID = [VALUE OBTAINED FROM QUERY 1] ORDER BY Packages.Timestamp DESC LIMIT 0,1;

*Querying both tables to produce Result 2.
SELECT Users.UserID, Users.Name, Users.TargetID, Packages.Timestamp, Packages.Latitude, Packages.Longitude, Packages.Message FROM Users, Packages WHERE Packages.UserID = Users.UserID AND Users.TargetID = [VALUE SUBMITTED IN USER REQUEST] ORDER BY Packages.Timestamp DESC LIMIT 0,1;

Then I've merged Results 1 & 2 in a PHP array, and fired the contents of this array back to the User submitting the request.  In any situation involving many many such requests, I have a hard time believing this approach is efficient, let alone ideal.  Despite the fact Queries 2 & 3 are virtually identical, and I'm sure a simple OR condition within a WHERE clause should be able to combine them, I cannot successfully do so without returning all Packages for both the users I'm interested in, or alternatively, returning exactly one record, discarding the second (I clearly apply the time constraint incorrectly).  For example, MySQL complains I incorrectly use UNION And ORDER BY statements together at times.  I'm just getting the syntax all wrong every time I try to modify it.
I am really unhappy with my current solution, because looking at my project at this point it is the single MySQL task my server must execute more often than all others.  I do realise this question is rather verbose, but I think it is always better to explain things thoroughly so it can be understood the first time.  Thanks in advance for any guidance or direction you can give me.  Cheers.

A: If I understand correctly, something like:
select
Users.UserID,
TargetedPackages.UserID as TargetedID,
TargetedPackages.TimeStamp as TargetedTimestamp,
TargeterPackages.UserID as TargeterID,
TargeterPackages.Timestamp as TargetedTimestamp
from
Users

INNER JOIN Users as Targeted
on Targeted.TargetId = Users.TargetID

INNER JOIN Users as Targeter
on Targeter.TargetId = Users.UserID

LEFT JOIN Packages as TargetedPackages
on Users.TargetID = TargetedPackages.UserID AND TargetedPackages.Timestamp = (SELECT Max(Timestamp) FROM Packages where Packages.UserID = Users.TargetID)

LEFT JOIN Packages as TargeterPackages
on Targeter.UserID = TargeterPackages.UserID AND TargeterPackages.Timestamp = (SELECT Max(Timestamp) FROM Packages where Packages.UserID = Targeter.UserID)

where Users.UserID = 2


Q: Managing tables in MS Word by Java application I am using XDocReport and Velocity to fill simple tables in docx files. Now, I would like to create table with merged fields.

Is it possible to do this in XDocReport? If not, how can I do it?

A: If I understand your need, you wish to set a mergefield and replace this mergefield with a table?
If it that, you can use HTML text styling. You design your docx template like this :
${htmlTable}

You mark that htmlTable field uses HTML syntax :
FieldsMetadata metadata = report.createFieldsMetadata();
metadata.addFieldAsTextStyling("htmlTable", SyntaxKind.Html);

You put in the context, the HTML table :
context.put("htmlTable", "

A	B

");

But today, it's very basic, you cannot manage border, width, height, etc for HTML table. See issue 302


Q: Why in Presto, it shows cardinality function is "Python function"? But this cardinality function doesn't exist in Python though..
https://prestodb.io/docs/current/search.html?q=cardinality+function


Q: How to get around calling Wait inside of a task I have code something like this:
var myTask = requiredTask.ContinueWith(_=>
{
    var otherTasks = from item in otherObjects select item.DoSomethingAsync();
    Task.WaitAll(otherTasks);
    // do my real work
});

My understanding is that the call to WaitAll is going to block and hold up a thread in the thread pool while the (IO bound) subtasks are completing.  My question is:

*

*Is my assumption about tying up a thread pool thread correct?

*If so what is the best method to avoid doing this?
Note that this is for a library that needs to support .NET4/Windows XP so using await is not an option.

A: If you include the Microsoft.Bcl.Async assembly and build with a compatible IDE (VS2012+), you can use async/await with .NET 4. Then you can await Task.WhenAll, e.g.
var myTask = await requiredTask;
var otherTasks = from item in otherObjects select item.DoSomethingAsync();
await Task.WhenAll(otherTasks);
// do my real work

Since Task.WhenAll was added in .NET 4.5, not in the Microsoft.Bcl.Async assembly, this is how you'd do it in .NET 4:
var myTask = await requiredTask;
var otherTasks = (from item in otherObjects select item.DoSomethingAsync()).ToList();
foreach (var otherTask in otherTasks)
    await otherTask;

I also threw in a ToList() so that if you use otherTasks later (e.g. to get results), the expression will not be reevaluated.


Q: Add new column to WooCommerce admin products list with discount percentage on sale products I am trying to display the percentage discount of simple products that are on sale in an additional column in the backend.
I have used the code below
add_filter( 'manage_edit-product_columns', 'discount_column', 20 );
function discount_column( $col_th ) {
    return wp_parse_args( array( 'discount' => 'Discount' ), $col_th );

}
add_action( 'manage_posts_custom_column', 'discount_col' );
function discount_col( $column_id ) {

    if( $column_id  == 'discount' )
      $saleprice = get_post_meta( get_the_ID(), '_sale_price', true );
      $regularprice = get_post_meta( get_the_ID(), '_regular_price', true );

      if ($saleprice > 0) {
        $discountperc = ($regularprice -$saleprice) /$regularprice * 100;
        echo (round($discountperc,2)). '%';
      }
}

But I am getting multiple (same) errors:
Undefined variable: saleprice
Can someone walk me through how to do that?

A: UPDATE 06/21: now also works for variable products.
It is not necessary to get the postmeta data via get_post_meta because you can access the product object via the $postid.
Once you have the product object, you have access to all kinds of product information.

*

*WooCommerce: Get Product Info (ID, SKU, $) From $product Object
So you get:
// Column header
function filter_manage_edit_product_columns( $columns ) {
    // Add column
    $columns['discount'] = __( 'Discount', 'woocommerce' );

    return $columns;
}
add_filter( 'manage_edit-product_columns', 'filter_manage_edit_product_columns', 10, 1 );

// Column content
function action_manage_product_posts_custom_column( $column, $postid ) {
    // Compare
    if ( $column == 'discount' ) {
        // Get product object
        $product = wc_get_product( $postid );

        // Is a WC product
        if ( is_a( $product, 'WC_Product' ) ) {
            // Product is on sale
            if ( $product->is_on_sale() ) {
                // Output
                echo '
';

                // Simple products
                if ( $product->is_type( 'simple' ) ) {
                    // Get regular price
                    $regular_price = $product->get_regular_price();

                    // Get sale price
                    $sale_price = $product->get_sale_price();

                    // Calculate discount percentage
                    $discount_percentage = ( ( $sale_price - $regular_price ) / $regular_price ) * 100;

                    // Output
                    echo '
' . abs( number_format( $discount_percentage, 2, '.', '') ) . '%' . '
';
                // Variable products
                }  elseif ( $product->is_type( 'variable' ) ) {
                    foreach( $product->get_visible_children() as $variation_id ) {
                        // Get product
                        $variation = wc_get_product( $variation_id );

                        // Get regular price
                        $regular_price = $variation->get_regular_price();

                        // Get sale price
                        $sale_price = $variation->get_sale_price();

                        // NOT empty
                        if ( ! empty ( $sale_price ) ) {
                            // Get name
                            $name = $variation->get_name();

                            // Calculate discount percentage
                            $discount_percentage = ( ( $sale_price - $regular_price ) / $regular_price ) * 100;

                            // Output
                            echo '
' . $name . '
';
                            echo '
' . abs( number_format( $discount_percentage, 2, '.', '') ) . '%' . '
';
                        }
                    }
                }

                // Output
                echo '
';
            }
        }
    }
}
add_action( 'manage_product_posts_custom_column', 'action_manage_product_posts_custom_column', 10, 2 );


Q: Examples of non-hypercomplete sheaves on affine schemes Let $A$ be a commutative ring and let $\mathcal{O}$ be a sheaf of $E_{\infty}$-ring spectra on $\mathrm{Spec} A$ such that $\pi_0\mathcal{O} = \mathcal{O}_{\mathrm{Spec} A}$. Lurie provides a criterion when $(\mathrm{Spec} A, \mathcal{O})$ coincides with $\mathrm{Spec}\, \mathcal{O}(\mathrm{Spec} A)$, namely if the homotopy groups $\pi_n\mathcal{O}$ are quasi-coherent sheaves on $\mathrm{Spec} A$ and $\mathcal{O}$ is hypercomplete (Spectral Algebraic Geometry, Proposition 1.6.1.1). To get a better understanding why this last condition is really necessary, I would like to know the answer to the following question:

Is there an example of sheaf $\mathcal{O}$ that is not hypercomplete, but satisfies the other conditions?

By Spectral Algebraic Geometry, Corollary 1.1.3.6, this cannot happen if $\mathrm{Spec} A$ is a noetherian space of finite Krull dimension. So a counterexample has to be something big like $A = \mathbb{Z}[x_1, x_2, x_3, \dots]$.


Q: Unit Testing a Java Chat Application I have developed a basic Chat application in Java. It consists of a server and multiple client. The server continually monitors for incoming messages and broadcasts them to all the clients. The client is made up of a Swing GUI with a text area (for messages sent by the server and other clients), a text field (to send Text messages) and a button (SEND). The client also continually monitors for incoming messages from other clients (via the Server). This is achieved with Threads and Event Listeners and the application works as expected.
But, how do I go about unit testing my chat application? As the methods involve establishing a connection with the server and sending/receiving messages from the server, I am not sure if these methods should be unit tested. As per my understanding, Unit Testing shouldn't be done for tasks like connecting to a database or network.
The few test cases that I could come up with are:
1) The max limit of the text field
2) Client can connect to the Server
3) Server can connect to the Client
4) Client can send message
5) Client can receive message
6) Server can send message
7) Server can receive message
8) Server can accept connections from multiple clients
But, since most of the above methods involve some kind of network communication, I cannot perform unit testing. How should I go about unit testing my chat application?

A: You should test the server and client in isolation.
The way to do this is to use mock objects to mock either the server (for testing the client) or the client (for testing the server).
A mock server would have the same methods as the real server, but you can decide what they return, i.e. simulate a connection error, a timeout, etc. Because it is a mock, you have full control over the functioning and you don't have to worry about actual connection errors.
For Java, look at the Mockito mocking framework.

A: Unit tests should be focused on exercising public APIs of each class you have built. However, things get a little tricky when dealing with Swing. Consider swingUnit for unit testing Swing components.

A: Chapter 7 of Beautiful Testing describes testing an XMPP chat client. I recommend reading the chapter. The conclusion is illustrative and may provide some pointers for your chat application:

In our quest to create beautiful tests for checking XMPP protocol implementations, we started out by testing simple request-response protocols at the lowest level: the data sent of the network stream. After discovering that this form of testing does not really scale well, we abstracted out the protocol to a higher level, up to the point where the tests used only high-level data structures. By testing protocol behavior on a high level, we were able to write tests for more complex protocols without compromising the clarity of the tests. For the most complex protocols, writing scenarios helped to cover all of the possible situations that can arise in a protocol session. Finally, since XMPP is an open protocol with many different implementations, it's very important to test an XMPP application on the real network, to ensure interoperability with other implementations. By running small test programs regularly, we were able to test the system in its entirety, and check whether our implementation of the protocol plays together nicely with other entities on the network.


Q: Webkit browsers renders multi-column layout contents wrong I have a two-column layout in a bootstrap modal. There should be a bootstrap dropdown button as the content. Firefox renders it correctly but webkit based browsers fail to display the button correctly. The button does not get hover or click events since its position is rendered wrong.
The question is: Am I doing something wrong? And is there a way to avoid this problem?
The jsfiddle is here: http://jsfiddle.net/cenap/mtpj8god/4/
Full screen: http://jsfiddle.net/cenap/mtpj8god/4/embedded/result/

.multicolumn-container {
  width: 250px;
  height: 300px;
  -webkit-column-count: 2;
  /* Chrome, Safari, Opera */
  -moz-column-count: 2;
  /* Firefox */
  column-count: 2;
  -webkit-column-rule: 1px outset #CCC;
  /* Chrome, Safari, Opera */
  -moz-column-rule: 1px outset #CCC;
  /* Firefox */
  column-rule: 1px outset #CCC;
  overflow: auto;
}
.box {
  display: inline-block;
  width: 100px;
  min-height: 60px;
  text-align: center;
  border: 3px solid #666;
  padding: 10px;
  margin: 10px;
}
.err {
  font-size: 8px;
  color: red;
}

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />

Multicolumn in Bootstrap modal

    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>

        <button type="button" class="close" data-dismiss="modal">×Close
        </button>

Modal title

          <button class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown'>
          </button>

Some Action

Some Other Action

        <--- This works but the ones in columns below do not render correctly in webkit.

1

                  <button class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown'>
                  </button>

Some Action

Some Other Action

                This is rendered wrong in webkit browsers

2

                  <button class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown'>
                  </button>

Some Action

Some Other Action

                This is rendered wrong in webkit browsers

3

4

5

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: its working fine on Mac OSX webkit browsers - Chrome 37+ and Safari 7+, as on Firefox 30+. Please specify the browser version.

A: It seems like there is a bug in Webkit and columns have been disabled for printing by its developer (Dave Hyatt) because page breaking couldn't be implemented properly. So the WebKit implementation have CSS3 columns turned off, but Firefox renders them correctly. I’ve tried making columns work for printing in Chrome, but still getting better results from Firefox. Also there are some posts by Dave Hyatt and one of them stating that “Columns are using the new pagination model, but printing isn't using it yet.”(https://bugs.webkit.org/show_bug.cgi?id=45993)

A: I know the question was asked over a year ago, but I found this worked for me.
-webkit-perspective: 1;

See http://jsfiddle.net/mtpj8god/6/
More about it (from http://caniuse.com/#search=column-count, in known issues):

Chrome is reported to incorrectly calculate the container height, and
  often breaks on margins, padding, and can display 1px of the next
  column at the bottom of the previous column. Part of these issues can
  be solved by adding -webkit-perspective:1; to the column container.
  This creates a new stacking context for the container, and apparently
  causes chrome to (re)calculate column layout.


Q: Data available for all views in codeigniter I have a variable, contaning data that should be present in the entire site. Instead of passing this data to each view of each controller, I was wondering if there is a way to make this data available for every view in the site.
Pd. Storing this data as a session variable / ci session cookie is not an option.
Thanks so much.

A: Set in application/config/autoload.php
$autoload['libraries'] = array('config_loader');

Create application/libraries/Config_loader.php
defined('BASEPATH') OR exit('No direct script access allowed.');

class Config_loader
{
    protected $CI;

    public function __construct()
    {
        $this->CI =& get_instance(); //read manual: create libraries

        $dataX = array(); // set here all your vars to views

        $dataX['titlePage'] = 'my app title';
        $dataX['urlAssets'] = base_url().'assets/';
        $dataX['urlBootstrap'] = $dataX['urlAssets'].'bootstrap-3.3.5-dist/';

        $this->CI->load->vars($dataX);
    }
}

on your views
<title><?php echo $titlePage; ?></title>
<!-- Bootstrap core CSS -->
<link href="<?php echo $urlBootstrap; ?>css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap theme -->
<link href="<?php echo $urlBootstrap; ?>css/bootstrap-theme.min.css" rel="stylesheet">

A: Create a MY_Controller.php file and save it inside the application/core folder. In it, something like:
class MY_Controller extends CI_Controller {

   public $site_data;

   function __construct() {
       parent::__construct();
       $this->site_data = array('key' => 'value');
   }
}

Throughout your controllers, views, $this->site_datais now available.
Note that for this to work, all your other controllers need to extend MY_Controllerinstead of CI_Controller.

A: You need to extend CI_Controller to create a Base Controller:
https://www.codeigniter.com/user_guide/general/core_classes.html
core/MY_Controller.php
<?php

class MY_Controller extend CI_Controller {

     public function __construct() {
         parent::__construct();

         //get your data
         $global_data = array('some_var'=>'some_data');

         //Send the data into the current view
         //http://ellislab.com/codeigniter/user-guide/libraries/loader.html
         $this->load->vars($global_data);

     }
}

controllers/welcome.php
 class Welcome extend MY_Controller {
      public function index() {
          $this->load->view('welcome');
      }
 }

views/welcome.php
var_dump($some_var);
Note: to get this vars in your functions or controllers, you can use $this->load->get_var('some_var')

A: If this is not an Variable(value keep changing) then I would suggest to create a constant in the constant.php file under the config directory in the apps directory, if it's an variable keep changing then I would suggest to create a custom controller in the core folder (if not exist, go ahead an create folder "core") under apps folder. Need to do some changes in other controller as mentioned here :
extend your new controller with the "CI_Controller" class. Example
open-php-tag if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 class LD_Controller extends CI_Controller {
}
close-php-tag
Here LD_  is my custom keyword, if you want to change you can change it in config.php file under line# 112 as shown here : $config['subclass_prefix'] = 'LD_';
and extend this class in all your controllers as "class Mynewclass extends LD_Controller..
And in LD_controller you've to write the method in which you want to define the variable/array of values & call that array in all over the application as shown here :
defining variable :
var $data = array();
Method to get values from db through the Model class:
function getbooks()
{
   $books =   $this->mybooks_model->getbooks(); //array of records
   $this->data = array('books'=>$books);
}

to call this variable in the views : print_r($this->data['books']);); you will get all the array values... here we've to make sure atleast one "$data" parameter needs to be passed if not no problem you can define this $data param into the view as shown here :
$this->load->view('mybookstore',$data);
then it works absolutely fine,,, love to share... have a fun working friends

A: you can use $this->load->vars('varname', $data);[ or load data at 1st view only] onse and use in any loaded views after this

A: Use sessions in your controllers
$this->session->set_userdata('data');
then display them in your view
$this->session->userdata('data');
Or include a page in base view file e.g index.php
include "page.php";
then in page.php,
add $this->session->userdata('data'); to any element or div
then this will show on all your views

A: I read all answers, but imho the best approch is via hook:

*

*Create hook, let's get new messages for example:
class NewMessages {
    public function contact()
    {
        // Get CI instance CI_Base::get_instance();
        $CI = &get_instance(); // <-- this is contoller in the matter of fact
        $CI->load->database();

        // Is there new messages?
        $CI->db->where(array('new' => 1));
        $r = $CI->db->count_all_results('utf_contact_requests');

        $CI->load->vars(array('new_message' => $r));
    }
}

*Attach it to some of the flow point, for example on 'post_controller_constructor'. This way, it will be loaded every time any of your controller is instantiated.
$hook['post_controller_constructor'][] = array(
    'class'    => 'NewMessages',
    'function' => 'contact',
    'filename' => 'NewMessages.php',
    'filepath' => 'hooks',
    'params'   => array(),
);

*Now, we can access to our variable $new_message in every view or template.
As easy as that :)

A: You could override the view loader with a MY_loader. I use it on a legacy system to add csrf tokens to the page where some of the forms in views don't use the builtin form generator. This way you don't have to retrospectively change all your controllers to call MY_Controller from CI_Controller.
Save the below as application/core/MY_Loader.php
<?php
class MY_Loader extends CI_Loader {
    /**
     * View Loader
     *
     * Overides the core view function to add csrf token hash into every page.
     *
     * @author   Tony Dunlop
     *
     * @param   string  $view   View name
     * @param   array   $vars   An associative array of data
     *              to be extracted for use in the view
     * @param   bool    $return Whether to return the view output
     *              or leave it to the Output class
     * @return  object|string
     */
    public function view($view, $vars = array(), $return = FALSE)
    {
        $CI =& get_instance();
        $vars['csrf_token'] = $CI->security->get_csrf_hash();
        return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return));
    }
}


Q: Based on todays date, how to get the date of the penultimate working day? I try to figure out, how I can get the penultimate workingday from todays date.
In my query, I would like to add an where clause where a specific date is <= today´s date minus 2 working days.
Like:
SELECT

    SalesAmount
   ,SalesDate

FROM mytable t

JOIN D_Calendar c ON t.Date = c.CAL_DATE

WHERE SalesDate <= GETDATE()- 2 workingdays

I have a calendar table with a column "isworkingDay" in my database and I think i have to use this but i don´t know how?!
Structure of this table is like:

CAL_DATE
DayIsWorkDay

2022-07-28
1

2022-07-29
1

2022-07-30
0

2022-07-31
0

2022-08-01
1

One example: Today is Monday, August 01, 2022. So based on today, I need to get Thursday, July 28 2022.
My desired result in the where clause should get me something like this:
where SalesDate<= Getdate() minus 2 workingdays

Thanks for your ideas!

A: You could use something like this:
SELECT  t.SalesDate,
        PreviousWorkingDay = d.CAL_DATE
FROM    mytable t
        CROSS APPLY
        (   SELECT  c.CAL_DATE
            FROM    D_Calendar AS c
            WHERE   c.CAL_DATE < t.SalesDate
            AND     c.DayIsWorkDay = 1
            ORDER BY c.CAL_DATE DESC OFFSET 1 ROWS FETCH NEXT 1 ROW ONLY
        ) AS d;

It uses OFFSET 1 ROWS within the CROSS APPLY to get the penultimate working day

A: This is how i implemented the idea from @SMor:
SELECT

SalesAmount
,SalesDate

FROM mytable t

JOIN D_Calendar c ON t.Date = c.CAL_DATE

WHERE SalesDate <= (SELECT
    MIN(t1.CAL_DATE) as MinDate
  FROM
    (SELECT TOP 2
        [CAL_DATE]
    FROM [DWH_PROD].[cbi].[D_Calendar]
    WHERE CAL_DAYISWORKDAY = 1 AND CAL_DATE <  DATEADD(dd,0,DATEDIFF(dd,0,GETDATE()))
    ORDER BY CAL_DATE DESC
    ) t1)

Thank you for your ideas and recommendations!

A: You can use a ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) getting  get the top 2 rows then take the row with number 2.
Example:
-- setup
Declare @D_Calendar as Table (CAL_DATE date, DayIsWorkDay bit)

insert into @D_Calendar values('2022-07-27', 1)
insert into @D_Calendar values('2022-07-28', 1)
insert into @D_Calendar values('2022-07-29', 1)
insert into @D_Calendar values('2022-07-30', 0)
insert into @D_Calendar values('2022-07-31', 0)
insert into @D_Calendar values('2022-08-01', 1)

Declare @RefDate DateTime = '2022-08-01 10:00'

-- example query
Select CAL_DATE
From
    (Select top 2 ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) AS BusinessDaysBack, CAL_DATE
    from @D_Calendar
    where DayIsWorkDay = 1
    and CAL_DATE < Cast(@RefDate as Date)) as Data
Where BusinessDaysBack = 2

From there you can plug that into your where clause to get :

SELECT
    SalesAmount
   ,SalesDate
FROM mytable t
WHERE SalesDate <= (Select CAL_DATE
                    From (Select top 2 ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) AS BusinessDaysBack, CAL_DATE
                        from D_Calendar
                        where DayIsWorkDay = 1
                        and CAL_DATE < Cast(getdate() as Date)) as Data
                    Where BusinessDaysBack = 2)

Change the 2 to 3 to go three days back etc


Q: Obtaining hyperbola in projective geometry (Courant)
Reading "Courant's – What is Mathematics", where a definition has just been introduced stating "[a] conic is the locus of intersection of corresponding lines in two projectively related pencils". A little later "If the pencil O and O' are congruent we obtain a circle. If angles are equal but with opposite sense, the conic is an equilateral hyperbola (see Fig 99 [me: below])".
The sentence in italics is basically the only explanation given as to how the hyperbolas had been obtained, and I have a hard time understanding it; for example I can't understand why and how we use points of intersection here (I know about cross-ratio, but not how it relates to the construction)... Could someone explain?

A: I believe that it's saying this: take  the (vertical) line from $O$ to $O';$ draw a line $15$ degrees clockwise from this, going through $O'$ (the line going from $O'$ to the vertex called "7". Draw  line $15$ degrees counterclockwise from this, going through $O$ (the line from $O$ to the vertex called "21"); find their intersection and plot it. Now repeat for 30, 45, 60, and so on degrees.
The problem is that this isn't what's shown in the drawing. The line $O-21$ is there, but the one marked to intersect with it is $O'-5$. The $O-20$ intersects $O'-4$, and so on. The resulting little circles, when connected, form a hyperbola.
The other side of this story is how the circle got there in the first place: for each line through $O$, you find a "corresponding" line through $O'$ (and "corresponding" here seems to mean "rotated by 90 degrees"), and you find their intersections. The result is the set of all points of the circle.
How is such a correspondence defined? Well, it looks as if Courant is using angles, but my preferred version is one where you define a projectivity as any sequence of perspectivities, as Hartshorne does in his little book on projective geometry. Doubtless in the real projective plane, the two things end up amounting to the same thing.


Q: Using iText and C#, create named destinations at exact same page coordinate as each PDF bookmark I can iterate through all the bookmarks in my PDF file and create named destinations but positioned at the top of the same page as each bookmark and not at the same coordinates.
The code below works but how do I set the named destination to also be at the exact same page coordinates as the bookmark (there can be a few bookmarks per page):
string file = @"C:\MyDocs\MyDoc1.pdf";
string newFile = @"C:\MyDocs\MyDoc2.pdf";

PdfDocument pdf = new PdfDocument(new PdfReader(file), new PdfWriter(newFile));

// Get the bookmarks
PdfOutline outlines = pdf.GetOutlines(false);
List<PdfOutline> bookmarks = outlines.GetAllChildren().ToList<PdfOutline>();

PdfNameTree destsTree = pdf.GetCatalog().GetNameTree(PdfName.Dests);
IDictionary<String, PdfObject> Tnames = destsTree.GetNames();

foreach (var item in bookmarks)
{
     string title = item.GetTitle();

     int pgn = pdf.GetPageNumber((PdfDictionary)item.GetDestination().GetDestinationPage(Tnames));

     PdfPage pdfPage = pdf.GetPage(pgn);
     iText.Kernel.Geom.Rectangle pageRect = pdfPage.GetPageSize();
     float getLeft = pageRect.GetLeft();
     float getTop = pageRect.GetTop();
     PdfExplicitDestination destObj = PdfExplicitDestination.CreateXYZ(pdfPage, getLeft, getTop, 1);
     pdf.AddNamedDestination(title, destObj.GetPdfObject());
}

pdf.Close();


Q: Groovy AST INSTRUCTION_SELECTION phase vs SEMANTIC_ANALYSIS This piece of code works in my visitor in the SEMANTIC_ANALYSIS phase but not in the INSTRUCTION_SELECTION phase. It looks like I am not able to use the constructor call. If I change the constructor instead to Arrays.asList() it seems to compile. Any help is appreciated
val codeBlock = GeneralUtils.block()

// Declare the futures list
val arrayListNode = ClassHelper.make(ArrayList::class.java)
val variable = "myVariable"
val variableDeclaration = GeneralUtils.varX(variable, arrayListNode)
val asListExpression = GeneralUtils.ctorX(arrayListNode)
val variableStmt = GeneralUtils.declS(variableDeclaration, asListExpression)
codeBlock.addStatement(variableStmt)

//
// Set the codeBlock back to the closure
closure.code = codeBlock

In the instruction selection phase, the error I get is
java.lang.ArrayIndexOutOfBoundsException: size==0
at org.codehaus.groovy.classgen.asm.OperandStack.getTopOperand(OperandStack.java:672)
at org.codehaus.groovy.classgen.asm.BinaryExpressionHelper.evaluateEqual(BinaryExpressionHelper.java:318)
at org.codehaus.groovy.classgen.asm.sc.StaticTypesBinaryExpressionMultiTypeDispatcher.evaluateEqual(StaticTypesBinaryExpressionMultiTypeDispatcher.java:142)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitDeclarationExpression(AsmClassGenerator.java:637)
at org.codehaus.groovy.ast.expr.DeclarationExpression.visit(DeclarationExpression.java:89)

A: This code seemed to work.
// Declare the futures list
val arrayListNode = ClassHelper.make(ArrayList::class.java)
val variable = "myVariable"
val variableDeclaration = GeneralUtils.varX(variable, arrayListNode)
val asListExpression = GeneralUtils.ctorX(arrayListNode)

// Look for the arraylist constructor in the node
val arrayNodeConstructorMethod = arrayListNode.getDeclaredConstructor(arrayOf())
asListExpression.setNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, arrayNodeConstructorMethod)

val variableStmt = GeneralUtils.declS(variableDeclaration, asListExpression)
codeBlock.addStatement(variableStmt)

//
// Set the codeBlock back to the closure
closure.code = codeBlock


Q: Extract a portion of a url I am trying to extract a portion of a URL using regex.
An example of my url would be:
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food

Using php, how could I extract the data in the q variable or the sourceid variable?

A: Don't use a regex for this. Instead, use parse_url() and parse_str().
$params = array();
$url= "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food";
$url_query = parse_url($url, PHP_URL_QUERY);
parse_str($url_query, $params);
echo $params['q']; // Outputs food

Demo

A: A perfect tutorial for what you're trying to accomplish:
$parts = parse_url('http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food');
parse_str($parts['query'], $query);
echo $query['q'];


Q: Mixing words from wordlist and making new wordlist I am trying to do mixing of words from wordlist and creating newwordlist
this is my wordlist
Nice
have fun
its cool
_
make
quote
backtick
_
jobs
public
over

what i am trying to do is mixing those words and want output like this.
Nice
make
jobs
_
have fun
quote
public
_
its cool
backtick
over

this is what i've tried
with open('wordlist.txt') as f:
    wordlist= f.read().splitlines()

newwordlist = []

for x in range(2):
   newx = wordlist[x]
   newwordlist.append(newx)

A: You can just basically "transpose" them with zip:
with open('wordlist.txt','r') as f:
    wordlist= list(zip(*[i.splitlines() for i in f.read().split('_')]))

If there are no underlines:
with open('wordlist.txt','r') as f:
    wordlist= list(zip(*[f.readlines()[i:i+3] for i in range(0,len(f.readlines()),3)]))

And do new file:
...
with open('wordlist2.txt','w') as f2:
    f2.write('_'.join(['\n'.join(i) for i in wordlist]))

A: With underscores you could use the concept proposed by U9-Forward
with open('wordlist.txt','r') as f:
    wordlist = list(zip(*[i.splitlines() for i in f.read().split('_\n')]))

with open('newwordlist.txt','w') as f2:
    f2.write('\n_\n'.join(['\n'.join(i) for i in wordlist]))

U9 was really close, just the newlines became issues

If you have just have a list of words and no underscores, you could use random.shuffle.
from random import shuffle

with open('wordlist.txt', 'r') as f:
    words = f.read().splitlines()
    shuffle(words)    # shuffles words randomly

with open('newwordlist.txt', 'w') as f2:
    f2.write('\n'.join(words))


Q: New badge for reputation-saving edits In honor of my heroic edit of this answer, I propose a new badge, named Grandmaster of Altruism to award those who selflessly give up their shot at momentary fame and quite a lot of reputation to help a misguided user that has posted an admirable, but in the end, wrong, answer to a question.
The result is a friendlier site experience for all, as expressed by these two members in the comments relating to the affair:

What was going on here is that users were jealous of H2CO3 getting rep for an answer essentially given by rubenvb, even though all that should matter is that another correct answer is now close to the top. (Upvotes should be given according to the correctness of the answer, not according to whether the user getting them would "deserve" them.) - sbi

and

Then we should be applauding rubenvb for his altruism and demonstrating the unique nature of our site and demonstrating how answers can be improved for the good of everyone. Sorry for the two rollbacks everyone, I automatically assumed something bad was going on here :) - Kev

The badge should obviously be golden, if not platinum, to express how deeply appreciated and cherished these random acts of kindness must be on the Stackexchange network.


Q: Can I run a VBScript script from inside Visual Studio 2008? I'm writing pop-up's for a website (please don't get angry. It's an internal application that shows energy usage for different buildings and the specification is to alert the users every time they log on) and I have a VBScript script that will run at the end of the a Windows user's logon script.
Is there a command to run the script from within Visual Studio rather than having to drop to Windows Explorer. It's only a tiny thing but if I don't ask I'll never know!
I have VBScript script running at the end of some local builds and such but I'd like to be able to select the file, right-click, then run. But I don't seem to be able to.

A: I don't believe so, but am hoping I am proved wrong.

A: To do what you want you need to extend the Visual Studio development environment by using an add-in. I don't know if the add-in you need already exists, but it is possible to write your own.
There is a list of popular add-ins here on Stack Overflow.

A: Try running cscript //X yourvbscript.vbs - it'll promt you for the debugging application. Select Visual Studio if have it installed.
Can do the same thing from VS but I don't remember at this moment ...

A: You can create a macro that runs your script, either by invoking cscript/wscript or by using the scripting COM-component. You can then add the macro to the context menu.
Another way is to add it as en external tool on the tool menu.


Q: Difference between User and System Installer of Visual Studio Code Visual Studio code offers User and System Installer but I have not found any description about the differences between these two options.
Could someone please shed a light on this for me?

A:
User setup for Windows
Announced last release, the user setup package for Windows is now available on stable. Installing the user setup does not require Administrator privileges as the location will be under your user Local AppData (LOCALAPPDATA) folder. User setup also provides a smoother background update experience.
Download User Setup
If you are a current user of the system-wide Windows setup, you will be prompted to install user setup, which we recommend using from now on. Don't worry, all your settings and extensions will be kept during the transition. During installation, you will also be prompted to uninstall the system-wide setup.

Reference: https://code.visualstudio.com/updates/v1_26#_user-setup-for-windows

A: I installed the user version side-by-side with the system version with no problems. The basic differences between the two is that the system version installs on the file system like every other app. The user install is basically a click-once (or web installer) version that installs in the User folder of the machine.
The settings made to VS Code in the system version save for Everybody on the computer and the user version the settings are only for the user. I find that the behavior of the user version is a bit annoying for me because I have reasons to want to open multiple copies of VS Code at the same time and the user version only allows one instance. Otherwise, there's not really anything different between the two as far as I can tell.

A: Many companies (like mine) dont allow Admin privileges, I think that's the main point so you  can still install VSC with the user installer

A: After user version of Visual Studio Code is downloaded, make cmd in the download folder and run a command below, replacing the correct version in the VS ode installation file name:

runas /trustlevel:0x20000 ./VSCodeUserSetup-x64-1.74.3.exe

start the command below in order to check which trust levels are supported:

runas /showtrustlevels


Q: Changing locale not working after `onResume` method? I have an app that is (more or less) translated in other languages. For this I used locale and for saving the language preferred by the user I used SharedPreferences.
Using this I managed to load the prefered language on any/every activity inside the app.
     @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pick);

    findViewById(R.id.flagcollection).setVisibility(View.GONE);

    findViewById(R.id.worldmapswitch)
            .setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (flagWorld) {
                        // means true
                        findViewById(R.id.flagcollection).setVisibility(View.GONE);
                        flagWorld = false;
                    } else {
                        findViewById(R.id.flagcollection).setVisibility(View.VISIBLE);
                        flagWorld = true;
                    }
                }
            });

    preferences = getSharedPreferences("settings_values", MODE_PRIVATE);

    String SavedLocaleLang = preferences.getString("LocalLang", null);
    Locale locale = new Locale(SavedLocaleLang);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());
....

The problem is that if for whatever reason I leave the app (not exiting/ending activity), after a while when I return to the app, it runs using the PHONE'S default language and not the saved value for locale.
Then, after reading numerous posts regarding the miracles of onResume, combined with my java no-skills I tried this :
@Override
public void onResume(){
    super.onResume();
    // put your code here...

    preferences = getSharedPreferences("settings_values", MODE_PRIVATE);

    String SavedLocaleLang = preferences.getString("LocalLang", null);
    Locale locale = new Locale(SavedLocaleLang);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());

}

I thought that I have solved my problem, but after testing the result in less than 1 hour I realized that I've done nothing (at least nothing good). Somewhere I'm doing something wrong.
If anyone has the skills, the patience and much, much good will, PLEASE help me understand what and where I am doing wrong.
Any help will be greatly appreciated! No sarcasm though, please. There I'm doing just fine :P
THANK YOU !!!
P.S. User "Cochi" requested the code for saving the locale in Prefereces ... so here you go :
findViewById(R.id.flaghungary)
            .setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String localeHU = "hu";
                    SharedPreferences settings = getSharedPreferences("settings_values", MODE_PRIVATE);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("LocalLang", localeHU);
                    editor.apply();

                    Locale locale = new Locale("hu");
                    Locale.setDefault(locale);
                    Configuration config = new Configuration();
                    config.locale = locale;
                    getResources().updateConfiguration(config, getResources().getDisplayMetrics());
                    setContentView(R.layout.activity_pick);
                    Context context = getApplicationContext();
                    Toast.makeText(context, "Magyar nyelv kiválasztva", Toast.LENGTH_SHORT).show();
                    recreate();
                }

            });

A: Try putting that code inside onCreate, before the setContentView :
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    String SavedLocaleLang = preferences.getString("LocalLang", null);
    Locale locale = new Locale(SavedLocaleLang);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


Q: How to improve the binarization of Text document ( Fill missing pixels of alphabets, reduce noise etc) What (and how) can be done (like where exactly to plcae Erosion, Dialiation, Opening, Closing etc) so that the words are not cut / invisible in between (maybe some other binarization technique which works on most of the cases or some parameter tuning)
I have this code to binarize / Threshold the image. It works fine on a wide range of images except a couple of things and the major problem being that it leads to loss of info due to some brightness and other factors. Some of the words are not readable or gets broken. Below is the code to threshold / Binarize along with some of the images. Also, here is the link to 200 sample and resulting images
import cv2
import skimage.filters as filters

def convert(path):
    img = cv2.imread(path)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    smooth = cv2.GaussianBlur(gray, (103,103), 0)

    division = cv2.divide(gray, smooth, scale=255)

    sharp = filters.unsharp_mask(division, radius=1.5, amount=5, multichannel=False, preserve_range=False) # High Radius increase the density or surrounding pixels making it dense
    sharp = (255*sharp).clip(0,255).astype(np.uint8)

    thresh = cv2.threshold(sharp, 0, 255, cv2.THRESH_OTSU )[1]
    return thresh

A: You can test several types of histogram equalization techniques. I've scripted down two examples of histogram equalization with your above photo. You can than later keep preprocessing those raw results for better outcomes depending on your data variance.
import cv2
import matplotlib.pyplot as plt

# read a image using imread
img = cv2.imread("test.png")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# creating a Histograms Equalization
equ = cv2.equalizeHist(img_gray)

# clahe
clahe = cv2.createCLAHE(clipLimit=10.0, tileGridSize=(100,100))
cl = clahe.apply(img_gray)

# show image input vs output
plt.figure(figsize=(10,10))
plt.imshow(img)
plt.title("original image")
plt.show()

plt.figure(figsize=(10,10))
plt.imshow(equ, cmap='gray', vmin=0, vmax=255)
plt.title("histogram equalization")
plt.show()

plt.figure(figsize=(10,10))
plt.imshow(cl, cmap='gray', vmin=0, vmax=255)
plt.title("CLAHE")
plt.show()

The results are:


Q: Reduction of independence to uncorrelatedness Consider two random variables $Y, Z \in \mathbb R$. Someone claims that $Y$ is independent of $Z$ if and only if $1\{Y \ge t\}$ is uncorrelated with $Z$ for all $t \in \mathbb R$. Is this true?
The statement seems suspect to me. I can see that they are independent iff $1\{Y \ge t\}$ is uncorrelated with $1\{Z \ge s\}$ for all $s,t \in \mathbb R$. But not the above.

A: Since $1\{Y\ge t\}$ is uncorrelated with $Z$ for all $t\in \Bbb R$, we can show that $Y$ itself is uncorrelated with $Z$. To do this, first assume $Y\ge 0$ for simplicity. I use this trick to relate $Y$ to $1\{Y\ge t\}$:
$$
Y=\int_0^\infty 1\{Y\ge t\}\,dt \tag 1
$$
Therefore,
$$
\begin{align}
E[YZ]
&=E\left[Z\int_0^\infty 1\{Y\ge t\}\,dt\right]
\\&=\int_0^\infty E[Z1\{Y\ge t\}]\,dt
\\&=\int_0^\infty E[Z]E[1\{Y\ge t\}]\,dt
\\&=E[Z]\int_0^\infty P(Y\ge t)\,dt
\\&=E[Z]E[Y]
\end{align}
$$
To exchange the order of $\int$ and $E[]$, you can use Fubini's theorem. When $Y$ can be negative, replace $(1)$ with $Y = \int_0^\infty [1\{Y\ge t\}-1\{Y\le -t\}]\,dt$.
Therefore, it makes sense to look for an example of $Y$ and $Z$ which are uncorrelated but dependent, and hope that we additionally have $1_{Y\ge t}$ being uncorrelated with $Z$.
One common example of uncorrelated and dependent random variables is when $Y$ and $Z$ are given by the following joint pmf:

$Z=-1$
$Z=0$
$Z=1$

$Y=-1$
0
$\frac14$
0

$Y=0$
$\frac14$
0
$\frac14$

$Y=1$
0
$\frac14$
0

You can check that $1_{Y\ge t}$ is uncorrelated with $Z$ for all $t$, so this is a counterexample which solves your problem.


Q: Retrieving elements from a data.frame when the addressed column is misspelled I stumbled on some strange behavior of R when working with a data.frame called DS.inp.
In this data.frame I have a column called "DATE_EGFR_CREAT". When I wanted to print the elements of this column in the console to see what data this column contained, I accidentally used a misspelled version of this column name:   "DS.inp$DATE_EGFR".  Still, R provided the results from "DATE_EGFR_CREAT" in the console. This was rather unexpected, as there is no column called "DATE_EGFR" in the data.frame DS.inp.
The following code was used to verify whether the misspelled column was in my data.frame originally:
> "DATE_EGFR" %in% names(DS.inp)
FALSE

Knowing what is causing this behavior in R might have a lot of impact on my work.
Does someone know what is going on here?


Q: Where is encapsulated the operators between integers? I need to group some operators to be able to call them by index and to do that I need to know where they belong.
When 1 + 1 is executed there is clearly an operator+(int, int) which must belong to a class that has some relation with ints -maybe a template parameter?-
I tried accessing such function with functional header file included using int::operator+ with no luck.
If something like
[
    the_class_i_need::operator+,
    the_class_i_need::operator-,
    ...
]

could be achieved or something alike, that'd perfect.


Q: Filtering Pandas Dataframe by the ending of the string I have a data frame called df and in one column 'Properties' I have listed properties of some product. These properties are a single sentence. Some of them have the same ending i.e. stock.
I was trying to do something like:
df.loc[df['Properties'][-6:] == 'stock']

to filter this values but it was not working.
I'd like to implement functionality where I can filter data frame by its last 5 characters.
Do you have any ideas how to do this task?

A: Try this:
df = df[df['Properties'].str.endswith('stock')]

If you want to try what you were trying, this would work:
df = df[df['Properties'].str[-5:]=='stock']